context
stringlengths 2.52k
185k
| gt
stringclasses 1
value |
---|---|
/*
* Anarres C Preprocessor
* Copyright (c) 2007-2008, Shevek
*
* 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.IO;
namespace CppNet
{
internal class JoinReader /* extends Reader */ {
private TextReader _in;
private PreprocessorListenerBase listener;
private LexerSource source;
private bool trigraphs;
private bool warnings;
private int newlines;
private bool flushnl;
private int[] unget;
private int uptr;
public JoinReader(TextReader ain, bool trigraphs)
{
this._in = ain;
this.trigraphs = trigraphs;
this.newlines = 0;
this.flushnl = false;
this.unget = new int[2];
this.uptr = 0;
}
public JoinReader(TextReader ain) :
this(ain, false)
{
}
public void setTrigraphs(bool enable, bool warnings)
{
this.trigraphs = enable;
this.warnings = warnings;
}
internal void init(Preprocessor pp, LexerSource s)
{
this.listener = pp.getListener();
this.source = s;
setTrigraphs(pp.getFeature(Feature.TRIGRAPHS),
pp.getWarning(Warning.TRIGRAPHS));
}
private int __read()
{
if(uptr > 0)
return unget[--uptr];
return _in.Read();
}
private void _unread(int c)
{
if(c != -1)
unget[uptr++] = c;
System.Diagnostics.Debug.Assert(uptr <= unget.Length,
"JoinReader ungets too many characters");
}
protected void warning(String msg)
{
if(source != null)
source.warning(msg);
else
throw new LexerException(msg);
}
private char trigraph(char raw, char repl)
{
if(trigraphs) {
if(warnings)
warning("trigraph ??" + raw + " converted to " + repl);
return repl;
} else {
if(warnings)
warning("trigraph ??" + raw + " ignored");
_unread(raw);
_unread('?');
return '?';
}
}
private int _read()
{
int c = __read();
if(c == '?' && (trigraphs || warnings)) {
int d = __read();
if(d == '?') {
int e = __read();
switch(e) {
case '(': return trigraph('(', '[');
case ')': return trigraph(')', ']');
case '<': return trigraph('<', '{');
case '>': return trigraph('>', '}');
case '=': return trigraph('=', '#');
case '/': return trigraph('/', '\\');
case '\'': return trigraph('\'', '^');
case '!': return trigraph('!', '|');
case '-': return trigraph('-', '~');
}
_unread(e);
}
_unread(d);
}
return c;
}
public int read()
{
if(flushnl) {
if(newlines > 0) {
newlines--;
return '\n';
}
flushnl = false;
}
for(; ; ) {
int c = _read();
switch(c) {
case '\\':
int d = _read();
switch(d) {
case '\n':
newlines++;
continue;
case '\r':
newlines++;
int e = _read();
if(e != '\n')
_unread(e);
continue;
default:
_unread(d);
return c;
}
case '\r':
case '\n':
case '\u2028':
case '\u2029':
case '\u000B':
case '\u000C':
case '\u0085':
flushnl = true;
return c;
case -1:
if(newlines > 0) {
newlines--;
return '\n';
}
goto default;
default:
return c;
}
}
}
public int read(char[] cbuf, int off, int len)
{
for(int i = 0; i < len; i++) {
int ch = read();
if(ch == -1)
return i;
cbuf[off + i] = (char)ch;
}
return len;
}
public void close()
{
if(_in == null) {
return;
}
_in.Dispose();
}
override public String ToString()
{
return "JoinReader(nl=" + newlines + ")";
}
/*
public static void main(String[] args) throws IOException {
FileReader f = new FileReader(new File(args[0]));
BufferedReader b = new BufferedReader(f);
JoinReader r = new JoinReader(b);
BufferedWriter w = new BufferedWriter(
new java.io.OutputStreamWriter(System.out)
);
int c;
while ((c = r.read()) != -1) {
w.write((char)c);
}
w.close();
}
*/
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using Hangfire.Mongo.Database;
using Hangfire.Mongo.Migration;
using Hangfire.Mongo.Migration.Steps.Version15;
using Hangfire.Mongo.Tests.Utils;
using MongoDB.Bson;
using MongoDB.Driver;
using Moq;
using Xunit;
namespace Hangfire.Mongo.Tests.Migration
{
[Collection("Database")]
public class Version15MigrationStepFacts
{
private readonly HangfireDbContext _dbContext;
private readonly Mock<IMongoMigrationContext> _mongoMigrationBagMock;
private readonly IMongoDatabase _database;
public Version15MigrationStepFacts()
{
_dbContext = ConnectionUtils.CreateDbContext();
_database = _dbContext.Database;
_mongoMigrationBagMock = new Mock<IMongoMigrationContext>(MockBehavior.Strict);
}
[Fact]
public void ExecuteStep00_ValidExistingLockDto_Success()
{
// ARRANGE
var collection = _database.GetCollection<BsonDocument>("hangfire.locks");
collection.Indexes.DropAll();
var indexBuilder = Builders<BsonDocument>.IndexKeys;
var indexNames = new[] {"Resource", "ExpireAt"};
var indexModels = indexNames.Select(indexName =>
{
var index = indexBuilder.Descending(indexName);
return new CreateIndexModel<BsonDocument>(index, new CreateIndexOptions
{
Name = indexName,
Sparse = true
});
}).ToList();
collection.Indexes.CreateMany(indexModels);
// ACT
var result = new CreateUniqueLockIndex().Execute(_dbContext.Database, new MongoStorageOptions(),
_mongoMigrationBagMock.Object);
// ASSERT
var indexes = collection.Indexes.List().ToList();
AssertIndex(indexes, "Resource", true);
}
[Fact]
public void ExecuteStep01_ValidExistingServerDto_Success()
{
// ARRANGE
var json =
@"
{ '_id' : 'test-server',
'Data' : '{\'WorkerCount\':20,\'Queues\':[\'default\'],\'StartedAt\':\'2018-12-03T22:19:00Z\'}',
'LastHeartbeat' : ISODate('2018-12-03T22:19:00.636Z')
}";
var originalServerDto = BsonDocument.Parse(json);
var document = BsonDocument.Parse(originalServerDto["Data"].AsString);
var collection = _database.GetCollection<BsonDocument>("hangfire.server");
collection.DeleteOne(new BsonDocument("_id", "test-server"));
collection.InsertOne(originalServerDto);
// ACT
var result = new MakeServerDataEmbeddedDocument().Execute(_database, new MongoStorageOptions(),
_mongoMigrationBagMock.Object);
// ASSERT
var migratedServerDto = collection.Find(new BsonDocument()).Single();
Assert.True(result, "Expected migration to be successful, reported 'false'");
Assert.Equal(originalServerDto["_id"], migratedServerDto["_id"]);
Assert.Equal(document["WorkerCount"].AsInt32, migratedServerDto["WorkerCount"].AsInt32);
Assert.Equal(document["Queues"].AsBsonArray.Select(d => d.AsString).ToArray(),
migratedServerDto["Queues"].AsBsonArray.Select(d => d.AsString).ToArray());
Assert.Equal(DateTime.Parse(document["StartedAt"].AsString).ToUniversalTime(), migratedServerDto["StartedAt"].ToUniversalTime());
Assert.Equal(originalServerDto["LastHeartbeat"], migratedServerDto["LastHeartbeat"].ToUniversalTime());
}
[Fact]
public void ExecuteStep02_ValidExistingSetDto_Success()
{
// ARRANGE
var collection = _database.GetCollection<BsonDocument>("hangfire.jobGraph");
var originalSetDto = new BsonDocument
{
["_id"] = ObjectId.GenerateNewId(),
["Key"] = "Key",
["Value"] = "Value",
["_t"] = "SetDto"
};
collection.DeleteMany(new BsonDocument("_t", "SetDto"));
collection.InsertOne(originalSetDto);
// ACT
var result = new CreateCompositeKeys().Execute(_database, new MongoStorageOptions(), _mongoMigrationBagMock.Object);
// ASSERT
var migratedSetDto = collection.Find(new BsonDocument("_t", "SetDto")).Single();
Assert.True(result, "Expected migration to be successful, reported 'false'");
Assert.Equal("Key:Value", migratedSetDto["Key"].AsString);
}
[Fact]
public void ExecuteStep03_MultipleCountersNotDeleted_OldCountersDeleted()
{
// ARRANGE
var collection = _database.GetCollection<BsonDocument>("hangfire.jobGraph");
collection.Indexes.DropAll();
collection.DeleteMany(new BsonDocument("_t", "CounterDto"));
var counters = new List<BsonDocument>();
foreach (var i in Enumerable.Range(0, 5))
{
counters.Add(new BsonDocument
{
["_id"] = ObjectId.GenerateNewId(),
["Key"] = "stats:succeeded",
["Value"] = 1L,
["ExpireAt"] = BsonNull.Value,
["_t"] = "CounterDto"
});
}
var mergedCounter = new BsonDocument
{
["_id"] = ObjectId.GenerateNewId(),
["Key"] = "stats:succeeded",
["Value"] = 5L,
["ExpireAt"] = BsonNull.Value,
["_t"] = "CounterDto"
};
counters.Add(mergedCounter);
collection.InsertMany(counters);
// ACT
var result = new RemoveMergedCounters().Execute(_database, new MongoStorageOptions(), _mongoMigrationBagMock.Object);
// ASSERT
var remainingCounter = collection.Find(new BsonDocument("_t", "CounterDto")).Single();
Assert.True(result, "Expected migration to be successful, reported 'false'");
Assert.Equal(5, remainingCounter["Value"].AsInt64);
}
[Fact]
public void ExecuteStep03_MultipleCountersDifferentValues_CountersMerged()
{
// ARRANGE
var collection = _database.GetCollection<BsonDocument>("hangfire.jobGraph");
collection.Indexes.DropAll();
collection.DeleteMany(new BsonDocument("_t", "CounterDto"));
var counters = new List<BsonDocument>();
foreach (var i in Enumerable.Range(0, 5))
{
counters.Add(new BsonDocument
{
["_id"] = ObjectId.GenerateNewId(),
["Key"] = "stats:succeeded",
["Value"] = 1L,
["ExpireAt"] = BsonNull.Value,
["_t"] = "CounterDto"
});
}
var mergedCounter = new BsonDocument
{
["_id"] = ObjectId.GenerateNewId(),
["Key"] = "stats:succeeded",
["Value"] = 5L,
["ExpireAt"] = BsonNull.Value,
["_t"] = "CounterDto"
};
var aggregatedCounter = new BsonDocument
{
["_id"] = ObjectId.GenerateNewId(),
["Key"] = "stats:succeeded",
["Value"] = 5L,
["ExpireAt"] = BsonNull.Value,
["_t"] = "CounterDto"
};
counters.Add(mergedCounter);
counters.Add(aggregatedCounter);
collection.InsertMany(counters);
// ACT
var result = new RemoveMergedCounters().Execute(_database, new MongoStorageOptions(), _mongoMigrationBagMock.Object);
// ASSERT
var remainingCounter = collection.Find(new BsonDocument("_t", "CounterDto")).Single();
Assert.True(result, "Expected migration to be successful, reported 'false'");
Assert.Equal(10, remainingCounter["Value"].AsInt64);
}
[Fact]
public void ExecuteStep03_OneCounter_Nothing()
{
// ARRANGE
var collection = _database.GetCollection<BsonDocument>("hangfire.jobGraph");
collection.DeleteMany(new BsonDocument("Key", "stats:succeeded"));
collection.InsertOne(new BsonDocument
{
["_id"] = ObjectId.GenerateNewId(),
["Key"] = "stats:succeeded",
["Value"] = 1L,
["ExpireAt"] = BsonNull.Value,
["_t"] = "CounterDto"
});
// ACT
var result = new RemoveMergedCounters().Execute(_database, new MongoStorageOptions(), _mongoMigrationBagMock.Object);
// ASSERT
var remainingCounter = collection.Find(new BsonDocument("_t", "CounterDto")).Single();
Assert.NotNull(remainingCounter);
Assert.True(result, "Expected migration to be successful, reported 'false'");
}
[Fact]
public void ExecuteStep03_TwoCountersSameValue_NewestChosen()
{
// ARRANGE
var collection = _database.GetCollection<BsonDocument>("hangfire.jobGraph");
collection.Indexes.DropAll();
collection.DeleteMany(new BsonDocument("_t", "CounterDto"));
collection.InsertOne(new BsonDocument
{
["_id"] = ObjectId.GenerateNewId(),
["Key"] = "stats:succeeded",
["Value"] = 1L,
["ExpireAt"] = BsonNull.Value,
["_t"] = "CounterDto"
});
var expectedDoc = new BsonDocument
{
["_id"] = ObjectId.GenerateNewId(),
["Key"] = "stats:succeeded",
["Value"] = 1L,
["ExpireAt"] = BsonNull.Value,
["_t"] = "CounterDto"
};
collection.InsertOne(expectedDoc);
// ACT
var result = new RemoveMergedCounters().Execute(_database, new MongoStorageOptions(), _mongoMigrationBagMock.Object);
// ASSERT
var remainingCounter = collection.Find(new BsonDocument("_t", "CounterDto")).Single();
Assert.NotNull(remainingCounter);
Assert.True(result, "Expected migration to be successful, reported 'false'");
Assert.Equal(expectedDoc["_id"], remainingCounter["_id"]);
}
[Fact]
public void ExecuteStep04_UpdateListDtoKeySchema_Success()
{
// ARRANGE
var collection = _database.GetCollection<BsonDocument>("hangfire.jobGraph");
collection.DeleteMany(new BsonDocument("_t", "ListDto"));
collection.InsertOne(new BsonDocument
{
["_id"] = ObjectId.GenerateNewId(),
["Key"] = "list-key",
["Value"] = "Value",
["ExpireAt"] = BsonNull.Value,
["_t"] = "ListDto"
});
// ACT
var result = new UpdateListDtoKeySchema().Execute(_database, new MongoStorageOptions(), _mongoMigrationBagMock.Object);
// ASSERT
var listDto = collection.Find(new BsonDocument("_t", "ListDto")).Single();
Assert.NotNull(listDto);
Assert.True(result, "Expected migration to be successful, reported 'false'");
Assert.True(listDto.Contains("Item"));
Assert.False(listDto.Contains("Key"));
Assert.Equal(BsonArray.Create(new[]{"BaseJobDto", "ExpiringJobDto", "ListDto"}), listDto["_t"]);
}
[Fact]
public void ExecuteStep05_UpdateIndexes_Success()
{
// ARRANGE
var collection = _database.GetCollection<BsonDocument>("hangfire.jobGraph");
collection.Indexes.DropAll();
// ACT
var result = new UpdateIndexes().Execute(_database, new MongoStorageOptions(), _mongoMigrationBagMock.Object);
// ASSERT
Assert.True(result, "Expected migration to be successful, reported 'false'");
var indexes = collection.Indexes.List().ToList();
AssertIndex(indexes, "Key", true, descending: false);
AssertIndex(indexes, "StateName", false);
AssertIndex(indexes, "ExpireAt", false);
AssertIndex(indexes, "_t", false);
AssertIndex(indexes, "Queue", false);
AssertIndex(indexes, "FetchedAt", false);
AssertIndex(indexes, "Value", false);
AssertIndex(indexes, "Item", false);
}
private static void AssertIndex(IList<BsonDocument> indexes, string indexName, bool unique ,bool descending = true)
{
var index = indexes.FirstOrDefault(d => d["name"].Equals(indexName));
Assert.True(index != null, $"Expected '{indexName}' field to be indexed");
if (unique)
{
Assert.True(index.Contains("unique"), "Expected 'unique' field to be present");
Assert.True(index["unique"].Equals(true), "Expected 'unique' field to be 'true'");
}
if (descending)
{
Assert.True(index["key"][indexName].AsInt32 == -1, "Expected index to be 'Descending'");
}
else
{
Assert.True(index["key"][indexName].AsInt32 == 1, "Expected index to be 'Descending'");
}
}
}
}
| |
using System;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Data.Common;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Xml;
using System.Xml.Serialization;
using SubSonic;
using SubSonic.Utilities;
namespace DalSic
{
/// <summary>
/// Strongly-typed collection for the ConConsultaOdontologium class.
/// </summary>
[Serializable]
public partial class ConConsultaOdontologiumCollection : ActiveList<ConConsultaOdontologium, ConConsultaOdontologiumCollection>
{
public ConConsultaOdontologiumCollection() {}
/// <summary>
/// Filters an existing collection based on the set criteria. This is an in-memory filter
/// Thanks to developingchris for this!
/// </summary>
/// <returns>ConConsultaOdontologiumCollection</returns>
public ConConsultaOdontologiumCollection Filter()
{
for (int i = this.Count - 1; i > -1; i--)
{
ConConsultaOdontologium o = this[i];
foreach (SubSonic.Where w in this.wheres)
{
bool remove = false;
System.Reflection.PropertyInfo pi = o.GetType().GetProperty(w.ColumnName);
if (pi.CanRead)
{
object val = pi.GetValue(o, null);
switch (w.Comparison)
{
case SubSonic.Comparison.Equals:
if (!val.Equals(w.ParameterValue))
{
remove = true;
}
break;
}
}
if (remove)
{
this.Remove(o);
break;
}
}
}
return this;
}
}
/// <summary>
/// This is an ActiveRecord class which wraps the CON_ConsultaOdontologia table.
/// </summary>
[Serializable]
public partial class ConConsultaOdontologium : ActiveRecord<ConConsultaOdontologium>, IActiveRecord
{
#region .ctors and Default Settings
public ConConsultaOdontologium()
{
SetSQLProps();
InitSetDefaults();
MarkNew();
}
private void InitSetDefaults() { SetDefaults(); }
public ConConsultaOdontologium(bool useDatabaseDefaults)
{
SetSQLProps();
if(useDatabaseDefaults)
ForceDefaults();
MarkNew();
}
public ConConsultaOdontologium(object keyID)
{
SetSQLProps();
InitSetDefaults();
LoadByKey(keyID);
}
public ConConsultaOdontologium(string columnName, object columnValue)
{
SetSQLProps();
InitSetDefaults();
LoadByParam(columnName,columnValue);
}
protected static void SetSQLProps() { GetTableSchema(); }
#endregion
#region Schema and Query Accessor
public static Query CreateQuery() { return new Query(Schema); }
public static TableSchema.Table Schema
{
get
{
if (BaseSchema == null)
SetSQLProps();
return BaseSchema;
}
}
private static void GetTableSchema()
{
if(!IsSchemaInitialized)
{
//Schema declaration
TableSchema.Table schema = new TableSchema.Table("CON_ConsultaOdontologia", TableType.Table, DataService.GetInstance("sicProvider"));
schema.Columns = new TableSchema.TableColumnCollection();
schema.SchemaName = @"dbo";
//columns
TableSchema.TableColumn colvarIdConsultaOdontologia = new TableSchema.TableColumn(schema);
colvarIdConsultaOdontologia.ColumnName = "idConsultaOdontologia";
colvarIdConsultaOdontologia.DataType = DbType.Int32;
colvarIdConsultaOdontologia.MaxLength = 0;
colvarIdConsultaOdontologia.AutoIncrement = true;
colvarIdConsultaOdontologia.IsNullable = false;
colvarIdConsultaOdontologia.IsPrimaryKey = true;
colvarIdConsultaOdontologia.IsForeignKey = false;
colvarIdConsultaOdontologia.IsReadOnly = false;
colvarIdConsultaOdontologia.DefaultSetting = @"";
colvarIdConsultaOdontologia.ForeignKeyTableName = "";
schema.Columns.Add(colvarIdConsultaOdontologia);
TableSchema.TableColumn colvarIdConsulta = new TableSchema.TableColumn(schema);
colvarIdConsulta.ColumnName = "idConsulta";
colvarIdConsulta.DataType = DbType.Int32;
colvarIdConsulta.MaxLength = 0;
colvarIdConsulta.AutoIncrement = false;
colvarIdConsulta.IsNullable = false;
colvarIdConsulta.IsPrimaryKey = false;
colvarIdConsulta.IsForeignKey = false;
colvarIdConsulta.IsReadOnly = false;
colvarIdConsulta.DefaultSetting = @"";
colvarIdConsulta.ForeignKeyTableName = "";
schema.Columns.Add(colvarIdConsulta);
TableSchema.TableColumn colvarIdNomenclador = new TableSchema.TableColumn(schema);
colvarIdNomenclador.ColumnName = "idNomenclador";
colvarIdNomenclador.DataType = DbType.Int32;
colvarIdNomenclador.MaxLength = 0;
colvarIdNomenclador.AutoIncrement = false;
colvarIdNomenclador.IsNullable = false;
colvarIdNomenclador.IsPrimaryKey = false;
colvarIdNomenclador.IsForeignKey = false;
colvarIdNomenclador.IsReadOnly = false;
colvarIdNomenclador.DefaultSetting = @"";
colvarIdNomenclador.ForeignKeyTableName = "";
schema.Columns.Add(colvarIdNomenclador);
TableSchema.TableColumn colvarDiente = new TableSchema.TableColumn(schema);
colvarDiente.ColumnName = "diente";
colvarDiente.DataType = DbType.Int32;
colvarDiente.MaxLength = 0;
colvarDiente.AutoIncrement = false;
colvarDiente.IsNullable = false;
colvarDiente.IsPrimaryKey = false;
colvarDiente.IsForeignKey = false;
colvarDiente.IsReadOnly = false;
colvarDiente.DefaultSetting = @"((0))";
colvarDiente.ForeignKeyTableName = "";
schema.Columns.Add(colvarDiente);
TableSchema.TableColumn colvarCaraM = new TableSchema.TableColumn(schema);
colvarCaraM.ColumnName = "caraM";
colvarCaraM.DataType = DbType.Boolean;
colvarCaraM.MaxLength = 0;
colvarCaraM.AutoIncrement = false;
colvarCaraM.IsNullable = false;
colvarCaraM.IsPrimaryKey = false;
colvarCaraM.IsForeignKey = false;
colvarCaraM.IsReadOnly = false;
colvarCaraM.DefaultSetting = @"((0))";
colvarCaraM.ForeignKeyTableName = "";
schema.Columns.Add(colvarCaraM);
TableSchema.TableColumn colvarCaraP = new TableSchema.TableColumn(schema);
colvarCaraP.ColumnName = "caraP";
colvarCaraP.DataType = DbType.Boolean;
colvarCaraP.MaxLength = 0;
colvarCaraP.AutoIncrement = false;
colvarCaraP.IsNullable = false;
colvarCaraP.IsPrimaryKey = false;
colvarCaraP.IsForeignKey = false;
colvarCaraP.IsReadOnly = false;
colvarCaraP.DefaultSetting = @"((0))";
colvarCaraP.ForeignKeyTableName = "";
schema.Columns.Add(colvarCaraP);
TableSchema.TableColumn colvarCaraD = new TableSchema.TableColumn(schema);
colvarCaraD.ColumnName = "caraD";
colvarCaraD.DataType = DbType.Boolean;
colvarCaraD.MaxLength = 0;
colvarCaraD.AutoIncrement = false;
colvarCaraD.IsNullable = false;
colvarCaraD.IsPrimaryKey = false;
colvarCaraD.IsForeignKey = false;
colvarCaraD.IsReadOnly = false;
colvarCaraD.DefaultSetting = @"((0))";
colvarCaraD.ForeignKeyTableName = "";
schema.Columns.Add(colvarCaraD);
TableSchema.TableColumn colvarCaraO = new TableSchema.TableColumn(schema);
colvarCaraO.ColumnName = "caraO";
colvarCaraO.DataType = DbType.Boolean;
colvarCaraO.MaxLength = 0;
colvarCaraO.AutoIncrement = false;
colvarCaraO.IsNullable = false;
colvarCaraO.IsPrimaryKey = false;
colvarCaraO.IsForeignKey = false;
colvarCaraO.IsReadOnly = false;
colvarCaraO.DefaultSetting = @"((0))";
colvarCaraO.ForeignKeyTableName = "";
schema.Columns.Add(colvarCaraO);
TableSchema.TableColumn colvarCaraV = new TableSchema.TableColumn(schema);
colvarCaraV.ColumnName = "caraV";
colvarCaraV.DataType = DbType.Boolean;
colvarCaraV.MaxLength = 0;
colvarCaraV.AutoIncrement = false;
colvarCaraV.IsNullable = false;
colvarCaraV.IsPrimaryKey = false;
colvarCaraV.IsForeignKey = false;
colvarCaraV.IsReadOnly = false;
colvarCaraV.DefaultSetting = @"((0))";
colvarCaraV.ForeignKeyTableName = "";
schema.Columns.Add(colvarCaraV);
TableSchema.TableColumn colvarCaraL = new TableSchema.TableColumn(schema);
colvarCaraL.ColumnName = "caraL";
colvarCaraL.DataType = DbType.Boolean;
colvarCaraL.MaxLength = 0;
colvarCaraL.AutoIncrement = false;
colvarCaraL.IsNullable = false;
colvarCaraL.IsPrimaryKey = false;
colvarCaraL.IsForeignKey = false;
colvarCaraL.IsReadOnly = false;
colvarCaraL.DefaultSetting = @"";
colvarCaraL.ForeignKeyTableName = "";
schema.Columns.Add(colvarCaraL);
TableSchema.TableColumn colvarCantidad = new TableSchema.TableColumn(schema);
colvarCantidad.ColumnName = "cantidad";
colvarCantidad.DataType = DbType.Int32;
colvarCantidad.MaxLength = 0;
colvarCantidad.AutoIncrement = false;
colvarCantidad.IsNullable = false;
colvarCantidad.IsPrimaryKey = false;
colvarCantidad.IsForeignKey = false;
colvarCantidad.IsReadOnly = false;
colvarCantidad.DefaultSetting = @"((0))";
colvarCantidad.ForeignKeyTableName = "";
schema.Columns.Add(colvarCantidad);
BaseSchema = schema;
//add this schema to the provider
//so we can query it later
DataService.Providers["sicProvider"].AddSchema("CON_ConsultaOdontologia",schema);
}
}
#endregion
#region Props
[XmlAttribute("IdConsultaOdontologia")]
[Bindable(true)]
public int IdConsultaOdontologia
{
get { return GetColumnValue<int>(Columns.IdConsultaOdontologia); }
set { SetColumnValue(Columns.IdConsultaOdontologia, value); }
}
[XmlAttribute("IdConsulta")]
[Bindable(true)]
public int IdConsulta
{
get { return GetColumnValue<int>(Columns.IdConsulta); }
set { SetColumnValue(Columns.IdConsulta, value); }
}
[XmlAttribute("IdNomenclador")]
[Bindable(true)]
public int IdNomenclador
{
get { return GetColumnValue<int>(Columns.IdNomenclador); }
set { SetColumnValue(Columns.IdNomenclador, value); }
}
[XmlAttribute("Diente")]
[Bindable(true)]
public int Diente
{
get { return GetColumnValue<int>(Columns.Diente); }
set { SetColumnValue(Columns.Diente, value); }
}
[XmlAttribute("CaraM")]
[Bindable(true)]
public bool CaraM
{
get { return GetColumnValue<bool>(Columns.CaraM); }
set { SetColumnValue(Columns.CaraM, value); }
}
[XmlAttribute("CaraP")]
[Bindable(true)]
public bool CaraP
{
get { return GetColumnValue<bool>(Columns.CaraP); }
set { SetColumnValue(Columns.CaraP, value); }
}
[XmlAttribute("CaraD")]
[Bindable(true)]
public bool CaraD
{
get { return GetColumnValue<bool>(Columns.CaraD); }
set { SetColumnValue(Columns.CaraD, value); }
}
[XmlAttribute("CaraO")]
[Bindable(true)]
public bool CaraO
{
get { return GetColumnValue<bool>(Columns.CaraO); }
set { SetColumnValue(Columns.CaraO, value); }
}
[XmlAttribute("CaraV")]
[Bindable(true)]
public bool CaraV
{
get { return GetColumnValue<bool>(Columns.CaraV); }
set { SetColumnValue(Columns.CaraV, value); }
}
[XmlAttribute("CaraL")]
[Bindable(true)]
public bool CaraL
{
get { return GetColumnValue<bool>(Columns.CaraL); }
set { SetColumnValue(Columns.CaraL, value); }
}
[XmlAttribute("Cantidad")]
[Bindable(true)]
public int Cantidad
{
get { return GetColumnValue<int>(Columns.Cantidad); }
set { SetColumnValue(Columns.Cantidad, value); }
}
#endregion
//no foreign key tables defined (0)
//no ManyToMany tables defined (0)
#region ObjectDataSource support
/// <summary>
/// Inserts a record, can be used with the Object Data Source
/// </summary>
public static void Insert(int varIdConsulta,int varIdNomenclador,int varDiente,bool varCaraM,bool varCaraP,bool varCaraD,bool varCaraO,bool varCaraV,bool varCaraL,int varCantidad)
{
ConConsultaOdontologium item = new ConConsultaOdontologium();
item.IdConsulta = varIdConsulta;
item.IdNomenclador = varIdNomenclador;
item.Diente = varDiente;
item.CaraM = varCaraM;
item.CaraP = varCaraP;
item.CaraD = varCaraD;
item.CaraO = varCaraO;
item.CaraV = varCaraV;
item.CaraL = varCaraL;
item.Cantidad = varCantidad;
if (System.Web.HttpContext.Current != null)
item.Save(System.Web.HttpContext.Current.User.Identity.Name);
else
item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name);
}
/// <summary>
/// Updates a record, can be used with the Object Data Source
/// </summary>
public static void Update(int varIdConsultaOdontologia,int varIdConsulta,int varIdNomenclador,int varDiente,bool varCaraM,bool varCaraP,bool varCaraD,bool varCaraO,bool varCaraV,bool varCaraL,int varCantidad)
{
ConConsultaOdontologium item = new ConConsultaOdontologium();
item.IdConsultaOdontologia = varIdConsultaOdontologia;
item.IdConsulta = varIdConsulta;
item.IdNomenclador = varIdNomenclador;
item.Diente = varDiente;
item.CaraM = varCaraM;
item.CaraP = varCaraP;
item.CaraD = varCaraD;
item.CaraO = varCaraO;
item.CaraV = varCaraV;
item.CaraL = varCaraL;
item.Cantidad = varCantidad;
item.IsNew = false;
if (System.Web.HttpContext.Current != null)
item.Save(System.Web.HttpContext.Current.User.Identity.Name);
else
item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name);
}
#endregion
#region Typed Columns
public static TableSchema.TableColumn IdConsultaOdontologiaColumn
{
get { return Schema.Columns[0]; }
}
public static TableSchema.TableColumn IdConsultaColumn
{
get { return Schema.Columns[1]; }
}
public static TableSchema.TableColumn IdNomencladorColumn
{
get { return Schema.Columns[2]; }
}
public static TableSchema.TableColumn DienteColumn
{
get { return Schema.Columns[3]; }
}
public static TableSchema.TableColumn CaraMColumn
{
get { return Schema.Columns[4]; }
}
public static TableSchema.TableColumn CaraPColumn
{
get { return Schema.Columns[5]; }
}
public static TableSchema.TableColumn CaraDColumn
{
get { return Schema.Columns[6]; }
}
public static TableSchema.TableColumn CaraOColumn
{
get { return Schema.Columns[7]; }
}
public static TableSchema.TableColumn CaraVColumn
{
get { return Schema.Columns[8]; }
}
public static TableSchema.TableColumn CaraLColumn
{
get { return Schema.Columns[9]; }
}
public static TableSchema.TableColumn CantidadColumn
{
get { return Schema.Columns[10]; }
}
#endregion
#region Columns Struct
public struct Columns
{
public static string IdConsultaOdontologia = @"idConsultaOdontologia";
public static string IdConsulta = @"idConsulta";
public static string IdNomenclador = @"idNomenclador";
public static string Diente = @"diente";
public static string CaraM = @"caraM";
public static string CaraP = @"caraP";
public static string CaraD = @"caraD";
public static string CaraO = @"caraO";
public static string CaraV = @"caraV";
public static string CaraL = @"caraL";
public static string Cantidad = @"cantidad";
}
#endregion
#region Update PK Collections
#endregion
#region Deep Save
#endregion
}
}
| |
//Copyright (c) Microsoft Corporation. All rights reserved.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Security.Permissions;
using MS.WindowsAPICodePack.Internal;
namespace Microsoft.WindowsAPICodePack.Dialogs
{
/// <summary>
/// Encapsulates a new-to-Vista Win32 TaskDialog window
/// - a powerful successor to the MessageBox available
/// in previous versions of Windows.
/// </summary>
[SecurityPermissionAttribute(SecurityAction.InheritanceDemand, Flags = SecurityPermissionFlag.UnmanagedCode)]
public class TaskDialog : IDialogControlHost, IDisposable
{
// Global instance of TaskDialog, to be used by static Show() method.
// As most parameters of a dialog created via static Show() will have
// identical parameters, we'll create one TaskDialog and treat it
// as a NativeTaskDialog generator for all static Show() calls.
private static TaskDialog staticDialog;
// Main current native dialog.
private NativeTaskDialog nativeDialog;
private List<TaskDialogButtonBase> buttons;
private List<TaskDialogButtonBase> radioButtons;
private List<TaskDialogButtonBase> commandLinks;
private IntPtr ownerWindow;
#region Public Properties
/// <summary>
/// Occurs when a progress bar changes.
/// </summary>
public event EventHandler<TaskDialogTickEventArgs> Tick;
/// <summary>
/// Occurs when a user clicks a hyperlink.
/// </summary>
public event EventHandler<TaskDialogHyperlinkClickedEventArgs> HyperlinkClick;
/// <summary>
/// Occurs when the TaskDialog is closing.
/// </summary>
public event EventHandler<TaskDialogClosingEventArgs> Closing;
/// <summary>
/// Occurs when a user clicks on Help.
/// </summary>
public event EventHandler HelpInvoked;
/// <summary>
/// Occurs when the TaskDialog is opened.
/// </summary>
public event EventHandler Opened;
/// <summary>
/// Gets or sets a value that contains the owner window's handle.
/// </summary>
public IntPtr OwnerWindowHandle
{
get { return ownerWindow; }
set
{
ThrowIfDialogShowing("Dialog owner cannot be modified while dialog is showing.");
ownerWindow = value;
}
}
// Main content (maps to MessageBox's "message").
private string text;
/// <summary>
/// Gets or sets a value that contains the message text.
/// </summary>
public string Text
{
get { return text; }
set
{
// Set local value, then update native dialog if showing.
text = value;
if (NativeDialogShowing)
nativeDialog.UpdateText(text);
}
}
private string instructionText;
/// <summary>
/// Gets or sets a value that contains the instruction text.
/// </summary>
public string InstructionText
{
get { return instructionText; }
set
{
// Set local value, then update native dialog if showing.
instructionText = value;
if (NativeDialogShowing)
nativeDialog.UpdateInstruction(instructionText);
}
}
private string caption;
/// <summary>
/// Gets or sets a value that contains the caption text.
/// </summary>
public string Caption
{
get { return caption; }
set
{
ThrowIfDialogShowing("Dialog caption can't be set while dialog is showing.");
caption = value;
}
}
private string footerText;
/// <summary>
/// Gets or sets a value that contains the footer text.
/// </summary>
public string FooterText
{
get { return footerText; }
set
{
// Set local value, then update native dialog if showing.
footerText = value;
if (NativeDialogShowing)
nativeDialog.UpdateFooterText(footerText);
}
}
private string checkBoxText;
/// <summary>
/// Gets or sets a value that contains the footer check box text.
/// </summary>
public string FooterCheckBoxText
{
get { return checkBoxText; }
set
{
ThrowIfDialogShowing("Checkbox text can't be set while dialog is showing.");
checkBoxText = value;
}
}
private string detailsExpandedText;
/// <summary>
/// Gets or sets a value that contains the expanded text in the details section.
/// </summary>
public string DetailsExpandedText
{
get { return detailsExpandedText; }
set
{
// Set local value, then update native dialog if showing.
detailsExpandedText = value;
if (NativeDialogShowing)
nativeDialog.UpdateExpandedText(detailsExpandedText);
}
}
private bool detailsExpanded;
/// <summary>
/// Gets or sets a value that determines if the details section is expanded.
/// </summary>
public bool DetailsExpanded
{
get { return detailsExpanded; }
set
{
ThrowIfDialogShowing("Expanded state of the dialog can't be modified while dialog is showing.");
detailsExpanded = value;
}
}
private string detailsExpandedLabel;
/// <summary>
/// Gets or sets a value that contains the expanded control text.
/// </summary>
public string DetailsExpandedLabel
{
get { return detailsExpandedLabel; }
set
{
ThrowIfDialogShowing("Expanded control label can't be set while dialog is showing.");
detailsExpandedLabel = value;
}
}
private string detailsCollapsedLabel;
/// <summary>
/// Gets or sets a value that contains the collapsed control text.
/// </summary>
public string DetailsCollapsedLabel
{
get { return detailsCollapsedLabel; }
set
{
ThrowIfDialogShowing("Collapsed control text can't be set while dialog is showing.");
detailsCollapsedLabel = value;
}
}
private bool cancelable;
/// <summary>
/// Gets or sets a value that determines if Cancelable is set.
/// </summary>
public bool Cancelable
{
get { return cancelable; }
set
{
ThrowIfDialogShowing("Cancelable can't be set while dialog is showing.");
cancelable = value;
}
}
private TaskDialogStandardIcon icon;
/// <summary>
/// Gets or sets a value that contains the TaskDialog main icon.
/// </summary>
public TaskDialogStandardIcon Icon
{
get { return icon; }
set
{
// Set local value, then update native dialog if showing.
icon = value;
if (NativeDialogShowing)
nativeDialog.UpdateMainIcon(icon);
}
}
private TaskDialogStandardIcon footerIcon;
/// <summary>
/// Gets or sets a value that contains the footer icon.
/// </summary>
public TaskDialogStandardIcon FooterIcon
{
get { return footerIcon; }
set
{
// Set local value, then update native dialog if showing.
footerIcon = value;
if (NativeDialogShowing)
nativeDialog.UpdateFooterIcon(footerIcon);
}
}
private TaskDialogStandardButtons standardButtons = TaskDialogStandardButtons.None;
/// <summary>
/// Gets or sets a value that contains the standard buttons.
/// </summary>
public TaskDialogStandardButtons StandardButtons
{
get { return standardButtons; }
set
{
ThrowIfDialogShowing("Standard buttons can't be set while dialog is showing.");
standardButtons = value;
}
}
private DialogControlCollection<TaskDialogControl> controls;
/// <summary>
/// Gets a value that contains the TaskDialog controls.
/// </summary>
public DialogControlCollection<TaskDialogControl> Controls
{
// "Show protection" provided by collection itself,
// as well as individual controls.
get { return controls; }
}
private bool hyperlinksEnabled;
/// <summary>
/// Gets or sets a value that determines if hyperlinks are enabled.
/// </summary>
public bool HyperlinksEnabled
{
get { return hyperlinksEnabled; }
set
{
ThrowIfDialogShowing("Hyperlinks can't be enabled/disabled while dialog is showing.");
hyperlinksEnabled = value;
}
}
private bool? footerCheckBoxChecked = null;
/// <summary>
/// Gets or sets a value that indicates if the footer checkbox is checked.
/// </summary>
public bool? FooterCheckBoxChecked
{
get
{
if (!footerCheckBoxChecked.HasValue)
return false;
else
return footerCheckBoxChecked;
}
set
{
// Set local value, then update native dialog if showing.
footerCheckBoxChecked = value;
if (NativeDialogShowing)
nativeDialog.UpdateCheckBoxChecked(footerCheckBoxChecked.Value);
}
}
private TaskDialogExpandedDetailsLocation expansionMode;
/// <summary>
/// Gets or sets a value that contains the expansion mode for this dialog.
/// </summary>
public TaskDialogExpandedDetailsLocation ExpansionMode
{
get { return expansionMode; }
set
{
ThrowIfDialogShowing("Expanded information mode can't be set while dialog is showing.");
expansionMode = value;
}
}
private TaskDialogStartupLocation startupLocation;
/// <summary>
/// Gets or sets a value that contains the startup location.
/// </summary>
public TaskDialogStartupLocation StartupLocation
{
get { return startupLocation; }
set
{
ThrowIfDialogShowing("Startup location can't be changed while dialog is showing.");
startupLocation = value;
}
}
private TaskDialogProgressBar progressBar;
/// <summary>
/// Gets or sets the progress bar on the taskdialog. ProgressBar a visual representation
/// of the progress of a long running operation.
/// </summary>
public TaskDialogProgressBar ProgressBar
{
get { return progressBar; }
set
{
ThrowIfDialogShowing("Progress bar can't be changed while dialog is showing");
if (value != null)
{
if (value.HostingDialog != null)
throw new InvalidOperationException("Progress bar cannot be hosted in multiple dialogs.");
value.HostingDialog = this;
}
progressBar = value;
}
}
#endregion
#region Constructors
// Constructors.
/// <summary>
/// Creates a basic TaskDialog window
/// </summary>
public TaskDialog()
{
// Throw PlatformNotSupportedException if the user is not running Vista or beyond
CoreHelpers.ThrowIfNotVista();
// Initialize various data structs.
controls = new DialogControlCollection<TaskDialogControl>(this);
buttons = new List<TaskDialogButtonBase>();
radioButtons = new List<TaskDialogButtonBase>();
commandLinks = new List<TaskDialogButtonBase>();
}
#endregion
#region Static Show Methods
/// <summary>
/// Creates and shows a task dialog with the specified message text.
/// </summary>
/// <param name="text">The text to display.</param>
/// <returns>The dialog result.</returns>
public static TaskDialogResult Show(string text)
{
return ShowCoreStatic(
text,
TaskDialogDefaults.MainInstruction,
TaskDialogDefaults.Caption);
}
/// <summary>
/// Creates and shows a task dialog with the specified supporting text and main instruction.
/// </summary>
/// <param name="text">The supporting text to display.</param>
/// <param name="instructionText">The main instruction text to display.</param>
/// <returns>The dialog result.</returns>
public static TaskDialogResult Show(string text, string instructionText)
{
return ShowCoreStatic(
text, instructionText,
TaskDialogDefaults.Caption);
}
/// <summary>
/// Creates and shows a task dialog with the specified supporting text, main instruction, and dialog caption.
/// </summary>
/// <param name="text">The supporting text to display.</param>
/// <param name="instructionText">The main instruction text to display.</param>
/// <param name="caption">The caption for the dialog.</param>
/// <returns>The dialog result.</returns>
public static TaskDialogResult Show(string text, string instructionText, string caption)
{
return ShowCoreStatic(text, instructionText, caption);
}
#endregion
#region Instance Show Methods
/// <summary>
/// Creates and shows a task dialog.
/// </summary>
/// <returns>The dialog result.</returns>
public TaskDialogResult Show()
{
return ShowCore();
}
#endregion
#region Core Show Logic
// CORE SHOW METHODS:
// All static Show() calls forward here -
// it is responsible for retrieving
// or creating our cached TaskDialog instance, getting it configured,
// and in turn calling the appropriate instance Show.
private static TaskDialogResult ShowCoreStatic(
string text,
string instructionText,
string caption)
{
// Throw PlatformNotSupportedException if the user is not running Vista or beyond
CoreHelpers.ThrowIfNotVista();
// If no instance cached yet, create it.
if (staticDialog == null)
{
// New TaskDialog will automatically pick up defaults when
// a new config structure is created as part of ShowCore().
staticDialog = new TaskDialog();
}
// Set the few relevant properties,
// and go with the defaults for the others.
staticDialog.text = text;
staticDialog.instructionText = instructionText;
staticDialog.caption = caption;
return staticDialog.Show();
}
private TaskDialogResult ShowCore()
{
TaskDialogResult result;
try
{
// Populate control lists, based on current
// contents - note we are somewhat late-bound
// on our control lists, to support XAML scenarios.
SortDialogControls();
// First, let's make sure it even makes
// sense to try a show.
ValidateCurrentDialogSettings();
// Create settings object for new dialog,
// based on current state.
NativeTaskDialogSettings settings =
new NativeTaskDialogSettings();
ApplyCoreSettings(settings);
ApplySupplementalSettings(settings);
// Show the dialog.
// NOTE: this is a BLOCKING call; the dialog proc callbacks
// will be executed by the same thread as the
// Show() call before the thread of execution
// contines to the end of this method.
nativeDialog = new NativeTaskDialog(settings, this);
nativeDialog.NativeShow();
// Build and return dialog result to public API - leaving it
// null after an exception is thrown is fine in this case
result = ConstructDialogResult(nativeDialog);
footerCheckBoxChecked = nativeDialog.CheckBoxChecked;
}
finally
{
CleanUp();
nativeDialog = null;
}
return result;
}
// Helper that looks at the current state of the TaskDialog and verifies
// that there aren't any abberant combinations of properties.
// NOTE that this method is designed to throw
// rather than return a bool.
private void ValidateCurrentDialogSettings()
{
if (footerCheckBoxChecked.HasValue &&
footerCheckBoxChecked.Value == true &&
String.IsNullOrEmpty(checkBoxText))
throw new InvalidOperationException(
"Checkbox text must be provided to enable the dialog checkbox.");
// Progress bar validation.
// Make sure the progress bar values are valid.
// the Win32 API will valiantly try to rationalize
// bizarre min/max/value combinations, but we'll save
// it the trouble by validating.
if (progressBar != null)
if (!progressBar.HasValidValues)
throw new ArgumentException(
"Progress bar must have a value between the minimum and maxium values.");
// Validate Buttons collection.
// Make sure we don't have buttons AND
// command-links - the Win32 API treats them as different
// flavors of a single button struct.
if (buttons.Count > 0 && commandLinks.Count > 0)
throw new NotSupportedException(
"Dialog cannot display both non-standard buttons and command links.");
if (buttons.Count > 0 && standardButtons != TaskDialogStandardButtons.None)
throw new NotSupportedException(
"Dialog cannot display both non-standard buttons and standard buttons.");
}
// Analyzes the final state of the NativeTaskDialog instance and creates the
// final TaskDialogResult that will be returned from the public API
private TaskDialogResult ConstructDialogResult(NativeTaskDialog native)
{
Debug.Assert(native.ShowState == DialogShowState.Closed, "dialog result being constructed for unshown dialog.");
TaskDialogResult result = TaskDialogResult.Cancel;
TaskDialogStandardButtons standardButton = MapButtonIdToStandardButton(native.SelectedButtonID);
// If returned ID isn't a standard button, let's fetch
if (standardButton == TaskDialogStandardButtons.None)
result = TaskDialogResult.CustomButtonClicked;
else
result = (TaskDialogResult)standardButton;
return result;
}
/// <summary>
/// Close TaskDialog
/// </summary>
/// <exception cref="InvalidOperationException">if TaskDialog is not showing.</exception>
public void Close()
{
if (!NativeDialogShowing)
throw new InvalidOperationException(
"Attempting to close a non-showing dialog.");
nativeDialog.NativeClose(TaskDialogResult.Cancel);
// TaskDialog's own cleanup code -
// which runs post show - will handle disposal of native dialog.
}
/// <summary>
/// Close TaskDialog with a given TaskDialogResult
/// </summary>
/// <param name="closingResult">TaskDialogResult to return from the TaskDialog.Show() method</param>
/// <exception cref="InvalidOperationException">if TaskDialog is not showing.</exception>
public void Close(TaskDialogResult closingResult)
{
if (!NativeDialogShowing)
throw new InvalidOperationException(
"Attempting to close a non-showing dialog.");
nativeDialog.NativeClose(closingResult);
// TaskDialog's own cleanup code -
// which runs post show - will handle disposal of native dialog.
}
#endregion
#region Configuration Construction
private void ApplyCoreSettings(NativeTaskDialogSettings settings)
{
ApplyGeneralNativeConfiguration(settings.NativeConfiguration);
ApplyTextConfiguration(settings.NativeConfiguration);
ApplyOptionConfiguration(settings.NativeConfiguration);
ApplyControlConfiguration(settings);
}
private void ApplyGeneralNativeConfiguration(TaskDialogNativeMethods.TASKDIALOGCONFIG dialogConfig)
{
// If an owner wasn't specifically specified,
// we'll use the app's main window.
if (ownerWindow != IntPtr.Zero)
dialogConfig.hwndParent = ownerWindow;
// Other miscellaneous sets.
dialogConfig.MainIcon =
new TaskDialogNativeMethods.TASKDIALOGCONFIG_ICON_UNION((int)icon);
dialogConfig.FooterIcon =
new TaskDialogNativeMethods.TASKDIALOGCONFIG_ICON_UNION((int)footerIcon);
dialogConfig.dwCommonButtons =
(TaskDialogNativeMethods.TASKDIALOG_COMMON_BUTTON_FLAGS)standardButtons;
}
/// <summary>
/// Sets important text properties.
/// </summary>
/// <param name="dialogConfig">An instance of a <see cref="TaskDialogNativeMethods.TASKDIALOGCONFIG"/> object.</param>
private void ApplyTextConfiguration(TaskDialogNativeMethods.TASKDIALOGCONFIG dialogConfig)
{
// note that nulls or empty strings are fine here.
dialogConfig.pszContent = text;
dialogConfig.pszWindowTitle = caption;
dialogConfig.pszMainInstruction = instructionText;
dialogConfig.pszExpandedInformation = detailsExpandedText;
dialogConfig.pszExpandedControlText = detailsExpandedLabel;
dialogConfig.pszCollapsedControlText = detailsCollapsedLabel;
dialogConfig.pszFooter = footerText;
dialogConfig.pszVerificationText = checkBoxText;
}
private void ApplyOptionConfiguration(TaskDialogNativeMethods.TASKDIALOGCONFIG dialogConfig)
{
// Handle options - start with no options set.
TaskDialogNativeMethods.TASKDIALOG_FLAGS options = TaskDialogNativeMethods.TASKDIALOG_FLAGS.NONE;
if (cancelable)
options |= TaskDialogNativeMethods.TASKDIALOG_FLAGS.TDF_ALLOW_DIALOG_CANCELLATION;
if (footerCheckBoxChecked.HasValue && footerCheckBoxChecked.Value)
options |= TaskDialogNativeMethods.TASKDIALOG_FLAGS.TDF_VERIFICATION_FLAG_CHECKED;
if (hyperlinksEnabled)
options |= TaskDialogNativeMethods.TASKDIALOG_FLAGS.TDF_ENABLE_HYPERLINKS;
if (detailsExpanded)
options |= TaskDialogNativeMethods.TASKDIALOG_FLAGS.TDF_EXPANDED_BY_DEFAULT;
if (Tick != null)
options |= TaskDialogNativeMethods.TASKDIALOG_FLAGS.TDF_CALLBACK_TIMER;
if (startupLocation == TaskDialogStartupLocation.CenterOwner)
options |= TaskDialogNativeMethods.TASKDIALOG_FLAGS.TDF_POSITION_RELATIVE_TO_WINDOW;
// Note: no validation required, as we allow this to
// be set even if there is no expanded information
// text because that could be added later.
// Default for Win32 API is to expand into (and after)
// the content area.
if (expansionMode == TaskDialogExpandedDetailsLocation.ExpandFooter)
options |= TaskDialogNativeMethods.TASKDIALOG_FLAGS.TDF_EXPAND_FOOTER_AREA;
// Finally, apply options to config.
dialogConfig.dwFlags = options;
}
// Builds the actual configuration
// that the NativeTaskDialog (and underlying Win32 API)
// expects, by parsing the various control
// lists, marshalling to the unmanaged heap, etc.
private void ApplyControlConfiguration(NativeTaskDialogSettings settings)
{
// Deal with progress bars/marquees.
if (progressBar != null)
{
if (progressBar.State == TaskDialogProgressBarState.Marquee)
settings.NativeConfiguration.dwFlags |= TaskDialogNativeMethods.TASKDIALOG_FLAGS.TDF_SHOW_MARQUEE_PROGRESS_BAR;
else
settings.NativeConfiguration.dwFlags |= TaskDialogNativeMethods.TASKDIALOG_FLAGS.TDF_SHOW_PROGRESS_BAR;
}
// Build the native struct arrays that NativeTaskDialog
// needs - though NTD will handle
// the heavy lifting marshalling to make sure
// all the cleanup is centralized there.
if (buttons.Count > 0 || commandLinks.Count > 0)
{
// These are the actual arrays/lists of
// the structs that we'll copy to the
// unmanaged heap.
List<TaskDialogButtonBase> sourceList = (
buttons.Count > 0 ? buttons : commandLinks);
settings.Buttons = BuildButtonStructArray(sourceList);
// Apply option flag that forces all
// custom buttons to render as command links.
if (commandLinks.Count > 0)
settings.NativeConfiguration.dwFlags |=
TaskDialogNativeMethods.TASKDIALOG_FLAGS.TDF_USE_COMMAND_LINKS;
// Set default button and add elevation icons
// to appropriate buttons.
settings.NativeConfiguration.nDefaultButton =
FindDefaultButtonId(sourceList);
ApplyElevatedIcons(settings, sourceList);
}
if (radioButtons.Count > 0)
{
settings.RadioButtons = BuildButtonStructArray(radioButtons);
// Set default radio button - radio buttons don't support.
int defaultRadioButton = FindDefaultButtonId(radioButtons);
settings.NativeConfiguration.nDefaultRadioButton =
defaultRadioButton;
if (defaultRadioButton ==
TaskDialogNativeMethods.NO_DEFAULT_BUTTON_SPECIFIED)
settings.NativeConfiguration.dwFlags |= TaskDialogNativeMethods.TASKDIALOG_FLAGS.TDF_NO_DEFAULT_RADIO_BUTTON;
}
}
private static TaskDialogNativeMethods.TASKDIALOG_BUTTON[] BuildButtonStructArray(List<TaskDialogButtonBase> controls)
{
TaskDialogNativeMethods.TASKDIALOG_BUTTON[] buttonStructs;
TaskDialogButtonBase button;
int totalButtons = controls.Count;
buttonStructs = new TaskDialogNativeMethods.TASKDIALOG_BUTTON[totalButtons];
for (int i = 0; i < totalButtons; i++)
{
button = controls[i];
buttonStructs[i] = new TaskDialogNativeMethods.TASKDIALOG_BUTTON(button.Id, button.ToString());
}
return buttonStructs;
}
// Searches list of controls and returns the ID of
// the default control, or null if no default was specified.
private static int FindDefaultButtonId(List<TaskDialogButtonBase> controls)
{
int found = TaskDialogNativeMethods.NO_DEFAULT_BUTTON_SPECIFIED;
foreach (TaskDialogButtonBase control in controls)
{
if (control.Default)
{
// Check if we've found a default in this list already.
if (found != TaskDialogNativeMethods.NO_DEFAULT_BUTTON_SPECIFIED)
throw new InvalidOperationException("Can't have more than one default button of a given type.");
return control.Id;
}
}
return found;
}
private static void ApplyElevatedIcons(NativeTaskDialogSettings settings, List<TaskDialogButtonBase> controls)
{
foreach (TaskDialogButton control in controls)
{
if (control.ShowElevationIcon)
{
if (settings.ElevatedButtons == null)
settings.ElevatedButtons = new List<int>();
settings.ElevatedButtons.Add(control.Id);
}
}
}
private void ApplySupplementalSettings(NativeTaskDialogSettings settings)
{
if (progressBar != null)
{
if (progressBar.State != TaskDialogProgressBarState.Marquee)
{
settings.ProgressBarMinimum = progressBar.Minimum;
settings.ProgressBarMaximum = progressBar.Maximum;
settings.ProgressBarValue = progressBar.Value;
settings.ProgressBarState = progressBar.State;
}
}
if (HelpInvoked != null)
settings.InvokeHelp = true;
}
// Here we walk our controls collection and
// sort the various controls by type.
private void SortDialogControls()
{
foreach (TaskDialogControl control in controls)
{
if (control is TaskDialogButtonBase && String.IsNullOrEmpty(((TaskDialogButtonBase)control).Text))
{
if (control is TaskDialogCommandLink && String.IsNullOrEmpty(((TaskDialogCommandLink)control).Instruction))
throw new InvalidOperationException(
"Button text must be non-empty");
}
// Loop through child controls
// and sort the controls based on type.
if (control is TaskDialogCommandLink)
{
commandLinks.Add((TaskDialogCommandLink)control);
}
else if (control is TaskDialogRadioButton)
{
if (radioButtons == null)
radioButtons = new List<TaskDialogButtonBase>();
radioButtons.Add((TaskDialogRadioButton)control);
}
else if (control is TaskDialogButtonBase)
{
if (buttons == null)
buttons = new List<TaskDialogButtonBase>();
buttons.Add((TaskDialogButtonBase)control);
}
else if (control is TaskDialogProgressBar)
{
progressBar = (TaskDialogProgressBar)control;
}
else
{
throw new ArgumentException("Unknown dialog control type.");
}
}
}
#endregion
#region Helpers
// Helper to map the standard button IDs returned by
// TaskDialogIndirect to the standard button ID enum -
// note that we can't just cast, as the Win32
// typedefs differ incoming and outgoing.
private static TaskDialogStandardButtons MapButtonIdToStandardButton(int id)
{
switch ((TaskDialogNativeMethods.TASKDIALOG_COMMON_BUTTON_RETURN_ID)id)
{
case TaskDialogNativeMethods.TASKDIALOG_COMMON_BUTTON_RETURN_ID.IDOK:
return TaskDialogStandardButtons.Ok;
case TaskDialogNativeMethods.TASKDIALOG_COMMON_BUTTON_RETURN_ID.IDCANCEL:
return TaskDialogStandardButtons.Cancel;
case TaskDialogNativeMethods.TASKDIALOG_COMMON_BUTTON_RETURN_ID.IDABORT:
// Included for completeness in API -
// we can't pass in an Abort standard button.
return TaskDialogStandardButtons.None;
case TaskDialogNativeMethods.TASKDIALOG_COMMON_BUTTON_RETURN_ID.IDRETRY:
return TaskDialogStandardButtons.Retry;
case TaskDialogNativeMethods.TASKDIALOG_COMMON_BUTTON_RETURN_ID.IDIGNORE:
// Included for completeness in API -
// we can't pass in an Ignore standard button.
return TaskDialogStandardButtons.None;
case TaskDialogNativeMethods.TASKDIALOG_COMMON_BUTTON_RETURN_ID.IDYES:
return TaskDialogStandardButtons.Yes;
case TaskDialogNativeMethods.TASKDIALOG_COMMON_BUTTON_RETURN_ID.IDNO:
return TaskDialogStandardButtons.No;
case TaskDialogNativeMethods.TASKDIALOG_COMMON_BUTTON_RETURN_ID.IDCLOSE:
return TaskDialogStandardButtons.Close;
default:
return TaskDialogStandardButtons.None;
}
}
private void ThrowIfDialogShowing(string message)
{
if (NativeDialogShowing)
throw new NotSupportedException(message);
}
private bool NativeDialogShowing
{
get
{
return (nativeDialog != null)
&& (nativeDialog.ShowState == DialogShowState.Showing ||
nativeDialog.ShowState == DialogShowState.Closing);
}
}
// NOTE: we are going to require names be unique
// across both buttons and radio buttons,
// even though the Win32 API allows them to be separate.
private TaskDialogButtonBase GetButtonForId(int id)
{
return (TaskDialogButtonBase)controls.GetControlbyId(id);
}
#endregion
#region IDialogControlHost Members
// We're explicitly implementing this interface
// as the user will never need to know about it
// or use it directly - it is only for the internal
// implementation of "pseudo controls" within
// the dialogs.
// Called whenever controls are being added
// to or removed from the dialog control collection.
bool IDialogControlHost.IsCollectionChangeAllowed()
{
// Only allow additions to collection if dialog is NOT showing.
return !NativeDialogShowing;
}
// Called whenever controls have been added or removed.
void IDialogControlHost.ApplyCollectionChanged()
{
// If we're showing, we should never get here -
// the changing notification would have thrown and the
// property would not have been changed.
Debug.Assert(!NativeDialogShowing,
"Collection changed notification received despite show state of dialog");
}
// Called when a control currently in the collection
// has a property changing - this is
// basically to screen out property changes that
// cannot occur while the dialog is showing
// because the Win32 API has no way for us to
// propagate the changes until we re-invoke the Win32 call.
bool IDialogControlHost.IsControlPropertyChangeAllowed(string propertyName, DialogControl control)
{
Debug.Assert(control is TaskDialogControl,
"Property changing for a control that is not a TaskDialogControl-derived type");
Debug.Assert(propertyName != "Name",
"Name changes at any time are not supported - public API should have blocked this");
bool canChange = false;
if (!NativeDialogShowing)
{
// Certain properties can't be changed if the dialog is not showing
// we need a handle created before we can set these...
switch(propertyName)
{
case "Enabled":
canChange = false;
break;
default:
canChange = true;
break;
}
}
else
{
// If the dialog is showing, we can only
// allow some properties to change.
switch (propertyName)
{
// Properties that CAN'T be changed while dialog is showing.
case "Text":
case "Default":
canChange = false;
break;
// Properties that CAN be changed while dialog is showing.
case "ShowElevationIcon":
case "Enabled":
canChange = true;
break;
default:
Debug.Assert(true, "Unknown property name coming through property changing handler");
break;
}
}
return canChange;
}
// Called when a control currently in the collection
// has a property changed - this handles propagating
// the new property values to the Win32 API.
// If there isn't a way to change the Win32 value, then we
// should have already screened out the property set
// in NotifyControlPropertyChanging.
void IDialogControlHost.ApplyControlPropertyChange(string propertyName, DialogControl control)
{
// We only need to apply changes to the
// native dialog when it actually exists.
if (NativeDialogShowing)
{
if (control is TaskDialogProgressBar)
{
if (!progressBar.HasValidValues)
throw new ArgumentException(
"Progress bar must have a value between Minimum and Maximum.");
switch (propertyName)
{
case "State":
nativeDialog.UpdateProgressBarState(progressBar.State);
break;
case "Value":
nativeDialog.UpdateProgressBarValue(progressBar.Value);
break;
case "Minimum":
case "Maximum":
nativeDialog.UpdateProgressBarRange();
break;
default:
Debug.Assert(true, "Unknown property being set");
break;
}
}
else if (control is TaskDialogButton)
{
TaskDialogButton button = (TaskDialogButton)control;
switch (propertyName)
{
case "ShowElevationIcon":
nativeDialog.UpdateElevationIcon(button.Id, button.ShowElevationIcon);
break;
case "Enabled":
nativeDialog.UpdateButtonEnabled(button.Id, button.Enabled);
break;
default:
Debug.Assert(true, "Unknown property being set");
break;
}
}
else if (control is TaskDialogRadioButton)
{
TaskDialogRadioButton button = (TaskDialogRadioButton)control;
switch (propertyName)
{
case "Enabled":
nativeDialog.UpdateRadioButtonEnabled(button.Id, button.Enabled);
break;
default:
Debug.Assert(true, "Unknown property being set");
break;
}
}
else
{
// Do nothing with property change -
// note that this shouldn't ever happen, we should have
// either thrown on the changing event, or we handle above.
Debug.Assert(true, "Control property changed notification not handled properly - being ignored");
}
}
return;
}
#endregion
#region Event Percolation Methods
// All Raise*() methods are called by the
// NativeTaskDialog when various pseudo-controls
// are triggered.
internal void RaiseButtonClickEvent(int id)
{
// First check to see if the ID matches a custom button.
TaskDialogButtonBase button = GetButtonForId(id);
// If a custom button was found,
// raise the event - if not, it's a standard button, and
// we don't support custom event handling for the standard buttons
if (button != null)
button.RaiseClickEvent();
}
internal void RaiseHyperlinkClickEvent(string link)
{
EventHandler<TaskDialogHyperlinkClickedEventArgs> handler = HyperlinkClick;
if (handler != null)
{
handler(this, new TaskDialogHyperlinkClickedEventArgs(link));
}
}
// Gives event subscriber a chance to prevent
// the dialog from closing, based on
// the current state of the app and the button
// used to commit. Note that we don't
// have full access at this stage to
// the full dialog state.
internal int RaiseClosingEvent(int id)
{
EventHandler<TaskDialogClosingEventArgs> handler = Closing;
if (handler != null)
{
TaskDialogButtonBase customButton = null;
TaskDialogClosingEventArgs e = new TaskDialogClosingEventArgs();
// Try to identify the button - is it a standard one?
TaskDialogStandardButtons buttonClicked = MapButtonIdToStandardButton(id);
// If not, it had better be a custom button...
if (buttonClicked == TaskDialogStandardButtons.None)
{
customButton = GetButtonForId(id);
// ... or we have a problem.
if (customButton == null)
throw new InvalidOperationException("Bad button ID in closing event.");
e.CustomButton = customButton.Name;
e.TaskDialogResult = TaskDialogResult.CustomButtonClicked;
}
else
e.TaskDialogResult = (TaskDialogResult)buttonClicked;
// Raise the event and determine how to proceed.
handler(this, e);
if (e.Cancel)
return (int)HRESULT.S_FALSE;
}
// It's okay to let the dialog close.
return (int)HRESULT.S_OK;
}
internal void RaiseHelpInvokedEvent()
{
EventHandler handler = HelpInvoked;
if (handler != null)
handler(this, EventArgs.Empty);
}
internal void RaiseOpenedEvent()
{
EventHandler handler = Opened;
if (handler != null)
handler(this, EventArgs.Empty);
}
internal void RaiseTickEvent(int ticks)
{
EventHandler<TaskDialogTickEventArgs> handler = Tick;
if (handler != null)
handler(this, new TaskDialogTickEventArgs(ticks));
}
#endregion
#region Cleanup Code
// Cleans up data and structs from a single
// native dialog Show() invocation.
private void CleanUp()
{
// Reset values that would be considered
// 'volatile' in a given instance.
if (progressBar != null)
{
progressBar.Reset();
}
// Clean out sorted control lists -
// though we don't of course clear the main controls collection,
// so the controls are still around; we'll
// resort on next show, since the collection may have changed.
if (buttons != null)
buttons.Clear();
if (commandLinks != null)
commandLinks.Clear();
if (radioButtons != null)
radioButtons.Clear();
progressBar = null;
// Have the native dialog clean up the rest.
if (nativeDialog != null)
nativeDialog.Dispose();
}
// Dispose pattern - cleans up data and structs for
// a) any native dialog currently showing, and
// b) anything else that the outer TaskDialog has.
private bool disposed;
/// <summary>
/// Dispose TaskDialog Resources
/// </summary>
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
/// <summary>
/// TaskDialog Finalizer
/// </summary>
~TaskDialog()
{
Dispose(false);
}
/// <summary>
/// Dispose TaskDialog Resources
/// </summary>
/// <param name="disposing">If true, indicates that this is being called via Dispose rather than via the finalizer.</param>
public virtual void Dispose(bool disposing)
{
if (!disposed)
{
disposed = true;
if (disposing)
{
// Clean up managed resources.
if (nativeDialog != null && nativeDialog.ShowState == DialogShowState.Showing)
{
nativeDialog.NativeClose(TaskDialogResult.Cancel);
}
buttons = null;
radioButtons = null;
commandLinks = null;
}
// Clean up unmanaged resources SECOND, NTD counts on
// being closed before being disposed.
if (nativeDialog != null)
{
nativeDialog.Dispose();
nativeDialog = null;
}
if (staticDialog != null)
{
staticDialog.Dispose();
staticDialog = null;
}
}
}
#endregion
/// <summary>
/// Indicates whether this feature is supported on the current platform.
/// </summary>
public static bool IsPlatformSupported
{
get
{
// We need Windows Vista onwards ...
return CoreHelpers.RunningOnVista;
}
}
}
}
| |
using UnityEngine;
using Casanova.Prelude;
using System.Linq;
using System;
using System.Collections.Generic;
public enum RuleResult { Done, Working }
namespace Casanova.Prelude
{
public class Tuple<T,E> {
public T Item1 { get; set;}
public E Item2 { get; set;}
public Tuple(T item1, E item2)
{
Item1 = item1;
Item2 = item2;
}
}
public static class MyExtensions
{
//public T this[List<T> list]
//{
// get { return list.ElementAt(0); }
//}
public static T Head<T>(this List<T> list) { return list.ElementAt(0); }
public static T Head<T>(this IEnumerable<T> list) { return list.ElementAt(0); }
public static int Length<T>(this List<T> list) { return list.Count; }
public static int Length<T>(this IEnumerable<T> list) { return list.ToList<T>().Count; }
}
public class Cons<T> : IEnumerable<T>
{
public class Enumerator : IEnumerator<T>
{
public Enumerator(Cons<T> parent)
{
firstEnumerated = 0;
this.parent = parent;
tailEnumerator = parent.tail.GetEnumerator();
}
byte firstEnumerated;
Cons<T> parent;
IEnumerator<T> tailEnumerator;
public T Current
{
get
{
if (firstEnumerated == 0) return default(T);
if (firstEnumerated == 1) return parent.head;
else return tailEnumerator.Current;
}
}
object System.Collections.IEnumerator.Current { get { throw new Exception("Empty sequence has no elements"); } }
public bool MoveNext()
{
if (firstEnumerated == 0)
{
if (parent.head == null) return false;
firstEnumerated++;
return true;
}
if (firstEnumerated == 1) firstEnumerated++;
return tailEnumerator.MoveNext();
}
public void Reset() { firstEnumerated = 0; tailEnumerator.Reset(); }
public void Dispose() { }
}
T head;
IEnumerable<T> tail;
public Cons(T head, IEnumerable<T> tail)
{
this.head = head;
this.tail = tail;
}
public IEnumerator<T> GetEnumerator()
{
return new Enumerator(this);
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return new Enumerator(this);
}
}
public class Empty<T> : IEnumerable<T>
{
public Empty() { }
public class Enumerator : IEnumerator<T>
{
public T Current { get { throw new Exception("Empty sequence has no elements"); } }
object System.Collections.IEnumerator.Current { get { throw new Exception("Empty sequence has no elements"); } }
public bool MoveNext() { return false; }
public void Reset() { }
public void Dispose() { }
}
public IEnumerator<T> GetEnumerator()
{
return new Enumerator();
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return new Enumerator();
}
}
public abstract class Option<T> : IComparable, IEquatable<Option<T>>
{
public bool IsSome;
public bool IsNone { get { return !IsSome; } }
protected abstract Just<T> Some { get; }
public U Match<U>(Func<T,U> f, Func<U> g) {
if (this.IsSome)
return f(this.Some.Value);
else
return g();
}
public bool Equals(Option<T> b)
{
return this.Match(
x => b.Match(
y => x.Equals(y),
() => false),
() => b.Match(
y => false,
() => true));
}
public override bool Equals(System.Object other)
{
if (other == null) return false;
if (other is Option<T>)
{
var other1 = other as Option<T>;
return this.Equals(other1);
}
return false;
}
public override int GetHashCode() { return this.GetHashCode(); }
public static bool operator ==(Option<T> a, Option<T> b)
{
if ((System.Object)a == null || (System.Object)b == null) return System.Object.Equals(a, b);
return a.Equals(b);
}
public static bool operator !=(Option<T> a, Option<T> b)
{
if ((System.Object)a == null || (System.Object)b == null) return System.Object.Equals(a, b);
return !(a.Equals(b));
}
public int CompareTo(object obj)
{
if (obj == null) return 1;
if (obj is Option<T>)
{
var obj1 = obj as Option<T>;
if (this.Equals(obj1)) return 0;
}
return -1;
}
abstract public T Value { get; }
public override string ToString()
{
return "Option<" + typeof(T).ToString() + ">";
}
}
public class Just<T> : Option<T>
{
T elem;
public Just(T elem) { this.elem = elem; this.IsSome = true; }
protected override Just<T> Some { get { return this; } }
public override T Value { get { return elem; } }
}
public class Nothing<T> : Option<T>
{
public Nothing() { this.IsSome = false; }
protected override Just<T> Some { get { return null; } }
public override T Value { get { throw new Exception("Cant get a value from a None object"); } }
}
public class Utils
{
public static T IfThenElse<T>(Func<bool> c, Func<T> t, Func<T> e)
{
if (c())
return t();
else
return e();
}
}
}
public class FastStack
{
public int[] Elements;
public int Top;
public FastStack(int elems)
{
Top = 0;
Elements = new int[elems];
}
public void Clear() { Top = 0; }
public void Push(int x) { Elements[Top++] = x; }
}
public class RuleTable
{
public RuleTable(int elems)
{
ActiveIndices = new FastStack(elems);
SupportStack = new FastStack(elems);
ActiveSlots = new bool[elems];
}
public FastStack ActiveIndices;
public FastStack SupportStack;
public bool[] ActiveSlots;
public void Add(int i)
{
if (!ActiveSlots[i])
{
ActiveSlots[i] = true;
ActiveIndices.Push(i);
}
}
}
public class World : MonoBehaviour{
void Update () { Update(Time.deltaTime, this); }
public void Start()
{ Factor = 0f;
UnityCube = UnityCube.Find();
}
public UnityCube UnityCube;
public UnityEngine.Color Color{ set{UnityCube.Color = value; }
}
public System.Boolean useGUILayout{ get { return UnityCube.useGUILayout; }
set{UnityCube.useGUILayout = value; }
}
public System.Boolean enabled{ get { return UnityCube.enabled; }
set{UnityCube.enabled = value; }
}
public UnityEngine.Transform transform{ get { return UnityCube.transform; }
}
public UnityEngine.Rigidbody rigidbody{ get { return UnityCube.rigidbody; }
}
public UnityEngine.Rigidbody2D rigidbody2D{ get { return UnityCube.rigidbody2D; }
}
public UnityEngine.Camera camera{ get { return UnityCube.camera; }
}
public UnityEngine.Light light{ get { return UnityCube.light; }
}
public UnityEngine.Animation animation{ get { return UnityCube.animation; }
}
public UnityEngine.ConstantForce constantForce{ get { return UnityCube.constantForce; }
}
public UnityEngine.Renderer renderer{ get { return UnityCube.renderer; }
}
public UnityEngine.AudioSource audio{ get { return UnityCube.audio; }
}
public UnityEngine.GUIText guiText{ get { return UnityCube.guiText; }
}
public UnityEngine.NetworkView networkView{ get { return UnityCube.networkView; }
}
public UnityEngine.GUIElement guiElement{ get { return UnityCube.guiElement; }
}
public UnityEngine.GUITexture guiTexture{ get { return UnityCube.guiTexture; }
}
public UnityEngine.Collider collider{ get { return UnityCube.collider; }
}
public UnityEngine.Collider2D collider2D{ get { return UnityCube.collider2D; }
}
public UnityEngine.HingeJoint hingeJoint{ get { return UnityCube.hingeJoint; }
}
public UnityEngine.ParticleEmitter particleEmitter{ get { return UnityCube.particleEmitter; }
}
public UnityEngine.ParticleSystem particleSystem{ get { return UnityCube.particleSystem; }
}
public UnityEngine.GameObject gameObject{ get { return UnityCube.gameObject; }
}
public System.Boolean active{ get { return UnityCube.active; }
set{UnityCube.active = value; }
}
public System.String tag{ get { return UnityCube.tag; }
set{UnityCube.tag = value; }
}
public System.String name{ get { return UnityCube.name; }
set{UnityCube.name = value; }
}
public UnityEngine.HideFlags hideFlags{ get { return UnityCube.hideFlags; }
set{UnityCube.hideFlags = value; }
}
public System.Single Factor;
public System.Single count_down1;
public void Update(float dt, World world) {
this.Rule0(dt, world);
this.Rule1(dt, world);
}
public void Rule0(float dt, World world)
{
UnityCube.Color = Color.Lerp(Color.white,Color.blue,Factor);
}
int s1=-1;
public void Rule1(float dt, World world){
switch (s1)
{
case -1:
if(!(UnityEngine.Input.GetKeyDown(KeyCode.Space)))
{
s1 = -1;
return; }else
{
goto case 5; }
case 5:
if(!(((1f) > (Factor))))
{
goto case 4; }else
{
Factor = ((Factor) + (0.02f));
s1 = 5;
return; }
case 4:
if(!(UnityEngine.Input.GetKeyDown(KeyCode.Space)))
{
s1 = 4;
return; }else
{
goto case 2; }
case 2:
if(!(((Factor) > (0f))))
{
goto case 0; }else
{
Factor = ((Factor) - (0.02f));
s1 = 2;
return; }
case 0:
count_down1 = 1f;
goto case 1;
case 1:
if(((count_down1) > (0f)))
{
count_down1 = ((count_down1) - (dt));
s1 = 1;
return; }else
{
s1 = -1;
return; }
default: return;}}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using PWLib.FileSyncLib;
namespace AutoUSBBackup
{
public class SpineThread : IDisposable
{
VolumeEventController mVolumeEventController = new VolumeEventController();
PWLib.BackgroundWorkerThread mWorkerThread;
Spine mSpine = null;
class QueuedRestoreInfo
{
public VolumeDescriptor mDescriptor = null;
public VolumeSnapshotRevision mVolumeRevision = null;
public string mDiskPath = "";
}
class QueuedBackupInfo
{
public Volume mVolume = null;
public bool mFirstBackupOnLoad = false;
}
class QueuedTransferInfo
{
public VolumeDescriptor mDescriptor = null;
public PWLib.UsbDrive.UsbDriveInfo mNewDrive = null;
}
class QueuedRemoveInfo
{
public VolumeDescriptor mDescriptor = null;
public bool mDeleteAllData = false;
}
volatile bool mForceFullBackup = false;
bool mFirstFullBackupSinceLoad = true;
DateTime mTimeOfLastBackupOfAllActiveVolumes = DateTime.Now;
public Spine Spine { get { return mSpine; } }
public VolumeEventController EventController { get { return mVolumeEventController; } }
public bool Disposed { get { return mWorkerThread.Disposed; } }
public DateTime TimeOfLastBackup { get { return mTimeOfLastBackupOfAllActiveVolumes; } }
public DateTime TimeForNextBackup { get { return mTimeOfLastBackupOfAllActiveVolumes + Config.Active.BackupInterval; } }
public TimeSpan NextBackupDueIn { get { return TimeForNextBackup - DateTime.Now; } }
public SpineThread()
{
mSpine = new Spine( mVolumeEventController );
VolumeSnapshotDirectory.IgnoredDirectoryNames.Add( "nobackup" );
VolumeSnapshotDirectory.IgnoredDirectoryNames.Add( "System Volume Information" );
mWorkerThread = new PWLib.BackgroundWorkerThread( 100 );
mWorkerThread.InitialisationTask += new PWLib.BackgroundWorkerThread.Task(OnWorkerThreadInit);
mWorkerThread.ShutdownTask += new PWLib.BackgroundWorkerThread.Task(OnWorkerShutdown);
mVolumeEventController.VolumeDescriptorActiveStateChanged += new VolumeDescriptorChangedHandler( mVolumeEventController_VolumeDescriptorActiveStateChanged );
mVolumeEventController.VolumeSourceActiveStateChanged += new VolumeSourceActiveChangedHandler( mVolumeEventController_VolumeSourceActiveStateChanged );
mWorkerThread.RegisterPersistentTask( new PWLib.BackgroundWorkerThread.Task( OnWorkerPersistentTask ), null );
}
void mVolumeEventController_VolumeDescriptorActiveStateChanged( VolumeDescriptor desc, bool isActive )
{
if ( desc.ReadyForBackup )
{
Log.WriteLine( LogType.TextLogVerbose, "Backing up volume as the descriptor (.vol) file state has recently changed" );
ForceBackup( desc.Volume );
}
}
void mVolumeEventController_VolumeSourceActiveStateChanged( Volume volume, bool isActive )
{
// Find relevant VolumeSource, then do a backup (if enabled on that particular volume)
try
{
if ( isActive )
{
lock ( VolumeDescriptorList.Instance.Descriptors )
{
if ( volume.Descriptor.ReadyForBackup )
{
// kick off first insert backup
Log.WriteLine( LogType.TextLogVerbose, "Backing up volume by volume source state change (normally usb stick being plugged in)" );
ForceBackup( volume );
}
}
}
}
catch ( System.Exception e )
{
Log.WriteException( "DeviceInserted failed", e );
}
}
public void Start()
{
mWorkerThread.Start();
}
void OnWorkerThreadInit( object userObject )
{
mTimeOfLastBackupOfAllActiveVolumes = DateTime.Now;
mSpine.Init();
mVolumeEventController.InvokeApplicationInitialised( this );
mForceFullBackup = true; // Do a full backup on startup on any inserted usb drives.
// TODO: Replace with this with something that can potentially cause an RC
System.Threading.Thread.Sleep( 5000 ); // wait 5 seconds after load before performing any backups to give time to load form
}
void OnWorkerPersistentTask( object userObject )
{
VolumeDescriptorList.Instance.CheckAvailability();
if ( !VolumeDescriptorList.Instance.AnyBusyVolumes )
{
DateTime testDT = DateTime.Now;
if ( mTimeOfLastBackupOfAllActiveVolumes + Config.Active.BackupInterval <= testDT || mForceFullBackup )
{
mForceFullBackup = false;
lock ( VolumeDescriptorList.Instance.Descriptors )
{
foreach ( VolumeDescriptor desc in VolumeDescriptorList.Instance.Descriptors )
{
if ( desc.ReadyForBackup )
{
Log.WriteLine( LogType.TextLogVerbose, "Adding intervaled backup to queue (" + desc.VolumeName + ")" );
ForceBackup( desc.Volume, mFirstFullBackupSinceLoad );
}
}
}
mFirstFullBackupSinceLoad = false;
mTimeOfLastBackupOfAllActiveVolumes = testDT;
}
}
}
public void CancelOperation()
{
if ( mSpine != null )
mSpine.CancelOperation();
}
void OnWorkerShutdown( object userObject )
{
mSpine.Dispose();
}
public void Dispose()
{
mWorkerThread.Dispose();
}
public bool WndProc( ref Message m )
{
if ( PWLib.UsbDrive.UsbDriveList.Instance != null )
return PWLib.UsbDrive.UsbDriveList.Instance.WndProc( ref m );
else
return true;
}
public void ForceFullBackup()
{
mForceFullBackup = true;
}
public void ForceBackup( Volume volume )
{
ForceBackup( volume, false );
}
public void ForceBackup( Volume volume, bool firstBackupOnLoad )
{
if ( volume.Descriptor.ReadyForBackup )
{
Log.WriteLine( LogType.TextLogVerbose, "Adding QueuedBackup (" + volume.Descriptor.VolumeName + ")" );
QueuedBackupInfo qbi = new QueuedBackupInfo();
qbi.mVolume = volume;
qbi.mFirstBackupOnLoad = firstBackupOnLoad;
mWorkerThread.RegisterOneShotTask( new PWLib.BackgroundWorkerThread.TaskPredicate( OnWorkerPredicate ),
new PWLib.BackgroundWorkerThread.Task( OnWorkerBackup ), new PWLib.BackgroundWorkerThread.TaskError( OnWorkerError ), qbi );
}
}
bool OnWorkerPredicate( object userObject )
{
return !VolumeDescriptorList.Instance.AnyBusyVolumes;
}
void OnWorkerBackup( object backupInfo )
{
QueuedBackupInfo backupVolume = (QueuedBackupInfo)backupInfo;
Log.WriteLine( LogType.TextLogVerbose, "Processing QueuedBackup (" + backupVolume.mVolume.Descriptor.VolumeName + ")" );
mSpine.BackupVolume( backupVolume.mVolume, backupVolume.mFirstBackupOnLoad );
}
void OnWorkerError( object userObject, Exception e )
{
Log.WriteException( "Spine.StartThread failed", e );
}
public void TransferVolume( VolumeDescriptor vid, PWLib.UsbDrive.UsbDriveInfo newDrive )
{
QueuedTransferInfo transferInfo = new QueuedTransferInfo();
transferInfo.mDescriptor = vid;
transferInfo.mNewDrive = newDrive;
mWorkerThread.RegisterOneShotTask( new PWLib.BackgroundWorkerThread.TaskPredicate( OnWorkerPredicate ),
new PWLib.BackgroundWorkerThread.Task( OnWorkerTransfer ), new PWLib.BackgroundWorkerThread.TaskError( OnWorkerError ), transferInfo );
}
void OnWorkerTransfer( object userObject )
{
}
public void RestoreVolume( VolumeDescriptor vid, VolumeSnapshotRevision revision, string onDiskPath )
{
if ( vid.ReadyForRestore )
{
Log.WriteLine( LogType.TextLogVerbose, "Adding QueuedRestore (" + vid.VolumeName + ")" );
QueuedRestoreInfo restoreInfo = new QueuedRestoreInfo();
restoreInfo.mDescriptor = vid;
restoreInfo.mVolumeRevision = revision;
restoreInfo.mDiskPath = onDiskPath;
mWorkerThread.RegisterOneShotTask( new PWLib.BackgroundWorkerThread.TaskPredicate( OnWorkerPredicate ),
new PWLib.BackgroundWorkerThread.Task( OnWorkerRestore ), new PWLib.BackgroundWorkerThread.TaskError( OnWorkerError ), restoreInfo );
}
}
void OnWorkerRestore( object userObject )
{
QueuedRestoreInfo restoreInfo = (QueuedRestoreInfo)userObject;
Log.WriteLine( LogType.TextLogVerbose, "Processing QueuedRestore (" + restoreInfo.mDescriptor.VolumeName + ")" );
if ( restoreInfo.mDescriptor.IsAvailable )
restoreInfo.mDescriptor.Volume.Restore( restoreInfo.mVolumeRevision, restoreInfo.mDiskPath );
}
public void FormatUsbDrive( PWLib.UsbDrive.UsbDriveInfo driveInfo )
{
mWorkerThread.RegisterOneShotTask( new PWLib.BackgroundWorkerThread.TaskPredicate( OnWorkerPredicate ),
new PWLib.BackgroundWorkerThread.Task( OnWorkerUsbFormat ), new PWLib.BackgroundWorkerThread.TaskError( OnWorkerError ), driveInfo );
}
void OnWorkerUsbFormat( object userObject )
{
PWLib.UsbDrive.UsbDriveInfo di = (PWLib.UsbDrive.UsbDriveInfo)userObject;
mSpine.FormatUsbDrive( di );
}
public void RemoveVolume( VolumeDescriptor desc, bool removeAllData )
{
QueuedRemoveInfo removeInfo = new QueuedRemoveInfo();
removeInfo.mDescriptor = desc;
removeInfo.mDeleteAllData = removeAllData;
mWorkerThread.RegisterOneShotTask( new PWLib.BackgroundWorkerThread.TaskPredicate( OnWorkerPredicate ),
new PWLib.BackgroundWorkerThread.Task( OnWorkerRemove ), new PWLib.BackgroundWorkerThread.TaskError( OnWorkerError ), removeInfo );
}
void OnWorkerRemove( object userObject )
{
QueuedRemoveInfo removeInfo = (QueuedRemoveInfo)userObject;
Log.WriteLine( LogType.TextLogVerbose, "Processing QueuedRemove (" + removeInfo.mDescriptor.VolumeName + ")" );
mSpine.RemoveVolume( removeInfo.mDescriptor, removeInfo.mDeleteAllData );
}
}
}
| |
/*
* MindTouch Core - open source enterprise collaborative networking
* Copyright (c) 2006-2010 MindTouch Inc.
* www.mindtouch.com [email protected]
*
* For community documentation and downloads visit www.opengarden.org;
* please review the licensing section.
*
* 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.
* http://www.gnu.org/copyleft/gpl.html
*/
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Security.Cryptography;
using System.Text;
using MindTouch.Deki.Data;
using MindTouch.Deki.Util;
using MindTouch.Dream;
using MindTouch.Security.Cryptography;
using MindTouch.Tasking;
using MindTouch.Web;
using MindTouch.Xml;
namespace MindTouch.Deki.Logic {
public enum LicenseStateType : byte {
UNDEFINED,
INVALID,
INACTIVE,
COMMUNITY,
TRIAL,
COMMERCIAL,
EXPIRED
};
public abstract class MindTouchLicenseException : Exception { }
public class MindTouchLicenseUserCreationException : MindTouchLicenseException { }
public class MindTouchLicenseInstanceException : MindTouchLicenseException { }
public class MindTouchLicenseInvalidOperationException : MindTouchLicenseException {
//--- Fields ---
public readonly string Operation;
//--- Constructors ---
public MindTouchLicenseInvalidOperationException(string operation) {
Operation = operation;
}
}
public class MindTouchLicenseTransitionException : MindTouchLicenseException {
//--- Fields ---
public readonly LicenseStateType CurrentState;
public readonly LicenseStateType ProposedState;
//--- Constructors ---
public MindTouchLicenseTransitionException(LicenseStateType currentState, LicenseStateType proposedState) {
CurrentState = currentState;
ProposedState = proposedState;
}
}
public class MindTouchTooManyUsersLicenseException : MindTouchLicenseException {
//--- Fields ---
public readonly uint CurrentActiveUsers;
public readonly uint MaxUsers;
public readonly uint UserDelta;
//--- Constructors ---
public MindTouchTooManyUsersLicenseException(uint currentActiveUsers, uint maxUsers, uint userDelta) {
CurrentActiveUsers = currentActiveUsers;
MaxUsers = maxUsers;
UserDelta = userDelta;
}
}
public class MindTouchNoNewUserLicenseException : MindTouchLicenseException {
//--- Fields ---
public readonly LicenseStateType CurrentLicenseState;
//--- Constructors ---
public MindTouchNoNewUserLicenseException(LicenseStateType currentLicenseState) {
CurrentLicenseState = currentLicenseState;
}
}
internal struct LicenseData {
//--- Fields ---
public readonly XDoc CurrentLicense;
public readonly LicenseStateType LicenseState;
public readonly DateTime LicenseStateChecked;
public readonly DateTime LicenseExpiration;
public readonly Permissions AnonymousPermissions;
//--- Constructors ---
public LicenseData(XDoc currentLicense, LicenseStateType licenseState, DateTime licenseExpiration, Permissions anonymousPermissions) {
this.CurrentLicense = currentLicense;
this.LicenseState = licenseState;
this.LicenseStateChecked = DateTime.UtcNow;
this.LicenseExpiration = licenseExpiration;
this.AnonymousPermissions = anonymousPermissions;
}
}
internal static class LicenseBL {
//--- Constants ---
private const int LICENSECHECKINTERVAL = 300; //seconds
private const int GRACE_PERIOD = 14; // days
public const string CONTENTRATING = "content-rating";
public const string CONTENTRATING_ENABLED = "enabled";
//--- Fields ---
private static readonly log4net.ILog _log = LogUtils.CreateLog();
private static readonly object _sync = new object();
//--- Properties ---
internal static LicenseStateType LicenseState { get { return DetermineCurrentLicenseState(); } }
internal static DateTime LicenseExpiration { get { return DekiService.License.LicenseExpiration; } }
private static Plug LicensePlug { get { return DekiService.Storage.At("license.xml"); } }
private static DekiWikiService DekiService { get { return ((DekiWikiService)DreamContext.Current.Service); } }
//--- Methods ---
internal static string GetCapability(string name) {
return DekiLicense.GetCapability(DekiService.License.CurrentLicense, name);
}
internal static void UpdateLicense(XDoc license) {
// verify that new license is valid
DekiLicense.Validate(license);
// check if new license can be accepted. An exception is thrown for invalid transitions
DateTime expiration;
Permissions anonymousPermissions;
LicenseStateType state = ValidateNewLicenseTransition(license, out expiration, out anonymousPermissions);
lock(_sync) {
//Save the license to Deki's storage service
LicensePlug.Put(DreamMessage.Ok(license));
// update in-memory license information
DekiService.License = new LicenseData(license, state, expiration, anonymousPermissions);
ConfigBL.ClearConfigCache();
}
}
internal static bool IsUserCreationAllowed(bool throwException) {
bool ret = true;
uint? maxUsers = null;
if (!IsLicenseValid()) {
if (throwException) {
throw new MindTouchNoNewUserLicenseException(DetermineCurrentLicenseState());
}
ret = false;
} else {
//Active-users not defined implies unlimited users
maxUsers = RetrieveLicense(false)["/license.private/grants/active-users"].AsUInt ?? uint.MaxValue;
}
uint currentUsers = DbUtils.CurrentSession.Users_GetCount();
if (currentUsers >= (maxUsers ?? 0)) {
ret = false;
if (throwException) {
throw new MindTouchLicenseUserCreationException();
}
}
return ret;
}
internal static bool IsDekiInstanceStartupAllowed(bool throwException) {
bool ret = true;
uint maxInstances;
switch (DetermineCurrentLicenseState()) {
case LicenseStateType.COMMERCIAL:
//Full license may have a limit on number of instances
maxInstances = RetrieveLicense(false)["/license.private/grants/active-sites"].AsUInt ?? uint.MaxValue;
break;
default:
//Invalid and expired license allows starting any number of (invalid/expired) instances.
maxInstances = uint.MaxValue;
break;
}
uint currentSites = ((DekiWikiService) DreamContext.Current.Service).Instancemanager.InstancesRunning;
if (currentSites >= maxInstances) {
ret = false;
if (throwException) {
throw new MindTouchLicenseInstanceException();
}
}
return ret;
}
internal static ulong LicensePermissionRevokeMask() {
if (IsLicenseValid()) {
return ~0UL;
}
return ~(ulong)PermissionSets.INVALID_LICENSE_REVOKE_LIST;
}
internal static ulong AnonymousUserMask(UserBE user) {
if(!UserBL.IsAnonymous(user)) {
return ~0UL;
}
return (ulong)DekiService.License.AnonymousPermissions;
}
internal static XDoc RetrieveCurrentLicense(bool publicOnly) {
if(DekiService.License.CurrentLicense == null || DekiService.License.CurrentLicense.IsEmpty) {
return XDoc.Empty;
}
return publicOnly ? DekiService.License.CurrentLicense["license.public"] : DekiService.License.CurrentLicense;
}
private static XDoc RetrieveLicense(bool publicOnly) {
XDoc license = XDoc.Empty;
// load license
DreamMessage msg = LicensePlug.GetAsync().Wait();
if (msg.IsSuccessful) {
try {
license = msg.ToDocument();
} catch(Exception x) {
_log.WarnExceptionFormat(x, "The commercial license could not be loaded");
license = XDoc.Empty;
}
}
// check if a license was found
if(license.IsEmpty) {
msg = Plug.New("resource://mindtouch.deki/MindTouch.Deki.Resources.license-community.xml").With(DreamOutParam.TYPE, MimeType.XML.ToString()).GetAsync().Wait();
if(msg.IsSuccessful) {
try {
license = msg.ToDocument();
} catch (Exception x) {
_log.WarnExceptionFormat(x, "The community license could not be loaded");
license = XDoc.Empty;
}
} else {
// unable to retrieve the license
_log.Warn("unable to retrieve the license built in community license");
}
}
// check if only the public part is required
if(publicOnly) {
license = license["license.public"];
}
return license;
}
private static bool IsLicenseValid() {
switch (DetermineCurrentLicenseState()) {
case LicenseStateType.INVALID:
case LicenseStateType.EXPIRED:
case LicenseStateType.INACTIVE:
return false;
default:
return true;
}
}
private static LicenseStateType DetermineCurrentLicenseState() {
LicenseData licenseData = DekiService.License;
LicenseStateType state = licenseData.LicenseState;
// Re-evaluate license after interval or if it's undefined
if((state == LicenseStateType.UNDEFINED) || ((DateTime.UtcNow - DekiService.License.LicenseStateChecked).TotalSeconds > LICENSECHECKINTERVAL)) {
lock(_sync) {
DateTime expiration;
XDoc license = RetrieveLicense(false);
Permissions anonymousPermissions;
DetermineLicenseState(license, out state, out expiration, out anonymousPermissions);
DekiService.License = new LicenseData(license, state, expiration, anonymousPermissions);
}
}
return state;
}
private static void DetermineLicenseState(XDoc license, out LicenseStateType state, out DateTime expiration, out Permissions anonymousPermissions) {
expiration = DateTime.MaxValue;
state = LicenseStateType.INVALID;
anonymousPermissions = PermissionSets.MINIMAL_ANONYMOUS_PERMISSIONS;
// check if a valid license was passed in
if((license == null) || license.IsEmpty) {
return;
}
// check if the deki assembly is signed
Assembly assembly = typeof(DekiWikiService).Assembly;
if(ArrayUtil.IsNullOrEmpty(assembly.GetName().GetPublicKey())) {
// no signature, default to community
_log.Warn("Unable to validate signature of license since the MindTouch Core service was not signed by MindTouch. Reverting to community edition.");
state = LicenseStateType.COMMUNITY;
anonymousPermissions = PermissionSets.ALL;
return;
}
// assembly is signed: validate xml signature
RSACryptoServiceProvider rsa = RSAUtil.ProviderFrom(assembly);
if((rsa == null) || !license.HasValidSignature(rsa)) {
_log.Warn("License failed XML validation");
state = LicenseStateType.INVALID;
return;
}
// check license matched product key
string productKey = license["licensee/product-key"].AsText;
if((productKey != null) && !productKey.EqualsInvariantIgnoreCase(StringUtil.ComputeHashString(DekiService.MasterApiKey, Encoding.UTF8))) {
_log.Warn("Invalid product-key in license");
state = LicenseStateType.INVALID;
return;
}
// determine license type
switch(license["@type"].AsText ?? "inactive") {
case "trial":
state = LicenseStateType.TRIAL;
break;
case "inactive":
state = LicenseStateType.INACTIVE;
break;
case "community":
state = LicenseStateType.COMMUNITY;
break;
case "commercial":
state = LicenseStateType.COMMERCIAL;
break;
default:
_log.Warn("Unknown license type");
state = LicenseStateType.INVALID;
break;
}
// check expiration
expiration = license["date.expiration"].AsDate ?? DateTime.MaxValue;
if(state == LicenseStateType.COMMERCIAL) {
// check if license is passed grace period
if(expiration <= DateTime.UtcNow.AddDays(-GRACE_PERIOD)) {
state = LicenseStateType.EXPIRED;
return;
}
} else if(expiration <= DateTime.UtcNow) {
state = LicenseStateType.EXPIRED;
return;
}
// check version
var licenseVersion = (license["version"].AsText ?? "*").Split('.');
var assemblyVersion = typeof(LicenseBL).Assembly.GetName().Version;
var appVersion = new[] { assemblyVersion.Major, assemblyVersion.Minor, assemblyVersion.Revision, assemblyVersion.Build };
for(int i = 0; (i < licenseVersion.Length) && (i < appVersion.Length); ++i) {
string pattern = licenseVersion[i];
int value;
if(!pattern.Equals("*") && (!int.TryParse(pattern, out value) || (value < appVersion[i]))) {
state = LicenseStateType.EXPIRED;
return;
}
}
// determine permissions for anonymous user
anonymousPermissions = PermissionsBL.MaskFromString(DekiLicense.GetCapability(license, "anonymous-permissions")) | PermissionSets.MINIMAL_ANONYMOUS_PERMISSIONS;
}
private static LicenseStateType ValidateNewLicenseTransition(XDoc licenseDoc, out DateTime expiration, out Permissions anonymousPermissions) {
/*
* State transitions:
* community -> community
* community -> commercial
* trial -> commercial
* trial -> trial
* commercial -> commercial
* expired -> trial
* expired -> commercial
* inactive -> trial
* inactive -> commercial
* invalid -> *
*/
// retrieve current license state
LicenseStateType currentState = DetermineCurrentLicenseState();
// retrieve desired license state
LicenseStateType proposedState;
DetermineLicenseState(licenseDoc, out proposedState, out expiration, out anonymousPermissions);
bool exception = true;
// check if the license transition is valid
if (proposedState == LicenseStateType.INVALID) {
// cannot switch to an invalid license
throw new DreamBadRequestException(DekiResources.LICENSE_UPDATE_INVALID);
}
if (proposedState == LicenseStateType.EXPIRED){
// cannot switch to an expired license
throw new DreamBadRequestException(string.Format(DekiResources.LICENSE_UPDATE_EXPIRED, expiration.ToString(DreamContext.Current.Culture)));
}
switch(currentState) {
case LicenseStateType.COMMUNITY:
switch(proposedState) {
case LicenseStateType.COMMUNITY:
case LicenseStateType.COMMERCIAL:
exception = false;
break;
}
break;
case LicenseStateType.INACTIVE:
switch(proposedState) {
case LicenseStateType.COMMERCIAL:
case LicenseStateType.TRIAL:
exception = false;
break;
}
break;
case LicenseStateType.TRIAL:
switch(proposedState) {
case LicenseStateType.COMMERCIAL:
case LicenseStateType.TRIAL:
exception = false;
break;
}
break;
case LicenseStateType.COMMERCIAL:
switch(proposedState) {
case LicenseStateType.COMMERCIAL:
exception = false;
break;
}
break;
case LicenseStateType.EXPIRED:
switch(proposedState) {
case LicenseStateType.TRIAL:
case LicenseStateType.COMMERCIAL:
exception = false;
break;
}
break;
case LicenseStateType.INVALID:
exception = false;
break;
default:
throw new DreamBadRequestException(DekiResources.LICENSE_UPDATE_INVALID);
}
// verify that this license of for this installations
if (exception) {
throw new MindTouchLicenseTransitionException(currentState, proposedState);
}
//Extra validation when updating or transitioning to commerical license
if(proposedState == LicenseStateType.COMMERCIAL) {
//user count
uint? maxUsers = licenseDoc["/license.private/grants/active-users"].AsUInt;
if(maxUsers != null) {
//Reject license if its user limit is lower than current number of users
uint currentActiveUsers = DbUtils.CurrentSession.Users_GetCount();
if(currentActiveUsers > maxUsers.Value) {
uint userDelta = currentActiveUsers - maxUsers.Value;
throw new MindTouchTooManyUsersLicenseException(currentActiveUsers, maxUsers.Value, userDelta);
}
}
}
return proposedState;
}
}
}
| |
/**
* \file NETGeographicLib\GeodesicPanel.cs
* \brief NETGeographicLib.Geodesic example
*
* NETGeographicLib.Geodesic,
* NETGeographicLib.GeodesicLine,
* NETGeographicLib.GeodesicExact,
* NETGeographicLib.GeodesicLineExact
*
* NETGeographicLib is copyright (c) Scott Heiman (2013)
* GeographicLib is Copyright (c) Charles Karney (2010-2012)
* <[email protected]> and licensed under the MIT/X11 License.
* For more information, see
* https://geographiclib.sourceforge.io/
**********************************************************************/
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using NETGeographicLib;
namespace Projections
{
public partial class GeodesicPanel : UserControl
{
public string warning = "GeographicLib Error";
public string warning2 = "Data Conversion Error";
enum Function
{
Direct = 0,
Inverse = 1
};
Function m_function = Function.Direct;
enum Variable
{
Distance = 0,
ArcLength = 2
};
Variable m_variable = Variable.Distance;
enum Classes
{
GEODESIC = 0,
GEODESICEXACT= 1,
GEODESICLINE = 2,
GEODESICLINEEXACT = 3
};
Classes m_class = Classes.GEODESIC;
Geodesic m_geodesic = null;
public GeodesicPanel()
{
InitializeComponent();
m_tooltips.SetToolTip(button1, "Performs the selected function with the selected class");
m_tooltips.SetToolTip(m_setButton, "Sets the ellipsoid attributes");
m_tooltips.SetToolTip(m_validateButton, "Validates Geodesic, GeodesicExact, GeodesicLine, and GeodesicLineExact interfaces");
try
{
m_geodesic = new Geodesic();
}
catch (GeographicErr err)
{
MessageBox.Show(err.Message, warning, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
m_equatorialRadiusTextBox.Text = m_geodesic.EquatorialRadius.ToString();
m_flatteningTextBox.Text = m_geodesic.Flattening.ToString();
m_functionComboBox.SelectedIndex = 0;
m_classComboBox.SelectedIndex = 0;
}
// gets the equatorial radius and flattening and creates a new Geodesic
private void OnSet(object sender, EventArgs e)
{
try
{
double radius = Double.Parse(m_equatorialRadiusTextBox.Text);
double flattening = Double.Parse(m_flatteningTextBox.Text);
m_geodesic = new Geodesic(radius, flattening);
}
catch (GeographicErr err)
{
MessageBox.Show(err.Message, warning, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
catch (Exception err2)
{
MessageBox.Show(err2.Message, warning2, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
// Gets the input parameters and calls the appropriate function
private void OnForward(object sender, EventArgs e)
{
double origLatitude = 0.0, origLongitude = 0.0, origAzimuth = 0.0,
distance = 0.0, finalLatitude = 0.0, finalLongitude = 0.0;
// get & validate inputs
try
{
if ( m_function == Function.Direct )
{
distance = Double.Parse( m_variable == Variable.Distance ?
m_distanceTextBox.Text : m_ArcLengthTextBox.Text );
origAzimuth = Double.Parse( m_originAzimuthTextBox.Text );
if ( origAzimuth < -180.0 || origAzimuth > 180.0 )
{
m_originAzimuthTextBox.Focus();
throw new Exception( "Range Error: -180 <= initial azimuth <= 180 degrees" );
}
}
else
{
finalLatitude = Double.Parse( m_finalLatitudeTextBox.Text );
if (finalLatitude < -90.0 || finalLatitude > 90.0)
{
m_finalLatitudeTextBox.Focus();
throw new Exception("Range Error: -90 <= final latitude <= 90 degrees");
}
finalLongitude = Double.Parse( m_finalLongitudeTextBox.Text );
if (finalLongitude < -540.0 || finalLongitude > 540.0)
{
m_finalLongitudeTextBox.Focus();
throw new Exception("Range Error: -540 <= final longitude <= 540 degrees");
}
}
origLatitude = Double.Parse( m_originLatitudeTextBox.Text );
if (origLatitude < -90.0 || origLatitude > 90.0)
{
m_originLatitudeTextBox.Focus();
throw new Exception("Range Error: -90 <= initial latitude <= 90 degrees");
}
origLongitude = Double.Parse(m_originLongitudeTextBox.Text);
if (origLongitude < -540.0 || origLongitude > 540.0)
{
m_originLongitudeTextBox.Focus();
throw new Exception("Range Error: -540 <= initial longitude <= 540 degrees");
}
}
catch ( Exception xcpt )
{
MessageBox.Show(xcpt.Message, warning2, MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
// excute the appropriate function.
double finalAzimuth = 0.0, reducedLength = 0.0, M12 = 0.0, M21 = 0.0,
S12 = 0.0, arcDistance = 0.0;
int sw = (int)m_function | (int)m_variable;
if (sw == 3) sw = 1; // cases 1 & 3 are identical.
try
{
switch (m_class)
{
case Classes.GEODESIC:
switch (sw)
{
case 0: // function == Direct, variable == distance
m_ArcLengthTextBox.Text =
m_geodesic.Direct(origLatitude, origLongitude, origAzimuth, distance,
out finalLatitude, out finalLongitude, out finalAzimuth, out reducedLength,
out M12, out M21, out S12).ToString();
m_finalLatitudeTextBox.Text = finalLatitude.ToString();
m_finalLongitudeTextBox.Text = finalLongitude.ToString();
break;
case 1: // function == Inverse, variable == distance
m_ArcLengthTextBox.Text =
m_geodesic.Inverse(origLatitude, origLongitude, finalLatitude, finalLongitude,
out distance, out origAzimuth, out finalAzimuth, out reducedLength, out M12,
out M21, out S12).ToString();
m_distanceTextBox.Text = distance.ToString();
m_originAzimuthTextBox.Text = origAzimuth.ToString();
break;
case 2: // function == Direct, variable == arc length
m_geodesic.ArcDirect(origLatitude, origLongitude, origAzimuth, distance,
out finalLatitude, out finalLongitude, out finalAzimuth, out arcDistance,
out reducedLength, out M12, out M21, out S12);
m_distanceTextBox.Text = arcDistance.ToString();
m_finalLatitudeTextBox.Text = finalLatitude.ToString();
m_finalLongitudeTextBox.Text = finalLongitude.ToString();
break;
}
m_finalAzimuthTextBox.Text = finalAzimuth.ToString();
m_reducedLengthTextBox.Text = reducedLength.ToString();
m_M12TextBox.Text = M12.ToString();
m_M21TextBox.Text = M21.ToString();
m_S12TextBox.Text = S12.ToString();
break;
case Classes.GEODESICEXACT:
GeodesicExact ge = new GeodesicExact(m_geodesic.EquatorialRadius, m_geodesic.Flattening);
switch (sw)
{
case 0: // function == Direct, variable == distance
m_ArcLengthTextBox.Text =
ge.Direct(origLatitude, origLongitude, origAzimuth, distance,
out finalLatitude, out finalLongitude, out finalAzimuth, out reducedLength,
out M12, out M21, out S12).ToString();
m_finalLatitudeTextBox.Text = finalLatitude.ToString();
m_finalLongitudeTextBox.Text = finalLongitude.ToString();
break;
case 1: // function == Inverse, variable == distance
m_ArcLengthTextBox.Text =
ge.Inverse(origLatitude, origLongitude, finalLatitude, finalLongitude,
out distance, out origAzimuth, out finalAzimuth, out reducedLength, out M12,
out M21, out S12).ToString();
m_distanceTextBox.Text = distance.ToString();
m_originAzimuthTextBox.Text = origAzimuth.ToString();
break;
case 2: // function == Direct, variable == arc length
ge.ArcDirect(origLatitude, origLongitude, origAzimuth, distance,
out finalLatitude, out finalLongitude, out finalAzimuth, out arcDistance,
out reducedLength, out M12, out M21, out S12);
m_distanceTextBox.Text = arcDistance.ToString();
m_finalLatitudeTextBox.Text = finalLatitude.ToString();
m_finalLongitudeTextBox.Text = finalLongitude.ToString();
break;
}
m_finalAzimuthTextBox.Text = finalAzimuth.ToString();
m_reducedLengthTextBox.Text = reducedLength.ToString();
m_M12TextBox.Text = M12.ToString();
m_M21TextBox.Text = M21.ToString();
m_S12TextBox.Text = S12.ToString();
break;
case Classes.GEODESICLINE:
GeodesicLine gl = new GeodesicLine(m_geodesic, origLatitude, origLongitude, origAzimuth, Mask.ALL);
switch (sw)
{
case 0: // function == Direct, variable == distance
m_ArcLengthTextBox.Text =
gl.Position(distance,
out finalLatitude, out finalLongitude, out finalAzimuth, out reducedLength,
out M12, out M21, out S12).ToString();
m_finalLatitudeTextBox.Text = finalLatitude.ToString();
m_finalLongitudeTextBox.Text = finalLongitude.ToString();
break;
case 1: // function == Inverse, variable == distance
throw new Exception("GeodesicLine does not have an Inverse function");
case 2: // function == Direct, variable == arc length
gl.ArcPosition(distance,
out finalLatitude, out finalLongitude, out finalAzimuth, out arcDistance,
out reducedLength, out M12, out M21, out S12);
m_distanceTextBox.Text = arcDistance.ToString();
m_finalLatitudeTextBox.Text = finalLatitude.ToString();
m_finalLongitudeTextBox.Text = finalLongitude.ToString();
break;
}
m_finalAzimuthTextBox.Text = finalAzimuth.ToString();
m_reducedLengthTextBox.Text = reducedLength.ToString();
m_M12TextBox.Text = M12.ToString();
m_M21TextBox.Text = M21.ToString();
m_S12TextBox.Text = S12.ToString();
break;
case Classes.GEODESICLINEEXACT:
GeodesicLineExact gle = new GeodesicLineExact(origLatitude, origLongitude, origAzimuth, Mask.ALL);
switch (sw)
{
case 0: // function == Direct, variable == distance
m_ArcLengthTextBox.Text =
gle.Position(distance,
out finalLatitude, out finalLongitude, out finalAzimuth, out reducedLength,
out M12, out M21, out S12).ToString();
m_finalLatitudeTextBox.Text = finalLatitude.ToString();
m_finalLongitudeTextBox.Text = finalLongitude.ToString();
break;
case 1: // function == Inverse, variable == distance
throw new Exception("GeodesicLineExact does not have an Inverse function");
case 2: // function == Direct, variable == arc length
gle.ArcPosition(distance,
out finalLatitude, out finalLongitude, out finalAzimuth, out arcDistance,
out reducedLength, out M12, out M21, out S12);
m_distanceTextBox.Text = arcDistance.ToString();
m_finalLatitudeTextBox.Text = finalLatitude.ToString();
m_finalLongitudeTextBox.Text = finalLongitude.ToString();
break;
}
m_finalAzimuthTextBox.Text = finalAzimuth.ToString();
m_reducedLengthTextBox.Text = reducedLength.ToString();
m_M12TextBox.Text = M12.ToString();
m_M21TextBox.Text = M21.ToString();
m_S12TextBox.Text = S12.ToString();
break;
}
}
catch (Exception err)
{
MessageBox.Show(err.Message, warning, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
// gui stuff
private void OnDistance(object sender, EventArgs e)
{
m_distanceTextBox.ReadOnly = false;
m_ArcLengthTextBox.ReadOnly = true;
m_variable = Variable.Distance;
}
// gui stuff
private void OnArcLength(object sender, EventArgs e)
{
m_distanceTextBox.ReadOnly = true;
m_ArcLengthTextBox.ReadOnly = false;
m_variable = Variable.ArcLength;
}
// gui stuff
private void OnFunction(object sender, EventArgs e)
{
m_function = (Function)m_functionComboBox.SelectedIndex;
switch (m_function)
{
case Function.Direct:
m_distanceTextBox.ReadOnly = m_variable == Variable.ArcLength;
m_ArcLengthTextBox.ReadOnly = m_variable == Variable.Distance;
m_originAzimuthTextBox.ReadOnly = false;
m_finalLatitudeTextBox.ReadOnly = true;
m_finalLongitudeTextBox.ReadOnly = true;
break;
case Function.Inverse:
m_distanceTextBox.ReadOnly = true;
m_ArcLengthTextBox.ReadOnly = true;
m_originAzimuthTextBox.ReadOnly = true;
m_finalLatitudeTextBox.ReadOnly = false;
m_finalLongitudeTextBox.ReadOnly = false;
break;
}
}
// gui stuff
private void OnClassChanged(object sender, EventArgs e)
{
m_class = (Classes)m_classComboBox.SelectedIndex;
}
// a simple validation function...does not change GUI elements
private void OnValidate(object sender, EventArgs e)
{
double finalAzimuth = 0.0, reducedLength = 0.0, M12 = 0.0, M21 = 0.0,
S12 = 0.0, arcDistance = 0.0, finalLatitude = 0.0, finalLongitude = 0.0,
distance = 0.0;
try
{
Geodesic g = new Geodesic();
g = new Geodesic(g.EquatorialRadius, g.Flattening);
arcDistance = g.Direct(32.0, -86.0, 45.0, 20000.0, out finalLatitude, out finalLongitude,
out finalAzimuth, out reducedLength, out M12, out M21,
out S12);
double flat = 0.0, flon = 0.0, faz = 0.0, frd = 0.0, fm12 = 0.0, fm21 = 0.0, fs12 = 0.0, fad = 0.0;
fad = g.Direct(32.0, -86.0, 45.0, 20000.0, out flat, out flon);
if (fad != arcDistance || flat != finalLatitude || flon != finalLongitude)
throw new Exception("Geodesic.Direct #1 failed");
fad = g.Direct(32.0, -86.0, 45.0, 20000.0, out flat, out flon, out faz);
if (fad != arcDistance || flat != finalLatitude || flon != finalLongitude ||
faz != finalAzimuth)
throw new Exception("Geodesic.Direct #2 failed");
fad = g.Direct(32.0, -86.0, 45.0, 20000.0, out flat, out flon, out faz, out frd);
if (fad != arcDistance || flat != finalLatitude || flon != finalLongitude ||
faz != finalAzimuth || frd != reducedLength)
throw new Exception("Geodesic.Direct #3 failed");
fad = g.Direct(32.0, -86.0, 45.0, 20000.0, out flat, out flon, out faz, out fm12, out fm21);
if (fad != arcDistance || flat != finalLatitude || flon != finalLongitude ||
faz != finalAzimuth || fm12 != M12 || fm21 != M21)
throw new Exception("Geodesic.Direct #4 failed");
fad = g.Direct(32.0, -86.0, 45.0, 20000.0, out flat, out flon, out faz, out frd, out fm12, out fm21);
if (fad != arcDistance || flat != finalLatitude || flon != finalLongitude ||
faz != finalAzimuth || frd != reducedLength || fm12 != M12 || fm21 != M21)
throw new Exception("Geodesic.Direct #5 failed");
double outd = 0.0;
fad = g.GenDirect(32.0, -86.0, 45.0, false, 20000.0, Geodesic.mask.ALL, out flat, out flon, out faz, out outd, out frd, out fm12, out fm21, out fs12);
if (fad != arcDistance || flat != finalLatitude || flon != finalLongitude ||
faz != finalAzimuth || frd != reducedLength || fm12 != M12 || fm21 != M21 ||
outd != 20000.0 || fs12 != S12)
throw new Exception("Geodesic.GenDirect (false) failed");
g.ArcDirect(32.0, -86.0, 45.0, 1.0, out finalLatitude, out finalLongitude, out finalAzimuth,
out arcDistance, out reducedLength, out M12, out M21, out S12);
g.ArcDirect(32.0, -86.0, 45.0, 1.0, out flat, out flon);
if (flat != finalLatitude || flon != finalLongitude)
throw new Exception("Geodesic.ArcDirect #1 failed");
g.ArcDirect(32.0, -86.0, 45.0, 1.0, out flat, out flon, out faz);
if (flat != finalLatitude || flon != finalLongitude || faz != finalAzimuth)
throw new Exception("Geodesic.ArcDirect #2 failed");
g.ArcDirect(32.0, -86.0, 45.0, 1.0, out flat, out flon, out faz, out fad);
if (flat != finalLatitude || flon != finalLongitude || faz != finalAzimuth ||
fad != arcDistance)
throw new Exception("Geodesic.ArcDirect #3 failed");
g.ArcDirect(32.0, -86.0, 45.0, 1.0, out flat, out flon, out faz, out fad, out frd);
if (flat != finalLatitude || flon != finalLongitude || faz != finalAzimuth ||
fad != arcDistance || frd != reducedLength)
throw new Exception("Geodesic.ArcDirect #4 failed");
g.ArcDirect(32.0, -86.0, 45.0, 1.0, out flat, out flon, out faz, out fad, out fm12, out fm21);
if (flat != finalLatitude || flon != finalLongitude || faz != finalAzimuth ||
fad != arcDistance || fm12 != M12 || fm21 != M21)
throw new Exception("Geodesic.ArcDirect #5 failed");
fad = g.GenDirect(32.0, -86.0, 45.0, true, 1.0, Geodesic.mask.ALL, out flat, out flon,
out faz, out outd, out frd, out fm12, out fm21, out fs12);
if (outd != arcDistance || flat != finalLatitude || flon != finalLongitude ||
faz != finalAzimuth || frd != reducedLength || fm12 != M12 || fm21 != M21 ||
fs12 != S12 || fad != 1.0)
throw new Exception("Geodesic.GenDirect (true) failed");
double initAzimuth = 0.0, iaz = 0.0;
arcDistance = g.Inverse(32.0, -86.0, 33.0, -87.0, out distance, out initAzimuth, out finalAzimuth,
out reducedLength, out M12, out M21, out S12);
fad = g.Inverse(32.0, -86.0, 33.0, -87.0, out outd);
if (fad != arcDistance || outd != distance)
throw new Exception("Geodesic.Inverse #1 failed");
fad = g.Inverse(32.0, -86.0, 33.0, -87.0, out iaz, out faz);
if (fad != arcDistance || iaz != initAzimuth || faz != finalAzimuth)
throw new Exception("Geodesic.Inverse #2 failed");
fad = g.Inverse(32.0, -86.0, 33.0, -87.0, out outd, out iaz, out faz);
if (fad != arcDistance || outd != distance || faz != finalAzimuth ||
outd != distance)
throw new Exception("Geodesic.Inverse #3 failed");
fad = g.Inverse(32.0, -86.0, 33.0, -87.0, out outd, out iaz, out faz, out frd);
if (fad != arcDistance || outd != distance || faz != finalAzimuth ||
outd != distance || frd != reducedLength)
throw new Exception("Geodesic.Inverse #4 failed");
fad = g.Inverse(32.0, -86.0, 33.0, -87.0, out outd, out iaz, out faz, out fm12, out fm21 );
if (fad != arcDistance || outd != distance || faz != finalAzimuth ||
outd != distance || fm12 != M12 || fm21 != M21 )
throw new Exception("Geodesic.Inverse #5 failed");
fad = g.Inverse(32.0, -86.0, 33.0, -87.0, out outd, out iaz, out faz, out frd, out fm12, out fm21);
if (fad != arcDistance || outd != distance || faz != finalAzimuth ||
outd != distance || fm12 != M12 || fm21 != M21 || frd != reducedLength)
throw new Exception("Geodesic.Inverse #6 failed");
GeodesicLine gl = g.Line(32.0, -86.0, 45.0, Mask.ALL);
gl = g.InverseLine(32.0, -86.0, 33.0, -87.0, Mask.ALL);
gl = g.DirectLine(32.0, -86.0, 45.0, 10000.0, Mask.ALL);
gl = g.ArcDirectLine(32.0, -86.0, 45.0, 10000.0, Mask.ALL);
gl = new GeodesicLine(32.0, -86.0, 45.0, Mask.ALL);
gl = new GeodesicLine(g, 32.0, -86.0, 45.0, Mask.ALL);
arcDistance = gl.Position(10000.0, out finalLatitude, out finalLongitude, out finalAzimuth,
out reducedLength, out M12, out M21, out S12);
fad = gl.Position(10000.0, out flat, out flon);
if (fad != arcDistance || flat != finalLatitude || flon != finalLongitude)
throw new Exception("GeodesicLine.Position #1 failed");
fad = gl.Position(10000.0, out flat, out flon, out faz);
if (fad != arcDistance || flat != finalLatitude || flon != finalLongitude ||
faz != finalAzimuth)
throw new Exception("GeodesicLine.Position #2 failed");
fad = gl.Position(10000.0, out flat, out flon, out faz, out frd);
if (fad != arcDistance || flat != finalLatitude || flon != finalLongitude ||
faz != finalAzimuth || frd != reducedLength)
throw new Exception("GeodesicLine.Position #3 failed");
fad = gl.Position(10000.0, out flat, out flon, out faz, out fm12, out fm21);
if (fad != arcDistance || flat != finalLatitude || flon != finalLongitude ||
faz != finalAzimuth || fm12 != M12 || fm21 != M21)
throw new Exception("GeodesicLine.Position #4 failed");
fad = gl.Position(10000.0, out flat, out flon, out faz, out frd, out fm12, out fm21);
if (fad != arcDistance || flat != finalLatitude || flon != finalLongitude ||
faz != finalAzimuth || fm12 != M12 || fm21 != M21 || frd != reducedLength )
throw new Exception("GeodesicLine.Position #5 failed");
fad = gl.GenPosition(false, 10000.0, GeodesicLine.mask.ALL, out flat, out flon, out faz, out outd, out frd, out fm12, out fm21, out fs12);
if (fad != arcDistance || flat != finalLatitude || flon != finalLongitude ||
faz != finalAzimuth || outd != 10000.0 || fm12 != M12 || fm21 != M21 ||
frd != reducedLength || fs12 != S12 )
throw new Exception("GeodesicLine.GenPosition (false) failed");
gl.ArcPosition(1.0, out finalLatitude, out finalLongitude, out finalAzimuth,
out distance, out reducedLength, out M12, out M21, out S12);
gl.ArcPosition(1.0, out flat, out flon);
if (flat != finalLatitude || flon != finalLongitude)
throw new Exception("GeodesicLine.ArcPosition #1 failed");
gl.ArcPosition(1.0, out flat, out flon, out faz);
if (flat != finalLatitude || flon != finalLongitude || faz != finalAzimuth)
throw new Exception("GeodesicLine.ArcPosition #2 failed");
gl.ArcPosition(1.0, out flat, out flon, out faz, out outd);
if (flat != finalLatitude || flon != finalLongitude || faz != finalAzimuth ||
outd != distance)
throw new Exception("GeodesicLine.ArcPosition #3 failed");
gl.ArcPosition(1.0, out flat, out flon, out faz, out outd, out frd);
if (flat != finalLatitude || flon != finalLongitude || faz != finalAzimuth ||
outd != distance || frd != reducedLength)
throw new Exception("GeodesicLine.ArcPosition #4 failed");
gl.ArcPosition(1.0, out flat, out flon, out faz, out outd, out fm12, out fm21);
if (flat != finalLatitude || flon != finalLongitude || faz != finalAzimuth ||
outd != distance || fm12 != M12 || fm21 != M21)
throw new Exception("GeodesicLine.ArcPosition #5 failed");
gl.ArcPosition(1.0, out flat, out flon, out faz, out outd, out frd, out fm12, out fm21);
if (flat != finalLatitude || flon != finalLongitude || faz != finalAzimuth ||
outd != distance || fm12 != M12 || fm21 != M21 || frd != reducedLength)
throw new Exception("GeodesicLine.ArcPosition #6 failed");
fad = gl.GenPosition(true, 1.0, GeodesicLine.mask.ALL, out flat, out flon, out faz, out outd, out frd, out fm12, out fm21, out fs12);
if (fad != 1.0 || flat != finalLatitude || flon != finalLongitude ||
faz != finalAzimuth || outd != distance || fm12 != M12 || fm21 != M21 ||
frd != reducedLength || fs12 != S12)
throw new Exception("GeodesicLine.GenPosition (false) failed");
GeodesicExact ge = new GeodesicExact();
ge = new GeodesicExact(g.EquatorialRadius, g.Flattening);
arcDistance = ge.Direct(32.0, -86.0, 45.0, 20000.0, out finalLatitude, out finalLongitude,
out finalAzimuth, out reducedLength, out M12, out M21,
out S12);
fad = ge.Direct(32.0, -86.0, 45.0, 20000.0, out flat, out flon);
if (fad != arcDistance || flat != finalLatitude || flon != finalLongitude)
throw new Exception("GeodesicExact.Direct #1 failed");
fad = ge.Direct(32.0, -86.0, 45.0, 20000.0, out flat, out flon, out faz);
if (fad != arcDistance || flat != finalLatitude || flon != finalLongitude ||
faz != finalAzimuth)
throw new Exception("GeodesicExact.Direct #2 failed");
fad = ge.Direct(32.0, -86.0, 45.0, 20000.0, out flat, out flon, out faz, out frd);
if (fad != arcDistance || flat != finalLatitude || flon != finalLongitude ||
faz != finalAzimuth || frd != reducedLength)
throw new Exception("GeodesicExact.Direct #3 failed");
fad = ge.Direct(32.0, -86.0, 45.0, 20000.0, out flat, out flon, out faz, out fm12, out fm21);
if (fad != arcDistance || flat != finalLatitude || flon != finalLongitude ||
faz != finalAzimuth || fm12 != M12 || fm21 != M21)
throw new Exception("GeodesicExact.Direct #4 failed");
fad = ge.Direct(32.0, -86.0, 45.0, 20000.0, out flat, out flon, out faz, out frd, out fm12, out fm21);
if (fad != arcDistance || flat != finalLatitude || flon != finalLongitude ||
faz != finalAzimuth || frd != reducedLength || fm12 != M12 || fm21 != M21)
throw new Exception("GeodesicExact.Direct #5 failed");
fad = ge.GenDirect(32.0, -86.0, 45.0, false, 20000.0, GeodesicExact.mask.ALL, out flat, out flon, out faz, out outd, out frd, out fm12, out fm21, out fs12);
if (fad != arcDistance || flat != finalLatitude || flon != finalLongitude ||
faz != finalAzimuth || frd != reducedLength || fm12 != M12 || fm21 != M21 ||
outd != 20000.0 || fs12 != S12)
throw new Exception("GeodesicExact.GenDirect (false) failed");
ge.ArcDirect(32.0, -86.0, 45.0, 1.0, out finalLatitude, out finalLongitude, out finalAzimuth,
out arcDistance, out reducedLength, out M12, out M21, out S12);
ge.ArcDirect(32.0, -86.0, 45.0, 1.0, out flat, out flon);
if (flat != finalLatitude || flon != finalLongitude)
throw new Exception("GeodesicExact.ArcDirect #1 failed");
ge.ArcDirect(32.0, -86.0, 45.0, 1.0, out flat, out flon, out faz);
if (flat != finalLatitude || flon != finalLongitude || faz != finalAzimuth)
throw new Exception("GeodesicExact.ArcDirect #2 failed");
ge.ArcDirect(32.0, -86.0, 45.0, 1.0, out flat, out flon, out faz, out fad);
if (flat != finalLatitude || flon != finalLongitude || faz != finalAzimuth ||
fad != arcDistance)
throw new Exception("GeodesicExact.ArcDirect #3 failed");
ge.ArcDirect(32.0, -86.0, 45.0, 1.0, out flat, out flon, out faz, out fad, out frd);
if (flat != finalLatitude || flon != finalLongitude || faz != finalAzimuth ||
fad != arcDistance || frd != reducedLength)
throw new Exception("GeodesicExact.ArcDirect #4 failed");
ge.ArcDirect(32.0, -86.0, 45.0, 1.0, out flat, out flon, out faz, out fad, out fm12, out fm21);
if (flat != finalLatitude || flon != finalLongitude || faz != finalAzimuth ||
fad != arcDistance || fm12 != M12 || fm21 != M21)
throw new Exception("GeodesicExact.ArcDirect #5 failed");
fad = ge.GenDirect(32.0, -86.0, 45.0, true, 1.0, GeodesicExact.mask.ALL, out flat, out flon, out faz, out outd, out frd, out fm12, out fm21, out fs12);
if (outd != arcDistance || flat != finalLatitude || flon != finalLongitude ||
faz != finalAzimuth || frd != reducedLength || fm12 != M12 || fm21 != M21 ||
fad != 1.0 || fs12 != S12)
throw new Exception("GeodesicExact.GenDirect (true) failed");
arcDistance = ge.Inverse(32.0, -86.0, 33.0, -87.0, out distance, out initAzimuth, out finalAzimuth,
out reducedLength, out M12, out M21, out S12);
fad = ge.Inverse(32.0, -86.0, 33.0, -87.0, out outd);
if (fad != arcDistance || outd != distance)
throw new Exception("GeodesicExact.Inverse #1 failed");
fad = ge.Inverse(32.0, -86.0, 33.0, -87.0, out iaz, out faz);
if (fad != arcDistance || iaz != initAzimuth || faz != finalAzimuth)
throw new Exception("GeodesicExact.Inverse #2 failed");
fad = ge.Inverse(32.0, -86.0, 33.0, -87.0, out outd, out iaz, out faz);
if (fad != arcDistance || outd != distance || faz != finalAzimuth ||
outd != distance)
throw new Exception("GeodesicExact.Inverse #3 failed");
fad = ge.Inverse(32.0, -86.0, 33.0, -87.0, out outd, out iaz, out faz, out frd);
if (fad != arcDistance || outd != distance || faz != finalAzimuth ||
outd != distance || frd != reducedLength)
throw new Exception("GeodesicExact.Inverse #4 failed");
fad = ge.Inverse(32.0, -86.0, 33.0, -87.0, out outd, out iaz, out faz, out fm12, out fm21);
if (fad != arcDistance || outd != distance || faz != finalAzimuth ||
outd != distance || fm12 != M12 || fm21 != M21)
throw new Exception("GeodesicExact.Inverse #5 failed");
fad = ge.Inverse(32.0, -86.0, 33.0, -87.0, out outd, out iaz, out faz, out frd, out fm12, out fm21);
if (fad != arcDistance || outd != distance || faz != finalAzimuth ||
outd != distance || fm12 != M12 || fm21 != M21 || frd != reducedLength)
throw new Exception("GeodesicExact.Inverse #6 failed");
GeodesicLineExact gle = ge.Line(32.0, -86.0, 45.0, Mask.ALL);
gle = ge.InverseLine(32.0, -86.0, 33.0, -87.0, Mask.ALL);
gle = ge.DirectLine(32.0, -86.0, 45.0, 10000.0, Mask.ALL);
gle = ge.ArcDirectLine(32.0, -86.0, 45.0, 10000.0, Mask.ALL);
gle = new GeodesicLineExact(32.0, -86.0, 45.0, Mask.ALL);
gle = new GeodesicLineExact(ge, 32.0, -86.0, 45.0, Mask.ALL);
arcDistance = gle.Position(10000.0, out finalLatitude, out finalLongitude, out finalAzimuth,
out reducedLength, out M12, out M21, out S12);
fad = gle.Position(10000.0, out flat, out flon);
if (fad != arcDistance || flat != finalLatitude || flon != finalLongitude)
throw new Exception("GeodesicLineExact.Position #1 failed");
fad = gle.Position(10000.0, out flat, out flon, out faz);
if (fad != arcDistance || flat != finalLatitude || flon != finalLongitude ||
faz != finalAzimuth)
throw new Exception("GeodesicLineExact.Position #2 failed");
fad = gle.Position(10000.0, out flat, out flon, out faz, out frd);
if (fad != arcDistance || flat != finalLatitude || flon != finalLongitude ||
faz != finalAzimuth || frd != reducedLength)
throw new Exception("GeodesicLineExact.Position #3 failed");
fad = gle.Position(10000.0, out flat, out flon, out faz, out fm12, out fm21);
if (fad != arcDistance || flat != finalLatitude || flon != finalLongitude ||
faz != finalAzimuth || fm12 != M12 || fm21 != M21)
throw new Exception("GeodesicLineExact.Position #4 failed");
fad = gle.Position(10000.0, out flat, out flon, out faz, out frd, out fm12, out fm21);
if (fad != arcDistance || flat != finalLatitude || flon != finalLongitude ||
faz != finalAzimuth || fm12 != M12 || fm21 != M21 || frd != reducedLength)
throw new Exception("GeodesicLineExact.Position #5 failed");
fad = gle.GenPosition(false, 10000.0, GeodesicLineExact.mask.ALL, out flat, out flon, out faz, out outd, out frd, out fm12, out fm21, out fs12);
if (fad != arcDistance || flat != finalLatitude || flon != finalLongitude ||
faz != finalAzimuth || outd != 10000.0 || fm12 != M12 || fm21 != M21 ||
frd != reducedLength || fs12 != S12)
throw new Exception("GeodesicLineExact.GenPosition (false) failed");
gle.ArcPosition(1.0, out finalLatitude, out finalLongitude, out finalAzimuth,
out distance, out reducedLength, out M12, out M21, out S12);
gle.ArcPosition(1.0, out flat, out flon);
if (flat != finalLatitude || flon != finalLongitude)
throw new Exception("GeodesicLineExact.ArcPosition #1 failed");
gle.ArcPosition(1.0, out flat, out flon, out faz);
if (flat != finalLatitude || flon != finalLongitude || faz != finalAzimuth)
throw new Exception("GeodesicLineExact.ArcPosition #2 failed");
gle.ArcPosition(1.0, out flat, out flon, out faz, out outd);
if (flat != finalLatitude || flon != finalLongitude || faz != finalAzimuth ||
outd != distance)
throw new Exception("GeodesicLineExact.ArcPosition #3 failed");
gle.ArcPosition(1.0, out flat, out flon, out faz, out outd, out frd);
if (flat != finalLatitude || flon != finalLongitude || faz != finalAzimuth ||
outd != distance || frd != reducedLength)
throw new Exception("GeodesicLineExact.ArcPosition #4 failed");
gle.ArcPosition(1.0, out flat, out flon, out faz, out outd, out fm12, out fm21);
if (flat != finalLatitude || flon != finalLongitude || faz != finalAzimuth ||
outd != distance || fm12 != M12 || fm21 != M21)
throw new Exception("GeodesicLineExact.ArcPosition #5 failed");
gle.ArcPosition(1.0, out flat, out flon, out faz, out outd, out frd, out fm12, out fm21);
if (flat != finalLatitude || flon != finalLongitude || faz != finalAzimuth ||
outd != distance || fm12 != M12 || fm21 != M21 || frd != reducedLength)
throw new Exception("GeodesicLineExact.ArcPosition #6 failed");
fad = gle.GenPosition(true, 1.0, GeodesicLineExact.mask.ALL, out flat, out flon, out faz, out outd, out frd, out fm12, out fm21, out fs12);
if (fad != 1.0 || flat != finalLatitude || flon != finalLongitude ||
faz != finalAzimuth || outd != distance || fm12 != M12 || fm21 != M21 ||
frd != reducedLength || fs12 != S12)
throw new Exception("GeodesicLineExact.GenPosition (false) failed");
}
catch (Exception xcpt)
{
MessageBox.Show(xcpt.Message, "Interface Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
MessageBox.Show("No errors detected", "Interfaces OK", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
}
| |
/*
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 java.lang;
using java.util;
using stab.query;
using stab.reflection;
using cnatural.syntaxtree;
namespace cnatural.compiler {
class ExpressionTreeGenerator : StatementHandler<Void, Void> {
private CompilerContext context;
private ExpressionGenerator expressionGenerator;
private TypeInfo expressionType;
private TypeInfo statementType;
private TypeInfo binaryOperatorType;
private TypeInfo unaryOperatorType;
private TypeInfo unboundedConstructorType;
private TypeInfo memberInitializerType;
private MethodInfo blockMethod;
private MethodInfo makeBreakMethod;
private MethodInfo makeCatchMethod;
private MethodInfo makeContinueMethod;
private MethodInfo makeDoMethod;
private MethodInfo emptyMethod;
private MethodInfo expressionMethod;
private MethodInfo makeForMethod;
private MethodInfo makeForeachMethod;
private MethodInfo makeGotoMethod;
private MethodInfo gotoCaseMethod;
private MethodInfo makeIfMethod;
private MethodInfo labelMethod;
private MethodInfo labeledMethod;
private MethodInfo makeReturnMethod;
private MethodInfo makeThrowMethod;
private MethodInfo switchLabelMethod;
private MethodInfo switchSectionMethod;
private MethodInfo makeSwitchMethod;
private MethodInfo makeSynchronizedMethod;
private MethodInfo makeTryMethod;
private MethodInfo makeUsingMethod;
private MethodInfo makeWhileMethod;
private MethodInfo valueMethod;
private MethodInfo getDeclaredMethodMethod;
private MethodInfo getDeclaredFieldMethod;
private MethodInfo getDeclaredConstructorMethod;
private MethodInfo callMethod;
private MethodInfo invokeMethod;
private MethodInfo makeInstanceofMethod;
private MethodInfo localMethod;
private MethodInfo parameterMethod;
private MethodInfo lambdaMethod;
private MethodInfo treeMethod;
private MethodInfo fieldMethod;
private MethodInfo binaryMethod;
private MethodInfo unaryMethod;
private MethodInfo conditionalMethod;
private MethodInfo newObjectMethod;
private MethodInfo newArrayMethod;
private MethodInfo memberInitializerConstructor;
ExpressionTreeGenerator(CompilerContext context)
: super(true) {
this.context = context;
this.expressionGenerator = new ExpressionGenerator(this, context);
}
#region Reflection cache
TypeInfo ExpressionType {
get {
if (expressionType == null) {
expressionType = context.TypeSystem.getType("stab/tree/Expression");
}
return expressionType;
}
}
TypeInfo StatementType {
get {
if (statementType == null) {
statementType = context.TypeSystem.getType("stab/tree/Statement");
}
return statementType;
}
}
TypeInfo UnaryOperatorType {
get {
if (unaryOperatorType == null) {
unaryOperatorType = context.TypeSystem.getType("stab/tree/UnaryOperator");
}
return unaryOperatorType;
}
}
TypeInfo BinaryOperatorType {
get {
if (binaryOperatorType == null) {
binaryOperatorType = context.TypeSystem.getType("stab/tree/BinaryOperator");
}
return binaryOperatorType;
}
}
TypeInfo UnboundedConstructorType {
get {
if (unboundedConstructorType == null) {
var type = context.TypeSystem.getType("java/lang/reflect/Constructor");
unboundedConstructorType = context.TypeSystem.getGenericType(type, Query.singleton(context.TypeSystem.UnboundedWildcard));
}
return unboundedConstructorType;
}
}
TypeInfo MemberInitializerType {
get {
if (memberInitializerType == null) {
memberInitializerType = context.TypeSystem.getType("stab/tree/MemberInitializer");
}
return memberInitializerType;
}
}
MethodInfo BlockMethod {
get {
if (blockMethod == null) {
blockMethod = this.StatementType.getMethod("block", Query.singleton(this.StatementType.ArrayType));
}
return blockMethod;
}
}
MethodInfo MakeBreakMethod {
get {
if (makeBreakMethod == null) {
makeBreakMethod = this.StatementType.getMethod("makeBreak", Query.empty<TypeInfo>());
}
return makeBreakMethod;
}
}
MethodInfo MakeCatchMethod {
get {
if (makeCatchMethod == null) {
makeCatchMethod = this.StatementType.getMethod("makeCatch", Query.pair(this.ParameterMethod.ReturnType,
this.BlockMethod.ReturnType));
}
return makeCatchMethod;
}
}
MethodInfo MakeContinueMethod {
get {
if (makeContinueMethod == null) {
makeContinueMethod = this.StatementType.getMethod("makeContinue", Query.empty<TypeInfo>());
}
return makeContinueMethod;
}
}
MethodInfo MakeDoMethod {
get {
if (makeDoMethod == null) {
makeDoMethod = this.StatementType.getMethod("makeDo", Query.pair(this.StatementType, this.ExpressionType));
}
return makeDoMethod;
}
}
MethodInfo EmptyMethod {
get {
if (emptyMethod == null) {
emptyMethod = this.StatementType.getMethod("empty", Query.empty<TypeInfo>());
}
return emptyMethod;
}
}
MethodInfo ExpressionMethod {
get {
if (expressionMethod == null) {
expressionMethod = this.StatementType.getMethod("expression", Query.singleton(this.ExpressionType));
}
return expressionMethod;
}
}
MethodInfo MakeForMethod {
get {
if (makeForMethod == null) {
makeForMethod = this.StatementType.getMethod("makeFor", Query.quadruple(this.StatementType.ArrayType, this.ExpressionType,
this.StatementType.ArrayType, this.StatementType));
}
return makeForMethod;
}
}
MethodInfo MakeForeachMethod {
get {
if (makeForeachMethod == null) {
makeForeachMethod = this.StatementType.getMethod("makeForeach", Query.triple(this.LocalMethod.ReturnType, this.ExpressionType,
this.StatementType));
}
return makeForeachMethod;
}
}
MethodInfo MakeGotoMethod {
get {
if (makeGotoMethod == null) {
makeGotoMethod = this.StatementType.getMethod("makeGoto", Query.singleton(this.LabelMethod.ReturnType));
}
return makeGotoMethod;
}
}
MethodInfo GotoCaseMethod {
get {
if (gotoCaseMethod == null) {
gotoCaseMethod = this.StatementType.getMethod("gotoCase", Query.singleton(this.SwitchLabelMethod.ReturnType));
}
return gotoCaseMethod;
}
}
MethodInfo MakeIfMethod {
get {
if (makeIfMethod == null) {
makeIfMethod = this.StatementType.getMethod("makeIf", Query.triple(this.ExpressionType, this.StatementType, this.StatementType));
}
return makeIfMethod;
}
}
MethodInfo LabelMethod {
get {
if (labelMethod == null) {
labelMethod = this.StatementType.getMethod("label", Query.singleton(context.TypeSystem.StringType));
}
return labelMethod;
}
}
MethodInfo LabeledMethod {
get {
if (labeledMethod == null) {
labeledMethod = this.StatementType.getMethod("labeled", Query.pair(this.LabelMethod.ReturnType, this.StatementType));
}
return labeledMethod;
}
}
MethodInfo MakeReturnMethod {
get {
if (makeReturnMethod == null) {
makeReturnMethod = this.StatementType.getMethod("makeReturn", Query.singleton(this.ExpressionType));
}
return makeReturnMethod;
}
}
MethodInfo MakeThrowMethod {
get {
if (makeThrowMethod == null) {
makeThrowMethod = this.StatementType.getMethod("makeThrow", Query.singleton(this.ExpressionType));
}
return makeThrowMethod;
}
}
MethodInfo SwitchLabelMethod {
get {
if (switchLabelMethod == null) {
switchLabelMethod = this.StatementType.getMethod("switchLabel", Query.triple(context.TypeSystem.StringType,
context.TypeSystem.IntType, context.TypeSystem.BooleanType));
}
return switchLabelMethod;
}
}
MethodInfo SwitchSectionMethod {
get {
if (switchSectionMethod == null) {
switchSectionMethod = this.StatementType.getMethod("switchSection", Query.pair(this.SwitchLabelMethod.ReturnType.ArrayType,
this.StatementType.ArrayType));
}
return switchSectionMethod;
}
}
MethodInfo MakeSwitchMethod {
get {
if (makeSwitchMethod == null) {
makeSwitchMethod = this.StatementType.getMethod("makeSwitch", Query.pair(this.ExpressionType,
this.SwitchSectionMethod.ReturnType.ArrayType));
}
return makeSwitchMethod;
}
}
MethodInfo MakeSynchronizedMethod {
get {
if (makeSynchronizedMethod == null) {
makeSynchronizedMethod = this.StatementType.getMethod("makeSynchronized", Query.pair(this.ExpressionType, this.StatementType));
}
return makeSynchronizedMethod;
}
}
MethodInfo MakeTryMethod {
get {
if (makeTryMethod == null) {
makeTryMethod = this.StatementType.getMethod("makeTry", Query.triple(this.BlockMethod.ReturnType,
this.MakeCatchMethod.ReturnType.ArrayType, this.BlockMethod.ReturnType));
}
return makeTryMethod;
}
}
MethodInfo MakeUsingMethod {
get {
if (makeUsingMethod == null) {
makeUsingMethod = this.StatementType.getMethod("makeUsing", Query.pair(this.StatementType, this.StatementType));
}
return makeUsingMethod;
}
}
MethodInfo MakeWhileMethod {
get {
if (makeWhileMethod == null) {
makeWhileMethod = this.StatementType.getMethod("makeWhile", Query.pair(this.ExpressionType, this.StatementType));
}
return makeWhileMethod;
}
}
MethodInfo ValueMethod {
get {
if (valueMethod == null) {
var parameters = Query.pair(context.TypeSystem.UnboundedClassType, context.TypeSystem.ObjectType);
valueMethod = this.ExpressionType.getMethod("value", parameters);
}
return valueMethod;
}
}
MethodInfo GetDeclaredMethodMethod {
get {
if (getDeclaredMethodMethod == null) {
var parameters = Query.pair(context.TypeSystem.StringType, context.TypeSystem.UnboundedClassType.ArrayType);
getDeclaredMethodMethod = context.TypeSystem.ClassType.getMethod("getDeclaredMethod", parameters);
}
return getDeclaredMethodMethod;
}
}
MethodInfo GetDeclaredFieldMethod {
get {
if (getDeclaredFieldMethod == null) {
var parameters = Query.singleton(context.TypeSystem.StringType);
getDeclaredFieldMethod = context.TypeSystem.ClassType.getMethod("getDeclaredField", parameters);
}
return getDeclaredFieldMethod;
}
}
MethodInfo GetDeclaredConstructorMethod {
get {
if (getDeclaredConstructorMethod == null) {
var parameters = Query.singleton(context.TypeSystem.UnboundedClassType.ArrayType);
getDeclaredConstructorMethod = context.TypeSystem.ClassType.getMethod("getDeclaredConstructor", parameters);
}
return getDeclaredConstructorMethod;
}
}
MethodInfo CallMethod {
get {
if (callMethod == null) {
var parameters = Query.triple(this.ExpressionType, this.GetDeclaredMethodMethod.ReturnType, this.ExpressionType.ArrayType);
callMethod = this.ExpressionType.getMethod("call", parameters);
}
return callMethod;
}
}
MethodInfo InvokeMethod {
get {
if (invokeMethod == null) {
var parameters = Query.pair(this.ExpressionType, this.ExpressionType.ArrayType);
invokeMethod = this.ExpressionType.getMethod("invoke", parameters);
}
return invokeMethod;
}
}
MethodInfo MakeInstanceofMethod {
get {
if (makeInstanceofMethod == null) {
var parameters = Query.pair(this.ExpressionType, context.TypeSystem.UnboundedClassType.ArrayType);
makeInstanceofMethod = this.ExpressionType.getMethod("makeInstanceof", parameters);
}
return makeInstanceofMethod;
}
}
MethodInfo LocalMethod {
get {
if (localMethod == null) {
var parameters = Query.pair(context.TypeSystem.UnboundedClassType, context.TypeSystem.StringType);
localMethod = this.ExpressionType.getMethod("local", parameters);
}
return localMethod;
}
}
MethodInfo ParameterMethod {
get {
if (parameterMethod == null) {
var parameters = Query.pair(context.TypeSystem.UnboundedClassType, context.TypeSystem.StringType);
parameterMethod = this.ExpressionType.getMethod("parameter", parameters);
}
return parameterMethod;
}
}
MethodInfo LambdaMethod {
get {
if (lambdaMethod == null) {
var parameters = Query.triple(context.TypeSystem.UnboundedClassType, this.ParameterMethod.ReturnType.ArrayType,
this.StatementType);
lambdaMethod = this.ExpressionType.getMethod("lambda", parameters);
}
return lambdaMethod;
}
}
MethodInfo TreeMethod {
get {
if (treeMethod == null) {
treeMethod = this.ExpressionType.Methods.where(p => p.Name.equals("tree")).single();
}
return treeMethod;
}
}
MethodInfo FieldMethod {
get {
if (fieldMethod == null) {
var parameters = Query.pair(this.ExpressionType, this.GetDeclaredFieldMethod.ReturnType);
fieldMethod = this.ExpressionType.getMethod("field", parameters);
}
return fieldMethod;
}
}
MethodInfo BinaryMethod {
get {
if (binaryMethod == null) {
var parameters = Query.quadruple(context.TypeSystem.UnboundedClassType,
this.ExpressionType, this.BinaryOperatorType, this.ExpressionType);
binaryMethod = this.ExpressionType.getMethod("binary", parameters);
}
return binaryMethod;
}
}
MethodInfo UnaryMethod {
get {
if (unaryMethod == null) {
var parameters = Query.triple(context.TypeSystem.UnboundedClassType, this.UnaryOperatorType, this.ExpressionType);
unaryMethod = this.ExpressionType.getMethod("unary", parameters);
}
return unaryMethod;
}
}
MethodInfo ConditionalMethod {
get {
if (conditionalMethod == null) {
var parameters = Query.quadruple(context.TypeSystem.UnboundedClassType,
this.ExpressionType, this.ExpressionType, this.ExpressionType);
conditionalMethod = this.ExpressionType.getMethod("conditional", parameters);
}
return conditionalMethod;
}
}
MethodInfo NewObjectMethod {
get {
if (newObjectMethod == null) {
var parameters = Query.triple(this.UnboundedConstructorType, this.ExpressionType.ArrayType,
this.MemberInitializerType.ArrayType);
newObjectMethod = this.ExpressionType.getMethod("newObject", parameters);
}
return newObjectMethod;
}
}
MethodInfo NewArrayMethod {
get {
if (newArrayMethod == null) {
var parameters = Query.quadruple(context.TypeSystem.UnboundedClassType, this.ExpressionType.ArrayType,
context.TypeSystem.IntType, this.ExpressionType.ArrayType);
newArrayMethod = this.ExpressionType.getMethod("newArray", parameters);
}
return newArrayMethod;
}
}
MethodInfo MemberInitializerConstructor {
get {
if (memberInitializerConstructor == null) {
memberInitializerConstructor = this.MemberInitializerType.Methods.where(p => p.Name.equals("<init>")).single();
}
return memberInitializerConstructor;
}
}
#endregion
void generateExpressionTree(LambdaExpressionNode lambda) {
expressionGenerator.handleExpression(lambda, null, false);
}
protected override Void handleBlock(BlockStatementNode block, Void source) {
var info = block.getUserData(typeof(StatementInfo));
if (info == null) {
return null;
}
var generator = context.MethodGenerationContext.Generator;
BytecodeHelper.emitIntConstant(generator, block.Statements.size());
BytecodeHelper.emitNewarray(generator, 1, this.StatementType);
int i = 0;
foreach (var statement in block.Statements) {
generator.emit(Opcode.Dup);
BytecodeHelper.emitIntConstant(generator, i++);
handleStatement(statement, null);
generator.emit(Opcode.Aastore);
}
generator.emit(Opcode.Invokestatic, this.BlockMethod);
return null;
}
protected override Void handleBreak(BreakStatementNode breakStatement, Void source) {
var info = breakStatement.getUserData(typeof(StatementInfo));
if (info == null) {
return null;
}
var generator = context.MethodGenerationContext.Generator;
generator.emit(Opcode.Invokestatic, this.MakeBreakMethod);
return null;
}
protected override Void handleContinue(ContinueStatementNode continueStatement, Void source) {
var info = continueStatement.getUserData(typeof(StatementInfo));
if (info == null) {
return null;
}
var generator = context.MethodGenerationContext.Generator;
generator.emit(Opcode.Invokestatic, this.MakeContinueMethod);
return null;
}
protected override Void handleDo(DoStatementNode doStatement, Void source) {
var info = doStatement.getUserData(typeof(StatementInfo));
if (info == null) {
return null;
}
var generator = context.MethodGenerationContext.Generator;
handleStatement(doStatement.Statement, null);
expressionGenerator.handleExpression(doStatement.Condition, null, true);
generator.emit(Opcode.Invokestatic, this.MakeDoMethod);
return null;
}
protected override Void handleEmpty(EmptyStatementNode empty, Void source) {
var info = empty.getUserData(typeof(StatementInfo));
if (info == null) {
return null;
}
var generator = context.MethodGenerationContext.Generator;
generator.emit(Opcode.Invokestatic, this.EmptyMethod);
return null;
}
protected override Void handleExpression(ExpressionStatementNode expression, Void source) {
var info = expression.getUserData(typeof(StatementInfo));
if (info == null) {
return null;
}
var generator = context.MethodGenerationContext.Generator;
expressionGenerator.handleExpression(expression.Expression, null, true);
generator.emit(Opcode.Invokestatic, this.ExpressionMethod);
return null;
}
protected override Void handleFor(ForStatementNode forStatement, Void source) {
var info = forStatement.getUserData(typeof(StatementInfo));
if (info == null) {
return null;
}
var generator = context.MethodGenerationContext.Generator;
if (forStatement.Initializer == null) {
generator.emit(Opcode.Aconst_Null);
} else {
BytecodeHelper.emitIntConstant(generator, forStatement.Initializer.size());
BytecodeHelper.emitNewarray(generator, 1, this.StatementType);
int i = 0;
foreach (var s in forStatement.Initializer) {
generator.emit(Opcode.Dup);
BytecodeHelper.emitIntConstant(generator, i++);
handleStatement(s, source);
generator.emit(Opcode.Aastore);
}
}
if (forStatement.Condition == null) {
generator.emit(Opcode.Aconst_Null);
} else {
expressionGenerator.handleExpression(forStatement.Condition, null, true);
}
if (forStatement.Iterator == null) {
generator.emit(Opcode.Aconst_Null);
} else {
BytecodeHelper.emitIntConstant(generator, forStatement.Iterator.size());
BytecodeHelper.emitNewarray(generator, 1, this.StatementType);
int i = 0;
foreach (var s in forStatement.Iterator) {
generator.emit(Opcode.Dup);
BytecodeHelper.emitIntConstant(generator, i++);
handleStatement(s, source);
generator.emit(Opcode.Aastore);
}
}
handleStatement(forStatement.Statement, null);
generator.emit(Opcode.Invokestatic, this.MakeForMethod);
return null;
}
protected override Void handleForeach(ForeachStatementNode foreachStatement, Void source) {
var info = foreachStatement.getUserData(typeof(StatementInfo));
if (info == null) {
return null;
}
var generator = context.MethodGenerationContext.Generator;
var linfo = foreachStatement.getUserData(typeof(LocalMemberInfo));
var local = generator.declareLocal(this.LocalMethod.ReturnType, "tree$local" + context.MethodGenerationContext.nextGeneratedLocal());
context.MethodGenerationContext.TreeLocals[linfo] = local;
BytecodeHelper.emitTypeof(generator, context.TypeSystem, linfo.Type);
generator.emit(Opcode.Ldc, linfo.Name);
generator.emit(Opcode.Invokestatic, this.LocalMethod);
generator.emit(Opcode.Dup);
generator.emit(Opcode.Astore, local);
expressionGenerator.handleExpression(foreachStatement.Source, null, true);
handleStatement(foreachStatement.Statement, null);
generator.emit(Opcode.Invokestatic, this.MakeForeachMethod);
return null;
}
protected override Void handleGoto(GotoStatementNode gotoStatement, Void source) {
var info = gotoStatement.getUserData(typeof(StatementInfo));
if (info == null) {
return null;
}
var generator = context.MethodGenerationContext.Generator;
var local = context.MethodGenerationContext.TreeLabels[info.Target];
if (local == null) {
local = generator.declareLocal(this.LabelMethod.ReturnType, "tree$local" + context.MethodGenerationContext.nextGeneratedLocal());
generator.emit(Opcode.Ldc, context.getIdentifier(gotoStatement.LabelOffset, gotoStatement.LabelLength));
generator.emit(Opcode.Invokestatic, this.LabelMethod);
generator.emit(Opcode.Astore, local);
context.MethodGenerationContext.TreeLabels[info.Target] = local;
}
generator.emit(Opcode.Aload, local);
generator.emit(Opcode.Invokestatic, this.MakeGotoMethod);
return null;
}
protected override Void handleGotoCase(GotoCaseStatementNode gotoCase, Void source) {
var info = gotoCase.getUserData(typeof(StatementInfo));
if (info == null) {
return null;
}
var generator = context.MethodGenerationContext.Generator;
var labels = context.MethodGenerationContext.Labels[context.MethodGenerationContext.Labels.size() - 1];
LocalInfo label;
if (gotoCase.Expression == null) {
label = labels[null];
} else {
var sinfo = gotoCase.Expression.getUserData(typeof(ExpressionInfo));
if (sinfo == null) {
var name = (SimpleNameExpressionNode)gotoCase.Expression;
var enumField = context.getIdentifier(name.NameOffset, name.NameLength);
label = labels[enumField];
} else if (sinfo.Type.IsNumeric) {
Integer value;
if (sinfo.Value instanceof Character) {
value = Integer.valueOf(((Character)sinfo.Value).charValue());
} else {
value = Integer.valueOf(((Number)sinfo.Value).intValue());
}
label = labels[value];
} else {
var value = sinfo.Value;
label = labels[value];
}
}
generator.emit(Opcode.Aload, label);
generator.emit(Opcode.Invokestatic, this.GotoCaseMethod);
return null;
}
protected override Void handleIf(IfStatementNode ifStatement, Void source) {
var info = ifStatement.getUserData(typeof(StatementInfo));
if (info == null) {
return null;
}
var generator = context.MethodGenerationContext.Generator;
expressionGenerator.handleExpression(ifStatement.Condition, null, true);
handleStatement(ifStatement.IfTrue, null);
if (ifStatement.IfFalse != null) {
handleStatement(ifStatement.IfFalse, null);
} else {
generator.emit(Opcode.Aconst_Null);
}
generator.emit(Opcode.Invokestatic, this.MakeIfMethod);
return null;
}
protected override Void handleLabeled(LabeledStatementNode labeled, Void source) {
var info = labeled.getUserData(typeof(StatementInfo));
if (info == null) {
return null;
}
var generator = context.MethodGenerationContext.Generator;
var local = context.MethodGenerationContext.TreeLabels[labeled];
if (local == null) {
local = generator.declareLocal(this.LabelMethod.ReturnType, "tree$local" + context.MethodGenerationContext.nextGeneratedLocal());
generator.emit(Opcode.Ldc, context.getIdentifier(labeled.NameOffset, labeled.NameLength));
generator.emit(Opcode.Invokestatic, this.LabelMethod);
generator.emit(Opcode.Astore, local);
context.MethodGenerationContext.TreeLabels[labeled] = local;
}
generator.emit(Opcode.Aload, local);
handleStatement(labeled.Statement, null);
generator.emit(Opcode.Invokestatic, this.LabeledMethod);
return null;
}
protected override Void handleLocalDeclaration(LocalDeclarationStatementNode localDeclaration, Void source) {
var info = localDeclaration.getUserData(typeof(StatementInfo));
if (info == null) {
return null;
}
var generator = context.MethodGenerationContext.Generator;
foreach (var decl in localDeclaration.Declarators) {
var linfo = decl.getUserData(typeof(LocalMemberInfo));
var local = generator.declareLocal(this.LocalMethod.ReturnType, "tree$local" + context.MethodGenerationContext.nextGeneratedLocal());
context.MethodGenerationContext.TreeLocals[linfo] = local;
BytecodeHelper.emitTypeof(generator, context.TypeSystem, linfo.Type);
generator.emit(Opcode.Ldc, linfo.Name);
generator.emit(Opcode.Invokestatic, this.LocalMethod);
generator.emit(Opcode.Astore, local);
if (decl.Value != null) {
var vinfo = decl.Value.getUserData(typeof(ExpressionInfo));
BytecodeHelper.emitTypeof(generator, context.TypeSystem, vinfo.Type);
generator.emit(Opcode.Aload, local);
generator.emit(Opcode.Getstatic, this.BinaryOperatorType.getField("Assign"));
expressionGenerator.handleExpression(decl.Value, null, true);
generator.emit(Opcode.Invokestatic, this.BinaryMethod);
generator.emit(Opcode.Invokestatic, this.ExpressionMethod);
}
}
return null;
}
protected override Void handleReturn(ReturnStatementNode returnStatement, Void source) {
var info = returnStatement.getUserData(typeof(StatementInfo));
if (info == null) {
return null;
}
var generator = context.MethodGenerationContext.Generator;
if (returnStatement.Value == null) {
generator.emit(Opcode.Aconst_Null);
} else {
expressionGenerator.handleExpression(returnStatement.Value, null, true);
}
generator.emit(Opcode.Invokestatic, this.MakeReturnMethod);
return null;
}
protected override Void handleSwitch(SwitchStatementNode switchStatement, Void source) {
var info = switchStatement.getUserData(typeof(StatementInfo));
if (info == null) {
return null;
}
var generator = context.MethodGenerationContext.Generator;
expressionGenerator.handleExpression(switchStatement.Selector, null, true);
var sinfo = switchStatement.Selector.getUserData(typeof(ExpressionInfo));
var isNumeric = sinfo.Type.IsNumeric;
var isEnum = sinfo.Type.IsEnum;
var runs = new ArrayList<List<Object>>();
var statements = new ArrayList<List<StatementNode>>();
List<Object> run = null;
var labels = new HashMap<Object, LocalInfo>();
foreach (var section in switchStatement.Sections) {
Object value;
if (section.CaseExpression == null) {
value = null;
} else if (isEnum) {
int ordinal = section.CaseExpression.getUserData(typeof(Integer)).intValue();
value = sinfo.Type.Fields.where(p => p.IsEnum).elementAt(ordinal).Name;
} else {
value = section.CaseExpression.getUserData(typeof(ExpressionInfo)).Value;
}
var local = generator.declareLocal(this.SwitchLabelMethod.ReturnType,
"tree$local" + context.MethodGenerationContext.nextGeneratedLocal());
labels[value] = local;
if (value == null) {
generator.emit(Opcode.Aconst_Null);
generator.emit(Opcode.Iconst_0);
generator.emit(Opcode.Iconst_1);
} else if (isNumeric) {
generator.emit(Opcode.Aconst_Null);
BytecodeHelper.emitIntConstant(generator, ((Integer)value).intValue());
generator.emit(Opcode.Iconst_0);
} else {
generator.emit(Opcode.Ldc, value);
generator.emit(Opcode.Iconst_0);
generator.emit(Opcode.Iconst_1);
}
generator.emit(Opcode.Invokestatic, this.SwitchLabelMethod);
generator.emit(Opcode.Astore, local);
if (run == null) {
run = new ArrayList<Object>();
}
run.add(value);
if (!section.Statements.isEmpty()) {
runs.add(run);
statements.add(section.Statements);
run = null;
}
}
context.MethodGenerationContext.Labels.add(labels);
BytecodeHelper.emitIntConstant(generator, runs.size());
BytecodeHelper.emitNewarray(generator, 1, this.SwitchSectionMethod.ReturnType);
int index = 0;
for (int i = 0; i < runs.size(); i++) {
generator.emit(Opcode.Dup);
BytecodeHelper.emitIntConstant(generator, index++);
run = runs[i];
BytecodeHelper.emitIntConstant(generator, run.size());
BytecodeHelper.emitNewarray(generator, 1, this.SwitchLabelMethod.ReturnType);
for (int r = 0; r < run.size(); r++) {
generator.emit(Opcode.Dup);
BytecodeHelper.emitIntConstant(generator, r);
generator.emit(Opcode.Aload, labels[run[r]]);
generator.emit(Opcode.Aastore);
}
var stmts = statements[i];
BytecodeHelper.emitIntConstant(generator, stmts.size());
BytecodeHelper.emitNewarray(generator, 1, this.StatementType);
for (int s = 0; s < stmts.size(); s++) {
generator.emit(Opcode.Dup);
BytecodeHelper.emitIntConstant(generator, s);
handleStatement(stmts[s], null);
generator.emit(Opcode.Aastore);
}
generator.emit(Opcode.Invokestatic, this.SwitchSectionMethod);
generator.emit(Opcode.Aastore);
}
generator.emit(Opcode.Invokestatic, this.MakeSwitchMethod);
context.MethodGenerationContext.Labels.remove(context.MethodGenerationContext.Labels.size() - 1);
return null;
}
protected override Void handleSynchronized(SynchronizedStatementNode synchronizedStatement, Void source) {
var info = synchronizedStatement.getUserData(typeof(StatementInfo));
if (info == null) {
return null;
}
var generator = context.MethodGenerationContext.Generator;
expressionGenerator.handleExpression(synchronizedStatement.Lock, null, true);
handleStatement(synchronizedStatement.Statement, null);
generator.emit(Opcode.Invokestatic, this.MakeSynchronizedMethod);
return null;
}
protected override Void handleThrow(ThrowStatementNode throwStatement, Void source) {
var info = throwStatement.getUserData(typeof(StatementInfo));
if (info == null) {
return null;
}
var generator = context.MethodGenerationContext.Generator;
if (throwStatement.Exception == null) {
generator.emit(Opcode.Aconst_Null);
} else {
expressionGenerator.handleExpression(throwStatement.Exception, null, true);
}
generator.emit(Opcode.Invokestatic, this.MakeThrowMethod);
return null;
}
protected override Void handleTry(TryStatementNode tryStatement, Void source) {
var info = tryStatement.getUserData(typeof(StatementInfo));
if (info == null) {
return null;
}
var generator = context.MethodGenerationContext.Generator;
handleStatement(tryStatement.Block, null);
if (tryStatement.CatchClauses.isEmpty()) {
generator.emit(Opcode.Aconst_Null);
} else {
BytecodeHelper.emitIntConstant(generator, tryStatement.CatchClauses.size());
BytecodeHelper.emitNewarray(generator, 1, this.MakeCatchMethod.ReturnType);
int i = 0;
foreach (var clause in tryStatement.CatchClauses) {
generator.emit(Opcode.Dup);
BytecodeHelper.emitIntConstant(generator, i++);
if (clause.NameLength == 0) {
generator.emit(Opcode.Aconst_Null);
} else {
var linfo = clause.getUserData(typeof(LocalMemberInfo));
var local = generator.declareLocal(this.LocalMethod.ReturnType,
"tree$local" + context.MethodGenerationContext.nextGeneratedLocal());
context.MethodGenerationContext.TreeLocals[linfo] = local;
BytecodeHelper.emitTypeof(generator, context.TypeSystem, linfo.Type);
generator.emit(Opcode.Ldc, linfo.Name);
generator.emit(Opcode.Invokestatic, this.LocalMethod);
generator.emit(Opcode.Dup);
generator.emit(Opcode.Astore, local);
}
if (clause.Block.getUserData(typeof(StatementInfo)) == null) {
clause.Block.addUserData(new StatementInfo());
}
handleStatement(clause.Block, null);
generator.emit(Opcode.Invokestatic, this.MakeCatchMethod);
generator.emit(Opcode.Aastore);
}
}
if (tryStatement.Finally == null) {
generator.emit(Opcode.Aconst_Null);
} else {
handleStatement(tryStatement.Finally, null);
}
generator.emit(Opcode.Invokestatic, this.MakeTryMethod);
return null;
}
protected override Void handleUsing(UsingStatementNode usingStatement, Void source) {
var info = usingStatement.getUserData(typeof(StatementInfo));
if (info == null) {
return null;
}
var generator = context.MethodGenerationContext.Generator;
handleStatement(usingStatement.ResourceAcquisition, null);
handleStatement(usingStatement.Statement, null);
generator.emit(Opcode.Invokestatic, this.MakeUsingMethod);
return null;
}
protected override Void handleWhile(WhileStatementNode whileStatement, Void source) {
var info = whileStatement.getUserData(typeof(StatementInfo));
if (info == null) {
return null;
}
var generator = context.MethodGenerationContext.Generator;
expressionGenerator.handleExpression(whileStatement.Condition, null, true);
handleStatement(whileStatement.Statement, null);
generator.emit(Opcode.Invokestatic, this.MakeWhileMethod);
return null;
}
void emitThisAccess(CompilerContext context, CodeGenerator generator) {
BytecodeHelper.emitTypeof(generator, context.TypeSystem, context.MethodGenerationContext.CurrentMethod.DeclaringType);
BytecodeGenerator.emitThisAccess(context, generator);
generator.emit(Opcode.Invokestatic, this.ValueMethod);
}
void emitArray(int dimensions, TypeInfo type, Iterator<ExpressionNode> values) {
var generator = context.MethodGenerationContext.Generator;
BytecodeHelper.emitNewarray(generator, dimensions, type.ElementType);
if (values != null) {
var opcode = BytecodeHelper.getAstoreOpcode(type.ElementType);
int i = 0;
while (values.hasNext()) {
var e = values.next();
generator.emit(Opcode.Dup);
BytecodeHelper.emitIntConstant(generator, i++);
expressionGenerator.handleExpression(e, null, true);
generator.emit(opcode);
}
}
}
private class ExpressionGenerator : ExpressionHandler<Void, Void> {
private ExpressionTreeGenerator statementGenerator;
private CompilerContext context;
ExpressionGenerator(ExpressionTreeGenerator statementGenerator, CompilerContext context)
: super(true) {
this.statementGenerator = statementGenerator;
this.context = context;
}
public override Void handleExpression(ExpressionNode expression, Void source, bool nested) {
var generator = context.MethodGenerationContext.Generator;
var info = expression.getUserData(typeof(ExpressionInfo));
if (info == null) {
emitNull();
return null;
}
if (!info.IsConstant) {
return super.handleExpression(expression, null, nested);
}
BytecodeHelper.emitTypeof(generator, context.TypeSystem, info.Type);
var value = info.Value;
switch (info.Type.TypeKind) {
case Boolean:
if (((Boolean)value).booleanValue()) {
generator.emit(Opcode.Iconst_1);
} else {
generator.emit(Opcode.Iconst_0);
}
generator.emit(Opcode.Invokestatic, context.TypeSystem.getBoxingMethod(info.Type));
break;
case Char:
case Byte:
case Short:
case Int:
BytecodeHelper.emitIntConstant(generator, value);
generator.emit(Opcode.Invokestatic, context.TypeSystem.getBoxingMethod(info.Type));
break;
case Long:
BytecodeHelper.emitLongConstant(generator, value);
generator.emit(Opcode.Invokestatic, context.TypeSystem.getBoxingMethod(info.Type));
break;
case Float:
BytecodeHelper.emitFloatConstant(generator, value);
generator.emit(Opcode.Invokestatic, context.TypeSystem.getBoxingMethod(info.Type));
break;
case Double:
BytecodeHelper.emitDoubleConstant(generator, value);
generator.emit(Opcode.Invokestatic, context.TypeSystem.getBoxingMethod(info.Type));
break;
default:
generator.emit(Opcode.Ldc, value);
break;
}
generator.emit(Opcode.Invokestatic, statementGenerator.ValueMethod);
return null;
}
protected override Void handleAnonymousObjectCreation(AnonymousObjectCreationExpressionNode anonymousObject,
Void source, bool nested) {
var generator = context.MethodGenerationContext.Generator;
var typeInfo = anonymousObject.getUserData(typeof(ExpressionInfo)).Type;
CompilerHelper.initializeAnonymousType(context, typeInfo);
var constructor = typeInfo.Methods.where(p => p.Name.equals("<init>")).first();
BytecodeHelper.emitTypeof(generator, context.TypeSystem, typeInfo);
BytecodeHelper.emitIntConstant(generator, constructor.Parameters.count());
BytecodeHelper.emitNewarray(generator, 1, context.TypeSystem.ClassType);
int i = 0;
foreach (var p in constructor.Parameters) {
generator.emit(Opcode.Dup);
BytecodeHelper.emitIntConstant(generator, i++);
BytecodeHelper.emitTypeof(generator, context.TypeSystem, p.Type);
generator.emit(Opcode.Aastore);
}
generator.emit(Opcode.Invokevirtual, statementGenerator.GetDeclaredConstructorMethod);
BytecodeHelper.emitIntConstant(generator, constructor.Parameters.count());
BytecodeHelper.emitNewarray(generator, 1, statementGenerator.ExpressionType);
i = 0;
foreach (var decl in anonymousObject.MemberDeclarators) {
generator.emit(Opcode.Dup);
BytecodeHelper.emitIntConstant(generator, i++);
handleExpression(decl.Value, null, true);
generator.emit(Opcode.Aastore);
}
generator.emit(Opcode.Aconst_Null);
generator.emit(Opcode.Invokestatic, statementGenerator.NewObjectMethod);
return null;
}
protected override Void handleArrayCreation(ArrayCreationExpressionNode arrayCreation, Void source, bool nested) {
var generator = context.MethodGenerationContext.Generator;
var type = arrayCreation.getUserData(typeof(ExpressionInfo)).Type;
var initializer = arrayCreation.Initializer;
BytecodeHelper.emitTypeof(generator, context.TypeSystem, type);
if (arrayCreation.DimensionExpressions.size() == 0) {
generator.emit(Opcode.Aconst_Null);
} else {
BytecodeHelper.emitIntConstant(generator, arrayCreation.DimensionExpressions.size());
BytecodeHelper.emitNewarray(generator, 1, statementGenerator.ExpressionType);
int i = 0;
foreach (var e in arrayCreation.DimensionExpressions) {
generator.emit(Opcode.Dup);
BytecodeHelper.emitIntConstant(generator, i++);
handleExpression(e, null, true);
generator.emit(Opcode.Aastore);
}
}
BytecodeHelper.emitIntConstant(generator, arrayCreation.Dimensions);
if (initializer == null) {
generator.emit(Opcode.Aconst_Null);
} else {
BytecodeHelper.emitIntConstant(generator, initializer.Values.size());
BytecodeHelper.emitNewarray(generator, 1, statementGenerator.ExpressionType);
int i = 0;
foreach (var e in initializer.Values) {
generator.emit(Opcode.Dup);
BytecodeHelper.emitIntConstant(generator, i++);
handleExpression(e, null, true);
generator.emit(Opcode.Aastore);
}
}
generator.emit(Opcode.Invokestatic, statementGenerator.NewArrayMethod);
return null;
}
protected override Void handleAssign(AssignExpressionNode assign, Void source, bool nested) {
var generator = context.MethodGenerationContext.Generator;
var info = assign.getUserData(typeof(ExpressionInfo));
BytecodeHelper.emitTypeof(generator, context.TypeSystem, info.Type);
handleExpression(assign.Left, null, true);
var op = (assign.Operator.equals("Assign")) ? "Assign" : assign.Operator.toString() + "Assign";
generator.emit(Opcode.Getstatic, statementGenerator.BinaryOperatorType.getField(op));
handleExpression(assign.Right, null, true);
generator.emit(Opcode.Invokestatic, statementGenerator.BinaryMethod);
return null;
}
protected override Void handleBinary(BinaryExpressionNode binary, Void source, bool nested) {
var generator = context.MethodGenerationContext.Generator;
var info = binary.getUserData(typeof(ExpressionInfo));
if (binary.Operator == BinaryOperator.As) {
BytecodeHelper.emitTypeof(generator, context.TypeSystem, info.Type);
generator.emit(Opcode.Getstatic, statementGenerator.UnaryOperatorType.getField("As"));
handleExpression(binary.LeftOperand, null, true);
generator.emit(Opcode.Invokestatic, statementGenerator.UnaryMethod);
} else if (binary.Operator == BinaryOperator.Instanceof) {
var rinfo = binary.RightOperand.getUserData(typeof(ExpressionInfo));
handleExpression(binary.LeftOperand, null, true);
BytecodeHelper.emitTypeof(generator, context.TypeSystem, rinfo.Type);
generator.emit(Opcode.Invokestatic, statementGenerator.MakeInstanceofMethod);
} else {
BytecodeHelper.emitTypeof(generator, context.TypeSystem, info.Type);
handleExpression(binary.LeftOperand, null, true);
generator.emit(Opcode.Getstatic, statementGenerator.BinaryOperatorType.getField(binary.Operator.toString()));
handleExpression(binary.RightOperand, null, true);
generator.emit(Opcode.Invokestatic, statementGenerator.BinaryMethod);
}
return null;
}
protected override Void handleCast(CastExpressionNode cast, Void source, bool nested) {
var generator = context.MethodGenerationContext.Generator;
var info = cast.getUserData(typeof(ExpressionInfo));
BytecodeHelper.emitTypeof(generator, context.TypeSystem, info.Type);
generator.emit(Opcode.Getstatic, statementGenerator.UnaryOperatorType.getField("Cast"));
handleExpression(cast.Expression, null, true);
generator.emit(Opcode.Invokestatic, statementGenerator.UnaryMethod);
return null;
}
protected override Void handleConditional(ConditionalExpressionNode conditional, Void source, bool nested) {
var generator = context.MethodGenerationContext.Generator;
var info = conditional.getUserData(typeof(ExpressionInfo));
BytecodeHelper.emitTypeof(generator, context.TypeSystem, info.Type);
handleExpression(conditional.Condition, null, true);
handleExpression(conditional.IfTrue, null, true);
handleExpression(conditional.IfFalse, null, true);
generator.emit(Opcode.Invokestatic, statementGenerator.ConditionalMethod);
return null;
}
protected override Void handleElementAccess(ElementAccessExpressionNode elementAccess, Void source, bool nested) {
var generator = context.MethodGenerationContext.Generator;
var info = elementAccess.getUserData(typeof(ExpressionInfo));
var target = elementAccess.TargetObject;
var tinfo = target.getUserData(typeof(ExpressionInfo));
var ttype = tinfo.Type;
if (!ttype.IsArray) {
var method = elementAccess.getUserData(typeof(ExpressionInfo)).Member.GetAccessor.OriginalMethodDefinition;
if (!method.IsStatic) {
handleExpression(target, null, true);
} else {
emitNull();
}
generator.emit(Opcode.Ldc, method.DeclaringType);
generator.emit(Opcode.Ldc, method.Name);
BytecodeHelper.emitIntConstant(generator, 1);
BytecodeHelper.emitNewarray(generator, 1, context.TypeSystem.ClassType);
generator.emit(Opcode.Dup);
BytecodeHelper.emitIntConstant(generator, 0);
BytecodeHelper.emitTypeof(generator, context.TypeSystem, method.Parameters.first().Type);
generator.emit(Opcode.Aastore);
generator.emit(Opcode.Invokevirtual, statementGenerator.GetDeclaredMethodMethod);
BytecodeHelper.emitIntConstant(generator, method.Parameters.count());
BytecodeHelper.emitNewarray(generator, 1, statementGenerator.ExpressionType);
var arguments = elementAccess.Indexes;
emitArguments(arguments, method.Parameters, method.Parameters.count(), method.IsVarargs);
generator.emit(Opcode.Invokestatic, statementGenerator.CallMethod);
} else {
BytecodeHelper.emitTypeof(generator, context.TypeSystem, info.Type);
handleExpression(target, null, true);
generator.emit(Opcode.Getstatic, statementGenerator.BinaryOperatorType.getField("Element"));
var index = elementAccess.Indexes[0];
handleExpression(index, null, true);
generator.emit(Opcode.Invokestatic, statementGenerator.BinaryMethod);
}
return null;
}
protected override Void handleInvocation(InvocationExpressionNode invocation, Void source, bool nested) {
var generator = context.MethodGenerationContext.Generator;
var info = invocation.getUserData(typeof(ExpressionInfo));
var method = info.Method;
if (method.IsExcludedFromCompilation || CompilerHelper.shouldIgnoreCalls(context, method)) {
return null;
}
method = method.OriginalMethodDefinition;
var isDelegateInvocation = BytecodeHelper.isDelegateType(method.DeclaringType) && method.Name.equals("invoke");
if (!method.IsStatic) {
if (isDelegateInvocation) {
handleExpression(invocation.TargetObject, null, true);
} else if (invocation.TargetObject.ExpressionKind == ExpressionKind.MemberAccess || invocation.TargetObject.ExpressionKind == ExpressionKind.NullSafeMemberAccess) {
var targetTarget = ((MemberAccessExpressionNode)invocation.TargetObject).TargetObject;
handleExpression(targetTarget, null, true);
} else { // SimpleName
statementGenerator.emitThisAccess(context, generator);
}
} else {
emitNull();
}
if (!isDelegateInvocation) {
generator.emit(Opcode.Ldc, method.DeclaringType);
generator.emit(Opcode.Ldc, method.Name);
BytecodeHelper.emitIntConstant(generator, method.Parameters.count());
BytecodeHelper.emitNewarray(generator, 1, context.TypeSystem.ClassType);
int i = 0;
foreach (var p in method.Parameters) {
generator.emit(Opcode.Dup);
BytecodeHelper.emitIntConstant(generator, i++);
BytecodeHelper.emitTypeof(generator, context.TypeSystem, p.Type);
generator.emit(Opcode.Aastore);
}
generator.emit(Opcode.Invokevirtual, statementGenerator.GetDeclaredMethodMethod);
}
BytecodeHelper.emitIntConstant(generator, method.Parameters.count());
BytecodeHelper.emitNewarray(generator, 1, statementGenerator.ExpressionType);
var arguments = invocation.Arguments;
if (info.IsExtension) {
var target = (MemberAccessExpressionNode)invocation.TargetObject;
arguments = new ArrayList<ExpressionNode> { target.TargetObject };
arguments.addAll(invocation.Arguments);
}
emitArguments(arguments, method.Parameters, method.Parameters.count(), method.IsVarargs);
if (!isDelegateInvocation) {
generator.emit(Opcode.Invokestatic, statementGenerator.CallMethod);
} else {
generator.emit(Opcode.Invokestatic, statementGenerator.InvokeMethod);
}
return null;
}
protected override Void handleLambda(LambdaExpressionNode lambda, Void source, bool nested) {
var methodBuilder = lambda.getUserData(typeof(MethodBuilder));
((TypeBuilder)methodBuilder.DeclaringType).undefineMethod(methodBuilder);
var info = lambda.getUserData(typeof(ExpressionInfo));
var generator = context.MethodGenerationContext.Generator;
generator.beginScope();
var parameterExpressionType = statementGenerator.ParameterMethod.ReturnType;
var parameters = new ArrayList<LocalInfo>();
foreach (var pi in methodBuilder.Parameters) {
var local = generator.declareLocal(parameterExpressionType, "tree$local" + context.MethodGenerationContext.nextGeneratedLocal());
parameters.add(local);
context.MethodGenerationContext.TreeLocals[pi.getUserData(typeof(LocalMemberInfo))] = local;
BytecodeHelper.emitTypeof(generator, context.TypeSystem, pi.Type);
generator.emit(Opcode.Ldc, pi.Name);
generator.emit(Opcode.Invokestatic, statementGenerator.ParameterMethod);
generator.emit(Opcode.Astore, local);
}
var method = (nested) ? statementGenerator.LambdaMethod : statementGenerator.TreeMethod;
if (info.Type.FullName.equals("stab/tree/ExpressionTree")) {
BytecodeHelper.emitTypeof(generator, context.TypeSystem, info.Type.GenericArguments.single());
} else {
BytecodeHelper.emitTypeof(generator, context.TypeSystem, info.Type);
}
BytecodeHelper.emitIntConstant(generator, parameters.count());
BytecodeHelper.emitNewarray(generator, 1, parameterExpressionType);
int i = 0;
foreach (var p in parameters) {
generator.emit(Opcode.Dup);
BytecodeHelper.emitIntConstant(generator, i++);
generator.emit(Opcode.Aload, p);
generator.emit(Opcode.Aastore);
}
statementGenerator.handleStatement(lambda.Body, null);
generator.emit(Opcode.Invokestatic, method);
generator.endScope();
return null;
}
protected override Void handleMemberAccess(MemberAccessExpressionNode memberAccess, Void source, bool nested) {
var generator = context.MethodGenerationContext.Generator;
var info = memberAccess.getUserData(typeof(ExpressionInfo));
if (info.Method != null) {
emitDelegateCreation(info.Type, info.Method, memberAccess, nested);
return null;
}
var member = info.Member;
if (member == null) {
handleExpression(memberAccess.TargetObject, null, true);
return null;
}
switch (member.MemberKind) {
case Field: {
var field = member.Field;
if (!field.IsStatic) {
handleExpression(memberAccess.TargetObject, null, true);
} else {
emitNull();
}
generator.emit(Opcode.Ldc, field.DeclaringType);
generator.emit(Opcode.Ldc, field.Name);
generator.emit(Opcode.Invokevirtual, statementGenerator.GetDeclaredFieldMethod);
generator.emit(Opcode.Invokestatic, statementGenerator.FieldMethod);
break;
}
case Property: {
var method = member.GetAccessor;
if (!method.IsStatic) {
handleExpression(memberAccess.TargetObject, null, true);
} else {
emitNull();
}
generator.emit(Opcode.Ldc, method.DeclaringType);
generator.emit(Opcode.Ldc, method.Name);
BytecodeHelper.emitIntConstant(generator, 0);
BytecodeHelper.emitNewarray(generator, 1, context.TypeSystem.ClassType);
generator.emit(Opcode.Invokevirtual, statementGenerator.GetDeclaredMethodMethod);
BytecodeHelper.emitIntConstant(generator, 0);
BytecodeHelper.emitNewarray(generator, 1, statementGenerator.ExpressionType);
generator.emit(Opcode.Invokestatic, statementGenerator.CallMethod);
break;
}
default:
throw new Exception("Internal error: unhandled name kind: " + member.MemberKind);
}
return null;
}
protected override Void handleObjectCreation(ObjectCreationExpressionNode objectCreation, Void source, bool nested) {
var generator = context.MethodGenerationContext.Generator;
var info = objectCreation.getUserData(typeof(ExpressionInfo));
var method = info.Method;
if (BytecodeHelper.isDelegateType(info.Type)) {
emitDelegateCreation(info.Type, method, objectCreation.Arguments[0], nested);
return null;
}
int nparams = method.Parameters.count();
BytecodeHelper.emitTypeof(generator, context.TypeSystem, info.Type);
BytecodeHelper.emitIntConstant(generator, nparams);
BytecodeHelper.emitNewarray(generator, 1, context.TypeSystem.ClassType);
int i = 0;
foreach (var p in method.Parameters) {
generator.emit(Opcode.Dup);
BytecodeHelper.emitIntConstant(generator, i++);
BytecodeHelper.emitTypeof(generator, context.TypeSystem, p.Type);
generator.emit(Opcode.Aastore);
}
generator.emit(Opcode.Invokevirtual, statementGenerator.GetDeclaredConstructorMethod);
BytecodeHelper.emitIntConstant(generator, nparams);
BytecodeHelper.emitNewarray(generator, 1, statementGenerator.ExpressionType);
var arguments = objectCreation.Arguments;
emitArguments(arguments, method.Parameters, method.Parameters.count(), method.IsVarargs);
var init = objectCreation.Initializer;
if (init == null) {
generator.emit(Opcode.Aconst_Null);
} else {
if (init.ExpressionKind == ExpressionKind.ObjectInitializer) {
var initializer = (ObjectInitializerExpressionNode)init;
BytecodeHelper.emitIntConstant(generator, initializer.MemberInitializers.size());
BytecodeHelper.emitNewarray(generator, 1, statementGenerator.MemberInitializerType);
i = 0;
foreach (var mi in initializer.MemberInitializers) {
generator.emit(Opcode.Dup);
BytecodeHelper.emitIntConstant(generator, i++);
MemberInfo memb = mi.getUserData(typeof(MemberInfo));
generator.emit(Opcode.New, statementGenerator.MemberInitializerType);
generator.emit(Opcode.Dup);
BytecodeHelper.emitTypeof(generator, context.TypeSystem, memb.DeclaringType);
if (memb.MemberKind == MemberKind.Property) {
var meth = memb.SetAccessor;
generator.emit(Opcode.Ldc, meth.getName());
nparams = meth.Parameters.count();
BytecodeHelper.emitIntConstant(generator, nparams);
BytecodeHelper.emitNewarray(generator, 1, context.TypeSystem.ClassType);
i = 0;
foreach (var p in meth.Parameters) {
generator.emit(Opcode.Dup);
BytecodeHelper.emitIntConstant(generator, i++);
BytecodeHelper.emitTypeof(generator, context.TypeSystem, p.Type);
generator.emit(Opcode.Aastore);
}
generator.emit(Opcode.Invokevirtual, statementGenerator.GetDeclaredMethodMethod);
} else {
generator.emit(Opcode.Ldc, memb.Name);
generator.emit(Opcode.Invokevirtual, statementGenerator.GetDeclaredFieldMethod);
}
BytecodeHelper.emitIntConstant(generator, 1);
BytecodeHelper.emitNewarray(generator, 1, statementGenerator.ExpressionType);
generator.emit(Opcode.Dup);
BytecodeHelper.emitIntConstant(generator, 0);
handleExpression(mi.Value, null, true);
generator.emit(Opcode.Aastore);
generator.emit(Opcode.Invokespecial, statementGenerator.MemberInitializerConstructor);
generator.emit(Opcode.Aastore);
}
} else {
var initializer = (CollectionInitializerExpressionNode)init;
var addMethod = initializer.getUserData(typeof(MethodInfo)).OriginalMethodDefinition;
BytecodeHelper.emitIntConstant(generator, initializer.Values.size());
BytecodeHelper.emitNewarray(generator, 1, statementGenerator.MemberInitializerType);
i = 0;
foreach (var args in initializer.Values) {
generator.emit(Opcode.Dup);
BytecodeHelper.emitIntConstant(generator, i++);
generator.emit(Opcode.New, statementGenerator.MemberInitializerType);
generator.emit(Opcode.Dup);
BytecodeHelper.emitTypeof(generator, context.TypeSystem, addMethod.DeclaringType);
generator.emit(Opcode.Ldc, addMethod.getName());
nparams = addMethod.Parameters.count();
BytecodeHelper.emitIntConstant(generator, nparams);
BytecodeHelper.emitNewarray(generator, 1, context.TypeSystem.ClassType);
i = 0;
foreach (var p in addMethod.Parameters) {
generator.emit(Opcode.Dup);
BytecodeHelper.emitIntConstant(generator, i++);
BytecodeHelper.emitTypeof(generator, context.TypeSystem, p.Type);
generator.emit(Opcode.Aastore);
}
generator.emit(Opcode.Invokevirtual, statementGenerator.GetDeclaredMethodMethod);
BytecodeHelper.emitIntConstant(generator, args.size());
BytecodeHelper.emitNewarray(generator, 1, statementGenerator.ExpressionType);
int j = 0;
foreach (var e in args) {
generator.emit(Opcode.Dup);
BytecodeHelper.emitIntConstant(generator, j++);
handleExpression(e, null, true);
generator.emit(Opcode.Aastore);
}
generator.emit(Opcode.Invokespecial, statementGenerator.MemberInitializerConstructor);
generator.emit(Opcode.Aastore);
}
}
}
generator.emit(Opcode.Invokestatic, statementGenerator.NewObjectMethod);
return null;
}
protected override Void handleSimpleName(SimpleNameExpressionNode simpleName, Void source, bool nested) {
var generator = context.MethodGenerationContext.Generator;
var info = simpleName.getUserData(typeof(ExpressionInfo));
var member = info.Member;
switch (member.MemberKind) {
case Local: {
var local = (LocalMemberInfo)member;
if (context.MethodGenerationContext.TreeLocals.containsKey(local)) {
generator.emit(Opcode.Aload, context.MethodGenerationContext.TreeLocals[local]);
} else {
BytecodeHelper.emitTypeof(generator, context.TypeSystem, local.Type);
if (local.IsUsedFromLambda) {
BytecodeGenerator.emitLoadLambdaScope(context, generator, local.Method);
generator.emit(Opcode.Getfield, BytecodeGenerator.getLambdaScopeField(context, local));
} else {
generator.emit(BytecodeHelper.getLoadOpcode(local.Type), generator.getLocal(local.Name));
}
BytecodeGenerator.emitBoxing(context, simpleName);
if (local.Type.IsPrimitive) {
generator.emit(Opcode.Invokestatic, context.TypeSystem.getBoxingMethod(local.Type));
}
generator.emit(Opcode.Invokestatic, statementGenerator.ValueMethod);
}
break;
}
case Field: {
var field = member.Field;
if (!field.IsStatic) {
statementGenerator.emitThisAccess(context, generator);
} else {
emitNull();
}
generator.emit(Opcode.Ldc, field.DeclaringType);
generator.emit(Opcode.Ldc, field.Name);
generator.emit(Opcode.Invokevirtual, statementGenerator.GetDeclaredFieldMethod);
generator.emit(Opcode.Invokestatic, statementGenerator.FieldMethod);
break;
}
case Method: {
if (info.Method != null) {
emitDelegateCreation(info.Type, info.Method, simpleName, nested);
} else {
statementGenerator.emitThisAccess(context, generator);
}
break;
}
case Property: {
var method = member.GetAccessor;
if (!method.IsStatic) {
statementGenerator.emitThisAccess(context, generator);
} else {
emitNull();
}
generator.emit(Opcode.Ldc, method.DeclaringType);
generator.emit(Opcode.Ldc, method.Name);
BytecodeHelper.emitIntConstant(generator, 0);
BytecodeHelper.emitNewarray(generator, 1, context.TypeSystem.ClassType);
generator.emit(Opcode.Invokevirtual, statementGenerator.GetDeclaredMethodMethod);
BytecodeHelper.emitIntConstant(generator, 0);
BytecodeHelper.emitNewarray(generator, 1, statementGenerator.ExpressionType);
generator.emit(Opcode.Invokestatic, statementGenerator.CallMethod);
break;
}
default:
throw new Exception("Internal error: unhandled name kind: " + member.MemberKind);
}
return null;
}
protected override Void handleSizeof(SizeofExpressionNode sizeofExpression, Void source, bool nested) {
var generator = context.MethodGenerationContext.Generator;
BytecodeHelper.emitTypeof(generator, context.TypeSystem, context.TypeSystem.IntType);
generator.emit(Opcode.Getstatic, statementGenerator.UnaryOperatorType.getField("Sizeof"));
handleExpression(sizeofExpression.Expression, null, true);
generator.emit(Opcode.Invokestatic, statementGenerator.UnaryMethod);
return null;
}
protected override Void handleThisAccess(ThisAccessExpressionNode thisAccess, Void source, bool nested) {
var generator = context.MethodGenerationContext.Generator;
statementGenerator.emitThisAccess(context, generator);
return null;
}
protected override Void handleTypeof(TypeofExpressionNode typeofExpression, Void source, bool nested) {
var generator = context.MethodGenerationContext.Generator;
BytecodeHelper.emitTypeof(generator, context.TypeSystem, context.TypeSystem.ClassType);
var type = typeofExpression.getUserData(typeof(TypeInfo));
BytecodeHelper.emitTypeof(generator, context.TypeSystem, type);
generator.emit(Opcode.Invokestatic, statementGenerator.ValueMethod);
return null;
}
protected override Void handleUnary(UnaryExpressionNode unary, Void source, bool nested) {
var generator = context.MethodGenerationContext.Generator;
var info = unary.getUserData(typeof(ExpressionInfo));
BytecodeHelper.emitTypeof(generator, context.TypeSystem, info.Type);
generator.emit(Opcode.Getstatic, statementGenerator.UnaryOperatorType.getField(unary.Operator.toString()));
handleExpression(unary.Operand, null, true);
generator.emit(Opcode.Invokestatic, statementGenerator.UnaryMethod);
return null;
}
void emitNull() {
var generator = context.MethodGenerationContext.Generator;
generator.emit(Opcode.Aconst_Null);
generator.emit(Opcode.Aconst_Null);
generator.emit(Opcode.Invokestatic, statementGenerator.ValueMethod);
}
void emitArguments(List<ExpressionNode> arguments, Iterable<ParameterInfo> parameters, int nparams, bool varargs) {
int fixedLength = (varargs) ? nparams - 1 : nparams;
var generator = context.MethodGenerationContext.Generator;
var it1 = parameters.iterator();
var it2 = arguments.iterator();
int i;
for (i = 0; i < fixedLength; i++) {
it1.next();
var e = it2.next();
generator.emit(Opcode.Dup);
BytecodeHelper.emitIntConstant(generator, i);
handleExpression(e, null, true);
generator.emit(Opcode.Aastore);
}
if (varargs) {
int nvarargs = arguments.size() - fixedLength;
generator.emit(Opcode.Dup);
BytecodeHelper.emitIntConstant(generator, i);
if (nvarargs == 1) {
var paramType = it1.next().Type;
var e = arguments[i];
var ei = e.getUserData(typeof(ExpressionInfo));
if (ei == null) {
emitNull();
} else if (ei.Type.IsArray && paramType.isAssignableFrom(ei.Type)) {
handleExpression(e, null, true);
} else {
BytecodeHelper.emitIntConstant(generator, 1);
statementGenerator.emitArray(1, paramType, it2);
}
} else {
BytecodeHelper.emitIntConstant(generator, nvarargs);
statementGenerator.emitArray(1, it1.next().Type, it2);
}
generator.emit(Opcode.Aastore);
}
}
void emitDelegateCreation(TypeInfo delegateType, MethodInfo method, ExpressionNode argument, bool nested) {
if (argument != null) {
var argType = argument.getUserData(typeof(ExpressionInfo)).Type;
if (argType != null && BytecodeHelper.isDelegateType(argType)) {
handleExpression(argument, null, nested);
return;
}
}
var generator = context.MethodGenerationContext.Generator;
var typeInfo = CompilerHelper.createDelegateType(context, delegateType, method);
var constructor = typeInfo.Methods.where(p => p.Name.equals("<init>")).first();
BytecodeHelper.emitTypeof(generator, context.TypeSystem, typeInfo);
BytecodeHelper.emitIntConstant(generator, constructor.Parameters.count());
BytecodeHelper.emitNewarray(generator, 1, context.TypeSystem.ClassType);
if (!method.IsStatic) {
generator.emit(Opcode.Dup);
BytecodeHelper.emitIntConstant(generator, 0);
BytecodeHelper.emitTypeof(generator, context.TypeSystem, constructor.Parameters.first().Type);
generator.emit(Opcode.Aastore);
}
generator.emit(Opcode.Invokevirtual, statementGenerator.GetDeclaredConstructorMethod);
BytecodeHelper.emitIntConstant(generator, (method.IsStatic) ? 0 : 1);
BytecodeHelper.emitNewarray(generator, 1, statementGenerator.ExpressionType);
if (!method.IsStatic) {
generator.emit(Opcode.Dup);
BytecodeHelper.emitIntConstant(generator, 0);
handleExpression(argument, null, true);
generator.emit(Opcode.Aastore);
}
generator.emit(Opcode.Aconst_Null);
generator.emit(Opcode.Invokestatic, statementGenerator.NewObjectMethod);
}
}
}
}
| |
// Original source: http://fluorinefx.googlecode.com/svn/trunk/Source/FluorineFx/Util/ByteBuffer.cs
/*
FluorineFx open source library
Copyright (C) 2007 Zoltan Csibi, [email protected], FluorineFx.com
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
using System;
using System.IO;
namespace BitCoinSharp.IO
{
/// <summary>
/// This type supports the Fluorine infrastructure and is not intended to be used directly from your code.
/// http://java.sun.com/j2se/1.5.0/docs/api/java/nio/ByteBuffer.html
///
/// The following invariant holds for the mark, position, limit, and capacity values:
/// 0 <= mark <= position <= limit <= capacity
/// </summary>
internal class ByteBuffer : Stream
{
private MemoryStream _stream;
private long _bookmark;
/// <summary>
/// Initializes a new instance of the ByteBuffer class.
/// </summary>
/// <param name="stream">Wraps the MemoryStream into a buffer.</param>
public ByteBuffer(MemoryStream stream)
{
_stream = stream;
ClearBookmark();
}
/// <summary>
/// Allocates a new byte buffer.
/// The new buffer's position will be zero, its limit will be its capacity,
/// and its mark will be undefined.
/// It will have a backing array, and its array offset will be zero.
/// </summary>
/// <param name="capacity"></param>
/// <returns></returns>
public static ByteBuffer Allocate(int capacity)
{
var ms = new MemoryStream(capacity);
var buffer = new ByteBuffer(ms);
buffer.Limit = capacity;
return buffer;
}
/// <summary>
/// Wraps a byte array into a buffer.
/// The new buffer will be backed by the given byte array; that is, modifications
/// to the buffer will cause the array to be modified and vice versa.
/// The new buffer's capacity will be array.length, its position will be offset,
/// its limit will be offset + length, and its mark will be undefined.
/// </summary>
/// <param name="array">Byte array to wrap.</param>
/// <param name="offset">Offset in the byte array.</param>
/// <param name="length"></param>
/// <returns></returns>
public static ByteBuffer Wrap(byte[] array, int offset, int length)
{
var ms = new MemoryStream(array, offset, length, true, true);
ms.Capacity = array.Length;
ms.SetLength(offset + length);
ms.Position = offset;
return new ByteBuffer(ms);
}
/// <summary>
/// Wraps a byte array into a buffer.
/// The new buffer will be backed by the given byte array; that is, modifications
/// to the buffer will cause the array to be modified and vice versa.
/// The new buffer's capacity and limit will be array.length, its position will be zero,
/// and its mark will be undefined.
/// </summary>
/// <param name="array"></param>
/// <returns></returns>
public static ByteBuffer Wrap(byte[] array)
{
return Wrap(array, 0, array.Length);
}
/// <summary>
/// Turns on or off autoExpand
/// </summary>
public bool AutoExpand { get; set; }
/// <summary>
/// Returns this buffer's capacity.
/// </summary>
public int Capacity
{
get { return _stream.Capacity; }
}
/// <summary>
/// Returns this buffer's limit.
/// </summary>
public int Limit
{
get { return (int) _stream.Length; }
set { _stream.SetLength(value); }
}
/// <summary>
/// Returns the number of elements between the current position and the limit.
/// </summary>
public int Remaining
{
get { return Limit - (int) Position; }
}
/// <summary>
/// Tells whether there are any elements between the current position and the limit.
/// </summary>
public bool HasRemaining
{
get { return Remaining > 0; }
}
/// <summary>
/// Gets the current bookmark value.
/// </summary>
public long Bookmark
{
get { return _bookmark; }
}
/// <summary>
/// Sets this buffer's bookmark at its position.
/// </summary>
/// <returns>Returns this bookmark value.</returns>
public long Mark()
{
_bookmark = Position;
return _bookmark;
}
/// <summary>
/// Clears the current bookmark.
/// </summary>
public void ClearBookmark()
{
_bookmark = -1;
}
/// <summary>
/// Resets this buffer's position to the previously-marked position.
/// Invoking this method neither changes nor discards the mark's value.
/// </summary>
public void Reset()
{
if (_bookmark != -1)
Position = _bookmark;
}
/// <summary>
/// Clears this buffer. The position is set to zero, the limit is set to the capacity, and the mark is discarded.
/// </summary>
public void Clear()
{
ClearBookmark();
Position = 0;
}
#if !(NET_1_1)
/// <summary>
/// Releases all resources used by this object.
/// </summary>
/// <param name="disposing">Indicates if this is a dispose call dispose.</param>
protected override void Dispose(bool disposing)
{
if (disposing)
{
if (_stream != null)
_stream.Dispose();
_stream = null;
}
base.Dispose(disposing);
}
#endif
/// <summary>
/// Flips this buffer. The limit is set to the current position and then
/// the position is set to zero. If the mark is defined then it is discarded.
/// </summary>
public void Flip()
{
ClearBookmark();
Limit = (int) Position;
Position = 0;
}
/// <summary>
/// Rewinds this buffer. The position is set to zero and the mark is discarded.
/// </summary>
public void Rewind()
{
ClearBookmark();
Position = 0;
}
/// <summary>
/// Writes the given byte into this buffer at the current position, and then increments the position.
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
public void Put(byte value)
{
WriteByte(value);
}
/// <summary>
/// Relative bulk put method.
///
/// This method transfers bytes into this buffer from the given source array.
/// If there are more bytes to be copied from the array than remain in this buffer,
/// that is, if length > remaining(), then no bytes are transferred and a
/// BufferOverflowException is thrown.
///
/// Otherwise, this method copies length bytes from the given array into this buffer,
/// starting at the given offset in the array and at the current position of this buffer.
/// The position of this buffer is then incremented by length.
/// </summary>
/// <param name="src">The array from which bytes are to be read.</param>
/// <param name="offset">The offset within the array of the first byte to be read; must be non-negative and no larger than the array length.</param>
/// <param name="length">The number of bytes to be read from the given array; must be non-negative and no larger than length - offset.</param>
public void Put(byte[] src, int offset, int length)
{
_stream.Write(src, offset, length);
}
/// <summary>
/// This method transfers the entire content of the given source byte array into this buffer.
/// </summary>
/// <param name="src">The array from which bytes are to be read.</param>
public void Put(byte[] src)
{
Put(src, 0, src.Length);
}
/// <summary>
/// Appends a byte buffer to this ByteArray.
/// </summary>
/// <param name="src">The byte buffer to append.</param>
public void Append(byte[] src)
{
Append(src, 0, src.Length);
}
/// <summary>
/// Appends a byte buffer to this ByteArray.
/// </summary>
/// <param name="src">The byte buffer to append.</param>
/// <param name="offset">Offset in the byte buffer.</param>
/// <param name="length">Number of bytes to append.</param>
public void Append(byte[] src, int offset, int length)
{
var position = Position;
Position = Limit;
Put(src, offset, length);
Position = position;
}
/// <summary>
/// This method transfers the bytes remaining in the given source buffer into this buffer.
/// If there are more bytes remaining in the source buffer than in this buffer,
/// that is, if src.remaining() > remaining(), then no bytes are transferred
/// and a BufferOverflowException is thrown.
///
/// Otherwise, this method copies n = src.remaining() bytes from the given buffer into this buffer,
/// starting at each buffer's current position. The positions of both buffers are then
/// incremented by n.
/// </summary>
/// <param name="src">The source buffer from which bytes are to be read; must not be this buffer.</param>
public void Put(ByteBuffer src)
{
while (src.HasRemaining)
Put(src.Get());
}
/// <summary>
/// Transfers the specified number of bytes from the given source buffer into this buffer.
/// </summary>
/// <param name="src">The source buffer from which bytes are to be read; must not be this buffer.</param>
/// <param name="count">Number of bytes to transfer.</param>
public void Put(ByteBuffer src, int count)
{
for (var i = 0; i < count; i++)
{
Put(src.Get());
}
}
/// <summary>
/// Absolute put method.
/// Writes the given byte into this buffer at the given index.
/// </summary>
/// <param name="index">The index.</param>
/// <param name="value">The byte to write.</param>
public void Put(int index, byte value)
{
_stream.GetBuffer()[index] = value;
}
/// <summary>
/// Relative get method. Reads the byte at this buffer's current position, and then increments the position.
/// </summary>
/// <returns></returns>
public byte Get()
{
return (byte) ReadByte();
}
/// <summary>
/// Reads a 4-byte signed integer using network byte order encoding.
/// </summary>
/// <returns>The 4-byte signed integer.</returns>
public int GetInt()
{
// Read the next 4 bytes, shift and add
var bytes = ReadBytes(4);
return ((bytes[0] << 24) | (bytes[1] << 16) | (bytes[2] << 8) | bytes[3]);
}
/// <summary>
/// Reads a 2-byte signed integer using network byte order encoding.
/// </summary>
/// <returns>The 2-byte signed integer.</returns>
public short GetShort()
{
//Read the next 2 bytes, shift and add.
var bytes = ReadBytes(2);
return (short) ((bytes[0] << 8) | bytes[1]);
}
/// <summary>
/// Absolute get method. Reads the byte at the given index.
/// </summary>
/// <param name="index"></param>
/// <returns></returns>
public byte Get(int index)
{
return _stream.GetBuffer()[index];
}
/// <summary>
/// Relative bulk get method.
/// </summary>
/// <param name="dst"></param>
public void Get(byte[] dst)
{
_stream.Read(dst, 0, dst.Length);
}
public byte this[int index]
{
get { return Get(index); }
set { Put(index, value); }
}
/// <summary>
/// Writes the stream contents to a byte array, regardless of the Position property.
/// </summary>
/// <returns>A new byte array.</returns>
/// <remarks>
/// This method omits unused bytes in ByteBuffer from the array. To get the entire buffer, use the GetBuffer method.
/// </remarks>
public byte[] ToArray()
{
return _stream.ToArray();
}
/// <summary>
/// Returns the array of unsigned bytes from which this stream was created.
/// </summary>
/// <returns>
/// The byte array from which this ByteBuffer was created, or the underlying array if a byte array was not provided to the ByteBuffer constructor during construction of the current instance.
/// </returns>
public byte[] GetBuffer()
{
return _stream.GetBuffer();
}
/// <summary>
/// Compacts this buffer
///
/// The bytes between the buffer's current position and its limit, if any,
/// are copied to the beginning of the buffer. That is, the byte at
/// index p = position() is copied to index zero, the byte at index p + 1 is copied
/// to index one, and so forth until the byte at index limit() - 1 is copied
/// to index n = limit() - 1 - p.
/// The buffer's position is then set to n+1 and its limit is set to its capacity.
/// The mark, if defined, is discarded.
/// The buffer's position is set to the number of bytes copied, rather than to zero,
/// so that an invocation of this method can be followed immediately by an invocation of
/// another relative put method.
/// </summary>
public void Compact()
{
if (Position == 0)
return;
for (var i = (int) Position; i < Limit; i++)
{
var value = Get(i);
Put(i - (int) Position, value);
}
Limit = Limit - (int) Position;
Position = 0;
}
/// <summary>
/// Forwards the position of this buffer as the specified size bytes.
/// </summary>
/// <param name="size"></param>
public void Skip(int size)
{
Position += size;
}
/// <summary>
/// Fills this buffer with the specified value.
/// </summary>
/// <param name="value"></param>
/// <param name="count"></param>
public void Fill(byte value, int count)
{
for (var i = 0; i < count; i++)
Put(value);
}
#region Stream
/// <summary>
/// Gets a value indicating whether the current stream supports reading.
/// </summary>
public override bool CanRead
{
get { return _stream.CanRead; }
}
/// <summary>
/// Gets a value indicating whether the current stream supports seeking.
/// </summary>
public override bool CanSeek
{
get { return _stream.CanSeek; }
}
/// <summary>
/// Gets a value indicating whether the current stream supports writing.
/// </summary>
public override bool CanWrite
{
get { return _stream.CanWrite; }
}
/// <summary>
/// Closes the current stream and releases any resources associated with the current stream.
/// </summary>
public override void Close()
{
_stream.Close();
}
/// <summary>
/// Clears all buffers for this stream and causes any buffered data to be written to the underlying device.
/// </summary>
public override void Flush()
{
_stream.Flush();
}
/// <summary>
/// Gets the length in bytes of the stream.
/// </summary>
public override long Length
{
get { return _stream.Length; }
}
/// <summary>
/// Gets or sets the position within the current stream.
/// </summary>
public override long Position
{
get { return _stream.Position; }
set
{
_stream.Position = value;
if (_bookmark > value)
{
//discard bookmark
_bookmark = 0;
}
}
}
/// <summary>
/// Reads a sequence of bytes from the current stream and advances the position within the stream by the number of bytes read.
/// </summary>
/// <param name="buffer">An array of bytes. When this method returns, the buffer contains the specified byte array with the values between offset and (offset + count - 1) replaced by the bytes read from the current source.</param>
/// <param name="offset">The zero-based byte offset in buffer at which to begin storing the data read from the current stream.</param>
/// <param name="count">The maximum number of bytes to be read from the current stream.</param>
/// <returns>The total number of bytes read into the buffer. This can be less than the number of bytes requested if that many bytes are not currently available, or zero (0) if the end of the stream has been reached.</returns>
public override int Read(byte[] buffer, int offset, int count)
{
return _stream.Read(buffer, offset, count);
}
/// <summary>
/// Relative bulk get method.
/// This method transfers bytes from this buffer into the given destination array.
/// An invocation of this method behaves in exactly the same way as the invocation buffer.Get(a, 0, a.Length)
/// </summary>
/// <param name="buffer">An array of bytes.</param>
/// <returns>The total number of bytes read into the buffer.</returns>
public int Read(byte[] buffer)
{
return _stream.Read(buffer, 0, buffer.Length);
}
/// <summary>
/// Reads a byte from the stream and advances the position within the stream by one byte, or returns -1 if at the end of the stream.
/// </summary>
/// <returns>The unsigned byte cast to an Int32, or -1 if at the end of the stream.</returns>
public override int ReadByte()
{
return _stream.ReadByte();
}
/// <summary>
/// Sets the position within the current stream.
/// </summary>
/// <param name="offset">A byte offset relative to the origin parameter.</param>
/// <param name="origin">A value of type SeekOrigin indicating the reference point used to obtain the new position.</param>
/// <returns>The new position within the current stream.</returns>
public override long Seek(long offset, SeekOrigin origin)
{
return _stream.Seek(offset, origin);
}
/// <summary>
/// Sets the length of the current stream.
/// </summary>
/// <param name="value">The desired length of the current stream in bytes.</param>
public override void SetLength(long value)
{
_stream.SetLength(value);
}
/// <summary>
/// Writes a sequence of bytes to the current stream and advances the current position within this stream by the number of bytes written.
/// </summary>
/// <param name="buffer">An array of bytes. This method copies count bytes from buffer to the current stream.</param>
/// <param name="offset">The zero-based byte offset in buffer at which to begin copying bytes to the current stream.</param>
/// <param name="count">The number of bytes to be written to the current stream.</param>
public override void Write(byte[] buffer, int offset, int count)
{
_stream.Write(buffer, offset, count);
}
/// <summary>
/// Writes a byte to the current position in the stream and advances the position within the stream by one byte.
/// </summary>
/// <param name="value">The byte to write to the stream.</param>
public override void WriteByte(byte value)
{
_stream.WriteByte(value);
}
#endregion Stream
/// <summary>
/// Reads count bytes from the current stream into a byte array and advances the current position by count bytes.
/// </summary>
/// <param name="count"></param>
/// <returns></returns>
public byte[] ReadBytes(int count)
{
var bytes = new byte[count];
for (var i = 0; i < count; i++)
{
bytes[i] = (byte) ReadByte();
}
return bytes;
}
/// <summary>
/// Writes a 32-bit signed integer to the current position using variable length unsigned 29-bit integer encoding.
/// </summary>
/// <param name="value">A 32-bit signed integer.</param>
public void WriteMediumInt(int value)
{
var bytes = new byte[3];
bytes[0] = (byte) (value >> 16);
bytes[1] = (byte) (value >> 8);
bytes[2] = (byte) (value >> 0);
Write(bytes, 0, bytes.Length);
}
public void WriteReverseInt(int value)
{
var bytes = new byte[4];
bytes[3] = (byte) (value >> 24);
bytes[2] = (byte) (value >> 16);
bytes[1] = (byte) (value >> 8);
bytes[0] = (byte) value;
Write(bytes, 0, bytes.Length);
}
private void WriteBigEndian(byte[] bytes)
{
WriteBigEndian((int) Position, bytes);
}
private void WriteBigEndian(int index, byte[] bytes)
{
for (int i = bytes.Length - 1, j = 0; i >= 0; i--, j++)
{
Put(index + j, bytes[i]);
}
Position += bytes.Length;
}
private void WriteBytes(int index, byte[] bytes)
{
for (var i = 0; i < bytes.Length; i++)
{
Put(index + i, bytes[i]);
}
}
/// <summary>
/// Writes a 16-bit unsigned integer to the current position.
/// </summary>
/// <param name="value">A 16-bit unsigned integer.</param>
public void PutShort(short value)
{
var bytes = BitConverter.GetBytes(value);
WriteBigEndian(bytes);
}
/// <summary>
/// Relative put method for writing an int value.
/// Writes four bytes containing the given int value, in the current byte order, into this buffer at the current position, and then increments the position by four.
/// </summary>
/// <param name="value">The int value to be written.</param>
public void PutInt(int value)
{
var bytes = BitConverter.GetBytes(value);
WriteBigEndian(bytes);
}
/// <summary>
/// Absolute put method for writing an int value.
/// Writes four bytes containing the given int value, in the current byte order, into this buffer at the given index.
/// </summary>
/// <param name="index">The index at which the bytes will be written.</param>
/// <param name="value">The int value to be written.</param>
public void PutInt(int index, int value)
{
var bytes = BitConverter.GetBytes(value);
for (int i = bytes.Length - 1, j = 0; i >= 0; i--, j++)
{
Put(index + j, bytes[i]);
}
}
/// <summary>
/// Absolute put method for writing an int value.
/// Writes four bytes containing the given int value, in the current byte order, into this buffer at the given index.
/// </summary>
/// <param name="index">The index at which the bytes will be written.</param>
/// <param name="value">The int value to be written.</param>
public void Put(int index, UInt32 value)
{
var bytes = BitConverter.GetBytes(value);
WriteBytes(index, bytes);
}
public void Put(int index, UInt16 value)
{
var bytes = BitConverter.GetBytes(value);
WriteBytes(index, bytes);
}
public int ReadUInt24()
{
var bytes = ReadBytes(3);
var value = bytes[0] << 16 | bytes[1] << 8 | bytes[2];
return value;
}
/// <summary>
/// Reads a 4-byte signed integer.
/// </summary>
/// <returns>The 4-byte signed integer.</returns>
public int ReadReverseInt()
{
var bytes = ReadBytes(4);
var val = 0;
val += bytes[3] << 24;
val += bytes[2] << 16;
val += bytes[1] << 8;
val += bytes[0];
return val;
}
/// <summary>
/// Puts an in buffer stream onto an out buffer stream and returns the bytes written.
/// </summary>
/// <param name="output"></param>
/// <param name="input"></param>
/// <param name="numBytesMax"></param>
/// <returns></returns>
public static int Put(ByteBuffer output, ByteBuffer input, int numBytesMax)
{
var numBytesRead = (numBytesMax > input.Remaining) ? input.Remaining : numBytesMax;
output.Put(input, numBytesRead);
return numBytesRead;
}
/// <summary>
/// Write the buffer content to a file.
/// </summary>
/// <param name="file"></param>
public void Dump(string file)
{
using (var fs = new FileStream(file, FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite))
{
var buffer = ToArray();
fs.Write(buffer, 0, buffer.Length);
fs.Close();
}
}
/// <summary>
/// Returns a string summarizing the state of this buffer.
/// </summary>
/// <returns>A summary string</returns>
public override string ToString()
{
return string.Format("{0} [pos={1} lim={2} cap={3}]", GetType().Name, Position, Limit, Capacity);
}
/// <summary>
/// Returns the current hash code of this buffer.
/// </summary>
/// <returns>The current hash code of this buffer</returns>
public override int GetHashCode()
{
var hash = 1;
var lim = Limit;
for (var i = (int) Position; i < lim; i++)
hash = 31*hash + Get(i);
return hash;
}
/// <summary>
/// Tells whether or not this buffer is equal to another object.
/// </summary>
/// <param name="obj">The object to which this buffer is to be compared</param>
/// <returns><tt>true</tt> if, and only if, this buffer is equal to the given object</returns>
public override bool Equals(object obj)
{
var that = obj as ByteBuffer;
if (that == null)
return false;
if (Remaining != that.Remaining)
return false;
var lim = Limit;
var thatLim = that.Limit;
for (int i = (int) Position, j = (int) that.Position; i < lim && j < thatLim; i++, j++)
{
var v1 = Get(i);
var v2 = that.Get(j);
if (v1 != v2)
{
return false;
}
}
return true;
}
}
}
| |
// *****************************************************************************
//
// (c) Crownwood Consulting Limited 2002
// All rights reserved. The software and associated documentation
// supplied hereunder are the proprietary information of Crownwood Consulting
// Limited, Haxey, North Lincolnshire, England and are supplied subject to
// licence terms.
//
// IDE Version 1.7 www.dotnetmagic.com
// *****************************************************************************
using System;
using System.Drawing;
using System.Collections;
using System.Windows.Forms;
using IDE.Common;
using IDE.Controls;
using IDE.Collections;
namespace IDE.Controls
{
internal class Target
{
internal enum TargetActions
{
Transfer,
GroupLeft,
GroupRight,
GroupTop,
GroupBottom
}
// Instance fields
protected Rectangle _hotRect;
protected Rectangle _drawRect;
protected TabGroupLeaf _leaf;
protected TargetActions _action;
public Target(Rectangle hotRect, Rectangle drawRect, TabGroupLeaf leaf, TargetActions action)
{
// Define state
_hotRect = hotRect;
_drawRect = drawRect;
_leaf = leaf;
_action = action;
}
public Rectangle HotRect
{
get { return _hotRect; }
}
public Rectangle DrawRect
{
get { return _drawRect; }
}
public TabGroupLeaf Leaf
{
get { return _leaf; }
}
public TargetActions Action
{
get { return _action; }
}
}
internal class TargetManager
{
// Class fields
protected const int _rectWidth = 4;
protected static Cursor _validCursor;
protected static Cursor _invalidCursor;
// Instance fields
protected TabbedGroups _host;
protected TabGroupLeaf _leaf;
protected Controls.TabControl _source;
protected Target _lastTarget;
protected TargetCollection _targets;
static TargetManager()
{
_validCursor = ResourceHelper.LoadCursor(Type.GetType("IDE.Controls.TabbedGroups"),
"IDE.Resources.TabbedValid.cur");
_invalidCursor = ResourceHelper.LoadCursor(Type.GetType("IDE.Controls.TabbedGroups"),
"IDE.Resources.TabbedInvalid.cur");
}
public TargetManager(TabbedGroups host, TabGroupLeaf leaf, Controls.TabControl source)
{
// Define state
_host = host;
_leaf = leaf;
_source = source;
_lastTarget = null;
// Create collection to hold generated targets
_targets = new TargetCollection();
// Process each potential leaf in turn
TabGroupLeaf tgl = host.FirstLeaf();
while(tgl != null)
{
// Create all possible targets for this leaf
CreateTargets(tgl);
// Enumerate all leafs
tgl = host.NextLeaf(tgl);
}
}
protected void CreateTargets(TabGroupLeaf leaf)
{
// Grab the underlying tab control
Controls.TabControl tc = leaf.GroupControl as Controls.TabControl;
// Get the total size of the tab control itself in screen coordinates
Rectangle totalSize = tc.RectangleToScreen(tc.ClientRectangle);
// We do not allow a page to be transfered to its own leaf!
if (leaf != _leaf)
{
Rectangle tabsSize = tc.RectangleToScreen(tc.TabsAreaRect);
// Give priority to the tabs area being used to transfer page
_targets.Add(new Target(tabsSize, totalSize, leaf, Target.TargetActions.Transfer));
}
// Can only create new groups if moving relative to a new group
// or we have more than one page in the originating group
if ((leaf != _leaf) || ((leaf == _leaf) && _leaf.TabPages.Count > 1))
{
int horzThird = totalSize.Width / 3;
int vertThird = totalSize.Height / 3;
// Create the four spacing rectangle
Rectangle leftRect = new Rectangle(totalSize.X, totalSize.Y, horzThird, totalSize.Height);
Rectangle rightRect = new Rectangle(totalSize.Right - horzThird, totalSize.Y, horzThird, totalSize.Height);
Rectangle topRect = new Rectangle(totalSize.X, totalSize.Y, totalSize.Width, vertThird);
Rectangle bottomRect = new Rectangle(totalSize.X, totalSize.Bottom - vertThird, totalSize.Width, vertThird);
TabGroupSequence tgs = _leaf.Parent as TabGroupSequence;
// Can only create new groups in same direction, unless this is the only leaf
if (tgs.Count <= 1)
{
// Add each new target
_targets.Add(new Target(leftRect, leftRect, leaf, Target.TargetActions.GroupLeft));
_targets.Add(new Target(rightRect, rightRect, leaf, Target.TargetActions.GroupRight));
_targets.Add(new Target(topRect, topRect, leaf, Target.TargetActions.GroupTop));
_targets.Add(new Target(bottomRect, bottomRect, leaf, Target.TargetActions.GroupBottom));
}
else
{
if (tgs.Direction == Direction.Vertical)
{
_targets.Add(new Target(topRect, topRect, leaf, Target.TargetActions.GroupTop));
_targets.Add(new Target(bottomRect, bottomRect, leaf, Target.TargetActions.GroupBottom));
}
else
{
_targets.Add(new Target(leftRect, leftRect, leaf, Target.TargetActions.GroupLeft));
_targets.Add(new Target(rightRect, rightRect, leaf, Target.TargetActions.GroupRight));
}
}
}
// We do not allow a page to be transfered to its own leaf!
if (leaf != _leaf)
{
// Any remaining space is used to
_targets.Add(new Target(totalSize, totalSize, leaf, Target.TargetActions.Transfer));
}
}
public void MouseMove(Point mousePos)
{
// Find the Target the mouse is currently over (if any)
Target t = _targets.Contains(mousePos);
// Set appropriate cursor
if (t != null)
_source.Cursor = _validCursor;
else
_source.Cursor = _invalidCursor;
if (t != _lastTarget)
{
// Remove the old indicator
if (_lastTarget != null)
DrawHelper.DrawDragRectangle(_lastTarget.DrawRect, _rectWidth);
// Draw the new indicator
if (t != null)
DrawHelper.DrawDragRectangle(t.DrawRect, _rectWidth);
// Remember for next time around
_lastTarget = t;
}
}
public void Exit()
{
// Remove any showing indicator
Quit();
if (_lastTarget != null)
{
// Perform action specific operation
switch(_lastTarget.Action)
{
case Target.TargetActions.Transfer:
// Transfer selecte page from source to destination
_leaf.MovePageToLeaf(_lastTarget.Leaf);
break;
case Target.TargetActions.GroupLeft:
_lastTarget.Leaf.NewHorizontalGroup(_leaf, true);
break;
case Target.TargetActions.GroupRight:
_lastTarget.Leaf.NewHorizontalGroup(_leaf, false);
break;
case Target.TargetActions.GroupTop:
_lastTarget.Leaf.NewVerticalGroup(_leaf, true);
break;
case Target.TargetActions.GroupBottom:
_lastTarget.Leaf.NewVerticalGroup(_leaf, false);
break;
}
}
}
public void Quit()
{
// Remove drawing of any indicator
if (_lastTarget != null)
DrawHelper.DrawDragRectangle(_lastTarget.DrawRect, _rectWidth);
}
public static void DrawDragRectangle(Rectangle rect)
{
DrawHelper.DrawDragRectangle(rect, _rectWidth);
}
}
}
| |
using System;
using System.Linq;
using System.IO;
using System.Text;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.Serialization;
using Newtonsoft.Json;
namespace DocuSign.eSign.Model
{
/// <summary>
///
/// </summary>
[DataContract]
public class BulkEnvelope : IEquatable<BulkEnvelope>
{
/// <summary>
/// Used to identify an envelope. The id is a sender-generated value and is valid in the DocuSign system for 7 days. It is recommended that a transaction ID is used for offline signing to ensure that an envelope is not sent multiple times. The `transactionId` property can be used determine if an envelope status (i.e. was created or not) for cases where an internet connection was lost before the envelope status could be returned.
/// </summary>
/// <value>Used to identify an envelope. The id is a sender-generated value and is valid in the DocuSign system for 7 days. It is recommended that a transaction ID is used for offline signing to ensure that an envelope is not sent multiple times. The `transactionId` property can be used determine if an envelope status (i.e. was created or not) for cases where an internet connection was lost before the envelope status could be returned.</value>
[DataMember(Name="transactionId", EmitDefaultValue=false)]
public string TransactionId { get; set; }
/// <summary>
///
/// </summary>
/// <value></value>
[DataMember(Name="submittedDateTime", EmitDefaultValue=false)]
public string SubmittedDateTime { get; set; }
/// <summary>
/// The envelope ID of the envelope status that failed to post.
/// </summary>
/// <value>The envelope ID of the envelope status that failed to post.</value>
[DataMember(Name="envelopeId", EmitDefaultValue=false)]
public string EnvelopeId { get; set; }
/// <summary>
/// Contains a URI for an endpoint that you can use to retrieve the envelope or envelopes.
/// </summary>
/// <value>Contains a URI for an endpoint that you can use to retrieve the envelope or envelopes.</value>
[DataMember(Name="envelopeUri", EmitDefaultValue=false)]
public string EnvelopeUri { get; set; }
/// <summary>
/// Reserved: TBD
/// </summary>
/// <value>Reserved: TBD</value>
[DataMember(Name="bulkRecipientRow", EmitDefaultValue=false)]
public string BulkRecipientRow { get; set; }
/// <summary>
///
/// </summary>
/// <value></value>
[DataMember(Name="name", EmitDefaultValue=false)]
public string Name { get; set; }
/// <summary>
///
/// </summary>
/// <value></value>
[DataMember(Name="email", EmitDefaultValue=false)]
public string Email { get; set; }
/// <summary>
///
/// </summary>
/// <value></value>
[DataMember(Name="bulkStatus", EmitDefaultValue=false)]
public string BulkStatus { get; set; }
/// <summary>
/// Gets or Sets ErrorDetails
/// </summary>
[DataMember(Name="errorDetails", EmitDefaultValue=false)]
public ErrorDetails ErrorDetails { 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 BulkEnvelope {\n");
sb.Append(" TransactionId: ").Append(TransactionId).Append("\n");
sb.Append(" SubmittedDateTime: ").Append(SubmittedDateTime).Append("\n");
sb.Append(" EnvelopeId: ").Append(EnvelopeId).Append("\n");
sb.Append(" EnvelopeUri: ").Append(EnvelopeUri).Append("\n");
sb.Append(" BulkRecipientRow: ").Append(BulkRecipientRow).Append("\n");
sb.Append(" Name: ").Append(Name).Append("\n");
sb.Append(" Email: ").Append(Email).Append("\n");
sb.Append(" BulkStatus: ").Append(BulkStatus).Append("\n");
sb.Append(" ErrorDetails: ").Append(ErrorDetails).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 BulkEnvelope);
}
/// <summary>
/// Returns true if BulkEnvelope instances are equal
/// </summary>
/// <param name="other">Instance of BulkEnvelope to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(BulkEnvelope other)
{
// credit: http://stackoverflow.com/a/10454552/677735
if (other == null)
return false;
return
(
this.TransactionId == other.TransactionId ||
this.TransactionId != null &&
this.TransactionId.Equals(other.TransactionId)
) &&
(
this.SubmittedDateTime == other.SubmittedDateTime ||
this.SubmittedDateTime != null &&
this.SubmittedDateTime.Equals(other.SubmittedDateTime)
) &&
(
this.EnvelopeId == other.EnvelopeId ||
this.EnvelopeId != null &&
this.EnvelopeId.Equals(other.EnvelopeId)
) &&
(
this.EnvelopeUri == other.EnvelopeUri ||
this.EnvelopeUri != null &&
this.EnvelopeUri.Equals(other.EnvelopeUri)
) &&
(
this.BulkRecipientRow == other.BulkRecipientRow ||
this.BulkRecipientRow != null &&
this.BulkRecipientRow.Equals(other.BulkRecipientRow)
) &&
(
this.Name == other.Name ||
this.Name != null &&
this.Name.Equals(other.Name)
) &&
(
this.Email == other.Email ||
this.Email != null &&
this.Email.Equals(other.Email)
) &&
(
this.BulkStatus == other.BulkStatus ||
this.BulkStatus != null &&
this.BulkStatus.Equals(other.BulkStatus)
) &&
(
this.ErrorDetails == other.ErrorDetails ||
this.ErrorDetails != null &&
this.ErrorDetails.Equals(other.ErrorDetails)
);
}
/// <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.TransactionId != null)
hash = hash * 57 + this.TransactionId.GetHashCode();
if (this.SubmittedDateTime != null)
hash = hash * 57 + this.SubmittedDateTime.GetHashCode();
if (this.EnvelopeId != null)
hash = hash * 57 + this.EnvelopeId.GetHashCode();
if (this.EnvelopeUri != null)
hash = hash * 57 + this.EnvelopeUri.GetHashCode();
if (this.BulkRecipientRow != null)
hash = hash * 57 + this.BulkRecipientRow.GetHashCode();
if (this.Name != null)
hash = hash * 57 + this.Name.GetHashCode();
if (this.Email != null)
hash = hash * 57 + this.Email.GetHashCode();
if (this.BulkStatus != null)
hash = hash * 57 + this.BulkStatus.GetHashCode();
if (this.ErrorDetails != null)
hash = hash * 57 + this.ErrorDetails.GetHashCode();
return hash;
}
}
}
}
| |
using System;
using System.Text;
using System.Collections.Generic;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using Arebis.Types;
namespace Arebis.Extensions.Tests.Arebis.Types
{
/// <summary>
/// Summary description for AmountVectorTests
/// </summary>
[TestClass]
public class UnitAmountVectorTests
{
[TestMethod]
public void Enumeration01Test()
{
AmountVector v = new AmountVector(4, LengthUnits.KiloMeter);
v[0] = new Amount(500, LengthUnits.Meter);
v[2] = new Amount(200, LengthUnits.Meter);
// Enumerate:
decimal sum = 0m;
int loops = 0;
foreach (Amount a in v.All())
{
Console.WriteLine((a == null) ? "-" : a.ToString());
if (a != null) sum += a.Value;
loops++;
}
// Checks:
Assert.AreEqual(4, loops);
Assert.AreEqual(0.7m, sum);
}
[TestMethod]
public void Enumeration02Test()
{
AmountVector v = new AmountVector(4, LengthUnits.KiloMeter);
v[0] = new Amount(500, LengthUnits.Meter);
v[2] = new Amount(200, LengthUnits.Meter);
// Enumerate:
decimal sum = 0m;
int loops = 0;
foreach (Amount a in v.NonNulls())
{
Console.WriteLine((a == null) ? "-" : a.ToString());
if (a != null) sum += a.Value;
loops++;
}
// Checks:
Assert.AreEqual(2, loops);
Assert.AreEqual(0.7m, sum);
}
[TestMethod]
public void AllZeros01Test()
{
AmountVector v = AmountVector.AllZeros(4, LengthUnits.Meter);
v[2] = new Amount(0.2m, LengthUnits.KiloMeter);
int loops = 0;
foreach (Amount a in v.NonNulls())
{
loops++;
}
Assert.AreEqual(4, loops);
Assert.AreEqual(new Amount(200m, LengthUnits.Meter), v.Sum);
}
[TestMethod]
public void Sum01Test()
{
AmountVector v = new AmountVector(4, LengthUnits.Meter);
v[0] = new Amount(150m, LengthUnits.Meter);
v[2] = new Amount(0.2m, LengthUnits.KiloMeter);
v[3] = new Amount(650m, LengthUnits.Meter);
Assert.AreEqual(new Amount(1m, LengthUnits.KiloMeter), v.Sum);
}
[TestMethod]
public void Average01Test()
{
AmountVector v = new AmountVector(4, LengthUnits.Meter);
v[1] = new Amount(1m, LengthUnits.KiloMeter);
v[3] = new Amount(500m, LengthUnits.Meter);
Assert.AreEqual(new Amount(0.750m, LengthUnits.KiloMeter), v.Average);
}
[TestMethod]
public void ConvertedTo01Test()
{
AmountVector v = new AmountVector(4, LengthUnits.Meter);
v[0] = new Amount(150m, LengthUnits.Meter);
v[2] = new Amount(0.2m, LengthUnits.KiloMeter);
v[3] = new Amount(650m, LengthUnits.Meter);
AmountVector c = v.ConvertedTo(LengthUnits.KiloMeter);
Assert.AreEqual(1000m, v.Sum.Value);
Assert.AreEqual(LengthUnits.Meter, v.Sum.Unit);
Assert.AreEqual(1m, c.Sum.Value);
Assert.AreEqual(LengthUnits.KiloMeter, c.Sum.Unit);
}
[TestMethod]
public void MaxAndMin01Test()
{
AmountVector v = new AmountVector(5, LengthUnits.Meter);
v[0] = new Amount(0.2m, LengthUnits.KiloMeter);
v[2] = new Amount(150m, LengthUnits.Meter);
v[3] = new Amount(650m, LengthUnits.Meter);
v[4] = new Amount(500m, LengthUnits.Meter);
Assert.AreEqual(new Amount(650m, LengthUnits.Meter), v.Max);
Assert.AreEqual(new Amount(150m, LengthUnits.Meter), v.Min);
}
[TestMethod]
public void ToArray01Test()
{
AmountVector v = new AmountVector(5, LengthUnits.Meter);
v[0] = new Amount(0.2m, LengthUnits.KiloMeter);
v[2] = new Amount(150m, LengthUnits.Meter);
v[3] = new Amount(650m, LengthUnits.Meter);
v[4] = new Amount(500m, LengthUnits.Meter);
Amount[] array = v.ToArray();
Assert.AreEqual(5, array.Length);
Assert.AreEqual(v.Length, array.Length);
Assert.AreEqual(v[0], array[0]);
Assert.AreEqual(v[1], array[1]);
Assert.AreEqual(v[2], array[2]);
Assert.AreEqual(v[3], array[3]);
Assert.AreEqual(v[4], array[4]);
}
[TestMethod]
public void Length01Test()
{
AmountVector v = new AmountVector(new decimal?[] { 10m, 3m, null, 5m }, LengthUnits.Meter);
Assert.AreEqual(4, v.Length);
Assert.AreEqual(3, v.LengthNonNulls);
}
[TestMethod]
public void FirstAndLast01Test()
{
AmountVector v = new AmountVector(new decimal?[] { 10m, 3m, null, 5m }, LengthUnits.Meter);
AmountVector w = new AmountVector(new decimal?[] { null, 3m, null, null }, LengthUnits.Meter);
AmountVector x = new AmountVector(new decimal?[] { null, null, null, null }, LengthUnits.Meter);
Assert.AreEqual(new Amount(10m, LengthUnits.Meter), v.FirstNonNull);
Assert.AreEqual(new Amount(3m, LengthUnits.Meter), w.FirstNonNull);
Assert.AreEqual(null, x.FirstNonNull);
Assert.AreEqual(new Amount(5m, LengthUnits.Meter), v.LastNonNull);
Assert.AreEqual(new Amount(3m, LengthUnits.Meter), w.LastNonNull);
Assert.AreEqual(null, x.LastNonNull);
Assert.AreEqual(3, v.LengthNonNulls);
}
[TestMethod]
public void OperatorAdd01Test()
{
AmountVector v = new AmountVector(new decimal?[] { 10m, null, null, 5m }, LengthUnits.Meter);
AmountVector w = new AmountVector(new decimal?[] { null, null, 12m, 6m }, LengthUnits.Meter);
AmountVector r = v + w;
foreach (Amount a in r.All())
{
Console.WriteLine(a);
}
Assert.AreEqual(4, r.Length);
Assert.AreEqual(v.Unit, r.Unit);
Assert.AreEqual(10m, r[0].Value);
Assert.AreEqual(null, r[1]);
Assert.AreEqual(12m, r[2].Value);
Assert.AreEqual(11m, r[3].Value);
}
[TestMethod]
public void OperatorSubstract01Test()
{
AmountVector v = new AmountVector(new decimal?[] { 10m, null, null, 5m }, LengthUnits.Meter);
AmountVector w = new AmountVector(new decimal?[] { null, null, 12m, 6m }, LengthUnits.Meter);
AmountVector r = v - w;
foreach (Amount a in r.All())
{
Console.WriteLine(a);
}
Assert.AreEqual(4, r.Length);
Assert.AreEqual(v.Unit, r.Unit);
Assert.AreEqual(10m, r[0].Value);
Assert.AreEqual(null, r[1]);
Assert.AreEqual(-12m, r[2].Value);
Assert.AreEqual(-1m, r[3].Value);
}
[TestMethod]
public void OperatorMultiply01Test()
{
// Suppose following rooms in a house have following areas:
AmountVector areas = new AmountVector(new decimal?[] { 13m, 7.5m, 6m, 8m, 2m }, SurfaceUnits.Meter2);
// Suppose all rooms have following height:
Amount height = new Amount(2.8m, LengthUnits.Meter);
// Volumes of rooms:
AmountVector volumes = areas * height;
foreach (Amount a in volumes.All())
{
Console.WriteLine(a);
}
Console.WriteLine("Sum: {0}", volumes.Sum);
Assert.AreEqual(5, volumes.Length);
Assert.AreEqual(VolumeUnits.Meter3, volumes.Unit);
Assert.AreEqual(new Amount(36.4m, VolumeUnits.Meter3), volumes[0]);
Assert.AreEqual(new Amount(21m, VolumeUnits.Meter3), volumes[1]);
Assert.AreEqual(new Amount(16.8m, VolumeUnits.Meter3), volumes[2]);
Assert.AreEqual(new Amount(22.4m, VolumeUnits.Meter3), volumes[3]);
Assert.AreEqual(new Amount(5.6m, VolumeUnits.Meter3), volumes[4]);
Assert.AreEqual(new Amount(102.2m, VolumeUnits.Meter3), volumes.Sum);
}
[TestMethod]
public void OperatorMultiply02Test()
{
// Suppose I have following length measures for rooms:
AmountVector lengths = new AmountVector(new decimal?[] { 13m, 7.5m, 6m, 8m, 2m }, LengthUnits.Meter);
// And following width measures for rooms:
AmountVector widths = new AmountVector(new decimal?[] { 2m, 2m, 3m, 1m, 4m}, LengthUnits.Meter);
// What are the area's of the respective rooms ?
AmountVector areas = lengths * widths;
// Total area:
Amount totalArea = areas.Sum.ConvertedTo(SurfaceUnits.Meter2);
for (int i=0; i<lengths.Length; i++)
{
Console.WriteLine("{0}: {1} x {2} = {3}", i, lengths[i], widths[i], areas[i]);
}
Console.WriteLine("Total area: {0}", totalArea);
Assert.AreEqual(5, areas.Length);
Assert.AreEqual(SurfaceUnits.Meter2, areas.Unit);
Assert.AreEqual(new Amount(26m, SurfaceUnits.Meter2), areas[0]);
Assert.AreEqual(new Amount(15m, SurfaceUnits.Meter2), areas[1]);
Assert.AreEqual(new Amount(18m, SurfaceUnits.Meter2), areas[2]);
Assert.AreEqual(new Amount(8m, SurfaceUnits.Meter2), areas[3]);
Assert.AreEqual(new Amount(8m, SurfaceUnits.Meter2), areas[4]);
Assert.AreEqual(new Amount(75m, SurfaceUnits.Meter2), areas.Sum);
}
[TestMethod]
public void OperatorDivide01Test()
{
AmountVector energies = new AmountVector(new decimal?[] { 83000m, null, 12600m, 99250m }, EnergyUnits.KiloWattHour);
Amount ghv = new Amount(6600m, EnergyUnits.KiloWattHour / VolumeUnits.Meter3);
AmountVector volumes = energies / ghv;
foreach (Amount a in volumes.All())
{
Console.WriteLine(a);
}
Console.WriteLine("Sum: {0}", volumes.Sum);
Assert.AreEqual(4, volumes.Length);
Assert.AreEqual(VolumeUnits.Meter3, volumes.Unit);
Assert.AreEqual(new Amount(12.58m, VolumeUnits.Meter3), volumes[0].ConvertedTo(VolumeUnits.Meter3, 2));
Assert.AreEqual(null, volumes[1]);
Assert.AreEqual(new Amount(1.91m, VolumeUnits.Meter3), volumes[2].ConvertedTo(VolumeUnits.Meter3, 2));
Assert.AreEqual(new Amount(15.04m, VolumeUnits.Meter3), volumes[3].ConvertedTo(VolumeUnits.Meter3, 2));
Assert.AreEqual(new Amount(29.52m, VolumeUnits.Meter3), volumes.Sum.ConvertedTo(VolumeUnits.Meter3, 2));
}
[TestMethod()]
public void SerializeDeserialize01Test()
{
MemoryStream buffer = new MemoryStream();
// Make some amountvector:
AmountVector v1before = new AmountVector(new decimal?[] { 83000m, null, 12600m, 99250m }, EnergyUnits.KiloWattHour);
AmountVector v2before = new AmountVector(new decimal?[] { 4m, null, null, 6m }, TimeUnits.Hour);
// Serialize the units:
BinaryFormatter f = new BinaryFormatter();
f.Serialize(buffer, v1before);
f.Serialize(buffer, v2before);
// Reset stream:
buffer.Seek(0, SeekOrigin.Begin);
// Deserialize units:
BinaryFormatter g = new BinaryFormatter();
AmountVector v1after = (AmountVector)g.Deserialize(buffer);
AmountVector v2after = (AmountVector)g.Deserialize(buffer);
buffer.Close();
Console.WriteLine("{0} => {1}", v1before, v1after);
Console.WriteLine("{0} => {1}", v2before, v2after);
Console.WriteLine("{0} => {1}", v1before / v2before, v1after / v2after);
Assert.AreEqual(v1before.Sum, v1after.Sum);
Assert.AreEqual(v2before.Sum, v2after.Sum);
}
}
}
| |
using Lucene.Net.Index;
using Lucene.Net.Store;
using Lucene.Net.Util;
using System.Collections.Generic;
using System.Diagnostics;
namespace Lucene.Net.Codecs.Pulsing
{
/*
* 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.
*/
// TODO: we now inline based on total TF of the term,
// but it might be better to inline by "net bytes used"
// so that a term that has only 1 posting but a huge
// payload would not be inlined. Though this is
// presumably rare in practice...
/// <summary>
/// Writer for the pulsing format.
/// <para/>
/// Wraps another postings implementation and decides
/// (based on total number of occurrences), whether a terms
/// postings should be inlined into the term dictionary,
/// or passed through to the wrapped writer.
/// <para/>
/// @lucene.experimental
/// </summary>
public sealed class PulsingPostingsWriter : PostingsWriterBase
{
internal static readonly string CODEC = "PulsedPostingsWriter";
internal static readonly string SUMMARY_EXTENSION = "smy"; // recording field summary
// To add a new version, increment from the last one, and
// change VERSION_CURRENT to point to your new version:
internal static readonly int VERSION_START = 0;
internal static readonly int VERSION_META_ARRAY = 1;
internal static readonly int VERSION_CURRENT = VERSION_META_ARRAY;
private readonly SegmentWriteState _segmentState;
private IndexOutput _termsOut;
private readonly List<FieldMetaData> _fields;
private IndexOptions _indexOptions;
private bool _storePayloads;
// information for wrapped PF, in current field
private int _longsSize;
private long[] _longs;
private bool _absolute;
private class PulsingTermState : BlockTermState
{
internal byte[] bytes;
internal BlockTermState wrappedState;
public override string ToString()
{
if (bytes != null)
{
return "inlined";
}
return "not inlined wrapped=" + wrappedState;
}
}
// one entry per position
private readonly Position[] _pending;
private int _pendingCount = 0; // -1 once we've hit too many positions
private Position _currentDoc; // first Position entry of current doc
private sealed class Position
{
internal BytesRef payload;
internal int termFreq; // only incremented on first position for a given doc
internal int pos;
internal int docID;
internal int startOffset;
internal int endOffset;
}
private class FieldMetaData
{
internal int FieldNumber { get; private set; }
/// <summary>
/// NOTE: This was longsSize (field) in Lucene.
/// </summary>
internal int Int64sSize { get; private set; }
public FieldMetaData(int number, int size)
{
FieldNumber = number;
Int64sSize = size;
}
}
// TODO: -- lazy init this? ie, if every single term
// was inlined (eg for a "primary key" field) then we
// never need to use this fallback? Fallback writer for
// non-inlined terms:
private readonly PostingsWriterBase _wrappedPostingsWriter;
/// <summary>
/// If the total number of positions (summed across all docs
/// for this term) is less than or equal <paramref name="maxPositions"/>, then the postings are
/// inlined into terms dict.
/// </summary>
public PulsingPostingsWriter(SegmentWriteState state, int maxPositions, PostingsWriterBase wrappedPostingsWriter)
{
_pending = new Position[maxPositions];
for (var i = 0; i < maxPositions; i++)
{
_pending[i] = new Position();
}
_fields = new List<FieldMetaData>();
// We simply wrap another postings writer, but only call
// on it when tot positions is >= the cutoff:
_wrappedPostingsWriter = wrappedPostingsWriter;
_segmentState = state;
}
public override void Init(IndexOutput termsOut)
{
_termsOut = termsOut;
CodecUtil.WriteHeader(termsOut, CODEC, VERSION_CURRENT);
termsOut.WriteVInt32(_pending.Length); // encode maxPositions in header
_wrappedPostingsWriter.Init(termsOut);
}
public override BlockTermState NewTermState()
{
var state = new PulsingTermState { wrappedState = _wrappedPostingsWriter.NewTermState() };
return state;
}
public override void StartTerm()
{
Debug.Assert(_pendingCount == 0);
}
// TODO: -- should we NOT reuse across fields? would
// be cleaner
/// <summary>
/// Currently, this instance is re-used across fields, so
/// our parent calls setField whenever the field changes.
/// </summary>
public override int SetField(FieldInfo fieldInfo)
{
_indexOptions = fieldInfo.IndexOptions;
_storePayloads = fieldInfo.HasPayloads;
_absolute = false;
_longsSize = _wrappedPostingsWriter.SetField(fieldInfo);
_longs = new long[_longsSize];
_fields.Add(new FieldMetaData(fieldInfo.Number, _longsSize));
return 0;
}
//private bool DEBUG; // LUCENENET NOTE: Not used
public override void StartDoc(int docId, int termDocFreq)
{
Debug.Assert(docId >= 0, "Got DocID=" + docId);
if (_pendingCount == _pending.Length)
{
Push();
_wrappedPostingsWriter.FinishDoc();
}
if (_pendingCount != -1)
{
Debug.Assert(_pendingCount < _pending.Length);
_currentDoc = _pending[_pendingCount];
_currentDoc.docID = docId;
if (_indexOptions == IndexOptions.DOCS_ONLY)
{
_pendingCount++;
}
else if (_indexOptions == IndexOptions.DOCS_AND_FREQS)
{
_pendingCount++;
_currentDoc.termFreq = termDocFreq;
}
else
{
_currentDoc.termFreq = termDocFreq;
}
}
else
{
// We've already seen too many docs for this term --
// just forward to our fallback writer
_wrappedPostingsWriter.StartDoc(docId, termDocFreq);
}
}
public override void AddPosition(int position, BytesRef payload, int startOffset, int endOffset)
{
if (_pendingCount == _pending.Length)
{
Push();
}
if (_pendingCount == -1)
{
// We've already seen too many docs for this term --
// just forward to our fallback writer
_wrappedPostingsWriter.AddPosition(position, payload, startOffset, endOffset);
}
else
{
// buffer up
Position pos = _pending[_pendingCount++];
pos.pos = position;
pos.startOffset = startOffset;
pos.endOffset = endOffset;
pos.docID = _currentDoc.docID;
if (payload != null && payload.Length > 0)
{
if (pos.payload == null)
{
pos.payload = BytesRef.DeepCopyOf(payload);
}
else
{
pos.payload.CopyBytes(payload);
}
}
else if (pos.payload != null)
{
pos.payload.Length = 0;
}
}
}
public override void FinishDoc()
{
if (_pendingCount == -1)
{
_wrappedPostingsWriter.FinishDoc();
}
}
private readonly RAMOutputStream _buffer = new RAMOutputStream();
/// <summary>
/// Called when we are done adding docs to this term.
/// </summary>
public override void FinishTerm(BlockTermState state)
{
var state2 = (PulsingTermState)state;
Debug.Assert(_pendingCount > 0 || _pendingCount == -1);
if (_pendingCount == -1)
{
state2.wrappedState.DocFreq = state2.DocFreq;
state2.wrappedState.TotalTermFreq = state2.TotalTermFreq;
state2.bytes = null;
_wrappedPostingsWriter.FinishTerm(state2.wrappedState);
}
else
{
// There were few enough total occurrences for this
// term, so we fully inline our postings data into
// terms dict, now:
// TODO: it'd be better to share this encoding logic
// in some inner codec that knows how to write a
// single doc / single position, etc. This way if a
// given codec wants to store other interesting
// stuff, it could use this pulsing codec to do so
if (_indexOptions.CompareTo(IndexOptions.DOCS_AND_FREQS_AND_POSITIONS) >= 0)
{
var lastDocID = 0;
var pendingIDX = 0;
var lastPayloadLength = -1;
var lastOffsetLength = -1;
while (pendingIDX < _pendingCount)
{
var doc = _pending[pendingIDX];
var delta = doc.docID - lastDocID;
lastDocID = doc.docID;
// if (DEBUG) System.out.println(" write doc=" + doc.docID + " freq=" + doc.termFreq);
if (doc.termFreq == 1)
{
_buffer.WriteVInt32((delta << 1) | 1);
}
else
{
_buffer.WriteVInt32(delta << 1);
_buffer.WriteVInt32(doc.termFreq);
}
var lastPos = 0;
var lastOffset = 0;
for (var posIDX = 0; posIDX < doc.termFreq; posIDX++)
{
var pos = _pending[pendingIDX++];
Debug.Assert(pos.docID == doc.docID);
var posDelta = pos.pos - lastPos;
lastPos = pos.pos;
var payloadLength = pos.payload == null ? 0 : pos.payload.Length;
if (_storePayloads)
{
if (payloadLength != lastPayloadLength)
{
_buffer.WriteVInt32((posDelta << 1) | 1);
_buffer.WriteVInt32(payloadLength);
lastPayloadLength = payloadLength;
}
else
{
_buffer.WriteVInt32(posDelta << 1);
}
}
else
{
_buffer.WriteVInt32(posDelta);
}
if (_indexOptions.CompareTo(IndexOptions.DOCS_AND_FREQS_AND_POSITIONS_AND_OFFSETS) >= 0)
{
//System.out.println("write=" + pos.startOffset + "," + pos.endOffset);
var offsetDelta = pos.startOffset - lastOffset;
var offsetLength = pos.endOffset - pos.startOffset;
if (offsetLength != lastOffsetLength)
{
_buffer.WriteVInt32(offsetDelta << 1 | 1);
_buffer.WriteVInt32(offsetLength);
}
else
{
_buffer.WriteVInt32(offsetDelta << 1);
}
lastOffset = pos.startOffset;
lastOffsetLength = offsetLength;
}
if (payloadLength > 0)
{
Debug.Assert(_storePayloads);
_buffer.WriteBytes(pos.payload.Bytes, 0, pos.payload.Length);
}
}
}
}
else if (_indexOptions == IndexOptions.DOCS_AND_FREQS)
{
int lastDocId = 0;
for (int posIdx = 0; posIdx < _pendingCount; posIdx++)
{
Position doc = _pending[posIdx];
int delta = doc.docID - lastDocId;
Debug.Assert(doc.termFreq != 0);
if (doc.termFreq == 1)
{
_buffer.WriteVInt32((delta << 1) | 1);
}
else
{
_buffer.WriteVInt32(delta << 1);
_buffer.WriteVInt32(doc.termFreq);
}
lastDocId = doc.docID;
}
}
else if (_indexOptions == IndexOptions.DOCS_ONLY)
{
int lastDocId = 0;
for (int posIdx = 0; posIdx < _pendingCount; posIdx++)
{
Position doc = _pending[posIdx];
_buffer.WriteVInt32(doc.docID - lastDocId);
lastDocId = doc.docID;
}
}
state2.bytes = new byte[(int)_buffer.GetFilePointer()];
_buffer.WriteTo(state2.bytes, 0);
_buffer.Reset();
}
_pendingCount = 0;
}
public override void EncodeTerm(long[] empty, DataOutput output, FieldInfo fieldInfo, BlockTermState state,
bool abs)
{
var _state = (PulsingTermState)state;
Debug.Assert(empty.Length == 0);
_absolute = _absolute || abs;
if (_state.bytes == null)
{
_wrappedPostingsWriter.EncodeTerm(_longs, _buffer, fieldInfo, _state.wrappedState, _absolute);
for (var i = 0; i < _longsSize; i++)
{
output.WriteVInt64(_longs[i]);
}
_buffer.WriteTo(output);
_buffer.Reset();
_absolute = false;
}
else
{
output.WriteVInt32(_state.bytes.Length);
output.WriteBytes(_state.bytes, 0, _state.bytes.Length);
_absolute = _absolute || abs;
}
}
protected override void Dispose(bool disposing)
{
_wrappedPostingsWriter.Dispose();
if (_wrappedPostingsWriter is PulsingPostingsWriter ||
VERSION_CURRENT < VERSION_META_ARRAY)
{
return;
}
var summaryFileName = IndexFileNames.SegmentFileName(_segmentState.SegmentInfo.Name,
_segmentState.SegmentSuffix, SUMMARY_EXTENSION);
IndexOutput output = null;
try
{
output =
_segmentState.Directory.CreateOutput(summaryFileName, _segmentState.Context);
CodecUtil.WriteHeader(output, CODEC, VERSION_CURRENT);
output.WriteVInt32(_fields.Count);
foreach (var field in _fields)
{
output.WriteVInt32(field.FieldNumber);
output.WriteVInt32(field.Int64sSize);
}
output.Dispose();
}
finally
{
IOUtils.DisposeWhileHandlingException(output);
}
}
/// <summary>
/// Pushes pending positions to the wrapped codec.
/// </summary>
private void Push()
{
Debug.Assert(_pendingCount == _pending.Length);
_wrappedPostingsWriter.StartTerm();
// Flush all buffered docs
if (_indexOptions.CompareTo(IndexOptions.DOCS_AND_FREQS_AND_POSITIONS) >= 0)
{
Position doc = null;
foreach (var pos in _pending)
{
if (doc == null)
{
doc = pos;
_wrappedPostingsWriter.StartDoc(doc.docID, doc.termFreq);
}
else if (doc.docID != pos.docID)
{
Debug.Assert(pos.docID > doc.docID);
_wrappedPostingsWriter.FinishDoc();
doc = pos;
_wrappedPostingsWriter.StartDoc(doc.docID, doc.termFreq);
}
_wrappedPostingsWriter.AddPosition(pos.pos, pos.payload, pos.startOffset, pos.endOffset);
}
//wrappedPostingsWriter.finishDoc();
}
else
{
foreach (var doc in _pending)
{
_wrappedPostingsWriter.StartDoc(doc.docID, _indexOptions == IndexOptions.DOCS_ONLY ? 0 : doc.termFreq);
}
}
_pendingCount = -1;
}
}
}
| |
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gax = Google.Api.Gax;
using gagr = Google.Api.Gax.ResourceNames;
using gctv = Google.Cloud.Tpu.V1;
using sys = System;
namespace Google.Cloud.Tpu.V1
{
/// <summary>Resource name for the <c>Node</c> resource.</summary>
public sealed partial class NodeName : gax::IResourceName, sys::IEquatable<NodeName>
{
/// <summary>The possible contents of <see cref="NodeName"/>.</summary>
public enum ResourceNameType
{
/// <summary>An unparsed resource name.</summary>
Unparsed = 0,
/// <summary>
/// A resource name with pattern <c>projects/{project}/locations/{location}/nodes/{node}</c>.
/// </summary>
ProjectLocationNode = 1,
}
private static gax::PathTemplate s_projectLocationNode = new gax::PathTemplate("projects/{project}/locations/{location}/nodes/{node}");
/// <summary>Creates a <see cref="NodeName"/> 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="NodeName"/> containing the provided <paramref name="unparsedResourceName"/>.
/// </returns>
public static NodeName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) =>
new NodeName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName)));
/// <summary>
/// Creates a <see cref="NodeName"/> with the pattern <c>projects/{project}/locations/{location}/nodes/{node}</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="nodeId">The <c>Node</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>A new instance of <see cref="NodeName"/> constructed from the provided ids.</returns>
public static NodeName FromProjectLocationNode(string projectId, string locationId, string nodeId) =>
new NodeName(ResourceNameType.ProjectLocationNode, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), nodeId: gax::GaxPreconditions.CheckNotNullOrEmpty(nodeId, nameof(nodeId)));
/// <summary>
/// Formats the IDs into the string representation of this <see cref="NodeName"/> with pattern
/// <c>projects/{project}/locations/{location}/nodes/{node}</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="nodeId">The <c>Node</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="NodeName"/> with pattern
/// <c>projects/{project}/locations/{location}/nodes/{node}</c>.
/// </returns>
public static string Format(string projectId, string locationId, string nodeId) =>
FormatProjectLocationNode(projectId, locationId, nodeId);
/// <summary>
/// Formats the IDs into the string representation of this <see cref="NodeName"/> with pattern
/// <c>projects/{project}/locations/{location}/nodes/{node}</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="nodeId">The <c>Node</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="NodeName"/> with pattern
/// <c>projects/{project}/locations/{location}/nodes/{node}</c>.
/// </returns>
public static string FormatProjectLocationNode(string projectId, string locationId, string nodeId) =>
s_projectLocationNode.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), gax::GaxPreconditions.CheckNotNullOrEmpty(nodeId, nameof(nodeId)));
/// <summary>Parses the given resource name string into a new <see cref="NodeName"/> instance.</summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item><description><c>projects/{project}/locations/{location}/nodes/{node}</c></description></item>
/// </list>
/// </remarks>
/// <param name="nodeName">The resource name in string form. Must not be <c>null</c>.</param>
/// <returns>The parsed <see cref="NodeName"/> if successful.</returns>
public static NodeName Parse(string nodeName) => Parse(nodeName, false);
/// <summary>
/// Parses the given resource name string into a new <see cref="NodeName"/> instance; optionally allowing an
/// unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item><description><c>projects/{project}/locations/{location}/nodes/{node}</c></description></item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="nodeName">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="NodeName"/> if successful.</returns>
public static NodeName Parse(string nodeName, bool allowUnparsed) =>
TryParse(nodeName, allowUnparsed, out NodeName 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="NodeName"/> instance.</summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item><description><c>projects/{project}/locations/{location}/nodes/{node}</c></description></item>
/// </list>
/// </remarks>
/// <param name="nodeName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="result">
/// When this method returns, the parsed <see cref="NodeName"/>, 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 nodeName, out NodeName result) => TryParse(nodeName, false, out result);
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="NodeName"/> instance; optionally
/// allowing an unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item><description><c>projects/{project}/locations/{location}/nodes/{node}</c></description></item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="nodeName">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="NodeName"/>, 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 nodeName, bool allowUnparsed, out NodeName result)
{
gax::GaxPreconditions.CheckNotNull(nodeName, nameof(nodeName));
gax::TemplatedResourceName resourceName;
if (s_projectLocationNode.TryParseName(nodeName, out resourceName))
{
result = FromProjectLocationNode(resourceName[0], resourceName[1], resourceName[2]);
return true;
}
if (allowUnparsed)
{
if (gax::UnparsedResourceName.TryParse(nodeName, out gax::UnparsedResourceName unparsedResourceName))
{
result = FromUnparsed(unparsedResourceName);
return true;
}
}
result = null;
return false;
}
private NodeName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string locationId = null, string nodeId = null, string projectId = null)
{
Type = type;
UnparsedResource = unparsedResourceName;
LocationId = locationId;
NodeId = nodeId;
ProjectId = projectId;
}
/// <summary>
/// Constructs a new instance of a <see cref="NodeName"/> class from the component parts of pattern
/// <c>projects/{project}/locations/{location}/nodes/{node}</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="nodeId">The <c>Node</c> ID. Must not be <c>null</c> or empty.</param>
public NodeName(string projectId, string locationId, string nodeId) : this(ResourceNameType.ProjectLocationNode, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), nodeId: gax::GaxPreconditions.CheckNotNullOrEmpty(nodeId, nameof(nodeId)))
{
}
/// <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>Location</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string LocationId { get; }
/// <summary>
/// The <c>Node</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string NodeId { get; }
/// <summary>
/// The <c>Project</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string ProjectId { get; }
/// <summary>Whether this instance contains a resource name with a known pattern.</summary>
public bool IsKnownPattern => Type != ResourceNameType.Unparsed;
/// <summary>The string representation of the resource name.</summary>
/// <returns>The string representation of the resource name.</returns>
public override string ToString()
{
switch (Type)
{
case ResourceNameType.Unparsed: return UnparsedResource.ToString();
case ResourceNameType.ProjectLocationNode: return s_projectLocationNode.Expand(ProjectId, LocationId, NodeId);
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 NodeName);
/// <inheritdoc/>
public bool Equals(NodeName other) => ToString() == other?.ToString();
/// <inheritdoc/>
public static bool operator ==(NodeName a, NodeName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false);
/// <inheritdoc/>
public static bool operator !=(NodeName a, NodeName b) => !(a == b);
}
/// <summary>Resource name for the <c>TensorFlowVersion</c> resource.</summary>
public sealed partial class TensorFlowVersionName : gax::IResourceName, sys::IEquatable<TensorFlowVersionName>
{
/// <summary>The possible contents of <see cref="TensorFlowVersionName"/>.</summary>
public enum ResourceNameType
{
/// <summary>An unparsed resource name.</summary>
Unparsed = 0,
/// <summary>
/// A resource name with pattern
/// <c>projects/{project}/locations/{location}/tensorFlowVersions/{tensor_flow_version}</c>.
/// </summary>
ProjectLocationTensorFlowVersion = 1,
}
private static gax::PathTemplate s_projectLocationTensorFlowVersion = new gax::PathTemplate("projects/{project}/locations/{location}/tensorFlowVersions/{tensor_flow_version}");
/// <summary>Creates a <see cref="TensorFlowVersionName"/> 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="TensorFlowVersionName"/> containing the provided
/// <paramref name="unparsedResourceName"/>.
/// </returns>
public static TensorFlowVersionName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) =>
new TensorFlowVersionName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName)));
/// <summary>
/// Creates a <see cref="TensorFlowVersionName"/> with the pattern
/// <c>projects/{project}/locations/{location}/tensorFlowVersions/{tensor_flow_version}</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="tensorFlowVersionId">The <c>TensorFlowVersion</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>A new instance of <see cref="TensorFlowVersionName"/> constructed from the provided ids.</returns>
public static TensorFlowVersionName FromProjectLocationTensorFlowVersion(string projectId, string locationId, string tensorFlowVersionId) =>
new TensorFlowVersionName(ResourceNameType.ProjectLocationTensorFlowVersion, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), tensorFlowVersionId: gax::GaxPreconditions.CheckNotNullOrEmpty(tensorFlowVersionId, nameof(tensorFlowVersionId)));
/// <summary>
/// Formats the IDs into the string representation of this <see cref="TensorFlowVersionName"/> with pattern
/// <c>projects/{project}/locations/{location}/tensorFlowVersions/{tensor_flow_version}</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="tensorFlowVersionId">The <c>TensorFlowVersion</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="TensorFlowVersionName"/> with pattern
/// <c>projects/{project}/locations/{location}/tensorFlowVersions/{tensor_flow_version}</c>.
/// </returns>
public static string Format(string projectId, string locationId, string tensorFlowVersionId) =>
FormatProjectLocationTensorFlowVersion(projectId, locationId, tensorFlowVersionId);
/// <summary>
/// Formats the IDs into the string representation of this <see cref="TensorFlowVersionName"/> with pattern
/// <c>projects/{project}/locations/{location}/tensorFlowVersions/{tensor_flow_version}</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="tensorFlowVersionId">The <c>TensorFlowVersion</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="TensorFlowVersionName"/> with pattern
/// <c>projects/{project}/locations/{location}/tensorFlowVersions/{tensor_flow_version}</c>.
/// </returns>
public static string FormatProjectLocationTensorFlowVersion(string projectId, string locationId, string tensorFlowVersionId) =>
s_projectLocationTensorFlowVersion.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), gax::GaxPreconditions.CheckNotNullOrEmpty(tensorFlowVersionId, nameof(tensorFlowVersionId)));
/// <summary>
/// Parses the given resource name string into a new <see cref="TensorFlowVersionName"/> instance.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description>
/// <c>projects/{project}/locations/{location}/tensorFlowVersions/{tensor_flow_version}</c>
/// </description>
/// </item>
/// </list>
/// </remarks>
/// <param name="tensorFlowVersionName">The resource name in string form. Must not be <c>null</c>.</param>
/// <returns>The parsed <see cref="TensorFlowVersionName"/> if successful.</returns>
public static TensorFlowVersionName Parse(string tensorFlowVersionName) => Parse(tensorFlowVersionName, false);
/// <summary>
/// Parses the given resource name string into a new <see cref="TensorFlowVersionName"/> instance; optionally
/// allowing an unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description>
/// <c>projects/{project}/locations/{location}/tensorFlowVersions/{tensor_flow_version}</c>
/// </description>
/// </item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="tensorFlowVersionName">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="TensorFlowVersionName"/> if successful.</returns>
public static TensorFlowVersionName Parse(string tensorFlowVersionName, bool allowUnparsed) =>
TryParse(tensorFlowVersionName, allowUnparsed, out TensorFlowVersionName 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="TensorFlowVersionName"/> instance.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description>
/// <c>projects/{project}/locations/{location}/tensorFlowVersions/{tensor_flow_version}</c>
/// </description>
/// </item>
/// </list>
/// </remarks>
/// <param name="tensorFlowVersionName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="result">
/// When this method returns, the parsed <see cref="TensorFlowVersionName"/>, 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 tensorFlowVersionName, out TensorFlowVersionName result) =>
TryParse(tensorFlowVersionName, false, out result);
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="TensorFlowVersionName"/> instance;
/// optionally allowing an unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description>
/// <c>projects/{project}/locations/{location}/tensorFlowVersions/{tensor_flow_version}</c>
/// </description>
/// </item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="tensorFlowVersionName">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="TensorFlowVersionName"/>, 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 tensorFlowVersionName, bool allowUnparsed, out TensorFlowVersionName result)
{
gax::GaxPreconditions.CheckNotNull(tensorFlowVersionName, nameof(tensorFlowVersionName));
gax::TemplatedResourceName resourceName;
if (s_projectLocationTensorFlowVersion.TryParseName(tensorFlowVersionName, out resourceName))
{
result = FromProjectLocationTensorFlowVersion(resourceName[0], resourceName[1], resourceName[2]);
return true;
}
if (allowUnparsed)
{
if (gax::UnparsedResourceName.TryParse(tensorFlowVersionName, out gax::UnparsedResourceName unparsedResourceName))
{
result = FromUnparsed(unparsedResourceName);
return true;
}
}
result = null;
return false;
}
private TensorFlowVersionName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string locationId = null, string projectId = null, string tensorFlowVersionId = null)
{
Type = type;
UnparsedResource = unparsedResourceName;
LocationId = locationId;
ProjectId = projectId;
TensorFlowVersionId = tensorFlowVersionId;
}
/// <summary>
/// Constructs a new instance of a <see cref="TensorFlowVersionName"/> class from the component parts of pattern
/// <c>projects/{project}/locations/{location}/tensorFlowVersions/{tensor_flow_version}</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="tensorFlowVersionId">The <c>TensorFlowVersion</c> ID. Must not be <c>null</c> or empty.</param>
public TensorFlowVersionName(string projectId, string locationId, string tensorFlowVersionId) : this(ResourceNameType.ProjectLocationTensorFlowVersion, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), tensorFlowVersionId: gax::GaxPreconditions.CheckNotNullOrEmpty(tensorFlowVersionId, nameof(tensorFlowVersionId)))
{
}
/// <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>Location</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string LocationId { get; }
/// <summary>
/// The <c>Project</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string ProjectId { get; }
/// <summary>
/// The <c>TensorFlowVersion</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource
/// name.
/// </summary>
public string TensorFlowVersionId { 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.ProjectLocationTensorFlowVersion: return s_projectLocationTensorFlowVersion.Expand(ProjectId, LocationId, TensorFlowVersionId);
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 TensorFlowVersionName);
/// <inheritdoc/>
public bool Equals(TensorFlowVersionName other) => ToString() == other?.ToString();
/// <inheritdoc/>
public static bool operator ==(TensorFlowVersionName a, TensorFlowVersionName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false);
/// <inheritdoc/>
public static bool operator !=(TensorFlowVersionName a, TensorFlowVersionName b) => !(a == b);
}
/// <summary>Resource name for the <c>AcceleratorType</c> resource.</summary>
public sealed partial class AcceleratorTypeName : gax::IResourceName, sys::IEquatable<AcceleratorTypeName>
{
/// <summary>The possible contents of <see cref="AcceleratorTypeName"/>.</summary>
public enum ResourceNameType
{
/// <summary>An unparsed resource name.</summary>
Unparsed = 0,
/// <summary>
/// A resource name with pattern
/// <c>projects/{project}/locations/{location}/acceleratorTypes/{accelerator_type}</c>.
/// </summary>
ProjectLocationAcceleratorType = 1,
}
private static gax::PathTemplate s_projectLocationAcceleratorType = new gax::PathTemplate("projects/{project}/locations/{location}/acceleratorTypes/{accelerator_type}");
/// <summary>Creates a <see cref="AcceleratorTypeName"/> 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="AcceleratorTypeName"/> containing the provided
/// <paramref name="unparsedResourceName"/>.
/// </returns>
public static AcceleratorTypeName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) =>
new AcceleratorTypeName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName)));
/// <summary>
/// Creates a <see cref="AcceleratorTypeName"/> with the pattern
/// <c>projects/{project}/locations/{location}/acceleratorTypes/{accelerator_type}</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="acceleratorTypeId">The <c>AcceleratorType</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>A new instance of <see cref="AcceleratorTypeName"/> constructed from the provided ids.</returns>
public static AcceleratorTypeName FromProjectLocationAcceleratorType(string projectId, string locationId, string acceleratorTypeId) =>
new AcceleratorTypeName(ResourceNameType.ProjectLocationAcceleratorType, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), acceleratorTypeId: gax::GaxPreconditions.CheckNotNullOrEmpty(acceleratorTypeId, nameof(acceleratorTypeId)));
/// <summary>
/// Formats the IDs into the string representation of this <see cref="AcceleratorTypeName"/> with pattern
/// <c>projects/{project}/locations/{location}/acceleratorTypes/{accelerator_type}</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="acceleratorTypeId">The <c>AcceleratorType</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="AcceleratorTypeName"/> with pattern
/// <c>projects/{project}/locations/{location}/acceleratorTypes/{accelerator_type}</c>.
/// </returns>
public static string Format(string projectId, string locationId, string acceleratorTypeId) =>
FormatProjectLocationAcceleratorType(projectId, locationId, acceleratorTypeId);
/// <summary>
/// Formats the IDs into the string representation of this <see cref="AcceleratorTypeName"/> with pattern
/// <c>projects/{project}/locations/{location}/acceleratorTypes/{accelerator_type}</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="acceleratorTypeId">The <c>AcceleratorType</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="AcceleratorTypeName"/> with pattern
/// <c>projects/{project}/locations/{location}/acceleratorTypes/{accelerator_type}</c>.
/// </returns>
public static string FormatProjectLocationAcceleratorType(string projectId, string locationId, string acceleratorTypeId) =>
s_projectLocationAcceleratorType.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), gax::GaxPreconditions.CheckNotNullOrEmpty(acceleratorTypeId, nameof(acceleratorTypeId)));
/// <summary>
/// Parses the given resource name string into a new <see cref="AcceleratorTypeName"/> instance.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description>
/// <c>projects/{project}/locations/{location}/acceleratorTypes/{accelerator_type}</c>
/// </description>
/// </item>
/// </list>
/// </remarks>
/// <param name="acceleratorTypeName">The resource name in string form. Must not be <c>null</c>.</param>
/// <returns>The parsed <see cref="AcceleratorTypeName"/> if successful.</returns>
public static AcceleratorTypeName Parse(string acceleratorTypeName) => Parse(acceleratorTypeName, false);
/// <summary>
/// Parses the given resource name string into a new <see cref="AcceleratorTypeName"/> instance; optionally
/// allowing an unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description>
/// <c>projects/{project}/locations/{location}/acceleratorTypes/{accelerator_type}</c>
/// </description>
/// </item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="acceleratorTypeName">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="AcceleratorTypeName"/> if successful.</returns>
public static AcceleratorTypeName Parse(string acceleratorTypeName, bool allowUnparsed) =>
TryParse(acceleratorTypeName, allowUnparsed, out AcceleratorTypeName 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="AcceleratorTypeName"/> instance.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description>
/// <c>projects/{project}/locations/{location}/acceleratorTypes/{accelerator_type}</c>
/// </description>
/// </item>
/// </list>
/// </remarks>
/// <param name="acceleratorTypeName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="result">
/// When this method returns, the parsed <see cref="AcceleratorTypeName"/>, 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 acceleratorTypeName, out AcceleratorTypeName result) =>
TryParse(acceleratorTypeName, false, out result);
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="AcceleratorTypeName"/> instance;
/// optionally allowing an unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description>
/// <c>projects/{project}/locations/{location}/acceleratorTypes/{accelerator_type}</c>
/// </description>
/// </item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="acceleratorTypeName">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="AcceleratorTypeName"/>, 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 acceleratorTypeName, bool allowUnparsed, out AcceleratorTypeName result)
{
gax::GaxPreconditions.CheckNotNull(acceleratorTypeName, nameof(acceleratorTypeName));
gax::TemplatedResourceName resourceName;
if (s_projectLocationAcceleratorType.TryParseName(acceleratorTypeName, out resourceName))
{
result = FromProjectLocationAcceleratorType(resourceName[0], resourceName[1], resourceName[2]);
return true;
}
if (allowUnparsed)
{
if (gax::UnparsedResourceName.TryParse(acceleratorTypeName, out gax::UnparsedResourceName unparsedResourceName))
{
result = FromUnparsed(unparsedResourceName);
return true;
}
}
result = null;
return false;
}
private AcceleratorTypeName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string acceleratorTypeId = null, string locationId = null, string projectId = null)
{
Type = type;
UnparsedResource = unparsedResourceName;
AcceleratorTypeId = acceleratorTypeId;
LocationId = locationId;
ProjectId = projectId;
}
/// <summary>
/// Constructs a new instance of a <see cref="AcceleratorTypeName"/> class from the component parts of pattern
/// <c>projects/{project}/locations/{location}/acceleratorTypes/{accelerator_type}</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="acceleratorTypeId">The <c>AcceleratorType</c> ID. Must not be <c>null</c> or empty.</param>
public AcceleratorTypeName(string projectId, string locationId, string acceleratorTypeId) : this(ResourceNameType.ProjectLocationAcceleratorType, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), acceleratorTypeId: gax::GaxPreconditions.CheckNotNullOrEmpty(acceleratorTypeId, nameof(acceleratorTypeId)))
{
}
/// <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>AcceleratorType</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource
/// name.
/// </summary>
public string AcceleratorTypeId { get; }
/// <summary>
/// The <c>Location</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string LocationId { get; }
/// <summary>
/// The <c>Project</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string ProjectId { get; }
/// <summary>Whether this instance contains a resource name with a known pattern.</summary>
public bool IsKnownPattern => Type != ResourceNameType.Unparsed;
/// <summary>The string representation of the resource name.</summary>
/// <returns>The string representation of the resource name.</returns>
public override string ToString()
{
switch (Type)
{
case ResourceNameType.Unparsed: return UnparsedResource.ToString();
case ResourceNameType.ProjectLocationAcceleratorType: return s_projectLocationAcceleratorType.Expand(ProjectId, LocationId, AcceleratorTypeId);
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 AcceleratorTypeName);
/// <inheritdoc/>
public bool Equals(AcceleratorTypeName other) => ToString() == other?.ToString();
/// <inheritdoc/>
public static bool operator ==(AcceleratorTypeName a, AcceleratorTypeName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false);
/// <inheritdoc/>
public static bool operator !=(AcceleratorTypeName a, AcceleratorTypeName b) => !(a == b);
}
public partial class Node
{
/// <summary>
/// <see cref="gctv::NodeName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gctv::NodeName NodeName
{
get => string.IsNullOrEmpty(Name) ? null : gctv::NodeName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
}
public partial class ListNodesRequest
{
/// <summary>
/// <see cref="gagr::LocationName"/>-typed view over the <see cref="Parent"/> resource name property.
/// </summary>
public gagr::LocationName ParentAsLocationName
{
get => string.IsNullOrEmpty(Parent) ? null : gagr::LocationName.Parse(Parent, allowUnparsed: true);
set => Parent = value?.ToString() ?? "";
}
}
public partial class GetNodeRequest
{
/// <summary>
/// <see cref="gctv::NodeName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gctv::NodeName NodeName
{
get => string.IsNullOrEmpty(Name) ? null : gctv::NodeName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
}
public partial class CreateNodeRequest
{
/// <summary>
/// <see cref="gagr::LocationName"/>-typed view over the <see cref="Parent"/> resource name property.
/// </summary>
public gagr::LocationName ParentAsLocationName
{
get => string.IsNullOrEmpty(Parent) ? null : gagr::LocationName.Parse(Parent, allowUnparsed: true);
set => Parent = value?.ToString() ?? "";
}
}
public partial class DeleteNodeRequest
{
/// <summary>
/// <see cref="gctv::NodeName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gctv::NodeName NodeName
{
get => string.IsNullOrEmpty(Name) ? null : gctv::NodeName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
}
public partial class TensorFlowVersion
{
/// <summary>
/// <see cref="gctv::TensorFlowVersionName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gctv::TensorFlowVersionName TensorFlowVersionName
{
get => string.IsNullOrEmpty(Name) ? null : gctv::TensorFlowVersionName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
}
public partial class GetTensorFlowVersionRequest
{
/// <summary>
/// <see cref="gctv::TensorFlowVersionName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gctv::TensorFlowVersionName TensorFlowVersionName
{
get => string.IsNullOrEmpty(Name) ? null : gctv::TensorFlowVersionName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
}
public partial class ListTensorFlowVersionsRequest
{
/// <summary>
/// <see cref="TensorFlowVersionName"/>-typed view over the <see cref="Parent"/> resource name property.
/// </summary>
public TensorFlowVersionName ParentAsTensorFlowVersionName
{
get => string.IsNullOrEmpty(Parent) ? null : TensorFlowVersionName.Parse(Parent, allowUnparsed: true);
set => Parent = value?.ToString() ?? "";
}
}
public partial class AcceleratorType
{
/// <summary>
/// <see cref="gctv::AcceleratorTypeName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gctv::AcceleratorTypeName AcceleratorTypeName
{
get => string.IsNullOrEmpty(Name) ? null : gctv::AcceleratorTypeName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
}
public partial class GetAcceleratorTypeRequest
{
/// <summary>
/// <see cref="gctv::AcceleratorTypeName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gctv::AcceleratorTypeName AcceleratorTypeName
{
get => string.IsNullOrEmpty(Name) ? null : gctv::AcceleratorTypeName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
}
public partial class ListAcceleratorTypesRequest
{
/// <summary>
/// <see cref="AcceleratorTypeName"/>-typed view over the <see cref="Parent"/> resource name property.
/// </summary>
public AcceleratorTypeName ParentAsAcceleratorTypeName
{
get => string.IsNullOrEmpty(Parent) ? null : AcceleratorTypeName.Parse(Parent, allowUnparsed: true);
set => Parent = value?.ToString() ?? "";
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.OData.Routing.Controllers;
using Microsoft.AspNetCore.OData.Query;
using Microsoft.AspNetCore.OData.Results;
using Microsoft.AspNetCore.OData.Formatter;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.AspNetCore.OData.Deltas;
using hihapi.Exceptions;
using hihapi.Models;
using hihapi.Utilities;
namespace hihapi.Controllers
{
[Authorize]
public sealed class FinanceOrdersController : ODataController
{
private readonly hihDataContext _context;
public FinanceOrdersController(hihDataContext context)
{
_context = context;
}
/// GET: /FinanceOrders
[EnableQuery]
[HttpGet]
//public IQueryable Get(ODataQueryOptions<FinanceOrder> option)
public IActionResult Get()
{
String usrName = String.Empty;
try
{
usrName = HIHAPIUtility.GetUserID(this);
if (String.IsNullOrEmpty(usrName))
throw new UnauthorizedAccessException();
}
catch
{
throw new UnauthorizedAccessException();
}
//return option.ApplyTo(query);
// Check whether User assigned with specified Home ID
return Ok(from hmem in _context.HomeMembers
where hmem.User == usrName
select new { hmem.HomeID, hmem.IsChild } into hids
join ords in _context.FinanceOrder on hids.HomeID equals ords.HomeID
select ords);
}
[EnableQuery]
[HttpGet]
public FinanceOrder Get([FromODataUri] Int32 key)
{
String usrName = String.Empty;
try
{
usrName = HIHAPIUtility.GetUserID(this);
if (String.IsNullOrEmpty(usrName))
throw new UnauthorizedAccessException();
}
catch
{
throw new UnauthorizedAccessException();
}
var hidquery = from hmem in _context.HomeMembers
where hmem.User == usrName
select new { HomeID = hmem.HomeID };
var ordquery = from ord in _context.FinanceOrder
where ord.ID == key
select ord;
var rstquery = from ord in ordquery
join hid in hidquery
on ord.HomeID equals hid.HomeID
select ord;
return rstquery.SingleOrDefault();
}
[HttpPost]
public async Task<IActionResult> Post([FromBody] FinanceOrder order)
{
if (!ModelState.IsValid)
{
HIHAPIUtility.HandleModalStateError(ModelState);
}
// Check
if (!order.IsValid(this._context))
{
throw new BadRequestException("Inputted Object IsValid failed");
}
// User
String usrName = String.Empty;
try
{
usrName = HIHAPIUtility.GetUserID(this);
if (String.IsNullOrEmpty(usrName))
{
throw new UnauthorizedAccessException();
}
}
catch
{
throw new UnauthorizedAccessException();
}
// Check whether User assigned with specified Home ID
var hms = _context.HomeMembers.Where(p => p.HomeID == order.HomeID && p.User == usrName).Count();
if (hms <= 0)
{
throw new UnauthorizedAccessException();
}
order.CreatedAt = DateTime.Now;
order.Createdby = usrName;
_context.FinanceOrder.Add(order);
await _context.SaveChangesAsync();
return Created(order);
}
[HttpPut]
public async Task<IActionResult> Put([FromODataUri] int key, [FromBody] FinanceOrder update)
{
if (!ModelState.IsValid)
{
HIHAPIUtility.HandleModalStateError(ModelState);
}
if (key != update.ID)
{
throw new BadRequestException("Inputted ID mismatched");
}
// User
String usrName = String.Empty;
try
{
usrName = HIHAPIUtility.GetUserID(this);
if (String.IsNullOrEmpty(usrName))
{
throw new UnauthorizedAccessException();
}
}
catch
{
throw new UnauthorizedAccessException();
}
// Check whether User assigned with specified Home ID
var hms = _context.HomeMembers.Where(p => p.HomeID == update.HomeID && p.User == usrName).Count();
if (hms <= 0)
{
throw new UnauthorizedAccessException();
}
if (!update.IsValid(this._context))
return BadRequest();
update.Updatedby = usrName;
update.UpdatedAt = DateTime.Now;
_context.Entry(update).State = EntityState.Modified;
// SRules.
var rulesInDB = _context.FinanceOrderSRule.Where(p => p.OrderID == update.ID).ToList();
foreach (var rule in update.SRule)
{
var itemindb = rulesInDB.Find(p => p.OrderID == update.ID && p.RuleID == rule.RuleID);
if (itemindb == null)
{
_context.FinanceOrderSRule.Add(rule);
}
else
{
// Update
_context.Entry(itemindb).State = EntityState.Modified;
}
}
foreach (var rule in rulesInDB)
{
var nitem = update.SRule.FirstOrDefault(p => p.OrderID == update.ID && p.RuleID == rule.RuleID);
if (nitem == null)
{
_context.FinanceOrderSRule.Remove(rule);
}
}
try
{
await _context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException exp)
{
if (!_context.FinanceOrder.Any(p => p.ID == key))
{
return NotFound();
}
else
{
throw new DBOperationException(exp.Message);
}
}
return Updated(update);
}
[HttpPatch]
public async Task<IActionResult> Patch([FromODataUri] int key, [FromBody] Delta<FinanceOrder> doc)
{
if (!ModelState.IsValid)
{
HIHAPIUtility.HandleModalStateError(ModelState);
}
var entity = await _context.FinanceOrder.FindAsync(key);
if (entity == null)
{
return NotFound();
}
// User
string usrName;
try
{
usrName = HIHAPIUtility.GetUserID(this);
if (String.IsNullOrEmpty(usrName))
{
throw new UnauthorizedAccessException();
}
}
catch
{
throw new UnauthorizedAccessException();
}
// Patch it
doc.Patch(entity);
try
{
await _context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!_context.FinanceOrder.Any(p => p.ID == key))
{
return NotFound();
}
else
{
throw;
}
}
return Updated(entity);
}
[HttpDelete]
public async Task<IActionResult> Delete([FromODataUri] int key)
{
var cc = await _context.FinanceOrder.FindAsync(key);
if (cc == null)
{
return NotFound();
}
// User
String usrName = String.Empty;
try
{
usrName = HIHAPIUtility.GetUserID(this);
if (String.IsNullOrEmpty(usrName))
{
throw new UnauthorizedAccessException();
}
}
catch
{
throw new UnauthorizedAccessException();
}
// Check whether User assigned with specified Home ID
var hms = _context.HomeMembers.Where(p => p.HomeID == cc.HomeID && p.User == usrName).Count();
if (hms <= 0)
{
throw new UnauthorizedAccessException();
}
if (!cc.IsDeleteAllowed(this._context))
throw new BadRequestException("Inputted Object IsDeleteAllowed failed");
_context.FinanceOrder.Remove(cc);
await _context.SaveChangesAsync();
return StatusCode(204); // HttpStatusCode.NoContent
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Fixtures.AcceptanceTestsAzureBodyDurationNoSync
{
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Microsoft.Rest.Serialization;
using Models;
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
/// <summary>
/// Test Infrastructure for AutoRest
/// </summary>
public partial class AutoRestDurationTestServiceClient : ServiceClient<AutoRestDurationTestServiceClient>, IAutoRestDurationTestServiceClient, IAzureClient
{
/// <summary>
/// The base URI of the service.
/// </summary>
public System.Uri BaseUri { get; set; }
/// <summary>
/// Gets or sets json serialization settings.
/// </summary>
public JsonSerializerSettings SerializationSettings { get; private set; }
/// <summary>
/// Gets or sets json deserialization settings.
/// </summary>
public JsonSerializerSettings DeserializationSettings { get; private set; }
/// <summary>
/// Credentials needed for the client to connect to Azure.
/// </summary>
public ServiceClientCredentials Credentials { get; private set; }
/// <summary>
/// Gets or sets the preferred language for the response.
/// </summary>
public string AcceptLanguage { get; set; }
/// <summary>
/// Gets or sets the retry timeout in seconds for Long Running Operations.
/// Default value is 30.
/// </summary>
public int? LongRunningOperationRetryTimeout { get; set; }
/// <summary>
/// When set to true a unique x-ms-client-request-id value is generated and
/// included in each request. Default is true.
/// </summary>
public bool? GenerateClientRequestId { get; set; }
/// <summary>
/// Gets the IDurationOperations.
/// </summary>
public virtual IDurationOperations Duration { get; private set; }
/// <summary>
/// Initializes a new instance of the AutoRestDurationTestServiceClient class.
/// </summary>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
protected AutoRestDurationTestServiceClient(params System.Net.Http.DelegatingHandler[] handlers) : base(handlers)
{
Initialize();
}
/// <summary>
/// Initializes a new instance of the AutoRestDurationTestServiceClient class.
/// </summary>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
protected AutoRestDurationTestServiceClient(System.Net.Http.HttpClientHandler rootHandler, params System.Net.Http.DelegatingHandler[] handlers) : base(rootHandler, handlers)
{
Initialize();
}
/// <summary>
/// Initializes a new instance of the AutoRestDurationTestServiceClient class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
protected AutoRestDurationTestServiceClient(System.Uri baseUri, params System.Net.Http.DelegatingHandler[] handlers) : this(handlers)
{
if (baseUri == null)
{
throw new System.ArgumentNullException("baseUri");
}
BaseUri = baseUri;
}
/// <summary>
/// Initializes a new instance of the AutoRestDurationTestServiceClient class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
protected AutoRestDurationTestServiceClient(System.Uri baseUri, System.Net.Http.HttpClientHandler rootHandler, params System.Net.Http.DelegatingHandler[] handlers) : this(rootHandler, handlers)
{
if (baseUri == null)
{
throw new System.ArgumentNullException("baseUri");
}
BaseUri = baseUri;
}
/// <summary>
/// Initializes a new instance of the AutoRestDurationTestServiceClient class.
/// </summary>
/// <param name='credentials'>
/// Required. Credentials needed for the client to connect to Azure.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public AutoRestDurationTestServiceClient(ServiceClientCredentials credentials, params System.Net.Http.DelegatingHandler[] handlers) : this(handlers)
{
if (credentials == null)
{
throw new System.ArgumentNullException("credentials");
}
Credentials = credentials;
if (Credentials != null)
{
Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// Initializes a new instance of the AutoRestDurationTestServiceClient class.
/// </summary>
/// <param name='credentials'>
/// Required. Credentials needed for the client to connect to Azure.
/// </param>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public AutoRestDurationTestServiceClient(ServiceClientCredentials credentials, System.Net.Http.HttpClientHandler rootHandler, params System.Net.Http.DelegatingHandler[] handlers) : this(rootHandler, handlers)
{
if (credentials == null)
{
throw new System.ArgumentNullException("credentials");
}
Credentials = credentials;
if (Credentials != null)
{
Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// Initializes a new instance of the AutoRestDurationTestServiceClient class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='credentials'>
/// Required. Credentials needed for the client to connect to Azure.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public AutoRestDurationTestServiceClient(System.Uri baseUri, ServiceClientCredentials credentials, params System.Net.Http.DelegatingHandler[] handlers) : this(handlers)
{
if (baseUri == null)
{
throw new System.ArgumentNullException("baseUri");
}
if (credentials == null)
{
throw new System.ArgumentNullException("credentials");
}
BaseUri = baseUri;
Credentials = credentials;
if (Credentials != null)
{
Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// Initializes a new instance of the AutoRestDurationTestServiceClient class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='credentials'>
/// Required. Credentials needed for the client to connect to Azure.
/// </param>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public AutoRestDurationTestServiceClient(System.Uri baseUri, ServiceClientCredentials credentials, System.Net.Http.HttpClientHandler rootHandler, params System.Net.Http.DelegatingHandler[] handlers) : this(rootHandler, handlers)
{
if (baseUri == null)
{
throw new System.ArgumentNullException("baseUri");
}
if (credentials == null)
{
throw new System.ArgumentNullException("credentials");
}
BaseUri = baseUri;
Credentials = credentials;
if (Credentials != null)
{
Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// An optional partial-method to perform custom initialization.
/// </summary>
partial void CustomInitialize();
/// <summary>
/// Initializes client properties.
/// </summary>
private void Initialize()
{
Duration = new DurationOperations(this);
BaseUri = new System.Uri("https://localhost");
AcceptLanguage = "en-US";
LongRunningOperationRetryTimeout = 30;
GenerateClientRequestId = true;
SerializationSettings = new JsonSerializerSettings
{
Formatting = Formatting.Indented,
DateFormatHandling = DateFormatHandling.IsoDateFormat,
DateTimeZoneHandling = DateTimeZoneHandling.Utc,
NullValueHandling = NullValueHandling.Ignore,
ReferenceLoopHandling = ReferenceLoopHandling.Serialize,
ContractResolver = new ReadOnlyJsonContractResolver(),
Converters = new List<JsonConverter>
{
new Iso8601TimeSpanConverter()
}
};
DeserializationSettings = new JsonSerializerSettings
{
DateFormatHandling = DateFormatHandling.IsoDateFormat,
DateTimeZoneHandling = DateTimeZoneHandling.Utc,
NullValueHandling = NullValueHandling.Ignore,
ReferenceLoopHandling = ReferenceLoopHandling.Serialize,
ContractResolver = new ReadOnlyJsonContractResolver(),
Converters = new List<JsonConverter>
{
new Iso8601TimeSpanConverter()
}
};
CustomInitialize();
DeserializationSettings.Converters.Add(new CloudErrorJsonConverter());
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.Serialization;
///This file contains all the typed enums that the client rest api spec exposes.
///This file is automatically generated from https://github.com/elasticsearch/elasticsearch-rest-api-spec
///Generated of commit
namespace Elasticsearch.Net
{
public enum Consistency
{
[EnumMember(Value = "one")]
One,
[EnumMember(Value = "quorum")]
Quorum,
[EnumMember(Value = "all")]
All
}
public enum Bytes
{
[EnumMember(Value = "b")]
B,
[EnumMember(Value = "k")]
K,
[EnumMember(Value = "m")]
M,
[EnumMember(Value = "g")]
G
}
public enum Level
{
[EnumMember(Value = "cluster")]
Cluster,
[EnumMember(Value = "indices")]
Indices,
[EnumMember(Value = "shards")]
Shards
}
public enum WaitForStatus
{
[EnumMember(Value = "green")]
Green,
[EnumMember(Value = "yellow")]
Yellow,
[EnumMember(Value = "red")]
Red
}
public enum ExpandWildcards
{
[EnumMember(Value = "open")]
Open,
[EnumMember(Value = "closed")]
Closed,
[EnumMember(Value = "none")]
None,
[EnumMember(Value = "all")]
All
}
public enum DefaultOperator
{
[EnumMember(Value = "AND")]
And,
[EnumMember(Value = "OR")]
Or
}
public enum VersionType
{
[EnumMember(Value = "internal")]
Internal,
[EnumMember(Value = "external")]
External,
[EnumMember(Value = "external_gte")]
ExternalGte,
[EnumMember(Value = "force")]
Force
}
public enum OpType
{
[EnumMember(Value = "index")]
Index,
[EnumMember(Value = "create")]
Create
}
public enum Format
{
[EnumMember(Value = "detailed")]
Detailed,
[EnumMember(Value = "text")]
Text
}
public enum SearchType
{
[EnumMember(Value = "query_then_fetch")]
QueryThenFetch,
[EnumMember(Value = "query_and_fetch")]
QueryAndFetch,
[EnumMember(Value = "dfs_query_then_fetch")]
DfsQueryThenFetch,
[EnumMember(Value = "dfs_query_and_fetch")]
DfsQueryAndFetch,
[EnumMember(Value = "count")]
Count,
[EnumMember(Value = "scan")]
Scan
}
public enum ThreadType
{
[EnumMember(Value = "cpu")]
Cpu,
[EnumMember(Value = "wait")]
Wait,
[EnumMember(Value = "block")]
Block
}
public enum PercolateFormat
{
[EnumMember(Value = "ids")]
Ids
}
public enum SuggestMode
{
[EnumMember(Value = "missing")]
Missing,
[EnumMember(Value = "popular")]
Popular,
[EnumMember(Value = "always")]
Always
}
[Flags]public enum ClusterStateMetric
{
[EnumMember(Value = "blocks")]
Blocks = 1 << 0,
[EnumMember(Value = "metadata")]
Metadata = 1 << 1,
[EnumMember(Value = "nodes")]
Nodes = 1 << 2,
[EnumMember(Value = "routing_table")]
RoutingTable = 1 << 3,
[EnumMember(Value = "routing_nodes")]
RoutingNodes = 1 << 4,
[EnumMember(Value = "master_node")]
MasterNode = 1 << 5,
[EnumMember(Value = "version")]
Version = 1 << 6,
[EnumMember(Value = "_all")]
All = 1 << 7
}
[Flags]public enum Feature
{
[EnumMember(Value = "_settings")]
Settings = 1 << 0,
[EnumMember(Value = "_mappings")]
Mappings = 1 << 1,
[EnumMember(Value = "_warmers")]
Warmers = 1 << 2,
[EnumMember(Value = "_aliases")]
Aliases = 1 << 3
}
[Flags]public enum IndicesStatsMetric
{
[EnumMember(Value = "completion")]
Completion = 1 << 0,
[EnumMember(Value = "docs")]
Docs = 1 << 1,
[EnumMember(Value = "fielddata")]
Fielddata = 1 << 2,
[EnumMember(Value = "query_cache")]
QueryCache = 1 << 3,
[EnumMember(Value = "flush")]
Flush = 1 << 4,
[EnumMember(Value = "get")]
Get = 1 << 5,
[EnumMember(Value = "indexing")]
Indexing = 1 << 6,
[EnumMember(Value = "merge")]
Merge = 1 << 7,
[EnumMember(Value = "percolate")]
Percolate = 1 << 8,
[EnumMember(Value = "request_cache")]
RequestCache = 1 << 9,
[EnumMember(Value = "refresh")]
Refresh = 1 << 10,
[EnumMember(Value = "search")]
Search = 1 << 11,
[EnumMember(Value = "segments")]
Segments = 1 << 12,
[EnumMember(Value = "store")]
Store = 1 << 13,
[EnumMember(Value = "warmer")]
Warmer = 1 << 14,
[EnumMember(Value = "suggest")]
Suggest = 1 << 15,
[EnumMember(Value = "_all")]
All = 1 << 16
}
[Flags]public enum NodesInfoMetric
{
[EnumMember(Value = "settings")]
Settings = 1 << 0,
[EnumMember(Value = "os")]
Os = 1 << 1,
[EnumMember(Value = "process")]
Process = 1 << 2,
[EnumMember(Value = "jvm")]
Jvm = 1 << 3,
[EnumMember(Value = "thread_pool")]
ThreadPool = 1 << 4,
[EnumMember(Value = "transport")]
Transport = 1 << 5,
[EnumMember(Value = "http")]
Http = 1 << 6,
[EnumMember(Value = "plugins")]
Plugins = 1 << 7
}
[Flags]public enum NodesStatsMetric
{
[EnumMember(Value = "breaker")]
Breaker = 1 << 0,
[EnumMember(Value = "fs")]
Fs = 1 << 1,
[EnumMember(Value = "http")]
Http = 1 << 2,
[EnumMember(Value = "indices")]
Indices = 1 << 3,
[EnumMember(Value = "jvm")]
Jvm = 1 << 4,
[EnumMember(Value = "os")]
Os = 1 << 5,
[EnumMember(Value = "process")]
Process = 1 << 6,
[EnumMember(Value = "thread_pool")]
ThreadPool = 1 << 7,
[EnumMember(Value = "transport")]
Transport = 1 << 8,
[EnumMember(Value = "_all")]
All = 1 << 9
}
[Flags]public enum NodesStatsIndexMetric
{
[EnumMember(Value = "completion")]
Completion = 1 << 0,
[EnumMember(Value = "docs")]
Docs = 1 << 1,
[EnumMember(Value = "fielddata")]
Fielddata = 1 << 2,
[EnumMember(Value = "query_cache")]
QueryCache = 1 << 3,
[EnumMember(Value = "flush")]
Flush = 1 << 4,
[EnumMember(Value = "get")]
Get = 1 << 5,
[EnumMember(Value = "indexing")]
Indexing = 1 << 6,
[EnumMember(Value = "merge")]
Merge = 1 << 7,
[EnumMember(Value = "percolate")]
Percolate = 1 << 8,
[EnumMember(Value = "request_cache")]
RequestCache = 1 << 9,
[EnumMember(Value = "refresh")]
Refresh = 1 << 10,
[EnumMember(Value = "search")]
Search = 1 << 11,
[EnumMember(Value = "segments")]
Segments = 1 << 12,
[EnumMember(Value = "store")]
Store = 1 << 13,
[EnumMember(Value = "warmer")]
Warmer = 1 << 14,
[EnumMember(Value = "suggest")]
Suggest = 1 << 15,
[EnumMember(Value = "_all")]
All = 1 << 16
}
public static class KnownEnums
{
public static string UnknownEnum { get; } = "_UNKNOWN_ENUM_";
public static string Resolve(Enum e)
{
if (e is Consistency)
{
switch((Consistency)e)
{
case Consistency.One: return "one";
case Consistency.Quorum: return "quorum";
case Consistency.All: return "all";
}
}
if (e is Bytes)
{
switch((Bytes)e)
{
case Bytes.B: return "b";
case Bytes.K: return "k";
case Bytes.M: return "m";
case Bytes.G: return "g";
}
}
if (e is Level)
{
switch((Level)e)
{
case Level.Cluster: return "cluster";
case Level.Indices: return "indices";
case Level.Shards: return "shards";
}
}
if (e is WaitForStatus)
{
switch((WaitForStatus)e)
{
case WaitForStatus.Green: return "green";
case WaitForStatus.Yellow: return "yellow";
case WaitForStatus.Red: return "red";
}
}
if (e is ExpandWildcards)
{
switch((ExpandWildcards)e)
{
case ExpandWildcards.Open: return "open";
case ExpandWildcards.Closed: return "closed";
case ExpandWildcards.None: return "none";
case ExpandWildcards.All: return "all";
}
}
if (e is DefaultOperator)
{
switch((DefaultOperator)e)
{
case DefaultOperator.And: return "AND";
case DefaultOperator.Or: return "OR";
}
}
if (e is VersionType)
{
switch((VersionType)e)
{
case VersionType.Internal: return "internal";
case VersionType.External: return "external";
case VersionType.ExternalGte: return "external_gte";
case VersionType.Force: return "force";
}
}
if (e is OpType)
{
switch((OpType)e)
{
case OpType.Index: return "index";
case OpType.Create: return "create";
}
}
if (e is Format)
{
switch((Format)e)
{
case Format.Detailed: return "detailed";
case Format.Text: return "text";
}
}
if (e is SearchType)
{
switch((SearchType)e)
{
case SearchType.QueryThenFetch: return "query_then_fetch";
case SearchType.QueryAndFetch: return "query_and_fetch";
case SearchType.DfsQueryThenFetch: return "dfs_query_then_fetch";
case SearchType.DfsQueryAndFetch: return "dfs_query_and_fetch";
case SearchType.Count: return "count";
case SearchType.Scan: return "scan";
}
}
if (e is ThreadType)
{
switch((ThreadType)e)
{
case ThreadType.Cpu: return "cpu";
case ThreadType.Wait: return "wait";
case ThreadType.Block: return "block";
}
}
if (e is PercolateFormat)
{
switch((PercolateFormat)e)
{
case PercolateFormat.Ids: return "ids";
}
}
if (e is SuggestMode)
{
switch((SuggestMode)e)
{
case SuggestMode.Missing: return "missing";
case SuggestMode.Popular: return "popular";
case SuggestMode.Always: return "always";
}
}
if (e is ClusterStateMetric)
{
var list = new List<string>();
if (e.HasFlag(ClusterStateMetric.Blocks)) list.Add("blocks");
if (e.HasFlag(ClusterStateMetric.Metadata)) list.Add("metadata");
if (e.HasFlag(ClusterStateMetric.Nodes)) list.Add("nodes");
if (e.HasFlag(ClusterStateMetric.RoutingTable)) list.Add("routing_table");
if (e.HasFlag(ClusterStateMetric.RoutingNodes)) list.Add("routing_nodes");
if (e.HasFlag(ClusterStateMetric.MasterNode)) list.Add("master_node");
if (e.HasFlag(ClusterStateMetric.Version)) list.Add("version");
if (e.HasFlag(ClusterStateMetric.All)) return "_all";
return string.Join(",", list);
}
if (e is Feature)
{
var list = new List<string>();
if (e.HasFlag(Feature.Settings)) list.Add("_settings");
if (e.HasFlag(Feature.Mappings)) list.Add("_mappings");
if (e.HasFlag(Feature.Warmers)) list.Add("_warmers");
if (e.HasFlag(Feature.Aliases)) list.Add("_aliases");
return string.Join(",", list);
}
if (e is IndicesStatsMetric)
{
var list = new List<string>();
if (e.HasFlag(IndicesStatsMetric.Completion)) list.Add("completion");
if (e.HasFlag(IndicesStatsMetric.Docs)) list.Add("docs");
if (e.HasFlag(IndicesStatsMetric.Fielddata)) list.Add("fielddata");
if (e.HasFlag(IndicesStatsMetric.QueryCache)) list.Add("query_cache");
if (e.HasFlag(IndicesStatsMetric.Flush)) list.Add("flush");
if (e.HasFlag(IndicesStatsMetric.Get)) list.Add("get");
if (e.HasFlag(IndicesStatsMetric.Indexing)) list.Add("indexing");
if (e.HasFlag(IndicesStatsMetric.Merge)) list.Add("merge");
if (e.HasFlag(IndicesStatsMetric.Percolate)) list.Add("percolate");
if (e.HasFlag(IndicesStatsMetric.RequestCache)) list.Add("request_cache");
if (e.HasFlag(IndicesStatsMetric.Refresh)) list.Add("refresh");
if (e.HasFlag(IndicesStatsMetric.Search)) list.Add("search");
if (e.HasFlag(IndicesStatsMetric.Segments)) list.Add("segments");
if (e.HasFlag(IndicesStatsMetric.Store)) list.Add("store");
if (e.HasFlag(IndicesStatsMetric.Warmer)) list.Add("warmer");
if (e.HasFlag(IndicesStatsMetric.Suggest)) list.Add("suggest");
if (e.HasFlag(IndicesStatsMetric.All)) return "_all";
return string.Join(",", list);
}
if (e is NodesInfoMetric)
{
var list = new List<string>();
if (e.HasFlag(NodesInfoMetric.Settings)) list.Add("settings");
if (e.HasFlag(NodesInfoMetric.Os)) list.Add("os");
if (e.HasFlag(NodesInfoMetric.Process)) list.Add("process");
if (e.HasFlag(NodesInfoMetric.Jvm)) list.Add("jvm");
if (e.HasFlag(NodesInfoMetric.ThreadPool)) list.Add("thread_pool");
if (e.HasFlag(NodesInfoMetric.Transport)) list.Add("transport");
if (e.HasFlag(NodesInfoMetric.Http)) list.Add("http");
if (e.HasFlag(NodesInfoMetric.Plugins)) list.Add("plugins");
return string.Join(",", list);
}
if (e is NodesStatsMetric)
{
var list = new List<string>();
if (e.HasFlag(NodesStatsMetric.Breaker)) list.Add("breaker");
if (e.HasFlag(NodesStatsMetric.Fs)) list.Add("fs");
if (e.HasFlag(NodesStatsMetric.Http)) list.Add("http");
if (e.HasFlag(NodesStatsMetric.Indices)) list.Add("indices");
if (e.HasFlag(NodesStatsMetric.Jvm)) list.Add("jvm");
if (e.HasFlag(NodesStatsMetric.Os)) list.Add("os");
if (e.HasFlag(NodesStatsMetric.Process)) list.Add("process");
if (e.HasFlag(NodesStatsMetric.ThreadPool)) list.Add("thread_pool");
if (e.HasFlag(NodesStatsMetric.Transport)) list.Add("transport");
if (e.HasFlag(NodesStatsMetric.All)) return "_all";
return string.Join(",", list);
}
if (e is NodesStatsIndexMetric)
{
var list = new List<string>();
if (e.HasFlag(NodesStatsIndexMetric.Completion)) list.Add("completion");
if (e.HasFlag(NodesStatsIndexMetric.Docs)) list.Add("docs");
if (e.HasFlag(NodesStatsIndexMetric.Fielddata)) list.Add("fielddata");
if (e.HasFlag(NodesStatsIndexMetric.QueryCache)) list.Add("query_cache");
if (e.HasFlag(NodesStatsIndexMetric.Flush)) list.Add("flush");
if (e.HasFlag(NodesStatsIndexMetric.Get)) list.Add("get");
if (e.HasFlag(NodesStatsIndexMetric.Indexing)) list.Add("indexing");
if (e.HasFlag(NodesStatsIndexMetric.Merge)) list.Add("merge");
if (e.HasFlag(NodesStatsIndexMetric.Percolate)) list.Add("percolate");
if (e.HasFlag(NodesStatsIndexMetric.RequestCache)) list.Add("request_cache");
if (e.HasFlag(NodesStatsIndexMetric.Refresh)) list.Add("refresh");
if (e.HasFlag(NodesStatsIndexMetric.Search)) list.Add("search");
if (e.HasFlag(NodesStatsIndexMetric.Segments)) list.Add("segments");
if (e.HasFlag(NodesStatsIndexMetric.Store)) list.Add("store");
if (e.HasFlag(NodesStatsIndexMetric.Warmer)) list.Add("warmer");
if (e.HasFlag(NodesStatsIndexMetric.Suggest)) list.Add("suggest");
if (e.HasFlag(NodesStatsIndexMetric.All)) return "_all";
return string.Join(",", list);
}
return UnknownEnum;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections;
using Mogre;
using System.Runtime.InteropServices;
using System.Xml.XPath;
using System.Xml;
using System.Xml.Serialization;
using System.Windows.Forms;
using System.IO;
namespace GameX
{
public class App
{
const int VERSION = 1000;
public class Param
{
public string Property { get; set; }
public string Value { get; set; }
public string Description { get; set; }
}
public static void ShowOgreException()
{
if (OgreException.IsThrown)
System.Windows.Forms.MessageBox.Show(OgreException.LastException.FullDescription,
"An exception has occured!", System.Windows.Forms.MessageBoxButtons.OK,
System.Windows.Forms.MessageBoxIcon.Error);
}
// settings
private bool DebugMode {
get { return true; }
}
private bool UseBufferedInput {
get { return true; }
}
// set to true - to lock the mouse automatically by MOIS
private bool AutoLockMouse
{
get { return false; }
}
private int emitterId = 0;
private int systemId = 0;
private float time = 0;
private ParticleSystem psystem = null;
private ParticleEmitter pemitter = null;
private ParticleAffector paffector = null;
private List<ParticleSystem> plist = new List<ParticleSystem>();
private bool running = true;
private Root root;
private Camera camera;
private Viewport viewport;
private SceneManager sceneMgr;
private RenderWindow window;
private MOIS.InputManager inputManager;
private MOIS.Keyboard inputKeyboard;
private MOIS.Mouse inputMouse;
private Overlay debugOverlay;
private String mDebugText = "";
private static IntPtr WindowHandle;
//Do NOT call root.Dispose at the finalizer thread because GL renderer requires that disposing of its objects is made
//in the same thread as the thread that created the GL renderer.
//~ExampleApplication()
//{
// if (root != null)
// {
// root.Dispose();
// root = null;
// }
//}
// custom imports
[DllImport("user32.dll")]
public static extern int ShowCursor(bool bShow);
[DllImport("user32.dll")]
public static extern bool SetCursorPos(int x, int y);
public struct RECT
{
public int Left; // x position of upper-left corner
public int Top; // y position of upper-left corner
public int Right; // x position of lower-right corner
public int Bottom; // y position of lower-right corner
}
[DllImport("user32.dll")]
public static extern bool GetWindowRect(HandleRef hwnd, out RECT lpRect);
public void Go()
{
// show toolbox
if (DebugMode){
(new Toolbox()).Show();
}
if (!Setup()) return;
root.StartRendering();
// clean up
DestroyScene();
root.Dispose();
root = null;
}
public void ShutDown(){
running = false;
}
private bool Setup()
{
root = new Root();
SetupResources();
bool carryOn = Configure(true);
if (!carryOn) return false;
ChooseSceneManager();
CreateCamera();
CreateViewports();
// Set default mipmap level (NB some APIs ignore this)
TextureManager.Singleton.DefaultNumMipmaps = 5;
// Create any resource listeners (for loading screens)
CreateResourceListener();
// Load resources
LoadResources();
// Create the scene
CreateScene();
CreateFrameListener();
CreateInput();
return true;
}
private bool Configure(bool trySkip)
{
if (trySkip)
{
if(root.RestoreConfig())
{
window = root.Initialise(true);
return true;
}
}
// Show the configuration dialog and initialise the system
// You can skip this and use root.restoreConfig() to load configuration
// settings if you were sure there are valid ones saved in ogre.cfg
if (root.ShowConfigDialog())
{
// If returned true, user clicked OK so initialise
// Here we choose to let the system create a default rendering window by passing 'true'
window = root.Initialise(true);
return true;
}
else
{
return false;
}
}
private void ChooseSceneManager()
{
// Get the SceneManager, in this case a generic one
sceneMgr = root.CreateSceneManager(SceneType.ST_GENERIC, "SceneMgr");
}
private void CreateCamera()
{
// Create the camera
camera = sceneMgr.CreateCamera("PlayerCam");
SceneNode node = sceneMgr.RootSceneNode.CreateChildSceneNode("camNode");
node.AttachObject(camera);
// Position it at 500 in Z direction
camera.Position = new Vector3(0, 10, 20);
camera.FOVy = (new Degree(60)).ValueRadians;
// Look back along -Z
camera.LookAt(new Vector3(0, 0, -10));
camera.NearClipDistance = 0.1f; // see nearer
camera.FarClipDistance = 2000;
}
private void CreateFrameListener()
{
debugOverlay = OverlayManager.Singleton.GetByName("Core/DebugOverlay");
debugOverlay.Show();
root.FrameStarted += new FrameListener.FrameStartedHandler(Update);
}
private bool Update(FrameEvent evt)
{
if (window.IsClosed || !running)
return false;
time += evt.timeSinceLastFrame;
inputKeyboard.Capture();
UpdateStats();
return running;
}
private bool KeyPressed(MOIS.KeyEvent arg)
{
// stop
if(arg.key == MOIS.KeyCode.KC_ESCAPE){
running = false;
}
return true;
}
private bool KeyReleased(MOIS.KeyEvent arg)
{
return true;
}
private bool MouseMoved(MOIS.MouseEvent arg)
{
return true;
}
private bool MousePressed(MOIS.MouseEvent arg, MOIS.MouseButtonID id)
{
return true;
}
private bool MouseReleased(MOIS.MouseEvent arg, MOIS.MouseButtonID id)
{
return true;
}
public void TakeScreenshot()
{
string[] temp = System.IO.Directory.GetFiles(Environment.CurrentDirectory, "screenshot*.jpg");
string fileName = string.Format("screenshot{0}.jpg", temp.Length + 1);
window.WriteContentsToFile(fileName);
}
private void UpdateStats()
{
string currFps = "Current FPS: ";
string avgFps = "Average FPS: ";
string bestFps = "Best FPS: ";
string worstFps = "Worst FPS: ";
string tris = "Triangle Count: ";
// update stats when necessary
try
{
OverlayElement guiAvg = OverlayManager.Singleton.GetOverlayElement("Core/AverageFps");
OverlayElement guiCurr = OverlayManager.Singleton.GetOverlayElement("Core/CurrFps");
OverlayElement guiBest = OverlayManager.Singleton.GetOverlayElement("Core/BestFps");
OverlayElement guiWorst = OverlayManager.Singleton.GetOverlayElement("Core/WorstFps");
RenderTarget.FrameStats stats = window.GetStatistics();
guiAvg.Caption = avgFps + stats.AvgFPS;
guiCurr.Caption = currFps + stats.LastFPS;
guiBest.Caption = bestFps + stats.BestFPS + " " + stats.BestFrameTime + " ms";
guiWorst.Caption = worstFps + stats.WorstFPS + " " + stats.WorstFrameTime + " ms";
OverlayElement guiTris = OverlayManager.Singleton.GetOverlayElement("Core/NumTris");
guiTris.Caption = tris + stats.TriangleCount;
OverlayElement guiDbg = OverlayManager.Singleton.GetOverlayElement("Core/DebugText");
guiDbg.Caption = mDebugText;
}
catch
{
// ignore
}
}
////////////////////////////////////////////////////////
public void xSelectSystem(ParticleSystem s)
{
psystem = s;
}
public void xSelectSystem(String name)
{
psystem = xGetSystemByName(name);
}
public ParticleSystem xAddParticleSystem()
{
// fetch unique name
while (sceneMgr.HasParticleSystem("System" + systemId)) {
systemId++;
}
return xAddParticleSystem("System" + systemId++);
}
public ParticleSystem xAddParticleSystem(string name)
{
ParticleSystem ps = sceneMgr.CreateParticleSystem(name);
sceneMgr.RootSceneNode.CreateChildSceneNode(ps.Name).AttachObject(ps);
ps.SetMaterialName("ParticleDefault");
ps.SetDefaultDimensions(1, 1);
plist.Add(ps);
return ps;
}
public ParticleSystem xGetCurrentSystem(){
return psystem;
}
public ParticleEmitter xGetCurrentEmitter()
{
return pemitter;
}
public ParticleAffector xGetCurrentAffector()
{
return paffector;
}
public ParticleSystem xGetSystemByName(String name)
{
for (int i = 0; i < plist.Count; i++)
{
if (plist[i].Name == name)
{
return plist[i];
}
}
return null;
}
public void xResetCurrSystem()
{
}
public string[] xGetSystemNames()
{
string[] names = new string[plist.Count];
for(int i=0; i<plist.Count; i++)
{
ParticleSystem p = plist[i];
names[i] = p.Name;
}
return names;
}
public string[] xGetEmitterNames()
{
if (psystem == null) return null;
string[] names = new string[psystem.NumEmitters];
for (int i = 0; i < psystem.NumEmitters; i++)
{
ParticleEmitter pe = psystem.GetEmitter((ushort)i);
names[i] = pe.Name;
}
return names;
}
public string[] xGetEmitterTypes()
{
List<string> names = new List<string>();
try{
XPathDocument doc = new XPathDocument("../media/materials/emitters.xml");
XPathNavigator xp = doc.CreateNavigator();
XPathNodeIterator it = xp.Select("//@emitter");
while(it.MoveNext()){
names.Add(it.Current.Value);
}
}catch(Exception err){
Console.WriteLine("Error reading emitters.xml: " + err);
}
return names.ToArray();
}
public Dictionary<string, string> xGetDefEmitterParams(string emitterType){
Dictionary<string, string> par = new Dictionary<string, string>();
try
{
XPathDocument doc = new XPathDocument("../media/materials/emitters.xml");
XPathNavigator xp = doc.CreateNavigator();
string xpath = String.Format("//add[@emitter='{0}']/param", emitterType);
XPathNodeIterator it = xp.Select(xpath);
while (it.MoveNext())
{
string name = it.Current.GetAttribute("name", "");
string defval = it.Current.GetAttribute("default", "");
par.Add(name, defval);
}
}
catch (Exception err)
{
Console.WriteLine("Error reading emitters.xml: " + err);
}
return par;
}
public List<Param> xGetExtraEmitterParams(ParticleEmitter pe)
{
List<Param> list = new List<Param>();
if (pe == null) return list;
// the default
Dictionary<string, string> def = xGetDefEmitterParams(pe.Type);
//////////////////////////////////////////////////////////////////////////
Const_ParameterList plist = pe.GetParameters();
foreach (ParameterDef_NativePtr c in plist)
{
// dont include base emitter properties!
if (def.ContainsKey(c.name) == false) continue;
string value = pe.GetParameter(c.name);
list.Add(new Param() { Property = c.name, Value = value, Description = c.description });
}
return list;
}
public List<Param> xGetExtraAffectorParams(ParticleAffector af)
{
List<Param> list = new List<Param>();
if (af == null) return list;
// the default
//Dictionary<string, string> def = xGetDefEmitterParams(pe.Type);
//////////////////////////////////////////////////////////////////////////
Const_ParameterList plist = af.GetParameters();
foreach (ParameterDef_NativePtr c in plist)
{
// dont include base emitter properties!
//if (def.ContainsKey(c.name) == false) continue;
string value = af.GetParameter(c.name);
list.Add(new Param() { Property = c.name, Value = value, Description = c.description });
}
return list;
}
public string[] xGetBillboardTypes()
{
List<string> names = new List<string>();
try
{
XPathDocument doc = new XPathDocument("../media/materials/billboards.xml");
XPathNavigator xp = doc.CreateNavigator();
XPathNodeIterator it = xp.Select("//@name");
while (it.MoveNext())
{
names.Add(it.Current.Value);
}
}
catch (Exception e)
{
Console.WriteLine("Error reading billboards.xml: " + e);
}
return names.ToArray();
}
public string[] xGetParticleMaterials()
{
List<string> names = new List<string>();
try
{
XPathDocument doc = new XPathDocument("../media/materials/mats.xml");
XPathNavigator xp = doc.CreateNavigator();
XPathNodeIterator it = xp.Select("//@name");
while (it.MoveNext())
{
names.Add(it.Current.Value);
}
}
catch(Exception e)
{
Console.WriteLine("Error reading mats.xml: " + e);
}
return names.ToArray();
}
public string[] xGetAffectorTypes()
{
List<string> names = new List<string>();
try
{
XPathDocument doc = new XPathDocument("../media/materials/affectors.xml");
XPathNavigator xp = doc.CreateNavigator();
XPathNodeIterator it = xp.Select("//@name");
while (it.MoveNext())
{
names.Add(it.Current.Value);
}
}
catch (Exception e)
{
Console.WriteLine("Error reading affectors.xml: " + e);
}
return names.ToArray();
}
public void xRemoveEmitterModels(string name)
{
try
{
SceneNode node = sceneMgr.GetSceneNode(name);
node.DetachAllObjects();
sceneMgr.DestroySceneNode(node);
sceneMgr.DestroyManualObject(name); // destroy dummy model
}
catch(Exception err)
{
MessageBox.Show("Error: "+err);
}
}
public void xRemoveSystem(ParticleSystem ps)
{
if (ps == null) return;
if(psystem == ps){
// destroy emitter model data
for(int i=0; i<ps.NumEmitters; i++){
xRemoveEmitterModels(ps.GetEmitter((ushort)i).Name);
}
// free model data
SceneNode node = sceneMgr.GetSceneNode(ps.Name);
node.DetachAllObjects();
sceneMgr.DestroySceneNode(node);
sceneMgr.DestroyParticleSystem(ps);
}
plist.Remove(ps);
}
public ParticleEmitter xAddTypedEmitter(string type, Dictionary<string, string> defParams)
{
ParticleEmitter em = null;
try
{
em = psystem.AddEmitter(type);
em.Name = "Emitter" + emitterId++ + ":"+type;
em.SetColour(new ColourValue(1, 1, 1, 1), new ColourValue(1, 1, 1, 0));
em.SetDuration(5, 10);
em.SetEmitted(false);
em.SetParticleVelocity(1, 2);
em.SetRepeatDelay(0, 0.1f);
em.SetTimeToLive(0, 10);
em.Position = new Vector3(0, 3, 0);
em.Direction = new Vector3(0, 1, 0);
em.Angle = (new Degree(30)).ValueRadians;
em.EmissionRate = 100;
em.StartTime = 0;
// apply params
if (defParams != null)
{
foreach (KeyValuePair<string, string> p in defParams)
{
em.SetParameter(p.Key, p.Value);
}
}
// create dummy
MovableObject dummy = Utils.MakeDummy(sceneMgr, em.Name, "Dummy", 1);
SceneNode node = sceneMgr.RootSceneNode.CreateChildSceneNode(em.Name);
node.AttachObject(dummy);
node.Position = em.Position;
}catch(Exception err){
MessageBox.Show("Error: Invalid emitter settings" + err);
}
return em;
}
public ParticleEmitter xGetEmitterByName(String name)
{
for (int i = 0; i < psystem.NumEmitters; i++)
{
ParticleEmitter pe = psystem.GetEmitter((ushort)i);
if (pe.Name == name)
{
return pe;
}
}
return null;
}
public void xSelectEmitter(ParticleEmitter e)
{
pemitter = e;
}
public void xSelectEmitter(String name)
{
pemitter = xGetEmitterByName(name);
}
public void xSelectAffector(ParticleAffector af)
{
paffector = af;
}
public void xUpdateEmitter(ParticleEmitter pe){
if (pe == null) return;
// update dummy model
if (pemitter != null)
{
SceneNode node = sceneMgr.GetSceneNode(pemitter.Name);
node.Position = pe.Position;
}
}
public float xGetSystemTime(){
return (float)time;
}
public void xRotateCamera(float amount)
{
Radian r = (new Degree(amount)).ValueRadians;
SceneNode node = sceneMgr.GetSceneNode("camNode");
node.Yaw(r, Node.TransformSpace.TS_WORLD);
}
public void xZoomCamera(float fovangle)
{
Radian r = (new Degree(fovangle)).ValueRadians;
camera.FOVy = r;
}
// show/hide skybox
public void xToggleSkybox(bool state)
{
if (state == false)
{
sceneMgr.SetSkyBox(false, "");
}
else
{
sceneMgr.SetSkyBox(true, "SimpleSky", 1000);
}
}
// show/hide emitter octahedron models
public void xToggleEmitterModel(bool state)
{
foreach(ParticleSystem p in plist)
{
for(int i=0; i<p.NumEmitters; i++){
ParticleEmitter em = p.GetEmitter((ushort)i);
SceneNode node = sceneMgr.GetSceneNode(em.Name);
if(node != null){
node.SetVisible(state);
}
}
}
}
public ParticleAffector xAddAffector(string type)
{
ParticleSystem ps = xGetCurrentSystem();
if(ps == null) return null;
return ps.AddAffector(type);
}
// export ogre particle script
public void xExportScript(string filename)
{
StreamWriter fp = null;
try
{
fp = File.CreateText(filename);
}
catch (Exception err)
{
MessageBox.Show("Error: " + err.Message);
return;
}
for (int i = 0; i < plist.Count; i++ )
{
ParticleSystem ps = plist[i];
fp.WriteLine("particle_system {0}", ps.Name);
fp.WriteLine("{");
fp.WriteLine("\tmaterial {0}", ps.MaterialName);
fp.WriteLine("\tparticle_width {0}", ps.DefaultWidth);
fp.WriteLine("\tparticle_height {0}", ps.DefaultHeight);
fp.WriteLine("\tcull_each {0}", ps.CullIndividually);
fp.WriteLine("\tquota {0}", ps.ParticleQuota);
fp.WriteLine("\tsorted {0}", ps.SortingEnabled);
fp.WriteLine("\tbillboard_type {0}", ps.Renderer.GetParameter("billboard_type"));
fp.WriteLine("\tcommon_direction {0}", ps.Renderer.GetParameter("common_direction"));
fp.WriteLine("\tcommon_up_vector {0}", ps.Renderer.GetParameter("common_up_vector"));
fp.WriteLine();
// emitters
for (int j = 0; j < ps.NumEmitters; j++ )
{
ParticleEmitter pe = ps.GetEmitter((ushort)j);
fp.WriteLine("\temitter {0}", pe.Type);
fp.WriteLine("\t{");
foreach (ParameterDef_NativePtr param in pe.GetParameters())
{
string value = pe.GetParameter(param.name);
if (value == "") continue; // no empty
if (param.name == "name") continue;
fp.WriteLine("\t\t{0} {1}", param.name, value);
}
fp.WriteLine("\t}");
fp.WriteLine();
}
// affectors
for (int j = 0; j < ps.NumAffectors; j++)
{
ParticleAffector af = ps.GetAffector((ushort)j);
fp.WriteLine("\taffector {0}", af.Type);
fp.WriteLine("\t{");
foreach (ParameterDef_NativePtr param in af.GetParameters())
{
string value = af.GetParameter(param.name);
fp.WriteLine("\t\t{0} {1}", param.name, value);
}
fp.WriteLine("\t}");
fp.WriteLine();
}
fp.WriteLine("}");
fp.WriteLine();
}
fp.Close();
}
// clear existing particle systems
public void xClearEverything()
{
while (plist.Count > 0)
{
this.xRemoveSystem(plist[0]);
//plist.RemoveAt(0); // not needed handles in xRemoveSystem()
}
sceneMgr.DestroyAllParticleSystems(); // just to make sure all is clear
psystem = null;
pemitter = null;
paffector = null;
}
// save flow file
public void xSaveConfinguration(string filename)
{
XmlTextWriter xml = null;
try
{
xml = new XmlTextWriter(filename, null);
}
catch(Exception err)
{
MessageBox.Show("Error: " + err.Message);
return;
}
xml.Formatting = Formatting.Indented; // tabs & newlines
xml.WriteStartDocument();
{
xml.WriteStartElement("config");
xml.WriteStartAttribute("version");
xml.WriteValue(1000);
xml.WriteEndAttribute();
for(int i=0; i<plist.Count; i++)
{
ParticleSystem p = plist[i];
xml.WriteStartElement("system");
xml.WriteStartAttribute("name");
xml.WriteValue(p.Name);
xml.WriteEndAttribute();
xml.WriteStartElement("params");
foreach (ParameterDef_NativePtr param in p.GetParameters())
{
xml.WriteStartElement("add");
xml.WriteStartAttribute("key");
xml.WriteValue(param.name);
xml.WriteEndAttribute();
xml.WriteStartAttribute("value");
xml.WriteValue(p.GetParameter(param.name));
xml.WriteEndAttribute();
xml.WriteEndElement();
}
// billboard type
xml.WriteStartElement("add");
xml.WriteStartAttribute("key");
xml.WriteValue("billboard_type");
xml.WriteEndAttribute();
xml.WriteStartAttribute("value");
xml.WriteValue(p.Renderer.GetParameter("billboard_type"));
xml.WriteEndAttribute();
xml.WriteEndElement();
// common dir
xml.WriteStartElement("add");
xml.WriteStartAttribute("key");
xml.WriteValue("common_direction");
xml.WriteEndAttribute();
xml.WriteStartAttribute("value");
xml.WriteValue(p.Renderer.GetParameter("common_direction"));
xml.WriteEndAttribute();
xml.WriteEndElement();
xml.WriteEndElement();
// affectors
for (int j = 0; j < p.NumAffectors; j++ )
{
ParticleAffector af = p.GetAffector((ushort)j);
xml.WriteStartElement("affector");
xml.WriteStartAttribute("type");
xml.WriteValue(af.Type);
xml.WriteEndAttribute();
xml.WriteStartAttribute("name");
xml.WriteValue("Affector"+j);
xml.WriteEndAttribute();
{
xml.WriteStartElement("params");
foreach (ParameterDef_NativePtr param in af.GetParameters())
{
xml.WriteStartElement("add");
xml.WriteStartAttribute("key");
xml.WriteValue(param.name);
xml.WriteEndAttribute();
xml.WriteStartAttribute("value");
xml.WriteValue(af.GetParameter(param.name));
xml.WriteEndAttribute();
xml.WriteEndElement();
}
xml.WriteEndElement();
}
xml.WriteEndElement();
}
// emitters
for (int j = 0; j < p.NumEmitters; j++)
{
ParticleEmitter em = p.GetEmitter((ushort)j);
xml.WriteStartElement("emitter");
xml.WriteStartAttribute("type");
xml.WriteValue(em.Type);
xml.WriteEndAttribute();
xml.WriteStartAttribute("name");
xml.WriteValue("Emitter" + j);
xml.WriteEndAttribute();
{
xml.WriteStartElement("params");
foreach (ParameterDef_NativePtr param in em.GetParameters())
{
xml.WriteStartElement("add");
xml.WriteStartAttribute("key");
xml.WriteValue(param.name);
xml.WriteEndAttribute();
xml.WriteStartAttribute("value");
xml.WriteValue(em.GetParameter(param.name));
xml.WriteEndAttribute();
xml.WriteEndElement();
}
xml.WriteEndElement();
}
xml.WriteEndElement();
}
xml.WriteEndElement(); // </system>
}
xml.WriteEndElement();//</config>
}
xml.WriteEndDocument();
xml.Close();
}
// load flow file
public void xLoadConfinguration(string filename)
{
this.xClearEverything();
XPathDocument doc = null;
try
{
doc = new XPathDocument(filename);
}
catch (Exception err)
{
MessageBox.Show("Error: " + err.Message);
return;
}
XPathNavigator nav = doc.CreateNavigator();
try
{
XPathNodeIterator it = nav.Select("/config");
it.MoveNext();
string version = it.Current.GetAttribute("version", "");
// get all systems
XPathNodeIterator sysnames = nav.Select("//system/@name");
while (sysnames.MoveNext())
{
string sysName = sysnames.Current.Value;
ParticleSystem ps = this.xAddParticleSystem(sysName);
this.xSelectSystem(ps);
// get system params
string path = String.Format("//system[@name='{0}']/params/add", sysName);
XPathNodeIterator param = nav.Select(path);
while(param.MoveNext())
{
string pName = param.Current.GetAttribute("key","");
string pValue = param.Current.GetAttribute("value","");
ps.SetParameter(pName, pValue);
}
// create affectors
string affpath = String.Format("//system[@name='{0}']/affector", sysName);
XPathNodeIterator affit = nav.Select(affpath);
while(affit.MoveNext())
{
string af_type = affit.Current.GetAttribute("type", "");
string af_name = affit.Current.GetAttribute("name", "");
ParticleAffector af = this.xAddAffector(af_type);
string affparam = String.Format(
"//system[@name='{0}']/affector[@name='{1}']/params/add",
sysName, af_name);
XPathNodeIterator pit = nav.Select(affparam);
while(pit.MoveNext())
{
string pName = pit.Current.GetAttribute("key","");
string pValue = pit.Current.GetAttribute("value","");
af.SetParameter(pName, pValue);
}
}
// create emitters
string empath = String.Format("//system[@name='{0}']/emitter", sysName);
XPathNodeIterator emit = nav.Select(empath);
while (emit.MoveNext())
{
string em_type = emit.Current.GetAttribute("type", "");
string em_name = emit.Current.GetAttribute("name", "");
ParticleEmitter em = this.xAddTypedEmitter(em_type,
this.xGetDefEmitterParams(em_type));
string emparam = String.Format(
"//system[@name='{0}']/emitter[@name='{1}']/params/add",
sysName, em_name);
XPathNodeIterator pit = nav.Select(emparam);
while (pit.MoveNext())
{
string pName = pit.Current.GetAttribute("key", "");
if (pName == "name") continue; // do not overwrite name!
string pValue = pit.Current.GetAttribute("value", "");
em.SetParameter(pName, pValue);
}
}
}
}
catch(Exception err)
{
MessageBox.Show("Error: " + err);
}
// select first
if(plist.Count>0)
{
this.xSelectSystem(plist[0]);
if(plist[0] != null && plist[0].NumEmitters>0){
this.xSelectEmitter(plist[0].GetEmitter(0));
}
}
}
////////////////////////////////////////////////////////
private void CreateScene()
{
window.SetDeactivateOnFocusChange(false);
// load all data here!
this.xToggleSkybox(true);
//Light sun = sceneMgr.CreateLight();
//sun.Type = Light.LightTypes.LT_DIRECTIONAL;
//sun.Direction = (new Vector3(-1, -1, 0)).NormalisedCopy;
//sun.SetDiffuseColour(1, 1, 1);
// example plane
const float MAP_SZ = 100;
Entity plane = Utils.MakePlane(sceneMgr, MAP_SZ, 20);
plane.SetMaterialName("PlaneGround");
sceneMgr.RootSceneNode.AttachObject(plane);
//sceneMgr.ShowBoundingBoxes = true;
}
private void DestroyScene()
{
}
private void CreateInput()
{
LogManager.Singleton.LogMessage("*** Initializing OIS ***");
MOIS.ParamList pl = new MOIS.ParamList();
if (AutoLockMouse == false)
{
pl.Insert("w32_mouse", "DISCL_FOREGROUND");
pl.Insert("w32_mouse", "DISCL_NONEXCLUSIVE");
}
window.GetCustomAttribute("WINDOW", out WindowHandle);
pl.Insert("WINDOW", WindowHandle.ToString());
inputManager = MOIS.InputManager.CreateInputSystem(pl);
//Create all devices (We only catch joystick exceptions here, as, most people have Key/Mouse)
inputKeyboard = (MOIS.Keyboard)inputManager.CreateInputObject(MOIS.Type.OISKeyboard, UseBufferedInput);
inputMouse = (MOIS.Mouse)inputManager.CreateInputObject(MOIS.Type.OISMouse, UseBufferedInput);
if (inputKeyboard != null)
{
LogManager.Singleton.LogMessage("Setting up keyboard listeners");
inputKeyboard.KeyPressed += new MOIS.KeyListener.KeyPressedHandler(KeyPressed);
inputKeyboard.KeyReleased += new MOIS.KeyListener.KeyReleasedHandler(KeyReleased);
}
if (inputMouse != null)
{
LogManager.Singleton.LogMessage("Setting up mouse listeners");
inputMouse.MousePressed += new MOIS.MouseListener.MousePressedHandler(MousePressed);
inputMouse.MouseReleased += new MOIS.MouseListener.MouseReleasedHandler(MouseReleased);
inputMouse.MouseMoved += new MOIS.MouseListener.MouseMovedHandler(MouseMoved);
}
}
private void CreateViewports()
{
// Create one viewport, entire window
viewport = window.AddViewport(camera);
viewport.BackgroundColour = new ColourValue(0, 0, 0);
// Alter the camera aspect ratio to match the viewport
camera.AspectRatio = ((float)viewport.ActualWidth) / ((float)viewport.ActualHeight);
}
/// Method which will define the source of resources (other than current folder)
private void SetupResources()
{
// Load resource paths from config file
ConfigFile cf = new ConfigFile();
cf.Load("../resources.cfg", "\t:=", true);
// Go through all sections & settings in the file
ConfigFile.SectionIterator seci = cf.GetSectionIterator();
String secName, typeName, archName;
// Normally we would use the foreach syntax, which enumerates the values, but in this case we need CurrentKey too;
while (seci.MoveNext())
{
secName = seci.CurrentKey;
ConfigFile.SettingsMultiMap settings = seci.Current;
foreach (KeyValuePair<string, string> pair in settings)
{
typeName = pair.Key;
archName = pair.Value;
ResourceGroupManager.Singleton.AddResourceLocation(archName, typeName, secName);
}
}
}
/// Optional override method where you can create resource listeners (e.g. for loading screens)
private void CreateResourceListener()
{
}
/// Optional override method where you can perform resource group loading
/// Must at least do ResourceGroupManager.Singleton.InitialiseAllResourceGroups();
private void LoadResources()
{
// Initialise, parse scripts etc
ResourceGroupManager.Singleton.InitialiseAllResourceGroups();
}
public static App Singleton { get; set; }
[STAThread]
public static void Main(){
Singleton = new App();
Singleton.Go();
}
}
}
| |
using System;
using System.Collections;
using NUnit.Framework;
using Org.BouncyCastle.Asn1;
using Org.BouncyCastle.Asn1.Cms;
using Org.BouncyCastle.Asn1.Pkcs;
using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.Security;
using Org.BouncyCastle.Utilities;
using Org.BouncyCastle.Utilities.Encoders;
using Org.BouncyCastle.Utilities.IO;
using Org.BouncyCastle.Utilities.Test;
using Org.BouncyCastle.X509;
using Org.BouncyCastle.X509.Store;
namespace Org.BouncyCastle.Cms.Tests
{
[TestFixture]
public class Rfc4134Test
{
private static readonly byte[] exContent = GetRfc4134Data("ExContent.bin");
private static readonly byte[] sha1 = Hex.Decode("406aec085279ba6e16022d9e0629c0229687dd48");
[Test]
public void Test4_1()
{
byte[] data = GetRfc4134Data("4.1.bin");
CmsSignedData signedData = new CmsSignedData(data);
VerifySignatures(signedData);
CmsSignedDataParser parser = new CmsSignedDataParser(data);
VerifySignatures(parser);
}
[Test]
public void Test4_2()
{
byte[] data = GetRfc4134Data("4.2.bin");
CmsSignedData signedData = new CmsSignedData(data);
VerifySignatures(signedData);
CmsSignedDataParser parser = new CmsSignedDataParser(data);
VerifySignatures(parser);
}
[Test]
public void Test4_3()
{
CmsProcessableByteArray unencap = new CmsProcessableByteArray(exContent);
byte[] data = GetRfc4134Data("4.3.bin");
CmsSignedData signedData = new CmsSignedData(unencap, data);
VerifySignatures(signedData, sha1);
CmsSignedDataParser parser = new CmsSignedDataParser(
new CmsTypedStream(unencap.GetInputStream()), data);
VerifySignatures(parser);
}
[Test]
public void Test4_4()
{
byte[] data = GetRfc4134Data("4.4.bin");
byte[] counterSigCert = GetRfc4134Data("AliceRSASignByCarl.cer");
CmsSignedData signedData = new CmsSignedData(data);
VerifySignatures(signedData, sha1);
VerifySignerInfo4_4(GetFirstSignerInfo(signedData.GetSignerInfos()), counterSigCert);
CmsSignedDataParser parser = new CmsSignedDataParser(data);
VerifySignatures(parser);
VerifySignerInfo4_4(GetFirstSignerInfo(parser.GetSignerInfos()), counterSigCert);
}
[Test]
public void Test4_5()
{
byte[] data = GetRfc4134Data("4.5.bin");
CmsSignedData signedData = new CmsSignedData(data);
VerifySignatures(signedData);
CmsSignedDataParser parser = new CmsSignedDataParser(data);
VerifySignatures(parser);
}
[Test]
public void Test4_6()
{
byte[] data = GetRfc4134Data("4.6.bin");
CmsSignedData signedData = new CmsSignedData(data);
VerifySignatures(signedData);
CmsSignedDataParser parser = new CmsSignedDataParser(data);
VerifySignatures(parser);
}
[Test]
public void Test4_7()
{
byte[] data = GetRfc4134Data("4.7.bin");
CmsSignedData signedData = new CmsSignedData(data);
VerifySignatures(signedData);
CmsSignedDataParser parser = new CmsSignedDataParser(data);
VerifySignatures(parser);
}
[Test]
public void Test5_1()
{
byte[] data = GetRfc4134Data("5.1.bin");
CmsEnvelopedData envelopedData = new CmsEnvelopedData(data);
VerifyEnvelopedData(envelopedData, CmsEnvelopedDataGenerator.DesEde3Cbc);
CmsEnvelopedDataParser envelopedParser = new CmsEnvelopedDataParser(data);
VerifyEnvelopedData(envelopedParser, CmsEnvelopedDataGenerator.DesEde3Cbc);
}
[Test]
public void Test5_2()
{
byte[] data = GetRfc4134Data("5.2.bin");
CmsEnvelopedData envelopedData = new CmsEnvelopedData(data);
VerifyEnvelopedData(envelopedData, CmsEnvelopedDataGenerator.RC2Cbc);
CmsEnvelopedDataParser envelopedParser = new CmsEnvelopedDataParser(data);
VerifyEnvelopedData(envelopedParser, CmsEnvelopedDataGenerator.RC2Cbc);
}
private void VerifyEnvelopedData(CmsEnvelopedData envelopedData, string symAlgorithmOID)
{
byte[] privKeyData = GetRfc4134Data("BobPrivRSAEncrypt.pri");
IAsymmetricKeyParameter privKey = PrivateKeyFactory.CreateKey(privKeyData);
Assert.IsTrue(privKey.IsPrivate);
Assert.IsTrue(privKey is RsaKeyParameters);
RecipientInformationStore recipients = envelopedData.GetRecipientInfos();
Assert.AreEqual(envelopedData.EncryptionAlgOid, symAlgorithmOID);
ArrayList c = new ArrayList(recipients.GetRecipients());
Assert.LessOrEqual(1, c.Count);
Assert.GreaterOrEqual(2, c.Count);
VerifyRecipient((RecipientInformation)c[0], privKey);
if (c.Count == 2)
{
RecipientInformation recInfo = (RecipientInformation)c[1];
Assert.AreEqual(PkcsObjectIdentifiers.IdAlgCmsRC2Wrap.Id, recInfo.KeyEncryptionAlgOid);
}
}
private void VerifyEnvelopedData(CmsEnvelopedDataParser envelopedParser, string symAlgorithmOID)
{
byte[] privKeyData = GetRfc4134Data("BobPrivRSAEncrypt.pri");
IAsymmetricKeyParameter privKey = PrivateKeyFactory.CreateKey(privKeyData);
Assert.IsTrue(privKey.IsPrivate);
Assert.IsTrue(privKey is RsaKeyParameters);
RecipientInformationStore recipients = envelopedParser.GetRecipientInfos();
Assert.AreEqual(envelopedParser.EncryptionAlgOid, symAlgorithmOID);
ArrayList c = new ArrayList(recipients.GetRecipients());
Assert.LessOrEqual(1, c.Count);
Assert.GreaterOrEqual(2, c.Count);
VerifyRecipient((RecipientInformation)c[0], privKey);
if (c.Count == 2)
{
RecipientInformation recInfo = (RecipientInformation)c[1];
Assert.AreEqual(PkcsObjectIdentifiers.IdAlgCmsRC2Wrap.Id, recInfo.KeyEncryptionAlgOid);
}
}
private void VerifyRecipient(RecipientInformation recipient, IAsymmetricKeyParameter privKey)
{
Assert.IsTrue(privKey.IsPrivate);
Assert.AreEqual(recipient.KeyEncryptionAlgOid, PkcsObjectIdentifiers.RsaEncryption.Id);
byte[] recData = recipient.GetContent(privKey);
Assert.IsTrue(Arrays.AreEqual(exContent, recData));
}
private void VerifySignerInfo4_4(SignerInformation signerInfo, byte[] counterSigCert)
{
VerifyCounterSignature(signerInfo, counterSigCert);
VerifyContentHint(signerInfo);
}
private SignerInformation GetFirstSignerInfo(SignerInformationStore store)
{
IEnumerator e = store.GetSigners().GetEnumerator();
e.MoveNext();
return (SignerInformation)e.Current;
}
private void VerifyCounterSignature(SignerInformation signInfo, byte[] certificate)
{
SignerInformation csi = GetFirstSignerInfo(signInfo.GetCounterSignatures());
X509Certificate cert = new X509CertificateParser().ReadCertificate(certificate);
Assert.IsTrue(csi.Verify(cert));
}
private void VerifyContentHint(SignerInformation signInfo)
{
Asn1.Cms.AttributeTable attrTable = signInfo.UnsignedAttributes;
Asn1.Cms.Attribute attr = attrTable[CmsAttributes.ContentHint];
Assert.AreEqual(1, attr.AttrValues.Count);
Asn1EncodableVector v = new Asn1EncodableVector(
new DerUtf8String("Content Hints Description Buffer"),
CmsObjectIdentifiers.Data);
Assert.IsTrue(attr.AttrValues[0].Equals(new DerSequence(v)));
}
private void VerifySignatures(CmsSignedData s, byte[] contentDigest)
{
IX509Store x509Certs = s.GetCertificates("Collection");
IX509Store x509Crls = s.GetCrls("Collection");
SignerInformationStore signers = s.GetSignerInfos();
foreach (SignerInformation signer in signers.GetSigners())
{
ICollection certCollection = x509Certs.GetMatches(signer.SignerID);
IEnumerator certEnum = certCollection.GetEnumerator();
certEnum.MoveNext();
X509Certificate cert = (X509Certificate) certEnum.Current;
VerifySigner(signer, cert);
if (contentDigest != null)
{
Assert.IsTrue(Arrays.AreEqual(contentDigest, signer.GetContentDigest()));
}
}
ICollection certColl = x509Certs.GetMatches(null);
ICollection crlColl = x509Crls.GetMatches(null);
Assert.AreEqual(certColl.Count, s.GetCertificates("Collection").GetMatches(null).Count);
Assert.AreEqual(crlColl.Count, s.GetCrls("Collection").GetMatches(null).Count);
}
private void VerifySignatures(CmsSignedData s)
{
VerifySignatures(s, null);
}
private void VerifySignatures(CmsSignedDataParser sp)
{
CmsTypedStream sc = sp.GetSignedContent();
if (sc != null)
{
sc.Drain();
}
IX509Store x509Certs = sp.GetCertificates("Collection");
SignerInformationStore signers = sp.GetSignerInfos();
foreach (SignerInformation signer in signers.GetSigners())
{
ICollection certCollection = x509Certs.GetMatches(signer.SignerID);
IEnumerator certEnum = certCollection.GetEnumerator();
certEnum.MoveNext();
X509Certificate cert = (X509Certificate)certEnum.Current;
VerifySigner(signer, cert);
}
}
private void VerifySigner(SignerInformation signer, X509Certificate cert)
{
if (cert.GetPublicKey() is DsaPublicKeyParameters)
{
DsaPublicKeyParameters key = (DsaPublicKeyParameters)cert.GetPublicKey();
if (key.Parameters == null)
{
Assert.IsTrue(signer.Verify(GetInheritedKey(key)));
}
else
{
Assert.IsTrue(signer.Verify(cert));
}
}
else
{
Assert.IsTrue(signer.Verify(cert));
}
}
private DsaPublicKeyParameters GetInheritedKey(DsaPublicKeyParameters dsaPubKey)
{
X509Certificate cert = new X509CertificateParser().ReadCertificate(
GetRfc4134Data("CarlDSSSelf.cer"));
DsaParameters dsaParams = ((DsaPublicKeyParameters)cert.GetPublicKey()).Parameters;
return new DsaPublicKeyParameters(dsaPubKey.Y, dsaParams);
}
private static byte[] GetRfc4134Data(string name)
{
return Streams.ReadAll(SimpleTest.GetTestDataAsStream("rfc4134." + name));
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.ComponentModel.Composition;
using System.ComponentModel.Composition.Factories;
using System.ComponentModel.Composition.Primitives;
using Xunit;
namespace Tests.Integration
{
public class DelegateCompositionTests
{
public delegate int SimpleDelegate();
public delegate object DoWorkDelegate(int i, ref object o, out string s);
public class MethodExporter
{
[Export]
public int SimpleMethod()
{
return 1;
}
[Export(typeof(DoWorkDelegate))]
public object DoWork(int i, ref object o, out string s)
{
s = "";
return o;
}
[Export("ActionWith8Arguments")]
[Export("ActionWith8Arguments", typeof(Delegate))]
public void Action(int i1, int i2, int i3, int i4, int i5, int i6, int i7, int i8)
{
}
[Export("FunctionWith8Arguments")]
[Export("FunctionWith8Arguments", typeof(Delegate))]
public int Function(int i1, int i2, int i3, int i4, int i5, int i6, int i7, int i8)
{
return i1 + i2 + i3 + i4 + i5 + i6 + i7 + i8;
}
[Export("FunctionWithDefaultValue")]
public int FunctionWithDefaultValue(int i, string s = "")
{
return i;
}
}
[Fact]
public void Export_SimpleCustomDelegate_ShouldWork()
{
var container = ContainerFactory.CreateWithAttributedCatalog(
typeof(MethodExporter));
var contractName = AttributedModelServices.GetContractName(typeof(SimpleDelegate));
var export1 = container.GetExportedValue<SimpleDelegate>();
Assert.Equal(1, export1());
var export2 = container.GetExportedValue<Func<int>>();
Assert.Equal(1, export1());
var export3 = (ExportedDelegate)container.GetExportedValue<object>(contractName);
var export4 = (SimpleDelegate)export3.CreateDelegate(typeof(SimpleDelegate));
Assert.Equal(1, export4());
}
[Fact]
public void Export_CustomDelegateWithOutRefParams_ShouldWork()
{
var container = ContainerFactory.CreateWithAttributedCatalog(
typeof(MethodExporter));
var export1 = container.GetExportedValue<DoWorkDelegate>();
int i = 0;
object o = new object();
string s;
export1(i, ref o, out s);
}
[Fact]
public void Export_FunctionWith8Arguments_ShouldWorkFine()
{
var container = ContainerFactory.CreateWithAttributedCatalog(
typeof(MethodExporter));
Assert.NotNull(container.GetExportedValue<Delegate>("FunctionWith8Arguments"));
}
[Fact]
public void Export_ActionWith8Arguments_ShouldWorkFine()
{
var container = ContainerFactory.CreateWithAttributedCatalog(
typeof(MethodExporter));
Assert.NotNull(container.GetExportedValue<Delegate>("ActionWith8Arguments"));
}
[Fact]
public void Export_FunctionWithDefaultValue_ShouldWorkFine()
{
var container = ContainerFactory.CreateWithAttributedCatalog(
typeof(MethodExporter));
var export = container.GetExportedValue<Func<int, string, int>>("FunctionWithDefaultValue");
Assert.Equal(3, export(3, "a"));
// Even though the string argument is optional it still cannot be cast to Func<int, int>.
var export2 = (ExportedDelegate)container.GetExportedValue<object>("FunctionWithDefaultValue");
var export3 = export2.CreateDelegate(typeof(Func<int, int>));
Assert.Null(export3);
}
public delegate int DelegateOneArg(int i);
public delegate int DelegateTwoArgs(int i, int j);
public class CustomExportedDelegate : ExportedDelegate
{
private Func<int, int, int> _func;
public CustomExportedDelegate(Func<int, int, int> func)
{
this._func = func;
}
public override Delegate CreateDelegate(Type delegateType)
{
if (delegateType == typeof(DelegateOneArg))
{
return (DelegateOneArg)((i) => this._func(i, 0));
}
else if (delegateType == typeof(DelegateTwoArgs))
{
return (DelegateTwoArgs)((i, j) => this._func(i, j));
}
return null;
}
}
public class ExportCustomExportedDelegates
{
[Export("CustomExportedDelegate", typeof(DelegateOneArg))]
[Export("CustomExportedDelegate", typeof(DelegateTwoArgs))]
public ExportedDelegate MyExportedDelegate
{
get
{
return new CustomExportedDelegate(DoWork);
}
}
public int DoWork(int i, int j)
{
return i + j;
}
}
[Export]
public class ImportCustomExportedDelegates
{
[Import("CustomExportedDelegate")]
public DelegateOneArg DelegateOneArg { get; set; }
[Import("CustomExportedDelegate")]
public DelegateTwoArgs DelegateTwoArgs { get; set; }
}
[Fact]
public void CustomExportedDelegate_ShouldWork()
{
var container = ContainerFactory.CreateWithAttributedCatalog(
typeof(ExportCustomExportedDelegates),
typeof(ImportCustomExportedDelegates));
var importer = container.GetExportedValue<ImportCustomExportedDelegates>();
Assert.Equal(1, importer.DelegateOneArg(1));
Assert.Equal(2, importer.DelegateTwoArgs(1, 1));
}
public delegate void GetRef(ref int i);
public delegate void GetOut(out int i);
public class RefOutMethodExporter
{
[Export]
public void MyGetOut(out int i)
{
i = 29;
}
}
[Fact]
public void MethodWithOutParam_ShouldWorkWithRefParam()
{
var container = ContainerFactory.CreateWithAttributedCatalog(
typeof(RefOutMethodExporter));
int i = 0;
var export1 = container.GetExportedValue<GetRef>();
export1(ref i);
Assert.Equal(29, i);
i = 0;
var export2 = container.GetExportedValue<GetOut>();
export2(out i);
Assert.Equal(29, i);
}
}
}
| |
/*
* Copyright 2002-2015 Drew Noakes
*
* Modified by Yakov Danilov <[email protected]> for Imazen LLC (Ported from Java to C#)
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* More information about this project is available at:
*
* https://drewnoakes.com/code/exif/
* https://github.com/drewnoakes/metadata-extractor
*/
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using Com.Drew.Lang;
using JetBrains.Annotations;
using Sharpen;
using Sharpen.Reflect;
namespace Com.Drew.Metadata
{
/// <summary>
/// Abstract base class for all directory implementations, having methods for getting and setting tag values of various
/// data types.
/// </summary>
/// <author>Drew Noakes https://drewnoakes.com</author>
public abstract class Directory
{
/// <summary>Map of values hashed by type identifiers.</summary>
[NotNull]
protected internal readonly IDictionary<int?, object> _tagMap = new Dictionary<int?, object>();
/// <summary>A convenient list holding tag values in the order in which they were stored.</summary>
/// <remarks>
/// A convenient list holding tag values in the order in which they were stored.
/// This is used for creation of an iterator, and for counting the number of
/// defined tags.
/// </remarks>
[NotNull]
protected internal readonly ICollection<Tag> _definedTagList = new AList<Tag>();
[NotNull]
private readonly ICollection<string> _errorList = new AList<string>(4);
/// <summary>The descriptor used to interpret tag values.</summary>
protected internal ITagDescriptor _descriptor;
// ABSTRACT METHODS
/// <summary>Provides the name of the directory, for display purposes.</summary>
/// <remarks>Provides the name of the directory, for display purposes. E.g. <code>Exif</code></remarks>
/// <returns>the name of the directory</returns>
[NotNull]
public abstract string GetName();
/// <summary>Provides the map of tag names, hashed by tag type identifier.</summary>
/// <returns>the map of tag names</returns>
[NotNull]
protected internal abstract Dictionary<int?, string> GetTagNameMap();
protected internal Directory()
{
}
// VARIOUS METHODS
/// <summary>Gets a value indicating whether the directory is empty, meaning it contains no errors and no tag values.</summary>
public virtual bool IsEmpty()
{
return _errorList.IsEmpty() && _definedTagList.IsEmpty();
}
/// <summary>Indicates whether the specified tag type has been set.</summary>
/// <param name="tagType">the tag type to check for</param>
/// <returns>true if a value exists for the specified tag type, false if not</returns>
public virtual bool ContainsTag(int tagType)
{
return _tagMap.ContainsKey(Sharpen.Extensions.ValueOf(tagType));
}
/// <summary>Returns an Iterator of Tag instances that have been set in this Directory.</summary>
/// <returns>an Iterator of Tag instances</returns>
[NotNull]
public virtual ICollection<Tag> GetTags()
{
return Sharpen.Collections.UnmodifiableCollection(_definedTagList);
}
/// <summary>Returns the number of tags set in this Directory.</summary>
/// <returns>the number of tags set in this Directory</returns>
public virtual int GetTagCount()
{
return _definedTagList.Count;
}
/// <summary>Sets the descriptor used to interpret tag values.</summary>
/// <param name="descriptor">the descriptor used to interpret tag values</param>
public virtual void SetDescriptor([NotNull] ITagDescriptor descriptor)
{
if (descriptor == null)
{
throw new ArgumentNullException("cannot set a null descriptor");
}
_descriptor = descriptor;
}
/// <summary>Registers an error message with this directory.</summary>
/// <param name="message">an error message.</param>
public virtual void AddError([NotNull] string message)
{
_errorList.Add(message);
}
/// <summary>Gets a value indicating whether this directory has any error messages.</summary>
/// <returns>true if the directory contains errors, otherwise false</returns>
public virtual bool HasErrors()
{
return _errorList.Count > 0;
}
/// <summary>Used to iterate over any error messages contained in this directory.</summary>
/// <returns>an iterable collection of error message strings.</returns>
[NotNull]
public virtual Iterable<string> GetErrors()
{
return Sharpen.Collections.UnmodifiableCollection(_errorList).AsIterable();
}
/// <summary>Returns the count of error messages in this directory.</summary>
public virtual int GetErrorCount()
{
return _errorList.Count;
}
// TAG SETTERS
/// <summary>Sets an <code>int</code> value for the specified tag.</summary>
/// <param name="tagType">the tag's value as an int</param>
/// <param name="value">the value for the specified tag as an int</param>
public virtual void SetInt(int tagType, int value)
{
SetObject(tagType, value);
}
/// <summary>Sets an <code>int[]</code> (array) for the specified tag.</summary>
/// <param name="tagType">the tag identifier</param>
/// <param name="ints">the int array to store</param>
public virtual void SetIntArray(int tagType, [NotNull] int[] ints)
{
SetObjectArray(tagType, ints);
}
/// <summary>Sets a <code>float</code> value for the specified tag.</summary>
/// <param name="tagType">the tag's value as an int</param>
/// <param name="value">the value for the specified tag as a float</param>
public virtual void SetFloat(int tagType, float value)
{
SetObject(tagType, value);
}
/// <summary>Sets a <code>float[]</code> (array) for the specified tag.</summary>
/// <param name="tagType">the tag identifier</param>
/// <param name="floats">the float array to store</param>
public virtual void SetFloatArray(int tagType, [NotNull] float[] floats)
{
SetObjectArray(tagType, floats);
}
/// <summary>Sets a <code>double</code> value for the specified tag.</summary>
/// <param name="tagType">the tag's value as an int</param>
/// <param name="value">the value for the specified tag as a double</param>
public virtual void SetDouble(int tagType, double value)
{
SetObject(tagType, value);
}
/// <summary>Sets a <code>double[]</code> (array) for the specified tag.</summary>
/// <param name="tagType">the tag identifier</param>
/// <param name="doubles">the double array to store</param>
public virtual void SetDoubleArray(int tagType, [NotNull] double[] doubles)
{
SetObjectArray(tagType, doubles);
}
/// <summary>Sets a <code>String</code> value for the specified tag.</summary>
/// <param name="tagType">the tag's value as an int</param>
/// <param name="value">the value for the specified tag as a String</param>
public virtual void SetString(int tagType, [NotNull] string value)
{
if (value == null)
{
throw new ArgumentNullException("cannot set a null String");
}
SetObject(tagType, value);
}
/// <summary>Sets a <code>String[]</code> (array) for the specified tag.</summary>
/// <param name="tagType">the tag identifier</param>
/// <param name="strings">the String array to store</param>
public virtual void SetStringArray(int tagType, [NotNull] string[] strings)
{
SetObjectArray(tagType, strings);
}
/// <summary>Sets a <code>boolean</code> value for the specified tag.</summary>
/// <param name="tagType">the tag's value as an int</param>
/// <param name="value">the value for the specified tag as a boolean</param>
public virtual void SetBoolean(int tagType, bool value)
{
SetObject(tagType, value);
}
/// <summary>Sets a <code>long</code> value for the specified tag.</summary>
/// <param name="tagType">the tag's value as an int</param>
/// <param name="value">the value for the specified tag as a long</param>
public virtual void SetLong(int tagType, long value)
{
SetObject(tagType, value);
}
/// <summary>Sets a <code>java.util.Date</code> value for the specified tag.</summary>
/// <param name="tagType">the tag's value as an int</param>
/// <param name="value">the value for the specified tag as a java.util.Date</param>
public virtual void SetDate(int tagType, [NotNull] DateTime value)
{
SetObject(tagType, value);
}
/// <summary>Sets a <code>Rational</code> value for the specified tag.</summary>
/// <param name="tagType">the tag's value as an int</param>
/// <param name="rational">rational number</param>
public virtual void SetRational(int tagType, [NotNull] Rational rational)
{
SetObject(tagType, rational);
}
/// <summary>Sets a <code>Rational[]</code> (array) for the specified tag.</summary>
/// <param name="tagType">the tag identifier</param>
/// <param name="rationals">the Rational array to store</param>
public virtual void SetRationalArray(int tagType, [NotNull] Rational[] rationals)
{
SetObjectArray(tagType, rationals);
}
/// <summary>Sets a <code>byte[]</code> (array) for the specified tag.</summary>
/// <param name="tagType">the tag identifier</param>
/// <param name="bytes">the byte array to store</param>
public virtual void SetByteArray(int tagType, [NotNull] sbyte[] bytes)
{
SetObjectArray(tagType, bytes);
}
/// <summary>Sets a <code>Object</code> for the specified tag.</summary>
/// <param name="tagType">the tag's value as an int</param>
/// <param name="value">the value for the specified tag</param>
/// <exception cref="System.ArgumentNullException">if value is <code>null</code></exception>
public virtual void SetObject(int tagType, [NotNull] object value)
{
if (value == null)
{
throw new ArgumentNullException("cannot set a null object");
}
if (!_tagMap.ContainsKey(Sharpen.Extensions.ValueOf(tagType)))
{
_definedTagList.Add(new Tag(tagType, this));
}
// else {
// final Object oldValue = _tagMap.get(tagType);
// if (!oldValue.equals(value))
// addError(String.format("Overwritten tag 0x%s (%s). Old=%s, New=%s", Integer.toHexString(tagType), getTagName(tagType), oldValue, value));
// }
_tagMap.Put(tagType, value);
}
/// <summary>Sets an array <code>Object</code> for the specified tag.</summary>
/// <param name="tagType">the tag's value as an int</param>
/// <param name="array">the array of values for the specified tag</param>
public virtual void SetObjectArray(int tagType, [NotNull] object array)
{
// for now, we don't do anything special -- this method might be a candidate for removal once the dust settles
SetObject(tagType, array);
}
// TAG GETTERS
/// <summary>Returns the specified tag's value as an int, if possible.</summary>
/// <remarks>
/// Returns the specified tag's value as an int, if possible. Every attempt to represent the tag's value as an int
/// is taken. Here is a list of the action taken depending upon the tag's original type:
/// <ul>
/// <li> int - Return unchanged.
/// <li> Number - Return an int value (real numbers are truncated).
/// <li> Rational - Truncate any fractional part and returns remaining int.
/// <li> String - Attempt to parse string as an int. If this fails, convert the char[] to an int (using shifts and OR).
/// <li> Rational[] - Return int value of first item in array.
/// <li> byte[] - Return int value of first item in array.
/// <li> int[] - Return int value of first item in array.
/// </ul>
/// </remarks>
/// <exception cref="MetadataException">if no value exists for tagType or if it cannot be converted to an int.</exception>
/// <exception cref="Com.Drew.Metadata.MetadataException"/>
public virtual int GetInt(int tagType)
{
int? integer = GetInteger(tagType);
if (integer != null)
{
return (int)integer;
}
object o = GetObject(tagType);
if (o == null)
{
throw new MetadataException("Tag '" + GetTagName(tagType) + "' has not been set -- check using containsTag() first");
}
throw new MetadataException("Tag '" + tagType + "' cannot be converted to int. It is of type '" + o.GetType() + "'.");
}
/// <summary>Returns the specified tag's value as an Integer, if possible.</summary>
/// <remarks>
/// Returns the specified tag's value as an Integer, if possible. Every attempt to represent the tag's value as an
/// Integer is taken. Here is a list of the action taken depending upon the tag's original type:
/// <ul>
/// <li> int - Return unchanged
/// <li> Number - Return an int value (real numbers are truncated)
/// <li> Rational - Truncate any fractional part and returns remaining int
/// <li> String - Attempt to parse string as an int. If this fails, convert the char[] to an int (using shifts and OR)
/// <li> Rational[] - Return int value of first item in array if length > 0
/// <li> byte[] - Return int value of first item in array if length > 0
/// <li> int[] - Return int value of first item in array if length > 0
/// </ul>
/// If the value is not found or cannot be converted to int, <code>null</code> is returned.
/// </remarks>
[CanBeNull]
public virtual int? GetInteger(int tagType)
{
object o = GetObject(tagType);
if (o == null)
{
return null;
}
if (o.IsNumber())
{
return Number.GetInstance(o).IntValue();
}
else
{
if (o is string)
{
try
{
return System.Convert.ToInt32((string)o);
}
catch (FormatException)
{
// convert the char array to an int
string s = (string)o;
sbyte[] bytes = Sharpen.Runtime.GetBytesForString(s);
long val = 0;
foreach (sbyte aByte in bytes)
{
val = val << 8;
val += (aByte & unchecked((int)(0xff)));
}
return (int)val;
}
}
else
{
if (o is Rational[])
{
Rational[] rationals = (Rational[])o;
if (rationals.Length == 1)
{
return rationals[0].IntValue();
}
}
else
{
if (o is sbyte[])
{
sbyte[] bytes = (sbyte[])o;
if (bytes.Length == 1)
{
return (int)bytes[0];
}
}
else
{
if (o is int[])
{
int[] ints = (int[])o;
if (ints.Length == 1)
{
return ints[0];
}
}
}
}
}
}
return null;
}
/// <summary>Gets the specified tag's value as a String array, if possible.</summary>
/// <remarks>
/// Gets the specified tag's value as a String array, if possible. Only supported
/// where the tag is set as String[], String, int[], byte[] or Rational[].
/// </remarks>
/// <param name="tagType">the tag identifier</param>
/// <returns>the tag's value as an array of Strings. If the value is unset or cannot be converted, <code>null</code> is returned.</returns>
[CanBeNull]
public virtual string[] GetStringArray(int tagType)
{
object o = GetObject(tagType);
if (o == null)
{
return null;
}
if (o is string[])
{
return (string[])o;
}
if (o is string)
{
return new string[] { (string)o };
}
if (o is int[])
{
int[] ints = (int[])o;
string[] strings = new string[ints.Length];
for (int i = 0; i < strings.Length; i++)
{
strings[i] = Sharpen.Extensions.ConvertToString(ints[i]);
}
return strings;
}
else
{
if (o is sbyte[])
{
sbyte[] bytes = (sbyte[])o;
string[] strings = new string[bytes.Length];
for (int i = 0; i < strings.Length; i++)
{
strings[i] = Sharpen.Extensions.ConvertToString(bytes[i]);
}
return strings;
}
else
{
if (o is Rational[])
{
Rational[] rationals = (Rational[])o;
string[] strings = new string[rationals.Length];
for (int i = 0; i < strings.Length; i++)
{
strings[i] = rationals[i].ToSimpleString(false);
}
return strings;
}
}
}
return null;
}
/// <summary>Gets the specified tag's value as an int array, if possible.</summary>
/// <remarks>
/// Gets the specified tag's value as an int array, if possible. Only supported
/// where the tag is set as String, Integer, int[], byte[] or Rational[].
/// </remarks>
/// <param name="tagType">the tag identifier</param>
/// <returns>the tag's value as an int array</returns>
[CanBeNull]
public virtual int[] GetIntArray(int tagType)
{
object o = GetObject(tagType);
if (o == null)
{
return null;
}
if (o is int[])
{
return (int[])o;
}
if (o is Rational[])
{
Rational[] rationals = (Rational[])o;
int[] ints = new int[rationals.Length];
for (int i = 0; i < ints.Length; i++)
{
ints[i] = rationals[i].IntValue();
}
return ints;
}
if (o is short[])
{
short[] shorts = (short[])o;
int[] ints = new int[shorts.Length];
for (int i = 0; i < shorts.Length; i++)
{
ints[i] = shorts[i];
}
return ints;
}
if (o is sbyte[])
{
sbyte[] bytes = (sbyte[])o;
int[] ints = new int[bytes.Length];
for (int i = 0; i < bytes.Length; i++)
{
ints[i] = bytes[i];
}
return ints;
}
if (o is CharSequence)
{
CharSequence str = (CharSequence)o;
int[] ints = new int[str.Length];
for (int i = 0; i < str.Length; i++)
{
ints[i] = str[i];
}
return ints;
}
if (o is int?)
{
return new int[] { (int)o };
}
return null;
}
/// <summary>Gets the specified tag's value as an byte array, if possible.</summary>
/// <remarks>
/// Gets the specified tag's value as an byte array, if possible. Only supported
/// where the tag is set as String, Integer, int[], byte[] or Rational[].
/// </remarks>
/// <param name="tagType">the tag identifier</param>
/// <returns>the tag's value as a byte array</returns>
[CanBeNull]
public virtual sbyte[] GetByteArray(int tagType)
{
object o = GetObject(tagType);
if (o == null)
{
return null;
}
else
{
if (o is Rational[])
{
Rational[] rationals = (Rational[])o;
sbyte[] bytes = new sbyte[rationals.Length];
for (int i = 0; i < bytes.Length; i++)
{
bytes[i] = rationals[i].ByteValue();
}
return bytes;
}
else
{
if (o is sbyte[])
{
return (sbyte[])o;
}
else
{
if (o is int[])
{
int[] ints = (int[])o;
sbyte[] bytes = new sbyte[ints.Length];
for (int i = 0; i < ints.Length; i++)
{
bytes[i] = unchecked((sbyte)ints[i]);
}
return bytes;
}
else
{
if (o is short[])
{
short[] shorts = (short[])o;
sbyte[] bytes = new sbyte[shorts.Length];
for (int i = 0; i < shorts.Length; i++)
{
bytes[i] = unchecked((sbyte)shorts[i]);
}
return bytes;
}
else
{
if (o is CharSequence)
{
CharSequence str = (CharSequence)o;
sbyte[] bytes = new sbyte[str.Length];
for (int i = 0; i < str.Length; i++)
{
bytes[i] = unchecked((sbyte)str[i]);
}
return bytes;
}
}
}
}
}
}
if (o is int?)
{
return new sbyte[] { ((int?)o).ByteValue() };
}
return null;
}
/// <summary>Returns the specified tag's value as a double, if possible.</summary>
/// <exception cref="Com.Drew.Metadata.MetadataException"/>
public virtual double GetDouble(int tagType)
{
double? value = GetDoubleObject(tagType);
if (value != null)
{
return (double)value;
}
object o = GetObject(tagType);
if (o == null)
{
throw new MetadataException("Tag '" + GetTagName(tagType) + "' has not been set -- check using containsTag() first");
}
throw new MetadataException("Tag '" + tagType + "' cannot be converted to a double. It is of type '" + o.GetType() + "'.");
}
/// <summary>Returns the specified tag's value as a Double.</summary>
/// <remarks>Returns the specified tag's value as a Double. If the tag is not set or cannot be converted, <code>null</code> is returned.</remarks>
[CanBeNull]
public virtual double? GetDoubleObject(int tagType)
{
object o = GetObject(tagType);
if (o == null)
{
return null;
}
if (o is string)
{
try
{
return double.Parse((string)o);
}
catch (FormatException)
{
return null;
}
}
if (o.IsNumber())
{
return Number.GetInstance(o).DoubleValue();
}
return null;
}
/// <summary>Returns the specified tag's value as a float, if possible.</summary>
/// <exception cref="Com.Drew.Metadata.MetadataException"/>
public virtual float GetFloat(int tagType)
{
float? value = GetFloatObject(tagType);
if (value != null)
{
return (float)value;
}
object o = GetObject(tagType);
if (o == null)
{
throw new MetadataException("Tag '" + GetTagName(tagType) + "' has not been set -- check using containsTag() first");
}
throw new MetadataException("Tag '" + tagType + "' cannot be converted to a float. It is of type '" + o.GetType() + "'.");
}
/// <summary>Returns the specified tag's value as a float.</summary>
/// <remarks>Returns the specified tag's value as a float. If the tag is not set or cannot be converted, <code>null</code> is returned.</remarks>
[CanBeNull]
public virtual float? GetFloatObject(int tagType)
{
object o = GetObject(tagType);
if (o == null)
{
return null;
}
if (o is string)
{
try
{
return float.Parse((string)o);
}
catch (FormatException)
{
return null;
}
}
if (o.IsNumber())
{
return Number.GetInstance(o).FloatValue();
}
return null;
}
/// <summary>Returns the specified tag's value as a long, if possible.</summary>
/// <exception cref="Com.Drew.Metadata.MetadataException"/>
public virtual long GetLong(int tagType)
{
long? value = GetLongObject(tagType);
if (value != null)
{
return (long)value;
}
object o = GetObject(tagType);
if (o == null)
{
throw new MetadataException("Tag '" + GetTagName(tagType) + "' has not been set -- check using containsTag() first");
}
throw new MetadataException("Tag '" + tagType + "' cannot be converted to a long. It is of type '" + o.GetType() + "'.");
}
/// <summary>Returns the specified tag's value as a long.</summary>
/// <remarks>Returns the specified tag's value as a long. If the tag is not set or cannot be converted, <code>null</code> is returned.</remarks>
[CanBeNull]
public virtual long? GetLongObject(int tagType)
{
object o = GetObject(tagType);
if (o == null)
{
return null;
}
if (o is string)
{
try
{
return System.Convert.ToInt64((string)o);
}
catch (FormatException)
{
return null;
}
}
if (o.IsNumber())
{
return Number.GetInstance(o).LongValue();
}
return null;
}
/// <summary>Returns the specified tag's value as a boolean, if possible.</summary>
/// <exception cref="Com.Drew.Metadata.MetadataException"/>
public virtual bool GetBoolean(int tagType)
{
bool? value = GetBooleanObject(tagType);
if (value != null)
{
return (bool)value;
}
object o = GetObject(tagType);
if (o == null)
{
throw new MetadataException("Tag '" + GetTagName(tagType) + "' has not been set -- check using containsTag() first");
}
throw new MetadataException("Tag '" + tagType + "' cannot be converted to a boolean. It is of type '" + o.GetType() + "'.");
}
/// <summary>Returns the specified tag's value as a boolean.</summary>
/// <remarks>Returns the specified tag's value as a boolean. If the tag is not set or cannot be converted, <code>null</code> is returned.</remarks>
[CanBeNull]
public virtual bool? GetBooleanObject(int tagType)
{
object o = GetObject(tagType);
if (o == null)
{
return null;
}
if (o is bool?)
{
return (bool?)o;
}
if (o is string)
{
try
{
return bool.Parse((string)o);
}
catch (FormatException)
{
return null;
}
}
if (o.IsNumber())
{
return Number.GetInstance(o).DoubleValue() != 0;
}
return null;
}
/// <summary>Returns the specified tag's value as a java.util.Date.</summary>
/// <remarks>
/// Returns the specified tag's value as a java.util.Date. If the value is unset or cannot be converted, <code>null</code> is returned.
/// <p>
/// If the underlying value is a
/// <see cref="string"/>
/// , then attempts will be made to parse the string as though it is in
/// the current
/// <see cref="System.TimeZoneInfo"/>
/// . If the
/// <see cref="System.TimeZoneInfo"/>
/// is known, call the overload that accepts one as an argument.
/// </remarks>
[CanBeNull]
public virtual DateTime? GetDate(int tagType)
{
return GetDate(tagType, null);
}
/// <summary>Returns the specified tag's value as a java.util.Date.</summary>
/// <remarks>
/// Returns the specified tag's value as a java.util.Date. If the value is unset or cannot be converted, <code>null</code> is returned.
/// <p>
/// If the underlying value is a
/// <see cref="string"/>
/// , then attempts will be made to parse the string as though it is in
/// the
/// <see cref="System.TimeZoneInfo"/>
/// represented by the
/// <paramref name="timeZone"/>
/// parameter (if it is non-null). Note that this parameter
/// is only considered if the underlying value is a string and parsing occurs, otherwise it has no effect.
/// </remarks>
[CanBeNull]
public virtual DateTime? GetDate(int tagType, [CanBeNull] TimeZoneInfo timeZone)
{
object o = GetObject(tagType);
if (o == null)
{
return null;
}
if (o is DateTime)
{
return (DateTime)o;
}
if (o is string)
{
// This seems to cover all known Exif date strings
// Note that " : : : : " is a valid date string according to the Exif spec (which means 'unknown date'): http://www.awaresystems.be/imaging/tiff/tifftags/privateifd/exif/datetimeoriginal.html
string[] datePatterns = new string[] { "yyyy:MM:dd HH:mm:ss", "yyyy:MM:dd HH:mm", "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm", "yyyy.MM.dd HH:mm:ss", "yyyy.MM.dd HH:mm" };
string dateString = (string)o;
foreach (string datePattern in datePatterns)
{
try
{
DateFormat parser = new SimpleDateFormat(datePattern);
if (timeZone != null)
{
parser.SetTimeZone(timeZone);
}
return parser.Parse(dateString);
}
catch (ParseException)
{
}
}
}
// simply try the next pattern
return null;
}
/// <summary>Returns the specified tag's value as a Rational.</summary>
/// <remarks>Returns the specified tag's value as a Rational. If the value is unset or cannot be converted, <code>null</code> is returned.</remarks>
[CanBeNull]
public virtual Rational GetRational(int tagType)
{
object o = GetObject(tagType);
if (o == null)
{
return null;
}
if (o is Rational)
{
return (Rational)o;
}
if (o is int?)
{
return new Rational((int)o, 1);
}
if (o is long?)
{
return new Rational((long)o, 1);
}
// NOTE not doing conversions for real number types
return null;
}
/// <summary>Returns the specified tag's value as an array of Rational.</summary>
/// <remarks>Returns the specified tag's value as an array of Rational. If the value is unset or cannot be converted, <code>null</code> is returned.</remarks>
[CanBeNull]
public virtual Rational[] GetRationalArray(int tagType)
{
object o = GetObject(tagType);
if (o == null)
{
return null;
}
if (o is Rational[])
{
return (Rational[])o;
}
return null;
}
/// <summary>Returns the specified tag's value as a String.</summary>
/// <remarks>
/// Returns the specified tag's value as a String. This value is the 'raw' value. A more presentable decoding
/// of this value may be obtained from the corresponding Descriptor.
/// </remarks>
/// <returns>
/// the String representation of the tag's value, or
/// <code>null</code> if the tag hasn't been defined.
/// </returns>
[CanBeNull]
public virtual string GetString(int tagType)
{
object o = GetObject(tagType);
if (o == null)
{
return null;
}
if (o is Rational)
{
return ((Rational)o).ToSimpleString(true);
}
if (o.GetType().IsArray)
{
// handle arrays of objects and primitives
int arrayLength = Sharpen.Runtime.GetArrayLength(o);
Type componentType = o.GetType().GetElementType();
bool isObjectArray = typeof(object).IsAssignableFrom(componentType);
bool isFloatArray = componentType.FullName.Equals("float");
bool isDoubleArray = componentType.FullName.Equals("double");
bool isIntArray = componentType.FullName.Equals("int");
bool isLongArray = componentType.FullName.Equals("long");
bool isByteArray = componentType.FullName.Equals("byte");
bool isShortArray = componentType.FullName.Equals("short");
StringBuilder @string = new StringBuilder();
for (int i = 0; i < arrayLength; i++)
{
if (i != 0)
{
@string.Append(' ');
}
if (isObjectArray)
{
@string.Append(Sharpen.Extensions.ConvertToString(Sharpen.Runtime.GetArrayValue(o, i)));
}
else
{
if (isIntArray)
{
@string.Append(Sharpen.Runtime.GetInt(o, i));
}
else
{
if (isShortArray)
{
@string.Append(Sharpen.Runtime.GetShort(o, i));
}
else
{
if (isLongArray)
{
@string.Append(Sharpen.Runtime.GetLong(o, i));
}
else
{
if (isFloatArray)
{
@string.Append(Sharpen.Runtime.GetFloat(o, i));
}
else
{
if (isDoubleArray)
{
@string.Append(Sharpen.Runtime.GetDouble(o, i));
}
else
{
if (isByteArray)
{
@string.Append(Sharpen.Runtime.GetByte(o, i));
}
else
{
AddError("Unexpected array component type: " + componentType.FullName);
}
}
}
}
}
}
}
}
return Sharpen.Extensions.ConvertToString(@string);
}
// Note that several cameras leave trailing spaces (Olympus, Nikon) but this library is intended to show
// the actual data within the file. It is not inconceivable that whitespace may be significant here, so we
// do not trim. Also, if support is added for writing data back to files, this may cause issues.
// We leave trimming to the presentation layer.
return Sharpen.Extensions.ConvertToString(o);
}
[CanBeNull]
public virtual string GetString(int tagType, string charset)
{
sbyte[] bytes = GetByteArray(tagType);
if (bytes == null)
{
return null;
}
try
{
return Sharpen.Runtime.GetStringForBytes(bytes, charset);
}
catch (UnsupportedEncodingException)
{
return null;
}
}
/// <summary>Returns the object hashed for the particular tag type specified, if available.</summary>
/// <param name="tagType">the tag type identifier</param>
/// <returns>the tag's value as an Object if available, else <code>null</code></returns>
[CanBeNull]
public virtual object GetObject(int tagType)
{
return _tagMap.Get(Sharpen.Extensions.ValueOf(tagType));
}
// OTHER METHODS
/// <summary>Returns the name of a specified tag as a String.</summary>
/// <param name="tagType">the tag type identifier</param>
/// <returns>the tag's name as a String</returns>
[NotNull]
public virtual string GetTagName(int tagType)
{
Dictionary<int?, string> nameMap = GetTagNameMap();
if (!nameMap.ContainsKey(tagType))
{
string hex = Sharpen.Extensions.ToHexString(tagType);
while (hex.Length < 4)
{
hex = "0" + hex;
}
return "Unknown tag (0x" + hex + ")";
}
return nameMap.Get(tagType);
}
/// <summary>Gets whether the specified tag is known by the directory and has a name.</summary>
/// <param name="tagType">the tag type identifier</param>
/// <returns>whether this directory has a name for the specified tag</returns>
public virtual bool HasTagName(int tagType)
{
return GetTagNameMap().ContainsKey(tagType);
}
/// <summary>
/// Provides a description of a tag's value using the descriptor set by
/// <code>setDescriptor(Descriptor)</code>.
/// </summary>
/// <param name="tagType">the tag type identifier</param>
/// <returns>the tag value's description as a String</returns>
[CanBeNull]
public virtual string GetDescription(int tagType)
{
System.Diagnostics.Debug.Assert((_descriptor != null));
return _descriptor.GetDescription(tagType);
}
public override string ToString()
{
return Sharpen.Extensions.StringFormat("%s Directory (%d %s)", GetName(), _tagMap.Count, _tagMap.Count == 1 ? "tag" : "tags");
}
}
}
| |
namespace Charity.Data.Migrations
{
using System;
using System.Collections.Generic;
using System.Data.Entity.Migrations;
using System.Linq;
using Charity.Common;
using Charity.Data.Extensions;
using Charity.Data.Models;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
internal sealed class Configuration : DbMigrationsConfiguration<ApplicationDbContext>
{
private readonly List<string> organizationNames = new List<string>()
{
"Acme",
"Universal Exports",
"Smith and Co.",
"Allied Biscuit",
"Galaxy",
"Globex",
"ZiffCorp",
"Gringotts",
"Water and Power",
"Bluth",
"Praxis",
"Luthor",
"Tessier-Ashpool",
"Three Waters",
"Sto Plains",
"Mooby Foods",
"Strickland",
"AnimalHope",
"Green Planet",
"North Central",
};
private readonly List<string> contactNames = new List<string>()
{
"Teddy Ferrara",
"Dyan Fisher",
"Anne Smith",
"Maria Finnegan",
"Ronnie Foltz",
"Eleanor Fowler",
"William Heller",
"Bobbi Canfield",
"Christina Buxton",
"Alexander Byrnes",
"Simon Cambell",
"Peter Callaghan",
"Ashley Hong",
"Hayden Jacques",
"Ida Jacobson",
"Jamie Miller",
"Jason Peterson",
"Michael Kaiser",
"Ivy Kearney",
"Sammy Keen",
};
private readonly List<string> images = new List<string>()
{
"/Content/Images/Donations_Food/food-in-wooden-basket.jpg",
"/Content/Images/Donations_Food/cartboxes-with-food.jpeg",
"/Content/Images/Donations_Food/packaged-food-on-a-table.jpg",
"/Content/Images/Donations_Food/food-in-wooden-donation-box.jpg",
"/Content/Images/Donations_Food/fruits-and-vegetables.jpg",
};
private readonly Random randomGenerator = new Random();
public Configuration()
{
AutomaticMigrationsEnabled = true;
// TODO: Remove in production
AutomaticMigrationDataLossAllowed = true;
}
protected override void Seed(ApplicationDbContext context)
{
// This method will be called after migrating to the latest version.
// You can use the DbSet<T>.AddOrUpdate() helper extension method
// to avoid creating duplicate seed data. E.g.
//
// context.People.AddOrUpdate(
// p => p.FullName,
// new Person { FullName = "Andrew Peters" },
// new Person { FullName = "Brice Lambson" },
// new Person { FullName = "Rowan Miller" }
// );
//
var userManager = this.CreateUserManager(context);
var roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(context));
context.Configuration.AutoDetectChangesEnabled = false;
this.SeedRoles(context);
this.SeedAdminUser(context, userManager, roleManager);
var cities = this.SeedCities(context);
var recipientTypes = this.SeedRecipientTypes(context);
var foodCategories = this.SeedFoodCategories(context);
var donors = this.SeedDonors(context, userManager, roleManager, cities);
var recipients = this.SeedRecipients(
context,
userManager,
roleManager,
recipientTypes,
cities,
foodCategories);
var foodDonations = this.SeedFoodDonations(context, foodCategories, donors);
this.SeedFoodRequests(context, recipients, foodDonations);
context.Configuration.AutoDetectChangesEnabled = true;
}
private void SeedRoles(ApplicationDbContext context)
{
if (context.Roles.Any())
{
return;
}
context.Roles.AddOrUpdate(new IdentityRole(GlobalConstants.AdministratorRoleName));
context.Roles.AddOrUpdate(new IdentityRole(GlobalConstants.DonorRoleName));
context.Roles.AddOrUpdate(new IdentityRole(GlobalConstants.RecipientRoleName));
context.SaveChanges();
}
private void SeedAdminUser(
ApplicationDbContext context,
UserManager<ApplicationUser> userManager,
RoleManager<IdentityRole> roleManager)
{
if (context.Administrators.Any())
{
return;
}
var administratorProfile = new Administrator();
administratorProfile.FirstName = "Admin";
administratorProfile.LastName = "Admin";
administratorProfile.CreatedOn = DateTime.Now;
// Create Admin Role if it does not exist
if (! roleManager.RoleExists(GlobalConstants.AdministratorRoleName))
{
roleManager.Create(new IdentityRole(GlobalConstants.AdministratorRoleName));
}
// Create Admin User with password
var administratorUser = new ApplicationUser();
administratorUser.UserName = "admin";
administratorUser.Email = "[email protected]";
administratorUser.CreatedOn = DateTime.Now;
string password = "111";
var result = userManager.Create(administratorUser, password);
// Add Admin User to Admin Role
if (result.Succeeded)
{
userManager.AddToRole(administratorUser.Id, GlobalConstants.AdministratorRoleName);
}
// Add Admin User to Admin Profile
administratorProfile.ApplicationUser = administratorUser;
context.Administrators.Add(administratorProfile);
context.SaveChanges();
}
private List<Donor> SeedDonors(
ApplicationDbContext context,
UserManager<ApplicationUser> userManager,
RoleManager<IdentityRole> roleManager,
List<City> cities)
{
var donors = new List<Donor>();
if (context.Donors.Any())
{
return donors;
}
for (int i = 1; i <= 20; i++)
{
var donorProfile = new Donor();
donorProfile.OrganizationName = this.organizationNames[i - 1];
donorProfile.ContactName = this.contactNames[20 - i];
var cityIndex = this.randomGenerator.Next(0, cities.Count);
donorProfile.City = cities[cityIndex];
donorProfile.CreatedOn = DateTime.Now;
// Create Donor Role if it does not exist
if (!roleManager.RoleExists(GlobalConstants.DonorRoleName))
{
roleManager.Create(new IdentityRole(GlobalConstants.DonorRoleName));
}
// Create Donor User with password
var donorUser = new ApplicationUser();
donorUser.UserName = "donor" + i;
donorUser.Email = "d" + i + "@d.com";
donorUser.CreatedOn = DateTime.Now;
string password = "111";
var result = userManager.Create(donorUser, password);
// Add Donor User to Donor Role
if (result.Succeeded)
{
userManager.AddToRole(donorUser.Id, GlobalConstants.DonorRoleName);
}
// Add Donor User to Donor Profile
donorProfile.ApplicationUser = donorUser;
context.Donors.Add(donorProfile);
donors.Add(donorProfile);
}
context.SaveChanges();
return donors;
}
private List<Recipient> SeedRecipients(
ApplicationDbContext context,
UserManager<ApplicationUser> userManager,
RoleManager<IdentityRole> roleManager,
List<RecipientType> recipientTypes,
List<City> cities,
List<FoodCategory> foodCategories)
{
var recipients = new List<Recipient>();
if (context.Recipients.Any())
{
return recipients;
}
for (int i = 1; i <= 20; i++)
{
var recipientProfile = new Recipient();
recipientProfile.OrganizationName = this.organizationNames[20 - i];
recipientProfile.ContactName = this.contactNames[20 - i];
var recipientTypeIndex = this.randomGenerator.Next(0, recipientTypes.Count);
recipientProfile.RecipientType = recipientTypes[recipientTypeIndex];
var cityIndex = this.randomGenerator.Next(0, cities.Count);
recipientProfile.City = cities[cityIndex];
foodCategories.Shuffle();
recipientProfile.FoodCategories = foodCategories.Take(5).ToList();
recipientProfile.CreatedOn = DateTime.Now;
// Create Recipient Role if it does not exist
if (!roleManager.RoleExists(GlobalConstants.RecipientRoleName))
{
roleManager.Create(new IdentityRole(GlobalConstants.RecipientRoleName));
}
// Create Recipient User with password
var donorUser = new ApplicationUser();
donorUser.UserName = "recipient" + i;
donorUser.Email = "r" + i + "@r.com";
donorUser.CreatedOn = DateTime.Now;
string password = "111";
var result = userManager.Create(donorUser, password);
// Add Recipient User to Recipient Role
if (result.Succeeded)
{
userManager.AddToRole(donorUser.Id, GlobalConstants.RecipientRoleName);
}
// Add Recipient User to Recipient Profile
recipientProfile.ApplicationUser = donorUser;
context.Recipients.Add(recipientProfile);
recipients.Add(recipientProfile);
}
context.SaveChanges();
return recipients;
}
private UserManager<ApplicationUser> CreateUserManager(ApplicationDbContext context)
{
var userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context));
// Configure user manager
// Configure validation logic for usernames
userManager.UserValidator = new UserValidator<ApplicationUser>(userManager)
{
AllowOnlyAlphanumericUserNames = true,
RequireUniqueEmail = true
};
// Configure validation logic for passwords
userManager.PasswordValidator = new PasswordValidator
{
RequiredLength = 3,
RequireNonLetterOrDigit = false,
RequireDigit = false,
RequireLowercase = false,
RequireUppercase = false,
};
return userManager;
}
private List<City> SeedCities(ApplicationDbContext context)
{
var cities = new List<City>();
if (context.Cities.Any())
{
return cities;
}
var city = new City();
city.Name = "Sofia";
city.CreatedOn = DateTime.Now;
cities.Add(city);
context.Cities.Add(city);
city = new City();
city.Name = "Plovdiv";
city.CreatedOn = DateTime.Now;
cities.Add(city);
context.Cities.Add(city);
city = new City();
city.Name = "Varna";
city.CreatedOn = DateTime.Now;
cities.Add(city);
context.Cities.Add(city);
city = new City();
city.Name = "Burgas";
city.CreatedOn = DateTime.Now;
cities.Add(city);
context.Cities.Add(city);
context.SaveChanges();
return cities;
}
private List<RecipientType> SeedRecipientTypes(ApplicationDbContext context)
{
var recipientTypes = new List<RecipientType>();
if (context.RecipientTypes.Any())
{
return recipientTypes;
}
var type = new RecipientType();
type.Name = "Homeless Centre";
type.CreatedOn = DateTime.Now;
recipientTypes.Add(type);
context.RecipientTypes.Add(type);
type = new RecipientType();
type.Name = "Crisis Accommodation";
type.CreatedOn = DateTime.Now;
recipientTypes.Add(type);
context.RecipientTypes.Add(type);
type = new RecipientType();
type.Name = "School";
type.CreatedOn = DateTime.Now;
recipientTypes.Add(type);
context.RecipientTypes.Add(type);
type = new RecipientType();
type.Name = "Animal shelter";
type.CreatedOn = DateTime.Now;
recipientTypes.Add(type);
context.RecipientTypes.Add(type);
type = new RecipientType();
type.Name = "Other";
type.CreatedOn = DateTime.Now;
recipientTypes.Add(type);
context.RecipientTypes.Add(type);
context.SaveChanges();
return recipientTypes;
}
private List<FoodCategory> SeedFoodCategories(ApplicationDbContext context)
{
var foodCategories = new List<FoodCategory>();
if (context.FoodCategories.Any())
{
return foodCategories;
}
var category = new FoodCategory();
category.Name = "Meat";
category.CreatedOn = DateTime.Now;
foodCategories.Add(category);
context.FoodCategories.Add(category);
category = new FoodCategory();
category.Name = "Seafood";
category.CreatedOn = DateTime.Now;
foodCategories.Add(category);
context.FoodCategories.Add(category);
category = new FoodCategory();
category.Name = "Egg Products";
category.CreatedOn = DateTime.Now;
foodCategories.Add(category);
context.FoodCategories.Add(category);
category = new FoodCategory();
category.Name = "Dairy Products";
category.CreatedOn = DateTime.Now;
foodCategories.Add(category);
context.FoodCategories.Add(category);
category = new FoodCategory();
category.Name = "Fresh fruits and vegetables";
category.CreatedOn = DateTime.Now;
foodCategories.Add(category);
context.FoodCategories.Add(category);
category = new FoodCategory();
category.Name = "Nuts, Grains and Beans";
category.CreatedOn = DateTime.Now;
foodCategories.Add(category);
context.FoodCategories.Add(category);
category = new FoodCategory();
category.Name = "Ready meals";
category.CreatedOn = DateTime.Now;
foodCategories.Add(category);
context.FoodCategories.Add(category);
category = new FoodCategory();
category.Name = "Baby food";
category.CreatedOn = DateTime.Now;
foodCategories.Add(category);
context.FoodCategories.Add(category);
category = new FoodCategory();
category.Name = "Pet food";
category.CreatedOn = DateTime.Now;
foodCategories.Add(category);
context.FoodCategories.Add(category);
category = new FoodCategory();
category.Name = "Other";
category.CreatedOn = DateTime.Now;
foodCategories.Add(category);
context.FoodCategories.Add(category);
context.SaveChanges();
return foodCategories;
}
private List<FoodDonation> SeedFoodDonations(ApplicationDbContext context, List<FoodCategory> foodCategories, List<Donor> donors)
{
var foodDonations = new List<FoodDonation>();
if (context.FoodDonations.Any())
{
return foodDonations;
}
for (int i = 0; i < 20; i++)
{
for (int j = 1; j <= 20; j++)
{
var foodDonation = new FoodDonation();
var categoryIndex = this.randomGenerator.Next(0, foodCategories.Count);
var foodCategory = foodCategories[categoryIndex];
foodDonation.Donor = donors[i];
foodDonation.FoodCategory = foodCategory;
foodDonation.Name = foodCategory.Name;
foodDonation.Quantity = j.ToString() + (j == 1 ? " item" : " items");
foodDonation.Description = foodCategory.Name;
var imageIndex = this.randomGenerator.Next(0, images.Count);
foodDonation.ImageUrl = images[imageIndex];
foodDonation.ExpirationDate = DateTime.Now.AddDays(j + 10);
foodDonation.AvailableFrom = DateTime.Now;
foodDonation.AvailableTo = foodDonation.ExpirationDate.AddDays(-3);
foodDonation.CreatedOn = DateTime.Now;
context.FoodDonations.Add(foodDonation);
foodDonations.Add(foodDonation);
}
}
context.SaveChanges();
return foodDonations;
}
private void SeedFoodRequests(ApplicationDbContext context, List<Recipient> recipients, List<FoodDonation> foodDonations)
{
if (context.FoodRequests.Any())
{
return;
}
for (int i = 0; i < 20; i++)
{
for (int j = 1; j <= 20; j++)
{
var foodRequest = new FoodRequest();
var foodDonationIndex = this.randomGenerator.Next(0, foodDonations.Count);
var foodDonation = foodDonations[foodDonationIndex];
foodRequest.Recipient = recipients[i];
foodRequest.FoodDonation = foodDonation;
foodRequest.Quantity = j.ToString() + (j == 1 ? " item" : " items");
foodRequest.Description = foodDonation.Name;
foodRequest.NeedFrom = DateTime.Now;
foodRequest.NeedTo = foodDonation.AvailableTo;
foodRequest.CreatedOn = DateTime.Now;
context.FoodRequests.Add(foodRequest);
}
}
context.SaveChanges();
}
}
}
| |
// ********************************************************************************************************
// Product Name: DotSpatial.Symbology.dll
// Description: The core libraries for the DotSpatial project.
//
// ********************************************************************************************************
// The contents of this file are subject to the MIT License (MIT)
// you may not use this file except in compliance with the License. You may obtain a copy of the License at
// http://dotspatial.codeplex.com/license
//
// Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF
// ANY KIND, either expressed or implied. See the License for the specific language governing rights and
// limitations under the License.
//
// The Original Code is from MapWindow.dll version 6.0
//
// The Initial Developer of this Original Code is Ted Dunsford. Created 2/20/2008 3:42:21 PM
//
// Contributor(s): (Open source contributors should list themselves and their modifications here).
//
// ********************************************************************************************************
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using DotSpatial.Data;
using DotSpatial.Projections;
using DotSpatial.Serialization;
namespace DotSpatial.Symbology
{
/// <summary>
/// A raster layer describes using a single raster, and the primary application will be using this as a texture.
/// </summary>
public class RasterLayer : Layer, IRasterLayer
{
#region Fields
[Serialize("Symbolizer", ConstructorArgumentIndex = 1)]
private IRasterSymbolizer _symbolizer;
private IGetBitmap _bitmapGetter;
/// <summary>
/// Gets or sets maximum number of cells which can be stored in memory.
/// By default it is 8000 * 8000.
/// </summary>
public static int MaxCellsInMemory = 8000 * 8000;
#endregion
#region Constructors
/// <summary>
/// Opens the specified fileName using the layer manager.
/// </summary>
/// <param name="fileName"></param>
/// <param name="symbolizer"></param>
public RasterLayer(string fileName, IRasterSymbolizer symbolizer)
{
DataSet = DataManager.DefaultDataManager.OpenRaster(fileName);
Symbolizer = symbolizer;
}
/// <summary>
/// Opens the specified fileName and automatically creates a raster that can be used by this raster layer.
/// </summary>
/// <param name="fileName">The string fileName to use in order to open the file</param>
/// <param name="inProgressHandler">The progress handler to show progress messages</param>
public RasterLayer(string fileName, IProgressHandler inProgressHandler)
: base(inProgressHandler)
{
DataSet = DataManager.DefaultDataManager.OpenRaster(fileName, true, inProgressHandler);
Symbolizer = new RasterSymbolizer(this);
}
/// <summary>
/// Creates a new raster layer using the progress handler defined on the DefaultLayerManager
/// </summary>
/// <param name="raster">The raster to create this layer for</param>
public RasterLayer(IRaster raster)
{
DataSet = raster;
Symbolizer = new RasterSymbolizer(this);
}
/// <summary>
/// Creates a new instance of RasterLayer
/// </summary>
/// <param name="raster">The Raster</param>
/// <param name="inProgressHandler">The Progress handler for any status updates</param>
public RasterLayer(IRaster raster, IProgressHandler inProgressHandler)
: base(inProgressHandler)
{
DataSet = raster;
Symbolizer = new RasterSymbolizer(this);
}
#endregion
#region Methods
/// <summary>
/// This only updates the bitmap representation of the raster. It does not write to a file unless
/// the file is too large to fit in memory, in which case it will update the pyramid image.
/// </summary>
public void WriteBitmap()
{
WriteBitmap(ProgressHandler);
}
/// <summary>
/// This only updates the bitmap representation of this raster. This can be overridden, but currently
/// uses the default implementation.
/// </summary>
/// <param name="progressHandler">An implementation of IProgressHandler to receive status messages</param>
public virtual void WriteBitmap(IProgressHandler progressHandler)
{
DefaultWriteBitmap(progressHandler);
}
/// <summary>
/// Creates a bmp texture and saves it to the specified fileName.
/// </summary>
/// <param name="fileName">The string fileName to write to</param>
/// <param name="bandType">The color band type.</param>
public void ExportBitmap(string fileName, ImageBandType bandType)
{
ExportBitmap(fileName, DataSet.ProgressHandler, bandType);
}
/// <summary>
/// Creates a new filename and saves the content from the current BitmapGetter to the
/// file format. This relies on the DataManager and will only be successful for
/// formats supported by the write format possibility. This will not update this raster
/// </summary>
/// <param name="fileName">The string fileName to write to</param>
/// <param name="progressHandler">The progress handler for creating a new bitmap.</param>
/// <param name="bandType">The band type ot use.</param>
public void ExportBitmap(string fileName, IProgressHandler progressHandler, ImageBandType bandType)
{
int rows = DataSet.NumRowsInFile;
int cols = DataSet.NumColumnsInFile;
IImageData result = DataManager.DefaultDataManager.CreateImage(fileName, rows, cols, false, progressHandler, bandType);
int numBlocks = 1;
const int maxRC = 8000 * 8000;
if (rows * cols > maxRC)
{
numBlocks = Convert.ToInt32(Math.Ceiling(maxRC / (double)cols));
}
int blockRows = maxRC / cols;
ProjectionHelper ph = new ProjectionHelper(DataSet.Extent, new Rectangle(0, 0, cols, rows));
for (int iblock = 0; iblock < numBlocks; iblock++)
{
int rowCount = blockRows;
if (iblock == numBlocks - 1) rowCount = rows - blockRows * iblock;
Rectangle r = new Rectangle(0, iblock * blockRows, cols, rowCount);
Bitmap block = BitmapGetter.GetBitmap(ph.PixelToProj(r), r);
result.WriteBlock(block, 0, iblock * blockRows);
}
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing)
{
BitmapGetter = null;
RasterLayerActions = null;
Symbolizer = null;
}
base.Dispose(disposing);
}
/// <summary>
/// Render the full raster block by block, and then save the values to the pyramid raster.
/// This will probably be nasty and time consuming, but what can you do.
/// </summary>
/// <param name="pyrFile"></param>
/// <param name="progressHandler"></param>
/// <returns></returns>
public IImageData CreatePyramidImage(string pyrFile, IProgressHandler progressHandler)
{
PyramidImage py = new PyramidImage(pyrFile, DataSet.Bounds);
int width = DataSet.Bounds.NumColumns;
int blockHeight = 32000000 / width;
if (blockHeight > DataSet.Bounds.NumRows) blockHeight = DataSet.Bounds.NumRows;
int numBlocks = (int)Math.Ceiling(DataSet.Bounds.NumRows / (double)blockHeight);
int count = DataSet.NumRows;
if (_symbolizer.ShadedRelief.IsUsed)
{
count = count * 2;
}
ProgressMeter pm = new ProgressMeter(progressHandler, "Creating Pyramids", count);
PerformanceCounter pcRemaining = new PerformanceCounter("Memory", "Available Bytes");
Process proc = Process.GetCurrentProcess();
long mem;
long freeRAM;
for (int j = 0; j < numBlocks; j++)
{
int h = blockHeight;
if (j == numBlocks - 1)
{
h = DataSet.Bounds.NumRows - j * blockHeight;
}
mem = proc.PrivateMemorySize64 / 1000000;
freeRAM = Convert.ToInt64(pcRemaining.NextValue()) / 1000000;
Debug.WriteLine("Memory before: " + mem + ", " + freeRAM + " remaining.");
pm.BaseMessage = "Reading from Raster";
pm.SendProgress();
using (IRaster r = DataSet.ReadBlock(0, j * blockHeight, width, h))
{
byte[] vals = new byte[h * 4 * width];
r.DrawToBitmap(Symbolizer, vals, width * 4, pm);
pm.BaseMessage = "Writing to Pyramids";
pm.SendProgress();
py.WriteWindow(vals, j * blockHeight, 0, h, width, 0);
Symbolizer.HillShade = null;
}
mem = proc.PrivateMemorySize64 / 1000000;
freeRAM = Convert.ToInt64(pcRemaining.NextValue()) / 1000000;
Debug.WriteLine("Memory after: " + mem + "Mb | " + freeRAM + " remaining Mb.");
}
pm.Reset();
py.ProgressHandler = ProgressHandler;
py.CreatePyramids();
py.WriteHeader(pyrFile);
return py;
}
/// <summary>
/// This does not have to be used to work, but provides a default implementation for writing bitmap,
/// and will be used by the MapRasterLayer class during file creation.
/// </summary>
/// <param name="progressHandler"></param>
protected void DefaultWriteBitmap(IProgressHandler progressHandler)
{
if ((long)DataSet.NumRowsInFile * DataSet.NumColumnsInFile > MaxCellsInMemory)
{
// For huge images, assume that GDAL or something was needed anyway,
// and we would rather avoid having to re-create the pyramids if there is any chance
// that the old values will work ok.
string pyrFile = Path.ChangeExtension(DataSet.Filename, ".mwi");
BitmapGetter = CreatePyramidImage(pyrFile, progressHandler);
OnItemChanged(this);
return;
}
Bitmap bmp = new Bitmap(DataSet.NumColumns, DataSet.NumRows, PixelFormat.Format32bppArgb);
if (_symbolizer.DrapeVectorLayers == false)
{
// Generate the colorscheme, modified by hillshading if that hillshading is used all in one pass
DataSet.DrawToBitmap(Symbolizer, bmp, progressHandler);
}
else
{
// work backwards. when we get to this layer do the colorscheme.
// First, use this raster and its colorscheme to drop the background
DataSet.PaintColorSchemeToBitmap(Symbolizer, bmp, progressHandler);
// Set up a graphics object with a transformation pre-set so drawing a geographic coordinate
// will draw to the correct location on the bitmap
Graphics g = Graphics.FromImage(bmp);
g.SmoothingMode = SmoothingMode.AntiAlias;
Extent extents = DataSet.Extent;
Rectangle target = new Rectangle(0, 0, bmp.Width, bmp.Height);
ImageProjection ip = new ImageProjection(extents, target);
// Cycle through each layer, and as long as it is not this layer, draw the bmp
foreach (ILegendItem layer in GetParentItem().LegendItems)
{
// Temporarily I am only interested in doing this for vector datasets
IFeatureLayer fl = layer as IFeatureLayer;
if (fl == null) continue;
fl.DrawSnapShot(g, ip);
}
if (Symbolizer.ShadedRelief.IsUsed)
{
// After we have drawn the underlying texture, apply a hillshade if it is requested
Symbolizer.PaintShadingToBitmap(bmp, progressHandler);
}
}
InRamImage image = new InRamImage(bmp);
image.Bounds = DataSet.Bounds.Copy();
BitmapGetter = image;
Symbolizer.Validate();
OnInvalidate(this, EventArgs.Empty);
OnItemChanged();
}
/// <summary>
/// Handles the situation for exporting the layer as a new source.
/// </summary>
protected override void OnExportData()
{
var rla = RasterLayerActions;
if (rla != null)
{
rla.ExportData(DataSet);
}
}
#endregion
#region properties
/// <summary>
/// Gets or sets custom actions for RasterLayer
/// </summary>
[Browsable(false)]
public IRasterLayerActions RasterLayerActions { get; set; }
/// <summary>
/// Gets or sets the boundaries of the raster.
/// </summary>
/// <remarks>
/// [Editor(typeof(Forms.PropertyGridEditor), typeof(UITypeEditor))]
/// [TypeConverter(typeof(Forms.GeneralTypeConverter))]
/// </remarks>
[Category("Bounds")]
[Description("Shows more detail about the geographic position of the raster.")]
public virtual IRasterBounds Bounds
{
get
{
if (DataSet != null) return DataSet.Bounds;
return null;
}
set
{
if (DataSet != null)
DataSet.Bounds = value;
if (BitmapGetter != null)
BitmapGetter.Bounds = value;
}
}
/// <summary>
/// This is what the raster layer uses to retrieve a bitmap representing the specified
/// extent. This could later be redesigned to generate the bitmap on the fly, but I think
/// that that would be slow, so caching is probably better.
/// </summary>
[Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public IGetBitmap BitmapGetter
{
get { return _bitmapGetter; }
set
{
if (value == _bitmapGetter) return;
if (_bitmapGetter != null) _bitmapGetter.Dispose(); // Dispose previous bitmapGetter to avoid memory leaks
_bitmapGetter = value;
}
}
/// <summary>
/// Gets the geographic height of the cells for this raster (North-South)
/// </summary>
[Category("Raster Properties"), Description("The geographic width of each cell in this raster.")]
public virtual double CellHeight
{
get
{
if (DataSet != null) return DataSet.CellHeight;
return 0;
}
}
/// <summary>
/// Gets the geographic width of the cells for this raster (East-West)
/// </summary>
[Category("Raster Properties"), Description("The geographic width of each cell in this raster.")]
public virtual double CellWidth
{
get
{
if (DataSet != null) return DataSet.CellWidth;
return 0;
}
}
/// <summary>
/// Gets or sets whether this should appear as checked in the legend. This is also how the
/// layer will
/// </summary>
[Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public override bool Checked
{
get
{
if (_symbolizer == null) return true;
return _symbolizer.IsVisible;
}
set
{
if (_symbolizer == null) return;
if (value != _symbolizer.IsVisible)
{
IsVisible = value;
}
}
}
/// <summary>
/// Gets the data type of the values in this raster.
/// </summary>
[Category("Raster Properties"), Description("The numeric data type of the values in this raster.")]
public Type DataType
{
get
{
if (DataSet != null) return DataSet.DataType;
return null;
}
}
/// <summary>
/// Gets the eastern boundary of this raster.
/// </summary>
[Category("Bounds"), Description("The East boundary of this raster.")]
public virtual double East
{
get
{
return (DataSet != null && DataSet.Bounds != null) ? DataSet.Bounds.Right() : 0;
}
}
/// <summary>
/// This is a conversion factor that is required in order to convert the elevation units into the same units as the geospatial projection for the latitude and logitude values of the grid.
/// </summary>
[DisplayName(@"Elevation Factor"), Category("Symbology"), Description("This is a conversion factor that is required in order to convert the elevation units into the same units as the geospatial projection for the latitude and logitude values of the grid.")]
public virtual float ElevationFactor
{
get
{
if (_symbolizer != null) return _symbolizer.ElevationFactor;
return 0f;
}
set
{
if (_symbolizer == null) return;
_symbolizer.ElevationFactor = value;
}
}
/// <summary>
/// Obtains an envelope
/// </summary>
/// <returns></returns>
[Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public override Extent Extent
{
get
{
if (DataSet != null)
return DataSet.Extent;
return null;
}
}
/// <summary>
/// Gets the exaggeration beyond normal elevation values. A value of 1 is normal elevation,
/// a value of 0 would be flat, while a value of 2 would be twice the normal elevation.
/// This applies to the three-dimensional rendering and is not related to the shaded relief pattern
/// created by the texture.
/// </summary>
[DisplayName(@"Extrusion")]
[Category("Symbology")]
[Description("the exaggeration beyond normal elevation values. A value of 1 is normal elevation, a value of 0 would be flat, while a value of 2 would be twice the normal elevation. This applies to the three-dimensional rendering and is not related to the shaded relief pattern created by the texture.")]
public virtual float Extrusion
{
get
{
if (_symbolizer != null) return _symbolizer.Extrusion;
return 0f;
}
set
{
if (_symbolizer == null) return;
_symbolizer.Extrusion = value;
}
}
/// <summary>
/// Gets the fileName where this raster is saved.
/// </summary>
[Category("Raster Properties")]
[Description("The fileName of this raster.")]
[Serialize("Filename", ConstructorArgumentIndex = 0)]
public virtual string Filename
{
get
{
if (DataSet != null) return DataSet.Filename;
return "No Raster Specified";
}
}
/// <summary>
/// If this is false, then the drawing function will not render anything.
/// Warning! This will also prevent any execution of calculations that take place
/// as part of the drawing methods and will also abort the drawing methods of any
/// sub-members to this IRenderable.
/// </summary>
[Category("Symbology")]
[DisplayName(@"Visible")]
[Description("Controls whether or not this layer will be drawn.")]
public override bool IsVisible
{
get
{
if (_symbolizer != null) return _symbolizer.IsVisible;
return false;
}
set
{
if (_symbolizer == null) return;
_symbolizer.IsVisible = value;
OnVisibleChanged(this, EventArgs.Empty);
}
}
/// <summary>
/// Gets or sets the complete list of legend items contained within this legend item
/// </summary>
[Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public override IEnumerable<ILegendItem> LegendItems
{
get
{
if (_symbolizer == null) return null;
return _symbolizer.Scheme.Categories.Cast<ILegendItem>();
}
}
/// <summary>
/// The text that will appear in the legend
/// </summary>
[Category("Appearance"), DisplayName(@"Caption"), Description(" The text that will appear in the legend")]
public override string LegendText
{
get
{
if (base.LegendText == null && DataSet != null)
base.LegendText = DataSet.Name;
return base.LegendText;
}
set { base.LegendText = value; }
}
/// <summary>
/// Gets the maximum value of this raster. If this is an elevation raster, this is also the top.
/// </summary>
[Category("Raster Properties"),
Description("The maximum value of this raster. If this is an elevation raster, this is also the top.")]
public virtual double Maximum
{
get
{
if (DataSet != null) return DataSet.Maximum;
return 0;
}
}
/// <summary>
/// Gets the minimum value of this raster. If this is an elevation raster, this is also the bottom.
/// </summary>
[Category("Raster Properties"),
Description("The minimum value of this raster. If this is an elevation raster, this is also the bottom.")]
public virtual double Minimum
{
get
{
if (DataSet != null) return DataSet.Minimum;
return 0;
}
}
/// <summary>
/// Gets the value that is used when no actual data exists for the specified location.
/// </summary>
[Category("Raster Properties"),
Description("The value that is used when no actual data exists for the specified location.")]
public virtual double NoDataValue
{
get
{
if (DataSet != null) return DataSet.NoDataValue;
return 0;
}
}
/// <summary>
/// Gets the northern boundary of this raster.
/// </summary>
[Category("Bounds"), Description("The North boundary of this raster.")]
public virtual double North
{
get
{
if (DataSet != null && DataSet.Bounds != null)
return DataSet.Bounds.Top();
return 0;
}
}
/// <summary>
/// Gets the number of bands in this raster.
/// </summary>
[DisplayName(@"Number of Bands"), Category("Raster Properties"),
Description("Gets the number of bands in this raster.")]
public virtual int NumBands
{
get
{
if (DataSet != null) return DataSet.NumBands;
return 0;
}
}
/// <summary>
/// Gets the number of columns in this raster.
/// </summary>
[DisplayName(@"Number of Columns"), Category("Raster Properties"),
Description("Gets the number of columns in this raster.")]
public virtual int NumColumns
{
get
{
if (DataSet != null) return DataSet.NumColumns;
return 0;
}
}
/// <summary>
/// Gets the number of rows in this raster.
/// </summary>
[DisplayName(@"Number of Rows"), Category("Raster Properties"),
Description("Gets the number of rows in this raster.")]
public virtual int NumRows
{
get
{
if (DataSet != null) return DataSet.NumRows;
return 0;
}
}
/// <summary>
/// Gets or sets the underlying dataset
/// </summary>
/// <remarks>
/// [TypeConverter(typeof(Forms.GeneralTypeConverter))]
/// [Editor(typeof(Forms.PropertyGridEditor), typeof(UITypeEditor))]
/// </remarks>
[Category("Data")]
[DisplayName(@"Raster Properties")]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
[Description("This gives access to more comprehensive information about the underlying data.")]
[ShallowCopy]
[Browsable(false)]
public new IRaster DataSet
{
get { return base.DataSet as IRaster; }
set { base.DataSet = value; }
}
/// <summary>
/// Gets or sets the collection of symbolzier properties to use for this raster.
/// [Editor(typeof(Forms.RasterColorSchemeEditor), typeof(UITypeEditor))]
/// [TypeConverter(typeof(Forms.GeneralTypeConverter))]
/// </summary>
[Category("Symbology")]
[DisplayName(@"Color Scheme")]
[Browsable(false)]
[ShallowCopy]
public IRasterSymbolizer Symbolizer
{
get { return _symbolizer; }
set
{
if (_symbolizer == value) return;
if (_symbolizer != null) _symbolizer.ColorSchemeUpdated -= _symbolizer_SymbologyUpdated;
_symbolizer = value;
if (_symbolizer == null) return;
_symbolizer.ParentLayer = this;
_symbolizer.Scheme.SetParentItem(this);
_symbolizer.ColorSchemeUpdated += _symbolizer_SymbologyUpdated;
}
}
/// <summary>
/// Gets the southern boundary of this raster.
/// </summary>
[Category("Bounds"), Description("The South boundary of this raster.")]
public virtual double South
{
get
{
if (DataSet != null && DataSet.Bounds != null)
return DataSet.Bounds.Bottom();
return 0;
}
}
/// <summary>
/// Gets the western boundary of this raster.
/// </summary>
[Category("Bounds"), Description("The West boundary of this raster.")]
public virtual double West
{
get
{
if (DataSet != null && DataSet.Bounds != null)
return DataSet.Bounds.Left();
return 0;
}
}
#endregion
/// <summary>
/// Occurs when this member should raise the shared event to show the property dialog for this raster layer.
/// </summary>
/// <param name="e"></param>
protected override void OnShowProperties(HandledEventArgs e)
{
var rla = RasterLayerActions;
if (rla != null)
rla.ShowProperties(this);
e.Handled = true;
}
#region Event Handlers
/// <summary>
/// Reprojects the dataset for this layer.
/// </summary>
/// <param name="targetProjection">The target projection to use.</param>
public override void Reproject(ProjectionInfo targetProjection)
{
if (DataSet != null)
{
DataSet.Reproject(targetProjection);
if (BitmapGetter != null)
{
double[] aff = new double[6];
Array.Copy(DataSet.Bounds.AffineCoefficients, aff, 6);
BitmapGetter.Bounds.AffineCoefficients = aff;
}
}
}
private void _symbolizer_SymbologyUpdated(object sender, EventArgs e)
{
OnItemChanged();
}
#endregion
#region Nested Class : ProjectionHelper
private class ProjectionHelper : IProj
{
/// <summary>
/// Initializes a new instance of the ProjectionHelper class.
/// </summary>
/// <param name="geographicExtents">The geographic extents to project to and from.</param>
/// <param name="viewRectangle">The view rectangle in pixels to transform with.</param>
public ProjectionHelper(Extent geographicExtents, Rectangle viewRectangle)
{
GeographicExtents = geographicExtents;
ImageRectangle = viewRectangle;
}
/// <summary>
/// Gets or sets the geographic extent to use.
/// </summary>
public Extent GeographicExtents { get; set; }
/// <summary>
/// Gets or sets the rectangular pixel region to use.
/// </summary>
public Rectangle ImageRectangle { get; set; }
}
#endregion
}
}
| |
// Copyright (c) DotSpatial Team. All rights reserved.
// Licensed under the MIT license. See License.txt file in the project root for full license information.
using System;
using DotSpatial.Serialization;
namespace DotSpatial.Symbology
{
/// <summary>
/// Numeric range using doubles.
/// </summary>
public class Range
{
#region Fields
#endregion
#region Constructors
/// <summary>
/// Initializes a new instance of the <see cref="Range"/> class with undefined interval.
/// </summary>
public Range()
{
Minimum = null;
Maximum = null;
}
/// <summary>
/// Initializes a new instance of the <see cref="Range"/> class.
/// </summary>
/// <param name="value1">Either bound of the range.</param>
/// <param name="value2">The other bound of the range.</param>
public Range(double? value1, double? value2)
{
Minimum = value1;
Maximum = value2;
FixOrder();
}
/// <summary>
/// Initializes a new instance of the <see cref="Range"/> class where both the minimum and maximum are the
/// same value and both are inclusive.
/// </summary>
/// <param name="value">Value for Minimum and Maximum.</param>
public Range(double value)
{
Minimum = value;
Maximum = value;
MinIsInclusive = true;
MaxIsInclusive = true;
}
/// <summary>
/// Initializes a new instance of the <see cref="Range"/> class.
/// </summary>
/// <param name="expression">A string expression that can be two separate numbers separated by a dash.</param>
public Range(string expression)
{
string exp = expression ?? "-";
if (exp.Contains(">=") || exp.Contains(">"))
{
MinIsInclusive = exp.Contains(">=");
Maximum = null;
double min;
if (double.TryParse(exp.Replace(">=", string.Empty).Replace(">", string.Empty), out min))
{
Minimum = min;
}
}
else if (exp.Contains("<=") || exp.Contains("<"))
{
MaxIsInclusive = exp.Contains("<=");
Minimum = null;
double max;
if (double.TryParse(exp.Replace("<=", string.Empty).Replace("<", string.Empty), out max))
{
Maximum = max;
}
}
else if (exp.Contains("-"))
{
// The default is to actually include the maximums, but not the minimums.
MaxIsInclusive = true;
// - can mean negative or the break. A minus before any numbers means
// it is negative. Two dashes in the middle means the second number is negative.
// If there is only one dash, treat it like a break, not a negative.
int numDashes = CountOf(exp, "-");
string[] args = exp.Split('-');
bool minNegative = false;
bool maxNegative = false;
int minIndex = 0;
int maxIndex = 1;
if (numDashes > 1)
{
// -10 - 20 | 10 - -20 | -20 - -10
if (args[0] == string.Empty)
{
// -10 - 20
minNegative = true;
minIndex = 1;
maxIndex = 2;
if (numDashes > 2)
{
// -20 - -10
maxNegative = true;
maxIndex = 3;
}
}
else
{
// the range could be out of order, like 10 - -20.
maxNegative = true;
maxIndex = 2;
}
}
double min;
double max;
if (double.TryParse(args[minIndex], out min))
{
Minimum = minNegative ? -min : min;
}
if (double.TryParse(args[maxIndex], out max))
{
Maximum = maxNegative ? -max : max;
}
FixOrder();
}
}
#endregion
#region Properties
/// <summary>
/// Gets or sets the maximum value. If this is null, the upper range is unbounded.
/// </summary>
[Serialize("Maximum")]
public double? Maximum { get; set; }
/// <summary>
/// Gets or sets a value indicating whether the upper bounds includes the maximum value.
/// </summary>
[Serialize("MaxIsInclusive")]
public bool MaxIsInclusive { get; set; }
/// <summary>
/// Gets or sets the Minimum value. If this is null, the lower range is unbounded.
/// </summary>
[Serialize("Minimum")]
public double? Minimum { get; set; }
/// <summary>
/// Gets or sets a value indicating whether the lower bounds includes the minimum value.
/// </summary>
[Serialize("MinIsInclusive")]
public bool MinIsInclusive { get; set; }
#endregion
#region Methods
/// <summary>
/// Tests to determine if this range contains the specified double value.
/// </summary>
/// <param name="value">the double value to test.</param>
/// <returns>Boolean, true if the value is within the current bounds.</returns>
public bool Contains(double value)
{
if (Minimum == null && Maximum == null) return true;
if (Minimum == null)
{
return MaxIsInclusive ? (value <= Maximum) : (value < Maximum);
}
if (Maximum == null)
{
return MinIsInclusive ? (value >= Minimum) : (value > Minimum);
}
if (MaxIsInclusive && MinIsInclusive)
{
return value >= Minimum && value <= Maximum;
}
if (MaxIsInclusive)
{
return value > Minimum && value <= Maximum;
}
if (MinIsInclusive)
{
return value >= Minimum && value < Maximum;
}
return value > Minimum && value < Maximum;
}
/// <summary>
/// Generates a valid SQL query expression for this range, using the field string
/// as the member being compared. The field string should already be bound in
/// brackets, or put together as a normal composit like "[males]/[pop1990]".
/// </summary>
/// <param name="field">The field name to build into an expression. This should already be wrapped in square brackets.</param>
/// <returns>The string SQL query expression.</returns>
public string ToExpression(string field)
{
if (Minimum == null && Maximum == null) return string.Empty;
string maxExp = MaxIsInclusive ? field + " <= " + Maximum : field + " < " + Maximum;
string minExp = MinIsInclusive ? field + " >= " + Minimum : field + " > " + Minimum;
if (Minimum == null) return maxExp;
if (Maximum == null) return minExp;
return minExp + " AND " + maxExp;
}
/// <summary>
/// Expresses this range in string form. By default, ranges include the maximum,
/// and exclude the minimum. A null value for one expression will result in a
/// a semi-unbounded range using the greater than or less than symbols. A null
/// expression for both values is completely unbounded and will result in a string
/// that reads like [All Values].
/// </summary>
/// <returns>A string representing the range.</returns>
public override string ToString()
{
if (Minimum == null && Maximum == null)
{
return "[All Values]";
}
if (Minimum == null)
{
return MaxIsInclusive ? "<= " + Maximum : "< " + Maximum;
}
if (Maximum == null)
{
return MinIsInclusive ? ">= " + Minimum : "> " + Minimum;
}
return Minimum + " - " + Maximum;
}
/// <summary>
/// This is a slightly more complex specification where the numeric formatting
/// controls how the generated string will appear.
/// </summary>
/// <param name="method">The interval snap method.</param>
/// <param name="digits">This is only used for rounding or significant figures, but controls those options.</param>
/// <returns>A string equivalent of this range, but using a number format.</returns>
public string ToString(IntervalSnapMethod method, int digits)
{
if (Minimum == null && Maximum == null)
{
return "[All Values]";
}
if (Minimum == null)
{
string max = Format(Maximum.Value, method, digits);
return MaxIsInclusive ? "<= " + max : "< " + max;
}
if (Maximum == null)
{
string min = Format(Minimum.Value, method, digits);
return MinIsInclusive ? ">= " + min : "> " + min;
}
return Format(Minimum.Value, method, digits) + " - " + Format(Maximum.Value, method, digits);
}
private static int CountOf(string source, string instance)
{
int iStart = 0;
int count = 0;
while ((iStart = source.IndexOf(instance, iStart + 1)) > 0)
{
count++;
}
return count;
}
private static string Format(double value, IntervalSnapMethod method, int digits)
{
if (method == IntervalSnapMethod.None)
{
return value.ToString();
}
if (method == IntervalSnapMethod.DataValue)
{
return value.ToString();
}
if (method == IntervalSnapMethod.Rounding)
{
return value.ToString("N" + digits);
}
if (method == IntervalSnapMethod.SignificantFigures)
{
int dig = (int)Math.Ceiling(Math.Log10(Math.Abs(value)));
dig = digits - dig;
if (dig < 0) dig = 0;
if (dig > 10)
{
return value.ToString("E" + digits);
}
return value.ToString("N" + dig);
}
return value.ToString("N");
}
/// <summary>
/// If the minimum and maximum are out of order, this reverses them.
/// </summary>
private void FixOrder()
{
if (Maximum == null || Minimum == null || Maximum.Value >= Minimum.Value) return;
double? temp = Maximum;
Maximum = Minimum;
Minimum = temp;
}
#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.Reflection;
using System.Diagnostics;
using System.Collections.Generic;
using System.Reflection.Runtime.General;
using System.Reflection.Runtime.TypeInfos;
using System.Reflection.Runtime.ParameterInfos;
using Internal.Reflection.Core.Execution;
using Internal.Reflection.Tracing;
using Internal.Metadata.NativeFormat;
namespace System.Reflection.Runtime.MethodInfos
{
//
// The runtime's implementation of non-constructor MethodInfo's that represent a method definition.
//
internal sealed partial class RuntimeNamedMethodInfo : RuntimeMethodInfo
{
//
// methodHandle - the "tkMethodDef" that identifies the method.
// definingType - the "tkTypeDef" that defined the method (this is where you get the metadata reader that created methodHandle.)
// contextType - the type that supplies the type context (i.e. substitutions for generic parameters.) Though you
// get your raw information from "definingType", you report "contextType" as your DeclaringType property.
//
// For example:
//
// typeof(Foo<>).GetTypeInfo().DeclaredMembers
//
// The definingType and contextType are both Foo<>
//
// typeof(Foo<int,String>).GetTypeInfo().DeclaredMembers
//
// The definingType is "Foo<,>"
// The contextType is "Foo<int,String>"
//
// We don't report any DeclaredMembers for arrays or generic parameters so those don't apply.
//
private RuntimeNamedMethodInfo(MethodHandle methodHandle, RuntimeNamedTypeInfo definingTypeInfo, RuntimeTypeInfo contextTypeInfo)
: base()
{
_common = new RuntimeMethodCommon(methodHandle, definingTypeInfo, contextTypeInfo);
}
public sealed override MethodAttributes Attributes
{
get
{
return _common.Attributes;
}
}
public sealed override CallingConventions CallingConvention
{
get
{
return _common.CallingConvention;
}
}
public sealed override IEnumerable<CustomAttributeData> CustomAttributes
{
get
{
#if ENABLE_REFLECTION_TRACE
if (ReflectionTrace.Enabled)
ReflectionTrace.MethodBase_CustomAttributes(this);
#endif
return _common.CustomAttributes;
}
}
public sealed override MethodInfo GetGenericMethodDefinition()
{
if (IsGenericMethodDefinition)
return this;
throw new InvalidOperationException();
}
public sealed override bool IsGenericMethod
{
get
{
return IsGenericMethodDefinition;
}
}
public sealed override bool IsGenericMethodDefinition
{
get
{
Method method = _common.MethodHandle.GetMethod(_common.Reader);
return method.GenericParameters.GetEnumerator().MoveNext();
}
}
public sealed override MethodInfo MakeGenericMethod(params Type[] typeArguments)
{
#if ENABLE_REFLECTION_TRACE
if (ReflectionTrace.Enabled)
ReflectionTrace.MethodInfo_MakeGenericMethod(this, typeArguments);
#endif
if (typeArguments == null)
throw new ArgumentNullException(nameof(typeArguments));
if (GenericTypeParameters.Length == 0)
throw new InvalidOperationException(SR.Format(SR.Arg_NotGenericMethodDefinition, this));
RuntimeTypeInfo[] genericTypeArguments = new RuntimeTypeInfo[typeArguments.Length];
for (int i = 0; i < typeArguments.Length; i++)
{
if (typeArguments[i] == null)
throw new ArgumentNullException();
if (!typeArguments[i].IsRuntimeImplemented())
throw new ArgumentException(SR.Format(SR.Reflection_CustomReflectionObjectsNotSupported, typeArguments[i]), "typeArguments[" + i + "]"); // Not a runtime type.
genericTypeArguments[i] = typeArguments[i].CastToRuntimeTypeInfo();
}
if (typeArguments.Length != GenericTypeParameters.Length)
throw new ArgumentException(SR.Format(SR.Argument_NotEnoughGenArguments, typeArguments.Length, GenericTypeParameters.Length));
RuntimeMethodInfo methodInfo = (RuntimeMethodInfo)RuntimeConstructedGenericMethodInfo.GetRuntimeConstructedGenericMethodInfo(this, genericTypeArguments);
MethodInvoker methodInvoker = methodInfo.MethodInvoker; // For compatibility with other Make* apis, trigger any MissingMetadataExceptions now rather than later.
return methodInfo;
}
public sealed override MethodImplAttributes MethodImplementationFlags
{
get
{
return _common.MethodImplementationFlags;
}
}
public sealed override Module Module
{
get
{
return _common.Module;
}
}
public sealed override String ToString()
{
return ComputeToString(this);
}
public sealed override bool Equals(Object obj)
{
RuntimeNamedMethodInfo other = obj as RuntimeNamedMethodInfo;
if (other == null)
return false;
return _common.Equals(other._common);
}
public sealed override int GetHashCode()
{
return _common.GetHashCode();
}
internal String ComputeToString(RuntimeMethodInfo contextMethod)
{
return _common.ComputeToString(contextMethod, contextMethod.RuntimeGenericArgumentsOrParameters);
}
internal MethodHandle Handle
{
get
{
return _common.MethodHandle;
}
}
internal MetadataReader Reader
{
get
{
return _common.Reader;
}
}
internal sealed override RuntimeTypeInfo[] RuntimeGenericArgumentsOrParameters
{
get
{
return this.GenericTypeParameters;
}
}
internal sealed override RuntimeParameterInfo[] GetRuntimeParametersAndReturn(RuntimeMethodInfo contextMethod)
{
return _common.GetRuntimeParametersAndReturn(contextMethod, contextMethod.RuntimeGenericArgumentsOrParameters);
}
internal sealed override RuntimeTypeInfo RuntimeDeclaringType
{
get
{
return _common.DeclaringType;
}
}
internal sealed override String RuntimeName
{
get
{
return _common.Name;
}
}
private RuntimeTypeInfo[] GenericTypeParameters
{
get
{
Method method = _common.MethodHandle.GetMethod(_common.Reader);
int genericParametersCount = method.GenericParameters.Count;
if (genericParametersCount == 0)
return Array.Empty<RuntimeTypeInfo>();
RuntimeTypeInfo[] genericTypeParameters = new RuntimeTypeInfo[genericParametersCount];
int i = 0;
foreach (GenericParameterHandle genericParameterHandle in method.GenericParameters)
{
RuntimeNamedMethodInfo owningMethod = this;
if (DeclaringType.IsConstructedGenericType)
{
// Desktop compat: Constructed generic types and their generic type definitions share the same Type objects for method generic parameters.
RuntimeNamedTypeInfo genericTypeDefinition = DeclaringType.GetGenericTypeDefinition().CastToRuntimeNamedTypeInfo();
owningMethod = RuntimeNamedMethodInfo.GetRuntimeNamedMethodInfo(Handle, genericTypeDefinition, genericTypeDefinition);
}
RuntimeTypeInfo genericParameterType = RuntimeGenericParameterTypeInfoForMethods.GetRuntimeGenericParameterTypeInfoForMethods(owningMethod, owningMethod._common.Reader, genericParameterHandle);
genericTypeParameters[i++] = genericParameterType;
}
return genericTypeParameters;
}
}
protected sealed override MethodInvoker UncachedMethodInvoker
{
get
{
return ReflectionCoreExecution.ExecutionEnvironment.GetMethodInvoker(_common.Reader, _common.DeclaringType, _common.MethodHandle, Array.Empty<RuntimeTypeInfo>(), this);
}
}
private readonly RuntimeMethodCommon _common;
}
}
| |
// Copyright 2004-2011 Castle Project - http://www.castleproject.org/
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
namespace Castle.DynamicProxy.Contributors
{
using System;
using System.Collections.Generic;
using System.Reflection;
#if FEATURE_SERIALIZATION
using System.Runtime.Serialization;
#endif
using Castle.DynamicProxy.Generators.Emitters;
using Castle.DynamicProxy.Generators.Emitters.CodeBuilders;
using Castle.DynamicProxy.Generators.Emitters.SimpleAST;
using Castle.DynamicProxy.Internal;
using Castle.DynamicProxy.Tokens;
public class ClassProxyInstanceContributor : ProxyInstanceContributor
{
#if FEATURE_SERIALIZATION
private readonly bool delegateToBaseGetObjectData;
private readonly bool implementISerializable;
private ConstructorInfo serializationConstructor;
private readonly IList<FieldReference> serializedFields = new List<FieldReference>();
#endif
public ClassProxyInstanceContributor(Type targetType, IList<MethodInfo> methodsToSkip, Type[] interfaces,
string typeId)
: base(targetType, interfaces, typeId)
{
#if FEATURE_SERIALIZATION
if (targetType.IsSerializable)
{
implementISerializable = true;
delegateToBaseGetObjectData = VerifyIfBaseImplementsGetObjectData(targetType, methodsToSkip);
}
#endif
}
protected override Expression GetTargetReferenceExpression(ClassEmitter emitter)
{
return SelfReference.Self.ToExpression();
}
public override void Generate(ClassEmitter @class, ProxyGenerationOptions options)
{
var interceptors = @class.GetField("__interceptors");
#if FEATURE_SERIALIZATION
if (implementISerializable)
{
ImplementGetObjectData(@class);
Constructor(@class);
}
#endif
ImplementProxyTargetAccessor(@class, interceptors);
foreach (var attribute in targetType.GetNonInheritableAttributes())
{
@class.DefineCustomAttribute(attribute);
}
}
#if FEATURE_SERIALIZATION
protected override void AddAddValueInvocation(ArgumentReference serializationInfo, MethodEmitter getObjectData,
FieldReference field)
{
serializedFields.Add(field);
base.AddAddValueInvocation(serializationInfo, getObjectData, field);
}
protected override void CustomizeGetObjectData(AbstractCodeBuilder codebuilder, ArgumentReference serializationInfo,
ArgumentReference streamingContext, ClassEmitter emitter)
{
codebuilder.AddStatement(new ExpressionStatement(
new MethodInvocationExpression(
serializationInfo,
SerializationInfoMethods.AddValue_Bool,
new ConstReference("__delegateToBase").ToExpression(),
new ConstReference(delegateToBaseGetObjectData).
ToExpression())));
if (delegateToBaseGetObjectData == false)
{
EmitCustomGetObjectData(codebuilder, serializationInfo);
return;
}
EmitCallToBaseGetObjectData(codebuilder, serializationInfo, streamingContext);
}
private void EmitCustomGetObjectData(AbstractCodeBuilder codebuilder, ArgumentReference serializationInfo)
{
var members = codebuilder.DeclareLocal(typeof(MemberInfo[]));
var data = codebuilder.DeclareLocal(typeof(object[]));
var getSerializableMembers = new MethodInvocationExpression(
null,
FormatterServicesMethods.GetSerializableMembers,
new TypeTokenExpression(targetType));
codebuilder.AddStatement(new AssignStatement(members, getSerializableMembers));
// Sort to keep order on both serialize and deserialize side the same, c.f DYNPROXY-ISSUE-127
var callSort = new MethodInvocationExpression(
null,
TypeUtilMethods.Sort,
members.ToExpression());
codebuilder.AddStatement(new AssignStatement(members, callSort));
var getObjectData = new MethodInvocationExpression(
null,
FormatterServicesMethods.GetObjectData,
SelfReference.Self.ToExpression(),
members.ToExpression());
codebuilder.AddStatement(new AssignStatement(data, getObjectData));
var addValue = new MethodInvocationExpression(
serializationInfo,
SerializationInfoMethods.AddValue_Object,
new ConstReference("__data").ToExpression(),
data.ToExpression());
codebuilder.AddStatement(new ExpressionStatement(addValue));
}
private void EmitCallToBaseGetObjectData(AbstractCodeBuilder codebuilder, ArgumentReference serializationInfo,
ArgumentReference streamingContext)
{
var baseGetObjectData = targetType.GetMethod("GetObjectData",
new[] { typeof(SerializationInfo), typeof(StreamingContext) });
codebuilder.AddStatement(new ExpressionStatement(
new MethodInvocationExpression(baseGetObjectData,
serializationInfo.ToExpression(),
streamingContext.ToExpression())));
}
private void Constructor(ClassEmitter emitter)
{
if (!delegateToBaseGetObjectData)
{
return;
}
GenerateSerializationConstructor(emitter);
}
private void GenerateSerializationConstructor(ClassEmitter emitter)
{
var serializationInfo = new ArgumentReference(typeof(SerializationInfo));
var streamingContext = new ArgumentReference(typeof(StreamingContext));
var ctor = emitter.CreateConstructor(serializationInfo, streamingContext);
ctor.CodeBuilder.AddStatement(
new ConstructorInvocationStatement(serializationConstructor,
serializationInfo.ToExpression(),
streamingContext.ToExpression()));
foreach (var field in serializedFields)
{
var getValue = new MethodInvocationExpression(serializationInfo,
SerializationInfoMethods.GetValue,
new ConstReference(field.Reference.Name).ToExpression(),
new TypeTokenExpression(field.Reference.FieldType));
ctor.CodeBuilder.AddStatement(new AssignStatement(
field,
new ConvertExpression(field.Reference.FieldType,
typeof(object),
getValue)));
}
ctor.CodeBuilder.AddStatement(new ReturnStatement());
}
private bool VerifyIfBaseImplementsGetObjectData(Type baseType, IList<MethodInfo> methodsToSkip)
{
if (!typeof(ISerializable).IsAssignableFrom(baseType))
{
return false;
}
if (IsDelegate(baseType))
{
//working around bug in CLR which returns true for "does this type implement ISerializable" for delegates
return false;
}
// If base type implements ISerializable, we have to make sure
// the GetObjectData is marked as virtual
var getObjectDataMethod = baseType.GetInterfaceMap(typeof(ISerializable)).TargetMethods[0];
if (getObjectDataMethod.IsPrivate) //explicit interface implementation
{
return false;
}
if (!getObjectDataMethod.IsVirtual || getObjectDataMethod.IsFinal)
{
var message = String.Format("The type {0} implements ISerializable, but GetObjectData is not marked as virtual. " +
"Dynamic Proxy needs types implementing ISerializable to mark GetObjectData as virtual " +
"to ensure correct serialization process.",
baseType.FullName);
throw new ArgumentException(message);
}
methodsToSkip.Add(getObjectDataMethod);
serializationConstructor = baseType.GetConstructor(
BindingFlags.Instance | BindingFlags.Public |
BindingFlags.NonPublic,
null,
new[] { typeof(SerializationInfo), typeof(StreamingContext) },
null);
if (serializationConstructor == null)
{
var message = String.Format("The type {0} implements ISerializable, " +
"but failed to provide a deserialization constructor",
baseType.FullName);
throw new ArgumentException(message);
}
return true;
}
private bool IsDelegate(Type baseType)
{
return baseType.BaseType == typeof(MulticastDelegate);
}
#endif
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
// In the desktop version of the framework, this file is generated from ProviderBase\DbConnectionHelper.cs
// #line 1 "e:\\fxdata\\src\\ndp\\fx\\src\\data\\system\\data\\providerbase\\dbconnectionhelper.cs"
using System.Data.Common;
using System.Data.ProviderBase;
using System.Diagnostics;
using System.Threading;
using System.Transactions;
namespace System.Data.SqlClient
{
public sealed partial class SqlConnection : DbConnection
{
private static readonly DbConnectionFactory s_connectionFactory = SqlConnectionFactory.SingletonInstance;
private DbConnectionOptions _userConnectionOptions;
private DbConnectionPoolGroup _poolGroup;
private DbConnectionInternal _innerConnection;
private int _closeCount;
public SqlConnection() : base()
{
GC.SuppressFinalize(this);
_innerConnection = DbConnectionClosedNeverOpened.SingletonInstance;
}
internal int CloseCount
{
get
{
return _closeCount;
}
}
internal DbConnectionFactory ConnectionFactory
{
get
{
return s_connectionFactory;
}
}
internal DbConnectionOptions ConnectionOptions
{
get
{
System.Data.ProviderBase.DbConnectionPoolGroup poolGroup = PoolGroup;
return ((null != poolGroup) ? poolGroup.ConnectionOptions : null);
}
}
private string ConnectionString_Get()
{
bool hidePassword = InnerConnection.ShouldHidePassword;
DbConnectionOptions connectionOptions = UserConnectionOptions;
return ((null != connectionOptions) ? connectionOptions.UsersConnectionString(hidePassword) : "");
}
private void ConnectionString_Set(DbConnectionPoolKey key)
{
DbConnectionOptions connectionOptions = null;
System.Data.ProviderBase.DbConnectionPoolGroup poolGroup = ConnectionFactory.GetConnectionPoolGroup(key, null, ref connectionOptions);
DbConnectionInternal connectionInternal = InnerConnection;
bool flag = connectionInternal.AllowSetConnectionString;
if (flag)
{
flag = SetInnerConnectionFrom(DbConnectionClosedBusy.SingletonInstance, connectionInternal);
if (flag)
{
_userConnectionOptions = connectionOptions;
_poolGroup = poolGroup;
_innerConnection = DbConnectionClosedNeverOpened.SingletonInstance;
}
}
if (!flag)
{
throw ADP.OpenConnectionPropertySet(nameof(ConnectionString), connectionInternal.State);
}
}
internal DbConnectionInternal InnerConnection
{
get
{
return _innerConnection;
}
}
internal System.Data.ProviderBase.DbConnectionPoolGroup PoolGroup
{
get
{
return _poolGroup;
}
set
{
Debug.Assert(null != value, "null poolGroup");
_poolGroup = value;
}
}
internal DbConnectionOptions UserConnectionOptions
{
get
{
return _userConnectionOptions;
}
}
internal void Abort(Exception e)
{
DbConnectionInternal innerConnection = _innerConnection;
if (ConnectionState.Open == innerConnection.State)
{
Interlocked.CompareExchange(ref _innerConnection, DbConnectionClosedPreviouslyOpened.SingletonInstance, innerConnection);
innerConnection.DoomThisConnection();
}
}
internal void AddWeakReference(object value, int tag)
{
InnerConnection.AddWeakReference(value, tag);
}
override protected DbCommand CreateDbCommand()
{
DbCommand command = null;
DbProviderFactory providerFactory = ConnectionFactory.ProviderFactory;
command = providerFactory.CreateCommand();
command.Connection = this;
return command;
}
override protected void Dispose(bool disposing)
{
if (disposing)
{
_userConnectionOptions = null;
_poolGroup = null;
Close();
}
DisposeMe(disposing);
base.Dispose(disposing);
}
partial void RepairInnerConnection();
public override void EnlistTransaction(Transaction transaction)
{
// If we're currently enlisted in a transaction and we were called
// on the EnlistTransaction method (Whidbey) we're not allowed to
// enlist in a different transaction.
DbConnectionInternal innerConnection = InnerConnection;
// NOTE: since transaction enlistment involves round trips to the
// server, we don't want to lock here, we'll handle the race conditions
// elsewhere.
Transaction enlistedTransaction = innerConnection.EnlistedTransaction;
if (enlistedTransaction != null)
{
// Allow calling enlist if already enlisted (no-op)
if (enlistedTransaction.Equals(transaction))
{
return;
}
// Allow enlisting in a different transaction if the enlisted transaction has completed.
if (enlistedTransaction.TransactionInformation.Status == TransactionStatus.Active)
{
throw ADP.TransactionPresent();
}
}
RepairInnerConnection();
InnerConnection.EnlistTransaction(transaction);
// NOTE: If this outer connection were to be GC'd while we're
// enlisting, the pooler would attempt to reclaim the inner connection
// while we're attempting to enlist; not sure how likely that is but
// we should consider a GC.KeepAlive(this) here.
GC.KeepAlive(this);
}
internal void NotifyWeakReference(int message)
{
InnerConnection.NotifyWeakReference(message);
}
internal void PermissionDemand()
{
Debug.Assert(DbConnectionClosedConnecting.SingletonInstance == _innerConnection, "not connecting");
System.Data.ProviderBase.DbConnectionPoolGroup poolGroup = PoolGroup;
DbConnectionOptions connectionOptions = ((null != poolGroup) ? poolGroup.ConnectionOptions : null);
if ((null == connectionOptions) || connectionOptions.IsEmpty)
{
throw ADP.NoConnectionString();
}
DbConnectionOptions userConnectionOptions = UserConnectionOptions;
Debug.Assert(null != userConnectionOptions, "null UserConnectionOptions");
}
internal void RemoveWeakReference(object value)
{
InnerConnection.RemoveWeakReference(value);
}
internal void SetInnerConnectionEvent(DbConnectionInternal to)
{
Debug.Assert(null != _innerConnection, "null InnerConnection");
Debug.Assert(null != to, "to null InnerConnection");
ConnectionState originalState = _innerConnection.State & ConnectionState.Open;
ConnectionState currentState = to.State & ConnectionState.Open;
if ((originalState != currentState) && (ConnectionState.Closed == currentState))
{
unchecked { _closeCount++; }
}
_innerConnection = to;
if (ConnectionState.Closed == originalState && ConnectionState.Open == currentState)
{
OnStateChange(DbConnectionInternal.StateChangeOpen);
}
else if (ConnectionState.Open == originalState && ConnectionState.Closed == currentState)
{
OnStateChange(DbConnectionInternal.StateChangeClosed);
}
else
{
Debug.Assert(false, "unexpected state switch");
if (originalState != currentState)
{
OnStateChange(new StateChangeEventArgs(originalState, currentState));
}
}
}
internal bool SetInnerConnectionFrom(DbConnectionInternal to, DbConnectionInternal from)
{
Debug.Assert(null != _innerConnection, "null InnerConnection");
Debug.Assert(null != from, "from null InnerConnection");
Debug.Assert(null != to, "to null InnerConnection");
bool result = (from == Interlocked.CompareExchange<DbConnectionInternal>(ref _innerConnection, to, from));
return result;
}
internal void SetInnerConnectionTo(DbConnectionInternal to)
{
Debug.Assert(null != _innerConnection, "null InnerConnection");
Debug.Assert(null != to, "to null InnerConnection");
_innerConnection = to;
}
}
}
| |
/*
* Exchange Web Services Managed API
*
* 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.
*/
namespace Microsoft.Exchange.WebServices.Data
{
/// <summary>
/// Defines the available properties of a rule.
/// </summary>
public enum RuleProperty
{
/// <summary>
/// The RuleId property of a rule.
/// </summary>
[EwsEnum("RuleId")]
RuleId,
/// <summary>
/// The DisplayName property of a rule.
/// </summary>
[EwsEnum("DisplayName")]
DisplayName,
/// <summary>
/// The Priority property of a rule.
/// </summary>
[EwsEnum("Priority")]
Priority,
/// <summary>
/// The IsNotSupported property of a rule.
/// </summary>
[EwsEnum("IsNotSupported")]
IsNotSupported,
/// <summary>
/// The Actions property of a rule.
/// </summary>
[EwsEnum("Actions")]
Actions,
/// <summary>
/// The Categories property of a rule's set of conditions.
/// </summary>
[EwsEnum("Condition:Categories")]
ConditionCategories,
/// <summary>
/// The ContainsBodyStrings property of a rule's set of conditions.
/// </summary>
[EwsEnum("Condition:ContainsBodyStrings")]
ConditionContainsBodyStrings,
/// <summary>
/// The ContainsHeaderStrings property of a rule's set of conditions.
/// </summary>
[EwsEnum("Condition:ContainsHeaderStrings")]
ConditionContainsHeaderStrings,
/// <summary>
/// The ContainsRecipientStrings property of a rule's set of conditions.
/// </summary>
[EwsEnum("Condition:ContainsRecipientStrings")]
ConditionContainsRecipientStrings,
/// <summary>
/// The ContainsSenderStrings property of a rule's set of conditions.
/// </summary>
[EwsEnum("Condition:ContainsSenderStrings")]
ConditionContainsSenderStrings,
/// <summary>
/// The ContainsSubjectOrBodyStrings property of a rule's set of conditions.
/// </summary>
[EwsEnum("Condition:ContainsSubjectOrBodyStrings")]
ConditionContainsSubjectOrBodyStrings,
/// <summary>
/// The ContainsSubjectStrings property of a rule's set of conditions.
/// </summary>
[EwsEnum("Condition:ContainsSubjectStrings")]
ConditionContainsSubjectStrings,
/// <summary>
/// The FlaggedForAction property of a rule's set of conditions.
/// </summary>
[EwsEnum("Condition:FlaggedForAction")]
ConditionFlaggedForAction,
/// <summary>
/// The FromAddresses property of a rule's set of conditions.
/// </summary>
[EwsEnum("Condition:FromAddresses")]
ConditionFromAddresses,
/// <summary>
/// The FromConnectedAccounts property of a rule's set of conditions.
/// </summary>
[EwsEnum("Condition:FromConnectedAccounts")]
ConditionFromConnectedAccounts,
/// <summary>
/// The HasAttachments property of a rule's set of conditions.
/// </summary>
[EwsEnum("Condition:HasAttachments")]
ConditionHasAttachments,
/// <summary>
/// The Importance property of a rule's set of conditions.
/// </summary>
[EwsEnum("Condition:Importance")]
ConditionImportance,
/// <summary>
/// The IsApprovalRequest property of a rule's set of conditions.
/// </summary>
[EwsEnum("Condition:IsApprovalRequest")]
ConditionIsApprovalRequest,
/// <summary>
/// The IsAutomaticForward property of a rule's set of conditions.
/// </summary>
[EwsEnum("Condition:IsAutomaticForward")]
ConditionIsAutomaticForward,
/// <summary>
/// The IsAutomaticReply property of a rule's set of conditions.
/// </summary>
[EwsEnum("Condition:IsAutomaticReply")]
ConditionIsAutomaticReply,
/// <summary>
/// The IsEncrypted property of a rule's set of conditions.
/// </summary>
[EwsEnum("Condition:IsEncrypted")]
ConditionIsEncrypted,
/// <summary>
/// The IsMeetingRequest property of a rule's set of conditions.
/// </summary>
[EwsEnum("Condition:IsMeetingRequest")]
ConditionIsMeetingRequest,
/// <summary>
/// The IsMeetingResponse property of a rule's set of conditions.
/// </summary>
[EwsEnum("Condition:IsMeetingResponse")]
ConditionIsMeetingResponse,
/// <summary>
/// The IsNonDeliveryReport property of a rule's set of conditions.
/// </summary>
[EwsEnum("Condition:IsNDR")]
ConditionIsNonDeliveryReport,
/// <summary>
/// The IsPermissionControlled property of a rule's set of conditions.
/// </summary>
[EwsEnum("Condition:IsPermissionControlled")]
ConditionIsPermissionControlled,
/// <summary>
/// The IsRead property of a rule's set of conditions.
/// </summary>
[EwsEnum("Condition:IsRead")]
ConditionIsRead,
/// <summary>
/// The IsSigned property of a rule's set of conditions.
/// </summary>
[EwsEnum("Condition:IsSigned")]
ConditionIsSigned,
/// <summary>
/// The IsVoicemail property of a rule's set of conditions.
/// </summary>
[EwsEnum("Condition:IsVoicemail")]
ConditionIsVoicemail,
/// <summary>
/// The IsReadReceipt property of a rule's set of conditions.
/// </summary>
[EwsEnum("Condition:IsReadReceipt")]
ConditionIsReadReceipt,
/// <summary>
/// The ItemClasses property of a rule's set of conditions.
/// </summary>
[EwsEnum("Condition:ItemClasses")]
ConditionItemClasses,
/// <summary>
/// The MessageClassifications property of a rule's set of conditions.
/// </summary>
[EwsEnum("Condition:MessageClassifications")]
ConditionMessageClassifications,
/// <summary>
/// The NotSentToMe property of a rule's set of conditions.
/// </summary>
[EwsEnum("Condition:NotSentToMe")]
ConditionNotSentToMe,
/// <summary>
/// The SentCcMe property of a rule's set of conditions.
/// </summary>
[EwsEnum("Condition:SentCcMe")]
ConditionSentCcMe,
/// <summary>
/// The SentOnlyToMe property of a rule's set of conditions.
/// </summary>
[EwsEnum("Condition:SentOnlyToMe")]
ConditionSentOnlyToMe,
/// <summary>
/// The SentToAddresses property of a rule's set of conditions.
/// </summary>
[EwsEnum("Condition:SentToAddresses")]
ConditionSentToAddresses,
/// <summary>
/// The SentToMe property of a rule's set of conditions.
/// </summary>
[EwsEnum("Condition:SentToMe")]
ConditionSentToMe,
/// <summary>
/// The SentToOrCcMe property of a rule's set of conditions.
/// </summary>
[EwsEnum("Condition:SentToOrCcMe")]
ConditionSentToOrCcMe,
/// <summary>
/// The Sensitivity property of a rule's set of conditions.
/// </summary>
[EwsEnum("Condition:Sensitivity")]
ConditionSensitivity,
/// <summary>
/// The WithinDateRange property of a rule's set of conditions.
/// </summary>
[EwsEnum("Condition:WithinDateRange")]
ConditionWithinDateRange,
/// <summary>
/// The WithinSizeRange property of a rule's set of conditions.
/// </summary>
[EwsEnum("Condition:WithinSizeRange")]
ConditionWithinSizeRange,
/// <summary>
/// The Categories property of a rule's set of exceptions.
/// </summary>
[EwsEnum("Exception:Categories")]
ExceptionCategories,
/// <summary>
/// The ContainsBodyStrings property of a rule's set of exceptions.
/// </summary>
[EwsEnum("Exception:ContainsBodyStrings")]
ExceptionContainsBodyStrings,
/// <summary>
/// The ContainsHeaderStrings property of a rule's set of exceptions.
/// </summary>
[EwsEnum("Exception:ContainsHeaderStrings")]
ExceptionContainsHeaderStrings,
/// <summary>
/// The ContainsRecipientStrings property of a rule's set of exceptions.
/// </summary>
[EwsEnum("Exception:ContainsRecipientStrings")]
ExceptionContainsRecipientStrings,
/// <summary>
/// The ContainsSenderStrings property of a rule's set of exceptions.
/// </summary>
[EwsEnum("Exception:ContainsSenderStrings")]
ExceptionContainsSenderStrings,
/// <summary>
/// The ContainsSubjectOrBodyStrings property of a rule's set of exceptions.
/// </summary>
[EwsEnum("Exception:ContainsSubjectOrBodyStrings")]
ExceptionContainsSubjectOrBodyStrings,
/// <summary>
/// The ContainsSubjectStrings property of a rule's set of exceptions.
/// </summary>
[EwsEnum("Exception:ContainsSubjectStrings")]
ExceptionContainsSubjectStrings,
/// <summary>
/// The FlaggedForAction property of a rule's set of exceptions.
/// </summary>
[EwsEnum("Exception:FlaggedForAction")]
ExceptionFlaggedForAction,
/// <summary>
/// The FromAddresses property of a rule's set of exceptions.
/// </summary>
[EwsEnum("Exception:FromAddresses")]
ExceptionFromAddresses,
/// <summary>
/// The FromConnectedAccounts property of a rule's set of exceptions.
/// </summary>
[EwsEnum("Exception:FromConnectedAccounts")]
ExceptionFromConnectedAccounts,
/// <summary>
/// The HasAttachments property of a rule's set of exceptions.
/// </summary>
[EwsEnum("Exception:HasAttachments")]
ExceptionHasAttachments,
/// <summary>
/// The Importance property of a rule's set of exceptions.
/// </summary>
[EwsEnum("Exception:Importance")]
ExceptionImportance,
/// <summary>
/// The IsApprovalRequest property of a rule's set of exceptions.
/// </summary>
[EwsEnum("Exception:IsApprovalRequest")]
ExceptionIsApprovalRequest,
/// <summary>
/// The IsAutomaticForward property of a rule's set of exceptions.
/// </summary>
[EwsEnum("Exception:IsAutomaticForward")]
ExceptionIsAutomaticForward,
/// <summary>
/// The IsAutomaticReply property of a rule's set of exceptions.
/// </summary>
[EwsEnum("Exception:IsAutomaticReply")]
ExceptionIsAutomaticReply,
/// <summary>
/// The IsEncrypted property of a rule's set of exceptions.
/// </summary>
[EwsEnum("Exception:IsEncrypted")]
ExceptionIsEncrypted,
/// <summary>
/// The IsMeetingRequest property of a rule's set of exceptions.
/// </summary>
[EwsEnum("Exception:IsMeetingRequest")]
ExceptionIsMeetingRequest,
/// <summary>
/// The IsMeetingResponse property of a rule's set of exceptions.
/// </summary>
[EwsEnum("Exception:IsMeetingResponse")]
ExceptionIsMeetingResponse,
/// <summary>
/// The IsNonDeliveryReport property of a rule's set of exceptions.
/// </summary>
[EwsEnum("Exception:IsNDR")]
ExceptionIsNonDeliveryReport,
/// <summary>
/// The IsPermissionControlled property of a rule's set of exceptions.
/// </summary>
[EwsEnum("Exception:IsPermissionControlled")]
ExceptionIsPermissionControlled,
/// <summary>
/// The IsRead property of a rule's set of exceptions.
/// </summary>
[EwsEnum("Exception:IsRead")]
ExceptionIsRead,
/// <summary>
/// The IsSigned property of a rule's set of exceptions.
/// </summary>
[EwsEnum("Exception:IsSigned")]
ExceptionIsSigned,
/// <summary>
/// The IsVoicemail property of a rule's set of exceptions.
/// </summary>
[EwsEnum("Exception:IsVoicemail")]
ExceptionIsVoicemail,
/// <summary>
/// The ItemClasses property of a rule's set of exceptions.
/// </summary>
[EwsEnum("Exception:ItemClasses")]
ExceptionItemClasses,
/// <summary>
/// The MessageClassifications property of a rule's set of exceptions.
/// </summary>
[EwsEnum("Exception:MessageClassifications")]
ExceptionMessageClassifications,
/// <summary>
/// The NotSentToMe property of a rule's set of exceptions.
/// </summary>
[EwsEnum("Exception:NotSentToMe")]
ExceptionNotSentToMe,
/// <summary>
/// The SentCcMe property of a rule's set of exceptions.
/// </summary>
[EwsEnum("Exception:SentCcMe")]
ExceptionSentCcMe,
/// <summary>
/// The SentOnlyToMe property of a rule's set of exceptions.
/// </summary>
[EwsEnum("Exception:SentOnlyToMe")]
ExceptionSentOnlyToMe,
/// <summary>
/// The SentToAddresses property of a rule's set of exceptions.
/// </summary>
[EwsEnum("Exception:SentToAddresses")]
ExceptionSentToAddresses,
/// <summary>
/// The SentToMe property of a rule's set of exceptions.
/// </summary>
[EwsEnum("Exception:SentToMe")]
ExceptionSentToMe,
/// <summary>
/// The SentToOrCcMe property of a rule's set of exceptions.
/// </summary>
[EwsEnum("Exception:SentToOrCcMe")]
ExceptionSentToOrCcMe,
/// <summary>
/// The Sensitivity property of a rule's set of exceptions.
/// </summary>
[EwsEnum("Exception:Sensitivity")]
ExceptionSensitivity,
/// <summary>
/// The WithinDateRange property of a rule's set of exceptions.
/// </summary>
[EwsEnum("Exception:WithinDateRange")]
ExceptionWithinDateRange,
/// <summary>
/// The WithinSizeRange property of a rule's set of exceptions.
/// </summary>
[EwsEnum("Exception:WithinSizeRange")]
ExceptionWithinSizeRange,
/// <summary>
/// The Categories property in a rule's set of actions.
/// </summary>
[EwsEnum("Action:Categories")]
ActionCategories,
/// <summary>
/// The CopyToFolder property in a rule's set of actions.
/// </summary>
[EwsEnum("Action:CopyToFolder")]
ActionCopyToFolder,
/// <summary>
/// The Delete property in a rule's set of actions.
/// </summary>
[EwsEnum("Action:Delete")]
ActionDelete,
/// <summary>
/// The ForwardAsAttachmentToRecipients property in a rule's set of actions.
/// </summary>
[EwsEnum("Action:ForwardAsAttachmentToRecipients")]
ActionForwardAsAttachmentToRecipients,
/// <summary>
/// The ForwardToRecipients property in a rule's set of actions.
/// </summary>
[EwsEnum("Action:ForwardToRecipients")]
ActionForwardToRecipients,
/// <summary>
/// The Importance property in a rule's set of actions.
/// </summary>
[EwsEnum("Action:Importance")]
ActionImportance,
/// <summary>
/// The MarkAsRead property in a rule's set of actions.
/// </summary>
[EwsEnum("Action:MarkAsRead")]
ActionMarkAsRead,
/// <summary>
/// The MoveToFolder property in a rule's set of actions.
/// </summary>
[EwsEnum("Action:MoveToFolder")]
ActionMoveToFolder,
/// <summary>
/// The PermanentDelete property in a rule's set of actions.
/// </summary>
[EwsEnum("Action:PermanentDelete")]
ActionPermanentDelete,
/// <summary>
/// The RedirectToRecipients property in a rule's set of actions.
/// </summary>
[EwsEnum("Action:RedirectToRecipients")]
ActionRedirectToRecipients,
/// <summary>
/// The SendSMSAlertToRecipients property in a rule's set of actions.
/// </summary>
[EwsEnum("Action:SendSMSAlertToRecipients")]
ActionSendSMSAlertToRecipients,
/// <summary>
/// The ServerReplyWithMessage property in a rule's set of actions.
/// </summary>
[EwsEnum("Action:ServerReplyWithMessage")]
ActionServerReplyWithMessage,
/// <summary>
/// The StopProcessingRules property in a rule's set of actions.
/// </summary>
[EwsEnum("Action:StopProcessingRules")]
ActionStopProcessingRules,
/// <summary>
/// The IsEnabled property of a rule, indicating if the rule is enabled.
/// </summary>
[EwsEnum("IsEnabled")]
IsEnabled,
/// <summary>
/// The IsInError property of a rule, indicating if the rule is in error.
/// </summary>
[EwsEnum("IsInError")]
IsInError,
/// <summary>
/// The Conditions property of a rule, contains all conditions of the rule.
/// </summary>
[EwsEnum("Conditions")]
Conditions,
/// <summary>
/// The Exceptions property of a rule, contains all exceptions of the rule.
/// </summary>
[EwsEnum("Exceptions")]
Exceptions
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Windows.Forms;
using EDEngineer.Localization;
using Application = System.Windows.Application;
namespace EDEngineer.Utils.System
{
public static class IOUtils
{
private static readonly Dictionary<char, string> specialCharactersMapping = new Dictionary<char, string>()
{
['<'] = "<",
['>'] = ">",
[':'] = ":",
['"'] = "“",
['/'] = "/",
['\\'] = "\",
['|'] = "|",
['?'] = "?",
['*'] = "*",
};
private static readonly Dictionary<string, string> specialCharactersMappingReversed =
specialCharactersMapping.ToDictionary(k => k.Value, k => k.Key.ToString());
private static string SanitizeChar(char input)
{
string output;
if (!specialCharactersMapping.TryGetValue(input, out output))
{
return input.ToString();
}
return output;
}
public static string Sanitize(this string input)
{
return input.Select(name => name)
.Aggregate(string.Empty, (acc, c) => acc + IOUtils.SanitizeChar(c));
}
public static string Desanitize(this string input)
{
specialCharactersMappingReversed.Keys.ToList().ForEach(k =>
{
input = input.Replace(k,
specialCharactersMappingReversed[k]);
});
return input;
}
public static string RetrieveLogDirectory(bool forcePickFolder, string currentLogDirectory)
{
var translator = Languages.Instance;
string logDirectory = null;
if (!forcePickFolder)
{
logDirectory = Properties.Settings.Default.LogDirectory;
if (string.IsNullOrEmpty(logDirectory))
{
var userProfile = Environment.GetEnvironmentVariable("USERPROFILE");
if (userProfile != null)
{
logDirectory = Path.Combine(userProfile, @"saved games\Frontier Developments\Elite Dangerous");
}
}
}
if (forcePickFolder || logDirectory == null || !Directory.Exists(logDirectory))
{
var dialog = new FolderBrowserDialog
{
Description = forcePickFolder ?
translator.Translate("Select a new log directory") :
translator.Translate("Couldn't find the log folder for elite, you'll have to specify it")
};
if (forcePickFolder && !string.IsNullOrEmpty(currentLogDirectory))
{
dialog.SelectedPath = currentLogDirectory;
}
var pickFolderResult = dialog.ShowDialog();
if (pickFolderResult == DialogResult.OK)
{
if (!Directory.GetFiles(dialog.SelectedPath).Any(f => f != null &&
Path.GetFileName(f).StartsWith("Journal.") &&
Path.GetFileName(f).EndsWith(".log")))
{
var result =
MessageBox.Show(
translator.Translate("Selected directory doesn't seem to contain any log file ; are you sure?"),
translator.Translate("Warning"), MessageBoxButtons.AbortRetryIgnore, MessageBoxIcon.Warning);
if (result == DialogResult.Retry)
{
RetrieveLogDirectory(forcePickFolder, null);
}
if (result == DialogResult.Abort)
{
if (forcePickFolder)
{
return currentLogDirectory;
}
Application.Current.Shutdown();
}
}
logDirectory = dialog.SelectedPath;
}
else if (forcePickFolder)
{
return currentLogDirectory;
}
else
{
MessageBox.Show(translator.Translate("You did not select a log directory, EDEngineer won't be able to track changes. You can still use the app manually though."),
translator.Translate("Warning"), MessageBoxButtons.OK, MessageBoxIcon.Warning);
logDirectory = @"\" + translator.Translate("No folder in use ; click to change");
}
}
Properties.Settings.Default.LogDirectory = logDirectory;
Properties.Settings.Default.Save();
return logDirectory;
}
public static string GetBlueprintsJson()
{
using (var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream("EDEngineer.Resources.Data.blueprints.json"))
using (var reader = new StreamReader(stream))
{
return reader.ReadToEnd();
}
}
public static string GetReleaseNotesJson()
{
using (var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream("EDEngineer.Resources.Data.releaseNotes.json"))
using (var reader = new StreamReader(stream))
{
return reader.ReadToEnd();
}
}
public static string GetLocalizationJson()
{
using (var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream("EDEngineer.Resources.Data.localization.json"))
using (var reader = new StreamReader(stream))
{
return reader.ReadToEnd();
}
}
public static string GetEntryDatasJson()
{
using (var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream("EDEngineer.Resources.Data.entryData.json"))
using (var reader = new StreamReader(stream))
{
return reader.ReadToEnd();
}
}
public static string GetManualChangesDirectory()
{
string directory;
var localDirectory = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
"EDEngineer");
var roamingDirectory = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),
"EDEngineer");
if (Directory.Exists(roamingDirectory))
{
directory = roamingDirectory;
}
else if (Directory.Exists(localDirectory) && Directory.GetFiles(localDirectory).Any(f => f != null && Path.GetFileName(f).StartsWith("manualChanges.") && f.EndsWith(".json")))
{
directory = localDirectory;
}
else
{
try
{
Directory.CreateDirectory(roamingDirectory);
directory = roamingDirectory;
}
catch
{
Directory.CreateDirectory(localDirectory);
directory = localDirectory;
}
}
return directory;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.IO;
using System.Net.Test.Common;
using System.Threading;
using System.Threading.Tasks;
using Xunit;
namespace System.Net.Tests
{
public class RequestStreamTest
{
readonly byte[] buffer = new byte[1];
#region Write
[Fact]
public void Write_BufferIsNull_ThrowsArgumentNullException()
{
using (Stream stream = GetRequestStream())
{
Assert.Throws<ArgumentNullException>("buffer", () => stream.Write(null, 0, 1));
}
}
[Fact]
public void Write_OffsetIsNegative_ThrowsArgumentOutOfRangeException()
{
using (Stream stream = GetRequestStream())
{
Assert.Throws<ArgumentOutOfRangeException>("offset", () => stream.Write(buffer, -1, buffer.Length));
}
}
[Fact]
public void Write_CountIsNegative_ThrowsArgumentOutOfRangeException()
{
using (Stream stream = GetRequestStream())
{
AssertExtensions.Throws<ArgumentOutOfRangeException>("count", "size", () => stream.Write(buffer, 0, -1));
}
}
[Fact]
public void Write_OffsetPlusCountExceedsBufferLength_ThrowsArgumentException()
{
using (Stream stream = GetRequestStream())
{
AssertExtensions.Throws<ArgumentOutOfRangeException>("count", "size", () => stream.Write(buffer, 0, buffer.Length + 1));
}
}
[Fact]
public void Write_OffsetPlusCountMaxValueExceedsBufferLength_Throws()
{
using (Stream stream = GetRequestStream())
{
Assert.Throws<ArgumentOutOfRangeException>("offset", () => stream.Write(buffer, int.MaxValue, int.MaxValue));
}
}
#endregion
#region WriteAsync
[Fact]
public void WriteAsync_BufferIsNull_ThrowsArgumentNullException()
{
using (Stream stream = GetRequestStream())
{
Assert.Throws<ArgumentNullException>("buffer", () => { Task t = stream.WriteAsync(null, 0, 1); });
}
}
[Fact]
public void WriteAsync_OffsetIsNegative_ThrowsArgumentOutOfRangeException()
{
using (Stream stream = GetRequestStream())
{
Assert.Throws<ArgumentOutOfRangeException>("offset", () => { Task t = stream.WriteAsync(buffer, -1, buffer.Length); });
}
}
[Fact]
public void WriteAsync_CountIsNegative_ThrowsArgumentOutOfRangeException()
{
using (Stream stream = GetRequestStream())
{
AssertExtensions.Throws<ArgumentOutOfRangeException>("count", "size", () => { Task t = stream.WriteAsync(buffer, 0, -1); });
}
}
[Fact]
public void WriteAsync_OffsetPlusCountExceedsBufferLength_ThrowsArgumentException()
{
using (Stream stream = GetRequestStream())
{
AssertExtensions.Throws<ArgumentOutOfRangeException>("count", "size", () => { Task t = stream.WriteAsync(buffer, 0, buffer.Length + 1); });
}
}
[Fact]
public void WriteAsync_OffsetPlusCountMaxValueExceedsBufferLength_Throws()
{
using (Stream stream = GetRequestStream())
{
Assert.Throws<ArgumentOutOfRangeException>("offset", () => { Task t = stream.WriteAsync(buffer, int.MaxValue, int.MaxValue); });
}
}
[Fact]
public void WriteAsync_ValidParameters_TaskRanToCompletion()
{
using (Stream stream = GetRequestStream())
{
Task t = stream.WriteAsync(buffer, 0, buffer.Length);
Assert.Equal(TaskStatus.RanToCompletion, t.Status);
}
}
[Fact]
public void WriteAsync_TokenIsCanceled_TaskIsCanceled()
{
using (Stream stream = GetRequestStream())
{
var cts = new CancellationTokenSource();
cts.Cancel();
Task t = stream.WriteAsync(buffer, 0, buffer.Length, cts.Token);
Assert.True(t.IsCanceled);
}
}
#endregion
#region BeginWrite
[Fact]
public void BeginWriteAsync_BufferIsNull_ThrowsArgumentNullException()
{
using (Stream stream = GetRequestStream())
{
Assert.Throws<ArgumentNullException>("buffer", () => stream.BeginWrite(null, 0, 1, null, null));
}
}
[Fact]
public void BeginWriteAsync_OffsetIsNegative_ThrowsArgumentOutOfRangeException()
{
using (Stream stream = GetRequestStream())
{
Assert.Throws<ArgumentOutOfRangeException>("offset", () => stream.BeginWrite(buffer, -1, buffer.Length, null, null));
}
}
[Fact]
public void BeginWriteAsync_CountIsNegative_ThrowsArgumentOutOfRangeException()
{
using (Stream stream = GetRequestStream())
{
AssertExtensions.Throws<ArgumentOutOfRangeException>("count", "size", () => stream.BeginWrite(buffer, 0, -1, null, null));
}
}
[Fact]
public void BeginWriteAsync_OffsetPlusCountExceedsBufferLength_ThrowsArgumentException()
{
using (Stream stream = GetRequestStream())
{
AssertExtensions.Throws<ArgumentOutOfRangeException>("count", "size", () => stream.BeginWrite(buffer, 0, buffer.Length + 1, null, null));
}
}
[Fact]
public void BeginWriteAsync_OffsetPlusCountMaxValueExceedsBufferLength_Throws()
{
using (Stream stream = GetRequestStream())
{
Assert.Throws<ArgumentOutOfRangeException>("offset", () => stream.BeginWrite(buffer, int.MaxValue, int.MaxValue, null, null));
}
}
[Fact]
public void BeginWriteAsync_ValidParameters_TaskRanToCompletion()
{
using (Stream stream = GetRequestStream())
{
object state = new object();
IAsyncResult result = stream.BeginWrite(buffer, 0, buffer.Length, null, state);
stream.EndWrite(result);
Assert.True(result.IsCompleted);
}
}
#endregion
[Fact]
public void FlushAsync_TaskRanToCompletion()
{
using (Stream stream = GetRequestStream())
{
Task t = stream.FlushAsync();
Assert.Equal(TaskStatus.RanToCompletion, t.Status);
}
}
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "cancellation token ignored on netfx")]
[Fact]
public void FlushAsync_TokenIsCanceled_TaskIsCanceled()
{
using (Stream stream = GetRequestStream())
{
var cts = new CancellationTokenSource();
cts.Cancel();
Task t = stream.FlushAsync(cts.Token);
Assert.True(t.IsCanceled);
}
}
private Stream GetRequestStream()
{
HttpWebRequest request = HttpWebRequest.CreateHttp(System.Net.Test.Common.Configuration.Http.RemoteEchoServer);
request.Method = "POST";
return request.GetRequestStreamAsync().GetAwaiter().GetResult();
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Runtime.InteropServices;
using Xunit;
using System.Linq;
namespace System.IO.Tests
{
public class Directory_GetFileSystemEntries_str_str : Directory_GetFileSystemEntries_str
{
#region Utilities
public override string[] GetEntries(string dirName)
{
return Directory.GetFileSystemEntries(dirName, "*");
}
public virtual string[] GetEntries(string dirName, string searchPattern)
{
return Directory.GetFileSystemEntries(dirName, searchPattern);
}
#endregion
#region UniversalTests
[Fact]
public void SearchPatternNull()
{
Assert.Throws<ArgumentNullException>(() => GetEntries(TestDirectory, null));
}
[Fact]
public void SearchPatternEmpty()
{
// To avoid OS differences we have decided not to throw an argument exception when empty
// string passed. But we should return 0 items.
Assert.Empty(GetEntries(TestDirectory, string.Empty));
}
[Fact]
public void SearchPatternValid()
{
Assert.Empty(GetEntries(TestDirectory, "a..b abc..d")); //Should not throw
}
[Fact]
public void SearchPatternDotIsStar()
{
DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath());
testDir.CreateSubdirectory("TestDir1");
testDir.CreateSubdirectory("TestDir2");
using (File.Create(Path.Combine(testDir.FullName, "TestFile1")))
using (File.Create(Path.Combine(testDir.FullName, "TestFile2")))
{
string[] strArr = GetEntries(testDir.FullName, ".");
if (TestFiles)
{
Assert.Contains(Path.Combine(testDir.FullName, "TestFile1"), strArr);
Assert.Contains(Path.Combine(testDir.FullName, "TestFile2"), strArr);
}
if (TestDirectories)
{
Assert.Contains(Path.Combine(testDir.FullName, "TestDir1"), strArr);
Assert.Contains(Path.Combine(testDir.FullName, "TestDir2"), strArr);
}
}
}
[Fact]
public void SearchPatternWithTrailingStar()
{
DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath());
testDir.CreateSubdirectory("TestDir1");
testDir.CreateSubdirectory("TestDir2");
testDir.CreateSubdirectory("TestDir3");
using (File.Create(Path.Combine(testDir.FullName, "TestFile1")))
using (File.Create(Path.Combine(testDir.FullName, "TestFile2")))
using (File.Create(Path.Combine(testDir.FullName, "Test1File2")))
using (File.Create(Path.Combine(testDir.FullName, "Test1Dir2")))
{
string[] strArr = GetEntries(testDir.FullName, "Test1*");
if (TestFiles)
{
Assert.Contains(Path.Combine(testDir.FullName, "Test1File2"), strArr);
Assert.Contains(Path.Combine(testDir.FullName, "Test1Dir2"), strArr);
}
strArr = GetEntries(testDir.FullName, "*");
if (TestFiles)
{
Assert.Contains(Path.Combine(testDir.FullName, "TestFile1"), strArr);
Assert.Contains(Path.Combine(testDir.FullName, "TestFile2"), strArr);
Assert.Contains(Path.Combine(testDir.FullName, "Test1File2"), strArr);
Assert.Contains(Path.Combine(testDir.FullName, "Test1Dir2"), strArr);
}
if (TestDirectories)
{
Assert.Contains(Path.Combine(testDir.FullName, "TestDir1"), strArr);
Assert.Contains(Path.Combine(testDir.FullName, "TestDir2"), strArr);
Assert.Contains(Path.Combine(testDir.FullName, "TestDir3"), strArr);
}
}
}
[Fact]
public void SearchPatternWithLeadingStar()
{
DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath());
testDir.CreateSubdirectory("TestDir1");
testDir.CreateSubdirectory("TestDir2");
testDir.CreateSubdirectory("TestDir3");
using (File.Create(Path.Combine(testDir.FullName, "TestFile1")))
using (File.Create(Path.Combine(testDir.FullName, "TestFile2")))
using (File.Create(Path.Combine(testDir.FullName, "Test1File2")))
using (File.Create(Path.Combine(testDir.FullName, "Test1Dir2")))
{
string[] strArr = GetEntries(testDir.FullName, "*2");
if (TestFiles)
{
Assert.Contains(Path.Combine(testDir.FullName, "Test1Dir2"), strArr);
Assert.Contains(Path.Combine(testDir.FullName, "Test1File2"), strArr);
Assert.Contains(Path.Combine(testDir.FullName, "TestFile2"), strArr);
}
if (TestDirectories)
{
Assert.Contains(Path.Combine(testDir.FullName, "TestDir2"), strArr);
}
strArr = GetEntries(testDir.FullName, "*Dir*");
if (TestFiles)
{
Assert.Contains(Path.Combine(testDir.FullName, "Test1Dir2"), strArr);
}
if (TestDirectories)
{
Assert.Contains(Path.Combine(testDir.FullName, "TestDir1"), strArr);
Assert.Contains(Path.Combine(testDir.FullName, "TestDir2"), strArr);
Assert.Contains(Path.Combine(testDir.FullName, "TestDir3"), strArr);
}
}
}
[Fact]
public void SearchPatternByExtension()
{
if (TestFiles)
{
DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath());
using (File.Create(Path.Combine(testDir.FullName, "TestFile1.txt")))
using (File.Create(Path.Combine(testDir.FullName, "TestFile2.xxt")))
using (File.Create(Path.Combine(testDir.FullName, "Test1File2.txt")))
using (File.Create(Path.Combine(testDir.FullName, "Test1Dir2.txx")))
{
string[] strArr = GetEntries(testDir.FullName, "*.txt");
Assert.Equal(2, strArr.Length);
Assert.Contains(Path.Combine(testDir.FullName, "TestFile1.txt"), strArr);
Assert.Contains(Path.Combine(testDir.FullName, "Test1File2.txt"), strArr);
}
}
}
[Fact]
public void SearchPatternExactMatch()
{
DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath());
Directory.CreateDirectory(Path.Combine(testDir.FullName, "AAA"));
Directory.CreateDirectory(Path.Combine(testDir.FullName, "AAAB"));
Directory.CreateDirectory(Path.Combine(testDir.FullName, "CAAA"));
using (File.Create(Path.Combine(testDir.FullName, "AAABB")))
using (File.Create(Path.Combine(testDir.FullName, "AAABBC")))
using (File.Create(Path.Combine(testDir.FullName, "CAAABB")))
{
if (TestFiles)
{
string[] results = GetEntries(testDir.FullName, "AAABB");
Assert.Equal(1, results.Length);
Assert.Contains(Path.Combine(testDir.FullName, "AAABB"), results);
}
if (TestDirectories)
{
string[] results = GetEntries(testDir.FullName, "AAA");
Assert.Equal(1, results.Length);
Assert.Contains(Path.Combine(testDir.FullName, "AAA"), results);
}
}
}
[Fact]
public void SearchPatternIgnoreSubDirectories()
{
//Shouldn't get files on full path by default
DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath());
Directory.CreateDirectory(Path.Combine(testDir.FullName, GetTestFileName()));
using (File.Create(Path.Combine(testDir.FullName, GetTestFileName())))
using (File.Create(Path.Combine(TestDirectory, GetTestFileName())))
{
string[] results = GetEntries(TestDirectory, Path.Combine(testDir.Name, "*"));
if (TestDirectories && TestFiles)
Assert.Equal(2, results.Length);
else
Assert.Equal(1, results.Length);
}
}
[Theory,
// '[' should not matter, but is special to Unix matching APIs
InlineData(
"[foo]",
new string[] { @"f", @"o", @"o", @"foo", @"[foo]" },
new string[] { @"[foo]" }),
]
public void PatternTests_UnixPatterns(string pattern, string[] sourceFiles, string[] expected)
{
string testDir = PrepareDirectory(sourceFiles);
ValidatePatternMatch(expected, GetEntries(testDir, pattern));
}
[ActiveIssue(20779, TestPlatforms.AnyUnix)]
[Theory,
// Question marks collapse (right) to periods
InlineData(
"f???.txt",
new string[] { @"f.txt", @"foo.txt", @"foob.txt", @"fooba.txt", @"foobar.txt" },
new string[] { @"f.txt", @"foo.txt", @"foob.txt" }),
// Question marks don't collapse to !periods
InlineData(
"???b??.txt",
new string[] { @"f.txt", @"foo.txt", @"foob.txt", @"fooba.txt", @"foobar.txt" },
new string[] { @"foob.txt", @"fooba.txt", @"foobar.txt" }),
// Question marks collapse (right) to end
InlineData(
"foo.t??",
new string[] { @"foo", @"foo.t", @"foo.tx", @"foo.txt", @"bar.txt", @"foo.txxt" },
new string[] { @"foo.t", @"foo.tx", @"foo.txt" }),
]
public void PatternTests_DosQM(string pattern, string[] sourceFiles, string[] expected)
{
// Question marks always collapse right to periods or the end of the string if they are contiguous
string testDir = PrepareDirectory(sourceFiles);
ValidatePatternMatch(expected, GetEntries(testDir, pattern));
}
[ActiveIssue(20779, TestPlatforms.AnyUnix)]
[ActiveIssue(20780, TestPlatforms.AnyUnix)]
[Theory,
// Periods are optional if left of ? and end of match
InlineData(
"foo.???",
new string[] { @"foo", @"foo.t", @"foo.tx", @"foo.txt", @"bar.txt", @"foo.txxt" },
new string[] { @"foo", @"foo.t", @"foo.tx", @"foo.txt" }),
// Periods are optional if left of ? and end of match
InlineData(
"foo.???.?.?.?",
new string[] { @"foo", @"foo.t", @"foo.tx", @"foo.txt", @"bar.txt", @"foo.txxt" },
new string[] { @"foo", @"foo.t", @"foo.tx", @"foo.txt" }),
// Periods are optional if left of ? and end of match
InlineData(
"foo.?.??.???.?",
new string[] { @"foo", @"foo.t", @"foo.tx", @"foo.txt", @"bar.txt", @"foo.txxt" },
new string[] { @"foo", @"foo.t" }),
// Periods are optional if left of ? and end of match
InlineData(
"foo.??.???.?",
new string[] { @"foo", @"foo.t", @"foo.tx", @"foo.txt", @"bar.txt", @"foo.txxt" },
new string[] { @"foo", @"foo.t", @"foo.tx" }),
// Periods are optional if left of * and end of match, question marks collapse (right) to end
InlineData(
"foo.*??",
new string[] { @"foo", @"foo.t", @"foo.tx", @"foo.txt", @"bar.txt", @"foo.txxt" },
new string[] { @"foo", @"foo.t", @"foo.tx", @"foo.txt", @"foo.txxt" }),
// Periods are optional if left of * and end of match, question marks collapse (right) to end
InlineData(
"foo.*??*",
new string[] { @"foo", @"foo.t", @"foo.tx", @"foo.txt", @"bar.txt", @"foo.txxt" },
new string[] { @"foo", @"foo.t", @"foo.tx", @"foo.txt", @"foo.txxt" })
]
public void PatternTests_DosDotQm(string pattern, string[] sourceFiles, string[] expected)
{
// Tests for collapsing question marks and DOS_DOT, ", which is what periods get changed to when they are followed by a '?' or '*'.
string testDir = PrepareDirectory(sourceFiles);
ValidatePatternMatch(expected, GetEntries(testDir, pattern));
}
[ActiveIssue(20780, TestPlatforms.AnyUnix)]
[Theory,
// Periods are optional if left of * and end of match
InlineData(
"foo.*",
new string[] { @"foo", @"foo.t", @"foo.tx", @"foo.txt", @"bar.txt", @"foo.txxt" },
new string[] { @"foo", @"foo.t", @"foo.tx", @"foo.txt", @"foo.txxt" }),
// Periods are optional if left of * and end of match
InlineData(
"foo.*.*.*.*",
new string[] { @"foo", @"foo.t", @"foo.tx", @"foo.txt", @"bar.txt", @"foo.txxt" },
new string[] { @"foo", @"foo.t", @"foo.tx", @"foo.txt", @"foo.txxt" })
]
public void PatternTests_DosDot(string pattern, string[] sourceFiles, string[] expected)
{
// Tests for DOS_DOT, ", which is what periods get changed to when they are followed by a '?' or '*'.
string testDir = PrepareDirectory(sourceFiles);
ValidatePatternMatch(expected, GetEntries(testDir, pattern));
}
[ActiveIssue(20780, TestPlatforms.AnyUnix)]
// Can't do these without extended path support on Windows, UsingNewNormalization filters appropriately
[ConditionalTheory(nameof(UsingNewNormalization)),
// Periods are optional if left of * or ? and end of match
InlineData(
"foo.*",
new string[] { @"foo", @"foo.", @"foo.t", @"foo.tx", @"foo.txt", @"bar.txt", @"foo.txxt" },
new string[] { @"foo", @"foo.", @"foo.t", @"foo.tx", @"foo.txt", @"foo.txxt" }),
InlineData(
"foo.*.*",
new string[] { @"foo", @"foo.", @"foo.t", @"foo.tx", @"foo.txt", @"bar.txt", @"foo.txxt" },
new string[] { @"foo", @"foo.", @"foo.t", @"foo.tx", @"foo.txt", @"foo.txxt" }),
InlineData(
"foo.?",
new string[] { @"foo", @"foo.", @"foo.t", @"foo.tx", @"foo.txt", @"bar.txt", @"foo.txxt" },
new string[] { @"foo", @"foo.", @"foo.t" }),
InlineData(
"foo.??",
new string[] { @"foo", @"foo.", @"foo.t", @"foo.tx", @"foo.txt", @"bar.txt", @"foo.txxt" },
new string[] { @"foo", @"foo.", @"foo.t", @"foo.tx" }),
InlineData(
"foo.?.?",
new string[] { @"foo", @"foo.", @"foo.t", @"foo.tx", @"foo.txt", @"bar.txt", @"foo.txxt" },
new string[] { @"foo", @"foo.", @"foo.t" }),
InlineData(
"foo.??.??",
new string[] { @"foo", @"foo.", @"foo.t", @"foo.tx", @"foo.txt", @"bar.txt", @"foo.txxt" },
new string[] { @"foo", @"foo.", @"foo.t", @"foo.tx" }),
InlineData(
"foo.?.*",
new string[] { @"foo", @"foo.", @"foo.t", @"foo.tx", @"foo.txt", @"bar.txt", @"foo.txxt" },
new string[] { @"foo", @"foo.", @"foo.t" }),
InlineData(
"foo.??.*",
new string[] { @"foo", @"foo.", @"foo.t", @"foo.tx", @"foo.txt", @"bar.txt", @"foo.txxt" },
new string[] { @"foo", @"foo.", @"foo.t", @"foo.tx" }),
]
public void PatternTests_DosDotTrailingDot(string pattern, string[] sourceFiles, string[] expected)
{
// Tests for DOS_DOT, ", which is what periods get changed to when they are followed by a '?' or '*'.
// We don't want to eat trailing space/periods in this test
string testDir = PrepareDirectory(sourceFiles, useExtendedPaths: true);
ValidatePatternMatch(expected, GetEntries(testDir, pattern));
}
[ActiveIssue(20781, TestPlatforms.AnyUnix)]
[Theory,
InlineData(
"foo*.",
new string[] { @"foo", @"foobar", @"foo.bar" },
new string[] { @"foo", @"foobar" })
]
public void PatternTests_DosStar(string pattern, string[] sourceFiles, string[] expected)
{
// Tests for DOS_STAR, which only occurs when the source pattern ends in *.
string testDir = PrepareDirectory(sourceFiles);
ValidatePatternMatch(expected, GetEntries(testDir, pattern));
}
[ActiveIssue(20781, TestPlatforms.AnyUnix)]
// Can't do these without extended path support on Windows, UsingNewNormalization filters appropriately
[ConditionalTheory(nameof(UsingNewNormalization)),
InlineData(
"foo*.",
new string[] { @"foo", @"foo.", @"foo.t", @"foo.tx", @"foo.txt", @"bar.txt", @"foo..", @"foo...", @"foo .", @"foo. . .", @"foo. t" },
new string[] { @"foo", @"foo .", @"foo.", @"foo..", @"foo...", @"foo. . ." }),
InlineData(
"foodies*.",
new string[] { @"foodies.", @"foodies. ", @"foodies. " },
new string[] { @"foodies." }),
InlineData(
"foodies*.",
new string[] { @"foodies. ", @"foodies. ", @"foodies. " },
new string[] { }),
InlineData(
"foooooo*.",
new string[] { @"foooooo.", @"foooooo. ", @"foooooo. " },
new string[] { @"foooooo." }),
InlineData(
"foooooo*.",
new string[] { @"foooooo. ", @"foooooo. ", @"foooooo. " },
new string[] { }),
InlineData(
"foodies*.",
new string[] { @"foodies.", @"foodies. ", @"foodies. ", @"foodies. ", @"foodies. ", @"foodies. " },
new string[] { @"foodies." }),
InlineData(
"foodies*.",
new string[] { @"foodies. ", @"foodies. ", @"foodies. ", @"foodies. ", @"foodies. " },
new string[] { }),
InlineData(
"foo*.",
new string[] { @"foo..", @"foo...", @"foo....", @"foo.....", @"foo......" },
new string[] { @"foo..", @"foo...", @"foo....", @"foo.....", @"foo......" }),
]
public void PatternTests_DosStarSpace(string pattern, string[] sourceFiles, string[] expected)
{
// Tests for DOS_STAR, which only occurs when the source pattern ends in *. These are the subset of tests
// with trailing spaces that work as documented.
// We don't want to eat trailing space/periods in this test
string testDir = PrepareDirectory(sourceFiles, useExtendedPaths: true);
ValidatePatternMatch(expected, GetEntries(testDir, pattern));
}
[ActiveIssue(20781, TestPlatforms.AnyUnix)]
[OuterLoop("These are pretty corner, don't need to run all the time.")]
// Can't do these without extended path support on Windows, UsingNewNormalization filters appropriately
[ConditionalTheory(nameof(UsingNewNormalization)),
// "foo*." actually becomes "foo<" when passed to NT. It matches all characters up to, and including, the final period.
//
// There is a "bug" somewhere in the Windows stack where *some* files with trailing spaces after the final period will be returned when
// using "*." at the end of a string (which becomes "<"). According to the rules (and the actual pattern matcher used FsRtlIsNameInExpression)
// *nothing* should match after the final period.
//
// The results as passed to RtlIsNameInExpression (after changing *. to <) are in comments.
InlineData(
"foo*.",
new string[] { @"foo", @"foo.", @"foo.t", @"foo.tx", @"foo.txt", @"bar.txt", @"foo..", @"foo...", @"foo. ", @"foo. ", @"foo .", @"foo. . .", @"foo. t" },
// Really should be: new string[] { @"foo", @"foo.", @"foo..", @"foo...", @"foo .", @"foo. . ." }), but is
new string[] { @"foo", @"foo .", @"foo.", @"foo..", @"foo...", @"foo. ", @"foo. . ." }),
InlineData(
"*.",
new string[] { @"foo. ", @"foo. ", @"foo..", @"foo. t" },
// Really should be: new string[] { @"foo.." }), but is
new string[] { @"foo. ", @"foo. ", @"foo.." }),
InlineData(
"f*.",
new string[] { @"foo. ", @"foo. ", @"foo..", @"foo. t" },
// Really should be: new string[] { @"foo.." }), but is
new string[] { @"foo. ", @"foo. ", @"foo.." }),
InlineData(
"fo*.",
new string[] { @"foo. ", @"foo. ", @"foo..", @"foo. t" },
// Really should be: new string[] { @"foo.." }), but is
new string[] { @"foo. ", @"foo. ", @"foo.." }),
InlineData(
"foo*.",
new string[] { @"foo. ", @"foo. ", @"foo. ", @"foo. " },
// Really should be: new string[] { }), but is
new string[] { @"foo. ", @"foo. ", @"foo. ", @"foo. " }),
InlineData(
"foo*.",
new string[] { @"foo. ", @"foo. ", @"foo. ", @"foo. ", @"foo." },
// Really should be: new string[] { @"foo." }), but is
new string[] { @"foo. ", @"foo. ", @"foo. ", @"foo. ", @"foo." }),
InlineData(
"foo*.",
new string[] { @"foo.", @"foo. ", @"foo. ", @"foo. ", @"foo. " },
// Really should be: new string[] { @"foo." }), but is
new string[] { @"foo. ", @"foo. ", @"foo. ", @"foo." }),
InlineData(
"foo*.",
new string[] { @"foo.", @"foo", @"foo. ", @"foo. ", @"foo. ", @"foo. " },
// Really should be: new string[] { @"foo.", @"foo" }), but is
new string[] { @"foo.", @"foo", @"foo. ", @"foo. ", @"foo. " }),
InlineData(
"foo*.",
new string[] { @"foo.", @"foo. ", @"foo. ", @"foo. ", @"foo. ", @"foo" },
// Really should be: new string[] { @"foo.", @"foo" }), but is
new string[] { @"foo.", @"foo", @"foo. ", @"foo. ", @"foo. " }),
InlineData(
"foo*.",
new string[] { @"foo. ", @"foo", @"foo.", @"foo. ", @"foo. ", @"foo. " },
// Really should be: new string[] { @"foo.", @"foo" }), but is
new string[] { @"foo.", @"foo", @"foo. ", @"foo. ", @"foo. " }),
InlineData(
"foo*.",
new string[] { @"foo. ", @"foo", @"food", @"foo.", @"foo. ", @"foo. ", @"foo. " },
// Really should be: new string[] { @"foo.", @"foo", @"food" }), but is
new string[] { @"foo.", @"foo", @"foo. ", @"foo. ", @"foo. ", @"food" }),
InlineData(
"fo*.",
new string[] { @"foo.", @"foo. ", @"foo. ", @"foo. ", @"foo. " },
// Really should be: new string[] { @"foo." }), but is
new string[] { @"foo. ", @"foo. ", @"foo. ", @"foo.", @"foo. " }),
InlineData(
"foo*.",
new string[] { @"foo. ", @"foo. ", @"foo. ", @"foo. ", @"foo. " },
// Really should be: new string[] { }), but is
new string[] { @"foo. ", @"foo. ", @"foo. ", @"foo. " }),
InlineData(
"foo*.",
new string[] { @"foo. ", @"foo. .", @"foo. . ", @"foo. . .", @"foo. . . " },
// Really should be: new string[] { @"foo. .", @"foo. . ." }), but is
new string[] { @"foo. ", @"foo. .", @"foo. . ", @"foo. . ." }),
InlineData(
"foo*.",
new string[] { @"foo. ", @"foo. .", @"foo.. .", @"foo.... .", @"foo..... ." },
// Really should be: new string[] { @"foo. .", @"foo.. .", @"foo.... .", @"foo..... ." }), but is
new string[] { @"foo. ", @"foo. .", @"foo.. .", @"foo.... .", @"foo..... ." }),
InlineData(
"fo*.",
new string[] { @"foo. ", @"foo. .", @"foo. . ", @"foo. . .", @"foo. . . " },
// Really should be: new string[] { @"foo. .", @"foo. . ."}), but is
new string[] { @"foo. ", @"foo. .", @"foo. . ", @"foo. . .", @"foo. . . " }),
InlineData(
"foo*.",
new string[] { @"foo.", @"foo. ", @"foo. ", @"foo. ", @"foo. ", @"foo. " },
// Really should be: new string[] { @"foo." }), but is
new string[] { @"foo.", @"foo. ", @"foo. ", @"foo. " }),
InlineData(
"food*.",
new string[] { @"food.", @"food. ", @"food. ", @"food. ", @"food. ", @"food. " },
// Really should be: new string[] { @"food." }), but is
new string[] { @"food.", @"food. ", @"food. ", @"food. " }),
InlineData(
"food*.",
new string[] { @"food.", @"food. ", @"food. ", @"food. ", @"food. ", @"food. ", @"foodi." },
// Really should be: new string[] { @"food.", @"foodi." }), but is
new string[] { @"food.", @"food. ", @"food. ", @"food. ", @"foodi." }),
InlineData(
"foodi*.",
new string[] { @"foodi.", @"foodi. ", @"foodi. ", @"foodi. ", @"foodi. ", @"foodi. " },
// Really should be: new string[] { @"foodi." }), but is
new string[] { @"foodi.", @"foodi. ", @"foodi. ", @"foodi. " }),
InlineData(
"foodie*.",
new string[] { @"foodie.", @"foodie. ", @"foodie. ", @"foodie. ", @"foodie. ", @"foodie. " },
// Really should be: new string[] { @"foodie." }), but is
new string[] { @"foodie.", @"foodie. ", @"foodie. ", @"foodie. " }),
InlineData(
"fooooo*.",
new string[] { @"foooooo.", @"foooooo. ", @"foooooo. " },
// Really should be: new string[] { @"foooooo." }), but is
new string[] { @"foooooo.", @"foooooo. ", @"foooooo. " }),
InlineData(
"fooooo*.",
new string[] { @"foooooo. ", @"foooooo. ", @"foooooo. " },
// Really should be: new string[] { }), but is
new string[] { @"foooooo. ", @"foooooo. ", @"foooooo. " }),
InlineData(
"fo*.",
new string[] { @"foo. ", @"foo. ", @"foo. ", @"foo. ", @"foo. " },
// Really should be: new string[] { }), but is
new string[] { @"foo. ", @"foo. ", @"foo. ", @"foo. ", @"foo. " }),
InlineData(
"fo*.",
new string[] { @"foo. ", @"foo. ", @"foo. ", @"foo. ", @"foo. ", @"foo. ", @"foo. " },
// Really should be: new string[] { }), but is
new string[] { @"foo. ", @"foo. ", @"foo. ", @"foo. ", @"foo. ", @"foo. ", @"foo. " }),
InlineData(
"fo*.",
new string[] { @"fo. ", @"fo. ", @"fo. ", @"fo. ", @"foo. ", @"foo. ", @"foo. ", @"foo. ", @"foo. ", @"foo. " },
// Really should be: new string[] { }), but is
new string[] { @"fo. ", @"fo. ", @"fo. ", @"fo. ", @"foo. ", @"foo. ", @"foo. ", @"foo. ", @"foo. ", @"foo. " }),
InlineData(
"fo*.",
new string[] { @"fo. ", @"fo. ", @"fo. ", @"fo. ", @"fo. ", @"fo. ", @"foo. ", @"foo. ", @"foo. ", @"foo. ", @"foo. ", @"foo. " },
// Really should be: new string[] { }), but is
new string[] { @"fo. ", @"fo. ", @"fo. ", @"fo. ", @"fo. ", @"fo. ", @"foo. ", @"foo. ", @"foo. ", @"foo. ", @"foo. ", @"foo. " }),
InlineData(
"foo*.",
new string[] { @"foo. ", @"foo. ", @"foo..", @"foo. t", @"foo. ", @"foo. " },
// Really should be: new string[] { @"foo.." }), but is
new string[] { @"foo. ", @"foo. ", @"foo. ", @"foo.." }),
]
public void PatternTests_DosStarOddSpace(string pattern, string[] sourceFiles, string[] expected)
{
// Tests for DOS_STAR, which only occurs when the source pattern ends in *.
// These cases don't match documented behavior on Windows- matching *should* end at the final period.
// We don't want to eat trailing space/periods in this test
string testDir = PrepareDirectory(sourceFiles, useExtendedPaths: true);
ValidatePatternMatch(expected, GetEntries(testDir, pattern));
}
private string PrepareDirectory(string[] sourceFiles, bool useExtendedPaths = false)
{
string testDir = Directory.CreateDirectory(GetTestFilePath()).FullName;
foreach (string file in sourceFiles)
CreateItem(useExtendedPaths && PlatformDetection.IsWindows
? @"\\?\" + Path.Combine(testDir, file)
: Path.Combine(testDir, file));
return testDir;
}
private void ValidatePatternMatch(string[] expected, string[] result)
{
Assert.Equal(expected.OrderBy(s => s), result.Select(Path.GetFileName).OrderBy(s => s));
}
#endregion
#region PlatformSpecific
[PlatformSpecific(TestPlatforms.AnyUnix)]
[Theory,
InlineData(
@"foo\bar",
new string[] { @"foo", @"bar", @"foo\bar" },
new string[] { @"foo\bar" }),
]
public void PatternTests_UnixEscape(string pattern, string[] sourceFiles, string[] expected)
{
// We shouldn't be allowing escaping in Unix filename searches
string testDir = PrepareDirectory(sourceFiles);
ValidatePatternMatch(expected, GetEntries(testDir, pattern));
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)] // Long path segment in search pattern throws PathTooLongException
public void WindowsSearchPatternLongSegment()
{
// Create a path segment longer than the normal max of 255
DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath());
string longName = new string('k', 257);
Assert.Throws<PathTooLongException>(() => GetEntries(testDir.FullName, longName));
}
[ConditionalFact(nameof(AreAllLongPathsAvailable))]
[ActiveIssue(20117, TargetFrameworkMonikers.Uap)]
public void SearchPatternLongPath()
{
// Create a destination path longer than the traditional Windows limit of 256 characters
DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath());
string longName = new string('k', 254);
string longFullname = Path.Combine(testDir.FullName, longName);
if (TestFiles)
{
using (File.Create(longFullname)) { }
}
else
{
Directory.CreateDirectory(longFullname);
}
string[] results = GetEntries(testDir.FullName, longName);
Assert.Contains(longFullname, results);
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)] // Search pattern with double dots throws ArgumentException
public void WindowsSearchPatternWithDoubleDots()
{
Assert.Throws<ArgumentException>(() => GetEntries(TestDirectory, Path.Combine("..ab ab.. .. abc..d", "abc..")));
Assert.Throws<ArgumentException>(() => GetEntries(TestDirectory, ".."));
Assert.Throws<ArgumentException>(() => GetEntries(TestDirectory, @".." + Path.DirectorySeparatorChar));
}
private static char[] OldWildcards = new char[] { '*', '?' };
private static char[] NewWildcards = new char[] { '<', '>', '\"' };
[Fact]
[PlatformSpecific(TestPlatforms.Windows)] // Windows-invalid search patterns throw
public void WindowsSearchPatternInvalid()
{
Assert.Throws<ArgumentException>(() => GetEntries(TestDirectory, "\0"));
Assert.Throws<ArgumentException>(() => GetEntries(TestDirectory, "|"));
Assert.All(Path.GetInvalidFileNameChars().Except(OldWildcards).Except(NewWildcards), invalidChar =>
{
switch (invalidChar)
{
case '\\':
case '/':
Assert.Throws<DirectoryNotFoundException>(() => GetEntries(Directory.GetCurrentDirectory(), string.Format("te{0}st", invalidChar.ToString())));
break;
//We don't throw in V1 too
case ':':
//History:
// 1) we assumed that this will work in all non-9x machine
// 2) Then only in XP
// 3) NTFS?
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows) &&
FileSystemDebugInfo.IsCurrentDriveNTFS()) // testing NTFS
{
Assert.Throws<IOException>(() => GetEntries(Directory.GetCurrentDirectory(), string.Format("te{0}st", invalidChar.ToString())));
}
else
{
GetEntries(Directory.GetCurrentDirectory(), string.Format("te{0}st", invalidChar.ToString()));
}
break;
default:
Assert.Throws<ArgumentException>(() => GetEntries(Directory.GetCurrentDirectory(), string.Format("te{0}st", invalidChar.ToString())));
break;
}
});
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)] // Windows-invalid search patterns throw
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "In netcoreapp we made three new characters be treated as valid wildcards instead of invalid characters. NetFX still treats them as InvalidChars.")]
public void WindowsSearchPatternInvalid_Wildcards_netcoreapp()
{
Assert.All(OldWildcards, invalidChar =>
{
GetEntries(Directory.GetCurrentDirectory(), string.Format("te{0}st", invalidChar.ToString()));
});
Assert.All(NewWildcards, invalidChar =>
{
GetEntries(Directory.GetCurrentDirectory(), string.Format("te{0}st", invalidChar.ToString()));
});
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)] // Windows-invalid search patterns throw
[SkipOnTargetFramework(~TargetFrameworkMonikers.NetFramework, "In netcoreapp we made three new characters be treated as valid wildcards instead of invalid characters. NetFX still treats them as InvalidChars.")]
public void WindowsSearchPatternInvalid_Wildcards_netfx()
{
Assert.All(OldWildcards, invalidChar =>
{
GetEntries(Directory.GetCurrentDirectory(), string.Format("te{0}st", invalidChar.ToString()));
});
Assert.All(NewWildcards, invalidChar =>
{
Assert.Throws<ArgumentException>(() => GetEntries(Directory.GetCurrentDirectory(), string.Format("te{0}st", invalidChar.ToString())));
});
}
[Fact]
[PlatformSpecific(TestPlatforms.AnyUnix)] // Unix-invalid sarch patterns throw ArgumentException
public void UnixSearchPatternInvalid()
{
Assert.Throws<ArgumentException>(() => GetEntries(TestDirectory, "\0"));
Assert.Throws<ArgumentException>(() => GetEntries(TestDirectory, string.Format("te{0}st", "\0".ToString())));
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)] // ? in search pattern returns results
public virtual void WindowsSearchPatternQuestionMarks()
{
string testDir1Str = GetTestFileName();
DirectoryInfo testDir = new DirectoryInfo(TestDirectory);
DirectoryInfo testDir1 = testDir.CreateSubdirectory(testDir1Str);
using (File.Create(Path.Combine(TestDirectory, testDir1Str, GetTestFileName())))
using (File.Create(Path.Combine(TestDirectory, GetTestFileName())))
{
string[] results = GetEntries(TestDirectory, string.Format("{0}.???", new string('?', GetTestFileName().Length)));
if (TestFiles && TestDirectories)
Assert.Equal(2, results.Length);
else
Assert.Equal(1, results.Length);
}
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)] // Whitespace in search pattern returns nothing
public void WindowsSearchPatternWhitespace()
{
Assert.Empty(GetEntries(TestDirectory, " "));
Assert.Empty(GetEntries(TestDirectory, "\n"));
Assert.Empty(GetEntries(TestDirectory, " "));
Assert.Empty(GetEntries(TestDirectory, "\t"));
}
[Fact]
[PlatformSpecific(CaseSensitivePlatforms)]
public void SearchPatternCaseSensitive()
{
DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath());
string testBase = GetTestFileName();
testDir.CreateSubdirectory(testBase + "aBBb");
testDir.CreateSubdirectory(testBase + "aBBB");
File.Create(Path.Combine(testDir.FullName, testBase + "AAAA")).Dispose();
File.Create(Path.Combine(testDir.FullName, testBase + "aAAa")).Dispose();
if (TestDirectories)
{
Assert.Equal(2, GetEntries(testDir.FullName, "*BB*").Length);
}
if (TestFiles)
{
Assert.Equal(2, GetEntries(testDir.FullName, "*AA*").Length);
}
}
[Fact]
[PlatformSpecific(CaseInsensitivePlatforms)]
public void SearchPatternCaseInsensitive()
{
DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath());
string testBase = GetTestFileName();
testDir.CreateSubdirectory(testBase + "yZZz");
testDir.CreateSubdirectory(testBase + "yZZZ");
File.Create(Path.Combine(testDir.FullName, testBase + "YYYY")).Dispose();
File.Create(Path.Combine(testDir.FullName, testBase + "yYYy")).Dispose();
if (TestDirectories)
{
Assert.Equal(1, GetEntries(testDir.FullName, "*ZZ*").Length);
}
if (TestFiles)
{
Assert.Equal(1, GetEntries(testDir.FullName, "*YY*").Length);
}
}
[Fact]
[PlatformSpecific(TestPlatforms.AnyUnix)] // Unix-valid chars in file search patterns
public void UnixSearchPatternFileValidChar()
{
if (TestFiles)
{
DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath());
foreach (string valid in WindowsInvalidUnixValid)
File.Create(Path.Combine(testDir.FullName, valid)).Dispose();
foreach (string valid in WindowsInvalidUnixValid)
Assert.Contains(Path.Combine(testDir.FullName, valid), GetEntries(testDir.FullName, valid));
}
}
[Fact]
[PlatformSpecific(TestPlatforms.AnyUnix)] // Unix-valid chars in directory search patterns
public void UnixSearchPatternDirectoryValidChar()
{
if (TestDirectories)
{
DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath());
foreach (string valid in WindowsInvalidUnixValid)
testDir.CreateSubdirectory(valid);
foreach (string valid in WindowsInvalidUnixValid)
Assert.Contains(Path.Combine(testDir.FullName, valid), GetEntries(testDir.FullName, valid));
}
}
[Fact]
[PlatformSpecific(TestPlatforms.AnyUnix)] // Search pattern with DoubleDots on Unix
public void UnixSearchPatternWithDoubleDots()
{
// search pattern is valid but directory doesn't exist
Assert.Throws<DirectoryNotFoundException>(() => GetEntries(TestDirectory, Path.Combine("..ab ab.. .. abc..d", "abc..")));
// invalid search pattern trying to go up a directory with ..
Assert.Throws<ArgumentException>(() => GetEntries(TestDirectory, ".."));
Assert.Throws<ArgumentException>(() => GetEntries(TestDirectory, @".." + Path.DirectorySeparatorChar));
Assert.Throws<ArgumentException>(() => GetEntries(TestDirectory, Path.Combine("..ab ab.. .. abc..d", "abc", "..")));
Assert.Throws<ArgumentException>(() => GetEntries(TestDirectory, Path.Combine("..ab ab.. .. abc..d", "..", "abc")));
Assert.Throws<ArgumentException>(() => GetEntries(TestDirectory, Path.Combine("..", "..ab ab.. .. abc..d", "abc")));
Assert.Throws<ArgumentException>(() => GetEntries(TestDirectory, Path.Combine("..", "..ab ab.. .. abc..d", "abc") + Path.DirectorySeparatorChar));
}
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Xunit;
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.overloadResolution.method.Oneclass.Twoparam.accessibility001.accessibility001
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.overloadResolution.method.Oneclass.Twoparam.accessibility001.accessibility001;
public class Test
{
public void Method()
{
}
protected void Method(int x, object o)
{
s_status = 1;
}
internal protected void Method(long x, object o)
{
s_status = 2;
}
internal void Method(short x, object o)
{
s_status = 3;
}
private static int s_status = -1;
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod(null));
}
public static int MainMethod(string[] args)
{
Test b = new Test();
dynamic x = 1;
dynamic y = null;
b.Method(x, y);
return s_status == 1 ? 0 : 1;
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.overloadResolution.method.Oneclass.Twoparam.accessibility002.accessibility002
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.overloadResolution.method.Oneclass.Twoparam.accessibility002.accessibility002;
public class Test
{
public void Method()
{
}
protected void Method(int x, object o)
{
s_status = 1;
}
internal protected void Method(long x, object o)
{
s_status = 2;
}
internal void Method(short x, object o)
{
s_status = 3;
}
private static int s_status = -1;
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod(null));
}
public static int MainMethod(string[] args)
{
var b = new Test();
b.Method();
dynamic x = short.MinValue;
dynamic y = null;
b.Method(x, y);
return s_status == 3 ? 0 : 1;
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.overloadResolution.method.Oneclass.Twoparam.errorverifier.errorverifier
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.overloadResolution.method.Oneclass.Twoparam.errorverifier.errorverifier;
using ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.overloadResolution.method.Oneclass.Twoparam.accessibility003.accessibility003;
using System;
using System.Collections;
using System.IO;
using System.Globalization;
using System.Reflection;
using System.Resources;
using Microsoft.CSharp.RuntimeBinder;
public enum ErrorElementId
{
None,
SK_METHOD, // method
SK_CLASS, // type
SK_NAMESPACE, // namespace
SK_FIELD, // field
SK_PROPERTY, // property
SK_UNKNOWN, // element
SK_VARIABLE, // variable
SK_EVENT, // event
SK_TYVAR, // type parameter
SK_ALIAS, // using alias
ERRORSYM, // <error>
NULL, // <null>
GlobalNamespace, // <global namespace>
MethodGroup, // method group
AnonMethod, // anonymous method
Lambda, // lambda expression
AnonymousType, // anonymous type
}
public enum ErrorMessageId
{
None,
BadBinaryOps, // Operator '{0}' cannot be applied to operands of type '{1}' and '{2}'
IntDivByZero, // Division by constant zero
BadIndexLHS, // Cannot apply indexing with [] to an expression of type '{0}'
BadIndexCount, // Wrong number of indices inside []; expected '{0}'
BadUnaryOp, // Operator '{0}' cannot be applied to operand of type '{1}'
NoImplicitConv, // Cannot implicitly convert type '{0}' to '{1}'
NoExplicitConv, // Cannot convert type '{0}' to '{1}'
ConstOutOfRange, // Constant value '{0}' cannot be converted to a '{1}'
AmbigBinaryOps, // Operator '{0}' is ambiguous on operands of type '{1}' and '{2}'
AmbigUnaryOp, // Operator '{0}' is ambiguous on an operand of type '{1}'
ValueCantBeNull, // Cannot convert null to '{0}' because it is a non-nullable value type
WrongNestedThis, // Cannot access a non-static member of outer type '{0}' via nested type '{1}'
NoSuchMember, // '{0}' does not contain a definition for '{1}'
ObjectRequired, // An object reference is required for the non-static field, method, or property '{0}'
AmbigCall, // The call is ambiguous between the following methods or properties: '{0}' and '{1}'
BadAccess, // '{0}' is inaccessible due to its protection level
MethDelegateMismatch, // No overload for '{0}' matches delegate '{1}'
AssgLvalueExpected, // The left-hand side of an assignment must be a variable, property or indexer
NoConstructors, // The type '{0}' has no constructors defined
BadDelegateConstructor, // The delegate '{0}' does not have a valid constructor
PropertyLacksGet, // The property or indexer '{0}' cannot be used in this context because it lacks the get accessor
ObjectProhibited, // Member '{0}' cannot be accessed with an instance reference; qualify it with a type name instead
AssgReadonly, // A readonly field cannot be assigned to (except in a constructor or a variable initializer)
RefReadonly, // A readonly field cannot be passed ref or out (except in a constructor)
AssgReadonlyStatic, // A static readonly field cannot be assigned to (except in a static constructor or a variable initializer)
RefReadonlyStatic, // A static readonly field cannot be passed ref or out (except in a static constructor)
AssgReadonlyProp, // Property or indexer '{0}' cannot be assigned to -- it is read only
AbstractBaseCall, // Cannot call an abstract base member: '{0}'
RefProperty, // A property or indexer may not be passed as an out or ref parameter
ManagedAddr, // Cannot take the address of, get the size of, or declare a pointer to a managed type ('{0}')
FixedNotNeeded, // You cannot use the fixed statement to take the address of an already fixed expression
UnsafeNeeded, // Dynamic calls cannot be used in conjunction with pointers
BadBoolOp, // In order to be applicable as a short circuit operator a user-defined logical operator ('{0}') must have the same return type as the type of its 2 parameters
MustHaveOpTF, // The type ('{0}') must contain declarations of operator true and operator false
CheckedOverflow, // The operation overflows at compile time in checked mode
ConstOutOfRangeChecked, // Constant value '{0}' cannot be converted to a '{1}' (use 'unchecked' syntax to override)
AmbigMember, // Ambiguity between '{0}' and '{1}'
SizeofUnsafe, // '{0}' does not have a predefined size, therefore sizeof can only be used in an unsafe context (consider using System.Runtime.InteropServices.Marshal.SizeOf)
FieldInitRefNonstatic, // A field initializer cannot reference the non-static field, method, or property '{0}'
CallingFinalizeDepracated, // Destructors and object.Finalize cannot be called directly. Consider calling IDisposable.Dispose if available.
CallingBaseFinalizeDeprecated, // Do not directly call your base class Finalize method. It is called automatically from your destructor.
BadCastInFixed, // The right hand side of a fixed statement assignment may not be a cast expression
NoImplicitConvCast, // Cannot implicitly convert type '{0}' to '{1}'. An explicit conversion exists (are you missing a cast?)
InaccessibleGetter, // The property or indexer '{0}' cannot be used in this context because the get accessor is inaccessible
InaccessibleSetter, // The property or indexer '{0}' cannot be used in this context because the set accessor is inaccessible
BadArity, // Using the generic {1} '{0}' requires '{2}' type arguments
BadTypeArgument, // The type '{0}' may not be used as a type argument
TypeArgsNotAllowed, // The {1} '{0}' cannot be used with type arguments
HasNoTypeVars, // The non-generic {1} '{0}' cannot be used with type arguments
NewConstraintNotSatisfied, // '{2}' must be a non-abstract type with a public parameterless constructor in order to use it as parameter '{1}' in the generic type or method '{0}'
GenericConstraintNotSatisfiedRefType, // The type '{3}' cannot be used as type parameter '{2}' in the generic type or method '{0}'. There is no implicit reference conversion from '{3}' to '{1}'.
GenericConstraintNotSatisfiedNullableEnum, // The type '{3}' cannot be used as type parameter '{2}' in the generic type or method '{0}'. The nullable type '{3}' does not satisfy the constraint of '{1}'.
GenericConstraintNotSatisfiedNullableInterface, // The type '{3}' cannot be used as type parameter '{2}' in the generic type or method '{0}'. The nullable type '{3}' does not satisfy the constraint of '{1}'. Nullable types can not satisfy any interface constraints.
GenericConstraintNotSatisfiedTyVar, // The type '{3}' cannot be used as type parameter '{2}' in the generic type or method '{0}'. There is no boxing conversion or type parameter conversion from '{3}' to '{1}'.
GenericConstraintNotSatisfiedValType, // The type '{3}' cannot be used as type parameter '{2}' in the generic type or method '{0}'. There is no boxing conversion from '{3}' to '{1}'.
TypeVarCantBeNull, // Cannot convert null to type parameter '{0}' because it could be a non-nullable value type. Consider using 'default({0})' instead.
BadRetType, // '{1} {0}' has the wrong return type
CantInferMethTypeArgs, // The type arguments for method '{0}' cannot be inferred from the usage. Try specifying the type arguments explicitly.
MethGrpToNonDel, // Cannot convert method group '{0}' to non-delegate type '{1}'. Did you intend to invoke the method?
RefConstraintNotSatisfied, // The type '{2}' must be a reference type in order to use it as parameter '{1}' in the generic type or method '{0}'
ValConstraintNotSatisfied, // The type '{2}' must be a non-nullable value type in order to use it as parameter '{1}' in the generic type or method '{0}'
CircularConstraint, // Circular constraint dependency involving '{0}' and '{1}'
BaseConstraintConflict, // Type parameter '{0}' inherits conflicting constraints '{1}' and '{2}'
ConWithValCon, // Type parameter '{1}' has the 'struct' constraint so '{1}' cannot be used as a constraint for '{0}'
AmbigUDConv, // Ambiguous user defined conversions '{0}' and '{1}' when converting from '{2}' to '{3}'
PredefinedTypeNotFound, // Predefined type '{0}' is not defined or imported
PredefinedTypeBadType, // Predefined type '{0}' is declared incorrectly
BindToBogus, // '{0}' is not supported by the language
CantCallSpecialMethod, // '{0}': cannot explicitly call operator or accessor
BogusType, // '{0}' is a type not supported by the language
MissingPredefinedMember, // Missing compiler required member '{0}.{1}'
LiteralDoubleCast, // Literal of type double cannot be implicitly converted to type '{1}'; use an '{0}' suffix to create a literal of this type
UnifyingInterfaceInstantiations, // '{0}' cannot implement both '{1}' and '{2}' because they may unify for some type parameter substitutions
ConvertToStaticClass, // Cannot convert to static type '{0}'
GenericArgIsStaticClass, // '{0}': static types cannot be used as type arguments
PartialMethodToDelegate, // Cannot create delegate from method '{0}' because it is a partial method without an implementing declaration
IncrementLvalueExpected, // The operand of an increment or decrement operator must be a variable, property or indexer
NoSuchMemberOrExtension, // '{0}' does not contain a definition for '{1}' and no extension method '{1}' accepting a first argument of type '{0}' could be found (are you missing a using directive or an assembly reference?)
ValueTypeExtDelegate, // Extension methods '{0}' defined on value type '{1}' cannot be used to create delegates
BadArgCount, // No overload for method '{0}' takes '{1}' arguments
BadArgTypes, // The best overloaded method match for '{0}' has some invalid arguments
BadArgType, // Argument '{0}': cannot convert from '{1}' to '{2}'
RefLvalueExpected, // A ref or out argument must be an assignable variable
BadProtectedAccess, // Cannot access protected member '{0}' via a qualifier of type '{1}'; the qualifier must be of type '{2}' (or derived from it)
BindToBogusProp2, // Property, indexer, or event '{0}' is not supported by the language; try directly calling accessor methods '{1}' or '{2}'
BindToBogusProp1, // Property, indexer, or event '{0}' is not supported by the language; try directly calling accessor method '{1}'
BadDelArgCount, // Delegate '{0}' does not take '{1}' arguments
BadDelArgTypes, // Delegate '{0}' has some invalid arguments
AssgReadonlyLocal, // Cannot assign to '{0}' because it is read-only
RefReadonlyLocal, // Cannot pass '{0}' as a ref or out argument because it is read-only
ReturnNotLValue, // Cannot modify the return value of '{0}' because it is not a variable
BadArgExtraRef, // Argument '{0}' should not be passed with the '{1}' keyword
// DelegateOnConditional, // Cannot create delegate with '{0}' because it has a Conditional attribute (REMOVED)
BadArgRef, // Argument '{0}' must be passed with the '{1}' keyword
AssgReadonly2, // Members of readonly field '{0}' cannot be modified (except in a constructor or a variable initializer)
RefReadonly2, // Members of readonly field '{0}' cannot be passed ref or out (except in a constructor)
AssgReadonlyStatic2, // Fields of static readonly field '{0}' cannot be assigned to (except in a static constructor or a variable initializer)
RefReadonlyStatic2, // Fields of static readonly field '{0}' cannot be passed ref or out (except in a static constructor)
AssgReadonlyLocalCause, // Cannot assign to '{0}' because it is a '{1}'
RefReadonlyLocalCause, // Cannot pass '{0}' as a ref or out argument because it is a '{1}'
ThisStructNotInAnonMeth, // Anonymous methods, lambda expressions, and query expressions inside structs cannot access instance members of 'this'. Consider copying 'this' to a local variable outside the anonymous method, lambda expression or query expression and using the local instead.
DelegateOnNullable, // Cannot bind delegate to '{0}' because it is a member of 'System.Nullable<T>'
BadCtorArgCount, // '{0}' does not contain a constructor that takes '{1}' arguments
BadExtensionArgTypes, // '{0}' does not contain a definition for '{1}' and the best extension method overload '{2}' has some invalid arguments
BadInstanceArgType, // Instance argument: cannot convert from '{0}' to '{1}'
BadArgTypesForCollectionAdd, // The best overloaded Add method '{0}' for the collection initializer has some invalid arguments
InitializerAddHasParamModifiers, // The best overloaded method match '{0}' for the collection initializer element cannot be used. Collection initializer 'Add' methods cannot have ref or out parameters.
NonInvocableMemberCalled, // Non-invocable member '{0}' cannot be used like a method.
NamedArgumentSpecificationBeforeFixedArgument, // Named argument specifications must appear after all fixed arguments have been specified
BadNamedArgument, // The best overload for '{0}' does not have a parameter named '{1}'
BadNamedArgumentForDelegateInvoke, // The delegate '{0}' does not have a parameter named '{1}'
DuplicateNamedArgument, // Named argument '{0}' cannot be specified multiple times
NamedArgumentUsedInPositional, // Named argument '{0}' specifies a parameter for which a positional argument has already been given
}
public enum RuntimeErrorId
{
None,
// RuntimeBinderInternalCompilerException
InternalCompilerError, // An unexpected exception occurred while binding a dynamic operation
// ArgumentException
BindRequireArguments, // Cannot bind call with no calling object
// RuntimeBinderException
BindCallFailedOverloadResolution, // Overload resolution failed
// ArgumentException
BindBinaryOperatorRequireTwoArguments, // Binary operators must be invoked with two arguments
// ArgumentException
BindUnaryOperatorRequireOneArgument, // Unary operators must be invoked with one argument
// RuntimeBinderException
BindPropertyFailedMethodGroup, // The name '{0}' is bound to a method and cannot be used like a property
// RuntimeBinderException
BindPropertyFailedEvent, // The event '{0}' can only appear on the left hand side of += or -=
// RuntimeBinderException
BindInvokeFailedNonDelegate, // Cannot invoke a non-delegate type
// ArgumentException
BindImplicitConversionRequireOneArgument, // Implicit conversion takes exactly one argument
// ArgumentException
BindExplicitConversionRequireOneArgument, // Explicit conversion takes exactly one argument
// ArgumentException
BindBinaryAssignmentRequireTwoArguments, // Binary operators cannot be invoked with one argument
// RuntimeBinderException
BindBinaryAssignmentFailedNullReference, // Cannot perform member assignment on a null reference
// RuntimeBinderException
NullReferenceOnMemberException, // Cannot perform runtime binding on a null reference
// RuntimeBinderException
BindCallToConditionalMethod, // Cannot dynamically invoke method '{0}' because it has a Conditional attribute
// RuntimeBinderException
BindToVoidMethodButExpectResult, // Cannot implicitly convert type 'void' to 'object'
// EE?
EmptyDynamicView, // No further information on this object could be discovered
// MissingMemberException
GetValueonWriteOnlyProperty, // Write Only properties are not supported
}
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.overloadResolution.method.Oneclass.Twoparam.accessibility003.accessibility003
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.overloadResolution.method.Oneclass.Twoparam.errorverifier.errorverifier;
using ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.overloadResolution.method.Oneclass.Twoparam.accessibility003.accessibility003;
public class Test
{
private delegate void Del(long x, int y);
public void Method(long x, int y)
{
}
private void Method(int x, int y)
{
}
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod(null));
}
public static int MainMethod(string[] args)
{
dynamic b = new Test();
try
{
Del ddd = new Del(b.Method);
dynamic d1 = 1;
dynamic d2 = 2;
ddd(d1, d2);
}
catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException e)
{
return 0;
}
return 1;
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.overloadResolution.method.Oneclass.Twoparam.accessibility004.accessibility004
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.overloadResolution.method.Oneclass.Twoparam.accessibility004.accessibility004;
// <Title>Accessibility</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
// <Expects Status=success></Expects>
// <Code>
public struct Test
{
public void Method()
{
}
private void Method(int x, object o)
{
s_status = 1;
}
internal void Method(long x, object o)
{
s_status = 2;
}
internal void Method(short x, object o)
{
s_status = 3;
}
private static int s_status = -1;
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod(null));
}
public static int MainMethod(string[] args)
{
Test b = new Test();
dynamic x = -1;
dynamic y = null;
b.Method(x, y);
return s_status == 1 ? 0 : 1;
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.overloadResolution.method.Oneclass.Twoparam.accessibility005.accessibility005
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.overloadResolution.method.Oneclass.Twoparam.accessibility005.accessibility005;
public class Test
{
private class Base
{
public void Method(int x)
{
}
}
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod(null));
}
public static int MainMethod(string[] args)
{
Base b = new Base();
dynamic x = int.MaxValue;
b.Method(x);
return 0;
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.overloadResolution.method.Oneclass.Twoparam.accessibility006.accessibility006
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.overloadResolution.method.Oneclass.Twoparam.accessibility006.accessibility006;
public class Test
{
protected class Base
{
public void Method()
{
}
protected void Method(int x, object o)
{
}
internal protected void Method(long x, object o)
{
}
internal void Method(short x, object o)
{
}
public void Method(byte x, object o)
{
}
}
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod(null));
}
public static int MainMethod(string[] args)
{
Base b = new Base();
dynamic x = byte.MaxValue;
dynamic y = new object();
b.Method(x, y);
return 0;
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.overloadResolution.method.Oneclass.Twoparam.accessibility007.accessibility007
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.overloadResolution.method.Oneclass.Twoparam.accessibility007.accessibility007;
public class Test
{
public void Method(int x, int y)
{
s_status = 1;
}
private void Method(long x, int y)
{
s_status = 2;
}
internal void Method1(short x, int y)
{
s_status = 3;
}
protected void Method1(long x, int y)
{
s_status = 4;
}
private static int s_status = -1;
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod(null));
}
public static int MainMethod(string[] args)
{
dynamic b = new Test();
dynamic d1 = 1;
dynamic d2 = 2;
b.Method(d1, d2);
bool ret = s_status == 1;
b.Method1(d1, d2);
ret &= (s_status == 4);
return ret ? 0 : 1;
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.overloadResolution.method.Oneclass.Twoparam.accessibility011.accessibility011
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.overloadResolution.method.Oneclass.Twoparam.accessibility011.accessibility011;
public class Test
{
public class Higher
{
private class Base
{
public void Method(int x)
{
}
}
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod(null));
}
public static int MainMethod(string[] args)
{
Base b = new Base();
dynamic x = int.MaxValue;
b.Method(x);
return 0;
}
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.overloadResolution.method.Oneclass.Twoparam.accessibility012.accessibility012
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.overloadResolution.method.Oneclass.Twoparam.accessibility012.accessibility012;
public class Test
{
internal class Base
{
public void Method(int x)
{
Test.Status = 1;
}
}
public static int Status;
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod(null));
}
public static int MainMethod(string[] args)
{
Base b = new Base();
dynamic x = int.MaxValue;
b.Method(x);
if (Test.Status == 1)
return 0;
return 1;
}
}
// </Code>
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using Microsoft.Xml;
using System.Diagnostics;
using System.Collections.Generic;
namespace Microsoft.Xml.Schema
{
using System;
using Microsoft.Xml;
internal enum AttributeMatchState
{
AttributeFound,
AnyIdAttributeFound,
UndeclaredElementAndAttribute,
UndeclaredAttribute,
AnyAttributeLax,
AnyAttributeSkip,
ProhibitedAnyAttribute,
ProhibitedAttribute,
AttributeNameMismatch,
ValidateAttributeInvalidCall,
}
internal class SchemaInfo : IDtdInfo
{
private Dictionary<XmlQualifiedName, SchemaElementDecl> _elementDecls = new Dictionary<XmlQualifiedName, SchemaElementDecl>();
private Dictionary<XmlQualifiedName, SchemaElementDecl> _undeclaredElementDecls = new Dictionary<XmlQualifiedName, SchemaElementDecl>();
private Dictionary<XmlQualifiedName, SchemaEntity> _generalEntities;
private Dictionary<XmlQualifiedName, SchemaEntity> _parameterEntities;
private XmlQualifiedName _docTypeName = XmlQualifiedName.Empty;
private string _internalDtdSubset = string.Empty;
private bool _hasNonCDataAttributes = false;
private bool _hasDefaultAttributes = false;
private Dictionary<string, bool> _targetNamespaces = new Dictionary<string, bool>();
private Dictionary<XmlQualifiedName, SchemaAttDef> _attributeDecls = new Dictionary<XmlQualifiedName, SchemaAttDef>();
private int _errorCount;
private SchemaType _schemaType;
private Dictionary<XmlQualifiedName, SchemaElementDecl> _elementDeclsByType = new Dictionary<XmlQualifiedName, SchemaElementDecl>();
private Dictionary<string, SchemaNotation> _notations;
internal SchemaInfo()
{
_schemaType = SchemaType.None;
}
public XmlQualifiedName DocTypeName
{
get { return _docTypeName; }
set { _docTypeName = value; }
}
internal string InternalDtdSubset
{
get { return _internalDtdSubset; }
set { _internalDtdSubset = value; }
}
internal Dictionary<XmlQualifiedName, SchemaElementDecl> ElementDecls
{
get { return _elementDecls; }
}
internal Dictionary<XmlQualifiedName, SchemaElementDecl> UndeclaredElementDecls
{
get { return _undeclaredElementDecls; }
}
internal Dictionary<XmlQualifiedName, SchemaEntity> GeneralEntities
{
get
{
if (_generalEntities == null)
{
_generalEntities = new Dictionary<XmlQualifiedName, SchemaEntity>();
}
return _generalEntities;
}
}
internal Dictionary<XmlQualifiedName, SchemaEntity> ParameterEntities
{
get
{
if (_parameterEntities == null)
{
_parameterEntities = new Dictionary<XmlQualifiedName, SchemaEntity>();
}
return _parameterEntities;
}
}
internal SchemaType SchemaType
{
get { return _schemaType; }
set { _schemaType = value; }
}
internal Dictionary<string, bool> TargetNamespaces
{
get { return _targetNamespaces; }
}
internal Dictionary<XmlQualifiedName, SchemaElementDecl> ElementDeclsByType
{
get { return _elementDeclsByType; }
}
internal Dictionary<XmlQualifiedName, SchemaAttDef> AttributeDecls
{
get { return _attributeDecls; }
}
internal Dictionary<string, SchemaNotation> Notations
{
get
{
if (_notations == null)
{
_notations = new Dictionary<string, SchemaNotation>();
}
return _notations;
}
}
internal int ErrorCount
{
get { return _errorCount; }
set { _errorCount = value; }
}
internal SchemaElementDecl GetElementDecl(XmlQualifiedName qname)
{
SchemaElementDecl elemDecl;
if (_elementDecls.TryGetValue(qname, out elemDecl))
{
return elemDecl;
}
return null;
}
internal SchemaElementDecl GetTypeDecl(XmlQualifiedName qname)
{
SchemaElementDecl elemDecl;
if (_elementDeclsByType.TryGetValue(qname, out elemDecl))
{
return elemDecl;
}
return null;
}
internal XmlSchemaElement GetElement(XmlQualifiedName qname)
{
SchemaElementDecl ed = GetElementDecl(qname);
if (ed != null)
{
return ed.SchemaElement;
}
return null;
}
internal XmlSchemaAttribute GetAttribute(XmlQualifiedName qname)
{
SchemaAttDef attdef = (SchemaAttDef)_attributeDecls[qname];
if (attdef != null)
{
return attdef.SchemaAttribute;
}
return null;
}
internal XmlSchemaElement GetType(XmlQualifiedName qname)
{
SchemaElementDecl ed = GetElementDecl(qname);
if (ed != null)
{
return ed.SchemaElement;
}
return null;
}
internal bool HasSchema(string ns)
{
return _targetNamespaces.ContainsKey(ns);
}
internal bool Contains(string ns)
{
return _targetNamespaces.ContainsKey(ns);
}
internal SchemaAttDef GetAttributeXdr(SchemaElementDecl ed, XmlQualifiedName qname)
{
SchemaAttDef attdef = null;
if (ed != null)
{
attdef = ed.GetAttDef(qname); ;
if (attdef == null)
{
if (!ed.ContentValidator.IsOpen || qname.Namespace.Length == 0)
{
throw new XmlSchemaException(ResXml.Sch_UndeclaredAttribute, qname.ToString());
}
if (!_attributeDecls.TryGetValue(qname, out attdef) && _targetNamespaces.ContainsKey(qname.Namespace))
{
throw new XmlSchemaException(ResXml.Sch_UndeclaredAttribute, qname.ToString());
}
}
}
return attdef;
}
internal SchemaAttDef GetAttributeXsd(SchemaElementDecl ed, XmlQualifiedName qname, XmlSchemaObject partialValidationType, out AttributeMatchState attributeMatchState)
{
SchemaAttDef attdef = null;
attributeMatchState = AttributeMatchState.UndeclaredAttribute;
if (ed != null)
{
attdef = ed.GetAttDef(qname);
if (attdef != null)
{
attributeMatchState = AttributeMatchState.AttributeFound;
return attdef;
}
XmlSchemaAnyAttribute any = ed.AnyAttribute;
if (any != null)
{
if (!any.NamespaceList.Allows(qname))
{
attributeMatchState = AttributeMatchState.ProhibitedAnyAttribute;
}
else if (any.ProcessContentsCorrect != XmlSchemaContentProcessing.Skip)
{
if (_attributeDecls.TryGetValue(qname, out attdef))
{
if (attdef.Datatype.TypeCode == XmlTypeCode.Id)
{ //anyAttribute match whose type is ID
attributeMatchState = AttributeMatchState.AnyIdAttributeFound;
}
else
{
attributeMatchState = AttributeMatchState.AttributeFound;
}
}
else if (any.ProcessContentsCorrect == XmlSchemaContentProcessing.Lax)
{
attributeMatchState = AttributeMatchState.AnyAttributeLax;
}
}
else
{
attributeMatchState = AttributeMatchState.AnyAttributeSkip;
}
}
else if (ed.ProhibitedAttributes.ContainsKey(qname))
{
attributeMatchState = AttributeMatchState.ProhibitedAttribute;
}
}
else if (partialValidationType != null)
{
XmlSchemaAttribute attr = partialValidationType as XmlSchemaAttribute;
if (attr != null)
{
if (qname.Equals(attr.QualifiedName))
{
attdef = attr.AttDef;
attributeMatchState = AttributeMatchState.AttributeFound;
}
else
{
attributeMatchState = AttributeMatchState.AttributeNameMismatch;
}
}
else
{
attributeMatchState = AttributeMatchState.ValidateAttributeInvalidCall;
}
}
else
{
if (_attributeDecls.TryGetValue(qname, out attdef))
{
attributeMatchState = AttributeMatchState.AttributeFound;
}
else
{
attributeMatchState = AttributeMatchState.UndeclaredElementAndAttribute;
}
}
return attdef;
}
internal SchemaAttDef GetAttributeXsd(SchemaElementDecl ed, XmlQualifiedName qname, ref bool skip)
{
AttributeMatchState attributeMatchState;
SchemaAttDef attDef = GetAttributeXsd(ed, qname, null, out attributeMatchState);
switch (attributeMatchState)
{
case AttributeMatchState.UndeclaredAttribute:
throw new XmlSchemaException(ResXml.Sch_UndeclaredAttribute, qname.ToString());
case AttributeMatchState.ProhibitedAnyAttribute:
case AttributeMatchState.ProhibitedAttribute:
throw new XmlSchemaException(ResXml.Sch_ProhibitedAttribute, qname.ToString());
case AttributeMatchState.AttributeFound:
case AttributeMatchState.AnyIdAttributeFound:
case AttributeMatchState.AnyAttributeLax:
case AttributeMatchState.UndeclaredElementAndAttribute:
break;
case AttributeMatchState.AnyAttributeSkip:
skip = true;
break;
default:
Debug.Assert(false);
break;
}
return attDef;
}
internal void Add(SchemaInfo sinfo, ValidationEventHandler eventhandler)
{
if (_schemaType == SchemaType.None)
{
_schemaType = sinfo.SchemaType;
}
else if (_schemaType != sinfo.SchemaType)
{
if (eventhandler != null)
{
eventhandler(this, new ValidationEventArgs(new XmlSchemaException(ResXml.Sch_MixSchemaTypes, string.Empty)));
}
return;
}
foreach (string tns in sinfo.TargetNamespaces.Keys)
{
if (!_targetNamespaces.ContainsKey(tns))
{
_targetNamespaces.Add(tns, true);
}
}
foreach (KeyValuePair<XmlQualifiedName, SchemaElementDecl> entry in sinfo._elementDecls)
{
if (!_elementDecls.ContainsKey(entry.Key))
{
_elementDecls.Add(entry.Key, entry.Value);
}
}
foreach (KeyValuePair<XmlQualifiedName, SchemaElementDecl> entry in sinfo._elementDeclsByType)
{
if (!_elementDeclsByType.ContainsKey(entry.Key))
{
_elementDeclsByType.Add(entry.Key, entry.Value);
}
}
foreach (SchemaAttDef attdef in sinfo.AttributeDecls.Values)
{
if (!_attributeDecls.ContainsKey(attdef.Name))
{
_attributeDecls.Add(attdef.Name, attdef);
}
}
foreach (SchemaNotation notation in sinfo.Notations.Values)
{
if (!Notations.ContainsKey(notation.Name.Name))
{
Notations.Add(notation.Name.Name, notation);
}
}
}
internal void Finish()
{
Dictionary<XmlQualifiedName, SchemaElementDecl> elements = _elementDecls;
for (int i = 0; i < 2; i++)
{
foreach (SchemaElementDecl e in elements.Values)
{
if (e.HasNonCDataAttribute)
{
_hasNonCDataAttributes = true;
}
if (e.DefaultAttDefs != null)
{
_hasDefaultAttributes = true;
}
}
elements = _undeclaredElementDecls;
}
}
//
// IDtdInfo interface
//
#region IDtdInfo Members
bool IDtdInfo.HasDefaultAttributes
{
get
{
return _hasDefaultAttributes;
}
}
bool IDtdInfo.HasNonCDataAttributes
{
get
{
return _hasNonCDataAttributes;
}
}
IDtdAttributeListInfo IDtdInfo.LookupAttributeList(string prefix, string localName)
{
XmlQualifiedName qname = new XmlQualifiedName(prefix, localName);
SchemaElementDecl elementDecl;
if (!_elementDecls.TryGetValue(qname, out elementDecl))
{
_undeclaredElementDecls.TryGetValue(qname, out elementDecl);
}
return elementDecl;
}
IEnumerable<IDtdAttributeListInfo> IDtdInfo.GetAttributeLists()
{
foreach (SchemaElementDecl elemDecl in _elementDecls.Values)
{
IDtdAttributeListInfo eleDeclAsAttList = (IDtdAttributeListInfo)elemDecl;
yield return eleDeclAsAttList;
}
}
IDtdEntityInfo IDtdInfo.LookupEntity(string name)
{
if (_generalEntities == null)
{
return null;
}
XmlQualifiedName qname = new XmlQualifiedName(name);
SchemaEntity entity;
if (_generalEntities.TryGetValue(qname, out entity))
{
return entity;
}
return null;
}
XmlQualifiedName IDtdInfo.Name
{
get { return _docTypeName; }
}
string IDtdInfo.InternalDtdSubset
{
get { return _internalDtdSubset; }
}
#endregion
}
}
| |
//! \file ImageDAT.cs
//! \date 2018 Jul 07
//! \brief Studio Jikkenshitsu compressed image.
//
// Copyright (C) 2018 by morkt
//
// 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.ComponentModel.Composition;
using System.IO;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using GameRes.Formats.Strings;
// [010719][Studio Jikkenshitsu] Shin Gekka Bijin ~Hitori Shizuka
// [030606][Studio Jikkenshitsu] Bias {biAs+}
// [031212][Studio Jikkenshitsu] Jam n' Limit
namespace GameRes.Formats.Jikkenshitsu
{
internal class SpMetaData : ImageMetaData
{
public int Flags;
public int Colors;
public byte[] Key;
public bool IsEncrypted { get { return (Flags & 8) != 0; } }
}
[Serializable]
public class SjSchemeMap : ResourceScheme
{
public IDictionary<string, byte[]> KnownSchemes;
}
internal class SjOptions : ResourceOptions
{
public byte[] Key;
}
[Export(typeof(ImageFormat))]
public class SpDatFormat : ImageFormat
{
public override string Tag { get { return "DAT/SPEED"; } }
public override string Description { get { return "Studio Jikkenshitsu image format"; } }
public override uint Signature { get { return 0; } }
public SpDatFormat ()
{
Extensions = new string[] { /* "dat" */ };
Signatures = new uint[] { 0x010003, 0x010007, 0x01000B, 0x010046, 0 };
}
byte[] DefaultKey = null;
public override ImageMetaData ReadMetaData (IBinaryStream file)
{
var header = file.ReadHeader (0x22);
if (header.ToInt32 (4) != 0)
return null;
int flags = header.ToUInt16 (0);
if ((flags & ~0xFF) != 0 || header[2] != 1)
return null;
var info = new SpMetaData {
Width = header.ToUInt16 (0x16),
Height = header.ToUInt16 (0x18),
BPP = 8,
Flags = flags,
Colors = header.ToUInt16 (0x1E),
};
if (info.Width == 0 || info.Width > 0x2000 || info.Height == 0 || info.Height > 0x2000 ||
info.Colors > 0x100)
return null;
if (info.IsEncrypted)
{
if (null == DefaultKey)
{
DefaultKey = QueryKey (file.Name);
if (null == DefaultKey)
return null;
}
info.Key = DefaultKey;
}
return info;
}
public override ImageData Read (IBinaryStream file, ImageMetaData info)
{
var reader = new SpReader (file, (SpMetaData)info);
var pixels = reader.Unpack();
return ImageData.CreateFlipped (info, reader.Format, reader.Palette, pixels, reader.Stride);
}
public override void Write (Stream file, ImageData image)
{
throw new System.NotImplementedException ("SpDatFormat.Write not implemented");
}
SjSchemeMap DefaultScheme = new SjSchemeMap { KnownSchemes = new Dictionary<string, byte[]>() };
public override ResourceScheme Scheme
{
get { return DefaultScheme; }
set { DefaultScheme = (SjSchemeMap)value; }
}
public override ResourceOptions GetDefaultOptions ()
{
return new SjOptions { Key = GetKey (Properties.Settings.Default.SJDatTitle) };
}
public override object GetAccessWidget ()
{
return new GUI.WidgetSJDAT (DefaultScheme.KnownSchemes.Keys);
}
byte[] QueryKey (string filename)
{
var options = Query<SjOptions> (arcStrings.ArcImageEncrypted);
return options.Key;
}
byte[] GetKey (string title)
{
byte[] key = null;
if (!string.IsNullOrEmpty (title))
DefaultScheme.KnownSchemes.TryGetValue (title, out key);
return key;
}
}
internal class SpReader
{
IBinaryStream m_input;
SpMetaData m_info;
byte[] m_output;
int m_stride;
public PixelFormat Format { get; private set; }
public int Stride { get { return m_stride; } }
public BitmapPalette Palette { get; private set; }
public SpReader (IBinaryStream input, SpMetaData info)
{
m_input = input;
m_info = info;
m_output = new byte[info.Width * info.Height];
m_stride = info.iWidth;
}
public byte[] Unpack ()
{
m_input.Position = 0x22;
int packed_size = m_input.ReadInt32();
if (m_info.Colors > 0)
Palette = ImageFormat.ReadPalette (m_input.AsStream, m_info.Colors);
UnpackStream (m_output, packed_size);
if ((m_info.Flags & 0xF4) == 4)
{
packed_size = m_input.ReadInt32();
if (packed_size != 0)
{
var alpha = new byte[m_output.Length >> 1];
UnpackStream (alpha, packed_size);
return ConvertToRgbA (alpha);
}
}
Format = m_info.Colors > 0 ? PixelFormats.Indexed8 : PixelFormats.Gray4;
return m_output;
}
void UnpackStream (byte[] output, int packed_size)
{
if (0 == packed_size)
{
m_input.Read (output, 0, output.Length);
return;
}
var input = m_input.AsStream;
var input_pos = m_input.Position;
if (m_info.IsEncrypted)
{
input = new StreamRegion (input, input_pos, packed_size, true);
input = new InputCryptoStream (input, new SjTransform (m_info.Key));
}
try
{
UnpackRle (input, output);
}
finally
{
if (input != m_input.AsStream)
input.Dispose();
m_input.Position = input_pos + packed_size;
}
}
void UnpackRle (Stream input, byte[] output)
{
int dst = 0;
int state = 0;
byte pixel = 0;
while (dst < output.Length)
{
int rep = input.ReadByte();
if (-1 == rep)
break;
if (0 == state)
{
state = 1;
output[dst++] = (byte)rep;
}
else if (1 == state)
{
if (output[dst - 1] == rep)
{
pixel = (byte)rep;
state = 2;
}
output[dst++] = (byte)rep;
}
else
{
int count = rep - 2;
for (int j = 0; j < count; ++j)
output[dst++] = pixel;
state = 0;
}
}
}
byte[] ConvertToRgbA (byte[] alpha)
{
m_stride = m_info.iWidth * 4;
var pixels = new byte[m_stride * m_info.iHeight];
var colors = Palette.Colors;
int dst = 0;
for (int src = 0; src < m_output.Length; ++src)
{
var color = colors[m_output[src]];
int a = ((alpha[src >> 1] >> ((~src & 1) << 2)) & 0xF) * 0x11;
pixels[dst++] = color.B;
pixels[dst++] = color.G;
pixels[dst++] = color.R;
pixels[dst++] = (byte)a;
}
Format = PixelFormats.Bgra32;
return pixels;
}
}
}
| |
// 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.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeRefactorings;
using Microsoft.CodeAnalysis.CodeRefactorings.GenerateFromMembers.GenerateConstructorFromMembers;
using Microsoft.CodeAnalysis.CodeStyle;
using Microsoft.CodeAnalysis.CSharp.CodeStyle;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.CodeRefactorings.GenerateFromMembers.GenerateConstructorFromMembers
{
public class GenerateConstructorFromMembersTests : AbstractCSharpCodeActionTest
{
protected override CodeRefactoringProvider CreateCodeRefactoringProvider(Workspace workspace)
{
return new GenerateConstructorFromMembersCodeRefactoringProvider();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateConstructorFromMembers)]
public async Task TestSingleField()
{
await TestAsync(
@"using System.Collections.Generic;
class Z
{
[|int a;|]
}",
@"using System.Collections.Generic;
class Z
{
int a;
public Z(int a)
{
this.a = a;
}
}",
index: 0);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateConstructorFromMembers)]
public async Task TestSingleFieldWithCodeStyle()
{
await TestAsync(
@"using System.Collections.Generic;
class Z
{
[|int a;|]
}",
@"using System.Collections.Generic;
class Z
{
int a;
public Z(int a) => this . a = a ; }",
options: Option(CSharpCodeStyleOptions.PreferExpressionBodiedConstructors, CodeStyleOptions.TrueWithNoneEnforcement));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateConstructorFromMembers)]
public async Task TestMultipleFields()
{
await TestAsync(
@"using System.Collections.Generic;
class Z
{
[|int a;
string b;|]
}",
@"using System.Collections.Generic;
class Z
{
int a;
string b;
public Z(int a, string b)
{
this.a = a;
this.b = b;
}
}",
index: 0);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateConstructorFromMembers)]
public async Task TestSecondField()
{
await TestAsync(
@"using System.Collections.Generic;
class Z
{
int a;
[|string b;|]
public Z(int a)
{
this.a = a;
}
}",
@"using System.Collections.Generic;
class Z
{
int a;
string b;
public Z(string b)
{
this.b = b;
}
public Z(int a)
{
this.a = a;
}
}",
index: 0);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateConstructorFromMembers)]
public async Task TestFieldAssigningConstructor()
{
await TestAsync(
@"using System.Collections.Generic;
class Z
{
[|int a;
string b;|]
public Z(int a)
{
this.a = a;
}
}",
@"using System.Collections.Generic;
class Z
{
int a;
string b;
public Z(int a)
{
this.a = a;
}
public Z(int a, string b)
{
this.a = a;
this.b = b;
}
}",
index: 0);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateConstructorFromMembers)]
public async Task TestFieldAssigningConstructor2()
{
await TestAsync(
@"using System.Collections.Generic;
class Z
{
[|int a;
string b;|]
public Z(int a)
{
this.a = a;
}
}",
@"using System.Collections.Generic;
class Z
{
int a;
string b;
public Z(int a)
{
this.a = a;
}
public Z(int a, string b)
{
this.a = a;
this.b = b;
}
}",
index: 0);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateConstructorFromMembers)]
public async Task TestDelegatingConstructor()
{
await TestAsync(
@"using System.Collections.Generic;
class Z
{
[|int a;
string b;|]
public Z(int a)
{
this.a = a;
}
}",
@"using System.Collections.Generic;
class Z
{
int a;
string b;
public Z(int a)
{
this.a = a;
}
public Z(int a, string b) : this(a)
{
this.b = b;
}
}",
index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateConstructorFromMembers)]
public async Task TestMissingWithExistingConstructor()
{
await TestMissingAsync(
@"using System.Collections.Generic;
class Z
{
[|int a;
string b;|]
public Z(int a)
{
this.a = a;
}
public Z(int a, string b)
{
this.a = a;
this.b = b;
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateConstructorFromMembers)]
public async Task TestMultipleProperties()
{
await TestAsync(
@"class Z
{
[|public int A { get; private set; }
public string B { get; private set; }|]
}",
@"class Z
{
public Z(int a, string b)
{
A = a;
B = b;
}
public int A { get; private set; }
public string B { get; private set; }
}",
index: 0);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateConstructorFromMembers)]
public async Task TestMultiplePropertiesWithQualification()
{
await TestAsync(
@"class Z
{
[|public int A { get; private set; }
public string B { get; private set; }|]
}",
@"class Z
{
public Z(int a, string b)
{
this.A = a;
this.B = b;
}
public int A { get; private set; }
public string B { get; private set; }
}",
index: 0, options: Option(CodeStyleOptions.QualifyPropertyAccess, true, NotificationOption.Error));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateConstructorFromMembers)]
public async Task TestStruct()
{
await TestAsync(
@"using System.Collections.Generic;
struct S
{
[|int i;|]
}",
@"using System.Collections.Generic;
struct S
{
int i;
public S(int i)
{
this.i = i;
}
}",
index: 0);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateConstructorFromMembers)]
public async Task TestStruct1()
{
await TestAsync(
@"using System.Collections.Generic;
struct S
{
[|int i { get; set; }|]
}",
@"using System.Collections.Generic;
struct S
{
public S(int i) : this()
{
this.i = i;
}
int i { get; set; }
}",
index: 0);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateConstructorFromMembers)]
public async Task TestStruct2()
{
await TestAsync(
@"using System.Collections.Generic;
struct S
{
int i { get; set; }
[|int y;|]
}",
@"using System.Collections.Generic;
struct S
{
int i { get; set; }
int y;
public S(int y) : this()
{
this.y = y;
}
}",
index: 0);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateConstructorFromMembers)]
public async Task TestStruct3()
{
await TestAsync(
@"using System.Collections.Generic;
struct S
{
[|int i { get; set; }|]
int y;
}",
@"using System.Collections.Generic;
struct S
{
int i { get; set; }
int y;
public S(int i) : this()
{
this.i = i;
}
}",
index: 0);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateConstructorFromMembers)]
public async Task TestGenericType()
{
await TestAsync(
@"using System.Collections.Generic;
class Program<T>
{
[|int i;|]
}",
@"using System.Collections.Generic;
class Program<T>
{
int i;
public Program(int i)
{
this.i = i;
}
}",
index: 0);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateConstructorFromMembers)]
public async Task TestSmartTagText1()
{
await TestSmartTagTextAsync(
@"using System.Collections.Generic;
class Program
{
[|bool b;
HashSet<string> s;|]
}",
string.Format(FeaturesResources.Generate_constructor_0_1, "Program", "bool, HashSet<string>"));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateConstructorFromMembers)]
public async Task TestSmartTagText2()
{
await TestSmartTagTextAsync(
@"using System.Collections.Generic;
class Program
{
[|bool b;
HashSet<string> s;|]
public Program(bool b)
{
this.b = b;
}
}",
string.Format(FeaturesResources.Generate_field_assigning_constructor_0_1, "Program", "bool, HashSet<string>"));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateConstructorFromMembers)]
public async Task TestSmartTagText3()
{
await TestSmartTagTextAsync(
@"using System.Collections.Generic;
class Program
{
[|bool b;
HashSet<string> s;|]
public Program(bool b)
{
this.b = b;
}
}",
string.Format(FeaturesResources.Generate_delegating_constructor_0_1, "Program", "bool, HashSet<string>"),
index: 1);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateConstructorFromMembers)]
public async Task TestContextualKeywordName()
{
await TestAsync(
@"class Program
{
[|int yield;|]
}",
@"class Program
{
int yield;
public Program(int yield)
{
this.yield = yield;
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateConstructorFromMembers)]
public async Task TestGenerateConstructorNotOfferedForDuplicate()
{
await TestMissingAsync(
@"using System;
class X
{
public X(string v)
{
}
static void Test()
{
new X(new [|string|]());
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateConstructorFromMembers)]
public async Task Tuple()
{
await TestAsync(
@"using System.Collections.Generic;
class Z
{
[|(int, string) a;|]
}",
@"using System.Collections.Generic;
class Z
{
(int, string) a;
public Z((int, string) a)
{
this.a = a;
}
}",
index: 0,
parseOptions: TestOptions.Regular,
withScriptOption: true);
}
[WorkItem(14219, "https://github.com/dotnet/roslyn/issues/14219")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateConstructorFromMembers)]
public async Task TestUnderscoreInName1()
{
await TestAsync(
@"class Program
{
[|int _field;|]
}",
@"class Program
{
int _field;
public Program(int field)
{
_field = field;
}
}");
}
[WorkItem(14219, "https://github.com/dotnet/roslyn/issues/14219")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateConstructorFromMembers)]
public async Task TestUnderscoreInName_PreferThis()
{
await TestAsync(
@"class Program
{
[|int _field;|]
}",
@"class Program
{
int _field;
public Program(int field)
{
this._field = field;
}
}",
options: Option(CodeStyleOptions.QualifyFieldAccess, CodeStyleOptions.TrueWithSuggestionEnforcement));
}
[WorkItem(13944, "https://github.com/dotnet/roslyn/issues/13944")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateConstructorFromMembers)]
public async Task TestGetter_Only_Auto_Props()
{
await TestAsync(
@"abstract class Contribution
{
[|public string Title { get; }
public int Number { get; }|]
}",
@"abstract class Contribution
{
public Contribution(string title, int number)
{
Title = title;
Number = number;
}
public string Title { get; }
public int Number { get; }
}",
options: Option(CodeStyleOptions.QualifyFieldAccess, CodeStyleOptions.TrueWithSuggestionEnforcement));
}
[WorkItem(13944, "https://github.com/dotnet/roslyn/issues/13944")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateConstructorFromMembers)]
public async Task TestAbstract_Getter_Only_Auto_Props()
{
await TestMissingAsync(
@"abstract class Contribution
{
[|public abstract string Title { get; }
public int Number { get; }|]
}",
options: Option(CodeStyleOptions.QualifyFieldAccess, CodeStyleOptions.TrueWithSuggestionEnforcement));
}
}
}
| |
// Code generated by Microsoft (R) AutoRest Code Generator 0.17.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.RecoveryServices.Backup
{
using System.Linq;
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
/// <summary>
/// ProtectedItemOperationResultsOperations operations.
/// </summary>
internal partial class ProtectedItemOperationResultsOperations : Microsoft.Rest.IServiceOperations<RecoveryServicesBackupClient>, IProtectedItemOperationResultsOperations
{
/// <summary>
/// Initializes a new instance of the ProtectedItemOperationResultsOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
internal ProtectedItemOperationResultsOperations(RecoveryServicesBackupClient client)
{
if (client == null)
{
throw new System.ArgumentNullException("client");
}
this.Client = client;
}
/// <summary>
/// Gets a reference to the RecoveryServicesBackupClient
/// </summary>
public RecoveryServicesBackupClient Client { get; private set; }
/// <summary>
/// Fetches the result of any operation on the backup item.
/// </summary>
/// <param name='vaultName'>
/// The name of the recovery services vault.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group where the recovery services vault is
/// present.
/// </param>
/// <param name='fabricName'>
/// Fabric name associated with the backup item.
/// </param>
/// <param name='containerName'>
/// Container name associated with the backup item.
/// </param>
/// <param name='protectedItemName'>
/// Backup item name whose details are to be fetched.
/// </param>
/// <param name='operationId'>
/// OperationID which represents the operation whose result needs to be
/// fetched.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<ProtectedItemResource>> GetWithHttpMessagesAsync(string vaultName, string resourceGroupName, string fabricName, string containerName, string protectedItemName, string operationId, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
if (vaultName == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "vaultName");
}
if (resourceGroupName == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "resourceGroupName");
}
if (this.Client.SubscriptionId == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
if (fabricName == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "fabricName");
}
if (containerName == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "containerName");
}
if (protectedItemName == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "protectedItemName");
}
if (operationId == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "operationId");
}
string apiVersion = "2016-06-01";
// Tracing
bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString();
System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>();
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("vaultName", vaultName);
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("fabricName", fabricName);
tracingParameters.Add("containerName", containerName);
tracingParameters.Add("protectedItemName", protectedItemName);
tracingParameters.Add("operationId", operationId);
tracingParameters.Add("cancellationToken", cancellationToken);
Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{vaultName}/backupFabrics/{fabricName}/protectionContainers/{containerName}/protectedItems/{protectedItemName}/operationResults/{operationId}").ToString();
_url = _url.Replace("{vaultName}", System.Uri.EscapeDataString(vaultName));
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(this.Client.SubscriptionId));
_url = _url.Replace("{fabricName}", System.Uri.EscapeDataString(fabricName));
_url = _url.Replace("{containerName}", System.Uri.EscapeDataString(containerName));
_url = _url.Replace("{protectedItemName}", System.Uri.EscapeDataString(protectedItemName));
_url = _url.Replace("{operationId}", System.Uri.EscapeDataString(operationId));
System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200 && (int)_statusCode != 202 && (int)_statusCode != 204)
{
var ex = new Microsoft.Rest.Azure.CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new Microsoft.Rest.Azure.CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (Newtonsoft.Json.JsonException)
{
// Ignore the exception
}
ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new Microsoft.Rest.Azure.AzureOperationResponse<ProtectedItemResource>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<ProtectedItemResource>(_responseContent, this.Client.DeserializationSettings);
}
catch (Newtonsoft.Json.JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new Microsoft.Rest.SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
| |
#region CopyrightHeader
//
// Copyright by Contributors
//
// 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.txt
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#endregion
using System;
using System.Collections.Generic;
using System.Text;
using NUnit.Framework;
namespace gov.va.medora.mdo
{
/// <summary>
/// Test class for gov.va.medora.mdo.SocSecNum
/// </summary>
/// <remarks>
/// Contributed by Matt Schmidt (vhaindschmim0) and Robert Ruff (vhawpbruffr)
/// </remarks>
[TestFixture]
public class SocSecNumTest
{
/// <summary>
/// Test method for SocSecNum(). Each number should return null.
/// </summary>
[Test]
public void testSocSecNum()
{
SocSecNum theSSN = new SocSecNum();
Assert.IsNull(theSSN.AreaNumber);
Assert.IsNull(theSSN.GroupNumber);
Assert.IsNull(theSSN.SerialNumber);
}
/// <summary>
/// Test method for SocSecNum(String). An invalid input should result in all nulls for area, group, serial number.
/// </summary>
[Test]
public void testSocSecNumString()
{
SocSecNum theSSN = new SocSecNum("123456789");
Assert.AreEqual("123", theSSN.AreaNumber, "Expected area # to be 123");
Assert.AreEqual("45", theSSN.GroupNumber, "Expected group # to be 45");
Assert.AreEqual("6789", theSSN.SerialNumber, "Expected serial # to be 6789");
}
/// <summary>
/// First test method for SocSecNum(String). This tests various issues involving hyphenated ssns.
/// </summary>
[Test]
public void testSocSecNumStringHyphen1()
{
SocSecNum theSSN;
theSSN = new SocSecNum("123-45-6789");
Assert.AreEqual("123", theSSN.AreaNumber, "Expected dashed area # to be 123");
Assert.AreEqual("45", theSSN.GroupNumber, "Expected dashed group # to be 45");
Assert.AreEqual("6789", theSSN.SerialNumber, "Expected dashed serial # to be 6789");
}
/// <summary>
/// Second test method for SocSecNum(String). This tests various issues involving hyphenated ssns.
/// </summary>
[Test]
public void testSocSecNumStringHyphen2()
{
SocSecNum theSSN;
theSSN = new SocSecNum("12-345-6789");
Assert.AreEqual("123", theSSN.AreaNumber, "Expected dashed area # to be 123");
Assert.AreEqual("45", theSSN.GroupNumber, "Expected dashed group # to be 45");
Assert.AreEqual("6789", theSSN.SerialNumber, "Expected dashed serial # to be 6789");
}
/// <summary>
/// Third test method for SocSecNum(String). This tests various issues involving hyphenated ssns.
/// </summary>
[Test]
[ExpectedException(typeof(ArgumentException))]
public void testSocSecNumStringHyphen3()
{
SocSecNum theSSN;
theSSN = new SocSecNum("12a-45-6789");
}
/// <summary>
/// Fourth test method for SocSecNum(String). This tests various issues involving hyphenated ssns.
/// </summary>
[Test]
[ExpectedException(typeof(ArgumentException))]
public void testSocSecNumStringHyphen4()
{
SocSecNum theSSN;
theSSN = new SocSecNum("123-4a-6789");
}
/// <summary>
/// Fifth test method for SocSecNum(String). This tests various issues involving hyphenated ssns.
/// </summary>
[Test]
[ExpectedException(typeof(ArgumentException))]
public void testSocSecNumStringHyphen5()
{
SocSecNum theSSN;
theSSN = new SocSecNum("123-45-678a");
}
/// <summary>
/// Test method for SocSecNum(String). This tests various alphanumeric inputs.
/// </summary>
[Test]
[ExpectedException(typeof(ArgumentException))]
public void testSocSecNumStringAlpha()
{
SocSecNum theSSN;
theSSN = new SocSecNum("abcdefghi");
}
/// <summary>
/// Test method for the AreaNumber get.
/// </summary>
[Test]
public void testAreaNumberGet()
{
SocSecNum theSSN = new SocSecNum();
theSSN.AreaNumber = "123";
Assert.AreEqual("123", theSSN.AreaNumber, "Expected AreaNumber to return 123");
}
/// <summary>
/// Test method for the AreaNumber set. Checks the set value against the contents of the internal AreaNumber property.
/// </summary>
[Test]
public void testAreaNumberSet()
{
SocSecNum theSSN = new SocSecNum();
theSSN.AreaNumber = "123";
Assert.AreEqual("123", theSSN.AreaNumber, "Expected AreaNumber to be 123");
}
/// <summary>
/// Test method for the AreaNumber set. Make sure 819 (Manila) is invalid.
/// </summary>
[Test]
[ExpectedException(typeof(ArgumentException))]
public void testAreaNumber819()
{
SocSecNum theSSN = new SocSecNum();
theSSN.AreaNumber = "819";
}
/// <summary>
/// Test method for the AreaNumber set. Checks that the exception for a non-numeric arg is thrown.
/// </summary>
[Test]
[ExpectedException(typeof(ArgumentException))]
public void testAreaNumberSetExArgument()
{
SocSecNum theSSN = new SocSecNum();
theSSN.AreaNumber = "abc";
}
/// <summary>
/// Test method for the GroupNumber get.
/// </summary>
[Test]
public void testGroupNumberGet()
{
SocSecNum theSSN = new SocSecNum();
theSSN.GroupNumber = "45";
Assert.AreEqual("45", theSSN.GroupNumber, "Expected GroupNumber to return 45");
}
/// <summary>
/// Test method for the GroupNumber set. Checks the set value against the contents of the internal GroupNumber property.
/// </summary>
[Test]
public void testGroupNumberSet()
{
SocSecNum theSSN = new SocSecNum();
theSSN.GroupNumber = "45";
Assert.AreEqual("45", theSSN.GroupNumber, "Expected GroupNumber to be 45");
}
/// <summary>
/// Test method for the GroupNumber set. Checks that the exception for a non-numeric arg is thrown.
/// </summary>
[Test]
[ExpectedException(typeof(ArgumentException))]
public void testGroupNumberSetExArgument()
{
SocSecNum theSSN = new SocSecNum();
theSSN.GroupNumber = "ab";
}
/// <summary>
/// Test method for the SerialNumber get.
/// </summary>
[Test]
public void testSerialNumberGet()
{
SocSecNum theSSN = new SocSecNum();
theSSN.SerialNumber = "6789";
Assert.AreEqual("6789", theSSN.SerialNumber, "Expected SerailNumber to return 6789");
}
/// <summary>
/// Test method for the SerialNumber set. Checks the set value against the contents of the internal SerialNumber property.
/// </summary>
[Test]
public void testSerialNumberSet()
{
SocSecNum theSSN = new SocSecNum();
theSSN.SerialNumber = "6789";
Assert.AreEqual("6789", theSSN.SerialNumber, "Expected SerialNumber to be 6789");
}
/// <summary>
/// Test method for the SerialNumber set. Checks that the exception for a non-numeric arg is thrown.
/// </summary>
[Test]
[ExpectedException(typeof(ArgumentException))]
public void testSerialNumberSetExArgument()
{
SocSecNum theSSN = new SocSecNum();
theSSN.SerialNumber = "abcd";
}
/// <summary>
/// First test method for IsValidAreaNumber.
/// </summary>
[Test]
public void testIsValidAreaNumber1()
{
SocSecNum theSSN = new SocSecNum();
theSSN.AreaNumber = "123";
Assert.IsTrue(theSSN.IsValidAreaNumber, "Expected 123 to be valid");
}
/// <summary>
/// Second test method for IsValidAreaNumber.
/// </summary>
[Test]
[ExpectedException(typeof(ArgumentException))]
public void testIsValidAreaNumber2()
{
SocSecNum theSSN = new SocSecNum();
theSSN.AreaNumber = "12";
}
/// <summary>
/// Third test method for IsValidAreaNumber.
/// </summary>
[Test]
[ExpectedException(typeof(ArgumentException))]
public void testIsValidAreaNumber3()
{
SocSecNum theSSN = new SocSecNum();
theSSN.AreaNumber = "1234";
}
/// <summary>
/// Fourth test method for IsValidAreaNumber.
/// </summary>
[Test]
[ExpectedException(typeof(ArgumentException))]
public void testIsValidAreaNumber4()
{
SocSecNum theSSN = new SocSecNum();
theSSN.AreaNumber = "000";
}
/// <summary>
/// Fifth test method for IsValidAreaNumber.
/// </summary>
[Test]
[ExpectedException(typeof(ArgumentException))]
public void testIsValidAreaNumber5()
{
SocSecNum theSSN = new SocSecNum();
theSSN.AreaNumber = "666";
}
/// <summary>
/// Sixth test method for IsValidAreaNumber.
/// </summary>
[Test]
[ExpectedException(typeof(ArgumentException))]
public void testIsValidAreaNumber6()
{
SocSecNum theSSN = new SocSecNum();
theSSN.AreaNumber = "773";
}
/// <summary>
/// Seventh test method for IsValidAreaNumber.
/// </summary>
[Test]
[ExpectedException(typeof(ArgumentException))]
public void testIsValidAreaNumber7()
{
SocSecNum theSSN = new SocSecNum();
theSSN.AreaNumber = "abc";
}
/// <summary>
/// Eighth test method for IsValidAreaNumber.
/// </summary>
[Test]
[ExpectedException(typeof(ArgumentException))]
public void testIsValidAreaNumber8()
{
SocSecNum theSSN = new SocSecNum();
theSSN.AreaNumber = "";
}
/// <summary>
/// First test method for isValidAreaNumber(String).
/// </summary>
[Test]
public void testIsValidAreaNumberString1()
{
Assert.IsTrue(SocSecNum.isValidAreaNumber("123"), "Expected 123 to be valid");
}
/// <summary>
/// Second test method for isValidAreaNumber(String).
/// </summary>
[Test]
public void testIsValidAreaNumberString2()
{
Assert.IsFalse(SocSecNum.isValidAreaNumber("12"), "Expected strings shorter than 3 chars to be invalid");
}
/// <summary>
/// Third test method for isValidAreaNumber(String).
/// </summary>
[Test]
public void testIsValidAreaNumberString3()
{
Assert.IsFalse(SocSecNum.isValidAreaNumber("1234"), "Expected strings longer than 3 chars to be invalid");
}
/// <summary>
/// Fourth test method for isValidAreaNumber(String).
/// </summary>
[Test]
public void testIsValidAreaNumberString4()
{
Assert.IsFalse(SocSecNum.isValidAreaNumber("000"), "Expected 000 to be invalid");
}
/// <summary>
/// Fifth test method for isValidAreaNumber(String).
/// </summary>
[Test]
public void testIsValidAreaNumberString5()
{
Assert.IsFalse(SocSecNum.isValidAreaNumber("666"), "Expected 666 to be invalid");
}
/// <summary>
/// Sixth test method for isValidAreaNumber(String).
/// </summary>
[Test]
public void testIsValidAreaNumberString6()
{
Assert.IsFalse(SocSecNum.isValidAreaNumber("773"), "Expected numbers over 772 to be invalid");
}
/// <summary>
/// Seventh test method for isValidAreaNumber(String).
/// </summary>
[Test]
public void testIsValidAreaNumberString7()
{
Assert.IsFalse(SocSecNum.isValidAreaNumber("abc"), "Expected abc to be invalid");
}
/// <summary>
/// Eigth test method for isValidAreaNumber(String).
/// </summary>
[Test]
public void testIsValidAreaNumberString8()
{
Assert.IsFalse(SocSecNum.isValidAreaNumber(""), "Expected blank to be invalid");
}
/// <summary>
/// First test method for IsValidGroupNumber.
/// </summary>
[Test]
public void testIsValidGroupNumber1()
{
SocSecNum theSSN = new SocSecNum();
theSSN.GroupNumber = "12";
Assert.IsTrue(theSSN.IsValidGroupNumber, "Expected 12 to be valid");
}
/// <summary>
/// Second test method for IsValidGroupNumber.
/// </summary>
[Test]
[ExpectedException(typeof(ArgumentException))]
public void testIsValidGroupNumber2()
{
SocSecNum theSSN = new SocSecNum();
theSSN.GroupNumber = "00";
}
/// <summary>
/// Third test method for IsValidGroupNumber.
/// </summary>
[Test]
[ExpectedException(typeof(ArgumentException))]
public void testIsValidGroupNumber3()
{
SocSecNum theSSN = new SocSecNum();
theSSN.GroupNumber = "1";
}
/// <summary>
/// Fourth test method for IsValidGroupNumber.
/// </summary>
[Test]
[ExpectedException(typeof(ArgumentException))]
public void testIsValidGroupNumber4()
{
SocSecNum theSSN = new SocSecNum();
theSSN.GroupNumber = "123";
}
/// <summary>
/// Fifth test method for IsValidGroupNumber.
/// </summary>
[Test]
[ExpectedException(typeof(ArgumentException))]
public void testIsValidGroupNumber5()
{
SocSecNum theSSN = new SocSecNum();
theSSN.GroupNumber = "ab";
}
/// <summary>
/// Sixth test method for IsValidGroupNumber.
/// </summary>
[Test]
[ExpectedException(typeof(ArgumentException))]
public void testIsValidGroupNumber6()
{
SocSecNum theSSN = new SocSecNum();
theSSN.GroupNumber = "";
}
/// <summary>
/// First test method for isValidGroupNumber(String).
/// </summary>
[Test]
public void testIsValidGroupNumberString()
{
Assert.IsTrue(SocSecNum.isValidGroupNumber("12"), "Expected 12 to be valid");
}
/// <summary>
/// Second test method for isValidGroupNumber(String).
/// </summary>
[Test]
public void testIsValidGroupNumberString2()
{
Assert.IsFalse(SocSecNum.isValidGroupNumber("00"), "Expected 00 to be invalid");
}
/// <summary>
/// Third test method for isValidGroupNumber(String).
/// </summary>
[Test]
public void testIsValidGroupNumberString3()
{
Assert.IsFalse(SocSecNum.isValidGroupNumber("1"), "Expected strings shorter than 2 chars to be invalid");
}
/// <summary>
/// Fourth test method for isValidGroupNumber(String).
/// </summary>
[Test]
public void testIsValidGroupNumberString4()
{
Assert.IsFalse(SocSecNum.isValidGroupNumber("123"), "Expected strings over 2 chars to be invalid");
}
/// <summary>
/// Fifth test method for isValidGroupNumber(String).
/// </summary>
[Test]
public void testIsValidGroupNumberString5()
{
Assert.IsFalse(SocSecNum.isValidGroupNumber("ab"), "Expected ab to be invalid");
}
/// <summary>
/// Sixth test method for isValidGroupNumber(String).
/// </summary>
[Test]
public void testIsValidGroupNumberString6()
{
Assert.IsFalse(SocSecNum.isValidGroupNumber(""), "Expected blank to be invalid");
}
/// <summary>
/// First test method for IsValidSerialNumber.
/// </summary>
[Test]
public void testIsValidSerialNumber1()
{
SocSecNum theSSN = new SocSecNum();
theSSN.SerialNumber = "1234";
Assert.IsTrue(theSSN.IsValidSerialNumber, "Expected 1234 to be valid");
}
/// <summary>
/// Second test method for IsValidSerialNumber.
/// </summary>
[Test]
[ExpectedException(typeof(ArgumentException))]
public void testIsValidSerialNumber2()
{
SocSecNum theSSN = new SocSecNum();
theSSN.SerialNumber = "0000";
}
/// <summary>
/// Third test method for IsValidSerialNumber.
/// </summary>
[Test]
[ExpectedException(typeof(ArgumentException))]
public void testIsValidSerialNumber3()
{
SocSecNum theSSN = new SocSecNum();
theSSN.SerialNumber = "123";
}
/// <summary>
/// Fourth test method for IsValidSerialNumber.
/// </summary>
[Test]
[ExpectedException(typeof(ArgumentException))]
public void testIsValidSerialNumber4()
{
SocSecNum theSSN = new SocSecNum();
theSSN.SerialNumber = "12345";
}
/// <summary>
/// Fifth test method for IsValidSerialNumber.
/// </summary>
[Test]
[ExpectedException(typeof(ArgumentException))]
public void testIsValidSerialNumber5()
{
SocSecNum theSSN = new SocSecNum();
theSSN.SerialNumber = "abcd";
}
/// <summary>
/// Sixth test method for IsValidSerialNumber.
/// </summary>
[Test]
[ExpectedException(typeof(ArgumentException))]
public void testIsValidSerialNumber6()
{
SocSecNum theSSN = new SocSecNum();
theSSN.SerialNumber = "";
}
/// <summary>
/// First test method for isValidSerialNumber(String).
/// </summary>
[Test]
public void testIsValidSerialNumberString1()
{
Assert.IsTrue(SocSecNum.isValidSerialNumber("1234"), "Expected 1234 to be valid");
}
/// <summary>
/// Second test method for isValidSerialNumber(String).
/// </summary>
[Test]
public void testIsValidSerialNumberString2()
{
Assert.IsFalse(SocSecNum.isValidSerialNumber("0000"), "Expected 0000 to be invalid");
}
/// <summary>
/// Third test method for isValidSerialNumber(String).
/// </summary>
[Test]
public void testIsValidSerialNumberString3()
{
Assert.IsFalse(SocSecNum.isValidSerialNumber("123"), "Expected strings under 4 chars to be invalid");
}
/// <summary>
/// Fourth test method for isValidSerialNumber(String).
/// </summary>
[Test]
public void testIsValidSerialNumberString4()
{
Assert.IsFalse(SocSecNum.isValidSerialNumber("12345"), "Expected strings over 4 chars to be invalid");
}
/// <summary>
/// Fifth test method for isValidSerialNumber(String).
/// </summary>
[Test]
public void testIsValidSerialNumberString5()
{
Assert.IsFalse(SocSecNum.isValidSerialNumber("abcd"), "Expected abcd to be invalid");
}
/// <summary>
/// Sixth test method for isValidSerialNumber(String).
/// </summary>
[Test]
public void testIsValidSerialNumberString6()
{
Assert.IsFalse(SocSecNum.isValidSerialNumber(""), "Expected blank to be invalid");
}
/// <summary>
/// First test method for IsValid.
/// </summary>
[Test]
public void testIsValid1()
{
SocSecNum theSSN = new SocSecNum();
theSSN.AreaNumber = "123"; theSSN.GroupNumber = "45"; theSSN.SerialNumber = "6789";
Assert.IsTrue(theSSN.IsValid, "Expected 123456789 to be valid");
}
/// <summary>
/// Second test method for IsValid.
/// </summary>
[Test]
[ExpectedException(typeof(ArgumentException))]
public void testIsValid2()
{
SocSecNum theSSN = new SocSecNum();
theSSN.AreaNumber = "123"; theSSN.GroupNumber = "45"; theSSN.SerialNumber = "678";
}
/// <summary>
/// Third test method for IsValid.
/// </summary>
[Test]
[ExpectedException(typeof(ArgumentException))]
public void testIsValid3()
{
SocSecNum theSSN = new SocSecNum();
theSSN.AreaNumber = "1234"; theSSN.GroupNumber = "45"; theSSN.SerialNumber = "6789";
}
/// <summary>
/// Fourth test method for IsValid.
/// </summary>
[Test]
[ExpectedException(typeof(ArgumentException))]
public void testIsValid4()
{
SocSecNum theSSN = new SocSecNum();
theSSN.AreaNumber = "123"; theSSN.GroupNumber = "456"; theSSN.SerialNumber = "6789";
}
/// <summary>
/// Fifth test method for IsValid.
/// </summary>
[Test]
[ExpectedException(typeof(ArgumentException))]
public void testIsValid5()
{
SocSecNum theSSN = new SocSecNum();
theSSN.AreaNumber = "123"; theSSN.GroupNumber = "45"; theSSN.SerialNumber = "67890";
}
/// <summary>
/// Test method for IsValid. This tests issues with alphanumeric input.
/// </summary>
[Test]
[ExpectedException(typeof(ArgumentException))]
public void testIsValidAlpha()
{
SocSecNum theSSN = new SocSecNum();
theSSN.AreaNumber = "abc"; theSSN.GroupNumber = "de"; theSSN.SerialNumber = "fghi";
}
/// <summary>
/// First test method for isValid(String).
/// </summary>
[Test]
public void testIsValidString1()
{
Assert.IsTrue(SocSecNum.isValid("123456789"), "Expected 123456789 to be valid");
}
/// <summary>
/// Second test method for isValid(String).
/// </summary>
[Test]
public void testIsValidString2()
{
Assert.IsFalse(SocSecNum.isValid("12345678"), "Expected 12345678 to be invalid");
}
/// <summary>
/// Third test method for isValid(String).
/// </summary>
[Test]
public void testIsValidString3()
{
Assert.IsFalse(SocSecNum.isValid("1234567890"), "Expected 1234567890 to be invalid");
}
/// <summary>
/// Test method for isValid(String). This tests issues with alphanumeric input.
/// </summary>
[Test]
public void testIsValidStringAlpha()
{
Assert.IsFalse(SocSecNum.isValid("abcdefghi"), "Expected abcdefghi to be invalid");
}
/// <summary>
/// First test method for isValid(String). This tests issues with hyphenated input.
/// </summary>
[Test]
public void testIsValidStringHyphen1()
{
Assert.IsTrue(SocSecNum.isValid("123-45-6789"), "SocSecNum with dashes should be valid");
}
/// <summary>
/// Second test method for isValid(String). This tests issues with hyphenated input.
/// </summary>
[Test]
public void testIsValidStringHyphen2()
{
Assert.IsTrue(SocSecNum.isValid("12-345-6789"), "Don't care about misplaced dashes");
}
/// <summary>
/// Third test method for isValid(String). This tests issues with hyphenated input.
/// </summary>
[Test]
public void testIsValidStringHyphen3()
{
Assert.IsTrue(SocSecNum.isValid("123_45@6789"), "Don't care about odd delimiters - only the 9 numbers");
}
/// <summary>
/// Test method for stripField(String, int).
/// </summary>
[Test]
public void testStripField()
{
Assert.AreEqual("123", SocSecNum.stripField("123456789", 1), "Expected valid ssn to strip area num to 123");
Assert.AreEqual("45", SocSecNum.stripField("123456789", 2), "Expected valid ssn to strip group num to 45");
Assert.AreEqual("6789", SocSecNum.stripField("123456789", 3), "Expected valid ssn to strip serial num to 6789");
}
/// <summary>
/// Test method for stripField(String, int). This tests issues with an invalid fldnum argument.
/// </summary>
[Test]
public void testStripFieldFldnum()
{
Assert.AreEqual("", SocSecNum.stripField("123456789", 4), "Expected invalid fldnum of stripField to return blank");
}
/// <summary>
/// Test method for stripField(String, int). This tests issues with an input string being too short.
/// </summary>
[Test]
public void testStripFieldShort()
{
Assert.AreEqual("", SocSecNum.stripField("12", 1), "Expected short ssn to strip area number to be blank");
Assert.AreEqual("", SocSecNum.stripField("1234", 2), "Expected short ssn to strip group number to be blank");
Assert.AreEqual("", SocSecNum.stripField("12345678", 3), "Expected short ssn to strip serial number to be blank");
}
/// <summary>
/// Test method for stripField(String, int). This tests issues with an input string being too long.
/// </summary>
[Test]
public void testStripFieldLong()
{
Assert.AreEqual("123", SocSecNum.stripField("1234", 1), "Expected long ssn to strip area number to be 123");
Assert.AreEqual("45", SocSecNum.stripField("123456", 2), "Expected long ssn to strip group number to be 45");
Assert.AreEqual("6789", SocSecNum.stripField("1234567890", 3), "Expected long ssn to strip serial number to be 6789");
}
/// <summary>
/// Test method for stripField(String, int). This tests issues with a hyphenated input string.
/// </summary>
[Test]
public void testStripFieldHyphen()
{
Assert.AreEqual("123", SocSecNum.stripField("123-45-6789", 1), "Expected hyphenated ssn to strip area num to 123");
Assert.AreEqual("45", SocSecNum.stripField("123-45-6789", 2), "Expected hyphenated ssn to strip group num to 45");
Assert.AreEqual("6789", SocSecNum.stripField("123-45-6789", 3), "Expected hyphenated ssn to strip serial num to 6789");
}
#region PSEUDO_SSN_HANDLING
/// <summary>
/// Need to handle Pseudo SSNs as well. These should be indicated by a P (case-insensitive?) at the end of the number
/// This tests what would otherwise be a valid SSN
/// </summary>
[Test]
[Category("unit-only")]
public void TestPseudoSSNValidSSN()
{
SocSecNum testSsn = new SocSecNum("123456789p");
Assert.AreEqual("123", testSsn.AreaNumber, "Expected dashed area # to be 123");
Assert.AreEqual("45", testSsn.GroupNumber, "Expected dashed group # to be 45");
Assert.AreEqual("6789", testSsn.SerialNumber, "Expected dashed serial # to be 6789");
}
/// <summary>
/// Checking that making validity more inclusive by supporting pseudo SSNs
/// doesn't make validation more lax across the board for SSNs
/// </summary>
[Test]
[Category("unit-only")]
public void TestPseudoSSNInvalidSSN()
{
/// the 666 should invalidate the SSN, not the P
SocSecNum testSsn = new SocSecNum("666456789p");
Assert.IsFalse(testSsn.IsValid, "Should be an invalid SSN, even with the P stripped");
}
#endregion
#region WOOLWORTHS_AND_PAMPHLET_SSNS
[Test]
[Category("InvalidSocialSecurityNumbers")]
public void testSocialSecurityNumberInvalidNoDashesWoolworth()
{
SocSecNum theSSN = new SocSecNum("078051120");
Assert.IsFalse(theSSN.IsValid, "For social security number 078051120, expected IsValid to hold false");
}
[Test]
[Category("InvalidSocialSecurityNumbers")]
public void testSocialSecurityNumberInvalidNoDashesPamphlet()
{
SocSecNum theSSN = new SocSecNum("219099999");
Assert.IsFalse(theSSN.IsValid, "For social security number 219099999, expected IsValid to hold false");
}
[Test]
[Category("InvalidSocialSecurityNumbers")]
public void testSocialSecurityNumberInvalidDashesWoolworth()
{
SocSecNum theSSN = new SocSecNum("078-05-1120");
Assert.IsFalse(theSSN.IsValid, "For social security number 078-05-1120, expected IsValid to hold false");
}
[Test]
[Category("InvalidSocialSecurityNumbers")]
public void testSocialSecurityNumberInvalidDashesPamphlet()
{
SocSecNum theSSN = new SocSecNum("219-09-9999");
Assert.IsFalse(theSSN.IsValid, "For social security number 219-09-9999, expected IsValid to hold false");
}
#endregion // WOOLWORTHS_AND_PAMPHLET_SSNS
/// <summary>
/// Test method for toString().
/// </summary>
[Test]
public void testtoString()
{
SocSecNum theSSN = new SocSecNum("123456789");
Assert.AreEqual("123456789", theSSN.toString(), "Expected 123456789");
}
/// <summary>
/// Overriden ToString() returns unhyphenated SSN
/// </summary>
[Test]
public void testToString()
{
SocSecNum theSSN = new SocSecNum("123456789");
Assert.AreEqual("123456789", theSSN.ToString(), "Expected 123456789");
}
/// <summary>
/// Test method for toHyphenatedString().
/// </summary>
[Test]
public void testToHyphenatedString()
{
SocSecNum theSSN = new SocSecNum("123456789");
Assert.AreEqual("123-45-6789", theSSN.toHyphenatedString(), "Expected 123-45-6789");
}
[Test]
public void testSensitiveSsn()
{
SocSecNum theSSN = new SocSecNum("*SENSITIVE*");
Assert.IsTrue(theSSN.Sensitive);
Assert.IsTrue(theSSN.SensitivityString == theSSN.ToString());
}
[Test]
public void testSensitivityConstructor()
{
SocSecNum theSSN = new SocSecNum(true);
Assert.IsTrue(theSSN.Sensitive);
Assert.IsTrue(theSSN.SensitivityString == theSSN.ToString());
}
}
}
| |
// Copyright 2007-2017 Chris Patterson, Dru Sellers, Travis Smith, et. al.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed
// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
// CONDITIONS OF ANY KIND, either express or implied. See the License for the
// specific language governing permissions and limitations under the License.
namespace MassTransit.Tests.Serialization
{
using System;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
using Builders;
using MassTransit.Serialization;
using MassTransit.Testing;
using NUnit.Framework;
using Shouldly;
using TestFramework;
[TestFixture(typeof(JsonMessageSerializer))]
[TestFixture(typeof(BsonMessageSerializer))]
[TestFixture(typeof(XmlMessageSerializer))]
[TestFixture(typeof(EncryptedMessageSerializer))]
[TestFixture(typeof(EncryptedMessageSerializerV2))]
public class Deserializing_an_interface :
SerializationTest
{
[Test]
public void Should_create_a_proxy_for_the_interface()
{
var user = new UserImpl("Chris", "[email protected]");
ComplaintAdded complaint = new ComplaintAddedImpl(user, "No toilet paper", BusinessArea.Appearance)
{
Body = "There was no toilet paper in the stall, forcing me to use my treasured issue of .NET Developer magazine."
};
var result = SerializeAndReturn(complaint);
complaint.Equals(result).ShouldBe(true);
}
[Test]
public async Task Should_dispatch_an_interface_via_the_pipeline()
{
var pipe = new ConsumePipeBuilder().Build();
var consumer = new MultiTestConsumer(TestTimeout);
consumer.Consume<ComplaintAdded>();
consumer.Connect(pipe);
var user = new UserImpl("Chris", "[email protected]");
ComplaintAdded complaint = new ComplaintAddedImpl(user, "No toilet paper", BusinessArea.Appearance)
{
Body = "There was no toilet paper in the stall, forcing me to use my treasured issue of .NET Developer magazine."
};
await pipe.Send(new TestConsumeContext<ComplaintAdded>(complaint));
consumer.Received.Select<ComplaintAdded>().Any().ShouldBe(true);
}
public Deserializing_an_interface(Type serializerType)
: base(serializerType)
{
}
}
public interface ComplaintAdded
{
User AddedBy { get; }
DateTime AddedAt { get; }
string Subject { get; }
string Body { get; }
BusinessArea Area { get; }
}
public enum BusinessArea
{
Unknown = 0,
Appearance,
Courtesy
}
public interface User
{
string Name { get; }
string Email { get; }
}
public class UserImpl : User
{
public UserImpl(string name, string email)
{
Name = name;
Email = email;
}
protected UserImpl()
{
}
public string Name { get; set; }
public string Email { get; set; }
public bool Equals(User other)
{
if (ReferenceEquals(null, other))
return false;
if (ReferenceEquals(this, other))
return true;
return Equals(other.Name, Name) && Equals(other.Email, Email);
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj))
return false;
if (ReferenceEquals(this, obj))
return true;
if (!typeof(User).IsAssignableFrom(obj.GetType()))
return false;
return Equals((User)obj);
}
public override int GetHashCode()
{
unchecked
{
return ((Name != null ? Name.GetHashCode() : 0) * 397) ^ (Email != null ? Email.GetHashCode() : 0);
}
}
}
public class ComplaintAddedImpl :
ComplaintAdded
{
public ComplaintAddedImpl(User addedBy, string subject, BusinessArea area)
{
var dateTime = DateTime.UtcNow;
AddedAt = new DateTime(dateTime.Year, dateTime.Month, dateTime.Day, dateTime.Hour, dateTime.Minute, dateTime.Second,
dateTime.Millisecond, DateTimeKind.Utc);
AddedBy = addedBy;
Subject = subject;
Area = area;
Body = string.Empty;
}
protected ComplaintAddedImpl()
{
}
public User AddedBy { get; set; }
public DateTime AddedAt { get; set; }
public string Subject { get; set; }
public string Body { get; set; }
public BusinessArea Area { get; set; }
public bool Equals(ComplaintAdded other)
{
if (ReferenceEquals(null, other))
return false;
if (ReferenceEquals(this, other))
return true;
return AddedBy.Equals(other.AddedBy) && other.AddedAt.Equals(AddedAt) && Equals(other.Subject, Subject) && Equals(other.Body, Body)
&& Equals(other.Area, Area);
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj))
return false;
if (ReferenceEquals(this, obj))
return true;
if (!typeof(ComplaintAdded).GetTypeInfo().IsAssignableFrom(obj.GetType()))
return false;
return Equals((ComplaintAdded)obj);
}
public override int GetHashCode()
{
unchecked
{
var result = (AddedBy != null ? AddedBy.GetHashCode() : 0);
result = (result * 397) ^ AddedAt.GetHashCode();
result = (result * 397) ^ (Subject != null ? Subject.GetHashCode() : 0);
result = (result * 397) ^ (Body != null ? Body.GetHashCode() : 0);
result = (result * 397) ^ Area.GetHashCode();
return result;
}
}
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.IO;
using System.Reflection;
using System.Xml;
using System.Xml.Serialization;
using System.Text;
using System.Collections.Generic;
using log4net;
using Nini.Config;
using OpenSim.Framework;
using OpenMetaverse;
using Mono.Addins;
using OpenSim.Framework.Servers.HttpServer;
using OpenSim.Framework.Servers;
using OpenMetaverse.StructuredData; // LitJson is hidden on this
[assembly:AddinRoot("Robust", OpenSim.VersionInfo.VersionNumber)]
namespace OpenSim.Server.Base
{
[TypeExtensionPoint(Path="/Robust/Connector", Name="RobustConnector")]
public interface IRobustConnector
{
string ConfigName
{
get;
}
bool Enabled
{
get;
}
string PluginPath
{
get;
set;
}
uint Configure(IConfigSource config);
void Initialize(IHttpServer server);
void Unload();
}
public class PluginLoader
{
static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
public AddinRegistry Registry
{
get;
private set;
}
public IConfigSource Config
{
get;
private set;
}
public PluginLoader(IConfigSource config, string registryPath)
{
Config = config;
Registry = new AddinRegistry(registryPath, ".");
//suppress_console_output_(true);
AddinManager.Initialize(registryPath);
//suppress_console_output_(false);
AddinManager.Registry.Update();
CommandManager commandmanager = new CommandManager(Registry);
AddinManager.AddExtensionNodeHandler("/Robust/Connector", OnExtensionChanged);
}
private static TextWriter prev_console_;
// Temporarily masking the errors reported on start
// This is caused by a non-managed dll in the ./bin dir
// when the registry is initialized. The dll belongs to
// libomv, which has a hard-coded path to "." for pinvoke
// to load the openjpeg dll
//
// Will look for a way to fix, but for now this keeps the
// confusion to a minimum. this was copied from our region
// plugin loader, we have been doing this in there for a long time.
//
public void suppress_console_output_(bool save)
{
if (save)
{
prev_console_ = System.Console.Out;
System.Console.SetOut(new StreamWriter(Stream.Null));
}
else
{
if (prev_console_ != null)
System.Console.SetOut(prev_console_);
}
}
private void OnExtensionChanged(object s, ExtensionNodeEventArgs args)
{
IRobustConnector connector = (IRobustConnector)args.ExtensionObject;
Addin a = Registry.GetAddin(args.ExtensionNode.Addin.Id);
if(a == null)
{
Registry.Rebuild(null);
a = Registry.GetAddin(args.ExtensionNode.Addin.Id);
}
switch(args.Change)
{
case ExtensionChange.Add:
if (a.AddinFile.Contains(Registry.DefaultAddinsFolder))
{
m_log.InfoFormat("[SERVER UTILS]: Adding {0} from registry", a.Name);
connector.PluginPath = System.IO.Path.Combine(Registry.DefaultAddinsFolder,a.Name.Replace(',', '.')); }
else
{
m_log.InfoFormat("[SERVER UTILS]: Adding {0} from ./bin", a.Name);
connector.PluginPath = a.AddinFile;
}
LoadPlugin(connector);
break;
case ExtensionChange.Remove:
m_log.InfoFormat("[SERVER UTILS]: Removing {0}", a.Name);
UnloadPlugin(connector);
break;
}
}
private void LoadPlugin(IRobustConnector connector)
{
IHttpServer server = null;
uint port = connector.Configure(Config);
if(connector.Enabled)
{
server = GetServer(connector, port);
connector.Initialize(server);
}
else
{
m_log.InfoFormat("[SERVER UTILS]: {0} Disabled.", connector.ConfigName);
}
}
private void UnloadPlugin(IRobustConnector connector)
{
m_log.InfoFormat("[SERVER UTILS]: Unloading {0}", connector.ConfigName);
connector.Unload();
}
private IHttpServer GetServer(IRobustConnector connector, uint port)
{
IHttpServer server;
if(port != 0)
server = MainServer.GetHttpServer(port);
else
server = MainServer.Instance;
return server;
}
}
public static class ServerUtils
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
public static byte[] SerializeResult(XmlSerializer xs, object data)
{
using (MemoryStream ms = new MemoryStream())
using (XmlTextWriter xw = new XmlTextWriter(ms, Util.UTF8))
{
xw.Formatting = Formatting.Indented;
xs.Serialize(xw, data);
xw.Flush();
ms.Seek(0, SeekOrigin.Begin);
byte[] ret = ms.ToArray();
return ret;
}
}
/// <summary>
/// Load a plugin from a dll with the given class or interface
/// </summary>
/// <param name="dllName"></param>
/// <param name="args">The arguments which control which constructor is invoked on the plugin</param>
/// <returns></returns>
public static T LoadPlugin<T> (string dllName, Object[] args) where T:class
{
// This is good to debug configuration problems
//if (dllName == string.Empty)
// Util.PrintCallStack();
string className = String.Empty;
// The path for a dynamic plugin will contain ":" on Windows
string[] parts = dllName.Split (new char[] {':'});
if (parts [0].Length > 1)
{
dllName = parts [0];
if (parts.Length > 1)
className = parts[1];
}
else
{
// This is Windows - we must replace the ":" in the path
dllName = String.Format ("{0}:{1}", parts [0], parts [1]);
if (parts.Length > 2)
className = parts[2];
}
// Handle extra string arguments in a more generic way
if (dllName.Contains("@"))
{
string[] dllNameParts = dllName.Split(new char[] {'@'});
dllName = dllNameParts[dllNameParts.Length - 1];
List<Object> argList = new List<Object>(args);
for (int i = 0 ; i < dllNameParts.Length - 1 ; ++i)
argList.Add(dllNameParts[i]);
args = argList.ToArray();
}
return LoadPlugin<T>(dllName, className, args);
}
/// <summary>
/// Load a plugin from a dll with the given class or interface
/// </summary>
/// <param name="dllName"></param>
/// <param name="className"></param>
/// <param name="args">The arguments which control which constructor is invoked on the plugin</param>
/// <returns></returns>
public static T LoadPlugin<T>(string dllName, string className, Object[] args) where T:class
{
string interfaceName = typeof(T).ToString();
try
{
Assembly pluginAssembly = Assembly.LoadFrom(dllName);
foreach (Type pluginType in pluginAssembly.GetTypes())
{
if (pluginType.IsPublic)
{
if (className != String.Empty
&& pluginType.ToString() != pluginType.Namespace + "." + className)
continue;
Type typeInterface = pluginType.GetInterface(interfaceName);
if (typeInterface != null)
{
T plug = null;
try
{
plug = (T)Activator.CreateInstance(pluginType,
args);
}
catch (Exception e)
{
if (!(e is System.MissingMethodException))
{
m_log.Error(string.Format("[SERVER UTILS]: Error loading plugin {0} from {1}. Exception: {2}",
interfaceName,
dllName,
e.InnerException == null ? e.Message : e.InnerException.Message),
e);
}
m_log.ErrorFormat("[SERVER UTILS]: Error loading plugin {0}: {1} args.Length {2}", dllName, e.Message, args.Length);
return null;
}
return plug;
}
}
}
return null;
}
catch (ReflectionTypeLoadException rtle)
{
m_log.Error(string.Format("[SERVER UTILS]: Error loading plugin from {0}:\n{1}", dllName,
String.Join("\n", Array.ConvertAll(rtle.LoaderExceptions, e => e.ToString()))),
rtle);
return null;
}
catch (Exception e)
{
m_log.Error(string.Format("[SERVER UTILS]: Error loading plugin from {0}", dllName), e);
return null;
}
}
public static Dictionary<string, object> ParseQueryString(string query)
{
string[] terms = query.Split(new char[] {'&'});
int nterms = terms.Length;
if (nterms == 0)
return new Dictionary<string, object>();
Dictionary<string, object> result = new Dictionary<string, object>(nterms);
string name;
for(int i = 0; i < nterms; ++i)
{
string[] elems = terms[i].Split(new char[] {'='});
if (elems.Length == 0)
continue;
if(String.IsNullOrWhiteSpace(elems[0]))
continue;
name = System.Web.HttpUtility.UrlDecode(elems[0]);
if (name.EndsWith("[]"))
{
name = name.Substring(0, name.Length - 2);
if(String.IsNullOrWhiteSpace(name))
continue;
if (result.ContainsKey(name))
{
if (!(result[name] is List<string>))
continue;
List<string> l = (List<string>)result[name];
if (elems.Length > 1 && !String.IsNullOrWhiteSpace(elems[1]))
l.Add(System.Web.HttpUtility.UrlDecode(elems[1]));
else
l.Add(String.Empty);
}
else
{
List<string> newList = new List<string>();
if (elems.Length > 1 && !String.IsNullOrWhiteSpace(elems[1]))
newList.Add(System.Web.HttpUtility.UrlDecode(elems[1]));
else
newList.Add(String.Empty);
result[name] = newList;
}
}
else
{
if (!result.ContainsKey(name))
{
if (elems.Length > 1 && !String.IsNullOrWhiteSpace(elems[1]))
result[name] = System.Web.HttpUtility.UrlDecode(elems[1]);
else
result[name] = String.Empty;
}
}
}
return result;
}
public static string BuildQueryString(Dictionary<string, object> data)
{
// this is not conform to html url encoding
// can only be used on Body of POST or PUT
StringBuilder sb = new StringBuilder(4096);
string pvalue;
foreach (KeyValuePair<string, object> kvp in data)
{
if (kvp.Value is List<string>)
{
List<string> l = (List<String>)kvp.Value;
int llen = l.Count;
string nkey = System.Web.HttpUtility.UrlEncode(kvp.Key);
for(int i = 0; i < llen; ++i)
{
if (sb.Length != 0)
sb.Append("&");
sb.Append(nkey);
sb.Append("[]=");
sb.Append(System.Web.HttpUtility.UrlEncode(l[i]));
}
}
else if(kvp.Value is Dictionary<string, object>)
{
// encode complex structures as JSON
// needed for estate bans with the encoding used on xml
// encode can be here because object does contain the structure information
// but decode needs to be on estateSettings (or other user)
string js;
try
{
// bypass libovm, we dont need even more useless high level maps
// this should only be called once.. but no problem, i hope
// (other uses may need more..)
LitJson.JsonMapper.RegisterExporter<UUID>((uuid, writer) => writer.Write(uuid.ToString()) );
js = LitJson.JsonMapper.ToJson(kvp.Value);
}
// catch(Exception e)
catch
{
continue;
}
if (sb.Length != 0)
sb.Append("&");
sb.Append(System.Web.HttpUtility.UrlEncode(kvp.Key));
sb.Append("=");
sb.Append(System.Web.HttpUtility.UrlEncode(js));
}
else
{
if (sb.Length != 0)
sb.Append("&");
sb.Append(System.Web.HttpUtility.UrlEncode(kvp.Key));
pvalue = kvp.Value.ToString();
if (!String.IsNullOrEmpty(pvalue))
{
sb.Append("=");
sb.Append(System.Web.HttpUtility.UrlEncode(pvalue));
}
}
}
return sb.ToString();
}
public static string BuildXmlResponse(Dictionary<string, object> data)
{
XmlDocument doc = new XmlDocument();
XmlNode xmlnode = doc.CreateNode(XmlNodeType.XmlDeclaration,
"", "");
doc.AppendChild(xmlnode);
XmlElement rootElement = doc.CreateElement("", "ServerResponse",
"");
doc.AppendChild(rootElement);
BuildXmlData(rootElement, data);
return doc.InnerXml;
}
private static void BuildXmlData(XmlElement parent, Dictionary<string, object> data)
{
foreach (KeyValuePair<string, object> kvp in data)
{
if (kvp.Value == null)
continue;
XmlElement elem = parent.OwnerDocument.CreateElement("",
XmlConvert.EncodeLocalName(kvp.Key), "");
if (kvp.Value is Dictionary<string, object>)
{
XmlAttribute type = parent.OwnerDocument.CreateAttribute("",
"type", "");
type.Value = "List";
elem.Attributes.Append(type);
BuildXmlData(elem, (Dictionary<string, object>)kvp.Value);
}
else
{
elem.AppendChild(parent.OwnerDocument.CreateTextNode(
kvp.Value.ToString()));
}
parent.AppendChild(elem);
}
}
public static Dictionary<string, object> ParseXmlResponse(string data)
{
//m_log.DebugFormat("[XXX]: received xml string: {0}", data);
Dictionary<string, object> ret = new Dictionary<string, object>();
XmlDocument doc = new XmlDocument();
try
{
doc.LoadXml(data);
XmlNodeList rootL = doc.GetElementsByTagName("ServerResponse");
if (rootL.Count != 1)
return ret;
XmlNode rootNode = rootL[0];
ret = ParseElement(rootNode);
}
catch (Exception e)
{
m_log.DebugFormat("[serverUtils.ParseXmlResponse]: failed error: {0} \n --- string: {1} - ",e.Message, data);
}
return ret;
}
private static Dictionary<string, object> ParseElement(XmlNode element)
{
Dictionary<string, object> ret = new Dictionary<string, object>();
XmlNodeList partL = element.ChildNodes;
foreach (XmlNode part in partL)
{
XmlNode type = part.Attributes.GetNamedItem("type");
if (type == null || type.Value != "List")
{
ret[XmlConvert.DecodeName(part.Name)] = part.InnerText;
}
else
{
ret[XmlConvert.DecodeName(part.Name)] = ParseElement(part);
}
}
return ret;
}
public static IConfig GetConfig(string configFile, string configName)
{
IConfig config;
if (File.Exists(configFile))
{
IConfigSource configsource = new IniConfigSource(configFile);
config = configsource.Configs[configName];
}
else
config = null;
return config;
}
public static IConfigSource LoadInitialConfig(string url)
{
IConfigSource source = new XmlConfigSource();
m_log.InfoFormat("[SERVER UTILS]: {0} is a http:// URI, fetching ...", url);
// The ini file path is a http URI
// Try to read it
try
{
IConfigSource cs;
using( XmlReader r = XmlReader.Create(url))
{
cs = new XmlConfigSource(r);
source.Merge(cs);
}
}
catch (Exception e)
{
m_log.FatalFormat("[SERVER UTILS]: Exception reading config from URI {0}\n" + e.ToString(), url);
Environment.Exit(1);
}
return source;
}
}
}
| |
// 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 JitTest
{
using System;
internal class Test
{
private static void Fail(String func, double arg, double exp, double res)
{
throw new Exception(func + "(" + arg.ToString() +
") failed: expected " + exp.ToString() + ", got " + res.ToString());
}
private static void Fail2(String func, double arg1, double arg2, double exp, double res)
{
throw new Exception(func + "(" + arg1.ToString() +
", " + arg2.ToString() +
") failed: expected " + exp.ToString() + ", got " + res.ToString());
}
private static void TestAbs(double arg, double exp)
{
double res = Math.Abs(arg);
if (Double.IsNaN(exp) && Double.IsNaN(res) ||
Double.IsNegativeInfinity(exp) && Double.IsNegativeInfinity(res) ||
Double.IsPositiveInfinity(exp) && Double.IsPositiveInfinity(res))
{
Console.WriteLine(
"Abs(" + arg.ToString() + ") == " + res.ToString() + " OK");
return;
}
if (exp == res)
{
Console.WriteLine(
"Abs(" + arg.ToString() + ") == " + res.ToString() + " OK");
return;
}
Fail("Abs", arg, exp, res);
}
private static void TestAcos(double arg, double exp)
{
double res = Math.Acos(arg);
if (Double.IsNaN(exp) && Double.IsNaN(res) ||
Double.IsNegativeInfinity(exp) && Double.IsNegativeInfinity(res) ||
Double.IsPositiveInfinity(exp) && Double.IsPositiveInfinity(res))
{
Console.WriteLine(
"Acos(" + arg.ToString() + ") == " + res.ToString() + " OK");
return;
}
if (exp == res)
{
Console.WriteLine(
"Acos(" + arg.ToString() + ") == " + res.ToString() + " OK");
return;
}
Fail("Acos", res, arg, exp);
}
private static void TestAsin(double arg, double exp)
{
double res = Math.Asin(arg);
if (Double.IsNaN(exp) && Double.IsNaN(res) ||
Double.IsNegativeInfinity(exp) && Double.IsNegativeInfinity(res) ||
Double.IsPositiveInfinity(exp) && Double.IsPositiveInfinity(res))
{
Console.WriteLine(
"Asin(" + arg.ToString() + ") == " + res.ToString() + " OK");
return;
}
if (exp == res)
{
Console.WriteLine(
"Asin(" + arg.ToString() + ") == " + res.ToString() + " OK");
return;
}
Fail("Asin", res, arg, exp);
}
private static void TestAtan(double arg, double exp)
{
double res = Math.Atan(arg);
if (Double.IsNaN(exp) && Double.IsNaN(res) ||
Double.IsNegativeInfinity(exp) && Double.IsNegativeInfinity(res) ||
Double.IsPositiveInfinity(exp) && Double.IsPositiveInfinity(res))
{
Console.WriteLine(
"Atan(" + arg.ToString() + ") == " + res.ToString() + " OK");
return;
}
if (exp == res)
{
Console.WriteLine(
"Atan(" + arg.ToString() + ") == " + res.ToString() + " OK");
return;
}
Fail("Atan", res, arg, exp);
}
private static void TestCeiling(double arg, double exp)
{
double res = Math.Ceiling(arg);
if (Double.IsNaN(exp) && Double.IsNaN(res) ||
Double.IsNegativeInfinity(exp) && Double.IsNegativeInfinity(res) ||
Double.IsPositiveInfinity(exp) && Double.IsPositiveInfinity(res))
{
Console.WriteLine(
"Ceiling(" + arg.ToString() + ") == " + res.ToString() + " OK");
return;
}
if (exp == res)
{
Console.WriteLine(
"Ceiling(" + arg.ToString() + ") == " + res.ToString() + " OK");
return;
}
Fail("Ceiling", res, arg, exp);
}
private static void TestCos(double arg, double exp)
{
double res = Math.Cos(arg);
if (Double.IsNaN(exp) && Double.IsNaN(res) ||
Double.IsNegativeInfinity(exp) && Double.IsNegativeInfinity(res) ||
Double.IsPositiveInfinity(exp) && Double.IsPositiveInfinity(res))
{
Console.WriteLine(
"Cos(" + arg.ToString() + ") == " + res.ToString() + " OK");
return;
}
if (exp == res)
{
Console.WriteLine(
"Cos(" + arg.ToString() + ") == " + res.ToString() + " OK");
return;
}
Fail("Cos", res, arg, exp);
}
private static void TestCosh(double arg, double exp)
{
double res = Math.Cosh(arg);
if (Double.IsNaN(exp) && Double.IsNaN(res) ||
Double.IsNegativeInfinity(exp) && Double.IsNegativeInfinity(res) ||
Double.IsPositiveInfinity(exp) && Double.IsPositiveInfinity(res))
{
Console.WriteLine(
"Cosh(" + arg.ToString() + ") == " + res.ToString() + " OK");
return;
}
if (exp == res)
{
Console.WriteLine(
"Cosh(" + arg.ToString() + ") == " + res.ToString() + " OK");
return;
}
Fail("Cosh", res, arg, exp);
}
private static void TestExp(double arg, double exp)
{
double res = Math.Exp(arg);
if (Double.IsNaN(exp) && Double.IsNaN(res) ||
Double.IsNegativeInfinity(exp) && Double.IsNegativeInfinity(res) ||
Double.IsPositiveInfinity(exp) && Double.IsPositiveInfinity(res))
{
Console.WriteLine(
"Exp(" + arg.ToString() + ") == " + res.ToString() + " OK");
return;
}
if (exp == res)
{
Console.WriteLine(
"Exp(" + arg.ToString() + ") == " + res.ToString() + " OK");
return;
}
Fail("Exp", res, arg, exp);
}
private static void TestFloor(double arg, double exp)
{
double res = Math.Floor(arg);
if (Double.IsNaN(exp) && Double.IsNaN(res) ||
Double.IsNegativeInfinity(exp) && Double.IsNegativeInfinity(res) ||
Double.IsPositiveInfinity(exp) && Double.IsPositiveInfinity(res))
{
Console.WriteLine(
"Floor(" + arg.ToString() + ") == " + res.ToString() + " OK");
return;
}
if (exp == res)
{
Console.WriteLine(
"Floor(" + arg.ToString() + ") == " + res.ToString() + " OK");
return;
}
Fail("Floor", res, arg, exp);
}
private static void TestLog(double arg, double exp)
{
double res = Math.Log(arg);
if (Double.IsNaN(exp) && Double.IsNaN(res) ||
Double.IsNegativeInfinity(exp) && Double.IsNegativeInfinity(res) ||
Double.IsPositiveInfinity(exp) && Double.IsPositiveInfinity(res))
{
Console.WriteLine(
"Log(" + arg.ToString() + ") == " + res.ToString() + " OK");
return;
}
if (exp == res)
{
Console.WriteLine(
"Log(" + arg.ToString() + ") == " + res.ToString() + " OK");
return;
}
Fail("Log", res, arg, exp);
}
private static void TestLog10(double arg, double exp)
{
double res = Math.Log10(arg);
if (Double.IsNaN(exp) && Double.IsNaN(res) ||
Double.IsNegativeInfinity(exp) && Double.IsNegativeInfinity(res) ||
Double.IsPositiveInfinity(exp) && Double.IsPositiveInfinity(res))
{
Console.WriteLine(
"Log10(" + arg.ToString() + ") == " + res.ToString() + " OK");
return;
}
if (exp == res)
{
Console.WriteLine(
"Log10(" + arg.ToString() + ") == " + res.ToString() + " OK");
return;
}
Fail("Log10", res, arg, exp);
}
private static void TestRound(double arg, double exp)
{
double res = Math.Round(arg);
if (Double.IsNaN(exp) && Double.IsNaN(res) ||
Double.IsNegativeInfinity(exp) && Double.IsNegativeInfinity(res) ||
Double.IsPositiveInfinity(exp) && Double.IsPositiveInfinity(res))
{
Console.WriteLine(
"Round(" + arg.ToString() + ") == " + res.ToString() + " OK");
return;
}
if (exp == res)
{
Console.WriteLine(
"Round(" + arg.ToString() + ") == " + res.ToString() + " OK");
return;
}
Fail("Round", res, arg, exp);
}
private static void TestSign(double arg, double exp)
{
double res = Math.Sign(arg);
if (Double.IsNaN(exp) && Double.IsNaN(res) ||
Double.IsNegativeInfinity(exp) && Double.IsNegativeInfinity(res) ||
Double.IsPositiveInfinity(exp) && Double.IsPositiveInfinity(res))
{
Console.WriteLine(
"Sign(" + arg.ToString() + ") == " + res.ToString() + " OK");
return;
}
if (exp == res)
{
Console.WriteLine(
"Sign(" + arg.ToString() + ") == " + res.ToString() + " OK");
return;
}
Fail("Sign", res, arg, exp);
}
private static void TestSin(double arg, double exp)
{
double res = Math.Sin(arg);
if (Double.IsNaN(exp) && Double.IsNaN(res) ||
Double.IsNegativeInfinity(exp) && Double.IsNegativeInfinity(res) ||
Double.IsPositiveInfinity(exp) && Double.IsPositiveInfinity(res))
{
Console.WriteLine(
"Sin(" + arg.ToString() + ") == " + res.ToString() + " OK");
return;
}
if (exp == res)
{
Console.WriteLine(
"Sin(" + arg.ToString() + ") == " + res.ToString() + " OK");
return;
}
Fail("Sin", res, arg, exp);
}
private static void TestSinh(double arg, double exp)
{
double res = Math.Sinh(arg);
if (Double.IsNaN(exp) && Double.IsNaN(res) ||
Double.IsNegativeInfinity(exp) && Double.IsNegativeInfinity(res) ||
Double.IsPositiveInfinity(exp) && Double.IsPositiveInfinity(res))
{
Console.WriteLine(
"Sinh(" + arg.ToString() + ") == " + res.ToString() + " OK");
return;
}
if (exp == res)
{
Console.WriteLine(
"Sinh(" + arg.ToString() + ") == " + res.ToString() + " OK");
return;
}
Fail("Sinh", res, arg, exp);
}
private static void TestSqrt(double arg, double exp)
{
double res = Math.Sqrt(arg);
if (Double.IsNaN(exp) && Double.IsNaN(res) ||
Double.IsNegativeInfinity(exp) && Double.IsNegativeInfinity(res) ||
Double.IsPositiveInfinity(exp) && Double.IsPositiveInfinity(res))
{
Console.WriteLine(
"Sqrt(" + arg.ToString() + ") == " + res.ToString() + " OK");
return;
}
if (exp == res)
{
Console.WriteLine(
"Sqrt(" + arg.ToString() + ") == " + res.ToString() + " OK");
return;
}
Fail("Sqrt", res, arg, exp);
}
private static void TestTan(double arg, double exp)
{
double res = Math.Tan(arg);
if (Double.IsNaN(exp) && Double.IsNaN(res) ||
Double.IsNegativeInfinity(exp) && Double.IsNegativeInfinity(res) ||
Double.IsPositiveInfinity(exp) && Double.IsPositiveInfinity(res))
{
Console.WriteLine(
"Tan(" + arg.ToString() + ") == " + res.ToString() + " OK");
return;
}
if (exp == res)
{
Console.WriteLine(
"Tan(" + arg.ToString() + ") == " + res.ToString() + " OK");
return;
}
Fail("Tan", res, arg, exp);
}
private static void TestTanh(double arg, double exp)
{
double res = Math.Tanh(arg);
if (Double.IsNaN(exp) && Double.IsNaN(res) ||
Double.IsNegativeInfinity(exp) && Double.IsNegativeInfinity(res) ||
Double.IsPositiveInfinity(exp) && Double.IsPositiveInfinity(res))
{
Console.WriteLine(
"Tanh(" + arg.ToString() + ") == " + res.ToString() + " OK");
return;
}
if (exp == res)
{
Console.WriteLine(
"Tanh(" + arg.ToString() + ") == " + res.ToString() + " OK");
return;
}
Fail("Tanh", res, arg, exp);
}
private static void TestLog2(double arg1, double arg2, double exp)
{
double res = Math.Log(arg1, arg2);
if (Double.IsNaN(exp) && Double.IsNaN(res) ||
Double.IsNegativeInfinity(exp) && Double.IsNegativeInfinity(res) ||
Double.IsPositiveInfinity(exp) && Double.IsPositiveInfinity(res))
{
Console.WriteLine(
"Log2(" + arg1.ToString() + ", " + arg2.ToString() + ") == " + res.ToString() + " OK");
return;
}
if (exp == res)
{
Console.WriteLine(
"Log2(" + arg1.ToString() + ", " + arg2.ToString() + ") == " + res.ToString() + " OK");
return;
}
Fail2("Log2", arg1, arg2, exp, res);
}
private static void TestPow(double arg1, double arg2, double exp)
{
double res = Math.Pow(arg1, arg2);
if (Double.IsNaN(exp) && Double.IsNaN(res) ||
Double.IsNegativeInfinity(exp) && Double.IsNegativeInfinity(res) ||
Double.IsPositiveInfinity(exp) && Double.IsPositiveInfinity(res))
{
Console.WriteLine(
"Pow(" + arg1.ToString() + ", " + arg2.ToString() + ") == " + res.ToString() + " OK");
return;
}
if (exp == res)
{
Console.WriteLine(
"Pow(" + arg1.ToString() + ", " + arg2.ToString() + ") == " + res.ToString() + " OK");
return;
}
Fail2("Pow", arg1, arg2, exp, res);
}
private static void TestAtan2(double arg1, double arg2, double exp)
{
double res = Math.Atan2(arg1, arg2);
if (Double.IsNaN(exp) && Double.IsNaN(res) ||
Double.IsNegativeInfinity(exp) && Double.IsNegativeInfinity(res) ||
Double.IsPositiveInfinity(exp) && Double.IsPositiveInfinity(res))
{
Console.WriteLine(
"Atan2(" + arg1.ToString() + ", " + arg2.ToString() + ") == " + res.ToString() + " OK");
return;
}
if (exp == res)
{
Console.WriteLine(
"Atan2(" + arg1.ToString() + ", " + arg2.ToString() + ") == " + res.ToString() + " OK");
return;
}
Fail2("Atan2", arg1, arg2, exp, res);
}
private static int Main()
{
try
{
TestAbs(Double.NaN, Double.NaN);
TestAbs(Double.NegativeInfinity, Double.PositiveInfinity);
TestAbs(Double.PositiveInfinity, Double.PositiveInfinity);
TestAcos(Double.NaN, Double.NaN);
TestAcos(Double.NegativeInfinity, Double.NaN);
TestAcos(Double.PositiveInfinity, Double.NaN);
TestAsin(Double.NaN, Double.NaN);
TestAsin(Double.NegativeInfinity, Double.NaN);
TestAsin(Double.PositiveInfinity, Double.NaN);
TestAtan(Double.NaN, Double.NaN);
TestAtan(Double.NegativeInfinity, -Math.PI / 2);
TestAtan(Double.PositiveInfinity, Math.PI / 2);
TestCeiling(Double.NaN, Double.NaN);
TestCeiling(Double.NegativeInfinity, Double.NegativeInfinity);
TestCeiling(Double.PositiveInfinity, Double.PositiveInfinity);
TestCos(Double.NaN, Double.NaN);
TestCos(Double.NegativeInfinity, Double.NaN);
TestCos(Double.PositiveInfinity, Double.NaN);
TestCosh(Double.NaN, Double.NaN);
TestCosh(Double.NegativeInfinity, Double.PositiveInfinity);
TestCosh(Double.PositiveInfinity, Double.PositiveInfinity);
TestExp(Double.NaN, Double.NaN);
TestExp(Double.NegativeInfinity, 0.0);
TestExp(Double.PositiveInfinity, Double.PositiveInfinity);
TestFloor(Double.NaN, Double.NaN);
TestFloor(Double.NegativeInfinity, Double.NegativeInfinity);
TestFloor(Double.PositiveInfinity, Double.PositiveInfinity);
TestLog(Double.NaN, Double.NaN);
TestLog(Double.NegativeInfinity, Double.NaN);
TestLog(Double.PositiveInfinity, Double.PositiveInfinity);
TestLog10(Double.NaN, Double.NaN);
TestLog10(Double.NegativeInfinity, Double.NaN);
TestLog10(Double.PositiveInfinity, Double.PositiveInfinity);
TestRound(Double.NaN, Double.NaN);
TestRound(Double.NegativeInfinity, Double.NegativeInfinity);
TestRound(Double.PositiveInfinity, Double.PositiveInfinity);
TestSign(Double.NegativeInfinity, -1);
TestSign(Double.PositiveInfinity, 1);
TestSin(Double.NaN, Double.NaN);
TestSin(Double.NegativeInfinity, Double.NaN);
TestSin(Double.PositiveInfinity, Double.NaN);
TestSinh(Double.NaN, Double.NaN);
TestSinh(Double.NegativeInfinity, Double.NegativeInfinity);
TestSinh(Double.PositiveInfinity, Double.PositiveInfinity);
TestSqrt(Double.NaN, Double.NaN);
TestSqrt(Double.NegativeInfinity, Double.NaN);
TestSqrt(Double.PositiveInfinity, Double.PositiveInfinity);
TestTan(Double.NaN, Double.NaN);
TestTan(Double.NegativeInfinity, Double.NaN);
TestTan(Double.PositiveInfinity, Double.NaN);
TestTanh(Double.NaN, Double.NaN);
TestTanh(Double.NegativeInfinity, -1);
TestTanh(Double.PositiveInfinity, 1);
TestLog2(Double.NaN, Double.NaN, Double.NaN);
TestLog2(Double.NaN, Double.PositiveInfinity, Double.NaN);
TestLog2(Double.NaN, Double.NegativeInfinity, Double.NaN);
TestLog2(Double.PositiveInfinity, Double.NaN, Double.NaN);
TestLog2(Double.PositiveInfinity, Double.PositiveInfinity, Double.NaN);
TestLog2(Double.PositiveInfinity, Double.NegativeInfinity, Double.NaN);
TestLog2(Double.NegativeInfinity, Double.NaN, Double.NaN);
TestLog2(Double.NegativeInfinity, Double.PositiveInfinity, Double.NaN);
TestLog2(Double.NegativeInfinity, Double.NegativeInfinity, Double.NaN);
TestPow(Double.NaN, Double.NaN, Double.NaN);
TestPow(Double.NaN, Double.PositiveInfinity, Double.NaN);
TestPow(Double.NaN, Double.NegativeInfinity, Double.NaN);
TestPow(Double.PositiveInfinity, Double.NaN, Double.NaN);
TestPow(Double.PositiveInfinity, Double.PositiveInfinity, Double.PositiveInfinity);
TestPow(Double.PositiveInfinity, Double.NegativeInfinity, 0.0);
TestPow(Double.NegativeInfinity, Double.NaN, Double.NaN);
TestPow(Double.NegativeInfinity, Double.PositiveInfinity, Double.PositiveInfinity);
TestPow(Double.NegativeInfinity, Double.NegativeInfinity, 0.0);
TestAtan2(Double.NaN, Double.NaN, Double.NaN);
TestAtan2(Double.NaN, Double.PositiveInfinity, Double.NaN);
TestAtan2(Double.NaN, Double.NegativeInfinity, Double.NaN);
TestAtan2(Double.PositiveInfinity, Double.NaN, Double.NaN);
TestAtan2(Double.PositiveInfinity, Double.PositiveInfinity, Double.NaN);
TestAtan2(Double.PositiveInfinity, Double.NegativeInfinity, Double.NaN);
TestAtan2(Double.NegativeInfinity, Double.NaN, Double.NaN);
TestAtan2(Double.NegativeInfinity, Double.PositiveInfinity, Double.NaN);
TestAtan2(Double.NegativeInfinity, Double.NegativeInfinity, Double.NaN);
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
Console.WriteLine("=== FAILED ===");
return 101;
}
Console.WriteLine("=== PASSED ===");
return 100;
}
}
}
| |
using PlayFab.Json;
using PlayFab.Public;
using PlayFab.SharedModels;
using System;
using System.Collections.Generic;
using System.Text;
using UnityEngine;
namespace PlayFab.Internal
{
/// <summary>
/// This is a wrapper for Http So we can better separate the functionaity of Http Requests delegated to WWW or HttpWebRequest
/// </summary>
public class PlayFabHttp : SingletonMonoBehaviour<PlayFabHttp>
{
private static IPlayFabHttp _internalHttp; //This is the default;
private static List<CallRequestContainer> _apiCallQueue = new List<CallRequestContainer>(); // Starts initialized, and is nulled when it's flushed
public delegate void ApiProcessingEvent<in TEventArgs>(TEventArgs e);
public delegate void ApiProcessErrorEvent(PlayFabRequestCommon request, PlayFabError error);
public static event ApiProcessingEvent<ApiProcessingEventArgs> ApiProcessingEventHandler;
public static event ApiProcessErrorEvent ApiProcessingErrorEventHandler;
public static readonly Dictionary<string, string> GlobalHeaderInjection = new Dictionary<string, string>();
#if ENABLE_PLAYFABPLAYSTREAM_API && ENABLE_PLAYFABSERVER_API
private static IPlayFabSignalR _internalSignalR;
#endif
private static IPlayFabLogger _logger;
#if PLAYFAB_REQUEST_TIMING
public struct RequestTiming
{
public DateTime StartTimeUtc;
public string ApiEndpoint;
public int WorkerRequestMs;
public int MainThreadRequestMs;
}
public delegate void ApiRequestTimingEvent(RequestTiming time);
public static event ApiRequestTimingEvent ApiRequestTimingEventHandler;
#endif
/// <summary>
/// Return the number of api calls that are waiting for results from the server
/// </summary>
/// <returns></returns>
public static int GetPendingMessages()
{
return _internalHttp == null ? 0 : _internalHttp.GetPendingMessages();
}
/// <summary>
/// Optional redirect to allow mocking of _internalHttp calls, or use a custom _internalHttp utility
/// </summary>
public static void SetHttp<THttpObject>(THttpObject httpObj) where THttpObject : IPlayFabHttp
{
_internalHttp = httpObj;
}
/// <summary>
/// Optional redirect to allow mocking of AuthKey
/// </summary>
/// <param name="authKey"></param>
public static void SetAuthKey(string authKey)
{
_internalHttp.AuthKey = authKey;
}
/// <summary>
/// This initializes the GameObject and ensures it is in the scene.
/// </summary>
public static void InitializeHttp()
{
if (_internalHttp != null)
return;
Application.runInBackground = true; // Http requests respond even if you lose focus
#if !UNITY_WSA && !UNITY_WP8
if (PlayFabSettings.RequestType == WebRequestType.HttpWebRequest)
_internalHttp = new PlayFabWebRequest();
#endif
if (_internalHttp == null)
_internalHttp = new PlayFabWww();
_internalHttp.InitializeHttp();
CreateInstance(); // Invoke the SingletonMonoBehaviour
}
/// <summary>
/// This initializes the GameObject and ensures it is in the scene.
/// </summary>
public static void InitializeLogger(IPlayFabLogger setLogger = null)
{
if (_logger != null)
throw new Exception("Once initialized, the logger cannot be reset.");
if (setLogger == null)
setLogger = new PlayFabLogger();
_logger = setLogger;
}
#if ENABLE_PLAYFABPLAYSTREAM_API && ENABLE_PLAYFABSERVER_API
public static void InitializeSignalR(string baseUrl, string hubName, Action onConnected, Action<string>onReceived, Action onReconnected, Action onDisconnected, Action<Exception> onError)
{
CreateInstance();
if (_internalSignalR != null) return;
_internalSignalR = new PlayFabSignalR (onConnected);
_internalSignalR.OnReceived += onReceived;
_internalSignalR.OnReconnected += onReconnected;
_internalSignalR.OnDisconnected += onDisconnected;
_internalSignalR.OnError += onError;
_internalSignalR.Start(baseUrl, hubName);
}
public static void SubscribeSignalR(string onInvoked, Action<object[]> callbacks)
{
_internalSignalR.Subscribe(onInvoked, callbacks);
}
public static void InvokeSignalR(string methodName, Action callback, params object[] args)
{
_internalSignalR.Invoke(methodName, callback, args);
}
public static void StopSignalR()
{
_internalSignalR.Stop();
}
#endif
/// <summary>
/// Internal method for Make API Calls
/// </summary>
protected internal static void MakeApiCall<TResult>(string apiEndpoint,
PlayFabRequestCommon request, AuthType authType, Action<TResult> resultCallback,
Action<PlayFabError> errorCallback, object customData = null, Dictionary<string, string> extraHeaders = null, bool allowQueueing = false)
where TResult : PlayFabResultCommon
{
InitializeHttp();
SendEvent(apiEndpoint, request, null, ApiProcessingEventType.Pre);
var reqContainer = new CallRequestContainer
{
ApiEndpoint = apiEndpoint,
FullUrl = PlayFabSettings.GetFullUrl(apiEndpoint),
CustomData = customData,
Payload = Encoding.UTF8.GetBytes(JsonWrapper.SerializeObject(request)),
ApiRequest = request,
ErrorCallback = errorCallback,
RequestHeaders = extraHeaders ?? new Dictionary<string, string>() // Use any headers provided by the customer
};
// Append any additional headers
foreach (var pair in GlobalHeaderInjection)
if (!reqContainer.RequestHeaders.ContainsKey(pair.Key))
reqContainer.RequestHeaders[pair.Key] = pair.Value;
#if PLAYFAB_REQUEST_TIMING
reqContainer.Timing.StartTimeUtc = DateTime.UtcNow;
reqContainer.Timing.ApiEndpoint = apiEndpoint;
#endif
// Add PlayFab Headers
reqContainer.RequestHeaders["X-ReportErrorAsSuccess"] = "true"; // Makes processing PlayFab errors a little easier
reqContainer.RequestHeaders["X-PlayFabSDK"] = PlayFabSettings.VersionString; // Tell PlayFab which SDK this is
switch (authType)
{
#if ENABLE_PLAYFABSERVER_API || ENABLE_PLAYFABADMIN_API
case AuthType.DevSecretKey: reqContainer.RequestHeaders["X-SecretKey"] = PlayFabSettings.DeveloperSecretKey; break;
#endif
case AuthType.LoginSession: reqContainer.RequestHeaders["X-Authorization"] = _internalHttp.AuthKey; break;
}
// These closures preserve the TResult generic information in a way that's safe for all the devices
reqContainer.DeserializeResultJson = () =>
{
reqContainer.ApiResult = JsonWrapper.DeserializeObject<TResult>(reqContainer.JsonResponse);
};
reqContainer.InvokeSuccessCallback = () =>
{
if (resultCallback != null)
resultCallback((TResult)reqContainer.ApiResult);
};
if (allowQueueing && _apiCallQueue != null && !_internalHttp.SessionStarted)
{
for (var i = _apiCallQueue.Count - 1; i >= 0; i--)
if (_apiCallQueue[i].ApiEndpoint == apiEndpoint)
_apiCallQueue.RemoveAt(i);
_apiCallQueue.Add(reqContainer);
}
else
{
_internalHttp.MakeApiCall(reqContainer);
}
}
/// <summary>
/// MonoBehaviour OnEnable Method
/// </summary>
public void OnEnable()
{
if (_logger != null)
{
_logger.OnEnable();
}
}
/// <summary>
/// MonoBehaviour OnDisable
/// </summary>
public void OnDisable()
{
if (_logger != null)
{
_logger.OnDisable();
}
}
/// <summary>
/// MonoBehaviour OnDestroy
/// </summary>
public void OnDestroy()
{
if (_internalHttp != null)
{
_internalHttp.OnDestroy();
}
#if ENABLE_PLAYFABPLAYSTREAM_API && ENABLE_PLAYFABSERVER_API
if (_internalSignalR != null)
{
_internalSignalR.Stop();
}
#endif
if (_logger != null)
{
_logger.OnDestroy();
}
}
/// <summary>
/// MonoBehaviour Update
/// </summary>
public void Update()
{
if (_internalHttp != null)
{
if (!_internalHttp.SessionStarted && _apiCallQueue != null)
{
foreach (var eachRequest in _apiCallQueue)
_internalHttp.MakeApiCall(eachRequest); // Flush the queue
_apiCallQueue = null; // null this after it's flushed
}
_internalHttp.Update();
}
#if ENABLE_PLAYFABPLAYSTREAM_API && ENABLE_PLAYFABSERVER_API
if (_internalSignalR != null)
{
_internalSignalR.Update();
}
#endif
}
#region Helpers
public static bool IsClientLoggedIn()
{
return _internalHttp != null && !string.IsNullOrEmpty(_internalHttp.AuthKey);
}
public static void ForgetClientCredentials()
{
if (_internalHttp != null)
_internalHttp.AuthKey = null;
}
protected internal static PlayFabError GeneratePlayFabError(string json, object customData)
{
JsonObject errorDict = null;
Dictionary<string, List<string>> errorDetails = null;
try
{
// Deserialize the error
errorDict = JsonWrapper.DeserializeObject<JsonObject>(json);
}
catch (Exception) { /* Unusual, but shouldn't actually matter */ }
try
{
if (errorDict != null && errorDict.ContainsKey("errorDetails"))
errorDetails = JsonWrapper.DeserializeObject<Dictionary<string, List<string>>>(errorDict["errorDetails"].ToString());
}
catch (Exception) { /* Unusual, but shouldn't actually matter */ }
return new PlayFabError
{
HttpCode = errorDict != null && errorDict.ContainsKey("code") ? Convert.ToInt32(errorDict["code"]) : 400,
HttpStatus = errorDict != null && errorDict.ContainsKey("status") ? (string)errorDict["status"] : "BadRequest",
Error = errorDict != null && errorDict.ContainsKey("errorCode") ? (PlayFabErrorCode)Convert.ToInt32(errorDict["errorCode"]) : PlayFabErrorCode.ServiceUnavailable,
ErrorMessage = errorDict != null && errorDict.ContainsKey("errorMessage") ? (string)errorDict["errorMessage"] : json,
ErrorDetails = errorDetails,
CustomData = customData
};
}
protected internal static void SendErrorEvent(PlayFabRequestCommon request, PlayFabError error)
{
if (ApiProcessingErrorEventHandler == null)
return;
try
{
ApiProcessingErrorEventHandler(request, error);
}
catch (Exception e)
{
Debug.LogException(e);
}
}
protected internal static void SendEvent(string apiEndpoint, PlayFabRequestCommon request, PlayFabResultCommon result, ApiProcessingEventType eventType)
{
if (ApiProcessingEventHandler == null)
return;
try
{
ApiProcessingEventHandler(new ApiProcessingEventArgs
{
ApiEndpoint = apiEndpoint,
EventType = eventType,
Request = request,
Result = result
});
}
catch (Exception e)
{
Debug.LogException(e);
}
}
protected internal static void ClearAllEvents()
{
ApiProcessingEventHandler = null;
ApiProcessingErrorEventHandler = null;
}
#if PLAYFAB_REQUEST_TIMING
protected internal static void SendRequestTiming(RequestTiming rt) {
if (ApiRequestTimingEventHandler != null) {
ApiRequestTimingEventHandler(rt);
}
}
#endif
#endregion
}
#region Event Classes
public enum ApiProcessingEventType
{
Pre,
Post
}
public class ApiProcessingEventArgs
{
public string ApiEndpoint;
public ApiProcessingEventType EventType;
public PlayFabRequestCommon Request;
public PlayFabResultCommon Result;
public TRequest GetRequest<TRequest>() where TRequest : PlayFabRequestCommon
{
return Request as TRequest;
}
}
#endregion
}
| |
#pragma warning disable CS0618 // Type or member is obsolete
using System.ComponentModel;
using System.Diagnostics;
using System.Runtime.InteropServices;
using FluentAssertions;
using TestUtilities;
using Xunit;
namespace Meziantou.Framework.Tests;
[Collection("ProcessExtensions")]
public class ProcessExtensionsTests
{
[Fact]
public async Task RunAsTask()
{
static Task<ProcessResult> CreateProcess()
{
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
return ProcessExtensions.RunAsTaskAsync("cmd", "/C echo test", CancellationToken.None);
return ProcessExtensions.RunAsTaskAsync("echo", "test", CancellationToken.None);
}
var result = await CreateProcess().ConfigureAwait(false);
result.ExitCode.Should().Be(0);
result.Output.Should().ContainSingle();
result.Output[0].Text.Should().Be("test");
result.Output[0].Type.Should().Be(ProcessOutputType.StandardOutput);
}
[Fact]
public async Task RunAsTask_RedirectOutput()
{
ProcessStartInfo psi;
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
psi = new ProcessStartInfo
{
FileName = "cmd.exe",
Arguments = "/C echo test",
};
}
else
{
psi = new ProcessStartInfo
{
FileName = "echo",
Arguments = "test",
};
}
var result = await psi.RunAsTaskAsync(redirectOutput: true, CancellationToken.None).ConfigureAwait(false);
result.ExitCode.Should().Be(0);
result.Output.Should().ContainSingle();
result.Output[0].Text.Should().Be("test");
result.Output[0].Type.Should().Be(ProcessOutputType.StandardOutput);
}
[Fact]
public async Task RunAsTask_DoNotRedirectOutput()
{
ProcessStartInfo psi;
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
psi = new ProcessStartInfo
{
FileName = "cmd.exe",
Arguments = "/C echo test",
};
}
else
{
psi = new ProcessStartInfo
{
FileName = "echo",
Arguments = "test",
};
}
var result = await psi.RunAsTaskAsync(redirectOutput: false, CancellationToken.None).ConfigureAwait(false);
result.ExitCode.Should().Be(0);
result.Output.Should().BeEmpty();
}
[Fact]
public async Task RunAsTask_ProcessDoesNotExists()
{
var psi = new ProcessStartInfo("ProcessDoesNotExists.exe");
await new Func<Task>(() => psi.RunAsTaskAsync(CancellationToken.None)).Should().ThrowExactlyAsync<Win32Exception>().ConfigureAwait(false);
}
[Fact]
public async Task RunAsTask_Cancel()
{
var stopwatch = Stopwatch.StartNew();
using var cts = new CancellationTokenSource();
Task task;
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
task = ProcessExtensions.RunAsTaskAsync("ping.exe", "127.0.0.1 -n 10", cts.Token);
}
else
{
task = ProcessExtensions.RunAsTaskAsync("ping", "127.0.0.1 -c 10", cts.Token);
}
// Wait for the process to start
while (true)
{
var processes = Process.GetProcesses();
if (processes.Any(p => p.ProcessName.EqualsIgnoreCase("ping") || p.ProcessName.EqualsIgnoreCase("ping.exe")))
break;
await Task.Delay(100);
(stopwatch.Elapsed > TimeSpan.FromSeconds(10)).Should().BeFalse("Cannot find the process");
}
cts.Cancel();
await new Func<Task>(() => task).Should().ThrowAsync<OperationCanceledException>().ConfigureAwait(false);
}
[RunIfFact(FactOperatingSystem.Windows)]
public void GetProcesses()
{
var processes = ProcessExtensions.GetProcesses();
var currentProcess = Process.GetCurrentProcess();
processes.Should().Contain(p => p.ProcessId == currentProcess.Id, "Current process is not in the list of processes");
processes.Should().OnlyHaveUniqueItems();
}
[RunIfFact(FactOperatingSystem.Windows)]
public void GetDescendantProcesses()
{
using var process = Process.Start("cmd.exe", "/C ping 127.0.0.1 -n 10");
try
{
// We need to wait for the process to be started by cmd
IReadOnlyCollection<Process> processes;
while ((processes = process.GetDescendantProcesses()).Count == 0)
{
Thread.Sleep(100);
continue;
}
(processes.Count == 1 || processes.Count == 2).Should().BeTrue($"There should be 1 or 2 children (ping and conhost): {string.Join(",", processes.Select(p => p.ProcessName))}");
processes.Any(p => p.ProcessName.EqualsIgnoreCase("PING") || p.ProcessName.EqualsIgnoreCase("CONHOST")).Should().BeTrue($"PING and CONHOST are not in the child processes: {string.Join(",", processes.Select(p => p.ProcessName))}");
}
finally
{
process.Kill(entireProcessTree: true);
process.WaitForExit();
}
}
[RunIfFact(FactOperatingSystem.Windows | FactOperatingSystem.Linux)]
public void GetParentProcessId()
{
var current = Process.GetCurrentProcess();
var parent = current.GetParentProcessId();
parent.Should().NotBeNull();
parent.Should().NotBe(current.Id);
}
[RunIfFact(FactOperatingSystem.Windows)]
public void GetParent()
{
var current = Process.GetCurrentProcess();
var parent = current.GetParentProcess();
var grandParent = parent.GetParentProcess();
grandParent.Should().NotBeNull();
var descendants = grandParent.GetDescendantProcesses();
descendants.Should().Contain(p => p.Id == current.Id, "Descendants must contains current process");
descendants.Should().Contain(p => p.Id == parent.Id, "Descendants must contains parent process");
}
[RunIfFact(FactOperatingSystem.Windows)]
public void KillProcess_EntireProcessTree_False()
{
using var process = Process.Start("cmd.exe", "/C ping 127.0.0.1 -n 10");
try
{
// We need to wait for the process to be started by cmd
IReadOnlyCollection<Process> processes;
while ((processes = process.GetChildProcesses()).Count == 0)
{
Thread.Sleep(100);
continue;
}
(processes.Count == 1 || processes.Count == 2).Should().BeTrue($"There should be 1 or 2 children (ping and conhost): {string.Join(",", processes.Select(p => p.ProcessName))}");
var childProcess = processes.First();
process.Kill(entireProcessTree: false);
childProcess.HasExited.Should().BeFalse();
childProcess.Kill();
childProcess.WaitForExit();
}
finally
{
process.Kill(entireProcessTree: true);
process.WaitForExit();
}
}
[RunIfFact(FactOperatingSystem.Windows)]
public void KillProcess_EntireProcessTree_True()
{
var start = DateTime.UtcNow;
static Process CreateProcess()
{
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
return Process.Start("cmd.exe", "/C ping 127.0.0.1 -n 10");
}
return Process.Start("sh", "-c \"ping 127.0.0.1 -c 10\"");
}
Process GetPingProcess()
{
var processes = Process.GetProcesses();
var pingProcesses = processes.Where(p => p.ProcessName.EqualsIgnoreCase("ping")).ToList();
return pingProcesses.SingleOrDefault(p => p.StartTime >= start.ToLocalTime());
}
using var shellProcess = CreateProcess();
Process pingProcess = null;
try
{
// We need to wait for the process to be started by cmd
while ((pingProcess = GetPingProcess()) == null)
{
// Must be greater than the ping time to prevent other tests from using this ping instance
if (DateTime.UtcNow - start > TimeSpan.FromSeconds(15))
{
var allProcesses = Process.GetProcesses();
false.Should().BeTrue("Cannot find the ping process. Running processes: " + string.Join(", ", allProcesses.Select(p => p.ProcessName)));
}
Thread.Sleep(100);
continue;
}
pingProcess.Should().NotBeNull();
ProcessExtensions.Kill(shellProcess, entireProcessTree: true);
shellProcess.WaitForExit(1000);
shellProcess.HasExited.Should().BeTrue($"Shell process ({shellProcess.Id.ToStringInvariant()}) has not exited");
pingProcess.WaitForExit(1000);
pingProcess.HasExited.Should().BeTrue($"Ping process ({pingProcess.Id.ToStringInvariant()}) has not exited");
}
finally
{
if (pingProcess != null)
{
pingProcess.Kill(entireProcessTree: true);
pingProcess.WaitForExit();
}
shellProcess.Kill(entireProcessTree: true);
shellProcess.WaitForExit();
}
}
}
| |
// 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.Security.Cryptography.X509Certificates;
using System.Security.Cryptography.Xml;
using Test.Cryptography;
using Xunit;
namespace System.Security.Cryptography.Pkcs.Tests
{
public static partial class SignedCmsTests
{
[Fact]
public static void DefaultStateBehavior()
{
SignedCms cms = new SignedCms();
Assert.Equal(0, cms.Version);
Assert.False(cms.Detached, "cms.Detached");
X509Certificate2Collection certificates = cms.Certificates;
X509Certificate2Collection certificates2 = cms.Certificates;
Assert.NotSame(certificates, certificates2);
Assert.Equal(0, certificates.Count);
Assert.Equal(0, certificates2.Count);
ContentInfo content = cms.ContentInfo;
ContentInfo content2 = cms.ContentInfo;
Assert.Same(content, content2);
Assert.Equal("1.2.840.113549.1.7.1", content.ContentType.Value);
Assert.Equal(Array.Empty<byte>(), content.Content);
SignerInfoCollection signers = cms.SignerInfos;
SignerInfoCollection signers2 = cms.SignerInfos;
Assert.NotSame(signers, signers2);
Assert.Equal(0, signers.Count);
Assert.Equal(0, signers2.Count);
Assert.Throws<InvalidOperationException>(() => cms.CheckSignature(true));
Assert.Throws<InvalidOperationException>(() => cms.CheckHash());
Assert.Throws<InvalidOperationException>(() => cms.RemoveSignature(0));
Assert.Throws<InvalidOperationException>(() => cms.RemoveSignature(-1));
Assert.Throws<InvalidOperationException>(() => cms.RemoveSignature(10000));
Assert.Throws<InvalidOperationException>(() => cms.Encode());
}
[Fact]
public static void DecodeNull()
{
SignedCms cms = new SignedCms();
Assert.Throws<ArgumentNullException>(() => cms.Decode(null));
}
[Theory]
[InlineData("Empty", "")]
[InlineData("Not a sequence", "010100")]
[InlineData("Too-long BER length", "3005")]
public static void DecodeInvalid(string description, string inputHex)
{
byte[] inputData = inputHex.HexToByteArray();
SignedCms cms = new SignedCms();
Assert.Throws<CryptographicException>(() => cms.Decode(inputData));
}
[Fact]
public static void Decode_WrongContentType()
{
const string InputHex =
"3080" +
"0609608648016503040201" +
"A080" +
"3002" +
"0500" +
"0000" +
"0000";
byte[] inputData = InputHex.HexToByteArray();
SignedCms cms = new SignedCms();
Assert.Throws<CryptographicException>(() => cms.Decode(inputData));
}
[Fact]
public static void Decode_OverwritesAttachedContentInfo()
{
ContentInfo original = new ContentInfo(new byte [] { 1, 2, 3, 4, 5 });
SignedCms cms = new SignedCms(original, false);
Assert.False(cms.Detached);
cms.Decode(SignedDocuments.RsaPkcs1OneSignerIssuerAndSerialNumber);
Assert.False(cms.Detached);
ContentInfo newInfo = cms.ContentInfo;
ContentInfo newInfo2 = cms.ContentInfo;
Assert.NotSame(original, newInfo);
Assert.Same(newInfo, newInfo2);
Assert.NotEqual(original.Content, newInfo.Content);
}
[Fact]
public static void Decode_PreservesDetachedContentInfo()
{
ContentInfo original = new ContentInfo(new byte[] { 1, 2, 3, 4, 5 });
SignedCms cms = new SignedCms(original, true);
Assert.True(cms.Detached);
cms.Decode(SignedDocuments.RsaPkcs1OneSignerIssuerAndSerialNumber);
Assert.True(cms.Detached);
ContentInfo newInfo = cms.ContentInfo;
ContentInfo newInfo2 = cms.ContentInfo;
Assert.Same(original, newInfo);
Assert.Same(newInfo, newInfo2);
}
[Fact]
public static void SignedCms_SignerInfos_UniquePerCall()
{
SignedCms cms = new SignedCms();
cms.Decode(SignedDocuments.RsaPkcs1OneSignerIssuerAndSerialNumber);
SignerInfoCollection signers = cms.SignerInfos;
SignerInfoCollection signers2 = cms.SignerInfos;
Assert.NotSame(signers, signers2);
Assert.Single(signers);
Assert.Single(signers2);
Assert.NotSame(signers[0], signers2[0]);
Assert.NotSame(signers[0].Certificate, signers2[0].Certificate);
Assert.Equal(signers[0].Certificate, signers2[0].Certificate);
}
[Fact]
public static void SignedCms_Certificates_UniquePerCall()
{
SignedCms cms = new SignedCms();
cms.Decode(SignedDocuments.RsaPssDocument);
X509Certificate2Collection certs = cms.Certificates;
X509Certificate2Collection certs2 = cms.Certificates;
Assert.NotSame(certs, certs2);
Assert.Single(certs);
Assert.Single(certs2);
Assert.NotSame(certs[0], certs2[0]);
Assert.Equal(certs[0], certs2[0]);
}
[Fact]
public static void CheckSignature_ThrowsOnNullStore()
{
SignedCms cms = new SignedCms();
cms.Decode(SignedDocuments.RsaPssDocument);
AssertExtensions.Throws<ArgumentNullException>(
"extraStore",
() => cms.CheckSignature(null, true));
AssertExtensions.Throws<ArgumentNullException>(
"extraStore",
() => cms.CheckSignature(null, false));
}
[Fact]
public static void Ctor_NoContent_Throws()
{
Assert.Throws<ArgumentNullException>(() => new SignedCms(null));
Assert.Throws<ArgumentNullException>(() => new SignedCms(null, false));
Assert.Throws<ArgumentNullException>(() => new SignedCms(null, true));
Assert.Throws<ArgumentNullException>(
() => new SignedCms(SubjectIdentifierType.SubjectKeyIdentifier, null));
Assert.Throws<ArgumentNullException>(
() => new SignedCms(SubjectIdentifierType.SubjectKeyIdentifier, null, false));
Assert.Throws<ArgumentNullException>(
() => new SignedCms(SubjectIdentifierType.SubjectKeyIdentifier, null, true));
}
[Fact]
public static void CheckSignature_ExtraStore_IsAdditional()
{
SignedCms cms = new SignedCms();
cms.Decode(SignedDocuments.RsaPkcs1OneSignerIssuerAndSerialNumber);
// Assert.NotThrows
cms.CheckSignature(true);
// Assert.NotThrows
cms.CheckSignature(new X509Certificate2Collection(), true);
}
[Fact]
public static void Decode_IgnoresExtraData()
{
byte[] basis = SignedDocuments.RsaPkcs1OneSignerIssuerAndSerialNumber;
byte[] data = new byte[basis.Length + 60];
data.AsSpan(basis.Length).Fill(0x5E);
basis.AsSpan().CopyTo(data);
SignedCms cms = new SignedCms();
cms.Decode(data);
// Assert.NotThrows
cms.CheckSignature(true);
byte[] encoded = cms.Encode();
Assert.Equal(basis.Length, encoded.Length);
Assert.Equal(basis.ByteArrayToHex(), encoded.ByteArrayToHex());
}
[Fact]
public static void CheckSignatures_AllRemoved()
{
SignedCms cms = new SignedCms();
cms.Decode(SignedDocuments.RsaPkcs1OneSignerIssuerAndSerialNumber);
Assert.Single(cms.SignerInfos);
cms.RemoveSignature(0);
Assert.Empty(cms.SignerInfos);
Assert.Throws<CryptographicException>(() => cms.CheckSignature(true));
}
[Fact]
public static void CheckHash_AllRemoved()
{
SignedCms cms = new SignedCms();
cms.Decode(SignedDocuments.RsaPkcs1OneSignerIssuerAndSerialNumber);
Assert.Single(cms.SignerInfos);
cms.RemoveSignature(0);
Assert.Empty(cms.SignerInfos);
Assert.Throws<CryptographicException>(() => cms.CheckHash());
}
[Fact]
public static void RemoveSignature_MatchesIssuerAndSerialNumber()
{
SignedCms cms = new SignedCms();
cms.Decode(SignedDocuments.RsaPkcs1OneSignerIssuerAndSerialNumber);
Assert.Single(cms.SignerInfos);
SignerInfo signerInfo = cms.SignerInfos[0];
Assert.Equal(SubjectIdentifierType.IssuerAndSerialNumber, signerInfo.SignerIdentifier.Type);
int certCount = cms.Certificates.Count;
cms.RemoveSignature(signerInfo);
Assert.Empty(cms.SignerInfos);
Assert.Equal(certCount, cms.Certificates.Count);
}
[Fact]
public static void RemoveSignature_MatchesSubjectKeyIdentifier()
{
SignedCms cms = new SignedCms();
cms.Decode(SignedDocuments.RsaPssDocument);
Assert.Single(cms.SignerInfos);
SignerInfo signerInfo = cms.SignerInfos[0];
Assert.Equal(SubjectIdentifierType.SubjectKeyIdentifier, signerInfo.SignerIdentifier.Type);
int certCount = cms.Certificates.Count;
cms.RemoveSignature(signerInfo);
Assert.Empty(cms.SignerInfos);
Assert.Equal(certCount, cms.Certificates.Count);
}
[Fact]
public static void RemoveSignature_MatchesNoSignature()
{
SignedCms cms = new SignedCms();
cms.Decode(SignedDocuments.NoSignatureSignedWithAttributesAndCounterSignature);
Assert.Single(cms.SignerInfos);
SignerInfo signerInfo = cms.SignerInfos[0];
Assert.Equal(SubjectIdentifierType.NoSignature, signerInfo.SignerIdentifier.Type);
cms.RemoveSignature(signerInfo);
Assert.Empty(cms.SignerInfos);
}
[Fact]
public static void RemoveSignature_WithNoMatch()
{
SignedCms cms = new SignedCms();
cms.Decode(SignedDocuments.RsaPkcs1OneSignerIssuerAndSerialNumber);
SignerInfo wrongSignerInfo = cms.SignerInfos[0];
cms.Decode(SignedDocuments.RsaPssDocument);
Assert.Single(cms.SignerInfos);
Assert.Throws<CryptographicException>(() => cms.RemoveSignature(wrongSignerInfo));
Assert.Single(cms.SignerInfos);
Assert.Single(cms.Certificates);
}
[Fact]
public static void RemoveSignature_Null()
{
SignedCms cms = new SignedCms();
cms.Decode(SignedDocuments.RsaPkcs1OneSignerIssuerAndSerialNumber);
AssertExtensions.Throws<ArgumentNullException>(
"signerInfo",
() => cms.RemoveSignature(null));
Assert.Single(cms.SignerInfos);
Assert.Single(cms.Certificates);
}
[Fact]
public static void RemoveSignature_OutOfRange()
{
SignedCms cms = new SignedCms();
cms.Decode(SignedDocuments.RsaPkcs1OneSignerIssuerAndSerialNumber);
ArgumentOutOfRangeException ex = AssertExtensions.Throws<ArgumentOutOfRangeException>(
"index",
() => cms.RemoveSignature(-1));
Assert.Equal(null, ex.ActualValue);
Assert.Single(cms.SignerInfos);
Assert.Single(cms.Certificates);
ex = AssertExtensions.Throws<ArgumentOutOfRangeException>(
"index",
() => cms.RemoveSignature(1));
Assert.Equal(null, ex.ActualValue);
Assert.Single(cms.SignerInfos);
Assert.Single(cms.Certificates);
}
[Fact]
public static void DetachedContent_ConcatEmbeddedContent()
{
// 1: Prove the document works.
SignedCms cms = new SignedCms();
cms.Decode(SignedDocuments.NoSignatureWithNoAttributes);
cms.SignerInfos[0].CheckHash();
ContentInfo save = cms.ContentInfo;
// 2: Using the empty detached content, see that the document still works.
cms = new SignedCms(new ContentInfo(Array.Empty<byte>()), true);
cms.Decode(SignedDocuments.NoSignatureWithNoAttributes);
cms.SignerInfos[0].CheckHash();
//// 3: Using the saved content, prove that the document no longer works.
cms = new SignedCms(save, true);
cms.Decode(SignedDocuments.NoSignatureWithNoAttributes);
Assert.Throws<CryptographicException>(() => cms.SignerInfos[0].CheckHash());
// 4: Modify the contained hash, see that it previously didn't work for the "right" reason.
string inputHex = SignedDocuments.NoSignatureWithNoAttributes.ByteArrayToHex();
inputHex = inputHex.Replace(
// SHA1("Microsoft Corporation")
"A5F085E7F326F3D6CA3BFD6280A3DE8EBC2EA60E",
// SHA1("Microsoft CorporationMicrosoft Corporation")
"346804FD67B37C27A203CD514B267711CFB39118");
cms = new SignedCms(save, true);
cms.Decode(inputHex.HexToByteArray());
cms.SignerInfos[0].CheckHash();
}
[Theory]
[InlineData(SubjectIdentifierType.Unknown)]
[InlineData(SubjectIdentifierType.IssuerAndSerialNumber)]
[InlineData(SubjectIdentifierType.SubjectKeyIdentifier)]
[InlineData((SubjectIdentifierType)76)]
public static void ZeroArgComputeSignature(SubjectIdentifierType identifierType)
{
ContentInfo contentInfo = new ContentInfo(new byte[] { 9, 8, 7, 6, 5 });
SignedCms cms = new SignedCms(identifierType, contentInfo);
Assert.Throws<InvalidOperationException>(() => cms.ComputeSignature());
cms = new SignedCms(identifierType, contentInfo, detached: true);
Assert.Throws<InvalidOperationException>(() => cms.ComputeSignature());
}
[Theory]
[InlineData(false)]
[InlineData(true)]
public static void ZeroArgComputeSignature_NoSignature(bool detached)
{
ContentInfo contentInfo = new ContentInfo(new byte[] { 9, 8, 7, 6, 5 });
SignedCms cms = new SignedCms(SubjectIdentifierType.NoSignature, contentInfo, detached);
if (PlatformDetection.IsFullFramework)
{
Assert.Throws<NullReferenceException>(() => cms.ComputeSignature());
}
else
{
cms.ComputeSignature();
SignerInfoCollection signers = cms.SignerInfos;
Assert.Equal(1, signers.Count);
Assert.Equal(SubjectIdentifierType.NoSignature, signers[0].SignerIdentifier.Type);
cms.CheckHash();
Assert.Throws<CryptographicException>(() => cms.CheckSignature(true));
}
}
[Theory]
[InlineData(SubjectIdentifierType.IssuerAndSerialNumber, false)]
[InlineData(SubjectIdentifierType.IssuerAndSerialNumber, true)]
[InlineData(SubjectIdentifierType.SubjectKeyIdentifier, false)]
[InlineData(SubjectIdentifierType.SubjectKeyIdentifier, true)]
// NoSignature is a different test, because it succeeds (CoreFX) or fails differently (NetFX)
public static void SignSilentWithNoCertificate(SubjectIdentifierType identifierType, bool detached)
{
ContentInfo contentInfo = new ContentInfo(new byte[] { 9, 8, 7, 6, 5 });
SignedCms cms = new SignedCms(contentInfo, detached);
Assert.Throws<InvalidOperationException>(
() => cms.ComputeSignature(new CmsSigner(identifierType), silent: true));
}
[Theory]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework)]
[InlineData(SubjectIdentifierType.IssuerAndSerialNumber, false)]
[InlineData(SubjectIdentifierType.IssuerAndSerialNumber, true)]
[InlineData(SubjectIdentifierType.SubjectKeyIdentifier, false)]
[InlineData(SubjectIdentifierType.SubjectKeyIdentifier, true)]
// NoSignature is a different test, because it succeeds (CoreFX) or fails differently (NetFX)
public static void SignNoisyWithNoCertificate_NotSupported(
SubjectIdentifierType identifierType,
bool detached)
{
ContentInfo contentInfo = new ContentInfo(new byte[] { 9, 8, 7, 6, 5 });
SignedCms cms = new SignedCms(contentInfo, detached);
Assert.Throws<PlatformNotSupportedException>(
() => cms.ComputeSignature(new CmsSigner(identifierType), silent: false));
}
[Theory]
[InlineData(SubjectIdentifierType.IssuerAndSerialNumber, false)]
[InlineData(SubjectIdentifierType.IssuerAndSerialNumber, true)]
[InlineData(SubjectIdentifierType.SubjectKeyIdentifier, false)]
[InlineData(SubjectIdentifierType.SubjectKeyIdentifier, true)]
public static void AddFirstSigner_RSA(SubjectIdentifierType identifierType, bool detached)
{
ContentInfo contentInfo = new ContentInfo(new byte[] { 9, 8, 7, 6, 5 });
SignedCms cms = new SignedCms(contentInfo, detached);
using (X509Certificate2 signerCert = Certificates.RSA2048SignatureOnly.TryGetCertificateWithPrivateKey())
{
CmsSigner signer = new CmsSigner(identifierType, signerCert);
cms.ComputeSignature(signer);
}
Assert.Same(contentInfo.Content, cms.ContentInfo.Content);
Assert.Single(cms.SignerInfos);
Assert.Single(cms.Certificates);
int expectedVersion = identifierType == SubjectIdentifierType.SubjectKeyIdentifier ? 3 : 1;
Assert.Equal(expectedVersion, cms.Version);
SignerInfo firstSigner = cms.SignerInfos[0];
Assert.Equal(identifierType, firstSigner.SignerIdentifier.Type);
Assert.NotNull(firstSigner.Certificate);
Assert.NotSame(cms.Certificates[0], firstSigner.Certificate);
Assert.Equal(cms.Certificates[0], firstSigner.Certificate);
cms.CheckSignature(true);
byte[] encoded = cms.Encode();
cms = new SignedCms();
cms.Decode(encoded);
Assert.Single(cms.SignerInfos);
Assert.Single(cms.Certificates);
Assert.Equal(expectedVersion, cms.Version);
Assert.Equal(identifierType, cms.SignerInfos[0].SignerIdentifier.Type);
Assert.Equal(firstSigner.Certificate, cms.SignerInfos[0].Certificate);
if (detached)
{
Assert.Throws<CryptographicException>(() => cms.CheckSignature(true));
cms = new SignedCms(contentInfo, detached);
cms.Decode(encoded);
}
cms.CheckSignature(true);
}
[Fact]
public static void AddSignerWithNegativeSerial()
{
const string expectedSerial = "FD319CB1514B06AF49E00522277E43C8";
ContentInfo contentInfo = new ContentInfo(new byte[] { 9, 8, 7, 6, 5 });
SignedCms cms = new SignedCms(contentInfo, false);
using (X509Certificate2 cert = Certificates.NegativeSerialNumber.TryGetCertificateWithPrivateKey())
{
Assert.Equal(expectedSerial, cert.SerialNumber);
CmsSigner signer = new CmsSigner(SubjectIdentifierType.IssuerAndSerialNumber, cert);
signer.IncludeOption = X509IncludeOption.EndCertOnly;
cms.ComputeSignature(signer);
}
SignerInfoCollection signers = cms.SignerInfos;
Assert.Equal(1, signers.Count);
SignerInfo signerInfo = signers[0];
Assert.Equal(SubjectIdentifierType.IssuerAndSerialNumber, signerInfo.SignerIdentifier.Type);
X509IssuerSerial issuerSerial = (X509IssuerSerial)signerInfo.SignerIdentifier.Value;
Assert.Equal(expectedSerial, issuerSerial.SerialNumber);
Assert.NotNull(signerInfo.Certificate);
// Assert.NoThrow
cms.CheckSignature(true);
}
[Theory]
[InlineData(SubjectIdentifierType.IssuerAndSerialNumber, false)]
[InlineData(SubjectIdentifierType.IssuerAndSerialNumber, true)]
[ActiveIssue(31977, TargetFrameworkMonikers.Uap)]
public static void AddFirstSigner_DSA(SubjectIdentifierType identifierType, bool detached)
{
ContentInfo contentInfo = new ContentInfo(new byte[] { 9, 8, 7, 6, 5 });
SignedCms cms = new SignedCms(contentInfo, detached);
using (X509Certificate2 signerCert = Certificates.Dsa1024.TryGetCertificateWithPrivateKey())
{
CmsSigner signer = new CmsSigner(identifierType, signerCert);
signer.IncludeOption = X509IncludeOption.EndCertOnly;
// Best compatibility for DSA is SHA-1 (FIPS 186-2)
signer.DigestAlgorithm = new Oid(Oids.Sha1, Oids.Sha1);
cms.ComputeSignature(signer);
}
Assert.Single(cms.SignerInfos);
Assert.Single(cms.Certificates);
int expectedVersion = identifierType == SubjectIdentifierType.SubjectKeyIdentifier ? 3 : 1;
Assert.Equal(expectedVersion, cms.Version);
SignerInfo firstSigner = cms.SignerInfos[0];
Assert.Equal(identifierType, firstSigner.SignerIdentifier.Type);
Assert.NotNull(firstSigner.Certificate);
Assert.NotSame(cms.Certificates[0], firstSigner.Certificate);
Assert.Equal(cms.Certificates[0], firstSigner.Certificate);
#if netcoreapp
byte[] signature = firstSigner.GetSignature();
Assert.NotEmpty(signature);
// DSA PKIX signature format is a DER SEQUENCE.
Assert.Equal(0x30, signature[0]);
#endif
cms.CheckSignature(true);
byte[] encoded = cms.Encode();
cms = new SignedCms();
cms.Decode(encoded);
Assert.Single(cms.SignerInfos);
Assert.Single(cms.Certificates);
Assert.Equal(expectedVersion, cms.Version);
Assert.Equal(identifierType, cms.SignerInfos[0].SignerIdentifier.Type);
Assert.Equal(firstSigner.Certificate, cms.SignerInfos[0].Certificate);
#if netcoreapp
byte[] sig2 = cms.SignerInfos[0].GetSignature();
Assert.Equal(signature, sig2);
#endif
if (detached)
{
Assert.Throws<CryptographicException>(() => cms.CheckSignature(true));
cms = new SignedCms(contentInfo, detached);
cms.Decode(encoded);
}
cms.CheckSignature(true);
}
[Theory]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework)]
[InlineData(SubjectIdentifierType.IssuerAndSerialNumber, false, Oids.Sha256)]
[InlineData(SubjectIdentifierType.IssuerAndSerialNumber, true, Oids.Sha256)]
[InlineData(SubjectIdentifierType.SubjectKeyIdentifier, false, Oids.Sha256)]
[InlineData(SubjectIdentifierType.SubjectKeyIdentifier, true, Oids.Sha256)]
[InlineData(SubjectIdentifierType.IssuerAndSerialNumber, false, Oids.Sha1)]
[InlineData(SubjectIdentifierType.SubjectKeyIdentifier, true, Oids.Sha1)]
[InlineData(SubjectIdentifierType.IssuerAndSerialNumber, true, Oids.Sha384)]
[InlineData(SubjectIdentifierType.SubjectKeyIdentifier, false, Oids.Sha384)]
[InlineData(SubjectIdentifierType.IssuerAndSerialNumber, false, Oids.Sha512)]
[InlineData(SubjectIdentifierType.SubjectKeyIdentifier, true, Oids.Sha512)]
public static void AddFirstSigner_ECDSA(SubjectIdentifierType identifierType, bool detached, string digestOid)
{
ContentInfo contentInfo = new ContentInfo(new byte[] { 9, 8, 7, 6, 5 });
SignedCms cms = new SignedCms(contentInfo, detached);
using (X509Certificate2 signerCert = Certificates.ECDsaP256Win.TryGetCertificateWithPrivateKey())
{
CmsSigner signer = new CmsSigner(identifierType, signerCert);
signer.IncludeOption = X509IncludeOption.EndCertOnly;
signer.DigestAlgorithm = new Oid(digestOid, digestOid);
cms.ComputeSignature(signer);
}
Assert.Single(cms.SignerInfos);
Assert.Single(cms.Certificates);
int expectedVersion = identifierType == SubjectIdentifierType.SubjectKeyIdentifier ? 3 : 1;
Assert.Equal(expectedVersion, cms.Version);
SignerInfo firstSigner = cms.SignerInfos[0];
Assert.Equal(identifierType, firstSigner.SignerIdentifier.Type);
Assert.NotNull(firstSigner.Certificate);
Assert.NotSame(cms.Certificates[0], firstSigner.Certificate);
Assert.Equal(cms.Certificates[0], firstSigner.Certificate);
#if netcoreapp
byte[] signature = firstSigner.GetSignature();
Assert.NotEmpty(signature);
// ECDSA PKIX signature format is a DER SEQUENCE.
Assert.Equal(0x30, signature[0]);
// ECDSA Oids are all under 1.2.840.10045.4.
Assert.StartsWith("1.2.840.10045.4.", firstSigner.SignatureAlgorithm.Value);
#endif
cms.CheckSignature(true);
byte[] encoded = cms.Encode();
cms = new SignedCms();
cms.Decode(encoded);
Assert.Single(cms.SignerInfos);
Assert.Single(cms.Certificates);
Assert.Equal(expectedVersion, cms.Version);
Assert.Equal(identifierType, cms.SignerInfos[0].SignerIdentifier.Type);
Assert.Equal(firstSigner.Certificate, cms.SignerInfos[0].Certificate);
#if netcoreapp
byte[] sig2 = cms.SignerInfos[0].GetSignature();
Assert.Equal(signature, sig2);
#endif
if (detached)
{
Assert.Throws<CryptographicException>(() => cms.CheckSignature(true));
cms = new SignedCms(contentInfo, detached);
cms.Decode(encoded);
}
cms.CheckSignature(true);
}
[Theory]
[InlineData(false, false)]
[InlineData(false, true)]
[InlineData(true, false)]
[InlineData(true, true)]
public static void AddFirstSigner_NoSignature(bool detached, bool includeExtraCert)
{
ContentInfo contentInfo = new ContentInfo(new byte[] { 9, 8, 7, 6, 5 });
SignedCms cms = new SignedCms(contentInfo, detached);
X509Certificate2Collection certs;
// A certificate shouldn't really be required here, but on .NET Framework
// it will encounter throw a NullReferenceException.
using (X509Certificate2 cert = Certificates.RSAKeyTransferCapi1.GetCertificate())
using (X509Certificate2 cert2 = Certificates.DHKeyAgree1.GetCertificate())
{
CmsSigner cmsSigner = new CmsSigner(SubjectIdentifierType.NoSignature, cert);
if (includeExtraCert)
{
cmsSigner.Certificates.Add(cert2);
}
cms.ComputeSignature(cmsSigner);
certs = cms.Certificates;
if (includeExtraCert)
{
Assert.Equal(1, certs.Count);
Assert.Equal(cert2.RawData, certs[0].RawData);
}
else
{
Assert.Equal(0, certs.Count);
}
}
Assert.ThrowsAny<CryptographicException>(() => cms.CheckSignature(true));
cms.CheckHash();
byte[] encoded = cms.Encode();
if (detached)
{
cms = new SignedCms(contentInfo, detached);
}
else
{
cms = new SignedCms();
}
cms.Decode(encoded);
Assert.ThrowsAny<CryptographicException>(() => cms.CheckSignature(true));
cms.CheckHash();
SignerInfoCollection signerInfos = cms.SignerInfos;
Assert.Equal(1, signerInfos.Count);
SignerInfo firstSigner = signerInfos[0];
Assert.ThrowsAny<CryptographicException>(() => firstSigner.CheckSignature(true));
firstSigner.CheckHash();
certs = cms.Certificates;
if (includeExtraCert)
{
Assert.Equal(1, certs.Count);
Assert.Equal("CN=DfHelleKeyAgreement1", certs[0].SubjectName.Name);
}
else
{
Assert.Equal(0, certs.Count);
}
}
[Theory]
[InlineData(false)]
[InlineData(true)]
public static void AddFirstSigner_NoSignature_NoCert(bool detached)
{
ContentInfo contentInfo = new ContentInfo(new byte[] { 9, 8, 7, 6, 5 });
SignedCms cms = new SignedCms(contentInfo, detached);
Action sign = () =>
cms.ComputeSignature(
new CmsSigner(SubjectIdentifierType.NoSignature)
{
IncludeOption = X509IncludeOption.None,
});
if (PlatformDetection.IsFullFramework)
{
Assert.Throws<NullReferenceException>(sign);
}
else
{
sign();
Assert.ThrowsAny<CryptographicException>(() => cms.CheckSignature(true));
cms.CheckHash();
Assert.Equal(1, cms.SignerInfos.Count);
}
}
[Theory]
[InlineData(false)]
[InlineData(true)]
public static void AddSecondSigner_NoSignature(bool detached)
{
ContentInfo contentInfo = new ContentInfo(new byte[] { 9, 8, 7, 6, 5 });
SignedCms cms = new SignedCms(contentInfo, detached);
using (X509Certificate2 cert = Certificates.RSAKeyTransferCapi1.TryGetCertificateWithPrivateKey())
{
cms.ComputeSignature(
new CmsSigner(cert)
{
IncludeOption = X509IncludeOption.None,
});
Assert.Throws<CryptographicException>(
() =>
cms.ComputeSignature(
new CmsSigner(SubjectIdentifierType.NoSignature)
{
IncludeOption = X509IncludeOption.None,
}));
}
Assert.Equal(1, cms.SignerInfos.Count);
Assert.ThrowsAny<CryptographicException>(() => cms.CheckSignature(true));
cms.CheckHash();
}
[Theory]
[InlineData(false)]
[InlineData(true)]
public static void AddSecondSigner_NoSignature_AfterRemove(bool detached)
{
ContentInfo contentInfo = new ContentInfo(new byte[] { 9, 8, 7, 6, 5 });
SignedCms cms = new SignedCms(contentInfo, detached);
using (X509Certificate2 cert = Certificates.RSAKeyTransferCapi1.TryGetCertificateWithPrivateKey())
{
cms.ComputeSignature(
new CmsSigner(cert)
{
IncludeOption = X509IncludeOption.None,
});
Assert.Throws<CryptographicException>(
() =>
cms.ComputeSignature(
new CmsSigner(SubjectIdentifierType.NoSignature)
{
IncludeOption = X509IncludeOption.None,
}));
cms.RemoveSignature(0);
// Because the document was already initialized (when initially signed),
// the "NoSignature must be the first signer" exception is thrown, even
// though there are no signers.
Assert.Throws<CryptographicException>(
() =>
cms.ComputeSignature(
new CmsSigner(SubjectIdentifierType.NoSignature)
{
IncludeOption = X509IncludeOption.None,
}));
}
Assert.Equal(0, cms.SignerInfos.Count);
}
[Theory]
[InlineData(false)]
[InlineData(true)]
public static void AddSecondSigner_NoSignature_LoadUnsigned(bool detached)
{
ContentInfo contentInfo = new ContentInfo(new byte[] { 9, 8, 7, 6, 5 });
SignedCms cms = new SignedCms(contentInfo, detached);
using (X509Certificate2 cert = Certificates.RSAKeyTransferCapi1.TryGetCertificateWithPrivateKey())
{
cms.ComputeSignature(
new CmsSigner(cert)
{
IncludeOption = X509IncludeOption.None,
});
Assert.Throws<CryptographicException>(
() =>
cms.ComputeSignature(
new CmsSigner(SubjectIdentifierType.NoSignature)
{
IncludeOption = X509IncludeOption.None,
}));
cms.RemoveSignature(0);
// Reload the document now that it has no signatures.
byte[] encoded = cms.Encode();
if (detached)
{
cms = new SignedCms(contentInfo, detached);
}
else
{
cms = new SignedCms();
}
cms.Decode(encoded);
// Because the document was already initialized (when loaded),
// the "NoSignature must be the first signer" exception is thrown, even
// though there are no signers.
Assert.Throws<CryptographicException>(
() =>
cms.ComputeSignature(
new CmsSigner(SubjectIdentifierType.NoSignature)
{
IncludeOption = X509IncludeOption.None,
}));
}
Assert.Equal(0, cms.SignerInfos.Count);
}
[Theory]
[InlineData(false, false)]
[InlineData(false, true)]
[InlineData(true, true)]
[InlineData(true, false)]
public static void AddSigner_DuplicateCert_RSA(bool skidFirst, bool detached)
{
ContentInfo contentInfo = new ContentInfo(new byte[] { 9, 8, 7, 6, 5 });
SignedCms cms = new SignedCms(contentInfo, detached);
SubjectIdentifierType first;
SubjectIdentifierType second;
int expectedInitialVersion;
if (skidFirst)
{
first = SubjectIdentifierType.SubjectKeyIdentifier;
second = SubjectIdentifierType.IssuerAndSerialNumber;
expectedInitialVersion = 3;
}
else
{
first = SubjectIdentifierType.IssuerAndSerialNumber;
second = SubjectIdentifierType.SubjectKeyIdentifier;
expectedInitialVersion = 1;
}
byte[] firstEncoding;
using (X509Certificate2 signerCert = Certificates.RSA2048SignatureOnly.TryGetCertificateWithPrivateKey())
{
CmsSigner signer = new CmsSigner(first, signerCert);
cms.ComputeSignature(signer);
Assert.Single(cms.Certificates);
Assert.Single(cms.SignerInfos);
Assert.Equal(expectedInitialVersion, cms.Version);
Assert.Equal(first, cms.SignerInfos[0].SignerIdentifier.Type);
Assert.Equal(expectedInitialVersion, cms.SignerInfos[0].Version);
firstEncoding = cms.Encode();
CmsSigner signer2 = new CmsSigner(second, signerCert);
cms.ComputeSignature(signer2);
}
Assert.Single(cms.Certificates);
Assert.Equal(2, cms.SignerInfos.Count);
// One of them is a V3 signer, so the whole document is V3.
#if netfx
// Windows CMS computes the version on the first signer, and doesn't
// seem to lift it on the second one.
// It encoded the message as
// SignedData.version=1,
// SignedData.SignerInfos[0].version=3
// SignedData.SignerInfos[1].version=1
if (skidFirst)
{
#endif
Assert.Equal(3, cms.Version);
#if netfx
}
#endif
Assert.Equal(first, cms.SignerInfos[0].SignerIdentifier.Type);
Assert.Equal(second, cms.SignerInfos[1].SignerIdentifier.Type);
Assert.Equal(cms.SignerInfos[0].Certificate, cms.SignerInfos[1].Certificate);
cms.CheckSignature(true);
byte[] secondEncoding = cms.Encode();
Assert.True(secondEncoding.Length > firstEncoding.Length);
}
[Fact]
public static void CannotSignEmptyContent()
{
SignedCms cms = new SignedCms();
using (X509Certificate2 cert = Certificates.RSA2048SignatureOnly.TryGetCertificateWithPrivateKey())
{
CmsSigner signer = new CmsSigner(SubjectIdentifierType.IssuerAndSerialNumber, cert);
Assert.Throws<CryptographicException>(() => cms.ComputeSignature(signer));
}
}
[Fact]
public static void EncodeDoesNotPreserveOrder_DecodeDoes()
{
SignedCms cms = new SignedCms();
cms.Decode(SignedDocuments.UnsortedSignerInfos);
// The document here was built by the CounterSigningDerOrder tests,
// then editing the binary to flip the one-counter-signer "yellow"
// into the first position.
Assert.Equal(3, cms.SignerInfos.Count);
// Enough data to prove the order.
Assert.Single(cms.SignerInfos[0].CounterSignerInfos);
Assert.Empty(cms.SignerInfos[1].CounterSignerInfos);
Assert.Empty(cms.SignerInfos[1].SignedAttributes);
Assert.Empty(cms.SignerInfos[2].CounterSignerInfos);
Assert.NotEmpty(cms.SignerInfos[2].SignedAttributes);
cms.Decode(cms.Encode());
// { 0, 1, 2 } => { 1, 2, 0 }
Assert.Empty(cms.SignerInfos[0].CounterSignerInfos);
Assert.Empty(cms.SignerInfos[0].SignedAttributes);
Assert.Empty(cms.SignerInfos[1].CounterSignerInfos);
Assert.NotEmpty(cms.SignerInfos[1].SignedAttributes);
Assert.Single(cms.SignerInfos[2].CounterSignerInfos);
}
[Theory]
[InlineData(false)]
[InlineData(true)]
[ActiveIssue(31977, TargetFrameworkMonikers.Uap)]
public static void EnsureExtraCertsAdded(bool newDocument)
{
SignedCms cms;
if (newDocument)
{
ContentInfo data = new ContentInfo(new byte[] { 1, 2, 3 });
cms = new SignedCms(data, false);
}
else
{
cms = new SignedCms();
cms.Decode(SignedDocuments.OneDsa1024);
}
int preCount = cms.Certificates.Count;
using (X509Certificate2 unrelated1 = Certificates.DHKeyAgree1.GetCertificate())
using (X509Certificate2 unrelated1Copy = Certificates.DHKeyAgree1.GetCertificate())
using (X509Certificate2 unrelated2 = Certificates.RSAKeyTransfer2.GetCertificate())
using (X509Certificate2 unrelated3 = Certificates.RSAKeyTransfer3.GetCertificate())
using (X509Certificate2 signerCert = Certificates.RSAKeyTransferCapi1.TryGetCertificateWithPrivateKey())
{
var signer = new CmsSigner(SubjectIdentifierType.IssuerAndSerialNumber, signerCert);
signer.Certificates.Add(unrelated1);
signer.Certificates.Add(unrelated2);
signer.Certificates.Add(unrelated3);
signer.Certificates.Add(unrelated1Copy);
cms.ComputeSignature(signer);
bool ExpectCopyRemoved =
#if !netfx
true
#else
false
#endif
;
int expectedAddedCount = 4;
if (!ExpectCopyRemoved)
{
expectedAddedCount++;
}
// In .NET Framework adding (document) signers adds certificates at the end
// EXCEPT for the first signer, which triggers an internal Decode(Encode())
// which is only observable if there were multiple certificates.
int u1Idx;
int u1CopyIdx;
int u2Idx;
int u3Idx;
int sIdx;
if (newDocument)
{
// These indicies are manually computable by observing the certificate sizes.
// But they'll be stable unless a cert changes.
u1Idx = 3;
u1CopyIdx = 4;
u2Idx = 0;
u3Idx = 1;
sIdx = 2;
}
else
{
u1Idx = 0;
u1CopyIdx = 3;
u2Idx = 1;
u3Idx = 2;
sIdx = ExpectCopyRemoved ? 3 : 4;
}
X509Certificate2Collection certs = cms.Certificates;
Assert.Equal(preCount + expectedAddedCount, certs.Count);
Assert.Equal(unrelated1, certs[preCount + u1Idx]);
Assert.NotSame(unrelated1, certs[preCount + u1Idx]);
Assert.Equal(unrelated2, certs[preCount + u2Idx]);
Assert.NotSame(unrelated2, certs[preCount + u2Idx]);
Assert.Equal(unrelated3, certs[preCount + u3Idx]);
Assert.NotSame(unrelated3, certs[preCount + u3Idx]);
if (!ExpectCopyRemoved)
{
Assert.Equal(unrelated1, certs[preCount + u1CopyIdx]);
Assert.NotSame(unrelated1, certs[preCount + u1CopyIdx]);
}
Assert.Equal(signerCert, certs[preCount + sIdx]);
Assert.NotSame(signerCert, certs[preCount + sIdx]);
}
cms.CheckSignature(true);
}
[Fact]
public static void UntrustedCertFails_WhenTrustChecked()
{
SignedCms cms = new SignedCms();
cms.Decode(SignedDocuments.RsaPkcs1OneSignerIssuerAndSerialNumber);
// Assert.NoThrow
cms.CheckSignature(true);
Assert.Throws<CryptographicException>(() => cms.CheckSignature(false));
}
[Theory]
[InlineData(false)]
[InlineData(true)]
public static void EnsureDataIsolation_NewDocument(bool detached)
{
byte[] contentBytes = { 9, 8, 7, 6, 5 };
ContentInfo contentInfo = new ContentInfo(contentBytes);
SignedCms cms = new SignedCms(contentInfo, detached);
SubjectIdentifierType firstType = SubjectIdentifierType.IssuerAndSerialNumber;
SubjectIdentifierType secondType = SubjectIdentifierType.SubjectKeyIdentifier;
using (X509Certificate2 signerCert = Certificates.RSA2048SignatureOnly.TryGetCertificateWithPrivateKey())
{
CmsSigner signer = new CmsSigner(firstType, signerCert);
signer.SignedAttributes.Add(new Pkcs9SigningTime());
cms.ComputeSignature(signer);
}
// CheckSignature doesn't read the public mutable data
contentInfo.Content[0] ^= 0xFF;
contentInfo.ContentType.Value = Oids.Pkcs7Hashed;
cms.CheckSignature(true);
using (X509Certificate2 signerCert = Certificates.RSA2048SignatureOnly.TryGetCertificateWithPrivateKey())
{
CmsSigner signer = new CmsSigner(secondType, signerCert);
signer.SignedAttributes.Add(new Pkcs9SigningTime());
// A second ComputeSignature uses the content value from the first one.
cms.ComputeSignature(signer);
}
// They should have the same content digests.
AsnEncodedData firstDigest = cms.SignerInfos[0].SignedAttributes
.OfType<CryptographicAttributeObject>().First(cao => cao.Oid.Value == Oids.MessageDigest).Values[0];
AsnEncodedData secondDigest = cms.SignerInfos[1].SignedAttributes
.OfType<CryptographicAttributeObject>().First(cao => cao.Oid.Value == Oids.MessageDigest).Values[0];
Assert.Equal(firstDigest.RawData.ByteArrayToHex(), secondDigest.RawData.ByteArrayToHex());
byte[] encoded = cms.Encode();
if (detached)
{
cms.Decode(encoded);
// Because Decode leaves ContentInfo alone, and Decode resets the
// "known" content, this will fail due to the tampered content.
Assert.Throws<CryptographicException>(() => cms.CheckSignature(true));
// So put it back.
cms.ContentInfo.Content[0] ^= 0xFF;
}
cms.Decode(encoded);
if (detached)
{
// And break it again.
cms.ContentInfo.Content[0] ^= 0xFF;
}
// Destroy the content that just got decoded.
encoded.AsSpan().Fill(0x55);
cms.CheckSignature(true);
}
[Fact]
public static void SignWithImplicitSubjectKeyIdentifier()
{
byte[] contentBytes = { 9, 8, 7, 6, 5 };
ContentInfo contentInfo = new ContentInfo(contentBytes);
SignedCms cms = new SignedCms(contentInfo, false);
using (X509Certificate2 signerCert = Certificates.RSAKeyTransferCapi1.TryGetCertificateWithPrivateKey())
{
// This cert has no Subject Key Identifier extension.
Assert.Null(signerCert.Extensions[Oids.SubjectKeyIdentifier]);
CmsSigner signer = new CmsSigner(SubjectIdentifierType.SubjectKeyIdentifier, signerCert);
cms.ComputeSignature(signer);
}
Assert.Equal(
"6B4A6B92FDED07EE0119F3674A96D1A70D2A588D",
(string)cms.SignerInfos[0].SignerIdentifier.Value);
// Assert.NoThrow
cms.CheckSignature(true);
}
[Fact]
public static void SignerInfoCollection_Indexer_MinusOne ()
{
SignedCms cms = new SignedCms();
cms.Decode(SignedDocuments.RsaPkcs1OneSignerIssuerAndSerialNumber);
Assert.Throws<ArgumentOutOfRangeException>(() => cms.SignerInfos[-1]);
Assert.Throws<ArgumentOutOfRangeException>(() => cms.SignerInfos[1]);
}
[Theory]
[InlineData(SubjectIdentifierType.IssuerAndSerialNumber)]
[InlineData(SubjectIdentifierType.SubjectKeyIdentifier)]
public static void SignEnveloped(SubjectIdentifierType signerType)
{
using (X509Certificate2 cert = Certificates.RSAKeyTransferCapi1.TryGetCertificateWithPrivateKey())
{
EnvelopedCms envelopedCms = new EnvelopedCms(new ContentInfo(new byte[] { 3 }));
envelopedCms.Encrypt(new CmsRecipient(signerType, cert));
SignedCms signedCms = new SignedCms(
new ContentInfo(new Oid(Oids.Pkcs7Enveloped), envelopedCms.Encode()));
signedCms.ComputeSignature(new CmsSigner(cert));
signedCms.CheckSignature(true);
SignerInfoCollection signers = signedCms.SignerInfos;
Assert.Equal(1, signers.Count);
CryptographicAttributeObjectCollection attrs = signers[0].SignedAttributes;
Assert.Equal(2, attrs.Count);
CryptographicAttributeObject firstAttrSet = attrs[0];
Assert.Equal(Oids.ContentType, firstAttrSet.Oid.Value);
Assert.Equal(1, firstAttrSet.Values.Count);
Assert.Equal(Oids.ContentType, firstAttrSet.Values[0].Oid.Value);
Assert.Equal("06092A864886F70D010703", firstAttrSet.Values[0].RawData.ByteArrayToHex());
CryptographicAttributeObject secondAttrSet = attrs[1];
Assert.Equal(Oids.MessageDigest, secondAttrSet.Oid.Value);
Assert.Equal(1, secondAttrSet.Values.Count);
Assert.Equal(Oids.MessageDigest, secondAttrSet.Values[0].Oid.Value);
}
}
[Theory]
[InlineData(Oids.Pkcs7Data, "0102", false)]
// NetFX PKCS7: The length exceeds the payload, so this fails.
[InlineData("0.0", "0102", true)]
[InlineData("0.0", "04020102", false)]
// NetFX PKCS7: The payload exceeds the length, so this fails.
[InlineData("0.0", "0402010203", true)]
[InlineData("0.0", "010100", false)]
[InlineData(Oids.Pkcs7Hashed, "010100", false)]
[InlineData(Oids.Pkcs7Hashed, "3000", false)]
public static void SignIdentifiedContent(string oidValue, string contentHex, bool netfxProblem)
{
SignedCms signedCms = new SignedCms(
new ContentInfo(new Oid(oidValue, "Some Friendly Name"), contentHex.HexToByteArray()));
using (X509Certificate2 cert = Certificates.RSAKeyTransferCapi1.TryGetCertificateWithPrivateKey())
{
try
{
signedCms.ComputeSignature(new CmsSigner(cert));
}
catch (CryptographicException) when (netfxProblem)
{
// When no signed or unsigned attributes are present and the signer uses
// IssuerAndSerial as the identifier type, NetFx uses an older PKCS7 encoding
// of the current CMS one. The older encoding fails on these inputs because of a
// difference in PKCS7 vs CMS encoding of values using types other than Pkcs7Data.
return;
}
byte[] encoded = signedCms.Encode();
signedCms.Decode(encoded);
}
// Assert.NoThrows
signedCms.CheckSignature(true);
Assert.Equal(oidValue, signedCms.ContentInfo.ContentType.Value);
Assert.Equal(contentHex, signedCms.ContentInfo.Content.ByteArrayToHex());
}
[Fact]
public static void VerifyUnsortedAttributeSignature()
{
SignedCms cms = new SignedCms();
cms.Decode(SignedDocuments.DigiCertTimeStampToken);
// Assert.NoThrows
cms.CheckSignature(true);
}
[Fact]
public static void VerifyUnsortedAttributeSignature_ImportExportImport()
{
SignedCms cms = new SignedCms();
cms.Decode(SignedDocuments.DigiCertTimeStampToken);
// Assert.NoThrows
cms.CheckSignature(true);
byte[] exported = cms.Encode();
cms = new SignedCms();
cms.Decode(exported);
// Assert.NoThrows
cms.CheckSignature(true);
}
[Fact]
public static void AddSignerToUnsortedAttributeSignature()
{
SignedCms cms = new SignedCms();
cms.Decode(SignedDocuments.DigiCertTimeStampToken);
// Assert.NoThrows
cms.CheckSignature(true);
using (X509Certificate2 cert = Certificates.RSAKeyTransferCapi1.TryGetCertificateWithPrivateKey())
{
cms.ComputeSignature(
new CmsSigner(
SubjectIdentifierType.IssuerAndSerialNumber,
cert));
cms.ComputeSignature(
new CmsSigner(
SubjectIdentifierType.SubjectKeyIdentifier,
cert));
}
// Assert.NoThrows
cms.CheckSignature(true);
byte[] exported = cms.Encode();
cms = new SignedCms();
cms.Decode(exported);
// Assert.NoThrows
cms.CheckSignature(true);
}
[Fact]
public static void CheckSignature_Pkcs1_RsaWithSha256()
{
SignedCms signedCms = new SignedCms();
signedCms.Decode(SignedDocuments.RsaPkcs1Sha256WithRsa);
// Assert.NoThrows
signedCms.CheckSignature(true);
}
[Fact]
public static void CheckSignature_Pkcs1_Sha1_Declared_Sha256WithRsa()
{
SignedCms signedCms = new SignedCms();
signedCms.Decode(SignedDocuments.RsaPkcs1SignedSha1DeclaredSha256WithRsa);
Assert.Throws<CryptographicException>(() => {
signedCms.CheckSignature(true);
});
}
[Theory]
[InlineData(null, "0102", Oids.Pkcs7Data)]
[InlineData(null, "010100", Oids.Pkcs7Data)]
[InlineData("potato", "010100", null)]
[InlineData(" 1.1", "010100", null)]
[InlineData("1.1 ", "010100", null)]
[InlineData("1 1", "010100", null)]
public static void SignIdentifiedContent_BadOid(string oidValueIn, string contentHex, string oidValueOut)
{
SignedCms signedCms = new SignedCms(
new ContentInfo(new Oid(oidValueIn, "Some Friendly Name"), contentHex.HexToByteArray()));
using (X509Certificate2 cert = Certificates.RSAKeyTransferCapi1.TryGetCertificateWithPrivateKey())
{
Action signAction = () => signedCms.ComputeSignature(new CmsSigner(cert));
if (oidValueOut == null)
{
Assert.ThrowsAny<CryptographicException>(signAction);
return;
}
signAction();
byte[] encoded = signedCms.Encode();
signedCms.Decode(encoded);
}
// Assert.NoThrows
signedCms.CheckSignature(true);
Assert.Equal(oidValueOut, signedCms.ContentInfo.ContentType.Value);
Assert.Equal(contentHex, signedCms.ContentInfo.Content.ByteArrayToHex());
}
[Fact]
public static void CheckSignedEncrypted_IssuerSerial_FromNetFx()
{
CheckSignedEncrypted(
SignedDocuments.SignedCmsOverEnvelopedCms_IssuerSerial_NetFx,
SubjectIdentifierType.IssuerAndSerialNumber);
}
[Fact]
public static void CheckSignedEncrypted_SKID_FromNetFx()
{
CheckSignedEncrypted(
SignedDocuments.SignedCmsOverEnvelopedCms_SKID_NetFx,
SubjectIdentifierType.SubjectKeyIdentifier);
}
[Fact]
public static void CheckSignedEncrypted_IssuerSerial_FromCoreFx()
{
CheckSignedEncrypted(
SignedDocuments.SignedCmsOverEnvelopedCms_IssuerSerial_CoreFx,
SubjectIdentifierType.IssuerAndSerialNumber);
}
[Fact]
public static void CheckSignedEncrypted_SKID_FromCoreFx()
{
CheckSignedEncrypted(
SignedDocuments.SignedCmsOverEnvelopedCms_SKID_CoreFx,
SubjectIdentifierType.SubjectKeyIdentifier);
}
[Theory]
[InlineData(false)]
[InlineData(true)]
public static void ReadAndWriteDocumentWithIndefiniteLengthContent(bool checkSignature)
{
SignedCms cms = new SignedCms();
cms.Decode(SignedDocuments.IndefiniteLengthContentDocument);
if (checkSignature)
{
cms.CheckSignature(true);
}
cms.Encode();
}
private static void CheckSignedEncrypted(byte[] docBytes, SubjectIdentifierType expectedType)
{
SignedCms signedCms = new SignedCms();
signedCms.Decode(docBytes);
Assert.Equal(Oids.Pkcs7Enveloped, signedCms.ContentInfo.ContentType.Value);
SignerInfoCollection signers = signedCms.SignerInfos;
Assert.Equal(1, signers.Count);
Assert.Equal(expectedType, signers[0].SignerIdentifier.Type);
// Assert.NotThrows
signedCms.CheckSignature(true);
EnvelopedCms envelopedCms = new EnvelopedCms();
envelopedCms.Decode(signedCms.ContentInfo.Content);
using (X509Certificate2 cert = Certificates.RSAKeyTransferCapi1.TryGetCertificateWithPrivateKey())
{
envelopedCms.Decrypt(new X509Certificate2Collection(cert));
}
Assert.Equal("42", envelopedCms.ContentInfo.Content.ByteArrayToHex());
}
[Fact]
public static void CheckNoSignature_FromNetFx()
{
byte[] encoded = (
"30819F06092A864886F70D010702A0819130818E020101310F300D0609608648" +
"0165030402010500301406092A864886F70D010701A007040509080706053162" +
"3060020101301C3017311530130603550403130C44756D6D79205369676E6572" +
"020100300D06096086480165030402010500300C06082B060105050706020500" +
"0420AF5F6F5C5967C377E49193ECA1EE0B98300A171CD3165C9A2410E8FB7C02" +
"8674"
).HexToByteArray();
CheckNoSignature(encoded);
}
[Fact]
public static void CheckNoSignature_FromNetFx_TamperSignatureOid()
{
// CheckNoSignature_FromNetFx with the algorithm identifier changed from
// 1.3.6.1.5.5.7.6.2 to 10.3.6.1.5.5.7.6.10
byte[] encoded = (
"30819F06092A864886F70D010702A0819130818E020101310F300D0609608648" +
"0165030402010500301406092A864886F70D010701A007040509080706053162" +
"3060020101301C3017311530130603550403130C44756D6D79205369676E6572" +
"020100300D06096086480165030402010500300C06082B0601050507060A0500" +
"0420AF5F6F5C5967C377E49193ECA1EE0B98300A171CD3165C9A2410E8FB7C02" +
"8674"
).HexToByteArray();
CheckNoSignature(encoded, badOid: true);
}
[Fact]
public static void CheckNoSignature_FromCoreFx()
{
byte[] encoded = (
"30819906092A864886F70D010702A0818B308188020101310D300B0609608648" +
"016503040201301406092A864886F70D010701A00704050908070605315E305C" +
"020101301C3017311530130603550403130C44756D6D79205369676E65720201" +
"00300B0609608648016503040201300A06082B060105050706020420AF5F6F5C" +
"5967C377E49193ECA1EE0B98300A171CD3165C9A2410E8FB7C028674"
).HexToByteArray();
CheckNoSignature(encoded);
}
[Fact]
public static void CheckNoSignature_FromCoreFx_TamperSignatureOid()
{
// CheckNoSignature_FromCoreFx with the algorithm identifier changed from
// 1.3.6.1.5.5.7.6.2 to 10.3.6.1.5.5.7.6.10
byte[] encoded = (
"30819906092A864886F70D010702A0818B308188020101310D300B0609608648" +
"016503040201301406092A864886F70D010701A00704050908070605315E305C" +
"020101301C3017311530130603550403130C44756D6D79205369676E65720201" +
"00300B0609608648016503040201300A06082B0601050507060A0420AF5F6F5C" +
"5967C377E49193ECA1EE0B98300A171CD3165C9A2410E8FB7C028674"
).HexToByteArray();
CheckNoSignature(encoded, badOid: true);
}
[Fact]
public static void CheckNoSignature_FromCoreFx_TamperIssuerName()
{
// CheckNoSignature_FromCoreFx with the issuer name changed from "Dummy Cert"
// to "Dumny Cert" (m => n / 0x6D => 0x6E)
byte[] encoded = (
"30819906092A864886F70D010702A0818B308188020101310D300B0609608648" +
"016503040201301406092A864886F70D010701A00704050908070605315E305C" +
"020101301C3017311530130603550403130C44756D6E79205369676E65720201" +
"00300B0609608648016503040201300A06082B060105050706020420AF5F6F5C" +
"5967C377E49193ECA1EE0B98300A171CD3165C9A2410E8FB7C028674"
).HexToByteArray();
SignedCms cms = new SignedCms();
cms.Decode(encoded);
SignerInfoCollection signers = cms.SignerInfos;
Assert.Equal(1, signers.Count);
Assert.Equal(SubjectIdentifierType.IssuerAndSerialNumber, signers[0].SignerIdentifier.Type);
Assert.ThrowsAny<CryptographicException>(() => cms.CheckSignature(true));
Assert.ThrowsAny<CryptographicException>(() => signers[0].CheckSignature(true));
// Assert.NoThrow
cms.CheckHash();
signers[0].CheckHash();
}
private static void CheckNoSignature(byte[] encoded, bool badOid=false)
{
SignedCms cms = new SignedCms();
cms.Decode(encoded);
SignerInfoCollection signers = cms.SignerInfos;
Assert.Equal(1, signers.Count);
Assert.Equal(SubjectIdentifierType.NoSignature, signers[0].SignerIdentifier.Type);
Assert.Throws<CryptographicException>(() => cms.CheckSignature(true));
if (badOid)
{
Assert.ThrowsAny<CryptographicException>(() => cms.CheckHash());
}
else
{
// Assert.NoThrow
cms.CheckHash();
}
}
}
}
| |
// Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using NUnit.Framework;
using osu.Framework.Bindables;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Graphics.Shapes;
using osu.Framework.Input;
using osu.Framework.Utils;
using osu.Framework.Timing;
using osu.Game.Beatmaps;
using osu.Game.Beatmaps.ControlPoints;
using osu.Game.Configuration;
using osu.Game.Rulesets;
using osu.Game.Rulesets.Difficulty;
using osu.Game.Rulesets.Mods;
using osu.Game.Rulesets.Objects;
using osu.Game.Rulesets.Objects.Drawables;
using osu.Game.Rulesets.Objects.Types;
using osu.Game.Rulesets.Osu;
using osu.Game.Rulesets.UI;
using osu.Game.Rulesets.UI.Scrolling;
using osuTK;
using osuTK.Graphics;
using JetBrains.Annotations;
namespace osu.Game.Tests.Visual.Gameplay
{
public class TestSceneDrawableScrollingRuleset : OsuTestScene
{
/// <summary>
/// The amount of time visible by the "view window" of the playfield.
/// All hitobjects added through <see cref="createBeatmap"/> are spaced apart by this value, such that for a beat length of 1000,
/// there will be at most 2 hitobjects visible in the "view window".
/// </summary>
private const double time_range = 1000;
private readonly ManualClock testClock = new ManualClock();
private TestDrawableScrollingRuleset drawableRuleset;
[SetUp]
public void Setup() => Schedule(() => testClock.CurrentTime = 0);
[TestCase("pooled")]
[TestCase("non-pooled")]
public void TestHitObjectLifetime(string pooled)
{
var beatmap = createBeatmap(_ => pooled == "pooled" ? new TestPooledHitObject() : new TestHitObject());
beatmap.ControlPointInfo.Add(0, new TimingControlPoint { BeatLength = time_range });
createTest(beatmap);
assertPosition(0, 0f);
assertDead(3);
setTime(3 * time_range);
assertPosition(3, 0f);
assertDead(0);
setTime(0 * time_range);
assertPosition(0, 0f);
assertDead(3);
}
[TestCase("pooled")]
[TestCase("non-pooled")]
public void TestNestedHitObject(string pooled)
{
var beatmap = createBeatmap(i =>
{
var h = pooled == "pooled" ? new TestPooledParentHitObject() : new TestParentHitObject();
h.Duration = 300;
h.ChildTimeOffset = i % 3 * 100;
return h;
});
beatmap.ControlPointInfo.Add(0, new TimingControlPoint { BeatLength = time_range });
createTest(beatmap);
assertPosition(0, 0f);
assertHeight(0);
assertChildPosition(0);
setTime(5 * time_range);
assertPosition(5, 0f);
assertHeight(5);
assertChildPosition(5);
}
[TestCase("pooled")]
[TestCase("non-pooled")]
public void TestLifetimeRecomputedWhenTimeRangeChanges(string pooled)
{
var beatmap = createBeatmap(_ => pooled == "pooled" ? new TestPooledHitObject() : new TestHitObject());
beatmap.ControlPointInfo.Add(0, new TimingControlPoint { BeatLength = time_range });
createTest(beatmap);
assertDead(3);
AddStep("increase time range", () => drawableRuleset.TimeRange.Value = 3 * time_range);
assertPosition(3, 1);
}
[Test]
public void TestRelativeBeatLengthScaleSingleTimingPoint()
{
var beatmap = createBeatmap();
beatmap.ControlPointInfo.Add(0, new TimingControlPoint { BeatLength = time_range / 2 });
createTest(beatmap, d => d.RelativeScaleBeatLengthsOverride = true);
assertPosition(0, 0f);
// The single timing point is 1x speed relative to itself, such that the hitobject occurring time_range milliseconds later should appear
// at the bottom of the view window regardless of the timing point's beat length
assertPosition(1, 1f);
}
[Test]
public void TestRelativeBeatLengthScaleTimingPointBeyondEndDoesNotBecomeDominant()
{
var beatmap = createBeatmap();
beatmap.ControlPointInfo.Add(0, new TimingControlPoint { BeatLength = time_range / 2 });
beatmap.ControlPointInfo.Add(12000, new TimingControlPoint { BeatLength = time_range });
beatmap.ControlPointInfo.Add(100000, new TimingControlPoint { BeatLength = time_range });
createTest(beatmap, d => d.RelativeScaleBeatLengthsOverride = true);
assertPosition(0, 0f);
assertPosition(1, 1f);
}
[Test]
public void TestRelativeBeatLengthScaleFromSecondTimingPoint()
{
var beatmap = createBeatmap();
beatmap.ControlPointInfo.Add(0, new TimingControlPoint { BeatLength = time_range });
beatmap.ControlPointInfo.Add(3 * time_range, new TimingControlPoint { BeatLength = time_range / 2 });
createTest(beatmap, d => d.RelativeScaleBeatLengthsOverride = true);
// The first timing point should have a relative velocity of 2
assertPosition(0, 0f);
assertPosition(1, 0.5f);
assertPosition(2, 1f);
// Move to the second timing point
setTime(3 * time_range);
assertPosition(3, 0f);
// As above, this is the timing point that is 1x speed relative to itself, so the hitobject occurring time_range milliseconds later should be at the bottom of the view window
assertPosition(4, 1f);
}
[Test]
public void TestNonRelativeScale()
{
var beatmap = createBeatmap();
beatmap.ControlPointInfo.Add(0, new TimingControlPoint { BeatLength = time_range });
beatmap.ControlPointInfo.Add(3 * time_range, new TimingControlPoint { BeatLength = time_range / 2 });
createTest(beatmap);
assertPosition(0, 0f);
assertPosition(1, 1);
// Move to the second timing point
setTime(3 * time_range);
assertPosition(3, 0f);
// For a beat length of 500, the view window of this timing point is elongated 2x (1000 / 500), such that the second hitobject is two TimeRanges away (offscreen)
// To bring it on-screen, half TimeRange is added to the current time, bringing the second half of the view window into view, and the hitobject should appear at the bottom
setTime(3 * time_range + time_range / 2);
assertPosition(4, 1f);
}
[Test]
public void TestSliderMultiplierDoesNotAffectRelativeBeatLength()
{
var beatmap = createBeatmap();
beatmap.ControlPointInfo.Add(0, new TimingControlPoint { BeatLength = time_range });
beatmap.BeatmapInfo.BaseDifficulty.SliderMultiplier = 2;
createTest(beatmap, d => d.RelativeScaleBeatLengthsOverride = true);
AddStep("adjust time range", () => drawableRuleset.TimeRange.Value = 5000);
for (int i = 0; i < 5; i++)
assertPosition(i, i / 5f);
}
[Test]
public void TestSliderMultiplierAffectsNonRelativeBeatLength()
{
var beatmap = createBeatmap();
beatmap.ControlPointInfo.Add(0, new TimingControlPoint { BeatLength = time_range });
beatmap.BeatmapInfo.BaseDifficulty.SliderMultiplier = 2;
createTest(beatmap);
AddStep("adjust time range", () => drawableRuleset.TimeRange.Value = 2000);
assertPosition(0, 0);
assertPosition(1, 1);
}
/// <summary>
/// Get a <see cref="DrawableTestHitObject" /> corresponding to the <paramref name="index"/>'th <see cref="TestHitObject"/>.
/// When the hit object is not alive, `null` is returned.
/// </summary>
[CanBeNull]
private DrawableTestHitObject getDrawableHitObject(int index)
{
var hitObject = drawableRuleset.Beatmap.HitObjects.ElementAt(index);
return (DrawableTestHitObject)drawableRuleset.Playfield.HitObjectContainer.AliveObjects.FirstOrDefault(obj => obj.HitObject == hitObject);
}
private float yScale => drawableRuleset.Playfield.HitObjectContainer.DrawHeight;
private void assertDead(int index) => AddAssert($"hitobject {index} is dead", () => getDrawableHitObject(index) == null);
private void assertHeight(int index) => AddAssert($"hitobject {index} height", () =>
{
var d = getDrawableHitObject(index);
return d != null && Precision.AlmostEquals(d.DrawHeight, yScale * (float)(d.HitObject.Duration / time_range), 0.1f);
});
private void assertChildPosition(int index) => AddAssert($"hitobject {index} child position", () =>
{
var d = getDrawableHitObject(index);
return d is DrawableTestParentHitObject && Precision.AlmostEquals(
d.NestedHitObjects.First().DrawPosition.Y,
yScale * (float)((TestParentHitObject)d.HitObject).ChildTimeOffset / time_range, 0.1f);
});
private void assertPosition(int index, float relativeY) => AddAssert($"hitobject {index} at {relativeY}",
() => Precision.AlmostEquals(getDrawableHitObject(index)?.DrawPosition.Y ?? -1, yScale * relativeY));
private void setTime(double time)
{
AddStep($"set time = {time}", () => testClock.CurrentTime = time);
}
/// <summary>
/// Creates an <see cref="IBeatmap"/>, containing 10 hitobjects and user-provided timing points.
/// The hitobjects are spaced <see cref="time_range"/> milliseconds apart.
/// </summary>
/// <returns>The <see cref="IBeatmap"/>.</returns>
private IBeatmap createBeatmap(Func<int, TestHitObject> createAction = null)
{
var beatmap = new Beatmap<TestHitObject> { BeatmapInfo = { Ruleset = new OsuRuleset().RulesetInfo } };
for (int i = 0; i < 10; i++)
{
var h = createAction?.Invoke(i) ?? new TestHitObject();
h.StartTime = i * time_range;
beatmap.HitObjects.Add(h);
}
return beatmap;
}
private void createTest(IBeatmap beatmap, Action<TestDrawableScrollingRuleset> overrideAction = null) => AddStep("create test", () =>
{
var ruleset = new TestScrollingRuleset();
drawableRuleset = (TestDrawableScrollingRuleset)ruleset.CreateDrawableRulesetWith(CreateWorkingBeatmap(beatmap).GetPlayableBeatmap(ruleset.RulesetInfo));
drawableRuleset.FrameStablePlayback = false;
overrideAction?.Invoke(drawableRuleset);
Child = new Container
{
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
RelativeSizeAxes = Axes.Y,
Height = 0.75f,
Width = 400,
Masking = true,
Clock = new FramedClock(testClock),
Child = drawableRuleset
};
});
#region Ruleset
private class TestScrollingRuleset : Ruleset
{
public override IEnumerable<Mod> GetModsFor(ModType type) => throw new NotImplementedException();
public override DrawableRuleset CreateDrawableRulesetWith(IBeatmap beatmap, IReadOnlyList<Mod> mods = null) => new TestDrawableScrollingRuleset(this, beatmap, mods);
public override IBeatmapConverter CreateBeatmapConverter(IBeatmap beatmap) => new TestBeatmapConverter(beatmap, null);
public override DifficultyCalculator CreateDifficultyCalculator(WorkingBeatmap beatmap) => throw new NotImplementedException();
public override string Description { get; } = string.Empty;
public override string ShortName { get; } = string.Empty;
}
private class TestDrawableScrollingRuleset : DrawableScrollingRuleset<TestHitObject>
{
public bool RelativeScaleBeatLengthsOverride { get; set; }
protected override bool RelativeScaleBeatLengths => RelativeScaleBeatLengthsOverride;
protected override ScrollVisualisationMethod VisualisationMethod => ScrollVisualisationMethod.Overlapping;
public new Bindable<double> TimeRange => base.TimeRange;
public TestDrawableScrollingRuleset(Ruleset ruleset, IBeatmap beatmap, IReadOnlyList<Mod> mods = null)
: base(ruleset, beatmap, mods)
{
TimeRange.Value = time_range;
}
public override DrawableHitObject<TestHitObject> CreateDrawableRepresentation(TestHitObject h)
{
switch (h)
{
case TestPooledHitObject _:
case TestPooledParentHitObject _:
return null;
case TestParentHitObject p:
return new DrawableTestParentHitObject(p);
default:
return new DrawableTestHitObject(h);
}
}
protected override PassThroughInputManager CreateInputManager() => new PassThroughInputManager();
protected override Playfield CreatePlayfield() => new TestPlayfield();
}
private class TestPlayfield : ScrollingPlayfield
{
public TestPlayfield()
{
AddInternal(new Container
{
RelativeSizeAxes = Axes.Both,
Children = new Drawable[]
{
new Box
{
RelativeSizeAxes = Axes.Both,
Alpha = 0.2f,
},
new Container
{
RelativeSizeAxes = Axes.Both,
Padding = new MarginPadding { Top = 150 },
Children = new Drawable[]
{
new Box
{
Anchor = Anchor.TopCentre,
Origin = Anchor.Centre,
RelativeSizeAxes = Axes.X,
Height = 2,
Colour = Color4.Green
},
HitObjectContainer
}
}
}
});
RegisterPool<TestPooledHitObject, DrawableTestPooledHitObject>(1);
RegisterPool<TestPooledParentHitObject, DrawableTestPooledParentHitObject>(1);
}
}
private class TestBeatmapConverter : BeatmapConverter<TestHitObject>
{
public TestBeatmapConverter(IBeatmap beatmap, Ruleset ruleset)
: base(beatmap, ruleset)
{
}
public override bool CanConvert() => true;
protected override IEnumerable<TestHitObject> ConvertHitObject(HitObject original, IBeatmap beatmap, CancellationToken cancellationToken) =>
throw new NotImplementedException();
}
#endregion
#region HitObject
private class TestHitObject : HitObject, IHasDuration
{
public double EndTime => StartTime + Duration;
public double Duration { get; set; } = 100;
}
private class TestPooledHitObject : TestHitObject
{
}
private class TestParentHitObject : TestHitObject
{
public double ChildTimeOffset;
protected override void CreateNestedHitObjects(CancellationToken cancellationToken)
{
AddNested(new TestHitObject { StartTime = StartTime + ChildTimeOffset });
}
}
private class TestPooledParentHitObject : TestParentHitObject
{
protected override void CreateNestedHitObjects(CancellationToken cancellationToken)
{
AddNested(new TestPooledHitObject { StartTime = StartTime + ChildTimeOffset });
}
}
private class DrawableTestHitObject : DrawableHitObject<TestHitObject>
{
public DrawableTestHitObject([CanBeNull] TestHitObject hitObject)
: base(hitObject)
{
Anchor = Anchor.TopCentre;
Origin = Anchor.TopCentre;
Size = new Vector2(100, 25);
AddRangeInternal(new Drawable[]
{
new Box
{
RelativeSizeAxes = Axes.Both,
Colour = Color4.LightPink
},
new Box
{
Origin = Anchor.CentreLeft,
RelativeSizeAxes = Axes.X,
Height = 2,
Colour = Color4.Red
}
});
}
protected override void Update() => LifetimeEnd = HitObject.EndTime;
}
private class DrawableTestPooledHitObject : DrawableTestHitObject
{
public DrawableTestPooledHitObject()
: base(null)
{
InternalChildren[0].Colour = Color4.LightSkyBlue;
InternalChildren[1].Colour = Color4.Blue;
}
}
private class DrawableTestParentHitObject : DrawableTestHitObject
{
private readonly Container<DrawableHitObject> container;
public DrawableTestParentHitObject([CanBeNull] TestHitObject hitObject)
: base(hitObject)
{
InternalChildren[0].Colour = Color4.LightYellow;
InternalChildren[1].Colour = Color4.Yellow;
AddInternal(container = new Container<DrawableHitObject>
{
RelativeSizeAxes = Axes.Both,
});
}
protected override DrawableHitObject CreateNestedHitObject(HitObject hitObject) =>
new DrawableTestHitObject((TestHitObject)hitObject);
protected override void AddNestedHitObject(DrawableHitObject hitObject) => container.Add(hitObject);
protected override void ClearNestedHitObjects() => container.Clear(false);
}
private class DrawableTestPooledParentHitObject : DrawableTestParentHitObject
{
public DrawableTestPooledParentHitObject()
: base(null)
{
InternalChildren[0].Colour = Color4.LightSeaGreen;
InternalChildren[1].Colour = Color4.Green;
}
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reactive.Linq;
using System.Threading.Tasks;
using FluentAssertions;
using NSubstitute;
using Toggl.Core.Interactors;
using Toggl.Core.Interactors.Suggestions;
using Toggl.Core.Models.Interfaces;
using Toggl.Core.Suggestions;
using Toggl.Core.Tests.Generators;
using Toggl.Core.Tests.Mocks;
using Xunit;
namespace Toggl.Core.Tests.Interactors.Suggestions
{
public sealed class GetSuggestionsInteractorTests
{
public sealed class TheConstructor : BaseInteractorTests
{
[Xunit.Theory, LogIfTooSlow]
[ConstructorData]
public void ThrowsIfAnyOfTheArgumentsIsNull(bool useInteractorFactory)
{
Action createInstance = () => new GetSuggestionsInteractor(
3,
useInteractorFactory ? InteractorFactory : null);
createInstance.Should().Throw<ArgumentNullException>();
}
[Xunit.Theory, LogIfTooSlow]
[InlineData(0)]
[InlineData(-1)]
[InlineData(10)]
[InlineData(-100)]
[InlineData(256)]
public void ThrowsIfTheCountIsOutOfRange(int count)
{
Action createInstance = () => new GetSuggestionsInteractor(
count,
InteractorFactory);
createInstance.Should().Throw<ArgumentException>();
}
}
public sealed class TheExecuteMethod : BaseInteractorTests
{
private IObservable<IEnumerable<IThreadSafeTimeEntry>> validTimeEntries =
Observable.Return(Enumerable.Range(0, 5).Select(i => new MockTimeEntry { Id = i }));
[Fact, LogIfTooSlow]
public async Task ReturnsSuggestionsWithoutDuplicates()
{
var randomProvider = makeProvider(new List<Suggestion>
{
makeSuggestion("same description", 12, SuggestionProviderType.MostUsedTimeEntries)
});
var suggestionProvidersObservable = Observable.Return(new List<ISuggestionProvider>
{
randomProvider,
randomProvider,
randomProvider
});
var interactorFactory = Substitute.For<IInteractorFactory>();
interactorFactory.GetSuggestionProviders(3).Execute()
.Returns(suggestionProvidersObservable);
interactorFactory.GetAllTimeEntriesVisibleToTheUser().Execute()
.Returns(validTimeEntries);
var interactor = new GetSuggestionsInteractor(3, interactorFactory);
var suggestions = await interactor.Execute();
suggestions.Should().HaveCount(1);
}
[Fact, LogIfTooSlow]
public async Task ReturnsSuggestionsWithoutRemoveingNonDuplicates()
{
var randomProvider1 = makeProvider(new List<Suggestion>
{
makeSuggestion("1 description", 11, SuggestionProviderType.RandomForest)
});
var randomProvider2 = makeProvider(new List<Suggestion>
{
makeSuggestion("2 description", 12, SuggestionProviderType.MostUsedTimeEntries)
});
var randomProvider3 = makeProvider(new List<Suggestion>
{
makeSuggestion("3 description", 13, SuggestionProviderType.Calendar)
});
var suggestionProvidersObservable = Observable.Return(new List<ISuggestionProvider>
{
randomProvider1,
randomProvider2,
randomProvider3
});
var interactorFactory = Substitute.For<IInteractorFactory>();
interactorFactory.GetSuggestionProviders(3).Execute()
.Returns(suggestionProvidersObservable);
interactorFactory.GetAllTimeEntriesVisibleToTheUser().Execute()
.Returns(validTimeEntries);
var interactor = new GetSuggestionsInteractor(3, interactorFactory);
var suggestions = await interactor.Execute();
suggestions.Should().HaveCount(3);
}
[Xunit.Theory, LogIfTooSlow]
[InlineData(3, 3)]
[InlineData(2, 1)]
[InlineData(5, 1)]
[InlineData(1, 5)]
public async Task ReturnsSuggestionsWithCountEqualOrLessThanRequested(int numberOfProviders, int numberofSuggestionsPerProvider)
{
var suggestionProvidersObservable = Observable.Return(makeCombinationProvidersAndSuggestions(numberOfProviders, numberofSuggestionsPerProvider));
var interactorFactory = Substitute.For<IInteractorFactory>();
interactorFactory.GetSuggestionProviders(3).Execute()
.Returns(suggestionProvidersObservable);
interactorFactory.GetAllTimeEntriesVisibleToTheUser().Execute()
.Returns(validTimeEntries);
var interactor = new GetSuggestionsInteractor(3, interactorFactory);
var suggestions = await interactor.Execute();
suggestions.Should().HaveCountLessOrEqualTo(3);
}
[Fact, LogIfTooSlow]
public async Task ReturnsNothingWhenTheresLessThan5TimeEntries()
{
var randomProvider = makeProvider(new List<Suggestion>
{
makeSuggestion("same description", 12, SuggestionProviderType.MostUsedTimeEntries)
});
var suggestionProvidersObservable = Observable.Return(new List<ISuggestionProvider>
{
randomProvider,
randomProvider,
randomProvider
});
var interactorFactory = Substitute.For<IInteractorFactory>();
interactorFactory.GetSuggestionProviders(3).Execute()
.Returns(suggestionProvidersObservable);
interactorFactory.GetAllTimeEntriesVisibleToTheUser().Execute()
.Returns(Observable.Return(Enumerable.Empty<IThreadSafeTimeEntry>()));
var interactor = new GetSuggestionsInteractor(3, interactorFactory);
var suggestions = await interactor.Execute();
suggestions.Should().HaveCount(0);
}
private Suggestion makeSuggestion(string description, long? projectId, SuggestionProviderType type)
=> new Suggestion(new MockTimeEntry
{
Description = description,
ProjectId = projectId
}, type);
private ISuggestionProvider makeProvider(List<Suggestion> suggestions)
{
var provider = Substitute.For<ISuggestionProvider>();
provider.GetSuggestions().Returns(suggestions.ToObservable());
return provider;
}
private List<ISuggestionProvider> makeCombinationProvidersAndSuggestions(int numberOfProviders, int numberofSuggestionsPerProvider)
{
var providers = new List<ISuggestionProvider>();
for (int i = 0; i < numberOfProviders; i++)
{
var suggestions = new List<Suggestion>();
for (int j = 0; j < numberofSuggestionsPerProvider; j++)
{
suggestions.Add(makeSuggestion($"{i}{j}", i * 1000 + j, SuggestionProviderType.MostUsedTimeEntries));
}
providers.Add(makeProvider(suggestions));
}
return providers;
}
}
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="Keys.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
namespace System.Windows.Forms {
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System;
using System.Drawing;
using System.ComponentModel;
using System.Windows.Forms;
using System.Drawing.Design;
using Microsoft.Win32;
/// <include file='doc\Keys.uex' path='docs/doc[@for="Keys"]/*' />
/// <devdoc>
/// <para>
/// Specifies key codes and modifiers.
/// </para>
/// </devdoc>
[
Flags,
TypeConverterAttribute(typeof(KeysConverter)),
Editor("System.Windows.Forms.Design.ShortcutKeysEditor, " + AssemblyRef.SystemDesign, typeof(UITypeEditor))
]
[System.Runtime.InteropServices.ComVisible(true)]
[
SuppressMessage("Microsoft.Usage", "CA2217:DoNotMarkEnumsWithFlags") // Certain memberd of Keys enum are actually meant to be OR'ed.
]
public enum Keys {
/// <include file='doc\Keys.uex' path='docs/doc[@for="Keys.KeyCode"]/*' />
/// <devdoc>
/// <para>
/// The bit mask to extract a key code from a key value.
///
/// </para>
/// </devdoc>
KeyCode = 0x0000FFFF,
/// <include file='doc\Keys.uex' path='docs/doc[@for="Keys.Modifiers"]/*' />
/// <devdoc>
/// <para>
/// The bit mask to extract modifiers from a key value.
///
/// </para>
/// </devdoc>
Modifiers = unchecked((int)0xFFFF0000),
/// <include file='doc\Keys.uex' path='docs/doc[@for="Keys.None"]/*' />
/// <devdoc>
/// <para>
/// No key pressed.
/// </para>
/// </devdoc>
None = 0x00,
/// <include file='doc\Keys.uex' path='docs/doc[@for="Keys.LButton"]/*' />
/// <devdoc>
/// <para>
/// The left mouse button.
///
/// </para>
/// </devdoc>
LButton = 0x01,
/// <include file='doc\Keys.uex' path='docs/doc[@for="Keys.RButton"]/*' />
/// <devdoc>
/// <para>
/// The right mouse button.
/// </para>
/// </devdoc>
RButton = 0x02,
/// <include file='doc\Keys.uex' path='docs/doc[@for="Keys.Cancel"]/*' />
/// <devdoc>
/// <para>
/// The CANCEL key.
/// </para>
/// </devdoc>
Cancel = 0x03,
/// <include file='doc\Keys.uex' path='docs/doc[@for="Keys.MButton"]/*' />
/// <devdoc>
/// <para>
/// The middle mouse button (three-button mouse).
/// </para>
/// </devdoc>
MButton = 0x04,
/// <include file='doc\Keys.uex' path='docs/doc[@for="Keys.XButton1"]/*' />
/// <devdoc>
/// <para>
/// The first x mouse button (five-button mouse).
/// </para>
/// </devdoc>
XButton1 = 0x05,
/// <include file='doc\Keys.uex' path='docs/doc[@for="Keys.XButton2"]/*' />
/// <devdoc>
/// <para>
/// The second x mouse button (five-button mouse).
/// </para>
/// </devdoc>
XButton2 = 0x06,
/// <include file='doc\Keys.uex' path='docs/doc[@for="Keys.Back"]/*' />
/// <devdoc>
/// <para>
/// The BACKSPACE key.
/// </para>
/// </devdoc>
Back = 0x08,
/// <include file='doc\Keys.uex' path='docs/doc[@for="Keys.Tab"]/*' />
/// <devdoc>
/// <para>
/// The TAB key.
/// </para>
/// </devdoc>
Tab = 0x09,
/// <include file='doc\Keys.uex' path='docs/doc[@for="Keys.LineFeed"]/*' />
/// <devdoc>
/// <para>
/// The CLEAR key.
/// </para>
/// </devdoc>
LineFeed = 0x0A,
/// <include file='doc\Keys.uex' path='docs/doc[@for="Keys.Clear"]/*' />
/// <devdoc>
/// <para>
/// The CLEAR key.
/// </para>
/// </devdoc>
Clear = 0x0C,
/// <include file='doc\Keys.uex' path='docs/doc[@for="Keys.Return"]/*' />
/// <devdoc>
/// <para>
/// The RETURN key.
///
/// </para>
/// </devdoc>
Return = 0x0D,
/// <include file='doc\Keys.uex' path='docs/doc[@for="Keys.Enter"]/*' />
/// <devdoc>
/// <para>
/// The ENTER key.
///
/// </para>
/// </devdoc>
Enter = Return,
/// <include file='doc\Keys.uex' path='docs/doc[@for="Keys.ShiftKey"]/*' />
/// <devdoc>
/// <para>
/// The SHIFT key.
/// </para>
/// </devdoc>
ShiftKey = 0x10,
/// <include file='doc\Keys.uex' path='docs/doc[@for="Keys.ControlKey"]/*' />
/// <devdoc>
/// <para>
/// The CTRL key.
/// </para>
/// </devdoc>
ControlKey = 0x11,
/// <include file='doc\Keys.uex' path='docs/doc[@for="Keys.Menu"]/*' />
/// <devdoc>
/// <para>
/// The ALT key.
/// </para>
/// </devdoc>
Menu = 0x12,
/// <include file='doc\Keys.uex' path='docs/doc[@for="Keys.Pause"]/*' />
/// <devdoc>
/// <para>
/// The PAUSE key.
/// </para>
/// </devdoc>
Pause = 0x13,
/// <include file='doc\Keys.uex' path='docs/doc[@for="Keys.Capital"]/*' />
/// <devdoc>
/// <para>
/// The CAPS LOCK key.
///
/// </para>
/// </devdoc>
Capital = 0x14,
/// <include file='doc\Keys.uex' path='docs/doc[@for="Keys.CapsLock"]/*' />
/// <devdoc>
/// <para>
/// The CAPS LOCK key.
/// </para>
/// </devdoc>
CapsLock = 0x14,
/// <include file='doc\Keys.uex' path='docs/doc[@for="Keys.Kana"]/*' />
/// <devdoc>
/// <para>
/// The IME Kana mode key.
/// </para>
/// </devdoc>
KanaMode = 0x15,
/// <include file='doc\Keys.uex' path='docs/doc[@for="Keys.HanguelMode"]/*' />
/// <devdoc>
/// <para>
/// The IME Hanguel mode key.
/// </para>
/// </devdoc>
HanguelMode = 0x15,
/// <include file='doc\Keys.uex' path='docs/doc[@for="Keys.HangulMode"]/*' />
/// <devdoc>
/// <para>
/// The IME Hangul mode key.
/// </para>
/// </devdoc>
HangulMode = 0x15,
/// <include file='doc\Keys.uex' path='docs/doc[@for="Keys.JunjaMode"]/*' />
/// <devdoc>
/// <para>
/// The IME Junja mode key.
/// </para>
/// </devdoc>
JunjaMode = 0x17,
/// <include file='doc\Keys.uex' path='docs/doc[@for="Keys.FinalMode"]/*' />
/// <devdoc>
/// <para>
/// The IME Final mode key.
/// </para>
/// </devdoc>
FinalMode = 0x18,
/// <include file='doc\Keys.uex' path='docs/doc[@for="Keys.HanjaMode"]/*' />
/// <devdoc>
/// <para>
/// The IME Hanja mode key.
/// </para>
/// </devdoc>
HanjaMode = 0x19,
/// <include file='doc\Keys.uex' path='docs/doc[@for="Keys.KanjiMode"]/*' />
/// <devdoc>
/// <para>
/// The IME Kanji mode key.
/// </para>
/// </devdoc>
KanjiMode = 0x19,
/// <include file='doc\Keys.uex' path='docs/doc[@for="Keys.Escape"]/*' />
/// <devdoc>
/// <para>
/// The ESC key.
/// </para>
/// </devdoc>
Escape = 0x1B,
/// <include file='doc\Keys.uex' path='docs/doc[@for="Keys.IMEConvert"]/*' />
/// <devdoc>
/// <para>
/// The IME Convert key.
/// </para>
/// </devdoc>
IMEConvert = 0x1C,
/// <include file='doc\Keys.uex' path='docs/doc[@for="Keys.IMENonconvert"]/*' />
/// <devdoc>
/// <para>
/// The IME NonConvert key.
/// </para>
/// </devdoc>
IMENonconvert = 0x1D,
/// <include file='doc\Keys.uex' path='docs/doc[@for="Keys.IMEAccept"]/*' />
/// <devdoc>
/// <para>
/// The IME Accept key.
/// </para>
/// </devdoc>
IMEAccept = 0x1E,
/// <include file='doc\Keys.uex' path='docs/doc[@for="Keys.IMEAceept"]/*' />
/// <devdoc>
/// <para>
/// The IME Accept key.
/// </para>
/// </devdoc>
IMEAceept = IMEAccept,
/// <include file='doc\Keys.uex' path='docs/doc[@for="Keys.IMEModeChange"]/*' />
/// <devdoc>
/// <para>
/// The IME Mode change request.
/// </para>
/// </devdoc>
IMEModeChange = 0x1F,
/// <include file='doc\Keys.uex' path='docs/doc[@for="Keys.Space"]/*' />
/// <devdoc>
/// <para>
/// The SPACEBAR key.
/// </para>
/// </devdoc>
Space = 0x20,
/// <include file='doc\Keys.uex' path='docs/doc[@for="Keys.Prior"]/*' />
/// <devdoc>
/// <para>
/// The PAGE UP key.
/// </para>
/// </devdoc>
Prior = 0x21,
/// <include file='doc\Keys.uex' path='docs/doc[@for="Keys.PageUp"]/*' />
/// <devdoc>
/// <para>
/// The PAGE UP key.
/// </para>
/// </devdoc>
PageUp = Prior,
/// <include file='doc\Keys.uex' path='docs/doc[@for="Keys.Next"]/*' />
/// <devdoc>
/// <para>
/// The PAGE DOWN key.
/// </para>
/// </devdoc>
Next = 0x22,
/// <include file='doc\Keys.uex' path='docs/doc[@for="Keys.PageDown"]/*' />
/// <devdoc>
/// <para>
/// The PAGE DOWN key.
/// </para>
/// </devdoc>
PageDown = Next,
/// <include file='doc\Keys.uex' path='docs/doc[@for="Keys.End"]/*' />
/// <devdoc>
/// <para>
/// The END key.
/// </para>
/// </devdoc>
End = 0x23,
/// <include file='doc\Keys.uex' path='docs/doc[@for="Keys.Home"]/*' />
/// <devdoc>
/// <para>
/// The HOME key.
/// </para>
/// </devdoc>
Home = 0x24,
/// <include file='doc\Keys.uex' path='docs/doc[@for="Keys.Left"]/*' />
/// <devdoc>
/// <para>
/// The LEFT ARROW key.
/// </para>
/// </devdoc>
Left = 0x25,
/// <include file='doc\Keys.uex' path='docs/doc[@for="Keys.Up"]/*' />
/// <devdoc>
/// <para>
/// The UP ARROW key.
/// </para>
/// </devdoc>
Up = 0x26,
/// <include file='doc\Keys.uex' path='docs/doc[@for="Keys.Right"]/*' />
/// <devdoc>
/// <para>
/// The RIGHT ARROW key.
/// </para>
/// </devdoc>
Right = 0x27,
/// <include file='doc\Keys.uex' path='docs/doc[@for="Keys.Down"]/*' />
/// <devdoc>
/// <para>
/// The DOWN ARROW key.
/// </para>
/// </devdoc>
Down = 0x28,
/// <include file='doc\Keys.uex' path='docs/doc[@for="Keys.Select"]/*' />
/// <devdoc>
/// <para>
/// The SELECT key.
/// </para>
/// </devdoc>
Select = 0x29,
/// <include file='doc\Keys.uex' path='docs/doc[@for="Keys.Print"]/*' />
/// <devdoc>
/// <para>
/// The PRINT key.
/// </para>
/// </devdoc>
Print = 0x2A,
/// <include file='doc\Keys.uex' path='docs/doc[@for="Keys.Execute"]/*' />
/// <devdoc>
/// <para>
/// The EXECUTE key.
/// </para>
/// </devdoc>
Execute = 0x2B,
/// <include file='doc\Keys.uex' path='docs/doc[@for="Keys.Snapshot"]/*' />
/// <devdoc>
/// <para>
/// The PRINT SCREEN key.
///
/// </para>
/// </devdoc>
Snapshot = 0x2C,
/// <include file='doc\Keys.uex' path='docs/doc[@for="Keys.PrintScreen"]/*' />
/// <devdoc>
/// <para>
/// The PRINT SCREEN key.
/// </para>
/// </devdoc>
PrintScreen = Snapshot,
/// <include file='doc\Keys.uex' path='docs/doc[@for="Keys.Insert"]/*' />
/// <devdoc>
/// <para>
/// The INS key.
/// </para>
/// </devdoc>
Insert = 0x2D,
/// <include file='doc\Keys.uex' path='docs/doc[@for="Keys.Delete"]/*' />
/// <devdoc>
/// <para>
/// The DEL key.
/// </para>
/// </devdoc>
Delete = 0x2E,
/// <include file='doc\Keys.uex' path='docs/doc[@for="Keys.Help"]/*' />
/// <devdoc>
/// <para>
/// The HELP key.
/// </para>
/// </devdoc>
Help = 0x2F,
/// <include file='doc\Keys.uex' path='docs/doc[@for="Keys.D0"]/*' />
/// <devdoc>
/// <para>
/// The 0 key.
/// </para>
/// </devdoc>
D0 = 0x30, // 0
/// <include file='doc\Keys.uex' path='docs/doc[@for="Keys.D1"]/*' />
/// <devdoc>
/// <para>
/// The 1 key.
/// </para>
/// </devdoc>
D1 = 0x31, // 1
/// <include file='doc\Keys.uex' path='docs/doc[@for="Keys.D2"]/*' />
/// <devdoc>
/// <para>
/// The 2 key.
/// </para>
/// </devdoc>
D2 = 0x32, // 2
/// <include file='doc\Keys.uex' path='docs/doc[@for="Keys.D3"]/*' />
/// <devdoc>
/// <para>
/// The 3 key.
/// </para>
/// </devdoc>
D3 = 0x33, // 3
/// <include file='doc\Keys.uex' path='docs/doc[@for="Keys.D4"]/*' />
/// <devdoc>
/// <para>
/// The 4 key.
/// </para>
/// </devdoc>
D4 = 0x34, // 4
/// <include file='doc\Keys.uex' path='docs/doc[@for="Keys.D5"]/*' />
/// <devdoc>
/// <para>
/// The 5 key.
/// </para>
/// </devdoc>
D5 = 0x35, // 5
/// <include file='doc\Keys.uex' path='docs/doc[@for="Keys.D6"]/*' />
/// <devdoc>
/// <para>
/// The 6 key.
/// </para>
/// </devdoc>
D6 = 0x36, // 6
/// <include file='doc\Keys.uex' path='docs/doc[@for="Keys.D7"]/*' />
/// <devdoc>
/// <para>
/// The 7 key.
/// </para>
/// </devdoc>
D7 = 0x37, // 7
/// <include file='doc\Keys.uex' path='docs/doc[@for="Keys.D8"]/*' />
/// <devdoc>
/// <para>
/// The 8 key.
/// </para>
/// </devdoc>
D8 = 0x38, // 8
/// <include file='doc\Keys.uex' path='docs/doc[@for="Keys.D9"]/*' />
/// <devdoc>
/// <para>
/// The 9 key.
/// </para>
/// </devdoc>
D9 = 0x39, // 9
/// <include file='doc\Keys.uex' path='docs/doc[@for="Keys.A"]/*' />
/// <devdoc>
/// <para>
/// The A key.
/// </para>
/// </devdoc>
A = 0x41,
/// <include file='doc\Keys.uex' path='docs/doc[@for="Keys.B"]/*' />
/// <devdoc>
/// <para>
/// The B key.
/// </para>
/// </devdoc>
B = 0x42,
/// <include file='doc\Keys.uex' path='docs/doc[@for="Keys.C"]/*' />
/// <devdoc>
/// <para>
/// The C key.
/// </para>
/// </devdoc>
C = 0x43,
/// <include file='doc\Keys.uex' path='docs/doc[@for="Keys.D"]/*' />
/// <devdoc>
/// <para>
/// The D key.
/// </para>
/// </devdoc>
D = 0x44,
/// <include file='doc\Keys.uex' path='docs/doc[@for="Keys.E"]/*' />
/// <devdoc>
/// <para>
/// The E key.
/// </para>
/// </devdoc>
E = 0x45,
/// <include file='doc\Keys.uex' path='docs/doc[@for="Keys.F"]/*' />
/// <devdoc>
/// <para>
/// The F key.
/// </para>
/// </devdoc>
F = 0x46,
/// <include file='doc\Keys.uex' path='docs/doc[@for="Keys.G"]/*' />
/// <devdoc>
/// <para>
/// The G key.
/// </para>
/// </devdoc>
G = 0x47,
/// <include file='doc\Keys.uex' path='docs/doc[@for="Keys.H"]/*' />
/// <devdoc>
/// <para>
/// The H key.
/// </para>
/// </devdoc>
H = 0x48,
/// <include file='doc\Keys.uex' path='docs/doc[@for="Keys.I"]/*' />
/// <devdoc>
/// <para>
/// The I key.
/// </para>
/// </devdoc>
I = 0x49,
/// <include file='doc\Keys.uex' path='docs/doc[@for="Keys.J"]/*' />
/// <devdoc>
/// <para>
/// The J key.
/// </para>
/// </devdoc>
J = 0x4A,
/// <include file='doc\Keys.uex' path='docs/doc[@for="Keys.K"]/*' />
/// <devdoc>
/// <para>
/// The K key.
/// </para>
/// </devdoc>
K = 0x4B,
/// <include file='doc\Keys.uex' path='docs/doc[@for="Keys.L"]/*' />
/// <devdoc>
/// <para>
/// The L key.
/// </para>
/// </devdoc>
L = 0x4C,
/// <include file='doc\Keys.uex' path='docs/doc[@for="Keys.M"]/*' />
/// <devdoc>
/// <para>
/// The M key.
/// </para>
/// </devdoc>
M = 0x4D,
/// <include file='doc\Keys.uex' path='docs/doc[@for="Keys.N"]/*' />
/// <devdoc>
/// <para>
/// The N key.
/// </para>
/// </devdoc>
N = 0x4E,
/// <include file='doc\Keys.uex' path='docs/doc[@for="Keys.O"]/*' />
/// <devdoc>
/// <para>
/// The O key.
/// </para>
/// </devdoc>
O = 0x4F,
/// <include file='doc\Keys.uex' path='docs/doc[@for="Keys.P"]/*' />
/// <devdoc>
/// <para>
/// The P key.
/// </para>
/// </devdoc>
P = 0x50,
/// <include file='doc\Keys.uex' path='docs/doc[@for="Keys.Q"]/*' />
/// <devdoc>
/// <para>
/// The Q key.
/// </para>
/// </devdoc>
Q = 0x51,
/// <include file='doc\Keys.uex' path='docs/doc[@for="Keys.R"]/*' />
/// <devdoc>
/// <para>
/// The R key.
/// </para>
/// </devdoc>
R = 0x52,
/// <include file='doc\Keys.uex' path='docs/doc[@for="Keys.S"]/*' />
/// <devdoc>
/// <para>
/// The S key.
/// </para>
/// </devdoc>
S = 0x53,
/// <include file='doc\Keys.uex' path='docs/doc[@for="Keys.T"]/*' />
/// <devdoc>
/// <para>
/// The T key.
/// </para>
/// </devdoc>
T = 0x54,
/// <include file='doc\Keys.uex' path='docs/doc[@for="Keys.U"]/*' />
/// <devdoc>
/// <para>
/// The U key.
/// </para>
/// </devdoc>
U = 0x55,
/// <include file='doc\Keys.uex' path='docs/doc[@for="Keys.V"]/*' />
/// <devdoc>
/// <para>
/// The V key.
/// </para>
/// </devdoc>
V = 0x56,
/// <include file='doc\Keys.uex' path='docs/doc[@for="Keys.W"]/*' />
/// <devdoc>
/// <para>
/// The W key.
/// </para>
/// </devdoc>
W = 0x57,
/// <include file='doc\Keys.uex' path='docs/doc[@for="Keys.X"]/*' />
/// <devdoc>
/// <para>
/// The X key.
/// </para>
/// </devdoc>
X = 0x58,
/// <include file='doc\Keys.uex' path='docs/doc[@for="Keys.Y"]/*' />
/// <devdoc>
/// <para>
/// The Y key.
/// </para>
/// </devdoc>
Y = 0x59,
/// <include file='doc\Keys.uex' path='docs/doc[@for="Keys.Z"]/*' />
/// <devdoc>
/// <para>
/// The Z key.
/// </para>
/// </devdoc>
Z = 0x5A,
/// <include file='doc\Keys.uex' path='docs/doc[@for="Keys.LWin"]/*' />
/// <devdoc>
/// <para>
/// The left Windows logo key (Microsoft Natural Keyboard).
/// </para>
/// </devdoc>
LWin = 0x5B,
/// <include file='doc\Keys.uex' path='docs/doc[@for="Keys.RWin"]/*' />
/// <devdoc>
/// <para>
/// The right Windows logo key (Microsoft Natural Keyboard).
/// </para>
/// </devdoc>
RWin = 0x5C,
/// <include file='doc\Keys.uex' path='docs/doc[@for="Keys.Apps"]/*' />
/// <devdoc>
/// <para>
/// The Application key (Microsoft Natural Keyboard).
/// </para>
/// </devdoc>
Apps = 0x5D,
/// <include file='doc\Keys.uex' path='docs/doc[@for="Keys.Sleep"]/*' />
/// <devdoc>
/// <para>
/// The Computer Sleep key.
/// </para>
/// </devdoc>
Sleep = 0x5F,
/// <include file='doc\Keys.uex' path='docs/doc[@for="Keys.NumPad0"]/*' />
/// <devdoc>
/// <para>
/// The 0 key on the numeric keypad.
/// </para>
/// </devdoc>
// PM team has reviewed and decided on naming changes already
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")]
NumPad0 = 0x60,
/// <include file='doc\Keys.uex' path='docs/doc[@for="Keys.NumPad1"]/*' />
/// <devdoc>
/// <para>
/// The 1 key on the numeric keypad.
/// </para>
/// </devdoc>
// PM team has reviewed and decided on naming changes already
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")]
NumPad1 = 0x61,
/// <include file='doc\Keys.uex' path='docs/doc[@for="Keys.NumPad2"]/*' />
/// <devdoc>
/// <para>
/// The 2 key on the numeric keypad.
/// </para>
/// </devdoc>
// PM team has reviewed and decided on naming changes already
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")]
NumPad2 = 0x62,
/// <include file='doc\Keys.uex' path='docs/doc[@for="Keys.NumPad3"]/*' />
/// <devdoc>
/// <para>
/// The 3 key on the numeric keypad.
/// </para>
/// </devdoc>
// PM team has reviewed and decided on naming changes already
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")]
NumPad3 = 0x63,
/// <include file='doc\Keys.uex' path='docs/doc[@for="Keys.NumPad4"]/*' />
/// <devdoc>
/// <para>
/// The 4 key on the numeric keypad.
/// </para>
/// </devdoc>
// PM team has reviewed and decided on naming changes already
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")]
NumPad4 = 0x64,
/// <include file='doc\Keys.uex' path='docs/doc[@for="Keys.NumPad5"]/*' />
/// <devdoc>
/// <para>
/// The 5 key on the numeric keypad.
/// </para>
/// </devdoc>
// PM team has reviewed and decided on naming changes already
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")]
NumPad5 = 0x65,
/// <include file='doc\Keys.uex' path='docs/doc[@for="Keys.NumPad6"]/*' />
/// <devdoc>
/// <para>
/// The 6 key on the numeric keypad.
/// </para>
/// </devdoc>
// PM team has reviewed and decided on naming changes already
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")]
NumPad6 = 0x66,
/// <include file='doc\Keys.uex' path='docs/doc[@for="Keys.NumPad7"]/*' />
/// <devdoc>
/// <para>
/// The 7 key on the numeric keypad.
/// </para>
/// </devdoc>
// PM team has reviewed and decided on naming changes already
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")]
NumPad7 = 0x67,
/// <include file='doc\Keys.uex' path='docs/doc[@for="Keys.NumPad8"]/*' />
/// <devdoc>
/// <para>
/// The 8 key on the numeric keypad.
/// </para>
/// </devdoc>
// PM team has reviewed and decided on naming changes already
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")]
NumPad8 = 0x68,
/// <include file='doc\Keys.uex' path='docs/doc[@for="Keys.NumPad9"]/*' />
/// <devdoc>
/// <para>
/// The 9 key on the numeric keypad.
/// </para>
/// </devdoc>
// PM team has reviewed and decided on naming changes already
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")]
NumPad9 = 0x69,
/// <include file='doc\Keys.uex' path='docs/doc[@for="Keys.Multiply"]/*' />
/// <devdoc>
/// <para>
/// The Multiply key.
/// </para>
/// </devdoc>
Multiply = 0x6A,
/// <include file='doc\Keys.uex' path='docs/doc[@for="Keys.Add"]/*' />
/// <devdoc>
/// <para>
/// The Add key.
/// </para>
/// </devdoc>
Add = 0x6B,
/// <include file='doc\Keys.uex' path='docs/doc[@for="Keys.Separator"]/*' />
/// <devdoc>
/// <para>
/// The Separator key.
/// </para>
/// </devdoc>
Separator = 0x6C,
/// <include file='doc\Keys.uex' path='docs/doc[@for="Keys.Subtract"]/*' />
/// <devdoc>
/// <para>
/// The Subtract key.
/// </para>
/// </devdoc>
Subtract = 0x6D,
/// <include file='doc\Keys.uex' path='docs/doc[@for="Keys.Decimal"]/*' />
/// <devdoc>
/// <para>
/// The Decimal key.
/// </para>
/// </devdoc>
Decimal = 0x6E,
/// <include file='doc\Keys.uex' path='docs/doc[@for="Keys.Divide"]/*' />
/// <devdoc>
/// <para>
/// The Divide key.
/// </para>
/// </devdoc>
Divide = 0x6F,
/// <include file='doc\Keys.uex' path='docs/doc[@for="Keys.F1"]/*' />
/// <devdoc>
/// <para>
/// The F1 key.
/// </para>
/// </devdoc>
F1 = 0x70,
/// <include file='doc\Keys.uex' path='docs/doc[@for="Keys.F2"]/*' />
/// <devdoc>
/// <para>
/// The F2 key.
/// </para>
/// </devdoc>
F2 = 0x71,
/// <include file='doc\Keys.uex' path='docs/doc[@for="Keys.F3"]/*' />
/// <devdoc>
/// <para>
/// The F3 key.
/// </para>
/// </devdoc>
F3 = 0x72,
/// <include file='doc\Keys.uex' path='docs/doc[@for="Keys.F4"]/*' />
/// <devdoc>
/// <para>
/// The F4 key.
/// </para>
/// </devdoc>
F4 = 0x73,
/// <include file='doc\Keys.uex' path='docs/doc[@for="Keys.F5"]/*' />
/// <devdoc>
/// <para>
/// The F5 key.
/// </para>
/// </devdoc>
F5 = 0x74,
/// <include file='doc\Keys.uex' path='docs/doc[@for="Keys.F6"]/*' />
/// <devdoc>
/// <para>
/// The F6 key.
/// </para>
/// </devdoc>
F6 = 0x75,
/// <include file='doc\Keys.uex' path='docs/doc[@for="Keys.F7"]/*' />
/// <devdoc>
/// <para>
/// The F7 key.
/// </para>
/// </devdoc>
F7 = 0x76,
/// <include file='doc\Keys.uex' path='docs/doc[@for="Keys.F8"]/*' />
/// <devdoc>
/// <para>
/// The F8 key.
/// </para>
/// </devdoc>
F8 = 0x77,
/// <include file='doc\Keys.uex' path='docs/doc[@for="Keys.F9"]/*' />
/// <devdoc>
/// <para>
/// The F9 key.
/// </para>
/// </devdoc>
F9 = 0x78,
/// <include file='doc\Keys.uex' path='docs/doc[@for="Keys.F10"]/*' />
/// <devdoc>
/// <para>
/// The F10 key.
/// </para>
/// </devdoc>
F10 = 0x79,
/// <include file='doc\Keys.uex' path='docs/doc[@for="Keys.F11"]/*' />
/// <devdoc>
/// <para>
/// The F11 key.
/// </para>
/// </devdoc>
F11 = 0x7A,
/// <include file='doc\Keys.uex' path='docs/doc[@for="Keys.F12"]/*' />
/// <devdoc>
/// <para>
/// The F12 key.
/// </para>
/// </devdoc>
F12 = 0x7B,
/// <include file='doc\Keys.uex' path='docs/doc[@for="Keys.F13"]/*' />
/// <devdoc>
/// <para>
/// The F13 key.
/// </para>
/// </devdoc>
F13 = 0x7C,
/// <include file='doc\Keys.uex' path='docs/doc[@for="Keys.F14"]/*' />
/// <devdoc>
/// <para>
/// The F14 key.
/// </para>
/// </devdoc>
F14 = 0x7D,
/// <include file='doc\Keys.uex' path='docs/doc[@for="Keys.F15"]/*' />
/// <devdoc>
/// <para>
/// The F15 key.
/// </para>
/// </devdoc>
F15 = 0x7E,
/// <include file='doc\Keys.uex' path='docs/doc[@for="Keys.F16"]/*' />
/// <devdoc>
/// <para>
/// The F16 key.
/// </para>
/// </devdoc>
F16 = 0x7F,
/// <include file='doc\Keys.uex' path='docs/doc[@for="Keys.F17"]/*' />
/// <devdoc>
/// <para>
/// The F17 key.
/// </para>
/// </devdoc>
F17 = 0x80,
/// <include file='doc\Keys.uex' path='docs/doc[@for="Keys.F18"]/*' />
/// <devdoc>
/// <para>
/// The F18 key.
/// </para>
/// </devdoc>
F18 = 0x81,
/// <include file='doc\Keys.uex' path='docs/doc[@for="Keys.F19"]/*' />
/// <devdoc>
/// <para>
/// The F19 key.
/// </para>
/// </devdoc>
F19 = 0x82,
/// <include file='doc\Keys.uex' path='docs/doc[@for="Keys.F20"]/*' />
/// <devdoc>
/// <para>
/// The F20 key.
/// </para>
/// </devdoc>
F20 = 0x83,
/// <include file='doc\Keys.uex' path='docs/doc[@for="Keys.F21"]/*' />
/// <devdoc>
/// <para>
/// The F21 key.
/// </para>
/// </devdoc>
F21 = 0x84,
/// <include file='doc\Keys.uex' path='docs/doc[@for="Keys.F22"]/*' />
/// <devdoc>
/// <para>
/// The F22 key.
/// </para>
/// </devdoc>
F22 = 0x85,
/// <include file='doc\Keys.uex' path='docs/doc[@for="Keys.F23"]/*' />
/// <devdoc>
/// <para>
/// The F23 key.
/// </para>
/// </devdoc>
F23 = 0x86,
/// <include file='doc\Keys.uex' path='docs/doc[@for="Keys.F24"]/*' />
/// <devdoc>
/// <para>
/// The F24 key.
/// </para>
/// </devdoc>
F24 = 0x87,
/// <include file='doc\Keys.uex' path='docs/doc[@for="Keys.NumLock"]/*' />
/// <devdoc>
/// <para>
/// The NUM LOCK key.
/// </para>
/// </devdoc>
// PM team has reviewed and decided on naming changes already
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")]
NumLock = 0x90,
/// <include file='doc\Keys.uex' path='docs/doc[@for="Keys.Scroll"]/*' />
/// <devdoc>
/// <para>
/// The SCROLL LOCK key.
/// </para>
/// </devdoc>
Scroll = 0x91,
/// <include file='doc\Keys.uex' path='docs/doc[@for="Keys.LShiftKey"]/*' />
/// <devdoc>
/// <para>
/// The left SHIFT key.
/// </para>
/// </devdoc>
LShiftKey = 0xA0,
/// <include file='doc\Keys.uex' path='docs/doc[@for="Keys.RShiftKey"]/*' />
/// <devdoc>
/// <para>
/// The right SHIFT key.
/// </para>
/// </devdoc>
RShiftKey = 0xA1,
/// <include file='doc\Keys.uex' path='docs/doc[@for="Keys.LControlKey"]/*' />
/// <devdoc>
/// <para>
/// The left CTRL key.
/// </para>
/// </devdoc>
LControlKey = 0xA2,
/// <include file='doc\Keys.uex' path='docs/doc[@for="Keys.RControlKey"]/*' />
/// <devdoc>
/// <para>
/// The right CTRL key.
/// </para>
/// </devdoc>
RControlKey = 0xA3,
/// <include file='doc\Keys.uex' path='docs/doc[@for="Keys.LMenu"]/*' />
/// <devdoc>
/// <para>
/// The left ALT key.
/// </para>
/// </devdoc>
LMenu = 0xA4,
/// <include file='doc\Keys.uex' path='docs/doc[@for="Keys.RMenu"]/*' />
/// <devdoc>
/// <para>
/// The right ALT key.
/// </para>
/// </devdoc>
RMenu = 0xA5,
/// <include file='doc\Keys.uex' path='docs/doc[@for="Keys.BrowserBack"]/*' />
/// <devdoc>
/// <para>
/// The Browser Back key.
/// </para>
/// </devdoc>
BrowserBack = 0xA6,
/// <include file='doc\Keys.uex' path='docs/doc[@for="Keys.BrowserForward"]/*' />
/// <devdoc>
/// <para>
/// The Browser Forward key.
/// </para>
/// </devdoc>
BrowserForward= 0xA7,
/// <include file='doc\Keys.uex' path='docs/doc[@for="Keys.BrowserRefresh"]/*' />
/// <devdoc>
/// <para>
/// The Browser Refresh key.
/// </para>
/// </devdoc>
BrowserRefresh= 0xA8,
/// <include file='doc\Keys.uex' path='docs/doc[@for="Keys.BrowserStop"]/*' />
/// <devdoc>
/// <para>
/// The Browser Stop key.
/// </para>
/// </devdoc>
BrowserStop = 0xA9,
/// <include file='doc\Keys.uex' path='docs/doc[@for="Keys.BrowserSearch"]/*' />
/// <devdoc>
/// <para>
/// The Browser Search key.
/// </para>
/// </devdoc>
BrowserSearch = 0xAA,
/// <include file='doc\Keys.uex' path='docs/doc[@for="Keys.BrowserFavorites"]/*' />
/// <devdoc>
/// <para>
/// The Browser Favorites key.
/// </para>
/// </devdoc>
BrowserFavorites = 0xAB,
/// <include file='doc\Keys.uex' path='docs/doc[@for="Keys.BrowserHome"]/*' />
/// <devdoc>
/// <para>
/// The Browser Home key.
/// </para>
/// </devdoc>
BrowserHome = 0xAC,
/// <include file='doc\Keys.uex' path='docs/doc[@for="Keys.VolumeMute"]/*' />
/// <devdoc>
/// <para>
/// The Volume Mute key.
/// </para>
/// </devdoc>
VolumeMute = 0xAD,
/// <include file='doc\Keys.uex' path='docs/doc[@for="Keys.VolumeDown"]/*' />
/// <devdoc>
/// <para>
/// The Volume Down key.
/// </para>
/// </devdoc>
VolumeDown = 0xAE,
/// <include file='doc\Keys.uex' path='docs/doc[@for="Keys.VolumeUp"]/*' />
/// <devdoc>
/// <para>
/// The Volume Up key.
/// </para>
/// </devdoc>
VolumeUp = 0xAF,
/// <include file='doc\Keys.uex' path='docs/doc[@for="Keys.MediaNextTrack"]/*' />
/// <devdoc>
/// <para>
/// The Media Next Track key.
/// </para>
/// </devdoc>
MediaNextTrack = 0xB0,
/// <include file='doc\Keys.uex' path='docs/doc[@for="Keys.MediaPreviousTrack"]/*' />
/// <devdoc>
/// <para>
/// The Media Previous Track key.
/// </para>
/// </devdoc>
MediaPreviousTrack = 0xB1,
/// <include file='doc\Keys.uex' path='docs/doc[@for="Keys.MediaStop"]/*' />
/// <devdoc>
/// <para>
/// The Media Stop key.
/// </para>
/// </devdoc>
MediaStop = 0xB2,
/// <include file='doc\Keys.uex' path='docs/doc[@for="Keys.MediaPlayPause"]/*' />
/// <devdoc>
/// <para>
/// The Media Play Pause key.
/// </para>
/// </devdoc>
MediaPlayPause = 0xB3,
/// <include file='doc\Keys.uex' path='docs/doc[@for="Keys.LaunchMail"]/*' />
/// <devdoc>
/// <para>
/// The Launch Mail key.
/// </para>
/// </devdoc>
LaunchMail = 0xB4,
/// <include file='doc\Keys.uex' path='docs/doc[@for="Keys.SelectMedia"]/*' />
/// <devdoc>
/// <para>
/// The Select Media key.
/// </para>
/// </devdoc>
SelectMedia = 0xB5,
/// <include file='doc\Keys.uex' path='docs/doc[@for="Keys.LaunchApplication1"]/*' />
/// <devdoc>
/// <para>
/// The Launch Application1 key.
/// </para>
/// </devdoc>
LaunchApplication1 = 0xB6,
/// <include file='doc\Keys.uex' path='docs/doc[@for="Keys.LaunchApplication2"]/*' />
/// <devdoc>
/// <para>
/// The Launch Application2 key.
/// </para>
/// </devdoc>
LaunchApplication2 = 0xB7,
/// <include file='doc\Keys.uex' path='docs/doc[@for="Keys.OemSemicolon"]/*' />
/// <devdoc>
/// <para>
/// The Oem Semicolon key.
/// </para>
/// </devdoc>
OemSemicolon = 0xBA,
/// <include file='doc\Keys.uex' path='docs/doc[@for="Keys.Oem1"]/*' />
/// <devdoc>
/// <para>
/// The Oem 1 key.
/// </para>
/// </devdoc>
Oem1 = OemSemicolon,
/// <include file='doc\Keys.uex' path='docs/doc[@for="Keys.Oemplus"]/*' />
/// <devdoc>
/// <para>
/// The Oem plus key.
/// </para>
/// </devdoc>
Oemplus = 0xBB,
/// <include file='doc\Keys.uex' path='docs/doc[@for="Keys.Oemcomma"]/*' />
/// <devdoc>
/// <para>
/// The Oem comma key.
/// </para>
/// </devdoc>
Oemcomma = 0xBC,
/// <include file='doc\Keys.uex' path='docs/doc[@for="Keys.OemMinus"]/*' />
/// <devdoc>
/// <para>
/// The Oem Minus key.
/// </para>
/// </devdoc>
OemMinus = 0xBD,
/// <include file='doc\Keys.uex' path='docs/doc[@for="Keys.OemPeriod"]/*' />
/// <devdoc>
/// <para>
/// The Oem Period key.
/// </para>
/// </devdoc>
OemPeriod = 0xBE,
/// <include file='doc\Keys.uex' path='docs/doc[@for="Keys.OemQuestion"]/*' />
/// <devdoc>
/// <para>
/// The Oem Question key.
/// </para>
/// </devdoc>
OemQuestion = 0xBF,
/// <include file='doc\Keys.uex' path='docs/doc[@for="Keys.Oem2"]/*' />
/// <devdoc>
/// <para>
/// The Oem 2 key.
/// </para>
/// </devdoc>
Oem2 = OemQuestion,
/// <include file='doc\Keys.uex' path='docs/doc[@for="Keys.Oemtilde"]/*' />
/// <devdoc>
/// <para>
/// The Oem tilde key.
/// </para>
/// </devdoc>
Oemtilde = 0xC0,
/// <include file='doc\Keys.uex' path='docs/doc[@for="Keys.Oem3"]/*' />
/// <devdoc>
/// <para>
/// The Oem 3 key.
/// </para>
/// </devdoc>
Oem3 = Oemtilde,
/// <include file='doc\Keys.uex' path='docs/doc[@for="Keys.OemOpenBrackets"]/*' />
/// <devdoc>
/// <para>
/// The Oem Open Brackets key.
/// </para>
/// </devdoc>
OemOpenBrackets = 0xDB,
/// <include file='doc\Keys.uex' path='docs/doc[@for="Keys.Oem4"]/*' />
/// <devdoc>
/// <para>
/// The Oem 4 key.
/// </para>
/// </devdoc>
Oem4 = OemOpenBrackets,
/// <include file='doc\Keys.uex' path='docs/doc[@for="Keys.OemPipe"]/*' />
/// <devdoc>
/// <para>
/// The Oem Pipe key.
/// </para>
/// </devdoc>
OemPipe = 0xDC,
/// <include file='doc\Keys.uex' path='docs/doc[@for="Keys.Oem5"]/*' />
/// <devdoc>
/// <para>
/// The Oem 5 key.
/// </para>
/// </devdoc>
Oem5 = OemPipe,
/// <include file='doc\Keys.uex' path='docs/doc[@for="Keys.OemCloseBrackets"]/*' />
/// <devdoc>
/// <para>
/// The Oem Close Brackets key.
/// </para>
/// </devdoc>
OemCloseBrackets = 0xDD,
/// <include file='doc\Keys.uex' path='docs/doc[@for="Keys.Oem6"]/*' />
/// <devdoc>
/// <para>
/// The Oem 6 key.
/// </para>
/// </devdoc>
Oem6 = OemCloseBrackets,
/// <include file='doc\Keys.uex' path='docs/doc[@for="Keys.OemQuotes"]/*' />
/// <devdoc>
/// <para>
/// The Oem Quotes key.
/// </para>
/// </devdoc>
OemQuotes = 0xDE,
/// <include file='doc\Keys.uex' path='docs/doc[@for="Keys.Oem7"]/*' />
/// <devdoc>
/// <para>
/// The Oem 7 key.
/// </para>
/// </devdoc>
Oem7 = OemQuotes,
/// <include file='doc\Keys.uex' path='docs/doc[@for="Keys.Oem8"]/*' />
/// <devdoc>
/// <para>
/// The Oem8 key.
/// </para>
/// </devdoc>
Oem8 = 0xDF,
/// <include file='doc\Keys.uex' path='docs/doc[@for="Keys.OemBackslash"]/*' />
/// <devdoc>
/// <para>
/// The Oem Backslash key.
/// </para>
/// </devdoc>
OemBackslash = 0xE2,
/// <include file='doc\Keys.uex' path='docs/doc[@for="Keys.Oem102"]/*' />
/// <devdoc>
/// <para>
/// The Oem 102 key.
/// </para>
/// </devdoc>
Oem102 = OemBackslash,
/// <include file='doc\Keys.uex' path='docs/doc[@for="Keys.ProcessKey"]/*' />
/// <devdoc>
/// <para>
/// The PROCESS KEY key.
/// </para>
/// </devdoc>
ProcessKey = 0xE5,
/// <include file='doc\Keys.uex' path='docs/doc[@for="Keys.Packet"]/*' />
/// <devdoc>
/// <para>
/// The Packet KEY key.
/// </para>
/// </devdoc>
Packet = 0xE7,
/// <include file='doc\Keys.uex' path='docs/doc[@for="Keys.Attn"]/*' />
/// <devdoc>
/// <para>
/// The ATTN key.
/// </para>
/// </devdoc>
Attn = 0xF6,
/// <include file='doc\Keys.uex' path='docs/doc[@for="Keys.Crsel"]/*' />
/// <devdoc>
/// <para>
/// The CRSEL key.
/// </para>
/// </devdoc>
Crsel = 0xF7,
/// <include file='doc\Keys.uex' path='docs/doc[@for="Keys.Exsel"]/*' />
/// <devdoc>
/// <para>
/// The EXSEL key.
/// </para>
/// </devdoc>
Exsel = 0xF8,
/// <include file='doc\Keys.uex' path='docs/doc[@for="Keys.EraseEof"]/*' />
/// <devdoc>
/// <para>
/// The ERASE EOF key.
/// </para>
/// </devdoc>
EraseEof = 0xF9,
/// <include file='doc\Keys.uex' path='docs/doc[@for="Keys.Play"]/*' />
/// <devdoc>
/// <para>
/// The PLAY key.
/// </para>
/// </devdoc>
Play = 0xFA,
/// <include file='doc\Keys.uex' path='docs/doc[@for="Keys.Zoom"]/*' />
/// <devdoc>
/// <para>
/// The ZOOM key.
/// </para>
/// </devdoc>
Zoom = 0xFB,
/// <include file='doc\Keys.uex' path='docs/doc[@for="Keys.NoName"]/*' />
/// <devdoc>
/// <para>
/// A constant reserved for future use.
/// </para>
/// </devdoc>
NoName = 0xFC,
/// <include file='doc\Keys.uex' path='docs/doc[@for="Keys.Pa1"]/*' />
/// <devdoc>
/// <para>
/// The PA1 key.
/// </para>
/// </devdoc>
Pa1 = 0xFD,
/// <include file='doc\Keys.uex' path='docs/doc[@for="Keys.OemClear"]/*' />
/// <devdoc>
/// <para>
/// The CLEAR key.
/// </para>
/// </devdoc>
OemClear = 0xFE,
/// <include file='doc\Keys.uex' path='docs/doc[@for="Keys.Shift"]/*' />
/// <devdoc>
/// <para>
/// The SHIFT modifier key.
/// </para>
/// </devdoc>
Shift = 0x00010000,
/// <include file='doc\Keys.uex' path='docs/doc[@for="Keys.Control"]/*' />
/// <devdoc>
/// <para>
/// The
/// CTRL modifier key.
///
/// </para>
/// </devdoc>
Control = 0x00020000,
/// <include file='doc\Keys.uex' path='docs/doc[@for="Keys.Alt"]/*' />
/// <devdoc>
/// <para>
/// The ALT modifier key.
///
/// </para>
/// </devdoc>
Alt = 0x00040000,
}
}
| |
/* ****************************************************************************
*
* 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.txt file at the root of this distribution.
*
* You must not remove this notice, or any other, from this software.
*
* ***************************************************************************/
using EnvDTE;
using Microsoft.VisualStudio.Shell;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Reflection;
using System.Runtime.InteropServices;
namespace Microsoft.VisualStudio.Project.Automation
{
/// <summary>
/// Contains all of the properties of a given object that are contained in a generic collection of properties.
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")]
[CLSCompliant(false), ComVisible(true)]
public class OAProperties : Properties
{
#region fields
private NodeProperties _target;
private Dictionary<string, EnvDTE.Property> _properties = new Dictionary<string, EnvDTE.Property>();
#endregion
#region properties
/// <summary>
/// Defines the NodeProperties object that contains the defines the properties.
/// </summary>
public NodeProperties Target
{
get
{
return _target;
}
}
/// <summary>
/// The hierarchy node for the object which properties this item represent
/// </summary>
public HierarchyNode Node
{
get
{
return this.Target.Node;
}
}
/// <summary>
/// Defines a dictionary of the properties contained.
/// </summary>
public Dictionary<string, Property> Properties
{
get
{
return _properties;
}
}
#endregion
#region ctor
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public OAProperties(NodeProperties target)
{
Utilities.ArgumentNotNull("target", target);
this._target = target;
this.AddPropertiesFromType(target.GetType());
}
#endregion
#region EnvDTE.Properties
/// <summary>
/// Microsoft Internal Use Only.
/// </summary>
public virtual object Application
{
get { return null; }
}
/// <summary>
/// Gets a value indicating the number of objects in the collection.
/// </summary>
public int Count
{
get { return _properties.Count; }
}
/// <summary>
/// Gets the top-level extensibility object.
/// </summary>
public virtual DTE DTE
{
get
{
return ThreadHelper.JoinableTaskFactory.Run(async delegate
{
await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();
if (_target == null || _target.Node == null || _target.Node.ProjectMgr == null || _target.Node.ProjectMgr.IsClosed ||
_target.Node.ProjectMgr.Site == null)
{
throw new InvalidOperationException();
}
return _target.Node.ProjectMgr.Site.GetService(typeof(DTE)) as DTE;
});
}
}
/// <summary>
/// Gets an enumeration for items in a collection.
/// </summary>
/// <returns>An enumerator. </returns>
public IEnumerator GetEnumerator()
{
if(_properties == null)
{
yield return null;
}
if(_properties.Count == 0)
{
yield return new OANullProperty(this);
}
IEnumerator enumerator = _properties.Values.GetEnumerator();
while(enumerator.MoveNext())
{
yield return enumerator.Current;
}
}
/// <summary>
/// Returns an indexed member of a Properties collection.
/// </summary>
/// <param name="index">The index at which to return a mamber.</param>
/// <returns>A Property object.</returns>
public virtual Property Item(object index)
{
if(index is string)
{
string indexAsString = (string)index;
if(_properties.ContainsKey(indexAsString))
{
return ThreadHelper.JoinableTaskFactory.Run(async delegate
{
await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();
return _properties[indexAsString];
});
}
}
else if(index is int)
{
int realIndex = (int)index - 1;
if(realIndex >= 0 && realIndex < _properties.Count)
{
IEnumerator enumerator = _properties.Values.GetEnumerator();
int i = 0;
while(enumerator.MoveNext())
{
if(i++ == realIndex)
{
return ThreadHelper.JoinableTaskFactory.Run(async delegate
{
await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();
return (EnvDTE.Property)enumerator.Current;
});
}
}
}
}
// do not throw exception.
//throw new ArgumentException(SR.GetString(SR.InvalidParameter, CultureInfo.CurrentUICulture), "index");
return new OANullProperty(this);
}
/// <summary>
/// Gets the immediate parent object of a Properties collection.
/// </summary>
public virtual object Parent
{
get { return null; }
}
#endregion
#region methods
/// <summary>
/// Add properties to the collection of properties filtering only those properties which are com-visible and AutomationBrowsable
/// </summary>
/// <param name="targetType">The type of NodeProperties the we should filter on</param>
protected void AddPropertiesFromType(Type targetType)
{
Utilities.ArgumentNotNull("targetType", targetType);
// If the type is not COM visible, we do not expose any of the properties
if(!IsComVisible(targetType))
return;
// Add all properties being ComVisible and AutomationVisible
PropertyInfo[] propertyInfos = targetType.GetProperties();
foreach(PropertyInfo propertyInfo in propertyInfos)
{
if(!IsInMap(propertyInfo) && IsComVisible(propertyInfo) && IsAutomationVisible(propertyInfo))
{
AddProperty(propertyInfo);
}
}
}
#endregion
#region virtual methods
/// <summary>
/// Creates a new OAProperty object and adds it to the current list of properties
/// </summary>
/// <param name="propertyInfo">The property to be associated with an OAProperty object</param>
protected virtual void AddProperty(PropertyInfo propertyInfo)
{
Utilities.ArgumentNotNull("propertyInfo", propertyInfo);
_properties.Add(propertyInfo.Name, new OAProperty(this, propertyInfo));
}
#endregion
#region helper methods
private bool IsInMap(PropertyInfo propertyInfo)
{
return _properties.ContainsKey(propertyInfo.Name);
}
private static bool IsAutomationVisible(PropertyInfo propertyInfo)
{
object[] customAttributes = propertyInfo.GetCustomAttributes(typeof(AutomationBrowsableAttribute), inherit: true);
for (int i = 0; i < customAttributes.Length; i++)
{
if (!((AutomationBrowsableAttribute)customAttributes[i]).Browsable)
{
return false;
}
}
return true;
}
private static bool IsComVisible(Type targetType)
{
object[] customAttributes = targetType.GetCustomAttributes(typeof(ComVisibleAttribute), inherit: true);
for (int i = 0; i < customAttributes.Length; i++)
{
if (!((ComVisibleAttribute)customAttributes[i]).Value)
{
return false;
}
}
return true;
}
private static bool IsComVisible(PropertyInfo propertyInfo)
{
object[] customAttributes = propertyInfo.GetCustomAttributes(typeof(ComVisibleAttribute), inherit: true);
for (int i = 0; i < customAttributes.Length; i++)
{
if (!((ComVisibleAttribute)customAttributes[i]).Value)
{
return false;
}
}
return true;
}
#endregion
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Fixtures.Azure.AcceptanceTestsPaging
{
using Fixtures.Azure;
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// Extension methods for PagingOperations.
/// </summary>
public static partial class PagingOperationsExtensions
{
/// <summary>
/// A paging operation that finishes on the first call without a nextlink
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static IPage<Product> GetSinglePages(this IPagingOperations operations)
{
return operations.GetSinglePagesAsync().GetAwaiter().GetResult();
}
/// <summary>
/// A paging operation that finishes on the first call without a nextlink
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<Product>> GetSinglePagesAsync(this IPagingOperations operations, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetSinglePagesWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// A paging operation that includes a nextLink that has 10 pages
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='clientRequestId'>
/// </param>
/// <param name='pagingGetMultiplePagesOptions'>
/// Additional parameters for the operation
/// </param>
public static IPage<Product> GetMultiplePages(this IPagingOperations operations, string clientRequestId = default(string), PagingGetMultiplePagesOptions pagingGetMultiplePagesOptions = default(PagingGetMultiplePagesOptions))
{
return operations.GetMultiplePagesAsync(clientRequestId, pagingGetMultiplePagesOptions).GetAwaiter().GetResult();
}
/// <summary>
/// A paging operation that includes a nextLink that has 10 pages
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='clientRequestId'>
/// </param>
/// <param name='pagingGetMultiplePagesOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<Product>> GetMultiplePagesAsync(this IPagingOperations operations, string clientRequestId = default(string), PagingGetMultiplePagesOptions pagingGetMultiplePagesOptions = default(PagingGetMultiplePagesOptions), CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetMultiplePagesWithHttpMessagesAsync(clientRequestId, pagingGetMultiplePagesOptions, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// A paging operation that includes a nextLink in odata format that has 10
/// pages
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='clientRequestId'>
/// </param>
/// <param name='pagingGetOdataMultiplePagesOptions'>
/// Additional parameters for the operation
/// </param>
public static IPage<Product> GetOdataMultiplePages(this IPagingOperations operations, string clientRequestId = default(string), PagingGetOdataMultiplePagesOptions pagingGetOdataMultiplePagesOptions = default(PagingGetOdataMultiplePagesOptions))
{
return operations.GetOdataMultiplePagesAsync(clientRequestId, pagingGetOdataMultiplePagesOptions).GetAwaiter().GetResult();
}
/// <summary>
/// A paging operation that includes a nextLink in odata format that has 10
/// pages
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='clientRequestId'>
/// </param>
/// <param name='pagingGetOdataMultiplePagesOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<Product>> GetOdataMultiplePagesAsync(this IPagingOperations operations, string clientRequestId = default(string), PagingGetOdataMultiplePagesOptions pagingGetOdataMultiplePagesOptions = default(PagingGetOdataMultiplePagesOptions), CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetOdataMultiplePagesWithHttpMessagesAsync(clientRequestId, pagingGetOdataMultiplePagesOptions, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// A paging operation that includes a nextLink that has 10 pages
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='pagingGetMultiplePagesWithOffsetOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='clientRequestId'>
/// </param>
public static IPage<Product> GetMultiplePagesWithOffset(this IPagingOperations operations, PagingGetMultiplePagesWithOffsetOptions pagingGetMultiplePagesWithOffsetOptions, string clientRequestId = default(string))
{
return operations.GetMultiplePagesWithOffsetAsync(pagingGetMultiplePagesWithOffsetOptions, clientRequestId).GetAwaiter().GetResult();
}
/// <summary>
/// A paging operation that includes a nextLink that has 10 pages
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='pagingGetMultiplePagesWithOffsetOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='clientRequestId'>
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<Product>> GetMultiplePagesWithOffsetAsync(this IPagingOperations operations, PagingGetMultiplePagesWithOffsetOptions pagingGetMultiplePagesWithOffsetOptions, string clientRequestId = default(string), CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetMultiplePagesWithOffsetWithHttpMessagesAsync(pagingGetMultiplePagesWithOffsetOptions, clientRequestId, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// A paging operation that fails on the first call with 500 and then retries
/// and then get a response including a nextLink that has 10 pages
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static IPage<Product> GetMultiplePagesRetryFirst(this IPagingOperations operations)
{
return operations.GetMultiplePagesRetryFirstAsync().GetAwaiter().GetResult();
}
/// <summary>
/// A paging operation that fails on the first call with 500 and then retries
/// and then get a response including a nextLink that has 10 pages
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<Product>> GetMultiplePagesRetryFirstAsync(this IPagingOperations operations, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetMultiplePagesRetryFirstWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// A paging operation that includes a nextLink that has 10 pages, of which the
/// 2nd call fails first with 500. The client should retry and finish all 10
/// pages eventually.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static IPage<Product> GetMultiplePagesRetrySecond(this IPagingOperations operations)
{
return operations.GetMultiplePagesRetrySecondAsync().GetAwaiter().GetResult();
}
/// <summary>
/// A paging operation that includes a nextLink that has 10 pages, of which the
/// 2nd call fails first with 500. The client should retry and finish all 10
/// pages eventually.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<Product>> GetMultiplePagesRetrySecondAsync(this IPagingOperations operations, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetMultiplePagesRetrySecondWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// A paging operation that receives a 400 on the first call
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static IPage<Product> GetSinglePagesFailure(this IPagingOperations operations)
{
return operations.GetSinglePagesFailureAsync().GetAwaiter().GetResult();
}
/// <summary>
/// A paging operation that receives a 400 on the first call
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<Product>> GetSinglePagesFailureAsync(this IPagingOperations operations, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetSinglePagesFailureWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// A paging operation that receives a 400 on the second call
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static IPage<Product> GetMultiplePagesFailure(this IPagingOperations operations)
{
return operations.GetMultiplePagesFailureAsync().GetAwaiter().GetResult();
}
/// <summary>
/// A paging operation that receives a 400 on the second call
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<Product>> GetMultiplePagesFailureAsync(this IPagingOperations operations, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetMultiplePagesFailureWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// A paging operation that receives an invalid nextLink
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static IPage<Product> GetMultiplePagesFailureUri(this IPagingOperations operations)
{
return operations.GetMultiplePagesFailureUriAsync().GetAwaiter().GetResult();
}
/// <summary>
/// A paging operation that receives an invalid nextLink
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<Product>> GetMultiplePagesFailureUriAsync(this IPagingOperations operations, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetMultiplePagesFailureUriWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// A paging operation that doesn't return a full URL, just a fragment
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='apiVersion'>
/// Sets the api version to use.
/// </param>
/// <param name='tenant'>
/// Sets the tenant to use.
/// </param>
public static IPage<Product> GetMultiplePagesFragmentNextLink(this IPagingOperations operations, string apiVersion, string tenant)
{
return operations.GetMultiplePagesFragmentNextLinkAsync(apiVersion, tenant).GetAwaiter().GetResult();
}
/// <summary>
/// A paging operation that doesn't return a full URL, just a fragment
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='apiVersion'>
/// Sets the api version to use.
/// </param>
/// <param name='tenant'>
/// Sets the tenant to use.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<Product>> GetMultiplePagesFragmentNextLinkAsync(this IPagingOperations operations, string apiVersion, string tenant, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetMultiplePagesFragmentNextLinkWithHttpMessagesAsync(apiVersion, tenant, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// A paging operation that doesn't return a full URL, just a fragment with
/// parameters grouped
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='customParameterGroup'>
/// Additional parameters for the operation
/// </param>
public static IPage<Product> GetMultiplePagesFragmentWithGroupingNextLink(this IPagingOperations operations, CustomParameterGroup customParameterGroup)
{
return operations.GetMultiplePagesFragmentWithGroupingNextLinkAsync(customParameterGroup).GetAwaiter().GetResult();
}
/// <summary>
/// A paging operation that doesn't return a full URL, just a fragment with
/// parameters grouped
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='customParameterGroup'>
/// Additional parameters for the operation
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<Product>> GetMultiplePagesFragmentWithGroupingNextLinkAsync(this IPagingOperations operations, CustomParameterGroup customParameterGroup, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetMultiplePagesFragmentWithGroupingNextLinkWithHttpMessagesAsync(customParameterGroup, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// A paging operation that doesn't return a full URL, just a fragment
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='apiVersion'>
/// Sets the api version to use.
/// </param>
/// <param name='tenant'>
/// Sets the tenant to use.
/// </param>
/// <param name='nextLink'>
/// Next link for list operation.
/// </param>
public static IPage<Product> NextFragment(this IPagingOperations operations, string apiVersion, string tenant, string nextLink)
{
return operations.NextFragmentAsync(apiVersion, tenant, nextLink).GetAwaiter().GetResult();
}
/// <summary>
/// A paging operation that doesn't return a full URL, just a fragment
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='apiVersion'>
/// Sets the api version to use.
/// </param>
/// <param name='tenant'>
/// Sets the tenant to use.
/// </param>
/// <param name='nextLink'>
/// Next link for list operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<Product>> NextFragmentAsync(this IPagingOperations operations, string apiVersion, string tenant, string nextLink, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.NextFragmentWithHttpMessagesAsync(apiVersion, tenant, nextLink, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// A paging operation that doesn't return a full URL, just a fragment
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextLink'>
/// Next link for list operation.
/// </param>
/// <param name='customParameterGroup'>
/// Additional parameters for the operation
/// </param>
public static IPage<Product> NextFragmentWithGrouping(this IPagingOperations operations, string nextLink, CustomParameterGroup customParameterGroup)
{
return operations.NextFragmentWithGroupingAsync(nextLink, customParameterGroup).GetAwaiter().GetResult();
}
/// <summary>
/// A paging operation that doesn't return a full URL, just a fragment
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextLink'>
/// Next link for list operation.
/// </param>
/// <param name='customParameterGroup'>
/// Additional parameters for the operation
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<Product>> NextFragmentWithGroupingAsync(this IPagingOperations operations, string nextLink, CustomParameterGroup customParameterGroup, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.NextFragmentWithGroupingWithHttpMessagesAsync(nextLink, customParameterGroup, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// A paging operation that finishes on the first call without a nextlink
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
public static IPage<Product> GetSinglePagesNext(this IPagingOperations operations, string nextPageLink)
{
return operations.GetSinglePagesNextAsync(nextPageLink).GetAwaiter().GetResult();
}
/// <summary>
/// A paging operation that finishes on the first call without a nextlink
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<Product>> GetSinglePagesNextAsync(this IPagingOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetSinglePagesNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// A paging operation that includes a nextLink that has 10 pages
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='clientRequestId'>
/// </param>
/// <param name='pagingGetMultiplePagesOptions'>
/// Additional parameters for the operation
/// </param>
public static IPage<Product> GetMultiplePagesNext(this IPagingOperations operations, string nextPageLink, string clientRequestId = default(string), PagingGetMultiplePagesOptions pagingGetMultiplePagesOptions = default(PagingGetMultiplePagesOptions))
{
return operations.GetMultiplePagesNextAsync(nextPageLink, clientRequestId, pagingGetMultiplePagesOptions).GetAwaiter().GetResult();
}
/// <summary>
/// A paging operation that includes a nextLink that has 10 pages
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='clientRequestId'>
/// </param>
/// <param name='pagingGetMultiplePagesOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<Product>> GetMultiplePagesNextAsync(this IPagingOperations operations, string nextPageLink, string clientRequestId = default(string), PagingGetMultiplePagesOptions pagingGetMultiplePagesOptions = default(PagingGetMultiplePagesOptions), CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetMultiplePagesNextWithHttpMessagesAsync(nextPageLink, clientRequestId, pagingGetMultiplePagesOptions, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// A paging operation that includes a nextLink in odata format that has 10
/// pages
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='clientRequestId'>
/// </param>
/// <param name='pagingGetOdataMultiplePagesOptions'>
/// Additional parameters for the operation
/// </param>
public static IPage<Product> GetOdataMultiplePagesNext(this IPagingOperations operations, string nextPageLink, string clientRequestId = default(string), PagingGetOdataMultiplePagesOptions pagingGetOdataMultiplePagesOptions = default(PagingGetOdataMultiplePagesOptions))
{
return operations.GetOdataMultiplePagesNextAsync(nextPageLink, clientRequestId, pagingGetOdataMultiplePagesOptions).GetAwaiter().GetResult();
}
/// <summary>
/// A paging operation that includes a nextLink in odata format that has 10
/// pages
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='clientRequestId'>
/// </param>
/// <param name='pagingGetOdataMultiplePagesOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<Product>> GetOdataMultiplePagesNextAsync(this IPagingOperations operations, string nextPageLink, string clientRequestId = default(string), PagingGetOdataMultiplePagesOptions pagingGetOdataMultiplePagesOptions = default(PagingGetOdataMultiplePagesOptions), CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetOdataMultiplePagesNextWithHttpMessagesAsync(nextPageLink, clientRequestId, pagingGetOdataMultiplePagesOptions, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// A paging operation that includes a nextLink that has 10 pages
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='clientRequestId'>
/// </param>
/// <param name='pagingGetMultiplePagesWithOffsetNextOptions'>
/// Additional parameters for the operation
/// </param>
public static IPage<Product> GetMultiplePagesWithOffsetNext(this IPagingOperations operations, string nextPageLink, string clientRequestId = default(string), PagingGetMultiplePagesWithOffsetNextOptions pagingGetMultiplePagesWithOffsetNextOptions = default(PagingGetMultiplePagesWithOffsetNextOptions))
{
return operations.GetMultiplePagesWithOffsetNextAsync(nextPageLink, clientRequestId, pagingGetMultiplePagesWithOffsetNextOptions).GetAwaiter().GetResult();
}
/// <summary>
/// A paging operation that includes a nextLink that has 10 pages
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='clientRequestId'>
/// </param>
/// <param name='pagingGetMultiplePagesWithOffsetNextOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<Product>> GetMultiplePagesWithOffsetNextAsync(this IPagingOperations operations, string nextPageLink, string clientRequestId = default(string), PagingGetMultiplePagesWithOffsetNextOptions pagingGetMultiplePagesWithOffsetNextOptions = default(PagingGetMultiplePagesWithOffsetNextOptions), CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetMultiplePagesWithOffsetNextWithHttpMessagesAsync(nextPageLink, clientRequestId, pagingGetMultiplePagesWithOffsetNextOptions, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// A paging operation that fails on the first call with 500 and then retries
/// and then get a response including a nextLink that has 10 pages
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
public static IPage<Product> GetMultiplePagesRetryFirstNext(this IPagingOperations operations, string nextPageLink)
{
return operations.GetMultiplePagesRetryFirstNextAsync(nextPageLink).GetAwaiter().GetResult();
}
/// <summary>
/// A paging operation that fails on the first call with 500 and then retries
/// and then get a response including a nextLink that has 10 pages
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<Product>> GetMultiplePagesRetryFirstNextAsync(this IPagingOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetMultiplePagesRetryFirstNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// A paging operation that includes a nextLink that has 10 pages, of which the
/// 2nd call fails first with 500. The client should retry and finish all 10
/// pages eventually.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
public static IPage<Product> GetMultiplePagesRetrySecondNext(this IPagingOperations operations, string nextPageLink)
{
return operations.GetMultiplePagesRetrySecondNextAsync(nextPageLink).GetAwaiter().GetResult();
}
/// <summary>
/// A paging operation that includes a nextLink that has 10 pages, of which the
/// 2nd call fails first with 500. The client should retry and finish all 10
/// pages eventually.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<Product>> GetMultiplePagesRetrySecondNextAsync(this IPagingOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetMultiplePagesRetrySecondNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// A paging operation that receives a 400 on the first call
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
public static IPage<Product> GetSinglePagesFailureNext(this IPagingOperations operations, string nextPageLink)
{
return operations.GetSinglePagesFailureNextAsync(nextPageLink).GetAwaiter().GetResult();
}
/// <summary>
/// A paging operation that receives a 400 on the first call
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<Product>> GetSinglePagesFailureNextAsync(this IPagingOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetSinglePagesFailureNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// A paging operation that receives a 400 on the second call
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
public static IPage<Product> GetMultiplePagesFailureNext(this IPagingOperations operations, string nextPageLink)
{
return operations.GetMultiplePagesFailureNextAsync(nextPageLink).GetAwaiter().GetResult();
}
/// <summary>
/// A paging operation that receives a 400 on the second call
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<Product>> GetMultiplePagesFailureNextAsync(this IPagingOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetMultiplePagesFailureNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// A paging operation that receives an invalid nextLink
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
public static IPage<Product> GetMultiplePagesFailureUriNext(this IPagingOperations operations, string nextPageLink)
{
return operations.GetMultiplePagesFailureUriNextAsync(nextPageLink).GetAwaiter().GetResult();
}
/// <summary>
/// A paging operation that receives an invalid nextLink
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<Product>> GetMultiplePagesFailureUriNextAsync(this IPagingOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetMultiplePagesFailureUriNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
}
}
| |
/// This code was generated by
/// \ / _ _ _| _ _
/// | (_)\/(_)(_|\/| |(/_ v1.0.0
/// / /
using System;
using System.Collections.Generic;
using System.Linq;
using Twilio.Base;
using Twilio.Converters;
namespace Twilio.Rest.IpMessaging.V1.Service
{
/// <summary>
/// FetchRoleOptions
/// </summary>
public class FetchRoleOptions : IOptions<RoleResource>
{
/// <summary>
/// The service_sid
/// </summary>
public string PathServiceSid { get; }
/// <summary>
/// The sid
/// </summary>
public string PathSid { get; }
/// <summary>
/// Construct a new FetchRoleOptions
/// </summary>
/// <param name="pathServiceSid"> The service_sid </param>
/// <param name="pathSid"> The sid </param>
public FetchRoleOptions(string pathServiceSid, string pathSid)
{
PathServiceSid = pathServiceSid;
PathSid = pathSid;
}
/// <summary>
/// Generate the necessary parameters
/// </summary>
public List<KeyValuePair<string, string>> GetParams()
{
var p = new List<KeyValuePair<string, string>>();
return p;
}
}
/// <summary>
/// DeleteRoleOptions
/// </summary>
public class DeleteRoleOptions : IOptions<RoleResource>
{
/// <summary>
/// The service_sid
/// </summary>
public string PathServiceSid { get; }
/// <summary>
/// The sid
/// </summary>
public string PathSid { get; }
/// <summary>
/// Construct a new DeleteRoleOptions
/// </summary>
/// <param name="pathServiceSid"> The service_sid </param>
/// <param name="pathSid"> The sid </param>
public DeleteRoleOptions(string pathServiceSid, string pathSid)
{
PathServiceSid = pathServiceSid;
PathSid = pathSid;
}
/// <summary>
/// Generate the necessary parameters
/// </summary>
public List<KeyValuePair<string, string>> GetParams()
{
var p = new List<KeyValuePair<string, string>>();
return p;
}
}
/// <summary>
/// CreateRoleOptions
/// </summary>
public class CreateRoleOptions : IOptions<RoleResource>
{
/// <summary>
/// The service_sid
/// </summary>
public string PathServiceSid { get; }
/// <summary>
/// The friendly_name
/// </summary>
public string FriendlyName { get; }
/// <summary>
/// The type
/// </summary>
public RoleResource.RoleTypeEnum Type { get; }
/// <summary>
/// The permission
/// </summary>
public List<string> Permission { get; }
/// <summary>
/// Construct a new CreateRoleOptions
/// </summary>
/// <param name="pathServiceSid"> The service_sid </param>
/// <param name="friendlyName"> The friendly_name </param>
/// <param name="type"> The type </param>
/// <param name="permission"> The permission </param>
public CreateRoleOptions(string pathServiceSid,
string friendlyName,
RoleResource.RoleTypeEnum type,
List<string> permission)
{
PathServiceSid = pathServiceSid;
FriendlyName = friendlyName;
Type = type;
Permission = permission;
}
/// <summary>
/// Generate the necessary parameters
/// </summary>
public List<KeyValuePair<string, string>> GetParams()
{
var p = new List<KeyValuePair<string, string>>();
if (FriendlyName != null)
{
p.Add(new KeyValuePair<string, string>("FriendlyName", FriendlyName));
}
if (Type != null)
{
p.Add(new KeyValuePair<string, string>("Type", Type.ToString()));
}
if (Permission != null)
{
p.AddRange(Permission.Select(prop => new KeyValuePair<string, string>("Permission", prop)));
}
return p;
}
}
/// <summary>
/// ReadRoleOptions
/// </summary>
public class ReadRoleOptions : ReadOptions<RoleResource>
{
/// <summary>
/// The service_sid
/// </summary>
public string PathServiceSid { get; }
/// <summary>
/// Construct a new ReadRoleOptions
/// </summary>
/// <param name="pathServiceSid"> The service_sid </param>
public ReadRoleOptions(string pathServiceSid)
{
PathServiceSid = pathServiceSid;
}
/// <summary>
/// Generate the necessary parameters
/// </summary>
public override List<KeyValuePair<string, string>> GetParams()
{
var p = new List<KeyValuePair<string, string>>();
if (PageSize != null)
{
p.Add(new KeyValuePair<string, string>("PageSize", PageSize.ToString()));
}
return p;
}
}
/// <summary>
/// UpdateRoleOptions
/// </summary>
public class UpdateRoleOptions : IOptions<RoleResource>
{
/// <summary>
/// The service_sid
/// </summary>
public string PathServiceSid { get; }
/// <summary>
/// The sid
/// </summary>
public string PathSid { get; }
/// <summary>
/// The permission
/// </summary>
public List<string> Permission { get; }
/// <summary>
/// Construct a new UpdateRoleOptions
/// </summary>
/// <param name="pathServiceSid"> The service_sid </param>
/// <param name="pathSid"> The sid </param>
/// <param name="permission"> The permission </param>
public UpdateRoleOptions(string pathServiceSid, string pathSid, List<string> permission)
{
PathServiceSid = pathServiceSid;
PathSid = pathSid;
Permission = permission;
}
/// <summary>
/// Generate the necessary parameters
/// </summary>
public List<KeyValuePair<string, string>> GetParams()
{
var p = new List<KeyValuePair<string, string>>();
if (Permission != null)
{
p.AddRange(Permission.Select(prop => new KeyValuePair<string, string>("Permission", prop)));
}
return p;
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Specialized;
using System.Diagnostics;
using System.IO;
using System.Text;
using System.Xml;
using nHydrate.Generator.Common.Util;
namespace nHydrate.Generator.Common.Logging
{
public class nHydrateLog
{
#region Constants
internal const string LOG_ERROR_SOURCE = "nHydrateLogger";
#endregion
#region Member Variables
private readonly string _exeName;
private static TraceSwitch _currentSwitch;
#endregion
#region Setup and Initilize
private nHydrateLog(string exeName)
{
_exeName = exeName;
_currentSwitch = new TraceSwitch("nHydrate", "nHydrate trace switch for " + exeName);
try
{
SetDefaults();
//InitializeConfigFile();
//mAppFileWatcher_Changed(this, new FileSystemEventArgs(WatcherChangeTypes.Changed, _appConfigFile.DirectoryName, _appConfigFile.Name));
}
catch (Exception ex)
{
LogLogFailure(ex.ToString());
}
}
private void SetDefaults()
{
_currentSwitch.Level = TraceLevel.Error;
var logFileFullPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "nHydrate\\" + _exeName + "nHydrate.log");
var logFile = new FileInfo(logFileFullPath);
AddListener("ExeDefaultListener", "System.Diagnostics.DefaultTraceListener", logFile.FullName);
}
#endregion
#region TraceStatements
private static void Log(TraceLevel level, string message)
{
string traceLevelString;
if (level == TraceLevel.Off)
{
traceLevelString = "Always";
traceLevelString = traceLevelString.PadRight(7);
}
else
{
traceLevelString = level.ToString();
traceLevelString = traceLevelString.PadRight(7);
}
var logString = String.Format("{0}:{1}: {2}", traceLevelString, DateTime.UtcNow.ToString("yyyyMMdd.HHmmss"), message);
Trace.WriteLine(logString);
}
private static void Log(TraceLevel level, string message, object arg1)
{
var logString = String.Format(message, arg1);
Log(level, logString);
}
private static void Log(TraceLevel level, string message, object arg1, object arg2)
{
var logString = String.Format(message, arg1, arg2);
Log(level, logString);
}
private static void Log(TraceLevel level, string message, object arg1, object arg2, object arg3)
{
var logString = String.Format(message, arg1, arg2, arg3);
Log(level, logString);
}
private static void Log(TraceLevel level, string message, object[] args)
{
var logString = String.Format(message, args);
Log(level, logString);
}
#endregion
#region LogAlways
public static void LogAlways(string message)
{
try
{
Log(TraceLevel.Off, message);
}
catch (Exception ex)
{
LogLogFailure(ex.ToString());
}
}
#endregion
#region LogError
public static void LogError(string message)
{
try
{
if (_currentSwitch.TraceError)
{
Log(TraceLevel.Error, message);
}
}
catch (Exception ex)
{
LogLogFailure(ex.ToString());
}
}
public static void LogError(string message, object arg1, object arg2)
{
try
{
if (_currentSwitch.TraceError)
{
Log(TraceLevel.Error, message, arg1, arg2);
}
}
catch (Exception ex)
{
LogLogFailure(ex.ToString());
}
}
public static void LogError(Exception ex)
{
try
{
LogError(ex.ToString());
}
catch (Exception ex2)
{
LogLogFailure(ex2.ToString());
}
}
public static void LogError(Exception ex, string error)
{
try
{
LogError("{0}\n{1}", error, ex.ToString());
}
catch (Exception ex2)
{
LogLogFailure(ex2.ToString());
}
}
#endregion
#region LogWarning
public static void LogWarning(string message)
{
try
{
if (_currentSwitch.TraceWarning)
{
Log(TraceLevel.Warning, message);
}
}
catch (Exception ex)
{
LogLogFailure(ex.ToString());
}
}
public static void LogWarning(Exception ex)
{
try
{
LogError(ex.ToString());
}
catch (Exception ex2)
{
LogLogFailure(ex2.ToString());
}
}
public static void LogWarning(Exception ex, string error)
{
try
{
LogError("{0}\n{1}", error, ex.ToString());
}
catch (Exception ex2)
{
LogLogFailure(ex2.ToString());
}
}
#endregion
#region LogInfo
public static void LogInfo(string message)
{
try
{
if (_currentSwitch.TraceInfo)
{
Log(TraceLevel.Info, message);
}
}
catch (Exception ex)
{
LogLogFailure(ex.ToString());
}
}
public static void LogInfo(string message, object arg1)
{
try
{
if (_currentSwitch.TraceInfo)
{
Log(TraceLevel.Info, message, arg1);
}
}
catch (Exception ex)
{
LogLogFailure(ex.ToString());
}
}
#endregion
#region LogVerbose
public static void LogVerbose(string message)
{
try
{
if (_currentSwitch.TraceVerbose)
{
Log(TraceLevel.Verbose, message);
}
}
catch (Exception ex)
{
LogLogFailure(ex.ToString());
}
}
public static void LogVerbose(string message, object arg1, object arg2, object arg3)
{
try
{
if (_currentSwitch.TraceVerbose)
{
Log(TraceLevel.Verbose, message, arg1, arg2, arg3);
}
}
catch (Exception ex)
{
LogLogFailure(ex.ToString());
}
}
#endregion
#region Log Log Failure
public static void LogLogFailure(string message)
{
try
{
var logName = "Application";
if (!EventLog.SourceExists(LOG_ERROR_SOURCE))
{
EventLog.CreateEventSource(LOG_ERROR_SOURCE, logName);
}
else
{
logName = EventLog.LogNameFromSourceName(LOG_ERROR_SOURCE, System.Environment.MachineName);
}
var applicationLog = new EventLog(logName);
applicationLog.Source = LOG_ERROR_SOURCE;
applicationLog.WriteEntry(message, EventLogEntryType.Warning);
}
catch (Exception ex)
{
//Do Nothing
}
}
#endregion
#region File System Watcher
private void AddListener(string listenerName, string typeString, string initializationData)
{
var newListener = CreateListener(listenerName, typeString, initializationData);
if (newListener != null)
Trace.Listeners.Add(newListener);
}
private TraceListener CreateListener(string listenerName, string typeString, string initializationData)
{
TraceListener retVal = null;
try
{
nHydrateLog.LogVerbose("CreateListener(string listenerName:{0}, string typeString:{1}, string initializationData:{2})", listenerName, typeString, initializationData);
if (typeString == ("System.Diagnostics.TextWriterTraceListener"))
{
retVal = new TextWriterTraceListener(initializationData);
}
else if (typeString == ("System.Diagnostics.EventLogTraceListener"))
{
retVal = new EventLogTraceListener(initializationData);
}
else if (typeString == "System.Diagnostics.DefaultTraceListener")
{
retVal = new System.Diagnostics.DefaultTraceListener();
}
else
{
var obj = Type.GetType(typeString);
if (obj != null)
retVal = (TraceListener)ReflectionHelper.CreateInstance(obj, new object[] { initializationData });
}
if (retVal != null)
{
retVal.Name = listenerName;
}
else
{
throw new nHydrate.Generator.Common.Exceptions.nHydrateException(String.Format("Could not create listener - listenerName:{0}- typeString:{1})", listenerName, typeString));
}
}
catch { }
return retVal;
}
#endregion
}
}
| |
#region Using declarations
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Input;
using System.Windows.Media;
using System.Xml.Serialization;
using NinjaTrader.Cbi;
using NinjaTrader.Gui;
using NinjaTrader.Gui.Chart;
using NinjaTrader.Gui.SuperDom;
using NinjaTrader.Gui.Tools;
using NinjaTrader.Data;
using NinjaTrader.NinjaScript;
using NinjaTrader.Core.FloatingPoint;
using NinjaTrader.NinjaScript.Indicators;
using NinjaTrader.NinjaScript.DrawingTools;
using System.Web.Script.Serialization;
using System.Net;
#endregion
//This namespace holds Strategies in this folder and is required. Do not change it.
namespace NinjaTrader.NinjaScript.Strategies
{
public class BreakingFrog : Strategy
{
private double frogUpper = -1;
private double frogLower = -1;
private double frogUpperLong = -1;
private double frogLowerShort = -1;
private int firstBarCountOfToday = 0;
private const string baseUrl = "http://127.0.0.1:8888/query?";
protected override void OnStateChange()
{
if (State == State.SetDefaults)
{
Description = @"Enter the description for your new custom Strategy here.";
Name = "BreakingFrog";
Calculate = Calculate.OnPriceChange;
EntriesPerDirection = 1;
EntryHandling = EntryHandling.AllEntries;
IsExitOnSessionCloseStrategy = true;
ExitOnSessionCloseSeconds = 30;
IsFillLimitOnTouch = false;
MaximumBarsLookBack = MaximumBarsLookBack.TwoHundredFiftySix;
OrderFillResolution = OrderFillResolution.Standard;
Slippage = 0;
StartBehavior = StartBehavior.WaitUntilFlat;
TimeInForce = TimeInForce.Gtc;
TraceOrders = true;
RealtimeErrorHandling = RealtimeErrorHandling.StopCancelClose;
StopTargetHandling = StopTargetHandling.PerEntryExecution;
BarsRequiredToTrade = 0;
// Disable this property for performance gains in Strategy Analyzer optimizations
// See the Help Guide for additional information
IsInstantiatedOnEachOptimizationIteration = false;
}
else if (State == State.Configure)
{
}
}
protected override void OnBarUpdate()
{
if(this.isValidBar())
{
this.updateFrogBoxPrice();
if (Close[0] > this.frogUpper)
{
this.EnterLongLimit(this.frogUpperLong, "frogBreak");
}
else if (Close[0] < this.frogLower)
{
this.EnterShortLimit(this.frogLowerShort, "frogBreak");
}
}
else
{
this.resetFrogBoxPrice();
}
}
private bool isValidBar()
{
this.updateFirstBarCountOfToday();
return CurrentBar - this.firstBarCountOfToday < 10;
}
private void updateFirstBarCountOfToday()
{
if (CurrentBar == 0 || Time[0].Date != Time[1].Date)
{
this.firstBarCountOfToday = CurrentBar;
}
}
private void updateFrogBoxPrice()
{
var currentOpen = CurrentDayOHL().CurrentOpen[0];
var frogInfo = getFrogModel();
this.frogUpper = currentOpen + frogInfo.hfb;
this.frogLower = currentOpen - frogInfo.hfb;
this.frogUpperLong = Math.Round(currentOpen + frogInfo.fb * 0.6, 2);
this.frogLowerShort = Math.Round(currentOpen - frogInfo.fb * 0.6, 2);
}
private void resetFrogBoxPrice()
{
this.frogUpper = -1;
this.frogLower = -1;
this.frogUpperLong = -1;
this.frogLowerShort = -1;
}
private FrogModel getFrogModel()
{
string url = baseUrl + String.Format("ticker={0}&date={1}", base.Instrument.FullName, Time[0].Date.ToString("yyyyMMdd"));
using (var client = new WebClient())
{
var json = client.DownloadString(url);
var serializer = new JavaScriptSerializer();
var model = serializer.Deserialize<FrogModel>(json);
return model;
}
}
public class FrogModel
{
public double rangestat {get;set;}
public double fb {get;set;}
public double hfb {get;set;}
public double lfb {get;set;}
public double sfb {get;set;}
}
}
}
| |
// 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.ObjectModel;
using System.Dynamic.Utils;
using System.Reflection;
using System.Runtime.CompilerServices;
namespace System.Linq.Expressions.Compiler
{
internal partial class StackSpiller
{
private abstract class BindingRewriter
{
protected readonly MemberBinding _binding;
protected readonly StackSpiller _spiller;
protected RewriteAction _action;
internal BindingRewriter(MemberBinding binding, StackSpiller spiller)
{
_binding = binding;
_spiller = spiller;
}
internal RewriteAction Action => _action;
internal abstract MemberBinding AsBinding();
internal abstract Expression AsExpression(Expression target);
internal static BindingRewriter Create(MemberBinding binding, StackSpiller spiller, Stack stack)
{
switch (binding.BindingType)
{
case MemberBindingType.Assignment:
MemberAssignment assign = (MemberAssignment)binding;
return new MemberAssignmentRewriter(assign, spiller, stack);
case MemberBindingType.ListBinding:
MemberListBinding list = (MemberListBinding)binding;
return new ListBindingRewriter(list, spiller, stack);
case MemberBindingType.MemberBinding:
MemberMemberBinding member = (MemberMemberBinding)binding;
return new MemberMemberBindingRewriter(member, spiller, stack);
}
throw Error.UnhandledBinding();
}
protected void RequireNoValueProperty()
{
var property = _binding.Member as PropertyInfo;
if (property != null && property.PropertyType.IsValueType)
{
throw Error.CannotAutoInitializeValueTypeMemberThroughProperty(property);
}
}
}
private sealed class MemberMemberBindingRewriter : BindingRewriter
{
private readonly ReadOnlyCollection<MemberBinding> _bindings;
private readonly BindingRewriter[] _bindingRewriters;
internal MemberMemberBindingRewriter(MemberMemberBinding binding, StackSpiller spiller, Stack stack) :
base(binding, spiller)
{
_bindings = binding.Bindings;
int count = _bindings.Count;
_bindingRewriters = new BindingRewriter[count];
for (int i = 0; i < count; i++)
{
BindingRewriter br = BindingRewriter.Create(_bindings[i], spiller, stack);
_action |= br.Action;
_bindingRewriters[i] = br;
}
}
internal override MemberBinding AsBinding()
{
switch (_action)
{
case RewriteAction.None:
return _binding;
case RewriteAction.Copy:
int count = _bindings.Count;
MemberBinding[] newBindings = new MemberBinding[count];
for (int i = 0; i < count; i++)
{
newBindings[i] = _bindingRewriters[i].AsBinding();
}
return new MemberMemberBinding(_binding.Member, new TrueReadOnlyCollection<MemberBinding>(newBindings));
}
throw ContractUtils.Unreachable;
}
internal override Expression AsExpression(Expression target)
{
RequireNoValueProperty();
Expression member = MemberExpression.Make(target, _binding.Member);
Expression memberTemp = _spiller.MakeTemp(member.Type);
int count = _bindings.Count;
Expression[] block = new Expression[count + 2];
block[0] = new AssignBinaryExpression(memberTemp, member);
for (int i = 0; i < count; i++)
{
BindingRewriter br = _bindingRewriters[i];
block[i + 1] = br.AsExpression(memberTemp);
}
// We need to copy back value types.
if (memberTemp.Type.IsValueType)
{
block[count + 1] = Expression.Block(
typeof(void),
new AssignBinaryExpression(MemberExpression.Make(target, _binding.Member), memberTemp)
);
}
else
{
block[count + 1] = Utils.Empty;
}
return MakeBlock(block);
}
}
private sealed class ListBindingRewriter : BindingRewriter
{
private readonly ReadOnlyCollection<ElementInit> _inits;
private readonly ChildRewriter[] _childRewriters;
internal ListBindingRewriter(MemberListBinding binding, StackSpiller spiller, Stack stack) :
base(binding, spiller)
{
_inits = binding.Initializers;
int count = _inits.Count;
_childRewriters = new ChildRewriter[count];
for (int i = 0; i < count; i++)
{
ElementInit init = _inits[i];
ChildRewriter cr = new ChildRewriter(spiller, stack, init.Arguments.Count);
cr.Add(init.Arguments);
_action |= cr.Action;
_childRewriters[i] = cr;
}
}
internal override MemberBinding AsBinding()
{
switch (_action)
{
case RewriteAction.None:
return _binding;
case RewriteAction.Copy:
int count = _inits.Count;
ElementInit[] newInits = new ElementInit[count];
for (int i = 0; i < count; i++)
{
ChildRewriter cr = _childRewriters[i];
if (cr.Action == RewriteAction.None)
{
newInits[i] = _inits[i];
}
else
{
newInits[i] = new ElementInit(_inits[i].AddMethod, new TrueReadOnlyCollection<Expression>(cr[0, -1]));
}
}
return new MemberListBinding(_binding.Member, new TrueReadOnlyCollection<ElementInit>(newInits));
}
throw ContractUtils.Unreachable;
}
internal override Expression AsExpression(Expression target)
{
RequireNoValueProperty();
Expression member = MemberExpression.Make(target, _binding.Member);
Expression memberTemp = _spiller.MakeTemp(member.Type);
int count = _inits.Count;
Expression[] block = new Expression[count + 2];
block[0] = new AssignBinaryExpression(memberTemp, member);
for (int i = 0; i < count; i++)
{
ChildRewriter cr = _childRewriters[i];
Result add = cr.Finish(new InstanceMethodCallExpressionN(_inits[i].AddMethod, memberTemp, cr[0, -1]));
block[i + 1] = add.Node;
}
// We need to copy back value types
if (memberTemp.Type.IsValueType)
{
block[count + 1] = Expression.Block(
typeof(void),
new AssignBinaryExpression(MemberExpression.Make(target, _binding.Member), memberTemp)
);
}
else
{
block[count + 1] = Utils.Empty;
}
return MakeBlock(block);
}
}
private sealed class MemberAssignmentRewriter : BindingRewriter
{
private readonly Expression _rhs;
internal MemberAssignmentRewriter(MemberAssignment binding, StackSpiller spiller, Stack stack) :
base(binding, spiller)
{
Result result = spiller.RewriteExpression(binding.Expression, stack);
_action = result.Action;
_rhs = result.Node;
}
internal override MemberBinding AsBinding() =>
_action switch
{
RewriteAction.None => _binding,
RewriteAction.Copy => new MemberAssignment(_binding.Member, _rhs),
_ => throw ContractUtils.Unreachable,
};
internal override Expression AsExpression(Expression target)
{
Expression member = MemberExpression.Make(target, _binding.Member);
Expression memberTemp = _spiller.MakeTemp(member.Type);
return MakeBlock(
new AssignBinaryExpression(memberTemp, _rhs),
new AssignBinaryExpression(member, memberTemp),
Utils.Empty
);
}
}
}
}
| |
#region -- License Terms --
//
// MessagePack for CLI
//
// Copyright (C) 2010-2012 FUJIWARA, Yusuke
//
// 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 -- License Terms --
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
#if !MSTEST
using NUnit.Framework;
#else
using TestFixtureAttribute = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestClassAttribute;
using TestAttribute = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestMethodAttribute;
using TimeoutAttribute = NUnit.Framework.TimeoutAttribute;
using Assert = NUnit.Framework.Assert;
using Is = NUnit.Framework.Is;
#endif
namespace MsgPack
{
[TestFixture]
public partial class UnpackingTest_Misc
{
[Test]
public void TestUnpackArrayLength_ArrayLengthIsGreaterThanInt32MaxValue()
{
var result = Unpacking.UnpackArrayLength( new byte[] { 0xDD, 0x80, 0x00, 0x00, 0x00, 0xFF } );
Assert.That( result.ReadCount, Is.EqualTo( 5 ) );
Assert.That( result.Value, Is.EqualTo( Int32.MaxValue + 1L ) );
}
[Test]
public void TestUnpackArray_ArrayLengthIsGreaterThanInt32MaxValue()
{
Assert.Throws<MessageNotSupportedException>( () => Unpacking.UnpackArray( new byte[] { 0xDD, 0x80, 0x00, 0x00, 0x00, 0xFF } ) );
}
[Test]
public void TestUnpackDictionaryCount_DictionaryCountIsGreaterThanInt32MaxValue()
{
var result = Unpacking.UnpackDictionaryCount( new byte[] { 0xDF, 0x80, 0x00, 0x00, 0x00, 0xFF } );
Assert.That( result.ReadCount, Is.EqualTo( 5 ) );
Assert.That( result.Value, Is.EqualTo( Int32.MaxValue + 1L ) );
}
[Test]
public void TestUnpackDictionary_DictionaryCountIsGreaterThanInt32MaxValue()
{
Assert.Throws<MessageNotSupportedException>( () => Unpacking.UnpackDictionary( new byte[] { 0xDF, 0x80, 0x00, 0x00, 0x00, 0xFF } ) );
}
[Test]
public void TestUnpackBinary_BinaryLengthIsGreaterThanInt32MaxValue()
{
Assert.Throws<MessageNotSupportedException>( () => Unpacking.UnpackBinary( new byte[] { 0xDB, 0x80, 0x00, 0x00, 0x00, 0xFF } ) );
}
[Test]
public void TestUnpackBinary_Stream_ReadOnlyStream()
{
using ( var stream = new WrapperStream( new MemoryStream(), canRead: false ) )
{
Assert.Throws<ArgumentException>( () => Unpacking.UnpackBinary( stream ) );
}
}
[Test]
public void TestUnpackString_ByteArray_Empty_AsIsAndBounded()
{
var result = Unpacking.UnpackString( new byte[] { 0xA0, 0xFF } );
Assert.That( result.ReadCount, Is.EqualTo( 1 ) );
Assert.That( result.Value, Is.EqualTo( String.Empty ) );
}
[Test]
public void TestUnpackString_ByteArray_1Char_AsIsAndBounded()
{
var result = Unpacking.UnpackString( new byte[] { 0xA1, ( byte )'A', 0xFF } );
Assert.That( result.ReadCount, Is.EqualTo( 2 ) );
Assert.That( result.Value, Is.EqualTo( "A" ) );
}
[Test]
public void TestUnpackString_ByteArray_1ByteNonUtf8String_ExceptionInReaderOperation()
{
Assert.Throws<MessageTypeException>( () => Unpacking.UnpackString( new byte[] { 0xA1, 0xFF } ) );
}
[Test]
public void TestUnpackString_ByteArray_Null()
{
Assert.Throws<ArgumentNullException>( () => Unpacking.UnpackString( default( byte[] ) ) );
}
[Test]
public void TestUnpackString_ByteArray_Encoding_Empty_AsIsAndBounded()
{
#if !NETFX_CORE && !SILVERLIGHT
var result = Unpacking.UnpackString( new byte[] { 0xA0, 0xFF }, Encoding.UTF32 );
#else
var result = Unpacking.UnpackString( new byte[] { 0xA0, 0xFF }, Encoding.UTF8 );
#endif // !NETFX_CORE && !SILVERLIGHT
Assert.That( result.ReadCount, Is.EqualTo( 1 ) );
Assert.That( result.Value, Is.EqualTo( String.Empty ) );
}
[Test]
public void TestUnpackString_ByteArray_Encoding_1Byte_AsIsAndBounded()
{
#if !NETFX_CORE && !SILVERLIGHT
var result = Unpacking.UnpackString( new byte[] { 0xA4, 0x00, 0x00, 0x00, ( byte )'A', 0xFF }, new UTF32Encoding( bigEndian: true, byteOrderMark: false, throwOnInvalidCharacters: true ) );
Assert.That( result.ReadCount, Is.EqualTo( 5 ) );
Assert.That( result.Value, Is.EqualTo( "A" ) );
#else
var result = Unpacking.UnpackString( new byte[] { 0xA2, 0x00, ( byte )'A', 0xFF }, new UnicodeEncoding( bigEndian: true, byteOrderMark: false, throwOnInvalidBytes: true ) );
Assert.That( result.ReadCount, Is.EqualTo( 3 ) );
Assert.That( result.Value, Is.EqualTo( "A" ) );
#endif // !NETFX_CORE && !SILVERLIGHT
}
[Test]
public void TestUnpackString_ByteArray_Encoding_1ByteNonSpecifiedString()
{
#if MONO || XAMDROID || UNITY
#warning TODO: Workaround
Assert.Inconclusive( "UTF32Encoding does not throw exception on Mono FCL." );
#elif !NETFX_CORE && !SILVERLIGHT
Assert.Throws<MessageTypeException>( () => Unpacking.UnpackString( new byte[] { 0xA4, 0x7F, 0x7F, 0x7F, 0x7F }, new UTF32Encoding( bigEndian: true, byteOrderMark: false, throwOnInvalidCharacters: true ) ) );
#else
Assert.Throws<MessageTypeException>( () => Unpacking.UnpackString( new byte[] { 0xA5, 0xF8, 0x88, 0x80, 0x80, 0x80 }, new UTF8Encoding( encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: true ) ) );
#endif
}
[Test]
public void TestUnpackString_ByteArray_ByteArrayIsNull()
{
Assert.Throws<ArgumentNullException>( () => Unpacking.UnpackString( default( byte[] ) ) );
}
[Test]
public void TestUnpackString_ByteArray_ByteArrayIsEmpty()
{
Assert.Throws<ArgumentException>( () => Unpacking.UnpackString( new byte[ 0 ] ) );
}
[Test]
public void TestUnpackString_ByteArray_Int32_ByteArrayIsNull()
{
Assert.Throws<ArgumentNullException>( () => Unpacking.UnpackString( null, 0 ) );
}
[Test]
public void TestUnpackString_ByteArray_Int32_ByteArrayIsEmpty()
{
Assert.Throws<ArgumentException>( () => Unpacking.UnpackString( new byte[ 0 ], 0 ) );
}
[Test]
public void TestUnpackString_ByteArray_Int32_OffsetIsTooBig()
{
Assert.Throws<ArgumentException>( () => Unpacking.UnpackString( new byte[] { 0x1 }, 1 ) );
}
[Test]
public void TestUnpackString_ByteArray_Int32_OffsetIsNegative()
{
Assert.Throws<ArgumentOutOfRangeException>( () => Unpacking.UnpackString( new byte[] { 0x1 }, -1 ) );
}
[Test]
public void TestUnpackString_ByteArray_Int32_Encoding_ByteArrayIsNull()
{
Assert.Throws<ArgumentNullException>( () => Unpacking.UnpackString( null, 0, Encoding.UTF8 ) );
}
[Test]
public void TestUnpackString_ByteArray_Int32_Encoding_ByteArrayIsEmpty()
{
Assert.Throws<ArgumentException>( () => Unpacking.UnpackString( new byte[ 0 ], 0, Encoding.UTF8 ) );
}
[Test]
public void TestUnpackString_ByteArray_Int32_Encoding_OffsetIsTooBig()
{
Assert.Throws<ArgumentException>( () => Unpacking.UnpackString( new byte[] { 0x1 }, 1, Encoding.UTF8 ) );
}
[Test]
public void TestUnpackString_ByteArray_Int32_Encoding_OffsetIsNegative()
{
Assert.Throws<ArgumentOutOfRangeException>( () => Unpacking.UnpackString( new byte[] { 0x1 }, -1, Encoding.UTF8 ) );
}
[Test]
public void TestUnpackString_ByteArray_Int32_Encoding_EncodingIsNull()
{
Assert.Throws<ArgumentNullException>( () => Unpacking.UnpackString( new byte[] { 0x1 }, 0, null ) );
}
[Test]
public void TestUnpackString_Stream_Empty_AsIsAndBounded()
{
using ( var stream = new MemoryStream( new byte[] { 0xA0, 0xFF } ) )
{
var result = Unpacking.UnpackString( stream );
Assert.That( stream.Position, Is.EqualTo( 1 ) );
Assert.That( result, Is.EqualTo( String.Empty ) );
}
}
[Test]
public void TestUnpackString_Stream_1Char_AsIsAndBounded()
{
using ( var stream = new MemoryStream( new byte[] { 0xA1, ( byte )'A', 0xFF } ) )
{
var result = Unpacking.UnpackString( stream );
Assert.That( stream.Position, Is.EqualTo( 2 ) );
Assert.That( result, Is.EqualTo( "A" ) );
}
}
[Test]
public void TestUnpackString_Stream_1ByteNonUtf8String()
{
using ( var stream = new MemoryStream( new byte[] { 0xA1, 0xFF } ) )
{
Assert.Throws<MessageTypeException>( () => Unpacking.UnpackString( stream ) );
}
}
[Test]
public void TestUnpackString_Stream_Null()
{
Assert.Throws<ArgumentNullException>( () => Unpacking.UnpackString( default( Stream ) ) );
}
[Test]
public void TestUnpackString_Stream_Encoding_Empty_AsIsAndBounded()
{
using ( var stream = new MemoryStream( new byte[] { 0xA0, 0xFF } ) )
{
#if !NETFX_CORE && !SILVERLIGHT
var result = Unpacking.UnpackString( stream, Encoding.UTF32 );
#else
var result = Unpacking.UnpackString( stream, Encoding.UTF8 );
#endif // !NETFX_CORE && !SILVERLIGHT
Assert.That( stream.Position, Is.EqualTo( 1 ) );
Assert.That( result, Is.EqualTo( String.Empty ) );
}
}
[Test]
public void TestUnpackString_Stream_Encoding_1Byte_AsIsAndBounded()
{
#if !NETFX_CORE && !SILVERLIGHT
using ( var stream = new MemoryStream( new byte[] { 0xA4, 0x00, 0x00, 0x00, ( byte )'A', 0xFF } ) )
{
var result = Unpacking.UnpackString( stream, new UTF32Encoding( bigEndian: true, byteOrderMark: false, throwOnInvalidCharacters: true ) );
Assert.That( stream.Position, Is.EqualTo( 5 ) );
Assert.That( result, Is.EqualTo( "A" ) );
}
#else
using ( var stream = new MemoryStream( new byte[] { 0xA2, 0x00, ( byte )'A', 0xFF } ) )
{
var result = Unpacking.UnpackString( stream, new UnicodeEncoding( bigEndian: true, byteOrderMark: false, throwOnInvalidBytes: true ) );
Assert.That( stream.Position, Is.EqualTo( 3 ) );
Assert.That( result, Is.EqualTo( "A" ) );
}
#endif // !NETFX_CORE && !SILVERLIGHT
}
[Test]
public void TestUnpackString_Stream_Encoding_1ByteNonSpecifiedString()
{
#if MONO || XAMDROID || UNITY
#warning TODO: Workaround
Assert.Inconclusive( "UTF32Encoding does not throw exception on Mono FCL." );
#endif
#if !NETFX_CORE && !SILVERLIGHT
using ( var stream = new MemoryStream( new byte[] { 0xA4, 0x7F, 0x7F, 0x7F, 0x7F } ) )
{
Assert.Throws<MessageTypeException>( () => Unpacking.UnpackString( stream, new UTF32Encoding( bigEndian: true, byteOrderMark: false, throwOnInvalidCharacters: true ) ) );
}
#else
using ( var stream = new MemoryStream( new byte[] { 0xA5, 0xF8, 0x88, 0x80, 0x80, 0x80 } ) )
{
Assert.Throws<MessageTypeException>( () => Unpacking.UnpackString( stream, new UTF8Encoding( encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: true ) ) );
}
#endif // !NETFX_CORE && !SILVERLIGHT
}
[Test]
public void TestUnpackString_Stream_Encoding_StreamIsNull()
{
Assert.Throws<ArgumentNullException>( () => Unpacking.UnpackString( default( Stream ), Encoding.UTF8 ) );
}
[Test]
public void TestUnpackString_Stream_Encoding_EncodingIsNull()
{
Assert.Throws<ArgumentNullException>( () => Unpacking.UnpackString( new MemoryStream( new byte[] { 0xA1, ( byte )'A' } ), null ) );
}
private static void AssertRawStream( Stream target, int length )
{
Assert.That( target, Is.Not.Null );
Assert.That( target.Length, Is.EqualTo( length ) );
byte[] buffer = new byte[ length ];
if ( length > 0 )
{
int readCount = target.Read( buffer, 0, length );
Assert.That( readCount, Is.EqualTo( length ) );
Assert.That( buffer, Is.All.EqualTo( 0xFF ) );
}
int readCountExtra = target.Read( buffer, 0, length );
Assert.That( readCountExtra, Is.EqualTo( 0 ) );
}
#if !NETFX_CORE && !SILVERLIGHT && !XAMARIN
[Test]
public void TestUnpackByteStream_Stream_LengthIsGreaterThanInt32MaxValue_CanReadToEnd()
{
// Header + Body Length ( Int32.MaxValue + 1 )
var bodyLength = Int32.MaxValue + 1L;
var length = 1L + 4L + bodyLength;
string filePath = Path.GetTempFileName();
try
{
File.SetAttributes( filePath, FileAttributes.SparseFile );
using ( var fileStream = new FileStream( filePath, FileMode.Open, FileAccess.ReadWrite, FileShare.None, 64 * 1024 ) )
{
fileStream.SetLength( length );
fileStream.Position = 0;
fileStream.Write( new byte[] { 0xDB, 0x80, 0x00, 0x00, 0x00 }, 0, 5 );
fileStream.Flush();
fileStream.Position = 0;
using ( var target = Unpacking.UnpackByteStream( fileStream ) )
{
Assert.That( target.Length, Is.EqualTo( bodyLength ) );
byte[] buffer = new byte[ 64 * 1024 ];
long totalLength = 0;
for ( int read = target.Read( buffer, 0, buffer.Length ); read > 0; read = target.Read( buffer, 0, buffer.Length ) )
{
totalLength += read;
}
Assert.That( totalLength, Is.EqualTo( bodyLength ) );
}
}
}
finally
{
File.Delete( filePath );
}
}
#endif // !NETFX_CORE && !SILVERLIGHT && !XAMARIN
[Test]
public void TestUnpackByteStream_Stream_Empty_AsIsAndBounded()
{
using ( var stream = new MemoryStream( new byte[] { 0xA0, 0x57 } ) )
{
using ( var result = Unpacking.UnpackByteStream( stream ) )
{
AssertRawStream( result, 0 );
}
// Assert is valid position on unerlying stream.
Assert.That( Unpacking.UnpackInt32( stream ), Is.EqualTo( 0x57 ) );
}
}
[Test]
public void TestUnpackByteStream_Stream_1Byte_AsIsAndBounded()
{
using ( var stream = new MemoryStream( new byte[] { 0xA1, 0xFF, 0x57 } ) )
{
using ( var result = Unpacking.UnpackByteStream( stream ) )
{
AssertRawStream( result, 1 );
}
// Assert is valid position on unerlying stream.
Assert.That( Unpacking.UnpackInt32( stream ), Is.EqualTo( 0x57 ) );
}
}
[Test]
public void TestUnpackByteStream_Stream_0x100Byte_AsIsAndBounded()
{
using ( var stream = new MemoryStream( new byte[] { 0xDA, 0x01, 0x00 }.Concat( Enumerable.Repeat( ( byte )0xFF, 0x100 ) ).Concat( Enumerable.Repeat( ( byte )0x57, 1 ) ).ToArray() ) )
{
using ( var result = Unpacking.UnpackByteStream( stream ) )
{
AssertRawStream( result, 0x100 );
}
// Assert is valid position on unerlying stream.
Assert.That( Unpacking.UnpackInt32( stream ), Is.EqualTo( 0x57 ) );
}
}
[Test]
public void TestUnpackByteStream_Stream_0x10000Byte_AsIsAndBounded()
{
using ( var stream = new MemoryStream( new byte[] { 0xDB, 0x00, 0x01, 0x00, 0x00 }.Concat( Enumerable.Repeat( ( byte )0xFF, 0x10000 ) ).Concat( Enumerable.Repeat( ( byte )0x57, 1 ) ).ToArray() ) )
{
using ( var result = Unpacking.UnpackByteStream( stream ) )
{
AssertRawStream( result, 0x10000 );
}
// Assert is valid position on unerlying stream.
Assert.That( Unpacking.UnpackInt32( stream ), Is.EqualTo( 0x57 ) );
}
}
[Test]
public void TestUnpackByteStream_Stream_SeekableStream_CanSeekIsTrue()
{
using ( var stream = new WrapperStream( new MemoryStream( new byte[] { 0xA0, 0x57 } ), canRead: true, canSeek: true ) )
{
using ( var result = Unpacking.UnpackByteStream( stream ) )
{
Assert.That( result.CanSeek, Is.True );
}
}
}
[Test]
public void TestUnpackByteStream_Stream_SeekableStream_CanSeekIsFalse()
{
using ( var stream = new WrapperStream( new MemoryStream( new byte[] { 0xA0, 0x57 } ), canRead: true, canSeek: false ) )
{
using ( var result = Unpacking.UnpackByteStream( stream ) )
{
Assert.That( result.CanSeek, Is.False );
}
}
}
[Test]
public void TestUnpackByteStream_Stream_Null()
{
Assert.Throws<ArgumentNullException>( () => Unpacking.UnpackByteStream( null ) );
}
private static void AssertStringReader( UnpackingStreamReader target, int byteLength, string expected )
{
Assert.That( target, Is.Not.Null );
Assert.That( target.ByteLength, Is.EqualTo( byteLength ) );
for ( int i = 0; i < expected.Length; i++ )
{
int c = target.Read();
Assert.That( c, Is.GreaterThanOrEqualTo( 0 ) );
Assert.That( ( char )c, Is.EqualTo( expected[ i ] ) );
}
Assert.That( target.EndOfStream, Is.True );
Assert.That( target.Read(), Is.EqualTo( -1 ) );
}
[Test]
public void TestUnpackCharStream_Stream_Empty_AsIsAndBounded()
{
using ( var stream = new MemoryStream( new byte[] { 0xA0, 0xFF } ) )
{
using ( var result = Unpacking.UnpackCharStream( stream ) )
{
AssertStringReader( result, 0, String.Empty );
}
// Assert is valid position on unerlying stream.
Assert.That( Unpacking.UnpackInt32( stream ), Is.EqualTo( -1 ) );
}
}
[Test]
public void TestUnpackCharStream_Stream_1Char_AsIsAndBounded()
{
using ( var stream = new MemoryStream( new byte[] { 0xA1, ( byte )'A', 0xFF } ) )
{
using ( var result = Unpacking.UnpackCharStream( stream ) )
{
AssertStringReader( result, 1, "A" );
}
// Assert is valid position on unerlying stream.
Assert.That( Unpacking.UnpackInt32( stream ), Is.EqualTo( -1 ) );
}
}
[Test]
public void TestUnpackCharStream_Stream_1ByteNonUtf8String_ExceptionInReaderOperation()
{
using ( var stream = new MemoryStream( new byte[] { 0xA1, 0xFF } ) )
{
using ( var result = Unpacking.UnpackCharStream( stream ) )
{
Assert.Throws<DecoderFallbackException>( () => result.Read() );
}
}
}
[Test]
public void TestUnpackCharStream_Stream_Null()
{
Assert.Throws<ArgumentNullException>( () => Unpacking.UnpackCharStream( null ) );
}
[Test]
public void TestUnpackCharStream_Stream_Encoding_Empty_AsIsAndBounded()
{
using ( var stream = new MemoryStream( new byte[] { 0xA0, 0xFF } ) )
{
#if !NETFX_CORE && !SILVERLIGHT
using ( var result = Unpacking.UnpackCharStream( stream, Encoding.UTF32 ) )
#else
using ( var result = Unpacking.UnpackCharStream( stream, Encoding.UTF8 ) )
#endif // !NETFX_CORE && !SILVERLIGHT
{
AssertStringReader( result, 0, String.Empty );
}
// Assert is valid position on unerlying stream.
Assert.That( Unpacking.UnpackInt32( stream ), Is.EqualTo( -1 ) );
}
}
[Test]
public void TestUnpackCharStream_Stream_Encoding_1Byte_AsIsAndBounded()
{
#if !NETFX_CORE && !SILVERLIGHT
using ( var stream = new MemoryStream( new byte[] { 0xA4, 0x00, 0x00, 0x00, ( byte )'A', 0xFF } ) )
#else
using ( var stream = new MemoryStream( new byte[] { 0xA2, 0x00, ( byte )'A', 0xFF } ) )
#endif // !NETFX_CORE && !SILVERLIGHT
{
#if !NETFX_CORE && !SILVERLIGHT
using ( var result = Unpacking.UnpackCharStream( stream, new UTF32Encoding( bigEndian: true, byteOrderMark: false, throwOnInvalidCharacters: true ) ) )
{
AssertStringReader( result, 4, "A" );
}
#else
using ( var result = Unpacking.UnpackCharStream( stream, new UnicodeEncoding( bigEndian: true, byteOrderMark: false, throwOnInvalidBytes: true ) ) )
{
AssertStringReader( result, 2, "A" );
}
#endif // !NETFX_CORE && !SILVERLIGHT
// Assert is valid position on unerlying stream.
Assert.That( Unpacking.UnpackInt32( stream ), Is.EqualTo( -1 ) );
}
}
[Test]
public void TestUnpackCharStream_Stream_Encoding_1ByteNonSpecifiedString_ExceptionInReaderOperation()
{
#if MONO || XAMDROID || UNITY
#warning TODO: Workaround
Assert.Inconclusive( "UTF32Encoding does not throw exception on Mono FCL." );
#endif
#if !NETFX_CORE && !SILVERLIGHT
using ( var stream = new MemoryStream( new byte[] { 0xA4, 0x7F, 0x7F, 0x7F, 0x7F } ) )
{
using ( var result = Unpacking.UnpackCharStream( stream, new UTF32Encoding( bigEndian: true, byteOrderMark: false, throwOnInvalidCharacters: true ) ) )
{
Assert.Throws<DecoderFallbackException>( () => result.Read() );
}
}
#else
using ( var stream = new MemoryStream( new byte[] { 0xA5, 0xF8, 0x88, 0x80, 0x80, 0x80 } ) )
{
using ( var result = Unpacking.UnpackCharStream( stream, new UTF8Encoding( encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: true ) ) )
{
Assert.Throws<DecoderFallbackException>( () => result.Read() );
}
}
#endif // !NETFX_CORE && !SILVERLIGHT
}
[Test]
public void TestUnpackCharStream_Stream_Encoding_StreamIsNull()
{
Assert.Throws<ArgumentNullException>( () => Unpacking.UnpackCharStream( null, Encoding.UTF8 ) );
}
[Test]
public void TestUnpackCharStream_Stream_Encoding_EncodingIsNull()
{
Assert.Throws<ArgumentNullException>( () => Unpacking.UnpackCharStream( new MemoryStream( new byte[] { 0xA1, ( byte )'A' } ), null ) );
}
[Test]
public void TestUnpackObject_ByteArray_Scalar_AsIs()
{
var result = Unpacking.UnpackObject( new byte[] { 0x1 } );
Assert.That( result.ReadCount, Is.EqualTo( 1 ) );
Assert.That( result.Value.Equals( 1 ) );
}
[Test]
public void TestUnpackObject_ByteArray_Int32_Scalar_AsIs()
{
var result = Unpacking.UnpackObject( new byte[] { 0xFF, 0x1, 0xFF }, 1 );
Assert.That( result.ReadCount, Is.EqualTo( 1 ) );
Assert.That( result.Value.Equals( 1 ) );
}
[Test]
public void TestUnpackObject_ByteArray_ByteArrayIsNull()
{
Assert.Throws<ArgumentNullException>( () => Unpacking.UnpackObject( default( byte[] ) ) );
}
[Test]
public void TestUnpackObject_ByteArray_ByteArrayIsEmpty()
{
Assert.Throws<ArgumentException>( () => Unpacking.UnpackObject( new byte[ 0 ] ) );
}
[Test]
public void TestUnpackObject_ByteArray_Int32_ByteArrayIsNull()
{
Assert.Throws<ArgumentNullException>( () => Unpacking.UnpackObject( null, 0 ) );
}
[Test]
public void TestUnpackObject_ByteArray_Int32_ByteArrayIsEmpty()
{
Assert.Throws<ArgumentException>( () => Unpacking.UnpackObject( new byte[ 0 ], 0 ) );
}
[Test]
public void TestUnpackObject_ByteArray_Int32_OffsetIsTooBig()
{
Assert.Throws<ArgumentException>( () => Unpacking.UnpackObject( new byte[] { 0x1 }, 1 ) );
}
[Test]
public void TestUnpackObject_ByteArray_Int32_OffsetIsNegative()
{
Assert.Throws<ArgumentOutOfRangeException>( () => Unpacking.UnpackObject( new byte[] { 0x1 }, -1 ) );
}
[Test]
public void TestUnpackObject_Stream_Scalar_AsIs()
{
using ( var stream = new MemoryStream( new byte[] { 0x1 } ) )
{
Assert.That( Unpacking.UnpackObject( stream ).Equals( 1 ) );
}
}
[Test]
public void TestUnpackObject_Stream_Nil_AsIs()
{
using ( var stream = new MemoryStream( new byte[] { 0xC0 } ) )
{
Assert.That( Unpacking.UnpackObject( stream ).IsNil );
}
}
[Test]
public void TestUnpackObject_Stream_EmptyArray_AsIs()
{
using ( var stream = new MemoryStream( new byte[] { 0x90 } ) )
{
var result = Unpacking.UnpackObject( stream );
Assert.That( result.IsArray, Is.True );
Assert.That( result.IsMap, Is.False );
Assert.That( result.IsRaw, Is.False );
Assert.That( result.AsList(), Is.Not.Null.And.Empty );
}
}
[Test]
public void TestUnpackObject_Stream_Array_AsIs()
{
using ( var stream = new MemoryStream( new byte[] { 0x91, 0x1 } ) )
{
var result = Unpacking.UnpackObject( stream );
Assert.That( result.IsArray, Is.True );
Assert.That( result.IsMap, Is.False );
Assert.That( result.IsRaw, Is.False );
Assert.That( result.AsList(), Is.Not.Null.And.Length.EqualTo( 1 ).And.All.EqualTo( new MessagePackObject( 1 ) ) );
}
}
[Test]
public void TestUnpackObject_Stream_EmptyMap_AsIs()
{
using ( var stream = new MemoryStream( new byte[] { 0x80 } ) )
{
var result = Unpacking.UnpackObject( stream );
Assert.That( result.IsArray, Is.False );
Assert.That( result.IsMap, Is.True );
Assert.That( result.IsRaw, Is.False );
Assert.That( result.AsDictionary(), Is.Not.Null.And.Empty );
}
}
[Test]
public void TestUnpackObject_Stream_Map_AsIs()
{
using ( var stream = new MemoryStream( new byte[] { 0x81, 0x1, 0x1 } ) )
{
var result = Unpacking.UnpackObject( stream );
Assert.That( result.IsArray, Is.False );
Assert.That( result.IsMap, Is.True );
Assert.That( result.IsRaw, Is.False );
Assert.That( result.AsDictionary(), Is.Not.Null.And.Count.EqualTo( 1 ).And.All.EqualTo( new KeyValuePair<MessagePackObject, MessagePackObject>( 1, 1 ) ) );
}
}
[Test]
public void TestUnpackObject_Stream_EmptyRaw_AsIs()
{
using ( var stream = new MemoryStream( new byte[] { 0xA0 } ) )
{
var result = Unpacking.UnpackObject( stream );
Assert.That( result.IsArray, Is.False );
Assert.That( result.IsMap, Is.False );
Assert.That( result.IsRaw, Is.True );
Assert.That( result.AsBinary(), Is.Not.Null.And.Empty );
Assert.That( result.AsString(), Is.Not.Null.And.Empty );
}
}
[Test]
public void TestUnpackObject_Stream_Raw_AsIs()
{
using ( var stream = new MemoryStream( new byte[] { 0xA1, ( byte )'A' } ) )
{
var result = Unpacking.UnpackObject( stream );
Assert.That( result.IsArray, Is.False );
Assert.That( result.IsMap, Is.False );
Assert.That( result.IsRaw, Is.True );
Assert.That( result.AsBinary(), Is.EqualTo( new byte[] { ( byte )'A' } ) );
Assert.That( result.AsString(), Is.EqualTo( "A" ) );
}
}
private static void AssertNested( IEnumerable<MessagePackObject> values )
{
var result = values.ToArray();
Assert.That( result.Length, Is.EqualTo( 6 ) );
Assert.That( result[ 0 ].AsList(), Is.Not.Null.And.Empty );
Assert.That( result[ 1 ].AsList(), Is.Not.Null.And.Length.EqualTo( 1 ).And.All.EqualTo( new MessagePackObject( 1 ) ) );
Assert.That( result[ 2 ].AsDictionary(), Is.Not.Null.And.Empty );
Assert.That( result[ 3 ].AsDictionary(), Is.Not.Null.And.Count.EqualTo( 1 ).And.All.EqualTo( new KeyValuePair<MessagePackObject, MessagePackObject>( 1, 1 ) ) );
Assert.That( result[ 4 ].AsString(), Is.Not.Null.And.Empty );
Assert.That( result[ 5 ].AsString(), Is.EqualTo( "A" ) );
}
[Test]
public void TestUnpackObject_Stream_NestedArray_AsIs()
{
using ( var stream = new MemoryStream( new byte[] { 0x96, 0x90, 0x91, 0x1, 0x80, 0x81, 0x1, 0x1, 0xA0, 0xA1, ( byte )'A' } ) )
{
var result = Unpacking.UnpackObject( stream );
AssertNested( result.AsList() );
}
}
[Test]
public void TestUnpackObject_Stream_NestedMap_AsIs()
{
using ( var stream = new MemoryStream( new byte[] { 0x86, 0x1, 0x90, 0x2, 0x91, 0x1, 0x3, 0x80, 0x4, 0x81, 0x1, 0x1, 0x5, 0xA0, 0x6, 0xA1, ( byte )'A' } ) )
{
var result = Unpacking.UnpackObject( stream );
var dictionary = result.AsDictionary();
Assert.That( dictionary, Is.Not.Null.And.Count.EqualTo( 6 ) );
AssertNested(
new MessagePackObject[]
{
dictionary [ 1 ],
dictionary [ 2 ],
dictionary [ 3 ],
dictionary [ 4 ],
dictionary [ 5 ],
dictionary [ 6 ]
}
);
}
}
[Test]
public void TestUnpackObject_Stream_Null()
{
Assert.Throws<ArgumentNullException>( () => Unpacking.UnpackObject( default( Stream ) ) );
}
// Edge cases
[Test]
public void TestUnpackInt32_NotNumeric()
{
Assert.Throws<MessageTypeException>( () => Unpacking.UnpackInt32( new byte[] { 0x80 } ) );
}
[Test]
public void TestUnpackInt32_Eof()
{
Assert.Throws<UnpackException>( () => Unpacking.UnpackInt32( new byte[] { 0xD0 } ) );
}
[Test]
public void TestUnpackDictionary_KeyDuplicated()
{
Assert.Throws<InvalidMessagePackStreamException>( () => Unpacking.UnpackDictionary( new byte[] { 0x82, 0x1, 0x0, 0x1, 0x0 } ) );
}
[Test]
public void TestUnpackArray_Eof()
{
Assert.Throws<UnpackException>( () => Unpacking.UnpackArray( new byte[] { 0x91 } ) );
}
[Test]
public void TestUnpackBinary_EofInHeader()
{
Assert.Throws<UnpackException>( () => Unpacking.UnpackBinary( new byte[] { 0xDA, 0x1 } ) );
}
[Test]
public void TestUnpackBinary_EofInBody()
{
Assert.Throws<UnpackException>( () => Unpacking.UnpackBinary( new byte[] { 0xA1 } ) );
}
[Test]
public void TestUnpackByteStream_Empty()
{
Assert.Throws<UnpackException>( () => Unpacking.UnpackByteStream( new MemoryStream() ) );
}
[Test]
public void TestUnpackByteStream_EofInHeader()
{
using ( var underlying = new MemoryStream( new byte[] { 0xDA, 0x1 } ) )
{
Assert.Throws<UnpackException>( () => Unpacking.UnpackByteStream( underlying ) );
}
}
[Test]
public void TestUnpackByteStream_EofInBody_CanFeed()
{
using ( var underlying = new MemoryStream() )
{
underlying.WriteByte( 0xA1 );
underlying.Position = 0;
var target = Unpacking.UnpackByteStream( underlying );
Assert.That( target.Length, Is.EqualTo( 1 ) );
// Check precondition
var b = target.ReadByte();
Assert.That( b, Is.EqualTo( -1 ) );
// Feed
// Assume that underlying supports Feed (appends bytes to tail, and does not move Position).
underlying.WriteByte( 0x57 );
underlying.Position -= 1;
b = target.ReadByte();
Assert.That( b, Is.EqualTo( 0x57 ) );
}
}
[Test]
public void TestUnpackByteStream_NotRaw()
{
Assert.Throws<MessageTypeException>( () => Unpacking.UnpackByteStream( new MemoryStream( new byte[] { 0x80 } ) ) );
}
[Test]
public void TestUnpackByteStream_Nil_AsEmpty()
{
var target = Unpacking.UnpackByteStream( new MemoryStream( new byte[] { 0xC0 } ) );
Assert.That( target, Is.Not.Null );
Assert.That( target.Length, Is.EqualTo( 0 ) );
}
private static Stream CreateStreamForByteStreamTest()
{
// Positin == Value
return Unpacking.UnpackByteStream( new MemoryStream( new byte[] { 0xA3, 0x0, 0x1, 0x2 } ) );
}
[Test]
public void TestUnpackBinaryResultStreamIsNotWriteable_CanWrite_False()
{
using ( var target = CreateStreamForByteStreamTest() )
{
Assert.IsFalse( target.CanWrite );
}
}
[Test]
public void TestUnpackBinaryResultStreamIsNotWriteable_Flush_Nop()
{
using ( var target = CreateStreamForByteStreamTest() )
{
target.Flush();
}
}
[Test]
public void TestUnpackBinaryResultStreamIsNotWriteable_Write_Fail()
{
using ( var target = CreateStreamForByteStreamTest() )
{
Assert.Throws<NotSupportedException>( () => target.Write( new byte[] { 0x0 }, 0, 1 ) );
}
}
[Test]
public void TestUnpackBinaryResultStreamIsNotWriteable_WriteByte_Fail()
{
using ( var target = CreateStreamForByteStreamTest() )
{
Assert.Throws<NotSupportedException>( () => target.WriteByte( 0 ) );
}
}
[Test]
public void TestUnpackBinaryResultStreamIsNotWriteable_SetLength_Fail()
{
using ( var target = CreateStreamForByteStreamTest() )
{
Assert.Throws<NotSupportedException>( () => target.SetLength( 1 ) );
}
}
private static void AssertStreamPosition( Stream target, int position )
{
// ReadByte() should return the value which equals to Position except tail.
AssertStreamPosition( target, position, position );
}
private static void AssertStreamPosition( Stream target, int position, int expectedValue )
{
Assert.That( target.Position, Is.EqualTo( position ) );
Assert.That( target.ReadByte(), Is.EqualTo( expectedValue ) );
}
[Test]
public void TestSeekableByteStream_Seek_0_Begin_Head()
{
using ( var target = CreateStreamForByteStreamTest() )
{
// Forward.
target.ReadByte();
target.Seek( 0, SeekOrigin.Begin );
AssertStreamPosition( target, 0 );
}
}
[Test]
public void TestSeekableByteStream_Seek_1_Begin_HeadPlus1()
{
using ( var target = CreateStreamForByteStreamTest() )
{
// Forward.
target.ReadByte();
target.Seek( 1, SeekOrigin.Begin );
AssertStreamPosition( target, 1 );
}
}
[Test]
public void TestSeekableByteStream_Seek_Minus1_Begin_Fail()
{
using ( var target = CreateStreamForByteStreamTest() )
{
// Forward.
target.ReadByte();
Assert.Throws<IOException>( () => target.Seek( -1, SeekOrigin.Begin ) );
}
}
[Test]
public void TestSeekableByteStream_setPosition_0_Head()
{
using ( var target = CreateStreamForByteStreamTest() )
{
// Forward.
target.ReadByte();
target.Position = 0;
AssertStreamPosition( target, 0 );
}
}
[Test]
public void TestSeekableByteStream_setPosition_1_HeadPlus1()
{
using ( var target = CreateStreamForByteStreamTest() )
{
// Forward.
target.ReadByte();
target.Position = 1;
AssertStreamPosition( target, 1 );
}
}
[Test]
public void TestSeekableByteStream_setPosition_Minus1_Fail()
{
using ( var target = CreateStreamForByteStreamTest() )
{
// Forward.
target.ReadByte();
Assert.Throws<IOException>( () => target.Position = -1 );
}
}
[Test]
public void TestSeekableByteStream_Seek_0_Current_DoesNotMove()
{
using ( var target = CreateStreamForByteStreamTest() )
{
// Forward.
target.ReadByte();
target.Seek( 0, SeekOrigin.Current );
AssertStreamPosition( target, 1 );
}
}
[Test]
public void TestSeekableByteStream_Seek_1_Current_Plus1()
{
using ( var target = CreateStreamForByteStreamTest() )
{
// Forward.
target.ReadByte();
target.Seek( 1, SeekOrigin.Current );
AssertStreamPosition( target, 2 );
}
}
[Test]
public void TestSeekableByteStream_Seek_Minus1_Current_Minus1()
{
using ( var target = CreateStreamForByteStreamTest() )
{
// Forward.
target.ReadByte();
target.Seek( -1, SeekOrigin.Current );
AssertStreamPosition( target, 0 );
}
}
[Test]
public void TestSeekableByteStream_Seek_0_End_Tail()
{
using ( var target = CreateStreamForByteStreamTest() )
{
// Forward.
target.ReadByte();
target.Seek( 0, SeekOrigin.End );
AssertStreamPosition( target, 3, -1 );
}
}
[Test]
public void TestSeekableByteStream_Seek_1_End_Fail()
{
using ( var target = CreateStreamForByteStreamTest() )
{
// Forward.
target.ReadByte();
Assert.Throws<NotSupportedException>( () => target.Seek( 1, SeekOrigin.End ) );
}
}
[Test]
public void TestSeekableByteStream_Seek_Minus1_End_TailMinus1()
{
using ( var target = CreateStreamForByteStreamTest() )
{
// Forward.
target.ReadByte();
target.Seek( -1, SeekOrigin.End );
AssertStreamPosition( target, 2 );
}
}
[Test]
public void TestUnseekableByteStream_Seek()
{
using ( var target = Unpacking.UnpackByteStream( new WrapperStream( new MemoryStream( new byte[] { 0xA1, 0xFF } ), canSeek: false ) ) )
{
Assert.Throws<NotSupportedException>( () => target.Seek( 0, SeekOrigin.Current ) );
}
}
[Test]
public void TestUnseekableByteStream_getPosition()
{
using ( var target = Unpacking.UnpackByteStream( new WrapperStream( new MemoryStream( new byte[] { 0xA1, 0xFF } ), canSeek: false ) ) )
{
Assert.Throws<NotSupportedException>( () => { var dummy = target.Position; } );
}
}
[Test]
public void TestUnseekableByteStream_setPosition()
{
using ( var target = Unpacking.UnpackByteStream( new WrapperStream( new MemoryStream( new byte[] { 0xA1, 0xFF } ), canSeek: false ) ) )
{
Assert.Throws<NotSupportedException>( () => target.Position = 0 );
}
}
private sealed class WrapperStream : Stream
{
private readonly Stream _underlying;
private bool _canRead;
private bool _canWrite;
private bool _canSeek;
public override bool CanRead
{
get { return this._canRead; }
}
public override bool CanWrite
{
get { return this._canWrite; }
}
public override bool CanSeek
{
get { return this._canSeek; }
}
public override long Position
{
get
{
VerifyState( this.CanSeek );
return this._underlying.Position;
}
set
{
VerifyState( this.CanSeek );
this._underlying.Position = value;
}
}
public override long Length
{
get
{
VerifyState( this.CanSeek );
return this._underlying.Length;
}
}
public WrapperStream( Stream stream, bool canRead = true, bool canWrite = true, bool canSeek = true )
{
this._underlying = stream;
this._canRead = canRead;
this._canWrite = canWrite;
this._canSeek = canSeek;
}
protected override void Dispose( bool disposing )
{
if ( disposing )
{
this._underlying.Dispose();
}
base.Dispose( disposing );
}
public override int Read( byte[] buffer, int offset, int count )
{
VerifyState( this.CanRead );
return this._underlying.Read( buffer, offset, count );
}
public override long Seek( long offset, SeekOrigin origin )
{
VerifyState( this.CanSeek );
return this._underlying.Seek( offset, origin );
}
public override void Write( byte[] buffer, int offset, int count )
{
VerifyState( this.CanWrite );
this._underlying.Write( buffer, offset, count );
}
public override void Flush()
{
this._underlying.Flush();
}
public override void SetLength( long length )
{
VerifyState( this.CanSeek );
VerifyState( this.CanWrite );
this._underlying.SetLength( length );
}
private static void VerifyState( bool precondition )
{
if ( !precondition )
{
throw new NotSupportedException();
}
}
}
}
}
| |
using log4net;
using Nini.Config;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Region.Physics.Manager;
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyrightD
* 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.Linq;
using System.Threading;
using Logging = OpenSim.Region.CoreModules.Framework.Statistics.Logging;
namespace OpenSim.Region.Physics.BulletSPlugin
{
public sealed class BSScene : PhysicsScene, IPhysicsParameters
{
internal static readonly ILog m_log = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
internal static readonly string LogHeader = "[BULLETS SCENE]";
// The name of the region we're working for.
public string RegionName { get; private set; }
public string BulletSimVersion = "?";
// The handle to the underlying managed or unmanaged version of Bullet being used.
public string BulletEngineName { get; private set; }
public BSAPITemplate PE;
// If the physics engine is running on a separate thread
public Thread m_physicsThread;
public ThreadedClasses.RwLockedDictionary<uint, BSPhysObject> PhysObjects;
public BSShapeCollection Shapes;
// Keeping track of the objects with collisions so we can report begin and end of a collision
public HashSet<BSPhysObject> ObjectsWithCollisions = new HashSet<BSPhysObject>();
public HashSet<BSPhysObject> ObjectsWithNoMoreCollisions = new HashSet<BSPhysObject>();
// All the collision processing is protected with this lock object
public Object CollisionLock = new Object();
// Properties are updated here
public Object UpdateLock = new Object();
public HashSet<BSPhysObject> ObjectsWithUpdates = new HashSet<BSPhysObject>();
// Keep track of all the avatars so we can send them a collision event
// every tick so OpenSim will update its animation.
private HashSet<BSPhysObject> m_avatars = new HashSet<BSPhysObject>();
private ReaderWriterLock m_avatarsRwLock = new ReaderWriterLock();
// let my minuions use my logger
public ILog Logger { get { return m_log; } }
public IMesher mesher;
public uint WorldID { get; private set; }
public BulletWorld World { get; private set; }
// All the constraints that have been allocated in this instance.
public BSConstraintCollection Constraints { get; private set; }
// Simulation parameters
//internal float m_physicsStepTime; // if running independently, the interval simulated by default
internal int m_maxSubSteps;
internal float m_fixedTimeStep;
internal float m_simulatedTime; // the time simulated previously. Used for physics framerate calc.
internal long m_simulationStep = 0; // The current simulation step.
public long SimulationStep { get { return m_simulationStep; } }
// A number to use for SimulationStep that is probably not any step value
// Used by the collision code (which remembers the step when a collision happens) to remember not any simulation step.
public static long NotASimulationStep = -1234;
internal float LastTimeStep { get; private set; } // The simulation time from the last invocation of Simulate()
internal float NominalFrameRate { get; set; } // Parameterized ideal frame rate that simulation is scaled to
// Physical objects can register for prestep or poststep events
public delegate void PreStepAction(float timeStep);
public delegate void PostStepAction(float timeStep);
public event PreStepAction BeforeStep;
public event PostStepAction AfterStep;
// A value of the time 'now' so all the collision and update routines do not have to get their own
// Set to 'now' just before all the prims and actors are called for collisions and updates
public int SimulationNowTime { get; private set; }
// True if initialized and ready to do simulation steps
private bool m_initialized = false;
// Flag which is true when processing taints.
// Not guaranteed to be correct all the time (don't depend on this) but good for debugging.
public bool InTaintTime { get; private set; }
// Pinned memory used to pass step information between managed and unmanaged
internal int m_maxCollisionsPerFrame;
internal CollisionDesc[] m_collisionArray;
internal int m_maxUpdatesPerFrame;
internal EntityProperties[] m_updateArray;
public const uint TERRAIN_ID = 0; // OpenSim senses terrain with a localID of zero
public const uint GROUNDPLANE_ID = 1;
public const uint CHILDTERRAIN_ID = 2; // Terrain allocated based on our mega-prim childre start here
public float SimpleWaterLevel { get; set; }
public BSTerrainManager TerrainManager { get; private set; }
public ConfigurationParameters Params
{
get { return UnmanagedParams[0]; }
}
public Vector3 DefaultGravity
{
get { return new Vector3(0f, 0f, Params.gravity); }
}
// Just the Z value of the gravity
public float DefaultGravityZ
{
get { return Params.gravity; }
}
// When functions in the unmanaged code must be called, it is only
// done at a known time just before the simulation step. The taint
// system saves all these function calls and executes them in
// order before the simulation.
public delegate void TaintCallback();
private struct TaintCallbackEntry
{
public String originator;
public String ident;
public TaintCallback callback;
public TaintCallbackEntry(string pIdent, TaintCallback pCallBack)
{
originator = BSScene.DetailLogZero;
ident = pIdent;
callback = pCallBack;
}
public TaintCallbackEntry(string pOrigin, string pIdent, TaintCallback pCallBack)
{
originator = pOrigin;
ident = pIdent;
callback = pCallBack;
}
}
private Object _taintLock = new Object(); // lock for using the next object
private List<TaintCallbackEntry> _taintOperations;
private Dictionary<string, TaintCallbackEntry> _postTaintOperations;
private List<TaintCallbackEntry> _postStepOperations;
// A pointer to an instance if this structure is passed to the C++ code
// Used to pass basic configuration values to the unmanaged code.
internal ConfigurationParameters[] UnmanagedParams;
// Sometimes you just have to log everything.
public Logging.LogWriter PhysicsLogging;
private bool m_physicsLoggingEnabled;
private string m_physicsLoggingDir;
private string m_physicsLoggingPrefix;
private int m_physicsLoggingFileMinutes;
private bool m_physicsLoggingDoFlush;
private bool m_physicsPhysicalDumpEnabled;
public int PhysicsMetricDumpFrames { get; set; }
// 'true' of the vehicle code is to log lots of details
public bool VehicleLoggingEnabled { get; private set; }
public bool VehiclePhysicalLoggingEnabled { get; private set; }
#region Construction and Initialization
public BSScene(string engineType, string identifier)
{
m_initialized = false;
// The name of the region we're working for is passed to us. Keep for identification.
RegionName = identifier;
// Set identifying variables in the PhysicsScene interface.
EngineType = engineType;
Name = EngineType + "/" + RegionName;
}
// Old version of initialization that assumes legacy sized regions (256x256)
public override void Initialise(IMesher meshmerizer, IConfigSource config)
{
m_log.ErrorFormat("{0} WARNING WARNING WARNING! BulletSim initialized without region extent specification. Terrain will be messed up.");
Vector3 regionExtent = new Vector3( Constants.RegionSize, Constants.RegionSize, Constants.RegionSize);
Initialise(meshmerizer, config, regionExtent);
}
public override void Initialise(IMesher meshmerizer, IConfigSource config, Vector3 regionExtent)
{
mesher = meshmerizer;
_taintOperations = new List<TaintCallbackEntry>();
_postTaintOperations = new Dictionary<string, TaintCallbackEntry>();
_postStepOperations = new List<TaintCallbackEntry>();
PhysObjects = new ThreadedClasses.RwLockedDictionary<uint, BSPhysObject>();
Shapes = new BSShapeCollection(this);
m_simulatedTime = 0f;
LastTimeStep = 0.1f;
// Allocate pinned memory to pass parameters.
UnmanagedParams = new ConfigurationParameters[1];
// Set default values for physics parameters plus any overrides from the ini file
GetInitialParameterValues(config);
// Force some parameters to values depending on other configurations
// Only use heightmap terrain implementation if terrain larger than legacy size
if ((uint)regionExtent.X > Constants.RegionSize || (uint)regionExtent.Y > Constants.RegionSize)
{
m_log.WarnFormat("{0} Forcing terrain implementation to heightmap for large region", LogHeader);
BSParam.TerrainImplementation = (float)BSTerrainPhys.TerrainImplementation.Heightmap;
}
// Get the connection to the physics engine (could be native or one of many DLLs)
PE = SelectUnderlyingBulletEngine(BulletEngineName);
// Enable very detailed logging.
// By creating an empty logger when not logging, the log message invocation code
// can be left in and every call doesn't have to check for null.
if (m_physicsLoggingEnabled)
{
PhysicsLogging = new Logging.LogWriter(m_physicsLoggingDir, m_physicsLoggingPrefix, m_physicsLoggingFileMinutes, m_physicsLoggingDoFlush);
PhysicsLogging.ErrorLogger = m_log; // for DEBUG. Let's the logger output its own error messages.
}
else
{
PhysicsLogging = new Logging.LogWriter();
}
// Allocate memory for returning of the updates and collisions from the physics engine
m_collisionArray = new CollisionDesc[m_maxCollisionsPerFrame];
m_updateArray = new EntityProperties[m_maxUpdatesPerFrame];
// The bounding box for the simulated world. The origin is 0,0,0 unless we're
// a child in a mega-region.
// Bullet actually doesn't care about the extents of the simulated
// area. It tracks active objects no matter where they are.
Vector3 worldExtent = regionExtent;
World = PE.Initialize(worldExtent, Params, m_maxCollisionsPerFrame, ref m_collisionArray, m_maxUpdatesPerFrame, ref m_updateArray);
Constraints = new BSConstraintCollection(World);
TerrainManager = new BSTerrainManager(this, worldExtent);
TerrainManager.CreateInitialGroundPlaneAndTerrain();
// Put some informational messages into the log file.
m_log.InfoFormat("{0} Linksets implemented with {1}", LogHeader, (BSLinkset.LinksetImplementation)BSParam.LinksetImplementation);
InTaintTime = false;
m_initialized = true;
// If the physics engine runs on its own thread, start same.
if (BSParam.UseSeparatePhysicsThread)
{
// The physics simulation should happen independently of the heartbeat loop
m_physicsThread = new Thread(BulletSPluginPhysicsThread);
m_physicsThread.Name = BulletEngineName;
m_physicsThread.Start();
}
}
// All default parameter values are set here. There should be no values set in the
// variable definitions.
private void GetInitialParameterValues(IConfigSource config)
{
ConfigurationParameters parms = new ConfigurationParameters();
UnmanagedParams[0] = parms;
BSParam.SetParameterDefaultValues(this);
if (config != null)
{
// If there are specifications in the ini file, use those values
IConfig pConfig = config.Configs["BulletSim"];
if (pConfig != null)
{
BSParam.SetParameterConfigurationValues(this, pConfig);
// There are two Bullet implementations to choose from
BulletEngineName = pConfig.GetString("BulletEngine", "BulletUnmanaged");
// Very detailed logging for physics debugging
// TODO: the boolean values can be moved to the normal parameter processing.
m_physicsLoggingEnabled = pConfig.GetBoolean("PhysicsLoggingEnabled", false);
m_physicsLoggingDir = pConfig.GetString("PhysicsLoggingDir", ".");
m_physicsLoggingPrefix = pConfig.GetString("PhysicsLoggingPrefix", "physics-%REGIONNAME%-");
m_physicsLoggingFileMinutes = pConfig.GetInt("PhysicsLoggingFileMinutes", 5);
m_physicsLoggingDoFlush = pConfig.GetBoolean("PhysicsLoggingDoFlush", false);
m_physicsPhysicalDumpEnabled = pConfig.GetBoolean("PhysicsPhysicalDumpEnabled", false);
// Very detailed logging for vehicle debugging
VehicleLoggingEnabled = pConfig.GetBoolean("VehicleLoggingEnabled", false);
VehiclePhysicalLoggingEnabled = pConfig.GetBoolean("VehiclePhysicalLoggingEnabled", false);
// Do any replacements in the parameters
m_physicsLoggingPrefix = m_physicsLoggingPrefix.Replace("%REGIONNAME%", RegionName);
}
else
{
// Nothing in the configuration INI file so assume unmanaged and other defaults.
BulletEngineName = "BulletUnmanaged";
m_physicsLoggingEnabled = false;
VehicleLoggingEnabled = false;
}
// The material characteristics.
BSMaterials.InitializeFromDefaults(Params);
if (pConfig != null)
{
// Let the user add new and interesting material property values.
BSMaterials.InitializefromParameters(pConfig);
}
}
}
// A helper function that handles a true/false parameter and returns the proper float number encoding
float ParamBoolean(IConfig config, string parmName, float deflt)
{
float ret = deflt;
if (config.Contains(parmName))
{
ret = ConfigurationParameters.numericFalse;
if (config.GetBoolean(parmName, false))
{
ret = ConfigurationParameters.numericTrue;
}
}
return ret;
}
// Select the connection to the actual Bullet implementation.
// The main engine selection is the engineName up to the first hypen.
// So "Bullet-2.80-OpenCL-Intel" specifies the 'bullet' class here and the whole name
// is passed to the engine to do its special selection, etc.
private BSAPITemplate SelectUnderlyingBulletEngine(string engineName)
{
// For the moment, do a simple switch statement.
// Someday do fancyness with looking up the interfaces in the assembly.
BSAPITemplate ret = null;
string selectionName = engineName.ToLower();
int hyphenIndex = engineName.IndexOf("-");
if (hyphenIndex > 0)
selectionName = engineName.ToLower().Substring(0, hyphenIndex - 1);
switch (selectionName)
{
case "bullet":
case "bulletunmanaged":
ret = new BSAPIUnman(engineName, this);
break;
case "bulletxna":
m_log.ErrorFormat("bulletxna removed to concentrate on a single BulletSim variant");
break;
}
if (ret == null)
{
m_log.ErrorFormat("{0) COULD NOT SELECT BULLET ENGINE: '[BulletSim]PhysicsEngine' must be either 'BulletUnmanaged-*'", LogHeader);
}
else
{
m_log.InfoFormat("{0} Selected bullet engine {1} -> {2}/{3}", LogHeader, engineName, ret.BulletEngineName, ret.BulletEngineVersion);
}
return ret;
}
public override void Dispose()
{
// m_log.DebugFormat("{0}: Dispose()", LogHeader);
// make sure no stepping happens while we're deleting stuff
m_initialized = false;
foreach (KeyValuePair<uint, BSPhysObject> kvp in PhysObjects)
{
kvp.Value.Destroy();
}
PhysObjects.Clear();
// Now that the prims are all cleaned up, there should be no constraints left
if (Constraints != null)
{
Constraints.Dispose();
Constraints = null;
}
if (Shapes != null)
{
Shapes.Dispose();
Shapes = null;
}
if (TerrainManager != null)
{
TerrainManager.ReleaseGroundPlaneAndTerrain();
TerrainManager.Dispose();
TerrainManager = null;
}
// Anything left in the unmanaged code should be cleaned out
PE.Shutdown(World);
// Not logging any more
PhysicsLogging.Close();
}
#endregion // Construction and Initialization
#region Prim and Avatar addition and removal
public override PhysicsActor AddAvatar(string avName, Vector3 position, Vector3 size, bool isFlying)
{
m_log.ErrorFormat("{0}: CALL TO AddAvatar in BSScene. NOT IMPLEMENTED", LogHeader);
return null;
}
public override PhysicsActor AddAvatar(uint localID, string avName, Vector3 position, Vector3 size, bool isFlying)
{
// m_log.DebugFormat("{0}: AddAvatar: {1}", LogHeader, avName);
if (!m_initialized) return null;
BSCharacter actor = new BSCharacter(localID, avName, this, position, size, isFlying);
PhysObjects.Add(localID, actor);
// TODO: Remove kludge someday.
// We must generate a collision for avatars whether they collide or not.
// This is required by OpenSim to update avatar animations, etc.
m_avatarsRwLock.AcquireWriterLock(-1);
try
{
m_avatars.Add(actor);
}
finally
{
m_avatarsRwLock.ReleaseWriterLock();
}
return actor;
}
public override void RemoveAvatar(PhysicsActor actor)
{
// m_log.DebugFormat("{0}: RemoveAvatar", LogHeader);
if (!m_initialized) return;
BSCharacter bsactor = actor as BSCharacter;
if (bsactor != null)
{
try
{
PhysObjects.Remove(bsactor.LocalID);
// Remove kludge someday
m_avatarsRwLock.AcquireWriterLock(-1);
try
{
m_avatars.Remove(bsactor);
}
finally
{
m_avatarsRwLock.ReleaseWriterLock();
}
}
catch (Exception e)
{
m_log.WarnFormat("{0}: Attempt to remove avatar that is not in physics scene: {1}", LogHeader, e);
}
bsactor.Destroy();
// bsactor.dispose();
}
else
{
m_log.ErrorFormat("{0}: Requested to remove avatar that is not a BSCharacter. ID={1}, type={2}",
LogHeader, actor.LocalID, actor.GetType().Name);
}
}
public override void RemovePrim(PhysicsActor prim)
{
if (!m_initialized) return;
BSPhysObject bsprim = prim as BSPhysObject;
if (bsprim != null)
{
DetailLog("{0},RemovePrim,call", bsprim.LocalID);
// m_log.DebugFormat("{0}: RemovePrim. id={1}/{2}", LogHeader, bsprim.Name, bsprim.LocalID);
try
{
PhysObjects.Remove(bsprim.LocalID);
}
catch (Exception e)
{
m_log.ErrorFormat("{0}: Attempt to remove prim that is not in physics scene: {1}", LogHeader, e);
}
bsprim.Destroy();
// bsprim.dispose();
}
else
{
m_log.ErrorFormat("{0}: Attempt to remove prim that is not a BSPrim type.", LogHeader);
}
}
public override PhysicsActor AddPrimShape(string primName, PrimitiveBaseShape pbs, Vector3 position,
Vector3 size, Quaternion rotation, bool isPhysical, uint localID)
{
// m_log.DebugFormat("{0}: AddPrimShape2: {1}", LogHeader, primName);
if (!m_initialized) return null;
// DetailLog("{0},BSScene.AddPrimShape,call", localID);
BSPhysObject prim = new BSPrimLinkable(localID, primName, this, position, size, rotation, pbs, isPhysical);
PhysObjects.Add(localID, prim);
return prim;
}
// This is a call from the simulator saying that some physical property has been updated.
// The BulletSim driver senses the changing of relevant properties so this taint
// information call is not needed.
public override void AddPhysicsActorTaint(PhysicsActor prim) { }
#endregion // Prim and Avatar addition and removal
#region Simulation
// Call from the simulator to send physics information to the simulator objects.
// This pushes all the collision and property update events into the objects in
// the simulator and, since it is on the heartbeat thread, there is an implicit
// locking of those data structures from other heartbeat events.
// If the physics engine is running on a separate thread, the update information
// will be in the ObjectsWithCollions and ObjectsWithUpdates structures.
public override float Simulate(float timeStep)
{
if (!BSParam.UseSeparatePhysicsThread)
{
DoPhysicsStep(timeStep);
}
return SendUpdatesToSimulator(timeStep);
}
// Call the physics engine to do one 'timeStep' and collect collisions and updates
// into ObjectsWithCollisions and ObjectsWithUpdates data structures.
private void DoPhysicsStep(float timeStep)
{
// prevent simulation until we've been initialized
if (!m_initialized) return;
LastTimeStep = timeStep;
int updatedEntityCount = 0;
int collidersCount = 0;
int beforeTime = Environment.TickCount;
int simTime = 0;
int numTaints = _taintOperations.Count;
InTaintTime = true; // Only used for debugging so locking is not necessary.
// update the prim states while we know the physics engine is not busy
ProcessTaints();
// Some of the physical objects requre individual, pre-step calls
// (vehicles and avatar movement, in particular)
TriggerPreStepEvent(timeStep);
// the prestep actions might have added taints
numTaints += _taintOperations.Count;
ProcessTaints();
InTaintTime = false; // Only used for debugging so locking is not necessary.
// The following causes the unmanaged code to output ALL the values found in ALL the objects in the world.
// Only enable this in a limited test world with few objects.
if (m_physicsPhysicalDumpEnabled)
PE.DumpAllInfo(World);
// step the physical world one interval
m_simulationStep++;
int numSubSteps = 0;
lock(CollisionLock)
{
try
{
numSubSteps = PE.PhysicsStep(World, timeStep, m_maxSubSteps, m_fixedTimeStep, out updatedEntityCount, out collidersCount);
}
catch (Exception e)
{
m_log.WarnFormat("{0},PhysicsStep Exception: nTaints={1}, substeps={2}, updates={3}, colliders={4}, e={5}",
LogHeader, numTaints, numSubSteps, updatedEntityCount, collidersCount, e);
DetailLog("{0},PhysicsStepException,call, nTaints={1}, substeps={2}, updates={3}, colliders={4}",
DetailLogZero, numTaints, numSubSteps, updatedEntityCount, collidersCount);
updatedEntityCount = 0;
collidersCount = 0;
}
// Make the physics engine dump useful statistics periodically
if (PhysicsMetricDumpFrames != 0 && ((m_simulationStep % PhysicsMetricDumpFrames) == 0))
PE.DumpPhysicsStatistics(World);
// Get a value for 'now' so all the collision and update routines don't have to get their own.
SimulationNowTime = Environment.TickCount;
// Send collision information to the colliding objects. The objects decide if the collision
// is 'real' (like linksets don't collide with themselves) and the individual objects
// know if the simulator has subscribed to collisions.
if (collidersCount > 0)
{
for (int ii = 0; ii < collidersCount; ii++)
{
uint cA = m_collisionArray[ii].aID;
uint cB = m_collisionArray[ii].bID;
Vector3 point = m_collisionArray[ii].point;
Vector3 normal = m_collisionArray[ii].normal;
float penetration = m_collisionArray[ii].penetration;
SendCollision(cA, cB, point, normal, penetration);
SendCollision(cB, cA, point, -normal, penetration);
}
}
}
// If any of the objects had updated properties, tell the managed objects about the update
// and remember that there was a change so it will be passed to the simulator.
lock (UpdateLock)
{
if (updatedEntityCount > 0)
{
for (int ii = 0; ii < updatedEntityCount; ii++)
{
EntityProperties entprop = m_updateArray[ii];
BSPhysObject pobj;
if (PhysObjects.TryGetValue(entprop.ID, out pobj))
{
if (pobj.IsInitialized)
pobj.UpdateProperties(entprop);
}
}
}
}
// Some actors want to know when the simulation step is complete.
TriggerPostStepEvent(timeStep);
simTime = Environment.TickCount - beforeTime;
if (PhysicsLogging.Enabled)
{
DetailLog("{0},DoPhysicsStep,complete,frame={1}, nTaints={2}, simTime={3}, substeps={4}, updates={5}, colliders={6}, objWColl={7}",
DetailLogZero, m_simulationStep, numTaints, simTime, numSubSteps,
updatedEntityCount, collidersCount, ObjectsWithCollisions.Count);
}
// The following causes the unmanaged code to output ALL the values found in ALL the objects in the world.
// Only enable this in a limited test world with few objects.
if (m_physicsPhysicalDumpEnabled)
PE.DumpAllInfo(World);
// The physics engine returns the number of milliseconds it simulated this call.
// These are summed and normalized to one second and divided by 1000 to give the reported physics FPS.
// Multiply by a fixed nominal frame rate to give a rate similar to the simulator (usually 55).
m_simulatedTime += (float)numSubSteps * m_fixedTimeStep * 1000f * NominalFrameRate;
}
// Called by a BSPhysObject to note that it has changed properties and this information
// should be passed up to the simulator at the proper time.
// Note: this is called by the BSPhysObject from invocation via DoPhysicsStep() above so
// this is is under UpdateLock.
public void PostUpdate(BSPhysObject updatee)
{
lock (UpdateLock)
{
ObjectsWithUpdates.Add(updatee);
}
}
// The simulator thinks it is physics time so return all the collisions and position
// updates that were collected in actual physics simulation.
private float SendUpdatesToSimulator(float timeStep)
{
if (!m_initialized) return 5.0f;
DetailLog("{0},SendUpdatesToSimulator,collisions={1},updates={2},simedTime={3}",
BSScene.DetailLogZero, ObjectsWithCollisions.Count, ObjectsWithUpdates.Count, m_simulatedTime);
// Push the collisions into the simulator.
lock (CollisionLock)
{
if (ObjectsWithCollisions.Count > 0)
{
foreach (BSPhysObject bsp in ObjectsWithCollisions)
if (!bsp.SendCollisions())
{
// If the object is done colliding, see that it's removed from the colliding list
ObjectsWithNoMoreCollisions.Add(bsp);
}
}
// This is a kludge to get avatar movement updates.
// The simulator expects collisions for avatars even if there are have been no collisions.
// The event updates avatar animations and stuff.
// If you fix avatar animation updates, remove this overhead and let normal collision processing happen.
m_avatarsRwLock.AcquireReaderLock(-1);
try
{
foreach (BSPhysObject bsp in m_avatars)
if (!ObjectsWithCollisions.Contains(bsp)) // don't call avatars twice
bsp.SendCollisions();
}
finally
{
m_avatarsRwLock.ReleaseReaderLock();
}
// Objects that are done colliding are removed from the ObjectsWithCollisions list.
// Not done above because it is inside an iteration of ObjectWithCollisions.
// This complex collision processing is required to create an empty collision
// event call after all real collisions have happened on an object. This allows
// the simulator to generate the 'collision end' event.
if (ObjectsWithNoMoreCollisions.Count > 0)
{
foreach (BSPhysObject po in ObjectsWithNoMoreCollisions)
ObjectsWithCollisions.Remove(po);
ObjectsWithNoMoreCollisions.Clear();
}
}
// Call the simulator for each object that has physics property updates.
HashSet<BSPhysObject> updatedObjects = null;
lock (UpdateLock)
{
if (ObjectsWithUpdates.Count > 0)
{
updatedObjects = ObjectsWithUpdates;
ObjectsWithUpdates = new HashSet<BSPhysObject>();
}
}
if (updatedObjects != null)
{
foreach (BSPhysObject obj in updatedObjects)
{
obj.RequestPhysicsterseUpdate();
}
updatedObjects.Clear();
}
// Return the framerate simulated to give the above returned results.
// (Race condition here but this is just bookkeeping so rare mistakes do not merit a lock).
float simTime = m_simulatedTime;
m_simulatedTime = 0f;
return simTime;
}
// Something has collided
private void SendCollision(uint localID, uint collidingWith, Vector3 collidePoint, Vector3 collideNormal, float penetration)
{
if (localID <= TerrainManager.HighestTerrainID)
{
return; // don't send collisions to the terrain
}
BSPhysObject collider;
if (!PhysObjects.TryGetValue(localID, out collider))
{
// If the object that is colliding cannot be found, just ignore the collision.
DetailLog("{0},BSScene.SendCollision,colliderNotInObjectList,id={1},with={2}", DetailLogZero, localID, collidingWith);
return;
}
// Note: the terrain is not in the physical object list so 'collidee' can be null when Collide() is called.
BSPhysObject collidee = null;
PhysObjects.TryGetValue(collidingWith, out collidee);
// DetailLog("{0},BSScene.SendCollision,collide,id={1},with={2}", DetailLogZero, localID, collidingWith);
if (collider.IsInitialized)
{
if (collider.Collide(collidingWith, collidee, collidePoint, collideNormal, penetration))
{
// If a collision was 'good', remember to send it to the simulator
lock (CollisionLock)
{
ObjectsWithCollisions.Add(collider);
}
}
}
return;
}
public void BulletSPluginPhysicsThread()
{
while (m_initialized)
{
int beginSimulationRealtimeMS = Environment.TickCount;
DoPhysicsStep(BSParam.PhysicsTimeStep);
int simulationRealtimeMS = Environment.TickCount - beginSimulationRealtimeMS;
int simulationTimeVsRealtimeDifferenceMS = ((int)(BSParam.PhysicsTimeStep*1000f)) - simulationRealtimeMS;
if (simulationTimeVsRealtimeDifferenceMS > 0)
{
// The simulation of the time interval took less than realtime.
// Do a sleep for the rest of realtime.
Thread.Sleep(simulationTimeVsRealtimeDifferenceMS);
}
else
{
// The simulation took longer than realtime.
// Do some scaling of simulation time.
// TODO.
DetailLog("{0},BulletSPluginPhysicsThread,longerThanRealtime={1}", BSScene.DetailLogZero, simulationTimeVsRealtimeDifferenceMS);
}
}
}
#endregion // Simulation
public override void GetResults() { }
#region Terrain
public override void SetTerrain(float[] heightMap) {
TerrainManager.SetTerrain(heightMap);
}
public override void SetWaterLevel(float baseheight)
{
SimpleWaterLevel = baseheight;
}
public override void DeleteTerrain()
{
// m_log.DebugFormat("{0}: DeleteTerrain()", LogHeader);
}
// Although no one seems to check this, I do support combining.
public override bool SupportsCombining()
{
return TerrainManager.SupportsCombining();
}
// This call says I am a child to region zero in a mega-region. 'pScene' is that
// of region zero, 'offset' is my offset from regions zero's origin, and
// 'extents' is the largest XY that is handled in my region.
public override void Combine(PhysicsScene pScene, Vector3 offset, Vector3 extents)
{
TerrainManager.Combine(pScene, offset, extents);
}
// Unhook all the combining that I know about.
public override void UnCombine(PhysicsScene pScene)
{
TerrainManager.UnCombine(pScene);
}
#endregion // Terrain
public override Dictionary<uint, float> GetTopColliders()
{
Dictionary<uint, float> topColliders;
PhysObjects.ForEach(delegate(BSPhysObject obj)
{
obj.ComputeCollisionScore();
});
List<BSPhysObject> orderedPrims = new List<BSPhysObject>(PhysObjects.Values);
orderedPrims.OrderByDescending(p => p.CollisionScore);
topColliders = orderedPrims.Take(25).ToDictionary(p => p.LocalID, p => p.CollisionScore);
return topColliders;
}
public override bool IsThreaded { get { return false; } }
#region Extensions
public override object Extension(string pFunct, params object[] pParams)
{
DetailLog("{0} BSScene.Extension,op={1}", DetailLogZero, pFunct);
return base.Extension(pFunct, pParams);
}
#endregion // Extensions
#region Taints
// The simulation execution order is:
// Simulate()
// DoOneTimeTaints
// TriggerPreStepEvent
// DoOneTimeTaints
// Step()
// ProcessAndSendToSimulatorCollisions
// ProcessAndSendToSimulatorPropertyUpdates
// TriggerPostStepEvent
// Calls to the PhysicsActors can't directly call into the physics engine
// because it might be busy. We delay changes to a known time.
// We rely on C#'s closure to save and restore the context for the delegate.
public void TaintedObject(string pOriginator, string pIdent, TaintCallback pCallback)
{
TaintedObject(false /*inTaintTime*/, pOriginator, pIdent, pCallback);
}
public void TaintedObject(uint pOriginator, String pIdent, TaintCallback pCallback)
{
TaintedObject(false /*inTaintTime*/, m_physicsLoggingEnabled ? pOriginator.ToString() : BSScene.DetailLogZero, pIdent, pCallback);
}
public void TaintedObject(bool inTaintTime, String pIdent, TaintCallback pCallback)
{
TaintedObject(inTaintTime, BSScene.DetailLogZero, pIdent, pCallback);
}
public void TaintedObject(bool inTaintTime, uint pOriginator, String pIdent, TaintCallback pCallback)
{
TaintedObject(inTaintTime, m_physicsLoggingEnabled ? pOriginator.ToString() : BSScene.DetailLogZero, pIdent, pCallback);
}
// Sometimes a potentially tainted operation can be used in and out of taint time.
// This routine executes the command immediately if in taint-time otherwise it is queued.
public void TaintedObject(bool inTaintTime, string pOriginator, string pIdent, TaintCallback pCallback)
{
if (!m_initialized) return;
if (inTaintTime)
pCallback();
else
{
lock (_taintLock)
{
_taintOperations.Add(new TaintCallbackEntry(pOriginator, pIdent, pCallback));
}
}
}
private void TriggerPreStepEvent(float timeStep)
{
PreStepAction actions = BeforeStep;
if (actions != null)
actions(timeStep);
}
private void TriggerPostStepEvent(float timeStep)
{
PostStepAction actions = AfterStep;
if (actions != null)
actions(timeStep);
}
// When someone tries to change a property on a BSPrim or BSCharacter, the object queues
// a callback into itself to do the actual property change. That callback is called
// here just before the physics engine is called to step the simulation.
public void ProcessTaints()
{
ProcessRegularTaints();
ProcessPostTaintTaints();
}
private void ProcessRegularTaints()
{
if (m_initialized && _taintOperations.Count > 0) // save allocating new list if there is nothing to process
{
// swizzle a new list into the list location so we can process what's there
List<TaintCallbackEntry> oldList;
lock (_taintLock)
{
oldList = _taintOperations;
_taintOperations = new List<TaintCallbackEntry>();
}
foreach (TaintCallbackEntry tcbe in oldList)
{
try
{
DetailLog("{0},BSScene.ProcessTaints,doTaint,id={1}", tcbe.originator, tcbe.ident); // DEBUG DEBUG DEBUG
tcbe.callback();
}
catch (Exception e)
{
m_log.ErrorFormat("{0}: ProcessTaints: {1}: Exception: {2}", LogHeader, tcbe.ident, e);
}
}
oldList.Clear();
}
}
// Schedule an update to happen after all the regular taints are processed.
// Note that new requests for the same operation ("ident") for the same object ("ID")
// will replace any previous operation by the same object.
public void PostTaintObject(String ident, uint ID, TaintCallback callback)
{
string IDAsString = ID.ToString();
string uniqueIdent = ident + "-" + IDAsString;
lock (_taintLock)
{
_postTaintOperations[uniqueIdent] = new TaintCallbackEntry(IDAsString, uniqueIdent, callback);
}
return;
}
// Taints that happen after the normal taint processing but before the simulation step.
private void ProcessPostTaintTaints()
{
if (m_initialized && _postTaintOperations.Count > 0)
{
Dictionary<string, TaintCallbackEntry> oldList;
lock (_taintLock)
{
oldList = _postTaintOperations;
_postTaintOperations = new Dictionary<string, TaintCallbackEntry>();
}
foreach (KeyValuePair<string,TaintCallbackEntry> kvp in oldList)
{
try
{
DetailLog("{0},BSScene.ProcessPostTaintTaints,doTaint,id={1}", DetailLogZero, kvp.Key); // DEBUG DEBUG DEBUG
kvp.Value.callback();
}
catch (Exception e)
{
m_log.ErrorFormat("{0}: ProcessPostTaintTaints: {1}: Exception: {2}", LogHeader, kvp.Key, e);
}
}
oldList.Clear();
}
}
// Only used for debugging. Does not change state of anything so locking is not necessary.
public bool AssertInTaintTime(string whereFrom)
{
if (!InTaintTime)
{
DetailLog("{0},BSScene.AssertInTaintTime,NOT IN TAINT TIME,Region={1},Where={2}", DetailLogZero, RegionName, whereFrom);
m_log.ErrorFormat("{0} NOT IN TAINT TIME!! Region={1}, Where={2}", LogHeader, RegionName, whereFrom);
// Util.PrintCallStack(DetailLog);
}
return InTaintTime;
}
#endregion // Taints
#region IPhysicsParameters
// Get the list of parameters this physics engine supports
public PhysParameterEntry[] GetParameterList()
{
BSParam.BuildParameterTable();
return BSParam.SettableParameters;
}
// Set parameter on a specific or all instances.
// Return 'false' if not able to set the parameter.
// Setting the value in the m_params block will change the value the physics engine
// will use the next time since it's pinned and shared memory.
// Some of the values require calling into the physics engine to get the new
// value activated ('terrainFriction' for instance).
public bool SetPhysicsParameter(string parm, string val, uint localID)
{
bool ret = false;
BSParam.ParameterDefnBase theParam;
if (BSParam.TryGetParameter(parm, out theParam))
{
// Set the value in the C# code
theParam.SetValue(this, val);
// Optionally set the parameter in the unmanaged code
if (theParam.HasSetOnObject)
{
// update all the localIDs specified
// If the local ID is APPLY_TO_NONE, just change the default value
// If the localID is APPLY_TO_ALL change the default value and apply the new value to all the lIDs
// If the localID is a specific object, apply the parameter change to only that object
List<uint> objectIDs = new List<uint>();
switch (localID)
{
case PhysParameterEntry.APPLY_TO_NONE:
// This will cause a call into the physical world if some operation is specified (SetOnObject).
objectIDs.Add(TERRAIN_ID);
TaintedUpdateParameter(parm, objectIDs, val);
break;
case PhysParameterEntry.APPLY_TO_ALL:
objectIDs = new List<uint>(PhysObjects.Keys);
TaintedUpdateParameter(parm, objectIDs, val);
break;
default:
// setting only one localID
objectIDs.Add(localID);
TaintedUpdateParameter(parm, objectIDs, val);
break;
}
}
ret = true;
}
return ret;
}
// schedule the actual updating of the paramter to when the phys engine is not busy
private void TaintedUpdateParameter(string parm, List<uint> lIDs, string val)
{
string xval = val;
List<uint> xlIDs = lIDs;
string xparm = parm;
TaintedObject(DetailLogZero, "BSScene.UpdateParameterSet", delegate() {
BSParam.ParameterDefnBase thisParam;
if (BSParam.TryGetParameter(xparm, out thisParam))
{
if (thisParam.HasSetOnObject)
{
foreach (uint lID in xlIDs)
{
BSPhysObject theObject = null;
if (PhysObjects.TryGetValue(lID, out theObject))
thisParam.SetOnObject(this, theObject);
}
}
}
});
}
// Get parameter.
// Return 'false' if not able to get the parameter.
public bool GetPhysicsParameter(string parm, out string value)
{
string val = String.Empty;
bool ret = false;
BSParam.ParameterDefnBase theParam;
if (BSParam.TryGetParameter(parm, out theParam))
{
val = theParam.GetValue(this);
ret = true;
}
value = val;
return ret;
}
#endregion IPhysicsParameters
// Invoke the detailed logger and output something if it's enabled.
public void DetailLog(string msg, params Object[] args)
{
PhysicsLogging.Write(msg, args);
}
// Used to fill in the LocalID when there isn't one. It's the correct number of characters.
public const string DetailLogZero = "0000000000";
}
}
| |
///<summary>
/// XsLiveAnimator is a component to bind Xsens MVN Studio stream to Unity3D Game Engine.
/// MVN Studio capable to stream 4 actors at the same time and this component makes the
/// connections between those actors and the characters in Unity3D.
///
/// Using the same settings on different characters will result of multiple characters are playing the same animation.
///
/// Relocation of the animation based on the start position of the character.
///
/// This component uses Macanim own animator to bind the bones with MVN avatar and the real model in Unity3D.
///
/// The animation applied on the pelvis as global position and rotation, while only the local rotation applied on each segments.
///</summary>
/// <version>
/// 1.0, 2013.04.11 by Attila Odry
/// </version>
///<remarks>
/// Copyright (c) 2013, Xsens Technologies B.V.
/// 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.
///
/// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
/// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
/// AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
/// BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
/// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
/// OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
/// STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
/// EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
///</remarks>
//todo turn on this feature once we send T-Pose in the first frame
//#define TPOSE_FIRST
using UnityEngine;
using System;
using System.Collections;
using System.Collections.Generic;
namespace xsens
{
/// <summary>
/// Xsens Live Animator.
///
/// This class provide the logic to read an actor pose from MVN Stream and
/// retarget the animation to a character.
/// </summary>
/// <remarks>
/// Attach this component to the character and bind the MvnActors with this object.
/// </remarks>
public class XsLiveAnimator : MonoBehaviour
{
public XsStreamReader mvnActors; //network streamer, which contains all 4 actor's poses
public int actorID = 1; //current actor ID, where 1 is the first streamed character from MVN
public bool applyRootMotion = true; //if true, position will be applied to the root (pelvis)
private Transform mvnActor; //reference for MVN Actor. This has the same layout as the streamed pose.
private Transform target; //Reference to the character in Unity3D.
private Transform origPos; //original position of the animation, this is the zero
private Transform[] targetModel; //Model holds each segments
private Transform[] currentPose; //animation applyed on skeleton. global position and rotation, used to represent a pose
private Quaternion[] modelRotTP; //T-Pose reference rotation on each segment
private Vector3[] modelPosTP; //T-Pose reference position on each segment
private Vector3 pelvisPosTP; //T-Pose's pos for the pelvis
private float scale = 0;
private GameObject missingSegments; //Empty object for not used segments
private Animator animator; //Animator object to get the Humanoid character mapping correct.
private Dictionary<XsAnimationSegment, HumanBodyBones> mecanimBones;
private bool isInited; //flag to check if the plugin was correctly intialized.
#if TPOSE_FIRST
private bool isFirstPose; //check if the first pose is passed
#endif
private bool isDebugFrame = false; //debug animation skeleton
/// <summary>
/// Contains the segment numbers for the animation
/// </summary>
public enum XsAnimationSegment
{
Pelvis = 0, //hips
RightUpperLeg = 1,
RightLowerLeg = 2,
RightFoot = 3,
RightToe = 4,
//--
LeftUpperLeg = 5,
LeftLowerLeg = 6,
LeftFoot = 7,
LeftToe = 8,
L5 = 9, //not used
L3 = 10, //spine
T12 = 11, //not used
T8 = 12, //chest
LeftShoulder = 13,
LeftUpperArm = 14,
LeftLowerArm = 15,
LeftHand = 16,
RightShoulder = 17,
RightUpperArm = 18,
RightLowerArm = 19,
RightHand = 20,
Neck = 21,
Head = 22
}
/// <summary>
/// The segment order.
/// </summary>
int[] segmentOrder =
{
(int)XsAnimationSegment.Pelvis,
(int)XsAnimationSegment.RightUpperLeg,
(int)XsAnimationSegment.RightLowerLeg,
(int)XsAnimationSegment.RightFoot,
(int)XsAnimationSegment.RightToe,
(int)XsAnimationSegment.LeftUpperLeg,
(int)XsAnimationSegment.LeftLowerLeg,
(int)XsAnimationSegment.LeftFoot,
(int)XsAnimationSegment.LeftToe,
(int)XsAnimationSegment.L5,
(int)XsAnimationSegment.L3,
(int)XsAnimationSegment.T12,
(int)XsAnimationSegment.T8,
(int)XsAnimationSegment.LeftShoulder,
(int)XsAnimationSegment.LeftUpperArm,
(int)XsAnimationSegment.LeftLowerArm,
(int)XsAnimationSegment.LeftHand,
(int)XsAnimationSegment.RightShoulder,
(int)XsAnimationSegment.RightUpperArm,
(int)XsAnimationSegment.RightLowerArm,
(int)XsAnimationSegment.RightHand,
(int)XsAnimationSegment.Neck,
(int)XsAnimationSegment.Head
};
/// <summary>
/// Maps the mecanim bones.
/// </summary>
protected void mapMecanimBones()
{
mecanimBones = new Dictionary<XsAnimationSegment, HumanBodyBones>();
mecanimBones.Add(XsAnimationSegment.Pelvis, HumanBodyBones.Hips);
mecanimBones.Add(XsAnimationSegment.LeftUpperLeg, HumanBodyBones.LeftUpperLeg);
mecanimBones.Add(XsAnimationSegment.LeftLowerLeg, HumanBodyBones.LeftLowerLeg);
mecanimBones.Add(XsAnimationSegment.LeftFoot, HumanBodyBones.LeftFoot);
mecanimBones.Add(XsAnimationSegment.LeftToe, HumanBodyBones.LeftToes);
mecanimBones.Add(XsAnimationSegment.RightUpperLeg, HumanBodyBones.RightUpperLeg);
mecanimBones.Add(XsAnimationSegment.RightLowerLeg, HumanBodyBones.RightLowerLeg);
mecanimBones.Add(XsAnimationSegment.RightFoot, HumanBodyBones.RightFoot);
mecanimBones.Add(XsAnimationSegment.RightToe, HumanBodyBones.RightToes);
mecanimBones.Add(XsAnimationSegment.L5, HumanBodyBones.LastBone); //not used
mecanimBones.Add(XsAnimationSegment.L3, HumanBodyBones.Spine);
mecanimBones.Add(XsAnimationSegment.T12, HumanBodyBones.LastBone); //not used
mecanimBones.Add(XsAnimationSegment.T8, HumanBodyBones.Chest);
mecanimBones.Add(XsAnimationSegment.LeftShoulder, HumanBodyBones.LeftShoulder);
mecanimBones.Add(XsAnimationSegment.LeftUpperArm, HumanBodyBones.LeftUpperArm);
mecanimBones.Add(XsAnimationSegment.LeftLowerArm, HumanBodyBones.LeftLowerArm);
mecanimBones.Add(XsAnimationSegment.LeftHand, HumanBodyBones.LeftHand);
mecanimBones.Add(XsAnimationSegment.RightShoulder, HumanBodyBones.RightShoulder);
mecanimBones.Add(XsAnimationSegment.RightUpperArm, HumanBodyBones.RightUpperArm);
mecanimBones.Add(XsAnimationSegment.RightLowerArm, HumanBodyBones.RightLowerArm);
mecanimBones.Add(XsAnimationSegment.RightHand, HumanBodyBones.RightHand);
mecanimBones.Add(XsAnimationSegment.Neck, HumanBodyBones.Neck);
mecanimBones.Add(XsAnimationSegment.Head, HumanBodyBones.Head);
}
/// <summary>
/// Awake this instance and initialize the live objects.
/// </summary>
void Awake()
{
isInited = false;
#if TPOSE_FIRST
isFirstPose = true;
#endif
//save start positions
target = gameObject.transform;
origPos = target;
//create an MvnActor
GameObject obj = (GameObject)Instantiate(Resources.Load("MvnActor"));
obj.transform.parent = gameObject.transform;
mvnActor = obj.transform;
if (mvnActor == null)
{
Debug.LogError("[xsens] No AnimationSkeleton found!");
return;
}
// Search for the network stream, so we can communicate with it.
if (mvnActors == null)
{
Debug.LogError("[xsens] No MvnActor found! You must assing an MvnActors to this component.");
return;
}
try
{
//setup arrays for pose's
targetModel = new Transform[XsMvnPose.MvnSegmentCount];
modelRotTP = new Quaternion[XsMvnPose.MvnSegmentCount];
modelPosTP = new Vector3[XsMvnPose.MvnSegmentCount];
currentPose = new Transform[XsMvnPose.MvnSegmentCount];
//add an empty object, which we can use for missing segments
missingSegments = new GameObject("MissingSegments");
missingSegments.transform.parent = gameObject.transform;
//map each bone with xsens bipad model and mecanim bones
mapMecanimBones();
//setup the animation and the model as well
if (!setupMvnActor())
{
Debug.Log("[xsens] failed to init MvnActor");
return;
}
if (!setupModel(target, targetModel))
{
Debug.Log("[xsens] failed to init the model");
return;
}
//face model to the right direction
//target.transform.rotation = transform.rotation;
isInited = true;
}
catch (Exception e)
{
print("[xsens] Something went wrong setting up.");
Debug.LogException(e);
}
}
/// <summary>
/// Setups the mvn actor, with binding the currentPose to the actor bones.
/// </summary>
/// <returns>
/// true on success
/// </returns>
public bool setupMvnActor()
{
mvnActor.rotation = transform.rotation;
mvnActor.position = transform.position;
currentPose[(int)XsAnimationSegment.Pelvis] = mvnActor.Find("Pelvis");
currentPose[(int)XsAnimationSegment.L5] = mvnActor.Find("Pelvis/L5");
currentPose[(int)XsAnimationSegment.L3] = mvnActor.Find("Pelvis/L5/L3");
currentPose[(int)XsAnimationSegment.T12] = mvnActor.Find("Pelvis/L5/L3/T12");
currentPose[(int)XsAnimationSegment.T8] = mvnActor.Find("Pelvis/L5/L3/T12/T8");
currentPose[(int)XsAnimationSegment.LeftShoulder] = mvnActor.Find("Pelvis/L5/L3/T12/T8/LeftShoulder");
currentPose[(int)XsAnimationSegment.LeftUpperArm] = mvnActor.Find("Pelvis/L5/L3/T12/T8/LeftShoulder/LeftUpperArm");
currentPose[(int)XsAnimationSegment.LeftLowerArm] = mvnActor.Find("Pelvis/L5/L3/T12/T8/LeftShoulder/LeftUpperArm/LeftLowerArm");
currentPose[(int)XsAnimationSegment.LeftHand] = mvnActor.Find("Pelvis/L5/L3/T12/T8/LeftShoulder/LeftUpperArm/LeftLowerArm/LeftHand");
currentPose[(int)XsAnimationSegment.Neck] = mvnActor.Find("Pelvis/L5/L3/T12/T8/Neck");
currentPose[(int)XsAnimationSegment.Head] = mvnActor.Find("Pelvis/L5/L3/T12/T8/Neck/Head");
currentPose[(int)XsAnimationSegment.RightShoulder] = mvnActor.Find("Pelvis/L5/L3/T12/T8/RightShoulder");
currentPose[(int)XsAnimationSegment.RightUpperArm] = mvnActor.Find("Pelvis/L5/L3/T12/T8/RightShoulder/RightUpperArm");
currentPose[(int)XsAnimationSegment.RightLowerArm] = mvnActor.Find("Pelvis/L5/L3/T12/T8/RightShoulder/RightUpperArm/RightLowerArm");
currentPose[(int)XsAnimationSegment.RightHand] = mvnActor.Find("Pelvis/L5/L3/T12/T8/RightShoulder/RightUpperArm/RightLowerArm/RightHand");
currentPose[(int)XsAnimationSegment.LeftUpperLeg] = mvnActor.Find("Pelvis/LeftUpperLeg");
currentPose[(int)XsAnimationSegment.LeftLowerLeg] = mvnActor.Find("Pelvis/LeftUpperLeg/LeftLowerLeg");
currentPose[(int)XsAnimationSegment.LeftFoot] = mvnActor.Find("Pelvis/LeftUpperLeg/LeftLowerLeg/LeftFoot");
currentPose[(int)XsAnimationSegment.LeftToe] = mvnActor.Find("Pelvis/LeftUpperLeg/LeftLowerLeg/LeftFoot/LeftToe");
currentPose[(int)XsAnimationSegment.RightUpperLeg] = mvnActor.Find("Pelvis/RightUpperLeg");
currentPose[(int)XsAnimationSegment.RightLowerLeg] = mvnActor.Find("Pelvis/RightUpperLeg/RightLowerLeg");
currentPose[(int)XsAnimationSegment.RightFoot] = mvnActor.Find("Pelvis/RightUpperLeg/RightLowerLeg/RightFoot");
currentPose[(int)XsAnimationSegment.RightToe] = mvnActor.Find("Pelvis/RightUpperLeg/RightLowerLeg/RightFoot/RightToe");
//reset pelvis TP
pelvisPosTP = currentPose[(int)XsAnimationSegment.Pelvis].position;
return true;
}
/// <summary>
/// Setups the model.
/// Bind the model with the animation.
/// This funciton will use Macanim animator to find the right bones,
/// then it will store it in an array by animation segment id
/// </summary>
/// <param name='model'>
/// Model.
/// </param>
/// <param name='modelRef'>
/// Model reference.
/// </param>
/// <returns>
/// true on success
/// </returns>
public bool setupModel(Transform model, Transform[] modelRef)
{
animator = model.GetComponent("Animator") as Animator;
if (!animator)
{
Debug.LogError("[xsens] No Animator component found for the model! You need to have an Animator attached to your model!");
return false;
}
//face the input model same as our animation
model.rotation = transform.rotation;
model.position = transform.position;
//go through the model's segments and store values
for (int i = 0; i < XsMvnPose.MvnSegmentCount; i++)
{
XsAnimationSegment segID = (XsAnimationSegment)segmentOrder[i];
HumanBodyBones boneID = mecanimBones[(XsAnimationSegment)segmentOrder[i]];
try
{
if (boneID == HumanBodyBones.LastBone)
{
//not used bones
modelRef[(int)segID] = null;
modelPosTP[(int)segID] = Vector3.zero;
modelRotTP[(int)segID] = Quaternion.Euler(Vector3.zero);
}
else
{
//used bones
modelRef[(int)segID] = animator.GetBoneTransform(boneID);
modelPosTP[(int)segID] = modelRef[(int)segID].position;
modelRotTP[(int)segID] = modelRef[(int)segID].rotation;
}
}
catch (Exception e)
{
Debug.Log("[xsens] Can't find " + boneID + " in the model! " + e);
modelRef[(int)segID] = null;
modelPosTP[(int)segID] = Vector3.zero;
modelRotTP[(int)segID] = Quaternion.Euler(Vector3.zero);
return false;
}
}
//calculate simple scale factor
scale = (float)(modelPosTP[(int)XsAnimationSegment.Pelvis].y / pelvisPosTP.y);
return true;
}
/// <summary>
/// Update the body segments in every frame.
///
/// The mvn actor's segment orientations and positions is read from the network,
/// using the MvnLiveActor component.
/// This component provides all data for the current pose for each actors.
/// </summary>
void Update()
{
//only do magic if we have everything ready
if (!isInited)
return;
Vector3[] latestPositions;
Quaternion[] latestOrientations;
// Get the pose data in one call, else the orientation might come from a different pose
// than the position
if (mvnActors.getLatestPose(actorID - 1, out latestPositions, out latestOrientations))
{
#if TPOSE_FIRST
if (isFirstPose)
{
//init the animation skeleton with the first pose
initSkeleton(currentPose, latestPositions, latestOrientations);
}
else
#endif
{
//update pose
updateMvnActor(currentPose, latestPositions, latestOrientations);
updateModel(currentPose, targetModel);
}
}
}
/// <summary>
/// Updates the actor skeleton local positions, based on the first valid pose
///
/// </summary>
/// <param name='model'>
/// Model.
/// </param>
/// <param name='positions'>
/// Positions.
/// </param>
protected void initSkeleton(Transform[] model, Vector3[] positions, Quaternion[] orientations)
{
//wait for real data
if (positions[(int)XsAnimationSegment.Pelvis] == Vector3.zero)
{
return;
}
//reposition the segments based on the data
#if TPOSE_FIRST
isFirstPose = false;
#endif
for (int i = 0; i < segmentOrder.Length; i++)
{
if (XsAnimationSegment.Pelvis == (XsAnimationSegment)segmentOrder[i])
{
//global for pelvis
model[segmentOrder[i]].transform.position = positions[segmentOrder[i]];
model[segmentOrder[i]].transform.rotation = orientations[segmentOrder[i]];
}
else
{
//local for segments
model[segmentOrder[i]].transform.localPosition = positions[segmentOrder[i]];
model[segmentOrder[i]].transform.localRotation = orientations[segmentOrder[i]];
}
}
//reinit the actor
setupMvnActor();
}
/// <summary>
/// Updates the mvn actor segment orientations and positions.
/// </summary>
/// <param name='model'>
/// Model to update.
/// </param>
/// <param name='positions'>
/// Positions in array
/// </param>
/// <param name='orientations'>
/// Orientations in array
/// </param>
private void updateMvnActor(Transform[] model, Vector3[] positions, Quaternion[] orientations)
{
try
{
for (int i = 0; i < segmentOrder.Length; i++) //front
{
if (XsAnimationSegment.Pelvis == (XsAnimationSegment)segmentOrder[i])
{
//we apply global position and orientaion to the pelvis
if (applyRootMotion)
{
model[segmentOrder[i]].transform.position = positions[segmentOrder[i]] + origPos.position;
}
model[segmentOrder[i]].transform.rotation = orientations[segmentOrder[i]];
}
else
{
//segment's data in local orientation (no position)
if (model[segmentOrder[i]] == null)
{
Debug.LogError("[xsens] XsLiveAnimator: Missing bone from mvn actor! Did you change MvnLive plugin? Please check if you are using the right actor!");
break;
}
model[segmentOrder[i]].transform.localRotation = orientations[segmentOrder[i]];
//draw wireframe for original animation
if (isDebugFrame)
{
Color color = new Color(1.0f, 0.0f, 0.0f, 1.0f);
int id = segmentOrder[i];
if (model[id - 1] != null)
{
if (((id - 1) != (int)XsAnimationSegment.LeftHand)
&& ((id - 1) != (int)XsAnimationSegment.RightHand)
&& ((id - 1) != (int)XsAnimationSegment.Head)
&& ((id - 1) != (int)XsAnimationSegment.LeftToe)
&& ((id - 1) != (int)XsAnimationSegment.RightToe))
{
Debug.DrawLine(model[id].position, model[id - 1].position, color);
}
}
}//isDebugFrame
}
}//for i
}
catch (Exception e)
{
Debug.LogException(e);
}
}
/// <summary>
/// Updates the model.
/// Evert pose contains the transform objects for each segments within the model.
/// </summary>
/// <param name='pose'>
/// Pose holds the positions and orientations of the actor.
/// </param>
/// <param name='model'>
/// Model to update with the pose.
/// </param>
private void updateModel(Transform[] pose, Transform[] model)
{
//reset the target, then set it based on segments
Vector3 pelvisPos = new Vector3();
Vector3 lastPos = target.position;
target.position = Vector3.zero;
for (int i = 0; i < XsMvnPose.MvnSegmentCount; i++)
{
switch (i)
{
//no update required
case (int)XsAnimationSegment.L5:
case (int)XsAnimationSegment.T12:
break;
case (int)XsAnimationSegment.Pelvis:
//position only on the y axis, leave the x,z to the body
pelvisPos = (pose[i].position * scale);
model[i].position = new Vector3(model[i].position.x, pelvisPos.y, model[i].position.z);
//we apply global position and orientaion to the pelvis
model[i].rotation = pose[i].rotation * modelRotTP[i];
break;
default:
//only update rotation for rest of the segments
if (model[i] != null)
{
model[i].rotation = pose[i].rotation * modelRotTP[i];
}
break;
}
}
//apply root motion if flag enabled only
if (applyRootMotion)
{
//only update x and z, pelvis is already modified by y
target.position = new Vector3(pelvisPos.x + pelvisPosTP.x, lastPos.y, pelvisPos.z + pelvisPosTP.z);
}
//set final rotation of the full body, but only position it to face similar as the pelvis
Quaternion q = Quaternion.Inverse(modelRotTP[(int)XsAnimationSegment.Pelvis]) * model[(int)XsAnimationSegment.Pelvis].rotation;
target.rotation = new Quaternion(target.rotation.x, q.y, target.rotation.z, target.rotation.w);
}
}//class XsLiveAnimator
}//namespace Xsens
| |
// <copyright file=Logger.cs
// <copyright>
// Copyright (c) 2016, University of Stuttgart
// 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>
// <license>MIT License</license>
// <main contributors>
// Markus Funk, Thomas Kosch, Sven Mayer
// </main contributors>
// <co-contributors>
// Paul Brombosch, Mai El-Komy, Juana Heusler,
// Matthias Hoppe, Robert Konrad, Alexander Martin
// </co-contributors>
// <patent information>
// We are aware that this software implements patterns and ideas,
// which might be protected by patents in your country.
// Example patents in Germany are:
// Patent reference number: DE 103 20 557.8
// Patent reference number: DE 10 2013 220 107.9
// Please make sure when using this software not to violate any existing patents in your country.
// </patent information>
// <date> 11/2/2016 12:25:58 PM</date>
using System;
using System.Collections.ObjectModel;
using System.IO;
using motionEAPAdmin.GUI;
namespace motionEAPAdmin.Backend
{
/// <summary>
/// Some sort of Logger
/// </summary>
///
///
public class Logger
{
public enum LoggerState
{
INFORMATION = 0,
WARNING = 1,
ERROR = 2,
CRITICAL = 3
}
private static Logger m_Instance;
private StreamWriter m_Writer;
private AdminView m_ViewHandle;
private string m_ErrorImagePath = "Resources\\Erroricon.png";
private string m_WarningImagePath = "Resources\\Warningicon.png";
private string m_InformationImagePath = "Resources\\Informationicon.png";
private string m_CriticalImagePath = "Resources\\Criticalicon.png";
private ObservableCollection<LogMessage> m_AllLogsList = new ObservableCollection<LogMessage>();
private ObservableCollection<LogMessage> m_FilteredLogsList = new ObservableCollection<LogMessage>();
private bool m_Informations = true;
private bool m_Warnings = true;
private bool m_Errors = true;
private bool m_Criticals = true;
public ObservableCollection<LogMessage> Rows
{
get { return m_FilteredLogsList; }
set { m_FilteredLogsList = value; }
}
public bool Informations
{
get
{
return m_Informations;
}
set
{
m_Informations = value;
}
}
public bool Warnings
{
get
{
return m_Warnings;
}
set
{
m_Warnings = value;
}
}
public bool Errors
{
get
{
return m_Errors;
}
set
{
m_Errors = value;
}
}
public bool Criticals
{
get
{
return m_Criticals;
}
set
{
m_Criticals = value;
}
}
private Logger()
{
m_Writer = File.AppendText("log.txt");
}
public static Logger Instance
{
get
{
if (m_Instance == null)
{
m_Instance = new Logger();
}
return m_Instance;
}
}
public AdminView ViewHandle
{
set
{
this.m_ViewHandle = value;
}
}
private void addImageAccordingToErrorLevel(LoggerState errorLevel, LogMessage @log)
{
if (errorLevel == LoggerState.INFORMATION)
{
string full = Path.GetFullPath(m_InformationImagePath);
log.Image = full;
}
if (errorLevel == LoggerState.WARNING)
{
string full = Path.GetFullPath(m_WarningImagePath);
log.Image = full;
}
if (errorLevel == LoggerState.ERROR)
{
string full = Path.GetFullPath(m_ErrorImagePath);
log.Image = full;
}
if (errorLevel == LoggerState.CRITICAL)
{
string full = Path.GetFullPath(m_CriticalImagePath);
log.Image = full;
}
}
public void applyFilter()
{
if (m_ViewHandle != null)
{
m_ViewHandle.Dispatcher.Invoke((Action)(() =>
{
m_FilteredLogsList.Clear();
foreach (LogMessage log in m_AllLogsList)
{
if (m_Informations && (log.ErrorLevel == LoggerState.INFORMATION))
{
m_FilteredLogsList.Add(log);
}
if (m_Warnings && (log.ErrorLevel == LoggerState.WARNING))
{
m_FilteredLogsList.Add(log);
}
if (m_Errors && (log.ErrorLevel == LoggerState.ERROR))
{
m_FilteredLogsList.Add(log);
}
if (m_Criticals && (log.ErrorLevel == LoggerState.CRITICAL))
{
m_FilteredLogsList.Add(log);
}
}
}));
}
}
public void applyTextFilter(String toFilter)
{
// in chase the filter textbox is empty you can restore the list
if(toFilter.Equals(""))
{
m_FilteredLogsList.Clear();
foreach(LogMessage log in m_AllLogsList)
{
if (m_Informations && (log.ErrorLevel == LoggerState.INFORMATION))
{
m_FilteredLogsList.Add(log);
}
if (m_Warnings && (log.ErrorLevel == LoggerState.WARNING))
{
m_FilteredLogsList.Add(log);
}
if (m_Errors && (log.ErrorLevel == LoggerState.ERROR))
{
m_FilteredLogsList.Add(log);
}
if (m_Criticals && (log.ErrorLevel == LoggerState.CRITICAL))
{
m_FilteredLogsList.Add(log);
}
}
}
else
{
m_FilteredLogsList.Clear();
foreach (LogMessage log in m_AllLogsList)
{
if (m_Informations && (log.ErrorLevel == LoggerState.INFORMATION) && log.Message.Contains(toFilter))
{
m_FilteredLogsList.Add(log);
}
if (m_Warnings && (log.ErrorLevel == LoggerState.WARNING) && log.Message.Contains(toFilter))
{
m_FilteredLogsList.Add(log);
}
if (m_Errors && (log.ErrorLevel == LoggerState.ERROR) && log.Message.Contains(toFilter))
{
m_FilteredLogsList.Add(log);
}
if (m_Criticals && (log.ErrorLevel == LoggerState.CRITICAL) && log.Message.Contains(toFilter))
{
m_FilteredLogsList.Add(log);
}
}
}
}
public void Log(string pLogMessage, LoggerState pErrorLevel)
{
// Propagate Log to GUI
if (m_ViewHandle != null)
{
LogMessage LogMessageT1 = new LogMessage();
LogMessageT1.Message = pLogMessage;
LogMessageT1.ErrorLevel = pErrorLevel;
addImageAccordingToErrorLevel(pErrorLevel,LogMessageT1);
this.m_AllLogsList.Add(LogMessageT1);
applyFilter();
}
switch (pErrorLevel)
{
case LoggerState.INFORMATION:
m_Writer.Write("\r\nINFORMATION: ");
m_Writer.WriteLine("{0} {1}", DateTime.Now.ToLongTimeString(),DateTime.Now.ToLongDateString());
m_Writer.WriteLine(pLogMessage);
m_Writer.WriteLine("-------------------------------");
break;
case LoggerState.WARNING:
m_Writer.Write("\r\nWARNING: ");
m_Writer.WriteLine("{0} {1}", DateTime.Now.ToLongTimeString(),DateTime.Now.ToLongDateString());
m_Writer.WriteLine(pLogMessage);
m_Writer.WriteLine("-------------------------------");
break;
case LoggerState.ERROR:
m_Writer.Write("\r\nERROR: ");
m_Writer.WriteLine("{0} {1}", DateTime.Now.ToLongTimeString(),DateTime.Now.ToLongDateString());
m_Writer.WriteLine(pLogMessage);
m_Writer.WriteLine("-------------------------------");
break;
case LoggerState.CRITICAL:
m_Writer.Write("\r\nCRITICAL: ");
m_Writer.WriteLine("{0} {1}", DateTime.Now.ToLongTimeString(),DateTime.Now.ToLongDateString());
m_Writer.WriteLine(pLogMessage);
m_Writer.WriteLine("-------------------------------");
break;
default:
// TODO: do something smart here
break;
}
m_Writer.Flush();
}
}
}
| |
// 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.Xml.Linq;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Diagnostics.Analyzers.NamingStyles
{
internal class NamingStyle
{
public Guid ID { get; set; }
public string Name { get; set; }
public string Prefix { get; set; }
public string Suffix { get; set; }
public string WordSeparator { get; set; }
public Capitalization CapitalizationScheme { get; set; }
public NamingStyle()
{
ID = Guid.NewGuid();
}
public string CreateName(IEnumerable<string> words)
{
EnsureNonNullProperties();
var wordsWithCasing = ApplyCapitalization(words);
var combinedWordsWithCasing = string.Join(WordSeparator, wordsWithCasing);
return Prefix + combinedWordsWithCasing + Suffix;
}
private IEnumerable<string> ApplyCapitalization(IEnumerable<string> words)
{
switch (CapitalizationScheme)
{
case Capitalization.PascalCase:
return words.Select(CapitalizeFirstLetter);
case Capitalization.CamelCase:
return words.Take(1).Select(DecapitalizeFirstLetter).Concat(words.Skip(1).Select(CapitalizeFirstLetter));
case Capitalization.FirstUpper:
return words.Take(1).Select(CapitalizeFirstLetter).Concat(words.Skip(1).Select(DecapitalizeFirstLetter));
case Capitalization.AllUpper:
return words.Select(w => w.ToUpper());
case Capitalization.AllLower:
return words.Select(w => w.ToLower());
default:
throw new InvalidOperationException();
}
}
private string CapitalizeFirstLetter(string word)
{
var chars = word.ToCharArray();
return new string(chars.Take(1).Select(c => char.ToUpper(c)).Concat(chars.Skip(1)).ToArray());
}
private string DecapitalizeFirstLetter(string word)
{
var chars = word.ToCharArray();
return new string(chars.Take(1).Select(c => char.ToLower(c)).Concat(chars.Skip(1)).ToArray());
}
public bool IsNameCompliant(string name, out string failureReason)
{
EnsureNonNullProperties();
if (!name.StartsWith(Prefix))
{
failureReason = string.Format(FeaturesResources.Missing_prefix_colon_0, Prefix);
return false;
}
if (!name.EndsWith(Suffix))
{
failureReason = string.Format(FeaturesResources.Missing_suffix_colon_0, Suffix);
return false;
}
if (name.Length <= Prefix.Length + Suffix.Length)
{
failureReason = null;
return true;
}
name = name.Substring(Prefix.Length);
name = name.Substring(0, name.Length - Suffix.Length);
var words = new[] { name };
if (!string.IsNullOrEmpty(WordSeparator))
{
words = name.Split(new[] { WordSeparator }, StringSplitOptions.RemoveEmptyEntries);
}
failureReason = string.Empty;
switch (CapitalizationScheme)
{
case Capitalization.PascalCase:
if (words.All(w => char.IsUpper(w[0])))
{
return true;
}
else
{
var violations = words.Where(w => !char.IsUpper(w[0]));
failureReason = string.Format(FeaturesResources.These_words_must_begin_with_upper_case_characters_colon_0, string.Join(", ", violations));
return false;
}
case Capitalization.CamelCase:
if (char.IsLower(words.First()[0]) && words.Skip(1).All(w => char.IsUpper(w[0])))
{
return true;
}
else
{
if (!char.IsLower(words.First()[0]))
{
failureReason = string.Format(FeaturesResources.The_first_word_0_must_begin_with_a_lower_case_character, words.First());
}
var violations = words.Skip(1).Where(w => !char.IsUpper(w[0]));
if (violations.Any())
{
if (failureReason != string.Empty)
{
failureReason += Environment.NewLine;
}
failureReason += string.Format(FeaturesResources.These_non_leading_words_must_begin_with_an_upper_case_letter_colon_0, string.Join(", ", violations));
}
return false;
}
case Capitalization.FirstUpper:
if (char.IsUpper(words.First()[0]) && words.Skip(1).All(w => char.IsLower(w[0])))
{
return true;
}
else
{
if (!char.IsUpper(words.First()[0]))
{
failureReason = string.Format(FeaturesResources.The_first_word_0_must_begin_with_an_upper_case_character, words.First());
}
var violations = words.Skip(1).Where(w => !char.IsLower(w[0]));
if (violations.Any())
{
if (failureReason != string.Empty)
{
failureReason += Environment.NewLine;
}
failureReason += string.Format(FeaturesResources.These_non_leading_words_must_begin_with_a_lowercase_letter_colon_0, string.Join(", ", violations));
}
return false;
}
case Capitalization.AllUpper:
if (words.SelectMany(w => w.ToCharArray()).All(c => char.IsUpper(c)))
{
return true;
}
else
{
var violations = words.Where(w => !w.ToCharArray().All(c => char.IsUpper(c)));
failureReason = string.Format(FeaturesResources.These_words_cannot_contain_lower_case_characters_colon_0, string.Join(", ", violations));
return false;
}
case Capitalization.AllLower:
if (words.SelectMany(w => w.ToCharArray()).All(c => char.IsLower(c)))
{
return true;
}
else
{
var violations = words.Where(w => !w.ToCharArray().All(c => char.IsLower(c)));
failureReason = string.Format(FeaturesResources.These_words_cannot_contain_upper_case_characters_colon_0, string.Join(", ", violations));
return false;
}
default:
throw new InvalidOperationException();
}
}
internal NamingStyle Clone()
{
return new NamingStyle
{
ID = ID,
Name = Name,
Prefix = Prefix,
Suffix = Suffix,
WordSeparator = WordSeparator,
CapitalizationScheme = CapitalizationScheme
};
}
private string CreateCompliantNameDirectly(string name)
{
EnsureNonNullProperties();
bool addPrefix = !name.StartsWith(Prefix);
bool addSuffix = !name.EndsWith(Suffix);
name = addPrefix ? (Prefix + name) : name;
name = addSuffix ? (name + Suffix) : name;
return FinishFixingName(name);
}
public IEnumerable<string> MakeCompliant(string name)
{
var name1 = CreateCompliantNameReusingPartialPrefixesAndSuffixes(name);
yield return name1;
var name2 = CreateCompliantNameDirectly(name);
if (name2 != name1)
{
yield return name2;
}
}
private string CreateCompliantNameReusingPartialPrefixesAndSuffixes(string name)
{
EnsureNonNullProperties();
name = EnsurePrefix(name);
name = EnsureSuffix(name);
return FinishFixingName(name);
}
private string FinishFixingName(string name)
{
// Edge case: prefix "as", suffix "sa", name "asa"
if (Suffix.Length + Prefix.Length >= name.Length)
{
return name;
}
name = name.Substring(Prefix.Length, name.Length - Suffix.Length - Prefix.Length);
IEnumerable<string> words = new[] { name };
if (!string.IsNullOrEmpty(WordSeparator))
{
words = name.Split(new[] { WordSeparator }, StringSplitOptions.RemoveEmptyEntries);
}
words = ApplyCapitalization(words);
return Prefix + string.Join(WordSeparator, words) + Suffix;
}
private string EnsureSuffix(string name)
{
// If the name already ends with any prefix of the Suffix, only append the suffix of
// the Suffix not contained in the longest such Suffix prefix. For example, if the
// required suffix is "_catdog" and the name is "test_cat", then only append "dog".
for (int i = Suffix.Length; i > 0 ; i--)
{
if (name.EndsWith(Suffix.Substring(0, i)))
{
return name + Suffix.Substring(i);
}
}
return name + Suffix;
}
private string EnsurePrefix(string name)
{
// If the name already starts with any suffix of the Prefix, only prepend the prefix of
// the Prefix not contained in the longest such Prefix suffix. For example, if the
// required prefix is "catdog_" and the name is "dog_test", then only prepend "cat".
for (int i = 0; i < Prefix.Length; i++)
{
if (name.StartsWith(Prefix.Substring(i)))
{
return Prefix.Substring(0, i) + name;
}
}
return Prefix + name;
}
private void EnsureNonNullProperties()
{
Prefix = Prefix ?? string.Empty;
Suffix = Suffix ?? string.Empty;
WordSeparator = WordSeparator ?? string.Empty;
}
internal XElement CreateXElement()
{
return new XElement(nameof(NamingStyle),
new XAttribute(nameof(ID), ID),
new XAttribute(nameof(Name), Name),
new XAttribute(nameof(Prefix), Prefix ?? string.Empty),
new XAttribute(nameof(Suffix), Suffix ?? string.Empty),
new XAttribute(nameof(WordSeparator), WordSeparator ?? string.Empty),
new XAttribute(nameof(CapitalizationScheme), CapitalizationScheme));
}
internal static NamingStyle FromXElement(XElement namingStyleElement)
{
return new NamingStyle()
{
ID = Guid.Parse(namingStyleElement.Attribute(nameof(ID)).Value),
Name = namingStyleElement.Attribute(nameof(Name)).Value,
Prefix = namingStyleElement.Attribute(nameof(Prefix)).Value,
Suffix = namingStyleElement.Attribute(nameof(Suffix)).Value,
WordSeparator = namingStyleElement.Attribute(nameof(WordSeparator)).Value,
CapitalizationScheme = (Capitalization)Enum.Parse(typeof(Capitalization), namingStyleElement.Attribute(nameof(CapitalizationScheme)).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.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;
using Xunit;
namespace System.Globalization.Tests
{
public class CultureInfoAll
{
[Fact]
[PlatformSpecific(Xunit.PlatformID.Windows)] // P/Invoke to Win32 function
public void TestAllCultures()
{
Assert.True(EnumSystemLocalesEx(EnumLocales, LOCALE_WINDOWS, IntPtr.Zero, IntPtr.Zero), "EnumSystemLocalesEx has failed");
Assert.All(cultures, Validate);
}
private void Validate(CultureInfo ci)
{
Assert.Equal(ci.EnglishName, GetLocaleInfo(ci, LOCALE_SENGLISHDISPLAYNAME));
// si-LK has some special case when running on Win7 so we just ignore this one
if (!ci.Name.Equals("si-LK", StringComparison.OrdinalIgnoreCase))
{
Assert.Equal(ci.Name.Length == 0 ? "Invariant Language (Invariant Country)" : GetLocaleInfo(ci, LOCALE_SNATIVEDISPLAYNAME), ci.NativeName);
}
// zh-Hans and zh-Hant has different behavior on different platform
Assert.Contains(GetLocaleInfo(ci, LOCALE_SPARENT), new[] { "zh-Hans", "zh-Hant", ci.Parent.Name }, StringComparer.OrdinalIgnoreCase);
Assert.Equal(ci.TwoLetterISOLanguageName, GetLocaleInfo(ci, LOCALE_SISO639LANGNAME));
ValidateDTFI(ci);
ValidateNFI(ci);
ValidateRegionInfo(ci);
}
private void ValidateDTFI(CultureInfo ci)
{
DateTimeFormatInfo dtfi = ci.DateTimeFormat;
Calendar cal = dtfi.Calendar;
int calId = GetCalendarId(cal);
Assert.Equal(GetDayNames(ci, calId, CAL_SABBREVDAYNAME1), dtfi.AbbreviatedDayNames);
Assert.Equal(GetDayNames(ci, calId, CAL_SDAYNAME1), dtfi.DayNames);
Assert.Equal(GetMonthNames(ci, calId, CAL_SMONTHNAME1), dtfi.MonthNames);
Assert.Equal(GetMonthNames(ci, calId, CAL_SABBREVMONTHNAME1), dtfi.AbbreviatedMonthNames);
Assert.Equal(GetMonthNames(ci, calId, CAL_SMONTHNAME1 | LOCALE_RETURN_GENITIVE_NAMES), dtfi.MonthGenitiveNames);
Assert.Equal(GetMonthNames(ci, calId, CAL_SABBREVMONTHNAME1 | LOCALE_RETURN_GENITIVE_NAMES), dtfi.AbbreviatedMonthGenitiveNames);
Assert.Equal(GetDayNames(ci, calId, CAL_SSHORTESTDAYNAME1), dtfi.ShortestDayNames);
Assert.Equal(GetLocaleInfo(ci, LOCALE_S1159), dtfi.AMDesignator, StringComparer.OrdinalIgnoreCase);
Assert.Equal(GetLocaleInfo(ci, LOCALE_S2359), dtfi.PMDesignator, StringComparer.OrdinalIgnoreCase);
Assert.Equal(calId, GetDefaultcalendar(ci));
Assert.Equal((int)dtfi.FirstDayOfWeek, ConvertFirstDayOfWeekMonToSun(GetLocaleInfoAsInt(ci, LOCALE_IFIRSTDAYOFWEEK)));
Assert.Equal((int)dtfi.CalendarWeekRule, GetLocaleInfoAsInt(ci, LOCALE_IFIRSTWEEKOFYEAR));
Assert.Equal(dtfi.MonthDayPattern, GetCalendarInfo(ci, calId, CAL_SMONTHDAY, true));
Assert.Equal("ddd, dd MMM yyyy HH':'mm':'ss 'GMT'", dtfi.RFC1123Pattern);
Assert.Equal("yyyy'-'MM'-'dd'T'HH':'mm':'ss", dtfi.SortableDateTimePattern);
Assert.Equal("yyyy'-'MM'-'dd HH':'mm':'ss'Z'", dtfi.UniversalSortableDateTimePattern);
string longDatePattern1 = GetCalendarInfo(ci, calId, CAL_SLONGDATE)[0];
string longDatePattern2 = ReescapeWin32String(GetLocaleInfo(ci, LOCALE_SLONGDATE));
string longTimePattern1 = GetTimeFormats(ci, 0)[0];
string longTimePattern2 = ReescapeWin32String(GetLocaleInfo(ci, LOCALE_STIMEFORMAT));
string fullDateTimePattern = longDatePattern1 + " " + longTimePattern1;
string fullDateTimePattern1 = longDatePattern2 + " " + longTimePattern2;
Assert.Contains(dtfi.FullDateTimePattern, new[] { fullDateTimePattern, fullDateTimePattern1 });
Assert.Contains(dtfi.LongDatePattern, new[] { longDatePattern1, longDatePattern2 });
Assert.Contains(dtfi.LongTimePattern, new[] { longTimePattern1, longTimePattern2 });
Assert.Contains(dtfi.ShortTimePattern, new[] { GetTimeFormats(ci, TIME_NOSECONDS)[0], ReescapeWin32String(GetLocaleInfo(ci, LOCALE_SSHORTTIME)) });
Assert.Contains(dtfi.ShortDatePattern, new[] { GetCalendarInfo(ci, calId, CAL_SSHORTDATE)[0], ReescapeWin32String(GetLocaleInfo(ci, LOCALE_SSHORTDATE)) });
Assert.Contains(dtfi.YearMonthPattern, new[] { GetCalendarInfo(ci, calId, CAL_SYEARMONTH)[0], ReescapeWin32String(GetLocaleInfo(ci, LOCALE_SYEARMONTH)) });
int eraNameIndex = 1;
Assert.All(GetCalendarInfo(ci, calId, CAL_SERASTRING), eraName => Assert.Equal(dtfi.GetEraName(eraNameIndex++), eraName, StringComparer.OrdinalIgnoreCase));
eraNameIndex = 1;
Assert.All(GetCalendarInfo(ci, calId, CAL_SABBREVERASTRING), eraName => Assert.Equal(dtfi.GetAbbreviatedEraName(eraNameIndex++), eraName, StringComparer.OrdinalIgnoreCase));
}
private void ValidateNFI(CultureInfo ci)
{
NumberFormatInfo nfi = ci.NumberFormat;
Assert.Equal(string.IsNullOrEmpty(GetLocaleInfo(ci, LOCALE_SPOSITIVESIGN)) ? "+" : GetLocaleInfo(ci, LOCALE_SPOSITIVESIGN), nfi.PositiveSign);
Assert.Equal(GetLocaleInfo(ci, LOCALE_SNEGATIVESIGN), nfi.NegativeSign);
Assert.Equal(GetLocaleInfo(ci, LOCALE_SDECIMAL), nfi.NumberDecimalSeparator);
Assert.Equal(GetLocaleInfo(ci, LOCALE_SDECIMAL), nfi.PercentDecimalSeparator);
Assert.Equal(GetLocaleInfo(ci, LOCALE_STHOUSAND), nfi.NumberGroupSeparator);
Assert.Equal(GetLocaleInfo(ci, LOCALE_STHOUSAND), nfi.PercentGroupSeparator);
Assert.Equal(GetLocaleInfo(ci, LOCALE_SMONTHOUSANDSEP), nfi.CurrencyGroupSeparator);
Assert.Equal(GetLocaleInfo(ci, LOCALE_SMONDECIMALSEP), nfi.CurrencyDecimalSeparator);
Assert.Equal(GetLocaleInfo(ci, LOCALE_SCURRENCY), nfi.CurrencySymbol);
Assert.Equal(GetLocaleInfoAsInt(ci, LOCALE_IDIGITS), nfi.NumberDecimalDigits);
Assert.Equal(GetLocaleInfoAsInt(ci, LOCALE_IDIGITS), nfi.PercentDecimalDigits);
Assert.Equal(GetLocaleInfoAsInt(ci, LOCALE_ICURRDIGITS), nfi.CurrencyDecimalDigits);
Assert.Equal(GetLocaleInfoAsInt(ci, LOCALE_ICURRENCY), nfi.CurrencyPositivePattern);
Assert.Equal(GetLocaleInfoAsInt(ci, LOCALE_INEGCURR), nfi.CurrencyNegativePattern);
Assert.Equal(GetLocaleInfoAsInt(ci, LOCALE_INEGNUMBER), nfi.NumberNegativePattern);
Assert.Equal(ConvertWin32GroupString(GetLocaleInfo(ci, LOCALE_SMONGROUPING)), nfi.CurrencyGroupSizes);
Assert.Equal(GetLocaleInfo(ci, LOCALE_SNAN), nfi.NaNSymbol);
Assert.Equal(GetLocaleInfo(ci, LOCALE_SNEGINFINITY), nfi.NegativeInfinitySymbol);
Assert.Equal(ConvertWin32GroupString(GetLocaleInfo(ci, LOCALE_SGROUPING)), nfi.NumberGroupSizes);
Assert.Equal(ConvertWin32GroupString(GetLocaleInfo(ci, LOCALE_SGROUPING)), nfi.PercentGroupSizes);
Assert.Equal(GetLocaleInfoAsInt(ci, LOCALE_INEGATIVEPERCENT), nfi.PercentNegativePattern);
Assert.Equal(GetLocaleInfoAsInt(ci, LOCALE_IPOSITIVEPERCENT), nfi.PercentPositivePattern);
Assert.Equal(GetLocaleInfo(ci, LOCALE_SPERCENT), nfi.PercentSymbol);
Assert.Equal(GetLocaleInfo(ci, LOCALE_SPERMILLE), nfi.PerMilleSymbol);
Assert.Equal(GetLocaleInfo(ci, LOCALE_SPOSINFINITY), nfi.PositiveInfinitySymbol);
}
private void ValidateRegionInfo(CultureInfo ci)
{
if (ci.Name.Length == 0) // no region for invariant
return;
RegionInfo ri = new RegionInfo(ci.Name);
Assert.Equal(GetLocaleInfo(ci, LOCALE_SCURRENCY), ri.CurrencySymbol);
Assert.Equal(GetLocaleInfo(ci, LOCALE_SENGLISHCOUNTRYNAME), ri.EnglishName);
Assert.Equal(GetLocaleInfoAsInt(ci, LOCALE_IMEASURE) == 0, ri.IsMetric);
Assert.Equal(GetLocaleInfo(ci, LOCALE_SINTLSYMBOL), ri.ISOCurrencySymbol);
Assert.True(ci.Name.Equals(ri.Name, StringComparison.OrdinalIgnoreCase) || // Desktop usese culture name as region name
ri.Name.Equals(GetLocaleInfo(ci, LOCALE_SISO3166CTRYNAME), StringComparison.OrdinalIgnoreCase)); // netcore uses 2 letter ISO for region name
Assert.Equal(GetLocaleInfo(ci, LOCALE_SISO3166CTRYNAME), ri.TwoLetterISORegionName, StringComparer.OrdinalIgnoreCase);
Assert.Equal(GetLocaleInfo(ci, LOCALE_SNATIVECOUNTRYNAME), ri.NativeName, StringComparer.OrdinalIgnoreCase);
}
private int[] ConvertWin32GroupString(String win32Str)
{
// None of these cases make any sense
if (win32Str == null || win32Str.Length == 0)
{
return (new int[] { 3 });
}
if (win32Str[0] == '0')
{
return (new int[] { 0 });
}
// Since its in n;n;n;n;n format, we can always get the length quickly
int[] values;
if (win32Str[win32Str.Length - 1] == '0')
{
// Trailing 0 gets dropped. 1;0 -> 1
values = new int[(win32Str.Length / 2)];
}
else
{
// Need extra space for trailing zero 1 -> 1;0
values = new int[(win32Str.Length / 2) + 2];
values[values.Length - 1] = 0;
}
int i;
int j;
for (i = 0, j = 0; i < win32Str.Length && j < values.Length; i += 2, j++)
{
// Note that this # shouldn't ever be zero, 'cause 0 is only at end
// But we'll test because its registry that could be anything
if (win32Str[i] < '1' || win32Str[i] > '9')
return new int[] { 3 };
values[j] = (int)(win32Str[i] - '0');
}
return (values);
}
private List<string> _timePatterns;
private bool EnumTimeFormats(string lpTimeFormatString, IntPtr lParam)
{
_timePatterns.Add(ReescapeWin32String(lpTimeFormatString));
return true;
}
private string[] GetTimeFormats(CultureInfo ci, uint flags)
{
_timePatterns = new List<string>();
Assert.True(EnumTimeFormatsEx(EnumTimeFormats, ci.Name, flags, IntPtr.Zero), String.Format("EnumTimeFormatsEx failed with culture {0} and flags {1}", ci, flags));
return _timePatterns.ToArray();
}
internal String ReescapeWin32String(String str)
{
// If we don't have data, then don't try anything
if (str == null)
return null;
StringBuilder result = null;
bool inQuote = false;
for (int i = 0; i < str.Length; i++)
{
// Look for quote
if (str[i] == '\'')
{
// Already in quote?
if (inQuote)
{
// See another single quote. Is this '' of 'fred''s' or '''', or is it an ending quote?
if (i + 1 < str.Length && str[i + 1] == '\'')
{
// Found another ', so we have ''. Need to add \' instead.
// 1st make sure we have our stringbuilder
if (result == null)
result = new StringBuilder(str, 0, i, str.Length * 2);
// Append a \' and keep going (so we don't turn off quote mode)
result.Append("\\'");
i++;
continue;
}
// Turning off quote mode, fall through to add it
inQuote = false;
}
else
{
// Found beginning quote, fall through to add it
inQuote = true;
}
}
// Is there a single \ character?
else if (str[i] == '\\')
{
// Found a \, need to change it to \\
// 1st make sure we have our stringbuilder
if (result == null)
result = new StringBuilder(str, 0, i, str.Length * 2);
// Append our \\ to the string & continue
result.Append("\\\\");
continue;
}
// If we have a builder we need to add our character
if (result != null)
result.Append(str[i]);
}
// Unchanged string? , just return input string
if (result == null)
return str;
// String changed, need to use the builder
return result.ToString();
}
private string[] GetMonthNames(CultureInfo ci, int calendar, uint calType)
{
string[] names = new string[13];
for (uint i = 0; i < 13; i++)
{
names[i] = GetCalendarInfo(ci, calendar, calType + i, false);
}
return names;
}
private int ConvertFirstDayOfWeekMonToSun(int iTemp)
{
// Convert Mon-Sun to Sun-Sat format
iTemp++;
if (iTemp > 6)
{
// Wrap Sunday and convert invalid data to Sunday
iTemp = 0;
}
return iTemp;
}
private string[] GetDayNames(CultureInfo ci, int calendar, uint calType)
{
string[] names = new string[7];
for (uint i = 1; i < 7; i++)
{
names[i] = GetCalendarInfo(ci, calendar, calType + i - 1, true);
}
names[0] = GetCalendarInfo(ci, calendar, calType + 6, true);
return names;
}
private int GetCalendarId(Calendar cal)
{
int calId = 0;
if (cal is System.Globalization.GregorianCalendar)
{
calId = (int)(cal as GregorianCalendar).CalendarType;
}
else if (cal is System.Globalization.JapaneseCalendar)
{
calId = CAL_JAPAN;
}
else if (cal is System.Globalization.TaiwanCalendar)
{
calId = CAL_TAIWAN;
}
else if (cal is System.Globalization.KoreanCalendar)
{
calId = CAL_KOREA;
}
else if (cal is System.Globalization.HijriCalendar)
{
calId = CAL_HIJRI;
}
else if (cal is System.Globalization.ThaiBuddhistCalendar)
{
calId = CAL_THAI;
}
else if (cal is System.Globalization.HebrewCalendar)
{
calId = CAL_HEBREW;
}
else if (cal is System.Globalization.UmAlQuraCalendar)
{
calId = CAL_UMALQURA;
}
else if (cal is System.Globalization.PersianCalendar)
{
calId = CAL_PERSIAN;
}
else
{
throw new KeyNotFoundException(String.Format("Got a calendar {0} which we cannot map its Id", cal));
}
return calId;
}
internal bool EnumLocales(string name, uint dwFlags, IntPtr param)
{
CultureInfo ci = new CultureInfo(name);
if (!ci.IsNeutralCulture)
cultures.Add(ci);
return true;
}
private string GetLocaleInfo(CultureInfo ci, uint lctype)
{
Assert.True(GetLocaleInfoEx(ci.Name, lctype, sb, 400) > 0, String.Format("GetLocaleInfoEx failed when calling with lctype {0} and culture {1}", lctype, ci));
return sb.ToString();
}
private string GetCalendarInfo(CultureInfo ci, int calendar, uint calType, bool throwInFail)
{
if (GetCalendarInfoEx(ci.Name, calendar, IntPtr.Zero, calType, sb, 400, IntPtr.Zero) <= 0)
{
Assert.False(throwInFail, String.Format("GetCalendarInfoEx failed when calling with caltype {0} and culture {1} and calendar Id {2}", calType, ci, calendar));
return "";
}
return ReescapeWin32String(sb.ToString());
}
private List<int> _optionalCals = new List<int>();
private bool EnumCalendarsCallback(string lpCalendarInfoString, int calendar, string pReserved, IntPtr lParam)
{
_optionalCals.Add(calendar);
return true;
}
private int[] GetOptionalCalendars(CultureInfo ci)
{
_optionalCals = new List<int>();
Assert.True(EnumCalendarInfoExEx(EnumCalendarsCallback, ci.Name, ENUM_ALL_CALENDARS, null, CAL_ICALINTVALUE, IntPtr.Zero), "EnumCalendarInfoExEx has been failed.");
return _optionalCals.ToArray();
}
private List<string> _calPatterns;
private bool EnumCalendarInfoCallback(string lpCalendarInfoString, int calendar, string pReserved, IntPtr lParam)
{
_calPatterns.Add(ReescapeWin32String(lpCalendarInfoString));
return true;
}
private string[] GetCalendarInfo(CultureInfo ci, int calId, uint calType)
{
_calPatterns = new List<string>();
Assert.True(EnumCalendarInfoExEx(EnumCalendarInfoCallback, ci.Name, (uint)calId, null, calType, IntPtr.Zero), "EnumCalendarInfoExEx has been failed in GetCalendarInfo.");
return _calPatterns.ToArray();
}
private int GetDefaultcalendar(CultureInfo ci)
{
int calId = GetLocaleInfoAsInt(ci, LOCALE_ICALENDARTYPE);
if (calId != 0)
return calId;
int[] cals = GetOptionalCalendars(ci);
Assert.True(cals.Length > 0);
return cals[0];
}
private int GetLocaleInfoAsInt(CultureInfo ci, uint lcType)
{
int data = 0;
Assert.True(GetLocaleInfoEx(ci.Name, lcType | LOCALE_RETURN_NUMBER, ref data, sizeof(int)) > 0, String.Format("GetLocaleInfoEx failed with culture {0} and lcType {1}.", ci, lcType));
return data;
}
internal delegate bool EnumLocalesProcEx([MarshalAs(UnmanagedType.LPWStr)] string name, uint dwFlags, IntPtr param);
internal delegate bool EnumCalendarInfoProcExEx([MarshalAs(UnmanagedType.LPWStr)] string lpCalendarInfoString, int Calendar, string lpReserved, IntPtr lParam);
internal delegate bool EnumTimeFormatsProcEx([MarshalAs(UnmanagedType.LPWStr)] string lpTimeFormatString, IntPtr lParam);
internal static StringBuilder sb = new StringBuilder(400);
internal static List<CultureInfo> cultures = new List<CultureInfo>();
internal const uint LOCALE_WINDOWS = 0x00000001;
internal const uint LOCALE_SENGLISHDISPLAYNAME = 0x00000072;
internal const uint LOCALE_SNATIVEDISPLAYNAME = 0x00000073;
internal const uint LOCALE_SPARENT = 0x0000006d;
internal const uint LOCALE_SISO639LANGNAME = 0x00000059;
internal const uint LOCALE_S1159 = 0x00000028; // AM designator, eg "AM"
internal const uint LOCALE_S2359 = 0x00000029; // PM designator, eg "PM"
internal const uint LOCALE_ICALENDARTYPE = 0x00001009;
internal const uint LOCALE_RETURN_NUMBER = 0x20000000;
internal const uint LOCALE_IFIRSTWEEKOFYEAR = 0x0000100D;
internal const uint LOCALE_IFIRSTDAYOFWEEK = 0x0000100C;
internal const uint LOCALE_SLONGDATE = 0x00000020;
internal const uint LOCALE_STIMEFORMAT = 0x00001003;
internal const uint LOCALE_RETURN_GENITIVE_NAMES = 0x10000000;
internal const uint LOCALE_SSHORTDATE = 0x0000001F;
internal const uint LOCALE_SSHORTTIME = 0x00000079;
internal const uint LOCALE_SYEARMONTH = 0x00001006;
internal const uint LOCALE_SPOSITIVESIGN = 0x00000050; // positive sign
internal const uint LOCALE_SNEGATIVESIGN = 0x00000051; // negative sign
internal const uint LOCALE_SDECIMAL = 0x0000000E;
internal const uint LOCALE_STHOUSAND = 0x0000000F;
internal const uint LOCALE_SMONTHOUSANDSEP = 0x00000017;
internal const uint LOCALE_SMONDECIMALSEP = 0x00000016;
internal const uint LOCALE_SCURRENCY = 0x00000014;
internal const uint LOCALE_IDIGITS = 0x00000011;
internal const uint LOCALE_ICURRDIGITS = 0x00000019;
internal const uint LOCALE_ICURRENCY = 0x0000001B;
internal const uint LOCALE_INEGCURR = 0x0000001C;
internal const uint LOCALE_INEGNUMBER = 0x00001010;
internal const uint LOCALE_SMONGROUPING = 0x00000018;
internal const uint LOCALE_SNAN = 0x00000069;
internal const uint LOCALE_SNEGINFINITY = 0x0000006b; // - Infinity
internal const uint LOCALE_SGROUPING = 0x00000010;
internal const uint LOCALE_INEGATIVEPERCENT = 0x00000074;
internal const uint LOCALE_IPOSITIVEPERCENT = 0x00000075;
internal const uint LOCALE_SPERCENT = 0x00000076;
internal const uint LOCALE_SPERMILLE = 0x00000077;
internal const uint LOCALE_SPOSINFINITY = 0x0000006a;
internal const uint LOCALE_SENGLISHCOUNTRYNAME = 0x00001002;
internal const uint LOCALE_IMEASURE = 0x0000000D;
internal const uint LOCALE_SINTLSYMBOL = 0x00000015;
internal const uint LOCALE_SISO3166CTRYNAME = 0x0000005A;
internal const uint LOCALE_SNATIVECOUNTRYNAME = 0x00000008;
internal const uint CAL_SABBREVDAYNAME1 = 0x0000000e;
internal const uint CAL_SMONTHNAME1 = 0x00000015;
internal const uint CAL_SABBREVMONTHNAME1 = 0x00000022;
internal const uint CAL_ICALINTVALUE = 0x00000001;
internal const uint CAL_SDAYNAME1 = 0x00000007;
internal const uint CAL_SLONGDATE = 0x00000006;
internal const uint CAL_SMONTHDAY = 0x00000038;
internal const uint CAL_SSHORTDATE = 0x00000005;
internal const uint CAL_SSHORTESTDAYNAME1 = 0x00000031;
internal const uint CAL_SYEARMONTH = 0x0000002f;
internal const uint CAL_SERASTRING = 0x00000004;
internal const uint CAL_SABBREVERASTRING = 0x00000039;
internal const uint ENUM_ALL_CALENDARS = 0xffffffff;
internal const uint TIME_NOSECONDS = 0x00000002;
internal const int CAL_JAPAN = 3; // Japanese Emperor Era calendar
internal const int CAL_TAIWAN = 4; // Taiwan Era calendar
internal const int CAL_KOREA = 5; // Korean Tangun Era calendar
internal const int CAL_HIJRI = 6; // Hijri (Arabic Lunar) calendar
internal const int CAL_THAI = 7; // Thai calendar
internal const int CAL_HEBREW = 8; // Hebrew (Lunar) calendar
internal const int CAL_PERSIAN = 22;
internal const int CAL_UMALQURA = 23;
[DllImport("api-ms-win-core-localization-l1-2-0.dll", CharSet = CharSet.Unicode)]
internal extern static int GetLocaleInfoEx(string lpLocaleName, uint LCType, StringBuilder data, int cchData);
[DllImport("api-ms-win-core-localization-l1-2-0.dll", CharSet = CharSet.Unicode)]
internal extern static int GetLocaleInfoEx(string lpLocaleName, uint LCType, ref int data, int cchData);
[DllImport("api-ms-win-core-localization-l1-2-1.dll", CharSet = CharSet.Unicode)]
internal extern static bool EnumSystemLocalesEx(EnumLocalesProcEx lpLocaleEnumProcEx, uint dwFlags, IntPtr lParam, IntPtr reserved);
[DllImport("api-ms-win-core-localization-l1-2-0.dll", CharSet = CharSet.Unicode)]
internal extern static int GetCalendarInfoEx(string lpLocaleName, int Calendar, IntPtr lpReserved, uint CalType, StringBuilder lpCalData, int cchData, IntPtr lpValue);
[DllImport("api-ms-win-core-localization-l1-2-1.dll", CharSet = CharSet.Unicode)]
internal extern static int GetCalendarInfoEx(string lpLocaleName, int Calendar, IntPtr lpReserved, uint CalType, StringBuilder lpCalData, int cchData, ref uint lpValue);
[DllImport("api-ms-win-core-localization-l2-1-0.dll", CharSet = CharSet.Unicode)]
internal extern static bool EnumCalendarInfoExEx(EnumCalendarInfoProcExEx pCalInfoEnumProcExEx, string lpLocaleName, uint Calendar, string lpReserved, uint CalType, IntPtr lParam);
[DllImport("api-ms-win-core-localization-l2-1-0.dll", CharSet = CharSet.Unicode)]
internal extern static bool EnumTimeFormatsEx(EnumTimeFormatsProcEx lpTimeFmtEnumProcEx, string lpLocaleName, uint dwFlags, IntPtr lParam);
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using LSL_Float = OpenSim.Region.ScriptEngine.Shared.LSL_Types.LSLFloat;
using LSL_Integer = OpenSim.Region.ScriptEngine.Shared.LSL_Types.LSLInteger;
using LSL_Key = OpenSim.Region.ScriptEngine.Shared.LSL_Types.LSLString;
using LSL_List = OpenSim.Region.ScriptEngine.Shared.LSL_Types.list;
using LSL_Rotation = OpenSim.Region.ScriptEngine.Shared.LSL_Types.Quaternion;
using LSL_String = OpenSim.Region.ScriptEngine.Shared.LSL_Types.LSLString;
using LSL_Vector = OpenSim.Region.ScriptEngine.Shared.LSL_Types.Vector3;
namespace OpenSim.Region.ScriptEngine.Shared.Api.Interfaces
{
public interface ILSL_Api
{
void state(string newState);
LSL_Integer llAbs(int i);
LSL_Float llAcos(double val);
void llAddToLandBanList(string avatar, double hours);
void llAddToLandPassList(string avatar, double hours);
void llAdjustSoundVolume(double volume);
void llAllowInventoryDrop(int add);
LSL_Float llAngleBetween(LSL_Rotation a, LSL_Rotation b);
void llApplyImpulse(LSL_Vector force, int local);
void llApplyRotationalImpulse(LSL_Vector force, int local);
LSL_Float llAsin(double val);
LSL_Float llAtan2(double x, double y);
void llAttachToAvatar(int attachment);
LSL_Key llAvatarOnSitTarget();
LSL_Key llAvatarOnLinkSitTarget(int linknum);
LSL_Rotation llAxes2Rot(LSL_Vector fwd, LSL_Vector left, LSL_Vector up);
LSL_Rotation llAxisAngle2Rot(LSL_Vector axis, double angle);
LSL_Integer llBase64ToInteger(string str);
LSL_String llBase64ToString(string str);
void llBreakAllLinks();
void llBreakLink(int linknum);
LSL_List llCastRay(LSL_Vector start, LSL_Vector end, LSL_List options);
LSL_Integer llCeil(double f);
void llClearCameraParams();
LSL_Integer llClearLinkMedia(LSL_Integer link, LSL_Integer face);
LSL_Integer llClearPrimMedia(LSL_Integer face);
void llCloseRemoteDataChannel(string channel);
LSL_Float llCloud(LSL_Vector offset);
void llCollisionFilter(string name, string id, int accept);
void llCollisionSound(string impact_sound, double impact_volume);
void llCollisionSprite(string impact_sprite);
LSL_Float llCos(double f);
void llCreateLink(string target, int parent);
LSL_List llCSV2List(string src);
LSL_List llDeleteSubList(LSL_List src, int start, int end);
LSL_String llDeleteSubString(string src, int start, int end);
void llDetachFromAvatar();
LSL_Vector llDetectedGrab(int number);
LSL_Integer llDetectedGroup(int number);
LSL_Key llDetectedKey(int number);
LSL_Integer llDetectedLinkNumber(int number);
LSL_String llDetectedName(int number);
LSL_Key llDetectedOwner(int number);
LSL_Vector llDetectedPos(int number);
LSL_Rotation llDetectedRot(int number);
LSL_Integer llDetectedType(int number);
LSL_Vector llDetectedTouchBinormal(int index);
LSL_Integer llDetectedTouchFace(int index);
LSL_Vector llDetectedTouchNormal(int index);
LSL_Vector llDetectedTouchPos(int index);
LSL_Vector llDetectedTouchST(int index);
LSL_Vector llDetectedTouchUV(int index);
LSL_Vector llDetectedVel(int number);
void llDialog(string avatar, string message, LSL_List buttons, int chat_channel);
void llDie();
LSL_String llDumpList2String(LSL_List src, string seperator);
LSL_Integer llEdgeOfWorld(LSL_Vector pos, LSL_Vector dir);
void llEjectFromLand(string pest);
void llEmail(string address, string subject, string message);
LSL_String llEscapeURL(string url);
LSL_Rotation llEuler2Rot(LSL_Vector v);
LSL_Float llFabs(double f);
LSL_Integer llFloor(double f);
void llForceMouselook(int mouselook);
LSL_Float llFrand(double mag);
LSL_Key llGenerateKey();
LSL_Vector llGetAccel();
LSL_Integer llGetAgentInfo(string id);
LSL_String llGetAgentLanguage(string id);
LSL_List llGetAgentList(LSL_Integer scope, LSL_List options);
LSL_Vector llGetAgentSize(string id);
LSL_Float llGetAlpha(int face);
LSL_Float llGetAndResetTime();
LSL_String llGetAnimation(string id);
LSL_List llGetAnimationList(string id);
LSL_Integer llGetAttached();
LSL_List llGetAttachedList(string id);
LSL_List llGetBoundingBox(string obj);
LSL_Vector llGetCameraPos();
LSL_Rotation llGetCameraRot();
LSL_Vector llGetCenterOfMass();
LSL_Vector llGetColor(int face);
LSL_Key llGetCreator();
LSL_String llGetDate();
LSL_Float llGetEnergy();
LSL_String llGetEnv(LSL_String name);
LSL_Vector llGetForce();
LSL_Integer llGetFreeMemory();
LSL_Integer llGetUsedMemory();
LSL_Integer llGetFreeURLs();
LSL_Vector llGetGeometricCenter();
LSL_Float llGetGMTclock();
LSL_String llGetHTTPHeader(LSL_Key request_id, string header);
LSL_Key llGetInventoryCreator(string item);
LSL_Key llGetInventoryKey(string name);
LSL_String llGetInventoryName(int type, int number);
LSL_Integer llGetInventoryNumber(int type);
LSL_Integer llGetInventoryPermMask(string item, int mask);
LSL_Integer llGetInventoryType(string name);
LSL_Key llGetKey();
LSL_Key llGetLandOwnerAt(LSL_Vector pos);
LSL_Key llGetLinkKey(int linknum);
LSL_String llGetLinkName(int linknum);
LSL_Integer llGetLinkNumber();
LSL_Integer llGetLinkNumberOfSides(int link);
LSL_List llGetLinkMedia(LSL_Integer link, LSL_Integer face, LSL_List rules);
LSL_List llGetLinkPrimitiveParams(int linknum, LSL_List rules);
LSL_Integer llGetListEntryType(LSL_List src, int index);
LSL_Integer llGetListLength(LSL_List src);
LSL_Vector llGetLocalPos();
LSL_Rotation llGetLocalRot();
LSL_Float llGetMass();
LSL_Float llGetMassMKS();
LSL_Integer llGetMemoryLimit();
void llGetNextEmail(string address, string subject);
LSL_Key llGetNotecardLine(string name, int line);
LSL_Key llGetNumberOfNotecardLines(string name);
LSL_Integer llGetNumberOfPrims();
LSL_Integer llGetNumberOfSides();
LSL_String llGetObjectDesc();
LSL_List llGetObjectDetails(string id, LSL_List args);
LSL_Float llGetObjectMass(string id);
LSL_String llGetObjectName();
LSL_Integer llGetObjectPermMask(int mask);
LSL_Integer llGetObjectPrimCount(string object_id);
LSL_Vector llGetOmega();
LSL_Key llGetOwner();
LSL_Key llGetOwnerKey(string id);
LSL_List llGetParcelDetails(LSL_Vector pos, LSL_List param);
LSL_Integer llGetParcelFlags(LSL_Vector pos);
LSL_Integer llGetParcelMaxPrims(LSL_Vector pos, int sim_wide);
LSL_String llGetParcelMusicURL();
LSL_Integer llGetParcelPrimCount(LSL_Vector pos, int category, int sim_wide);
LSL_List llGetParcelPrimOwners(LSL_Vector pos);
LSL_Integer llGetPermissions();
LSL_Key llGetPermissionsKey();
LSL_List llGetPrimMediaParams(int face, LSL_List rules);
LSL_Vector llGetPos();
LSL_List llGetPrimitiveParams(LSL_List rules);
LSL_Integer llGetRegionAgentCount();
LSL_Vector llGetRegionCorner();
LSL_Integer llGetRegionFlags();
LSL_Float llGetRegionFPS();
LSL_String llGetRegionName();
LSL_Float llGetRegionTimeDilation();
LSL_Vector llGetRootPosition();
LSL_Rotation llGetRootRotation();
LSL_Rotation llGetRot();
LSL_Vector llGetScale();
LSL_String llGetScriptName();
LSL_Integer llGetScriptState(string name);
LSL_String llGetSimulatorHostname();
LSL_Integer llGetSPMaxMemory();
LSL_Integer llGetStartParameter();
LSL_Integer llGetStatus(int status);
LSL_String llGetSubString(string src, int start, int end);
LSL_Vector llGetSunDirection();
LSL_String llGetTexture(int face);
LSL_Vector llGetTextureOffset(int face);
LSL_Float llGetTextureRot(int side);
LSL_Vector llGetTextureScale(int side);
LSL_Float llGetTime();
LSL_Float llGetTimeOfDay();
LSL_String llGetTimestamp();
LSL_Vector llGetTorque();
LSL_Integer llGetUnixTime();
LSL_Vector llGetVel();
LSL_Float llGetWallclock();
void llGiveInventory(string destination, string inventory);
void llGiveInventoryList(string destination, string category, LSL_List inventory);
LSL_Integer llGiveMoney(string destination, int amount);
LSL_Key llTransferLindenDollars(string destination, int amount);
void llGodLikeRezObject(string inventory, LSL_Vector pos);
LSL_Float llGround(LSL_Vector offset);
LSL_Vector llGroundContour(LSL_Vector offset);
LSL_Vector llGroundNormal(LSL_Vector offset);
void llGroundRepel(double height, int water, double tau);
LSL_Vector llGroundSlope(LSL_Vector offset);
LSL_Key llHTTPRequest(string url, LSL_List parameters, string body);
void llHTTPResponse(LSL_Key id, int status, string body);
LSL_String llInsertString(string dst, int position, string src);
void llInstantMessage(string user, string message);
LSL_String llIntegerToBase64(int number);
LSL_String llKey2Name(string id);
LSL_String llGetUsername(string id);
LSL_Key llRequestUsername(string id);
LSL_String llGetDisplayName(string id);
LSL_Key llRequestDisplayName(string id);
void llLinkParticleSystem(int linknum, LSL_List rules);
void llLinkSitTarget(LSL_Integer link, LSL_Vector offset, LSL_Rotation rot);
LSL_String llList2CSV(LSL_List src);
LSL_Float llList2Float(LSL_List src, int index);
LSL_Integer llList2Integer(LSL_List src, int index);
LSL_Key llList2Key(LSL_List src, int index);
LSL_List llList2List(LSL_List src, int start, int end);
LSL_List llList2ListStrided(LSL_List src, int start, int end, int stride);
LSL_Rotation llList2Rot(LSL_List src, int index);
LSL_String llList2String(LSL_List src, int index);
LSL_Vector llList2Vector(LSL_List src, int index);
LSL_Integer llListen(int channelID, string name, string ID, string msg);
void llListenControl(int number, int active);
void llListenRemove(int number);
LSL_Integer llListFindList(LSL_List src, LSL_List test);
LSL_List llListInsertList(LSL_List dest, LSL_List src, int start);
LSL_List llListRandomize(LSL_List src, int stride);
LSL_List llListReplaceList(LSL_List dest, LSL_List src, int start, int end);
LSL_List llListSort(LSL_List src, int stride, int ascending);
LSL_Float llListStatistics(int operation, LSL_List src);
void llLoadURL(string avatar_id, string message, string url);
LSL_Float llLog(double val);
LSL_Float llLog10(double val);
void llLookAt(LSL_Vector target, double strength, double damping);
void llLoopSound(string sound, double volume);
void llLoopSoundMaster(string sound, double volume);
void llLoopSoundSlave(string sound, double volume);
LSL_Integer llManageEstateAccess(int action, string avatar);
void llMakeExplosion(int particles, double scale, double vel, double lifetime, double arc, string texture, LSL_Vector offset);
void llMakeFire(int particles, double scale, double vel, double lifetime, double arc, string texture, LSL_Vector offset);
void llMakeFountain(int particles, double scale, double vel, double lifetime, double arc, int bounce, string texture, LSL_Vector offset, double bounce_offset);
void llMakeSmoke(int particles, double scale, double vel, double lifetime, double arc, string texture, LSL_Vector offset);
void llMapDestination(string simname, LSL_Vector pos, LSL_Vector look_at);
LSL_String llMD5String(string src, int nonce);
LSL_String llSHA1String(string src);
void llMessageLinked(int linknum, int num, string str, string id);
void llMinEventDelay(double delay);
void llModifyLand(int action, int brush);
LSL_Integer llModPow(int a, int b, int c);
void llMoveToTarget(LSL_Vector target, double tau);
void llOffsetTexture(double u, double v, int face);
void llOpenRemoteDataChannel();
LSL_Integer llOverMyLand(string id);
void llOwnerSay(string msg);
void llParcelMediaCommandList(LSL_List commandList);
LSL_List llParcelMediaQuery(LSL_List aList);
LSL_List llParseString2List(string str, LSL_List separators, LSL_List spacers);
LSL_List llParseStringKeepNulls(string src, LSL_List seperators, LSL_List spacers);
void llParticleSystem(LSL_List rules);
void llPassCollisions(int pass);
void llPassTouches(int pass);
void llPlaySound(string sound, double volume);
void llPlaySoundSlave(string sound, double volume);
void llPointAt(LSL_Vector pos);
LSL_Float llPow(double fbase, double fexponent);
void llPreloadSound(string sound);
void llPushObject(string target, LSL_Vector impulse, LSL_Vector ang_impulse, int local);
void llRefreshPrimURL();
void llRegionSay(int channelID, string text);
void llRegionSayTo(string target, int channelID, string text);
void llReleaseCamera(string avatar);
void llReleaseControls();
void llReleaseURL(string url);
void llRemoteDataReply(string channel, string message_id, string sdata, int idata);
void llRemoteDataSetRegion();
void llRemoteLoadScript(string target, string name, int running, int start_param);
void llRemoteLoadScriptPin(string target, string name, int pin, int running, int start_param);
void llRemoveFromLandBanList(string avatar);
void llRemoveFromLandPassList(string avatar);
void llRemoveInventory(string item);
void llRemoveVehicleFlags(int flags);
LSL_Key llRequestAgentData(string id, int data);
LSL_Key llRequestInventoryData(string name);
void llRequestPermissions(string agent, int perm);
LSL_Key llRequestSecureURL();
LSL_Key llRequestSimulatorData(string simulator, int data);
LSL_Key llRequestURL();
void llResetLandBanList();
void llResetLandPassList();
void llResetOtherScript(string name);
void llResetScript();
void llResetTime();
void llRezAtRoot(string inventory, LSL_Vector position, LSL_Vector velocity, LSL_Rotation rot, int param);
void llRezObject(string inventory, LSL_Vector pos, LSL_Vector vel, LSL_Rotation rot, int param);
LSL_Float llRot2Angle(LSL_Rotation rot);
LSL_Vector llRot2Axis(LSL_Rotation rot);
LSL_Vector llRot2Euler(LSL_Rotation r);
LSL_Vector llRot2Fwd(LSL_Rotation r);
LSL_Vector llRot2Left(LSL_Rotation r);
LSL_Vector llRot2Up(LSL_Rotation r);
void llRotateTexture(double rotation, int face);
LSL_Rotation llRotBetween(LSL_Vector start, LSL_Vector end);
void llRotLookAt(LSL_Rotation target, double strength, double damping);
LSL_Integer llRotTarget(LSL_Rotation rot, double error);
void llRotTargetRemove(int number);
LSL_Integer llRound(double f);
LSL_Integer llSameGroup(string agent);
void llSay(int channelID, string text);
LSL_Integer llScaleByFactor(double scaling_factor);
LSL_Float llGetMaxScaleFactor();
LSL_Float llGetMinScaleFactor();
void llScaleTexture(double u, double v, int face);
LSL_Integer llScriptDanger(LSL_Vector pos);
void llScriptProfiler(LSL_Integer flag);
LSL_Key llSendRemoteData(string channel, string dest, int idata, string sdata);
void llSensor(string name, string id, int type, double range, double arc);
void llSensorRemove();
void llSensorRepeat(string name, string id, int type, double range, double arc, double rate);
void llSetAlpha(double alpha, int face);
void llSetBuoyancy(double buoyancy);
void llSetCameraAtOffset(LSL_Vector offset);
void llSetCameraEyeOffset(LSL_Vector offset);
void llSetLinkCamera(LSL_Integer link, LSL_Vector eye, LSL_Vector at);
void llSetCameraParams(LSL_List rules);
void llSetClickAction(int action);
void llSetColor(LSL_Vector color, int face);
void llSetContentType(LSL_Key id, LSL_Integer type);
void llSetDamage(double damage);
void llSetForce(LSL_Vector force, int local);
void llSetForceAndTorque(LSL_Vector force, LSL_Vector torque, int local);
void llSetVelocity(LSL_Vector vel, int local);
void llSetAngularVelocity(LSL_Vector angularVelocity, int local);
void llSetHoverHeight(double height, int water, double tau);
void llSetInventoryPermMask(string item, int mask, int value);
void llSetLinkAlpha(int linknumber, double alpha, int face);
void llSetLinkColor(int linknumber, LSL_Vector color, int face);
LSL_Integer llSetLinkMedia(LSL_Integer link, LSL_Integer face, LSL_List rules);
void llSetLinkPrimitiveParams(int linknumber, LSL_List rules);
void llSetLinkTexture(int linknumber, string texture, int face);
void llSetLinkTextureAnim(int linknum, int mode, int face, int sizex, int sizey, double start, double length, double rate);
void llSetLocalRot(LSL_Rotation rot);
LSL_Integer llSetMemoryLimit(LSL_Integer limit);
void llSetObjectDesc(string desc);
void llSetObjectName(string name);
void llSetObjectPermMask(int mask, int value);
void llSetParcelMusicURL(string url);
void llSetPayPrice(int price, LSL_List quick_pay_buttons);
void llSetPos(LSL_Vector pos);
LSL_Integer llSetRegionPos(LSL_Vector pos);
LSL_Integer llSetPrimMediaParams(LSL_Integer face, LSL_List rules);
void llSetPrimitiveParams(LSL_List rules);
void llSetLinkPrimitiveParamsFast(int linknum, LSL_List rules);
void llSetPrimURL(string url);
void llSetRemoteScriptAccessPin(int pin);
void llSetRot(LSL_Rotation rot);
void llSetScale(LSL_Vector scale);
void llSetScriptState(string name, int run);
void llSetSitText(string text);
void llSetSoundQueueing(int queue);
void llSetSoundRadius(double radius);
void llSetStatus(int status, int value);
void llSetText(string text, LSL_Vector color, double alpha);
void llSetTexture(string texture, int face);
void llSetTextureAnim(int mode, int face, int sizex, int sizey, double start, double length, double rate);
void llSetTimerEvent(double sec);
void llSetTorque(LSL_Vector torque, int local);
void llSetTouchText(string text);
void llSetVehicleFlags(int flags);
void llSetVehicleFloatParam(int param, LSL_Float value);
void llSetVehicleRotationParam(int param, LSL_Rotation rot);
void llSetVehicleType(int type);
void llSetVehicleVectorParam(int param, LSL_Vector vec);
void llShout(int channelID, string text);
LSL_Float llSin(double f);
void llSitTarget(LSL_Vector offset, LSL_Rotation rot);
void llSleep(double sec);
void llSound(string sound, double volume, int queue, int loop);
void llSoundPreload(string sound);
LSL_Float llSqrt(double f);
void llStartAnimation(string anim);
void llStopAnimation(string anim);
void llStopHover();
void llStopLookAt();
void llStopMoveToTarget();
void llStopPointAt();
void llStopSound();
LSL_Integer llStringLength(string str);
LSL_String llStringToBase64(string str);
LSL_String llStringTrim(string src, int type);
LSL_Integer llSubStringIndex(string source, string pattern);
void llTakeCamera(string avatar);
void llTakeControls(int controls, int accept, int pass_on);
LSL_Float llTan(double f);
LSL_Integer llTarget(LSL_Vector position, double range);
void llTargetOmega(LSL_Vector axis, double spinrate, double gain);
void llTargetRemove(int number);
void llTeleportAgentHome(string agent);
void llTeleportAgent(string agent, string simname, LSL_Vector pos, LSL_Vector lookAt);
void llTeleportAgentGlobalCoords(string agent, LSL_Vector global, LSL_Vector pos, LSL_Vector lookAt);
void llTextBox(string avatar, string message, int chat_channel);
LSL_String llToLower(string source);
LSL_String llToUpper(string source);
void llTriggerSound(string sound, double volume);
void llTriggerSoundLimited(string sound, double volume, LSL_Vector top_north_east, LSL_Vector bottom_south_west);
LSL_String llUnescapeURL(string url);
void llUnSit(string id);
LSL_Float llVecDist(LSL_Vector a, LSL_Vector b);
LSL_Float llVecMag(LSL_Vector v);
LSL_Vector llVecNorm(LSL_Vector v);
void llVolumeDetect(int detect);
LSL_Float llWater(LSL_Vector offset);
void llWhisper(int channelID, string text);
LSL_Vector llWind(LSL_Vector offset);
LSL_String llXorBase64Strings(string str1, string str2);
LSL_String llXorBase64StringsCorrect(string str1, string str2);
LSL_Integer llGetLinkNumberOfSides(LSL_Integer link);
void llSetPhysicsMaterial(int material_bits, LSL_Float material_gravity_modifier, LSL_Float material_restitution, LSL_Float material_friction, LSL_Float material_density);
void SetPrimitiveParamsEx(LSL_Key prim, LSL_List rules, string originFunc);
void llSetKeyframedMotion(LSL_List frames, LSL_List options);
LSL_List GetPrimitiveParamsEx(LSL_Key prim, LSL_List rules);
LSL_List llGetPhysicsMaterial();
void llSetAnimationOverride(LSL_String animState, LSL_String anim);
void llResetAnimationOverride(LSL_String anim_state);
LSL_String llGetAnimationOverride(LSL_String anim_state);
LSL_String llJsonGetValue(LSL_String json, LSL_List specifiers);
LSL_List llJson2List(LSL_String json);
LSL_String llList2Json(LSL_String type, LSL_List values);
LSL_String llJsonSetValue(LSL_String json, LSL_List specifiers, LSL_String value);
LSL_String llJsonValueType(LSL_String json, LSL_List specifiers);
}
}
| |
//
// BEncodedNumber.cs
//
// Authors:
// Alan McGovern [email protected]
//
// Copyright (C) 2006 Alan McGovern
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Diagnostics;
using System.Globalization;
namespace BEncoding.NET {
/// <summary>
/// Class representing a BEncoded number
/// </summary>
public class BEncodedNumber : BEncodedValue, IComparable<BEncodedNumber> {
#region Member Variables
/// <summary>
/// The value of the BEncodedNumber
/// </summary>
public long Number {
get {
return _number;
}
set {
_number = value;
}
}
private long _number;
#endregion
#region Constructors
public BEncodedNumber()
: this(0) {
}
/// <summary>
/// Create a new BEncoded number with the given value
/// </summary>
/// <param name="value">The inital value of the BEncodedNumber</param>
public BEncodedNumber(long value) {
_number = value;
}
public static implicit operator BEncodedNumber(long value) {
return new BEncodedNumber(value);
}
#endregion
#region Encode/Decode Methods
/// <summary>
/// Encodes this number to the supplied byte[] starting at the supplied offset
/// </summary>
/// <param name="buffer">The buffer to write the data to</param>
/// <param name="offset">The offset to start writing the data at</param>
/// <returns></returns>
public override int Encode(byte[] buffer, int offset) {
long number = _number;
int written = offset;
buffer[written++] = (byte) 'i';
if(number < 0) {
buffer[written++] = (byte) '-';
number = -number;
}
// Reverse the number '12345' to get '54321'
long reversed = 0;
for(long i = number; i != 0; i /= 10)
reversed = reversed * 10 + i % 10;
// Write each digit of the reversed number to the array. We write '1'
// first, then '2', etc
for(long i = reversed; i != 0; i /= 10)
buffer[written++] = (byte) (i % 10 + '0');
if(number == 0)
buffer[written++] = (byte) '0';
// If the original number ends in one or more zeros, they are lost
// when we reverse the number. We add them back in here.
for(long i = number; i % 10 == 0 && number != 0; i /= 10)
buffer[written++] = (byte) '0';
buffer[written++] = (byte) 'e';
return written - offset;
}
/// <summary>
/// Decodes a BEncoded number from the supplied RawReader
/// </summary>
/// <param name="reader">RawReader containing a BEncoded Number</param>
internal override void DecodeInternal(RawReader reader) {
int sign = 1;
if(reader == null)
throw new ArgumentNullException("reader");
if(reader.ReadByte() != 'i') // remove the leading 'i'
throw new BEncodingException("Invalid data found. Aborting.");
if(reader.PeekByte() == '-') {
sign = -1;
reader.ReadByte();
}
int letter;
while(((letter = reader.PeekByte()) != -1) && letter != 'e') {
if(letter < '0' || letter > '9')
throw new BEncodingException("Invalid number found.");
_number = _number * 10 + (letter - '0');
reader.ReadByte();
}
if(reader.ReadByte() != 'e') //remove the trailing 'e'
throw new BEncodingException("Invalid data found. Aborting.");
_number *= sign;
}
#endregion
#region Helper Methods
/// <summary>
/// Returns the length of the encoded string in bytes
/// </summary>
/// <returns></returns>
public override int LengthInBytes() {
long number = _number;
int count = 2; // account for the 'i' and 'e'
if(number == 0)
return count + 1;
if(number < 0) {
number = -number;
count++;
}
for(long i = number; i != 0; i /= 10)
count++;
return count;
}
public int CompareTo(object other) {
if(other is BEncodedNumber || other is long || other is int)
return CompareTo((BEncodedNumber) other);
return -1;
}
public int CompareTo(BEncodedNumber other) {
if(other == null)
throw new ArgumentNullException("other");
return _number.CompareTo(other._number);
}
public int CompareTo(long other) {
return _number.CompareTo(other);
}
#endregion
#region Overridden Methods
/// <summary>
///
/// </summary>
/// <param name="obj"></param>
/// <returns></returns>
public override bool Equals(object obj) {
BEncodedNumber obj2 = obj as BEncodedNumber;
if(obj2 == null)
return false;
return (_number == obj2._number);
}
/// <summary>
///
/// </summary>
/// <returns></returns>
public override int GetHashCode() {
Debug.Assert(_number != null, "_textBytes != null");
return _number.GetHashCode();
}
/// <summary>
///
/// </summary>
/// <returns></returns>
public override string ToString() {
return (_number.ToString(CultureInfo.InvariantCulture));
}
#endregion
}
}
| |
using System;
using System.IO;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using EnvDTE;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.Interop;
using NuGet.VisualStudio.Resources;
namespace NuGet.VisualStudio
{
public class VsPackageManager : PackageManager, IVsPackageManager
{
private readonly ISharedPackageRepository _sharedRepository;
private readonly IDictionary<string, IProjectManager> _projects;
private readonly ISolutionManager _solutionManager;
private readonly IFileSystemProvider _fileSystemProvider;
private readonly IDeleteOnRestartManager _deleteOnRestartManager;
private readonly VsPackageInstallerEvents _packageEvents;
private bool _bindingRedirectEnabled = true;
public VsPackageManager(ISolutionManager solutionManager,
IPackageRepository sourceRepository,
IFileSystemProvider fileSystemProvider,
IFileSystem fileSystem,
ISharedPackageRepository sharedRepository,
IDeleteOnRestartManager deleteOnRestartManager,
VsPackageInstallerEvents packageEvents)
: base(sourceRepository, new DefaultPackagePathResolver(fileSystem), fileSystem, sharedRepository)
{
_solutionManager = solutionManager;
_sharedRepository = sharedRepository;
_packageEvents = packageEvents;
_fileSystemProvider = fileSystemProvider;
_deleteOnRestartManager = deleteOnRestartManager;
_projects = new Dictionary<string, IProjectManager>(StringComparer.OrdinalIgnoreCase);
}
public bool BindingRedirectEnabled
{
get { return _bindingRedirectEnabled; }
set { _bindingRedirectEnabled = value; }
}
internal void EnsureCached(Project project)
{
string projectUniqueName = project.GetUniqueName();
if (_projects.ContainsKey(projectUniqueName))
{
return;
}
_projects[projectUniqueName] = CreateProjectManager(project);
}
public virtual IProjectManager GetProjectManager(Project project)
{
EnsureCached(project);
IProjectManager projectManager;
bool projectExists = _projects.TryGetValue(project.GetUniqueName(), out projectManager);
Debug.Assert(projectExists, "Unknown project");
return projectManager;
}
private IProjectManager CreateProjectManager(Project project)
{
// Create the project system
IProjectSystem projectSystem = VsProjectSystemFactory.CreateProjectSystem(project, _fileSystemProvider);
var repository = new PackageReferenceRepository(projectSystem, _sharedRepository);
// Ensure the logger is null while registering the repository
FileSystem.Logger = null;
Logger = null;
// Ensure that this repository is registered with the shared repository if it needs to be
repository.RegisterIfNecessary();
// The source repository of the project is an aggregate since it might need to look for all
// available packages to perform updates on dependent packages
var sourceRepository = CreateProjectManagerSourceRepository();
var projectManager = new ProjectManager(sourceRepository, PathResolver, projectSystem, repository);
// The package reference repository also provides constraints for packages (via the allowedVersions attribute)
projectManager.ConstraintProvider = repository;
return projectManager;
}
public void InstallPackage(
IEnumerable<Project> projects,
IPackage package,
IEnumerable<PackageOperation> operations,
bool ignoreDependencies,
bool allowPrereleaseVersions,
ILogger logger,
IPackageOperationEventListener packageOperationEventListener)
{
if (package == null)
{
throw new ArgumentNullException("package");
}
if (operations == null)
{
throw new ArgumentNullException("operations");
}
if (projects == null)
{
throw new ArgumentNullException("projects");
}
ExecuteOperationsWithPackage(
projects,
package,
operations,
projectManager => AddPackageReference(projectManager, package.Id, package.Version, ignoreDependencies, allowPrereleaseVersions),
logger,
packageOperationEventListener);
}
public virtual void InstallPackage(
IProjectManager projectManager,
string packageId,
SemanticVersion version,
bool ignoreDependencies,
bool allowPrereleaseVersions,
ILogger logger)
{
InstallPackage(projectManager, packageId, version, ignoreDependencies, allowPrereleaseVersions,
skipAssemblyReferences: false, logger: logger);
}
public void InstallPackage(
IProjectManager projectManager,
string packageId,
SemanticVersion version,
bool ignoreDependencies,
bool allowPrereleaseVersions,
bool skipAssemblyReferences,
ILogger logger)
{
InitializeLogger(logger, projectManager);
IPackage package = PackageHelper.ResolvePackage(SourceRepository, LocalRepository, packageId, version, allowPrereleaseVersions);
if (skipAssemblyReferences)
{
package = new SkipAssemblyReferencesPackage(package);
}
RunSolutionAction(() =>
{
InstallPackage(
package,
projectManager != null ? projectManager.Project.TargetFramework : null,
ignoreDependencies,
allowPrereleaseVersions);
AddPackageReference(projectManager, package, ignoreDependencies, allowPrereleaseVersions);
});
}
public void InstallPackage(IProjectManager projectManager, IPackage package, IEnumerable<PackageOperation> operations, bool ignoreDependencies,
bool allowPrereleaseVersions, ILogger logger)
{
if (package == null)
{
throw new ArgumentNullException("package");
}
if (operations == null)
{
throw new ArgumentNullException("operations");
}
ExecuteOperationsWithPackage(
projectManager,
package,
operations,
() => AddPackageReference(projectManager, package.Id, package.Version, ignoreDependencies, allowPrereleaseVersions),
logger);
}
public void UninstallPackage(IProjectManager projectManager, string packageId, SemanticVersion version, bool forceRemove, bool removeDependencies)
{
UninstallPackage(projectManager, packageId, version, forceRemove, removeDependencies, NullLogger.Instance);
}
public virtual void UninstallPackage(IProjectManager projectManager, string packageId, SemanticVersion version, bool forceRemove, bool removeDependencies, ILogger logger)
{
EventHandler<PackageOperationEventArgs> uninstallingHandler =
(sender, e) => _packageEvents.NotifyUninstalling(e);
EventHandler<PackageOperationEventArgs> uninstalledHandler =
(sender, e) => _packageEvents.NotifyUninstalled(e);
try
{
InitializeLogger(logger, projectManager);
bool appliesToProject;
IPackage package = FindLocalPackage(projectManager,
packageId,
version,
CreateAmbiguousUninstallException,
out appliesToProject);
PackageUninstalling += uninstallingHandler;
PackageUninstalled += uninstalledHandler;
if (appliesToProject)
{
RemovePackageReference(projectManager, packageId, forceRemove, removeDependencies);
}
else
{
UninstallPackage(package, forceRemove, removeDependencies);
}
}
finally
{
PackageUninstalling -= uninstallingHandler;
PackageUninstalled -= uninstalledHandler;
}
}
public void UpdatePackage(
IEnumerable<Project> projects,
IPackage package,
IEnumerable<PackageOperation> operations,
bool updateDependencies,
bool allowPrereleaseVersions,
ILogger logger,
IPackageOperationEventListener packageOperationEventListener)
{
if (operations == null)
{
throw new ArgumentNullException("operations");
}
if (projects == null)
{
throw new ArgumentNullException("projects");
}
ExecuteOperationsWithPackage(
projects,
package,
operations,
projectManager => UpdatePackageReference(projectManager, package.Id, package.Version, updateDependencies, allowPrereleaseVersions),
logger,
packageOperationEventListener);
}
public virtual void UpdatePackage(IProjectManager projectManager, string packageId, SemanticVersion version, bool updateDependencies, bool allowPrereleaseVersions, ILogger logger)
{
UpdatePackage(projectManager,
packageId,
() => UpdatePackageReference(projectManager, packageId, version, updateDependencies, allowPrereleaseVersions),
() => SourceRepository.FindPackage(packageId, version, allowPrereleaseVersions, allowUnlisted: false),
updateDependencies,
allowPrereleaseVersions,
logger);
}
private void UpdatePackage(IProjectManager projectManager, string packageId, Action projectAction, Func<IPackage> resolvePackage, bool updateDependencies, bool allowPrereleaseVersions, ILogger logger)
{
try
{
InitializeLogger(logger, projectManager);
bool appliesToProject;
IPackage package = FindLocalPackageForUpdate(projectManager, packageId, out appliesToProject);
// Find the package we're going to update to
IPackage newPackage = resolvePackage();
if (newPackage != null && package.Version != newPackage.Version)
{
if (appliesToProject)
{
RunSolutionAction(projectAction);
}
else
{
// We might be updating a solution only package
UpdatePackage(newPackage, updateDependencies, allowPrereleaseVersions);
}
}
else
{
Logger.Log(MessageLevel.Info, VsResources.NoUpdatesAvailable, packageId);
}
}
finally
{
ClearLogger(projectManager);
}
}
public void UpdatePackages(IProjectManager projectManager, IEnumerable<IPackage> packages, IEnumerable<PackageOperation> operations, bool updateDependencies, bool allowPrereleaseVersions, ILogger logger)
{
if (packages == null)
{
throw new ArgumentNullException("packages");
}
if (operations == null)
{
throw new ArgumentNullException("operations");
}
ExecuteOperationsWithPackage(
projectManager,
null,
operations,
() =>
{
foreach (var package in packages)
{
UpdatePackageReference(projectManager, package.Id, package.Version, updateDependencies, allowPrereleaseVersions);
}
},
logger);
}
public void UpdatePackage(string packageId, IVersionSpec versionSpec, bool updateDependencies, bool allowPrereleaseVersions, ILogger logger, IPackageOperationEventListener eventListener)
{
UpdatePackage(packageId,
projectManager => UpdatePackageReference(projectManager, packageId, versionSpec, updateDependencies, allowPrereleaseVersions),
() => SourceRepository.FindPackage(packageId, versionSpec, allowPrereleaseVersions, allowUnlisted: false),
updateDependencies,
allowPrereleaseVersions,
logger,
eventListener);
}
public void UpdatePackage(string packageId, SemanticVersion version, bool updateDependencies, bool allowPrereleaseVersions, ILogger logger, IPackageOperationEventListener eventListener)
{
UpdatePackage(packageId,
projectManager => UpdatePackageReference(projectManager, packageId, version, updateDependencies, allowPrereleaseVersions),
() => SourceRepository.FindPackage(packageId, version, allowPrereleaseVersions, allowUnlisted: false),
updateDependencies,
allowPrereleaseVersions,
logger,
eventListener);
}
public void UpdatePackages(bool updateDependencies, bool allowPrereleaseVersions, ILogger logger, IPackageOperationEventListener eventListener)
{
UpdatePackages(updateDependencies, safeUpdate: false, allowPrereleaseVersions: allowPrereleaseVersions, logger: logger, eventListener: eventListener);
}
public void UpdatePackages(IProjectManager projectManager, bool updateDependencies, bool allowPrereleaseVersions, ILogger logger)
{
UpdatePackages(projectManager, updateDependencies, safeUpdate: false, allowPrereleaseVersions: allowPrereleaseVersions, logger: logger);
}
public void UpdateSolutionPackages(IEnumerable<IPackage> packages, IEnumerable<PackageOperation> operations, bool updateDependencies, bool allowPrereleaseVersions, ILogger logger, IPackageOperationEventListener eventListener)
{
if (packages == null)
{
throw new ArgumentNullException("packages");
}
if (operations == null)
{
throw new ArgumentNullException("operations");
}
try
{
InitializeLogger(logger, null);
RunSolutionAction(() =>
{
// update all packages in the 'packages' folder
foreach (var operation in operations)
{
Execute(operation);
}
if (eventListener == null)
{
eventListener = NullPackageOperationEventListener.Instance;
}
foreach (Project project in _solutionManager.GetProjects())
{
try
{
eventListener.OnBeforeAddPackageReference(project);
IProjectManager projectManager = GetProjectManager(project);
InitializeLogger(logger, projectManager);
foreach (var package in packages)
{
// only perform update when the local package exists and has smaller version than the new version
var localPackage = projectManager.LocalRepository.FindPackage(package.Id);
if (localPackage != null && localPackage.Version < package.Version)
{
UpdatePackageReference(projectManager, package.Id, package.Version, updateDependencies: true, allowPrereleaseVersions: allowPrereleaseVersions);
}
}
}
catch (Exception ex)
{
eventListener.OnAddPackageReferenceError(project, ex);
}
finally
{
eventListener.OnAfterAddPackageReference(project);
}
}
});
}
finally
{
ClearLogger(null);
}
}
public void SafeUpdatePackages(IProjectManager projectManager, bool updateDependencies, bool allowPrereleaseVersions, ILogger logger)
{
UpdatePackages(projectManager, updateDependencies, safeUpdate: true, allowPrereleaseVersions: allowPrereleaseVersions, logger: logger);
}
public void SafeUpdatePackage(string packageId, bool updateDependencies, bool allowPrereleaseVersions, ILogger logger, IPackageOperationEventListener eventListener)
{
UpdatePackage(packageId,
projectManager => UpdatePackageReference(projectManager, packageId, GetSafeRange(projectManager, packageId), updateDependencies, allowPrereleaseVersions),
() => SourceRepository.FindPackage(packageId, GetSafeRange(packageId), allowPrereleaseVersions: false, allowUnlisted: false),
updateDependencies,
allowPrereleaseVersions,
logger,
eventListener);
}
public void SafeUpdatePackage(IProjectManager projectManager, string packageId, bool updateDependencies, bool allowPrereleaseVersions, ILogger logger)
{
UpdatePackage(projectManager,
packageId,
() => UpdatePackageReference(projectManager, packageId, GetSafeRange(projectManager, packageId), updateDependencies, allowPrereleaseVersions),
() => SourceRepository.FindPackage(packageId, GetSafeRange(packageId), allowPrereleaseVersions: false, allowUnlisted: false),
updateDependencies,
allowPrereleaseVersions,
logger);
}
public void SafeUpdatePackages(bool updateDependencies, bool allowPrereleaseVersions, ILogger logger, IPackageOperationEventListener eventListener)
{
UpdatePackages(updateDependencies, safeUpdate: true, allowPrereleaseVersions: allowPrereleaseVersions, logger: logger, eventListener: eventListener);
}
// Reinstall all packages in all projects
public void ReinstallPackages(
bool updateDependencies,
bool allowPrereleaseVersions,
ILogger logger,
IPackageOperationEventListener eventListener)
{
UpdatePackages(
LocalRepository,
package => ReinstallPackage(
package.Id,
updateDependencies: updateDependencies,
allowPrereleaseVersions: allowPrereleaseVersions,
logger: logger,
eventListener: eventListener),
logger);
}
// Reinstall all packages in the specified project
public void ReinstallPackages(
IProjectManager projectManager,
bool updateDependencies,
bool allowPrereleaseVersions,
ILogger logger)
{
UpdatePackages(
projectManager.LocalRepository,
package => ReinstallPackageInProject(projectManager, package, updateDependencies, allowPrereleaseVersions, logger),
logger);
}
/// <summary>
/// Reinstall the specified package in all projects.
/// </summary>
public void ReinstallPackage(
string packageId,
bool updateDependencies,
bool allowPrereleaseVersions,
ILogger logger,
IPackageOperationEventListener eventListener)
{
bool appliesToProject;
IPackage package = FindLocalPackage(packageId, out appliesToProject);
if (appliesToProject)
{
ReinstallPackageToAllProjects(packageId, updateDependencies, allowPrereleaseVersions, logger, eventListener);
}
else
{
ReinstallSolutionPackage(package, updateDependencies, allowPrereleaseVersions, logger);
}
}
/// <summary>
/// Reinstall the specified package in the specified project.
/// </summary>
public void ReinstallPackage(
IProjectManager projectManager,
string packageId,
bool updateDependencies,
bool allowPrereleaseVersions,
ILogger logger)
{
bool appliesToProject;
IPackage package = FindLocalPackageForUpdate(projectManager, packageId, out appliesToProject);
if (appliesToProject)
{
ReinstallPackageInProject(projectManager, package, updateDependencies, allowPrereleaseVersions, logger);
}
else
{
ReinstallSolutionPackage(package, updateDependencies, allowPrereleaseVersions, logger);
}
}
/// <summary>
/// Reinstall the specified package in the specified project, taking care of logging too.
/// </summary>
private void ReinstallPackageInProject(
IProjectManager projectManager,
IPackage package,
bool updateDependencies,
bool allowPrereleaseVersions,
ILogger logger)
{
logger = logger ?? NullLogger.Instance;
try
{
InitializeLogger(logger, projectManager);
logger.Log(MessageLevel.Info, VsResources.ReinstallProjectPackage, package, projectManager.Project.ProjectName);
// Before we start reinstalling, need to make sure the package exists in the source repository.
// Otherwise, the package will be uninstalled and can't be reinstalled.
if (SourceRepository.Exists(package))
{
RunSolutionAction(
() =>
{
UninstallPackage(
projectManager,
package.Id,
package.Version,
forceRemove: true,
removeDependencies: updateDependencies,
logger: logger);
InstallPackage(
projectManager,
package.Id,
package.Version,
ignoreDependencies: !updateDependencies,
allowPrereleaseVersions: allowPrereleaseVersions || !package.IsReleaseVersion(),
logger: logger);
});
}
else
{
logger.Log(
MessageLevel.Warning,
VsResources.PackageRestoreSkipForProject,
package.GetFullName(),
projectManager.Project.ProjectName);
}
}
finally
{
ClearLogger(projectManager);
}
}
// Reinstall one package in all projects.
// We need to uninstall the package from all projects BEFORE
// reinstalling it back, so that the package will be refreshed from source repository.
private void ReinstallPackageToAllProjects(
string packageId,
bool updateDependencies,
bool allowPrereleaseVersions,
ILogger logger,
IPackageOperationEventListener eventListener)
{
logger = logger ?? NullLogger.Instance;
eventListener = eventListener ?? NullPackageOperationEventListener.Instance;
var projectsHasPackage = new Dictionary<Project, SemanticVersion>();
var versionsChecked = new Dictionary<SemanticVersion, bool>();
// first uninstall from all projects that has the package installed
RunActionOnProjects(
_solutionManager.GetProjects(),
project =>
{
IProjectManager projectManager = GetProjectManager(project);
// find the package version installed in this project
IPackage projectPackage = projectManager.LocalRepository.FindPackage(packageId);
if (projectPackage != null)
{
bool packageExistInSource;
if (!versionsChecked.TryGetValue(projectPackage.Version, out packageExistInSource))
{
// version has not been checked, so check it here
packageExistInSource = SourceRepository.Exists(packageId, projectPackage.Version);
// mark the version as checked so that we don't have to check again if we
// encounter another project with the same version.
versionsChecked[projectPackage.Version] = packageExistInSource;
}
if (packageExistInSource)
{
// save the version installed in this project so that we can restore the correct version later
projectsHasPackage.Add(project, projectPackage.Version);
UninstallPackage(
projectManager,
packageId,
version: null,
forceRemove: true,
removeDependencies: updateDependencies,
logger: logger);
}
else
{
logger.Log(
MessageLevel.Warning,
VsResources.PackageRestoreSkipForProject,
projectPackage.GetFullName(),
project.Name);
}
}
},
logger,
eventListener);
// now reinstall back to all the affected projects
RunActionOnProjects(
projectsHasPackage.Keys,
project =>
{
var projectManager = GetProjectManager(project);
if (!projectManager.LocalRepository.Exists(packageId))
{
SemanticVersion oldVersion = projectsHasPackage[project];
InstallPackage(
projectManager,
packageId,
version: oldVersion,
ignoreDependencies: !updateDependencies,
allowPrereleaseVersions: allowPrereleaseVersions || !String.IsNullOrEmpty(oldVersion.SpecialVersion),
logger: logger);
}
},
logger,
eventListener);
}
private void ReinstallSolutionPackage(
IPackage package,
bool updateDependencies,
bool allowPrereleaseVersions,
ILogger logger)
{
logger = logger ?? NullLogger.Instance;
try
{
InitializeLogger(logger);
logger.Log(MessageLevel.Info, VsResources.ReinstallSolutionPackage, package);
if (SourceRepository.Exists(package))
{
RunSolutionAction(
() =>
{
UninstallPackage(package, forceRemove: true, removeDependencies: !updateDependencies);
// Bug 2883: We must NOT use the overload that accepts 'package' object here,
// because after the UninstallPackage() call above, the package no longer exists.
InstallPackage(package.Id, package.Version, ignoreDependencies: !updateDependencies, allowPrereleaseVersions: allowPrereleaseVersions || !package.IsReleaseVersion());
});
}
else
{
logger.Log(
MessageLevel.Warning,
VsResources.PackageRestoreSkipForSolution,
package.GetFullName());
}
}
finally
{
ClearLogger();
}
}
protected override void ExecuteUninstall(IPackage package)
{
// Check if the package is in use before removing it
if (!_sharedRepository.IsReferenced(package.Id, package.Version))
{
base.ExecuteUninstall(package);
}
}
private IPackage FindLocalPackageForUpdate(IProjectManager projectManager, string packageId, out bool appliesToProject)
{
return FindLocalPackage(projectManager, packageId, null /* version */, CreateAmbiguousUpdateException, out appliesToProject);
}
private IPackage FindLocalPackage(IProjectManager projectManager,
string packageId,
SemanticVersion version,
Func<IProjectManager, IList<IPackage>, Exception> getAmbiguousMatchException,
out bool appliesToProject)
{
IPackage package = null;
bool existsInProject = false;
appliesToProject = false;
if (projectManager != null)
{
// Try the project repository first
package = projectManager.LocalRepository.FindPackage(packageId, version);
existsInProject = package != null;
}
// Fallback to the solution repository (it might be a solution only package)
if (package == null)
{
if (version != null)
{
// Get the exact package
package = LocalRepository.FindPackage(packageId, version);
}
else
{
// Get all packages by this name to see if we find an ambiguous match
var packages = LocalRepository.FindPackagesById(packageId).ToList();
if (packages.Count > 1)
{
throw getAmbiguousMatchException(projectManager, packages);
}
// Pick the only one of default if none match
package = packages.SingleOrDefault();
}
}
// Can't find the package in the solution or in the project then fail
if (package == null)
{
throw new InvalidOperationException(
String.Format(CultureInfo.CurrentCulture,
VsResources.UnknownPackage, packageId));
}
appliesToProject = IsProjectLevel(package);
if (appliesToProject)
{
if (!existsInProject)
{
if (_sharedRepository.IsReferenced(package.Id, package.Version))
{
// If the package doesn't exist in the project and is referenced by other projects
// then fail.
if (projectManager != null)
{
if (version == null)
{
throw new InvalidOperationException(
String.Format(CultureInfo.CurrentCulture,
VsResources.UnknownPackageInProject,
package.Id,
projectManager.Project.ProjectName));
}
throw new InvalidOperationException(
String.Format(CultureInfo.CurrentCulture,
VsResources.UnknownPackageInProject,
package.GetFullName(),
projectManager.Project.ProjectName));
}
}
else
{
// The operation applies to solution level since it's not installed in the current project
// but it is installed in some other project
appliesToProject = false;
}
}
}
// Can't have a project level operation if no project was specified
if (appliesToProject && projectManager == null)
{
throw new InvalidOperationException(VsResources.ProjectNotSpecified);
}
return package;
}
private IPackage FindLocalPackage(string packageId, out bool appliesToProject)
{
// It doesn't matter if there are multiple versions of the package installed at solution level,
// we just want to know that one exists.
var packages = LocalRepository.FindPackagesById(packageId).ToList();
// Can't find the package in the solution.
if (!packages.Any())
{
throw new InvalidOperationException(
String.Format(CultureInfo.CurrentCulture,
VsResources.UnknownPackage, packageId));
}
IPackage package = packages.FirstOrDefault();
appliesToProject = IsProjectLevel(package);
if (!appliesToProject)
{
if (packages.Count > 1)
{
throw CreateAmbiguousUpdateException(projectManager: null, packages: packages);
}
}
else if (!_sharedRepository.IsReferenced(package.Id, package.Version))
{
// If this package applies to a project but isn't installed in any project then
// it's probably a borked install.
throw new PackageNotInstalledException(
String.Format(CultureInfo.CurrentCulture,
VsResources.PackageNotInstalledInAnyProject, packageId));
}
return package;
}
/// <summary>
/// Check to see if this package applies to a project based on 2 criteria:
/// 1. The package has project content (i.e. content that can be applied to a project lib or content files)
/// 2. The package is referenced by any other project
///
/// This logic will probably fail in one edge case. If there is a meta package that applies to a project
/// that ended up not being installed in any of the projects and it only exists at solution level.
/// If this happens, then we think that the following operation applies to the solution instead of showing an error.
/// To solve that edge case we'd have to walk the graph to find out what the package applies to.
/// </summary>
public bool IsProjectLevel(IPackage package)
{
return package.HasProjectContent() || _sharedRepository.IsReferenced(package.Id, package.Version);
}
private Exception CreateAmbiguousUpdateException(IProjectManager projectManager, IList<IPackage> packages)
{
if (projectManager != null && packages.Any(IsProjectLevel))
{
return new InvalidOperationException(
String.Format(CultureInfo.CurrentCulture,
VsResources.UnknownPackageInProject,
packages[0].Id,
projectManager.Project.ProjectName));
}
return new InvalidOperationException(
String.Format(CultureInfo.CurrentCulture,
VsResources.AmbiguousUpdate,
packages[0].Id));
}
private Exception CreateAmbiguousUninstallException(IProjectManager projectManager, IList<IPackage> packages)
{
if (projectManager != null && packages.Any(IsProjectLevel))
{
return new InvalidOperationException(
String.Format(CultureInfo.CurrentCulture,
VsResources.AmbiguousProjectLevelUninstal,
packages[0].Id,
projectManager.Project.ProjectName));
}
return new InvalidOperationException(
String.Format(CultureInfo.CurrentCulture,
VsResources.AmbiguousUninstall,
packages[0].Id));
}
private void RemovePackageReference(IProjectManager projectManager, string packageId, bool forceRemove, bool removeDependencies)
{
RunProjectAction(projectManager, () => projectManager.RemovePackageReference(packageId, forceRemove, removeDependencies));
}
private void UpdatePackageReference(IProjectManager projectManager, string packageId, SemanticVersion version, bool updateDependencies, bool allowPrereleaseVersions)
{
RunProjectAction(projectManager, () => projectManager.UpdatePackageReference(packageId, version, updateDependencies, allowPrereleaseVersions));
}
private void UpdatePackageReference(IProjectManager projectManager, string packageId, IVersionSpec versionSpec, bool updateDependencies, bool allowPrereleaseVersions)
{
RunProjectAction(projectManager, () => projectManager.UpdatePackageReference(packageId, versionSpec, updateDependencies, allowPrereleaseVersions));
}
private void AddPackageReference(IProjectManager projectManager, string packageId, SemanticVersion version, bool ignoreDependencies, bool allowPrereleaseVersions)
{
RunProjectAction(projectManager, () => projectManager.AddPackageReference(packageId, version, ignoreDependencies, allowPrereleaseVersions));
}
private void AddPackageReference(IProjectManager projectManager, IPackage package, bool ignoreDependencies, bool allowPrereleaseVersions)
{
RunProjectAction(projectManager, () => projectManager.AddPackageReference(package, ignoreDependencies, allowPrereleaseVersions));
}
private void ExecuteOperationsWithPackage(IEnumerable<Project> projects, IPackage package, IEnumerable<PackageOperation> operations, Action<IProjectManager> projectAction, ILogger logger, IPackageOperationEventListener eventListener)
{
if (eventListener == null)
{
eventListener = NullPackageOperationEventListener.Instance;
}
ExecuteOperationsWithPackage(
null,
package,
operations,
() =>
{
bool successfulAtLeastOnce = false;
foreach (var project in projects)
{
try
{
eventListener.OnBeforeAddPackageReference(project);
IProjectManager projectManager = GetProjectManager(project);
InitializeLogger(logger, projectManager);
projectAction(projectManager);
successfulAtLeastOnce = true;
}
catch (Exception ex)
{
eventListener.OnAddPackageReferenceError(project, ex);
}
finally
{
eventListener.OnAfterAddPackageReference(project);
}
}
// Throw an exception only if all the update failed for all projects
// so we rollback any solution level operations that might have happened
if (projects.Any() && !successfulAtLeastOnce)
{
throw new InvalidOperationException(VsResources.OperationFailed);
}
},
logger);
}
private void ExecuteOperationsWithPackage(IProjectManager projectManager, IPackage package, IEnumerable<PackageOperation> operations, Action action, ILogger logger)
{
try
{
InitializeLogger(logger, projectManager);
RunSolutionAction(() =>
{
if (operations.Any())
{
foreach (var operation in operations)
{
Execute(operation);
}
}
else if (package != null && LocalRepository.Exists(package))
{
Logger.Log(MessageLevel.Info, VsResources.Log_PackageAlreadyInstalled, package.GetFullName());
}
action();
});
}
finally
{
ClearLogger(projectManager);
}
}
private Project GetProject(IProjectManager projectManager)
{
// We only support project systems that implement IVsProjectSystem
var vsProjectSystem = projectManager.Project as IVsProjectSystem;
if (vsProjectSystem == null)
{
return null;
}
// Find the project by it's unique name
return _solutionManager.GetProject(vsProjectSystem.UniqueName);
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "If we failed to add binding redirects we don't want it to stop the install/update.")]
private void AddBindingRedirects(IProjectManager projectManager)
{
// Find the project by it's unique name
Project project = GetProject(projectManager);
// If we can't find the project or it doesn't support binding redirects then don't add any redirects
if (project == null || !project.SupportsBindingRedirects())
{
return;
}
try
{
RuntimeHelpers.AddBindingRedirects(_solutionManager, project, _fileSystemProvider);
}
catch (Exception e)
{
// If there was an error adding binding redirects then print a warning and continue
Logger.Log(MessageLevel.Warning, String.Format(CultureInfo.CurrentCulture, VsResources.Warning_FailedToAddBindingRedirects, projectManager.Project.ProjectName, e.Message));
}
}
private void InitializeLogger(ILogger logger, IProjectManager projectManager = null)
{
// Setup logging on all of our objects
Logger = logger;
FileSystem.Logger = logger;
if (projectManager != null)
{
projectManager.Logger = logger;
projectManager.Project.Logger = logger;
}
}
private void ClearLogger(IProjectManager projectManager = null)
{
// clear logging on all of our objects
Logger = null;
FileSystem.Logger = null;
if (projectManager != null)
{
projectManager.Logger = null;
projectManager.Project.Logger = null;
}
}
/// <summary>
/// Runs the specified action and rolls back any installed packages if on failure.
/// </summary>
private void RunSolutionAction(Action action)
{
var packagesAdded = new List<IPackage>();
EventHandler<PackageOperationEventArgs> installHandler = (sender, e) =>
{
// Record packages that we are installing so that if one fails, we can rollback
packagesAdded.Add(e.Package);
_packageEvents.NotifyInstalling(e);
};
EventHandler<PackageOperationEventArgs> installedHandler = (sender, e) =>
{
_packageEvents.NotifyInstalled(e);
};
PackageInstalling += installHandler;
PackageInstalled += installedHandler;
try
{
// Execute the action
action();
}
catch
{
if (packagesAdded.Any())
{
// Only print the rollback warning if we have something to rollback
Logger.Log(MessageLevel.Warning, VsResources.Warning_RollingBack);
}
// Don't log anything during the rollback
Logger = null;
// Rollback the install if it fails
Uninstall(packagesAdded);
throw;
}
finally
{
// Remove the event handler
PackageInstalling -= installHandler;
PackageInstalled -= installedHandler;
}
}
/// <summary>
/// Runs the action on projects and log any error that may occur.
/// </summary>
private void RunActionOnProjects(
IEnumerable<Project> projects,
Action<Project> action,
ILogger logger,
IPackageOperationEventListener eventListener)
{
foreach (var project in projects)
{
try
{
eventListener.OnBeforeAddPackageReference(project);
action(project);
}
catch (Exception exception)
{
logger.Log(MessageLevel.Error, ExceptionUtility.Unwrap(exception).Message);
eventListener.OnAddPackageReferenceError(project, exception);
}
finally
{
eventListener.OnAfterAddPackageReference(project);
}
}
}
/// <summary>
/// Runs action on the project manager and rollsback any package installs if it fails.
/// </summary>
private void RunProjectAction(IProjectManager projectManager, Action action)
{
if (projectManager == null)
{
return;
}
// Keep track of what was added and removed
var packagesAdded = new Stack<IPackage>();
var packagesRemoved = new List<IPackage>();
EventHandler<PackageOperationEventArgs> removeHandler = (sender, e) =>
{
packagesRemoved.Add(e.Package);
_packageEvents.NotifyReferenceRemoved(e);
};
EventHandler<PackageOperationEventArgs> addingHandler = (sender, e) =>
{
packagesAdded.Push(e.Package);
_packageEvents.NotifyReferenceAdded(e);
// If this package doesn't exist at solution level (it might not be because of leveling)
// then we need to install it.
if (!LocalRepository.Exists(e.Package))
{
ExecuteInstall(e.Package);
}
};
// Try to get the project for this project manager
Project project = GetProject(projectManager);
IVsProjectBuildSystem build = null;
if (project != null)
{
build = project.ToVsProjectBuildSystem();
}
// Add the handlers
projectManager.PackageReferenceRemoved += removeHandler;
projectManager.PackageReferenceAdding += addingHandler;
try
{
if (build != null)
{
// Start a batch edit so there is no background compilation until we're done
// processing project actions
build.StartBatchEdit();
}
action();
if (BindingRedirectEnabled && projectManager.Project.IsBindingRedirectSupported)
{
// Only add binding redirects if install was successful
AddBindingRedirects(projectManager);
}
}
catch
{
// We need to Remove the handlers here since we're going to attempt
// a rollback and we don't want modify the collections while rolling back.
projectManager.PackageReferenceRemoved -= removeHandler;
projectManager.PackageReferenceAdded -= addingHandler;
// When things fail attempt a rollback
RollbackProjectActions(projectManager, packagesAdded, packagesRemoved);
// Rollback solution packages
Uninstall(packagesAdded);
// Clear removed packages so we don't try to remove them again (small optimization)
packagesRemoved.Clear();
throw;
}
finally
{
if (build != null)
{
// End the batch edit when we are done.
build.EndBatchEdit();
}
// Remove the handlers
projectManager.PackageReferenceRemoved -= removeHandler;
projectManager.PackageReferenceAdding -= addingHandler;
// Remove any packages that would be removed as a result of updating a dependency or the package itself
// We can execute the uninstall directly since we don't need to resolve dependencies again.
Uninstall(packagesRemoved);
}
}
private static void RollbackProjectActions(IProjectManager projectManager, IEnumerable<IPackage> packagesAdded, IEnumerable<IPackage> packagesRemoved)
{
// Disable logging when rolling back project operations
projectManager.Logger = null;
foreach (var package in packagesAdded)
{
// Remove each package that was added
projectManager.RemovePackageReference(package, forceRemove: false, removeDependencies: false);
}
foreach (var package in packagesRemoved)
{
// Add each package that was removed
projectManager.AddPackageReference(package, ignoreDependencies: true, allowPrereleaseVersions: true);
}
}
private void Uninstall(IEnumerable<IPackage> packages)
{
// Packages added to the sequence are added in the order in which they were visited. However for operations on satellite packages to work correctly,
// we need to ensure they are always uninstalled prior to the corresponding core package. To address this, we run it by Reduce which reorders it for us and ensures it
// returns the minimal set of operations required.
var packageOperations = packages.Select(p => new PackageOperation(p, PackageAction.Uninstall))
.Reduce();
foreach (var operation in packageOperations)
{
ExecuteUninstall(operation.Package);
}
}
private void UpdatePackage(string packageId, Action<IProjectManager> projectAction, Func<IPackage> resolvePackage, bool updateDependencies, bool allowPrereleaseVersions,
ILogger logger, IPackageOperationEventListener eventListener)
{
bool appliesToProject;
IPackage package = FindLocalPackage(packageId, out appliesToProject);
if (appliesToProject)
{
eventListener = eventListener ?? NullPackageOperationEventListener.Instance;
foreach (var project in _solutionManager.GetProjects())
{
IProjectManager projectManager = GetProjectManager(project);
try
{
InitializeLogger(logger, projectManager);
if (projectManager.LocalRepository.Exists(packageId))
{
eventListener.OnBeforeAddPackageReference(project);
try
{
RunSolutionAction(() => projectAction(projectManager));
}
catch (Exception e)
{
logger.Log(MessageLevel.Error, ExceptionUtility.Unwrap(e).Message);
eventListener.OnAddPackageReferenceError(project, e);
}
finally
{
eventListener.OnAfterAddPackageReference(project);
}
}
}
finally
{
ClearLogger(projectManager);
}
}
}
else
{
// Find the package we're going to update to
IPackage newPackage = resolvePackage();
if (newPackage != null && package.Version != newPackage.Version)
{
try
{
InitializeLogger(logger, projectManager: null);
// We might be updating a solution only package
UpdatePackage(newPackage, updateDependencies, allowPrereleaseVersions);
}
finally
{
ClearLogger(projectManager: null);
}
}
else
{
logger.Log(MessageLevel.Info, VsResources.NoUpdatesAvailable, packageId);
}
}
}
private void UpdatePackages(IProjectManager projectManager, bool updateDependencies, bool safeUpdate, bool allowPrereleaseVersions, ILogger logger)
{
UpdatePackages(projectManager.LocalRepository, package =>
{
if (safeUpdate)
{
SafeUpdatePackage(projectManager, package.Id, updateDependencies, allowPrereleaseVersions, logger);
}
else
{
UpdatePackage(projectManager, package.Id, version: null, updateDependencies: updateDependencies,
allowPrereleaseVersions: allowPrereleaseVersions, logger: logger);
}
}, logger);
}
private void UpdatePackages(bool updateDependencies, bool safeUpdate, bool allowPrereleaseVersions, ILogger logger, IPackageOperationEventListener eventListener)
{
UpdatePackages(LocalRepository, package =>
{
if (safeUpdate)
{
SafeUpdatePackage(package.Id, updateDependencies, allowPrereleaseVersions, logger, eventListener);
}
else
{
UpdatePackage(package.Id, version: null, updateDependencies: updateDependencies, allowPrereleaseVersions: allowPrereleaseVersions, logger: logger, eventListener: eventListener);
}
},
logger);
}
private void UpdatePackages(IPackageRepository localRepository, Action<IPackage> updateAction, ILogger logger)
{
var packageSorter = new PackageSorter(targetFramework: null);
// Get the packages in reverse dependency order then run update on each one i.e. if A -> B run Update(A) then Update(B)
var packages = packageSorter.GetPackagesByDependencyOrder(localRepository).Reverse();
foreach (var package in packages)
{
// While updating we might remove packages that were initially in the list. e.g.
// A 1.0 -> B 2.0, A 2.0 -> [], since updating to A 2.0 removes B, we end up skipping it.
if (localRepository.Exists(package.Id))
{
try
{
updateAction(package);
}
catch (PackageNotInstalledException e)
{
logger.Log(MessageLevel.Warning, ExceptionUtility.Unwrap(e).Message);
}
catch (Exception e)
{
logger.Log(MessageLevel.Error, ExceptionUtility.Unwrap(e).Message);
}
}
}
}
private IPackageRepository CreateProjectManagerSourceRepository()
{
// The source repo for the project manager is the aggregate of the shared repo and the selected repo.
// For dependency resolution, we want VS to look for packages in the selected source and then use the fallback logic
var fallbackRepository = SourceRepository as FallbackRepository;
if (fallbackRepository != null)
{
var primaryRepositories = new[] { _sharedRepository, fallbackRepository.SourceRepository.Clone() };
return new FallbackRepository(new AggregateRepository(primaryRepositories), fallbackRepository.DependencyResolver);
}
return new AggregateRepository(new[] { _sharedRepository, SourceRepository.Clone() });
}
private IVersionSpec GetSafeRange(string packageId)
{
bool appliesToProject;
IPackage package = FindLocalPackage(packageId, out appliesToProject);
return VersionUtility.GetSafeRange(package.Version);
}
private IVersionSpec GetSafeRange(IProjectManager projectManager, string packageId)
{
bool appliesToProject;
IPackage package = FindLocalPackageForUpdate(projectManager, packageId, out appliesToProject);
return VersionUtility.GetSafeRange(package.Version);
}
protected override void OnUninstalled(PackageOperationEventArgs e)
{
base.OnUninstalled(e);
_deleteOnRestartManager.MarkPackageDirectoryForDeletion(e.Package);
}
}
}
| |
// Author: abi
// Project: DungeonQuest
// Path: C:\code\Xna\DungeonQuest\GameScreens
// Creation date: 28.03.2007 01:01
// Last modified: 31.07.2007 04:40
#region Using directives
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Globalization;
using System.Threading;
using System.Diagnostics;
using System.Runtime.Serialization;
using DungeonQuest.Helpers;
using DungeonQuest.Graphics;
using DungeonQuest.Properties;
using DungeonQuest.Game;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
#endregion
namespace DungeonQuest.GameScreens
{
/// <summary>
/// Highscores
/// </summary>
class Highscores : IGameScreen
{
#region Variables
/// <summary>
/// Highscore modes
/// </summary>
private enum HighscoreModes
{
Local,
//obs: OnlineThisHour,
//OnlineTotal,
} // enum HighscoreModes
/// <summary>
/// Current highscore mode, initially set to local.
/// </summary>
private HighscoreModes highscoreMode = HighscoreModes.Local;
#endregion
#region Properties
/// <summary>
/// Name of this game screen
/// </summary>
/// <returns>String</returns>
public string Name
{
get
{
return "Highscores";
} // get
} // Name
private bool quit = false;
/// <summary>
/// Returns true if we want to quit this screen and return to the
/// previous screen. If no more screens are left the game is exited.
/// </summary>
/// <returns>Bool</returns>
public bool Quit
{
get
{
return quit;
} // get
} // Quit
#endregion
#region Highscore helper class
/// <summary>
/// Highscore helper class
/// </summary>
public struct Highscore
{
/// <summary>
/// Player name
/// </summary>
public string name;
/// <summary>
/// Level name
/// </summary>
public string level;
/// <summary>
/// Highscore points
/// </summary>
public int points;
/// <summary>
/// Create highscore
/// </summary>
/// <param name="setName">Set name</param>
/// <param name="setLevelName">Set level name</param>
/// <param name="setPoints">Set points</param>
public Highscore(string setName, string setLevelName, int setPoints)
{
name = setName;
level = setLevelName;
points = setPoints;
} // Highscore(setName, setLevelName, setPoints)
/// <summary>
/// To string
/// </summary>
/// <returns>String</returns>
public override string ToString()
{
return name + ":" + level + ":" + points;
} // ToString()
} // struct Highscore
/// <summary>
/// Number of highscores displayed in this screen.
/// </summary>
public const int NumOfHighscores = 10;
/// <summary>
/// List of remembered highscores.
/// </summary>
private static Highscore[] highscores = new Highscore[NumOfHighscores];
/// <summary>
/// Get top highscore, displayed in the upper right when playing.
/// </summary>
public static int TopHighscore
{
get
{
return highscores[0].points;
} // get
} // TopHighscore
/// <summary>
/// Get all highscores, displayed on the game over screen.
/// </summary>
/// <returns>Int</returns>
public static Highscore[] AllHighscores
{
get
{
return highscores;
} // get
} // AllHighscores
/// <summary>
/// Write highscores to string. Used to save to settings.
/// </summary>
private static void WriteHighscoresToSettings()
{
GameSettings.Default.Highscores = StringHelper.WriteArrayData(highscores);
} // WriteHighscoresToSettings()
/// <summary>
/// Read highscores from settings
/// </summary>
/// <returns>True if reading succeeded, false otherwise.</returns>
private static bool ReadHighscoresFromSettings()
{
if (String.IsNullOrEmpty(GameSettings.Default.Highscores))
return false;
try
{
string[] allHighscores = GameSettings.Default.Highscores.Split(
new char[] { ',' });
for (int num = 0; num < allHighscores.Length &&
num < highscores.Length; num++)
{
string[] oneHighscore =
StringHelper.SplitAndTrim(allHighscores[num], ':');
highscores[num] = new Highscore(
oneHighscore[0], oneHighscore[1],
Convert.ToInt32(oneHighscore[2]));
} // for (num)
return true;
} // try
catch (Exception ex)
{
Log.Write("Failed to load highscores: " + ex.ToString());
return false;
} // catch
} // ReadHighscoresFromSettings()
#endregion
#region Static constructor
/// <summary>
/// Default level name
/// </summary>
public static string DefaultLevelName = "Apocalypse";
/// <summary>
/// Create Highscores class, will basically try to load highscore list,
/// if that fails we generate a standard highscore list!
/// </summary>
static Highscores()
{
//obs: gameFileHash = GenerateHashFromFile("Rocket Commander.exe");
if (ReadHighscoresFromSettings() == false)
{
// Generate default list
highscores[9] = new Highscore("Newbie", DefaultLevelName, 0);
highscores[8] = new Highscore("Master_L", DefaultLevelName, 50);
highscores[7] = new Highscore("Freshman", DefaultLevelName, 100);
highscores[6] = new Highscore("Desert-Fox", DefaultLevelName, 150);
highscores[5] = new Highscore("Judge", DefaultLevelName, 200);
highscores[4] = new Highscore("ViperDK", DefaultLevelName, 250);
highscores[3] = new Highscore("Netfreak", DefaultLevelName, 300);
highscores[2] = new Highscore("exDreamBoy", DefaultLevelName, 350);
highscores[1] = new Highscore("Waii", DefaultLevelName, 400);
highscores[0] = new Highscore("abi", DefaultLevelName, 450);
WriteHighscoresToSettings();
} // if (ReadHighscoresFromSettings)
} // Highscores()
#endregion
#region Constructor
/// <summary>
/// Create highscores
/// </summary>
public Highscores()
{
} // Highscores()
#endregion
#region Get rank from current score
/// <summary>
/// Get rank from current score.
/// Used in game to determinate rank while flying around ^^
/// </summary>
/// <param name="score">Score</param>
/// <returns>Int</returns>
public static int GetRankFromCurrentScore(int score)
{
// Just compare with all highscores and return the rank we have reached.
for (int num = 0; num < highscores.Length; num++)
{
if (score >= highscores[num].points)
return num;
} // for (num)
// No Rank found, use rank 11
return highscores.Length;
} // GetRankFromCurrentScore(score)
#endregion
#region Submit highscore after game
//obs: static bool onlineUploadHighscoreFailedAlreadyLogged = false;
/// <summary>
/// Submit highscore. Done after each game is over (won or lost).
/// New highscore will be added to the highscore screen and send
/// to the online server.
/// </summary>
/// <param name="score">Score</param>
/// <param name="levelName">Level name</param>
public static void SubmitHighscore(int score, string levelName)
{
// Search which highscore rank we can replace
for (int num = 0; num < highscores.Length; num++)
{
if (score >= highscores[num].points)
{
// Move all highscores up
for (int moveUpNum = highscores.Length - 1; moveUpNum > num;
moveUpNum--)
{
highscores[moveUpNum] = highscores[moveUpNum - 1];
} // for (moveUpNum)
// Add this highscore into the local highscore table
highscores[num].name = GameSettings.Default.PlayerName;
highscores[num].level = levelName;
highscores[num].points = score;
// And save that
Highscores.WriteHighscoresToSettings();
break;
} // if
} // for (num)
// Else no highscore was reached, we can't replace any rank.
/*can't do on the Xbox 360!
// Upload highscore to server with help of the webservice :)
// Do this asyncronly, it could take a while and we don't want to wait
// for it to complete (there is no return value anyway).
new Thread(new ThreadStart(
* etc.
*/
} // SubmitHighscore(score)
#endregion
#region Get online highscores
Highscore[] onlineHighscores = new Highscore[10];
//obs: Thread onlineGetHighscoreThread = null;
/// <summary>
/// Get online highscores
/// </summary>
/// <param name="onlyThisHour">Only this hour</param>
private void GetOnlineHighscores(bool onlyThisHour)
{
// Clear all online highscores and wait for a new update!
for (int num = 0; num < onlineHighscores.Length; num++)
{
onlineHighscores[num].name = "-";
onlineHighscores[num].level = "";
onlineHighscores[num].points = 0;
} // for (num)
/*obs
// Stop any old threads
if (onlineGetHighscoreThread != null)
onlineGetHighscoreThread.Abort();
// Ask web service for highscore list! Do this asyncronly,
// it could take a while and we don't want to wait for it to complete.
onlineGetHighscoreThread = new Thread(new ThreadStart(
// Anoymous delegates, isn't .NET 2.0 great? ^^
* etc.
*/
} // GetOnlineHighscores(onlyThisHour)
#endregion
#region Run
/// <summary>
/// Run game screen. Called each frame.
/// </summary>
/// <param name="game">Form for access to asteroid manager and co</param>
public void Run(DungeonQuestGame game)
{
// Render background
game.RenderMenuBackground();
// Show highscores, allow to select between local highscores,
// online highscores this hour and online highscores best of all time.
int xPos = 100 * BaseGame.Width / 1024;
int yPos = 260 * BaseGame.Height / 768;
TextureFont.WriteText(xPos, yPos,
"Highscores:");
// Local Highscores
Rectangle rect = new Rectangle(
xPos + 210 * BaseGame.Width / 1024,
yPos + 0 * BaseGame.Height / 768, 130, 28);
bool highlighted = Input.MouseInBox(rect);
TextureFont.WriteText(rect.X, rect.Y, "Local",
highscoreMode == HighscoreModes.Local ? Color.Red :
highlighted ? Color.LightSalmon : Color.White);
if (highlighted &&
Input.MouseLeftButtonJustPressed)
highscoreMode = HighscoreModes.Local;
yPos = 310 * BaseGame.Height / 768;
Highscore[] selectedHighscores =
highscoreMode == HighscoreModes.Local ?
highscores : onlineHighscores;
for (int num = 0; num < NumOfHighscores; num++)
{
Color col = Input.MouseInBox(new Rectangle(
xPos, yPos + num * 30, 600 + 200, 28)) ?
Color.White : ColorHelper.FromArgb(200, 200, 200);
TextureFont.WriteText(xPos, yPos + num * 29,
(1 + num) + ".", col);
TextureFont.WriteText(xPos + 50, yPos + num * 30,
selectedHighscores[num].name, col);
TextureFont.WriteText(xPos + 340, yPos + num * 30,
"Score: " + selectedHighscores[num].points, col);
TextureFont.WriteText(xPos + 610, yPos + num * 30,
"Mission: " + selectedHighscores[num].level, col);
} // for (num)
/*TODO
if (game.RenderMenuButton(MenuButton.Back,
new Point(1024 - 230, 768 - 150)))
{
quit = true;
} // if
*/
} // Run(game)
#endregion
} // class Highscores
} // namespace DungeonQuest.GameScreens
| |
namespace AngleSharp.Css.Parser
{
using AngleSharp.Css.Dom;
using AngleSharp.Css.Values;
using AngleSharp.Text;
using System;
using System.Globalization;
using System.Text;
static class UnitParser
{
public static Unit ParseUnit(this StringSource source)
{
var pos = source.Index;
var result = UnitStart(source);
if (result == null)
{
source.BackTo(pos);
}
return result;
}
public static ICssValue ParseAutoLength(this StringSource source)
{
if (source.IsIdentifier(CssKeywords.Auto))
{
return Length.Auto;
}
return null;
}
public static Length? ParseNormalLength(this StringSource source)
{
if (source.IsIdentifier(CssKeywords.Normal))
{
return Length.Normal;
}
return null;
}
public static ICssValue ParseBorderWidth(this StringSource source) =>
source.ParseLengthOrCalc() ??
source.ParsePercentOrNumber() ??
source.ParseAutoLength();
public static ICssValue ParseLineWidth(this StringSource source) =>
source.ParseLengthOrCalc() ??
source.ParseConstant(Map.BorderWidths);
public static ICssValue ParseLineHeight(this StringSource source) =>
source.ParseLengthOrCalc() ??
source.ParsePercentOrNumber() ??
source.ParseNormalLength();
public static Double? ParsePercent(this StringSource source)
{
var pos = source.Index;
var test = source.ParseUnit();
if (test?.Dimension == "%" &&
Double.TryParse(test.Value, NumberStyles.Float, CultureInfo.InvariantCulture, out var value))
{
return value * 0.01;
}
source.BackTo(pos);
return null;
}
public static Length? ParsePercentOrNumber(this StringSource source)
{
var pos = source.Index;
var test = source.ParseUnit();
if (test != null && Double.TryParse(test.Value, NumberStyles.Float, CultureInfo.InvariantCulture, out var value))
{
if (test.Dimension == "%")
{
return new Length(value, Length.Unit.Percent);
}
else if (test.Dimension.Length == 0)
{
return new Length(value, Length.Unit.None);
}
}
source.BackTo(pos);
return null;
}
public static Angle? ParseAngle(this StringSource source)
{
var pos = source.Index;
var test = source.ParseUnit();
if (test != null)
{
var unit = Angle.GetUnit(test.Dimension);
if (unit != Angle.Unit.None &&
Double.TryParse(test.Value, NumberStyles.Float, CultureInfo.InvariantCulture, out var value))
{
return new Angle(value, unit);
}
source.BackTo(pos);
}
return null;
}
public static ICssValue ParseAngleOrCalc(this StringSource source) =>
source.ParseAngle().OrCalc(source);
public static Frequency? ParseFrequency(this StringSource source)
{
var pos = source.Index;
var test = source.ParseUnit();
if (test != null)
{
var unit = Frequency.GetUnit(test.Dimension);
if (unit != Frequency.Unit.None &&
Double.TryParse(test.Value, NumberStyles.Float, CultureInfo.InvariantCulture, out var value))
{
return new Frequency(value, unit);
}
source.BackTo(pos);
}
return null;
}
public static ICssValue ParseFontSize(this StringSource source) =>
source.ParseDistanceOrCalc() ??
source.ParseConstant(Map.FontSizes);
public static ICssValue ParseTrackBreadth(this StringSource source, Boolean flexible = true)
{
var pos = source.Index;
var test = source.ParseUnit();
var length = GetLength(test);
if (length.HasValue)
{
return length;
}
else if (test != null)
{
var unit = Fraction.GetUnit(test.Dimension);
if (flexible && unit != Fraction.Unit.None &&
Double.TryParse(test.Value, NumberStyles.Float, CultureInfo.InvariantCulture, out var value))
{
return new Fraction(value, unit);
}
}
else
{
var ident = source.ParseIdent();
if (ident != null)
{
if (ident.Isi(CssKeywords.MinContent))
{
return new Identifier(CssKeywords.MinContent);
}
else if (ident.Isi(CssKeywords.MaxContent))
{
return new Identifier(CssKeywords.MaxContent);
}
else if (ident.Isi(CssKeywords.Auto))
{
return new Identifier(CssKeywords.Auto);
}
}
}
source.BackTo(pos);
return source.ParseCalc();
}
public static Length? ParseDistance(this StringSource source)
{
var pos = source.Index;
var test = source.ParseUnit();
var length = GetLength(test);
if (!length.HasValue)
{
source.BackTo(pos);
}
return length;
}
public static ICssValue ParseDistanceOrCalc(this StringSource source) =>
source.ParseDistance().OrCalc(source);
public static Length? ParseLength(this StringSource source)
{
var pos = source.Index;
var test = source.ParseUnit();
var length = GetLength(test);
if (!length.HasValue || length.Value.Type == Length.Unit.Percent)
{
source.BackTo(pos);
return null;
}
return length;
}
public static ICssValue ParseLengthOrCalc(this StringSource source) =>
source.ParseLength().OrCalc(source);
public static Resolution? ParseResolution(this StringSource source)
{
var pos = source.Index;
var test = source.ParseUnit();
if (test != null)
{
var unit = Resolution.GetUnit(test.Dimension);
if (unit != Resolution.Unit.None &&
Double.TryParse(test.Value, NumberStyles.Float, CultureInfo.InvariantCulture, out var value))
{
return new Resolution(value, unit);
}
source.BackTo(pos);
}
return null;
}
public static Time? ParseTime(this StringSource source)
{
var pos = source.Index;
var test = source.ParseUnit();
if (test != null)
{
var unit = Time.GetUnit(test.Dimension);
if (unit != Time.Unit.None &&
Double.TryParse(test.Value, NumberStyles.Float, CultureInfo.InvariantCulture, out var value))
{
return new Time(value, unit);
}
source.BackTo(pos);
}
return null;
}
public static ICssValue ParseTimeOrCalc(this StringSource source)
{
return source.ParseTime().OrCalc(source);
}
private static Length? GetLength(Unit test)
{
if (test != null &&
Double.TryParse(test.Value, NumberStyles.Float, CultureInfo.InvariantCulture, out var value))
{
var unit = Length.Unit.Px;
if ((test.Dimension == String.Empty && test.Value == "0") ||
(unit = Length.GetUnit(test.Dimension)) != Length.Unit.None)
{
return new Length(value, unit);
}
}
return null;
}
private static Unit UnitStart(StringSource source)
{
var current = source.Current;
if (current is Symbols.Plus or Symbols.Minus)
{
var next = source.Next();
if (next == Symbols.Dot)
{
var buffer = StringBuilderPool.Obtain().Append(current).Append(next);
return UnitFraction(source, buffer);
}
else if (next.IsDigit())
{
var buffer = StringBuilderPool.Obtain().Append(current).Append(next);
return UnitRest(source, buffer);
}
}
else if (current == Symbols.Dot)
{
return UnitFraction(source, StringBuilderPool.Obtain().Append(current));
}
else if (current.IsDigit())
{
return UnitRest(source, StringBuilderPool.Obtain().Append(current));
}
return null;
}
private static Boolean IsDimension(StringSource source, Char current) =>
current != 'e' && current != 'E' && (current.IsNameStart() || source.IsValidEscape());
private static Unit UnitRest(StringSource source, StringBuilder buffer)
{
var current = source.Next();
while (true)
{
if (current.IsDigit())
{
buffer.Append(current);
}
else if (IsDimension(source, current))
{
var number = buffer.ToString();
return Dimension(source, number, buffer.Clear());
}
else
{
break;
}
current = source.Next();
}
switch (current)
{
case Symbols.Dot:
current = source.Next();
if (current.IsDigit())
{
buffer.Append(Symbols.Dot).Append(current);
return UnitFraction(source, buffer);
}
return new Unit(buffer.ToPool(), String.Empty);
case '%':
source.Next();
return new Unit(buffer.ToPool(), "%");
case 'e':
case 'E':
return NumberExponential(source, buffer);
case Symbols.Minus:
return NumberDash(source, buffer);
default:
return new Unit(buffer.ToPool(), String.Empty);
}
}
private static Unit UnitFraction(StringSource source, StringBuilder buffer)
{
var current = source.Next();
while (true)
{
if (current.IsDigit())
{
buffer.Append(current);
}
else if (IsDimension(source, current))
{
var number = buffer.ToString();
return Dimension(source, number, buffer.Clear());
}
else
{
break;
}
current = source.Next();
}
switch (current)
{
case 'e':
case 'E':
return NumberExponential(source, buffer);
case '%':
source.Next();
return new Unit(buffer.ToPool(), "%");
case Symbols.Minus:
return NumberDash(source, buffer);
default:
return new Unit(buffer.ToPool(), String.Empty);
}
}
private static Unit Dimension(StringSource source, String number, StringBuilder buffer)
{
var current = source.Current;
while (true)
{
if (current.IsLetter())
{
buffer.Append(current);
}
else if (source.IsValidEscape())
{
source.Next();
buffer.Append(source.ConsumeEscape());
}
else
{
return new Unit(number, buffer.ToPool());
}
current = source.Next();
}
}
private static Unit SciNotation(StringSource source, StringBuilder buffer)
{
while (true)
{
var current = source.Next();
if (current.IsDigit())
{
buffer.Append(current);
}
else if (current.IsNameStart() || source.IsValidEscape())
{
var number = buffer.ToString();
return Dimension(source, number, buffer.Clear());
}
else
{
return new Unit(buffer.ToPool(), String.Empty);
}
}
}
private static Unit NumberDash(StringSource source, StringBuilder buffer)
{
var current = source.Next();
if (current.IsNameStart() || source.IsValidEscape())
{
var number = buffer.ToString();
return Dimension(source, number, buffer.Clear().Append(Symbols.Minus));
}
else
{
source.Back();
return new Unit(buffer.ToPool(), String.Empty);
}
}
private static Unit NumberExponential(StringSource source, StringBuilder buffer)
{
var letter = source.Current;
var current = source.Next();
if (current.IsDigit())
{
buffer.Append(letter).Append(current);
return SciNotation(source, buffer);
}
else if (current == Symbols.Plus || current == Symbols.Minus)
{
var op = current;
current = source.Next();
if (current.IsDigit())
{
buffer.Append(letter).Append(op).Append(current);
return SciNotation(source, buffer);
}
source.Back();
}
var number = buffer.ToString();
return Dimension(source, number, buffer.Clear().Append(letter));
}
private static ICssValue OrCalc<T>(this T? value, StringSource source)
where T : struct, ICssValue
{
if (value.HasValue)
{
return value.Value;
}
return source.ParseCalc();
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Linq;
using Xunit;
namespace System.Collections.Immutable.Test
{
public class ImmutableSortedSetTest : ImmutableSetTest
{
private enum Operation
{
Add,
Union,
Remove,
Except,
Last,
}
protected override bool IncludesGetHashCodeDerivative
{
get { return false; }
}
[Fact]
public void RandomOperationsTest()
{
int operationCount = this.RandomOperationsCount;
var expected = new SortedSet<int>();
var actual = ImmutableSortedSet<int>.Empty;
int seed = (int)DateTime.Now.Ticks;
Debug.WriteLine("Using random seed {0}", seed);
var random = new Random(seed);
for (int iOp = 0; iOp < operationCount; iOp++)
{
switch ((Operation)random.Next((int)Operation.Last))
{
case Operation.Add:
int value = random.Next();
Debug.WriteLine("Adding \"{0}\" to the set.", value);
expected.Add(value);
actual = actual.Add(value);
break;
case Operation.Union:
int inputLength = random.Next(100);
int[] values = Enumerable.Range(0, inputLength).Select(i => random.Next()).ToArray();
Debug.WriteLine("Adding {0} elements to the set.", inputLength);
expected.UnionWith(values);
actual = actual.Union(values);
break;
case Operation.Remove:
if (expected.Count > 0)
{
int position = random.Next(expected.Count);
int element = expected.Skip(position).First();
Debug.WriteLine("Removing element \"{0}\" from the set.", element);
Assert.True(expected.Remove(element));
actual = actual.Remove(element);
}
break;
case Operation.Except:
var elements = expected.Where(el => random.Next(2) == 0).ToArray();
Debug.WriteLine("Removing {0} elements from the set.", elements.Length);
expected.ExceptWith(elements);
actual = actual.Except(elements);
break;
}
Assert.Equal<int>(expected.ToList(), actual.ToList());
}
}
[Fact]
public void EmptyTest()
{
this.EmptyTestHelper(Empty<int>(), 5, null);
this.EmptyTestHelper(Empty<string>().ToImmutableSortedSet(StringComparer.OrdinalIgnoreCase), "a", StringComparer.OrdinalIgnoreCase);
}
[Fact]
public void CustomSort()
{
this.CustomSortTestHelper(
ImmutableSortedSet<string>.Empty.WithComparer(StringComparer.Ordinal),
true,
new[] { "apple", "APPLE" },
new[] { "APPLE", "apple" });
this.CustomSortTestHelper(
ImmutableSortedSet<string>.Empty.WithComparer(StringComparer.OrdinalIgnoreCase),
true,
new[] { "apple", "APPLE" },
new[] { "apple" });
}
[Fact]
public void ChangeSortComparer()
{
var ordinalSet = ImmutableSortedSet<string>.Empty
.WithComparer(StringComparer.Ordinal)
.Add("apple")
.Add("APPLE");
Assert.Equal(2, ordinalSet.Count); // claimed count
Assert.False(ordinalSet.Contains("aPpLe"));
var ignoreCaseSet = ordinalSet.WithComparer(StringComparer.OrdinalIgnoreCase);
Assert.Equal(1, ignoreCaseSet.Count);
Assert.True(ignoreCaseSet.Contains("aPpLe"));
}
[Fact]
public void ToUnorderedTest()
{
var result = ImmutableSortedSet<int>.Empty.Add(3).ToImmutableHashSet();
Assert.True(result.Contains(3));
}
[Fact]
public void ToImmutableSortedSetTest()
{
var set = new[] { 1, 2, 2 }.ToImmutableSortedSet();
Assert.Same(Comparer<int>.Default, set.KeyComparer);
Assert.Equal(2, set.Count);
}
[Fact]
public void IndexOfTest()
{
var set = ImmutableSortedSet<int>.Empty;
Assert.Equal(~0, set.IndexOf(5));
set = ImmutableSortedSet<int>.Empty.Union(Enumerable.Range(1, 10).Select(n => n * 10)); // 10, 20, 30, ... 100
Assert.Equal(0, set.IndexOf(10));
Assert.Equal(1, set.IndexOf(20));
Assert.Equal(4, set.IndexOf(50));
Assert.Equal(8, set.IndexOf(90));
Assert.Equal(9, set.IndexOf(100));
Assert.Equal(~0, set.IndexOf(5));
Assert.Equal(~1, set.IndexOf(15));
Assert.Equal(~2, set.IndexOf(25));
Assert.Equal(~5, set.IndexOf(55));
Assert.Equal(~9, set.IndexOf(95));
Assert.Equal(~10, set.IndexOf(105));
}
[Fact]
public void IndexGetTest()
{
var set = ImmutableSortedSet<int>.Empty
.Union(Enumerable.Range(1, 10).Select(n => n * 10)); // 10, 20, 30, ... 100
int i = 0;
foreach (var item in set)
{
AssertAreSame(item, set[i++]);
}
Assert.Throws<ArgumentOutOfRangeException>(() => set[-1]);
Assert.Throws<ArgumentOutOfRangeException>(() => set[set.Count]);
}
[Fact]
public void ReverseTest()
{
var range = Enumerable.Range(1, 10);
var set = ImmutableSortedSet<int>.Empty.Union(range);
var expected = range.Reverse().ToList();
var actual = set.Reverse().ToList();
Assert.Equal<int>(expected, actual);
}
[Fact]
public void MaxTest()
{
Assert.Equal(5, ImmutableSortedSet<int>.Empty.Union(Enumerable.Range(1, 5)).Max);
Assert.Equal(0, ImmutableSortedSet<int>.Empty.Max);
}
[Fact]
public void MinTest()
{
Assert.Equal(1, ImmutableSortedSet<int>.Empty.Union(Enumerable.Range(1, 5)).Min);
Assert.Equal(0, ImmutableSortedSet<int>.Empty.Min);
}
[Fact]
public void InitialBulkAdd()
{
Assert.Equal(1, Empty<int>().Union(new[] { 1, 1 }).Count);
Assert.Equal(2, Empty<int>().Union(new[] { 1, 2 }).Count);
}
[Fact]
public void ICollectionOfTMethods()
{
ICollection<string> set = ImmutableSortedSet.Create<string>();
Assert.Throws<NotSupportedException>(() => set.Add("a"));
Assert.Throws<NotSupportedException>(() => set.Clear());
Assert.Throws<NotSupportedException>(() => set.Remove("a"));
Assert.True(set.IsReadOnly);
}
[Fact]
public void IListOfTMethods()
{
IList<string> set = ImmutableSortedSet.Create<string>("b");
Assert.Throws<NotSupportedException>(() => set.Insert(0, "a"));
Assert.Throws<NotSupportedException>(() => set.RemoveAt(0));
Assert.Throws<NotSupportedException>(() => set[0] = "a");
Assert.Equal("b", set[0]);
Assert.True(set.IsReadOnly);
}
[Fact]
public void UnionOptimizationsTest()
{
var set = ImmutableSortedSet.Create(1, 2, 3);
var builder = set.ToBuilder();
Assert.Same(set, ImmutableSortedSet.Create<int>().Union(builder));
Assert.Same(set, set.Union(ImmutableSortedSet.Create<int>()));
var smallSet = ImmutableSortedSet.Create(1);
var unionSet = smallSet.Union(set);
Assert.Same(set, unionSet); // adding a larger set to a smaller set is reversed, and then the smaller in this case has nothing unique
}
[Fact]
public void Create()
{
var comparer = StringComparer.OrdinalIgnoreCase;
var set = ImmutableSortedSet.Create<string>();
Assert.Equal(0, set.Count);
Assert.Same(Comparer<string>.Default, set.KeyComparer);
set = ImmutableSortedSet.Create<string>(comparer);
Assert.Equal(0, set.Count);
Assert.Same(comparer, set.KeyComparer);
set = ImmutableSortedSet.Create("a");
Assert.Equal(1, set.Count);
Assert.Same(Comparer<string>.Default, set.KeyComparer);
set = ImmutableSortedSet.Create(comparer, "a");
Assert.Equal(1, set.Count);
Assert.Same(comparer, set.KeyComparer);
set = ImmutableSortedSet.Create("a", "b");
Assert.Equal(2, set.Count);
Assert.Same(Comparer<string>.Default, set.KeyComparer);
set = ImmutableSortedSet.Create(comparer, "a", "b");
Assert.Equal(2, set.Count);
Assert.Same(comparer, set.KeyComparer);
set = ImmutableSortedSet.CreateRange((IEnumerable<string>)new[] { "a", "b" });
Assert.Equal(2, set.Count);
Assert.Same(Comparer<string>.Default, set.KeyComparer);
set = ImmutableSortedSet.CreateRange(comparer, (IEnumerable<string>)new[] { "a", "b" });
Assert.Equal(2, set.Count);
Assert.Same(comparer, set.KeyComparer);
}
[Fact]
public void IListMethods()
{
IList list = ImmutableSortedSet.Create("a", "b");
Assert.True(list.Contains("a"));
Assert.Equal("a", list[0]);
Assert.Equal("b", list[1]);
Assert.Equal(0, list.IndexOf("a"));
Assert.Equal(1, list.IndexOf("b"));
Assert.Throws<NotSupportedException>(() => list.Add("b"));
Assert.Throws<NotSupportedException>(() => list[3] = "c");
Assert.Throws<NotSupportedException>(() => list.Clear());
Assert.Throws<NotSupportedException>(() => list.Insert(0, "b"));
Assert.Throws<NotSupportedException>(() => list.Remove("a"));
Assert.Throws<NotSupportedException>(() => list.RemoveAt(0));
Assert.True(list.IsFixedSize);
Assert.True(list.IsReadOnly);
}
[Fact]
public void TryGetValueTest()
{
this.TryGetValueTestHelper(ImmutableSortedSet<string>.Empty.WithComparer(StringComparer.OrdinalIgnoreCase));
}
[Fact]
public void EnumeratorRecyclingMisuse()
{
var collection = ImmutableSortedSet.Create<int>();
var enumerator = collection.GetEnumerator();
var enumeratorCopy = enumerator;
Assert.False(enumerator.MoveNext());
enumerator.Dispose();
Assert.Throws<ObjectDisposedException>(() => enumerator.MoveNext());
Assert.Throws<ObjectDisposedException>(() => enumerator.Reset());
Assert.Throws<ObjectDisposedException>(() => enumerator.Current);
Assert.Throws<ObjectDisposedException>(() => enumeratorCopy.MoveNext());
Assert.Throws<ObjectDisposedException>(() => enumeratorCopy.Reset());
Assert.Throws<ObjectDisposedException>(() => enumeratorCopy.Current);
enumerator.Dispose(); // double-disposal should not throw
enumeratorCopy.Dispose();
// We expect that acquiring a new enumerator will use the same underlying Stack<T> object,
// but that it will not throw exceptions for the new enumerator.
enumerator = collection.GetEnumerator();
Assert.False(enumerator.MoveNext());
Assert.Throws<InvalidOperationException>(() => enumerator.Current);
enumerator.Dispose();
}
protected override IImmutableSet<T> Empty<T>()
{
return ImmutableSortedSet<T>.Empty;
}
protected ImmutableSortedSet<T> EmptyTyped<T>()
{
return ImmutableSortedSet<T>.Empty;
}
protected override ISet<T> EmptyMutable<T>()
{
return new SortedSet<T>();
}
internal override IBinaryTree GetRootNode<T>(IImmutableSet<T> set)
{
return ((ImmutableSortedSet<T>)set).Root;
}
/// <summary>
/// Tests various aspects of a sorted set.
/// </summary>
/// <typeparam name="T">The type of element stored in the set.</typeparam>
/// <param name="emptySet">The empty set.</param>
/// <param name="value">A value that could be placed in the set.</param>
/// <param name="comparer">The comparer used to obtain the empty set, if any.</param>
private void EmptyTestHelper<T>(IImmutableSet<T> emptySet, T value, IComparer<T> comparer)
{
Contract.Requires(emptySet != null);
this.EmptyTestHelper(emptySet);
Assert.Same(emptySet, emptySet.ToImmutableSortedSet(comparer));
Assert.Same(comparer ?? Comparer<T>.Default, ((ISortKeyCollection<T>)emptySet).KeyComparer);
var reemptied = emptySet.Add(value).Clear();
Assert.Same(reemptied, reemptied.ToImmutableSortedSet(comparer)); //, "Getting the empty set from a non-empty instance did not preserve the comparer.");
}
}
}
| |
using System;
using System.Diagnostics;
using System.Text;
using System.IO;
namespace IdSharp.Common.Utils
{
/// <summary>
/// Common utils
/// </summary>
public static class ByteUtils
{
private static readonly Encoding m_ISO88591 = Encoding.GetEncoding(28591);
/// <summary>
/// Gets the ISO-8859-1 encoding.
/// </summary>
public static Encoding ISO88591
{
get { return m_ISO88591; }
}
/// <summary>
/// Converts a byte array to a 64-bit integer using Big Endian.
/// </summary>
/// <param name="byteArray">The byte array.</param>
public static long ConvertToInt64(byte[] byteArray)
{
long value = 0;
for (int i = 0; i < byteArray.Length; i++)
{
value <<= 8;
value += byteArray[i];
}
return value;
}
/// <summary>
/// Determines whether a bit is set in the specified byte.
/// </summary>
/// <param name="byteToCheck">The byte to check.</param>
/// <param name="bitToCheck">The bit to check.</param>
/// <returns>
/// <c>true</c> if the bit is set; otherwise, <c>false</c>.
/// </returns>
public static bool IsBitSet(byte byteToCheck, byte bitToCheck)
{
if (bitToCheck > 7)
{
throw new ArgumentOutOfRangeException("bitToCheck", bitToCheck, "bitToCheck must be <= 7");
}
bool returnValue = ((byteToCheck >> bitToCheck) & 0x01) == 0x01;
return returnValue;
}
/// <summary>
/// Gets a byte array of the specified size. TODO - See how this is used
/// </summary>
/// <param name="decimalValue">The decimal value.</param>
/// <param name="byteArraySize">Size of the byte array.</param>
public static byte[] GetBytesDecimal(decimal decimalValue, int byteArraySize)
{
byte[] byteArray = GetBytesMinimal((ulong)decimalValue);
if (byteArray.Length == byteArraySize)
{
// Size is as requested, new byte array not needed
return byteArray;
}
else if (byteArray.Length > byteArraySize)
{
// Size is greater than requested. Return new array with right 'byteArraySize' bytes.
byte[] returnValue = new byte[byteArraySize];
for (int i = byteArray.Length - byteArraySize, j = 0; i < byteArray.Length; i++, j++)
{
returnValue[j] = byteArray[i];
}
return returnValue;
}
else
{
// Size is less than requested. Return new array left padded with 0's.
byte[] returnValue = new byte[byteArraySize];
for (int i = byteArraySize - byteArray.Length, j = 0; i < byteArraySize; i++, j++)
{
returnValue[i] = byteArray[j];
}
return returnValue;
}
}
/// <summary>
/// Gets a byte array representing the value using the minimal number of bytes.
/// </summary>
/// <param name="value">The value.</param>
public static byte[] GetBytesMinimal(long value)
{
return GetBytesMinimal((ulong)value);
}
/// <summary>
/// Gets a byte array representing the value using the minimal number of bytes.
/// </summary>
/// <param name="value">The value.</param>
public static byte[] GetBytesMinimal(ulong value)
{
byte[] returnValue;
if (value <= byte.MaxValue)
returnValue = new[] { (byte)value };
else if (value <= ushort.MaxValue)
returnValue = Get2Bytes((ushort)value);
else if (value <= uint.MaxValue)
returnValue = Get4Bytes((uint)value);
else
returnValue = Get8Bytes(value);
return returnValue;
}
/// <summary>
/// Gets an 8-byte length byte array representing the value.
/// </summary>
/// <param name="value">The value.</param>
public static byte[] Get8Bytes(ulong value)
{
// BitConverter.GetBytes uses LE - we need BE
byte[] byteArray = new[] { (byte)((value >> 56) & 0xFF),
(byte)((value >> 48) & 0xFF),
(byte)((value >> 40) & 0xFF),
(byte)((value >> 32) & 0xFF),
(byte)((value >> 24) & 0xFF),
(byte)((value >> 16) & 0xFF),
(byte)((value >> 8) & 0xFF),
(byte)(value & 0xFF)
};
return byteArray;
}
/// <summary>
/// Gets a 4-byte length byte array representing the value.
/// </summary>
/// <param name="value">The value.</param>
public static byte[] Get4Bytes(uint value)
{
// BitConverter.GetBytes uses LE - we need BE
byte[] byteArray = new[] { (byte)((value >> 24) & 0xFF),
(byte)((value >> 16) & 0xFF),
(byte)((value >> 8) & 0xFF),
(byte)(value & 0xFF)
};
return byteArray;
}
/// <summary>
/// Gets a 2-byte length byte array representing the value.
/// </summary>
/// <param name="value">The value.</param>
public static byte[] Get2Bytes(ushort value)
{
// BitConverter.GetBytes uses LE - we need BE
byte[] byteArray = new[] { (byte)((value >> 8) & 0xFF),
(byte)(value & 0xFF)
};
return byteArray;
}
/// <summary>
/// Gets a 4-byte length byte array representing the value.
/// </summary>
/// <param name="value">The value.</param>
public static byte[] Get4Bytes(int value)
{
if (value < 0)
throw new ArgumentOutOfRangeException("value", value, "Value cannot be less than 0");
return Get4Bytes((uint)value);
}
/// <summary>
/// Gets a 2-byte length byte array representing the value.
/// </summary>
/// <param name="value">The value.</param>
public static byte[] Get2Bytes(short value)
{
if (value < 0)
throw new ArgumentOutOfRangeException("value", value, "Value cannot be less than 0");
return Get2Bytes((ushort)value);
}
/// <summary>
/// Returns a byte array representing the ISO-8859-1 encoded value. If value is <c>null</c>,
/// a 0-byte array is returned. <c>null</c> is never returned.
/// </summary>
/// <param name="value">The ISO-8859-1 encoded value.</param>
/// <returns></returns>
public static byte[] ISO88591GetBytes(string value)
{
if (value == null)
return new byte[0];
else
return m_ISO88591.GetBytes(value);
}
/// <summary>
/// Returns a clone of the byte array, or <c>null</c> if <paramref name="value"/> is <c>null</c>.
/// </summary>
/// <param name="value">The value.</param>
/// <returns>A clone of the byte array, or <c>null</c> if <paramref name="value"/> is <c>null</c>.</returns>
public static byte[] Clone(byte[] value)
{
if (value == null)
return null;
else
return (byte[])value.Clone();
}
/// <summary>
/// Returns a string for the ISO-8859-1 encoded byte array. If the byte array is <c>null</c>,
/// String.Empty is returned. <c>null</c> is never returned.
/// </summary>
/// <param name="value">The value.</param>
/// <returns></returns>
public static string ISO88591GetString(byte[] value)
{
if (value == null)
return string.Empty;
else
return m_ISO88591.GetString(value);
}
/// <summary>
/// Replaces a number of 'bytesToRemove' from 'path' with the 'bytesToAdd' byte array, at a specified offset.
/// </summary>
/// <param name="path">The full path of the file.</param>
/// <param name="bytesToRemove">The number of bytes to remove.</param>
/// <param name="bytesToAdd">The bytes to add.</param>
/// <param name="offset">The offset which to start replacing bytes.</param>
public static void ReplaceBytes(string path, int bytesToRemove, byte[] bytesToAdd, long offset)
{
if (string.IsNullOrEmpty(path))
throw new ArgumentNullException("path");
if (bytesToAdd == null)
throw new ArgumentNullException("bytesToAdd");
using (FileStream infile = File.Open(path, FileMode.Open, FileAccess.ReadWrite, FileShare.None))
{
infile.Position = offset + bytesToRemove;
byte[] extraBytes = new byte[infile.Length - offset - bytesToRemove];
infile.Read(extraBytes, 0, extraBytes.Length);
infile.SetLength(offset);
infile.Position = offset;
infile.Write(bytesToAdd, 0, bytesToAdd.Length);
infile.Write(extraBytes, 0, extraBytes.Length);
}
}
/// <summary>
/// Replaces a number of 'bytesToRemove' from 'path' with the 'bytesToAdd' byte array, starting at the
/// beginning of the file.
/// </summary>
/// <param name="path">The full path of the file.</param>
/// <param name="bytesToRemove">The number of bytes to remove.</param>
/// <param name="bytesToAdd">The bytes to add.</param>
public static void ReplaceBytes(string path, int bytesToRemove, byte[] bytesToAdd)
{
if (string.IsNullOrEmpty(path))
throw new ArgumentNullException("path");
if (bytesToAdd == null)
throw new ArgumentNullException("bytesToAdd");
const int BUF_SIZE = 32767;
string tempPath = PathUtils.GetTemporaryFileNameBasedOnFileName(path);
File.Move(path, tempPath);
try
{
byte[] buffer = new byte[BUF_SIZE];
using (FileStream infile = File.Open(tempPath, FileMode.Open, FileAccess.Read, FileShare.None))
using (FileStream outfile = File.Open(path, FileMode.CreateNew, FileAccess.Write, FileShare.None))
{
outfile.Write(bytesToAdd, 0, bytesToAdd.Length);
infile.Position = bytesToRemove;
int bytesRead = infile.Read(buffer, 0, BUF_SIZE);
while (bytesRead > 0)
{
outfile.Write(buffer, 0, bytesRead);
bytesRead = infile.Read(buffer, 0, BUF_SIZE);
}
}
File.Delete(tempPath);
}
catch
{
// try to put the file back
try
{
File.Move(tempPath, path);
}
catch (Exception ex)
{
// swallow this one
Trace.WriteLine(ex);
}
throw;
}
}
/// <summary>
/// Compares the specified byte arrays.
/// </summary>
/// <param name="x">The first byte array.</param>
/// <param name="y">The second byte arrayy.</param>
/// <returns><c>true</c> if the byte arrays are equal; otherwise, <c>false</c></returns>
public static bool Compare(byte[] x, byte[] y)
{
if (x == null && y == null)
return true;
if (x == null || y == null)
return false;
if (x == y)
return true;
if (x.Length != y.Length)
return false;
for (int i = 0; i < x.Length; i++)
{
if (x[i] != y[i])
return false;
}
return true;
}
/// <summary>
/// Compares the specified byte arrays, up to Min(x.Length, y.Length, maxLength)
/// </summary>
/// <param name="x">The first byte array.</param>
/// <param name="y">The second byte arrayy.</param>
/// <param name="maxLength">Maximum number of bytes to compare.</param>
/// <returns>
/// <c>true</c> if the byte arrays are equal; otherwise, <c>false</c>
/// </returns>
public static bool Compare(byte[] x, byte[] y, int maxLength)
{
if (maxLength < 0)
throw new ArgumentOutOfRangeException("maxLength", "maxLength must be greater than or equal to 0.");
if (x == null && y == null)
return true;
if (x == null || y == null)
return false;
if (x == y)
return true;
int compareTo = MathUtils.Min(x.Length, y.Length, maxLength);
for (int i = 0; i < compareTo; i++)
{
if (x[i] != y[i])
return false;
}
return true;
}
}
}
| |
//
// Copyright (c) 2008-2011, Kenneth Bell
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
using System;
using System.IO;
using DiscUtils.Streams;
namespace DiscUtils.Vfs
{
/// <summary>
/// Base class for the public facade on a file system.
/// </summary>
/// <remarks>
/// The derived class can extend the functionality available from a file system
/// beyond that defined by DiscFileSystem.
/// </remarks>
public abstract class VfsFileSystemFacade : DiscFileSystem
{
private readonly DiscFileSystem _wrapped;
/// <summary>
/// Initializes a new instance of the VfsFileSystemFacade class.
/// </summary>
/// <param name="toWrap">The actual file system instance.</param>
protected VfsFileSystemFacade(DiscFileSystem toWrap)
{
_wrapped = toWrap;
}
/// <summary>
/// Indicates whether the file system is read-only or read-write.
/// </summary>
/// <returns>true if the file system is read-write.</returns>
public override bool CanWrite
{
get { return _wrapped.CanWrite; }
}
/// <summary>
/// Gets a friendly name for the file system.
/// </summary>
public override string FriendlyName
{
get { return _wrapped.FriendlyName; }
}
/// <summary>
/// Gets a value indicating whether the file system is thread-safe.
/// </summary>
public override bool IsThreadSafe
{
get { return _wrapped.IsThreadSafe; }
}
/// <summary>
/// Gets the file system options, which can be modified.
/// </summary>
public override DiscFileSystemOptions Options
{
get { return _wrapped.Options; }
}
/// <summary>
/// Gets the root directory of the file system.
/// </summary>
public override DiscDirectoryInfo Root
{
get { return new DiscDirectoryInfo(this, string.Empty); }
}
/// <summary>
/// Gets the volume label.
/// </summary>
public override string VolumeLabel
{
get { return _wrapped.VolumeLabel; }
}
/// <summary>
/// Copies an existing file to a new file.
/// </summary>
/// <param name="sourceFile">The source file.</param>
/// <param name="destinationFile">The destination file.</param>
public override void CopyFile(string sourceFile, string destinationFile)
{
_wrapped.CopyFile(sourceFile, destinationFile);
}
/// <summary>
/// Copies an existing file to a new file.
/// </summary>
/// <param name="sourceFile">The source file.</param>
/// <param name="destinationFile">The destination file.</param>
/// <param name="overwrite">Overwrite any existing file.</param>
public override void CopyFile(string sourceFile, string destinationFile, bool overwrite)
{
_wrapped.CopyFile(sourceFile, destinationFile, overwrite);
}
/// <summary>
/// Creates a directory.
/// </summary>
/// <param name="path">The path of the new directory.</param>
public override void CreateDirectory(string path)
{
_wrapped.CreateDirectory(path);
}
/// <summary>
/// Deletes a directory.
/// </summary>
/// <param name="path">The path of the directory to delete.</param>
public override void DeleteDirectory(string path)
{
_wrapped.DeleteDirectory(path);
}
/// <summary>
/// Deletes a directory, optionally with all descendants.
/// </summary>
/// <param name="path">The path of the directory to delete.</param>
/// <param name="recursive">Determines if the all descendants should be deleted.</param>
public override void DeleteDirectory(string path, bool recursive)
{
_wrapped.DeleteDirectory(path, recursive);
}
/// <summary>
/// Deletes a file.
/// </summary>
/// <param name="path">The path of the file to delete.</param>
public override void DeleteFile(string path)
{
_wrapped.DeleteFile(path);
}
/// <summary>
/// Indicates if a directory exists.
/// </summary>
/// <param name="path">The path to test.</param>
/// <returns>true if the directory exists.</returns>
public override bool DirectoryExists(string path)
{
return _wrapped.DirectoryExists(path);
}
/// <summary>
/// Indicates if a file exists.
/// </summary>
/// <param name="path">The path to test.</param>
/// <returns>true if the file exists.</returns>
public override bool FileExists(string path)
{
return _wrapped.FileExists(path);
}
/// <summary>
/// Indicates if a file or directory exists.
/// </summary>
/// <param name="path">The path to test.</param>
/// <returns>true if the file or directory exists.</returns>
public override bool Exists(string path)
{
return _wrapped.Exists(path);
}
/// <summary>
/// Gets the names of subdirectories in a specified directory.
/// </summary>
/// <param name="path">The path to search.</param>
/// <returns>Array of directories.</returns>
public override string[] GetDirectories(string path)
{
return _wrapped.GetDirectories(path);
}
/// <summary>
/// Gets the names of subdirectories in a specified directory matching a specified
/// search pattern.
/// </summary>
/// <param name="path">The path to search.</param>
/// <param name="searchPattern">The search string to match against.</param>
/// <returns>Array of directories matching the search pattern.</returns>
public override string[] GetDirectories(string path, string searchPattern)
{
return _wrapped.GetDirectories(path, searchPattern);
}
/// <summary>
/// Gets the names of subdirectories in a specified directory matching a specified
/// search pattern, using a value to determine whether to search subdirectories.
/// </summary>
/// <param name="path">The path to search.</param>
/// <param name="searchPattern">The search string to match against.</param>
/// <param name="searchOption">Indicates whether to search subdirectories.</param>
/// <returns>Array of directories matching the search pattern.</returns>
public override string[] GetDirectories(string path, string searchPattern, SearchOption searchOption)
{
return _wrapped.GetDirectories(path, searchPattern, searchOption);
}
/// <summary>
/// Gets the names of files in a specified directory.
/// </summary>
/// <param name="path">The path to search.</param>
/// <returns>Array of files.</returns>
public override string[] GetFiles(string path)
{
return _wrapped.GetFiles(path);
}
/// <summary>
/// Gets the names of files in a specified directory.
/// </summary>
/// <param name="path">The path to search.</param>
/// <param name="searchPattern">The search string to match against.</param>
/// <returns>Array of files matching the search pattern.</returns>
public override string[] GetFiles(string path, string searchPattern)
{
return _wrapped.GetFiles(path, searchPattern);
}
/// <summary>
/// Gets the names of files in a specified directory matching a specified
/// search pattern, using a value to determine whether to search subdirectories.
/// </summary>
/// <param name="path">The path to search.</param>
/// <param name="searchPattern">The search string to match against.</param>
/// <param name="searchOption">Indicates whether to search subdirectories.</param>
/// <returns>Array of files matching the search pattern.</returns>
public override string[] GetFiles(string path, string searchPattern, SearchOption searchOption)
{
return _wrapped.GetFiles(path, searchPattern, searchOption);
}
/// <summary>
/// Gets the names of all files and subdirectories in a specified directory.
/// </summary>
/// <param name="path">The path to search.</param>
/// <returns>Array of files and subdirectories matching the search pattern.</returns>
public override string[] GetFileSystemEntries(string path)
{
return _wrapped.GetFileSystemEntries(path);
}
/// <summary>
/// Gets the names of files and subdirectories in a specified directory matching a specified
/// search pattern.
/// </summary>
/// <param name="path">The path to search.</param>
/// <param name="searchPattern">The search string to match against.</param>
/// <returns>Array of files and subdirectories matching the search pattern.</returns>
public override string[] GetFileSystemEntries(string path, string searchPattern)
{
return _wrapped.GetFileSystemEntries(path, searchPattern);
}
/// <summary>
/// Moves a directory.
/// </summary>
/// <param name="sourceDirectoryName">The directory to move.</param>
/// <param name="destinationDirectoryName">The target directory name.</param>
public override void MoveDirectory(string sourceDirectoryName, string destinationDirectoryName)
{
_wrapped.MoveDirectory(sourceDirectoryName, destinationDirectoryName);
}
/// <summary>
/// Moves a file.
/// </summary>
/// <param name="sourceName">The file to move.</param>
/// <param name="destinationName">The target file name.</param>
public override void MoveFile(string sourceName, string destinationName)
{
_wrapped.MoveFile(sourceName, destinationName);
}
/// <summary>
/// Moves a file, allowing an existing file to be overwritten.
/// </summary>
/// <param name="sourceName">The file to move.</param>
/// <param name="destinationName">The target file name.</param>
/// <param name="overwrite">Whether to permit a destination file to be overwritten.</param>
public override void MoveFile(string sourceName, string destinationName, bool overwrite)
{
_wrapped.MoveFile(sourceName, destinationName, overwrite);
}
/// <summary>
/// Opens the specified file.
/// </summary>
/// <param name="path">The full path of the file to open.</param>
/// <param name="mode">The file mode for the created stream.</param>
/// <returns>The new stream.</returns>
public override SparseStream OpenFile(string path, FileMode mode)
{
return _wrapped.OpenFile(path, mode);
}
/// <summary>
/// Opens the specified file.
/// </summary>
/// <param name="path">The full path of the file to open.</param>
/// <param name="mode">The file mode for the created stream.</param>
/// <param name="access">The access permissions for the created stream.</param>
/// <returns>The new stream.</returns>
public override SparseStream OpenFile(string path, FileMode mode, FileAccess access)
{
return _wrapped.OpenFile(path, mode, access);
}
/// <summary>
/// Gets the attributes of a file or directory.
/// </summary>
/// <param name="path">The file or directory to inspect.</param>
/// <returns>The attributes of the file or directory.</returns>
public override FileAttributes GetAttributes(string path)
{
return _wrapped.GetAttributes(path);
}
/// <summary>
/// Sets the attributes of a file or directory.
/// </summary>
/// <param name="path">The file or directory to change.</param>
/// <param name="newValue">The new attributes of the file or directory.</param>
public override void SetAttributes(string path, FileAttributes newValue)
{
_wrapped.SetAttributes(path, newValue);
}
/// <summary>
/// Gets the creation time (in local time) of a file or directory.
/// </summary>
/// <param name="path">The path of the file or directory.</param>
/// <returns>The creation time.</returns>
public override DateTime GetCreationTime(string path)
{
return _wrapped.GetCreationTime(path);
}
/// <summary>
/// Sets the creation time (in local time) of a file or directory.
/// </summary>
/// <param name="path">The path of the file or directory.</param>
/// <param name="newTime">The new time to set.</param>
public override void SetCreationTime(string path, DateTime newTime)
{
_wrapped.SetCreationTime(path, newTime);
}
/// <summary>
/// Gets the creation time (in UTC) of a file or directory.
/// </summary>
/// <param name="path">The path of the file or directory.</param>
/// <returns>The creation time.</returns>
public override DateTime GetCreationTimeUtc(string path)
{
return _wrapped.GetCreationTimeUtc(path);
}
/// <summary>
/// Sets the creation time (in UTC) of a file or directory.
/// </summary>
/// <param name="path">The path of the file or directory.</param>
/// <param name="newTime">The new time to set.</param>
public override void SetCreationTimeUtc(string path, DateTime newTime)
{
_wrapped.SetCreationTimeUtc(path, newTime);
}
/// <summary>
/// Gets the last access time (in local time) of a file or directory.
/// </summary>
/// <param name="path">The path of the file or directory.</param>
/// <returns>The last access time.</returns>
public override DateTime GetLastAccessTime(string path)
{
return _wrapped.GetLastAccessTime(path);
}
/// <summary>
/// Sets the last access time (in local time) of a file or directory.
/// </summary>
/// <param name="path">The path of the file or directory.</param>
/// <param name="newTime">The new time to set.</param>
public override void SetLastAccessTime(string path, DateTime newTime)
{
_wrapped.SetLastAccessTime(path, newTime);
}
/// <summary>
/// Gets the last access time (in UTC) of a file or directory.
/// </summary>
/// <param name="path">The path of the file or directory.</param>
/// <returns>The last access time.</returns>
public override DateTime GetLastAccessTimeUtc(string path)
{
return _wrapped.GetLastAccessTimeUtc(path);
}
/// <summary>
/// Sets the last access time (in UTC) of a file or directory.
/// </summary>
/// <param name="path">The path of the file or directory.</param>
/// <param name="newTime">The new time to set.</param>
public override void SetLastAccessTimeUtc(string path, DateTime newTime)
{
_wrapped.SetLastAccessTimeUtc(path, newTime);
}
/// <summary>
/// Gets the last modification time (in local time) of a file or directory.
/// </summary>
/// <param name="path">The path of the file or directory.</param>
/// <returns>The last write time.</returns>
public override DateTime GetLastWriteTime(string path)
{
return _wrapped.GetLastWriteTime(path);
}
/// <summary>
/// Sets the last modification time (in local time) of a file or directory.
/// </summary>
/// <param name="path">The path of the file or directory.</param>
/// <param name="newTime">The new time to set.</param>
public override void SetLastWriteTime(string path, DateTime newTime)
{
_wrapped.SetLastWriteTime(path, newTime);
}
/// <summary>
/// Gets the last modification time (in UTC) of a file or directory.
/// </summary>
/// <param name="path">The path of the file or directory.</param>
/// <returns>The last write time.</returns>
public override DateTime GetLastWriteTimeUtc(string path)
{
return _wrapped.GetLastWriteTimeUtc(path);
}
/// <summary>
/// Sets the last modification time (in UTC) of a file or directory.
/// </summary>
/// <param name="path">The path of the file or directory.</param>
/// <param name="newTime">The new time to set.</param>
public override void SetLastWriteTimeUtc(string path, DateTime newTime)
{
_wrapped.SetLastWriteTimeUtc(path, newTime);
}
/// <summary>
/// Gets the length of a file.
/// </summary>
/// <param name="path">The path to the file.</param>
/// <returns>The length in bytes.</returns>
public override long GetFileLength(string path)
{
return _wrapped.GetFileLength(path);
}
/// <summary>
/// Gets an object representing a possible file.
/// </summary>
/// <param name="path">The file path.</param>
/// <returns>The representing object.</returns>
/// <remarks>The file does not need to exist.</remarks>
public override DiscFileInfo GetFileInfo(string path)
{
return new DiscFileInfo(this, path);
}
/// <summary>
/// Gets an object representing a possible directory.
/// </summary>
/// <param name="path">The directory path.</param>
/// <returns>The representing object.</returns>
/// <remarks>The directory does not need to exist.</remarks>
public override DiscDirectoryInfo GetDirectoryInfo(string path)
{
return new DiscDirectoryInfo(this, path);
}
/// <summary>
/// Gets an object representing a possible file system object (file or directory).
/// </summary>
/// <param name="path">The file system path.</param>
/// <returns>The representing object.</returns>
/// <remarks>The file system object does not need to exist.</remarks>
public override DiscFileSystemInfo GetFileSystemInfo(string path)
{
return new DiscFileSystemInfo(this, path);
}
/// <summary>
/// Size of the Filesystem in bytes
/// </summary>
public override long Size
{
get { return _wrapped.Size; }
}
/// <summary>
/// Used space of the Filesystem in bytes
/// </summary>
public override long UsedSpace
{
get { return _wrapped.UsedSpace; }
}
/// <summary>
/// Available space of the Filesystem in bytes
/// </summary>
public override long AvailableSpace
{
get { return _wrapped.AvailableSpace; }
}
/// <summary>
/// Provides access to the actual file system implementation.
/// </summary>
/// <typeparam name="TDirEntry">The concrete type representing directory entries.</typeparam>
/// <typeparam name="TFile">The concrete type representing files.</typeparam>
/// <typeparam name="TDirectory">The concrete type representing directories.</typeparam>
/// <typeparam name="TContext">The concrete type holding global state.</typeparam>
/// <returns>The actual file system instance.</returns>
protected VfsFileSystem<TDirEntry, TFile, TDirectory, TContext> GetRealFileSystem
<TDirEntry, TFile, TDirectory, TContext>()
where TDirEntry : VfsDirEntry
where TFile : IVfsFile
where TDirectory : class, IVfsDirectory<TDirEntry, TFile>, TFile
where TContext : VfsContext
{
return (VfsFileSystem<TDirEntry, TFile, TDirectory, TContext>)_wrapped;
}
/// <summary>
/// Provides access to the actual file system implementation.
/// </summary>
/// <typeparam name="T">The concrete type of the actual file system.</typeparam>
/// <returns>The actual file system instance.</returns>
protected T GetRealFileSystem<T>()
where T : DiscFileSystem
{
return (T)_wrapped;
}
}
}
| |
#region Copyright notice and license
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// https://developers.google.com/protocol-buffers/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#endregion
using System;
using System.IO;
using Google.Protobuf.TestProtos;
using Google.Protobuf.Buffers;
using NUnit.Framework;
namespace Google.Protobuf
{
public class CodedOutputStreamTest
{
/// <summary>
/// Writes the given value using WriteRawVarint32() and WriteRawVarint64() and
/// checks that the result matches the given bytes
/// </summary>
private static void AssertWriteVarint(byte[] data, ulong value)
{
// Only do 32-bit write if the value fits in 32 bits.
if ((value >> 32) == 0)
{
// CodedOutputStream
MemoryStream rawOutput = new MemoryStream();
CodedOutputStream output = new CodedOutputStream(rawOutput);
output.WriteRawVarint32((uint) value);
output.Flush();
Assert.AreEqual(data, rawOutput.ToArray());
// IBufferWriter
var bufferWriter = new ArrayBufferWriter<byte>();
WriteContext.Initialize(bufferWriter, out WriteContext ctx);
ctx.WriteUInt32((uint) value);
ctx.Flush();
Assert.AreEqual(data, bufferWriter.WrittenSpan.ToArray());
// Also try computing size.
Assert.AreEqual(data.Length, CodedOutputStream.ComputeRawVarint32Size((uint) value));
}
{
// CodedOutputStream
MemoryStream rawOutput = new MemoryStream();
CodedOutputStream output = new CodedOutputStream(rawOutput);
output.WriteRawVarint64(value);
output.Flush();
Assert.AreEqual(data, rawOutput.ToArray());
// IBufferWriter
var bufferWriter = new ArrayBufferWriter<byte>();
WriteContext.Initialize(bufferWriter, out WriteContext ctx);
ctx.WriteUInt64(value);
ctx.Flush();
Assert.AreEqual(data, bufferWriter.WrittenSpan.ToArray());
// Also try computing size.
Assert.AreEqual(data.Length, CodedOutputStream.ComputeRawVarint64Size(value));
}
// Try different buffer sizes.
for (int bufferSize = 1; bufferSize <= 16; bufferSize *= 2)
{
// Only do 32-bit write if the value fits in 32 bits.
if ((value >> 32) == 0)
{
MemoryStream rawOutput = new MemoryStream();
CodedOutputStream output =
new CodedOutputStream(rawOutput, bufferSize);
output.WriteRawVarint32((uint) value);
output.Flush();
Assert.AreEqual(data, rawOutput.ToArray());
var bufferWriter = new ArrayBufferWriter<byte>();
bufferWriter.MaxGrowBy = bufferSize;
WriteContext.Initialize(bufferWriter, out WriteContext ctx);
ctx.WriteUInt32((uint) value);
ctx.Flush();
Assert.AreEqual(data, bufferWriter.WrittenSpan.ToArray());
}
{
MemoryStream rawOutput = new MemoryStream();
CodedOutputStream output = new CodedOutputStream(rawOutput, bufferSize);
output.WriteRawVarint64(value);
output.Flush();
Assert.AreEqual(data, rawOutput.ToArray());
var bufferWriter = new ArrayBufferWriter<byte>();
bufferWriter.MaxGrowBy = bufferSize;
WriteContext.Initialize(bufferWriter, out WriteContext ctx);
ctx.WriteUInt64(value);
ctx.Flush();
Assert.AreEqual(data, bufferWriter.WrittenSpan.ToArray());
}
}
}
/// <summary>
/// Tests WriteRawVarint32() and WriteRawVarint64()
/// </summary>
[Test]
public void WriteVarint()
{
AssertWriteVarint(new byte[] {0x00}, 0);
AssertWriteVarint(new byte[] {0x01}, 1);
AssertWriteVarint(new byte[] {0x7f}, 127);
// 14882
AssertWriteVarint(new byte[] {0xa2, 0x74}, (0x22 << 0) | (0x74 << 7));
// 2961488830
AssertWriteVarint(new byte[] {0xbe, 0xf7, 0x92, 0x84, 0x0b},
(0x3e << 0) | (0x77 << 7) | (0x12 << 14) | (0x04 << 21) |
(0x0bL << 28));
// 64-bit
// 7256456126
AssertWriteVarint(new byte[] {0xbe, 0xf7, 0x92, 0x84, 0x1b},
(0x3e << 0) | (0x77 << 7) | (0x12 << 14) | (0x04 << 21) |
(0x1bL << 28));
// 41256202580718336
AssertWriteVarint(
new byte[] {0x80, 0xe6, 0xeb, 0x9c, 0xc3, 0xc9, 0xa4, 0x49},
(0x00 << 0) | (0x66 << 7) | (0x6b << 14) | (0x1c << 21) |
(0x43UL << 28) | (0x49L << 35) | (0x24UL << 42) | (0x49UL << 49));
// 11964378330978735131
AssertWriteVarint(
new byte[] {0x9b, 0xa8, 0xf9, 0xc2, 0xbb, 0xd6, 0x80, 0x85, 0xa6, 0x01},
unchecked((ulong)
((0x1b << 0) | (0x28 << 7) | (0x79 << 14) | (0x42 << 21) |
(0x3bL << 28) | (0x56L << 35) | (0x00L << 42) |
(0x05L << 49) | (0x26L << 56) | (0x01L << 63))));
}
/// <summary>
/// Parses the given bytes using WriteRawLittleEndian32() and checks
/// that the result matches the given value.
/// </summary>
private static void AssertWriteLittleEndian32(byte[] data, uint value)
{
{
var rawOutput = new MemoryStream();
var output = new CodedOutputStream(rawOutput);
output.WriteRawLittleEndian32(value);
output.Flush();
Assert.AreEqual(data, rawOutput.ToArray());
var bufferWriter = new ArrayBufferWriter<byte>();
WriteContext.Initialize(bufferWriter, out WriteContext ctx);
ctx.WriteFixed32(value);
ctx.Flush();
Assert.AreEqual(data, bufferWriter.WrittenSpan.ToArray());
}
// Try different buffer sizes.
for (int bufferSize = 1; bufferSize <= 16; bufferSize *= 2)
{
var rawOutput = new MemoryStream();
var output = new CodedOutputStream(rawOutput, bufferSize);
output.WriteRawLittleEndian32(value);
output.Flush();
Assert.AreEqual(data, rawOutput.ToArray());
var bufferWriter = new ArrayBufferWriter<byte>();
bufferWriter.MaxGrowBy = bufferSize;
WriteContext.Initialize(bufferWriter, out WriteContext ctx);
ctx.WriteFixed32(value);
ctx.Flush();
Assert.AreEqual(data, bufferWriter.WrittenSpan.ToArray());
}
}
/// <summary>
/// Parses the given bytes using WriteRawLittleEndian64() and checks
/// that the result matches the given value.
/// </summary>
private static void AssertWriteLittleEndian64(byte[] data, ulong value)
{
{
var rawOutput = new MemoryStream();
var output = new CodedOutputStream(rawOutput);
output.WriteRawLittleEndian64(value);
output.Flush();
Assert.AreEqual(data, rawOutput.ToArray());
var bufferWriter = new ArrayBufferWriter<byte>();
WriteContext.Initialize(bufferWriter, out WriteContext ctx);
ctx.WriteFixed64(value);
ctx.Flush();
Assert.AreEqual(data, bufferWriter.WrittenSpan.ToArray());
}
// Try different block sizes.
for (int blockSize = 1; blockSize <= 16; blockSize *= 2)
{
var rawOutput = new MemoryStream();
var output = new CodedOutputStream(rawOutput, blockSize);
output.WriteRawLittleEndian64(value);
output.Flush();
Assert.AreEqual(data, rawOutput.ToArray());
var bufferWriter = new ArrayBufferWriter<byte>();
bufferWriter.MaxGrowBy = blockSize;
WriteContext.Initialize(bufferWriter, out WriteContext ctx);
ctx.WriteFixed64(value);
ctx.Flush();
Assert.AreEqual(data, bufferWriter.WrittenSpan.ToArray());
}
}
/// <summary>
/// Tests writeRawLittleEndian32() and writeRawLittleEndian64().
/// </summary>
[Test]
public void WriteLittleEndian()
{
AssertWriteLittleEndian32(new byte[] {0x78, 0x56, 0x34, 0x12}, 0x12345678);
AssertWriteLittleEndian32(new byte[] {0xf0, 0xde, 0xbc, 0x9a}, 0x9abcdef0);
AssertWriteLittleEndian64(
new byte[] {0xf0, 0xde, 0xbc, 0x9a, 0x78, 0x56, 0x34, 0x12},
0x123456789abcdef0L);
AssertWriteLittleEndian64(
new byte[] {0x78, 0x56, 0x34, 0x12, 0xf0, 0xde, 0xbc, 0x9a},
0x9abcdef012345678UL);
}
[Test]
public void WriteWholeMessage_VaryingBlockSizes()
{
TestAllTypes message = SampleMessages.CreateFullTestAllTypes();
byte[] rawBytes = message.ToByteArray();
// Try different block sizes.
for (int blockSize = 1; blockSize < 256; blockSize *= 2)
{
MemoryStream rawOutput = new MemoryStream();
CodedOutputStream output = new CodedOutputStream(rawOutput, blockSize);
message.WriteTo(output);
output.Flush();
Assert.AreEqual(rawBytes, rawOutput.ToArray());
var bufferWriter = new ArrayBufferWriter<byte>();
bufferWriter.MaxGrowBy = blockSize;
message.WriteTo(bufferWriter);
Assert.AreEqual(rawBytes, bufferWriter.WrittenSpan.ToArray());
}
}
[Test]
public void WriteContext_WritesWithFlushes()
{
TestAllTypes message = SampleMessages.CreateFullTestAllTypes();
MemoryStream expectedOutput = new MemoryStream();
CodedOutputStream output = new CodedOutputStream(expectedOutput);
output.WriteMessage(message);
output.Flush();
byte[] expectedBytes1 = expectedOutput.ToArray();
output.WriteMessage(message);
output.Flush();
byte[] expectedBytes2 = expectedOutput.ToArray();
var bufferWriter = new ArrayBufferWriter<byte>();
WriteContext.Initialize(bufferWriter, out WriteContext ctx);
ctx.WriteMessage(message);
ctx.Flush();
Assert.AreEqual(expectedBytes1, bufferWriter.WrittenSpan.ToArray());
ctx.WriteMessage(message);
ctx.Flush();
Assert.AreEqual(expectedBytes2, bufferWriter.WrittenSpan.ToArray());
}
[Test]
public void EncodeZigZag32()
{
Assert.AreEqual(0u, WritingPrimitives.EncodeZigZag32(0));
Assert.AreEqual(1u, WritingPrimitives.EncodeZigZag32(-1));
Assert.AreEqual(2u, WritingPrimitives.EncodeZigZag32(1));
Assert.AreEqual(3u, WritingPrimitives.EncodeZigZag32(-2));
Assert.AreEqual(0x7FFFFFFEu, WritingPrimitives.EncodeZigZag32(0x3FFFFFFF));
Assert.AreEqual(0x7FFFFFFFu, WritingPrimitives.EncodeZigZag32(unchecked((int) 0xC0000000)));
Assert.AreEqual(0xFFFFFFFEu, WritingPrimitives.EncodeZigZag32(0x7FFFFFFF));
Assert.AreEqual(0xFFFFFFFFu, WritingPrimitives.EncodeZigZag32(unchecked((int) 0x80000000)));
}
[Test]
public void EncodeZigZag64()
{
Assert.AreEqual(0u, WritingPrimitives.EncodeZigZag64(0));
Assert.AreEqual(1u, WritingPrimitives.EncodeZigZag64(-1));
Assert.AreEqual(2u, WritingPrimitives.EncodeZigZag64(1));
Assert.AreEqual(3u, WritingPrimitives.EncodeZigZag64(-2));
Assert.AreEqual(0x000000007FFFFFFEuL,
WritingPrimitives.EncodeZigZag64(unchecked((long) 0x000000003FFFFFFFUL)));
Assert.AreEqual(0x000000007FFFFFFFuL,
WritingPrimitives.EncodeZigZag64(unchecked((long) 0xFFFFFFFFC0000000UL)));
Assert.AreEqual(0x00000000FFFFFFFEuL,
WritingPrimitives.EncodeZigZag64(unchecked((long) 0x000000007FFFFFFFUL)));
Assert.AreEqual(0x00000000FFFFFFFFuL,
WritingPrimitives.EncodeZigZag64(unchecked((long) 0xFFFFFFFF80000000UL)));
Assert.AreEqual(0xFFFFFFFFFFFFFFFEL,
WritingPrimitives.EncodeZigZag64(unchecked((long) 0x7FFFFFFFFFFFFFFFUL)));
Assert.AreEqual(0xFFFFFFFFFFFFFFFFL,
WritingPrimitives.EncodeZigZag64(unchecked((long) 0x8000000000000000UL)));
}
[Test]
public void RoundTripZigZag32()
{
// Some easier-to-verify round-trip tests. The inputs (other than 0, 1, -1)
// were chosen semi-randomly via keyboard bashing.
Assert.AreEqual(0, ParsingPrimitives.DecodeZigZag32(WritingPrimitives.EncodeZigZag32(0)));
Assert.AreEqual(1, ParsingPrimitives.DecodeZigZag32(WritingPrimitives.EncodeZigZag32(1)));
Assert.AreEqual(-1, ParsingPrimitives.DecodeZigZag32(WritingPrimitives.EncodeZigZag32(-1)));
Assert.AreEqual(14927, ParsingPrimitives.DecodeZigZag32(WritingPrimitives.EncodeZigZag32(14927)));
Assert.AreEqual(-3612, ParsingPrimitives.DecodeZigZag32(WritingPrimitives.EncodeZigZag32(-3612)));
}
[Test]
public void RoundTripZigZag64()
{
Assert.AreEqual(0, ParsingPrimitives.DecodeZigZag64(WritingPrimitives.EncodeZigZag64(0)));
Assert.AreEqual(1, ParsingPrimitives.DecodeZigZag64(WritingPrimitives.EncodeZigZag64(1)));
Assert.AreEqual(-1, ParsingPrimitives.DecodeZigZag64(WritingPrimitives.EncodeZigZag64(-1)));
Assert.AreEqual(14927, ParsingPrimitives.DecodeZigZag64(WritingPrimitives.EncodeZigZag64(14927)));
Assert.AreEqual(-3612, ParsingPrimitives.DecodeZigZag64(WritingPrimitives.EncodeZigZag64(-3612)));
Assert.AreEqual(856912304801416L,
ParsingPrimitives.DecodeZigZag64(WritingPrimitives.EncodeZigZag64(856912304801416L)));
Assert.AreEqual(-75123905439571256L,
ParsingPrimitives.DecodeZigZag64(WritingPrimitives.EncodeZigZag64(-75123905439571256L)));
}
[Test]
public void TestNegativeEnumNoTag()
{
Assert.AreEqual(10, CodedOutputStream.ComputeInt32Size(-2));
Assert.AreEqual(10, CodedOutputStream.ComputeEnumSize((int) SampleEnum.NegativeValue));
byte[] bytes = new byte[10];
CodedOutputStream output = new CodedOutputStream(bytes);
output.WriteEnum((int) SampleEnum.NegativeValue);
Assert.AreEqual(0, output.SpaceLeft);
Assert.AreEqual("FE-FF-FF-FF-FF-FF-FF-FF-FF-01", BitConverter.ToString(bytes));
}
[Test]
public void TestCodedInputOutputPosition()
{
byte[] content = new byte[110];
for (int i = 0; i < content.Length; i++)
content[i] = (byte)i;
byte[] child = new byte[120];
{
MemoryStream ms = new MemoryStream(child);
CodedOutputStream cout = new CodedOutputStream(ms, 20);
// Field 11: numeric value: 500
cout.WriteTag(11, WireFormat.WireType.Varint);
Assert.AreEqual(1, cout.Position);
cout.WriteInt32(500);
Assert.AreEqual(3, cout.Position);
//Field 12: length delimited 120 bytes
cout.WriteTag(12, WireFormat.WireType.LengthDelimited);
Assert.AreEqual(4, cout.Position);
cout.WriteBytes(ByteString.CopyFrom(content));
Assert.AreEqual(115, cout.Position);
// Field 13: fixed numeric value: 501
cout.WriteTag(13, WireFormat.WireType.Fixed32);
Assert.AreEqual(116, cout.Position);
cout.WriteSFixed32(501);
Assert.AreEqual(120, cout.Position);
cout.Flush();
}
byte[] bytes = new byte[130];
{
CodedOutputStream cout = new CodedOutputStream(bytes);
// Field 1: numeric value: 500
cout.WriteTag(1, WireFormat.WireType.Varint);
Assert.AreEqual(1, cout.Position);
cout.WriteInt32(500);
Assert.AreEqual(3, cout.Position);
//Field 2: length delimited 120 bytes
cout.WriteTag(2, WireFormat.WireType.LengthDelimited);
Assert.AreEqual(4, cout.Position);
cout.WriteBytes(ByteString.CopyFrom(child));
Assert.AreEqual(125, cout.Position);
// Field 3: fixed numeric value: 500
cout.WriteTag(3, WireFormat.WireType.Fixed32);
Assert.AreEqual(126, cout.Position);
cout.WriteSFixed32(501);
Assert.AreEqual(130, cout.Position);
cout.Flush();
}
// Now test Input stream:
{
CodedInputStream cin = new CodedInputStream(new MemoryStream(bytes), new byte[50], 0, 0, false);
Assert.AreEqual(0, cin.Position);
// Field 1:
uint tag = cin.ReadTag();
Assert.AreEqual(1, tag >> 3);
Assert.AreEqual(1, cin.Position);
Assert.AreEqual(500, cin.ReadInt32());
Assert.AreEqual(3, cin.Position);
//Field 2:
tag = cin.ReadTag();
Assert.AreEqual(2, tag >> 3);
Assert.AreEqual(4, cin.Position);
int childlen = cin.ReadLength();
Assert.AreEqual(120, childlen);
Assert.AreEqual(5, cin.Position);
int oldlimit = cin.PushLimit((int)childlen);
Assert.AreEqual(5, cin.Position);
// Now we are reading child message
{
// Field 11: numeric value: 500
tag = cin.ReadTag();
Assert.AreEqual(11, tag >> 3);
Assert.AreEqual(6, cin.Position);
Assert.AreEqual(500, cin.ReadInt32());
Assert.AreEqual(8, cin.Position);
//Field 12: length delimited 120 bytes
tag = cin.ReadTag();
Assert.AreEqual(12, tag >> 3);
Assert.AreEqual(9, cin.Position);
ByteString bstr = cin.ReadBytes();
Assert.AreEqual(110, bstr.Length);
Assert.AreEqual((byte) 109, bstr[109]);
Assert.AreEqual(120, cin.Position);
// Field 13: fixed numeric value: 501
tag = cin.ReadTag();
Assert.AreEqual(13, tag >> 3);
// ROK - Previously broken here, this returned 126 failing to account for bufferSizeAfterLimit
Assert.AreEqual(121, cin.Position);
Assert.AreEqual(501, cin.ReadSFixed32());
Assert.AreEqual(125, cin.Position);
Assert.IsTrue(cin.IsAtEnd);
}
cin.PopLimit(oldlimit);
Assert.AreEqual(125, cin.Position);
// Field 3: fixed numeric value: 501
tag = cin.ReadTag();
Assert.AreEqual(3, tag >> 3);
Assert.AreEqual(126, cin.Position);
Assert.AreEqual(501, cin.ReadSFixed32());
Assert.AreEqual(130, cin.Position);
Assert.IsTrue(cin.IsAtEnd);
}
}
[Test]
public void Dispose_DisposesUnderlyingStream()
{
var memoryStream = new MemoryStream();
Assert.IsTrue(memoryStream.CanWrite);
using (var cos = new CodedOutputStream(memoryStream))
{
cos.WriteRawBytes(new byte[] {0});
Assert.AreEqual(0, memoryStream.Position); // Not flushed yet
}
Assert.AreEqual(1, memoryStream.ToArray().Length); // Flushed data from CodedOutputStream to MemoryStream
Assert.IsFalse(memoryStream.CanWrite); // Disposed
}
[Test]
public void Dispose_WithLeaveOpen()
{
var memoryStream = new MemoryStream();
Assert.IsTrue(memoryStream.CanWrite);
using (var cos = new CodedOutputStream(memoryStream, true))
{
cos.WriteRawBytes(new byte[] {0});
Assert.AreEqual(0, memoryStream.Position); // Not flushed yet
}
Assert.AreEqual(1, memoryStream.Position); // Flushed data from CodedOutputStream to MemoryStream
Assert.IsTrue(memoryStream.CanWrite); // We left the stream open
}
[Test]
public void Dispose_FromByteArray()
{
var stream = new CodedOutputStream(new byte[10]);
stream.Dispose();
}
}
}
| |
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
namespace UMA
{
/// <summary>
/// Default mesh combiner for UMA UMAMeshdata from slots.
/// </summary>
public class UMADefaultMeshCombiner : UMAMeshCombiner
{
protected List<SkinnedMeshCombiner.CombineInstance> combinedMeshList;
protected List<Material> combinedMaterialList;
UMAData umaData;
int atlasResolution;
protected void EnsureUMADataSetup(UMAData umaData)
{
if (umaData.umaRoot == null)
{
GameObject newRoot = new GameObject("Root");
//make root of the UMAAvatar respect the layer setting of the UMAAvatar so cameras can just target this layer
newRoot.layer = umaData.gameObject.layer;
newRoot.transform.parent = umaData.transform;
newRoot.transform.localPosition = Vector3.zero;
newRoot.transform.localRotation = Quaternion.Euler(270f, 0, 0f);
newRoot.transform.localScale = Vector3.one;
umaData.umaRoot = newRoot;
GameObject newGlobal = new GameObject("Global");
newGlobal.transform.parent = newRoot.transform;
newGlobal.transform.localPosition = Vector3.zero;
newGlobal.transform.localRotation = Quaternion.Euler(90f, 90f, 0f);
GameObject newSMRGO = new GameObject("UMARenderer");
//make UMARenderer GO respect the layer setting of the UMAAvatar so cameras can just target this layer
newSMRGO.layer = umaData.gameObject.layer;
newSMRGO.transform.parent = umaData.transform;
newSMRGO.transform.localPosition = Vector3.zero;
newSMRGO.transform.localRotation = Quaternion.Euler(0, 0, 0f);
newSMRGO.transform.localScale = Vector3.one;
umaData.skeleton = new UMASkeleton(newGlobal.transform);
var newRenderer = newSMRGO.AddComponent<SkinnedMeshRenderer>();
newRenderer.rootBone = newGlobal.transform;
umaData.myRenderer = newRenderer;
umaData.myRenderer.enabled = false;
umaData.myRenderer.sharedMesh = new Mesh();
}
else
{
umaData.CleanMesh(false);
}
}
/// <summary>
/// Updates the UMA mesh and skeleton to match current slots.
/// </summary>
/// <param name="updatedAtlas">If set to <c>true</c> atlas has changed.</param>
/// <param name="umaData">UMA data.</param>
/// <param name="atlasResolution">Atlas resolution.</param>
public override void UpdateUMAMesh(bool updatedAtlas, UMAData umaData, int atlasResolution)
{
this.umaData = umaData;
this.atlasResolution = atlasResolution;
combinedMeshList = new List<SkinnedMeshCombiner.CombineInstance>(umaData.umaRecipe.slotDataList.Length);
combinedMaterialList = new List<Material>();
BuildCombineInstances();
EnsureUMADataSetup(umaData);
umaData.skeleton.BeginSkeletonUpdate();
UMAMeshData umaMesh = new UMAMeshData();
umaMesh.ClaimSharedBuffers();
SkinnedMeshCombiner.CombineMeshes(umaMesh, combinedMeshList.ToArray());
if (updatedAtlas)
{
RecalculateUV(umaMesh);
}
umaMesh.ApplyDataToUnityMesh(umaData.myRenderer, umaData.skeleton);
umaMesh.ReleaseSharedBuffers();
umaData.umaRecipe.ClearDNAConverters();
for (int i = 0; i < umaData.umaRecipe.slotDataList.Length; i++)
{
SlotData slotData = umaData.umaRecipe.slotDataList[i];
if (slotData != null)
{
// umaData.EnsureBoneData(slotData.umaBoneData, slotData.animatedBones, boneMap);
umaData.umaRecipe.AddDNAUpdater(slotData.asset.slotDNA);
}
}
umaData.myRenderer.quality = SkinQuality.Bone4;
//umaData.myRenderer.useLightProbes = true;
var materials = combinedMaterialList.ToArray();
umaData.myRenderer.sharedMaterials = materials;
//umaData.myRenderer.sharedMesh.RecalculateBounds();
umaData.myRenderer.sharedMesh.name = "UMAMesh";
umaData.firstBake = false;
//FireSlotAtlasNotification(umaData, materials);
}
//private void FireSlotAtlasNotification(UMAData umaData, Material[] materials)
//{
// for (int atlasIndex = 0; atlasIndex < umaData.atlasList.atlas.Count; atlasIndex++)
// {
// for (int materialDefinitionIndex = 0; materialDefinitionIndex < umaData.atlasList.atlas[atlasIndex].atlasMaterialDefinitions.Count; materialDefinitionIndex++)
// {
// var materialDefinition = umaData.atlasList.atlas[atlasIndex].atlasMaterialDefinitions[materialDefinitionIndex];
// var slotData = materialDefinition.source.slotData;
// if (slotData.SlotAtlassed != null)
// {
// slotData.SlotAtlassed.Invoke(umaData, slotData, materials[atlasIndex], materialDefinition.atlasRegion);
// }
// }
// }
// SlotData[] slots = umaData.umaRecipe.slotDataList;
// for (int slotIndex = 0; slotIndex < slots.Length; slotIndex++)
// {
// var slotData = slots[slotIndex];
// if (slotData == null) continue;
// if (slotData.textureNameList.Length == 1 && string.IsNullOrEmpty(slotData.textureNameList[0]))
// {
// if (slotData.SlotAtlassed != null)
// {
// slotData.SlotAtlassed.Invoke(umaData, slotData, materials[atlasIndex], materialDefinition.atlasRegion);
// }
// }
// }
//}
protected void BuildCombineInstances()
{
SkinnedMeshCombiner.CombineInstance combineInstance;
for (int materialIndex = 0; materialIndex < umaData.generatedMaterials.materials.Count; materialIndex++)
{
var generatedMaterial = umaData.generatedMaterials.materials[materialIndex];
combinedMaterialList.Add(generatedMaterial.material);
for (int materialDefinitionIndex = 0; materialDefinitionIndex < generatedMaterial.materialFragments.Count; materialDefinitionIndex++)
{
var materialDefinition = generatedMaterial.materialFragments[materialDefinitionIndex];
var slotData = materialDefinition.slotData;
combineInstance = new SkinnedMeshCombiner.CombineInstance();
combineInstance.meshData = slotData.asset.meshData;
combineInstance.targetSubmeshIndices = new int[combineInstance.meshData.subMeshCount];
for (int i = 0; i < combineInstance.meshData.subMeshCount; i++)
{
combineInstance.targetSubmeshIndices[i] = -1;
}
combineInstance.targetSubmeshIndices[slotData.asset.subMeshIndex] = materialIndex;
combinedMeshList.Add(combineInstance);
if (slotData.asset.SlotAtlassed != null)
{
slotData.asset.SlotAtlassed.Invoke(umaData, slotData, generatedMaterial.material, materialDefinition.atlasRegion);
}
}
}
}
protected void RecalculateUV(UMAMeshData umaMesh)
{
int idx = 0;
//Handle Atlassed Verts
for (int materialIndex = 0; materialIndex < umaData.generatedMaterials.materials.Count; materialIndex++)
{
var generatedMaterial = umaData.generatedMaterials.materials[materialIndex];
if (generatedMaterial.umaMaterial.materialType != UMAMaterial.MaterialType.Atlas)
{
var fragment = generatedMaterial.materialFragments[0];
int vertexCount = fragment.slotData.asset.meshData.vertices.Length;
idx += vertexCount;
continue;
}
for (int materialDefinitionIndex = 0; materialDefinitionIndex < generatedMaterial.materialFragments.Count; materialDefinitionIndex++)
{
var fragment = generatedMaterial.materialFragments[materialDefinitionIndex];
var tempAtlasRect = fragment.atlasRegion;
int vertexCount = fragment.slotData.asset.meshData.vertices.Length;
float atlasXMin = tempAtlasRect.xMin / atlasResolution;
float atlasXMax = tempAtlasRect.xMax / atlasResolution;
float atlasXRange = atlasXMax - atlasXMin;
float atlasYMin = tempAtlasRect.yMin / atlasResolution;
float atlasYMax = tempAtlasRect.yMax / atlasResolution;
float atlasYRange = atlasYMax - atlasYMin;
while (vertexCount-- > 0)
{
umaMesh.uv[idx].x = atlasXMin + atlasXRange * umaMesh.uv[idx].x;
umaMesh.uv[idx].y = atlasYMin + atlasYRange * umaMesh.uv[idx].y;
idx++;
}
}
}
}
}
}
| |
//---------------------------------------------------------------------
// <copyright file="ALinqExpressionVisitor.cs" company="Microsoft">
// Copyright (C) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
// </copyright>
//---------------------------------------------------------------------
#if ASTORIA_SERVER
namespace Microsoft.OData.Service
#else
namespace Microsoft.OData.Client
#endif
{
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq.Expressions;
#if ASTORIA_LIGHT
using System.Reflection;
using System.Security;
using System.Security.Permissions;
/// <summary>
/// This class introduced because of a bug in SL3 which prevents using non-public (e.g anonymous) types as return types for lambdas
/// We should be able to remove this for SL4.
/// devnote (sparra): This still seems to be an issue in SL4, but does not repro in Win8 .NETCore framework.
/// </summary>
internal static class ExpressionHelpers
{
/// <summary>Lambda function.</summary>
private static MethodInfo lambdaFunc;
/// <summary>
/// Create a lambda function given the expression and the parameters.
/// </summary>
/// <param name="body">Expression for the lambda function.</param>
/// <param name="parameters">Parameters for the lambda function.</param>
/// <returns>An instance of LambdaExpression.</returns>
internal static LambdaExpression CreateLambda(Expression body, params ParameterExpression[] parameters)
{
return CreateLambda(InferDelegateType(body, parameters), body, parameters);
}
/// <summary>
/// This creates a tree and compiles it just for the purposes of creating the real lambda.
/// </summary>
/// <param name="delegateType">Generic type for the Lambda function.</param>
/// <param name="body">Expression for the lambda function.</param>
/// <param name="parameters">Parameters for the lambda function.</param>
/// <returns>An instance of LambdaExpression.</returns>
internal static LambdaExpression CreateLambda(Type delegateType, Expression body, params ParameterExpression[] parameters)
{
// Expression.Lambda() doesn't work directly if "body" is a non-public type
// Work around this by calling the factory from a DynamicMethod.
var args = new[] { Expression.Parameter(typeof(Expression), "body"), Expression.Parameter(typeof(ParameterExpression[]), "parameters") };
var lambdaFactory = Expression.Lambda<Func<Expression, ParameterExpression[], LambdaExpression>>(
Expression.Call(GetLambdaFactoryMethod(delegateType), args), args);
return lambdaFactory.Compile().Invoke(body, parameters);
}
/// <summary>
/// Returns the generic type of the lambda function.
/// </summary>
/// <param name="body">Expression for the lambda function.</param>
/// <param name="parameters">Parameters for the lambda function.</param>
/// <returns>The generic type of the lambda function.</returns>
private static Type InferDelegateType(Expression body, params ParameterExpression[] parameters)
{
bool isVoid = body.Type == typeof(void);
int length = (parameters == null) ? 0 : parameters.Length;
var typeArgs = new Type[length + (isVoid ? 0 : 1)];
for (int i = 0; i < length; i++)
{
typeArgs[i] = parameters[i].Type;
}
if (isVoid)
{
return Expression.GetActionType(typeArgs);
}
else
{
typeArgs[length] = body.Type;
return Expression.GetFuncType(typeArgs);
}
}
/// <summary>
/// Returns the methodinfo for the lambda function.
/// </summary>
/// <param name="delegateType">Generic type of the lambda function.</param>
/// <returns>MethodInfo which binds the generic type to the lambda function.</returns>
private static MethodInfo GetLambdaFactoryMethod(Type delegateType)
{
// Gets the MethodInfo for Expression.Lambda<TDelegate>(Expression body, params ParameterExpression[] parameters)
if (lambdaFunc == null)
{
lambdaFunc = new Func<Expression, ParameterExpression[], Expression<Action>>(Expression.Lambda<Action>).Method.GetGenericMethodDefinition();
}
// Create a throwaway delegate to bind to the right Labda function with a specific delegate type.
return lambdaFunc.MakeGenericMethod(delegateType);
}
}
#endif
/// <summary>
/// base vistor class for walking an expression tree bottom up.
/// </summary>
internal abstract class ALinqExpressionVisitor
{
/// <summary>
/// Main visit method for ALinqExpressionVisitor
/// </summary>
/// <param name="exp">The expression to visit</param>
/// <returns>The visited expression </returns>
internal virtual Expression Visit(Expression exp)
{
if (exp == null)
{
return exp;
}
switch (exp.NodeType)
{
case ExpressionType.UnaryPlus:
case ExpressionType.Negate:
case ExpressionType.NegateChecked:
case ExpressionType.Not:
case ExpressionType.Convert:
case ExpressionType.ConvertChecked:
case ExpressionType.ArrayLength:
case ExpressionType.Quote:
case ExpressionType.TypeAs:
return this.VisitUnary((UnaryExpression)exp);
case ExpressionType.Add:
case ExpressionType.AddChecked:
case ExpressionType.Subtract:
case ExpressionType.SubtractChecked:
case ExpressionType.Multiply:
case ExpressionType.MultiplyChecked:
case ExpressionType.Divide:
case ExpressionType.Modulo:
#if !ASTORIA_CLIENT
case ExpressionType.Power:
#endif
case ExpressionType.And:
case ExpressionType.AndAlso:
case ExpressionType.Or:
case ExpressionType.OrElse:
case ExpressionType.LessThan:
case ExpressionType.LessThanOrEqual:
case ExpressionType.GreaterThan:
case ExpressionType.GreaterThanOrEqual:
case ExpressionType.Equal:
case ExpressionType.NotEqual:
case ExpressionType.Coalesce:
case ExpressionType.ArrayIndex:
case ExpressionType.RightShift:
case ExpressionType.LeftShift:
case ExpressionType.ExclusiveOr:
return this.VisitBinary((BinaryExpression)exp);
case ExpressionType.TypeIs:
return this.VisitTypeIs((TypeBinaryExpression)exp);
case ExpressionType.Conditional:
return this.VisitConditional((ConditionalExpression)exp);
case ExpressionType.Constant:
return this.VisitConstant((ConstantExpression)exp);
case ExpressionType.Parameter:
return this.VisitParameter((ParameterExpression)exp);
case ExpressionType.MemberAccess:
return this.VisitMemberAccess((MemberExpression)exp);
case ExpressionType.Call:
return this.VisitMethodCall((MethodCallExpression)exp);
case ExpressionType.Lambda:
return this.VisitLambda((LambdaExpression)exp);
case ExpressionType.New:
return this.VisitNew((NewExpression)exp);
case ExpressionType.NewArrayInit:
case ExpressionType.NewArrayBounds:
return this.VisitNewArray((NewArrayExpression)exp);
case ExpressionType.Invoke:
return this.VisitInvocation((InvocationExpression)exp);
case ExpressionType.MemberInit:
return this.VisitMemberInit((MemberInitExpression)exp);
case ExpressionType.ListInit:
return this.VisitListInit((ListInitExpression)exp);
default:
throw new NotSupportedException(Strings.ALinq_UnsupportedExpression(exp.NodeType.ToString()));
}
}
/// <summary>
/// MemberBinding visit method
/// </summary>
/// <param name="binding">The MemberBinding expression to visit</param>
/// <returns>The visited MemberBinding expression </returns>
internal virtual MemberBinding VisitBinding(MemberBinding binding)
{
switch (binding.BindingType)
{
case MemberBindingType.Assignment:
return this.VisitMemberAssignment((MemberAssignment)binding);
case MemberBindingType.MemberBinding:
return this.VisitMemberMemberBinding((MemberMemberBinding)binding);
case MemberBindingType.ListBinding:
return this.VisitMemberListBinding((MemberListBinding)binding);
default:
throw new NotSupportedException(Strings.ALinq_UnsupportedExpression(binding.BindingType.ToString()));
}
}
/// <summary>
/// ElementInit visit method
/// </summary>
/// <param name="initializer">The ElementInit expression to visit</param>
/// <returns>The visited ElementInit expression </returns>
internal virtual ElementInit VisitElementInitializer(ElementInit initializer)
{
ReadOnlyCollection<Expression> arguments = this.VisitExpressionList(initializer.Arguments);
return arguments != initializer.Arguments ? Expression.ElementInit(initializer.AddMethod, arguments) : initializer;
}
/// <summary>
/// UnaryExpression visit method
/// </summary>
/// <param name="u">The UnaryExpression expression to visit</param>
/// <returns>The visited UnaryExpression expression </returns>
internal virtual Expression VisitUnary(UnaryExpression u)
{
Expression operand = this.Visit(u.Operand);
return operand != u.Operand ? Expression.MakeUnary(u.NodeType, operand, u.Type, u.Method) : u;
}
/// <summary>
/// BinaryExpression visit method
/// </summary>
/// <param name="b">The BinaryExpression expression to visit</param>
/// <returns>The visited BinaryExpression expression </returns>
internal virtual Expression VisitBinary(BinaryExpression b)
{
Expression left = this.Visit(b.Left);
Expression right = this.Visit(b.Right);
Expression conversion = this.Visit(b.Conversion);
if (left != b.Left || right != b.Right || conversion != b.Conversion)
{
if (b.NodeType == ExpressionType.Coalesce && b.Conversion != null)
{
return Expression.Coalesce(left, right, conversion as LambdaExpression);
}
return Expression.MakeBinary(b.NodeType, left, right, b.IsLiftedToNull, b.Method);
}
return b;
}
/// <summary>
/// TypeBinaryExpression visit method
/// </summary>
/// <param name="b">The TypeBinaryExpression expression to visit</param>
/// <returns>The visited TypeBinaryExpression expression </returns>
internal virtual Expression VisitTypeIs(TypeBinaryExpression b)
{
Expression expr = this.Visit(b.Expression);
return expr != b.Expression ? Expression.TypeIs(expr, b.TypeOperand) : b;
}
/// <summary>
/// ConstantExpression visit method
/// </summary>
/// <param name="c">The ConstantExpression expression to visit</param>
/// <returns>The visited ConstantExpression expression </returns>
internal virtual Expression VisitConstant(ConstantExpression c)
{
return c;
}
/// <summary>
/// ConditionalExpression visit method
/// </summary>
/// <param name="c">The ConditionalExpression expression to visit</param>
/// <returns>The visited ConditionalExpression expression </returns>
internal virtual Expression VisitConditional(ConditionalExpression c)
{
Expression test = this.Visit(c.Test);
Expression iftrue = this.Visit(c.IfTrue);
Expression iffalse = this.Visit(c.IfFalse);
if (test != c.Test || iftrue != c.IfTrue || iffalse != c.IfFalse)
{
return Expression.Condition(test, iftrue, iffalse, iftrue.Type.IsAssignableFrom(iffalse.Type) ? iftrue.Type : iffalse.Type);
}
return c;
}
/// <summary>
/// ParameterExpression visit method
/// </summary>
/// <param name="p">The ParameterExpression expression to visit</param>
/// <returns>The visited ParameterExpression expression </returns>
internal virtual Expression VisitParameter(ParameterExpression p)
{
return p;
}
/// <summary>
/// MemberExpression visit method
/// </summary>
/// <param name="m">The MemberExpression expression to visit</param>
/// <returns>The visited MemberExpression expression </returns>
internal virtual Expression VisitMemberAccess(MemberExpression m)
{
Expression exp = this.Visit(m.Expression);
return exp != m.Expression ? Expression.MakeMemberAccess(exp, m.Member) : m;
}
/// <summary>
/// MethodCallExpression visit method
/// </summary>
/// <param name="m">The MethodCallExpression expression to visit</param>
/// <returns>The visited MethodCallExpression expression </returns>
internal virtual Expression VisitMethodCall(MethodCallExpression m)
{
Expression obj = this.Visit(m.Object);
IEnumerable<Expression> args = this.VisitExpressionList(m.Arguments);
return obj != m.Object || args != m.Arguments ? Expression.Call(obj, m.Method, args) : m;
}
/// <summary>
/// Expression list visit method
/// </summary>
/// <param name="original">The expression list to visit</param>
/// <returns>The visited expression list</returns>
internal virtual ReadOnlyCollection<Expression> VisitExpressionList(ReadOnlyCollection<Expression> original)
{
List<Expression> list = null;
for (int i = 0, n = original.Count; i < n; i++)
{
Expression p = this.Visit(original[i]);
if (list != null)
{
list.Add(p);
}
else if (p != original[i])
{
list = new List<Expression>(n);
for (int j = 0; j < i; j++)
{
list.Add(original[j]);
}
list.Add(p);
}
}
if (list != null)
{
return new ReadOnlyCollection<Expression>(list);
}
return original;
}
/// <summary>
/// MemberAssignment visit method
/// </summary>
/// <param name="assignment">The MemberAssignment to visit</param>
/// <returns>The visited MemberAssignmentt</returns>
internal virtual MemberAssignment VisitMemberAssignment(MemberAssignment assignment)
{
Expression e = this.Visit(assignment.Expression);
return e != assignment.Expression ? Expression.Bind(assignment.Member, e) : assignment;
}
/// <summary>
/// MemberMemberBinding visit method
/// </summary>
/// <param name="binding">The MemberMemberBinding to visit</param>
/// <returns>The visited MemberMemberBinding</returns>
internal virtual MemberMemberBinding VisitMemberMemberBinding(MemberMemberBinding binding)
{
IEnumerable<MemberBinding> bindings = this.VisitBindingList(binding.Bindings);
return bindings != binding.Bindings ? Expression.MemberBind(binding.Member, bindings) : binding;
}
/// <summary>
/// MemberListBinding visit method
/// </summary>
/// <param name="binding">The MemberListBinding to visit</param>
/// <returns>The visited MemberListBinding</returns>
internal virtual MemberListBinding VisitMemberListBinding(MemberListBinding binding)
{
IEnumerable<ElementInit> initializers = this.VisitElementInitializerList(binding.Initializers);
return initializers != binding.Initializers ? Expression.ListBind(binding.Member, initializers) : binding;
}
/// <summary>
/// Binding List visit method
/// </summary>
/// <param name="original">The Binding list to visit</param>
/// <returns>The visited Binding list</returns>
internal virtual IEnumerable<MemberBinding> VisitBindingList(ReadOnlyCollection<MemberBinding> original)
{
List<MemberBinding> list = null;
for (int i = 0, n = original.Count; i < n; i++)
{
MemberBinding b = this.VisitBinding(original[i]);
if (list != null)
{
list.Add(b);
}
else if (b != original[i])
{
list = new List<MemberBinding>(n);
for (int j = 0; j < i; j++)
{
list.Add(original[j]);
}
list.Add(b);
}
}
if (list != null)
{
return list;
}
return original;
}
/// <summary>
/// ElementInit expression list visit method
/// </summary>
/// <param name="original">The ElementInit expression list to visit</param>
/// <returns>The visited ElementInit expression list </returns>
internal virtual IEnumerable<ElementInit> VisitElementInitializerList(ReadOnlyCollection<ElementInit> original)
{
List<ElementInit> list = null;
for (int i = 0, n = original.Count; i < n; i++)
{
ElementInit init = this.VisitElementInitializer(original[i]);
if (list != null)
{
list.Add(init);
}
else if (init != original[i])
{
list = new List<ElementInit>(n);
for (int j = 0; j < i; j++)
{
list.Add(original[j]);
}
list.Add(init);
}
}
if (list != null)
{
return list;
}
return original;
}
/// <summary>
/// LambdaExpression visit method
/// </summary>
/// <param name="lambda">The LambdaExpression to visit</param>
/// <returns>The visited LambdaExpression</returns>
internal virtual Expression VisitLambda(LambdaExpression lambda)
{
Expression body = this.Visit(lambda.Body);
if (body != lambda.Body)
{
#if !ASTORIA_LIGHT
return Expression.Lambda(lambda.Type, body, lambda.Parameters);
#else
ParameterExpression[] parameters = new ParameterExpression[lambda.Parameters.Count];
lambda.Parameters.CopyTo(parameters, 0);
return ExpressionHelpers.CreateLambda(lambda.Type, body, parameters);
#endif
}
return lambda;
}
/// <summary>
/// NewExpression visit method
/// </summary>
/// <param name="nex">The NewExpression to visit</param>
/// <returns>The visited NewExpression</returns>
internal virtual NewExpression VisitNew(NewExpression nex)
{
IEnumerable<Expression> args = this.VisitExpressionList(nex.Arguments);
if (args != nex.Arguments)
{
return nex.Members != null
? Expression.New(nex.Constructor, args, nex.Members)
: Expression.New(nex.Constructor, args);
}
return nex;
}
/// <summary>
/// MemberInitExpression visit method
/// </summary>
/// <param name="init">The MemberInitExpression to visit</param>
/// <returns>The visited MemberInitExpression</returns>
internal virtual Expression VisitMemberInit(MemberInitExpression init)
{
NewExpression n = this.VisitNew(init.NewExpression);
IEnumerable<MemberBinding> bindings = this.VisitBindingList(init.Bindings);
return n != init.NewExpression || bindings != init.Bindings ? Expression.MemberInit(n, bindings) : init;
}
/// <summary>
/// ListInitExpression visit method
/// </summary>
/// <param name="init">The ListInitExpression to visit</param>
/// <returns>The visited ListInitExpression</returns>
internal virtual Expression VisitListInit(ListInitExpression init)
{
NewExpression n = this.VisitNew(init.NewExpression);
IEnumerable<ElementInit> initializers = this.VisitElementInitializerList(init.Initializers);
return n != init.NewExpression || initializers != init.Initializers ? Expression.ListInit(n, initializers) : init;
}
/// <summary>
/// NewArrayExpression visit method
/// </summary>
/// <param name="na">The NewArrayExpression to visit</param>
/// <returns>The visited NewArrayExpression</returns>
internal virtual Expression VisitNewArray(NewArrayExpression na)
{
IEnumerable<Expression> exprs = this.VisitExpressionList(na.Expressions);
if (exprs != na.Expressions)
{
return na.NodeType == ExpressionType.NewArrayInit ? Expression.NewArrayInit(na.Type.GetElementType(), exprs) : Expression.NewArrayBounds(na.Type.GetElementType(), exprs);
}
return na;
}
/// <summary>
/// InvocationExpression visit method
/// </summary>
/// <param name="iv">The InvocationExpression to visit</param>
/// <returns>The visited InvocationExpression</returns>
internal virtual Expression VisitInvocation(InvocationExpression iv)
{
IEnumerable<Expression> args = this.VisitExpressionList(iv.Arguments);
Expression expr = this.Visit(iv.Expression);
return args != iv.Arguments || expr != iv.Expression ? Expression.Invoke(expr, args) : iv;
}
}
}
| |
using System;
using System.Collections.Generic;
using BTDB.KVDBLayer;
using BTDB.ODBLayer;
using Xunit;
namespace BTDBTest
{
public class ObjectDbTableUpgradeTest : IDisposable
{
readonly IKeyValueDB _lowDb;
IObjectDB _db;
public ObjectDbTableUpgradeTest()
{
_lowDb = new InMemoryKeyValueDB();
OpenDb();
}
public void Dispose()
{
_db.Dispose();
_lowDb.Dispose();
}
void ReopenDb()
{
_db.Dispose();
OpenDb();
}
void OpenDb()
{
_db = new ObjectDB();
_db.Open(_lowDb, false, new DBOptions().WithoutAutoRegistration());
}
public class JobV1
{
[PrimaryKey(1)] public ulong Id { get; set; }
public string Name { get; set; }
}
public interface IJobTable1 : IRelation<JobV1>
{
void Insert(JobV1 job);
}
public class JobV2
{
[PrimaryKey(1)] public ulong Id { get; set; }
[SecondaryKey("Name")] public string Name { get; set; }
[SecondaryKey("Cost", IncludePrimaryKeyOrder = 1)]
public uint Cost { get; set; }
}
public interface IJobTable2 : IRelation<JobV2>
{
void Insert(JobV2 job);
JobV2 FindByNameOrDefault(string name);
JobV2 FindByCostOrDefault(ulong id, uint cost);
IEnumerator<JobV2> ListByCost(AdvancedEnumeratorParam<uint> param);
}
public class JobIncompatible
{
[PrimaryKey(1)] public Guid Id { get; set; }
}
public interface IJobTableIncompatible : IRelation<JobIncompatible>
{
void Insert(JobIncompatible job);
}
[Fact]
public void ChangeOfPrimaryKeyIsNotSupported()
{
using (var tr = _db.StartTransaction())
{
var creator = tr.InitRelation<IJobTable1>("Job");
var jobTable = creator(tr);
var job = new JobV1 {Id = 11, Name = "Code"};
jobTable.Insert(job);
tr.Commit();
}
ReopenDb();
using (var tr = _db.StartTransaction())
{
Assert.Throws<BTDBException>(() => tr.InitRelation<IJobTableIncompatible>("Job"));
}
}
[Fact]
public void NewIndexesAreAutomaticallyGenerated()
{
using (var tr = _db.StartTransaction())
{
var creator = tr.InitRelation<IJobTable1>("Job");
var jobTable = creator(tr);
var job = new JobV1 {Id = 11, Name = "Code"};
jobTable.Insert(job);
tr.Commit();
}
ReopenDb();
using (var tr = _db.StartTransaction())
{
var creator = tr.InitRelation<IJobTable2>("Job");
var jobTable = creator(tr);
var job = new JobV2 {Id = 21, Name = "Build", Cost = 42};
jobTable.Insert(job);
var j = jobTable.FindByNameOrDefault("Code");
Assert.Equal("Code", j.Name);
j = jobTable.FindByCostOrDefault(21, 42);
Assert.Equal("Build", j.Name);
var en = jobTable.ListByCost(new AdvancedEnumeratorParam<uint>(EnumerationOrder.Ascending));
Assert.True(en.MoveNext());
Assert.Equal(0u, en.Current.Cost);
Assert.True(en.MoveNext());
Assert.Equal(42u, en.Current.Cost);
tr.Commit();
}
}
public class Car
{
[PrimaryKey(1)] public ulong CompanyId { get; set; }
[PrimaryKey(2)] public ulong Id { get; set; }
public string Name { get; set; }
}
public interface ICarTableApart : IRelation<Car>
{
ulong CompanyId { get; set; }
void Insert(Car car);
Car FindById(ulong id);
}
public interface ICarTable : IRelation<Car>
{
void Insert(Car car);
Car FindById(ulong companyId, ulong id);
}
[Fact]
public void ApartFieldCanBeRemoved()
{
using (var tr = _db.StartTransaction())
{
var creator = tr.InitRelation<ICarTableApart>("Car");
var carTable = creator(tr);
carTable.CompanyId = 10;
var car = new Car {Id = 11, Name = "Ferrari"};
carTable.Insert(car);
tr.Commit();
}
ReopenDb();
using (var tr = _db.StartTransaction())
{
var creator = tr.InitRelation<ICarTable>("Car");
var carTable = creator(tr);
Assert.Equal("Ferrari", carTable.FindById(10, 11).Name);
}
}
[Fact]
public void ApartFieldCanBeAdded()
{
using (var tr = _db.StartTransaction())
{
var creator = tr.InitRelation<ICarTable>("Car");
var carTable = creator(tr);
var car = new Car {CompanyId = 10, Id = 11, Name = "Ferrari"};
carTable.Insert(car);
tr.Commit();
}
ReopenDb();
using (var tr = _db.StartTransaction())
{
var creator = tr.InitRelation<ICarTableApart>("Car");
var carTable = creator(tr);
carTable.CompanyId = 10;
Assert.Equal("Ferrari", carTable.FindById(11).Name);
}
}
public enum SimpleEnum
{
One = 1,
Two = 2
}
public enum SimpleEnumV2
{
Eins = 1,
Zwei = 2,
Drei = 3
}
public enum SimpleEnumV3
{
Two = 2,
Three = 3,
Four = 4
}
public class ItemWithEnumInKey
{
[PrimaryKey] public SimpleEnum Key { get; set; }
public string Value { get; set; }
}
public class ItemWithEnumInKeyV2
{
[PrimaryKey] public SimpleEnumV2 Key { get; set; }
public string Value { get; set; }
}
public class ItemWithEnumInKeyV3
{
[PrimaryKey] public SimpleEnumV3 Key { get; set; }
public string Value { get; set; }
}
public interface ITableWithEnumInKey : IRelation<ItemWithEnumInKey>
{
void Insert(ItemWithEnumInKey person);
}
public interface ITableWithEnumInKeyV2 : IRelation<ItemWithEnumInKeyV2>
{
ItemWithEnumInKeyV2 FindById(SimpleEnumV2 key);
}
public interface ITableWithEnumInKeyV3 : IRelation<ItemWithEnumInKeyV3>
{
}
[Fact]
public void UpgradePrimaryKeyWithEnumWorks()
{
using (var tr = _db.StartTransaction())
{
var creator = tr.InitRelation<ITableWithEnumInKey>("EnumWithItemInKey");
var table = creator(tr);
table.Insert(new ItemWithEnumInKey {Key = SimpleEnum.One, Value = "A"});
table.Insert(new ItemWithEnumInKey {Key = SimpleEnum.Two, Value = "B"});
tr.Commit();
}
ReopenDb();
using (var tr = _db.StartTransaction())
{
var creator = tr.InitRelation<ITableWithEnumInKeyV2>("EnumWithItemInKey");
var table = creator(tr);
Assert.Equal("A", table.FindById(SimpleEnumV2.Eins).Value);
Assert.False(table.Upsert(new ItemWithEnumInKeyV2 {Key = SimpleEnumV2.Zwei, Value = "B2"}));
Assert.True(table.Upsert(new ItemWithEnumInKeyV2 {Key = SimpleEnumV2.Drei, Value = "C"}));
Assert.Equal(3, table.Count);
}
}
[Fact]
public void UpgradePrimaryKeyWithIncompatibleEnumNotWork()
{
using (var tr = _db.StartTransaction())
{
var creator = tr.InitRelation<ITableWithEnumInKey>("EnumWithItemInKeyIncompatible");
var table = creator(tr);
table.Insert(new ItemWithEnumInKey {Key = SimpleEnum.One, Value = "A"});
tr.Commit();
}
ReopenDb();
using (var tr = _db.StartTransaction())
{
var ex = Assert.Throws<BTDBException>(() =>
tr.InitRelation<ITableWithEnumInKeyV3>("EnumWithItemInKeyIncompatible"));
Assert.Contains("Field 'Key'", ex.Message);
}
}
public class JobV21
{
[PrimaryKey(1)] public ulong Id { get; set; }
[SecondaryKey("Name", Order = 2)] public string Name { get; set; }
[SecondaryKey("Name", Order = 1)]
[SecondaryKey("Cost", IncludePrimaryKeyOrder = 1)]
public uint Cost { get; set; }
}
public interface IJobTable21 : IRelation<JobV21>
{
void Insert(JobV21 job);
JobV21 FindByNameOrDefault(uint cost, string name);
}
[Fact]
public void ModifiedIndexesAreRecalculated()
{
using (var tr = _db.StartTransaction())
{
var creator = tr.InitRelation<IJobTable2>("Job");
var jobTable = creator(tr);
var job = new JobV2 {Id = 11, Name = "Code", Cost = 1000};
jobTable.Insert(job);
tr.Commit();
}
ReopenDb();
using (var tr = _db.StartTransaction())
{
var creator = tr.InitRelation<IJobTable21>("Job");
var jobTable = creator(tr);
var j = jobTable.FindByNameOrDefault(1000, "Code");
Assert.NotNull(j);
Assert.Equal("Code", j.Name);
tr.Commit();
}
}
public class JobV3
{
public JobV3()
{
Status = 100;
}
[PrimaryKey(1)] public ulong Id { get; set; }
[SecondaryKey("Status")] public int Status { get; set; }
}
public interface IJobTable3 : IRelation<JobV3>
{
void Insert(JobV3 job);
void RemoveById(ulong id);
}
[Fact]
public void AddedFieldIsInsertedFromDefaultObject()
{
using (var tr = _db.StartTransaction())
{
var creator = tr.InitRelation<IJobTable2>("Job");
var jobTable = creator(tr);
var job = new JobV2 {Id = 11, Name = "Code"};
jobTable.Insert(job);
tr.Commit();
}
ReopenDb();
using (var tr = _db.StartTransaction())
{
var creator = tr.InitRelation<IJobTable3>("Job");
var jobTable = creator(tr);
jobTable.RemoveById(11);
Assert.Equal(0, jobTable.Count);
}
}
public class JobV31
{
public JobV31()
{
Status = 100;
}
[PrimaryKey(1)] public ulong Id { get; set; }
[SecondaryKey("Status")]
[SecondaryKey("ExpiredStatus", Order = 2)]
public int Status { get; set; }
[SecondaryKey("ExpiredStatus", Order = 1)]
public bool IsExpired { get; set; }
}
public interface IJobTable31 : IRelation<JobV31>
{
void Insert(JobV31 job);
void RemoveById(ulong id);
JobV31 FindByExpiredStatusOrDefault(bool isExpired, int status);
}
[Fact]
public void NewIndexesOnNewFieldAreDeletedWhenItemWasDeleted()
{
using (var tr = _db.StartTransaction())
{
var creator = tr.InitRelation<IJobTable3>("Job");
var jobTable = creator(tr);
var job1 = new JobV3 {Id = 11, Status = 300};
jobTable.Insert(job1);
var job2 = new JobV3 {Id = 12, Status = 200};
jobTable.Insert(job2);
tr.Commit();
}
ReopenDb();
using (var tr = _db.StartTransaction())
{
var creator = tr.InitRelation<IJobTable31>("Job");
var jobTable = creator(tr);
jobTable.RemoveById(11);
Assert.Equal(1, jobTable.Count);
Assert.Null(jobTable.FindByExpiredStatusOrDefault(false, 300));
var item = jobTable.FindByExpiredStatusOrDefault(false, 200);
Assert.Equal(12ul, item.Id);
tr.Commit();
}
}
}
}
| |
namespace Microsoft.PythonTools.Project {
partial class DefaultPythonLauncherOptions {
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing) {
if (disposing && (components != null)) {
components.Dispose();
}
base.Dispose(disposing);
}
#region 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() {
this.components = new System.ComponentModel.Container();
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(DefaultPythonLauncherOptions));
this._runGroup = new System.Windows.Forms.GroupBox();
this.tableLayoutPanel2 = new System.Windows.Forms.TableLayoutPanel();
this._envVars = new System.Windows.Forms.TextBox();
this._envVarsLabel = new System.Windows.Forms.Label();
this._searchPathLabel = new System.Windows.Forms.Label();
this._searchPaths = new System.Windows.Forms.TextBox();
this._argumentsLabel = new System.Windows.Forms.Label();
this._arguments = new System.Windows.Forms.TextBox();
this._interpArgsLabel = new System.Windows.Forms.Label();
this._interpArgs = new System.Windows.Forms.TextBox();
this._interpreterPath = new System.Windows.Forms.TextBox();
this._interpreterPathLabel = new System.Windows.Forms.Label();
this._toolTip = new System.Windows.Forms.ToolTip(this.components);
this.tableLayoutPanel1 = new System.Windows.Forms.TableLayoutPanel();
this._debugGroup = new System.Windows.Forms.GroupBox();
this.tableLayoutPanel3 = new System.Windows.Forms.TableLayoutPanel();
this._mixedMode = new System.Windows.Forms.CheckBox();
this._runGroup.SuspendLayout();
this.tableLayoutPanel2.SuspendLayout();
this.tableLayoutPanel1.SuspendLayout();
this._debugGroup.SuspendLayout();
this.tableLayoutPanel3.SuspendLayout();
this.SuspendLayout();
//
// _runGroup
//
resources.ApplyResources(this._runGroup, "_runGroup");
this._runGroup.Controls.Add(this.tableLayoutPanel2);
this._runGroup.Name = "_runGroup";
this._runGroup.TabStop = false;
//
// tableLayoutPanel2
//
resources.ApplyResources(this.tableLayoutPanel2, "tableLayoutPanel2");
this.tableLayoutPanel2.Controls.Add(this._envVars, 1, 4);
this.tableLayoutPanel2.Controls.Add(this._envVarsLabel, 0, 4);
this.tableLayoutPanel2.Controls.Add(this._searchPathLabel, 0, 0);
this.tableLayoutPanel2.Controls.Add(this._searchPaths, 1, 0);
this.tableLayoutPanel2.Controls.Add(this._argumentsLabel, 0, 1);
this.tableLayoutPanel2.Controls.Add(this._arguments, 1, 1);
this.tableLayoutPanel2.Controls.Add(this._interpArgs, 1, 3);
this.tableLayoutPanel2.Controls.Add(this._interpreterPath, 1, 2);
this.tableLayoutPanel2.Controls.Add(this._interpreterPathLabel, 0, 2);
this.tableLayoutPanel2.Controls.Add(this._interpArgsLabel, 0, 3);
this.tableLayoutPanel2.Name = "tableLayoutPanel2";
//
// _envVars
//
this._envVars.AcceptsReturn = true;
resources.ApplyResources(this._envVars, "_envVars");
this._envVars.Name = "_envVars";
this._toolTip.SetToolTip(this._envVars, resources.GetString("_envVars.ToolTip"));
this._envVars.TextChanged += new System.EventHandler(this._envVars_TextChanged);
//
// _envVarsLabel
//
resources.ApplyResources(this._envVarsLabel, "_envVarsLabel");
this._envVarsLabel.Name = "_envVarsLabel";
this._toolTip.SetToolTip(this._envVarsLabel, resources.GetString("_envVarsLabel.ToolTip"));
//
// _searchPathLabel
//
resources.ApplyResources(this._searchPathLabel, "_searchPathLabel");
this._searchPathLabel.Name = "_searchPathLabel";
this._toolTip.SetToolTip(this._searchPathLabel, resources.GetString("_searchPathLabel.ToolTip"));
//
// _searchPaths
//
resources.ApplyResources(this._searchPaths, "_searchPaths");
this._searchPaths.Name = "_searchPaths";
this._toolTip.SetToolTip(this._searchPaths, resources.GetString("_searchPaths.ToolTip"));
this._searchPaths.TextChanged += new System.EventHandler(this.SearchPathsTextChanged);
//
// _argumentsLabel
//
resources.ApplyResources(this._argumentsLabel, "_argumentsLabel");
this._argumentsLabel.Name = "_argumentsLabel";
this._toolTip.SetToolTip(this._argumentsLabel, resources.GetString("_argumentsLabel.ToolTip"));
//
// _arguments
//
resources.ApplyResources(this._arguments, "_arguments");
this._arguments.Name = "_arguments";
this._toolTip.SetToolTip(this._arguments, resources.GetString("_arguments.ToolTip"));
this._arguments.TextChanged += new System.EventHandler(this.ArgumentsTextChanged);
//
// _interpArgsLabel
//
resources.ApplyResources(this._interpArgsLabel, "_interpArgsLabel");
this._interpArgsLabel.Name = "_interpArgsLabel";
this._toolTip.SetToolTip(this._interpArgsLabel, resources.GetString("_interpArgsLabel.ToolTip"));
//
// _interpArgs
//
resources.ApplyResources(this._interpArgs, "_interpArgs");
this._interpArgs.Name = "_interpArgs";
this._toolTip.SetToolTip(this._interpArgs, resources.GetString("_interpArgs.ToolTip"));
this._interpArgs.TextChanged += new System.EventHandler(this.InterpreterArgumentsTextChanged);
//
// _interpreterPath
//
resources.ApplyResources(this._interpreterPath, "_interpreterPath");
this._interpreterPath.Name = "_interpreterPath";
this._toolTip.SetToolTip(this._interpreterPath, resources.GetString("_interpreterPath.ToolTip"));
this._interpreterPath.TextChanged += new System.EventHandler(this.InterpreterPathTextChanged);
//
// _interpreterPathLabel
//
resources.ApplyResources(this._interpreterPathLabel, "_interpreterPathLabel");
this._interpreterPathLabel.Name = "_interpreterPathLabel";
this._toolTip.SetToolTip(this._interpreterPathLabel, resources.GetString("_interpreterPathLabel.ToolTip"));
//
// tableLayoutPanel1
//
resources.ApplyResources(this.tableLayoutPanel1, "tableLayoutPanel1");
this.tableLayoutPanel1.Controls.Add(this._debugGroup, 0, 1);
this.tableLayoutPanel1.Controls.Add(this._runGroup, 0, 0);
this.tableLayoutPanel1.Name = "tableLayoutPanel1";
//
// _debugGroup
//
resources.ApplyResources(this._debugGroup, "_debugGroup");
this._debugGroup.Controls.Add(this.tableLayoutPanel3);
this._debugGroup.Name = "_debugGroup";
this._debugGroup.TabStop = false;
//
// tableLayoutPanel3
//
resources.ApplyResources(this.tableLayoutPanel3, "tableLayoutPanel3");
this.tableLayoutPanel3.Controls.Add(this._mixedMode, 0, 0);
this.tableLayoutPanel3.Name = "tableLayoutPanel3";
//
// _mixedMode
//
resources.ApplyResources(this._mixedMode, "_mixedMode");
this.tableLayoutPanel3.SetColumnSpan(this._mixedMode, 2);
this._mixedMode.Name = "_mixedMode";
this._mixedMode.UseVisualStyleBackColor = true;
this._mixedMode.CheckedChanged += new System.EventHandler(this._mixedMode_CheckedChanged);
//
// DefaultPythonLauncherOptions
//
resources.ApplyResources(this, "$this");
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.Controls.Add(this.tableLayoutPanel1);
this.Name = "DefaultPythonLauncherOptions";
this._runGroup.ResumeLayout(false);
this._runGroup.PerformLayout();
this.tableLayoutPanel2.ResumeLayout(false);
this.tableLayoutPanel2.PerformLayout();
this.tableLayoutPanel1.ResumeLayout(false);
this.tableLayoutPanel1.PerformLayout();
this._debugGroup.ResumeLayout(false);
this._debugGroup.PerformLayout();
this.tableLayoutPanel3.ResumeLayout(false);
this.tableLayoutPanel3.PerformLayout();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.GroupBox _runGroup;
private System.Windows.Forms.TextBox _arguments;
private System.Windows.Forms.Label _argumentsLabel;
private System.Windows.Forms.TextBox _searchPaths;
private System.Windows.Forms.Label _searchPathLabel;
private System.Windows.Forms.Label _interpArgsLabel;
private System.Windows.Forms.TextBox _interpArgs;
private System.Windows.Forms.TextBox _interpreterPath;
private System.Windows.Forms.Label _interpreterPathLabel;
private System.Windows.Forms.ToolTip _toolTip;
private System.Windows.Forms.TableLayoutPanel tableLayoutPanel2;
private System.Windows.Forms.TableLayoutPanel tableLayoutPanel1;
private System.Windows.Forms.GroupBox _debugGroup;
private System.Windows.Forms.TableLayoutPanel tableLayoutPanel3;
private System.Windows.Forms.CheckBox _mixedMode;
private System.Windows.Forms.TextBox _envVars;
private System.Windows.Forms.Label _envVarsLabel;
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/*============================================================
**
**
**
** Purpose: Platform independent integer
**
**
===========================================================*/
using System.Globalization;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security;
namespace System
{
// CONTRACT with Runtime
// The IntPtr type is one of the primitives understood by the compilers and runtime
// Data Contract: Single field of type void *
public struct IntPtr : IEquatable<IntPtr>
{
// WARNING: We allow diagnostic tools to directly inspect this member (_value).
// See https://github.com/dotnet/corert/blob/master/Documentation/design-docs/diagnostics/diagnostics-tools-contract.md for more details.
// Please do not change the type, the name, or the semantic usage of this member without understanding the implication for tools.
// Get in touch with the diagnostics team if you have questions.
unsafe private void* _value; // The compiler treats void* closest to uint hence explicit casts are required to preserve int behavior
[Intrinsic]
public static readonly IntPtr Zero;
[Intrinsic]
[NonVersionable]
public unsafe IntPtr(int value)
{
#if BIT64
_value = (void*)(long)value;
#else
_value = (void*)value;
#endif
}
[Intrinsic]
[NonVersionable]
public unsafe IntPtr(long value)
{
#if BIT64
_value = (void*)value;
#else
_value = (void*)checked((int)value);
#endif
}
[CLSCompliant(false)]
[Intrinsic]
[NonVersionable]
public unsafe IntPtr(void* value)
{
_value = value;
}
[CLSCompliant(false)]
[Intrinsic]
[NonVersionable]
public unsafe void* ToPointer()
{
return _value;
}
[Intrinsic]
[NonVersionable]
public unsafe int ToInt32()
{
#if BIT64
long l = (long)_value;
return checked((int)l);
#else
return (int)_value;
#endif
}
[Intrinsic]
[NonVersionable]
public unsafe long ToInt64()
{
#if BIT64
return (long)_value;
#else
return (long)(int)_value;
#endif
}
[Intrinsic]
[NonVersionable]
public unsafe static explicit operator IntPtr(int value)
{
return new IntPtr(value);
}
[Intrinsic]
[NonVersionable]
public unsafe static explicit operator IntPtr(long value)
{
return new IntPtr(value);
}
[CLSCompliant(false)]
[Intrinsic]
[NonVersionable]
public unsafe static explicit operator IntPtr(void* value)
{
return new IntPtr(value);
}
[CLSCompliant(false)]
[Intrinsic]
[NonVersionable]
public unsafe static explicit operator void* (IntPtr value)
{
return value._value;
}
[Intrinsic]
[NonVersionable]
public unsafe static explicit operator int (IntPtr value)
{
#if BIT64
long l = (long)value._value;
return checked((int)l);
#else
return (int)value._value;
#endif
}
[Intrinsic]
[NonVersionable]
public unsafe static explicit operator long (IntPtr value)
{
#if BIT64
return (long)value._value;
#else
return (long)(int)value._value;
#endif
}
unsafe bool IEquatable<IntPtr>.Equals(IntPtr value)
{
return _value == value._value;
}
[Intrinsic]
[NonVersionable]
public unsafe static bool operator ==(IntPtr value1, IntPtr value2)
{
return value1._value == value2._value;
}
[Intrinsic]
[NonVersionable]
public unsafe static bool operator !=(IntPtr value1, IntPtr value2)
{
return value1._value != value2._value;
}
internal unsafe bool IsNull()
{
return (_value == null);
}
[NonVersionable]
public static IntPtr Add(IntPtr pointer, int offset)
{
return pointer + offset;
}
[Intrinsic]
[NonVersionable]
public unsafe static IntPtr operator +(IntPtr pointer, int offset)
{
#if BIT64
return new IntPtr((long)pointer._value + offset);
#else
return new IntPtr((int)pointer._value + offset);
#endif
}
[NonVersionable]
public static IntPtr Subtract(IntPtr pointer, int offset)
{
return pointer - offset;
}
[Intrinsic]
[NonVersionable]
public unsafe static IntPtr operator -(IntPtr pointer, int offset)
{
#if BIT64
return new IntPtr((long)pointer._value - offset);
#else
return new IntPtr((int)pointer._value - offset);
#endif
}
public unsafe static int Size
{
[Intrinsic]
[NonVersionable]
get
{
#if BIT64
return 8;
#else
return 4;
#endif
}
}
public unsafe override String ToString()
{
#if BIT64
return ((long)_value).ToString(FormatProvider.InvariantCulture);
#else
return ((int)_value).ToString(FormatProvider.InvariantCulture);
#endif
}
public unsafe String ToString(String format)
{
#if BIT64
return ((long)_value).ToString(format, FormatProvider.InvariantCulture);
#else
return ((int)_value).ToString(format, FormatProvider.InvariantCulture);
#endif
}
public unsafe override bool Equals(Object obj)
{
if (obj is IntPtr)
{
return (_value == ((IntPtr)obj)._value);
}
return false;
}
public unsafe override int GetHashCode()
{
#if BIT64
long l = (long)_value;
return (unchecked((int)l) ^ (int)(l >> 32));
#else
return unchecked((int)_value);
#endif
}
}
}
| |
// Copyright (c) DotSpatial Team. All rights reserved.
// Licensed under the MIT license. See License.txt file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Windows.Forms;
namespace DotSpatial.Symbology.Forms
{
/// <summary>
/// LabelAlignmentControl
/// </summary>
[ToolboxItem(false)]
[DefaultEvent("ValueChanged")]
[DefaultProperty("Value")]
public class LabelAlignmentPicker : Control
{
#region Fields
private readonly Dictionary<ContentAlignment, LabelAlignmentButton> _buttons;
private readonly Timer _exitTimer;
private ContentAlignment _highlight;
private bool _timerIsActive;
#endregion
#region Constructors
/// <summary>
/// Initializes a new instance of the <see cref="LabelAlignmentPicker"/> class.
/// </summary>
public LabelAlignmentPicker()
{
Value = ContentAlignment.MiddleCenter;
Padding = 5;
_buttons = new Dictionary<ContentAlignment, LabelAlignmentButton>();
_exitTimer = new Timer
{
Interval = 100
};
_exitTimer.Tick += ExitTimerTick;
}
#endregion
#region Events
/// <summary>
/// Occurs when the value has changed
/// </summary>
public event EventHandler ValueChanged;
#endregion
#region Properties
/// <summary>
/// Gets or sets an integer value representing how much to separate the
/// interior region of the buttons.
/// </summary>
public new int Padding { get; set; }
/// <summary>
/// Gets or sets the content alignment for this control.
/// </summary>
public ContentAlignment Value { get; set; }
#endregion
#region Methods
/// <summary>
/// Handles the actual drawing for this control.
/// </summary>
/// <param name="g">The graphics object used for drawing.</param>
/// <param name="clipRectangle">The clip rectangle.</param>
protected virtual void OnDraw(Graphics g, Rectangle clipRectangle)
{
foreach (KeyValuePair<ContentAlignment, LabelAlignmentButton> pair in _buttons)
{
pair.Value.Draw(g);
}
}
/// <summary>
/// Handles mouse movements that highlight internal buttons
/// </summary>
/// <param name="e">The event args.</param>
protected override void OnMouseMove(MouseEventArgs e)
{
if (!_timerIsActive)
{
_timerIsActive = true;
_exitTimer.Start();
}
LabelAlignmentButton button;
if (_buttons.TryGetValue(_highlight, out button))
{
if (button.Bounds.Contains(e.Location)) return;
}
foreach (KeyValuePair<ContentAlignment, LabelAlignmentButton> pair in _buttons)
{
if (pair.Value.Bounds.Contains(e.Location))
{
pair.Value.Highlighted = true;
_highlight = pair.Key;
}
else
{
pair.Value.Highlighted = false;
}
}
Invalidate();
base.OnMouseMove(e);
}
/// <summary>
/// A mouse up event will alter the button that is currently selected.
/// </summary>
/// <param name="e">The event args.</param>
protected override void OnMouseUp(MouseEventArgs e)
{
LabelAlignmentButton button;
if (_buttons.TryGetValue(Value, out button))
{
if (button.Bounds.Contains(e.Location)) return;
}
foreach (KeyValuePair<ContentAlignment, LabelAlignmentButton> pair in _buttons)
{
if (pair.Value.Bounds.Contains(e.Location))
{
Value = pair.Key;
pair.Value.Selected = true;
OnValueChanged(pair.Value);
}
else
{
pair.Value.Selected = false;
}
}
base.OnMouseUp(e);
Invalidate();
}
/// <summary>
/// Custom drawing
/// </summary>
/// <param name="e">The event args.</param>
protected override void OnPaint(PaintEventArgs e)
{
Rectangle clip = e.ClipRectangle;
if (clip.IsEmpty) clip = ClientRectangle;
Bitmap bmp = new Bitmap(clip.Width, clip.Height);
Graphics g = Graphics.FromImage(bmp);
g.TranslateTransform(-clip.X, -clip.Y);
g.Clip = new Region(clip);
g.Clear(BackColor);
g.SmoothingMode = SmoothingMode.AntiAlias;
OnDraw(g, clip);
g.Dispose();
e.Graphics.DrawImage(bmp, clip, new Rectangle(0, 0, clip.Width, clip.Height), GraphicsUnit.Pixel);
}
/// <summary>
/// Prevent flicker.
/// </summary>
/// <param name="e">The event args.</param>
protected override void OnPaintBackground(PaintEventArgs e)
{
}
/// <summary>
/// Occurs when this is resized.
/// </summary>
/// <param name="e">The event args.</param>
protected override void OnResize(EventArgs e)
{
ResizeButtons();
base.OnResize(e);
Invalidate();
}
/// <summary>
/// Fires the Value Changed event.
/// </summary>
/// <param name="sender">The sender that raised the event.</param>
protected virtual void OnValueChanged(LabelAlignmentButton sender)
{
ValueChanged?.Invoke(sender, EventArgs.Empty);
}
private void ExitTimerTick(object sender, EventArgs e)
{
// as long as the mouse is over this control, keep ticking.
if (ClientRectangle.Contains(PointToClient(MousePosition))) return;
LabelAlignmentButton button;
if (_buttons.TryGetValue(_highlight, out button))
{
button.Highlighted = false;
}
_highlight = Value;
_exitTimer.Stop();
_timerIsActive = false;
Invalidate();
}
private void ResizeButtons()
{
_buttons.Clear();
int w = (Width > Padding * 2) ? (Width - (Padding * 2)) / 3 : Width / 3;
int h = (Height > Padding * 2) ? (Height - (Padding * 2)) / 3 : Height / 3;
int wp = w + Padding;
int hp = h + Padding;
_buttons.Add(ContentAlignment.TopLeft, new LabelAlignmentButton(new Rectangle(0, 0, w, h), BackColor));
_buttons.Add(ContentAlignment.TopCenter, new LabelAlignmentButton(new Rectangle(wp, 0, w, h), BackColor));
_buttons.Add(ContentAlignment.TopRight, new LabelAlignmentButton(new Rectangle(wp * 2, 0, w, h), BackColor));
_buttons.Add(ContentAlignment.MiddleLeft, new LabelAlignmentButton(new Rectangle(0, hp, w, h), BackColor));
_buttons.Add(ContentAlignment.MiddleCenter, new LabelAlignmentButton(new Rectangle(wp, hp, w, h), BackColor));
_buttons.Add(ContentAlignment.MiddleRight, new LabelAlignmentButton(new Rectangle(wp * 2, hp, w, h), BackColor));
_buttons.Add(ContentAlignment.BottomLeft, new LabelAlignmentButton(new Rectangle(0, hp * 2, w, h), BackColor));
_buttons.Add(ContentAlignment.BottomCenter, new LabelAlignmentButton(new Rectangle(wp, hp * 2, w, h), BackColor));
_buttons.Add(ContentAlignment.BottomRight, new LabelAlignmentButton(new Rectangle(wp * 2, hp * 2, w, h), BackColor));
LabelAlignmentButton button;
if (_buttons.TryGetValue(Value, out button))
{
button.Selected = true;
}
if (_buttons.TryGetValue(_highlight, out button))
{
button.Highlighted = true;
}
}
#endregion
}
}
| |
//------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//------------------------------------------------------------------------------
namespace Microsoft.Tools.ServiceModel.WsatConfig
{
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Security;
using System.Security.Cryptography.X509Certificates;
using System.Windows.Forms;
using System.Globalization;
using System.Security.Permissions;
using System.Security.Principal;
public partial class WsatControl : UserControl
{
bool changed = false;
string machineName;
string virtualServer;
IntPtr propPage = IntPtr.Zero;
IntPtr propSheetDialog = IntPtr.Zero;
WsatPropertySheet propertySheetPage;
WsatConfiguration previousConfig, config;
MsdtcWrapper msdtc;
bool oldNetworkSupportEnabledValue = false;
[SecurityCritical]
public WsatControl(IntPtr propPageParam, IntPtr propSheetDialogParam, WsatPropertySheet propertySheetPage)
{
if (propertySheetPage == null)
{
throw new ArgumentNullException("propSheetPage");
}
// The order of the following calls is important!
InitializeComponent();
this.propPage = propPageParam;
this.propSheetDialog = propSheetDialogParam;
this.propertySheetPage = propertySheetPage;
this.machineName = this.propertySheetPage.MachineName;
this.virtualServer = this.propertySheetPage.VirtualServer;
InitializeConfig();
if (config != null)
{
this.oldNetworkSupportEnabledValue = this.config.TransactionBridgeEnabled || this.config.TransactionBridge30Enabled;
propertySheetPage.ShowPropertyPage += new ShowWindowEventHander(OnShowContainerPropertyPage);
propertySheetPage.BeforeApplyChanges += new BeforeApplyChangesEventHandler(OnBeforeApplyChanges);
propertySheetPage.ApplyChanges += new ApplyChangesEventHandler(OnApplyChanges);
}
Application.EnableVisualStyles();
}
[SecurityCritical]
void InitializeConfig()
{
try
{
previousConfig = new WsatConfiguration(machineName, virtualServer, null, false);
previousConfig.LoadFromRegistry();
config = new WsatConfiguration(machineName, virtualServer, previousConfig, false);
msdtc = config.GetMsdtcWrapper();
ConfigurationToUI();
}
catch (WsatAdminException e)
{
HandleException(e);
}
}
void CheckNetworkDtcAccessStatus()
{
Utilities.Log("CheckNetworkDtcAccessStatus");
bool networkTransactionEnabled;
try
{
networkTransactionEnabled = msdtc.GetNetworkTransactionAccess();
}
catch (WsatAdminException e)
{
HandleException(e);
networkTransactionEnabled = oldNetworkSupportEnabledValue;
}
if (!networkTransactionEnabled)
{
// If Msdtc network access is disabled, we'll disable the NetworkSupport checkbox anyway
Utilities.Log("CheckNetworkDtcAccessStatus: msdtc.GetNetworkTransactionAccess = false");
this.checkBoxEnableNetworkSupport.Checked = false;
this.checkBoxEnableNetworkSupport.Enabled = false;
}
else
{
// Otherwise, we can't simply check it - we should use the original state saved before
// navigating away from the tab
Utilities.Log("CheckNetworkDtcAccessStatus: msdtc.GetNetworkTransactionAccess = true");
this.checkBoxEnableNetworkSupport.Enabled = true;
this.checkBoxEnableNetworkSupport.Checked = this.oldNetworkSupportEnabledValue;
}
}
internal bool OnBeforeApplyChanges()
{
try
{
if (changed && Enabled)
{
UIToConfiguration();
config.ValidateThrow();
}
return true;
}
catch (WsatAdminException e)
{
HandleException(e);
return false;
}
}
internal bool OnApplyChanges()
{
bool succeeded = true;
try
{
if (changed && Enabled)
{
DialogResult restart = MessageBox.Show(
SR.GetString(SR.PromptWhetherToRestartDTCMessage),
SR.GetString(SR.WSATUITitle),
MessageBoxButtons.YesNo,
MessageBoxIcon.Question,
MessageBoxDefaultButton.Button1,
(MessageBoxOptions)0);
config.Save(restart == DialogResult.Yes);
if (restart == DialogResult.Yes)
{
MessageBox.Show(SR.GetString(SR.PromptMSDTCRestartedMessage),
SR.GetString(SR.WSATUITitle),
MessageBoxButtons.OK,
MessageBoxIcon.Information,
MessageBoxDefaultButton.Button1,
(MessageBoxOptions)0);
}
succeeded = true;
changed = false;
}
}
catch (WsatAdminException e)
{
succeeded = false;
HandleException(e);
}
return succeeded;
}
static bool IsLocalAdmin()
{
WindowsPrincipal principal = new WindowsPrincipal(WindowsIdentity.GetCurrent());
return principal.IsInRole(WindowsBuiltInRole.Administrator);
}
internal void OnShowContainerPropertyPage(bool show)
{
if (show)
{
if (Utilities.IsLocalMachineName(machineName) && !IsLocalAdmin())
{
this.Enabled = false;
}
else
{
CheckNetworkDtcAccessStatus();
}
}
else
{
this.oldNetworkSupportEnabledValue = this.checkBoxEnableNetworkSupport.Checked;
}
}
string GetDisplayStringForCert(X509Certificate2 cert)
{
if (cert == null)
{
return SR.GetString(SR.WSATControlEndpointCertNotSelected);
}
string ret = cert.SubjectName.Name;
if (string.IsNullOrEmpty(ret))
{
ret = cert.Thumbprint;
}
return ret;
}
void ComponentChanged()
{
changed = true;
SafeNativeMethods.SendMessage(propSheetDialog, PSM.CHANGED, propPage, IntPtr.Zero);
}
void ConfigurationToUI()
{
this.checkBoxEnableNetworkSupport.Checked = this.config.TransactionBridgeEnabled || this.config.TransactionBridge30Enabled;
this.textBoxHttpsPort.Text = this.config.HttpsPort.ToString(CultureInfo.InvariantCulture);
this.textBoxEndpointCert.Text = GetDisplayStringForCert(config.X509Certificate);
this.textBoxDefaultTimeout.Text = this.config.DefaultTimeout.ToString(CultureInfo.InvariantCulture);
this.textBoxMaxTimeout.Text = this.config.MaxTimeout.ToString(CultureInfo.InvariantCulture);
checkBoxEnableNetworkSupport_CheckedChanged(null, null);
}
void UIToConfiguration()
{
ushort shortTemp = 0;
// Network Support
this.config.TransactionBridgeEnabled = this.checkBoxEnableNetworkSupport.Checked;
// Max Timeout
if (UInt16.TryParse(this.textBoxMaxTimeout.Text, out shortTemp))
{
this.config.MaxTimeout = shortTemp;
}
else
{
this.textBoxMaxTimeout.Focus();
throw new WsatAdminException(WsatAdminErrorCode.INVALID_MAXTIMEOUT_ARGUMENT,
SR.GetString(SR.ErrorMaximumTimeoutRange));
}
// The following perperties only matter when network support is enabled
if (this.config.TransactionBridgeEnabled)
{
// HTTPS port
if (UInt16.TryParse(this.textBoxHttpsPort.Text, out shortTemp))
{
this.config.HttpsPort = shortTemp;
}
else
{
this.textBoxHttpsPort.Focus();
throw new WsatAdminException(WsatAdminErrorCode.INVALID_HTTPS_PORT,
SR.GetString(SR.ErrorHttpsPortRange));
}
// Default Timeout
if (UInt16.TryParse(this.textBoxDefaultTimeout.Text, out shortTemp))
{
this.config.DefaultTimeout = shortTemp;
}
else
{
this.textBoxDefaultTimeout.Focus();
throw new WsatAdminException(WsatAdminErrorCode.INVALID_DEF_TIMEOUT,
SR.GetString(SR.ErrorDefaultTimeoutRange));
}
// The certs and Kerberos ACLs should have been validated and attached to configuration
// when users perform the corresponding selection steps
}
}
void checkBoxEnableNetworkSupport_CheckedChanged(object sender, EventArgs e)
{
if (checkBoxEnableNetworkSupport.Enabled)
{
try
{
QfeChecker.CheckQfe();
}
catch (WsatAdminException ex)
{
HandleException(ex);
}
}
groupBoxNetwork.Enabled = groupBoxTracing.Enabled = groupBoxTimeouts.Enabled = checkBoxEnableNetworkSupport.Checked;
ComponentChanged();
}
void textBoxHttpsPort_TextChanged(object sender, EventArgs e)
{
ComponentChanged();
}
void textBoxDefaultTimeout_TextChanged(object sender, EventArgs e)
{
ComponentChanged();
}
void textBoxMaxTimeout_TextChanged(object sender, EventArgs e)
{
ComponentChanged();
}
void buttonSelectEndpointCert_Click(object sender, EventArgs e)
{
try
{
SafeCertificateStore storeHandle = CertificateManager.GetCertificateStorePointer(machineName);
// do not display the Location column on the CryptUIDlgSelectCertificateFromStore
#pragma warning suppress 56523
SafeCertificateContext certContext = SafeNativeMethods.CryptUIDlgSelectCertificateFromStore(
storeHandle,
propPage,
SR.GetString(SR.SSLBindingTitle),
SR.GetString(SR.SSLBindingMessage),
SafeNativeMethods.CRYPTUI_SELECT_LOCATION_COLUMN,
0, IntPtr.Zero);
if (!certContext.IsInvalid)
{
config.X509Certificate = certContext.GetNewX509Certificate();
textBoxEndpointCert.Text = GetDisplayStringForCert(config.X509Certificate);
ComponentChanged();
}
certContext.Close();
storeHandle.Close();
}
catch (WsatAdminException ex)
{
HandleException(ex);
}
}
void buttonSelectAuthorizedAccounts_Click(object sender, EventArgs e)
{
// popup a new ACL window, providing the WSATSecurityModel
// and a handle for the parent window (this)
if (ACLWrapper.EditACLSecurity(new WsatSecurityModel(Utilities.LocalHostName, config), this.Handle))
{
ComponentChanged();
}
}
void buttonSelectAuthorizedCerts_Click(object sender, EventArgs e)
{
try
{
SafeCertificateStore storeHandle = CertificateManager.GetCertificateStorePointer(machineName);
SafeCertificateContext prev = new SafeCertificateContext();
SafeCertificateContext crt = new SafeCertificateContext();
X509Certificate2Collection certificateCollection = new X509Certificate2Collection();
do
{
#pragma warning suppress 56523
crt = SafeNativeMethods.CertFindCertificateInStore(
storeHandle,
SafeNativeMethods.X509_ASN_ENCODING,
0,
SafeNativeMethods.CERT_FIND_ANY,
IntPtr.Zero,
prev);
prev = crt;
if (!crt.IsInvalid)
{
certificateCollection.Add(crt.GetNewX509Certificate());
}
} while (!crt.IsInvalid);
storeHandle.Close();
prev.Close();
crt.Close();
AcceptedCertificatesForm dlg = new AcceptedCertificatesForm(certificateCollection, config.X509GlobalAcl);
DialogResult dialogResult = dlg.ShowDialog(this);
if (dialogResult == DialogResult.OK)
{
this.config.X509GlobalAcl = dlg.AllowedCertificates;
if (this.config.X509GlobalAcl.Length > 0)
{
Utilities.Log("selected allowed client cert [0]: " + this.config.X509GlobalAcl[0]);
}
ComponentChanged();
}
}
catch (WsatAdminException ex)
{
HandleException(ex);
}
}
void buttonTracingOptions_Click(object sender, EventArgs e)
{
TraceOptionsForm form = new TraceOptionsForm(this.config);
DialogResult result = form.ShowDialog();
if (result == DialogResult.OK)
{
ComponentChanged();
}
}
void HandleException(WsatAdminException ex)
{
if (ex.ErrorCode == WsatAdminErrorCode.REGISTRY_ACCESS
|| ex.ErrorCode == WsatAdminErrorCode.WRONG_WCF_INSTALLED
|| ex.ErrorCode == WsatAdminErrorCode.CANNOT_ENABLE_NETWORK_SUPPORT_WHEN_QFE_IS_NOT_INSTALLED)
{
MessageBox.Show(ex.Message, SR.GetString(SR.WSATUITitle),
MessageBoxButtons.OK,
MessageBoxIcon.Information,
MessageBoxDefaultButton.Button1,
(MessageBoxOptions)0);
if (this.Enabled)
{
this.Enabled = false;
}
}
else
{
MessageBox.Show(ex.Message, SR.GetString(SR.ErrorMessageBoxTitle),
MessageBoxButtons.OK,
MessageBoxIcon.Error,
MessageBoxDefaultButton.Button1,
(MessageBoxOptions)0);
}
}
}
}
| |
// ***********************************************************************
// Copyright (c) 2007 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;
#if NET_2_0
using System.Collections.Generic;
#endif
namespace NUnit.Framework.Constraints
{
/// <summary>
/// ConstraintBuilder maintains the stacks that are used in
/// processing a ConstraintExpression. An OperatorStack
/// is used to hold operators that are waiting for their
/// operands to be reognized. a ConstraintStack holds
/// input constraints as well as the results of each
/// operator applied.
/// </summary>
public class ConstraintBuilder
{
#region Nested Operator Stack Class
/// <summary>
/// OperatorStack is a type-safe stack for holding ConstraintOperators
/// </summary>
public class OperatorStack
{
#if NET_2_0
private Stack<ConstraintOperator> stack = new Stack<ConstraintOperator>();
#else
private Stack stack = new Stack();
#endif
/// <summary>
/// Initializes a new instance of the <see cref="T:OperatorStack"/> class.
/// </summary>
/// <param name="builder">The builder.</param>
public OperatorStack(ConstraintBuilder builder)
{
}
/// <summary>
/// Gets a value indicating whether this <see cref="T:OpStack"/> is empty.
/// </summary>
/// <value><c>true</c> if empty; otherwise, <c>false</c>.</value>
public bool Empty
{
get { return stack.Count == 0; }
}
/// <summary>
/// Gets the topmost operator without modifying the stack.
/// </summary>
/// <value>The top.</value>
public ConstraintOperator Top
{
get { return (ConstraintOperator)stack.Peek(); }
}
/// <summary>
/// Pushes the specified operator onto the stack.
/// </summary>
/// <param name="op">The op.</param>
public void Push(ConstraintOperator op)
{
stack.Push(op);
}
/// <summary>
/// Pops the topmost operator from the stack.
/// </summary>
/// <returns></returns>
public ConstraintOperator Pop()
{
return (ConstraintOperator)stack.Pop();
}
}
#endregion
#region Nested Constraint Stack Class
/// <summary>
/// ConstraintStack is a type-safe stack for holding Constraints
/// </summary>
public class ConstraintStack
{
#if NET_2_0
private Stack<Constraint> stack = new Stack<Constraint>();
#else
private Stack stack = new Stack();
#endif
private ConstraintBuilder builder;
/// <summary>
/// Initializes a new instance of the <see cref="T:ConstraintStack"/> class.
/// </summary>
/// <param name="builder">The builder.</param>
public ConstraintStack(ConstraintBuilder builder)
{
this.builder = builder;
}
/// <summary>
/// Gets a value indicating whether this <see cref="T:ConstraintStack"/> is empty.
/// </summary>
/// <value><c>true</c> if empty; otherwise, <c>false</c>.</value>
public bool Empty
{
get { return stack.Count == 0; }
}
/// <summary>
/// Gets the topmost constraint without modifying the stack.
/// </summary>
/// <value>The topmost constraint</value>
public Constraint Top
{
get { return (Constraint)stack.Peek(); }
}
/// <summary>
/// Pushes the specified constraint. As a side effect,
/// the constraint's builder field is set to the
/// ConstraintBuilder owning this stack.
/// </summary>
/// <param name="constraint">The constraint.</param>
public void Push(Constraint constraint)
{
stack.Push(constraint);
constraint.SetBuilder( this.builder );
}
/// <summary>
/// Pops this topmost constrait from the stack.
/// As a side effect, the constraint's builder
/// field is set to null.
/// </summary>
/// <returns></returns>
public Constraint Pop()
{
Constraint constraint = (Constraint)stack.Pop();
constraint.SetBuilder( null );
return constraint;
}
}
#endregion
#region Instance Fields
private OperatorStack ops;
private ConstraintStack constraints;
private object lastPushed;
#endregion
#region Constructor
/// <summary>
/// Initializes a new instance of the <see cref="T:ConstraintBuilder"/> class.
/// </summary>
public ConstraintBuilder()
{
this.ops = new OperatorStack(this);
this.constraints = new ConstraintStack(this);
}
#endregion
#region Properties
/// <summary>
/// Gets a value indicating whether this instance is resolvable.
/// </summary>
/// <value>
/// <c>true</c> if this instance is resolvable; otherwise, <c>false</c>.
/// </value>
public bool IsResolvable
{
get { return lastPushed is Constraint || lastPushed is SelfResolvingOperator; }
}
#endregion
#region Public Methods
/// <summary>
/// Appends the specified operator to the expression by first
/// reducing the operator stack and then pushing the new
/// operator on the stack.
/// </summary>
/// <param name="op">The operator to push.</param>
public void Append(ConstraintOperator op)
{
op.LeftContext = lastPushed;
if (lastPushed is ConstraintOperator)
SetTopOperatorRightContext(op);
// Reduce any lower precedence operators
ReduceOperatorStack(op.LeftPrecedence);
ops.Push(op);
lastPushed = op;
}
/// <summary>
/// Appends the specified constraint to the expresson by pushing
/// it on the constraint stack.
/// </summary>
/// <param name="constraint">The constraint to push.</param>
public void Append(Constraint constraint)
{
if (lastPushed is ConstraintOperator)
SetTopOperatorRightContext(constraint);
constraints.Push(constraint);
lastPushed = constraint;
constraint.SetBuilder( this );
}
/// <summary>
/// Sets the top operator right context.
/// </summary>
/// <param name="rightContext">The right context.</param>
private void SetTopOperatorRightContext(object rightContext)
{
// Some operators change their precedence based on
// the right context - save current precedence.
int oldPrecedence = ops.Top.LeftPrecedence;
ops.Top.RightContext = rightContext;
// If the precedence increased, we may be able to
// reduce the region of the stack below the operator
if (ops.Top.LeftPrecedence > oldPrecedence)
{
ConstraintOperator changedOp = ops.Pop();
ReduceOperatorStack(changedOp.LeftPrecedence);
ops.Push(changedOp);
}
}
/// <summary>
/// Reduces the operator stack until the topmost item
/// precedence is greater than or equal to the target precedence.
/// </summary>
/// <param name="targetPrecedence">The target precedence.</param>
private void ReduceOperatorStack(int targetPrecedence)
{
while (!ops.Empty && ops.Top.RightPrecedence < targetPrecedence)
ops.Pop().Reduce(constraints);
}
/// <summary>
/// Resolves this instance, returning a Constraint. If the builder
/// is not currently in a resolvable state, an exception is thrown.
/// </summary>
/// <returns>The resolved constraint</returns>
public Constraint Resolve()
{
if (!IsResolvable)
throw new InvalidOperationException("A partial expression may not be resolved");
while (!ops.Empty)
{
ConstraintOperator op = ops.Pop();
op.Reduce(constraints);
}
return constraints.Pop();
}
#endregion
}
}
| |
namespace Devshed.Web
{
using System;
using System.Globalization;
using System.Web.UI;
using System.Web.UI.WebControls;
public static class ControlValidationExtensions
{
public static string UrlValidationExpression =
@"^(ht|f)tp(s?)\:\/\/[0-9a-zA-Z]([-.\w]*[0-9a-zA-Z])*(:(0-9)*)*(\/?)([a-zA-Z0-9\-\.\?\,\'\/\\\+&%\$#_]*)?$";
public static string EmailValidationExpression =
@"^[a-zA-Z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-zA-Z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?\.)+[a-zA-Z](?:[a-zA-Z-]*[a-zA-Z])?$";
public static PasswordStrengthValidator BasicPassword(this ControlValidatorInjector controlValidator, int minimumLength = 8, PasswordScore minimumScore = PasswordScore.Strong)
{
var validator = controlValidator.AddValidator<PasswordStrengthValidator>(Resources.Validation.PasswordDoesNotMatchRequirements);
validator.MinimumLength = minimumLength;
validator.MinimumScore = minimumScore;
return validator;
}
public static RegularExpressionValidator AsUrl(this ControlValidatorInjector controlValidator)
{
var validator = controlValidator.AddValidator<RegularExpressionValidator>(Resources.Validation.UrlIsNotValid);
validator.ValidationExpression = UrlValidationExpression;
return validator;
}
public static RegularExpressionValidator AsEmail(this ControlValidatorInjector controlValidator)
{
var validator = controlValidator.AddValidator<RegularExpressionValidator>(Resources.Validation.EmailIsNotValid);
validator.ValidationExpression = EmailValidationExpression;
return validator;
}
public static TControl SetCustomInputMask<TControl>(this TControl control, string inputMask) where TControl : WebControl
{
control.Attributes["data-mask"] = inputMask;
return control;
}
/// <summary> Adds a validator to the control and registers it in the page. </summary>
/// <param name="controlValidator"> The control to validate. </param>
/// <param name="friendlyName"> Friendly name of the required field.</param>
public static RequiredFieldValidator RequiredField(this ControlValidatorInjector controlValidator, string friendlyName)
{
controlValidator.CssClass += " aspRequired";
return controlValidator.AddValidator<RequiredFieldValidator>(
string.Format(Resources.Validation.RequiredField, friendlyName));
}
public static CompareValidator CompareToControlValue(
this ControlValidatorInjector controlValidator,
WebControl controlToCompare,
string friendlyName)
{
var validator = controlValidator.AddValidator<CompareValidator>(
string.Format(Resources.Validation.ComparedValueDontMatchField, friendlyName));
validator.ControlToCompare = controlToCompare.ID;
validator.Operator = ValidationCompareOperator.Equal;
validator.Type = ValidationDataType.String;
return validator;
}
/// <summary> Adds a validator to the control and registers it in the page. </summary>
/// <param name="controlValidator"> The control to be validated. </param>
/// <param name="controlToCompare"> The control to compare </param>
/// <param name="compareOperator"> Compare operator. </param>
/// <param name="type"> The type of comparison. </param>
/// <returns> The created <see cref="CompareValidator"/> object.</returns>
public static CompareValidator CompareToControl(
this ControlValidatorInjector controlValidator,
WebControl controlToCompare,
ValidationCompareOperator compareOperator,
ValidationDataType type)
{
var validator = controlValidator.AddValidator<CompareValidator>(Resources.Validation.ComparedControlValuesDontMatch);
validator.ControlToCompare = controlToCompare.ID;
validator.Operator = compareOperator;
validator.Type = type;
return validator;
}
/// <summary> Adds a validator to the control and registers it in the page. </summary>
/// <param name="controlValidator"> The control to validate. </param>
/// <returns> The created <see cref="CompareValidator"/> object. </returns>
public static CompareValidator AsInteger(this ControlValidatorInjector controlValidator)
{
return ValidateAsDataType(controlValidator, ValidationDataType.Integer);
}
/// <summary> Adds a validator to the control and registers it in the page. </summary>
/// <param name="controlValidator"> The control to validate. </param>
/// <returns> The created <see cref="CompareValidator"/> object. </returns>
public static CompareValidator AsDateTime(this ControlValidatorInjector controlValidator)
{
controlValidator.CssClass += " date";
return ValidateAsDataType(controlValidator, ValidationDataType.Date);
}
/// <summary> Adds a validator to the control and registers it in the page. </summary>
/// <param name="controlValidator"> The control to validate. </param>
/// <param name="friendlyName"> The friendly name to display in the error. </param>
/// <returns> The created <see cref="CompareValidator"/> object. </returns>
public static RegularExpressionValidator AsTime(this ControlValidatorInjector controlValidator, string friendlyName)
{
controlValidator.CssClass += " time";
var validator = controlValidator.AddValidator<RegularExpressionValidator>(
string.Format(Resources.Validation.TimeFormatInvalid, friendlyName));
validator.ValidationExpression = Constants.TimeValidationExpression;
return validator;
}
/// <summary> Adds a validator to the control and registers it in the page. </summary>
/// <param name="controlValidator"> The control to validate. </param>
/// <returns> The created <see cref="CompareValidator"/> object. </returns>
public static CompareValidator AsCurrency(this ControlValidatorInjector controlValidator)
{
return ValidateAsDataType(controlValidator, ValidationDataType.Currency);
}
/// <summary> Adds a validator to the control and registers it in the page. </summary>
/// <param name="controlValidator"> The control to validate. </param>
/// <returns> The created <see cref="CompareValidator"/> object. </returns>
public static CompareValidator AsDouble(this ControlValidatorInjector controlValidator)
{
return ValidateAsDataType(controlValidator, ValidationDataType.Double);
}
/// <summary> Adds a validator to the control and registers it in the page. </summary>
/// <param name="controlValidator"> The control to validate. </param>
/// <returns> The created <see cref="CompareValidator"/> object. </returns>
public static CompareValidator AsString(this ControlValidatorInjector controlValidator)
{
return ValidateAsDataType(controlValidator, ValidationDataType.String);
}
public static CompareValidator IsEarlierThan(this ControlValidatorInjector controlValidator, DateTime date)
{
return CreateDateComparer(
controlValidator,
string.Format(Resources.Validation.DateMustBeEarlierThan, date.ToString()),
date,
ValidationCompareOperator.LessThan);
}
public static CompareValidator IsEarlierOrEqual(this ControlValidatorInjector controlValidator, DateTime date)
{
return CreateDateComparer(
controlValidator,
string.Format(Resources.Validation.DateMustBeEarlierOrEqual, date.ToString()),
date,
ValidationCompareOperator.LessThanEqual);
}
public static CompareValidator IsEarlierOrEqual(this ControlValidatorInjector controlValidator, Control control, string source, string name)
{
return CreateDateComparer(
controlValidator,
string.Format(Resources.Validation.DateControlMustBeEarlierOrEqual, source),
control,
source,
name.ToLower(),
ValidationCompareOperator.LessThanEqual);
}
public static CompareValidator IsLaterThan(this ControlValidatorInjector controlValidator, DateTime date)
{
return CreateDateComparer(
controlValidator,
string.Format(Resources.Validation.DateMustBeLaterThan, date.ToString()),
date,
ValidationCompareOperator.GreaterThan);
}
public static CompareValidator IsLaterOrEqual(this ControlValidatorInjector controlValidator, DateTime date)
{
return CreateDateComparer(
controlValidator,
string.Format(Resources.Validation.DateMustBeLaterOrEqual, date.ToString()),
date,
ValidationCompareOperator.GreaterThanEqual);
}
public static CompareValidator IsGreaterThan(this ControlValidatorInjector controlValidator, int value)
{
return IntCompareValidator(
controlValidator,
value,
string.Format(Resources.Validation.NumberMustBeHigherThan, value),
ValidationCompareOperator.GreaterThan);
}
public static CompareValidator IsGreaterOrEqual(this ControlValidatorInjector controlValidator, int value)
{
return IntCompareValidator(
controlValidator,
value,
string.Format(Resources.Validation.NumberMustBeHigherOrEqualTo, value),
ValidationCompareOperator.GreaterThanEqual);
}
public static CompareValidator IsLessOrEqual(this ControlValidatorInjector controlValidator, int value)
{
return IntCompareValidator(
controlValidator,
value,
string.Format(Resources.Validation.NumberMustBeLessOrEqualTo, value),
ValidationCompareOperator.LessThanEqual);
}
public static CompareValidator IsLessThan(this ControlValidatorInjector controlValidator, int value)
{
return IntCompareValidator(
controlValidator,
value,
string.Format(Resources.Validation.NumberMustBeLessThan, value),
ValidationCompareOperator.LessThan);
}
public static RegularExpressionValidator ValidateMaxLength(
this ControlValidatorInjector controlValidator,
string friendlyName,
int maxLength)
{
var validator = controlValidator.AddValidator<RegularExpressionValidator>(
string.Format(Resources.Validation.MaximumStringLengthExceeded, friendlyName, maxLength));
validator.ValidationExpression = @"^[\s\S]{0," + maxLength.ToString() + "}$";
return validator;
}
public static ConditionalValidator ConditionalCompareField(
this ControlValidatorInjector controlValidator,
Control controlToCompare,
string message)
{
var validator = new ConditionalCompareField() { ControlToCompare = controlToCompare.ID };
controlValidator.AddValidator(validator, message);
return validator;
}
public static ConditionalValidator ConditionalRequiredField(
this ControlValidatorInjector controlValidator,
string field)
{
var validator = controlValidator.AddValidator<ConditionalRequiredField>(field);
return validator;
}
private static CompareValidator CreateDateComparer(
ControlValidatorInjector controlValidator,
string errorMessageFormat,
DateTime date,
ValidationCompareOperator compare)
{
string errorMessage = string.Format(errorMessageFormat, date);
var validator = controlValidator.AddValidator<CompareValidator>(errorMessage);
validator.ValueToCompare = date.ToString("yyyy-MM-dd");
validator.Operator = compare;
validator.Type = ValidationDataType.Date;
return validator;
}
private static CompareValidator CreateDateComparer(
ControlValidatorInjector controlValidator,
string errorMessageFormat,
Control control,
string source,
string name,
ValidationCompareOperator compare)
{
string errorMessage = string.Format(errorMessageFormat, source, name);
var validator = controlValidator.AddValidator<CompareValidator>(errorMessage);
validator.ControlToCompare = control.ID;
validator.Operator = compare;
validator.Type = ValidationDataType.Date;
return validator;
}
private static CompareValidator IntCompareValidator(
ControlValidatorInjector controlValidator,
int value,
string errorMessageFormat,
ValidationCompareOperator equation)
{
string errorMessage = string.Format(errorMessageFormat, value);
var validator = controlValidator.AddValidator<CompareValidator>(errorMessage);
validator.ValueToCompare = value.ToString(CultureInfo.InvariantCulture);
validator.Operator = equation;
validator.Type = ValidationDataType.Double;
return validator;
}
/// <summary> Adds a validator to the control and registers it in the page. </summary>
/// <param name="controlValidator"> The control to validate. </param>
/// <param name="type">The data type to validate.</param>
/// <returns> The created <see cref="CompareValidator"/> object. </returns>
private static CompareValidator ValidateAsDataType(ControlValidatorInjector controlValidator, ValidationDataType type)
{
var validator = controlValidator.AddValidator<CompareValidator>(
string.Format(Resources.Validation.ValueMustBeOfType, type));
validator.Operator = ValidationCompareOperator.DataTypeCheck;
validator.Type = type;
return validator;
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Collections.Generic;
using Xunit;
namespace System.Linq.Parallel.Tests
{
public class GroupByTests
{
private const int GroupFactor = 8;
[Theory]
[MemberData("Ranges", (object)(new int[] { 0, 1, 2, GroupFactor - 1, GroupFactor, GroupFactor * 2 - 1, GroupFactor * 2 }), MemberType = typeof(UnorderedSources))]
public static void GroupBy_Unordered(Labeled<ParallelQuery<int>> labeled, int count)
{
ParallelQuery<int> query = labeled.Item;
IntegerRangeSet groupsSeen = new IntegerRangeSet(0, Math.Min(count, GroupFactor));
foreach (IGrouping<int, int> group in query.GroupBy(x => x % GroupFactor))
{
groupsSeen.Add(group.Key);
IntegerRangeSet elementsSeen = new IntegerRangeSet(0, 1 + (count - (group.Key + 1)) / GroupFactor);
foreach (int i in group)
{
Assert.Equal(group.Key, i % GroupFactor);
elementsSeen.Add(i / GroupFactor);
}
elementsSeen.AssertComplete();
}
groupsSeen.AssertComplete();
}
[Theory]
[OuterLoop]
[MemberData("Ranges", (object)(new int[] { 1024, 1024 * 16 }), MemberType = typeof(UnorderedSources))]
public static void GroupBy_Unordered_Longrunning(Labeled<ParallelQuery<int>> labeled, int count)
{
GroupBy_Unordered(labeled, count);
}
[Theory]
[MemberData("Ranges", (object)(new int[] { 0, 1, 2, GroupFactor - 1, GroupFactor, GroupFactor * 2 - 1, GroupFactor * 2 }), MemberType = typeof(Sources))]
public static void GroupBy(Labeled<ParallelQuery<int>> labeled, int count)
{
ParallelQuery<int> query = labeled.Item;
int groupsSeen = 0;
foreach (IGrouping<int, int> group in query.GroupBy(x => x % GroupFactor))
{
Assert.Equal(groupsSeen++, group.Key);
int elementsSeen = group.Key;
foreach (int i in group)
{
Assert.Equal(elementsSeen, i);
elementsSeen += GroupFactor;
}
Assert.Equal(group.Key + (1 + (count - (group.Key + 1)) / GroupFactor) * GroupFactor, elementsSeen);
}
Assert.Equal(Math.Min(count, GroupFactor), groupsSeen);
}
[Theory]
[OuterLoop]
[MemberData("Ranges", (object)(new int[] { 1024, 1024 * 16 }), MemberType = typeof(Sources))]
public static void GroupBy_Longrunning(Labeled<ParallelQuery<int>> labeled, int count)
{
GroupBy(labeled, count);
}
[Theory]
[MemberData("Ranges", (object)(new int[] { 0, 1, 2, GroupFactor - 1, GroupFactor, GroupFactor * 2 - 1, GroupFactor * 2 }), MemberType = typeof(UnorderedSources))]
public static void GroupBy_Unordered_NotPipelined(Labeled<ParallelQuery<int>> labeled, int count)
{
ParallelQuery<int> query = labeled.Item;
IntegerRangeSet groupsSeen = new IntegerRangeSet(0, Math.Min(count, GroupFactor));
foreach (IGrouping<int, int> group in query.GroupBy(x => x % GroupFactor).ToList())
{
groupsSeen.Add(group.Key);
IntegerRangeSet elementsSeen = new IntegerRangeSet(0, 1 + (count - (group.Key + 1)) / GroupFactor);
Assert.All(group, x => { Assert.Equal(group.Key, x % GroupFactor); elementsSeen.Add(x / GroupFactor); });
elementsSeen.AssertComplete();
}
groupsSeen.AssertComplete();
}
[Theory]
[OuterLoop]
[MemberData("Ranges", (object)(new int[] { 1024, 1024 * 16 }), MemberType = typeof(UnorderedSources))]
public static void GroupBy_Unordered_NotPipelined_Longrunning(Labeled<ParallelQuery<int>> labeled, int count)
{
GroupBy_Unordered_NotPipelined(labeled, count);
}
[Theory]
[MemberData("Ranges", (object)(new int[] { 0, 1, 2, GroupFactor - 1, GroupFactor, GroupFactor * 2 - 1, GroupFactor * 2 }), MemberType = typeof(Sources))]
public static void GroupBy_NotPipelined(Labeled<ParallelQuery<int>> labeled, int count)
{
ParallelQuery<int> query = labeled.Item;
int groupsSeen = 0;
foreach (IGrouping<int, int> group in query.GroupBy(x => x % GroupFactor).ToList())
{
Assert.Equal(groupsSeen++, group.Key);
int elementsSeen = group.Key;
Assert.All(group, x => { Assert.Equal(elementsSeen, x); elementsSeen += GroupFactor; });
Assert.Equal(group.Key + (1 + (count - (group.Key + 1)) / GroupFactor) * GroupFactor, elementsSeen);
}
Assert.Equal(Math.Min(count, GroupFactor), groupsSeen);
}
[Theory]
[OuterLoop]
[MemberData("Ranges", (object)(new int[] { 1024, 1024 * 16 }), MemberType = typeof(Sources))]
public static void GroupBy_NotPipelined_Longrunning(Labeled<ParallelQuery<int>> labeled, int count)
{
GroupBy_NotPipelined(labeled, count);
}
[Theory]
[MemberData("Ranges", (object)(new int[] { 0, 1, 2, GroupFactor - 1, GroupFactor, GroupFactor * 2 - 1, GroupFactor * 2 }), MemberType = typeof(UnorderedSources))]
public static void GroupBy_Unordered_CustomComparator(Labeled<ParallelQuery<int>> labeled, int count)
{
ParallelQuery<int> query = labeled.Item;
IntegerRangeSet groupsSeen = new IntegerRangeSet(0, Math.Min(count, GroupFactor));
foreach (IGrouping<int, int> group in query.GroupBy(x => x, new ModularCongruenceComparer(GroupFactor)))
{
groupsSeen.Add(group.Key % GroupFactor);
IntegerRangeSet elementsSeen = new IntegerRangeSet(0, 1 + (count - (group.Key % GroupFactor + 1)) / GroupFactor);
foreach (int i in group)
{
Assert.Equal(group.Key % GroupFactor, i % GroupFactor);
elementsSeen.Add(i / GroupFactor);
}
elementsSeen.AssertComplete();
}
groupsSeen.AssertComplete();
}
[Theory]
[OuterLoop]
[MemberData("Ranges", (object)(new int[] { 1024, 1024 * 16 }), MemberType = typeof(UnorderedSources))]
public static void GroupBy_Unordered_CustomComparator_Longrunning(Labeled<ParallelQuery<int>> labeled, int count)
{
GroupBy_Unordered_CustomComparator(labeled, count);
}
[Theory]
[MemberData("Ranges", (object)(new int[] { 0, 1, 2, GroupFactor - 1, GroupFactor, GroupFactor * 2 - 1, GroupFactor * 2 }), MemberType = typeof(Sources))]
// GroupBy doesn't select the first 'identical' key. Issue #1490
public static void GroupBy_CustomComparator(Labeled<ParallelQuery<int>> labeled, int count)
{
ParallelQuery<int> query = labeled.Item;
int groupsSeen = 0;
foreach (IGrouping<int, int> group in query.GroupBy(x => x, new ModularCongruenceComparer(GroupFactor)))
{
int elementsSeen = groupsSeen;
Assert.Equal(groupsSeen++, group.Key % GroupFactor);
foreach (int i in group)
{
Assert.Equal(elementsSeen, i);
elementsSeen += GroupFactor;
}
Assert.Equal(group.Key + (1 + (count - (group.Key + 1)) / GroupFactor) * GroupFactor, elementsSeen);
}
Assert.Equal(Math.Min(count, GroupFactor), groupsSeen);
}
[Theory]
[OuterLoop]
[MemberData("Ranges", (object)(new int[] { 1024, 1024 * 16 }), MemberType = typeof(Sources))]
public static void GroupBy_CustomComparator_Longrunning(Labeled<ParallelQuery<int>> labeled, int count)
{
GroupBy_CustomComparator(labeled, count);
}
[Theory]
[MemberData("Ranges", (object)(new int[] { 0, 1, 2, GroupFactor - 1, GroupFactor, GroupFactor * 2 - 1, GroupFactor * 2 }), MemberType = typeof(UnorderedSources))]
public static void GroupBy_Unordered_ElementSelector(Labeled<ParallelQuery<int>> labeled, int count)
{
ParallelQuery<int> query = labeled.Item;
IntegerRangeSet groupsSeen = new IntegerRangeSet(0, Math.Min(count, GroupFactor));
foreach (IGrouping<int, int> group in query.GroupBy(x => x % GroupFactor, x => -x))
{
groupsSeen.Add(group.Key);
int expected = 1 + (count - (group.Key + 1)) / GroupFactor;
IntegerRangeSet elementsSeen = new IntegerRangeSet(1 - expected, expected);
Assert.All(group, x => { Assert.Equal(group.Key, -x % GroupFactor); elementsSeen.Add(x / GroupFactor); });
elementsSeen.AssertComplete();
}
groupsSeen.AssertComplete();
}
[Theory]
[OuterLoop]
[MemberData("Ranges", (object)(new int[] { 1024, 1024 * 16 }), MemberType = typeof(UnorderedSources))]
public static void GroupBy_Unordered_ElementSelector_Longrunning(Labeled<ParallelQuery<int>> labeled, int count)
{
GroupBy_Unordered_ElementSelector(labeled, count);
}
[Theory]
[MemberData("Ranges", (object)(new int[] { 0, 1, 2, GroupFactor - 1, GroupFactor, GroupFactor * 2 - 1, GroupFactor * 2 }), MemberType = typeof(Sources))]
public static void GroupBy_ElementSelector(Labeled<ParallelQuery<int>> labeled, int count)
{
ParallelQuery<int> query = labeled.Item;
int groupsSeen = 0;
foreach (IGrouping<int, int> group in query.GroupBy(x => x % GroupFactor, x => -x))
{
Assert.Equal(groupsSeen++, group.Key);
int elementsSeen = -group.Key;
Assert.All(group, x => { Assert.Equal(elementsSeen, x); elementsSeen -= GroupFactor; });
Assert.Equal(-group.Key - (1 + (count - (group.Key + 1)) / GroupFactor) * GroupFactor, elementsSeen);
}
Assert.Equal(Math.Min(count, GroupFactor), groupsSeen);
}
[Theory]
[OuterLoop]
[MemberData("Ranges", (object)(new int[] { 1024, 1024 * 16 }), MemberType = typeof(Sources))]
public static void GroupBy_ElementSelector_Longrunning(Labeled<ParallelQuery<int>> labeled, int count)
{
GroupBy_ElementSelector(labeled, count);
}
[Theory]
[MemberData("Ranges", (object)(new int[] { 0, 1, 2, GroupFactor - 1, GroupFactor, GroupFactor * 2 - 1, GroupFactor * 2 }), MemberType = typeof(UnorderedSources))]
public static void GroupBy_Unordered_ElementSelector_NotPipelined(Labeled<ParallelQuery<int>> labeled, int count)
{
ParallelQuery<int> query = labeled.Item;
IntegerRangeSet groupsSeen = new IntegerRangeSet(0, Math.Min(count, GroupFactor));
foreach (IGrouping<int, int> group in query.GroupBy(x => x % GroupFactor, y => -y).ToList())
{
groupsSeen.Add(group.Key);
int expected = 1 + (count - (group.Key + 1)) / GroupFactor;
IntegerRangeSet elementsSeen = new IntegerRangeSet(1 - expected, expected);
Assert.All(group, x => { Assert.Equal(group.Key, -x % GroupFactor); elementsSeen.Add(x / GroupFactor); });
elementsSeen.AssertComplete();
}
groupsSeen.AssertComplete();
}
[Theory]
[OuterLoop]
[MemberData("Ranges", (object)(new int[] { 1024, 1024 * 16 }), MemberType = typeof(UnorderedSources))]
public static void GroupBy_Unordered_ElementSelector_NotPipelined_Longrunning(Labeled<ParallelQuery<int>> labeled, int count)
{
GroupBy_Unordered_ElementSelector_NotPipelined(labeled, count);
}
[Theory]
[MemberData("Ranges", (object)(new int[] { 0, 1, 2, GroupFactor - 1, GroupFactor, GroupFactor * 2 - 1, GroupFactor * 2 }), MemberType = typeof(Sources))]
public static void GroupBy_ElementSelector_NotPipelined(Labeled<ParallelQuery<int>> labeled, int count)
{
ParallelQuery<int> query = labeled.Item;
int groupsSeen = 0;
foreach (IGrouping<int, int> group in query.GroupBy(x => x % GroupFactor, y => -y).ToList())
{
Assert.Equal(groupsSeen++, group.Key);
int elementsSeen = -group.Key;
Assert.All(group, x => { Assert.Equal(elementsSeen, x); elementsSeen -= GroupFactor; });
Assert.Equal(-group.Key - (1 + (count - (group.Key + 1)) / GroupFactor) * GroupFactor, elementsSeen);
}
Assert.Equal(Math.Min(count, GroupFactor), groupsSeen);
}
[Theory]
[OuterLoop]
[MemberData("Ranges", (object)(new int[] { 1024, 1024 * 16 }), MemberType = typeof(Sources))]
public static void GroupBy_ElementSelector_NotPipelined_Longrunning(Labeled<ParallelQuery<int>> labeled, int count)
{
GroupBy_ElementSelector_NotPipelined(labeled, count);
}
[Theory]
[MemberData("Ranges", (object)(new int[] { 0, 1, 2, GroupFactor - 1, GroupFactor, GroupFactor * 2 - 1, GroupFactor * 2 }), MemberType = typeof(UnorderedSources))]
public static void GroupBy_Unordered_ResultSelector(Labeled<ParallelQuery<int>> labeled, int count)
{
ParallelQuery<int> query = labeled.Item;
IntegerRangeSet groupsSeen = new IntegerRangeSet(0, Math.Min(count, GroupFactor));
foreach (var group in query.GroupBy(x => x % GroupFactor, (key, elements) => KeyValuePair.Create(key, elements)))
{
groupsSeen.Add(group.Key);
IntegerRangeSet elementsSeen = new IntegerRangeSet(0, 1 + (count - (group.Key + 1)) / GroupFactor);
Assert.All(group.Value, x => { Assert.Equal(group.Key, x % GroupFactor); elementsSeen.Add(x / GroupFactor); });
elementsSeen.AssertComplete();
}
groupsSeen.AssertComplete();
}
[Theory]
[OuterLoop]
[MemberData("Ranges", (object)(new int[] { 1024, 1024 * 16 }), MemberType = typeof(UnorderedSources))]
public static void GroupBy_Unordered_ResultSelector_Longrunning(Labeled<ParallelQuery<int>> labeled, int count)
{
GroupBy_Unordered_ResultSelector(labeled, count);
}
[Theory]
[MemberData("Ranges", (object)(new int[] { 0, 1, 2, GroupFactor - 1, GroupFactor, GroupFactor * 2 - 1, GroupFactor * 2 }), MemberType = typeof(Sources))]
public static void GroupBy_ResultSelector(Labeled<ParallelQuery<int>> labeled, int count)
{
ParallelQuery<int> query = labeled.Item;
int groupsSeen = 0;
foreach (var group in query.GroupBy(x => x % GroupFactor, (key, elements) => KeyValuePair.Create(key, elements)))
{
Assert.Equal(groupsSeen++, group.Key);
int elementsSeen = group.Key;
Assert.All(group.Value, x => { Assert.Equal(elementsSeen, x); elementsSeen += GroupFactor; });
Assert.Equal(group.Key + (1 + (count - (group.Key + 1)) / GroupFactor) * GroupFactor, elementsSeen);
}
Assert.Equal(Math.Min(count, GroupFactor), groupsSeen);
}
[Theory]
[OuterLoop]
[MemberData("Ranges", (object)(new int[] { 1024, 1024 * 16 }), MemberType = typeof(Sources))]
public static void GroupBy_ResultSelector_Longrunning(Labeled<ParallelQuery<int>> labeled, int count)
{
GroupBy_ResultSelector(labeled, count);
}
[Theory]
[MemberData("Ranges", (object)(new int[] { 0, 1, 2, 7, 8, 15, 16 }), MemberType = typeof(UnorderedSources))]
public static void GroupBy_Unordered_ResultSelector_CustomComparator(Labeled<ParallelQuery<int>> labeled, int count)
{
ParallelQuery<int> query = labeled.Item;
IntegerRangeSet groupsSeen = new IntegerRangeSet(0, Math.Min(count, GroupFactor));
foreach (var group in query.GroupBy(x => x, (key, elements) => KeyValuePair.Create(key, elements), new ModularCongruenceComparer(GroupFactor)))
{
groupsSeen.Add(group.Key % GroupFactor);
IntegerRangeSet elementsSeen = new IntegerRangeSet(0, 1 + (count - (group.Key % GroupFactor + 1)) / GroupFactor);
Assert.All(group.Value, x => { Assert.Equal(group.Key % GroupFactor, x % GroupFactor); elementsSeen.Add(x / GroupFactor); });
elementsSeen.AssertComplete();
}
groupsSeen.AssertComplete();
}
[Theory]
[OuterLoop]
[MemberData("Ranges", (object)(new int[] { 1024, 1024 * 16 }), MemberType = typeof(UnorderedSources))]
public static void GroupBy_Unordered_ResultSelector_CustomComparator_Longrunning(Labeled<ParallelQuery<int>> labeled, int count)
{
GroupBy_Unordered_ResultSelector_CustomComparator(labeled, count);
}
[Theory]
[MemberData("Ranges", (object)(new int[] { 0, 1, 2, GroupFactor - 1, GroupFactor, GroupFactor * 2 - 1, GroupFactor * 2 }), MemberType = typeof(Sources))]
public static void GroupBy_ResultSelector_CustomComparator(Labeled<ParallelQuery<int>> labeled, int count)
{
ParallelQuery<int> query = labeled.Item;
int groupsSeen = 0;
foreach (var group in query.GroupBy(x => x, (key, elements) => KeyValuePair.Create(key, elements), new ModularCongruenceComparer(GroupFactor)))
{
int elementsSeen = groupsSeen;
Assert.Equal(groupsSeen++, group.Key % GroupFactor);
Assert.All(group.Value, x => { Assert.Equal(elementsSeen, x); elementsSeen += GroupFactor; });
Assert.Equal(group.Key + (1 + (count - (group.Key + 1)) / GroupFactor) * GroupFactor, elementsSeen);
}
Assert.Equal(Math.Min(count, GroupFactor), groupsSeen);
}
[Theory]
[OuterLoop]
[MemberData("Ranges", (object)(new int[] { 1024, 1024 * 16 }), MemberType = typeof(Sources))]
public static void GroupBy_ResultSelector_CustomComparator_Longrunning(Labeled<ParallelQuery<int>> labeled, int count)
{
GroupBy_ResultSelector_CustomComparator(labeled, count);
}
[Theory]
[MemberData("Ranges", (object)(new int[] { 0, 1, 2, 7, 8, 15, 16 }), MemberType = typeof(UnorderedSources))]
public static void GroupBy_Unordered_ElementSelector_ResultSelector(Labeled<ParallelQuery<int>> labeled, int count)
{
ParallelQuery<int> query = labeled.Item;
IntegerRangeSet groupsSeen = new IntegerRangeSet(0, Math.Min(count, GroupFactor));
foreach (var group in query.GroupBy(x => x % GroupFactor, x => -x, (key, elements) => KeyValuePair.Create(key, elements)))
{
groupsSeen.Add(group.Key);
int expected = 1 + (count - (group.Key + 1)) / GroupFactor;
IntegerRangeSet elementsSeen = new IntegerRangeSet(1 - expected, expected);
Assert.All(group.Value, x => { Assert.Equal(group.Key, -x % GroupFactor); elementsSeen.Add(x / GroupFactor); });
elementsSeen.AssertComplete();
}
groupsSeen.AssertComplete();
}
[Theory]
[OuterLoop]
[MemberData("Ranges", (object)(new int[] { 1024, 1024 * 16 }), MemberType = typeof(UnorderedSources))]
public static void GroupBy_Unordered_ElementSelector_ResultSelector_Longrunning(Labeled<ParallelQuery<int>> labeled, int count)
{
GroupBy_Unordered_ElementSelector_ResultSelector(labeled, count);
}
[Theory]
[MemberData("Ranges", (object)(new int[] { 0, 1, 2, GroupFactor - 1, GroupFactor, GroupFactor * 2 - 1, GroupFactor * 2 }), MemberType = typeof(Sources))]
public static void GroupBy_ElementSelector_ResultSelector(Labeled<ParallelQuery<int>> labeled, int count)
{
ParallelQuery<int> query = labeled.Item;
int groupsSeen = 0;
foreach (var group in query.GroupBy(x => x % GroupFactor, x => -x, (key, elements) => KeyValuePair.Create(key, elements)))
{
Assert.Equal(groupsSeen++, group.Key);
int elementsSeen = -group.Key;
Assert.All(group.Value, x => { Assert.Equal(elementsSeen, x); elementsSeen -= GroupFactor; });
Assert.Equal(-group.Key - (1 + (count - (group.Key + 1)) / GroupFactor) * GroupFactor, elementsSeen);
}
Assert.Equal(Math.Min(count, GroupFactor), groupsSeen);
}
[Theory]
[OuterLoop]
[MemberData("Ranges", (object)(new int[] { 1024, 1024 * 16 }), MemberType = typeof(Sources))]
public static void GroupBy_ElementSelector_ResultSelector_Longrunning(Labeled<ParallelQuery<int>> labeled, int count)
{
GroupBy_ElementSelector_ResultSelector(labeled, count);
}
[Fact]
public static void GroupBy_ArgumentNullException()
{
Assert.Throws<ArgumentNullException>(() => ((ParallelQuery<int>)null).GroupBy(i => i));
Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Range(0, 1).GroupBy((Func<int, int>)null));
Assert.Throws<ArgumentNullException>(() => ((ParallelQuery<int>)null).GroupBy(i => i, EqualityComparer<int>.Default));
Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Range(0, 1).GroupBy((Func<int, int>)null, EqualityComparer<int>.Default));
Assert.Throws<ArgumentNullException>(() => ((ParallelQuery<int>)null).GroupBy(i => i, i => i));
Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Range(0, 1).GroupBy((Func<int, int>)null, i => i));
Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Range(0, 1).GroupBy(i => i, (Func<int, int>)null));
Assert.Throws<ArgumentNullException>(() => ((ParallelQuery<int>)null).GroupBy(i => i, i => i, EqualityComparer<int>.Default));
Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Range(0, 1).GroupBy((Func<int, int>)null, i => i, EqualityComparer<int>.Default));
Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Range(0, 1).GroupBy(i => i, (Func<int, int>)null, EqualityComparer<int>.Default));
Assert.Throws<ArgumentNullException>(() => ((ParallelQuery<int>)null).GroupBy(i => i, (i, j) => i));
Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Range(0, 1).GroupBy((Func<int, int>)null, (i, j) => i));
Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Range(0, 1).GroupBy(i => i, (Func<int, IEnumerable<int>, int>)null));
Assert.Throws<ArgumentNullException>(() => ((ParallelQuery<int>)null).GroupBy(i => i, (i, j) => i, EqualityComparer<int>.Default));
Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Range(0, 1).GroupBy((Func<int, int>)null, (i, j) => i, EqualityComparer<int>.Default));
Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Range(0, 1).GroupBy(i => i, (Func<int, IEnumerable<int>, int>)null, EqualityComparer<int>.Default));
Assert.Throws<ArgumentNullException>(() => ((ParallelQuery<int>)null).GroupBy(i => i, i => i, (i, j) => i));
Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Range(0, 1).GroupBy((Func<int, int>)null, i => i, (i, j) => i));
Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Range(0, 1).GroupBy(i => i, (Func<int, int>)null, (i, j) => i));
Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Range(0, 1).GroupBy(i => i, i => i, (Func<int, IEnumerable<int>, int>)null));
Assert.Throws<ArgumentNullException>(() => ((ParallelQuery<int>)null).GroupBy(i => i, i => i, (i, j) => i, EqualityComparer<int>.Default));
Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Range(0, 1).GroupBy((Func<int, int>)null, i => i, (i, j) => i, EqualityComparer<int>.Default));
Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Range(0, 1).GroupBy(i => i, (Func<int, int>)null, (i, j) => i, EqualityComparer<int>.Default));
Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Range(0, 1).GroupBy(i => i, i => i, (Func<int, IEnumerable<int>, int>)null, EqualityComparer<int>.Default));
}
}
}
| |
/*
* SecurityElement.cs - Implementation of the
* "System.Security.SecurityElement" class.
*
* Copyright (C) 2001, 2003 Southern Storm Software, Pty Ltd.
*
* 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.Security
{
#if CONFIG_PERMISSIONS || CONFIG_POLICY_OBJECTS || CONFIG_REMOTING
using System;
using System.Text;
using System.Collections;
// Note: ECMA only specifies the "ToString()" method for this
// class, but it isn't very useful unless the other framework
// methods are also present.
public sealed class SecurityElement
{
// Internal state.
private String tag;
private String text;
private ArrayList attributes;
private ArrayList children;
// Attribute name/value information
private sealed class AttrNameValue
{
// Internal state.
public String name;
public String value;
// Constructor.
public AttrNameValue(String name, String value)
{
this.name = name;
this.value = value;
}
}; // class AttrNameValue
// Constructors.
public SecurityElement(String tag)
: this(tag, null)
{
// Nothing to do here.
}
public SecurityElement(String tag, String text)
{
if(tag == null)
{
throw new ArgumentNullException("tag");
}
else if(!IsValidTag(tag))
{
throw new ArgumentException(_("Arg_InvalidXMLTag"));
}
else if(text != null && !IsValidText(text))
{
throw new ArgumentException(_("Arg_InvalidXMLText"));
}
this.tag = tag;
this.text = text;
}
// Invalid XML characters.
private static readonly char[] InvalidChars = {'<', '>', '&', '"', '\''};
// Invalid XML tag and attribute name characters.
private static readonly char[] InvalidNameChars =
{'<', '>', '&', '"', '\'', '=',
'\u0009', '\u000A', '\u000B', '\u000C', '\u000D', '\u0020',
'\u00A0', '\u2001', '\u2002', '\u2003', '\u2004', '\u2005',
'\u2006', '\u2007', '\u2008', '\u2009', '\u200A', '\u200B',
'\u3000', '\uFEFF'};
// Invalid XML characters in text sections. It is assumed that
// occurrences of '&' are correctly-formatted XML escapes.
private static readonly char[] InvalidTextChars = {'<', '>'};
// Invalid XML characters in attribute values. It is assumed that
// occurrences of '&' are correctly-formatted XML escapes.
private static readonly char[] InvalidAttrChars = {'<', '>', '"'};
// Escape invalid XML characters in a string.
public static String Escape(String str)
{
StringBuilder newStr;
int start;
int index;
char ch;
// The null string is encoded as itself.
if(str == null)
{
return null;
}
// Do nothing if the string does not contain invalid chars.
index = str.IndexOfAny(InvalidChars);
if(index < 0)
{
return str;
}
// Replace the invalid characters and build a new string.
newStr = new StringBuilder(str.Substring(0, index));
for(;;)
{
ch = str[index++];
if(ch == '<')
{
newStr.Append("<");
}
else if(ch == '>')
{
newStr.Append(">");
}
else if(ch == '&')
{
newStr.Append("&");
}
else if(ch == '"')
{
newStr.Append(""");
}
else
{
newStr.Append("'");
}
start = index;
if(start >= str.Length)
{
break;
}
index = str.IndexOfAny(InvalidChars,
start, str.Length - start);
if(index == -1)
{
newStr.Append(str.Substring(start));
break;
}
else if(index > start)
{
newStr.Append(str.Substring(start, index - start));
}
}
// Return the escaped string to the caller.
return newStr.ToString();
}
// Unescape invalid XML characters in a string.
private static String Unescape(String str)
{
// Bail out early if there are no escapes in the string.
if(str == null || str.IndexOf('&') == -1)
{
return str;
}
// Construct a new string with the escapes removed.
StringBuilder newStr = new StringBuilder();
int posn = 0;
char ch;
String name;
while(posn < str.Length)
{
ch = str[posn++];
if(ch == '&')
{
name = String.Empty;
while(posn < str.Length && str[posn] != ';')
{
name += str[posn];
++posn;
}
if(posn < str.Length)
{
++posn;
}
if(name == "lt")
{
newStr.Append('<');
}
else if(name == "gt")
{
newStr.Append('>');
}
else if(name == "amp")
{
newStr.Append('&');
}
else if(name == "quot")
{
newStr.Append('"');
}
else if(name == "apos")
{
newStr.Append('\'');
}
}
else
{
newStr.Append(ch);
}
}
return newStr.ToString();
}
// Determine if a string is a valid attribute name.
public static bool IsValidAttributeName(String name)
{
if(name == null || name.Length == 0)
{
return false;
}
else
{
return (name.IndexOfAny(InvalidNameChars) < 0);
}
}
// Determine if a string is a valid attribute value.
public static bool IsValidAttributeValue(String value)
{
if(value == null)
{
return false;
}
else
{
return (value.IndexOfAny(InvalidAttrChars) < 0);
}
}
// Determine if a string is a valid tag name.
public static bool IsValidTag(String name)
{
if(name == null || name.Length == 0)
{
return false;
}
else
{
return (name.IndexOfAny(InvalidNameChars) < 0);
}
}
// Determine if a string is valid element text.
public static bool IsValidText(String text)
{
if(text == null)
{
return false;
}
else
{
return (text.IndexOfAny(InvalidTextChars) < 0);
}
}
// Get the attributes for this element.
public Hashtable Attributes
{
get
{
if(attributes == null)
{
return null;
}
else
{
Hashtable table = new Hashtable();
IEnumerator e = attributes.GetEnumerator();
AttrNameValue nv;
while(e.MoveNext())
{
nv = (AttrNameValue)(e.Current);
table.Add(nv.name, nv.value);
}
return table;
}
}
set
{
if(value == null)
{
attributes = null;
}
else
{
attributes = new ArrayList(value.Count);
IDictionaryEnumerator e = value.GetEnumerator();
String name, val;
while(e.MoveNext())
{
name = (String)(e.Key);
val = (String)(e.Value);
if(!IsValidAttributeName(name))
{
throw new ArgumentException
(_("Arg_InvalidXMLAttrName"));
}
if(!IsValidAttributeValue(val))
{
throw new ArgumentException
(_("Arg_InvalidXMLAttrValue"));
}
attributes.Add(new AttrNameValue(name, val));
}
}
}
}
// Get or set the children of this XML element.
public ArrayList Children
{
get
{
return children;
}
set
{
if(value == null)
{
children = null;
}
else
{
int posn;
for(posn = 0; posn < value.Count; ++posn)
{
if(value[posn] == null)
{
throw new ArgumentNullException
("value[" + posn.ToString() + "]");
}
}
children = value;
}
}
}
// Get or set the tag name.
public String Tag
{
get
{
return tag;
}
set
{
if(value == null)
{
throw new ArgumentNullException("value");
}
else if(!IsValidTag(value))
{
throw new ArgumentException(_("Arg_InvalidXMLTag"));
}
tag = value;
}
}
// Get or set the element text.
public String Text
{
get
{
return Unescape(text);
}
set
{
if(value != null && !IsValidText(value))
{
throw new ArgumentException(_("Arg_InvalidXMLText"));
}
text = value;
}
}
// Add an attribute to this element.
public void AddAttribute(String name, String value)
{
// Validate the parameters.
if(name == null)
{
throw new ArgumentNullException("name");
}
if(value == null)
{
throw new ArgumentNullException("value");
}
if(!IsValidAttributeName(name))
{
throw new ArgumentException
(_("Arg_InvalidXMLAttrName"));
}
if(!IsValidAttributeValue(value))
{
throw new ArgumentException
(_("Arg_InvalidXMLAttrValue"));
}
// Search for an attribute with the same name.
if(attributes != null)
{
int posn;
for(posn = 0; posn < attributes.Count; ++posn)
{
if(((AttrNameValue)(attributes[posn])).name == name)
{
throw new ArgumentException
(_("Arg_DuplicateXMLAttr"));
}
}
}
else
{
attributes = new ArrayList();
}
// Add the new attribute.
attributes.Add(new AttrNameValue(name, value));
}
// Set an attribute within this element.
internal void SetAttribute(String name, String value)
{
// Validate the parameters.
if(name == null)
{
throw new ArgumentNullException("name");
}
if(value == null)
{
throw new ArgumentNullException("value");
}
if(!IsValidAttributeName(name))
{
throw new ArgumentException
(_("Arg_InvalidXMLAttrName"));
}
if(!IsValidAttributeValue(value))
{
throw new ArgumentException
(_("Arg_InvalidXMLAttrValue"));
}
// Search for an attribute with the same name.
if(attributes != null)
{
int posn;
for(posn = 0; posn < attributes.Count; ++posn)
{
if(((AttrNameValue)(attributes[posn])).name == name)
{
((AttrNameValue)(attributes[posn])).value = value;
return;
}
}
}
else
{
attributes = new ArrayList();
}
// Add the new attribute.
attributes.Add(new AttrNameValue(name, value));
}
// Add a child to this element.
public void AddChild(SecurityElement child)
{
if(child == null)
{
throw new ArgumentNullException("child");
}
if(children == null)
{
children = new ArrayList();
}
children.Add(child);
}
// Get the value of a specific attribute.
public String Attribute(String name)
{
if(name == null)
{
throw new ArgumentNullException("name");
}
else if(attributes == null)
{
return null;
}
int posn;
AttrNameValue nv;
for(posn = 0; posn < attributes.Count; ++posn)
{
nv = (AttrNameValue)(attributes[posn]);
if(name == nv.name)
{
return Unescape(nv.value);
}
}
return null;
}
// Compare two security elements for equality.
public bool Equal(SecurityElement other)
{
int posn;
AttrNameValue nv;
// Check the easy cases first.
if(other == null)
{
return false;
}
else if(tag != other.tag || text != other.text)
{
return false;
}
// Compare the attribute values.
if(attributes == null && other.attributes != null)
{
return false;
}
else if(attributes != null && other.attributes == null)
{
return false;
}
else if(attributes != null)
{
if(attributes.Count != other.attributes.Count)
{
return false;
}
for(posn = 0; posn < attributes.Count; ++posn)
{
nv = (AttrNameValue)(attributes[posn]);
if(other.Attribute(nv.name) != nv.value)
{
return false;
}
}
}
// Compare the children.
if(children == null && other.children != null)
{
return false;
}
else if(children != null && other.children == null)
{
return false;
}
else if(children != null)
{
if(children.Count != other.children.Count)
{
return false;
}
for(posn = 0; posn < children.Count; ++posn)
{
if(!((SecurityElement)(children[posn])).Equal
((SecurityElement)(other.children[posn])))
{
return false;
}
}
}
// The elements are identical.
return true;
}
// Search for a child by tag name.
public SecurityElement SearchForChildByTag(String tag)
{
if(tag == null)
{
throw new ArgumentNullException("tag");
}
if(children != null)
{
int posn;
SecurityElement child;
for(posn = 0; posn < children.Count; ++posn)
{
child = (SecurityElement)(children[posn]);
if(child.Tag == tag)
{
return child;
}
}
}
return null;
}
// Search for the text of a named child.
public String SearchForTextOfTag(String tag)
{
if(tag == null)
{
throw new ArgumentNullException("tag");
}
if(children != null)
{
int posn;
SecurityElement child;
for(posn = 0; posn < children.Count; ++posn)
{
child = (SecurityElement)(children[posn]);
if(child.Tag == tag)
{
return child.Text;
}
}
}
return null;
}
// Convert this security element into an XML string.
public override String ToString()
{
int posn;
AttrNameValue nv;
String result = "<" + tag;
if(attributes != null)
{
// Add the attribute values.
for(posn = 0; posn < attributes.Count; ++posn)
{
nv = (AttrNameValue)(attributes[posn]);
result += " " + nv.name + "=\"" + nv.value + "\"";
}
}
if(text == null &&
(children == null || children.Count == 0))
{
// The element has no contents, so use the short-cut syntax.
result += "/>" + Environment.NewLine;
}
else
{
// Add the text and child elements.
result += ">";
if(text != null)
{
result += Escape(text);
}
else
{
result += Environment.NewLine;
}
if(children != null)
{
for(posn = 0; posn < children.Count; ++posn)
{
result +=
((SecurityElement)(children[posn])).ToString();
}
}
result += "</" + tag + ">" + Environment.NewLine;
}
return result;
}
// Parse an XML string into a tree of "SecurityElement" values.
internal static SecurityElement Parse(String xmlString)
{
MiniXml xml = new MiniXml(xmlString);
return xml.Parse();
}
// Search for a child by tag path.
internal SecurityElement SearchForChildByPath(params String[] tags)
{
if(tags == null)
{
throw new ArgumentNullException("tags");
}
SecurityElement current = this;
foreach(String tag in tags)
{
current = current.SearchForChildByTag(tag);
if(current == null)
{
break;
}
}
return current;
}
// Get the value of an attribute by tag path. The last string
// in the path is the attribute name.
internal String AttributeByPath(params String[] tags)
{
if(tags == null)
{
throw new ArgumentNullException("tags");
}
SecurityElement current = this;
int posn = 0;
while(posn < (tags.Length - 1))
{
current = current.SearchForChildByTag(tags[posn]);
if(current == null)
{
return null;
}
++posn;
}
return current.Attribute(tags[posn]);
}
}; // class SecurityElement
#endif // CONFIG_PERMISSIONS || CONFIG_POLICY_OBJECTS || CONFIG_REMOTING
}; // namespace System.Security
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
namespace Apache.Ignite.Core.Impl.Binary
{
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Reflection;
using System.Text.RegularExpressions;
/// <summary>
/// Resolves types by name.
/// </summary>
internal class TypeResolver
{
/** Regex to parse generic types from binary configuration. Allows nested generics in type arguments. */
private static readonly Regex GenericTypeRegex =
new Regex(@"([^`,\[\]]*)(?:`[0-9]+)?(?:\[((?:(?<br>\[)|(?<-br>\])|[^\[\]]*)+)\])?", RegexOptions.Compiled);
/** Assemblies loaded in ReflectionOnly mode. */
private readonly Dictionary<string, Assembly> _reflectionOnlyAssemblies = new Dictionary<string, Assembly>();
/// <summary>
/// Resolve type by name.
/// </summary>
/// <param name="typeName">Name of the type.</param>
/// <param name="assemblyName">Optional, name of the assembly.</param>
/// <returns>
/// Resolved type.
/// </returns>
public Type ResolveType(string typeName, string assemblyName = null)
{
Debug.Assert(!string.IsNullOrEmpty(typeName));
return ResolveType(assemblyName, typeName, AppDomain.CurrentDomain.GetAssemblies())
?? ResolveTypeInReferencedAssemblies(assemblyName, typeName);
}
/// <summary>
/// Resolve type by name in specified assembly set.
/// </summary>
/// <param name="assemblyName">Name of the assembly.</param>
/// <param name="typeName">Name of the type.</param>
/// <param name="assemblies">Assemblies to look in.</param>
/// <returns>
/// Resolved type.
/// </returns>
private static Type ResolveType(string assemblyName, string typeName, ICollection<Assembly> assemblies)
{
return ResolveGenericType(assemblyName, typeName, assemblies) ??
ResolveNonGenericType(assemblyName, typeName, assemblies);
}
/// <summary>
/// Resolves non-generic type by searching provided assemblies.
/// </summary>
/// <param name="assemblyName">Name of the assembly.</param>
/// <param name="typeName">Name of the type.</param>
/// <param name="assemblies">The assemblies.</param>
/// <returns>Resolved type, or null.</returns>
private static Type ResolveNonGenericType(string assemblyName, string typeName, ICollection<Assembly> assemblies)
{
if (!string.IsNullOrEmpty(assemblyName))
assemblies = assemblies
.Where(x => x.FullName == assemblyName || x.GetName().Name == assemblyName).ToArray();
if (!assemblies.Any())
return null;
// Trim assembly qualification
var commaIdx = typeName.IndexOf(',');
if (commaIdx > 0)
typeName = typeName.Substring(0, commaIdx);
return assemblies.Select(a => a.GetType(typeName, false, false)).FirstOrDefault(type => type != null);
}
/// <summary>
/// Resolves the name of the generic type by resolving each generic arg separately
/// and substituting it's fully qualified name.
/// (Assembly.GetType finds generic types only when arguments are fully qualified).
/// </summary>
/// <param name="assemblyName">Name of the assembly.</param>
/// <param name="typeName">Name of the type.</param>
/// <param name="assemblies">Assemblies</param>
/// <returns>Fully qualified generic type name, or null if argument(s) could not be resolved.</returns>
private static Type ResolveGenericType(string assemblyName, string typeName, ICollection<Assembly> assemblies)
{
var match = GenericTypeRegex.Match(typeName);
if (!match.Success || !match.Groups[2].Success)
return null;
// Try to construct generic type; each generic arg can also be a generic type.
var genericArgs = GenericTypeRegex.Matches(match.Groups[2].Value)
.OfType<Match>().Select(m => m.Value).Where(v => !string.IsNullOrWhiteSpace(v))
.Select(v => ResolveType(null, TrimBrackets(v), assemblies)).ToArray();
if (genericArgs.Any(x => x == null))
return null;
var genericType = ResolveNonGenericType(assemblyName,
string.Format(CultureInfo.InvariantCulture, "{0}`{1}", match.Groups[1].Value, genericArgs.Length),
assemblies);
if (genericType == null)
return null;
return genericType.MakeGenericType(genericArgs);
}
/// <summary>
/// Trims the brackets from generic type arg.
/// </summary>
private static string TrimBrackets(string s)
{
return s.StartsWith("[", StringComparison.Ordinal) && s.EndsWith("]", StringComparison.Ordinal)
? s.Substring(1, s.Length - 2)
: s;
}
/// <summary>
/// Resolve type by name in non-loaded referenced assemblies.
/// </summary>
/// <param name="assemblyName">Name of the assembly.</param>
/// <param name="typeName">Name of the type.</param>
/// <returns>
/// Resolved type.
/// </returns>
private Type ResolveTypeInReferencedAssemblies(string assemblyName, string typeName)
{
ResolveEventHandler resolver = (sender, args) => GetReflectionOnlyAssembly(args.Name);
AppDomain.CurrentDomain.ReflectionOnlyAssemblyResolve += resolver;
try
{
var result = ResolveType(assemblyName, typeName, GetNotLoadedReferencedAssemblies().ToArray());
if (result == null)
return null;
// result is from ReflectionOnly assembly, load it properly into current domain
var asm = AppDomain.CurrentDomain.Load(result.Assembly.GetName());
return asm.GetType(result.FullName);
}
finally
{
AppDomain.CurrentDomain.ReflectionOnlyAssemblyResolve -= resolver;
}
}
/// <summary>
/// Gets the reflection only assembly.
/// </summary>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
private Assembly GetReflectionOnlyAssembly(string fullName)
{
Assembly result;
if (!_reflectionOnlyAssemblies.TryGetValue(fullName, out result))
{
try
{
result = Assembly.ReflectionOnlyLoad(fullName);
}
catch (Exception)
{
// Some assemblies may fail to load
result = null;
}
_reflectionOnlyAssemblies[fullName] = result;
}
return result;
}
/// <summary>
/// Recursively gets all referenced assemblies for current app domain, excluding those that are loaded.
/// </summary>
private IEnumerable<Assembly> GetNotLoadedReferencedAssemblies()
{
var roots = new Stack<Assembly>(AppDomain.CurrentDomain.GetAssemblies());
var visited = new HashSet<string>();
var loaded = new HashSet<string>(roots.Select(x => x.FullName));
while (roots.Any())
{
var asm = roots.Pop();
if (visited.Contains(asm.FullName))
continue;
if (!loaded.Contains(asm.FullName))
yield return asm;
visited.Add(asm.FullName);
foreach (var refAsm in asm.GetReferencedAssemblies()
.Where(x => !visited.Contains(x.FullName))
.Where(x => !loaded.Contains(x.FullName))
.Select(x => GetReflectionOnlyAssembly(x.FullName))
.Where(x => x != null))
roots.Push(refAsm);
}
}
}
}
| |
// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Collections;
using System.Diagnostics;
namespace HtmlToXamlDemo
{
/// <summary>
/// HtmlSchema class
/// maintains static information about HTML structure
/// can be used by HtmlParser to check conditions under which an element starts or ends, etc.
/// </summary>
internal class HtmlSchema
{
// ---------------------------------------------------------------------
//
// Constructors
//
// ---------------------------------------------------------------------
#region Constructors
/// <summary>
/// static constructor, initializes the ArrayLists
/// that hold the elements in various sub-components of the schema
/// e.g _htmlEmptyElements, etc.
/// </summary>
static HtmlSchema()
{
// initializes the list of all html elements
InitializeInlineElements();
InitializeBlockElements();
InitializeOtherOpenableElements();
// initialize empty elements list
InitializeEmptyElements();
// initialize list of elements closing on the outer element end
InitializeElementsClosingOnParentElementEnd();
// initalize list of elements that close when a new element starts
InitializeElementsClosingOnNewElementStart();
// Initialize character entities
InitializeHtmlCharacterEntities();
}
#endregion Constructors;
// ---------------------------------------------------------------------
//
// Internal Methods
//
// ---------------------------------------------------------------------
#region Internal Methods
/// <summary>
/// returns true when xmlElementName corresponds to empty element
/// </summary>
/// <param name="xmlElementName">
/// string representing name to test
/// </param>
internal static bool IsEmptyElement(string xmlElementName) => _htmlEmptyElements.Contains(xmlElementName.ToLower());
/// <summary>
/// returns true if xmlElementName represents a block formattinng element.
/// It used in an algorithm of transferring inline elements over block elements
/// in HtmlParser
/// </summary>
/// <param name="xmlElementName"></param>
/// <returns></returns>
internal static bool IsBlockElement(string xmlElementName) => _htmlBlockElements.Contains(xmlElementName);
/// <summary>
/// returns true if the xmlElementName represents an inline formatting element
/// </summary>
/// <param name="xmlElementName"></param>
/// <returns></returns>
internal static bool IsInlineElement(string xmlElementName) => _htmlInlineElements.Contains(xmlElementName);
/// <summary>
/// It is a list of known html elements which we
/// want to allow to produce bt HTML parser,
/// but don'tt want to act as inline, block or no-scope.
/// Presence in this list will allow to open
/// elements during html parsing, and adding the
/// to a tree produced by html parser.
/// </summary>
internal static bool IsKnownOpenableElement(string xmlElementName) => _htmlOtherOpenableElements.Contains(xmlElementName);
/// <summary>
/// returns true when xmlElementName closes when the outer element closes
/// this is true of elements with optional start tags
/// </summary>
/// <param name="xmlElementName">
/// string representing name to test
/// </param>
internal static bool ClosesOnParentElementEnd(string xmlElementName) => _htmlElementsClosingOnParentElementEnd.Contains(xmlElementName.ToLower());
/// <summary>
/// returns true if the current element closes when the new element, whose name has just been read, starts
/// </summary>
/// <param name="currentElementName">
/// string representing current element name
/// </param>
/// <param name="elementName"></param>
/// string representing name of the next element that will start
internal static bool ClosesOnNextElementStart(string currentElementName, string nextElementName)
{
Debug.Assert(currentElementName == currentElementName.ToLower());
switch (currentElementName)
{
case "colgroup":
return _htmlElementsClosingColgroup.Contains(nextElementName) && IsBlockElement(nextElementName);
case "dd":
return _htmlElementsClosingDd.Contains(nextElementName) && IsBlockElement(nextElementName);
case "dt":
return _htmlElementsClosingDt.Contains(nextElementName) && IsBlockElement(nextElementName);
case "li":
return _htmlElementsClosingLi.Contains(nextElementName);
case "p":
return IsBlockElement(nextElementName);
case "tbody":
return _htmlElementsClosingTbody.Contains(nextElementName);
case "tfoot":
return _htmlElementsClosingTfoot.Contains(nextElementName);
case "thead":
return _htmlElementsClosingThead.Contains(nextElementName);
case "tr":
return _htmlElementsClosingTr.Contains(nextElementName);
case "td":
return _htmlElementsClosingTd.Contains(nextElementName);
case "th":
return _htmlElementsClosingTh.Contains(nextElementName);
}
return false;
}
/// <summary>
/// returns true if the string passed as argument is an Html entity name
/// </summary>
/// <param name="entityName">
/// string to be tested for Html entity name
/// </param>
internal static bool IsEntity(string entityName)
{
// we do not convert entity strings to lowercase because these names are case-sensitive
if (_htmlCharacterEntities.Contains(entityName))
{
return true;
}
return false;
}
/// <summary>
/// returns the character represented by the entity name string which is passed as an argument, if the string is an
/// entity name
/// as specified in _htmlCharacterEntities, returns the character value of 0 otherwise
/// </summary>
/// <param name="entityName">
/// string representing entity name whose character value is desired
/// </param>
internal static char EntityCharacterValue(string entityName)
{
if (_htmlCharacterEntities.Contains(entityName))
{
return (char) _htmlCharacterEntities[entityName];
}
return (char) 0;
}
#endregion Internal Methods
// ---------------------------------------------------------------------
//
// Internal Properties
//
// ---------------------------------------------------------------------
#region Internal Properties
#endregion Internal Indexers
// ---------------------------------------------------------------------
//
// Private Methods
//
// ---------------------------------------------------------------------
#region Private Methods
private static void InitializeInlineElements()
{
_htmlInlineElements = new ArrayList
{
"a",
"abbr",
"acronym",
"address",
"b",
"bdo",
"big",
"button",
"code",
"del",
"dfn",
"em",
"font",
"i",
"ins",
"kbd",
"label",
"legend",
"q",
"s",
"samp",
"small",
"span",
"strike",
"strong",
"sub",
"sup",
"u",
"var"
};
// ???
// deleted text
// inserted text
// text to entered by a user
// ???
// short inline quotation
// strike-through text style
// Specifies a code sample
// indicates an instance of a program variable
}
private static void InitializeBlockElements()
{
_htmlBlockElements = new ArrayList
{
"blockquote",
"body",
"caption",
"center",
"cite",
"dd",
"dir",
"div",
"dl",
"dt",
"form",
"h1",
"h2",
"h3",
"h4",
"h5",
"h6",
"html",
"li",
"menu",
"ol",
"p",
"pre",
"table",
"tbody",
"td",
"textarea",
"tfoot",
"th",
"thead",
"tr",
"tt",
"ul"
};
// treat as UL element
// Not a block according to XHTML spec
// treat as UL element
// Renders text in a fixed-width font
}
/// <summary>
/// initializes _htmlEmptyElements with empty elements in HTML 4 spec at
/// http://www.w3.org/TR/REC-html40/index/elements.html
/// </summary>
private static void InitializeEmptyElements()
{
// Build a list of empty (no-scope) elements
// (element not requiring closing tags, and not accepting any content)
_htmlEmptyElements = new ArrayList
{
"area",
"base",
"basefont",
"br",
"col",
"frame",
"hr",
"img",
"input",
"isindex",
"link",
"meta",
"param"
};
}
private static void InitializeOtherOpenableElements()
{
// It is a list of known html elements which we
// want to allow to produce bt HTML parser,
// but don'tt want to act as inline, block or no-scope.
// Presence in this list will allow to open
// elements during html parsing, and adding the
// to a tree produced by html parser.
_htmlOtherOpenableElements = new ArrayList
{
"applet",
"base",
"basefont",
"colgroup",
"fieldset",
"frameset",
"head",
"iframe",
"map",
"noframes",
"noscript",
"object",
"optgroup",
"option",
"script",
"select",
"style",
"title"
};
//_htmlOtherOpenableElements.Add("form"); --> treated as block
}
/// <summary>
/// initializes _htmlElementsClosingOnParentElementEnd with the list of HTML 4 elements for which closing tags are
/// optional
/// we assume that for any element for which closing tags are optional, the element closes when it's outer element
/// (in which it is nested) does
/// </summary>
private static void InitializeElementsClosingOnParentElementEnd()
{
_htmlElementsClosingOnParentElementEnd = new ArrayList
{
"body",
"colgroup",
"dd",
"dt",
"head",
"html",
"li",
"p",
"tbody",
"td",
"tfoot",
"thead",
"th",
"tr"
};
}
private static void InitializeElementsClosingOnNewElementStart()
{
_htmlElementsClosingColgroup = new ArrayList {"colgroup", "tr", "thead", "tfoot", "tbody"};
_htmlElementsClosingDd = new ArrayList {"dd", "dt"};
// TODO: dd may end in other cases as well - if a new "p" starts, etc.
// TODO: these are the basic "legal" cases but there may be more recovery
_htmlElementsClosingDt = new ArrayList();
_htmlElementsClosingDd.Add("dd");
_htmlElementsClosingDd.Add("dt");
// TODO: dd may end in other cases as well - if a new "p" starts, etc.
// TODO: these are the basic "legal" cases but there may be more recovery
_htmlElementsClosingLi = new ArrayList {"li"};
// TODO: more complex recovery
_htmlElementsClosingTbody = new ArrayList {"tbody", "thead", "tfoot"};
// TODO: more complex recovery
_htmlElementsClosingTr = new ArrayList {"thead", "tfoot", "tbody", "tr"};
// NOTE: tr should not really close on a new thead
// because if there are rows before a thead, it is assumed to be in tbody, whose start tag is optional
// and thead can't come after tbody
// however, if we do encounter this, it's probably best to end the row and ignore the thead or treat
// it as part of the table
// TODO: more complex recovery
_htmlElementsClosingTd = new ArrayList {"td", "th", "tr", "tbody", "tfoot", "thead"};
// TODO: more complex recovery
_htmlElementsClosingTh = new ArrayList {"td", "th", "tr", "tbody", "tfoot", "thead"};
// TODO: more complex recovery
_htmlElementsClosingThead = new ArrayList {"tbody", "tfoot"};
// TODO: more complex recovery
_htmlElementsClosingTfoot = new ArrayList {"tbody", "thead"};
// although thead comes before tfoot, we add it because if it is found the tfoot should close
// and some recovery processing be done on the thead
// TODO: more complex recovery
}
/// <summary>
/// initializes _htmlCharacterEntities hashtable with the character corresponding to entity names
/// </summary>
private static void InitializeHtmlCharacterEntities()
{
_htmlCharacterEntities = new Hashtable
{
["Aacute"] = (char) 193,
["aacute"] = (char) 225,
["Acirc"] = (char) 194,
["acirc"] = (char) 226,
["acute"] = (char) 180,
["AElig"] = (char) 198,
["aelig"] = (char) 230,
["Agrave"] = (char) 192,
["agrave"] = (char) 224,
["alefsym"] = (char) 8501,
["Alpha"] = (char) 913,
["alpha"] = (char) 945,
["amp"] = (char) 38,
["and"] = (char) 8743,
["ang"] = (char) 8736,
["Aring"] = (char) 197,
["aring"] = (char) 229,
["asymp"] = (char) 8776,
["Atilde"] = (char) 195,
["atilde"] = (char) 227,
["Auml"] = (char) 196,
["auml"] = (char) 228,
["bdquo"] = (char) 8222,
["Beta"] = (char) 914,
["beta"] = (char) 946,
["brvbar"] = (char) 166,
["bull"] = (char) 8226,
["cap"] = (char) 8745,
["Ccedil"] = (char) 199,
["ccedil"] = (char) 231,
["cent"] = (char) 162,
["Chi"] = (char) 935,
["chi"] = (char) 967,
["circ"] = (char) 710,
["clubs"] = (char) 9827,
["cong"] = (char) 8773,
["copy"] = (char) 169,
["crarr"] = (char) 8629,
["cup"] = (char) 8746,
["curren"] = (char) 164,
["dagger"] = (char) 8224,
["Dagger"] = (char) 8225,
["darr"] = (char) 8595,
["dArr"] = (char) 8659,
["deg"] = (char) 176,
["Delta"] = (char) 916,
["delta"] = (char) 948,
["diams"] = (char) 9830,
["divide"] = (char) 247,
["Eacute"] = (char) 201,
["eacute"] = (char) 233,
["Ecirc"] = (char) 202,
["ecirc"] = (char) 234,
["Egrave"] = (char) 200,
["egrave"] = (char) 232,
["empty"] = (char) 8709,
["emsp"] = (char) 8195,
["ensp"] = (char) 8194,
["Epsilon"] = (char) 917,
["epsilon"] = (char) 949,
["equiv"] = (char) 8801,
["Eta"] = (char) 919,
["eta"] = (char) 951,
["ETH"] = (char) 208,
["eth"] = (char) 240,
["Euml"] = (char) 203,
["euml"] = (char) 235,
["euro"] = (char) 8364,
["exist"] = (char) 8707,
["fnof"] = (char) 402,
["forall"] = (char) 8704,
["frac12"] = (char) 189,
["frac14"] = (char) 188,
["frac34"] = (char) 190,
["frasl"] = (char) 8260,
["Gamma"] = (char) 915,
["gamma"] = (char) 947,
["ge"] = (char) 8805,
["gt"] = (char) 62,
["harr"] = (char) 8596,
["hArr"] = (char) 8660,
["hearts"] = (char) 9829,
["hellip"] = (char) 8230,
["Iacute"] = (char) 205,
["iacute"] = (char) 237,
["Icirc"] = (char) 206,
["icirc"] = (char) 238,
["iexcl"] = (char) 161,
["Igrave"] = (char) 204,
["igrave"] = (char) 236,
["image"] = (char) 8465,
["infin"] = (char) 8734,
["int"] = (char) 8747,
["Iota"] = (char) 921,
["iota"] = (char) 953,
["iquest"] = (char) 191,
["isin"] = (char) 8712,
["Iuml"] = (char) 207,
["iuml"] = (char) 239,
["Kappa"] = (char) 922,
["kappa"] = (char) 954,
["Lambda"] = (char) 923,
["lambda"] = (char) 955,
["lang"] = (char) 9001,
["laquo"] = (char) 171,
["larr"] = (char) 8592,
["lArr"] = (char) 8656,
["lceil"] = (char) 8968,
["ldquo"] = (char) 8220,
["le"] = (char) 8804,
["lfloor"] = (char) 8970,
["lowast"] = (char) 8727,
["loz"] = (char) 9674,
["lrm"] = (char) 8206,
["lsaquo"] = (char) 8249,
["lsquo"] = (char) 8216,
["lt"] = (char) 60,
["macr"] = (char) 175,
["mdash"] = (char) 8212,
["micro"] = (char) 181,
["middot"] = (char) 183,
["minus"] = (char) 8722,
["Mu"] = (char) 924,
["mu"] = (char) 956,
["nabla"] = (char) 8711,
["nbsp"] = (char) 160,
["ndash"] = (char) 8211,
["ne"] = (char) 8800,
["ni"] = (char) 8715,
["not"] = (char) 172,
["notin"] = (char) 8713,
["nsub"] = (char) 8836,
["Ntilde"] = (char) 209,
["ntilde"] = (char) 241,
["Nu"] = (char) 925,
["nu"] = (char) 957,
["Oacute"] = (char) 211,
["ocirc"] = (char) 244,
["OElig"] = (char) 338,
["oelig"] = (char) 339,
["Ograve"] = (char) 210,
["ograve"] = (char) 242,
["oline"] = (char) 8254,
["Omega"] = (char) 937,
["omega"] = (char) 969,
["Omicron"] = (char) 927,
["omicron"] = (char) 959,
["oplus"] = (char) 8853,
["or"] = (char) 8744,
["ordf"] = (char) 170,
["ordm"] = (char) 186,
["Oslash"] = (char) 216,
["oslash"] = (char) 248,
["Otilde"] = (char) 213,
["otilde"] = (char) 245,
["otimes"] = (char) 8855,
["Ouml"] = (char) 214,
["ouml"] = (char) 246,
["para"] = (char) 182,
["part"] = (char) 8706,
["permil"] = (char) 8240,
["perp"] = (char) 8869,
["Phi"] = (char) 934,
["phi"] = (char) 966,
["pi"] = (char) 960,
["piv"] = (char) 982,
["plusmn"] = (char) 177,
["pound"] = (char) 163,
["prime"] = (char) 8242,
["Prime"] = (char) 8243,
["prod"] = (char) 8719,
["prop"] = (char) 8733,
["Psi"] = (char) 936,
["psi"] = (char) 968,
["quot"] = (char) 34,
["radic"] = (char) 8730,
["rang"] = (char) 9002,
["raquo"] = (char) 187,
["rarr"] = (char) 8594,
["rArr"] = (char) 8658,
["rceil"] = (char) 8969,
["rdquo"] = (char) 8221,
["real"] = (char) 8476,
["reg"] = (char) 174,
["rfloor"] = (char) 8971,
["Rho"] = (char) 929,
["rho"] = (char) 961,
["rlm"] = (char) 8207,
["rsaquo"] = (char) 8250,
["rsquo"] = (char) 8217,
["sbquo"] = (char) 8218,
["Scaron"] = (char) 352,
["scaron"] = (char) 353,
["sdot"] = (char) 8901,
["sect"] = (char) 167,
["shy"] = (char) 173,
["Sigma"] = (char) 931,
["sigma"] = (char) 963,
["sigmaf"] = (char) 962,
["sim"] = (char) 8764,
["spades"] = (char) 9824,
["sub"] = (char) 8834,
["sube"] = (char) 8838,
["sum"] = (char) 8721,
["sup"] = (char) 8835,
["sup1"] = (char) 185,
["sup2"] = (char) 178,
["sup3"] = (char) 179,
["supe"] = (char) 8839,
["szlig"] = (char) 223,
["Tau"] = (char) 932,
["tau"] = (char) 964,
["there4"] = (char) 8756,
["Theta"] = (char) 920,
["theta"] = (char) 952,
["thetasym"] = (char) 977,
["thinsp"] = (char) 8201,
["THORN"] = (char) 222,
["thorn"] = (char) 254,
["tilde"] = (char) 732,
["times"] = (char) 215,
["trade"] = (char) 8482,
["Uacute"] = (char) 218,
["uacute"] = (char) 250,
["uarr"] = (char) 8593,
["uArr"] = (char) 8657,
["Ucirc"] = (char) 219,
["ucirc"] = (char) 251,
["Ugrave"] = (char) 217,
["ugrave"] = (char) 249,
["uml"] = (char) 168,
["upsih"] = (char) 978,
["Upsilon"] = (char) 933,
["upsilon"] = (char) 965,
["Uuml"] = (char) 220,
["uuml"] = (char) 252,
["weierp"] = (char) 8472,
["Xi"] = (char) 926,
["xi"] = (char) 958,
["Yacute"] = (char) 221,
["yacute"] = (char) 253,
["yen"] = (char) 165,
["Yuml"] = (char) 376,
["yuml"] = (char) 255,
["Zeta"] = (char) 918,
["zeta"] = (char) 950,
["zwj"] = (char) 8205,
["zwnj"] = (char) 8204
};
}
#endregion Private Methods
// ---------------------------------------------------------------------
//
// Private Fields
//
// ---------------------------------------------------------------------
#region Private Fields
// html element names
// this is an array list now, but we may want to make it a hashtable later for better performance
private static ArrayList _htmlInlineElements;
private static ArrayList _htmlBlockElements;
private static ArrayList _htmlOtherOpenableElements;
// list of html empty element names
private static ArrayList _htmlEmptyElements;
// names of html elements for which closing tags are optional, and close when the outer nested element closes
private static ArrayList _htmlElementsClosingOnParentElementEnd;
// names of elements that close certain optional closing tag elements when they start
// names of elements closing the colgroup element
private static ArrayList _htmlElementsClosingColgroup;
// names of elements closing the dd element
private static ArrayList _htmlElementsClosingDd;
// names of elements closing the dt element
private static ArrayList _htmlElementsClosingDt;
// names of elements closing the li element
private static ArrayList _htmlElementsClosingLi;
// names of elements closing the tbody element
private static ArrayList _htmlElementsClosingTbody;
// names of elements closing the td element
private static ArrayList _htmlElementsClosingTd;
// names of elements closing the tfoot element
private static ArrayList _htmlElementsClosingTfoot;
// names of elements closing the thead element
private static ArrayList _htmlElementsClosingThead;
// names of elements closing the th element
private static ArrayList _htmlElementsClosingTh;
// names of elements closing the tr element
private static ArrayList _htmlElementsClosingTr;
// html character entities hashtable
private static Hashtable _htmlCharacterEntities;
#endregion Private Fields
}
}
| |
// 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.
// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
//
//
//
// TaskCompletionSource<TResult> is the producer end of an unbound future. Its
// Task member may be distributed as the consumer end of the future.
//
// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
using System;
using System.Diagnostics;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using System.Runtime.ExceptionServices;
using System.Threading;
// Disable the "reference to volatile field not treated as volatile" error.
#pragma warning disable 0420
namespace System.Threading.Tasks
{
/// <summary>
/// Represents the producer side of a <see cref="T:System.Threading.Tasks.Task{TResult}"/> unbound to a
/// delegate, providing access to the consumer side through the <see cref="Task"/> property.
/// </summary>
/// <remarks>
/// <para>
/// It is often the case that a <see cref="T:System.Threading.Tasks.Task{TResult}"/> is desired to
/// represent another asynchronous operation.
/// <see cref="TaskCompletionSource{TResult}">TaskCompletionSource</see> is provided for this purpose. It enables
/// the creation of a task that can be handed out to consumers, and those consumers can use the members
/// of the task as they would any other. However, unlike most tasks, the state of a task created by a
/// TaskCompletionSource is controlled explicitly by the methods on TaskCompletionSource. This enables the
/// completion of the external asynchronous operation to be propagated to the underlying Task. The
/// separation also ensures that consumers are not able to transition the state without access to the
/// corresponding TaskCompletionSource.
/// </para>
/// <para>
/// All members of <see cref="TaskCompletionSource{TResult}"/> are thread-safe
/// and may be used from multiple threads concurrently.
/// </para>
/// </remarks>
/// <typeparam name="TResult">The type of the result value associated with this <see
/// cref="TaskCompletionSource{TResult}"/>.</typeparam>
public class TaskCompletionSource<TResult>
{
private readonly Task<TResult> _task;
/// <summary>
/// Creates a <see cref="TaskCompletionSource{TResult}"/>.
/// </summary>
public TaskCompletionSource()
{
_task = new Task<TResult>();
}
/// <summary>
/// Creates a <see cref="TaskCompletionSource{TResult}"/>
/// with the specified options.
/// </summary>
/// <remarks>
/// The <see cref="T:System.Threading.Tasks.Task{TResult}"/> created
/// by this instance and accessible through its <see cref="Task"/> property
/// will be instantiated using the specified <paramref name="creationOptions"/>.
/// </remarks>
/// <param name="creationOptions">The options to use when creating the underlying
/// <see cref="T:System.Threading.Tasks.Task{TResult}"/>.</param>
/// <exception cref="T:System.ArgumentOutOfRangeException">
/// The <paramref name="creationOptions"/> represent options invalid for use
/// with a <see cref="TaskCompletionSource{TResult}"/>.
/// </exception>
public TaskCompletionSource(TaskCreationOptions creationOptions)
: this(null, creationOptions)
{
}
/// <summary>
/// Creates a <see cref="TaskCompletionSource{TResult}"/>
/// with the specified state.
/// </summary>
/// <param name="state">The state to use as the underlying
/// <see cref="T:System.Threading.Tasks.Task{TResult}"/>'s AsyncState.</param>
public TaskCompletionSource(object state)
: this(state, TaskCreationOptions.None)
{
}
/// <summary>
/// Creates a <see cref="TaskCompletionSource{TResult}"/> with
/// the specified state and options.
/// </summary>
/// <param name="creationOptions">The options to use when creating the underlying
/// <see cref="T:System.Threading.Tasks.Task{TResult}"/>.</param>
/// <param name="state">The state to use as the underlying
/// <see cref="T:System.Threading.Tasks.Task{TResult}"/>'s AsyncState.</param>
/// <exception cref="T:System.ArgumentOutOfRangeException">
/// The <paramref name="creationOptions"/> represent options invalid for use
/// with a <see cref="TaskCompletionSource{TResult}"/>.
/// </exception>
public TaskCompletionSource(object state, TaskCreationOptions creationOptions)
{
_task = new Task<TResult>(state, creationOptions);
}
/// <summary>
/// Gets the <see cref="T:System.Threading.Tasks.Task{TResult}"/> created
/// by this <see cref="TaskCompletionSource{TResult}"/>.
/// </summary>
/// <remarks>
/// This property enables a consumer access to the <see
/// cref="T:System.Threading.Tasks.Task{TResult}"/> that is controlled by this instance.
/// The <see cref="SetResult"/>, <see cref="SetException(System.Exception)"/>,
/// <see cref="SetException(System.Collections.Generic.IEnumerable{System.Exception})"/>, and <see cref="SetCanceled"/>
/// methods (and their "Try" variants) on this instance all result in the relevant state
/// transitions on this underlying Task.
/// </remarks>
public Task<TResult> Task => _task;
/// <summary>Spins until the underlying task is completed.</summary>
/// <remarks>This should only be called if the task is in the process of being completed by another thread.</remarks>
private void SpinUntilCompleted()
{
// Spin wait until the completion is finalized by another thread.
var sw = new SpinWait();
while (!_task.IsCompleted)
sw.SpinOnce();
}
/// <summary>
/// Attempts to transition the underlying
/// <see cref="T:System.Threading.Tasks.Task{TResult}"/> into the
/// <see cref="System.Threading.Tasks.TaskStatus.Faulted">Faulted</see>
/// state.
/// </summary>
/// <param name="exception">The exception to bind to this <see
/// cref="T:System.Threading.Tasks.Task{TResult}"/>.</param>
/// <returns>True if the operation was successful; otherwise, false.</returns>
/// <remarks>This operation will return false if the
/// <see cref="T:System.Threading.Tasks.Task{TResult}"/> is already in one
/// of the three final states:
/// <see cref="System.Threading.Tasks.TaskStatus.RanToCompletion">RanToCompletion</see>,
/// <see cref="System.Threading.Tasks.TaskStatus.Faulted">Faulted</see>, or
/// <see cref="System.Threading.Tasks.TaskStatus.Canceled">Canceled</see>.
/// </remarks>
/// <exception cref="T:System.ArgumentNullException">The <paramref name="exception"/> argument is null.</exception>
/// <exception cref="T:System.ObjectDisposedException">The <see cref="Task"/> was disposed.</exception>
public bool TrySetException(Exception exception)
{
if (exception == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.exception);
bool rval = _task.TrySetException(exception);
if (!rval && !_task.IsCompleted) SpinUntilCompleted();
return rval;
}
/// <summary>
/// Attempts to transition the underlying
/// <see cref="T:System.Threading.Tasks.Task{TResult}"/> into the
/// <see cref="System.Threading.Tasks.TaskStatus.Faulted">Faulted</see>
/// state.
/// </summary>
/// <param name="exceptions">The collection of exceptions to bind to this <see
/// cref="T:System.Threading.Tasks.Task{TResult}"/>.</param>
/// <returns>True if the operation was successful; otherwise, false.</returns>
/// <remarks>This operation will return false if the
/// <see cref="T:System.Threading.Tasks.Task{TResult}"/> is already in one
/// of the three final states:
/// <see cref="System.Threading.Tasks.TaskStatus.RanToCompletion">RanToCompletion</see>,
/// <see cref="System.Threading.Tasks.TaskStatus.Faulted">Faulted</see>, or
/// <see cref="System.Threading.Tasks.TaskStatus.Canceled">Canceled</see>.
/// </remarks>
/// <exception cref="T:System.ArgumentNullException">The <paramref name="exceptions"/> argument is null.</exception>
/// <exception cref="T:System.ArgumentException">There are one or more null elements in <paramref name="exceptions"/>.</exception>
/// <exception cref="T:System.ArgumentException">The <paramref name="exceptions"/> collection is empty.</exception>
/// <exception cref="T:System.ObjectDisposedException">The <see cref="Task"/> was disposed.</exception>
public bool TrySetException(IEnumerable<Exception> exceptions)
{
if (exceptions == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.exceptions);
List<Exception> defensiveCopy = new List<Exception>();
foreach (Exception e in exceptions)
{
if (e == null)
ThrowHelper.ThrowArgumentException(ExceptionResource.TaskCompletionSourceT_TrySetException_NullException, ExceptionArgument.exceptions);
defensiveCopy.Add(e);
}
if (defensiveCopy.Count == 0)
ThrowHelper.ThrowArgumentException(ExceptionResource.TaskCompletionSourceT_TrySetException_NoExceptions, ExceptionArgument.exceptions);
bool rval = _task.TrySetException(defensiveCopy);
if (!rval && !_task.IsCompleted) SpinUntilCompleted();
return rval;
}
/// <summary>
/// Transitions the underlying
/// <see cref="T:System.Threading.Tasks.Task{TResult}"/> into the
/// <see cref="System.Threading.Tasks.TaskStatus.Faulted">Faulted</see>
/// state.
/// </summary>
/// <param name="exception">The exception to bind to this <see
/// cref="T:System.Threading.Tasks.Task{TResult}"/>.</param>
/// <exception cref="T:System.ArgumentNullException">The <paramref name="exception"/> argument is null.</exception>
/// <exception cref="T:System.InvalidOperationException">
/// The underlying <see cref="T:System.Threading.Tasks.Task{TResult}"/> is already in one
/// of the three final states:
/// <see cref="System.Threading.Tasks.TaskStatus.RanToCompletion">RanToCompletion</see>,
/// <see cref="System.Threading.Tasks.TaskStatus.Faulted">Faulted</see>, or
/// <see cref="System.Threading.Tasks.TaskStatus.Canceled">Canceled</see>.
/// </exception>
/// <exception cref="T:System.ObjectDisposedException">The <see cref="Task"/> was disposed.</exception>
public void SetException(Exception exception)
{
if (exception == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.exception);
if (!TrySetException(exception))
{
ThrowHelper.ThrowInvalidOperationException(ExceptionResource.TaskT_TransitionToFinal_AlreadyCompleted);
}
}
/// <summary>
/// Transitions the underlying
/// <see cref="T:System.Threading.Tasks.Task{TResult}"/> into the
/// <see cref="System.Threading.Tasks.TaskStatus.Faulted">Faulted</see>
/// state.
/// </summary>
/// <param name="exceptions">The collection of exceptions to bind to this <see
/// cref="T:System.Threading.Tasks.Task{TResult}"/>.</param>
/// <exception cref="T:System.ArgumentNullException">The <paramref name="exceptions"/> argument is null.</exception>
/// <exception cref="T:System.ArgumentException">There are one or more null elements in <paramref name="exceptions"/>.</exception>
/// <exception cref="T:System.InvalidOperationException">
/// The underlying <see cref="T:System.Threading.Tasks.Task{TResult}"/> is already in one
/// of the three final states:
/// <see cref="System.Threading.Tasks.TaskStatus.RanToCompletion">RanToCompletion</see>,
/// <see cref="System.Threading.Tasks.TaskStatus.Faulted">Faulted</see>, or
/// <see cref="System.Threading.Tasks.TaskStatus.Canceled">Canceled</see>.
/// </exception>
/// <exception cref="T:System.ObjectDisposedException">The <see cref="Task"/> was disposed.</exception>
public void SetException(IEnumerable<Exception> exceptions)
{
if (!TrySetException(exceptions))
{
ThrowHelper.ThrowInvalidOperationException(ExceptionResource.TaskT_TransitionToFinal_AlreadyCompleted);
}
}
/// <summary>
/// Attempts to transition the underlying
/// <see cref="T:System.Threading.Tasks.Task{TResult}"/> into the
/// <see cref="System.Threading.Tasks.TaskStatus.RanToCompletion">RanToCompletion</see>
/// state.
/// </summary>
/// <param name="result">The result value to bind to this <see
/// cref="T:System.Threading.Tasks.Task{TResult}"/>.</param>
/// <returns>True if the operation was successful; otherwise, false.</returns>
/// <remarks>This operation will return false if the
/// <see cref="T:System.Threading.Tasks.Task{TResult}"/> is already in one
/// of the three final states:
/// <see cref="System.Threading.Tasks.TaskStatus.RanToCompletion">RanToCompletion</see>,
/// <see cref="System.Threading.Tasks.TaskStatus.Faulted">Faulted</see>, or
/// <see cref="System.Threading.Tasks.TaskStatus.Canceled">Canceled</see>.
/// </remarks>
/// <exception cref="T:System.ObjectDisposedException">The <see cref="Task"/> was disposed.</exception>
public bool TrySetResult(TResult result)
{
bool rval = _task.TrySetResult(result);
if (!rval) SpinUntilCompleted();
return rval;
}
/// <summary>
/// Transitions the underlying
/// <see cref="T:System.Threading.Tasks.Task{TResult}"/> into the
/// <see cref="System.Threading.Tasks.TaskStatus.RanToCompletion">RanToCompletion</see>
/// state.
/// </summary>
/// <param name="result">The result value to bind to this <see
/// cref="T:System.Threading.Tasks.Task{TResult}"/>.</param>
/// <exception cref="T:System.InvalidOperationException">
/// The underlying <see cref="T:System.Threading.Tasks.Task{TResult}"/> is already in one
/// of the three final states:
/// <see cref="System.Threading.Tasks.TaskStatus.RanToCompletion">RanToCompletion</see>,
/// <see cref="System.Threading.Tasks.TaskStatus.Faulted">Faulted</see>, or
/// <see cref="System.Threading.Tasks.TaskStatus.Canceled">Canceled</see>.
/// </exception>
/// <exception cref="T:System.ObjectDisposedException">The <see cref="Task"/> was disposed.</exception>
public void SetResult(TResult result)
{
if (!TrySetResult(result))
ThrowHelper.ThrowInvalidOperationException(ExceptionResource.TaskT_TransitionToFinal_AlreadyCompleted);
}
/// <summary>
/// Attempts to transition the underlying
/// <see cref="T:System.Threading.Tasks.Task{TResult}"/> into the
/// <see cref="System.Threading.Tasks.TaskStatus.Canceled">Canceled</see>
/// state.
/// </summary>
/// <returns>True if the operation was successful; otherwise, false.</returns>
/// <remarks>This operation will return false if the
/// <see cref="T:System.Threading.Tasks.Task{TResult}"/> is already in one
/// of the three final states:
/// <see cref="System.Threading.Tasks.TaskStatus.RanToCompletion">RanToCompletion</see>,
/// <see cref="System.Threading.Tasks.TaskStatus.Faulted">Faulted</see>, or
/// <see cref="System.Threading.Tasks.TaskStatus.Canceled">Canceled</see>.
/// </remarks>
/// <exception cref="T:System.ObjectDisposedException">The <see cref="Task"/> was disposed.</exception>
public bool TrySetCanceled()
{
return TrySetCanceled(default);
}
// Enables a token to be stored into the canceled task
public bool TrySetCanceled(CancellationToken cancellationToken)
{
bool rval = _task.TrySetCanceled(cancellationToken);
if (!rval && !_task.IsCompleted) SpinUntilCompleted();
return rval;
}
/// <summary>
/// Transitions the underlying
/// <see cref="T:System.Threading.Tasks.Task{TResult}"/> into the
/// <see cref="System.Threading.Tasks.TaskStatus.Canceled">Canceled</see>
/// state.
/// </summary>
/// <exception cref="T:System.InvalidOperationException">
/// The underlying <see cref="T:System.Threading.Tasks.Task{TResult}"/> is already in one
/// of the three final states:
/// <see cref="System.Threading.Tasks.TaskStatus.RanToCompletion">RanToCompletion</see>,
/// <see cref="System.Threading.Tasks.TaskStatus.Faulted">Faulted</see>, or
/// <see cref="System.Threading.Tasks.TaskStatus.Canceled">Canceled</see>.
/// </exception>
/// <exception cref="T:System.ObjectDisposedException">The <see cref="Task"/> was disposed.</exception>
public void SetCanceled()
{
if (!TrySetCanceled())
ThrowHelper.ThrowInvalidOperationException(ExceptionResource.TaskT_TransitionToFinal_AlreadyCompleted);
}
}
}
| |
// "Therefore those skilled at the unorthodox
// are infinite as heaven and earth,
// inexhaustible as the great rivers.
// When they come to an end,
// they begin again,
// like the days and months;
// they die and are reborn,
// like the four seasons."
//
// - Sun Tsu,
// "The Art of War"
using System;
using System.Collections.Generic;
using System.Globalization;
using Avalonia;
using Avalonia.Media;
using TheArtOfDev.HtmlRenderer.Adapters;
using TheArtOfDev.HtmlRenderer.Adapters.Entities;
using TheArtOfDev.HtmlRenderer.Core.Utils;
using TheArtOfDev.HtmlRenderer.Avalonia.Utilities;
namespace TheArtOfDev.HtmlRenderer.Avalonia.Adapters
{
/// <summary>
/// Adapter for Avalonia Graphics.
/// </summary>
internal sealed class GraphicsAdapter : RGraphics
{
#region Fields and Consts
/// <summary>
/// The wrapped Avalonia graphics object
/// </summary>
private readonly DrawingContext _g;
/// <summary>
/// if to release the graphics object on dispose
/// </summary>
private readonly bool _releaseGraphics;
#endregion
private readonly Stack<IDisposable> _clipStack = new Stack<IDisposable>();
/// <summary>
/// Init.
/// </summary>
/// <param name="g">the Avalonia graphics object to use</param>
/// <param name="initialClip">the initial clip of the graphics</param>
/// <param name="releaseGraphics">optional: if to release the graphics object on dispose (default - false)</param>
public GraphicsAdapter(DrawingContext g, RRect initialClip, bool releaseGraphics = false)
: base(AvaloniaAdapter.Instance, initialClip)
{
ArgChecker.AssertArgNotNull(g, "g");
_g = g;
_releaseGraphics = releaseGraphics;
}
/// <summary>
/// Init.
/// </summary>
public GraphicsAdapter()
: base(AvaloniaAdapter.Instance, RRect.Empty)
{
_g = null;
_releaseGraphics = false;
}
public override void PopClip()
{
_clipStack.Pop()?.Dispose();
}
public override void PushClip(RRect rect)
{
_clipStack.Push(_g.PushClip(Util.Convert(rect)));
//_clipStack.Push(rect);
//_g.PushClip(new RectangleGeometry(Utils.Convert(rect)));
}
public override void PushClipExclude(RRect rect)
{
_clipStack.Push(null);
//TODO: Implement exclude rect, see #128
//var geometry = new CombinedGeometry();
//geometry.Geometry1 = new RectangleGeometry(Utils.Convert(_clipStack.Peek()));
//geometry.Geometry2 = new RectangleGeometry(Utils.Convert(rect));
//geometry.GeometryCombineMode = GeometryCombineMode.Exclude;
//_clipStack.Push(_clipStack.Peek());
//_g.PushClip(geometry);
}
public override Object SetAntiAliasSmoothingMode()
{
return null;
}
public override void ReturnPreviousSmoothingMode(Object prevMode)
{ }
public override RSize MeasureString(string str, RFont font)
{
var text = GetText(str, font);
var measure = text.Measure();
return new RSize(measure.Width, measure.Height);
}
FormattedText GetText(string str, RFont font)
{
var f = ((FontAdapter)font);
return new FormattedText(str, f.Name, font.Size, f.FontStyle, TextAlignment.Left, f.Weight);
}
public override void MeasureString(string str, RFont font, double maxWidth, out int charFit, out double charFitWidth)
{
var text = GetText(str, font);
var fullLength = text.Measure().Width;
if (fullLength < maxWidth)
{
charFitWidth = fullLength;
charFit = str.Length;
return;
}
int lastLen = 0;
double lastMeasure = 0;
BinarySearch(len =>
{
text = GetText(str.Substring(0, len), font);
var size = text.Measure().Width;
lastMeasure = size;
lastLen = len;
if (size <= maxWidth)
return -1;
return 1;
}, 0, str.Length);
if (lastMeasure > maxWidth)
{
lastLen--;
lastMeasure = GetText(str.Substring(0, lastLen), font).Measure().Width;
}
charFit = lastLen;
charFitWidth = lastMeasure;
}
private static int BinarySearch(Func<int, int> condition, int start, int end)
{
do
{
int ind = start + (end - start)/2;
int res = condition(ind);
if (res == 0)
return ind;
else if (res > 0)
{
if (start != ind)
start = ind;
else
start = ind + 1;
}
else
end = ind;
} while (end > start);
return -1;
}
public override void DrawString(string str, RFont font, RColor color, RPoint point, RSize size, bool rtl)
{
var text = GetText(str, font);
text.Constraint = Util.Convert(size);
_g.DrawText(new SolidColorBrush(Util.Convert(color)), Util.Convert(point), text);
}
public override RBrush GetTextureBrush(RImage image, RRect dstRect, RPoint translateTransformLocation)
{
//TODO: Implement texture brush
return AvaloniaAdapter.Instance.GetSolidBrush(Util.Convert(Colors.Magenta));
//var brush = new ImageBrush(((ImageAdapter)image).Image);
//brush.Stretch = Stretch.None;
//brush.TileMode = TileMode.Tile;
//brush.Viewport = Utils.Convert(dstRect);
//brush.ViewportUnits = BrushMappingMode.Absolute;
//brush.Transform = new TranslateTransform(translateTransformLocation.X, translateTransformLocation.Y);
//brush.Freeze();
//return new BrushAdapter(brush);
}
public override RGraphicsPath GetGraphicsPath()
{
return new GraphicsPathAdapter();
}
public override void Dispose()
{
while (_clipStack.Count != 0)
PopClip();
if (_releaseGraphics)
_g.Dispose();
}
#region Delegate graphics methods
public override void DrawLine(RPen pen, double x1, double y1, double x2, double y2)
{
x1 = (int)x1;
x2 = (int)x2;
y1 = (int)y1;
y2 = (int)y2;
var adj = pen.Width;
if (Math.Abs(x1 - x2) < .1 && Math.Abs(adj % 2 - 1) < .1)
{
x1 += .5;
x2 += .5;
}
if (Math.Abs(y1 - y2) < .1 && Math.Abs(adj % 2 - 1) < .1)
{
y1 += .5;
y2 += .5;
}
_g.DrawLine(((PenAdapter)pen).CreatePen(), new Point(x1, y1), new Point(x2, y2));
}
public override void DrawRectangle(RPen pen, double x, double y, double width, double height)
{
var adj = pen.Width;
if (Math.Abs(adj % 2 - 1) < .1)
{
x += .5;
y += .5;
}
_g.DrawRectangle(((PenAdapter) pen).CreatePen(), new Rect(x, y, width, height));
}
public override void DrawRectangle(RBrush brush, double x, double y, double width, double height)
{
_g.FillRectangle(((BrushAdapter) brush).Brush, new Rect(x, y, width, height));
}
public override void DrawImage(RImage image, RRect destRect, RRect srcRect)
{
_g.DrawImage(((ImageAdapter) image).Image, 1, Util.Convert(srcRect), Util.Convert(destRect));
}
public override void DrawImage(RImage image, RRect destRect)
{
_g.DrawImage(((ImageAdapter) image).Image, 1, new Rect(0, 0, image.Width, image.Height),
Util.Convert(destRect));
}
public override void DrawPath(RPen pen, RGraphicsPath path)
{
_g.DrawGeometry(null, ((PenAdapter)pen).CreatePen(), ((GraphicsPathAdapter)path).GetClosedGeometry());
}
public override void DrawPath(RBrush brush, RGraphicsPath path)
{
_g.DrawGeometry(((BrushAdapter)brush).Brush, null, ((GraphicsPathAdapter)path).GetClosedGeometry());
}
public override void DrawPolygon(RBrush brush, RPoint[] points)
{
if (points != null && points.Length > 0)
{
var g = new StreamGeometry();
using (var context = g.Open())
{
context.BeginFigure(Util.Convert(points[0]), true);
for (int i = 1; i < points.Length; i++)
context.LineTo(Util.Convert(points[i]));
context.EndFigure(false);
}
_g.DrawGeometry(((BrushAdapter)brush).Brush, null, g);
}
}
#endregion
}
}
| |
// Copyright (c) .NET Core Community. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Data;
using System.Threading;
using System.Threading.Tasks;
using DotNetCore.CAP.Internal;
using DotNetCore.CAP.Messages;
using DotNetCore.CAP.Monitoring;
using DotNetCore.CAP.Persistence;
using DotNetCore.CAP.Serialization;
using Microsoft.Data.SqlClient;
using Microsoft.EntityFrameworkCore.Storage;
using Microsoft.Extensions.Options;
namespace DotNetCore.CAP.SqlServer
{
public class SqlServerDataStorage : IDataStorage
{
private readonly IOptions<CapOptions> _capOptions;
private readonly IOptions<SqlServerOptions> _options;
private readonly IStorageInitializer _initializer;
private readonly ISerializer _serializer;
private readonly string _pubName;
private readonly string _recName;
public SqlServerDataStorage(
IOptions<CapOptions> capOptions,
IOptions<SqlServerOptions> options,
IStorageInitializer initializer,
ISerializer serializer)
{
_options = options;
_initializer = initializer;
_capOptions = capOptions;
_serializer = serializer;
_pubName = initializer.GetPublishedTableName();
_recName = initializer.GetReceivedTableName();
}
public async Task ChangePublishStateAsync(MediumMessage message, StatusName state) =>
await ChangeMessageStateAsync(_pubName, message, state);
public async Task ChangeReceiveStateAsync(MediumMessage message, StatusName state) =>
await ChangeMessageStateAsync(_recName, message, state);
public MediumMessage StoreMessage(string name, Message content, object? dbTransaction = null)
{
var sql = $"INSERT INTO {_pubName} ([Id],[Version],[Name],[Content],[Retries],[Added],[ExpiresAt],[StatusName])" +
$"VALUES(@Id,'{_options.Value.Version}',@Name,@Content,@Retries,@Added,@ExpiresAt,@StatusName);";
var message = new MediumMessage
{
DbId = content.GetId(),
Origin = content,
Content = _serializer.Serialize(content),
Added = DateTime.Now,
ExpiresAt = null,
Retries = 0
};
object[] sqlParams =
{
new SqlParameter("@Id", message.DbId),
new SqlParameter("@Name", name),
new SqlParameter("@Content", message.Content),
new SqlParameter("@Retries", message.Retries),
new SqlParameter("@Added", message.Added),
new SqlParameter("@ExpiresAt", message.ExpiresAt.HasValue ? (object)message.ExpiresAt.Value : DBNull.Value),
new SqlParameter("@StatusName", nameof(StatusName.Scheduled))
};
if (dbTransaction == null)
{
using var connection = new SqlConnection(_options.Value.ConnectionString);
connection.ExecuteNonQuery(sql, sqlParams: sqlParams);
}
else
{
var dbTrans = dbTransaction as IDbTransaction;
if (dbTrans == null && dbTransaction is IDbContextTransaction dbContextTrans)
dbTrans = dbContextTrans.GetDbTransaction();
var conn = dbTrans?.Connection;
conn!.ExecuteNonQuery(sql, dbTrans, sqlParams);
}
return message;
}
public void StoreReceivedExceptionMessage(string name, string group, string content)
{
object[] sqlParams =
{
new SqlParameter("@Id", SnowflakeId.Default().NextId().ToString()),
new SqlParameter("@Name", name),
new SqlParameter("@Group", group),
new SqlParameter("@Content", content),
new SqlParameter("@Retries", _capOptions.Value.FailedRetryCount),
new SqlParameter("@Added", DateTime.Now),
new SqlParameter("@ExpiresAt", DateTime.Now.AddDays(15)),
new SqlParameter("@StatusName", nameof(StatusName.Failed))
};
StoreReceivedMessage(sqlParams);
}
public MediumMessage StoreReceivedMessage(string name, string group, Message message)
{
var mdMessage = new MediumMessage
{
DbId = SnowflakeId.Default().NextId().ToString(),
Origin = message,
Added = DateTime.Now,
ExpiresAt = null,
Retries = 0
};
object[] sqlParams =
{
new SqlParameter("@Id", mdMessage.DbId),
new SqlParameter("@Name", name),
new SqlParameter("@Group", group),
new SqlParameter("@Content", _serializer.Serialize(mdMessage.Origin)),
new SqlParameter("@Retries", mdMessage.Retries),
new SqlParameter("@Added", mdMessage.Added),
new SqlParameter("@ExpiresAt", mdMessage.ExpiresAt.HasValue ? mdMessage.ExpiresAt.Value : DBNull.Value),
new SqlParameter("@StatusName", nameof(StatusName.Scheduled))
};
StoreReceivedMessage(sqlParams);
return mdMessage;
}
public async Task<int> DeleteExpiresAsync(string table, DateTime timeout, int batchCount = 1000,
CancellationToken token = default)
{
await using var connection = new SqlConnection(_options.Value.ConnectionString);
return connection.ExecuteNonQuery(
$"DELETE TOP (@batchCount) FROM {table} WITH (readpast) WHERE ExpiresAt < @timeout;", null,
new SqlParameter("@timeout", timeout), new SqlParameter("@batchCount", batchCount));
}
public async Task<IEnumerable<MediumMessage>> GetPublishedMessagesOfNeedRetry() =>
await GetMessagesOfNeedRetryAsync(_pubName);
public async Task<IEnumerable<MediumMessage>> GetReceivedMessagesOfNeedRetry() =>
await GetMessagesOfNeedRetryAsync(_recName);
public IMonitoringApi GetMonitoringApi()
{
return new SqlServerMonitoringApi(_options, _initializer);
}
private async Task ChangeMessageStateAsync(string tableName, MediumMessage message, StatusName state)
{
var sql =
$"UPDATE {tableName} SET Content=@Content, Retries=@Retries,ExpiresAt=@ExpiresAt,StatusName=@StatusName WHERE Id=@Id";
object[] sqlParams =
{
new SqlParameter("@Id", message.DbId),
new SqlParameter("@Content", _serializer.Serialize(message.Origin)),
new SqlParameter("@Retries", message.Retries),
new SqlParameter("@ExpiresAt", message.ExpiresAt),
new SqlParameter("@StatusName", state.ToString("G"))
};
await using var connection = new SqlConnection(_options.Value.ConnectionString);
connection.ExecuteNonQuery(sql, sqlParams: sqlParams);
}
private void StoreReceivedMessage(object[] sqlParams)
{
var sql =
$"INSERT INTO {_recName}([Id],[Version],[Name],[Group],[Content],[Retries],[Added],[ExpiresAt],[StatusName])" +
$"VALUES(@Id,'{_capOptions.Value.Version}',@Name,@Group,@Content,@Retries,@Added,@ExpiresAt,@StatusName);";
using var connection = new SqlConnection(_options.Value.ConnectionString);
connection.ExecuteNonQuery(sql, sqlParams: sqlParams);
}
private async Task<IEnumerable<MediumMessage>> GetMessagesOfNeedRetryAsync(string tableName)
{
var fourMinAgo = DateTime.Now.AddMinutes(-4).ToString("O");
var sql =
$"SELECT TOP (200) Id, Content, Retries, Added FROM {tableName} WITH (readpast) WHERE Retries<{_capOptions.Value.FailedRetryCount} " +
$"AND Version='{_capOptions.Value.Version}' AND Added<'{fourMinAgo}' AND (StatusName = '{StatusName.Failed}' OR StatusName = '{StatusName.Scheduled}')";
List<MediumMessage> result;
await using (var connection = new SqlConnection(_options.Value.ConnectionString))
{
result = connection.ExecuteReader(sql, reader =>
{
var messages = new List<MediumMessage>();
while (reader.Read())
{
messages.Add(new MediumMessage
{
DbId = reader.GetInt64(0).ToString(),
Origin = _serializer.Deserialize(reader.GetString(1))!,
Retries = reader.GetInt32(2),
Added = reader.GetDateTime(3)
});
}
return messages;
});
}
return result;
}
}
}
| |
// 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.
#pragma warning disable 0420
// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
//
// ThreadLocal.cs
//
//
// A class that provides a simple, lightweight implementation of thread-local lazy-initialization, where a value is initialized once per accessing
// thread; this provides an alternative to using a ThreadStatic static variable and having
// to check the variable prior to every access to see if it's been initialized.
//
//
//
// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
using System.Diagnostics;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
namespace System.Threading
{
/// <summary>
/// Provides thread-local storage of data.
/// </summary>
/// <typeparam name="T">Specifies the type of data stored per-thread.</typeparam>
/// <remarks>
/// <para>
/// With the exception of <see cref="Dispose()"/>, all public and protected members of
/// <see cref="ThreadLocal{T}"/> are thread-safe and may be used
/// concurrently from multiple threads.
/// </para>
/// </remarks>
[DebuggerTypeProxy(typeof(SystemThreading_ThreadLocalDebugView<>))]
[DebuggerDisplay("IsValueCreated={IsValueCreated}, Value={ValueForDebugDisplay}, Count={ValuesCountForDebugDisplay}")]
public class ThreadLocal<T> : IDisposable
{
// a delegate that returns the created value, if null the created value will be default(T)
private Func<T> m_valueFactory;
//
// ts_slotArray is a table of thread-local values for all ThreadLocal<T> instances
//
// So, when a thread reads ts_slotArray, it gets back an array of *all* ThreadLocal<T> values for this thread and this T.
// The slot relevant to this particular ThreadLocal<T> instance is determined by the m_idComplement instance field stored in
// the ThreadLocal<T> instance.
//
[ThreadStatic]
static LinkedSlotVolatile[] ts_slotArray;
[ThreadStatic]
static FinalizationHelper ts_finalizationHelper;
// Slot ID of this ThreadLocal<> instance. We store a bitwise complement of the ID (that is ~ID), which allows us to distinguish
// between the case when ID is 0 and an incompletely initialized object, either due to a thread abort in the constructor, or
// possibly due to a memory model issue in user code.
private int m_idComplement;
// This field is set to true when the constructor completes. That is helpful for recognizing whether a constructor
// threw an exception - either due to invalid argument or due to a thread abort. Finally, the field is set to false
// when the instance is disposed.
private volatile bool m_initialized;
// IdManager assigns and reuses slot IDs. Additionally, the object is also used as a global lock.
private static IdManager s_idManager = new IdManager();
// A linked list of all values associated with this ThreadLocal<T> instance.
// We create a dummy head node. That allows us to remove any (non-dummy) node without having to locate the m_linkedSlot field.
private LinkedSlot m_linkedSlot = new LinkedSlot(null);
// Whether the Values property is supported
private bool m_trackAllValues;
/// <summary>
/// Initializes the <see cref="System.Threading.ThreadLocal{T}"/> instance.
/// </summary>
public ThreadLocal()
{
Initialize(null, false);
}
/// <summary>
/// Initializes the <see cref="System.Threading.ThreadLocal{T}"/> instance.
/// </summary>
/// <param name="trackAllValues">Whether to track all values set on the instance and expose them through the Values property.</param>
public ThreadLocal(bool trackAllValues)
{
Initialize(null, trackAllValues);
}
/// <summary>
/// Initializes the <see cref="System.Threading.ThreadLocal{T}"/> instance with the
/// specified <paramref name="valueFactory"/> function.
/// </summary>
/// <param name="valueFactory">
/// The <see cref="T:System.Func{T}"/> invoked to produce a lazily-initialized value when
/// an attempt is made to retrieve <see cref="Value"/> without it having been previously initialized.
/// </param>
/// <exception cref="T:System.ArgumentNullException">
/// <paramref name="valueFactory"/> is a null reference (Nothing in Visual Basic).
/// </exception>
public ThreadLocal(Func<T> valueFactory)
{
if (valueFactory == null)
throw new ArgumentNullException("valueFactory");
Initialize(valueFactory, false);
}
/// <summary>
/// Initializes the <see cref="System.Threading.ThreadLocal{T}"/> instance with the
/// specified <paramref name="valueFactory"/> function.
/// </summary>
/// <param name="valueFactory">
/// The <see cref="T:System.Func{T}"/> invoked to produce a lazily-initialized value when
/// an attempt is made to retrieve <see cref="Value"/> without it having been previously initialized.
/// </param>
/// <param name="trackAllValues">Whether to track all values set on the instance and expose them via the Values property.</param>
/// <exception cref="T:System.ArgumentNullException">
/// <paramref name="valueFactory"/> is a null reference (Nothing in Visual Basic).
/// </exception>
public ThreadLocal(Func<T> valueFactory, bool trackAllValues)
{
if (valueFactory == null)
throw new ArgumentNullException("valueFactory");
Initialize(valueFactory, trackAllValues);
}
private void Initialize(Func<T> valueFactory, bool trackAllValues)
{
m_valueFactory = valueFactory;
m_trackAllValues = trackAllValues;
// Assign the ID and mark the instance as initialized. To avoid leaking IDs, we assign the ID and set m_initialized
// in a finally block, to avoid a thread abort in between the two statements.
try { }
finally
{
m_idComplement = ~s_idManager.GetId();
// As the last step, mark the instance as fully initialized. (Otherwise, if m_initialized=false, we know that an exception
// occurred in the constructor.)
m_initialized = true;
}
}
/// <summary>
/// Releases the resources used by this <see cref="T:System.Threading.ThreadLocal{T}" /> instance.
/// </summary>
~ThreadLocal()
{
// finalizer to return the type combination index to the pool
Dispose(false);
}
#region IDisposable Members
/// <summary>
/// Releases the resources used by this <see cref="T:System.Threading.ThreadLocal{T}" /> instance.
/// </summary>
/// <remarks>
/// Unlike most of the members of <see cref="T:System.Threading.ThreadLocal{T}"/>, this method is not thread-safe.
/// </remarks>
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
/// <summary>
/// Releases the resources used by this <see cref="T:System.Threading.ThreadLocal{T}" /> instance.
/// </summary>
/// <param name="disposing">
/// A Boolean value that indicates whether this method is being called due to a call to <see cref="Dispose()"/>.
/// </param>
/// <remarks>
/// Unlike most of the members of <see cref="T:System.Threading.ThreadLocal{T}"/>, this method is not thread-safe.
/// </remarks>
protected virtual void Dispose(bool disposing)
{
int id;
lock (s_idManager.m_lock)
{
id = ~m_idComplement;
m_idComplement = 0;
if (id < 0 || !m_initialized)
{
Contract.Assert(id >= 0 || !m_initialized, "expected id >= 0 if initialized");
// Handle double Dispose calls or disposal of an instance whose constructor threw an exception.
return;
}
m_initialized = false;
for (LinkedSlot linkedSlot = m_linkedSlot.Next; linkedSlot != null; linkedSlot = linkedSlot.Next)
{
LinkedSlotVolatile[] slotArray = linkedSlot.SlotArray;
if (slotArray == null)
{
// The thread that owns this slotArray has already finished.
continue;
}
// Remove the reference from the LinkedSlot to the slot table.
linkedSlot.SlotArray = null;
// And clear the references from the slot table to the linked slot and the value so that
// both can get garbage collected.
slotArray[id].Value.Value = default(T);
slotArray[id].Value = null;
}
}
m_linkedSlot = null;
s_idManager.ReturnId(id);
}
#endregion
/// <summary>Creates and returns a string representation of this instance for the current thread.</summary>
/// <returns>The result of calling <see cref="System.Object.ToString"/> on the <see cref="Value"/>.</returns>
/// <exception cref="T:System.NullReferenceException">
/// The <see cref="Value"/> for the current thread is a null reference (Nothing in Visual Basic).
/// </exception>
/// <exception cref="T:System.InvalidOperationException">
/// The initialization function referenced <see cref="Value"/> in an improper manner.
/// </exception>
/// <exception cref="T:System.ObjectDisposedException">
/// The <see cref="ThreadLocal{T}"/> instance has been disposed.
/// </exception>
/// <remarks>
/// Calling this method forces initialization for the current thread, as is the
/// case with accessing <see cref="Value"/> directly.
/// </remarks>
public override string ToString()
{
return Value.ToString();
}
/// <summary>
/// Gets or sets the value of this instance for the current thread.
/// </summary>
/// <exception cref="T:System.InvalidOperationException">
/// The initialization function referenced <see cref="Value"/> in an improper manner.
/// </exception>
/// <exception cref="T:System.ObjectDisposedException">
/// The <see cref="ThreadLocal{T}"/> instance has been disposed.
/// </exception>
/// <remarks>
/// If this instance was not previously initialized for the current thread,
/// accessing <see cref="Value"/> will attempt to initialize it. If an initialization function was
/// supplied during the construction, that initialization will happen by invoking the function
/// to retrieve the initial value for <see cref="Value"/>. Otherwise, the default value of
/// <typeparamref name="T"/> will be used.
/// </remarks>
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
public T Value
{
get
{
LinkedSlotVolatile[] slotArray = ts_slotArray;
LinkedSlot slot;
int id = ~m_idComplement;
//
// Attempt to get the value using the fast path
//
if (slotArray != null // Has the slot array been initialized?
&& id >= 0 // Is the ID non-negative (i.e., instance is not disposed)?
&& id < slotArray.Length // Is the table large enough?
&& (slot = slotArray[id].Value) != null // Has a LinkedSlot object has been allocated for this ID?
&& m_initialized // Has the instance *still* not been disposed (important for races with Dispose)?
)
{
// We verified that the instance has not been disposed *after* we got a reference to the slot.
// This guarantees that we have a reference to the right slot.
//
// Volatile read of the LinkedSlotVolatile.Value property ensures that the m_initialized read
// will not be reordered before the read of slotArray[id].
return slot.Value;
}
return GetValueSlow();
}
set
{
LinkedSlotVolatile[] slotArray = ts_slotArray;
LinkedSlot slot;
int id = ~m_idComplement;
//
// Attempt to set the value using the fast path
//
if (slotArray != null // Has the slot array been initialized?
&& id >= 0 // Is the ID non-negative (i.e., instance is not disposed)?
&& id < slotArray.Length // Is the table large enough?
&& (slot = slotArray[id].Value) != null // Has a LinkedSlot object has been allocated for this ID?
&& m_initialized // Has the instance *still* not been disposed (important for races with Dispose)?
)
{
// We verified that the instance has not been disposed *after* we got a reference to the slot.
// This guarantees that we have a reference to the right slot.
//
// Volatile read of the LinkedSlotVolatile.Value property ensures that the m_initialized read
// will not be reordered before the read of slotArray[id].
slot.Value = value;
}
else
{
SetValueSlow(value, slotArray);
}
}
}
private T GetValueSlow()
{
// If the object has been disposed, the id will be -1.
int id = ~m_idComplement;
if (id < 0)
{
throw new ObjectDisposedException(SR.ThreadLocal_Disposed);
}
//Debugger.NotifyOfCrossThreadDependency();
// Determine the initial value
T value;
if (m_valueFactory == null)
{
value = default(T);
}
else
{
value = m_valueFactory();
if (IsValueCreated)
{
throw new InvalidOperationException(SR.ThreadLocal_Value_RecursiveCallsToValue);
}
}
// Since the value has been previously uninitialized, we also need to set it (according to the ThreadLocal semantics).
Value = value;
return value;
}
private void SetValueSlow(T value, LinkedSlotVolatile[] slotArray)
{
int id = ~m_idComplement;
// If the object has been disposed, id will be -1.
if (id < 0)
{
throw new ObjectDisposedException(SR.ThreadLocal_Disposed);
}
// If a slot array has not been created on this thread yet, create it.
if (slotArray == null)
{
slotArray = new LinkedSlotVolatile[GetNewTableSize(id + 1)];
ts_finalizationHelper = new FinalizationHelper(slotArray, m_trackAllValues);
ts_slotArray = slotArray;
}
// If the slot array is not big enough to hold this ID, increase the table size.
if (id >= slotArray.Length)
{
GrowTable(ref slotArray, id + 1);
ts_finalizationHelper.SlotArray = slotArray;
ts_slotArray = slotArray;
}
// If we are using the slot in this table for the first time, create a new LinkedSlot and add it into
// the linked list for this ThreadLocal instance.
if (slotArray[id].Value == null)
{
CreateLinkedSlot(slotArray, id, value);
}
else
{
// Volatile read of the LinkedSlotVolatile.Value property ensures that the m_initialized read
// that follows will not be reordered before the read of slotArray[id].
LinkedSlot slot = slotArray[id].Value;
// It is important to verify that the ThreadLocal instance has not been disposed. The check must come
// after capturing slotArray[id], but before assigning the value into the slot. This ensures that
// if this ThreadLocal instance was disposed on another thread and another ThreadLocal instance was
// created, we definitely won't assign the value into the wrong instance.
if (!m_initialized)
{
throw new ObjectDisposedException(SR.ThreadLocal_Disposed);
}
slot.Value = value;
}
}
/// <summary>
/// Creates a LinkedSlot and inserts it into the linked list for this ThreadLocal instance.
/// </summary>
private void CreateLinkedSlot(LinkedSlotVolatile[] slotArray, int id, T value)
{
// Create a LinkedSlot
var linkedSlot = new LinkedSlot(slotArray);
// Insert the LinkedSlot into the linked list maintained by this ThreadLocal<> instance and into the slot array
lock (s_idManager.m_lock)
{
// Check that the instance has not been disposed. It is important to check this under a lock, since
// Dispose also executes under a lock.
if (!m_initialized)
{
throw new ObjectDisposedException(SR.ThreadLocal_Disposed);
}
LinkedSlot firstRealNode = m_linkedSlot.Next;
//
// Insert linkedSlot between nodes m_linkedSlot and firstRealNode.
// (m_linkedSlot is the dummy head node that should always be in the front.)
//
linkedSlot.Next = firstRealNode;
linkedSlot.Previous = m_linkedSlot;
linkedSlot.Value = value;
if (firstRealNode != null)
{
firstRealNode.Previous = linkedSlot;
}
m_linkedSlot.Next = linkedSlot;
// Assigning the slot under a lock prevents a race with Dispose (dispose also acquires the lock).
// Otherwise, it would be possible that the ThreadLocal instance is disposed, another one gets created
// with the same ID, and the write would go to the wrong instance.
slotArray[id].Value = linkedSlot;
}
}
/// <summary>
/// Gets a list for all of the values currently stored by all of the threads that have accessed this instance.
/// </summary>
/// <exception cref="T:System.ObjectDisposedException">
/// The <see cref="ThreadLocal{T}"/> instance has been disposed.
/// </exception>
public IList<T> Values
{
get
{
if (!m_trackAllValues)
{
throw new InvalidOperationException(SR.ThreadLocal_ValuesNotAvailable);
}
var list = GetValuesAsList(); // returns null if disposed
if (list == null) throw new ObjectDisposedException(SR.ThreadLocal_Disposed);
return list;
}
}
/// <summary>Gets all of the threads' values in a list.</summary>
private List<T> GetValuesAsList()
{
List<T> valueList = new List<T>();
int id = ~m_idComplement;
if (id == -1)
{
return null;
}
// Walk over the linked list of slots and gather the values associated with this ThreadLocal instance.
for (LinkedSlot linkedSlot = m_linkedSlot.Next; linkedSlot != null; linkedSlot = linkedSlot.Next)
{
// We can safely read linkedSlot.Value. Even if this ThreadLocal has been disposed in the meantime, the LinkedSlot
// objects will never be assigned to another ThreadLocal instance.
valueList.Add(linkedSlot.Value);
}
return valueList;
}
/// <summary>Gets the number of threads that have data in this instance.</summary>
private int ValuesCountForDebugDisplay
{
get
{
int count = 0;
for (LinkedSlot linkedSlot = m_linkedSlot.Next; linkedSlot != null; linkedSlot = linkedSlot.Next)
{
count++;
}
return count;
}
}
/// <summary>
/// Gets whether <see cref="Value"/> is initialized on the current thread.
/// </summary>
/// <exception cref="T:System.ObjectDisposedException">
/// The <see cref="ThreadLocal{T}"/> instance has been disposed.
/// </exception>
public bool IsValueCreated
{
get
{
int id = ~m_idComplement;
if (id < 0)
{
throw new ObjectDisposedException(SR.ThreadLocal_Disposed);
}
LinkedSlotVolatile[] slotArray = ts_slotArray;
return slotArray != null && id < slotArray.Length && slotArray[id].Value != null;
}
}
/// <summary>Gets the value of the ThreadLocal<T> for debugging display purposes. It takes care of getting
/// the value for the current thread in the ThreadLocal mode.</summary>
internal T ValueForDebugDisplay
{
get
{
LinkedSlotVolatile[] slotArray = ts_slotArray;
int id = ~m_idComplement;
LinkedSlot slot;
if (slotArray == null || id >= slotArray.Length || (slot = slotArray[id].Value) == null || !m_initialized)
return default(T);
return slot.Value;
}
}
/// <summary>Gets the values of all threads that accessed the ThreadLocal<T>.</summary>
internal List<T> ValuesForDebugDisplay // same as Values property, but doesn't throw if disposed
{
get { return GetValuesAsList(); }
}
/// <summary>
/// Resizes a table to a certain length (or larger).
/// </summary>
private void GrowTable(ref LinkedSlotVolatile[] table, int minLength)
{
Contract.Assert(table.Length < minLength);
// Determine the size of the new table and allocate it.
int newLen = GetNewTableSize(minLength);
LinkedSlotVolatile[] newTable = new LinkedSlotVolatile[newLen];
//
// The lock is necessary to avoid a race with ThreadLocal.Dispose. GrowTable has to point all
// LinkedSlot instances referenced in the old table to reference the new table. Without locking,
// Dispose could use a stale SlotArray reference and clear out a slot in the old array only, while
// the value continues to be referenced from the new (larger) array.
//
lock (s_idManager.m_lock)
{
for (int i = 0; i < table.Length; i++)
{
LinkedSlot linkedSlot = table[i].Value;
if (linkedSlot != null && linkedSlot.SlotArray != null)
{
linkedSlot.SlotArray = newTable;
newTable[i] = table[i];
}
}
}
table = newTable;
}
const int MaxArrayLength = int.MaxValue;
/// <summary>
/// Chooses the next larger table size
/// </summary>
private static int GetNewTableSize(int minSize)
{
if ((uint)minSize > MaxArrayLength)
{
// Intentionally return a value that will result in an OutOfMemoryException
return int.MaxValue;
}
Contract.Assert(minSize > 0);
//
// Round up the size to the next power of 2
//
// The algorithm takes three steps:
// input -> subtract one -> propagate 1-bits to the right -> add one
//
// Let's take a look at the 3 steps in both interesting cases: where the input
// is (Example 1) and isn't (Example 2) a power of 2.
//
// Example 1: 100000 -> 011111 -> 011111 -> 100000
// Example 2: 011010 -> 011001 -> 011111 -> 100000
//
int newSize = minSize;
// Step 1: Decrement
newSize--;
// Step 2: Propagate 1-bits to the right.
newSize |= newSize >> 1;
newSize |= newSize >> 2;
newSize |= newSize >> 4;
newSize |= newSize >> 8;
newSize |= newSize >> 16;
// Step 3: Increment
newSize++;
// Don't set newSize to more than Array.MaxArrayLength
if ((uint)newSize > MaxArrayLength)
{
newSize = MaxArrayLength;
}
return newSize;
}
/// <summary>
/// A wrapper struct used as LinkedSlotVolatile[] - an array of LinkedSlot instances, but with volatile semantics
/// on array accesses.
/// </summary>
internal struct LinkedSlotVolatile
{
internal volatile LinkedSlot Value;
}
/// <summary>
/// A node in the doubly-linked list stored in the ThreadLocal instance.
///
/// The value is stored in one of two places:
///
/// 1. If SlotArray is not null, the value is in SlotArray.Table[id]
/// 2. If SlotArray is null, the value is in FinalValue.
/// </summary>
internal sealed class LinkedSlot
{
internal LinkedSlot(LinkedSlotVolatile[] slotArray)
{
SlotArray = slotArray;
}
// The next LinkedSlot for this ThreadLocal<> instance
internal volatile LinkedSlot Next;
// The previous LinkedSlot for this ThreadLocal<> instance
internal volatile LinkedSlot Previous;
// The SlotArray that stores this LinkedSlot at SlotArray.Table[id].
internal volatile LinkedSlotVolatile[] SlotArray;
// The value for this slot.
internal T Value;
}
/// <summary>
/// A manager class that assigns IDs to ThreadLocal instances
/// </summary>
private class IdManager
{
// The next ID to try
private int m_nextIdToTry = 0;
// Stores whether each ID is free or not. Additionally, the object is also used as a lock for the IdManager.
private List<bool> m_freeIds = new List<bool>();
internal Lock m_lock = new Lock();
internal int GetId()
{
lock (m_lock)
{
int availableId = m_nextIdToTry;
while (availableId < m_freeIds.Count)
{
if (m_freeIds[availableId]) { break; }
availableId++;
}
if (availableId == m_freeIds.Count)
{
m_freeIds.Add(false);
}
else
{
m_freeIds[availableId] = false;
}
m_nextIdToTry = availableId + 1;
return availableId;
}
}
// Return an ID to the pool
internal void ReturnId(int id)
{
lock (m_lock)
{
m_freeIds[id] = true;
if (id < m_nextIdToTry) m_nextIdToTry = id;
}
}
}
/// <summary>
/// A class that facilitates ThreadLocal cleanup after a thread exits.
///
/// After a thread with an associated thread-local table has exited, the FinalizationHelper
/// is reponsible for removing back-references to the table. Since an instance of FinalizationHelper
/// is only referenced from a single thread-local slot, the FinalizationHelper will be GC'd once
/// the thread has exited.
///
/// The FinalizationHelper then locates all LinkedSlot instances with back-references to the table
/// (all those LinkedSlot instances can be found by following references from the table slots) and
/// releases the table so that it can get GC'd.
/// </summary>
internal class FinalizationHelper
{
internal LinkedSlotVolatile[] SlotArray;
private bool m_trackAllValues;
internal FinalizationHelper(LinkedSlotVolatile[] slotArray, bool trackAllValues)
{
SlotArray = slotArray;
m_trackAllValues = trackAllValues;
}
~FinalizationHelper()
{
LinkedSlotVolatile[] slotArray = SlotArray;
Contract.Assert(slotArray != null);
for (int i = 0; i < slotArray.Length; i++)
{
LinkedSlot linkedSlot = slotArray[i].Value;
if (linkedSlot == null)
{
// This slot in the table is empty
continue;
}
if (m_trackAllValues)
{
// Set the SlotArray field to null to release the slot array.
linkedSlot.SlotArray = null;
}
else
{
// Remove the LinkedSlot from the linked list. Once the FinalizationHelper is done, all back-references to
// the table will be have been removed, and so the table can get GC'd.
lock (s_idManager.m_lock)
{
if (linkedSlot.Next != null)
{
linkedSlot.Next.Previous = linkedSlot.Previous;
}
// Since the list uses a dummy head node, the Previous reference should never be null.
Contract.Assert(linkedSlot.Previous != null);
linkedSlot.Previous.Next = linkedSlot.Next;
}
}
}
}
}
}
/// <summary>A debugger view of the ThreadLocal<T> to surface additional debugging properties and
/// to ensure that the ThreadLocal<T> does not become initialized if it was not already.</summary>
internal sealed class SystemThreading_ThreadLocalDebugView<T>
{
//The ThreadLocal object being viewed.
private readonly ThreadLocal<T> m_tlocal;
/// <summary>Constructs a new debugger view object for the provided ThreadLocal object.</summary>
/// <param name="tlocal">A ThreadLocal object to browse in the debugger.</param>
public SystemThreading_ThreadLocalDebugView(ThreadLocal<T> tlocal)
{
m_tlocal = tlocal;
}
/// <summary>Returns whether the ThreadLocal object is initialized or not.</summary>
public bool IsValueCreated
{
get { return m_tlocal.IsValueCreated; }
}
/// <summary>Returns the value of the ThreadLocal object.</summary>
public T Value
{
get
{
return m_tlocal.ValueForDebugDisplay;
}
}
/// <summary>Return all values for all threads that have accessed this instance.</summary>
public List<T> Values
{
get
{
return m_tlocal.ValuesForDebugDisplay;
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics.Contracts;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Security;
namespace System.Globalization
{
public partial class CompareInfo
{
[NonSerialized]
private Interop.GlobalizationInterop.SafeSortHandle _sortHandle;
[NonSerialized]
private bool _isAsciiEqualityOrdinal;
internal CompareInfo(CultureInfo culture)
{
_name = culture.m_name;
InitSort(culture);
}
private void InitSort(CultureInfo culture)
{
_sortName = culture.SortName;
_sortHandle = Interop.GlobalizationInterop.GetSortHandle(GetNullTerminatedUtf8String(_sortName));
_isAsciiEqualityOrdinal = (_sortName == "en-US" || _sortName == "");
}
internal static unsafe int IndexOfOrdinal(string source, string value, int startIndex, int count, bool ignoreCase)
{
Contract.Assert(source != null);
Contract.Assert(value != null);
if (value.Length == 0)
{
return startIndex;
}
if (count < value.Length)
{
return -1;
}
if (ignoreCase)
{
fixed (char* pSource = source)
{
int index = Interop.GlobalizationInterop.IndexOfOrdinalIgnoreCase(value, value.Length, pSource + startIndex, count, findLast: false);
return index != -1 ?
startIndex + index :
-1;
}
}
int endIndex = startIndex + (count - value.Length);
for (int i = startIndex; i <= endIndex; i++)
{
int valueIndex, sourceIndex;
for (valueIndex = 0, sourceIndex = i;
valueIndex < value.Length && source[sourceIndex] == value[valueIndex];
valueIndex++, sourceIndex++) ;
if (valueIndex == value.Length)
{
return i;
}
}
return -1;
}
internal static unsafe int LastIndexOfOrdinal(string source, string value, int startIndex, int count, bool ignoreCase)
{
Contract.Assert(source != null);
Contract.Assert(value != null);
if (value.Length == 0)
{
return startIndex;
}
if (count < value.Length)
{
return -1;
}
// startIndex is the index into source where we start search backwards from.
// leftStartIndex is the index into source of the start of the string that is
// count characters away from startIndex.
int leftStartIndex = startIndex - count + 1;
if (ignoreCase)
{
fixed (char* pSource = source)
{
int lastIndex = Interop.GlobalizationInterop.IndexOfOrdinalIgnoreCase(value, value.Length, pSource + leftStartIndex, count, findLast: true);
return lastIndex != -1 ?
leftStartIndex + lastIndex :
-1;
}
}
for (int i = startIndex - value.Length + 1; i >= leftStartIndex; i--)
{
int valueIndex, sourceIndex;
for (valueIndex = 0, sourceIndex = i;
valueIndex < value.Length && source[sourceIndex] == value[valueIndex];
valueIndex++, sourceIndex++) ;
if (valueIndex == value.Length) {
return i;
}
}
return -1;
}
private int GetHashCodeOfStringCore(string source, CompareOptions options)
{
Contract.Assert(source != null);
Contract.Assert((options & (CompareOptions.Ordinal | CompareOptions.OrdinalIgnoreCase)) == 0);
return GetHashCodeOfStringCore(source, options, forceRandomizedHashing: false, additionalEntropy: 0);
}
private static unsafe int CompareStringOrdinalIgnoreCase(char* string1, int count1, char* string2, int count2)
{
return Interop.GlobalizationInterop.CompareStringOrdinalIgnoreCase(string1, count1, string2, count2);
}
private unsafe int CompareString(string string1, int offset1, int length1, string string2, int offset2, int length2, CompareOptions options)
{
Contract.Assert(string1 != null);
Contract.Assert(string2 != null);
Contract.Assert((options & (CompareOptions.Ordinal | CompareOptions.OrdinalIgnoreCase)) == 0);
fixed (char* pString1 = string1)
{
fixed (char* pString2 = string2)
{
return Interop.GlobalizationInterop.CompareString(_sortHandle, pString1 + offset1, length1, pString2 + offset2, length2, options);
}
}
}
private unsafe int IndexOfCore(string source, string target, int startIndex, int count, CompareOptions options)
{
Contract.Assert(!string.IsNullOrEmpty(source));
Contract.Assert(target != null);
Contract.Assert((options & CompareOptions.OrdinalIgnoreCase) == 0);
if (target.Length == 0)
{
return startIndex;
}
if (options == CompareOptions.Ordinal)
{
return IndexOfOrdinal(source, target, startIndex, count, ignoreCase: false);
}
if (_isAsciiEqualityOrdinal && CanUseAsciiOrdinalForOptions(options) && source.IsFastSort() && target.IsFastSort())
{
return IndexOf(source, target, startIndex, count, GetOrdinalCompareOptions(options));
}
fixed (char* pSource = source)
{
int index = Interop.GlobalizationInterop.IndexOf(_sortHandle, target, target.Length, pSource + startIndex, count, options);
return index != -1 ? index + startIndex : -1;
}
}
private unsafe int LastIndexOfCore(string source, string target, int startIndex, int count, CompareOptions options)
{
Contract.Assert(!string.IsNullOrEmpty(source));
Contract.Assert(target != null);
Contract.Assert((options & CompareOptions.OrdinalIgnoreCase) == 0);
if (target.Length == 0)
{
return startIndex;
}
if (options == CompareOptions.Ordinal)
{
return LastIndexOfOrdinal(source, target, startIndex, count, ignoreCase: false);
}
if (_isAsciiEqualityOrdinal && CanUseAsciiOrdinalForOptions(options) && source.IsFastSort() && target.IsFastSort())
{
return LastIndexOf(source, target, startIndex, count, GetOrdinalCompareOptions(options));
}
// startIndex is the index into source where we start search backwards from. leftStartIndex is the index into source
// of the start of the string that is count characters away from startIndex.
int leftStartIndex = (startIndex - count + 1);
fixed (char* pSource = source)
{
int lastIndex = Interop.GlobalizationInterop.LastIndexOf(_sortHandle, target, target.Length, pSource + (startIndex - count + 1), count, options);
return lastIndex != -1 ? lastIndex + leftStartIndex : -1;
}
}
private bool StartsWith(string source, string prefix, CompareOptions options)
{
Contract.Assert(!string.IsNullOrEmpty(source));
Contract.Assert(!string.IsNullOrEmpty(prefix));
Contract.Assert((options & (CompareOptions.Ordinal | CompareOptions.OrdinalIgnoreCase)) == 0);
if (_isAsciiEqualityOrdinal && CanUseAsciiOrdinalForOptions(options) && source.IsFastSort() && prefix.IsFastSort())
{
return IsPrefix(source, prefix, GetOrdinalCompareOptions(options));
}
return Interop.GlobalizationInterop.StartsWith(_sortHandle, prefix, prefix.Length, source, source.Length, options);
}
private bool EndsWith(string source, string suffix, CompareOptions options)
{
Contract.Assert(!string.IsNullOrEmpty(source));
Contract.Assert(!string.IsNullOrEmpty(suffix));
Contract.Assert((options & (CompareOptions.Ordinal | CompareOptions.OrdinalIgnoreCase)) == 0);
if (_isAsciiEqualityOrdinal && CanUseAsciiOrdinalForOptions(options) && source.IsFastSort() && suffix.IsFastSort())
{
return IsSuffix(source, suffix, GetOrdinalCompareOptions(options));
}
return Interop.GlobalizationInterop.EndsWith(_sortHandle, suffix, suffix.Length, source, source.Length, options);
}
private unsafe SortKey CreateSortKey(String source, CompareOptions options)
{
if (source==null) { throw new ArgumentNullException("source"); }
Contract.EndContractBlock();
if ((options & ValidSortkeyCtorMaskOffFlags) != 0)
{
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidFlag"), "options");
}
byte [] keyData;
if (source.Length == 0)
{
keyData = EmptyArray<Byte>.Value;
}
else
{
int sortKeyLength = Interop.GlobalizationInterop.GetSortKey(_sortHandle, source, source.Length, null, 0, options);
keyData = new byte[sortKeyLength];
fixed (byte* pSortKey = keyData)
{
Interop.GlobalizationInterop.GetSortKey(_sortHandle, source, source.Length, pSortKey, sortKeyLength, options);
}
}
return new SortKey(Name, source, options, keyData);
}
private unsafe static bool IsSortable(char *text, int length)
{
int index = 0;
UnicodeCategory uc;
while (index < length)
{
if (Char.IsHighSurrogate(text[index]))
{
if (index == length - 1 || !Char.IsLowSurrogate(text[index+1]))
return false; // unpaired surrogate
uc = CharUnicodeInfo.InternalGetUnicodeCategory(Char.ConvertToUtf32(text[index], text[index+1]));
if (uc == UnicodeCategory.PrivateUse || uc == UnicodeCategory.OtherNotAssigned)
return false;
index += 2;
continue;
}
if (Char.IsLowSurrogate(text[index]))
{
return false; // unpaired surrogate
}
uc = CharUnicodeInfo.GetUnicodeCategory(text[index]);
if (uc == UnicodeCategory.PrivateUse || uc == UnicodeCategory.OtherNotAssigned)
{
return false;
}
index++;
}
return true;
}
// -----------------------------
// ---- PAL layer ends here ----
// -----------------------------
internal unsafe int GetHashCodeOfStringCore(string source, CompareOptions options, bool forceRandomizedHashing, long additionalEntropy)
{
Contract.Assert(source != null);
Contract.Assert((options & (CompareOptions.Ordinal | CompareOptions.OrdinalIgnoreCase)) == 0);
if (source.Length == 0)
{
return 0;
}
int sortKeyLength = Interop.GlobalizationInterop.GetSortKey(_sortHandle, source, source.Length, null, 0, options);
// As an optimization, for small sort keys we allocate the buffer on the stack.
if (sortKeyLength <= 256)
{
byte* pSortKey = stackalloc byte[sortKeyLength];
Interop.GlobalizationInterop.GetSortKey(_sortHandle, source, source.Length, pSortKey, sortKeyLength, options);
return InternalHashSortKey(pSortKey, sortKeyLength, false, additionalEntropy);
}
byte[] sortKey = new byte[sortKeyLength];
fixed(byte* pSortKey = sortKey)
{
Interop.GlobalizationInterop.GetSortKey(_sortHandle, source, source.Length, pSortKey, sortKeyLength, options);
return InternalHashSortKey(pSortKey, sortKeyLength, false, additionalEntropy);
}
}
[DllImport(JitHelpers.QCall)]
[SuppressUnmanagedCodeSecurity]
private static unsafe extern int InternalHashSortKey(byte* sortKey, int sortKeyLength, [MarshalAs(UnmanagedType.Bool)] bool forceRandomizedHashing, long additionalEntropy);
private static CompareOptions GetOrdinalCompareOptions(CompareOptions options)
{
if ((options & CompareOptions.IgnoreCase) == CompareOptions.IgnoreCase)
{
return CompareOptions.OrdinalIgnoreCase;
}
else
{
return CompareOptions.Ordinal;
}
}
private static bool CanUseAsciiOrdinalForOptions(CompareOptions options)
{
// Unlike the other Ignore options, IgnoreSymbols impacts ASCII characters (e.g. ').
return (options & CompareOptions.IgnoreSymbols) == 0;
}
private static byte[] GetNullTerminatedUtf8String(string s)
{
int byteLen = System.Text.Encoding.UTF8.GetByteCount(s);
// Allocate an extra byte (which defaults to 0) as the null terminator.
byte[] buffer = new byte[byteLen + 1];
int bytesWritten = System.Text.Encoding.UTF8.GetBytes(s, 0, s.Length, buffer, 0);
Contract.Assert(bytesWritten == byteLen);
return buffer;
}
}
}
| |
//
// NetTray - (C) 2016 Patrick Lambert - http://dendory.net - Provided under the MIT License
//
using System;
using System.IO;
using System.Net;
using System.Text;
using System.Drawing;
using System.Threading;
using System.Reflection;
using System.Diagnostics;
using System.Windows.Forms;
using System.ComponentModel;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Net.NetworkInformation;
using Microsoft.Win32;
[assembly: AssemblyTitle("NetTray")]
[assembly: AssemblyCopyright("(C) 2016 Patrick Lambert")]
[assembly: AssemblyFileVersion("1.3.0.0")]
namespace NetTrayNS
{
public class NetTray : Form
{
private NotifyIcon tray_icon; // The tray icon itself
private ContextMenu tray_menu; // The right click menu
private int interval = 1; // Interval used to check public IP and latency
private string url = "www.google.com"; // URL to ping for latency
private int min_latency = 500; // Minimum latency (ms) until slow connection is reported
private int dis_len = 10; // How long (secs) to display info bubbles
private string cur_ips = ""; // Current public and private IPs
private string new_ips = ""; // Latest public and private IPs
private int con_state = 0; // Connection state (0 = all fine, 1 = slow latency, 2 = no reply)
private long cur_latency = -1; // Current latency (ms)
private RegistryKey rkey; // Registry key to read config values
private string log_file = Path.GetTempPath() + "nettray.log"; // Log file
private int show_startup = 1; // Show the startup IP information
private int log_latency = 0; // Write every ping to the log
private int con_threas = 0; // Counter for 3 pings = no connection
private StreamWriter logfile; // Log file holder
private string lookup_name = ""; // Buffer for lookup value
private string url_name = "http://"; // Buffer for url value
[DllImport("kernel32")]
extern static UInt64 GetTickCount64();
[STAThread]
static void Main(string[] args)
{
Application.Run(new NetTray());
}
public NetTray()
{
rkey = Registry.CurrentUser.OpenSubKey("Software\\NetTray"); // Location of config values
if(rkey == null) // Location does not exist, create config values
{
rkey = Registry.CurrentUser.CreateSubKey("Software\\NetTray");
rkey.SetValue("latency_check_url", url);
rkey.SetValue("check_interval_in_seconds", interval);
rkey.SetValue("minimal_latency_in_ms", min_latency);
rkey.SetValue("info_display_length_in_seconds", dis_len);
rkey.SetValue("log_file", log_file);
rkey.SetValue("show_startup_info", show_startup);
rkey.SetValue("write_latency_to_log", log_latency);
}
else // Try to load config from registry
{
try
{
log_file = (string)rkey.GetValue("log_file");
url = (string)rkey.GetValue("latency_check_url");
interval = (int)rkey.GetValue("check_interval_in_seconds");
min_latency = (int)rkey.GetValue("minimal_latency_in_ms");
dis_len = (int)rkey.GetValue("info_display_length_in_seconds");
show_startup = (int)rkey.GetValue("show_startup_info");
log_latency = (int)rkey.GetValue("write_latency_to_log");
}
catch(Exception) // Display message but keep going
{
MessageBox.Show("An error occured while loading Registy settings. Using default values.", "NetTray");
}
}
logfile = File.AppendText(log_file);
logfile.AutoFlush = true;
logfile.WriteLine(DateTime.Now + " - Starting up.");
tray_menu = new ContextMenu(); // Make tray menu
tray_menu.MenuItems.Add("Interfaces", interfaces);
tray_menu.MenuItems.Add("Latency", latency);
tray_menu.MenuItems.Add("Lookup", nslookup);
tray_menu.MenuItems.Add("Test website", testwebsite);
tray_menu.MenuItems.Add("Uptime", uptime);
tray_menu.MenuItems.Add("Refresh", refresh);
tray_menu.MenuItems.Add("View log", viewlog);
tray_menu.MenuItems.Add("About", about);
tray_menu.MenuItems.Add("-");
tray_menu.MenuItems.Add("Exit", exit);
tray_icon = new NotifyIcon(); // Make tray icon
tray_icon.Icon = new Icon(System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceStream("res.notify_icon"));
tray_icon.ContextMenu = tray_menu;
tray_icon.Visible = true;
new_ips = "Private IP: " + get_private_ip() + "\r\nPublic IP: " + get_public_ip(); // Get private and public IPs
tray_icon.Text = new_ips;
logfile.WriteLine(DateTime.Now + " - IP information:\r\n" + new_ips);
if(show_startup == 1)
{
tray_icon.BalloonTipTitle = "NetTray"; // Show initial IPs info bubble
tray_icon.BalloonTipText = new_ips;
tray_icon.ShowBalloonTip(dis_len * 1000);
}
cur_ips = new_ips;
BackgroundWorker bw = new BackgroundWorker(); // Thread to check latency and IPs
bw.WorkerReportsProgress = true;
bw.DoWork += new DoWorkEventHandler(delegate(object o, DoWorkEventArgs args) // Enter thread here
{
BackgroundWorker b = o as BackgroundWorker;
Ping p = new Ping();
while(true) // Loop forever
{
PingReply r = p.Send(url);
if(r.Status == IPStatus.Success) // We got a ping reply
{
con_threas = 0;
if(r.RoundtripTime > min_latency) // Latency is above minimum acceptable value
{
b.ReportProgress(1, "Slow network connection detected: " + r.RoundtripTime.ToString() + "ms.");
}
else // Latency is fine
{
b.ReportProgress(0, "Connection restored.");
}
cur_latency = r.RoundtripTime; // Store latency for later use
if(log_latency == 1) logfile.WriteLine(DateTime.Now + " - Latency: " + cur_latency.ToString() + " ms.");
}
else // Timed out on the ping
{
con_threas = con_threas + 1;
if(log_latency == 1) logfile.WriteLine(DateTime.Now + " - Latency: Timed out.");
if(con_threas > 2)
{
b.ReportProgress(2, "No network connection detected.");
con_threas = 0;
}
}
new_ips = "Private IP: " + get_private_ip() + "\r\nPublic IP: " + get_public_ip(); // Get new IPs
tray_icon.Text = new_ips;
if(string.Compare(new_ips, cur_ips) != 0) // Check if new IPs are diff from old values
{
logfile.WriteLine(DateTime.Now + " - IP information:\r\n" + new_ips);
tray_icon.BalloonTipTitle = "NetTray";
tray_icon.BalloonTipText = new_ips;
tray_icon.ShowBalloonTip(dis_len * 1000);
}
cur_ips = new_ips;
Thread.Sleep(interval * 1000); // Sleep this thread for interval time
}
});
bw.ProgressChanged += new ProgressChangedEventHandler(delegate(object o, ProgressChangedEventArgs args) // Out of thread here
{
if(con_state != args.ProgressPercentage) // Check if state changed, if so show bubble with message from thread
{
logfile.WriteLine(DateTime.Now + " - " + args.UserState as String);
tray_icon.BalloonTipTitle = "NetTray";
tray_icon.BalloonTipText = args.UserState as String;
tray_icon.ShowBalloonTip(dis_len * 1000);
}
con_state = args.ProgressPercentage;
});
bw.RunWorkerAsync(); // Start thread
}
public static string input(string title, string text, string value) // Show a prompt on the screen for user input
{
Form prompt = new Form()
{
Width = 300,
Height = 150,
FormBorderStyle = FormBorderStyle.FixedDialog,
Text = title,
StartPosition = FormStartPosition.CenterScreen
};
Label textLabel = new Label() { Left = 50, Top=20, Width=200, Text=text };
TextBox textBox = new TextBox() { Left = 50, Top=50, Width=200, Text=value };
Button confirmation = new Button() { Text = "Ok", Left=150, Width=100, Top=80, DialogResult = DialogResult.OK };
confirmation.Click += (sender, e) => { prompt.Close(); };
prompt.Controls.Add(textBox);
prompt.Controls.Add(confirmation);
prompt.Controls.Add(textLabel);
prompt.AcceptButton = confirmation;
return prompt.ShowDialog() == DialogResult.OK ? textBox.Text : "";
}
private void exit(object sender, EventArgs e) // Clicked Exit
{
logfile.WriteLine(DateTime.Now + " - Shutting down.");
logfile.Close();
Application.Exit();
}
private void viewlog(object sender, EventArgs e) // Clicked View log
{
Process.Start(log_file);
}
private void nslookup(object sender, EventArgs e) // Clicked Lookup
{
string result = "Unknown";
lookup_name = input("Lookup", "Enter a hostname or IP address:", lookup_name);
try // Try to resolve hostname from ip
{
IPAddress hostIPAddress = IPAddress.Parse(lookup_name);
IPHostEntry hostInfo = Dns.GetHostEntry(hostIPAddress);
result = hostInfo.HostName;
}
catch (Exception)
{
try // If it didn't work, we probably need to resolve ip from hostname
{
IPHostEntry hostEntry = Dns.GetHostEntry(lookup_name);
var ip = hostEntry.AddressList[0];
result = ip.ToString();
}
catch(Exception){} // Not a valid hostname or ip
}
MessageBox.Show(lookup_name + " = " + result, "Lookup");
}
private void testwebsite(object sender, EventArgs e) // Clicked Test website
{
HttpWebResponse result;
url_name = input("Test website", "Enter a valid URL:", url_name);
try // Try to connect
{
HttpWebRequest req = WebRequest.Create(url_name) as HttpWebRequest;
result = req.GetResponse() as HttpWebResponse;
}
catch (WebException ex)
{
result = ex.Response as HttpWebResponse;
}
catch (Exception) // Crazy how many different ways it can fail
{
MessageBox.Show("Could not connect to " + url_name + ".", "Test website");
return;
}
if(result != null)
{
MessageBox.Show("Status of " + url_name + ": " + result.StatusCode, "Test website");
}
else
{
MessageBox.Show("Could not connect to " + url_name + ".", "Test website");
}
}
private void refresh(object sender, EventArgs e) // Clicked Refresh
{
new_ips = "Private IP: " + get_private_ip() + "\r\nPublic IP: " + get_public_ip(); // Get new IPs
tray_icon.Text = new_ips;
if(string.Compare(new_ips, cur_ips) != 0) // Check if new IPs are diff from old values
{
logfile.WriteLine(DateTime.Now + " - IP information:\r\n" + new_ips);
tray_icon.BalloonTipTitle = "NetTray";
tray_icon.BalloonTipText = new_ips;
tray_icon.ShowBalloonTip(dis_len * 1000);
}
cur_ips = new_ips;
}
private void uptime(object sender, EventArgs e) // Clicked Uptime
{
var uptime = TimeSpan.FromMilliseconds(GetTickCount64());
MessageBox.Show("System has been up for " + uptime.Days + " days and " + uptime.Hours + " hours.", "Uptime");
}
private void about(object sender, EventArgs e) // Clicked About
{
MessageBox.Show("This app fetches your current public IP address from <http://ipify.org> and your private IP addresses from your local interfaces. It also provides a latency check to <" + url + "> every " + interval + "s, and will alert you if your IP changes, latency becomes too bad, or your network connection drops. Log of connection issues is at <" + log_file + ">, configuration values can be found in the Registry at <HKCU\\Software\\NetTray>.\r\n\r\nProvided under the MIT License by Patrick Lambert <http://dendory.net>.", "About", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
private void latency(object sender, EventArgs e) // Clicked Latency
{
if(cur_latency != -1) // Latency is known, so show cached value
{
MessageBox.Show("Round trip to " + url + ": " + cur_latency.ToString() + "ms.", "Latency");
}
else // Latency is unknown, so try to ping
{
Ping p = new Ping();
PingReply r = p.Send(url);
if(r.Status == IPStatus.Success) // Got a reply
{
cur_latency = r.RoundtripTime;
MessageBox.Show("Round trip to " + url + ": " + cur_latency.ToString() + "ms.", "Latency");
}
else // Ping timed out
{
MessageBox.Show("Unable to ping " + url + ".", "Latency");
}
}
}
private void interfaces(object sender, EventArgs e) // Clicked Interfaces
{
string details = ""; // Buffer for text
try
{
foreach(NetworkInterface ni in NetworkInterface.GetAllNetworkInterfaces()) // Enumerate all interfaces from WMI
{
if(ni.NetworkInterfaceType == NetworkInterfaceType.Wireless80211 || ni.NetworkInterfaceType == NetworkInterfaceType.Ethernet) // Only care about ethernet and wifi
{
details += ni.Name + "\r\n";
foreach(UnicastIPAddressInformation ip in ni.GetIPProperties().UnicastAddresses) // IP addresses
{
if(ip.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
{
details += "- IP: " + ip.Address.ToString() + "\r\n";
}
if(ip.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetworkV6)
{
details += "- IPv6: " + ip.Address.ToString() + "\r\n";
}
}
foreach(GatewayIPAddressInformation gw in ni.GetIPProperties().GatewayAddresses) // Gateway
{
if(gw.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
{
details += "- Gateway: " + gw.Address.ToString() + "\r\n";
}
}
details += "- Type: " + ni.NetworkInterfaceType.ToString() + " (" + ni.OperationalStatus.ToString() + ")\r\n";
details += "- Speed: " + Int64.Parse(ni.Speed.ToString()) / 1000000 + " mbps\r\n";
details += "\r\n";
}
}
}
catch (Exception ex)
{
details += "An error occured: " + ex.Message;
}
MessageBox.Show(details, "All interfaces");
}
protected override void OnLoad(EventArgs e) // Display the tray icon on load
{
Visible = false;
ShowInTaskbar = false;
base.OnLoad(e);
}
protected override void Dispose(bool is_disposing) // Remove the tray icon on exit
{
if(is_disposing)
{
tray_icon.Dispose();
}
base.Dispose(is_disposing);
}
private string get_private_ip() // Fetch private IP from WMI
{
string privip = "";
try
{
foreach(NetworkInterface ni in NetworkInterface.GetAllNetworkInterfaces())
{
if(ni.NetworkInterfaceType == NetworkInterfaceType.Wireless80211 || ni.NetworkInterfaceType == NetworkInterfaceType.Ethernet)
{
foreach(UnicastIPAddressInformation ip in ni.GetIPProperties().UnicastAddresses)
{
if(ip.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork || ip.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetworkV6)
{
privip = ip.Address.ToString();
}
}
}
}
}
catch
{
return "Unknown";
}
return privip;
}
private string get_public_ip() // Fetch public IP from ipify.org
{
try
{
System.Net.WebRequest req = System.Net.WebRequest.Create("https://api.ipify.org?format=text");
System.Net.WebResponse resp = req.GetResponse();
System.IO.StreamReader sr = new System.IO.StreamReader(resp.GetResponseStream());
string response = sr.ReadToEnd().Trim();
return response;
}
catch (Exception)
{
return "Unknown";
}
}
}
}
| |
//
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
using Microsoft.Azure.Management.Compute.Models;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Management.Automation;
namespace Microsoft.Azure.Commands.Compute.Automation
{
[Cmdlet("New", "AzureRmVmssConfig")]
[OutputType(typeof(VirtualMachineScaleSet))]
public class NewAzureRmVmssConfigCommand : Microsoft.Azure.Commands.ResourceManager.Common.AzureRMCmdlet
{
[Parameter(
Mandatory = false,
Position = 0,
ValueFromPipelineByPropertyName = true)]
public bool? OverProvision { get; set; }
[Parameter(
Mandatory = false,
Position = 1,
ValueFromPipelineByPropertyName = true)]
public string Location { get; set; }
[Parameter(
Mandatory = false,
Position = 2,
ValueFromPipelineByPropertyName = true)]
public Hashtable Tag { get; set; }
[Parameter(
Mandatory = false,
Position = 3,
ValueFromPipelineByPropertyName = true)]
public string SkuName { get; set; }
[Parameter(
Mandatory = false,
Position = 4,
ValueFromPipelineByPropertyName = true)]
public string SkuTier { get; set; }
[Parameter(
Mandatory = false,
Position = 5,
ValueFromPipelineByPropertyName = true)]
public Int64? SkuCapacity { get; set; }
[Parameter(
Mandatory = false,
Position = 6,
ValueFromPipelineByPropertyName = true)]
public UpgradeMode? UpgradePolicyMode { get; set; }
[Parameter(
Mandatory = false,
Position = 7,
ValueFromPipelineByPropertyName = true)]
public VirtualMachineScaleSetOSProfile OsProfile { get; set; }
[Parameter(
Mandatory = false,
Position = 8,
ValueFromPipelineByPropertyName = true)]
public VirtualMachineScaleSetStorageProfile StorageProfile { get; set; }
[Parameter(
Mandatory = false,
Position = 9,
ValueFromPipelineByPropertyName = true)]
public VirtualMachineScaleSetNetworkConfiguration[] NetworkInterfaceConfiguration { get; set; }
[Parameter(
Mandatory = false,
Position = 10,
ValueFromPipelineByPropertyName = true)]
public VirtualMachineScaleSetExtension[] Extension { get; set; }
protected override void ProcessRecord()
{
// Sku
Microsoft.Azure.Management.Compute.Models.Sku vSku = null;
// UpgradePolicy
Microsoft.Azure.Management.Compute.Models.UpgradePolicy vUpgradePolicy = null;
// VirtualMachineProfile
Microsoft.Azure.Management.Compute.Models.VirtualMachineScaleSetVMProfile vVirtualMachineProfile = null;
if (this.SkuName != null)
{
if (vSku == null)
{
vSku = new Microsoft.Azure.Management.Compute.Models.Sku();
}
vSku.Name = this.SkuName;
}
if (this.SkuTier != null)
{
if (vSku == null)
{
vSku = new Microsoft.Azure.Management.Compute.Models.Sku();
}
vSku.Tier = this.SkuTier;
}
if (this.SkuCapacity != null)
{
if (vSku == null)
{
vSku = new Microsoft.Azure.Management.Compute.Models.Sku();
}
vSku.Capacity = this.SkuCapacity;
}
if (this.UpgradePolicyMode != null)
{
if (vUpgradePolicy == null)
{
vUpgradePolicy = new Microsoft.Azure.Management.Compute.Models.UpgradePolicy();
}
vUpgradePolicy.Mode = this.UpgradePolicyMode;
}
if (this.OsProfile != null)
{
if (vVirtualMachineProfile == null)
{
vVirtualMachineProfile = new Microsoft.Azure.Management.Compute.Models.VirtualMachineScaleSetVMProfile();
}
vVirtualMachineProfile.OsProfile = this.OsProfile;
}
if (this.StorageProfile != null)
{
if (vVirtualMachineProfile == null)
{
vVirtualMachineProfile = new Microsoft.Azure.Management.Compute.Models.VirtualMachineScaleSetVMProfile();
}
vVirtualMachineProfile.StorageProfile = this.StorageProfile;
}
if (this.NetworkInterfaceConfiguration != null)
{
if (vVirtualMachineProfile == null)
{
vVirtualMachineProfile = new Microsoft.Azure.Management.Compute.Models.VirtualMachineScaleSetVMProfile();
}
if (vVirtualMachineProfile.NetworkProfile == null)
{
vVirtualMachineProfile.NetworkProfile = new Microsoft.Azure.Management.Compute.Models.VirtualMachineScaleSetNetworkProfile();
}
vVirtualMachineProfile.NetworkProfile.NetworkInterfaceConfigurations = this.NetworkInterfaceConfiguration;
}
if (this.Extension != null)
{
if (vVirtualMachineProfile == null)
{
vVirtualMachineProfile = new Microsoft.Azure.Management.Compute.Models.VirtualMachineScaleSetVMProfile();
}
if (vVirtualMachineProfile.ExtensionProfile == null)
{
vVirtualMachineProfile.ExtensionProfile = new Microsoft.Azure.Management.Compute.Models.VirtualMachineScaleSetExtensionProfile();
}
vVirtualMachineProfile.ExtensionProfile.Extensions = this.Extension;
}
var vVirtualMachineScaleSet = new VirtualMachineScaleSet
{
OverProvision = this.OverProvision,
Location = this.Location,
Tags = (this.Tag == null) ? null : this.Tag.Cast<DictionaryEntry>().ToDictionary(ht => (string)ht.Key, ht => (string)ht.Value),
Sku = vSku,
UpgradePolicy = vUpgradePolicy,
VirtualMachineProfile = vVirtualMachineProfile,
};
WriteObject(vVirtualMachineScaleSet);
}
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Xml;
using log4net;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Framework.Serialization.External;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Services.Interfaces;
namespace OpenSim.Region.Framework.Scenes.Serialization
{
/// <summary>
/// Serialize and deserialize scene objects.
/// </summary>
/// This should really be in OpenSim.Framework.Serialization but this would mean circular dependency problems
/// right now - hopefully this isn't forever.
public class SceneObjectSerializer
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private static IUserManagement m_UserManagement;
/// <summary>
/// Deserialize a scene object from the original xml format
/// </summary>
/// <param name="xmlData"></param>
/// <returns>The scene object deserialized. Null on failure.</returns>
public static SceneObjectGroup FromOriginalXmlFormat(string xmlData)
{
String fixedData = ExternalRepresentationUtils.SanitizeXml(xmlData);
using (XmlTextReader wrappedReader = new XmlTextReader(fixedData, XmlNodeType.Element, null))
{
using (XmlReader reader = XmlReader.Create(wrappedReader, new XmlReaderSettings() { IgnoreWhitespace = true, ConformanceLevel = ConformanceLevel.Fragment }))
{
try {
return FromOriginalXmlFormat(reader);
}
catch (Exception e)
{
m_log.Error("[SERIALIZER]: Deserialization of xml failed ", e);
Util.LogFailedXML("[SERIALIZER]:", fixedData);
return null;
}
}
}
}
/// <summary>
/// Deserialize a scene object from the original xml format
/// </summary>
/// <param name="xmlData"></param>
/// <returns>The scene object deserialized. Null on failure.</returns>
public static SceneObjectGroup FromOriginalXmlFormat(XmlReader reader)
{
//m_log.DebugFormat("[SOG]: Starting deserialization of SOG");
//int time = System.Environment.TickCount;
int linkNum;
reader.ReadToFollowing("RootPart");
reader.ReadToFollowing("SceneObjectPart");
SceneObjectGroup sceneObject = new SceneObjectGroup(SceneObjectPart.FromXml(reader));
reader.ReadToFollowing("OtherParts");
if (reader.ReadToDescendant("Part"))
{
do
{
if (reader.ReadToDescendant("SceneObjectPart"))
{
SceneObjectPart part = SceneObjectPart.FromXml(reader);
linkNum = part.LinkNum;
sceneObject.AddPart(part);
part.LinkNum = linkNum;
part.TrimPermissions();
}
}
while (reader.ReadToNextSibling("Part"));
}
// Script state may, or may not, exist. Not having any, is NOT
// ever a problem.
sceneObject.LoadScriptState(reader);
sceneObject.AggregateDeepPerms();
return sceneObject;
}
/// <summary>
/// Serialize a scene object to the original xml format
/// </summary>
/// <param name="sceneObject"></param>
/// <returns></returns>
public static string ToOriginalXmlFormat(SceneObjectGroup sceneObject)
{
return ToOriginalXmlFormat(sceneObject, true);
}
/// <summary>
/// Serialize a scene object to the original xml format
/// </summary>
/// <param name="sceneObject"></param>
/// <param name="doScriptStates">Control whether script states are also serialized.</para>
/// <returns></returns>
public static string ToOriginalXmlFormat(SceneObjectGroup sceneObject, bool doScriptStates)
{
using (StringWriter sw = new StringWriter())
{
using (XmlTextWriter writer = new XmlTextWriter(sw))
{
ToOriginalXmlFormat(sceneObject, writer, doScriptStates);
}
return sw.ToString();
}
}
/// <summary>
/// Serialize a scene object to the original xml format
/// </summary>
/// <param name="sceneObject"></param>
/// <returns></returns>
public static void ToOriginalXmlFormat(SceneObjectGroup sceneObject, XmlTextWriter writer, bool doScriptStates)
{
ToOriginalXmlFormat(sceneObject, writer, doScriptStates, false);
}
public static string ToOriginalXmlFormat(SceneObjectGroup sceneObject, string scriptedState)
{
using (StringWriter sw = new StringWriter())
{
using (XmlTextWriter writer = new XmlTextWriter(sw))
{
writer.WriteStartElement(String.Empty, "SceneObjectGroup", String.Empty);
ToOriginalXmlFormat(sceneObject, writer, false, true);
writer.WriteRaw(scriptedState);
writer.WriteEndElement();
}
return sw.ToString();
}
}
/// <summary>
/// Serialize a scene object to the original xml format
/// </summary>
/// <param name="sceneObject"></param>
/// <param name="writer"></param>
/// <param name="noRootElement">If false, don't write the enclosing SceneObjectGroup element</param>
/// <returns></returns>
public static void ToOriginalXmlFormat(
SceneObjectGroup sceneObject, XmlTextWriter writer, bool doScriptStates, bool noRootElement)
{
// m_log.DebugFormat("[SERIALIZER]: Starting serialization of {0}", sceneObject.Name);
// int time = System.Environment.TickCount;
if (!noRootElement)
writer.WriteStartElement(String.Empty, "SceneObjectGroup", String.Empty);
writer.WriteStartElement(String.Empty, "RootPart", String.Empty);
ToXmlFormat(sceneObject.RootPart, writer);
writer.WriteEndElement();
writer.WriteStartElement(String.Empty, "OtherParts", String.Empty);
SceneObjectPart[] parts = sceneObject.Parts;
for (int i = 0; i < parts.Length; i++)
{
SceneObjectPart part = parts[i];
if (part.UUID != sceneObject.RootPart.UUID)
{
writer.WriteStartElement(String.Empty, "Part", String.Empty);
ToXmlFormat(part, writer);
writer.WriteEndElement();
}
}
writer.WriteEndElement(); // OtherParts
if (doScriptStates)
sceneObject.SaveScriptedState(writer);
if (!noRootElement)
writer.WriteEndElement(); // SceneObjectGroup
// m_log.DebugFormat("[SERIALIZER]: Finished serialization of SOG {0}, {1}ms", sceneObject.Name, System.Environment.TickCount - time);
}
protected static void ToXmlFormat(SceneObjectPart part, XmlTextWriter writer)
{
SOPToXml2(writer, part, new Dictionary<string, object>());
}
public static SceneObjectGroup FromXml2Format(string xmlData)
{
//m_log.DebugFormat("[SOG]: Starting deserialization of SOG");
//int time = System.Environment.TickCount;
try
{
XmlDocument doc = new XmlDocument();
doc.LoadXml(xmlData);
XmlNodeList parts = doc.GetElementsByTagName("SceneObjectPart");
if (parts.Count == 0)
{
m_log.Error("[SERIALIZER]: Deserialization of xml failed: No SceneObjectPart nodes");
Util.LogFailedXML("[SERIALIZER]:", xmlData);
return null;
}
StringReader sr = new StringReader(parts[0].OuterXml);
XmlTextReader reader = new XmlTextReader(sr);
SceneObjectGroup sceneObject = new SceneObjectGroup(SceneObjectPart.FromXml(reader));
reader.Close();
sr.Close();
// Then deal with the rest
for (int i = 1; i < parts.Count; i++)
{
sr = new StringReader(parts[i].OuterXml);
reader = new XmlTextReader(sr);
SceneObjectPart part = SceneObjectPart.FromXml(reader);
int originalLinkNum = part.LinkNum;
sceneObject.AddPart(part);
// SceneObjectGroup.AddPart() tries to be smart and automatically set the LinkNum.
// We override that here
if (originalLinkNum != 0)
part.LinkNum = originalLinkNum;
reader.Close();
sr.Close();
}
XmlNodeList keymotion = doc.GetElementsByTagName("KeyframeMotion");
if (keymotion.Count > 0)
sceneObject.RootPart.KeyframeMotion = KeyframeMotion.FromData(sceneObject, Convert.FromBase64String(keymotion[0].InnerText));
else
sceneObject.RootPart.KeyframeMotion = null;
// Script state may, or may not, exist. Not having any, is NOT
// ever a problem.
sceneObject.LoadScriptState(doc);
sceneObject.AggregatePerms();
return sceneObject;
}
catch (Exception e)
{
m_log.Error("[SERIALIZER]: Deserialization of xml failed ", e);
Util.LogFailedXML("[SERIALIZER]:", xmlData);
return null;
}
}
/// <summary>
/// Serialize a scene object to the 'xml2' format.
/// </summary>
/// <param name="sceneObject"></param>
/// <returns></returns>
public static string ToXml2Format(SceneObjectGroup sceneObject)
{
using (StringWriter sw = new StringWriter())
{
using (XmlTextWriter writer = new XmlTextWriter(sw))
{
SOGToXml2(writer, sceneObject, new Dictionary<string,object>());
}
return sw.ToString();
}
}
/// <summary>
/// Modifies a SceneObjectGroup.
/// </summary>
/// <param name="sog">The object</param>
/// <returns>Whether the object was actually modified</returns>
public delegate bool SceneObjectModifier(SceneObjectGroup sog);
/// <summary>
/// Modifies an object by deserializing it; applying 'modifier' to each SceneObjectGroup; and reserializing.
/// </summary>
/// <param name="assetId">The object's UUID</param>
/// <param name="data">Serialized data</param>
/// <param name="modifier">The function to run on each SceneObjectGroup</param>
/// <returns>The new serialized object's data, or null if an error occurred</returns>
public static byte[] ModifySerializedObject(UUID assetId, byte[] data, SceneObjectModifier modifier)
{
List<SceneObjectGroup> sceneObjects = new List<SceneObjectGroup>();
CoalescedSceneObjects coa = null;
string xmlData = ExternalRepresentationUtils.SanitizeXml(Utils.BytesToString(data));
if (CoalescedSceneObjectsSerializer.TryFromXml(xmlData, out coa))
{
// m_log.DebugFormat("[SERIALIZER]: Loaded coalescence {0} has {1} objects", assetId, coa.Count);
if (coa.Objects.Count == 0)
{
m_log.WarnFormat("[SERIALIZER]: Aborting load of coalesced object from asset {0} as it has zero loaded components", assetId);
return null;
}
sceneObjects.AddRange(coa.Objects);
}
else
{
SceneObjectGroup deserializedObject = FromOriginalXmlFormat(xmlData);
if (deserializedObject != null)
{
sceneObjects.Add(deserializedObject);
}
else
{
m_log.WarnFormat("[SERIALIZER]: Aborting load of object from asset {0} as deserialization failed", assetId);
return null;
}
}
bool modified = false;
foreach (SceneObjectGroup sog in sceneObjects)
{
if (modifier(sog))
modified = true;
}
if (modified)
{
if (coa != null)
data = Utils.StringToBytes(CoalescedSceneObjectsSerializer.ToXml(coa));
else
data = Utils.StringToBytes(ToOriginalXmlFormat(sceneObjects[0]));
}
return data;
}
#region manual serialization
private static Dictionary<string, Action<SceneObjectPart, XmlReader>> m_SOPXmlProcessors
= new Dictionary<string, Action<SceneObjectPart, XmlReader>>();
private static Dictionary<string, Action<TaskInventoryItem, XmlReader>> m_TaskInventoryXmlProcessors
= new Dictionary<string, Action<TaskInventoryItem, XmlReader>>();
private static Dictionary<string, Action<PrimitiveBaseShape, XmlReader>> m_ShapeXmlProcessors
= new Dictionary<string, Action<PrimitiveBaseShape, XmlReader>>();
static SceneObjectSerializer()
{
#region SOPXmlProcessors initialization
m_SOPXmlProcessors.Add("AllowedDrop", ProcessAllowedDrop);
m_SOPXmlProcessors.Add("CreatorID", ProcessCreatorID);
m_SOPXmlProcessors.Add("CreatorData", ProcessCreatorData);
m_SOPXmlProcessors.Add("FolderID", ProcessFolderID);
m_SOPXmlProcessors.Add("InventorySerial", ProcessInventorySerial);
m_SOPXmlProcessors.Add("TaskInventory", ProcessTaskInventory);
m_SOPXmlProcessors.Add("UUID", ProcessUUID);
m_SOPXmlProcessors.Add("LocalId", ProcessLocalId);
m_SOPXmlProcessors.Add("Name", ProcessName);
m_SOPXmlProcessors.Add("Material", ProcessMaterial);
m_SOPXmlProcessors.Add("PassTouches", ProcessPassTouches);
m_SOPXmlProcessors.Add("PassCollisions", ProcessPassCollisions);
m_SOPXmlProcessors.Add("RegionHandle", ProcessRegionHandle);
m_SOPXmlProcessors.Add("ScriptAccessPin", ProcessScriptAccessPin);
m_SOPXmlProcessors.Add("GroupPosition", ProcessGroupPosition);
m_SOPXmlProcessors.Add("OffsetPosition", ProcessOffsetPosition);
m_SOPXmlProcessors.Add("RotationOffset", ProcessRotationOffset);
m_SOPXmlProcessors.Add("Velocity", ProcessVelocity);
m_SOPXmlProcessors.Add("AngularVelocity", ProcessAngularVelocity);
m_SOPXmlProcessors.Add("Acceleration", ProcessAcceleration);
m_SOPXmlProcessors.Add("Description", ProcessDescription);
m_SOPXmlProcessors.Add("Color", ProcessColor);
m_SOPXmlProcessors.Add("Text", ProcessText);
m_SOPXmlProcessors.Add("SitName", ProcessSitName);
m_SOPXmlProcessors.Add("TouchName", ProcessTouchName);
m_SOPXmlProcessors.Add("LinkNum", ProcessLinkNum);
m_SOPXmlProcessors.Add("ClickAction", ProcessClickAction);
m_SOPXmlProcessors.Add("Shape", ProcessShape);
m_SOPXmlProcessors.Add("Scale", ProcessScale);
m_SOPXmlProcessors.Add("SitTargetOrientation", ProcessSitTargetOrientation);
m_SOPXmlProcessors.Add("SitTargetPosition", ProcessSitTargetPosition);
m_SOPXmlProcessors.Add("SitTargetPositionLL", ProcessSitTargetPositionLL);
m_SOPXmlProcessors.Add("SitTargetOrientationLL", ProcessSitTargetOrientationLL);
m_SOPXmlProcessors.Add("ParentID", ProcessParentID);
m_SOPXmlProcessors.Add("CreationDate", ProcessCreationDate);
m_SOPXmlProcessors.Add("Category", ProcessCategory);
m_SOPXmlProcessors.Add("SalePrice", ProcessSalePrice);
m_SOPXmlProcessors.Add("ObjectSaleType", ProcessObjectSaleType);
m_SOPXmlProcessors.Add("OwnershipCost", ProcessOwnershipCost);
m_SOPXmlProcessors.Add("GroupID", ProcessGroupID);
m_SOPXmlProcessors.Add("OwnerID", ProcessOwnerID);
m_SOPXmlProcessors.Add("LastOwnerID", ProcessLastOwnerID);
m_SOPXmlProcessors.Add("RezzerID", ProcessRezzerID);
m_SOPXmlProcessors.Add("BaseMask", ProcessBaseMask);
m_SOPXmlProcessors.Add("OwnerMask", ProcessOwnerMask);
m_SOPXmlProcessors.Add("GroupMask", ProcessGroupMask);
m_SOPXmlProcessors.Add("EveryoneMask", ProcessEveryoneMask);
m_SOPXmlProcessors.Add("NextOwnerMask", ProcessNextOwnerMask);
m_SOPXmlProcessors.Add("Flags", ProcessFlags);
m_SOPXmlProcessors.Add("CollisionSound", ProcessCollisionSound);
m_SOPXmlProcessors.Add("CollisionSoundVolume", ProcessCollisionSoundVolume);
m_SOPXmlProcessors.Add("MediaUrl", ProcessMediaUrl);
m_SOPXmlProcessors.Add("AttachedPos", ProcessAttachedPos);
m_SOPXmlProcessors.Add("DynAttrs", ProcessDynAttrs);
m_SOPXmlProcessors.Add("TextureAnimation", ProcessTextureAnimation);
m_SOPXmlProcessors.Add("ParticleSystem", ProcessParticleSystem);
m_SOPXmlProcessors.Add("PayPrice0", ProcessPayPrice0);
m_SOPXmlProcessors.Add("PayPrice1", ProcessPayPrice1);
m_SOPXmlProcessors.Add("PayPrice2", ProcessPayPrice2);
m_SOPXmlProcessors.Add("PayPrice3", ProcessPayPrice3);
m_SOPXmlProcessors.Add("PayPrice4", ProcessPayPrice4);
m_SOPXmlProcessors.Add("Buoyancy", ProcessBuoyancy);
m_SOPXmlProcessors.Add("Force", ProcessForce);
m_SOPXmlProcessors.Add("Torque", ProcessTorque);
m_SOPXmlProcessors.Add("VolumeDetectActive", ProcessVolumeDetectActive);
m_SOPXmlProcessors.Add("Vehicle", ProcessVehicle);
m_SOPXmlProcessors.Add("RotationAxisLocks", ProcessRotationAxisLocks);
m_SOPXmlProcessors.Add("PhysicsShapeType", ProcessPhysicsShapeType);
m_SOPXmlProcessors.Add("Density", ProcessDensity);
m_SOPXmlProcessors.Add("Friction", ProcessFriction);
m_SOPXmlProcessors.Add("Bounce", ProcessBounce);
m_SOPXmlProcessors.Add("GravityModifier", ProcessGravityModifier);
m_SOPXmlProcessors.Add("CameraEyeOffset", ProcessCameraEyeOffset);
m_SOPXmlProcessors.Add("CameraAtOffset", ProcessCameraAtOffset);
m_SOPXmlProcessors.Add("SoundID", ProcessSoundID);
m_SOPXmlProcessors.Add("SoundGain", ProcessSoundGain);
m_SOPXmlProcessors.Add("SoundFlags", ProcessSoundFlags);
m_SOPXmlProcessors.Add("SoundRadius", ProcessSoundRadius);
m_SOPXmlProcessors.Add("SoundQueueing", ProcessSoundQueueing);
#endregion
#region TaskInventoryXmlProcessors initialization
m_TaskInventoryXmlProcessors.Add("AssetID", ProcessTIAssetID);
m_TaskInventoryXmlProcessors.Add("BasePermissions", ProcessTIBasePermissions);
m_TaskInventoryXmlProcessors.Add("CreationDate", ProcessTICreationDate);
m_TaskInventoryXmlProcessors.Add("CreatorID", ProcessTICreatorID);
m_TaskInventoryXmlProcessors.Add("CreatorData", ProcessTICreatorData);
m_TaskInventoryXmlProcessors.Add("Description", ProcessTIDescription);
m_TaskInventoryXmlProcessors.Add("EveryonePermissions", ProcessTIEveryonePermissions);
m_TaskInventoryXmlProcessors.Add("Flags", ProcessTIFlags);
m_TaskInventoryXmlProcessors.Add("GroupID", ProcessTIGroupID);
m_TaskInventoryXmlProcessors.Add("GroupPermissions", ProcessTIGroupPermissions);
m_TaskInventoryXmlProcessors.Add("InvType", ProcessTIInvType);
m_TaskInventoryXmlProcessors.Add("ItemID", ProcessTIItemID);
m_TaskInventoryXmlProcessors.Add("OldItemID", ProcessTIOldItemID);
m_TaskInventoryXmlProcessors.Add("LastOwnerID", ProcessTILastOwnerID);
m_TaskInventoryXmlProcessors.Add("Name", ProcessTIName);
m_TaskInventoryXmlProcessors.Add("NextPermissions", ProcessTINextPermissions);
m_TaskInventoryXmlProcessors.Add("OwnerID", ProcessTIOwnerID);
m_TaskInventoryXmlProcessors.Add("CurrentPermissions", ProcessTICurrentPermissions);
m_TaskInventoryXmlProcessors.Add("ParentID", ProcessTIParentID);
m_TaskInventoryXmlProcessors.Add("ParentPartID", ProcessTIParentPartID);
m_TaskInventoryXmlProcessors.Add("PermsGranter", ProcessTIPermsGranter);
m_TaskInventoryXmlProcessors.Add("PermsMask", ProcessTIPermsMask);
m_TaskInventoryXmlProcessors.Add("Type", ProcessTIType);
m_TaskInventoryXmlProcessors.Add("OwnerChanged", ProcessTIOwnerChanged);
#endregion
#region ShapeXmlProcessors initialization
m_ShapeXmlProcessors.Add("ProfileCurve", ProcessShpProfileCurve);
m_ShapeXmlProcessors.Add("TextureEntry", ProcessShpTextureEntry);
m_ShapeXmlProcessors.Add("ExtraParams", ProcessShpExtraParams);
m_ShapeXmlProcessors.Add("PathBegin", ProcessShpPathBegin);
m_ShapeXmlProcessors.Add("PathCurve", ProcessShpPathCurve);
m_ShapeXmlProcessors.Add("PathEnd", ProcessShpPathEnd);
m_ShapeXmlProcessors.Add("PathRadiusOffset", ProcessShpPathRadiusOffset);
m_ShapeXmlProcessors.Add("PathRevolutions", ProcessShpPathRevolutions);
m_ShapeXmlProcessors.Add("PathScaleX", ProcessShpPathScaleX);
m_ShapeXmlProcessors.Add("PathScaleY", ProcessShpPathScaleY);
m_ShapeXmlProcessors.Add("PathShearX", ProcessShpPathShearX);
m_ShapeXmlProcessors.Add("PathShearY", ProcessShpPathShearY);
m_ShapeXmlProcessors.Add("PathSkew", ProcessShpPathSkew);
m_ShapeXmlProcessors.Add("PathTaperX", ProcessShpPathTaperX);
m_ShapeXmlProcessors.Add("PathTaperY", ProcessShpPathTaperY);
m_ShapeXmlProcessors.Add("PathTwist", ProcessShpPathTwist);
m_ShapeXmlProcessors.Add("PathTwistBegin", ProcessShpPathTwistBegin);
m_ShapeXmlProcessors.Add("PCode", ProcessShpPCode);
m_ShapeXmlProcessors.Add("ProfileBegin", ProcessShpProfileBegin);
m_ShapeXmlProcessors.Add("ProfileEnd", ProcessShpProfileEnd);
m_ShapeXmlProcessors.Add("ProfileHollow", ProcessShpProfileHollow);
m_ShapeXmlProcessors.Add("Scale", ProcessShpScale);
m_ShapeXmlProcessors.Add("LastAttachPoint", ProcessShpLastAttach);
m_ShapeXmlProcessors.Add("State", ProcessShpState);
m_ShapeXmlProcessors.Add("ProfileShape", ProcessShpProfileShape);
m_ShapeXmlProcessors.Add("HollowShape", ProcessShpHollowShape);
m_ShapeXmlProcessors.Add("SculptTexture", ProcessShpSculptTexture);
m_ShapeXmlProcessors.Add("SculptType", ProcessShpSculptType);
// Ignore "SculptData"; this element is deprecated
m_ShapeXmlProcessors.Add("FlexiSoftness", ProcessShpFlexiSoftness);
m_ShapeXmlProcessors.Add("FlexiTension", ProcessShpFlexiTension);
m_ShapeXmlProcessors.Add("FlexiDrag", ProcessShpFlexiDrag);
m_ShapeXmlProcessors.Add("FlexiGravity", ProcessShpFlexiGravity);
m_ShapeXmlProcessors.Add("FlexiWind", ProcessShpFlexiWind);
m_ShapeXmlProcessors.Add("FlexiForceX", ProcessShpFlexiForceX);
m_ShapeXmlProcessors.Add("FlexiForceY", ProcessShpFlexiForceY);
m_ShapeXmlProcessors.Add("FlexiForceZ", ProcessShpFlexiForceZ);
m_ShapeXmlProcessors.Add("LightColorR", ProcessShpLightColorR);
m_ShapeXmlProcessors.Add("LightColorG", ProcessShpLightColorG);
m_ShapeXmlProcessors.Add("LightColorB", ProcessShpLightColorB);
m_ShapeXmlProcessors.Add("LightColorA", ProcessShpLightColorA);
m_ShapeXmlProcessors.Add("LightRadius", ProcessShpLightRadius);
m_ShapeXmlProcessors.Add("LightCutoff", ProcessShpLightCutoff);
m_ShapeXmlProcessors.Add("LightFalloff", ProcessShpLightFalloff);
m_ShapeXmlProcessors.Add("LightIntensity", ProcessShpLightIntensity);
m_ShapeXmlProcessors.Add("FlexiEntry", ProcessShpFlexiEntry);
m_ShapeXmlProcessors.Add("LightEntry", ProcessShpLightEntry);
m_ShapeXmlProcessors.Add("SculptEntry", ProcessShpSculptEntry);
m_ShapeXmlProcessors.Add("Media", ProcessShpMedia);
#endregion
}
#region SOPXmlProcessors
private static void ProcessAllowedDrop(SceneObjectPart obj, XmlReader reader)
{
obj.AllowedDrop = Util.ReadBoolean(reader);
}
private static void ProcessCreatorID(SceneObjectPart obj, XmlReader reader)
{
obj.CreatorID = Util.ReadUUID(reader, "CreatorID");
}
private static void ProcessCreatorData(SceneObjectPart obj, XmlReader reader)
{
obj.CreatorData = reader.ReadElementContentAsString("CreatorData", String.Empty);
}
private static void ProcessFolderID(SceneObjectPart obj, XmlReader reader)
{
obj.FolderID = Util.ReadUUID(reader, "FolderID");
}
private static void ProcessInventorySerial(SceneObjectPart obj, XmlReader reader)
{
obj.InventorySerial = (uint)reader.ReadElementContentAsInt("InventorySerial", String.Empty);
}
private static void ProcessTaskInventory(SceneObjectPart obj, XmlReader reader)
{
obj.TaskInventory = ReadTaskInventory(reader, "TaskInventory");
}
private static void ProcessUUID(SceneObjectPart obj, XmlReader reader)
{
obj.UUID = Util.ReadUUID(reader, "UUID");
}
private static void ProcessLocalId(SceneObjectPart obj, XmlReader reader)
{
obj.LocalId = (uint)reader.ReadElementContentAsLong("LocalId", String.Empty);
}
private static void ProcessName(SceneObjectPart obj, XmlReader reader)
{
obj.Name = reader.ReadElementString("Name");
}
private static void ProcessMaterial(SceneObjectPart obj, XmlReader reader)
{
obj.Material = (byte)reader.ReadElementContentAsInt("Material", String.Empty);
}
private static void ProcessPassTouches(SceneObjectPart obj, XmlReader reader)
{
obj.PassTouches = Util.ReadBoolean(reader);
}
private static void ProcessPassCollisions(SceneObjectPart obj, XmlReader reader)
{
obj.PassCollisions = Util.ReadBoolean(reader);
}
private static void ProcessRegionHandle(SceneObjectPart obj, XmlReader reader)
{
obj.RegionHandle = (ulong)reader.ReadElementContentAsLong("RegionHandle", String.Empty);
}
private static void ProcessScriptAccessPin(SceneObjectPart obj, XmlReader reader)
{
obj.ScriptAccessPin = reader.ReadElementContentAsInt("ScriptAccessPin", String.Empty);
}
private static void ProcessGroupPosition(SceneObjectPart obj, XmlReader reader)
{
obj.GroupPosition = Util.ReadVector(reader, "GroupPosition");
}
private static void ProcessOffsetPosition(SceneObjectPart obj, XmlReader reader)
{
obj.OffsetPosition = Util.ReadVector(reader, "OffsetPosition"); ;
}
private static void ProcessRotationOffset(SceneObjectPart obj, XmlReader reader)
{
obj.RotationOffset = Util.ReadQuaternion(reader, "RotationOffset");
}
private static void ProcessVelocity(SceneObjectPart obj, XmlReader reader)
{
obj.Velocity = Util.ReadVector(reader, "Velocity");
}
private static void ProcessAngularVelocity(SceneObjectPart obj, XmlReader reader)
{
obj.AngularVelocity = Util.ReadVector(reader, "AngularVelocity");
}
private static void ProcessAcceleration(SceneObjectPart obj, XmlReader reader)
{
obj.Acceleration = Util.ReadVector(reader, "Acceleration");
}
private static void ProcessDescription(SceneObjectPart obj, XmlReader reader)
{
obj.Description = reader.ReadElementString("Description");
}
private static void ProcessColor(SceneObjectPart obj, XmlReader reader)
{
reader.ReadStartElement("Color");
if (reader.Name == "R")
{
float r = reader.ReadElementContentAsFloat("R", String.Empty);
float g = reader.ReadElementContentAsFloat("G", String.Empty);
float b = reader.ReadElementContentAsFloat("B", String.Empty);
float a = reader.ReadElementContentAsFloat("A", String.Empty);
obj.Color = Color.FromArgb((int)a, (int)r, (int)g, (int)b);
reader.ReadEndElement();
}
}
private static void ProcessText(SceneObjectPart obj, XmlReader reader)
{
obj.Text = reader.ReadElementString("Text", String.Empty);
}
private static void ProcessSitName(SceneObjectPart obj, XmlReader reader)
{
obj.SitName = reader.ReadElementString("SitName", String.Empty);
}
private static void ProcessTouchName(SceneObjectPart obj, XmlReader reader)
{
obj.TouchName = reader.ReadElementString("TouchName", String.Empty);
}
private static void ProcessLinkNum(SceneObjectPart obj, XmlReader reader)
{
obj.LinkNum = reader.ReadElementContentAsInt("LinkNum", String.Empty);
}
private static void ProcessClickAction(SceneObjectPart obj, XmlReader reader)
{
obj.ClickAction = (byte)reader.ReadElementContentAsInt("ClickAction", String.Empty);
}
private static void ProcessRotationAxisLocks(SceneObjectPart obj, XmlReader reader)
{
obj.RotationAxisLocks = (byte)reader.ReadElementContentAsInt("RotationAxisLocks", String.Empty);
}
private static void ProcessPhysicsShapeType(SceneObjectPart obj, XmlReader reader)
{
obj.PhysicsShapeType = (byte)reader.ReadElementContentAsInt("PhysicsShapeType", String.Empty);
}
private static void ProcessDensity(SceneObjectPart obj, XmlReader reader)
{
obj.Density = reader.ReadElementContentAsFloat("Density", String.Empty);
}
private static void ProcessFriction(SceneObjectPart obj, XmlReader reader)
{
obj.Friction = reader.ReadElementContentAsFloat("Friction", String.Empty);
}
private static void ProcessBounce(SceneObjectPart obj, XmlReader reader)
{
obj.Restitution = reader.ReadElementContentAsFloat("Bounce", String.Empty);
}
private static void ProcessGravityModifier(SceneObjectPart obj, XmlReader reader)
{
obj.GravityModifier = reader.ReadElementContentAsFloat("GravityModifier", String.Empty);
}
private static void ProcessCameraEyeOffset(SceneObjectPart obj, XmlReader reader)
{
obj.SetCameraEyeOffset(Util.ReadVector(reader, "CameraEyeOffset"));
}
private static void ProcessCameraAtOffset(SceneObjectPart obj, XmlReader reader)
{
obj.SetCameraAtOffset(Util.ReadVector(reader, "CameraAtOffset"));
}
private static void ProcessSoundID(SceneObjectPart obj, XmlReader reader)
{
obj.Sound = Util.ReadUUID(reader, "SoundID");
}
private static void ProcessSoundGain(SceneObjectPart obj, XmlReader reader)
{
obj.SoundGain = reader.ReadElementContentAsDouble("SoundGain", String.Empty);
}
private static void ProcessSoundFlags(SceneObjectPart obj, XmlReader reader)
{
obj.SoundFlags = (byte)reader.ReadElementContentAsInt("SoundFlags", String.Empty);
}
private static void ProcessSoundRadius(SceneObjectPart obj, XmlReader reader)
{
obj.SoundRadius = reader.ReadElementContentAsDouble("SoundRadius", String.Empty);
}
private static void ProcessSoundQueueing(SceneObjectPart obj, XmlReader reader)
{
obj.SoundQueueing = Util.ReadBoolean(reader);
}
private static void ProcessVehicle(SceneObjectPart obj, XmlReader reader)
{
SOPVehicle vehicle = SOPVehicle.FromXml2(reader);
if (vehicle == null)
{
obj.VehicleParams = null;
m_log.DebugFormat(
"[SceneObjectSerializer]: Parsing Vehicle for object part {0} {1} encountered errors. Please see earlier log entries.",
obj.Name, obj.UUID);
}
else
{
obj.VehicleParams = vehicle;
}
}
private static void ProcessShape(SceneObjectPart obj, XmlReader reader)
{
List<string> errorNodeNames;
obj.Shape = ReadShape(reader, "Shape", out errorNodeNames, obj);
if (errorNodeNames != null)
{
m_log.DebugFormat(
"[SceneObjectSerializer]: Parsing PrimitiveBaseShape for object part {0} {1} encountered errors in properties {2}.",
obj.Name, obj.UUID, string.Join(", ", errorNodeNames.ToArray()));
}
}
private static void ProcessScale(SceneObjectPart obj, XmlReader reader)
{
obj.Scale = Util.ReadVector(reader, "Scale");
}
private static void ProcessSitTargetOrientation(SceneObjectPart obj, XmlReader reader)
{
obj.SitTargetOrientation = Util.ReadQuaternion(reader, "SitTargetOrientation");
}
private static void ProcessSitTargetPosition(SceneObjectPart obj, XmlReader reader)
{
obj.SitTargetPosition = Util.ReadVector(reader, "SitTargetPosition");
}
private static void ProcessSitTargetPositionLL(SceneObjectPart obj, XmlReader reader)
{
obj.SitTargetPositionLL = Util.ReadVector(reader, "SitTargetPositionLL");
}
private static void ProcessSitTargetOrientationLL(SceneObjectPart obj, XmlReader reader)
{
obj.SitTargetOrientationLL = Util.ReadQuaternion(reader, "SitTargetOrientationLL");
}
private static void ProcessParentID(SceneObjectPart obj, XmlReader reader)
{
string str = reader.ReadElementContentAsString("ParentID", String.Empty);
obj.ParentID = Convert.ToUInt32(str);
}
private static void ProcessCreationDate(SceneObjectPart obj, XmlReader reader)
{
obj.CreationDate = reader.ReadElementContentAsInt("CreationDate", String.Empty);
}
private static void ProcessCategory(SceneObjectPart obj, XmlReader reader)
{
obj.Category = (uint)reader.ReadElementContentAsInt("Category", String.Empty);
}
private static void ProcessSalePrice(SceneObjectPart obj, XmlReader reader)
{
obj.SalePrice = reader.ReadElementContentAsInt("SalePrice", String.Empty);
}
private static void ProcessObjectSaleType(SceneObjectPart obj, XmlReader reader)
{
obj.ObjectSaleType = (byte)reader.ReadElementContentAsInt("ObjectSaleType", String.Empty);
}
private static void ProcessOwnershipCost(SceneObjectPart obj, XmlReader reader)
{
obj.OwnershipCost = reader.ReadElementContentAsInt("OwnershipCost", String.Empty);
}
private static void ProcessGroupID(SceneObjectPart obj, XmlReader reader)
{
obj.GroupID = Util.ReadUUID(reader, "GroupID");
}
private static void ProcessOwnerID(SceneObjectPart obj, XmlReader reader)
{
obj.OwnerID = Util.ReadUUID(reader, "OwnerID");
}
private static void ProcessLastOwnerID(SceneObjectPart obj, XmlReader reader)
{
obj.LastOwnerID = Util.ReadUUID(reader, "LastOwnerID");
}
private static void ProcessRezzerID(SceneObjectPart obj, XmlReader reader)
{
obj.RezzerID = Util.ReadUUID(reader, "RezzerID");
}
private static void ProcessBaseMask(SceneObjectPart obj, XmlReader reader)
{
obj.BaseMask = (uint)reader.ReadElementContentAsInt("BaseMask", String.Empty);
}
private static void ProcessOwnerMask(SceneObjectPart obj, XmlReader reader)
{
obj.OwnerMask = (uint)reader.ReadElementContentAsInt("OwnerMask", String.Empty);
}
private static void ProcessGroupMask(SceneObjectPart obj, XmlReader reader)
{
obj.GroupMask = (uint)reader.ReadElementContentAsInt("GroupMask", String.Empty);
}
private static void ProcessEveryoneMask(SceneObjectPart obj, XmlReader reader)
{
obj.EveryoneMask = (uint)reader.ReadElementContentAsInt("EveryoneMask", String.Empty);
}
private static void ProcessNextOwnerMask(SceneObjectPart obj, XmlReader reader)
{
obj.NextOwnerMask = (uint)reader.ReadElementContentAsInt("NextOwnerMask", String.Empty);
}
private static void ProcessFlags(SceneObjectPart obj, XmlReader reader)
{
obj.Flags = Util.ReadEnum<PrimFlags>(reader, "Flags");
}
private static void ProcessCollisionSound(SceneObjectPart obj, XmlReader reader)
{
obj.CollisionSound = Util.ReadUUID(reader, "CollisionSound");
}
private static void ProcessCollisionSoundVolume(SceneObjectPart obj, XmlReader reader)
{
obj.CollisionSoundVolume = reader.ReadElementContentAsFloat("CollisionSoundVolume", String.Empty);
}
private static void ProcessMediaUrl(SceneObjectPart obj, XmlReader reader)
{
obj.MediaUrl = reader.ReadElementContentAsString("MediaUrl", String.Empty);
}
private static void ProcessAttachedPos(SceneObjectPart obj, XmlReader reader)
{
obj.AttachedPos = Util.ReadVector(reader, "AttachedPos");
}
private static void ProcessDynAttrs(SceneObjectPart obj, XmlReader reader)
{
obj.DynAttrs.ReadXml(reader);
}
private static void ProcessTextureAnimation(SceneObjectPart obj, XmlReader reader)
{
obj.TextureAnimation = Convert.FromBase64String(reader.ReadElementContentAsString("TextureAnimation", String.Empty));
}
private static void ProcessParticleSystem(SceneObjectPart obj, XmlReader reader)
{
obj.ParticleSystem = Convert.FromBase64String(reader.ReadElementContentAsString("ParticleSystem", String.Empty));
}
private static void ProcessPayPrice0(SceneObjectPart obj, XmlReader reader)
{
obj.PayPrice[0] = (int)reader.ReadElementContentAsInt("PayPrice0", String.Empty);
}
private static void ProcessPayPrice1(SceneObjectPart obj, XmlReader reader)
{
obj.PayPrice[1] = (int)reader.ReadElementContentAsInt("PayPrice1", String.Empty);
}
private static void ProcessPayPrice2(SceneObjectPart obj, XmlReader reader)
{
obj.PayPrice[2] = (int)reader.ReadElementContentAsInt("PayPrice2", String.Empty);
}
private static void ProcessPayPrice3(SceneObjectPart obj, XmlReader reader)
{
obj.PayPrice[3] = (int)reader.ReadElementContentAsInt("PayPrice3", String.Empty);
}
private static void ProcessPayPrice4(SceneObjectPart obj, XmlReader reader)
{
obj.PayPrice[4] = (int)reader.ReadElementContentAsInt("PayPrice4", String.Empty);
}
private static void ProcessBuoyancy(SceneObjectPart obj, XmlReader reader)
{
obj.Buoyancy = (float)reader.ReadElementContentAsFloat("Buoyancy", String.Empty);
}
private static void ProcessForce(SceneObjectPart obj, XmlReader reader)
{
obj.Force = Util.ReadVector(reader, "Force");
}
private static void ProcessTorque(SceneObjectPart obj, XmlReader reader)
{
obj.Torque = Util.ReadVector(reader, "Torque");
}
private static void ProcessVolumeDetectActive(SceneObjectPart obj, XmlReader reader)
{
obj.VolumeDetectActive = Util.ReadBoolean(reader);
}
#endregion
#region TaskInventoryXmlProcessors
private static void ProcessTIAssetID(TaskInventoryItem item, XmlReader reader)
{
item.AssetID = Util.ReadUUID(reader, "AssetID");
}
private static void ProcessTIBasePermissions(TaskInventoryItem item, XmlReader reader)
{
item.BasePermissions = (uint)reader.ReadElementContentAsInt("BasePermissions", String.Empty);
}
private static void ProcessTICreationDate(TaskInventoryItem item, XmlReader reader)
{
item.CreationDate = (uint)reader.ReadElementContentAsInt("CreationDate", String.Empty);
}
private static void ProcessTICreatorID(TaskInventoryItem item, XmlReader reader)
{
item.CreatorID = Util.ReadUUID(reader, "CreatorID");
}
private static void ProcessTICreatorData(TaskInventoryItem item, XmlReader reader)
{
item.CreatorData = reader.ReadElementContentAsString("CreatorData", String.Empty);
}
private static void ProcessTIDescription(TaskInventoryItem item, XmlReader reader)
{
item.Description = reader.ReadElementContentAsString("Description", String.Empty);
}
private static void ProcessTIEveryonePermissions(TaskInventoryItem item, XmlReader reader)
{
item.EveryonePermissions = (uint)reader.ReadElementContentAsInt("EveryonePermissions", String.Empty);
}
private static void ProcessTIFlags(TaskInventoryItem item, XmlReader reader)
{
item.Flags = (uint)reader.ReadElementContentAsInt("Flags", String.Empty);
}
private static void ProcessTIGroupID(TaskInventoryItem item, XmlReader reader)
{
item.GroupID = Util.ReadUUID(reader, "GroupID");
}
private static void ProcessTIGroupPermissions(TaskInventoryItem item, XmlReader reader)
{
item.GroupPermissions = (uint)reader.ReadElementContentAsInt("GroupPermissions", String.Empty);
}
private static void ProcessTIInvType(TaskInventoryItem item, XmlReader reader)
{
item.InvType = reader.ReadElementContentAsInt("InvType", String.Empty);
}
private static void ProcessTIItemID(TaskInventoryItem item, XmlReader reader)
{
item.ItemID = Util.ReadUUID(reader, "ItemID");
}
private static void ProcessTIOldItemID(TaskInventoryItem item, XmlReader reader)
{
item.OldItemID = Util.ReadUUID(reader, "OldItemID");
}
private static void ProcessTILastOwnerID(TaskInventoryItem item, XmlReader reader)
{
item.LastOwnerID = Util.ReadUUID(reader, "LastOwnerID");
}
private static void ProcessTIName(TaskInventoryItem item, XmlReader reader)
{
item.Name = reader.ReadElementContentAsString("Name", String.Empty);
}
private static void ProcessTINextPermissions(TaskInventoryItem item, XmlReader reader)
{
item.NextPermissions = (uint)reader.ReadElementContentAsInt("NextPermissions", String.Empty);
}
private static void ProcessTIOwnerID(TaskInventoryItem item, XmlReader reader)
{
item.OwnerID = Util.ReadUUID(reader, "OwnerID");
}
private static void ProcessTICurrentPermissions(TaskInventoryItem item, XmlReader reader)
{
item.CurrentPermissions = (uint)reader.ReadElementContentAsInt("CurrentPermissions", String.Empty);
}
private static void ProcessTIParentID(TaskInventoryItem item, XmlReader reader)
{
item.ParentID = Util.ReadUUID(reader, "ParentID");
}
private static void ProcessTIParentPartID(TaskInventoryItem item, XmlReader reader)
{
item.ParentPartID = Util.ReadUUID(reader, "ParentPartID");
}
private static void ProcessTIPermsGranter(TaskInventoryItem item, XmlReader reader)
{
item.PermsGranter = Util.ReadUUID(reader, "PermsGranter");
}
private static void ProcessTIPermsMask(TaskInventoryItem item, XmlReader reader)
{
item.PermsMask = reader.ReadElementContentAsInt("PermsMask", String.Empty);
}
private static void ProcessTIType(TaskInventoryItem item, XmlReader reader)
{
item.Type = reader.ReadElementContentAsInt("Type", String.Empty);
}
private static void ProcessTIOwnerChanged(TaskInventoryItem item, XmlReader reader)
{
item.OwnerChanged = Util.ReadBoolean(reader);
}
#endregion
#region ShapeXmlProcessors
private static void ProcessShpProfileCurve(PrimitiveBaseShape shp, XmlReader reader)
{
shp.ProfileCurve = (byte)reader.ReadElementContentAsInt("ProfileCurve", String.Empty);
}
private static void ProcessShpTextureEntry(PrimitiveBaseShape shp, XmlReader reader)
{
byte[] teData = Convert.FromBase64String(reader.ReadElementString("TextureEntry"));
shp.Textures = new Primitive.TextureEntry(teData, 0, teData.Length);
}
private static void ProcessShpExtraParams(PrimitiveBaseShape shp, XmlReader reader)
{
shp.ExtraParams = Convert.FromBase64String(reader.ReadElementString("ExtraParams"));
}
private static void ProcessShpPathBegin(PrimitiveBaseShape shp, XmlReader reader)
{
shp.PathBegin = (ushort)reader.ReadElementContentAsInt("PathBegin", String.Empty);
}
private static void ProcessShpPathCurve(PrimitiveBaseShape shp, XmlReader reader)
{
shp.PathCurve = (byte)reader.ReadElementContentAsInt("PathCurve", String.Empty);
}
private static void ProcessShpPathEnd(PrimitiveBaseShape shp, XmlReader reader)
{
shp.PathEnd = (ushort)reader.ReadElementContentAsInt("PathEnd", String.Empty);
}
private static void ProcessShpPathRadiusOffset(PrimitiveBaseShape shp, XmlReader reader)
{
shp.PathRadiusOffset = (sbyte)reader.ReadElementContentAsInt("PathRadiusOffset", String.Empty);
}
private static void ProcessShpPathRevolutions(PrimitiveBaseShape shp, XmlReader reader)
{
shp.PathRevolutions = (byte)reader.ReadElementContentAsInt("PathRevolutions", String.Empty);
}
private static void ProcessShpPathScaleX(PrimitiveBaseShape shp, XmlReader reader)
{
shp.PathScaleX = (byte)reader.ReadElementContentAsInt("PathScaleX", String.Empty);
}
private static void ProcessShpPathScaleY(PrimitiveBaseShape shp, XmlReader reader)
{
shp.PathScaleY = (byte)reader.ReadElementContentAsInt("PathScaleY", String.Empty);
}
private static void ProcessShpPathShearX(PrimitiveBaseShape shp, XmlReader reader)
{
shp.PathShearX = (byte)reader.ReadElementContentAsInt("PathShearX", String.Empty);
}
private static void ProcessShpPathShearY(PrimitiveBaseShape shp, XmlReader reader)
{
shp.PathShearY = (byte)reader.ReadElementContentAsInt("PathShearY", String.Empty);
}
private static void ProcessShpPathSkew(PrimitiveBaseShape shp, XmlReader reader)
{
shp.PathSkew = (sbyte)reader.ReadElementContentAsInt("PathSkew", String.Empty);
}
private static void ProcessShpPathTaperX(PrimitiveBaseShape shp, XmlReader reader)
{
shp.PathTaperX = (sbyte)reader.ReadElementContentAsInt("PathTaperX", String.Empty);
}
private static void ProcessShpPathTaperY(PrimitiveBaseShape shp, XmlReader reader)
{
shp.PathTaperY = (sbyte)reader.ReadElementContentAsInt("PathTaperY", String.Empty);
}
private static void ProcessShpPathTwist(PrimitiveBaseShape shp, XmlReader reader)
{
shp.PathTwist = (sbyte)reader.ReadElementContentAsInt("PathTwist", String.Empty);
}
private static void ProcessShpPathTwistBegin(PrimitiveBaseShape shp, XmlReader reader)
{
shp.PathTwistBegin = (sbyte)reader.ReadElementContentAsInt("PathTwistBegin", String.Empty);
}
private static void ProcessShpPCode(PrimitiveBaseShape shp, XmlReader reader)
{
shp.PCode = (byte)reader.ReadElementContentAsInt("PCode", String.Empty);
}
private static void ProcessShpProfileBegin(PrimitiveBaseShape shp, XmlReader reader)
{
shp.ProfileBegin = (ushort)reader.ReadElementContentAsInt("ProfileBegin", String.Empty);
}
private static void ProcessShpProfileEnd(PrimitiveBaseShape shp, XmlReader reader)
{
shp.ProfileEnd = (ushort)reader.ReadElementContentAsInt("ProfileEnd", String.Empty);
}
private static void ProcessShpProfileHollow(PrimitiveBaseShape shp, XmlReader reader)
{
shp.ProfileHollow = (ushort)reader.ReadElementContentAsInt("ProfileHollow", String.Empty);
}
private static void ProcessShpScale(PrimitiveBaseShape shp, XmlReader reader)
{
shp.Scale = Util.ReadVector(reader, "Scale");
}
private static void ProcessShpState(PrimitiveBaseShape shp, XmlReader reader)
{
shp.State = (byte)reader.ReadElementContentAsInt("State", String.Empty);
}
private static void ProcessShpLastAttach(PrimitiveBaseShape shp, XmlReader reader)
{
shp.LastAttachPoint = (byte)reader.ReadElementContentAsInt("LastAttachPoint", String.Empty);
}
private static void ProcessShpProfileShape(PrimitiveBaseShape shp, XmlReader reader)
{
shp.ProfileShape = Util.ReadEnum<ProfileShape>(reader, "ProfileShape");
}
private static void ProcessShpHollowShape(PrimitiveBaseShape shp, XmlReader reader)
{
shp.HollowShape = Util.ReadEnum<HollowShape>(reader, "HollowShape");
}
private static void ProcessShpSculptTexture(PrimitiveBaseShape shp, XmlReader reader)
{
shp.SculptTexture = Util.ReadUUID(reader, "SculptTexture");
}
private static void ProcessShpSculptType(PrimitiveBaseShape shp, XmlReader reader)
{
shp.SculptType = (byte)reader.ReadElementContentAsInt("SculptType", String.Empty);
}
private static void ProcessShpFlexiSoftness(PrimitiveBaseShape shp, XmlReader reader)
{
shp.FlexiSoftness = reader.ReadElementContentAsInt("FlexiSoftness", String.Empty);
}
private static void ProcessShpFlexiTension(PrimitiveBaseShape shp, XmlReader reader)
{
shp.FlexiTension = reader.ReadElementContentAsFloat("FlexiTension", String.Empty);
}
private static void ProcessShpFlexiDrag(PrimitiveBaseShape shp, XmlReader reader)
{
shp.FlexiDrag = reader.ReadElementContentAsFloat("FlexiDrag", String.Empty);
}
private static void ProcessShpFlexiGravity(PrimitiveBaseShape shp, XmlReader reader)
{
shp.FlexiGravity = reader.ReadElementContentAsFloat("FlexiGravity", String.Empty);
}
private static void ProcessShpFlexiWind(PrimitiveBaseShape shp, XmlReader reader)
{
shp.FlexiWind = reader.ReadElementContentAsFloat("FlexiWind", String.Empty);
}
private static void ProcessShpFlexiForceX(PrimitiveBaseShape shp, XmlReader reader)
{
shp.FlexiForceX = reader.ReadElementContentAsFloat("FlexiForceX", String.Empty);
}
private static void ProcessShpFlexiForceY(PrimitiveBaseShape shp, XmlReader reader)
{
shp.FlexiForceY = reader.ReadElementContentAsFloat("FlexiForceY", String.Empty);
}
private static void ProcessShpFlexiForceZ(PrimitiveBaseShape shp, XmlReader reader)
{
shp.FlexiForceZ = reader.ReadElementContentAsFloat("FlexiForceZ", String.Empty);
}
private static void ProcessShpLightColorR(PrimitiveBaseShape shp, XmlReader reader)
{
shp.LightColorR = reader.ReadElementContentAsFloat("LightColorR", String.Empty);
}
private static void ProcessShpLightColorG(PrimitiveBaseShape shp, XmlReader reader)
{
shp.LightColorG = reader.ReadElementContentAsFloat("LightColorG", String.Empty);
}
private static void ProcessShpLightColorB(PrimitiveBaseShape shp, XmlReader reader)
{
shp.LightColorB = reader.ReadElementContentAsFloat("LightColorB", String.Empty);
}
private static void ProcessShpLightColorA(PrimitiveBaseShape shp, XmlReader reader)
{
shp.LightColorA = reader.ReadElementContentAsFloat("LightColorA", String.Empty);
}
private static void ProcessShpLightRadius(PrimitiveBaseShape shp, XmlReader reader)
{
shp.LightRadius = reader.ReadElementContentAsFloat("LightRadius", String.Empty);
}
private static void ProcessShpLightCutoff(PrimitiveBaseShape shp, XmlReader reader)
{
shp.LightCutoff = reader.ReadElementContentAsFloat("LightCutoff", String.Empty);
}
private static void ProcessShpLightFalloff(PrimitiveBaseShape shp, XmlReader reader)
{
shp.LightFalloff = reader.ReadElementContentAsFloat("LightFalloff", String.Empty);
}
private static void ProcessShpLightIntensity(PrimitiveBaseShape shp, XmlReader reader)
{
shp.LightIntensity = reader.ReadElementContentAsFloat("LightIntensity", String.Empty);
}
private static void ProcessShpFlexiEntry(PrimitiveBaseShape shp, XmlReader reader)
{
shp.FlexiEntry = Util.ReadBoolean(reader);
}
private static void ProcessShpLightEntry(PrimitiveBaseShape shp, XmlReader reader)
{
shp.LightEntry = Util.ReadBoolean(reader);
}
private static void ProcessShpSculptEntry(PrimitiveBaseShape shp, XmlReader reader)
{
shp.SculptEntry = Util.ReadBoolean(reader);
}
private static void ProcessShpMedia(PrimitiveBaseShape shp, XmlReader reader)
{
string value = reader.ReadElementContentAsString("Media", String.Empty);
shp.Media = PrimitiveBaseShape.MediaList.FromXml(value);
}
#endregion
////////// Write /////////
public static void SOGToXml2(XmlTextWriter writer, SceneObjectGroup sog, Dictionary<string, object>options)
{
writer.WriteStartElement(String.Empty, "SceneObjectGroup", String.Empty);
SOPToXml2(writer, sog.RootPart, options);
writer.WriteStartElement(String.Empty, "OtherParts", String.Empty);
sog.ForEachPart(delegate(SceneObjectPart sop)
{
if (sop.UUID != sog.RootPart.UUID)
SOPToXml2(writer, sop, options);
});
writer.WriteEndElement();
if (sog.RootPart.KeyframeMotion != null)
{
Byte[] data = sog.RootPart.KeyframeMotion.Serialize();
writer.WriteStartElement(String.Empty, "KeyframeMotion", String.Empty);
writer.WriteBase64(data, 0, data.Length);
writer.WriteEndElement();
}
writer.WriteEndElement();
}
public static void SOPToXml2(XmlTextWriter writer, SceneObjectPart sop, Dictionary<string, object> options)
{
writer.WriteStartElement("SceneObjectPart");
writer.WriteAttributeString("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance");
writer.WriteAttributeString("xmlns:xsd", "http://www.w3.org/2001/XMLSchema");
writer.WriteElementString("AllowedDrop", sop.AllowedDrop.ToString().ToLower());
WriteUUID(writer, "CreatorID", sop.CreatorID, options);
if (!string.IsNullOrEmpty(sop.CreatorData))
writer.WriteElementString("CreatorData", sop.CreatorData);
else if (options.ContainsKey("home"))
{
if (m_UserManagement == null)
m_UserManagement = sop.ParentGroup.Scene.RequestModuleInterface<IUserManagement>();
string name = m_UserManagement.GetUserName(sop.CreatorID);
writer.WriteElementString("CreatorData", ExternalRepresentationUtils.CalcCreatorData((string)options["home"], name));
}
WriteUUID(writer, "FolderID", sop.FolderID, options);
writer.WriteElementString("InventorySerial", sop.InventorySerial.ToString());
WriteTaskInventory(writer, sop.TaskInventory, options, sop.ParentGroup.Scene);
WriteUUID(writer, "UUID", sop.UUID, options);
writer.WriteElementString("LocalId", sop.LocalId.ToString());
writer.WriteElementString("Name", sop.Name);
writer.WriteElementString("Material", sop.Material.ToString());
writer.WriteElementString("PassTouches", sop.PassTouches.ToString().ToLower());
writer.WriteElementString("PassCollisions", sop.PassCollisions.ToString().ToLower());
writer.WriteElementString("RegionHandle", sop.RegionHandle.ToString());
writer.WriteElementString("ScriptAccessPin", sop.ScriptAccessPin.ToString());
WriteVector(writer, "GroupPosition", sop.GroupPosition);
WriteVector(writer, "OffsetPosition", sop.OffsetPosition);
WriteQuaternion(writer, "RotationOffset", sop.RotationOffset);
WriteVector(writer, "Velocity", sop.Velocity);
WriteVector(writer, "AngularVelocity", sop.AngularVelocity);
WriteVector(writer, "Acceleration", sop.Acceleration);
writer.WriteElementString("Description", sop.Description);
writer.WriteStartElement("Color");
writer.WriteElementString("R", sop.Color.R.ToString(Utils.EnUsCulture));
writer.WriteElementString("G", sop.Color.G.ToString(Utils.EnUsCulture));
writer.WriteElementString("B", sop.Color.B.ToString(Utils.EnUsCulture));
writer.WriteElementString("A", sop.Color.A.ToString(Utils.EnUsCulture));
writer.WriteEndElement();
writer.WriteElementString("Text", sop.Text);
writer.WriteElementString("SitName", sop.SitName);
writer.WriteElementString("TouchName", sop.TouchName);
writer.WriteElementString("LinkNum", sop.LinkNum.ToString());
writer.WriteElementString("ClickAction", sop.ClickAction.ToString());
WriteShape(writer, sop.Shape, options);
WriteVector(writer, "Scale", sop.Scale);
WriteQuaternion(writer, "SitTargetOrientation", sop.SitTargetOrientation);
WriteVector(writer, "SitTargetPosition", sop.SitTargetPosition);
WriteVector(writer, "SitTargetPositionLL", sop.SitTargetPositionLL);
WriteQuaternion(writer, "SitTargetOrientationLL", sop.SitTargetOrientationLL);
writer.WriteElementString("ParentID", sop.ParentID.ToString());
writer.WriteElementString("CreationDate", sop.CreationDate.ToString());
writer.WriteElementString("Category", sop.Category.ToString());
writer.WriteElementString("SalePrice", sop.SalePrice.ToString());
writer.WriteElementString("ObjectSaleType", sop.ObjectSaleType.ToString());
writer.WriteElementString("OwnershipCost", sop.OwnershipCost.ToString());
UUID groupID = options.ContainsKey("wipe-owners") ? UUID.Zero : sop.GroupID;
WriteUUID(writer, "GroupID", groupID, options);
UUID ownerID = options.ContainsKey("wipe-owners") ? UUID.Zero : sop.OwnerID;
WriteUUID(writer, "OwnerID", ownerID, options);
UUID lastOwnerID = options.ContainsKey("wipe-owners") ? UUID.Zero : sop.LastOwnerID;
WriteUUID(writer, "LastOwnerID", lastOwnerID, options);
UUID rezzerID = options.ContainsKey("wipe-owners") ? UUID.Zero : sop.RezzerID;
WriteUUID(writer, "RezzerID", rezzerID, options);
writer.WriteElementString("BaseMask", sop.BaseMask.ToString());
writer.WriteElementString("OwnerMask", sop.OwnerMask.ToString());
writer.WriteElementString("GroupMask", sop.GroupMask.ToString());
writer.WriteElementString("EveryoneMask", sop.EveryoneMask.ToString());
writer.WriteElementString("NextOwnerMask", sop.NextOwnerMask.ToString());
WriteFlags(writer, "Flags", sop.Flags.ToString(), options);
WriteUUID(writer, "CollisionSound", sop.CollisionSound, options);
writer.WriteElementString("CollisionSoundVolume", sop.CollisionSoundVolume.ToString());
if (sop.MediaUrl != null)
writer.WriteElementString("MediaUrl", sop.MediaUrl.ToString());
WriteVector(writer, "AttachedPos", sop.AttachedPos);
if (sop.DynAttrs.CountNamespaces > 0)
{
writer.WriteStartElement("DynAttrs");
sop.DynAttrs.WriteXml(writer);
writer.WriteEndElement();
}
WriteBytes(writer, "TextureAnimation", sop.TextureAnimation);
WriteBytes(writer, "ParticleSystem", sop.ParticleSystem);
writer.WriteElementString("PayPrice0", sop.PayPrice[0].ToString());
writer.WriteElementString("PayPrice1", sop.PayPrice[1].ToString());
writer.WriteElementString("PayPrice2", sop.PayPrice[2].ToString());
writer.WriteElementString("PayPrice3", sop.PayPrice[3].ToString());
writer.WriteElementString("PayPrice4", sop.PayPrice[4].ToString());
writer.WriteElementString("Buoyancy", sop.Buoyancy.ToString());
WriteVector(writer, "Force", sop.Force);
WriteVector(writer, "Torque", sop.Torque);
writer.WriteElementString("VolumeDetectActive", sop.VolumeDetectActive.ToString().ToLower());
if (sop.VehicleParams != null)
sop.VehicleParams.ToXml2(writer);
if(sop.RotationAxisLocks != 0)
writer.WriteElementString("RotationAxisLocks", sop.RotationAxisLocks.ToString().ToLower());
writer.WriteElementString("PhysicsShapeType", sop.PhysicsShapeType.ToString().ToLower());
if (sop.Density != 1000.0f)
writer.WriteElementString("Density", sop.Density.ToString().ToLower());
if (sop.Friction != 0.6f)
writer.WriteElementString("Friction", sop.Friction.ToString().ToLower());
if (sop.Restitution != 0.5f)
writer.WriteElementString("Bounce", sop.Restitution.ToString().ToLower());
if (sop.GravityModifier != 1.0f)
writer.WriteElementString("GravityModifier", sop.GravityModifier.ToString().ToLower());
WriteVector(writer, "CameraEyeOffset", sop.GetCameraEyeOffset());
WriteVector(writer, "CameraAtOffset", sop.GetCameraAtOffset());
// if (sop.Sound != UUID.Zero) force it till sop crossing does clear it on child prim
{
WriteUUID(writer, "SoundID", sop.Sound, options);
writer.WriteElementString("SoundGain", sop.SoundGain.ToString().ToLower());
writer.WriteElementString("SoundFlags", sop.SoundFlags.ToString().ToLower());
writer.WriteElementString("SoundRadius", sop.SoundRadius.ToString().ToLower());
}
writer.WriteElementString("SoundQueueing", sop.SoundQueueing.ToString().ToLower());
writer.WriteEndElement();
}
static void WriteUUID(XmlTextWriter writer, string name, UUID id, Dictionary<string, object> options)
{
writer.WriteStartElement(name);
if (options.ContainsKey("old-guids"))
writer.WriteElementString("Guid", id.ToString());
else
writer.WriteElementString("UUID", id.ToString());
writer.WriteEndElement();
}
static void WriteVector(XmlTextWriter writer, string name, Vector3 vec)
{
writer.WriteStartElement(name);
writer.WriteElementString("X", vec.X.ToString(Utils.EnUsCulture));
writer.WriteElementString("Y", vec.Y.ToString(Utils.EnUsCulture));
writer.WriteElementString("Z", vec.Z.ToString(Utils.EnUsCulture));
writer.WriteEndElement();
}
static void WriteQuaternion(XmlTextWriter writer, string name, Quaternion quat)
{
writer.WriteStartElement(name);
writer.WriteElementString("X", quat.X.ToString(Utils.EnUsCulture));
writer.WriteElementString("Y", quat.Y.ToString(Utils.EnUsCulture));
writer.WriteElementString("Z", quat.Z.ToString(Utils.EnUsCulture));
writer.WriteElementString("W", quat.W.ToString(Utils.EnUsCulture));
writer.WriteEndElement();
}
static void WriteBytes(XmlTextWriter writer, string name, byte[] data)
{
writer.WriteStartElement(name);
byte[] d;
if (data != null)
d = data;
else
d = Utils.EmptyBytes;
writer.WriteBase64(d, 0, d.Length);
writer.WriteEndElement(); // name
}
static void WriteFlags(XmlTextWriter writer, string name, string flagsStr, Dictionary<string, object> options)
{
// Older versions of serialization can't cope with commas, so we eliminate the commas
writer.WriteElementString(name, flagsStr.Replace(",", ""));
}
public static void WriteTaskInventory(XmlTextWriter writer, TaskInventoryDictionary tinv, Dictionary<string, object> options, Scene scene)
{
if (tinv.Count > 0) // otherwise skip this
{
writer.WriteStartElement("TaskInventory");
foreach (TaskInventoryItem item in tinv.Values)
{
writer.WriteStartElement("TaskInventoryItem");
WriteUUID(writer, "AssetID", item.AssetID, options);
writer.WriteElementString("BasePermissions", item.BasePermissions.ToString());
writer.WriteElementString("CreationDate", item.CreationDate.ToString());
WriteUUID(writer, "CreatorID", item.CreatorID, options);
if (!string.IsNullOrEmpty(item.CreatorData))
writer.WriteElementString("CreatorData", item.CreatorData);
else if (options.ContainsKey("home"))
{
if (m_UserManagement == null)
m_UserManagement = scene.RequestModuleInterface<IUserManagement>();
string name = m_UserManagement.GetUserName(item.CreatorID);
writer.WriteElementString("CreatorData", ExternalRepresentationUtils.CalcCreatorData((string)options["home"], name));
}
writer.WriteElementString("Description", item.Description);
writer.WriteElementString("EveryonePermissions", item.EveryonePermissions.ToString());
writer.WriteElementString("Flags", item.Flags.ToString());
UUID groupID = options.ContainsKey("wipe-owners") ? UUID.Zero : item.GroupID;
WriteUUID(writer, "GroupID", groupID, options);
writer.WriteElementString("GroupPermissions", item.GroupPermissions.ToString());
writer.WriteElementString("InvType", item.InvType.ToString());
WriteUUID(writer, "ItemID", item.ItemID, options);
WriteUUID(writer, "OldItemID", item.OldItemID, options);
UUID lastOwnerID = options.ContainsKey("wipe-owners") ? UUID.Zero : item.LastOwnerID;
WriteUUID(writer, "LastOwnerID", lastOwnerID, options);
writer.WriteElementString("Name", item.Name);
writer.WriteElementString("NextPermissions", item.NextPermissions.ToString());
UUID ownerID = options.ContainsKey("wipe-owners") ? UUID.Zero : item.OwnerID;
WriteUUID(writer, "OwnerID", ownerID, options);
writer.WriteElementString("CurrentPermissions", item.CurrentPermissions.ToString());
WriteUUID(writer, "ParentID", item.ParentID, options);
WriteUUID(writer, "ParentPartID", item.ParentPartID, options);
WriteUUID(writer, "PermsGranter", item.PermsGranter, options);
writer.WriteElementString("PermsMask", item.PermsMask.ToString());
writer.WriteElementString("Type", item.Type.ToString());
bool ownerChanged = options.ContainsKey("wipe-owners") ? false : item.OwnerChanged;
writer.WriteElementString("OwnerChanged", ownerChanged.ToString().ToLower());
writer.WriteEndElement(); // TaskInventoryItem
}
writer.WriteEndElement(); // TaskInventory
}
}
public static void WriteShape(XmlTextWriter writer, PrimitiveBaseShape shp, Dictionary<string, object> options)
{
if (shp != null)
{
writer.WriteStartElement("Shape");
writer.WriteElementString("ProfileCurve", shp.ProfileCurve.ToString());
writer.WriteStartElement("TextureEntry");
byte[] te;
if (shp.TextureEntry != null)
te = shp.TextureEntry;
else
te = Utils.EmptyBytes;
writer.WriteBase64(te, 0, te.Length);
writer.WriteEndElement(); // TextureEntry
writer.WriteStartElement("ExtraParams");
byte[] ep;
if (shp.ExtraParams != null)
ep = shp.ExtraParams;
else
ep = Utils.EmptyBytes;
writer.WriteBase64(ep, 0, ep.Length);
writer.WriteEndElement(); // ExtraParams
writer.WriteElementString("PathBegin", shp.PathBegin.ToString());
writer.WriteElementString("PathCurve", shp.PathCurve.ToString());
writer.WriteElementString("PathEnd", shp.PathEnd.ToString());
writer.WriteElementString("PathRadiusOffset", shp.PathRadiusOffset.ToString());
writer.WriteElementString("PathRevolutions", shp.PathRevolutions.ToString());
writer.WriteElementString("PathScaleX", shp.PathScaleX.ToString());
writer.WriteElementString("PathScaleY", shp.PathScaleY.ToString());
writer.WriteElementString("PathShearX", shp.PathShearX.ToString());
writer.WriteElementString("PathShearY", shp.PathShearY.ToString());
writer.WriteElementString("PathSkew", shp.PathSkew.ToString());
writer.WriteElementString("PathTaperX", shp.PathTaperX.ToString());
writer.WriteElementString("PathTaperY", shp.PathTaperY.ToString());
writer.WriteElementString("PathTwist", shp.PathTwist.ToString());
writer.WriteElementString("PathTwistBegin", shp.PathTwistBegin.ToString());
writer.WriteElementString("PCode", shp.PCode.ToString());
writer.WriteElementString("ProfileBegin", shp.ProfileBegin.ToString());
writer.WriteElementString("ProfileEnd", shp.ProfileEnd.ToString());
writer.WriteElementString("ProfileHollow", shp.ProfileHollow.ToString());
writer.WriteElementString("State", shp.State.ToString());
writer.WriteElementString("LastAttachPoint", shp.LastAttachPoint.ToString());
WriteFlags(writer, "ProfileShape", shp.ProfileShape.ToString(), options);
WriteFlags(writer, "HollowShape", shp.HollowShape.ToString(), options);
WriteUUID(writer, "SculptTexture", shp.SculptTexture, options);
writer.WriteElementString("SculptType", shp.SculptType.ToString());
// Don't serialize SculptData. It's just a copy of the asset, which can be loaded separately using 'SculptTexture'.
writer.WriteElementString("FlexiSoftness", shp.FlexiSoftness.ToString());
writer.WriteElementString("FlexiTension", shp.FlexiTension.ToString());
writer.WriteElementString("FlexiDrag", shp.FlexiDrag.ToString());
writer.WriteElementString("FlexiGravity", shp.FlexiGravity.ToString());
writer.WriteElementString("FlexiWind", shp.FlexiWind.ToString());
writer.WriteElementString("FlexiForceX", shp.FlexiForceX.ToString());
writer.WriteElementString("FlexiForceY", shp.FlexiForceY.ToString());
writer.WriteElementString("FlexiForceZ", shp.FlexiForceZ.ToString());
writer.WriteElementString("LightColorR", shp.LightColorR.ToString());
writer.WriteElementString("LightColorG", shp.LightColorG.ToString());
writer.WriteElementString("LightColorB", shp.LightColorB.ToString());
writer.WriteElementString("LightColorA", shp.LightColorA.ToString());
writer.WriteElementString("LightRadius", shp.LightRadius.ToString());
writer.WriteElementString("LightCutoff", shp.LightCutoff.ToString());
writer.WriteElementString("LightFalloff", shp.LightFalloff.ToString());
writer.WriteElementString("LightIntensity", shp.LightIntensity.ToString());
writer.WriteElementString("FlexiEntry", shp.FlexiEntry.ToString().ToLower());
writer.WriteElementString("LightEntry", shp.LightEntry.ToString().ToLower());
writer.WriteElementString("SculptEntry", shp.SculptEntry.ToString().ToLower());
if (shp.Media != null)
writer.WriteElementString("Media", shp.Media.ToXml());
writer.WriteEndElement(); // Shape
}
}
public static SceneObjectPart Xml2ToSOP(XmlReader reader)
{
SceneObjectPart obj = new SceneObjectPart();
reader.ReadStartElement("SceneObjectPart");
bool errors = ExternalRepresentationUtils.ExecuteReadProcessors(
obj,
m_SOPXmlProcessors,
reader,
(o, nodeName, e) => {
m_log.Debug(string.Format("[SceneObjectSerializer]: Error while parsing element {0} in object {1} {2} ",
nodeName, ((SceneObjectPart)o).Name, ((SceneObjectPart)o).UUID), e);
});
if (errors)
throw new XmlException(string.Format("Error parsing object {0} {1}", obj.Name, obj.UUID));
reader.ReadEndElement(); // SceneObjectPart
obj.AggregateInnerPerms();
// m_log.DebugFormat("[SceneObjectSerializer]: parsed SOP {0} {1}", obj.Name, obj.UUID);
return obj;
}
public static TaskInventoryDictionary ReadTaskInventory(XmlReader reader, string name)
{
TaskInventoryDictionary tinv = new TaskInventoryDictionary();
reader.ReadStartElement(name, String.Empty);
while (reader.Name == "TaskInventoryItem")
{
reader.ReadStartElement("TaskInventoryItem", String.Empty); // TaskInventory
TaskInventoryItem item = new TaskInventoryItem();
ExternalRepresentationUtils.ExecuteReadProcessors(
item,
m_TaskInventoryXmlProcessors,
reader);
reader.ReadEndElement(); // TaskInventoryItem
tinv.Add(item.ItemID, item);
}
if (reader.NodeType == XmlNodeType.EndElement)
reader.ReadEndElement(); // TaskInventory
return tinv;
}
/// <summary>
/// Read a shape from xml input
/// </summary>
/// <param name="reader"></param>
/// <param name="name">The name of the xml element containing the shape</param>
/// <param name="errors">a list containing the failing node names. If no failures then null.</param>
/// <returns>The shape parsed</returns>
public static PrimitiveBaseShape ReadShape(XmlReader reader, string name, out List<string> errorNodeNames, SceneObjectPart obj)
{
List<string> internalErrorNodeNames = null;
PrimitiveBaseShape shape = new PrimitiveBaseShape();
if (reader.IsEmptyElement)
{
reader.Read();
errorNodeNames = null;
return shape;
}
reader.ReadStartElement(name, String.Empty); // Shape
ExternalRepresentationUtils.ExecuteReadProcessors(
shape,
m_ShapeXmlProcessors,
reader,
(o, nodeName, e) => {
m_log.Debug(string.Format("[SceneObjectSerializer]: Error while parsing element {0} in Shape property of object {1} {2} ",
nodeName, obj.Name, obj.UUID), e);
if (internalErrorNodeNames == null)
internalErrorNodeNames = new List<string>();
internalErrorNodeNames.Add(nodeName);
});
reader.ReadEndElement(); // Shape
errorNodeNames = internalErrorNodeNames;
return shape;
}
#endregion
}
}
| |
using UnityEngine;
using System.Collections;
public class TempTestingCancel : MonoBehaviour {
public bool isTweening = false;
public bool tweenOverride = false;
private LTDescr tween;
// Use this for initialization
void Start () {
tween = LeanTween.move(gameObject, transform.position + Vector3.one*3f, Random.Range(2,2) ).setRepeat(-1).setLoopClamp ();
}
public void Update () {
if(tween != null){
isTweening = LeanTween.isTweening(gameObject);
if(tweenOverride){
// this next line works
//tween.cancel();
// this one doesn't
LeanTween.cancel(gameObject);
}
}
}
}
public class TestingEverything : MonoBehaviour {
public GameObject cube1;
public GameObject cube2;
public GameObject cube3;
private bool eventGameObjectWasCalled = false, eventGeneralWasCalled = false;
private LTDescr lt1;
private LTDescr lt2;
private LTDescr lt3;
private LTDescr lt4;
private LTDescr[] groupTweens;
private GameObject[] groupGOs;
private int groupTweensCnt;
private int rotateRepeat;
private int rotateRepeatAngle;
void Start () {
LeanTest.expected = 22;
// add a listener
LeanTween.addListener(cube1, 0, eventGameObjectCalled);
LeanTest.debug("NOTHING TWEEENING AT BEGINNING", LeanTween.isTweening() == false );
LeanTest.debug("OBJECT NOT TWEEENING AT BEGINNING", LeanTween.isTweening(cube1) == false );
// dispatch event that is received
LeanTween.dispatchEvent(0);
LeanTest.debug("EVENT GAMEOBJECT RECEIVED", eventGameObjectWasCalled );
// do not remove listener
LeanTest.debug("EVENT GAMEOBJECT NOT REMOVED", LeanTween.removeListener(cube2, 0, eventGameObjectCalled)==false );
// remove listener
LeanTest.debug("EVENT GAMEOBJECT REMOVED", LeanTween.removeListener(cube1, 0, eventGameObjectCalled) );
// add a listener
LeanTween.addListener(1, eventGeneralCalled);
// dispatch event that is received
LeanTween.dispatchEvent(1);
LeanTest.debug("EVENT ALL RECEIVED", eventGeneralWasCalled );
// remove listener
LeanTest.debug("EVENT ALL REMOVED", LeanTween.removeListener( 1, eventGeneralCalled) );
lt1 = LeanTween.move( cube1, new Vector3(3f,2f,0.5f), 1.1f );
LeanTween.move( cube2, new Vector3(-3f,-2f,-0.5f), 1.1f );
LeanTween.reset();
// ping pong
// rotateAround, Repeat, DestroyOnComplete
rotateRepeat = rotateRepeatAngle = 0;
LeanTween.rotateAround(cube3, Vector3.forward, 360f, 0.1f).setRepeat(3).setOnComplete(rotateRepeatFinished).setOnCompleteOnRepeat(true).setDestroyOnComplete(true);
LeanTween.delayedCall(0.1f*8f, rotateRepeatAllFinished);
// test all onUpdates and onCompletes are removed when tween is initialized
StartCoroutine( timeBasedTesting() );
}
IEnumerator timeBasedTesting(){
yield return new WaitForEndOfFrame();
yield return new WaitForEndOfFrame();
// Groups of tweens testing
groupTweens = new LTDescr[ 300 ];
groupGOs = new GameObject[ groupTweens.Length ];
groupTweensCnt = 0;
int descriptionMatchCount = 0;
for(int i = 0; i < groupTweens.Length; i++){
GameObject cube = GameObject.CreatePrimitive(PrimitiveType.Cube);
Destroy( cube.GetComponent( typeof(BoxCollider) ) as Component );
cube.transform.position = new Vector3(0,0,i*3);
cube.name = "c"+i;
groupGOs[i] = cube;
groupTweens[i] = LeanTween.move(cube, transform.position + Vector3.one*3f, 0.6f ).setOnComplete(groupTweenFinished);
if(LeanTween.description(groupTweens[i].id).trans==groupTweens[i].trans)
descriptionMatchCount++;
}
LeanTween.delayedCall(0.82f, groupTweensFinished);
LeanTest.debug("GROUP IDS MATCH", descriptionMatchCount==groupTweens.Length );
LeanTest.debug("MAX SEARCH OPTIMIZED", LeanTween.maxSearch<=groupTweens.Length+5, "maxSearch:"+LeanTween.maxSearch );
LeanTest.debug("SOMETHING IS TWEENING", LeanTween.isTweening() == true );
// resume item before calling pause should continue item along it's way
float previousXLT3 = cube3.transform.position.x;
lt3 = LeanTween.moveX( cube3, 5.0f, 1.1f);
lt3.resume();
yield return new WaitForEndOfFrame();
yield return new WaitForEndOfFrame();
lt1.cancel();
LeanTween.cancel(cube2);
int tweenCount = 0;
for(int i = 0; i < groupTweens.Length; i++){
if(LeanTween.isTweening( groupGOs[i] ))
tweenCount++;
if(i%3==0)
LeanTween.pause( groupGOs[i] );
else if(i%3==1)
groupTweens[i].pause();
else
LeanTween.pause( groupTweens[i].id );
}
LeanTest.debug("GROUP ISTWEENING", tweenCount==groupTweens.Length, "expected "+groupTweens.Length+" tweens but got "+tweenCount );
LeanTest.debug("RESUME OUT OF ORDER", previousXLT3!=cube3.transform.position.x, "previousXLT3:"+previousXLT3+" cube3.transform.position.x:"+cube3.transform.position.x);
yield return new WaitForEndOfFrame();
tweenCount = 0;
for(int i = 0; i < groupTweens.Length; i++){
if(i%3==0)
LeanTween.resume( groupGOs[i] );
else if(i%3==1)
groupTweens[i].resume();
else
LeanTween.resume( groupTweens[i].id );
if(i%2==0 ? LeanTween.isTweening( groupTweens[i].id ) : LeanTween.isTweening( groupGOs[i] ) )
tweenCount++;
}
LeanTest.debug("GROUP RESUME", tweenCount==groupTweens.Length );
LeanTest.debug("CANCEL TWEEN LTDESCR", LeanTween.isTweening(cube1)==false );
LeanTest.debug("CANCEL TWEEN LEANTWEEN", LeanTween.isTweening(cube2)==false );
Time.timeScale = 0.25f;
float start = Time.realtimeSinceStartup;
LeanTween.moveX(cube1, -5f, 0.2f).setOnComplete( ()=>{
float end = Time.realtimeSinceStartup;
float diff = end - start;
LeanTest.debug("SCALED TIMING diff:"+diff, Mathf.Abs(0.8f - diff) < 0.05f, "expected to complete in 0.8f but completed in "+diff );
LeanTest.debug("SCALED ENDING POSITION", Mathf.Approximately(cube1.transform.position.x, -5f), "expected to end at -5f, but it ended at "+cube1.transform.position.x);
});
int ltCount = 0;
GameObject[] allGos = FindObjectsOfType(typeof(GameObject)) as GameObject[];
foreach (GameObject go in allGos) {
if(go.name == "~LeanTween")
ltCount++;
}
LeanTest.debug("RESET CORRECTLY CLEANS UP", ltCount==1 );
}
void rotateRepeatFinished(){
if( Mathf.Abs(cube3.transform.eulerAngles.z)<0.0001f )
rotateRepeatAngle++;
rotateRepeat++;
}
void rotateRepeatAllFinished(){
LeanTest.debug("ROTATE AROUND MULTIPLE", rotateRepeatAngle==3, "expected 3 times received "+rotateRepeatAngle+" times" );
LeanTest.debug("ROTATE REPEAT", rotateRepeat==3 );
LeanTest.debug("DESTROY ON COMPLETE", cube3==null, "cube3:"+cube3 );
}
void groupTweenFinished(){
groupTweensCnt++;
}
void groupTweensFinished(){
LeanTest.debug("GROUP FINISH", groupTweensCnt==groupTweens.Length, "expected "+groupTweens.Length+" tweens but got "+groupTweensCnt);
}
void eventGameObjectCalled( LTEvent e ){
eventGameObjectWasCalled = true;
}
void eventGeneralCalled( LTEvent e ){
eventGeneralWasCalled = true;
}
}
| |
using System.Collections;
using Game;
using Game.Enums;
using Mod;
using Mod.Managers;
using Mod.Modules;
using Photon;
using Photon.Enums;
using UnityEngine;
using Extensions = Photon.Extensions;
using MonoBehaviour = UnityEngine.MonoBehaviour;
// ReSharper disable once CheckNamespace
public class AHSSShotGunCollider : MonoBehaviour
{
public bool active_me;
public GameObject currentCamera;
public ArrayList currentHits = new ArrayList();
public int dmg;
private int myTeam = 1;
private string ownerName = string.Empty;
public float scoreMulti;
private int viewID = -1;
private bool CheckIfBehind(GameObject titan)
{
Transform neck = titan.transform.Find("Amarture/Core/Controller_Body/hip/spine/chest/neck/head");
Vector3 to = this.transform.position - neck.transform.position;
return Vector3.Angle(-neck.transform.forward, to) < 100f;
}
private int _times;
private void FixedUpdate()
{
if (!active_me)
return;
if (_times > 1)
active_me = false;
_times++;
}
private void OnTriggerStay(Collider other)
{
if (IN_GAME_MAIN_CAMERA.GameType == GameType.Multiplayer && !transform.root.gameObject.GetPhotonView().isMine || !active_me)
return;
if (other.gameObject.CompareTag("playerHitbox"))
{
if (ModuleManager.Enabled(nameof(ModulePVPEverywhere)) || LevelInfoManager.Get(GameManager.Level).IsPvP)
{
float b = 1f - Vector3.Distance(other.gameObject.transform.position, transform.position) * 0.05f;
b = Mathf.Min(1f, b);
HitBox component = other.gameObject.GetComponent<HitBox>();
if (component != null &&
component.transform.root != null)
{
var hero = component.transform.root.GetComponent<HERO>();
if (!component.transform.root.gameObject.GetPhotonView().isMine && (hero.myTeam != this.myTeam || ModuleManager.Enabled(nameof(ModulePVPEverywhere))) &&
!hero.IsInvincible && !hero.HasDied() && !hero.IsGrabbed)
{
hero.markDie();
Vector3 distance = component.transform.root.position - transform.position;
component.transform.root.GetComponent<HERO>().photonView.RPC(Rpc.Die, PhotonTargets.All,
distance.normalized * b * 1000f + Vector3.up * 50f, // force : Vector3
false, // isBite : bool
this.viewID, // viewID : int
this.ownerName, // titanName : string
false); // killByTitan : bool
}
}
}
}
else if (other.gameObject.CompareTag("erenHitbox"))
{
if (dmg > 0 && !other.gameObject.transform.root.gameObject.GetComponent<TITAN_EREN>().isHit)
{
other.gameObject.transform.root.gameObject.GetComponent<TITAN_EREN>().hitByTitan();
}
}
else if (other.gameObject.CompareTag("titanneck"))
{
HitBox item = other.gameObject.GetComponent<HitBox>();
if (item != null && CheckIfBehind(item.transform.root.gameObject) && !this.currentHits.Contains(item))
{
item.hitPosition = (transform.position + item.transform.position) * 0.5f;
this.currentHits.Add(item);
TITAN titan = item.transform.root.GetComponent<TITAN>();
FEMALE_TITAN femaleTitan = item.transform.root.GetComponent<FEMALE_TITAN>();
COLOSSAL_TITAN colossalTitan = item.transform.root.GetComponent<COLOSSAL_TITAN>();
Vector3 velocity = IN_GAME_MAIN_CAMERA.instance.main_object.rigidbody.velocity - item.transform.root.rigidbody.velocity;
int damage = Mathf.Max(10, (int) (velocity.magnitude * 10f * this.scoreMulti));
switch (IN_GAME_MAIN_CAMERA.GameType)
{
// TITAN
// Single
case GameType.Singleplayer when titan != null && !titan.hasDie:
GameManager.instance.NetShowDamage(damage, null);
if (damage > titan.myLevel * 100f)
{
titan.die();
IN_GAME_MAIN_CAMERA.instance.TakeScreenshot(item.transform.position, damage, item.transform.root.gameObject, 0.02f);
GameManager.instance.PlayerKillInfoSingleplayerUpdate(damage);
}
break;
// Multi as MC
case GameType.Multiplayer when PhotonNetwork.isMasterClient && titan != null && !titan.hasDie:
if (damage > titan.myLevel * 100f)
{
IN_GAME_MAIN_CAMERA.instance.TakeScreenshot(item.transform.position, damage, item.transform.root.gameObject, 0.02f);
titan.TitanGetHit(transform.root.gameObject.GetPhotonView().viewID, damage);
}
break;
// Multi as user
case GameType.Multiplayer when titan != null && !titan.hasDie:
if (damage > titan.myLevel * 100f)
{
if (ModuleManager.Enabled(nameof(ModuleSnapshot)))
{
IN_GAME_MAIN_CAMERA.instance.TakeScreenshot(item.transform.position, damage, item.transform.root.gameObject, 0.02f);
titan.asClientLookTarget = false;
}
object[] objArray2 = new object[] { transform.root.gameObject.GetPhotonView().viewID, damage };
titan.photonView.RPC(Rpc.TitanGetHit, titan.photonView.owner, objArray2);
}
break;
// FEMALE TITAN
// Multi as MC
case GameType.Multiplayer when PhotonNetwork.isMasterClient && femaleTitan != null && !femaleTitan.hasDie:
IN_GAME_MAIN_CAMERA.instance.TakeScreenshot(item.transform.position, damage, null, 0.02f);
femaleTitan.TitanGetHit(transform.root.gameObject.GetPhotonView().viewID, damage);
break;
// Multi as user
case GameType.Multiplayer when femaleTitan != null && !femaleTitan.hasDie:
femaleTitan.photonView.RPC(Rpc.TitanGetHit, femaleTitan.photonView.owner,
transform.root.gameObject.GetPhotonView().viewID, damage);
break;
// COLOSSAL TITAN
// Multi as MC
case GameType.Multiplayer when PhotonNetwork.isMasterClient && colossalTitan != null && !colossalTitan.hasDie:
IN_GAME_MAIN_CAMERA.instance.TakeScreenshot(item.transform.position, damage, null, 0.02f);
colossalTitan.TitanGetHit(transform.root.gameObject.GetPhotonView().viewID, damage);
break;
// Multi as user
case GameType.Multiplayer when colossalTitan != null && !colossalTitan.hasDie:
colossalTitan.photonView.RPC(Rpc.TitanGetHit, colossalTitan.photonView.owner,
transform.root.gameObject.GetPhotonView().viewID, damage);
break;
}
this.ShowCriticalHitFX(other.gameObject.transform.position);
}
}
else if (other.gameObject.CompareTag("titaneye"))
{
if (!this.currentHits.Contains(other.gameObject))
{
this.currentHits.Add(other.gameObject);
GameObject eye = other.gameObject.transform.root.gameObject;
var femaleTitan = eye.GetComponent<FEMALE_TITAN>();
if (femaleTitan != null && !femaleTitan.hasDie)
{
if (IN_GAME_MAIN_CAMERA.GameType == GameType.Singleplayer)
femaleTitan.hitEye();
else if (!PhotonNetwork.isMasterClient)
femaleTitan.photonView.RPC(Rpc.HitEye, PhotonTargets.MasterClient, transform.root.gameObject.GetPhotonView().viewID);
else
femaleTitan.HitEyeRPC(transform.root.gameObject.GetPhotonView().viewID);
return;
}
var titan = eye.GetComponent<TITAN>();
if (titan != null && titan.abnormalType != AbnormalType.Crawler && !titan.hasDie)
{
if (IN_GAME_MAIN_CAMERA.GameType == GameType.Singleplayer)
titan.HitEye();
else if (!PhotonNetwork.isMasterClient)
titan.photonView.RPC(Rpc.HitEye, PhotonTargets.MasterClient, transform.root.gameObject.GetPhotonView().viewID);
else if (!titan.hasDie)
titan.HitEyeRPC(transform.root.gameObject.GetPhotonView().viewID);
this.ShowCriticalHitFX(other.gameObject.transform.position);
}
}
}
else if (other.gameObject.CompareTag("titanankle") && !this.currentHits.Contains(other.gameObject))
{
currentHits.Add(other.gameObject);
GameObject obj = other.gameObject.transform.root.gameObject;
Vector3 velocity = IN_GAME_MAIN_CAMERA.instance.main_object.rigidbody.velocity - obj.rigidbody.velocity;
int damage = Mathf.Max(10, (int) (velocity.magnitude * 10f * this.scoreMulti));
var titan = obj.GetComponent<TITAN>();
var femaleTitan = obj.GetComponent<FEMALE_TITAN>();
if (titan != null && titan.abnormalType != AbnormalType.Crawler && !titan.hasDie)
{
if (IN_GAME_MAIN_CAMERA.GameType == GameType.Singleplayer)
titan.hitAnkle();
else if (!PhotonNetwork.isMasterClient)
titan.photonView.RPC(Rpc.HitEye, PhotonTargets.MasterClient, transform.root.gameObject.GetPhotonView().viewID);
else
titan.hitAnkle();
ShowCriticalHitFX(other.gameObject.transform.position);
}
else if (femaleTitan != null && !femaleTitan.hasDie)
{
switch (IN_GAME_MAIN_CAMERA.GameType)
{
case GameType.Singleplayer:
if (other.gameObject.name == "ankleR")
femaleTitan.hitAnkleR(damage);
else
femaleTitan.hitAnkleL(damage);
break;
case GameType.Multiplayer:
if (PhotonNetwork.isMasterClient)
{
if (other.gameObject.name == "ankleR")
femaleTitan.HitAnkleRRPC(transform.root.gameObject.GetPhotonView().viewID, damage);
else
femaleTitan.HitAnkleLRPC(transform.root.gameObject.GetPhotonView().viewID, damage);
}
else
{
if (other.gameObject.name == "ankleR")
femaleTitan.photonView.RPC(Rpc.HitRightAnkle, PhotonTargets.MasterClient, transform.root.gameObject.GetPhotonView().viewID, damage);
else
femaleTitan.photonView.RPC(Rpc.HitLeftAnkle, PhotonTargets.MasterClient, transform.root.gameObject.GetPhotonView().viewID, damage);
}
break;
}
this.ShowCriticalHitFX(other.gameObject.transform.position);
}
}
}
private void ShowCriticalHitFX(Vector3 position)
{
IN_GAME_MAIN_CAMERA.instance.startShake(0.2f, 0.3f);
if (IN_GAME_MAIN_CAMERA.GameType == GameType.Singleplayer)
Instantiate(Resources.Load("redCross1"), position, Quaternion.Euler(270f, 0f, 0f));
else
PhotonNetwork.Instantiate("redCross1", transform.position, Quaternion.Euler(270f, 0f, 0f), 0);
}
private void Start()
{
switch (IN_GAME_MAIN_CAMERA.GameType)
{
case GameType.Singleplayer:
this.myTeam = IN_GAME_MAIN_CAMERA.instance.main_object.GetComponent<HERO>().myTeam;
break;
case GameType.Multiplayer when !transform.root.gameObject.GetPhotonView().isMine:
enabled = false;
return;
case GameType.Multiplayer:
var component = transform.root.gameObject.GetComponent<EnemyfxIDcontainer>();
if (component != null)
{
this.viewID = component.myOwnerViewID;
this.ownerName = component.titanName;
this.myTeam = PhotonView.Find(this.viewID).gameObject.GetComponent<HERO>().myTeam;
}
break;
}
this.active_me = true;
this.currentCamera = GameObject.Find("MainCamera");
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//------------------------------------------------------------------------------
// </copyright>
//------------------------------------------------------------------------------
#if !NET_NATIVE
namespace System.Xml.Serialization
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
using System.Reflection.Emit;
using System.Text.RegularExpressions;
using System.Xml.Extensions;
using Hashtable = System.Collections.Generic.Dictionary<object, object>;
internal class XmlSerializationILGen
{
private int _nextMethodNumber = 0;
private InternalHashtable _methodNames = new InternalHashtable();
// Lookup name->created Method
private Dictionary<string, MethodBuilderInfo> _methodBuilders = new Dictionary<string, MethodBuilderInfo>();
// Lookup name->created Type
internal Dictionary<string, Type> CreatedTypes = new Dictionary<string, Type>();
// Lookup name->class Member
internal Dictionary<string, MemberInfo> memberInfos = new Dictionary<string, MemberInfo>();
private ReflectionAwareILGen _raCodeGen;
private TypeScope[] _scopes;
private TypeDesc _stringTypeDesc = null;
private TypeDesc _qnameTypeDesc = null;
private string _className;
private TypeMapping[] _referencedMethods;
private int _references = 0;
private InternalHashtable _generatedMethods = new InternalHashtable();
private ModuleBuilder _moduleBuilder;
private TypeAttributes _typeAttributes;
protected TypeBuilder typeBuilder;
protected CodeGenerator ilg;
internal XmlSerializationILGen(TypeScope[] scopes, string access, string className)
{
_scopes = scopes;
if (scopes.Length > 0)
{
_stringTypeDesc = scopes[0].GetTypeDesc(typeof(string));
_qnameTypeDesc = scopes[0].GetTypeDesc(typeof(XmlQualifiedName));
}
_raCodeGen = new ReflectionAwareILGen();
_className = className;
System.Diagnostics.Debug.Assert(access == "public");
_typeAttributes = TypeAttributes.Public;
}
internal int NextMethodNumber { get { return _nextMethodNumber; } set { _nextMethodNumber = value; } }
internal ReflectionAwareILGen RaCodeGen { get { return _raCodeGen; } }
internal TypeDesc StringTypeDesc { get { return _stringTypeDesc; } }
internal TypeDesc QnameTypeDesc { get { return _qnameTypeDesc; } }
internal string ClassName { get { return _className; } }
internal TypeScope[] Scopes { get { return _scopes; } }
internal InternalHashtable MethodNames { get { return _methodNames; } }
internal InternalHashtable GeneratedMethods { get { return _generatedMethods; } }
internal ModuleBuilder ModuleBuilder
{
get { System.Diagnostics.Debug.Assert(_moduleBuilder != null); return _moduleBuilder; }
set { System.Diagnostics.Debug.Assert(_moduleBuilder == null && value != null); _moduleBuilder = value; }
}
internal TypeAttributes TypeAttributes { get { return _typeAttributes; } }
private static Dictionary<string, Regex> s_regexs = new Dictionary<string, Regex>();
static internal Regex NewRegex(string pattern)
{
Regex regex;
lock (s_regexs)
{
if (!s_regexs.TryGetValue(pattern, out regex))
{
regex = new Regex(pattern);
s_regexs.Add(pattern, regex);
}
}
return regex;
}
internal MethodBuilder EnsureMethodBuilder(TypeBuilder typeBuilder, string methodName,
MethodAttributes attributes, Type returnType, Type[] parameterTypes)
{
MethodBuilderInfo methodBuilderInfo;
if (!_methodBuilders.TryGetValue(methodName, out methodBuilderInfo))
{
MethodBuilder methodBuilder = typeBuilder.DefineMethod(
methodName,
attributes,
returnType,
parameterTypes);
methodBuilderInfo = new MethodBuilderInfo(methodBuilder, parameterTypes);
_methodBuilders.Add(methodName, methodBuilderInfo);
}
#if DEBUG
else
{
methodBuilderInfo.Validate(returnType, parameterTypes, attributes);
}
#endif
return methodBuilderInfo.MethodBuilder;
}
internal MethodBuilderInfo GetMethodBuilder(string methodName)
{
System.Diagnostics.Debug.Assert(_methodBuilders.ContainsKey(methodName));
return _methodBuilders[methodName];
}
internal virtual void GenerateMethod(TypeMapping mapping) { }
internal void GenerateReferencedMethods()
{
while (_references > 0)
{
TypeMapping mapping = _referencedMethods[--_references];
GenerateMethod(mapping);
}
}
internal string ReferenceMapping(TypeMapping mapping)
{
if (_generatedMethods[mapping] == null)
{
_referencedMethods = EnsureArrayIndex(_referencedMethods, _references);
_referencedMethods[_references++] = mapping;
}
return (string)_methodNames[mapping];
}
private TypeMapping[] EnsureArrayIndex(TypeMapping[] a, int index)
{
if (a == null) return new TypeMapping[32];
if (index < a.Length) return a;
TypeMapping[] b = new TypeMapping[a.Length + 32];
Array.Copy(a, 0, b, 0, index);
return b;
}
internal string GetCSharpString(string value)
{
return ReflectionAwareILGen.GetCSharpString(value);
}
internal FieldBuilder GenerateHashtableGetBegin(string privateName, string publicName, TypeBuilder serializerContractTypeBuilder)
{
FieldBuilder fieldBuilder = serializerContractTypeBuilder.DefineField(
privateName,
typeof(Hashtable),
FieldAttributes.Private
);
ilg = new CodeGenerator(serializerContractTypeBuilder);
PropertyBuilder propertyBuilder = serializerContractTypeBuilder.DefineProperty(
publicName,
PropertyAttributes.None,
typeof(IDictionary),
null, null, null, null, null);
ilg.BeginMethod(
typeof(IDictionary),
"get_" + publicName,
Array.Empty<Type>(),
Array.Empty<string>(),
CodeGenerator.PublicOverrideMethodAttributes | MethodAttributes.SpecialName);
propertyBuilder.SetGetMethod(ilg.MethodBuilder);
ilg.Ldarg(0);
ilg.LoadMember(fieldBuilder);
ilg.Load(null);
// this 'if' ends in GenerateHashtableGetEnd
ilg.If(Cmp.EqualTo);
ConstructorInfo Hashtable_ctor = typeof(Hashtable).GetConstructor(
CodeGenerator.InstanceBindingFlags,
Array.Empty<Type>()
);
LocalBuilder _tmpLoc = ilg.DeclareLocal(typeof(Hashtable), "_tmp");
ilg.New(Hashtable_ctor);
ilg.Stloc(_tmpLoc);
return fieldBuilder;
}
internal void GenerateHashtableGetEnd(FieldBuilder fieldBuilder)
{
ilg.Ldarg(0);
ilg.LoadMember(fieldBuilder);
ilg.Load(null);
ilg.If(Cmp.EqualTo);
{
ilg.Ldarg(0);
ilg.Ldloc(typeof(Hashtable), "_tmp");
ilg.StoreMember(fieldBuilder);
}
ilg.EndIf();
// 'endif' from GenerateHashtableGetBegin
ilg.EndIf();
ilg.Ldarg(0);
ilg.LoadMember(fieldBuilder);
ilg.GotoMethodEnd();
ilg.EndMethod();
}
internal FieldBuilder GeneratePublicMethods(string privateName, string publicName, string[] methods, XmlMapping[] xmlMappings, TypeBuilder serializerContractTypeBuilder)
{
FieldBuilder fieldBuilder = GenerateHashtableGetBegin(privateName, publicName, serializerContractTypeBuilder);
if (methods != null && methods.Length != 0 && xmlMappings != null && xmlMappings.Length == methods.Length)
{
MethodInfo Hashtable_set_Item = typeof(Hashtable).GetMethod(
"set_Item",
CodeGenerator.InstanceBindingFlags,
new Type[] { typeof(Object), typeof(Object) }
);
for (int i = 0; i < methods.Length; i++)
{
if (methods[i] == null)
continue;
ilg.Ldloc(typeof(Hashtable), "_tmp");
ilg.Ldstr(GetCSharpString(xmlMappings[i].Key));
ilg.Ldstr(GetCSharpString(methods[i]));
ilg.Call(Hashtable_set_Item);
}
}
GenerateHashtableGetEnd(fieldBuilder);
return fieldBuilder;
}
internal void GenerateSupportedTypes(Type[] types, TypeBuilder serializerContractTypeBuilder)
{
ilg = new CodeGenerator(serializerContractTypeBuilder);
ilg.BeginMethod(
typeof(bool),
"CanSerialize",
new Type[] { typeof(Type) },
new string[] { "type" },
CodeGenerator.PublicOverrideMethodAttributes);
InternalHashtable uniqueTypes = new InternalHashtable();
for (int i = 0; i < types.Length; i++)
{
Type type = types[i];
if (type == null)
continue;
if (!type.GetTypeInfo().IsPublic && !type.GetTypeInfo().IsNestedPublic)
continue;
if (uniqueTypes[type] != null)
continue;
// DDB172141: Wrong generated CS for serializer of List<string> type
if (type.GetTypeInfo().IsGenericType || type.GetTypeInfo().ContainsGenericParameters)
continue;
uniqueTypes[type] = type;
ilg.Ldarg("type");
ilg.Ldc(type);
ilg.If(Cmp.EqualTo);
{
ilg.Ldc(true);
ilg.GotoMethodEnd();
}
ilg.EndIf();
}
ilg.Ldc(false);
ilg.GotoMethodEnd();
ilg.EndMethod();
}
internal string GenerateBaseSerializer(string baseSerializer, string readerClass, string writerClass, CodeIdentifiers classes)
{
baseSerializer = CodeIdentifier.MakeValid(baseSerializer);
baseSerializer = classes.AddUnique(baseSerializer, baseSerializer);
TypeBuilder baseSerializerTypeBuilder = CodeGenerator.CreateTypeBuilder(
_moduleBuilder,
CodeIdentifier.GetCSharpName(baseSerializer),
TypeAttributes.Public | TypeAttributes.Abstract | TypeAttributes.BeforeFieldInit,
typeof(XmlSerializer),
Array.Empty<Type>());
ConstructorInfo readerCtor = CreatedTypes[readerClass].GetConstructor(
CodeGenerator.InstanceBindingFlags,
Array.Empty<Type>()
);
ilg = new CodeGenerator(baseSerializerTypeBuilder);
ilg.BeginMethod(typeof(XmlSerializationReader),
"CreateReader",
Array.Empty<Type>(),
Array.Empty<string>(),
CodeGenerator.ProtectedOverrideMethodAttributes);
ilg.New(readerCtor);
ilg.EndMethod();
ConstructorInfo writerCtor = CreatedTypes[writerClass].GetConstructor(
CodeGenerator.InstanceBindingFlags,
Array.Empty<Type>()
);
ilg.BeginMethod(typeof(XmlSerializationWriter),
"CreateWriter",
Array.Empty<Type>(),
Array.Empty<string>(),
CodeGenerator.ProtectedOverrideMethodAttributes);
ilg.New(writerCtor);
ilg.EndMethod();
baseSerializerTypeBuilder.DefineDefaultConstructor(
MethodAttributes.Family | MethodAttributes.HideBySig | MethodAttributes.SpecialName | MethodAttributes.RTSpecialName);
Type baseSerializerType = baseSerializerTypeBuilder.CreateTypeInfo().AsType();
CreatedTypes.Add(baseSerializerType.Name, baseSerializerType);
return baseSerializer;
}
internal string GenerateTypedSerializer(string readMethod, string writeMethod, XmlMapping mapping, CodeIdentifiers classes, string baseSerializer, string readerClass, string writerClass)
{
string serializerName = CodeIdentifier.MakeValid(Accessor.UnescapeName(mapping.Accessor.Mapping.TypeDesc.Name));
serializerName = classes.AddUnique(serializerName + "Serializer", mapping);
TypeBuilder typedSerializerTypeBuilder = CodeGenerator.CreateTypeBuilder(
_moduleBuilder,
CodeIdentifier.GetCSharpName(serializerName),
TypeAttributes.Public | TypeAttributes.Sealed | TypeAttributes.BeforeFieldInit,
CreatedTypes[baseSerializer],
Array.Empty<Type>()
);
ilg = new CodeGenerator(typedSerializerTypeBuilder);
ilg.BeginMethod(
typeof(Boolean),
"CanDeserialize",
new Type[] { typeof(XmlReader) },
new string[] { "xmlReader" },
CodeGenerator.PublicOverrideMethodAttributes
);
if (mapping.Accessor.Any)
{
ilg.Ldc(true);
ilg.Stloc(ilg.ReturnLocal);
ilg.Br(ilg.ReturnLabel);
}
else
{
MethodInfo XmlReader_IsStartElement = typeof(XmlReader).GetMethod(
"IsStartElement",
CodeGenerator.InstanceBindingFlags,
new Type[] { typeof(String), typeof(String) }
);
ilg.Ldarg(ilg.GetArg("xmlReader"));
ilg.Ldstr(GetCSharpString(mapping.Accessor.Name));
ilg.Ldstr(GetCSharpString(mapping.Accessor.Namespace));
ilg.Call(XmlReader_IsStartElement);
ilg.Stloc(ilg.ReturnLocal);
ilg.Br(ilg.ReturnLabel);
}
ilg.MarkLabel(ilg.ReturnLabel);
ilg.Ldloc(ilg.ReturnLocal);
ilg.EndMethod();
if (writeMethod != null)
{
ilg = new CodeGenerator(typedSerializerTypeBuilder);
ilg.BeginMethod(
typeof(void),
"Serialize",
new Type[] { typeof(object), typeof(XmlSerializationWriter) },
new string[] { "objectToSerialize", "writer" },
CodeGenerator.ProtectedOverrideMethodAttributes);
MethodInfo writerType_writeMethod = CreatedTypes[writerClass].GetMethod(
writeMethod,
CodeGenerator.InstanceBindingFlags,
new Type[] { (mapping is XmlMembersMapping) ? typeof(object[]) : typeof(object) }
);
ilg.Ldarg("writer");
ilg.Castclass(CreatedTypes[writerClass]);
ilg.Ldarg("objectToSerialize");
if (mapping is XmlMembersMapping)
{
ilg.ConvertValue(typeof(object), typeof(object[]));
}
ilg.Call(writerType_writeMethod);
ilg.EndMethod();
}
if (readMethod != null)
{
ilg = new CodeGenerator(typedSerializerTypeBuilder);
ilg.BeginMethod(
typeof(object),
"Deserialize",
new Type[] { typeof(XmlSerializationReader) },
new string[] { "reader" },
CodeGenerator.ProtectedOverrideMethodAttributes);
MethodInfo readerType_readMethod = CreatedTypes[readerClass].GetMethod(
readMethod,
CodeGenerator.InstanceBindingFlags,
Array.Empty<Type>()
);
ilg.Ldarg("reader");
ilg.Castclass(CreatedTypes[readerClass]);
ilg.Call(readerType_readMethod);
ilg.EndMethod();
}
typedSerializerTypeBuilder.DefineDefaultConstructor(CodeGenerator.PublicMethodAttributes);
Type typedSerializerType = typedSerializerTypeBuilder.CreateTypeInfo().AsType();
CreatedTypes.Add(typedSerializerType.Name, typedSerializerType);
return typedSerializerType.Name;
}
private FieldBuilder GenerateTypedSerializers(Hashtable serializers, TypeBuilder serializerContractTypeBuilder)
{
string privateName = "typedSerializers";
FieldBuilder fieldBuilder = GenerateHashtableGetBegin(privateName, "TypedSerializers", serializerContractTypeBuilder);
MethodInfo Hashtable_Add = typeof(Hashtable).GetMethod(
"Add",
CodeGenerator.InstanceBindingFlags,
new Type[] { typeof(Object), typeof(Object) }
);
foreach (string key in serializers.Keys)
{
ConstructorInfo ctor = CreatedTypes[(string)serializers[key]].GetConstructor(
CodeGenerator.InstanceBindingFlags,
Array.Empty<Type>()
);
ilg.Ldloc(typeof(Hashtable), "_tmp");
ilg.Ldstr(GetCSharpString(key));
ilg.New(ctor);
ilg.Call(Hashtable_Add);
}
GenerateHashtableGetEnd(fieldBuilder);
return fieldBuilder;
}
//GenerateGetSerializer(serializers, xmlMappings);
private void GenerateGetSerializer(Hashtable serializers, XmlMapping[] xmlMappings, TypeBuilder serializerContractTypeBuilder)
{
ilg = new CodeGenerator(serializerContractTypeBuilder);
ilg.BeginMethod(
typeof(XmlSerializer),
"GetSerializer",
new Type[] { typeof(Type) },
new string[] { "type" },
CodeGenerator.PublicOverrideMethodAttributes);
for (int i = 0; i < xmlMappings.Length; i++)
{
if (xmlMappings[i] is XmlTypeMapping)
{
Type type = xmlMappings[i].Accessor.Mapping.TypeDesc.Type;
if (type == null)
continue;
if (!type.GetTypeInfo().IsPublic && !type.GetTypeInfo().IsNestedPublic)
continue;
// DDB172141: Wrong generated CS for serializer of List<string> type
if (type.GetTypeInfo().IsGenericType || type.GetTypeInfo().ContainsGenericParameters)
continue;
ilg.Ldarg("type");
ilg.Ldc(type);
ilg.If(Cmp.EqualTo);
{
ConstructorInfo ctor = CreatedTypes[(string)serializers[xmlMappings[i].Key]].GetConstructor(
CodeGenerator.InstanceBindingFlags,
Array.Empty<Type>()
);
ilg.New(ctor);
ilg.Stloc(ilg.ReturnLocal);
ilg.Br(ilg.ReturnLabel);
}
ilg.EndIf();
}
}
ilg.Load(null);
ilg.Stloc(ilg.ReturnLocal);
ilg.Br(ilg.ReturnLabel);
ilg.MarkLabel(ilg.ReturnLabel);
ilg.Ldloc(ilg.ReturnLocal);
ilg.EndMethod();
}
internal void GenerateSerializerContract(string className, XmlMapping[] xmlMappings, Type[] types, string readerType, string[] readMethods, string writerType, string[] writerMethods, Hashtable serializers)
{
TypeBuilder serializerContractTypeBuilder = CodeGenerator.CreateTypeBuilder(
_moduleBuilder,
"XmlSerializerContract",
TypeAttributes.Public | TypeAttributes.BeforeFieldInit,
typeof(XmlSerializerImplementation),
Array.Empty<Type>()
);
ilg = new CodeGenerator(serializerContractTypeBuilder);
PropertyBuilder propertyBuilder = serializerContractTypeBuilder.DefineProperty(
"Reader",
PropertyAttributes.None,
typeof(XmlSerializationReader),
null, null, null, null, null);
ilg.BeginMethod(
typeof(XmlSerializationReader),
"get_Reader",
Array.Empty<Type>(),
Array.Empty<string>(),
CodeGenerator.PublicOverrideMethodAttributes | MethodAttributes.SpecialName);
propertyBuilder.SetGetMethod(ilg.MethodBuilder);
ConstructorInfo ctor = CreatedTypes[readerType].GetConstructor(
CodeGenerator.InstanceBindingFlags,
Array.Empty<Type>()
);
ilg.New(ctor);
ilg.EndMethod();
ilg = new CodeGenerator(serializerContractTypeBuilder);
propertyBuilder = serializerContractTypeBuilder.DefineProperty(
"Writer",
PropertyAttributes.None,
typeof(XmlSerializationWriter),
null, null, null, null, null);
ilg.BeginMethod(
typeof(XmlSerializationWriter),
"get_Writer",
Array.Empty<Type>(),
Array.Empty<string>(),
CodeGenerator.PublicOverrideMethodAttributes | MethodAttributes.SpecialName);
propertyBuilder.SetGetMethod(ilg.MethodBuilder);
ctor = CreatedTypes[writerType].GetConstructor(
CodeGenerator.InstanceBindingFlags,
Array.Empty<Type>()
);
ilg.New(ctor);
ilg.EndMethod();
FieldBuilder readMethodsField = GeneratePublicMethods("readMethods", "ReadMethods", readMethods, xmlMappings, serializerContractTypeBuilder);
FieldBuilder writeMethodsField = GeneratePublicMethods("writeMethods", "WriteMethods", writerMethods, xmlMappings, serializerContractTypeBuilder);
FieldBuilder typedSerializersField = GenerateTypedSerializers(serializers, serializerContractTypeBuilder);
GenerateSupportedTypes(types, serializerContractTypeBuilder);
GenerateGetSerializer(serializers, xmlMappings, serializerContractTypeBuilder);
// Default ctor
ConstructorInfo baseCtor = typeof(XmlSerializerImplementation).GetConstructor(
CodeGenerator.InstanceBindingFlags,
Array.Empty<Type>()
);
ilg = new CodeGenerator(serializerContractTypeBuilder);
ilg.BeginMethod(
typeof(void),
".ctor",
Array.Empty<Type>(),
Array.Empty<string>(),
CodeGenerator.PublicMethodAttributes | MethodAttributes.RTSpecialName | MethodAttributes.SpecialName
);
ilg.Ldarg(0);
ilg.Load(null);
ilg.StoreMember(readMethodsField);
ilg.Ldarg(0);
ilg.Load(null);
ilg.StoreMember(writeMethodsField);
ilg.Ldarg(0);
ilg.Load(null);
ilg.StoreMember(typedSerializersField);
ilg.Ldarg(0);
ilg.Call(baseCtor);
ilg.EndMethod();
// Instantiate type
Type serializerContractType = serializerContractTypeBuilder.CreateTypeInfo().AsType();
CreatedTypes.Add(serializerContractType.Name, serializerContractType);
}
internal static bool IsWildcard(SpecialMapping mapping)
{
if (mapping is SerializableMapping)
return ((SerializableMapping)mapping).IsAny;
return mapping.TypeDesc.CanBeElementValue;
}
internal void ILGenLoad(string source)
{
ILGenLoad(source, null);
}
internal void ILGenLoad(string source, Type type)
{
if (source.StartsWith("o.@", StringComparison.Ordinal))
{
System.Diagnostics.Debug.Assert(memberInfos.ContainsKey(source.Substring(3)));
MemberInfo memInfo = memberInfos[source.Substring(3)];
ilg.LoadMember(ilg.GetVariable("o"), memInfo);
if (type != null)
{
Type memType = (memInfo is FieldInfo) ? ((FieldInfo)memInfo).FieldType : ((PropertyInfo)memInfo).PropertyType;
ilg.ConvertValue(memType, type);
}
}
else
{
SourceInfo info = new SourceInfo(source, null, null, null, ilg);
info.Load(type);
}
}
}
}
#endif
| |
// ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
/*============================================================
**
** Purpose: Resource annotation rules.
**
===========================================================*/
using System;
using System.Diagnostics;
using System.Globalization;
using System.Runtime.CompilerServices;
using System.Text;
using Microsoft.Win32;
using System.Diagnostics.Contracts;
namespace System.Runtime.Versioning
{
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Constructor, Inherited = false)]
[Conditional("RESOURCE_ANNOTATION_WORK")]
public sealed class ResourceConsumptionAttribute : Attribute
{
private ResourceScope _consumptionScope;
private ResourceScope _resourceScope;
public ResourceConsumptionAttribute(ResourceScope resourceScope)
{
_resourceScope = resourceScope;
_consumptionScope = _resourceScope;
}
public ResourceConsumptionAttribute(ResourceScope resourceScope, ResourceScope consumptionScope)
{
_resourceScope = resourceScope;
_consumptionScope = consumptionScope;
}
public ResourceScope ResourceScope {
get { return _resourceScope; }
}
public ResourceScope ConsumptionScope {
get { return _consumptionScope; }
}
}
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Field | AttributeTargets.Property | AttributeTargets.Constructor, Inherited = false)]
[Conditional("RESOURCE_ANNOTATION_WORK")]
public sealed class ResourceExposureAttribute : Attribute
{
private ResourceScope _resourceExposureLevel;
public ResourceExposureAttribute(ResourceScope exposureLevel)
{
_resourceExposureLevel = exposureLevel;
}
public ResourceScope ResourceExposureLevel {
get { return _resourceExposureLevel; }
}
}
// Default visibility is Public, which isn't specified in this enum.
// Public == the lack of Private or Assembly
// Does this actually work? Need to investigate that.
[Flags]
public enum ResourceScope
{
None = 0,
// Resource type
Machine = 0x1,
Process = 0x2,
AppDomain = 0x4,
Library = 0x8,
// Visibility
Private = 0x10, // Private to this one class.
Assembly = 0x20, // Assembly-level, like C#'s "internal"
}
[Flags]
internal enum SxSRequirements
{
None = 0,
AppDomainID = 0x1,
ProcessID = 0x2,
CLRInstanceID = 0x4, // for multiple CLR's within the process
AssemblyName = 0x8,
TypeName = 0x10
}
public static class VersioningHelper
{
// These depend on the exact values given to members of the ResourceScope enum.
private const ResourceScope ResTypeMask = ResourceScope.Machine | ResourceScope.Process | ResourceScope.AppDomain | ResourceScope.Library;
private const ResourceScope VisibilityMask = ResourceScope.Private | ResourceScope.Assembly;
[System.Security.SecuritySafeCritical]
[ResourceExposure(ResourceScope.Process)]
[MethodImpl(MethodImplOptions.InternalCall)]
private static extern int GetRuntimeId();
public static String MakeVersionSafeName(String name, ResourceScope from, ResourceScope to)
{
return MakeVersionSafeName(name, from, to, null);
}
#if MONO
[MethodImplAttribute(MethodImplOptions.InternalCall)]
extern static uint GetCurrentProcessId ();
#endif
[System.Security.SecuritySafeCritical] // auto-generated
[ResourceExposure(ResourceScope.None)]
[ResourceConsumption(ResourceScope.Process, ResourceScope.Process)]
public static String MakeVersionSafeName(String name, ResourceScope from, ResourceScope to, Type type)
{
ResourceScope fromResType = from & ResTypeMask;
ResourceScope toResType = to & ResTypeMask;
if (fromResType > toResType)
throw new ArgumentException(Environment.GetResourceString("Argument_ResourceScopeWrongDirection", fromResType, toResType), "from");
SxSRequirements requires = GetRequirements(to, from);
if ((requires & (SxSRequirements.AssemblyName | SxSRequirements.TypeName)) != 0 && type == null)
throw new ArgumentNullException("type", Environment.GetResourceString("ArgumentNull_TypeRequiredByResourceScope"));
// Add in process ID, CLR base address, and appdomain ID's. Also, use a character identifier
// to ensure that these can never accidentally overlap (ie, you create enough appdomains and your
// appdomain ID might equal your process ID).
StringBuilder safeName = new StringBuilder(name);
char separator = '_';
if ((requires & SxSRequirements.ProcessID) != 0) {
safeName.Append(separator);
safeName.Append('p');
#if MONO
safeName.Append (GetCurrentProcessId ());
#else
safeName.Append(Win32Native.GetCurrentProcessId());
#endif
}
if ((requires & SxSRequirements.CLRInstanceID) != 0) {
String clrID = GetCLRInstanceString();
safeName.Append(separator);
safeName.Append('r');
safeName.Append(clrID);
}
if ((requires & SxSRequirements.AppDomainID) != 0) {
safeName.Append(separator);
safeName.Append("ad");
safeName.Append(AppDomain.CurrentDomain.Id);
}
if ((requires & SxSRequirements.TypeName) != 0) {
safeName.Append(separator);
safeName.Append(type.Name);
}
if ((requires & SxSRequirements.AssemblyName) != 0) {
safeName.Append(separator);
safeName.Append(type.Assembly.FullName);
}
return safeName.ToString();
}
private static String GetCLRInstanceString()
{
int id = GetRuntimeId();
return id.ToString(CultureInfo.InvariantCulture);
}
private static SxSRequirements GetRequirements(ResourceScope consumeAsScope, ResourceScope calleeScope)
{
SxSRequirements requires = SxSRequirements.None;
switch(calleeScope & ResTypeMask) {
case ResourceScope.Machine:
switch(consumeAsScope & ResTypeMask) {
case ResourceScope.Machine:
// No work
break;
case ResourceScope.Process:
requires |= SxSRequirements.ProcessID;
break;
case ResourceScope.AppDomain:
requires |= SxSRequirements.AppDomainID | SxSRequirements.CLRInstanceID | SxSRequirements.ProcessID;
break;
default:
throw new ArgumentException(Environment.GetResourceString("Argument_BadResourceScopeTypeBits", consumeAsScope), "consumeAsScope");
}
break;
case ResourceScope.Process:
if ((consumeAsScope & ResourceScope.AppDomain) != 0)
requires |= SxSRequirements.AppDomainID | SxSRequirements.CLRInstanceID;
break;
case ResourceScope.AppDomain:
// No work
break;
default:
throw new ArgumentException(Environment.GetResourceString("Argument_BadResourceScopeTypeBits", calleeScope), "calleeScope");
}
switch(calleeScope & VisibilityMask) {
case ResourceScope.None: // Public - implied
switch(consumeAsScope & VisibilityMask) {
case ResourceScope.None: // Public - implied
// No work
break;
case ResourceScope.Assembly:
requires |= SxSRequirements.AssemblyName;
break;
case ResourceScope.Private:
requires |= SxSRequirements.TypeName | SxSRequirements.AssemblyName;
break;
default:
throw new ArgumentException(Environment.GetResourceString("Argument_BadResourceScopeVisibilityBits", consumeAsScope), "consumeAsScope");
}
break;
case ResourceScope.Assembly:
if ((consumeAsScope & ResourceScope.Private) != 0)
requires |= SxSRequirements.TypeName;
break;
case ResourceScope.Private:
// No work
break;
default:
throw new ArgumentException(Environment.GetResourceString("Argument_BadResourceScopeVisibilityBits", calleeScope), "calleeScope");
}
if (consumeAsScope == calleeScope) {
Contract.Assert(requires == SxSRequirements.None, "Computed a strange set of required resource scoping. It's probably wrong.");
}
return requires;
}
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
namespace Apache.Ignite.Core.Impl.Compute
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Runtime.Serialization;
using System.Threading;
using Apache.Ignite.Core.Binary;
using Apache.Ignite.Core.Cluster;
using Apache.Ignite.Core.Common;
using Apache.Ignite.Core.Compute;
using Apache.Ignite.Core.Impl.Binary;
using Apache.Ignite.Core.Impl.Binary.IO;
using Apache.Ignite.Core.Impl.Cluster;
using Apache.Ignite.Core.Impl.Common;
using Apache.Ignite.Core.Impl.Compute.Closure;
using Apache.Ignite.Core.Impl.Unmanaged;
using UU = Apache.Ignite.Core.Impl.Unmanaged.UnmanagedUtils;
/// <summary>
/// Compute implementation.
/// </summary>
[SuppressMessage("Microsoft.Design", "CA1001:TypesThatOwnDisposableFieldsShouldBeDisposable")]
internal class ComputeImpl : PlatformTarget
{
/** */
private const int OpAffinity = 1;
/** */
private const int OpBroadcast = 2;
/** */
private const int OpExec = 3;
/** */
private const int OpExecAsync = 4;
/** */
private const int OpUnicast = 5;
/** */
private const int OpWithNoFailover = 6;
/** */
private const int OpWithTimeout = 7;
/** */
private const int OpExecNative = 8;
/** Underlying projection. */
private readonly ClusterGroupImpl _prj;
/** Whether objects must be kept in binary form. */
private readonly ThreadLocal<bool> _keepBinary = new ThreadLocal<bool>(() => false);
/// <summary>
/// Constructor.
/// </summary>
/// <param name="target">Target.</param>
/// <param name="marsh">Marshaller.</param>
/// <param name="prj">Projection.</param>
/// <param name="keepBinary">Binary flag.</param>
public ComputeImpl(IUnmanagedTarget target, Marshaller marsh, ClusterGroupImpl prj, bool keepBinary)
: base(target, marsh)
{
_prj = prj;
_keepBinary.Value = keepBinary;
}
/// <summary>
/// Grid projection to which this compute instance belongs.
/// </summary>
public IClusterGroup ClusterGroup
{
get
{
return _prj;
}
}
/// <summary>
/// Sets no-failover flag for the next executed task on this projection in the current thread.
/// If flag is set, job will be never failed over even if remote node crashes or rejects execution.
/// When task starts execution, the no-failover flag is reset, so all other task will use default
/// failover policy, unless this flag is set again.
/// </summary>
public void WithNoFailover()
{
DoOutInOp(OpWithNoFailover);
}
/// <summary>
/// Sets task timeout for the next executed task on this projection in the current thread.
/// When task starts execution, the timeout is reset, so one timeout is used only once.
/// </summary>
/// <param name="timeout">Computation timeout in milliseconds.</param>
public void WithTimeout(long timeout)
{
DoOutInOp(OpWithTimeout, timeout);
}
/// <summary>
/// Sets keep-binary flag for the next executed Java task on this projection in the current
/// thread so that task argument passed to Java and returned task results will not be
/// deserialized.
/// </summary>
public void WithKeepBinary()
{
_keepBinary.Value = true;
}
/// <summary>
/// Executes given Java task on the grid projection. If task for given name has not been deployed yet,
/// then 'taskName' will be used as task class name to auto-deploy the task.
/// </summary>
public TReduceRes ExecuteJavaTask<TReduceRes>(string taskName, object taskArg)
{
IgniteArgumentCheck.NotNullOrEmpty(taskName, "taskName");
ICollection<IClusterNode> nodes = _prj.Predicate == null ? null : _prj.GetNodes();
try
{
return DoOutInOp<TReduceRes>(OpExec, writer => WriteTask(writer, taskName, taskArg, nodes));
}
finally
{
_keepBinary.Value = false;
}
}
/// <summary>
/// Executes given Java task asynchronously on the grid projection.
/// If task for given name has not been deployed yet,
/// then 'taskName' will be used as task class name to auto-deploy the task.
/// </summary>
public Future<TReduceRes> ExecuteJavaTaskAsync<TReduceRes>(string taskName, object taskArg)
{
IgniteArgumentCheck.NotNullOrEmpty(taskName, "taskName");
ICollection<IClusterNode> nodes = _prj.Predicate == null ? null : _prj.GetNodes();
try
{
return DoOutOpObjectAsync<TReduceRes>(OpExecAsync, w => WriteTask(w, taskName, taskArg, nodes));
}
finally
{
_keepBinary.Value = false;
}
}
/// <summary>
/// Executes given task on the grid projection. For step-by-step explanation of task execution process
/// refer to <see cref="IComputeTask{A,T,R}"/> documentation.
/// </summary>
/// <param name="task">Task to execute.</param>
/// <param name="taskArg">Optional task argument.</param>
/// <returns>Task result.</returns>
public Future<TReduceRes> Execute<TArg, TJobRes, TReduceRes>(IComputeTask<TArg, TJobRes, TReduceRes> task,
TArg taskArg)
{
IgniteArgumentCheck.NotNull(task, "task");
var holder = new ComputeTaskHolder<TArg, TJobRes, TReduceRes>((Ignite) _prj.Ignite, this, task, taskArg);
long ptr = Marshaller.Ignite.HandleRegistry.Allocate(holder);
var futTarget = DoOutOpObject(OpExecNative, w =>
{
w.WriteLong(ptr);
w.WriteLong(_prj.TopologyVersion);
});
var future = holder.Future;
future.SetTarget(new Listenable(futTarget, Marshaller));
return future;
}
/// <summary>
/// Executes given task on the grid projection. For step-by-step explanation of task execution process
/// refer to <see cref="IComputeTask{A,T,R}"/> documentation.
/// </summary>
/// <param name="taskType">Task type.</param>
/// <param name="taskArg">Optional task argument.</param>
/// <returns>Task result.</returns>
public Future<TReduceRes> Execute<TArg, TJobRes, TReduceRes>(Type taskType, TArg taskArg)
{
IgniteArgumentCheck.NotNull(taskType, "taskType");
object task = FormatterServices.GetUninitializedObject(taskType);
var task0 = task as IComputeTask<TArg, TJobRes, TReduceRes>;
if (task0 == null)
throw new IgniteException("Task type doesn't implement IComputeTask: " + taskType.Name);
return Execute(task0, taskArg);
}
/// <summary>
/// Executes provided job on a node in this grid projection. The result of the
/// job execution is returned from the result closure.
/// </summary>
/// <param name="clo">Job to execute.</param>
/// <returns>Job result for this execution.</returns>
public Future<TJobRes> Execute<TJobRes>(IComputeFunc<TJobRes> clo)
{
IgniteArgumentCheck.NotNull(clo, "clo");
return ExecuteClosures0(new ComputeSingleClosureTask<object, TJobRes, TJobRes>(),
new ComputeOutFuncJob(clo.ToNonGeneric()), null, false);
}
/// <summary>
/// Executes provided delegate on a node in this grid projection. The result of the
/// job execution is returned from the result closure.
/// </summary>
/// <param name="func">Func to execute.</param>
/// <returns>Job result for this execution.</returns>
public Future<TJobRes> Execute<TJobRes>(Func<TJobRes> func)
{
IgniteArgumentCheck.NotNull(func, "func");
var wrappedFunc = new ComputeOutFuncWrapper(func, () => func());
return ExecuteClosures0(new ComputeSingleClosureTask<object, TJobRes, TJobRes>(),
new ComputeOutFuncJob(wrappedFunc), null, false);
}
/// <summary>
/// Executes collection of jobs on nodes within this grid projection.
/// </summary>
/// <param name="clos">Collection of jobs to execute.</param>
/// <returns>Collection of job results for this execution.</returns>
public Future<ICollection<TJobRes>> Execute<TJobRes>(IEnumerable<IComputeFunc<TJobRes>> clos)
{
IgniteArgumentCheck.NotNull(clos, "clos");
ICollection<IComputeJob> jobs = new List<IComputeJob>(GetCountOrZero(clos));
foreach (IComputeFunc<TJobRes> clo in clos)
jobs.Add(new ComputeOutFuncJob(clo.ToNonGeneric()));
return ExecuteClosures0(new ComputeMultiClosureTask<object, TJobRes, ICollection<TJobRes>>(jobs.Count),
null, jobs, false);
}
/// <summary>
/// Executes collection of jobs on nodes within this grid projection.
/// </summary>
/// <param name="clos">Collection of jobs to execute.</param>
/// <param name="rdc">Reducer to reduce all job results into one individual return value.</param>
/// <returns>Collection of job results for this execution.</returns>
public Future<TReduceRes> Execute<TJobRes, TReduceRes>(IEnumerable<IComputeFunc<TJobRes>> clos,
IComputeReducer<TJobRes, TReduceRes> rdc)
{
IgniteArgumentCheck.NotNull(clos, "clos");
ICollection<IComputeJob> jobs = new List<IComputeJob>(GetCountOrZero(clos));
foreach (var clo in clos)
jobs.Add(new ComputeOutFuncJob(clo.ToNonGeneric()));
return ExecuteClosures0(new ComputeReducingClosureTask<object, TJobRes, TReduceRes>(rdc), null, jobs, false);
}
/// <summary>
/// Broadcasts given job to all nodes in grid projection. Every participating node will return a job result.
/// </summary>
/// <param name="clo">Job to broadcast to all projection nodes.</param>
/// <returns>Collection of results for this execution.</returns>
public Future<ICollection<TJobRes>> Broadcast<TJobRes>(IComputeFunc<TJobRes> clo)
{
IgniteArgumentCheck.NotNull(clo, "clo");
return ExecuteClosures0(new ComputeMultiClosureTask<object, TJobRes, ICollection<TJobRes>>(1),
new ComputeOutFuncJob(clo.ToNonGeneric()), null, true);
}
/// <summary>
/// Broadcasts given closure job with passed in argument to all nodes in grid projection.
/// Every participating node will return a job result.
/// </summary>
/// <param name="clo">Job to broadcast to all projection nodes.</param>
/// <param name="arg">Job closure argument.</param>
/// <returns>Collection of results for this execution.</returns>
public Future<ICollection<TJobRes>> Broadcast<TArg, TJobRes>(IComputeFunc<TArg, TJobRes> clo, TArg arg)
{
IgniteArgumentCheck.NotNull(clo, "clo");
return ExecuteClosures0(new ComputeMultiClosureTask<object, TJobRes, ICollection<TJobRes>>(1),
new ComputeFuncJob(clo.ToNonGeneric(), arg), null, true);
}
/// <summary>
/// Broadcasts given job to all nodes in grid projection.
/// </summary>
/// <param name="action">Job to broadcast to all projection nodes.</param>
public Future<object> Broadcast(IComputeAction action)
{
IgniteArgumentCheck.NotNull(action, "action");
return ExecuteClosures0(new ComputeSingleClosureTask<object, object, object>(),
new ComputeActionJob(action), opId: OpBroadcast);
}
/// <summary>
/// Executes provided job on a node in this grid projection.
/// </summary>
/// <param name="action">Job to execute.</param>
public Future<object> Run(IComputeAction action)
{
IgniteArgumentCheck.NotNull(action, "action");
return ExecuteClosures0(new ComputeSingleClosureTask<object, object, object>(),
new ComputeActionJob(action));
}
/// <summary>
/// Executes collection of jobs on Ignite nodes within this grid projection.
/// </summary>
/// <param name="actions">Jobs to execute.</param>
public Future<object> Run(IEnumerable<IComputeAction> actions)
{
IgniteArgumentCheck.NotNull(actions, "actions");
var actions0 = actions as ICollection;
if (actions0 == null)
{
var jobs = actions.Select(a => new ComputeActionJob(a)).ToList();
return ExecuteClosures0(new ComputeSingleClosureTask<object, object, object>(), jobs: jobs,
jobsCount: jobs.Count);
}
else
{
var jobs = actions.Select(a => new ComputeActionJob(a));
return ExecuteClosures0(new ComputeSingleClosureTask<object, object, object>(), jobs: jobs,
jobsCount: actions0.Count);
}
}
/// <summary>
/// Executes provided closure job on a node in this grid projection.
/// </summary>
/// <param name="clo">Job to run.</param>
/// <param name="arg">Job argument.</param>
/// <returns>Job result for this execution.</returns>
public Future<TJobRes> Apply<TArg, TJobRes>(IComputeFunc<TArg, TJobRes> clo, TArg arg)
{
IgniteArgumentCheck.NotNull(clo, "clo");
return ExecuteClosures0(new ComputeSingleClosureTask<TArg, TJobRes, TJobRes>(),
new ComputeFuncJob(clo.ToNonGeneric(), arg), null, false);
}
/// <summary>
/// Executes provided closure job on nodes within this grid projection. A new job is executed for
/// every argument in the passed in collection. The number of actual job executions will be
/// equal to size of the job arguments collection.
/// </summary>
/// <param name="clo">Job to run.</param>
/// <param name="args">Job arguments.</param>
/// <returns>Collection of job results.</returns>
public Future<ICollection<TJobRes>> Apply<TArg, TJobRes>(IComputeFunc<TArg, TJobRes> clo,
IEnumerable<TArg> args)
{
IgniteArgumentCheck.NotNull(clo, "clo");
IgniteArgumentCheck.NotNull(clo, "clo");
var jobs = new List<IComputeJob>(GetCountOrZero(args));
var func = clo.ToNonGeneric();
foreach (TArg arg in args)
jobs.Add(new ComputeFuncJob(func, arg));
return ExecuteClosures0(new ComputeMultiClosureTask<TArg, TJobRes, ICollection<TJobRes>>(jobs.Count),
null, jobs, false);
}
/// <summary>
/// Executes provided closure job on nodes within this grid projection. A new job is executed for
/// every argument in the passed in collection. The number of actual job executions will be
/// equal to size of the job arguments collection. The returned job results will be reduced
/// into an individual result by provided reducer.
/// </summary>
/// <param name="clo">Job to run.</param>
/// <param name="args">Job arguments.</param>
/// <param name="rdc">Reducer to reduce all job results into one individual return value.</param>
/// <returns>Reduced job result for this execution.</returns>
public Future<TReduceRes> Apply<TArg, TJobRes, TReduceRes>(IComputeFunc<TArg, TJobRes> clo,
IEnumerable<TArg> args, IComputeReducer<TJobRes, TReduceRes> rdc)
{
IgniteArgumentCheck.NotNull(clo, "clo");
IgniteArgumentCheck.NotNull(clo, "clo");
IgniteArgumentCheck.NotNull(clo, "clo");
ICollection<IComputeJob> jobs = new List<IComputeJob>(GetCountOrZero(args));
var func = clo.ToNonGeneric();
foreach (TArg arg in args)
jobs.Add(new ComputeFuncJob(func, arg));
return ExecuteClosures0(new ComputeReducingClosureTask<TArg, TJobRes, TReduceRes>(rdc),
null, jobs, false);
}
/// <summary>
/// Executes given job on the node where data for provided affinity key is located
/// (a.k.a. affinity co-location).
/// </summary>
/// <param name="cacheName">Name of the cache to use for affinity co-location.</param>
/// <param name="affinityKey">Affinity key.</param>
/// <param name="action">Job to execute.</param>
public Future<object> AffinityRun(string cacheName, object affinityKey, IComputeAction action)
{
IgniteArgumentCheck.NotNull(action, "action");
return ExecuteClosures0(new ComputeSingleClosureTask<object, object, object>(),
new ComputeActionJob(action), opId: OpAffinity,
writeAction: w => WriteAffinity(w, cacheName, affinityKey));
}
/// <summary>
/// Executes given job on the node where data for provided affinity key is located
/// (a.k.a. affinity co-location).
/// </summary>
/// <param name="cacheName">Name of the cache to use for affinity co-location.</param>
/// <param name="affinityKey">Affinity key.</param>
/// <param name="clo">Job to execute.</param>
/// <returns>Job result for this execution.</returns>
/// <typeparam name="TJobRes">Type of job result.</typeparam>
public Future<TJobRes> AffinityCall<TJobRes>(string cacheName, object affinityKey, IComputeFunc<TJobRes> clo)
{
IgniteArgumentCheck.NotNull(clo, "clo");
return ExecuteClosures0(new ComputeSingleClosureTask<object, TJobRes, TJobRes>(),
new ComputeOutFuncJob(clo.ToNonGeneric()), opId: OpAffinity,
writeAction: w => WriteAffinity(w, cacheName, affinityKey));
}
/** <inheritDoc /> */
protected override T Unmarshal<T>(IBinaryStream stream)
{
bool keep = _keepBinary.Value;
return Marshaller.Unmarshal<T>(stream, keep);
}
/// <summary>
/// Internal routine for closure-based task execution.
/// </summary>
/// <param name="task">Task.</param>
/// <param name="job">Job.</param>
/// <param name="jobs">Jobs.</param>
/// <param name="broadcast">Broadcast flag.</param>
/// <returns>Future.</returns>
private Future<TReduceRes> ExecuteClosures0<TArg, TJobRes, TReduceRes>(
IComputeTask<TArg, TJobRes, TReduceRes> task, IComputeJob job,
ICollection<IComputeJob> jobs, bool broadcast)
{
return ExecuteClosures0(task, job, jobs, broadcast ? OpBroadcast : OpUnicast,
jobs == null ? 1 : jobs.Count);
}
/// <summary>
/// Internal routine for closure-based task execution.
/// </summary>
/// <param name="task">Task.</param>
/// <param name="job">Job.</param>
/// <param name="jobs">Jobs.</param>
/// <param name="opId">Op code.</param>
/// <param name="jobsCount">Jobs count.</param>
/// <param name="writeAction">Custom write action.</param>
/// <returns>Future.</returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes",
Justification = "User code can throw any exception")]
private Future<TReduceRes> ExecuteClosures0<TArg, TJobRes, TReduceRes>(
IComputeTask<TArg, TJobRes, TReduceRes> task, IComputeJob job = null,
IEnumerable<IComputeJob> jobs = null, int opId = OpUnicast, int jobsCount = 0,
Action<BinaryWriter> writeAction = null)
{
Debug.Assert(job != null || jobs != null);
var holder = new ComputeTaskHolder<TArg, TJobRes, TReduceRes>((Ignite) _prj.Ignite, this, task, default(TArg));
var taskHandle = Marshaller.Ignite.HandleRegistry.Allocate(holder);
var jobHandles = new List<long>(job != null ? 1 : jobsCount);
try
{
Exception err = null;
try
{
var futTarget = DoOutOpObject(opId, writer =>
{
writer.WriteLong(taskHandle);
if (job != null)
{
writer.WriteInt(1);
jobHandles.Add(WriteJob(job, writer));
}
else
{
writer.WriteInt(jobsCount);
Debug.Assert(jobs != null, "jobs != null");
jobHandles.AddRange(jobs.Select(jobEntry => WriteJob(jobEntry, writer)));
}
holder.JobHandles(jobHandles);
if (writeAction != null)
writeAction(writer);
});
holder.Future.SetTarget(new Listenable(futTarget, Marshaller));
}
catch (Exception e)
{
err = e;
}
if (err != null)
{
// Manual job handles release because they were not assigned to the task yet.
foreach (var hnd in jobHandles)
Marshaller.Ignite.HandleRegistry.Release(hnd);
holder.CompleteWithError(taskHandle, err);
}
}
catch (Exception e)
{
// This exception means that out-op failed.
holder.CompleteWithError(taskHandle, e);
}
return holder.Future;
}
/// <summary>
/// Writes the job.
/// </summary>
/// <param name="job">The job.</param>
/// <param name="writer">The writer.</param>
/// <returns>Handle to the job holder</returns>
private long WriteJob(IComputeJob job, BinaryWriter writer)
{
var jobHolder = new ComputeJobHolder((Ignite) _prj.Ignite, job);
var jobHandle = Marshaller.Ignite.HandleRegistry.Allocate(jobHolder);
writer.WriteLong(jobHandle);
try
{
writer.WriteObject(jobHolder);
}
catch (Exception)
{
Marshaller.Ignite.HandleRegistry.Release(jobHandle);
throw;
}
return jobHandle;
}
/// <summary>
/// Write task to the writer.
/// </summary>
/// <param name="writer">Writer.</param>
/// <param name="taskName">Task name.</param>
/// <param name="taskArg">Task arg.</param>
/// <param name="nodes">Nodes.</param>
private void WriteTask(IBinaryRawWriter writer, string taskName, object taskArg,
ICollection<IClusterNode> nodes)
{
writer.WriteString(taskName);
writer.WriteBoolean(_keepBinary.Value);
writer.WriteObject(taskArg);
WriteNodeIds(writer, nodes);
}
/// <summary>
/// Write node IDs.
/// </summary>
/// <param name="writer">Writer.</param>
/// <param name="nodes">Nodes.</param>
private static void WriteNodeIds(IBinaryRawWriter writer, ICollection<IClusterNode> nodes)
{
if (nodes == null)
writer.WriteBoolean(false);
else
{
writer.WriteBoolean(true);
writer.WriteInt(nodes.Count);
foreach (IClusterNode node in nodes)
writer.WriteGuid(node.Id);
}
}
/// <summary>
/// Writes the affinity info.
/// </summary>
/// <param name="writer">The writer.</param>
/// <param name="cacheName">Name of the cache to use for affinity co-location.</param>
/// <param name="affinityKey">Affinity key.</param>
private static void WriteAffinity(BinaryWriter writer, string cacheName, object affinityKey)
{
writer.WriteString(cacheName);
writer.WriteObject(affinityKey);
}
/// <summary>
/// Gets element count or zero.
/// </summary>
private static int GetCountOrZero(object collection)
{
var coll = collection as ICollection;
return coll == null ? 0 : coll.Count;
}
}
}
| |
// ============================================================
// Name: UMABonePoseMixerWindow
// Author: Eli Curtz
// Copyright: (c) 2013 Eli Curtz
// ============================================================
#if UNITY_EDITOR
using UnityEngine;
using UnityEditor;
using System.Text;
using System.Collections.Generic;
namespace UMA.PoseTools
{
public class UMABonePoseMixerWindow : EditorWindow
{
public Transform skeleton = null;
public UnityEngine.Object poseFolder = null;
public UMABonePose newComponent = null;
public string poseName = "";
private Dictionary<UMABonePose, float> poseComponents = new Dictionary<UMABonePose, float>();
private Dictionary<string, float> boneComponents = new Dictionary<string, float>();
public void EnforceFolder(ref UnityEngine.Object folderObject)
{
if (folderObject != null)
{
string destpath = AssetDatabase.GetAssetPath(folderObject);
if (string.IsNullOrEmpty(destpath))
{
folderObject = null;
}
else if (!System.IO.Directory.Exists(destpath))
{
destpath = destpath.Substring(0, destpath.LastIndexOf('/'));
folderObject = AssetDatabase.LoadMainAssetAtPath(destpath);
}
}
}
void OnGUI()
{
#pragma warning disable 0618
EditorGUIUtility.LookLikeControls();
Transform newSkeleton = EditorGUILayout.ObjectField("Rig Prefab", skeleton, typeof(Transform), true) as Transform;
if (skeleton != newSkeleton)
{
skeleton = newSkeleton;
boneComponents = new Dictionary<string, float>();
Transform[] transforms = UMABonePose.GetTransformsInPrefab(skeleton);
foreach (Transform bone in transforms)
{
boneComponents.Add(bone.name, 1f);
}
}
EditorGUILayout.Space();
EditorGUILayout.LabelField("Component Poses");
EditorGUI.indentLevel++;
UMABonePose changedPose = null;
UMABonePose deletedPose = null;
float sliderVal = 0;
List<string> activeBones = new List<string>();
foreach (KeyValuePair<UMABonePose, float> entry in poseComponents)
{
GUILayout.BeginHorizontal();
sliderVal = EditorGUILayout.Slider(entry.Key.name, entry.Value, 0f, 2f);
if (sliderVal != entry.Value)
{
changedPose = entry.Key;
}
if (GUILayout.Button("-", GUILayout.Width(20f)))
{
deletedPose = entry.Key;
}
else
{
foreach (UMABonePose.PoseBone pose in entry.Key.poses)
{
if (!activeBones.Contains(pose.bone))
{
activeBones.Add(pose.bone);
}
}
}
GUILayout.EndHorizontal();
}
if (changedPose != null)
{
poseComponents[changedPose] = sliderVal;
}
if (deletedPose != null)
{
poseComponents.Remove(deletedPose);
}
GUILayout.BeginHorizontal();
newComponent = EditorGUILayout.ObjectField(newComponent, typeof(UMABonePose), false) as UMABonePose;
GUI.enabled = (newComponent != null);
if (GUILayout.Button("+", GUILayout.Width(30f)))
{
poseComponents.Add(newComponent, 1f);
newComponent = null;
}
GUI.enabled = true;
GUILayout.EndHorizontal();
EditorGUI.indentLevel--;
EditorGUILayout.Space();
EditorGUILayout.LabelField("Component Bones");
EditorGUI.indentLevel++;
foreach (string bone in activeBones)
{
GUILayout.BeginHorizontal();
if (boneComponents.ContainsKey(bone))
{
boneComponents[bone] = EditorGUILayout.Slider(bone, boneComponents[bone], 0f, 2f);
}
GUILayout.EndHorizontal();
}
EditorGUI.indentLevel--;
GUILayout.BeginHorizontal();
if (GUILayout.Button("Left"))
{
foreach (string bone in activeBones)
{
if (bone.Contains("Left") || bone.Contains("left"))
{
boneComponents[bone] = 1f;
}
else if (bone.Contains("Right") || bone.Contains("right"))
{
boneComponents[bone] = 0f;
}
else
{
boneComponents[bone] = 0.5f;
}
}
}
if (GUILayout.Button("Right"))
{
foreach (string bone in activeBones)
{
if (bone.Contains("Left") || bone.Contains("left"))
{
boneComponents[bone] = 0f;
}
else if (bone.Contains("Right") || bone.Contains("right"))
{
boneComponents[bone] = 1f;
}
else
{
boneComponents[bone] = 0.5f;
}
}
}
if (GUILayout.Button("Mirror"))
{
foreach (string bone in activeBones)
{
boneComponents[bone] = Mathf.Max(1f - boneComponents[bone], 0f);
}
if (poseName.EndsWith("_L"))
{
poseName = poseName.Substring(0, poseName.Length - 1) + "R";
}
else if (poseName.EndsWith("_R"))
{
poseName = poseName.Substring(0, poseName.Length - 1) + "L";
}
}
GUILayout.EndHorizontal();
EditorGUILayout.Space();
poseFolder = EditorGUILayout.ObjectField("Pose Folder", poseFolder, typeof(UnityEngine.Object), false) as UnityEngine.Object;
EnforceFolder(ref poseFolder);
GUILayout.BeginHorizontal();
poseName = EditorGUILayout.TextField("New Pose", poseName);
if ((skeleton == null) || (poseFolder == null) || (poseComponents.Count < 1) || (poseName.Length < 1))
{
GUI.enabled = false;
}
if (GUILayout.Button("Build", GUILayout.Width(60f)))
{
string folderPath = AssetDatabase.GetAssetPath(poseFolder);
UMABonePose newPose = CreatePoseAsset(folderPath, poseName);
Transform[] sourceBones = UMABonePose.GetTransformsInPrefab(skeleton);
foreach (string bone in activeBones)
{
Transform source = System.Array.Find<Transform>(sourceBones, entry => entry.name == bone);
if (source != null)
{
Vector3 position = source.localPosition;
Quaternion rotation = source.localRotation;
Vector3 scale = source.localScale;
bool include = false;
foreach (KeyValuePair<UMABonePose, float> entry in poseComponents)
{
float strength = entry.Value * boneComponents[bone];
if (strength > 0f)
{
foreach (UMABonePose.PoseBone pose in entry.Key.poses)
{
if (pose.bone == bone)
{
position += pose.position * strength;
Quaternion posedRotation = rotation * pose.rotation;
rotation = Quaternion.Slerp(rotation, posedRotation, strength);
scale = Vector3.Slerp(scale, pose.scale, strength);
}
}
include = true;
}
}
if (include)
{
newPose.AddBone(source, position, rotation, scale);
}
}
else
{
Debug.LogWarning("Bone not found in skeleton: " + bone);
}
}
EditorUtility.SetDirty(newPose);
AssetDatabase.SaveAssets();
}
GUI.enabled = true;
GUILayout.EndHorizontal();
}
public static UMABonePose CreatePoseAsset(string assetFolder, string assetName)
{
if (!System.IO.Directory.Exists(assetFolder))
{
System.IO.Directory.CreateDirectory(assetFolder);
}
UMABonePose asset = ScriptableObject.CreateInstance<UMABonePose>();
AssetDatabase.CreateAsset(asset, assetFolder + "/" + assetName + ".asset");
return asset;
}
[MenuItem("UMA/Pose Tools/UMA Bone Pose Mixer")]
public static void OpenUMABonePoseBuildWindow()
{
EditorWindow win = EditorWindow.GetWindow(typeof(UMABonePoseMixerWindow));
#if !UNITY_4_6 && !UNITY_5_0
win.titleContent.text = "Pose Mixer";
#else
win.title = "Pose Mixer";
#endif
}
}
}
#endif
| |
// =================================================================================================
// ADOBE SYSTEMS INCORPORATED
// Copyright 2006 Adobe Systems Incorporated
// All Rights Reserved
//
// NOTICE: Adobe permits you to use, modify, and distribute this file in accordance with the terms
// of the Adobe license agreement accompanying it.
// =================================================================================================
using System.Text;
using Com.Adobe.Xmp;
using Sharpen;
namespace Com.Adobe.Xmp.Impl
{
/// <summary>Utility functions for the XMPToolkit implementation.</summary>
/// <since>06.06.2006</since>
public class Utils : XMPConst
{
/// <summary>segments of a UUID</summary>
public const int UuidSegmentCount = 4;
/// <summary>length of a UUID</summary>
public const int UuidLength = 32 + UuidSegmentCount;
/// <summary>table of XML name start chars (<= 0xFF)</summary>
private static bool[] xmlNameStartChars;
/// <summary>table of XML name chars (<= 0xFF)</summary>
private static bool[] xmlNameChars;
static Utils()
{
InitCharTables();
}
/// <summary>Private constructor</summary>
private Utils()
{
}
// EMPTY
/// <summary>
/// Normalize an xml:lang value so that comparisons are effectively case
/// insensitive as required by RFC 3066 (which superceeds RFC 1766).
/// </summary>
/// <remarks>
/// Normalize an xml:lang value so that comparisons are effectively case
/// insensitive as required by RFC 3066 (which superceeds RFC 1766). The
/// normalization rules:
/// <ul>
/// <li> The primary subtag is lower case, the suggested practice of ISO 639.
/// <li> All 2 letter secondary subtags are upper case, the suggested
/// practice of ISO 3166.
/// <li> All other subtags are lower case.
/// </ul>
/// </remarks>
/// <param name="value">raw value</param>
/// <returns>Returns the normalized value.</returns>
public static string NormalizeLangValue(string value)
{
// don't normalize x-default
if (XMPConstConstants.XDefault.Equals(value))
{
return value;
}
int subTag = 1;
StringBuilder buffer = new StringBuilder();
for (int i = 0; i < value.Length; i++)
{
switch (value[i])
{
case '-':
case '_':
{
// move to next subtag and convert underscore to hyphen
buffer.Append('-');
subTag++;
break;
}
case ' ':
{
// remove spaces
break;
}
default:
{
// convert second subtag to uppercase, all other to lowercase
if (subTag != 2)
{
buffer.Append(System.Char.ToLower(value[i]));
}
else
{
buffer.Append(System.Char.ToUpper(value[i]));
}
break;
}
}
}
return buffer.ToString();
}
/// <summary>
/// Split the name and value parts for field and qualifier selectors:
/// <ul>
/// <li>[qualName="value"] - An element in an array of structs, chosen by a
/// field value.
/// </summary>
/// <remarks>
/// Split the name and value parts for field and qualifier selectors:
/// <ul>
/// <li>[qualName="value"] - An element in an array of structs, chosen by a
/// field value.
/// <li>[?qualName="value"] - An element in an array, chosen by a qualifier
/// value.
/// </ul>
/// The value portion is a string quoted by ''' or '"'. The value may contain
/// any character including a doubled quoting character. The value may be
/// empty. <em>Note:</em> It is assumed that the expression is formal
/// correct
/// </remarks>
/// <param name="selector">the selector</param>
/// <returns>
/// Returns an array where the first entry contains the name and the
/// second the value.
/// </returns>
internal static string[] SplitNameAndValue(string selector)
{
// get the name
int eq = selector.IndexOf('=');
int pos = 1;
if (selector[pos] == '?')
{
pos++;
}
string name = Sharpen.Runtime.Substring(selector, pos, eq);
// get the value
pos = eq + 1;
char quote = selector[pos];
pos++;
int end = selector.Length - 2;
// quote and ]
StringBuilder value = new StringBuilder(end - eq);
while (pos < end)
{
value.Append(selector[pos]);
pos++;
if (selector[pos] == quote)
{
// skip one quote in value
pos++;
}
}
return new string[] { name, value.ToString() };
}
/// <param name="schema">a schema namespace</param>
/// <param name="prop">an XMP Property</param>
/// <returns>
/// Returns true if the property is defined as "Internal
/// Property", see XMP Specification.
/// </returns>
internal static bool IsInternalProperty(string schema, string prop)
{
bool isInternal = false;
if (XMPConstConstants.NsDc.Equals(schema))
{
if ("dc:format".Equals(prop) || "dc:language".Equals(prop))
{
isInternal = true;
}
}
else
{
if (XMPConstConstants.NsXmp.Equals(schema))
{
if ("xmp:BaseURL".Equals(prop) || "xmp:CreatorTool".Equals(prop) || "xmp:Format".Equals(prop) || "xmp:Locale".Equals(prop) || "xmp:MetadataDate".Equals(prop) || "xmp:ModifyDate".Equals(prop))
{
isInternal = true;
}
}
else
{
if (XMPConstConstants.NsPdf.Equals(schema))
{
if ("pdf:BaseURL".Equals(prop) || "pdf:Creator".Equals(prop) || "pdf:ModDate".Equals(prop) || "pdf:PDFVersion".Equals(prop) || "pdf:Producer".Equals(prop))
{
isInternal = true;
}
}
else
{
if (XMPConstConstants.NsTiff.Equals(schema))
{
isInternal = true;
if ("tiff:ImageDescription".Equals(prop) || "tiff:Artist".Equals(prop) || "tiff:Copyright".Equals(prop))
{
isInternal = false;
}
}
else
{
if (XMPConstConstants.NsExif.Equals(schema))
{
isInternal = true;
if ("exif:UserComment".Equals(prop))
{
isInternal = false;
}
}
else
{
if (XMPConstConstants.NsExifAux.Equals(schema))
{
isInternal = true;
}
else
{
if (XMPConstConstants.NsPhotoshop.Equals(schema))
{
if ("photoshop:ICCProfile".Equals(prop))
{
isInternal = true;
}
}
else
{
if (XMPConstConstants.NsCameraraw.Equals(schema))
{
if ("crs:Version".Equals(prop) || "crs:RawFileName".Equals(prop) || "crs:ToneCurveName".Equals(prop))
{
isInternal = true;
}
}
else
{
if (XMPConstConstants.NsAdobestockphoto.Equals(schema))
{
isInternal = true;
}
else
{
if (XMPConstConstants.NsXmpMm.Equals(schema))
{
isInternal = true;
}
else
{
if (XMPConstConstants.TypeText.Equals(schema))
{
isInternal = true;
}
else
{
if (XMPConstConstants.TypePagedfile.Equals(schema))
{
isInternal = true;
}
else
{
if (XMPConstConstants.TypeGraphics.Equals(schema))
{
isInternal = true;
}
else
{
if (XMPConstConstants.TypeImage.Equals(schema))
{
isInternal = true;
}
else
{
if (XMPConstConstants.TypeFont.Equals(schema))
{
isInternal = true;
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
return isInternal;
}
/// <summary>
/// Check some requirements for an UUID:
/// <ul>
/// <li>Length of the UUID is 32</li>
/// <li>The Delimiter count is 4 and all the 4 delimiter are on their right
/// position (8,13,18,23)</li>
/// </ul>
/// </summary>
/// <param name="uuid">uuid to test</param>
/// <returns>true - this is a well formed UUID, false - UUID has not the expected format</returns>
internal static bool CheckUUIDFormat(string uuid)
{
bool result = true;
int delimCnt = 0;
int delimPos = 0;
if (uuid == null)
{
return false;
}
for (delimPos = 0; delimPos < uuid.Length; delimPos++)
{
if (uuid[delimPos] == '-')
{
delimCnt++;
result = result && (delimPos == 8 || delimPos == 13 || delimPos == 18 || delimPos == 23);
}
}
return result && UuidSegmentCount == delimCnt && UuidLength == delimPos;
}
/// <summary>Simple check for valid XMLNames.</summary>
/// <remarks>
/// Simple check for valid XMLNames. Within ASCII range<br />
/// ":" | [A-Z] | "_" | [a-z] | [#xC0-#xD6] | [#xD8-#xF6]<br />
/// are accepted, above all characters (which is not entirely
/// correct according to the XML Spec.
/// </remarks>
/// <param name="name">an XML Name</param>
/// <returns>Return <code>true</code> if the name is correct.</returns>
public static bool IsXMLName(string name)
{
if (name.Length > 0 && !IsNameStartChar(name[0]))
{
return false;
}
for (int i = 1; i < name.Length; i++)
{
if (!IsNameChar(name[i]))
{
return false;
}
}
return true;
}
/// <summary>
/// Checks if the value is a legal "unqualified" XML name, as
/// defined in the XML Namespaces proposed recommendation.
/// </summary>
/// <remarks>
/// Checks if the value is a legal "unqualified" XML name, as
/// defined in the XML Namespaces proposed recommendation.
/// These are XML names, except that they must not contain a colon.
/// </remarks>
/// <param name="name">the value to check</param>
/// <returns>Returns true if the name is a valid "unqualified" XML name.</returns>
public static bool IsXMLNameNS(string name)
{
if (name.Length > 0 && (!IsNameStartChar(name[0]) || name[0] == ':'))
{
return false;
}
for (int i = 1; i < name.Length; i++)
{
if (!IsNameChar(name[i]) || name[i] == ':')
{
return false;
}
}
return true;
}
/// <param name="c">a char</param>
/// <returns>Returns true if the char is an ASCII control char.</returns>
internal static bool IsControlChar(char c)
{
return (c <= unchecked((int)(0x1F)) || c == unchecked((int)(0x7F))) && c != unchecked((int)(0x09)) && c != unchecked((int)(0x0A)) && c != unchecked((int)(0x0D));
}
/// <summary>Serializes the node value in XML encoding.</summary>
/// <remarks>
/// Serializes the node value in XML encoding. Its used for tag bodies and
/// attributes.<br />
/// <em>Note:</em> The attribute is always limited by quotes,
/// thats why <code>&apos;</code> is never serialized.<br />
/// <em>Note:</em> Control chars are written unescaped, but if the user uses others than tab, LF
/// and CR the resulting XML will become invalid.
/// </remarks>
/// <param name="value">a string</param>
/// <param name="forAttribute">flag if string is attribute value (need to additional escape quotes)</param>
/// <param name="escapeWhitespaces">Decides if LF, CR and TAB are escaped.</param>
/// <returns>Returns the value ready for XML output.</returns>
public static string EscapeXML(string value, bool forAttribute, bool escapeWhitespaces)
{
// quick check if character are contained that need special treatment
bool needsEscaping = false;
for (int i = 0; i < value.Length; i++)
{
char c = value[i];
if (c == '<' || c == '>' || c == '&' || (escapeWhitespaces && (c == '\t' || c == '\n' || c == '\r')) || (forAttribute && c == '"'))
{
// XML chars
needsEscaping = true;
break;
}
}
if (!needsEscaping)
{
// fast path
return value;
}
else
{
// slow path with escaping
StringBuilder buffer = new StringBuilder(value.Length * 4 / 3);
for (int i_1 = 0; i_1 < value.Length; i_1++)
{
char c = value[i_1];
if (!(escapeWhitespaces && (c == '\t' || c == '\n' || c == '\r')))
{
switch (c)
{
case '<':
{
// we do what "Canonical XML" expects
// AUDIT: ' not serialized as only outer qoutes are used
buffer.Append("<");
continue;
}
case '>':
{
buffer.Append(">");
continue;
}
case '&':
{
buffer.Append("&");
continue;
}
case '"':
{
buffer.Append(forAttribute ? """ : "\"");
continue;
}
default:
{
buffer.Append(c);
continue;
}
}
}
else
{
// write control chars escaped,
// if there are others than tab, LF and CR the xml will become invalid.
buffer.Append("&#x");
buffer.Append(Sharpen.Extensions.ToHexString(c).ToUpper());
buffer.Append(';');
}
}
return buffer.ToString();
}
}
/// <summary>Replaces the ASCII control chars with a space.</summary>
/// <param name="value">a node value</param>
/// <returns>Returns the cleaned up value</returns>
internal static string RemoveControlChars(string value)
{
StringBuilder buffer = new StringBuilder(value);
for (int i = 0; i < buffer.Length; i++)
{
if (IsControlChar(buffer[i]))
{
Sharpen.Runtime.SetCharAt(buffer, i, ' ');
}
}
return buffer.ToString();
}
/// <summary>Simple check if a character is a valid XML start name char.</summary>
/// <remarks>
/// Simple check if a character is a valid XML start name char.
/// All characters according to the XML Spec 1.1 are accepted:
/// http://www.w3.org/TR/xml11/#NT-NameStartChar
/// </remarks>
/// <param name="ch">a character</param>
/// <returns>Returns true if the character is a valid first char of an XML name.</returns>
private static bool IsNameStartChar(char ch)
{
return (ch <= unchecked((int)(0xFF)) && xmlNameStartChars[ch]) || (ch >= unchecked((int)(0x100)) && ch <= unchecked((int)(0x2FF))) || (ch >= unchecked((int)(0x370)) && ch <= unchecked((int)(0x37D))) || (ch >= unchecked((int)(0x37F)) && ch <=
unchecked((int)(0x1FFF))) || (ch >= unchecked((int)(0x200C)) && ch <= unchecked((int)(0x200D))) || (ch >= unchecked((int)(0x2070)) && ch <= unchecked((int)(0x218F))) || (ch >= unchecked((int)(0x2C00)) && ch <= unchecked((int)(0x2FEF))) ||
(ch >= unchecked((int)(0x3001)) && ch <= unchecked((int)(0xD7FF))) || (ch >= unchecked((int)(0xF900)) && ch <= unchecked((int)(0xFDCF))) || (ch >= unchecked((int)(0xFDF0)) && ch <= unchecked((int)(0xFFFD))) || (ch >= unchecked((int)(0x10000
)) && ch <= unchecked((int)(0xEFFFF)));
}
/// <summary>
/// Simple check if a character is a valid XML name char
/// (every char except the first one), according to the XML Spec 1.1:
/// http://www.w3.org/TR/xml11/#NT-NameChar
/// </summary>
/// <param name="ch">a character</param>
/// <returns>Returns true if the character is a valid char of an XML name.</returns>
private static bool IsNameChar(char ch)
{
return (ch <= unchecked((int)(0xFF)) && xmlNameChars[ch]) || IsNameStartChar(ch) || (ch >= unchecked((int)(0x300)) && ch <= unchecked((int)(0x36F))) || (ch >= unchecked((int)(0x203F)) && ch <= unchecked((int)(0x2040)));
}
/// <summary>
/// Initializes the char tables for the chars 0x00-0xFF for later use,
/// according to the XML 1.1 specification
/// http://www.w3.org/TR/xml11
/// </summary>
private static void InitCharTables()
{
xmlNameChars = new bool[unchecked((int)(0x0100))];
xmlNameStartChars = new bool[unchecked((int)(0x0100))];
for (char ch = (char)0; ch < xmlNameChars.Length; ch++)
{
xmlNameStartChars[ch] = ch == ':' || ('A' <= ch && ch <= 'Z') || ch == '_' || ('a' <= ch && ch <= 'z') || (unchecked((int)(0xC0)) <= ch && ch <= unchecked((int)(0xD6))) || (unchecked((int)(0xD8)) <= ch && ch <= unchecked((int)(0xF6))) || (unchecked(
(int)(0xF8)) <= ch && ch <= unchecked((int)(0xFF)));
xmlNameChars[ch] = xmlNameStartChars[ch] || ch == '-' || ch == '.' || ('0' <= ch && ch <= '9') || ch == unchecked((int)(0xB7));
}
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Xml;
using System.Runtime.CompilerServices;
using System.Linq;
using ICSharpCode.SharpZipLib.Zip;
using Umbraco.Core;
using Umbraco.Core.Logging;
using umbraco.cms.businesslogic.web;
using umbraco.cms.businesslogic.propertytype;
using umbraco.BusinessLogic;
using umbraco.DataLayer;
using System.Diagnostics;
using umbraco.cms.businesslogic.macro;
using umbraco.cms.businesslogic.template;
using umbraco.IO;
namespace umbraco.cms.businesslogic.packager
{
/// <summary>
/// The packager is a component which enables sharing of both data and functionality components between different umbraco installations.
///
/// The output is a .umb (a zip compressed file) which contains the exported documents/medias/macroes/documenttypes (etc.)
/// in a Xml document, along with the physical files used (images/usercontrols/xsl documents etc.)
///
/// Partly implemented, import of packages is done, the export is *under construction*.
/// </summary>
/// <remarks>
/// Ruben Verborgh 31/12/2007: I had to change some code, I marked my changes with "DATALAYER".
/// Reason: @@IDENTITY can't be used with the new datalayer.
/// I wasn't able to test the code, since I'm not aware how the code functions.
/// </remarks>
public class Installer
{
private string _name;
private string _version;
private string _url;
private string _license;
private string _licenseUrl;
private int _reqMajor;
private int _reqMinor;
private int _reqPatch;
private string _authorName;
private string _authorUrl;
private string _readme;
private string _control;
private bool _containUnsecureFiles = false;
private List<string> _unsecureFiles = new List<string>();
private bool _containsMacroConflict = false;
private Dictionary<string, string> _conflictingMacroAliases = new Dictionary<string, string>();
private bool _containsTemplateConflict = false;
private Dictionary<string, string> _conflictingTemplateAliases = new Dictionary<string, string>();
private bool _containsStyleSheetConflict = false;
private Dictionary<string, string> _conflictingStyleSheetNames = new Dictionary<string, string>();
private ArrayList _macros = new ArrayList();
private XmlDocument _packageConfig;
public string Name { get { return _name; } }
public string Version { get { return _version; } }
public string Url { get { return _url; } }
public string License { get { return _license; } }
public string LicenseUrl { get { return _licenseUrl; } }
public string Author { get { return _authorName; } }
public string AuthorUrl { get { return _authorUrl; } }
public string ReadMe { get { return _readme; } }
public string Control { get { return _control; } }
public bool ContainsMacroConflict { get { return _containsMacroConflict; } }
public IDictionary<string, string> ConflictingMacroAliases { get { return _conflictingMacroAliases; } }
public bool ContainsUnsecureFiles { get { return _containUnsecureFiles; } }
public List<string> UnsecureFiles { get { return _unsecureFiles; } }
public bool ContainsTemplateConflicts { get { return _containsTemplateConflict; } }
public IDictionary<string, string> ConflictingTemplateAliases { get { return _conflictingTemplateAliases; } }
public bool ContainsStyleSheeConflicts { get { return _containsStyleSheetConflict; } }
public IDictionary<string, string> ConflictingStyleSheetNames { get { return _conflictingStyleSheetNames; } }
public int RequirementsMajor { get { return _reqMajor; } }
public int RequirementsMinor { get { return _reqMinor; } }
public int RequirementsPatch { get { return _reqPatch; } }
/// <summary>
/// The xmldocument, describing the contents of a package.
/// </summary>
public XmlDocument Config
{
get { return _packageConfig; }
}
/// <summary>
/// Constructor
/// </summary>
public Installer()
{
}
/// <summary>
/// Constructor
/// </summary>
/// <param name="Name">The name of the package</param>
/// <param name="Version">The version of the package</param>
/// <param name="Url">The url to a descriptionpage</param>
/// <param name="License">The license under which the package is released (preferably GPL ;))</param>
/// <param name="LicenseUrl">The url to a licensedescription</param>
/// <param name="Author">The original author of the package</param>
/// <param name="AuthorUrl">The url to the Authors website</param>
/// <param name="RequirementsMajor">Umbraco version major</param>
/// <param name="RequirementsMinor">Umbraco version minor</param>
/// <param name="RequirementsPatch">Umbraco version patch</param>
/// <param name="Readme">The readme text</param>
/// <param name="Control">The name of the usercontrol used to configure the package after install</param>
public Installer(string Name, string Version, string Url, string License, string LicenseUrl, string Author, string AuthorUrl, int RequirementsMajor, int RequirementsMinor, int RequirementsPatch, string Readme, string Control)
{
_name = Name;
_version = Version;
_url = Url;
_license = License;
_licenseUrl = LicenseUrl;
_reqMajor = RequirementsMajor;
_reqMinor = RequirementsMinor;
_reqPatch = RequirementsPatch;
_authorName = Author;
_authorUrl = AuthorUrl;
_readme = Readme;
_control = Control;
}
#region Public Methods
/// <summary>
/// Adds the macro to the package
/// </summary>
/// <param name="MacroToAdd">Macro to add</param>
[Obsolete("This method does nothing but add the macro to an ArrayList that is never used, so don't call this method.")]
public void AddMacro(Macro MacroToAdd)
{
_macros.Add(MacroToAdd);
}
/// <summary>
/// Imports the specified package
/// </summary>
/// <param name="InputFile">Filename of the umbracopackage</param>
/// <returns></returns>
public string Import(string InputFile)
{
using (DisposableTimer.DebugDuration<Installer>(
() => "Importing package file " + InputFile,
() => "Package file " + InputFile + "imported"))
{
string tempDir = "";
if (File.Exists(IOHelper.MapPath(SystemDirectories.Data + Path.DirectorySeparatorChar + InputFile)))
{
FileInfo fi = new FileInfo(IOHelper.MapPath(SystemDirectories.Data + Path.DirectorySeparatorChar + InputFile));
// Check if the file is a valid package
if (fi.Extension.ToLower() == ".umb")
{
try
{
tempDir = UnPack(fi.FullName);
LoadConfig(tempDir);
}
catch (Exception unpackE)
{
throw new Exception("Error unpacking extension...", unpackE);
}
}
else
throw new Exception("Error - file isn't a package (doesn't have a .umb extension). Check if the file automatically got named '.zip' upon download.");
}
else
throw new Exception("Error - file not found. Could find file named '" + IOHelper.MapPath(SystemDirectories.Data + Path.DirectorySeparatorChar + InputFile) + "'");
return tempDir;
}
}
public int CreateManifest(string tempDir, string guid, string repoGuid)
{
//This is the new improved install rutine, which chops up the process into 3 steps, creating the manifest, moving files, and finally handling umb objects
string _packName = xmlHelper.GetNodeValue(_packageConfig.DocumentElement.SelectSingleNode("/umbPackage/info/package/name"));
string _packAuthor = xmlHelper.GetNodeValue(_packageConfig.DocumentElement.SelectSingleNode("/umbPackage/info/author/name"));
string _packAuthorUrl = xmlHelper.GetNodeValue(_packageConfig.DocumentElement.SelectSingleNode("/umbPackage/info/author/website"));
string _packVersion = xmlHelper.GetNodeValue(_packageConfig.DocumentElement.SelectSingleNode("/umbPackage/info/package/version"));
string _packReadme = xmlHelper.GetNodeValue(_packageConfig.DocumentElement.SelectSingleNode("/umbPackage/info/readme"));
string _packLicense = xmlHelper.GetNodeValue(_packageConfig.DocumentElement.SelectSingleNode("/umbPackage/info/package/license "));
string _packUrl = xmlHelper.GetNodeValue(_packageConfig.DocumentElement.SelectSingleNode("/umbPackage/info/package/url "));
bool _enableSkins = false;
string _skinRepoGuid = "";
if (_packageConfig.DocumentElement.SelectSingleNode("/umbPackage/enableSkins") != null)
{
XmlNode _skinNode = _packageConfig.DocumentElement.SelectSingleNode("/umbPackage/enableSkins");
_enableSkins = bool.Parse(xmlHelper.GetNodeValue(_skinNode));
if (_skinNode.Attributes["repository"] != null && !string.IsNullOrEmpty(_skinNode.Attributes["repository"].Value))
_skinRepoGuid = _skinNode.Attributes["repository"].Value;
}
//Create a new package instance to record all the installed package adds - this is the same format as the created packages has.
//save the package meta data
packager.InstalledPackage insPack = packager.InstalledPackage.MakeNew(_packName);
insPack.Data.Author = _packAuthor;
insPack.Data.AuthorUrl = _packAuthorUrl;
insPack.Data.Version = _packVersion;
insPack.Data.Readme = _packReadme;
insPack.Data.License = _packLicense;
insPack.Data.Url = _packUrl;
//skinning
insPack.Data.EnableSkins = _enableSkins;
insPack.Data.SkinRepoGuid = string.IsNullOrEmpty(_skinRepoGuid) ? Guid.Empty : new Guid(_skinRepoGuid);
insPack.Data.PackageGuid = guid; //the package unique key.
insPack.Data.RepositoryGuid = repoGuid; //the repository unique key, if the package is a file install, the repository will not get logged.
insPack.Save();
return insPack.Data.Id;
}
public void InstallFiles(int packageId, string tempDir)
{
using (DisposableTimer.DebugDuration<Installer>(
() => "Installing package files for package id " + packageId + " into temp folder " + tempDir,
() => "Package file installation complete for package id " + packageId))
{
//retrieve the manifest to continue installation
packager.InstalledPackage insPack = packager.InstalledPackage.GetById(packageId);
// Move files
//string virtualBasePath = System.Web.HttpContext.Current.Request.ApplicationPath;
string basePath = System.Web.Hosting.HostingEnvironment.ApplicationPhysicalPath;
foreach (XmlNode n in _packageConfig.DocumentElement.SelectNodes("//file"))
{
//we enclose the whole file-moving to ensure that the entire installer doesn't crash
try
{
String destPath = GetFileName(basePath, xmlHelper.GetNodeValue(n.SelectSingleNode("orgPath")));
String sourceFile = GetFileName(tempDir, xmlHelper.GetNodeValue(n.SelectSingleNode("guid")));
String destFile = GetFileName(destPath, xmlHelper.GetNodeValue(n.SelectSingleNode("orgName")));
// Create the destination directory if it doesn't exist
if (!Directory.Exists(destPath))
Directory.CreateDirectory(destPath);
//If a file with this name exists, delete it
else if (File.Exists(destFile))
File.Delete(destFile);
// Move the file
File.Move(sourceFile, destFile);
//PPH log file install
insPack.Data.Files.Add(xmlHelper.GetNodeValue(n.SelectSingleNode("orgPath")) + "/" + xmlHelper.GetNodeValue(n.SelectSingleNode("orgName")));
}
catch (Exception ex)
{
LogHelper.Error<Installer>("Package install error", ex);
}
}
insPack.Save();
}
}
public void InstallBusinessLogic(int packageId, string tempDir)
{
using (DisposableTimer.DebugDuration<Installer>(
() => "Installing business logic for package id " + packageId + " into temp folder " + tempDir,
() => "Package business logic installation complete for package id " + packageId))
{
//retrieve the manifest to continue installation
var insPack = InstalledPackage.GetById(packageId);
//bool saveNeeded = false;
// Get current user, with a fallback
var currentUser = new User(0);
if (string.IsNullOrEmpty(BasePages.UmbracoEnsuredPage.umbracoUserContextID) == false)
{
if (BasePages.UmbracoEnsuredPage.ValidateUserContextID(BasePages.UmbracoEnsuredPage.umbracoUserContextID))
{
currentUser = User.GetCurrent();
}
}
//Xml as XElement which is used with the new PackagingService
var rootElement = _packageConfig.DocumentElement.GetXElement();
var packagingService = ApplicationContext.Current.Services.PackagingService;
#region DataTypes
var dataTypeElement = rootElement.Descendants("DataTypes").FirstOrDefault();
if(dataTypeElement != null)
{
var dataTypeDefinitions = packagingService.ImportDataTypeDefinitions(dataTypeElement, currentUser.Id);
foreach (var dataTypeDefinition in dataTypeDefinitions)
{
insPack.Data.DataTypes.Add(dataTypeDefinition.Id.ToString(CultureInfo.InvariantCulture));
//saveNeeded = true;
}
}
/*foreach (XmlNode n in _packageConfig.DocumentElement.SelectNodes("//DataType"))
{
cms.businesslogic.datatype.DataTypeDefinition newDtd = cms.businesslogic.datatype.DataTypeDefinition.Import(n);
if (newDtd != null)
{
insPack.Data.DataTypes.Add(newDtd.Id.ToString());
saveNeeded = true;
}
}*/
//if (saveNeeded) { insPack.Save(); saveNeeded = false; }
#endregion
#region Languages
foreach (XmlNode n in _packageConfig.DocumentElement.SelectNodes("//Language"))
{
language.Language newLang = language.Language.Import(n);
if (newLang != null)
{
insPack.Data.Languages.Add(newLang.id.ToString(CultureInfo.InvariantCulture));
//saveNeeded = true;
}
}
//if (saveNeeded) { insPack.Save(); saveNeeded = false; }
#endregion
#region Dictionary items
foreach (XmlNode n in _packageConfig.DocumentElement.SelectNodes("./DictionaryItems/DictionaryItem"))
{
Dictionary.DictionaryItem newDi = Dictionary.DictionaryItem.Import(n);
if (newDi != null)
{
insPack.Data.DictionaryItems.Add(newDi.id.ToString());
//saveNeeded = true;
}
}
//if (saveNeeded) { insPack.Save(); saveNeeded = false; }
#endregion
#region Macros
foreach (XmlNode n in _packageConfig.DocumentElement.SelectNodes("//macro"))
{
Macro m = Macro.Import(n);
if (m != null)
{
insPack.Data.Macros.Add(m.Id.ToString(CultureInfo.InvariantCulture));
//saveNeeded = true;
}
}
//if (saveNeeded) { insPack.Save(); saveNeeded = false; }
#endregion
#region Templates
var templateElement = rootElement.Descendants("Templates").FirstOrDefault();
if (templateElement != null)
{
var templates = packagingService.ImportTemplates(templateElement, currentUser.Id);
foreach (var template in templates)
{
insPack.Data.Templates.Add(template.Id.ToString(CultureInfo.InvariantCulture));
//saveNeeded = true;
}
}
//if (saveNeeded) { insPack.Save(); saveNeeded = false; }
/*foreach (XmlNode n in _packageConfig.DocumentElement.SelectNodes("Templates/Template"))
{
var t = Template.Import(n, currentUser);
insPack.Data.Templates.Add(t.Id.ToString());
saveNeeded = true;
}
if (saveNeeded) { insPack.Save(); saveNeeded = false; }
//NOTE: SD: I'm pretty sure the only thing the below script does is ensure that the Master template Id is set
// in the database, but this is also duplicating the saving of the design content since the above Template.Import
// already does this. I've left this for now because I'm not sure the reprocussions of removing it but seems there
// is a lot of excess database calls happening here.
foreach (XmlNode n in _packageConfig.DocumentElement.SelectNodes("Templates/Template"))
{
string master = xmlHelper.GetNodeValue(n.SelectSingleNode("Master"));
Template t = Template.GetByAlias(xmlHelper.GetNodeValue(n.SelectSingleNode("Alias")));
if (master.Trim() != "")
{
var masterTemplate = Template.GetByAlias(master);
if (masterTemplate != null)
{
t.MasterTemplate = Template.GetByAlias(master).Id;
//SD: This appears to always just save an empty template because the design isn't set yet
// this fixes an issue now that we have MVC because if there is an empty template and MVC is
// the default, it will create a View not a master page and then the system will try to route via
// MVC which means that the package will not work anymore.
// The code below that imports the templates should suffice because it's actually importing
// template data not just blank data.
//if (UmbracoSettings.UseAspNetMasterPages)
// t.SaveMasterPageFile(t.Design);
}
}
// Master templates can only be generated when their master is known
if (UmbracoSettings.UseAspNetMasterPages)
{
t.ImportDesign(xmlHelper.GetNodeValue(n.SelectSingleNode("Design")));
t.SaveMasterPageFile(t.Design);
}
}*/
#endregion
#region DocumentTypes
//Check whether the root element is a doc type rather then a complete package
var docTypeElement = rootElement.Name.LocalName.Equals("DocumentType") ||
rootElement.Name.LocalName.Equals("DocumentTypes")
? rootElement
: rootElement.Descendants("DocumentTypes").FirstOrDefault();
if (docTypeElement != null)
{
var contentTypes = packagingService.ImportContentTypes(docTypeElement, currentUser.Id);
foreach (var contentType in contentTypes)
{
insPack.Data.Documenttypes.Add(contentType.Id.ToString(CultureInfo.InvariantCulture));
//saveNeeded = true;
}
}
//if (saveNeeded) { insPack.Save(); saveNeeded = false; }
/*foreach (XmlNode n in _packageConfig.DocumentElement.SelectNodes("DocumentTypes/DocumentType"))
{
ImportDocumentType(n, currentUser, false);
saveNeeded = true;
}
if (saveNeeded) { insPack.Save(); saveNeeded = false; }
// Add documenttype structure
foreach (XmlNode n in _packageConfig.DocumentElement.SelectNodes("DocumentTypes/DocumentType"))
{
DocumentType dt = DocumentType.GetByAlias(xmlHelper.GetNodeValue(n.SelectSingleNode("Info/Alias")));
if (dt != null)
{
ArrayList allowed = new ArrayList();
foreach (XmlNode structure in n.SelectNodes("Structure/DocumentType"))
{
DocumentType dtt = DocumentType.GetByAlias(xmlHelper.GetNodeValue(structure));
if (dtt != null)
allowed.Add(dtt.Id);
}
int[] adt = new int[allowed.Count];
for (int i = 0; i < allowed.Count; i++)
adt[i] = (int)allowed[i];
dt.AllowedChildContentTypeIDs = adt;
dt.Save();
//PPH we log the document type install here.
insPack.Data.Documenttypes.Add(dt.Id.ToString());
saveNeeded = true;
}
}
if (saveNeeded) { insPack.Save(); saveNeeded = false; }*/
#endregion
#region Stylesheets
foreach (XmlNode n in _packageConfig.DocumentElement.SelectNodes("Stylesheets/Stylesheet"))
{
StyleSheet s = StyleSheet.Import(n, currentUser);
insPack.Data.Stylesheets.Add(s.Id.ToString());
//saveNeeded = true;
}
//if (saveNeeded) { insPack.Save(); saveNeeded = false; }
#endregion
#region Documents
var documentElement = rootElement.Descendants("DocumentSet").FirstOrDefault();
if (documentElement != null)
{
var content = packagingService.ImportContent(documentElement, -1, currentUser.Id);
var firstContentItem = content.First();
insPack.Data.ContentNodeId = firstContentItem.Id.ToString(CultureInfo.InvariantCulture);
}
/*foreach (XmlElement n in _packageConfig.DocumentElement.SelectNodes("Documents/DocumentSet [@importMode = 'root']/*"))
{
insPack.Data.ContentNodeId = cms.businesslogic.web.Document.Import(-1, currentUser, n).ToString();
}*/
#endregion
#region Package Actions
foreach (XmlNode n in _packageConfig.DocumentElement.SelectNodes("Actions/Action"))
{
if (n.Attributes["undo"] == null || n.Attributes["undo"].Value == "true")
{
insPack.Data.Actions += n.OuterXml;
}
if (n.Attributes["runat"] != null && n.Attributes["runat"].Value == "install")
{
try
{
PackageAction.RunPackageAction(insPack.Data.Name, n.Attributes["alias"].Value, n);
}
catch
{
}
}
}
#endregion
// Trigger update of Apps / Trees config.
// (These are ApplicationStartupHandlers so just instantiating them will trigger them)
new ApplicationRegistrar();
new ApplicationTreeRegistrar();
insPack.Save();
}
}
/// <summary>
/// Remove the temp installation folder
/// </summary>
/// <param name="packageId"></param>
/// <param name="tempDir"></param>
public void InstallCleanUp(int packageId, string tempDir)
{
if (Directory.Exists(tempDir))
{
Directory.Delete(tempDir, true);
}
}
/// <summary>
/// Invoking this method installs the entire current package
/// </summary>
/// <param name="tempDir">Temporary folder where the package's content are extracted to</param>
/// <param name="guid"></param>
/// <param name="repoGuid"></param>
public void Install(string tempDir, string guid, string repoGuid)
{
//PPH added logging of installs, this adds all install info in the installedPackages config file.
string packName = xmlHelper.GetNodeValue(_packageConfig.DocumentElement.SelectSingleNode("/umbPackage/info/package/name"));
string packAuthor = xmlHelper.GetNodeValue(_packageConfig.DocumentElement.SelectSingleNode("/umbPackage/info/author/name"));
string packAuthorUrl = xmlHelper.GetNodeValue(_packageConfig.DocumentElement.SelectSingleNode("/umbPackage/info/author/website"));
string packVersion = xmlHelper.GetNodeValue(_packageConfig.DocumentElement.SelectSingleNode("/umbPackage/info/package/version"));
string packReadme = xmlHelper.GetNodeValue(_packageConfig.DocumentElement.SelectSingleNode("/umbPackage/info/readme"));
string packLicense = xmlHelper.GetNodeValue(_packageConfig.DocumentElement.SelectSingleNode("/umbPackage/info/package/license "));
//Create a new package instance to record all the installed package adds - this is the same format as the created packages has.
//save the package meta data
var insPack = InstalledPackage.MakeNew(packName);
insPack.Data.Author = packAuthor;
insPack.Data.AuthorUrl = packAuthorUrl;
insPack.Data.Version = packVersion;
insPack.Data.Readme = packReadme;
insPack.Data.License = packLicense;
insPack.Data.PackageGuid = guid; //the package unique key.
insPack.Data.RepositoryGuid = repoGuid; //the repository unique key, if the package is a file install, the repository will not get logged.
// Get current user, with a fallback
var currentUser = new User(0);
if (string.IsNullOrEmpty(BasePages.UmbracoEnsuredPage.umbracoUserContextID) == false)
{
if (BasePages.UmbracoEnsuredPage.ValidateUserContextID(BasePages.UmbracoEnsuredPage.umbracoUserContextID))
{
currentUser = User.GetCurrent();
}
}
//Xml as XElement which is used with the new PackagingService
var rootElement = _packageConfig.DocumentElement.GetXElement();
var packagingService = ApplicationContext.Current.Services.PackagingService;
#region DataTypes
var dataTypeElement = rootElement.Descendants("DataTypes").FirstOrDefault();
if(dataTypeElement != null)
{
var dataTypeDefinitions = packagingService.ImportDataTypeDefinitions(dataTypeElement, currentUser.Id);
foreach (var dataTypeDefinition in dataTypeDefinitions)
{
insPack.Data.DataTypes.Add(dataTypeDefinition.Id.ToString(CultureInfo.InvariantCulture));
}
}
#endregion
#region Install Languages
foreach (XmlNode n in _packageConfig.DocumentElement.SelectNodes("//Language"))
{
language.Language newLang = language.Language.Import(n);
if (newLang != null)
insPack.Data.Languages.Add(newLang.id.ToString());
}
#endregion
#region Install Dictionary Items
foreach (XmlNode n in _packageConfig.DocumentElement.SelectNodes("./DictionaryItems/DictionaryItem"))
{
Dictionary.DictionaryItem newDi = Dictionary.DictionaryItem.Import(n);
if (newDi != null)
insPack.Data.DictionaryItems.Add(newDi.id.ToString());
}
#endregion
#region Install Macros
foreach (XmlNode n in _packageConfig.DocumentElement.SelectNodes("//macro"))
{
Macro m = Macro.Import(n);
if (m != null)
insPack.Data.Macros.Add(m.Id.ToString());
}
#endregion
#region Move files
string basePath = System.Web.Hosting.HostingEnvironment.ApplicationPhysicalPath;
foreach (XmlNode n in _packageConfig.DocumentElement.SelectNodes("//file"))
{
String destPath = GetFileName(basePath, xmlHelper.GetNodeValue(n.SelectSingleNode("orgPath")));
String sourceFile = GetFileName(tempDir, xmlHelper.GetNodeValue(n.SelectSingleNode("guid")));
String destFile = GetFileName(destPath, xmlHelper.GetNodeValue(n.SelectSingleNode("orgName")));
// Create the destination directory if it doesn't exist
if (!Directory.Exists(destPath))
Directory.CreateDirectory(destPath);
// If a file with this name exists, delete it
else if (File.Exists(destFile))
File.Delete(destFile);
// Move the file
File.Move(sourceFile, destFile);
//PPH log file install
insPack.Data.Files.Add(xmlHelper.GetNodeValue(n.SelectSingleNode("orgPath")) + "/" + xmlHelper.GetNodeValue(n.SelectSingleNode("orgName")));
}
#endregion
#region Install Templates
var templateElement = rootElement.Descendants("Templates").FirstOrDefault();
if (templateElement != null)
{
var templates = packagingService.ImportTemplates(templateElement, currentUser.Id);
foreach (var template in templates)
{
insPack.Data.Templates.Add(template.Id.ToString(CultureInfo.InvariantCulture));
}
}
/*foreach (XmlNode n in _packageConfig.DocumentElement.SelectNodes("Templates/Template"))
{
Template t = Template.MakeNew(xmlHelper.GetNodeValue(n.SelectSingleNode("Name")), currentUser);
t.Alias = xmlHelper.GetNodeValue(n.SelectSingleNode("Alias"));
t.ImportDesign(xmlHelper.GetNodeValue(n.SelectSingleNode("Design")));
insPack.Data.Templates.Add(t.Id.ToString());
}
// Add master templates
foreach (XmlNode n in _packageConfig.DocumentElement.SelectNodes("Templates/Template"))
{
string master = xmlHelper.GetNodeValue(n.SelectSingleNode("Master"));
Template t = Template.GetByAlias(xmlHelper.GetNodeValue(n.SelectSingleNode("Alias")));
if (master.Trim() != "")
{
Template masterTemplate = Template.GetByAlias(master);
if (masterTemplate != null)
{
t.MasterTemplate = Template.GetByAlias(master).Id;
if (UmbracoSettings.UseAspNetMasterPages)
t.SaveMasterPageFile(t.Design);
}
}
// Master templates can only be generated when their master is known
if (UmbracoSettings.UseAspNetMasterPages)
{
t.ImportDesign(xmlHelper.GetNodeValue(n.SelectSingleNode("Design")));
t.SaveMasterPageFile(t.Design);
}
}*/
#endregion
#region Install DocumentTypes
//Check whether the root element is a doc type rather then a complete package
var docTypeElement = rootElement.Name.LocalName.Equals("DocumentType") ||
rootElement.Name.LocalName.Equals("DocumentTypes")
? rootElement
: rootElement.Descendants("DocumentTypes").FirstOrDefault();
if (docTypeElement != null)
{
var contentTypes = packagingService.ImportContentTypes(docTypeElement, currentUser.Id);
foreach (var contentType in contentTypes)
{
insPack.Data.Documenttypes.Add(contentType.Id.ToString(CultureInfo.InvariantCulture));
}
}
/*foreach (XmlNode n in _packageConfig.DocumentElement.SelectNodes("DocumentTypes/DocumentType"))
{
ImportDocumentType(n, currentUser, false);
}
// Add documenttype structure
foreach (XmlNode n in _packageConfig.DocumentElement.SelectNodes("DocumentTypes/DocumentType"))
{
DocumentType dt = DocumentType.GetByAlias(xmlHelper.GetNodeValue(n.SelectSingleNode("Info/Alias")));
if (dt != null)
{
ArrayList allowed = new ArrayList();
foreach (XmlNode structure in n.SelectNodes("Structure/DocumentType"))
{
DocumentType dtt = DocumentType.GetByAlias(xmlHelper.GetNodeValue(structure));
allowed.Add(dtt.Id);
}
int[] adt = new int[allowed.Count];
for (int i = 0; i < allowed.Count; i++)
adt[i] = (int)allowed[i];
dt.AllowedChildContentTypeIDs = adt;
//PPH we log the document type install here.
insPack.Data.Documenttypes.Add(dt.Id.ToString());
}
}*/
#endregion
#region Install Stylesheets
foreach (XmlNode n in _packageConfig.DocumentElement.SelectNodes("Stylesheets/Stylesheet"))
{
StyleSheet s = StyleSheet.MakeNew(
currentUser,
xmlHelper.GetNodeValue(n.SelectSingleNode("Name")),
xmlHelper.GetNodeValue(n.SelectSingleNode("FileName")),
xmlHelper.GetNodeValue(n.SelectSingleNode("Content")));
foreach (XmlNode prop in n.SelectNodes("Properties/Property"))
{
StylesheetProperty sp = StylesheetProperty.MakeNew(
xmlHelper.GetNodeValue(prop.SelectSingleNode("Name")),
s,
currentUser);
sp.Alias = xmlHelper.GetNodeValue(prop.SelectSingleNode("Alias"));
sp.value = xmlHelper.GetNodeValue(prop.SelectSingleNode("Value"));
}
s.saveCssToFile();
s.Save();
insPack.Data.Stylesheets.Add(s.Id.ToString());
}
#endregion
#region Install Documents
var documentElement = rootElement.Descendants("DocumentSet").FirstOrDefault();
if(documentElement != null)
{
var content = packagingService.ImportContent(documentElement, -1, currentUser.Id);
var firstContentItem = content.First();
insPack.Data.ContentNodeId = firstContentItem.Id.ToString(CultureInfo.InvariantCulture);
}
/*foreach (XmlElement n in _packageConfig.DocumentElement.SelectNodes("Documents/DocumentSet [@importMode = 'root']/*"))
{
Document.Import(-1, currentUser, n);
//PPH todo log document install...
}*/
#endregion
#region Install Actions
foreach (XmlNode n in _packageConfig.DocumentElement.SelectNodes("Actions/Action [@runat != 'uninstall']"))
{
try
{
PackageAction.RunPackageAction(packName, n.Attributes["alias"].Value, n);
}
catch { }
}
//saving the uninstall actions untill the package is uninstalled.
foreach (XmlNode n in _packageConfig.DocumentElement.SelectNodes("Actions/Action [@undo != false()]"))
{
insPack.Data.Actions += n.OuterXml;
}
#endregion
insPack.Save();
}
/// <summary>
/// Reads the configuration of the package from the configuration xmldocument
/// </summary>
/// <param name="tempDir">The folder to which the contents of the package is extracted</param>
public void LoadConfig(string tempDir)
{
_packageConfig = new XmlDocument();
_packageConfig.Load(tempDir + Path.DirectorySeparatorChar + "package.xml");
_name = _packageConfig.DocumentElement.SelectSingleNode("/umbPackage/info/package/name").FirstChild.Value;
_version = _packageConfig.DocumentElement.SelectSingleNode("/umbPackage/info/package/version").FirstChild.Value;
_url = _packageConfig.DocumentElement.SelectSingleNode("/umbPackage/info/package/url").FirstChild.Value;
_license = _packageConfig.DocumentElement.SelectSingleNode("/umbPackage/info/package/license").FirstChild.Value;
_licenseUrl = _packageConfig.DocumentElement.SelectSingleNode("/umbPackage/info/package/license").Attributes.GetNamedItem("url").Value;
_reqMajor = int.Parse(_packageConfig.DocumentElement.SelectSingleNode("/umbPackage/info/package/requirements/major").FirstChild.Value);
_reqMinor = int.Parse(_packageConfig.DocumentElement.SelectSingleNode("/umbPackage/info/package/requirements/minor").FirstChild.Value);
_reqPatch = int.Parse(_packageConfig.DocumentElement.SelectSingleNode("/umbPackage/info/package/requirements/patch").FirstChild.Value);
_authorName = _packageConfig.DocumentElement.SelectSingleNode("/umbPackage/info/author/name").FirstChild.Value;
_authorUrl = _packageConfig.DocumentElement.SelectSingleNode("/umbPackage/info/author/website").FirstChild.Value;
string basePath = System.Web.Hosting.HostingEnvironment.ApplicationPhysicalPath;
foreach (XmlNode n in _packageConfig.DocumentElement.SelectNodes("//file"))
{
bool badFile = false;
string destPath = GetFileName(basePath, xmlHelper.GetNodeValue(n.SelectSingleNode("orgPath")));
string destFile = GetFileName(destPath, xmlHelper.GetNodeValue(n.SelectSingleNode("orgName")));
if (destPath.ToLower().Contains(IOHelper.DirSepChar + "app_code"))
badFile = true;
if (destPath.ToLower().Contains(IOHelper.DirSepChar + "bin"))
badFile = true;
if (destFile.ToLower().EndsWith(".dll"))
badFile = true;
if (badFile)
{
_containUnsecureFiles = true;
_unsecureFiles.Add(xmlHelper.GetNodeValue(n.SelectSingleNode("orgName")));
}
}
//this will check for existing macros with the same alias
//since we will not overwrite on import it's a good idea to inform the user what will be overwritten
foreach (XmlNode n in _packageConfig.DocumentElement.SelectNodes("//macro"))
{
var alias = n.SelectSingleNode("alias").InnerText;
if (!string.IsNullOrEmpty(alias))
{
try
{
var m = new Macro(alias);
this._containsMacroConflict = true;
this._conflictingMacroAliases.Add(m.Name, alias);
}
catch (IndexOutOfRangeException) { } //thrown when the alias doesn't exist in the DB, ie - macro not there
}
}
foreach (XmlNode n in _packageConfig.DocumentElement.SelectNodes("Templates/Template"))
{
var alias = n.SelectSingleNode("Alias").InnerText;
if (!string.IsNullOrEmpty(alias))
{
var t = Template.GetByAlias(alias);
if (t != null)
{
this._containsTemplateConflict = true;
this._conflictingTemplateAliases.Add(t.Text, alias);
}
}
}
foreach (XmlNode n in _packageConfig.DocumentElement.SelectNodes("Stylesheets/Stylesheet"))
{
var alias = n.SelectSingleNode("Name").InnerText;
if (!string.IsNullOrEmpty(alias))
{
var s = StyleSheet.GetByName(alias);
if (s != null)
{
this._containsStyleSheetConflict = true;
this._conflictingStyleSheetNames.Add(s.Text, alias);
}
}
}
try
{
_readme = xmlHelper.GetNodeValue(_packageConfig.DocumentElement.SelectSingleNode("/umbPackage/info/readme"));
}
catch { }
try
{
_control = xmlHelper.GetNodeValue(_packageConfig.DocumentElement.SelectSingleNode("/umbPackage/control"));
}
catch { }
}
/// <summary>
/// This uses the old method of fetching and only supports the packages.umbraco.org repository.
/// </summary>
/// <param name="Package"></param>
/// <returns></returns>
public string Fetch(Guid Package)
{
// Check for package directory
if (!Directory.Exists(IOHelper.MapPath(SystemDirectories.Packages)))
Directory.CreateDirectory(IOHelper.MapPath(SystemDirectories.Packages));
var wc = new System.Net.WebClient();
wc.DownloadFile(
"http://" + UmbracoSettings.PackageServer + "/fetch?package=" + Package.ToString(),
IOHelper.MapPath(SystemDirectories.Packages + "/" + Package.ToString() + ".umb"));
return "packages\\" + Package.ToString() + ".umb";
}
#endregion
#region Public Static Methods
[Obsolete("This method is empty, so calling it will have no effect whatsoever.")]
public static void updatePackageInfo(Guid Package, int VersionMajor, int VersionMinor, int VersionPatch, User User)
{
//Why does this even exist?
}
[Obsolete("Use ApplicationContext.Current.Services.PackagingService.ImportContentTypes instead")]
public static void ImportDocumentType(XmlNode n, User u, bool ImportStructure)
{
var element = n.GetXElement();
var contentTypes = ApplicationContext.Current.Services.PackagingService.ImportContentTypes(element, ImportStructure, u.Id);
}
#endregion
#region Private Methods
/// <summary>
/// Gets the name of the file in the specified path.
/// Corrects possible problems with slashes that would result from a simple concatenation.
/// Can also be used to concatenate paths.
/// </summary>
/// <param name="path">The path.</param>
/// <param name="fileName">Name of the file.</param>
/// <returns>The name of the file in the specified path.</returns>
private static String GetFileName(String path, string fileName)
{
// virtual dir support
fileName = IOHelper.FindFile(fileName);
if (path.Contains("[$"))
{
//this is experimental and undocumented...
path = path.Replace("[$UMBRACO]", IO.SystemDirectories.Umbraco);
path = path.Replace("[$UMBRACOCLIENT]", IO.SystemDirectories.Umbraco_client);
path = path.Replace("[$CONFIG]", IO.SystemDirectories.Config);
path = path.Replace("[$DATA]", IO.SystemDirectories.Data);
}
//to support virtual dirs we try to lookup the file...
path = IOHelper.FindFile(path);
Debug.Assert(path != null && path.Length >= 1);
Debug.Assert(fileName != null && fileName.Length >= 1);
path = path.Replace('/', '\\');
fileName = fileName.Replace('/', '\\');
// Does filename start with a slash? Does path end with one?
bool fileNameStartsWithSlash = (fileName[0] == Path.DirectorySeparatorChar);
bool pathEndsWithSlash = (path[path.Length - 1] == Path.DirectorySeparatorChar);
// Path ends with a slash
if (pathEndsWithSlash)
{
if (!fileNameStartsWithSlash)
// No double slash, just concatenate
return path + fileName;
else
// Double slash, exclude that of the file
return path + fileName.Substring(1);
}
else
{
if (fileNameStartsWithSlash)
// Required slash specified, just concatenate
return path + fileName;
else
// Required slash missing, add it
return path + Path.DirectorySeparatorChar + fileName;
}
}
private static int FindDataTypeDefinitionFromType(ref Guid dtId)
{
int dfId = 0;
foreach (datatype.DataTypeDefinition df in datatype.DataTypeDefinition.GetAll())
if (df.DataType.Id == dtId)
{
dfId = df.Id;
break;
}
return dfId;
}
private static string UnPack(string zipName)
{
// Unzip
string tempDir = IOHelper.MapPath(SystemDirectories.Data) + Path.DirectorySeparatorChar + Guid.NewGuid().ToString();
Directory.CreateDirectory(tempDir);
var s = new ZipInputStream(File.OpenRead(zipName));
ZipEntry theEntry;
while ((theEntry = s.GetNextEntry()) != null)
{
string fileName = Path.GetFileName(theEntry.Name);
if (fileName != String.Empty)
{
FileStream streamWriter = File.Create(tempDir + Path.DirectorySeparatorChar + fileName);
int size = 2048;
byte[] data = new byte[2048];
while (true)
{
size = s.Read(data, 0, data.Length);
if (size > 0)
{
streamWriter.Write(data, 0, size);
}
else
{
break;
}
}
streamWriter.Close();
}
}
// Clean up
s.Close();
File.Delete(zipName);
return tempDir;
}
#endregion
}
public class Package
{
protected static ISqlHelper SqlHelper
{
get { return Application.SqlHelper; }
}
public Package()
{
}
/// <summary>
/// Initialize package install status object by specifying the internal id of the installation.
/// The id is specific to the local umbraco installation and cannot be used to identify the package in general.
/// Use the Package(Guid) constructor to check whether a package has been installed
/// </summary>
/// <param name="Id">The internal id.</param>
public Package(int Id)
{
initialize(Id);
}
public Package(Guid Id)
{
int installStatusId = SqlHelper.ExecuteScalar<int>(
"select id from umbracoInstalledPackages where package = @package and upgradeId = 0",
SqlHelper.CreateParameter("@package", Id));
if (installStatusId > 0)
initialize(installStatusId);
else
throw new ArgumentException("Package with id '" + Id.ToString() + "' is not installed");
}
private void initialize(int id)
{
IRecordsReader dr =
SqlHelper.ExecuteReader(
"select id, uninstalled, upgradeId, installDate, userId, package, versionMajor, versionMinor, versionPatch from umbracoInstalledPackages where id = @id",
SqlHelper.CreateParameter("@id", id));
if (dr.Read())
{
Id = id;
Uninstalled = dr.GetBoolean("uninstalled");
UpgradeId = dr.GetInt("upgradeId");
InstallDate = dr.GetDateTime("installDate");
User = User.GetUser(dr.GetInt("userId"));
PackageId = dr.GetGuid("package");
VersionMajor = dr.GetInt("versionMajor");
VersionMinor = dr.GetInt("versionMinor");
VersionPatch = dr.GetInt("versionPatch");
}
dr.Close();
}
[MethodImpl(MethodImplOptions.Synchronized)]
public void Save()
{
IParameter[] values = {
SqlHelper.CreateParameter("@uninstalled", Uninstalled),
SqlHelper.CreateParameter("@upgradeId", UpgradeId),
SqlHelper.CreateParameter("@installDate", InstallDate),
SqlHelper.CreateParameter("@userId", User.Id),
SqlHelper.CreateParameter("@versionMajor", VersionMajor),
SqlHelper.CreateParameter("@versionMinor", VersionMinor),
SqlHelper.CreateParameter("@versionPatch", VersionPatch),
SqlHelper.CreateParameter("@id", Id)
};
// check if package status exists
if (Id == 0)
{
// The method is synchronized
SqlHelper.ExecuteNonQuery("INSERT INTO umbracoInstalledPackages (uninstalled, upgradeId, installDate, userId, versionMajor, versionMinor, versionPatch) VALUES (@uninstalled, @upgradeId, @installDate, @userId, @versionMajor, @versionMinor, @versionPatch)", values);
Id = SqlHelper.ExecuteScalar<int>("SELECT MAX(id) FROM umbracoInstalledPackages");
}
SqlHelper.ExecuteNonQuery(
"update umbracoInstalledPackages set " +
"uninstalled = @uninstalled, " +
"upgradeId = @upgradeId, " +
"installDate = @installDate, " +
"userId = @userId, " +
"versionMajor = @versionMajor, " +
"versionMinor = @versionMinor, " +
"versionPatch = @versionPatch " +
"where id = @id",
values);
}
private bool _uninstalled;
public bool Uninstalled
{
get { return _uninstalled; }
set { _uninstalled = value; }
}
private User _user;
public User User
{
get { return _user; }
set { _user = value; }
}
private DateTime _installDate;
public DateTime InstallDate
{
get { return _installDate; }
set { _installDate = value; }
}
private int _id;
public int Id
{
get { return _id; }
set { _id = value; }
}
private int _upgradeId;
public int UpgradeId
{
get { return _upgradeId; }
set { _upgradeId = value; }
}
private Guid _packageId;
public Guid PackageId
{
get { return _packageId; }
set { _packageId = value; }
}
private int _versionPatch;
public int VersionPatch
{
get { return _versionPatch; }
set { _versionPatch = value; }
}
private int _versionMinor;
public int VersionMinor
{
get { return _versionMinor; }
set { _versionMinor = value; }
}
private int _versionMajor;
public int VersionMajor
{
get { return _versionMajor; }
set { _versionMajor = value; }
}
}
}
| |
// 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.Linq;
using System.Xml.Linq;
using CoreXml.Test.XLinq;
using Microsoft.Test.ModuleCore;
namespace XLinqTests
{
//[TestCase(Name = "Constructors with params - XElement - array", Param = InputParamStyle.Array)]
//[TestCase(Name = "Constructors with params - XElement - node + array", Param = InputParamStyle.SingleAndArray)]
//[TestCase(Name = "Constructors with params - XElement - IEnumerable", Param = InputParamStyle.IEnumerable)]
public class ParamsObjectsCreationElem : XLinqTestCase
{
// Type is CoreXml.Test.XLinq.FunctionalTests+TreeManipulationTests+ParamsObjectsCreationElem
// Test Case
// XElement
// - from node without parent, from nodes with parent
// - elements
// - attributes
// - PI, Comments
// - self reference
// - nulls inside
// - the same object multiple times
// - Document
// - array/IEnumerable of allowed types
// - array/IEnumerable including not allowed types
// - element state after invalid operations
// - text as plaint text & text as XText node
// - concatenation of the text nodes
// sanity for creation of a complete tree using params constructor
#region Enums
public enum InputParamStyle
{
Array,
SingleAndArray,
IEnumerable
};
#endregion
#region Public Methods and Operators
public override void AddChildren()
{
AddChild(new TestVariation(XElementValidCreate) { Attribute = new VariationAttribute("XElement - multiple nodes, not connected") { Params = new object[] { false, 4 }, Priority = 1 } });
AddChild(new TestVariation(XElementValidCreate) { Attribute = new VariationAttribute("XElement - single node, not connected") { Params = new object[] { false, 1 }, Priority = 0 } });
AddChild(new TestVariation(XElementValidCreate) { Attribute = new VariationAttribute("XElement - single node, connected") { Params = new object[] { true, 1 }, Priority = 0 } });
AddChild(new TestVariation(XElementValidCreate) { Attribute = new VariationAttribute("(BVT)XElement - multiple nodes, connected") { Params = new object[] { true, 2 }, Priority = 0 } });
AddChild(new TestVariation(XElementValidCreate) { Attribute = new VariationAttribute("(BVT)XElement - multiple nodes, not connected") { Params = new object[] { false, 2 }, Priority = 0 } });
AddChild(new TestVariation(XElementValidCreate) { Attribute = new VariationAttribute("XElement - multiple nodes, connected") { Params = new object[] { true, 4 }, Priority = 1 } });
AddChild(new TestVariation(XElementDuppAttr) { Attribute = new VariationAttribute("XElement - Not allowed - duplicate attributes") { Priority = 2 } });
AddChild(new TestVariation(XElementNotAllowedXDoc) { Attribute = new VariationAttribute("XElement - Not allowed - XDocument") { Priority = 2 } });
AddChild(new TestVariation(XElementNotAllowedXDocType) { Attribute = new VariationAttribute("XElement - Not allowed - XDocumentType") { Param = 3, Priority = 2 } });
AddChild(new TestVariation(XElementEmptyArray) { Attribute = new VariationAttribute("XElement - nulls") { Priority = 3 } });
AddChild(new TestVariation(BuildFromQuery) { Attribute = new VariationAttribute("XElement - build from Query result") { Priority = 2 } });
AddChild(new TestVariation(IsEmptyProp1) { Attribute = new VariationAttribute("IsEmpty propert Manipulation I.") { Priority = 0 } });
AddChild(new TestVariation(IsEmptyProp2) { Attribute = new VariationAttribute("IsEmpty propert Manipulation II.") { Priority = 0 } });
}
//[Variation(Priority = 0, Desc = "(BVT)XElement - multiple nodes, connected", Params = new object[] { true, 2 })]
//[Variation(Priority = 0, Desc = "(BVT)XElement - multiple nodes, not connected", Params = new object[] { false, 2 })]
//[Variation(Priority = 1, Desc = "XElement - multiple nodes, connected", Params = new object[] { true, 4 })]
//[Variation(Priority = 1, Desc = "XElement - multiple nodes, not connected", Params = new object[] { false, 4 })]
//[Variation(Priority = 0, Desc = "XElement - single node, connected", Params = new object[] { true, 1 })]
//[Variation(Priority = 0, Desc = "XElement - single node, not connected", Params = new object[] { false, 1 })]
//[Variation(Priority = 2, Desc = "XElement - build from Query result")]
public void BuildFromQuery()
{
var mode = (InputParamStyle)Param;
XElement e1 = XElement.Parse(@"<A><B id='a1'/><B id='a2'/><B id='a4'/></A>");
XElement e2 = XElement.Parse(@"<root><a1 a='a'/><a2/><a3 b='b'/><a4 c='c'/><a5/><a6/><a7/><a8/></root>");
IEnumerable<XElement> nodes = from data1 in e1.Elements() join data2 in e2.Elements() on data1.Attribute("id").Value equals data2.Name.LocalName select data2;
IEnumerable<XAttribute> attributes = from data1 in e1.Elements() join data2 in e2.Elements() on data1.Attribute("id").Value equals data2.Name.LocalName select data2.FirstAttribute;
IEnumerable<ExpectedValue> expectedContent = ExpectedContent(nodes).ProcessNodes().ToList();
IEnumerable<ExpectedValue> expectedAttributes = ExpectedContent(attributes).Where(n => n.Data is XAttribute).ToList();
XElement e = CreateElement(mode, nodes.OfType<object>().Concat(attributes.OfType<object>()));
TestLog.Compare(expectedContent.EqualAll(e.Nodes(), XNode.EqualityComparer), "Content");
TestLog.Compare(expectedAttributes.EqualAllAttributes(e.Attributes(), Helpers.MyAttributeComparer), "Attributes");
}
//[Variation(Priority = 0, Desc = "IsEmpty propert Manipulation I.")]
public void IsEmptyProp1()
{
var e = new XElement("e");
TestLog.Compare(e.IsEmpty, "Initial - empty");
TestLog.Compare(e.Value, "", "value 0");
e.RemoveNodes();
TestLog.Compare(e.IsEmpty, "Initial - after RemoveNodes 1");
TestLog.Compare(e.Value, "", "value 1");
e.Add("");
TestLog.Compare(!e.IsEmpty, "Initial - after Add");
TestLog.Compare(e.Value, "", "value 2");
e.RemoveNodes();
TestLog.Compare(e.IsEmpty, "Initial - after RemoveNodes 2");
TestLog.Compare(e.Value, "", "value 3");
}
//[Variation(Priority = 0, Desc = "IsEmpty propert Manipulation II.")]
public void IsEmptyProp2()
{
var e = new XElement("e", "");
TestLog.Compare(!e.IsEmpty, "Initial - empty");
TestLog.Compare(e.Value, "", "value 0");
e.Add("");
TestLog.Compare(!e.IsEmpty, "Initial - after Add");
TestLog.Compare(e.Value, "", "value 1");
e.RemoveNodes();
TestLog.Compare(e.IsEmpty, "Initial - after RemoveNodes 1");
TestLog.Compare(e.Value, "", "value 2");
e.Add("");
TestLog.Compare(!e.IsEmpty, "Initial - after Add");
TestLog.Compare(e.Value, "", "value 3");
}
public void XElementDuppAttr()
{
var mode = (InputParamStyle)Param;
object[] paras = { new XAttribute("id", "a1"), new XAttribute("other", "ooo"), new XAttribute("id", "a2"), null, "", "text", new XElement("aa"), new XProcessingInstruction("PI", "click"), new XComment("comment") };
try
{
XElement e = CreateElement(mode, paras);
TestLog.Compare(false, "Exception expected");
}
catch (InvalidOperationException)
{
}
}
public void XElementEmptyArray()
{
var mode = (InputParamStyle)Param;
object[] nulls = { new object[] { }, new object[] { null, null }, null, "", new object[] { null, new object[] { null, null }, null }, new object[] { null, new object[] { null, null }, new List<object> { null, null, null } } };
foreach (object paras in nulls)
{
XElement elem = CreateElement(mode, paras);
TestLog.Compare(elem != null, "elem != null");
TestLog.Compare(elem.FirstNode == null, "elem.FirstNode==null");
elem.Verify();
}
}
public void XElementNotAllowedXDoc()
{
var mode = (InputParamStyle)Param;
object[] paras = { new XAttribute("id", "a1"), null, "text", new XDocument(), new XElement("aa"), new XProcessingInstruction("PI", "click"), new XComment("comment") };
try
{
XElement e = CreateElement(mode, paras);
TestLog.Compare(false, "Exception expected");
}
catch (ArgumentException)
{
}
}
//[Variation(Priority = 2, Desc = "XElement - Not allowed - XDocumentType", Param = 3)]
public void XElementNotAllowedXDocType()
{
var mode = (InputParamStyle)Param;
object[] paras = { new XAttribute("id", "a1"), new XDocumentType("doctype", "", "", ""), "text", null, new XElement("aa"), new XProcessingInstruction("PI", "click"), new XComment("comment") };
try
{
XElement e = CreateElement(mode, paras);
TestLog.Compare(false, "Exception expected");
}
catch (ArgumentException)
{
}
}
public void XElementValidCreate()
{
var mode = (InputParamStyle)Param;
var isConnected = (bool)Variation.Params[0];
var CombinationLength = (int)Variation.Params[1];
object[] nodes = { new XElement("A"), new XElement("A", new XAttribute("a1", "a1")), new object[] { new XElement("B"), "", null, new XElement("C"), new XAttribute("xx", "yy") }, new XElement("{NS1}A"), new XAttribute("id", "a1"), new XAttribute("ie", "ie"), new XAttribute("{NS1}id", "b2"), "", new XAttribute(XNamespace.Xmlns + "NS1", "http://ns1"),
new XProcessingInstruction("Pi", "data"), new XProcessingInstruction("P2", ""), null, new XComment("comment"), new XText("text1"), new XCData("textCDATA"), "textPlain1", "textPlain2" };
XElement dummy = null;
if (isConnected)
{
dummy = new XElement("dummy", nodes);
}
foreach (var data in nodes.NonRecursiveVariations(CombinationLength))
{
IEnumerable<ExpectedValue> expectedContent = ExpectedContent(data.Flatten()).ProcessNodes().ToList();
IEnumerable<ExpectedValue> expectedAttributes = ExpectedContent(data.Flatten()).Where(n => n.Data is XAttribute).ToList();
XElement e = CreateElement(mode, data);
TestLog.Compare(expectedContent.EqualAll(e.Nodes(), XNode.EqualityComparer), "Content");
TestLog.Compare(expectedAttributes.EqualAllAttributes(e.Attributes(), Helpers.MyAttributeComparer), "Attributes");
e.Verify();
}
}
#endregion
#region Methods
private XElement CreateElement(InputParamStyle mode, object[] data)
{
XElement e = null;
switch (mode)
{
case InputParamStyle.Array:
e = new XElement("data", data);
break;
case InputParamStyle.SingleAndArray:
if (data.Length < 2)
{
goto case InputParamStyle.Array;
}
var copy = new object[data.Length - 1];
Array.Copy(data, 1, copy, 0, data.Length - 1);
e = new XElement("data", data[0], copy);
break;
case InputParamStyle.IEnumerable:
e = new XElement("data", data);
break;
default:
TestLog.Compare(false, "test failed");
break;
}
return e;
}
private XElement CreateElement(InputParamStyle mode, object data)
{
return new XElement("data", data);
}
private IEnumerable<ExpectedValue> ExpectedContent<T>(IEnumerable<T> data) where T : class
{
return data.Select(n => new ExpectedValue((n is XNode) && (!(n is XText)) && (n as XNode).Parent == null, n));
}
#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.
// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
//
// a set of lightweight static helpers for lazy initialization.
//
// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
using System.Diagnostics;
namespace System.Threading
{
/// <summary>
/// Provides lazy initialization routines.
/// </summary>
/// <remarks>
/// These routines avoid needing to allocate a dedicated, lazy-initialization instance, instead using
/// references to ensure targets have been initialized as they are accessed.
/// </remarks>
public static class LazyInitializer
{
/// <summary>
/// Initializes a target reference type with the type's default constructor if the target has not
/// already been initialized.
/// </summary>
/// <typeparam name="T">The refence type of the reference to be initialized.</typeparam>
/// <param name="target">A reference of type <typeparamref name="T"/> to initialize if it has not
/// already been initialized.</param>
/// <returns>The initialized reference of type <typeparamref name="T"/>.</returns>
/// <exception cref="T:System.MissingMemberException">Type <typeparamref name="T"/> does not have a default
/// constructor.</exception>
/// <exception cref="T:System.MemberAccessException">
/// Permissions to access the constructor of type <typeparamref name="T"/> were missing.
/// </exception>
/// <remarks>
/// <para>
/// This method may only be used on reference types. To ensure initialization of value
/// types, see other overloads of EnsureInitialized.
/// </para>
/// <para>
/// This method may be used concurrently by multiple threads to initialize <paramref name="target"/>.
/// In the event that multiple threads access this method concurrently, multiple instances of <typeparamref name="T"/>
/// may be created, but only one will be stored into <paramref name="target"/>. In such an occurrence, this method will not dispose of the
/// objects that were not stored. If such objects must be disposed, it is up to the caller to determine
/// if an object was not used and to then dispose of the object appropriately.
/// </para>
/// </remarks>
public static T EnsureInitialized<T>(ref T target) where T : class =>
Volatile.Read(ref target) ?? EnsureInitializedCore(ref target);
/// <summary>
/// Initializes a target reference type with the type's default constructor (slow path)
/// </summary>
/// <typeparam name="T">The reference type of the reference to be initialized.</typeparam>
/// <param name="target">The variable that need to be initialized</param>
/// <returns>The initialized variable</returns>
private static T EnsureInitializedCore<T>(ref T target) where T : class
{
try
{
Interlocked.CompareExchange(ref target, Activator.CreateInstance<T>(), null);
}
catch (MissingMethodException)
{
throw new MissingMemberException(SR.Lazy_CreateValue_NoParameterlessCtorForT);
}
Debug.Assert(target != null);
return target;
}
/// <summary>
/// Initializes a target reference type using the specified function if it has not already been
/// initialized.
/// </summary>
/// <typeparam name="T">The reference type of the reference to be initialized.</typeparam>
/// <param name="target">The reference of type <typeparamref name="T"/> to initialize if it has not
/// already been initialized.</param>
/// <param name="valueFactory">The <see cref="T:System.Func{T}"/> invoked to initialize the
/// reference.</param>
/// <returns>The initialized reference of type <typeparamref name="T"/>.</returns>
/// <exception cref="T:System.MissingMemberException">Type <typeparamref name="T"/> does not have a
/// default constructor.</exception>
/// <exception cref="T:System.InvalidOperationException"><paramref name="valueFactory"/> returned
/// null.</exception>
/// <remarks>
/// <para>
/// This method may only be used on reference types, and <paramref name="valueFactory"/> may
/// not return a null reference (Nothing in Visual Basic). To ensure initialization of value types or
/// to allow null reference types, see other overloads of EnsureInitialized.
/// </para>
/// <para>
/// This method may be used concurrently by multiple threads to initialize <paramref name="target"/>.
/// In the event that multiple threads access this method concurrently, multiple instances of <typeparamref name="T"/>
/// may be created, but only one will be stored into <paramref name="target"/>. In such an occurrence, this method will not dispose of the
/// objects that were not stored. If such objects must be disposed, it is up to the caller to determine
/// if an object was not used and to then dispose of the object appropriately.
/// </para>
/// </remarks>
public static T EnsureInitialized<T>(ref T target, Func<T> valueFactory) where T : class =>
Volatile.Read(ref target) ?? EnsureInitializedCore(ref target, valueFactory);
/// <summary>
/// Initialize the target using the given delegate (slow path).
/// </summary>
/// <typeparam name="T">The reference type of the reference to be initialized.</typeparam>
/// <param name="target">The variable that need to be initialized</param>
/// <param name="valueFactory">The delegate that will be executed to initialize the target</param>
/// <returns>The initialized variable</returns>
private static T EnsureInitializedCore<T>(ref T target, Func<T> valueFactory) where T : class
{
T value = valueFactory();
if (value == null)
{
throw new InvalidOperationException(SR.Lazy_StaticInit_InvalidOperation);
}
Interlocked.CompareExchange(ref target, value, null);
Debug.Assert(target != null);
return target;
}
/// <summary>
/// Initializes a target reference or value type with its default constructor if it has not already
/// been initialized.
/// </summary>
/// <typeparam name="T">The type of the reference to be initialized.</typeparam>
/// <param name="target">A reference or value of type <typeparamref name="T"/> to initialize if it
/// has not already been initialized.</param>
/// <param name="initialized">A reference to a boolean that determines whether the target has already
/// been initialized.</param>
/// <param name="syncLock">A reference to an object used as the mutually exclusive lock for initializing
/// <paramref name="target"/>. If <paramref name="syncLock"/> is null, a new object will be instantiated.</param>
/// <returns>The initialized value of type <typeparamref name="T"/>.</returns>
public static T EnsureInitialized<T>(ref T target, ref bool initialized, ref object syncLock)
{
// Fast path.
if (Volatile.Read(ref initialized))
{
return target;
}
return EnsureInitializedCore(ref target, ref initialized, ref syncLock);
}
/// <summary>
/// Ensure the target is initialized and return the value (slow path). This overload permits nulls
/// and also works for value type targets. Uses the type's default constructor to create the value.
/// </summary>
/// <typeparam name="T">The type of target.</typeparam>
/// <param name="target">A reference to the target to be initialized.</param>
/// <param name="initialized">A reference to a location tracking whether the target has been initialized.</param>
/// <param name="syncLock">A reference to a location containing a mutual exclusive lock. If <paramref name="syncLock"/> is null,
/// a new object will be instantiated.</param>
/// </param>
/// <returns>The initialized object.</returns>
private static T EnsureInitializedCore<T>(ref T target, ref bool initialized, ref object syncLock)
{
// Lazily initialize the lock if necessary and then double check if initialization is still required.
lock (EnsureLockInitialized(ref syncLock))
{
if (!Volatile.Read(ref initialized))
{
try
{
target = Activator.CreateInstance<T>();
}
catch (MissingMethodException)
{
throw new MissingMemberException(SR.Lazy_CreateValue_NoParameterlessCtorForT);
}
Volatile.Write(ref initialized, true);
}
}
return target;
}
/// <summary>
/// Initializes a target reference or value type with a specified function if it has not already been
/// initialized.
/// </summary>
/// <typeparam name="T">The type of the reference to be initialized.</typeparam>
/// <param name="target">A reference or value of type <typeparamref name="T"/> to initialize if it
/// has not already been initialized.</param>
/// <param name="initialized">A reference to a boolean that determines whether the target has already
/// been initialized.</param>
/// <param name="syncLock">A reference to an object used as the mutually exclusive lock for initializing
/// <paramref name="target"/>. If <paramref name="syncLock"/> is null, a new object will be instantiated.</param>
/// <param name="valueFactory">The <see cref="T:System.Func{T}"/> invoked to initialize the
/// reference or value.</param>
/// <returns>The initialized value of type <typeparamref name="T"/>.</returns>
public static T EnsureInitialized<T>(ref T target, ref bool initialized, ref object syncLock, Func<T> valueFactory)
{
// Fast path.
if (Volatile.Read(ref initialized))
{
return target;
}
return EnsureInitializedCore(ref target, ref initialized, ref syncLock, valueFactory);
}
/// <summary>
/// Ensure the target is initialized and return the value (slow path). This overload permits nulls
/// and also works for value type targets. Uses the supplied function to create the value.
/// </summary>
/// <typeparam name="T">The type of target.</typeparam>
/// <param name="target">A reference to the target to be initialized.</param>
/// <param name="initialized">A reference to a location tracking whether the target has been initialized.</param>
/// <param name="syncLock">A reference to a location containing a mutual exclusive lock. If <paramref name="syncLock"/> is null,
/// a new object will be instantiated.</param>
/// <param name="valueFactory">
/// The <see cref="T:System.Func{T}"/> to invoke in order to produce the lazily-initialized value.
/// </param>
/// <returns>The initialized object.</returns>
private static T EnsureInitializedCore<T>(ref T target, ref bool initialized, ref object syncLock, Func<T> valueFactory)
{
// Lazily initialize the lock if necessary and then double check if initialization is still required.
lock (EnsureLockInitialized(ref syncLock))
{
if (!Volatile.Read(ref initialized))
{
target = valueFactory();
Volatile.Write(ref initialized, true);
}
}
return target;
}
/// <summary>
/// Initializes a target reference type with a specified function if it has not already been initialized.
/// </summary>
/// <typeparam name="T">The type of the reference to be initialized. Has to be reference type.</typeparam>
/// <param name="target">A reference of type <typeparamref name="T"/> to initialize if it has not already been initialized.</param>
/// <param name="syncLock">A reference to an object used as the mutually exclusive lock for initializing
/// <paramref name="target"/>. If <paramref name="syncLock"/> is null, a new object will be instantiated.</param>
/// <param name="valueFactory">The <see cref="T:System.Func{T}"/> invoked to initialize the reference.</param>
/// <returns>The initialized value of type <typeparamref name="T"/>.</returns>
public static T EnsureInitialized<T>(ref T target, ref object syncLock, Func<T> valueFactory) where T : class =>
Volatile.Read(ref target) ?? EnsureInitializedCore(ref target, ref syncLock, valueFactory);
/// <summary>
/// Ensure the target is initialized and return the value (slow path). This overload works only for reference type targets.
/// Uses the supplied function to create the value.
/// </summary>
/// <typeparam name="T">The type of target. Has to be reference type.</typeparam>
/// <param name="target">A reference to the target to be initialized.</param>
/// <param name="syncLock">A reference to a location containing a mutual exclusive lock. If <paramref name="syncLock"/> is null,
/// a new object will be instantiated.</param>
/// <param name="valueFactory">
/// The <see cref="T:System.Func{T}"/> to invoke in order to produce the lazily-initialized value.
/// </param>
/// <returns>The initialized object.</returns>
private static T EnsureInitializedCore<T>(ref T target, ref object syncLock, Func<T> valueFactory) where T : class
{
// Lazily initialize the lock if necessary and then double check if initialization is still required.
lock (EnsureLockInitialized(ref syncLock))
{
if (Volatile.Read(ref target) == null)
{
Volatile.Write(ref target, valueFactory());
if (target == null)
{
throw new InvalidOperationException(SR.Lazy_StaticInit_InvalidOperation);
}
}
}
return target;
}
/// <summary>
/// Ensure the lock object is initialized.
/// </summary>
/// <param name="syncLock">A reference to a location containing a mutual exclusive lock. If <paramref name="syncLock"/> is null,
/// a new object will be instantiated.</param>
/// <returns>Initialized lock object.</returns>
private static object EnsureLockInitialized(ref object syncLock) =>
syncLock ??
Interlocked.CompareExchange(ref syncLock, new object(), null) ??
syncLock;
}
}
| |
// 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.Drawing;
using System.Globalization;
using System.Linq;
using Xunit;
namespace System.ComponentModel.TypeConverterTests
{
public class SizeConverterTests : StringTypeConverterTestBase<Size>
{
protected override TypeConverter Converter { get; } = new SizeConverter();
protected override bool StandardValuesSupported { get; } = false;
protected override bool StandardValuesExclusive { get; } = false;
protected override Size Default => new Size(1, 1);
protected override bool CreateInstanceSupported { get; } = true;
protected override bool IsGetPropertiesSupported { get; } = true;
protected override IEnumerable<Tuple<Size, Dictionary<string, object>>> CreateInstancePairs
{
get
{
yield return Tuple.Create(new Size(10, 20), new Dictionary<string, object>
{
["Width"] = 10,
["Height"] = 20,
});
yield return Tuple.Create(new Size(-2, 3), new Dictionary<string, object>
{
["Width"] = -2,
["Height"] = 3,
});
}
}
[Theory]
[InlineData(typeof(string))]
public void CanConvertFromTrue(Type type)
{
CanConvertFrom(type);
}
[Theory]
[InlineData(typeof(Rectangle))]
[InlineData(typeof(RectangleF))]
[InlineData(typeof(Point))]
[InlineData(typeof(PointF))]
[InlineData(typeof(Color))]
[InlineData(typeof(Size))]
[InlineData(typeof(SizeF))]
[InlineData(typeof(object))]
[InlineData(typeof(int))]
public void CanConvertFromFalse(Type type)
{
CannotConvertFrom(type);
}
[Theory]
[InlineData(typeof(string))]
public void CanConvertToTrue(Type type)
{
CanConvertTo(type);
}
[Theory]
[InlineData(typeof(Rectangle))]
[InlineData(typeof(RectangleF))]
[InlineData(typeof(Point))]
[InlineData(typeof(PointF))]
[InlineData(typeof(Color))]
[InlineData(typeof(Size))]
[InlineData(typeof(SizeF))]
[InlineData(typeof(object))]
[InlineData(typeof(int))]
public void CanConvertToFalse(Type type)
{
CannotConvertTo(type);
}
public static IEnumerable<object[]> SizeData =>
new[]
{
new object[] {0, 0},
new object[] {1, 1},
new object[] {-1, 1},
new object[] {1, -1},
new object[] {-1, -1},
new object[] {int.MaxValue, int.MaxValue},
new object[] {int.MinValue, int.MaxValue},
new object[] {int.MaxValue, int.MinValue},
new object[] {int.MinValue, int.MinValue},
};
[Theory]
[MemberData(nameof(SizeData))]
public void ConvertFrom(int width, int height)
{
TestConvertFromString(new Size(width, height), $"{width}, {height}");
}
[Theory]
[InlineData("1")]
[InlineData("1, 1, 1")]
public void ConvertFrom_ArgumentException(string value)
{
ConvertFromThrowsArgumentExceptionForString(value);
}
[Fact]
public void ConvertFrom_Invalid()
{
ConvertFromThrowsFormatInnerExceptionForString("*1, 1");
}
public static IEnumerable<object[]> ConvertFrom_NotSupportedData =>
new[]
{
new object[] {new Point(1, 1)},
new object[] {new PointF(1, 1)},
new object[] {new Size(1, 1)},
new object[] {new SizeF(1, 1)},
new object[] {0x10},
};
[Theory]
[MemberData(nameof(ConvertFrom_NotSupportedData))]
public void ConvertFrom_NotSupported(object value)
{
ConvertFromThrowsNotSupportedFor(value);
}
[Theory]
[MemberData(nameof(SizeData))]
public void ConvertTo(int width, int height)
{
TestConvertToString(new Size(width, height), $"{width}, {height}");
}
[Theory]
[InlineData(typeof(Size))]
[InlineData(typeof(SizeF))]
[InlineData(typeof(Point))]
[InlineData(typeof(PointF))]
[InlineData(typeof(int))]
public void ConvertTo_NotSupportedException(Type type)
{
ConvertToThrowsNotSupportedForType(type);
}
[Fact]
public void ConvertTo_NullCulture()
{
Assert.Equal("1, 1", Converter.ConvertTo(null, null, new Size(1, 1), typeof(string)));
}
[Fact]
public void CreateInstance_CaseSensitive()
{
Assert.Throws<ArgumentException>(() =>
{
Converter.CreateInstance(null, new Dictionary<string, object>
{
["width"] = 1,
["Height"] = 1,
});
});
}
[Fact]
public void GetProperties()
{
var pt = new Size(1, 1);
var props = Converter.GetProperties(new Size(1, 1));
Assert.Equal(3, props.Count);
Assert.Equal(1, props["Width"].GetValue(pt));
Assert.Equal(1, props["Height"].GetValue(pt));
Assert.Equal(false, props["IsEmpty"].GetValue(pt));
props = Converter.GetProperties(null, new Size(1, 1));
Assert.Equal(3, props.Count);
Assert.Equal(1, props["Width"].GetValue(pt));
Assert.Equal(1, props["Height"].GetValue(pt));
Assert.Equal(false, props["IsEmpty"].GetValue(pt));
props = Converter.GetProperties(null, new Size(1, 1), null);
Assert.Equal(3, props.Count);
Assert.Equal(1, props["Width"].GetValue(pt));
Assert.Equal(1, props["Height"].GetValue(pt));
Assert.Equal(false, props["IsEmpty"].GetValue(pt));
props = Converter.GetProperties(null, new Size(1, 1),
typeof(Size).GetCustomAttributes(true).OfType<Attribute>().ToArray());
Assert.Equal(3, props.Count);
Assert.Equal(1, props["Width"].GetValue(pt));
Assert.Equal(1, props["Height"].GetValue(pt));
Assert.Equal(false, props["IsEmpty"].GetValue(pt));
}
[Theory]
[MemberData(nameof(SizeData))]
public void ConvertFromInvariantString(int width, int height)
{
var point = (Size)Converter.ConvertFromInvariantString($"{width}, {height}");
Assert.Equal(width, point.Width);
Assert.Equal(height, point.Height);
}
[Fact]
public void ConvertFromInvariantString_ArgumentException()
{
ConvertFromInvariantStringThrowsArgumentException("1");
}
[Fact]
public void ConvertFromInvariantString_FormatException()
{
ConvertFromInvariantStringThrowsFormatInnerException("hello");
}
[Theory]
[MemberData(nameof(SizeData))]
public void ConvertFromString(int width, int height)
{
var point =
(Size)Converter.ConvertFromString(string.Format("{0}{2} {1}", width, height,
CultureInfo.CurrentCulture.TextInfo.ListSeparator));
Assert.Equal(width, point.Width);
Assert.Equal(height, point.Height);
}
[Fact]
public void ConvertFromString_ArgumentException()
{
ConvertFromStringThrowsArgumentException("1");
}
[Fact]
public void ConvertFromString_FormatException()
{
ConvertFromStringThrowsFormatInnerException("hello");
}
[Theory]
[MemberData(nameof(SizeData))]
public void ConvertToInvariantString(int width, int height)
{
var str = Converter.ConvertToInvariantString(new Size(width, height));
Assert.Equal($"{width}, {height}", str);
}
[Theory]
[MemberData(nameof(SizeData))]
public void ConvertToString(int width, int height)
{
var str = Converter.ConvertToString(new Size(width, height));
Assert.Equal(string.Format("{0}{2} {1}", width, height, CultureInfo.CurrentCulture.TextInfo.ListSeparator), str);
}
}
}
|
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.