context
stringlengths 2.52k
185k
| gt
stringclasses 1
value |
---|---|
using System;
using System.Collections;
using System.Collections.Generic;
namespace IniParser.Model
{
/// <summary>
/// <para>Represents a collection of SectionData.</para>
/// </summary>
public class SectionDataCollection : ICloneable, IEnumerable<SectionData>
{
IEqualityComparer<string> _searchComparer;
#region Initialization
/// <summary>
/// Initializes a new instance of the <see cref="SectionDataCollection"/> class.
/// </summary>
public SectionDataCollection()
:this(EqualityComparer<string>.Default)
{}
/// <summary>
/// Initializes a new instance of the <see cref="IniParser.Model.SectionDataCollection"/> class.
/// </summary>
/// <param name="searchComparer">
/// StringComparer used when accessing section names
/// </param>
public SectionDataCollection(IEqualityComparer<string> searchComparer)
{
_searchComparer = searchComparer;
_sectionData = new Dictionary<string, SectionData>(_searchComparer);
}
/// <summary>
/// Initializes a new instance of the <see cref="SectionDataCollection"/> class
/// from a previous instance of <see cref="SectionDataCollection"/>.
/// </summary>
/// <remarks>
/// Data is deeply copied
/// </remarks>
/// <param name="ori">
/// The instance of the <see cref="SectionDataCollection"/> class
/// used to create the new instance.</param>
public SectionDataCollection(SectionDataCollection ori, IEqualityComparer<string> searchComparer)
{
_searchComparer = searchComparer ?? EqualityComparer<string>.Default;
_sectionData = new Dictionary<string, SectionData> (ori._sectionData, _searchComparer);
}
#endregion
#region Properties
/// <summary>
/// Returns the number of SectionData elements in the collection
/// </summary>
public int Count { get { return _sectionData.Count; } }
/// <summary>
/// Gets the key data associated to a specified section name.
/// </summary>
/// <value>An instance of as <see cref="KeyDataCollection"/> class
/// holding the key data from the current parsed INI data, or a <c>null</c>
/// value if the section doesn't exist.</value>
public KeyDataCollection this[string sectionName]
{
get
{
if ( _sectionData.ContainsKey(sectionName) )
return _sectionData[sectionName].Keys;
return null;
}
}
#endregion
#region Public Members
/// <summary>
/// Creates a new section with empty data.
/// </summary>
/// <remarks>
/// <para>If a section with the same name exists, this operation has no effect.</para>
/// </remarks>
/// <param name="keyName">Name of the section to be created</param>
/// <return><c>true</c> if the a new section with the specified name was added,
/// <c>false</c> otherwise</return>
/// <exception cref="ArgumentException">If the section name is not valid.</exception>
public bool AddSection(string keyName)
{
//Checks valid section name
//if ( !Assert.StringHasNoBlankSpaces(keyName) )
// throw new ArgumentException("Section name contain whitespaces");
if ( !ContainsSection(keyName) )
{
_sectionData.Add( keyName, new SectionData(keyName, _searchComparer) );
return true;
}
return false;
}
/// <summary>
/// Adds a new SectionData instance to the collection
/// </summary>
/// <param name="data">Data.</param>
public void Add(SectionData data)
{
if (ContainsSection(data.SectionName))
{
SetSectionData(data.SectionName, new SectionData(data, _searchComparer));
}
else
{
_sectionData.Add(data.SectionName, new SectionData(data, _searchComparer));
}
}
/// <summary>
/// Removes all entries from this collection
/// </summary>
public void Clear()
{
_sectionData.Clear();
}
/// <summary>
/// Gets if a section with a specified name exists in the collection.
/// </summary>
/// <param name="keyName">Name of the section to search</param>
/// <returns>
/// <c>true</c> if a section with the specified name exists in the
/// collection <c>false</c> otherwise
/// </returns>
public bool ContainsSection(string keyName)
{
return _sectionData.ContainsKey(keyName);
}
/// <summary>
/// Returns the section data from a specify section given its name.
/// </summary>
/// <param name="sectionName">Name of the section.</param>
/// <returns>
/// An instance of a <see cref="SectionData"/> class
/// holding the section data for the currently INI data
/// </returns>
public SectionData GetSectionData(string sectionName)
{
if (_sectionData.ContainsKey(sectionName))
return _sectionData[sectionName];
return null;
}
public void Merge(SectionDataCollection sectionsToMerge)
{
foreach(var sectionDataToMerge in sectionsToMerge)
{
var sectionDataInThis = GetSectionData(sectionDataToMerge.SectionName);
if (sectionDataInThis == null)
{
AddSection(sectionDataToMerge.SectionName);
}
this[sectionDataToMerge.SectionName].Merge(sectionDataToMerge.Keys);
}
}
/// <summary>
/// Sets the section data for given a section name.
/// </summary>
/// <param name="sectionName"></param>
/// <param name="data">The new <see cref="SectionData"/>instance.</param>
public void SetSectionData(string sectionName, SectionData data)
{
if ( data != null )
_sectionData[sectionName] = data;
}
/// <summary>
///
/// </summary>
/// <param name="keyName"></param>
/// <return><c>true</c> if the section with the specified name was removed,
/// <c>false</c> otherwise</return>
public bool RemoveSection(string keyName)
{
return _sectionData.Remove(keyName);
}
#endregion
#region IEnumerable<SectionData> Members
/// <summary>
/// Returns an enumerator that iterates through the collection.
/// </summary>
/// <returns>
/// A <see cref="T:System.Collections.Generic.IEnumerator`1"/> that can be used to iterate through the collection.
/// </returns>
public IEnumerator<SectionData> GetEnumerator()
{
foreach (string sectionName in _sectionData.Keys)
yield return _sectionData[sectionName];
}
#endregion
#region IEnumerable Members
/// <summary>
/// Returns an enumerator that iterates through a collection.
/// </summary>
/// <returns>
/// An <see cref="T:System.Collections.IEnumerator"/> object that can be used to iterate through the collection.
/// </returns>
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
#endregion
#region ICloneable Members
/// <summary>
/// Creates a new object that is a copy of the current instance.
/// </summary>
/// <returns>
/// A new object that is a copy of this instance.
/// </returns>
public object Clone()
{
return new SectionDataCollection(this, _searchComparer);
}
#endregion
#region Non-public Members
/// <summary>
/// Data associated to this section
/// </summary>
private readonly Dictionary<string, SectionData> _sectionData;
#endregion
}
}
| |
using System;
using System.Text;
namespace Provider.VistaDB
{
internal class RemoteParameter
{
private enum ServerNativeType: ushort
{
Character = 1,
Date = 9,
DateTime = 11,
Boolean = 5,
Blob = 15,
Currency = 8,
Int32 = 3,
Int64 = 25,
Double = 6,
Guid = 35
}
private VistaDBType type;
private string name;
private object val;
public RemoteParameter(string name, VistaDBType type, object val)
{
this.type = type;
this.name = name;
this.val = val;
}
private int PutParamInfo(byte[] buffer, int offset, int dataSize, ushort serverDataType, Encoding encoding)
{
encoding.GetBytes(serverDataType.ToString("X8")).CopyTo(buffer, offset);
offset += 8;
encoding.GetBytes(serverDataType.ToString("X2")).CopyTo(buffer, offset);
offset += 2;
encoding.GetBytes("01").CopyTo(buffer, offset);
offset += 2;
encoding.GetBytes(this.name.PadRight(20)).CopyTo(buffer, offset);
offset += 20;
return offset;
}
private void CurrToBcd(byte[] buffer, int offset)
{
//Convert decimal to TBcd
long i64 = (long)((decimal)this.val * 10000);
int first = 16;
byte nibble;
buffer[offset] = 32;
buffer[offset + 1] = i64 < 0 ? (byte)0x80: (byte)0x00;
buffer[offset + 1] |= 4;
for(int i = first - 1; i >= 0; i--)
{
if(i64 == 0)
buffer[i + offset + 2] = 0;
else
{
nibble = (byte)(i64 % 100);
buffer[i + offset + 2] = (byte)(((nibble / 10) << 4) | (nibble % 10));
i64 /= 100;
}
}
}
public int PutParameterToBuffer(byte[] buffer, int offset, bool getSize)
{
int size = 0;
string s;
Encoding encoding = Encoding.Default;
if(this.val == null)
{
ushort type = 0;
switch(this.type)
{
case VistaDBType.Character:
case VistaDBType.Varchar:
case VistaDBType.Memo:
type = (ushort)ServerNativeType.Character;
break;
case VistaDBType.Date:
type = (ushort)ServerNativeType.Date;
break;
case VistaDBType.DateTime:
type = (ushort)ServerNativeType.DateTime;
break;
case VistaDBType.Boolean:
type = (ushort)ServerNativeType.Boolean;
break;
case VistaDBType.Picture:
case VistaDBType.Blob:
type = (ushort)ServerNativeType.Blob;
break;
case VistaDBType.Currency:
type = (ushort)ServerNativeType.Currency;
break;
case VistaDBType.Int32:
type= (ushort)ServerNativeType.Int32;
break;
case VistaDBType.Int64:
type = (ushort)ServerNativeType.Int64;
break;
case VistaDBType.Double:
type = (ushort)ServerNativeType.Double;
break;
case VistaDBType.Guid:
type = (ushort)ServerNativeType.Guid;
break;
}
if(!getSize)
{
offset = PutParamInfo(buffer, offset, 0, type, encoding);
}
}
else
{
switch(this.type)
{
case VistaDBType.Character:
case VistaDBType.Varchar:
case VistaDBType.Memo:
s = (string)this.val;
size = s.Length + 1;
if(!getSize)
{
offset = PutParamInfo(buffer, offset, size, (ushort)ServerNativeType.Character, encoding);
encoding.GetBytes(s).CopyTo(buffer, offset);
buffer[offset + s.Length] = 0;
}
break;
case VistaDBType.Date:
size = 4;
if(!getSize)
{
long timeStamp = ((DateTime)this.val).Ticks / 10000 + 86400000;
int date = (int)(timeStamp / VistaDBAPI.MSecsPerDay);
offset = PutParamInfo(buffer, offset, size, (ushort)ServerNativeType.Date, encoding);
BitConverter.GetBytes(date).CopyTo(buffer, offset);
}
break;
case VistaDBType.DateTime:
size = 8;
if(!getSize)
{
double dateTime = ((DateTime)this.val).Ticks / 10000;
offset = PutParamInfo(buffer, offset, size, (ushort)ServerNativeType.DateTime, encoding);
BitConverter.GetBytes(dateTime).CopyTo(buffer, offset);
}
break;
case VistaDBType.Boolean:
size = 2;
if(!getSize)
{
ushort b = (bool)this.val ? (ushort)1: (ushort)0;
offset = PutParamInfo(buffer, offset, size, (ushort)ServerNativeType.Boolean, encoding);
BitConverter.GetBytes(b).CopyTo(buffer, offset);
}
break;
case VistaDBType.Picture:
case VistaDBType.Blob:
size = ((byte[])this.val).Length;
if(!getSize)
{
offset = PutParamInfo(buffer, offset, size, (ushort)ServerNativeType.Blob, encoding);
((byte[])val).CopyTo(buffer, offset);
}
break;
case VistaDBType.Currency:
size = 34;
if(!getSize)
{
offset = PutParamInfo(buffer, offset, size, (ushort)ServerNativeType.Currency, encoding);
CurrToBcd(buffer, offset);
}
break;
case VistaDBType.Int32:
size = 4;
if(!getSize)
{
offset = PutParamInfo(buffer, offset, size, (ushort)ServerNativeType.Int32, encoding);
BitConverter.GetBytes((int)this.val).CopyTo(buffer, offset);
}
break;
case VistaDBType.Int64:
size = 8;
if(!getSize)
{
offset = PutParamInfo(buffer, offset, size, (ushort)ServerNativeType.Int64, encoding);
BitConverter.GetBytes((long)this.val).CopyTo(buffer, offset);
}
break;
case VistaDBType.Double:
size = 8;
if(!getSize)
{
offset = PutParamInfo(buffer, offset, size, (ushort)ServerNativeType.Double, encoding);
BitConverter.GetBytes((double)this.val).CopyTo(buffer, offset);
}
break;
case VistaDBType.Guid:
s = "{" + this.val.ToString() + "}";
size = s.Length + 1;
if(!getSize)
{
offset = PutParamInfo(buffer, offset, size, (ushort)ServerNativeType.Guid, encoding);
encoding.GetBytes(s).CopyTo(buffer, offset);
buffer[offset + s.Length] = 0;
}
break;
}
}
size += 8 + 2 + 2 + 20;
return size;
}
public string Name
{
get
{
return this.name;
}
}
public VistaDBType DataType
{
get
{
return this.type;
}
set
{
this.type = value;
}
}
public object Value
{
get
{
return val;
}
set
{
this.val = value;
}
}
}
internal class RemoteParameterCollection
{
private RemoteParameter[] parameters;
public RemoteParameterCollection()
{
this.parameters = null;
}
private void Add(string name, VistaDBType dataType, object val)
{
int len = this.parameters != null ? this.parameters.Length : 0;
RemoteParameter[] newParameters = new RemoteParameter[len + 1];
if(this.parameters != null)
this.parameters.CopyTo(newParameters, 0);
newParameters[len] = new RemoteParameter(name, dataType, val);
this.parameters = newParameters;
}
public void SetParameter(string name, VistaDBType dataType, object val)
{
if(this.parameters != null)
{
foreach(RemoteParameter p in this.parameters)
if(p.Name == name)
{
p.DataType = dataType;
p.Value = val;
}
}
Add(name, dataType, val);
}
public int GetParameters(byte[] buffer, int offset, bool getSize)
{
int len = 0;
//Put parameters to buffer
if(this.parameters != null)
{
foreach(RemoteParameter p in this.parameters)
len += p.PutParameterToBuffer(buffer, offset + len, getSize);
}
return len;
}
}
}
| |
// 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;
using System.Reflection.Runtime.TypeInfos;
namespace System.Reflection.TypeLoading
{
internal static class Assignability
{
public static bool IsAssignableFrom(Type toTypeInfo, Type fromTypeInfo, CoreTypes coreTypes)
{
if (toTypeInfo == null)
throw new NullReferenceException();
if (fromTypeInfo == null)
return false; // It would be more appropriate to throw ArgumentNullException here, but returning "false" is the desktop-compat behavior.
if (fromTypeInfo.Equals(toTypeInfo))
return true;
if (toTypeInfo.IsGenericTypeDefinition)
{
// Asking whether something can cast to a generic type definition is arguably meaningless. The desktop CLR Reflection layer converts all
// generic type definitions to generic type instantiations closed over the formal generic type parameters. The .NET Native framework
// keeps the two separate. Fortunately, under either interpretation, returning "false" unless the two types are identical is still a
// defensible behavior. To avoid having the rest of the code deal with the differing interpretations, we'll short-circuit this now.
return false;
}
if (fromTypeInfo.IsGenericTypeDefinition)
{
// The desktop CLR Reflection layer converts all generic type definitions to generic type instantiations closed over the formal
// generic type parameters. The .NET Native framework keeps the two separate. For the purpose of IsAssignableFrom(),
// it makes sense to unify the two for the sake of backward compat. We'll just make the transform here so that the rest of code
// doesn't need to know about this quirk.
fromTypeInfo = fromTypeInfo.GetGenericTypeDefinition().MakeGenericType(fromTypeInfo.GetGenericTypeParameters());
}
if (fromTypeInfo.CanCastTo(toTypeInfo, coreTypes))
return true;
// Desktop compat: IsAssignableFrom() considers T as assignable to Nullable<T> (but does not check if T is a generic parameter.)
if (!fromTypeInfo.IsGenericParameter)
{
if (toTypeInfo.IsConstructedGenericType && toTypeInfo.GetGenericTypeDefinition() == coreTypes[CoreType.NullableT])
{
Type nullableUnderlyingType = toTypeInfo.GenericTypeArguments[0];
if (nullableUnderlyingType.Equals(fromTypeInfo))
return true;
}
}
return false;
}
private static bool CanCastTo(this Type fromTypeInfo, Type toTypeInfo, CoreTypes coreTypes)
{
if (fromTypeInfo.Equals(toTypeInfo))
return true;
if (fromTypeInfo.IsArray)
{
if (toTypeInfo.IsInterface)
return fromTypeInfo.CanCastArrayToInterface(toTypeInfo, coreTypes);
if (fromTypeInfo.IsSubclassOf(toTypeInfo))
return true; // T[] is castable to Array or Object.
if (!toTypeInfo.IsArray)
return false;
int rank = fromTypeInfo.GetArrayRank();
if (rank != toTypeInfo.GetArrayRank())
return false;
bool fromTypeIsSzArray = fromTypeInfo.IsSZArray();
bool toTypeIsSzArray = toTypeInfo.IsSZArray();
if (fromTypeIsSzArray != toTypeIsSzArray)
{
// T[] is assignable to T[*] but not vice-versa.
if (!(rank == 1 && !toTypeIsSzArray))
{
return false; // T[*] is not castable to T[]
}
}
Type toElementTypeInfo = toTypeInfo.GetElementType();
Type fromElementTypeInfo = fromTypeInfo.GetElementType();
return fromElementTypeInfo.IsElementTypeCompatibleWith(toElementTypeInfo, coreTypes);
}
if (fromTypeInfo.IsByRef)
{
if (!toTypeInfo.IsByRef)
return false;
Type toElementTypeInfo = toTypeInfo.GetElementType();
Type fromElementTypeInfo = fromTypeInfo.GetElementType();
return fromElementTypeInfo.IsElementTypeCompatibleWith(toElementTypeInfo, coreTypes);
}
if (fromTypeInfo.IsPointer)
{
if (toTypeInfo.Equals(coreTypes[CoreType.Object]))
return true; // T* is castable to Object.
if (toTypeInfo.Equals(coreTypes[CoreType.UIntPtr]))
return true; // T* is castable to UIntPtr (but not IntPtr)
if (!toTypeInfo.IsPointer)
return false;
Type toElementTypeInfo = toTypeInfo.GetElementType();
Type fromElementTypeInfo = fromTypeInfo.GetElementType();
return fromElementTypeInfo.IsElementTypeCompatibleWith(toElementTypeInfo, coreTypes);
}
if (fromTypeInfo.IsGenericParameter)
{
//
// A generic parameter can be cast to any of its constraints, or object, if none are specified, or ValueType if the "struct" constraint is
// specified.
//
// This has to be coded as its own case as TypeInfo.BaseType on a generic parameter doesn't always return what you'd expect.
//
if (toTypeInfo.Equals(coreTypes[CoreType.Object]))
return true;
if (toTypeInfo.Equals(coreTypes[CoreType.ValueType]))
{
GenericParameterAttributes attributes = fromTypeInfo.GenericParameterAttributes;
if ((attributes & GenericParameterAttributes.NotNullableValueTypeConstraint) != 0)
return true;
}
foreach (Type constraintType in fromTypeInfo.GetGenericParameterConstraints())
{
if (constraintType.CanCastTo(toTypeInfo, coreTypes))
return true;
}
return false;
}
if (toTypeInfo.IsArray || toTypeInfo.IsByRef || toTypeInfo.IsPointer || toTypeInfo.IsGenericParameter)
return false;
if (fromTypeInfo.MatchesWithVariance(toTypeInfo, coreTypes))
return true;
if (toTypeInfo.IsInterface)
{
foreach (Type ifc in fromTypeInfo.GetInterfaces())
{
if (ifc.MatchesWithVariance(toTypeInfo, coreTypes))
return true;
}
return false;
}
else
{
// Interfaces are always castable to System.Object. The code below will not catch this as interfaces report their BaseType as null.
if (toTypeInfo.Equals(coreTypes[CoreType.Object]) && fromTypeInfo.IsInterface)
return true;
Type walk = fromTypeInfo;
while (true)
{
Type baseType = walk.BaseType;
if (baseType == null)
return false;
walk = baseType;
if (walk.MatchesWithVariance(toTypeInfo, coreTypes))
return true;
}
}
}
//
// Check a base type or implemented interface type for equivalence (taking into account variance for generic instantiations.)
// Does not check ancestors recursively.
//
private static bool MatchesWithVariance(this Type fromTypeInfo, Type toTypeInfo, CoreTypes coreTypes)
{
Debug.Assert(!(fromTypeInfo.IsArray || fromTypeInfo.IsByRef || fromTypeInfo.IsPointer || fromTypeInfo.IsGenericParameter));
Debug.Assert(!(toTypeInfo.IsArray || toTypeInfo.IsByRef || toTypeInfo.IsPointer || toTypeInfo.IsGenericParameter));
if (fromTypeInfo.Equals(toTypeInfo))
return true;
if (!(fromTypeInfo.IsConstructedGenericType && toTypeInfo.IsConstructedGenericType))
return false;
Type genericTypeDefinition = fromTypeInfo.GetGenericTypeDefinition();
if (!genericTypeDefinition.Equals(toTypeInfo.GetGenericTypeDefinition()))
return false;
Type[] fromTypeArguments = fromTypeInfo.GenericTypeArguments;
Type[] toTypeArguments = toTypeInfo.GenericTypeArguments;
Type[] genericTypeParameters = genericTypeDefinition.GetGenericTypeParameters();
for (int i = 0; i < genericTypeParameters.Length; i++)
{
Type fromTypeArgumentInfo = fromTypeArguments[i];
Type toTypeArgumentInfo = toTypeArguments[i];
GenericParameterAttributes attributes = genericTypeParameters[i].GenericParameterAttributes;
switch (attributes & GenericParameterAttributes.VarianceMask)
{
case GenericParameterAttributes.Covariant:
if (!(fromTypeArgumentInfo.IsGcReferenceTypeAndCastableTo(toTypeArgumentInfo, coreTypes)))
return false;
break;
case GenericParameterAttributes.Contravariant:
if (!(toTypeArgumentInfo.IsGcReferenceTypeAndCastableTo(fromTypeArgumentInfo, coreTypes)))
return false;
break;
case GenericParameterAttributes.None:
if (!(fromTypeArgumentInfo.Equals(toTypeArgumentInfo)))
return false;
break;
default:
throw new BadImageFormatException(); // Unexpected variance value in metadata.
}
}
return true;
}
//
// A[] can cast to B[] if one of the following are true:
//
// A can cast to B under variance rules.
//
// A and B are both integers or enums and have the same reduced type (i.e. represent the same-sized integer, ignoring signed/unsigned differences.)
// "char" is not interchangable with short/ushort. "bool" is not interchangable with byte/sbyte.
//
// For desktop compat, A& and A* follow the same rules.
//
private static bool IsElementTypeCompatibleWith(this Type fromTypeInfo, Type toTypeInfo, CoreTypes coreTypes)
{
if (fromTypeInfo.IsGcReferenceTypeAndCastableTo(toTypeInfo, coreTypes))
return true;
Type reducedFromType = fromTypeInfo.ReducedType(coreTypes);
Type reducedToType = toTypeInfo.ReducedType(coreTypes);
if (reducedFromType.Equals(reducedToType))
return true;
return false;
}
private static Type ReducedType(this Type t, CoreTypes coreTypes)
{
if (t.IsEnum)
t = t.GetEnumUnderlyingType();
if (t.Equals(coreTypes[CoreType.Byte]))
return coreTypes[CoreType.SByte] ?? throw new TypeLoadException(SR.Format(SR.CoreTypeNotFound, "System.SByte"));
if (t.Equals(coreTypes[CoreType.UInt16]))
return coreTypes[CoreType.Int16] ?? throw new TypeLoadException(SR.Format(SR.CoreTypeNotFound, "System.Int16"));
if (t.Equals(coreTypes[CoreType.UInt32]))
return coreTypes[CoreType.Int32] ?? throw new TypeLoadException(SR.Format(SR.CoreTypeNotFound, "System.Int32"));
if (t.Equals(coreTypes[CoreType.UInt64]))
return coreTypes[CoreType.Int64] ?? throw new TypeLoadException(SR.Format(SR.CoreTypeNotFound, "System.Int64"));
return t;
}
//
// Contra/CoVariance.
//
// IEnumerable<D> can cast to IEnumerable<B> if D can cast to B and if there's no possibility that D is a value type.
//
private static bool IsGcReferenceTypeAndCastableTo(this Type fromTypeInfo, Type toTypeInfo, CoreTypes coreTypes)
{
if (fromTypeInfo.Equals(toTypeInfo))
return true;
if (fromTypeInfo.ProvablyAGcReferenceType(coreTypes))
return fromTypeInfo.CanCastTo(toTypeInfo, coreTypes);
return false;
}
//
// A true result indicates that a type can never be a value type. This is important when testing variance-compatibility.
//
private static bool ProvablyAGcReferenceType(this Type t, CoreTypes coreTypes)
{
if (t.IsGenericParameter)
{
GenericParameterAttributes attributes = t.GenericParameterAttributes;
if ((attributes & GenericParameterAttributes.ReferenceTypeConstraint) != 0)
return true; // generic parameter with a "class" constraint.
}
return t.ProvablyAGcReferenceTypeHelper(coreTypes);
}
private static bool ProvablyAGcReferenceTypeHelper(this Type t, CoreTypes coreTypes)
{
if (t.IsArray)
return true;
if (t.IsByRef || t.IsPointer)
return false;
if (t.IsGenericParameter)
{
// We intentionally do not check for a "class" constraint on generic parameter ancestors.
// That's because this property does not propagate up the constraining hierarchy.
// (e.g. "class A<S, T> where S : T, where T : class" does not guarantee that S is a class.)
foreach (Type constraintType in t.GetGenericParameterConstraints())
{
if (constraintType.ProvablyAGcReferenceTypeHelper(coreTypes))
return true;
}
return false;
}
return t.IsClass && !t.Equals(coreTypes[CoreType.Object]) && !t.Equals(coreTypes[CoreType.ValueType]) && !t.Equals(coreTypes[CoreType.Enum]);
}
//
// T[] casts to IList<T>. This could be handled by the normal ancestor-walking code
// but for one complication: T[] also casts to IList<U> if T[] casts to U[].
//
private static bool CanCastArrayToInterface(this Type fromTypeInfo, Type toTypeInfo, CoreTypes coreTypes)
{
Debug.Assert(fromTypeInfo.IsArray);
Debug.Assert(toTypeInfo.IsInterface);
if (toTypeInfo.IsConstructedGenericType)
{
Type[] toTypeGenericTypeArguments = toTypeInfo.GenericTypeArguments;
if (toTypeGenericTypeArguments.Length != 1)
return false;
Type toElementTypeInfo = toTypeGenericTypeArguments[0];
Type toTypeGenericTypeDefinition = toTypeInfo.GetGenericTypeDefinition();
Type fromElementTypeInfo = fromTypeInfo.GetElementType();
foreach (Type ifc in fromTypeInfo.GetInterfaces())
{
if (ifc.IsConstructedGenericType)
{
Type ifcGenericTypeDefinition = ifc.GetGenericTypeDefinition();
if (ifcGenericTypeDefinition.Equals(toTypeGenericTypeDefinition))
{
if (fromElementTypeInfo.IsElementTypeCompatibleWith(toElementTypeInfo, coreTypes))
return true;
}
}
}
return false;
}
else
{
foreach (Type ifc in fromTypeInfo.GetInterfaces())
{
if (ifc.Equals(toTypeInfo))
return true;
}
return false;
}
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.IO;
using System.Text;
using FileHelpers.Events;
using FileHelpers.Helpers;
using FileHelpers.Streams;
namespace FileHelpers
{
/// <summary>
/// Basic engine to read record by record
/// </summary>
public class FileHelperEngine
: FileHelperEngine<object>
{
#region " Constructor "
/// <include file='FileHelperEngine.docs.xml' path='doc/FileHelperEngineCtr/*'/>
public FileHelperEngine(Type recordType)
: this(recordType, Encoding.GetEncoding(0)) { }
/// <include file='FileHelperEngine.docs.xml' path='doc/FileHelperEngineCtr/*'/>
/// <param name="recordType">The record mapping class.</param>
/// <param name="encoding">The Encoding used by the engine.</param>
public FileHelperEngine(Type recordType, Encoding encoding)
: base(recordType, encoding) {}
/// <include file='FileHelperEngine.docs.xml' path='doc/FileHelperEngineCtr/*'/>
/// <param name="ri">Record information on new type</param>
internal FileHelperEngine(RecordInfo ri)
: base(ri) {}
#endregion
}
/// <include file='FileHelperEngine.docs.xml' path='doc/FileHelperEngine/*'/>
/// <include file='Examples.xml' path='doc/examples/FileHelperEngine/*'/>
/// <typeparam name="T">The record type.</typeparam>
[DebuggerDisplay(
"FileHelperEngine for type: {RecordType.Name}. ErrorMode: {ErrorManager.ErrorMode.ToString()}. Encoding: {Encoding.EncodingName}"
)]
public class FileHelperEngine<T>
: EventEngineBase<T>,
IFileHelperEngine<T>
where T : class
{
private readonly bool mObjectEngine;
#region " Constructor "
/// <include file='FileHelperEngine.docs.xml' path='doc/FileHelperEngineCtr/*'/>
public FileHelperEngine()
: this(Encoding.GetEncoding(0)) { }
/// <include file='FileHelperEngine.docs.xml' path='doc/FileHelperEngineCtr/*'/>
/// <param name="encoding">The Encoding used by the engine.</param>
public FileHelperEngine(Encoding encoding)
: base(typeof (T), encoding)
{
mObjectEngine = typeof (T) == typeof (object);
}
/// <include file='FileHelperEngine.docs.xml' path='doc/FileHelperEngineCtr/*'/>
/// <param name="encoding">The Encoding used by the engine.</param>
/// <param name="recordType">Type of record we are reading</param>
protected FileHelperEngine(Type recordType, Encoding encoding)
: base(recordType, encoding)
{
mObjectEngine = typeof (T) == typeof (object);
}
/// <include file='FileHelperEngine.docs.xml' path='doc/FileHelperEngineCtr/*'/>
/// <param name="ri">Record information</param>
internal FileHelperEngine(RecordInfo ri)
: base(ri)
{
mObjectEngine = typeof (T) == typeof (object);
}
#endregion
#region " ReadFile "
/// <include file='FileHelperEngine.docs.xml' path='doc/ReadFile/*'/>
public T[] ReadFile(string fileName)
{
return ReadFile(fileName, int.MaxValue);
}
/// <include file='FileHelperEngine.docs.xml' path='doc/ReadFile/*'/>
/// <param name="maxRecords">The max number of records to read. Int32.MaxValue or -1 to read all records.</param>
public T[] ReadFile(string fileName, int maxRecords)
{
using (var fs = new InternalStreamReader(fileName, mEncoding, true, DefaultReadBufferSize))
{
T[] tempRes;
tempRes = ReadStream(fs, maxRecords);
fs.Close();
return tempRes;
}
}
/// <include file='FileHelperEngine.docs.xml' path='doc/ReadFile/*'/>
public List<T> ReadFileAsList(string fileName)
{
return ReadFileAsList(fileName, int.MaxValue);
}
/// <include file='FileHelperEngine.docs.xml' path='doc/ReadFile/*'/>
/// <param name="maxRecords">The max number of records to read. Int32.MaxValue or -1 to read all records.</param>
public List<T> ReadFileAsList(string fileName, int maxRecords)
{
using (var fs = new InternalStreamReader(fileName, mEncoding, true, DefaultReadBufferSize))
{
var res = ReadStreamAsList(fs, maxRecords);
fs.Close();
return res;
}
}
#endregion
#region " ReadStream "
/// <include file='FileHelperEngine.docs.xml' path='doc/ReadStream/*'/>
[EditorBrowsable(EditorBrowsableState.Advanced)]
public T[] ReadStream(TextReader reader)
{
return ReadStream(reader, int.MaxValue);
}
/// <include file='FileHelperEngine.docs.xml' path='doc/ReadStream/*'/>
/// <param name="maxRecords">The max number of records to read. Int32.MaxValue or -1 to read all records.</param>
[EditorBrowsable(EditorBrowsableState.Advanced)]
public T[] ReadStream(TextReader reader, int maxRecords)
{
var result = ReadStreamAsList(reader, maxRecords, null);
if (mObjectEngine)
return (T[]) ((ArrayList) result).ToArray(RecordInfo.RecordType);
else
return ((List<T>) result).ToArray();
}
private void ReadStream(TextReader reader, int maxRecords, DataTable dt)
{
ReadStreamAsList(reader, maxRecords, dt);
}
/// <include file='FileHelperEngine.docs.xml' path='doc/ReadStream/*'/>
/// <param name="maxRecords">The max number of records to read. Int32.MaxValue or -1 to read all records.</param>
[EditorBrowsable(EditorBrowsableState.Advanced)]
public List<T> ReadStreamAsList(TextReader reader, int maxRecords)
{
var result = ReadStreamAsList(reader, maxRecords, null);
if (mObjectEngine)
{
var res = new List<T>(result.Count);
for (int i = 0; i < result.Count; i++)
res.Add((T) result[i]);
return res;
}
else
return (List<T>) result;
}
private IList ReadStreamAsList(TextReader reader, int maxRecords, DataTable dt)
{
if (reader == null)
//?StreamReaderIsNull"The reader of the Stream can't be null"
throw new FileHelpersException("FileHelperMsg_StreamReaderIsNull", null);
var recordReader = new NewLineDelimitedRecordReader(reader);
ResetFields();
HeaderText = String.Empty;
mFooterText = String.Empty;
IList result;
if (mObjectEngine)
result = new ArrayList();
else
result = new List<T>();
int currentRecord = 0;
var streamInfo = new StreamInfoProvider(reader);
using (var freader = new ForwardReader(recordReader, RecordInfo.IgnoreLast))
{
freader.DiscardForward = true;
mLineNumber = 1;
string completeLine = freader.ReadNextLine();
string currentLine = completeLine;
if (MustNotifyProgress) // Avoid object creation
OnProgress(new ProgressEventArgs(0, -1, streamInfo.Position, streamInfo.TotalBytes));
if (RecordInfo.IgnoreFirst > 0)
{
for (int i = 0; i < RecordInfo.IgnoreFirst && currentLine != null; i++)
{
HeaderText += currentLine + StringHelper.NewLine;
currentLine = freader.ReadNextLine();
mLineNumber++;
}
}
bool byPass = false;
if (maxRecords < 0)
maxRecords = int.MaxValue;
var line = new LineInfo(currentLine)
{
mReader = freader
};
var values = new object[RecordInfo.FieldCount];
while (currentLine != null &&
currentRecord < maxRecords)
{
completeLine = currentLine;
try
{
mTotalRecords++;
currentRecord++;
line.ReLoad(currentLine);
var skip = false;
var record = (T) RecordInfo.Operations.CreateRecordHandler();
if (MustNotifyProgress) // Avoid object creation
{
OnProgress(new ProgressEventArgs(currentRecord,
-1,
streamInfo.Position,
streamInfo.TotalBytes));
}
BeforeReadEventArgs<T> e = null;
if (MustNotifyRead)
{
e = new BeforeReadEventArgs<T>(this, record, currentLine, LineNumber);
skip = OnBeforeReadRecord(e);
if (e.RecordLineChanged)
line.ReLoad(e.RecordLine);
}
if (skip == false)
{
Tuple<int, int>[] valuesPosition;
if (RecordInfo.Operations.StringToRecord(record, line, values, ErrorManager, -1, out valuesPosition))
{
if (MustNotifyRead) // Avoid object creation
skip = OnAfterReadRecord(currentLine, record, valuesPosition, e.RecordLineChanged, LineNumber);
if (skip == false)
{
if (dt == null)
result.Add(record);
else
dt.Rows.Add(RecordInfo.Operations.RecordToValues(record));
}
}
}
}
catch (Exception ex)
{
switch (mErrorManager.ErrorMode)
{
case ErrorMode.ThrowException:
byPass = true;
throw;
case ErrorMode.IgnoreAndContinue:
break;
case ErrorMode.SaveAndContinue:
var err = new ErrorInfo
{
mLineNumber = freader.LineNumber,
mExceptionInfo = ex,
mRecordString = completeLine,
mRecordTypeName = RecordInfo.RecordType.Name
};
mErrorManager.AddError(err);
break;
}
}
finally
{
if (byPass == false)
{
currentLine = freader.ReadNextLine();
mLineNumber++;
}
}
}
if (RecordInfo.IgnoreLast > 0)
mFooterText = freader.RemainingText;
}
return result;
}
#endregion
#region " ReadString "
/// <include file='FileHelperEngine.docs.xml' path='doc/ReadString/*'/>
public T[] ReadString(string source)
{
return ReadString(source, int.MaxValue);
}
/// <include file='FileHelperEngine.docs.xml' path='doc/ReadString/*'/>
/// <param name="maxRecords">The max number of records to read. Int32.MaxValue or -1 to read all records.</param>
public T[] ReadString(string source, int maxRecords)
{
if (source == null)
source = string.Empty;
using (var reader = new InternalStringReader(source))
{
var res = ReadStream(reader, maxRecords);
reader.Close();
return res;
}
}
/// <include file='FileHelperEngine.docs.xml' path='doc/ReadString/*'/>
public List<T> ReadStringAsList(string source)
{
return ReadStringAsList(source, int.MaxValue);
}
/// <include file='FileHelperEngine.docs.xml' path='doc/ReadString/*'/>
/// <param name="maxRecords">The max number of records to read. Int32.MaxValue or -1 to read all records.</param>
public List<T> ReadStringAsList(string source, int maxRecords)
{
if (source == null)
source = string.Empty;
using (var reader = new InternalStringReader(source))
{
var res = ReadStreamAsList(reader, maxRecords);
reader.Close();
return res;
}
}
#endregion
#region " WriteFile "
/// <include file='FileHelperEngine.docs.xml' path='doc/WriteFile/*'/>
public void WriteFile(string fileName, IEnumerable<T> records)
{
WriteFile(fileName, records, -1);
}
/// <include file='FileHelperEngine.docs.xml' path='doc/WriteFile2/*'/>
public void WriteFile(string fileName, IEnumerable<T> records, int maxRecords)
{
using (var fs = new StreamWriter(fileName, false, mEncoding, DefaultWriteBufferSize))
{
WriteStream(fs, records, maxRecords);
fs.Close();
}
}
#endregion
#region " WriteStream "
/// <include file='FileHelperEngine.docs.xml' path='doc/WriteStream/*'/>
[EditorBrowsable(EditorBrowsableState.Advanced)]
public void WriteStream(TextWriter writer, IEnumerable<T> records)
{
WriteStream(writer, records, -1);
}
/// <include file='FileHelperEngine.docs.xml' path='doc/WriteStream2/*'/>
[EditorBrowsable(EditorBrowsableState.Advanced)]
public void WriteStream(TextWriter writer, IEnumerable<T> records, int maxRecords)
{
if (writer == null)
//?StreamWriterIsNull"The writer of the Stream can be null"
throw new FileHelpersException("FileHelperMsg_StreamWriterIsNull", null);
if (records == null)
//?UseEmptyArray"The records can be null. Try with an empty array."
throw new FileHelpersException("FileHelperMsg_UseEmptyArray", null);
ResetFields();
writer.NewLine = NewLineForWrite;
WriteHeader(writer);
string currentLine = null;
int max = maxRecords;
if (records is IList)
{
max = Math.Min(max < 0
? int.MaxValue
: max,
((IList) records).Count);
}
if (MustNotifyProgress) // Avoid object creation
OnProgress(new ProgressEventArgs(0, max));
int recIndex = 0;
bool first = true;
foreach (var rec in records)
{
if (recIndex == maxRecords)
break;
mLineNumber++;
try
{
if (rec == null)
//?RecordIsNullAtIndex"The record at index {0} is null."
throw new BadUsageException("FileHelperMsg_RecordIsNullAtIndex", new List<string>() { recIndex.ToString() });
if (first)
{
first = false;
if (RecordInfo.RecordType.IsInstanceOfType(rec) == false)
{
//?RecordTypeMismatch"This engine works with record of type {0} and you use records of type {1}"
throw new BadUsageException("FileHelperMsg_RecordTypeMismatch", new List<string>() { RecordInfo.RecordType.Name, rec.GetType().Name });
}
}
bool skip = false;
if (MustNotifyProgress) // Avoid object creation
OnProgress(new ProgressEventArgs(recIndex + 1, max));
if (MustNotifyWrite)
skip = OnBeforeWriteRecord(rec, LineNumber);
if (skip == false)
{
currentLine = RecordInfo.Operations.RecordToString(rec);
if (MustNotifyWrite)
currentLine = OnAfterWriteRecord(currentLine, rec);
writer.WriteLine(currentLine);
}
}
catch (Exception ex)
{
switch (mErrorManager.ErrorMode)
{
case ErrorMode.ThrowException:
throw;
case ErrorMode.IgnoreAndContinue:
break;
case ErrorMode.SaveAndContinue:
var err = new ErrorInfo
{
mLineNumber = mLineNumber,
mExceptionInfo = ex,
mRecordString = currentLine,
mRecordTypeName = RecordInfo.RecordType.Name
};
mErrorManager.AddError(err);
break;
}
}
recIndex++;
}
mTotalRecords = recIndex;
WriteFooter(writer);
}
#endregion
#region " WriteString "
/// <include file='FileHelperEngine.docs.xml' path='doc/WriteString/*'/>
public string WriteString(IEnumerable<T> records)
{
return WriteString(records, -1);
}
/// <include file='FileHelperEngine.docs.xml' path='doc/WriteString2/*'/>
public string WriteString(IEnumerable<T> records, int maxRecords)
{
var sb = new StringBuilder();
using (var writer = new StringWriter(sb))
{
WriteStream(writer, records, maxRecords);
string res = writer.ToString();
return res;
}
}
#endregion
#region " AppendToFile "
/// <include file='FileHelperEngine.docs.xml' path='doc/AppendToFile1/*'/>
public void AppendToFile(string fileName, T record)
{
AppendToFile(fileName, new T[] {record});
}
/// <include file='FileHelperEngine.docs.xml' path='doc/AppendToFile2/*'/>
public void AppendToFile(string fileName, IEnumerable<T> records)
{
using (
TextWriter writer = StreamHelper.CreateFileAppender(fileName,
mEncoding,
true,
false,
DefaultWriteBufferSize))
{
HeaderText = String.Empty;
mFooterText = String.Empty;
WriteStream(writer, records);
writer.Close();
}
}
#endregion
#region " DataTable Ops "
/// <summary>
/// Read the records of the file and fill a DataTable with them
/// </summary>
/// <param name="fileName">The file name.</param>
/// <returns>The DataTable with the read records.</returns>
public DataTable ReadFileAsDT(string fileName)
{
return ReadFileAsDT(fileName, -1);
}
/// <summary>
/// Read the records of the file and fill a DataTable with them
/// </summary>
/// <param name="fileName">The file name.</param>
/// <param name="maxRecords">The max number of records to read. Int32.MaxValue or -1 to read all records.</param>
/// <returns>The DataTable with the read records.</returns>
public DataTable ReadFileAsDT(string fileName, int maxRecords)
{
using (var fs = new InternalStreamReader(fileName, mEncoding, true, DefaultReadBufferSize))
{
DataTable res = ReadStreamAsDT(fs, maxRecords);
fs.Close();
return res;
}
}
/// <summary>
/// Read the records of a string and fill a DataTable with them.
/// </summary>
/// <param name="source">The source string with the records.</param>
/// <returns>The DataTable with the read records.</returns>
public DataTable ReadStringAsDT(string source)
{
return ReadStringAsDT(source, -1);
}
/// <summary>
/// Read the records of a string and fill a DataTable with them.
/// </summary>
/// <param name="source">The source string with the records.</param>
/// <param name="maxRecords">The max number of records to read. Int32.MaxValue or -1 to read all records.</param>
/// <returns>The DataTable with the read records.</returns>
public DataTable ReadStringAsDT(string source, int maxRecords)
{
if (source == null)
source = string.Empty;
using (var reader = new InternalStringReader(source))
{
DataTable res = ReadStreamAsDT(reader, maxRecords);
reader.Close();
return res;
}
}
/// <summary>
/// Read the records of the stream and fill a DataTable with them
/// </summary>
/// <param name="reader">The stream with the source records.</param>
/// <returns>The DataTable with the read records.</returns>
public DataTable ReadStreamAsDT(TextReader reader)
{
return ReadStreamAsDT(reader, -1);
}
/// <summary>
/// Read the records of the stream and fill a DataTable with them
/// </summary>
/// <param name="reader">The stream with the source records.</param>
/// <param name="maxRecords">The max number of records to read. Int32.MaxValue or -1 to read all records.</param>
/// <returns>The DataTable with the read records.</returns>
public DataTable ReadStreamAsDT(TextReader reader, int maxRecords)
{
DataTable dt = RecordInfo.Operations.CreateEmptyDataTable();
dt.BeginLoadData();
ReadStream(reader, maxRecords, dt);
dt.EndLoadData();
return dt;
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using EnvDTE;
using EnvDTE80;
using VSLangProj;
using System.IO;
using Microsoft.Practices.ComponentModel;
namespace SPALM.SPSF.Library.Editors
{
[ServiceDependency(typeof(DTE))]
public partial class SelectLayoutFileForm : Form
{
public string selectedPath = "";
public SelectLayoutFileForm()
{
InitializeComponent();
}
public SelectLayoutFileForm(DTE envdte, object currentselection)
{
InitializeComponent();
try
{
LoadTree(envdte);
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
private void LoadTree(DTE envdte)
{
treeView1.Nodes.Clear();
foreach (Project project in envdte.Solution.Projects)
{
if (project.Object is SolutionFolder)
{
SolutionFolder x = (SolutionFolder)project.Object;
foreach (ProjectItem pitem in x.Parent.ProjectItems)
{
if (pitem.Object != null)
{
if (pitem.Object is Project)
{
LoadProject(pitem.Object as Project);
}
}
}
}
else
{
LoadProject(project);
}
}
}
private void LoadProject(Project project)
{
Load12Hive(project);
}
private void Load12Hive(Project project)
{
ProjectItem layoutsFolder = null;
ProjectItem imagesFolder = null;
ProjectItem adminFolder = null;
try
{
layoutsFolder = Helpers.GetProjectItemByName(Helpers.GetProjectItemByName(Helpers.GetProjectItemByName(project.ProjectItems, Helpers.GetSharePointHive(project.DTE)).ProjectItems, "template").ProjectItems, "Layouts");
}
catch (Exception)
{
}
try
{
imagesFolder = Helpers.GetProjectItemByName(Helpers.GetProjectItemByName(Helpers.GetProjectItemByName(project.ProjectItems, Helpers.GetSharePointHive(project.DTE)).ProjectItems, "template").ProjectItems, "Images");
}
catch (Exception)
{
}
try
{
adminFolder = Helpers.GetProjectItemByName(Helpers.GetProjectItemByName(Helpers.GetProjectItemByName(project.ProjectItems, Helpers.GetSharePointHive(project.DTE)).ProjectItems, "template").ProjectItems, "Admin");
}
catch (Exception)
{
}
if ((layoutsFolder != null) || (imagesFolder != null) || (adminFolder != null))
{
TreeNode node = treeView1.Nodes.Add(project.Name);
node.Tag = project;
node.ImageKey = "Folder";
node.SelectedImageKey = "Folder";
if (layoutsFolder != null)
{
TreeNode nodelayouts = new TreeNode("Layouts");
nodelayouts.Tag = layoutsFolder;
node.Nodes.Add(nodelayouts);
SetIcon(nodelayouts, layoutsFolder);
LoadItems(layoutsFolder, nodelayouts);
}
if (imagesFolder != null)
{
TreeNode nodelayouts = new TreeNode("Images");
nodelayouts.Tag = imagesFolder;
node.Nodes.Add(nodelayouts);
SetIcon(nodelayouts, layoutsFolder);
LoadItems(imagesFolder, nodelayouts);
}
if (adminFolder != null)
{
TreeNode nodelayouts = new TreeNode("Admin");
nodelayouts.Tag = adminFolder;
node.Nodes.Add(nodelayouts);
SetIcon(nodelayouts, adminFolder);
LoadItems(adminFolder, nodelayouts);
}
}
}
private void SetIcon(TreeNode nodelayouts, ProjectItem item)
{
if (item != null)
{
if (item.Kind == EnvDTE.Constants.vsProjectItemKindPhysicalFile)
{
try
{
switch (Path.GetExtension(item.get_FileNames(1)))
{
case ".ascx":
case ".asmx":
case ".aspx":
case ".htm":
case ".html":
nodelayouts.ImageKey = "Page";
nodelayouts.SelectedImageKey = "Picture";
return;
case ".jpg":
case ".jpeg":
case ".gif":
case ".png":
case ".bmp":
nodelayouts.ImageKey = "Picture";
nodelayouts.SelectedImageKey = "Picture";
return;
default:
nodelayouts.ImageKey = "Document";
nodelayouts.SelectedImageKey = "Document";
return;
}
}
catch (Exception)
{
nodelayouts.ImageKey = "Document";
nodelayouts.SelectedImageKey = "Document";
}
}
else
{
nodelayouts.ImageKey = "Folder";
nodelayouts.SelectedImageKey = "Folder";
}
}
else
{
nodelayouts.ImageKey = "Folder";
nodelayouts.SelectedImageKey = "Folder";
}
}
private void LoadItems(ProjectItem p, TreeNode parentNode)
{
foreach (ProjectItem child in p.ProjectItems)
{
TreeNode node = parentNode.Nodes.Add(child.Name);
node.Tag = child;
SetIcon(node, child);
LoadItems(child, node);
}
}
private void treeView1_AfterSelect(object sender, TreeViewEventArgs e)
{
if (e.Node.Tag != null)
{
if (e.Node.Tag is ProjectItem)
{
ProjectItem pitem = e.Node.Tag as ProjectItem;
if (pitem.Kind == EnvDTE.Constants.vsProjectItemKindPhysicalFile)
{
SetText(e.Node.FullPath);
return;
}
}
}
textBox1.Text = "";
}
private void SetText(string path)
{
DTE service = (DTE)this.GetService(typeof(DTE));
//remove
path = path.Substring(path.IndexOf("/")).ToLower();
if (path.StartsWith("/layouts/"))
{
path = path.Replace("/layouts/", "/_layouts" + Helpers.GetVersionedFolder(service) + "/");
}
if (path.StartsWith("/images/"))
{
path = path.Replace("/images/", "/_layouts" + Helpers.GetVersionedFolder(service) + "/images/");
}
if (path.StartsWith("/admin/"))
{
path = path.Replace("/admin/", "/_admin/");
}
textBox1.Text = path;
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
if (textBox1.Text != "")
{
button_ok.Enabled = true;
}
else
{
button_ok.Enabled = false;
}
}
private void buttonOK_Click(object sender, EventArgs e)
{
selectedPath = textBox1.Text;
Close();
}
}
}
| |
//-----------------------------------------------------------------------
// <copyright file="ListCommandHandler.cs" company="Fubar Development Junker">
// Copyright (c) Fubar Development Junker. All rights reserved.
// </copyright>
// <author>Mark Junker</author>
//-----------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using DotNet.Globbing;
using FubarDev.FtpServer.Commands;
using FubarDev.FtpServer.Features;
using FubarDev.FtpServer.FileSystem;
using FubarDev.FtpServer.ListFormatters;
using FubarDev.FtpServer.ServerCommands;
using FubarDev.FtpServer.Utilities;
using Microsoft.Extensions.Logging;
namespace FubarDev.FtpServer.CommandHandlers
{
/// <summary>
/// Implements the <c>LIST</c> and <c>NLST</c> commands.
/// </summary>
[FtpCommandHandler("LIST")]
[FtpCommandHandler("NLST")]
[FtpCommandHandler("LS")]
public class ListCommandHandler : FtpCommandHandler
{
private readonly ILogger<ListCommandHandler>? _logger;
/// <summary>
/// Initializes a new instance of the <see cref="ListCommandHandler"/> class.
/// </summary>
/// <param name="logger">The logger.</param>
public ListCommandHandler(
ILogger<ListCommandHandler>? logger = null)
{
_logger = logger;
}
/// <inheritdoc/>
public override async Task<IFtpResponse?> Process(FtpCommand command, CancellationToken cancellationToken)
{
await FtpContext.ServerCommandWriter
.WriteAsync(
new SendResponseServerCommand(new FtpResponse(150, T("Opening data connection."))),
cancellationToken)
.ConfigureAwait(false);
await FtpContext.ServerCommandWriter
.WriteAsync(
new DataConnectionServerCommand(
(dataConnection, ct) => ExecuteSend(dataConnection, command, ct),
command),
cancellationToken)
.ConfigureAwait(false);
return null;
}
private async Task<IFtpResponse?> ExecuteSend(IFtpDataConnection dataConnection, FtpCommand command, CancellationToken cancellationToken)
{
var encodingFeature = Connection.Features.Get<IEncodingFeature>();
// Parse arguments in a way that's compatible with broken FTP clients
var argument = new ListArguments(command.Argument);
var showHidden = argument.All;
// Instantiate the formatter
Encoding encoding;
IListFormatter formatter;
if (string.Equals(command.Name, "NLST", StringComparison.OrdinalIgnoreCase))
{
encoding = encodingFeature.NlstEncoding;
formatter = new ShortListFormatter();
}
else if (string.Equals(command.Name, "LS", StringComparison.OrdinalIgnoreCase))
{
encoding = encodingFeature.Encoding;
if (argument.PreferLong)
{
formatter = new LongListFormatter();
}
else
{
formatter = new ShortListFormatter();
}
}
else
{
encoding = encodingFeature.Encoding;
formatter = new LongListFormatter();
}
// Parse the given path to determine the mask (e.g. when information about a file was requested)
var directoriesToProcess = new Queue<DirectoryQueueItem>();
var fsFeature = Connection.Features.Get<IFileSystemFeature>();
// Use braces to avoid the definition of mask and path in the following parts
// of this function.
{
if (argument.Paths.Count != 0)
{
foreach (var searchPath in argument.Paths)
{
var mask = "*";
var path = fsFeature.Path.Clone();
var foundEntry = await fsFeature.FileSystem.SearchEntryAsync(path, searchPath, cancellationToken).ConfigureAwait(false);
if (foundEntry?.Directory == null)
{
return new FtpResponse(550, T("File system entry not found."));
}
if (!(foundEntry.Entry is IUnixDirectoryEntry dirEntry))
{
if (!string.IsNullOrEmpty(foundEntry.FileName))
{
mask = foundEntry.FileName!;
}
}
else if (!dirEntry.IsRoot)
{
path.Push(dirEntry);
}
directoriesToProcess.Enqueue(new DirectoryQueueItem(path, mask));
}
}
else
{
var mask = "*";
var path = fsFeature.Path.Clone();
directoriesToProcess.Enqueue(new DirectoryQueueItem(path, mask));
}
}
var stream = dataConnection.Stream;
using (var writer = new StreamWriter(stream, encoding, 4096, true)
{
NewLine = "\r\n",
})
{
while (directoriesToProcess.Count != 0)
{
var queueItem = directoriesToProcess.Dequeue();
var currentPath = queueItem.Path;
var mask = queueItem.Mask;
var currentDirEntry = currentPath.Count != 0 ? currentPath.Peek() : fsFeature.FileSystem.Root;
if (argument.Recursive)
{
var line = currentPath.ToDisplayString() + ":";
_logger?.LogTrace(line);
await writer.WriteLineAsync(line).ConfigureAwait(false);
}
var globOptions = new GlobOptions
{
Evaluation =
{
CaseInsensitive = fsFeature.FileSystem.FileSystemEntryComparer.Equals("a", "A"),
},
};
var glob = Glob.Parse(mask, globOptions);
var entries = await fsFeature.FileSystem.GetEntriesAsync(currentDirEntry, cancellationToken).ConfigureAwait(false);
var enumerator = new DirectoryListingEnumerator(entries, fsFeature.FileSystem, currentPath, true);
while (enumerator.MoveNext())
{
var name = enumerator.Name;
if (!enumerator.IsDotEntry)
{
if (!glob.IsMatch(name))
{
continue;
}
if (name.StartsWith(".") && !showHidden)
{
continue;
}
}
else if (mask != "*" && !glob.IsMatch(name))
{
// Ignore "." and ".." when the mask doesn't match.
continue;
}
var entry = enumerator.Entry;
if (argument.Recursive && !enumerator.IsDotEntry)
{
if (entry is IUnixDirectoryEntry dirEntry)
{
var subDirPath = currentPath.Clone();
subDirPath.Push(dirEntry);
directoriesToProcess.Enqueue(new DirectoryQueueItem(subDirPath, "*"));
}
}
var line = formatter.Format(entry, name);
_logger?.LogTrace(line);
await writer.WriteLineAsync(line).ConfigureAwait(false);
}
}
}
return null;
}
/// <summary>
/// Directory to process during recursive directory listing.
/// </summary>
private class DirectoryQueueItem
{
/// <summary>
/// Initializes a new instance of the <see cref="DirectoryQueueItem"/> class.
/// </summary>
/// <param name="path">The path to list.</param>
/// <param name="mask">The file mask to list.</param>
public DirectoryQueueItem(Stack<IUnixDirectoryEntry> path, string mask)
{
Path = path;
Mask = mask;
}
/// <summary>
/// Gets the path to list.
/// </summary>
public Stack<IUnixDirectoryEntry> Path { get; }
/// <summary>
/// Gets the file mask to list.
/// </summary>
public string Mask { get; }
}
/// <summary>
/// LIST command arguments.
/// </summary>
private class ListArguments
{
public ListArguments(string arguments)
{
var preferLong = false;
var showAll = false;
var recursive = false;
var options = new OptionSet()
{
{ "l|L", v => preferLong = v != null },
{ "r|R", v => recursive = v != null },
{ "a|A", v => showAll = v != null },
};
var args = ArgumentSource.GetArguments(new StringReader(arguments));
Paths = options.Parse(args).ToList();
PreferLong = preferLong;
All = showAll;
Recursive = recursive;
}
/// <summary>
/// Gets a value indicating whether <c>LIST</c> returns all entries (including <c>.</c> and <c>..</c>).
/// </summary>
public bool All { get; }
/// <summary>
/// Gets a value indicating whether <c>LIST</c> returns all file system entries recursively.
/// </summary>
public bool Recursive { get; }
/// <summary>
/// Gets a value indicating whether the long output is preferred.
/// </summary>
public bool PreferLong { get; }
/// <summary>
/// Gets the path argument (optionally with wildcard).
/// </summary>
public IReadOnlyCollection<string> Paths { get; }
}
}
}
| |
using System;
using System.Buffers;
using System.Buffers.Binary;
using System.IO;
#if NETCOREAPP3_1_OR_GREATER
using System.Numerics;
#endif
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using Orleans.Serialization.Session;
#if !NETCOREAPP3_1_OR_GREATER
using Orleans.Serialization.Utilities;
#endif
namespace Orleans.Serialization.Buffers
{
/// <summary>
/// Functionality for reading binary data.
/// </summary>
public abstract class ReaderInput
{
/// <summary>
/// Gets the position.
/// </summary>
/// <value>The position.</value>
public abstract long Position { get; }
/// <summary>
/// Gets the length.
/// </summary>
/// <value>The length.</value>
public abstract long Length { get; }
/// <summary>
/// Skips the specified number of bytes.
/// </summary>
/// <param name="count">The number of bytes to skip.</param>
public abstract void Skip(long count);
/// <summary>
/// Seeks to the specified position.
/// </summary>
/// <param name="position">The position.</param>
public abstract void Seek(long position);
/// <summary>
/// Reads a byte from the input.
/// </summary>
/// <returns>The byte which was read.</returns>
public abstract byte ReadByte();
/// <summary>
/// Reads a <see cref="uint"/> from the input.
/// </summary>
/// <returns>The <see cref="uint"/> which was read.</returns>
public abstract uint ReadUInt32();
/// <summary>
/// Reads a <see cref="ulong"/> from the input.
/// </summary>
/// <returns>The <see cref="ulong"/> which was read.</returns>
public abstract ulong ReadUInt64();
/// <summary>
/// Fills the destination span with data from the input.
/// </summary>
/// <param name="destination">The destination.</param>
public abstract void ReadBytes(in Span<byte> destination);
/// <summary>
/// Reads bytes from the input into the destination array.
/// </summary>
/// <param name="destination">The destination array.</param>
/// <param name="offset">The offset into the destination to start writing bytes.</param>
/// <param name="length">The number of bytes to copy into destination.</param>
public abstract void ReadBytes(byte[] destination, int offset, int length);
/// <summary>
/// Tries to read the specified number of bytes from the input.
/// </summary>
/// <param name="length">The number of bytes to read..</param>
/// <param name="bytes">The bytes which were read..</param>
/// <returns><see langword="true"/> if the number of bytes were successfully read, <see langword="false"/> otherwise.</returns>
public abstract bool TryReadBytes(int length, out ReadOnlySpan<byte> bytes);
}
internal sealed class StreamReaderInput : ReaderInput
{
[ThreadStatic]
private static byte[] Scratch;
private readonly Stream _stream;
private readonly ArrayPool<byte> _memoryPool;
public override long Position => _stream.Position;
public override long Length => _stream.Length;
public StreamReaderInput(Stream stream, ArrayPool<byte> memoryPool)
{
_stream = stream;
_memoryPool = memoryPool;
}
public override byte ReadByte()
{
var c = _stream.ReadByte();
if (c < 0)
{
ThrowInsufficientData();
}
return (byte)c;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public override void ReadBytes(in Span<byte> destination)
{
#if NETCOREAPP3_1_OR_GREATER
var count = _stream.Read(destination);
if (count < destination.Length)
{
ThrowInsufficientData();
}
#else
byte[] array = default;
try
{
array = _memoryPool.Rent(destination.Length);
var count = _stream.Read(array, 0, destination.Length);
if (count < destination.Length)
{
ThrowInsufficientData();
}
array.CopyTo(destination);
}
finally
{
if (array is object)
{
_memoryPool.Return(array);
}
}
#endif
}
public override void ReadBytes(byte[] destination, int offset, int length)
{
var count = _stream.Read(destination, offset, length);
if (count < length)
{
ThrowInsufficientData();
}
}
#if NET5_0_OR_GREATER
[SkipLocalsInit]
#endif
public override uint ReadUInt32()
{
#if NETCOREAPP3_1_OR_GREATER
Span<byte> buffer = stackalloc byte[sizeof(uint)];
ReadBytes(buffer);
return BinaryPrimitives.ReadUInt32LittleEndian(buffer);
#else
var buffer = GetScratchBuffer();
ReadBytes(buffer, 0, sizeof(uint));
return BinaryPrimitives.ReadUInt32LittleEndian(buffer.AsSpan(0, sizeof(uint)));
#endif
}
#if NET5_0_OR_GREATER
[SkipLocalsInit]
#endif
public override ulong ReadUInt64()
{
#if NETCOREAPP3_1_OR_GREATER
Span<byte> buffer = stackalloc byte[sizeof(ulong)];
ReadBytes(buffer);
return BinaryPrimitives.ReadUInt64LittleEndian(buffer);
#else
var buffer = GetScratchBuffer();
ReadBytes(buffer, 0, sizeof(ulong));
return BinaryPrimitives.ReadUInt64LittleEndian(buffer.AsSpan(0, sizeof(ulong)));
#endif
}
public override void Skip(long count) => _ = _stream.Seek(count, SeekOrigin.Current);
public override void Seek(long position) => _ = _stream.Seek(position, SeekOrigin.Begin);
public override bool TryReadBytes(int length, out ReadOnlySpan<byte> destination)
{
// Cannot get a span pointing to a stream's internal buffer.
destination = default;
return false;
}
[MethodImpl(MethodImplOptions.NoInlining)]
private static void ThrowInsufficientData() => throw new InvalidOperationException("Insufficient data present in buffer.");
private static byte[] GetScratchBuffer() => Scratch ??= new byte[1024];
}
/// <summary>
/// Helper methods for <see cref="Reader{TInput}"/>.
/// </summary>
public static class Reader
{
/// <summary>
/// Creates a reader for the provided input stream.
/// </summary>
/// <param name="stream">The stream.</param>
/// <param name="session">The session.</param>
/// <returns>A new <see cref="Reader{TInput}"/>.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Reader<ReaderInput> Create(Stream stream, SerializerSession session) => new Reader<ReaderInput>(new StreamReaderInput(stream, ArrayPool<byte>.Shared), session, 0);
/// <summary>
/// Creates a reader for the provided input data.
/// </summary>
/// <param name="sequence">The input data.</param>
/// <param name="session">The session.</param>
/// <returns>A new <see cref="Reader{TInput}"/>.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Reader<ReadOnlySequence<byte>> Create(ReadOnlySequence<byte> sequence, SerializerSession session) => new Reader<ReadOnlySequence<byte>>(sequence, session, 0);
/// <summary>
/// Creates a reader for the provided input data.
/// </summary>
/// <param name="buffer">The input data.</param>
/// <param name="session">The session.</param>
/// <returns>A new <see cref="Reader{TInput}"/>.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Reader<SpanReaderInput> Create(ReadOnlySpan<byte> buffer, SerializerSession session) => new Reader<SpanReaderInput>(buffer, session, 0);
/// <summary>
/// Creates a reader for the provided input data.
/// </summary>
/// <param name="buffer">The input data.</param>
/// <param name="session">The session.</param>
/// <returns>A new <see cref="Reader{TInput}"/>.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Reader<SpanReaderInput> Create(byte[] buffer, SerializerSession session) => new Reader<SpanReaderInput>(buffer, session, 0);
/// <summary>
/// Creates a reader for the provided input data.
/// </summary>
/// <param name="buffer">The input data.</param>
/// <param name="session">The session.</param>
/// <returns>A new <see cref="Reader{TInput}"/>.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Reader<SpanReaderInput> Create(ReadOnlyMemory<byte> buffer, SerializerSession session) => new Reader<SpanReaderInput>(buffer.Span, session, 0);
}
/// <summary>
/// Marker type for <see cref="Reader{TInput}"/> objects which operate over <see cref="ReadOnlySpan{Byte}"/> buffers.
/// </summary>
public readonly struct SpanReaderInput
{
}
/// <summary>
/// Provides functionality for parsing data from binary input.
/// </summary>
/// <typeparam name="TInput">The underlying buffer reader type.</typeparam>
public ref struct Reader<TInput>
{
private readonly static bool IsSpanInput = typeof(TInput) == typeof(SpanReaderInput);
private readonly static bool IsReadOnlySequenceInput = typeof(TInput) == typeof(ReadOnlySequence<byte>);
private readonly static bool IsReaderInput = typeof(ReaderInput).IsAssignableFrom(typeof(TInput));
private ReadOnlySpan<byte> _currentSpan;
private SequencePosition _nextSequencePosition;
private int _bufferPos;
private int _bufferSize;
private long _previousBuffersSize;
private readonly long _sequenceOffset;
private TInput _input;
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal Reader(TInput input, SerializerSession session, long globalOffset)
{
if (IsReadOnlySequenceInput)
{
ref var sequence = ref Unsafe.As<TInput, ReadOnlySequence<byte>>(ref input);
_input = input;
_nextSequencePosition = sequence.Start;
_currentSpan = sequence.First.Span;
_bufferPos = 0;
_bufferSize = _currentSpan.Length;
_previousBuffersSize = 0;
_sequenceOffset = globalOffset;
}
else if (IsReaderInput)
{
_input = input;
_nextSequencePosition = default;
_currentSpan = default;
_bufferPos = 0;
_bufferSize = default;
_previousBuffersSize = 0;
_sequenceOffset = globalOffset;
}
else
{
throw new NotSupportedException($"Type {typeof(TInput)} is not supported by this constructor");
}
Session = session;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal Reader(ReadOnlySpan<byte> input, SerializerSession session, long globalOffset)
{
if (IsSpanInput)
{
_input = default;
_nextSequencePosition = default;
_currentSpan = input;
_bufferPos = 0;
_bufferSize = _currentSpan.Length;
_previousBuffersSize = 0;
_sequenceOffset = globalOffset;
}
else
{
throw new NotSupportedException($"Type {typeof(TInput)} is not supported by this constructor");
}
Session = session;
}
/// <summary>
/// Gets the serializer session.
/// </summary>
/// <value>The serializer session.</value>
public SerializerSession Session { get; }
/// <summary>
/// Gets the current reader position.
/// </summary>
/// <value>The current position.</value>
public long Position
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get
{
if (IsReadOnlySequenceInput)
{
return _sequenceOffset + _previousBuffersSize + _bufferPos;
}
else if (IsSpanInput)
{
return _sequenceOffset + _bufferPos;
}
else if (_input is ReaderInput readerInput)
{
return readerInput.Position;
}
else
{
return ThrowNotSupportedInput<long>();
}
}
}
/// <summary>
/// Gets the input length.
/// </summary>
/// <value>The input length.</value>
public long Length
{
get
{
if (IsReadOnlySequenceInput)
{
return Unsafe.As<TInput, ReadOnlySequence<byte>>(ref _input).Length;
}
else if (IsSpanInput)
{
return _currentSpan.Length;
}
else if (_input is ReaderInput readerInput)
{
return readerInput.Length;
}
else
{
return ThrowNotSupportedInput<long>();
}
}
}
/// <summary>
/// Skips the specified number of bytes.
/// </summary>
/// <param name="count">The number of bytes to skip.</param>
public void Skip(long count)
{
if (IsReadOnlySequenceInput)
{
var end = Position + count;
while (Position < end)
{
if (Position + _bufferSize >= end)
{
_bufferPos = (int)(end - _previousBuffersSize);
}
else
{
MoveNext();
}
}
}
else if (IsSpanInput)
{
_bufferPos += (int)count;
if (_bufferPos > _currentSpan.Length || count > int.MaxValue)
{
ThrowInsufficientData();
}
}
else if (_input is ReaderInput input)
{
input.Skip(count);
}
else
{
ThrowNotSupportedInput();
}
}
/// <summary>
/// Creates a new reader beginning at the specified position.
/// </summary>
/// <param name="position">
/// The position in the input stream to fork from.
/// </param>
/// <param name="forked">
/// The forked reader instance.
/// </param>
public void ForkFrom(long position, out Reader<TInput> forked)
{
if (IsReadOnlySequenceInput)
{
ref var sequence = ref Unsafe.As<TInput, ReadOnlySequence<byte>>(ref _input);
var slicedSequence = sequence.Slice(position - _sequenceOffset);
forked = new Reader<TInput>(Unsafe.As<ReadOnlySequence<byte>, TInput>(ref slicedSequence), Session, position);
if (forked.Position != position)
{
ThrowInvalidPosition(position, forked.Position);
}
}
else if (IsSpanInput)
{
forked = new Reader<TInput>(_currentSpan.Slice((int)position), Session, position);
if (forked.Position != position || position > int.MaxValue)
{
ThrowInvalidPosition(position, forked.Position);
}
}
else if (_input is ReaderInput input)
{
input.Seek(position);
forked = new Reader<TInput>(_input, Session, 0);
if (forked.Position != position)
{
ThrowInvalidPosition(position, forked.Position);
}
}
else
{
throw new NotSupportedException($"Type {typeof(TInput)} is not supported");
}
[MethodImpl(MethodImplOptions.NoInlining)]
static void ThrowInvalidPosition(long expectedPosition, long actualPosition)
{
throw new InvalidOperationException($"Expected to arrive at position {expectedPosition} after {nameof(ForkFrom)}, but resulting position is {actualPosition}");
}
}
/// <summary>
/// Resumes the reader from the specified position after forked readers are no longer in use.
/// </summary>
/// <param name="position">
/// The position to resume reading from.
/// </param>
public void ResumeFrom(long position)
{
if (IsReadOnlySequenceInput)
{
// Nothing is required.
}
else if (IsSpanInput)
{
// Nothing is required.
}
else if (_input is ReaderInput input)
{
// Seek the input stream.
input.Seek(Position);
}
else
{
throw new NotSupportedException($"Type {typeof(TInput)} is not supported");
}
if (position != Position)
{
ThrowInvalidPosition(position, Position);
}
[MethodImpl(MethodImplOptions.NoInlining)]
static void ThrowInvalidPosition(long expectedPosition, long actualPosition)
{
throw new InvalidOperationException($"Expected to arrive at position {expectedPosition} after {nameof(ResumeFrom)}, but resulting position is {actualPosition}");
}
}
[MethodImpl(MethodImplOptions.NoInlining)]
private void MoveNext()
{
if (IsReadOnlySequenceInput)
{
ref var sequence = ref Unsafe.As<TInput, ReadOnlySequence<byte>>(ref _input);
_previousBuffersSize += _bufferSize;
// If this is the first call to MoveNext then nextSequencePosition is invalid and must be moved to the second position.
if (_nextSequencePosition.Equals(sequence.Start))
{
_ = sequence.TryGet(ref _nextSequencePosition, out _);
}
if (!sequence.TryGet(ref _nextSequencePosition, out var memory))
{
_currentSpan = memory.Span;
ThrowInsufficientData();
}
_currentSpan = memory.Span;
_bufferPos = 0;
_bufferSize = _currentSpan.Length;
}
else if (IsSpanInput)
{
ThrowInsufficientData();
}
else
{
ThrowNotSupportedInput();
}
}
/// <summary>
/// Reads a byte from the input.
/// </summary>
/// <returns>The byte which was read.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public byte ReadByte()
{
if (IsReadOnlySequenceInput || IsSpanInput)
{
var pos = _bufferPos;
var span = _currentSpan;
if ((uint)pos >= (uint)span.Length)
{
return ReadByteSlow(ref this);
}
var result = span[pos];
_bufferPos = pos + 1;
return result;
}
else if (_input is ReaderInput readerInput)
{
return readerInput.ReadByte();
}
else
{
return ThrowNotSupportedInput<byte>();
}
}
[MethodImpl(MethodImplOptions.NoInlining)]
private static byte ReadByteSlow(ref Reader<TInput> reader)
{
reader.MoveNext();
return reader._currentSpan[reader._bufferPos++];
}
/// <summary>
/// Reads an <see cref="int"/> from the input.
/// </summary>
/// <returns>The <see cref="int"/> which was read.</returns>
public int ReadInt32() => (int)ReadUInt32();
/// <summary>
/// Reads a <see cref="uint"/> from the input.
/// </summary>
/// <returns>The <see cref="uint"/> which was read.</returns>
public uint ReadUInt32()
{
if (IsReadOnlySequenceInput || IsSpanInput)
{
const int width = 4;
if (_bufferPos + width > _bufferSize)
{
return ReadSlower(ref this);
}
var result = BinaryPrimitives.ReadUInt32LittleEndian(_currentSpan.Slice(_bufferPos, width));
_bufferPos += width;
return result;
static uint ReadSlower(ref Reader<TInput> r)
{
uint b1 = r.ReadByte();
uint b2 = r.ReadByte();
uint b3 = r.ReadByte();
uint b4 = r.ReadByte();
return b1 | (b2 << 8) | (b3 << 16) | (b4 << 24);
}
}
else if (_input is ReaderInput readerInput)
{
return readerInput.ReadUInt32();
}
else
{
return ThrowNotSupportedInput<uint>();
}
}
/// <summary>
/// Reads a <see cref="long"/> from the input.
/// </summary>
/// <returns>The <see cref="long"/> which was read.</returns>
public long ReadInt64() => (long)ReadUInt64();
/// <summary>
/// Reads a <see cref="ulong"/> from the input.
/// </summary>
/// <returns>The <see cref="ulong"/> which was read.</returns>
public ulong ReadUInt64()
{
if (IsReadOnlySequenceInput || IsSpanInput)
{
const int width = 8;
if (_bufferPos + width > _bufferSize)
{
return ReadSlower(ref this);
}
var result = BinaryPrimitives.ReadUInt64LittleEndian(_currentSpan.Slice(_bufferPos, width));
_bufferPos += width;
return result;
static ulong ReadSlower(ref Reader<TInput> r)
{
ulong b1 = r.ReadByte();
ulong b2 = r.ReadByte();
ulong b3 = r.ReadByte();
ulong b4 = r.ReadByte();
ulong b5 = r.ReadByte();
ulong b6 = r.ReadByte();
ulong b7 = r.ReadByte();
ulong b8 = r.ReadByte();
return b1 | (b2 << 8) | (b3 << 16) | (b4 << 24)
| (b5 << 32) | (b6 << 40) | (b7 << 48) | (b8 << 56);
}
}
else if (_input is ReaderInput readerInput)
{
return readerInput.ReadUInt64();
}
else
{
return ThrowNotSupportedInput<uint>();
}
}
[MethodImpl(MethodImplOptions.NoInlining)]
private static void ThrowInsufficientData() => throw new InvalidOperationException("Insufficient data present in buffer.");
/// <summary>
/// Reads an array of bytes from the input.
/// </summary>
/// <param name="count">The length of the array to read.</param>
/// <returns>The array wihch was read.</returns>
public byte[] ReadBytes(uint count)
{
if (count == 0)
{
return Array.Empty<byte>();
}
if (count > 10240 && count > Length)
{
ThrowInvalidSizeException(count);
}
var bytes = new byte[count];
if (IsReadOnlySequenceInput || IsSpanInput)
{
var destination = new Span<byte>(bytes);
ReadBytes(in destination);
}
else if (_input is ReaderInput readerInput)
{
readerInput.ReadBytes(bytes, 0, (int)count);
}
return bytes;
}
/// <summary>
/// Fills <paramref name="destination"/> with bytes read from the input.
/// </summary>
/// <param name="destination">The destination.</param>
public void ReadBytes(in Span<byte> destination)
{
if (IsReadOnlySequenceInput || IsSpanInput)
{
if (_bufferPos + destination.Length <= _bufferSize)
{
_currentSpan.Slice(_bufferPos, destination.Length).CopyTo(destination);
_bufferPos += destination.Length;
return;
}
CopySlower(in destination, ref this);
static void CopySlower(in Span<byte> d, ref Reader<TInput> reader)
{
var dest = d;
while (true)
{
var writeSize = Math.Min(dest.Length, reader._currentSpan.Length - reader._bufferPos);
reader._currentSpan.Slice(reader._bufferPos, writeSize).CopyTo(dest);
reader._bufferPos += writeSize;
dest = dest.Slice(writeSize);
if (dest.Length == 0)
{
break;
}
reader.MoveNext();
}
}
}
else if (_input is ReaderInput readerInput)
{
readerInput.ReadBytes(in destination);
}
else
{
ThrowNotSupportedInput();
}
}
/// <summary>
/// Tries the read the specified number of bytes from the input.
/// </summary>
/// <param name="length">The length.</param>
/// <param name="bytes">The bytes which were read.</param>
/// <returns><see langword="true"/> if the specified number of bytes were read from the input, <see langword="false"/> otherwise.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public bool TryReadBytes(int length, out ReadOnlySpan<byte> bytes)
{
if (IsReadOnlySequenceInput || IsSpanInput)
{
if (_bufferPos + length <= _bufferSize)
{
bytes = _currentSpan.Slice(_bufferPos, length);
_bufferPos += length;
return true;
}
bytes = default;
return false;
}
else if (_input is ReaderInput readerInput)
{
return readerInput.TryReadBytes(length, out bytes);
}
else
{
bytes = default;
return ThrowNotSupportedInput<bool>();
}
}
[MethodImpl(MethodImplOptions.NoInlining)]
internal uint ReadVarUInt32NoInlining() => ReadVarUInt32();
/// <summary>
/// Reads a variable-width <see cref="uint"/> from the input.
/// </summary>
/// <returns>The <see cref="uint"/> which was read.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public unsafe uint ReadVarUInt32()
{
if (IsReadOnlySequenceInput || IsSpanInput)
{
var pos = _bufferPos;
if (!BitConverter.IsLittleEndian || pos + 8 > _currentSpan.Length)
{
return ReadVarUInt32Slow();
}
// The number of zeros in the msb position dictates the number of bytes to be read.
// Up to a maximum of 5 for a 32bit integer.
ref byte readHead = ref Unsafe.Add(ref MemoryMarshal.GetReference(_currentSpan), pos);
ulong result = Unsafe.ReadUnaligned<ulong>(ref readHead);
var bytesNeeded = BitOperations.TrailingZeroCount(result) + 1;
result >>= bytesNeeded;
_bufferPos += bytesNeeded;
// Mask off invalid data
var fullWidthReadMask = ~((ulong)bytesNeeded - 6 + 1);
var mask = ((1UL << (bytesNeeded * 7)) - 1) | fullWidthReadMask;
result &= mask;
return (uint)result;
}
else
{
return ReadVarUInt32Slow();
}
}
[MethodImpl(MethodImplOptions.NoInlining)]
private uint ReadVarUInt32Slow()
{
var header = ReadByte();
var numBytes = BitOperations.TrailingZeroCount(0x0100U | header) + 1;
// Widen to a ulong for the 5-byte case
ulong result = header;
// Read additional bytes as needed
var shiftBy = 8;
var i = numBytes;
while (--i > 0)
{
result |= (ulong)ReadByte() << shiftBy;
shiftBy += 8;
}
result >>= numBytes;
return (uint)result;
}
/// <summary>
/// Reads a variable-width <see cref="ulong"/> from the input.
/// </summary>
/// <returns>The <see cref="ulong"/> which was read.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public ulong ReadVarUInt64()
{
if (IsReadOnlySequenceInput || IsSpanInput)
{
var pos = _bufferPos;
if (!BitConverter.IsLittleEndian || pos + 10 > _currentSpan.Length)
{
return ReadVarUInt64Slow();
}
// The number of zeros in the msb position dictates the number of bytes to be read.
// Up to a maximum of 5 for a 32bit integer.
ref byte readHead = ref Unsafe.Add(ref MemoryMarshal.GetReference(_currentSpan), pos);
ulong result = Unsafe.ReadUnaligned<ulong>(ref readHead);
var bytesNeeded = BitOperations.TrailingZeroCount(result) + 1;
result >>= bytesNeeded;
_bufferPos += bytesNeeded;
ushort upper = Unsafe.ReadUnaligned<ushort>(ref Unsafe.Add(ref readHead, sizeof(ulong)));
result |= ((ulong)upper) << (64 - bytesNeeded);
// Mask off invalid data
var fullWidthReadMask = ~((ulong)bytesNeeded - 10 + 1);
var mask = ((1UL << (bytesNeeded * 7)) - 1) | fullWidthReadMask;
result &= mask;
return result;
}
else
{
return ReadVarUInt64Slow();
}
}
[MethodImpl(MethodImplOptions.NoInlining)]
private ulong ReadVarUInt64Slow()
{
var header = ReadByte();
var numBytes = BitOperations.TrailingZeroCount(0x0100U | header) + 1;
// Widen to a ulong for the 5-byte case
ulong result = header;
// Read additional bytes as needed
if (numBytes < 9)
{
var shiftBy = 8;
var i = numBytes;
while (--i > 0)
{
result |= (ulong)ReadByte() << shiftBy;
shiftBy += 8;
}
result >>= numBytes;
return result;
}
else
{
result |= (ulong)ReadByte() << 8;
// If there was more than one byte worth of trailing zeros, read again now that we have more data.
numBytes = BitOperations.TrailingZeroCount(result) + 1;
if (numBytes == 9)
{
result |= (ulong)ReadByte() << 16;
result |= (ulong)ReadByte() << 24;
result |= (ulong)ReadByte() << 32;
result |= (ulong)ReadByte() << 40;
result |= (ulong)ReadByte() << 48;
result |= (ulong)ReadByte() << 56;
result >>= 9;
var upper = (ushort)ReadByte();
result |= ((ulong)upper) << (64 - 9);
return result;
}
else if (numBytes == 10)
{
result |= (ulong)ReadByte() << 16;
result |= (ulong)ReadByte() << 24;
result |= (ulong)ReadByte() << 32;
result |= (ulong)ReadByte() << 40;
result |= (ulong)ReadByte() << 48;
result |= (ulong)ReadByte() << 56;
result >>= 10;
var upper = (ushort)(ReadByte() | (ushort)(ReadByte() << 8));
result |= ((ulong)upper) << (64 - 10);
return result;
}
}
return ExceptionHelper.ThrowArgumentOutOfRange<ulong>("value");
}
[MethodImpl(MethodImplOptions.NoInlining)]
private static T ThrowNotSupportedInput<T>() => throw new NotSupportedException($"Type {typeof(TInput)} is not supported");
[MethodImpl(MethodImplOptions.NoInlining)]
private static void ThrowNotSupportedInput() => throw new NotSupportedException($"Type {typeof(TInput)} is not supported");
[MethodImpl(MethodImplOptions.NoInlining)]
private static void ThrowInvalidSizeException(uint length) => throw new IndexOutOfRangeException(
$"Declared length of {typeof(byte[])}, {length}, is greater than total length of input.");
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using CocosSharp;
using Microsoft.Xna.Framework;
namespace tests
{
public class OrientationTest : CCLayer
{
static int MAX_LAYER = 1;
static int sceneIdx = -1;
public static CCDisplayOrientation s_currentOrientation = CCDisplayOrientation.LandscapeLeft;
public OrientationTest()
{
InitOrientationTest();
}
public static CCLayer CreateTestCaseLayer(int index)
{
switch (index)
{
case 0:
{
Orientation1 pRet = new Orientation1();
return pRet;
}
default:
return null;
}
}
public static CCLayer NextOrientationTestCase()
{
sceneIdx++;
sceneIdx = sceneIdx % MAX_LAYER;
return CreateTestCaseLayer(sceneIdx);
}
public static CCLayer BackOrientationTestCase()
{
sceneIdx--;
if (sceneIdx < 0)
sceneIdx += MAX_LAYER;
return CreateTestCaseLayer(sceneIdx);
}
public static CCLayer RestartOrientationTestCase()
{
return CreateTestCaseLayer(sceneIdx);
}
private bool InitOrientationTest ()
{
bool bRet = false;
do
{
CCSize s = Layer.VisibleBoundsWorldspace.Size;
CCLabelTtf label = new CCLabelTtf(title(), "Arial", 26);
AddChild(label, 1);
label.Position = new CCPoint(s.Width / 2, s.Height - 50);
string sSubtitle = subtitle();
if (sSubtitle.Length > 0)
{
CCLabelTtf l = new CCLabelTtf(sSubtitle, "Arial", 16);
AddChild(l, 1);
l.Position = new CCPoint(s.Width / 2, s.Height - 80);
}
CCMenuItemImage item1 = new CCMenuItemImage(TestResource.s_pPathB1, TestResource.s_pPathB2, BackCallback);
CCMenuItemImage item2 = new CCMenuItemImage(TestResource.s_pPathR1, TestResource.s_pPathR2, RestartCallback);
CCMenuItemImage item3 = new CCMenuItemImage(TestResource.s_pPathF1, TestResource.s_pPathF2, NextCallback);
CCMenu menu = new CCMenu(item1, item2, item3);
menu.Position = new CCPoint();
item1.Position = new CCPoint(s.Width / 2 - 100, 30);
item2.Position = new CCPoint(s.Width / 2, 30);
item3.Position = new CCPoint(s.Width / 2 + 100, 30);
bRet = true;
} while (false);
return bRet;
}
public void RestartCallback(object pSender)
{
CCScene s = new OrientationTestScene();
s.AddChild(RestartOrientationTestCase());
Scene.Director.ReplaceScene(s);
}
public void NextCallback(object pSender)
{
CCScene s = new OrientationTestScene();
s.AddChild(NextOrientationTestCase());
Scene.Director.ReplaceScene(s);
}
public void BackCallback(object pSender)
{
CCScene s = new OrientationTestScene();
s.AddChild(BackOrientationTestCase());
Scene.Director.ReplaceScene(s);
}
public virtual string title()
{
return "No title";
}
public virtual string subtitle()
{
return "";
}
}
public class Orientation1 : OrientationTest
{
public Orientation1()
{
InitOrientation1();
}
private bool InitOrientation1()
{
bool bRet = false;
do
{
// Register Touch Event
var touchListener = new CCEventListenerTouchAllAtOnce();
touchListener.OnTouchesEnded = onTouchesEnded;
AddEventListener(touchListener);
CCSize s = Layer.VisibleBoundsWorldspace.Size;
CCMenuItem item = new CCMenuItemFont("Rotate Device", RotateDevice);
CCMenu menu = new CCMenu(item);
menu.Position = new CCPoint(s.Width / 2, s.Height / 2);
AddChild(menu);
bRet = true;
} while (false);
return bRet;
}
public void NewOrientation()
{
switch (s_currentOrientation)
{
case CCDisplayOrientation.LandscapeLeft:
s_currentOrientation = CCDisplayOrientation.Portrait;
break;
case CCDisplayOrientation.Portrait:
s_currentOrientation = CCDisplayOrientation.LandscapeRight;
break;
case CCDisplayOrientation.LandscapeRight:
s_currentOrientation = CCDisplayOrientation.LandscapeLeft;
break;
}
// CCDrawManager.SharedDrawManager.SetOrientation(s_currentOrientation);
}
public void RotateDevice(object pSender)
{
NewOrientation();
RestartCallback(null);
}
void onTouchesEnded(List<CCTouch> touches, CCEvent touchEvent)
{
foreach (CCTouch touch in touches)
{
if (touch == null)
break;
CCPoint a = touch.LocationOnScreen;
//CCLog("(%d,%d) == (%d,%d)", (int) a.x, (int)a.y, (int)b.x, (int)b.y );
//CCLog.Log("({0},{1}) == ({2},{3})", (int)a.X, (int)a.Y, (int)b.X, (int)b.Y);
}
}
public override string title()
{
return "Testing conversion";
}
public override string subtitle()
{
return "Tap screen and see the debug console";
}
}
public class OrientationTestScene : TestScene
{
protected override void NextTestCase()
{
}
protected override void PreviousTestCase()
{
}
protected override void RestTestCase()
{
}
public override void runThisTest()
{
OrientationTest.s_currentOrientation = CCDisplayOrientation.LandscapeLeft;
CCLayer pLayer = OrientationTest.NextOrientationTestCase();
AddChild(pLayer);
Scene.Director.ReplaceScene(this);
}
public override void MainMenuCallback(object pSender)
{
//CCDrawManager.SharedDrawManager.GraphicsDevice.PresentationParameters.DisplayOrientation = DisplayOrientation.LandscapeLeft;
base.MainMenuCallback(pSender);
}
}
}
| |
namespace android.telephony
{
[global::MonoJavaBridge.JavaClass()]
public partial class PhoneNumberUtils : java.lang.Object
{
internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
static PhoneNumberUtils()
{
InitJNI();
}
protected PhoneNumberUtils(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
{
}
internal static global::MonoJavaBridge.MethodId _compare7363;
public static bool compare(java.lang.String arg0, java.lang.String arg1)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
return @__env.CallStaticBooleanMethod(android.telephony.PhoneNumberUtils.staticClass, global::android.telephony.PhoneNumberUtils._compare7363, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
internal static global::MonoJavaBridge.MethodId _compare7364;
public static bool compare(android.content.Context arg0, java.lang.String arg1, java.lang.String arg2)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
return @__env.CallStaticBooleanMethod(android.telephony.PhoneNumberUtils.staticClass, global::android.telephony.PhoneNumberUtils._compare7364, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2));
}
internal static global::MonoJavaBridge.MethodId _isISODigit7365;
public static bool isISODigit(char arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
return @__env.CallStaticBooleanMethod(android.telephony.PhoneNumberUtils.staticClass, global::android.telephony.PhoneNumberUtils._isISODigit7365, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _is12Key7366;
public static bool is12Key(char arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
return @__env.CallStaticBooleanMethod(android.telephony.PhoneNumberUtils.staticClass, global::android.telephony.PhoneNumberUtils._is12Key7366, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _isDialable7367;
public static bool isDialable(char arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
return @__env.CallStaticBooleanMethod(android.telephony.PhoneNumberUtils.staticClass, global::android.telephony.PhoneNumberUtils._isDialable7367, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _isReallyDialable7368;
public static bool isReallyDialable(char arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
return @__env.CallStaticBooleanMethod(android.telephony.PhoneNumberUtils.staticClass, global::android.telephony.PhoneNumberUtils._isReallyDialable7368, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _isNonSeparator7369;
public static bool isNonSeparator(char arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
return @__env.CallStaticBooleanMethod(android.telephony.PhoneNumberUtils.staticClass, global::android.telephony.PhoneNumberUtils._isNonSeparator7369, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _isStartsPostDial7370;
public static bool isStartsPostDial(char arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
return @__env.CallStaticBooleanMethod(android.telephony.PhoneNumberUtils.staticClass, global::android.telephony.PhoneNumberUtils._isStartsPostDial7370, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _getNumberFromIntent7371;
public static global::java.lang.String getNumberFromIntent(android.content.Intent arg0, android.content.Context arg1)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallStaticObjectMethod(android.telephony.PhoneNumberUtils.staticClass, global::android.telephony.PhoneNumberUtils._getNumberFromIntent7371, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1))) as java.lang.String;
}
internal static global::MonoJavaBridge.MethodId _extractNetworkPortion7372;
public static global::java.lang.String extractNetworkPortion(java.lang.String arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallStaticObjectMethod(android.telephony.PhoneNumberUtils.staticClass, global::android.telephony.PhoneNumberUtils._extractNetworkPortion7372, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.lang.String;
}
internal static global::MonoJavaBridge.MethodId _stripSeparators7373;
public static global::java.lang.String stripSeparators(java.lang.String arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallStaticObjectMethod(android.telephony.PhoneNumberUtils.staticClass, global::android.telephony.PhoneNumberUtils._stripSeparators7373, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.lang.String;
}
internal static global::MonoJavaBridge.MethodId _extractPostDialPortion7374;
public static global::java.lang.String extractPostDialPortion(java.lang.String arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallStaticObjectMethod(android.telephony.PhoneNumberUtils.staticClass, global::android.telephony.PhoneNumberUtils._extractPostDialPortion7374, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.lang.String;
}
internal static global::MonoJavaBridge.MethodId _toCallerIDMinMatch7375;
public static global::java.lang.String toCallerIDMinMatch(java.lang.String arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallStaticObjectMethod(android.telephony.PhoneNumberUtils.staticClass, global::android.telephony.PhoneNumberUtils._toCallerIDMinMatch7375, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.lang.String;
}
internal static global::MonoJavaBridge.MethodId _getStrippedReversed7376;
public static global::java.lang.String getStrippedReversed(java.lang.String arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallStaticObjectMethod(android.telephony.PhoneNumberUtils.staticClass, global::android.telephony.PhoneNumberUtils._getStrippedReversed7376, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.lang.String;
}
internal static global::MonoJavaBridge.MethodId _stringFromStringAndTOA7377;
public static global::java.lang.String stringFromStringAndTOA(java.lang.String arg0, int arg1)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallStaticObjectMethod(android.telephony.PhoneNumberUtils.staticClass, global::android.telephony.PhoneNumberUtils._stringFromStringAndTOA7377, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1))) as java.lang.String;
}
internal static global::MonoJavaBridge.MethodId _toaFromString7378;
public static int toaFromString(java.lang.String arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
return @__env.CallStaticIntMethod(android.telephony.PhoneNumberUtils.staticClass, global::android.telephony.PhoneNumberUtils._toaFromString7378, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _calledPartyBCDToString7379;
public static global::java.lang.String calledPartyBCDToString(byte[] arg0, int arg1, int arg2)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallStaticObjectMethod(android.telephony.PhoneNumberUtils.staticClass, global::android.telephony.PhoneNumberUtils._calledPartyBCDToString7379, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2))) as java.lang.String;
}
internal static global::MonoJavaBridge.MethodId _calledPartyBCDFragmentToString7380;
public static global::java.lang.String calledPartyBCDFragmentToString(byte[] arg0, int arg1, int arg2)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallStaticObjectMethod(android.telephony.PhoneNumberUtils.staticClass, global::android.telephony.PhoneNumberUtils._calledPartyBCDFragmentToString7380, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2))) as java.lang.String;
}
internal static global::MonoJavaBridge.MethodId _isWellFormedSmsAddress7381;
public static bool isWellFormedSmsAddress(java.lang.String arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
return @__env.CallStaticBooleanMethod(android.telephony.PhoneNumberUtils.staticClass, global::android.telephony.PhoneNumberUtils._isWellFormedSmsAddress7381, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _isGlobalPhoneNumber7382;
public static bool isGlobalPhoneNumber(java.lang.String arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
return @__env.CallStaticBooleanMethod(android.telephony.PhoneNumberUtils.staticClass, global::android.telephony.PhoneNumberUtils._isGlobalPhoneNumber7382, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _networkPortionToCalledPartyBCD7383;
public static byte[] networkPortionToCalledPartyBCD(java.lang.String arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
return global::MonoJavaBridge.JavaBridge.WrapJavaArrayObject<byte>(@__env.CallStaticObjectMethod(android.telephony.PhoneNumberUtils.staticClass, global::android.telephony.PhoneNumberUtils._networkPortionToCalledPartyBCD7383, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as byte[];
}
internal static global::MonoJavaBridge.MethodId _networkPortionToCalledPartyBCDWithLength7384;
public static byte[] networkPortionToCalledPartyBCDWithLength(java.lang.String arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
return global::MonoJavaBridge.JavaBridge.WrapJavaArrayObject<byte>(@__env.CallStaticObjectMethod(android.telephony.PhoneNumberUtils.staticClass, global::android.telephony.PhoneNumberUtils._networkPortionToCalledPartyBCDWithLength7384, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as byte[];
}
internal static global::MonoJavaBridge.MethodId _numberToCalledPartyBCD7385;
public static byte[] numberToCalledPartyBCD(java.lang.String arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
return global::MonoJavaBridge.JavaBridge.WrapJavaArrayObject<byte>(@__env.CallStaticObjectMethod(android.telephony.PhoneNumberUtils.staticClass, global::android.telephony.PhoneNumberUtils._numberToCalledPartyBCD7385, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as byte[];
}
internal static global::MonoJavaBridge.MethodId _formatNumber7386;
public static global::java.lang.String formatNumber(java.lang.String arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallStaticObjectMethod(android.telephony.PhoneNumberUtils.staticClass, global::android.telephony.PhoneNumberUtils._formatNumber7386, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.lang.String;
}
internal static global::MonoJavaBridge.MethodId _formatNumber7387;
public static void formatNumber(android.text.Editable arg0, int arg1)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
@__env.CallStaticVoidMethod(android.telephony.PhoneNumberUtils.staticClass, global::android.telephony.PhoneNumberUtils._formatNumber7387, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
internal static global::MonoJavaBridge.MethodId _getFormatTypeForLocale7388;
public static int getFormatTypeForLocale(java.util.Locale arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
return @__env.CallStaticIntMethod(android.telephony.PhoneNumberUtils.staticClass, global::android.telephony.PhoneNumberUtils._getFormatTypeForLocale7388, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _formatNanpNumber7389;
public static void formatNanpNumber(android.text.Editable arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
@__env.CallStaticVoidMethod(android.telephony.PhoneNumberUtils.staticClass, global::android.telephony.PhoneNumberUtils._formatNanpNumber7389, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _formatJapaneseNumber7390;
public static void formatJapaneseNumber(android.text.Editable arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
@__env.CallStaticVoidMethod(android.telephony.PhoneNumberUtils.staticClass, global::android.telephony.PhoneNumberUtils._formatJapaneseNumber7390, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _isEmergencyNumber7391;
public static bool isEmergencyNumber(java.lang.String arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
return @__env.CallStaticBooleanMethod(android.telephony.PhoneNumberUtils.staticClass, global::android.telephony.PhoneNumberUtils._isEmergencyNumber7391, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _convertKeypadLettersToDigits7392;
public static global::java.lang.String convertKeypadLettersToDigits(java.lang.String arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallStaticObjectMethod(android.telephony.PhoneNumberUtils.staticClass, global::android.telephony.PhoneNumberUtils._convertKeypadLettersToDigits7392, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.lang.String;
}
internal static global::MonoJavaBridge.MethodId _PhoneNumberUtils7393;
public PhoneNumberUtils() : base(global::MonoJavaBridge.JNIEnv.ThreadEnv)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.telephony.PhoneNumberUtils.staticClass, global::android.telephony.PhoneNumberUtils._PhoneNumberUtils7393);
Init(@__env, handle);
}
public static char PAUSE
{
get
{
return ',';
}
}
public static char WAIT
{
get
{
return ';';
}
}
public static char WILD
{
get
{
return 'N';
}
}
public static int TOA_International
{
get
{
return 145;
}
}
public static int TOA_Unknown
{
get
{
return 129;
}
}
public static int FORMAT_UNKNOWN
{
get
{
return 0;
}
}
public static int FORMAT_NANP
{
get
{
return 1;
}
}
public static int FORMAT_JAPAN
{
get
{
return 2;
}
}
private static void InitJNI()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::android.telephony.PhoneNumberUtils.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/telephony/PhoneNumberUtils"));
global::android.telephony.PhoneNumberUtils._compare7363 = @__env.GetStaticMethodIDNoThrow(global::android.telephony.PhoneNumberUtils.staticClass, "compare", "(Ljava/lang/String;Ljava/lang/String;)Z");
global::android.telephony.PhoneNumberUtils._compare7364 = @__env.GetStaticMethodIDNoThrow(global::android.telephony.PhoneNumberUtils.staticClass, "compare", "(Landroid/content/Context;Ljava/lang/String;Ljava/lang/String;)Z");
global::android.telephony.PhoneNumberUtils._isISODigit7365 = @__env.GetStaticMethodIDNoThrow(global::android.telephony.PhoneNumberUtils.staticClass, "isISODigit", "(C)Z");
global::android.telephony.PhoneNumberUtils._is12Key7366 = @__env.GetStaticMethodIDNoThrow(global::android.telephony.PhoneNumberUtils.staticClass, "is12Key", "(C)Z");
global::android.telephony.PhoneNumberUtils._isDialable7367 = @__env.GetStaticMethodIDNoThrow(global::android.telephony.PhoneNumberUtils.staticClass, "isDialable", "(C)Z");
global::android.telephony.PhoneNumberUtils._isReallyDialable7368 = @__env.GetStaticMethodIDNoThrow(global::android.telephony.PhoneNumberUtils.staticClass, "isReallyDialable", "(C)Z");
global::android.telephony.PhoneNumberUtils._isNonSeparator7369 = @__env.GetStaticMethodIDNoThrow(global::android.telephony.PhoneNumberUtils.staticClass, "isNonSeparator", "(C)Z");
global::android.telephony.PhoneNumberUtils._isStartsPostDial7370 = @__env.GetStaticMethodIDNoThrow(global::android.telephony.PhoneNumberUtils.staticClass, "isStartsPostDial", "(C)Z");
global::android.telephony.PhoneNumberUtils._getNumberFromIntent7371 = @__env.GetStaticMethodIDNoThrow(global::android.telephony.PhoneNumberUtils.staticClass, "getNumberFromIntent", "(Landroid/content/Intent;Landroid/content/Context;)Ljava/lang/String;");
global::android.telephony.PhoneNumberUtils._extractNetworkPortion7372 = @__env.GetStaticMethodIDNoThrow(global::android.telephony.PhoneNumberUtils.staticClass, "extractNetworkPortion", "(Ljava/lang/String;)Ljava/lang/String;");
global::android.telephony.PhoneNumberUtils._stripSeparators7373 = @__env.GetStaticMethodIDNoThrow(global::android.telephony.PhoneNumberUtils.staticClass, "stripSeparators", "(Ljava/lang/String;)Ljava/lang/String;");
global::android.telephony.PhoneNumberUtils._extractPostDialPortion7374 = @__env.GetStaticMethodIDNoThrow(global::android.telephony.PhoneNumberUtils.staticClass, "extractPostDialPortion", "(Ljava/lang/String;)Ljava/lang/String;");
global::android.telephony.PhoneNumberUtils._toCallerIDMinMatch7375 = @__env.GetStaticMethodIDNoThrow(global::android.telephony.PhoneNumberUtils.staticClass, "toCallerIDMinMatch", "(Ljava/lang/String;)Ljava/lang/String;");
global::android.telephony.PhoneNumberUtils._getStrippedReversed7376 = @__env.GetStaticMethodIDNoThrow(global::android.telephony.PhoneNumberUtils.staticClass, "getStrippedReversed", "(Ljava/lang/String;)Ljava/lang/String;");
global::android.telephony.PhoneNumberUtils._stringFromStringAndTOA7377 = @__env.GetStaticMethodIDNoThrow(global::android.telephony.PhoneNumberUtils.staticClass, "stringFromStringAndTOA", "(Ljava/lang/String;I)Ljava/lang/String;");
global::android.telephony.PhoneNumberUtils._toaFromString7378 = @__env.GetStaticMethodIDNoThrow(global::android.telephony.PhoneNumberUtils.staticClass, "toaFromString", "(Ljava/lang/String;)I");
global::android.telephony.PhoneNumberUtils._calledPartyBCDToString7379 = @__env.GetStaticMethodIDNoThrow(global::android.telephony.PhoneNumberUtils.staticClass, "calledPartyBCDToString", "([BII)Ljava/lang/String;");
global::android.telephony.PhoneNumberUtils._calledPartyBCDFragmentToString7380 = @__env.GetStaticMethodIDNoThrow(global::android.telephony.PhoneNumberUtils.staticClass, "calledPartyBCDFragmentToString", "([BII)Ljava/lang/String;");
global::android.telephony.PhoneNumberUtils._isWellFormedSmsAddress7381 = @__env.GetStaticMethodIDNoThrow(global::android.telephony.PhoneNumberUtils.staticClass, "isWellFormedSmsAddress", "(Ljava/lang/String;)Z");
global::android.telephony.PhoneNumberUtils._isGlobalPhoneNumber7382 = @__env.GetStaticMethodIDNoThrow(global::android.telephony.PhoneNumberUtils.staticClass, "isGlobalPhoneNumber", "(Ljava/lang/String;)Z");
global::android.telephony.PhoneNumberUtils._networkPortionToCalledPartyBCD7383 = @__env.GetStaticMethodIDNoThrow(global::android.telephony.PhoneNumberUtils.staticClass, "networkPortionToCalledPartyBCD", "(Ljava/lang/String;)[B");
global::android.telephony.PhoneNumberUtils._networkPortionToCalledPartyBCDWithLength7384 = @__env.GetStaticMethodIDNoThrow(global::android.telephony.PhoneNumberUtils.staticClass, "networkPortionToCalledPartyBCDWithLength", "(Ljava/lang/String;)[B");
global::android.telephony.PhoneNumberUtils._numberToCalledPartyBCD7385 = @__env.GetStaticMethodIDNoThrow(global::android.telephony.PhoneNumberUtils.staticClass, "numberToCalledPartyBCD", "(Ljava/lang/String;)[B");
global::android.telephony.PhoneNumberUtils._formatNumber7386 = @__env.GetStaticMethodIDNoThrow(global::android.telephony.PhoneNumberUtils.staticClass, "formatNumber", "(Ljava/lang/String;)Ljava/lang/String;");
global::android.telephony.PhoneNumberUtils._formatNumber7387 = @__env.GetStaticMethodIDNoThrow(global::android.telephony.PhoneNumberUtils.staticClass, "formatNumber", "(Landroid/text/Editable;I)V");
global::android.telephony.PhoneNumberUtils._getFormatTypeForLocale7388 = @__env.GetStaticMethodIDNoThrow(global::android.telephony.PhoneNumberUtils.staticClass, "getFormatTypeForLocale", "(Ljava/util/Locale;)I");
global::android.telephony.PhoneNumberUtils._formatNanpNumber7389 = @__env.GetStaticMethodIDNoThrow(global::android.telephony.PhoneNumberUtils.staticClass, "formatNanpNumber", "(Landroid/text/Editable;)V");
global::android.telephony.PhoneNumberUtils._formatJapaneseNumber7390 = @__env.GetStaticMethodIDNoThrow(global::android.telephony.PhoneNumberUtils.staticClass, "formatJapaneseNumber", "(Landroid/text/Editable;)V");
global::android.telephony.PhoneNumberUtils._isEmergencyNumber7391 = @__env.GetStaticMethodIDNoThrow(global::android.telephony.PhoneNumberUtils.staticClass, "isEmergencyNumber", "(Ljava/lang/String;)Z");
global::android.telephony.PhoneNumberUtils._convertKeypadLettersToDigits7392 = @__env.GetStaticMethodIDNoThrow(global::android.telephony.PhoneNumberUtils.staticClass, "convertKeypadLettersToDigits", "(Ljava/lang/String;)Ljava/lang/String;");
global::android.telephony.PhoneNumberUtils._PhoneNumberUtils7393 = @__env.GetMethodIDNoThrow(global::android.telephony.PhoneNumberUtils.staticClass, "<init>", "()V");
}
}
}
| |
/*
* Copyright (c) InWorldz Halcyon Developers
* Copyright (c) Contributors, http://opensimulator.org/
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the 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.Net;
using System.Threading;
using log4net;
using OpenSim.Framework;
using OpenMetaverse;
using OpenMetaverse.Packets;
using TokenBucket = OpenSim.Region.ClientStack.LindenUDP.TokenBucket;
namespace OpenSim.Region.ClientStack.LindenUDP
{
#region Delegates
/// <summary>
/// Fired when updated networking stats are produced for this client
/// </summary>
/// <param name="inPackets">Number of incoming packets received since this
/// event was last fired</param>
/// <param name="outPackets">Number of outgoing packets sent since this
/// event was last fired</param>
/// <param name="unAckedBytes">Current total number of bytes in packets we
/// are waiting on ACKs for</param>
public delegate void PacketStats(int inPackets, int outPackets, int unAckedBytes);
/// <summary>
/// Fired when the queue for one or more packet categories is empty. This
/// event can be hooked to put more data on the empty queues
/// </summary>
/// <param name="category">Categories of the packet queues that are empty</param>
public delegate void QueueEmpty(ThrottleOutPacketTypeFlags categories);
#endregion Delegates
/// <summary>
/// Tracks state for a client UDP connection and provides client-specific methods
/// </summary>
public sealed class LLUDPClient
{
// TODO: Make this a config setting
/// <summary>Percentage of the task throttle category that is allocated to avatar and prim
/// state updates</summary>
const float STATE_TASK_PERCENTAGE = 0.8f;
/// <summary>
/// 4 MB maximum outbound queue per avatar after this amount is reached non-reliable packets will
/// be dropped
/// </summary>
const int MAX_TOTAL_QUEUE_SIZE = 4 * 1024 * 1024;
private static readonly ILog m_log = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
/// <summary>The number of packet categories to throttle on. If a throttle category is added
/// or removed, this number must also change</summary>
public const int THROTTLE_CATEGORY_COUNT = 8;
/// <summary>Fired when updated networking stats are produced for this client</summary>
public event PacketStats OnPacketStats;
/// <summary>Fired when the queue for a packet category is empty. This event can be
/// hooked to put more data on the empty queue</summary>
public event QueueEmpty OnQueueEmpty;
/// <summary>AgentID for this client</summary>
public readonly UUID AgentID;
/// <summary>The remote address of the connected client</summary>
public readonly IPEndPoint RemoteEndPoint;
/// <summary>Circuit code that this client is connected on</summary>
public readonly uint CircuitCode;
/// <summary>Sequence numbers of packets we've received (for duplicate checking)</summary>
public readonly IncomingPacketHistoryCollection PacketArchive = new IncomingPacketHistoryCollection(384);
/// <summary>Packets we have sent that need to be ACKed by the client</summary>
public readonly UnackedPacketCollection NeedAcks;
/// <summary>ACKs that are queued up, waiting to be sent to the client</summary>
public readonly OpenSim.Framework.LocklessQueue<uint> PendingAcks = new OpenSim.Framework.LocklessQueue<uint>();
/// <summary>Current packet sequence number</summary>
public int CurrentSequence;
/// <summary>Current ping sequence number</summary>
public byte CurrentPingSequence;
/// <summary>True when this connection is alive, otherwise false</summary>
public bool IsConnected = true;
/// <summary>True when this connection is paused, otherwise false</summary>
public bool IsPaused;
/// <summary>Environment.TickCount when the last packet was received for this client</summary>
public int TickLastPacketReceived;
/// <summary>Smoothed round-trip time. A smoothed average of the round-trip time for sending a
/// reliable packet to the client and receiving an ACK</summary>
public float SRTT;
/// <summary>Round-trip time variance. Measures the consistency of round-trip times</summary>
public float RTTVAR;
/// <summary>Retransmission timeout. Packets that have not been acknowledged in this number of
/// milliseconds or longer will be resent</summary>
/// <remarks>Calculated from <seealso cref="SRTT"/> and <seealso cref="RTTVAR"/> using the
/// guidelines in RFC 2988</remarks>
public int RTO;
/// <summary>Number of bytes received since the last acknowledgement was sent out. This is used
/// to loosely follow the TCP delayed ACK algorithm in RFC 1122 (4.2.3.2)</summary>
public int BytesSinceLastACK;
/// <summary>Number of packets received from this client</summary>
public int PacketsReceived;
/// <summary>Number of packets sent to this client</summary>
public int PacketsSent;
/// <summary>Total byte count of unacked packets sent to this client</summary>
public int UnackedBytes;
/// <summary>Total number of received packets that we have reported to the OnPacketStats event(s)</summary>
private int m_packetsReceivedReported;
/// <summary>Total number of sent packets that we have reported to the OnPacketStats event(s)</summary>
private int m_packetsSentReported;
/// <summary>Holds the Environment.TickCount value of when the next OnQueueEmpty can be fired</summary>
private int m_nextOnQueueEmpty = 1;
/// <summary>Throttle bucket for this agent's connection</summary>
private readonly TokenBucket m_throttle;
/// <summary>Throttle buckets for each packet category</summary>
private readonly TokenBucket[] m_throttleCategories;
/// <summary>Outgoing queues for throttled packets</summary>
private readonly OpenSim.Framework.LocklessQueue<OutgoingPacket>[] m_packetOutboxes = new OpenSim.Framework.LocklessQueue<OutgoingPacket>[THROTTLE_CATEGORY_COUNT];
/// <summary>A container that can hold one packet for each outbox, used to store
/// dequeued packets that are being held for throttling</summary>
private readonly OutgoingPacket[] m_nextPackets = new OutgoingPacket[THROTTLE_CATEGORY_COUNT];
/// <summary>A reference to the LLUDPServer that is managing this client</summary>
private readonly LLUDPServer m_udpServer;
/// <summary>Caches packed throttle information</summary>
private UnpackedThrottles m_unpackedThrottles;
private int m_defaultRTO = 3000;
private int m_maxRTO = 60000;
/// <summary>
/// The current size of all packets on the outbound queue
/// </summary>
private int _currentOutboundQueueSize = 0;
/// <summary>
/// Records the last time an adjustment was made to the packet throttles
/// </summary>
private DateTime _lastDynamicThrottleAdjustment = DateTime.Now;
/// <summary>
/// The minmum amount of time to wait to report repeated dropped packets in seconds
/// </summary>
const int MIN_DROP_REPORT_INTERVAL = 60;
/// <summary>
/// The last time a packet drop was reported to the console
/// </summary>
private DateTime _lastDropReport = DateTime.Now;
private object _dropReportLock = new object();
/// <summary>
/// Random number generator to select random streams to start sending data on
/// during the dequeue phase
/// </summary>
private Random _rand = new Random();
/// <summary>
/// keeps tract of what buckets were empty on the last dequeue to inform
/// the throttle adjustment code
/// </summary>
private List<int> _emptyBucketHints = new List<int>();
/// <summary>
/// The current size of our queue
/// </summary>
public int OutboundQueueSize
{
get { return _currentOutboundQueueSize; }
}
/// <summary>
/// Default constructor
/// </summary>
/// <param name="server">Reference to the UDP server this client is connected to</param>
/// <param name="rates">Default throttling rates and maximum throttle limits</param>
/// <param name="parentThrottle">Parent HTB (hierarchical token bucket)
/// that the child throttles will be governed by</param>
/// <param name="circuitCode">Circuit code for this connection</param>
/// <param name="agentID">AgentID for the connected agent</param>
/// <param name="remoteEndPoint">Remote endpoint for this connection</param>
public LLUDPClient(LLUDPServer server, ThrottleRates rates, TokenBucket parentThrottle, uint circuitCode, UUID agentID, IPEndPoint remoteEndPoint, int defaultRTO, int maxRTO)
{
AgentID = agentID;
RemoteEndPoint = remoteEndPoint;
CircuitCode = circuitCode;
m_udpServer = server;
if (defaultRTO != 0)
m_defaultRTO = defaultRTO;
if (maxRTO != 0)
m_maxRTO = maxRTO;
// Create a token bucket throttle for this client that has the scene token bucket as a parent
m_throttle = new TokenBucket(parentThrottle, rates.TotalLimit, rates.Total);
// Create an array of token buckets for this clients different throttle categories
m_throttleCategories = new TokenBucket[THROTTLE_CATEGORY_COUNT];
for (int i = 0; i < THROTTLE_CATEGORY_COUNT; i++)
{
ThrottleOutPacketType type = (ThrottleOutPacketType)i;
// Initialize the packet outboxes, where packets sit while they are waiting for tokens
m_packetOutboxes[i] = new OpenSim.Framework.LocklessQueue<OutgoingPacket>();
// Initialize the token buckets that control the throttling for each category
m_throttleCategories[i] = new TokenBucket(m_throttle, rates.GetLimit(type), rates.GetRate(type));
}
// Default the retransmission timeout to three seconds
RTO = m_defaultRTO;
// Initialize this to a sane value to prevent early disconnects
TickLastPacketReceived = Environment.TickCount & Int32.MaxValue;
NeedAcks = new UnackedPacketCollection(server.ByteBufferPool);
}
/// <summary>
/// Shuts down this client connection
/// </summary>
public void Shutdown()
{
IsConnected = false;
for (int i = 0; i < THROTTLE_CATEGORY_COUNT; i++)
{
m_packetOutboxes[i].Clear();
m_nextPackets[i] = null;
}
OnPacketStats = null;
OnQueueEmpty = null;
}
/// <summary>
/// Modifies the UDP throttles
/// </summary>
/// <param name="info">New throttling values</param>
public void SetClientInfo(ClientInfo info)
{
// TODO: Allowing throttles to be manually set from this function seems like a reasonable
// idea. On the other hand, letting external code manipulate our ACK accounting is not
// going to happen
throw new NotImplementedException();
}
public string GetStats()
{
// TODO: ???
return string.Format("{0,7} {1,7} {2,7} {3,7} {4,7} {5,7} {6,7} {7,7} {8,7} {9,7}",
0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
}
public void SendPacketStats()
{
PacketStats callback = OnPacketStats;
if (callback != null)
{
int newPacketsReceived = PacketsReceived - m_packetsReceivedReported;
int newPacketsSent = PacketsSent - m_packetsSentReported;
callback(newPacketsReceived, newPacketsSent, UnackedBytes);
m_packetsReceivedReported += newPacketsReceived;
m_packetsSentReported += newPacketsSent;
}
}
public bool SetThrottles(byte[] throttleData)
{
byte[] adjData;
int pos = 0;
if (!BitConverter.IsLittleEndian)
{
byte[] newData = new byte[7 * 4];
Buffer.BlockCopy(throttleData, 0, newData, 0, 7 * 4);
for (int i = 0; i < 7; i++)
Array.Reverse(newData, i * 4, 4);
adjData = newData;
}
else
{
adjData = throttleData;
}
// 0.125f converts from bits to bytes
int resend = (int)(BitConverter.ToSingle(adjData, pos) * 0.125f); pos += 4;
int land = (int)(BitConverter.ToSingle(adjData, pos) * 0.125f); pos += 4;
int wind = (int)(BitConverter.ToSingle(adjData, pos) * 0.125f); pos += 4;
int cloud = (int)(BitConverter.ToSingle(adjData, pos) * 0.125f); pos += 4;
int task = (int)(BitConverter.ToSingle(adjData, pos) * 0.125f); pos += 4;
int texture = (int)(BitConverter.ToSingle(adjData, pos) * 0.125f); pos += 4;
int asset = (int)(BitConverter.ToSingle(adjData, pos) * 0.125f);
//int totalKbps = ((resend + land + wind + cloud + task + texture + asset)/1024)*8; // save this original value for below
// State is a subcategory of task that we allocate a percentage to
int state = (int)((float)task * STATE_TASK_PERCENTAGE);
task -= state;
//subtract 33% from the total to make up for LL's 50% hack
resend = (int)(resend * 0.6667);
land = (int)(land * 0.6667);
wind = (int)(wind * 0.6667);
cloud = (int)(cloud * 0.6667);
task = (int)(task * 0.6667);
texture = (int)(texture * 0.6667);
asset = (int)(asset * 0.6667);
state = (int)(state * 0.6667);
// Make sure none of the throttles are set below our packet MTU,
// otherwise a throttle could become permanently clogged
resend = Math.Max(resend, LLUDPServer.MTU);
land = Math.Max(land, LLUDPServer.MTU);
wind = Math.Max(wind, LLUDPServer.MTU);
cloud = Math.Max(cloud, LLUDPServer.MTU);
task = Math.Max(task, LLUDPServer.MTU);
texture = Math.Max(texture, LLUDPServer.MTU);
asset = Math.Max(asset, LLUDPServer.MTU);
state = Math.Max(state, LLUDPServer.MTU);
int total = resend + land + wind + cloud + task + texture + asset + state;
//m_log.InfoFormat("[LLUDP] Client {0} throttle {1}", AgentID, total);
//m_log.DebugFormat("[LLUDPCLIENT]: {0} is setting throttles. Resend={1}, Land={2}, Wind={3}, Cloud={4}, Task={5}, Texture={6}, Asset={7}, State={8}, Total={9}",
// AgentID, resend, land, wind, cloud, task, texture, asset, state, total);
// Update the token buckets with new throttle values
TokenBucket bucket;
bool throttleChanged = (m_throttle.DripRate != m_throttle.NormalizedDripRate(total));
// if (throttleChanged) m_log.InfoFormat("[LLUDPCLIENT]: Viewer agent bandwidth throttle request for {0} to {1} kbps.", this.AgentID, totalKbps);
bucket = m_throttle;
bucket.DripRate = total;
bucket.MaxBurst = total;
bucket = m_throttleCategories[(int)ThrottleOutPacketType.Resend];
bucket.DripRate = resend;
bucket.MaxBurst = resend;
bucket = m_throttleCategories[(int)ThrottleOutPacketType.Land];
bucket.DripRate = land;
bucket.MaxBurst = land;
bucket = m_throttleCategories[(int)ThrottleOutPacketType.Wind];
bucket.DripRate = wind;
bucket.MaxBurst = wind;
bucket = m_throttleCategories[(int)ThrottleOutPacketType.Cloud];
bucket.DripRate = cloud;
bucket.MaxBurst = cloud;
bucket = m_throttleCategories[(int)ThrottleOutPacketType.Asset];
bucket.DripRate = asset;
bucket.MaxBurst = asset;
bucket = m_throttleCategories[(int)ThrottleOutPacketType.Task];
bucket.DripRate = task + state;
bucket.MaxBurst = task + state;
bucket = m_throttleCategories[(int)ThrottleOutPacketType.State];
bucket.DripRate = state;
bucket.MaxBurst = state;
bucket = m_throttleCategories[(int)ThrottleOutPacketType.Texture];
bucket.DripRate = texture;
bucket.MaxBurst = texture;
// Reset the packed throttles cached data
m_unpackedThrottles = null;
return throttleChanged;
}
internal UnpackedThrottles GetThrottlesUnpacked()
{
UnpackedThrottles throttles = m_unpackedThrottles;
if (throttles == null)
{
float[] fthrottles = new float[THROTTLE_CATEGORY_COUNT - 1];
int i = 0;
fthrottles[i++] = (float)m_throttleCategories[(int)ThrottleOutPacketType.Resend].DripRate;
fthrottles[i++] = (float)m_throttleCategories[(int)ThrottleOutPacketType.Land].DripRate;
fthrottles[i++] = (float)m_throttleCategories[(int)ThrottleOutPacketType.Wind].DripRate;
fthrottles[i++] = (float)m_throttleCategories[(int)ThrottleOutPacketType.Cloud].DripRate;
fthrottles[i++] = (float)(m_throttleCategories[(int)ThrottleOutPacketType.Task].DripRate +
m_throttleCategories[(int)ThrottleOutPacketType.State].DripRate);
fthrottles[i++] = (float)m_throttleCategories[(int)ThrottleOutPacketType.Texture].DripRate;
fthrottles[i++] = (float)m_throttleCategories[(int)ThrottleOutPacketType.Asset].DripRate;
throttles = new UnpackedThrottles(fthrottles);
m_unpackedThrottles = throttles;
}
return throttles;
}
public void TestReportPacketDrop(OutgoingPacket packet)
{
lock (_dropReportLock)
{
if (DateTime.Now - _lastDropReport > TimeSpan.FromSeconds(MIN_DROP_REPORT_INTERVAL))
{
_lastDropReport = DateTime.Now;
m_log.WarnFormat("[LLUDP] Packets are being dropped for {0} due to overfilled outbound queue, last packet type {1}",
AgentID, packet.Type);
}
}
}
public void TestReportPacketShouldDrop(OutgoingPacket packet)
{
lock (_dropReportLock)
{
if (DateTime.Now - _lastDropReport > TimeSpan.FromSeconds(MIN_DROP_REPORT_INTERVAL))
{
_lastDropReport = DateTime.Now;
m_log.WarnFormat("[LLUDP] Packet should've been dropped for {0} due to overfilled outbound queue, but was reliable. Last packet type {1}",
AgentID, packet.Type);
}
}
}
public void TestReportCriticalPacketDrop(OutgoingPacket packet)
{
lock (_dropReportLock)
{
if (DateTime.Now - _lastDropReport > TimeSpan.FromSeconds(MIN_DROP_REPORT_INTERVAL))
{
_lastDropReport = DateTime.Now;
m_log.WarnFormat("[LLUDP] Reliable packets are being dropped for {0} due to overfilled outbound queue. Last packet type {1}",
AgentID, packet.Type);
}
}
}
public bool EnqueueOutgoing(OutgoingPacket packet)
{
int category = (int)packet.Category;
if (category >= 0 && category < m_packetOutboxes.Length)
{
OpenSim.Framework.LocklessQueue<OutgoingPacket> queue = m_packetOutboxes[category];
// Not enough tokens in the bucket, queue this packet
//check the queue
//Dont drop resends this can mess up the buffer pool as well as make the connection situation much worse
if (_currentOutboundQueueSize > MAX_TOTAL_QUEUE_SIZE && (packet.Buffer.Data[0] & Helpers.MSG_RESENT) == 0)
{
//queue already has too much data in it..
//can we drop this packet?
byte flags = packet.Buffer.Data[0];
bool isReliable = (flags & Helpers.MSG_RELIABLE) != 0;
if (!isReliable
&& packet.Type != PacketType.PacketAck
&& packet.Type != PacketType.CompletePingCheck)
{
//packet is unreliable and will be dropped
this.TestReportPacketDrop(packet);
packet.DecRef(m_udpServer.ByteBufferPool);
}
else
{
if (_currentOutboundQueueSize < MAX_TOTAL_QUEUE_SIZE * 1.5)
{
this.TestReportPacketShouldDrop(packet);
Interlocked.Add(ref _currentOutboundQueueSize, packet.DataSize);
packet.AddRef();
queue.Enqueue(packet);
}
else
{
//this connection is in a pretty critical state and probably will never catch up.
//drop all packets until we start to catch up. This includes acks which will disconnect
//the client eventually anyways
this.TestReportCriticalPacketDrop(packet);
packet.DecRef(m_udpServer.ByteBufferPool);
}
}
}
else
{
Interlocked.Add(ref _currentOutboundQueueSize, packet.DataSize);
packet.AddRef();
queue.Enqueue(packet);
}
return true;
}
else
{
// We don't have a token bucket for this category, so it will not be queued
return false;
}
}
/// <summary>
/// Loops through all of the packet queues for this client and tries to send
/// any outgoing packets, obeying the throttling bucket limits
/// </summary>
/// <remarks>This function is only called from a synchronous loop in the
/// UDPServer so we don't need to bother making this thread safe</remarks>
/// <returns>True if any packets were sent, otherwise false</returns>
public bool DequeueOutgoing()
{
OutgoingPacket packet;
OpenSim.Framework.LocklessQueue<OutgoingPacket> queue;
TokenBucket bucket;
bool packetSent = false;
ThrottleOutPacketTypeFlags emptyCategories = 0;
//string queueDebugOutput = String.Empty; // Serious debug business
int randStart = _rand.Next(7);
for (int j = 0; j < THROTTLE_CATEGORY_COUNT; j++)
{
int i = (j + randStart) % THROTTLE_CATEGORY_COUNT;
bucket = m_throttleCategories[i];
//queueDebugOutput += m_packetOutboxes[i].Count + " "; // Serious debug business
if (m_nextPackets[i] != null)
{
// This bucket was empty the last time we tried to send a packet,
// leaving a dequeued packet still waiting to be sent out. Try to
// send it again
OutgoingPacket nextPacket = m_nextPackets[i];
if (bucket.RemoveTokens(nextPacket.DataSize))
{
// Send the packet
Interlocked.Add(ref _currentOutboundQueueSize, -nextPacket.DataSize);
m_udpServer.SendPacketFinal(nextPacket);
nextPacket.DecRef(m_udpServer.ByteBufferPool);
m_nextPackets[i] = null;
packetSent = true;
this.PacketsSent++;
}
}
else
{
// No dequeued packet waiting to be sent, try to pull one off
// this queue
queue = m_packetOutboxes[i];
if (queue.Dequeue(out packet))
{
// A packet was pulled off the queue. See if we have
// enough tokens in the bucket to send it out
if (bucket.RemoveTokens(packet.DataSize))
{
// Send the packet
Interlocked.Add(ref _currentOutboundQueueSize, -packet.DataSize);
m_udpServer.SendPacketFinal(packet);
packet.DecRef(m_udpServer.ByteBufferPool);
packetSent = true;
this.PacketsSent++;
}
else
{
// Save the dequeued packet for the next iteration
m_nextPackets[i] = packet;
_emptyBucketHints.Add(i);
}
// If the queue is empty after this dequeue, fire the queue
// empty callback now so it has a chance to fill before we
// get back here
if (queue.Count == 0)
emptyCategories |= CategoryToFlag(i);
}
else
{
// No packets in this queue. Fire the queue empty callback
// if it has not been called recently
emptyCategories |= CategoryToFlag(i);
}
}
}
if (emptyCategories != 0)
BeginFireQueueEmpty(emptyCategories);
//m_log.Info("[LLUDPCLIENT]: Queues: " + queueDebugOutput); // Serious debug business
return packetSent;
}
/// <summary>
/// Called when an ACK packet is received and a round-trip time for a
/// packet is calculated. This is used to calculate the smoothed
/// round-trip time, round trip time variance, and finally the
/// retransmission timeout
/// </summary>
/// <param name="r">Round-trip time of a single packet and its
/// acknowledgement</param>
public void UpdateRoundTrip(float r)
{
const float ALPHA = 0.125f;
const float BETA = 0.25f;
const float K = 4.0f;
if (RTTVAR == 0.0f)
{
// First RTT measurement
SRTT = r;
RTTVAR = r * 0.5f;
}
else
{
// Subsequence RTT measurement
RTTVAR = (1.0f - BETA) * RTTVAR + BETA * Math.Abs(SRTT - r);
SRTT = (1.0f - ALPHA) * SRTT + ALPHA * r;
}
int rto = (int)(SRTT + Math.Max(m_udpServer.TickCountResolution, K * RTTVAR));
// Clamp the retransmission timeout to manageable values
rto = Utils.Clamp(rto, m_defaultRTO, m_maxRTO);
RTO = rto;
//m_log.Debug("[LLUDPCLIENT]: Setting agent " + this.Agent.FullName + "'s RTO to " + RTO + "ms with an RTTVAR of " +
// RTTVAR + " based on new RTT of " + r + "ms");
}
/// <summary>
/// Exponential backoff of the retransmission timeout, per section 5.5
/// of RFC 2988
/// </summary>
public void BackoffRTO()
{
// Reset SRTT and RTTVAR, we assume they are bogus since things
// didn't work out and we're backing off the timeout
SRTT = 0.0f;
RTTVAR = 0.0f;
// Double the retransmission timeout
RTO = Math.Min(RTO * 2, m_maxRTO);
}
/// <summary>
/// Does an early check to see if this queue empty callback is already
/// running, then asynchronously firing the event
/// </summary>
/// <param name="throttleIndex">Throttle category to fire the callback
/// for</param>
private void BeginFireQueueEmpty(ThrottleOutPacketTypeFlags categories)
{
if (m_nextOnQueueEmpty != 0 && (Environment.TickCount & Int32.MaxValue) >= m_nextOnQueueEmpty)
{
// Use a value of 0 to signal that FireQueueEmpty is running
m_nextOnQueueEmpty = 0;
// Asynchronously run the callback
Util.FireAndForget(FireQueueEmpty, categories);
}
}
/// <summary>
/// Fires the OnQueueEmpty callback and sets the minimum time that it
/// can be called again
/// </summary>
/// <param name="o">Throttle categories to fire the callback for,
/// stored as an object to match the WaitCallback delegate
/// signature</param>
private void FireQueueEmpty(object o)
{
const int MIN_CALLBACK_MS = 30;
ThrottleOutPacketTypeFlags categories = (ThrottleOutPacketTypeFlags)o;
QueueEmpty callback = OnQueueEmpty;
int start = Environment.TickCount & Int32.MaxValue;
if (callback != null)
{
try { callback(categories); }
catch (Exception e) { m_log.Error("[LLUDPCLIENT]: OnQueueEmpty(" + categories + ") threw an exception: " + e.Message, e); }
}
m_nextOnQueueEmpty = start + MIN_CALLBACK_MS;
if (m_nextOnQueueEmpty == 0)
m_nextOnQueueEmpty = 1;
}
/// <summary>
/// Converts a <seealso cref="ThrottleOutPacketType"/> integer to a
/// flag value
/// </summary>
/// <param name="i">Throttle category to convert</param>
/// <returns>Flag representation of the throttle category</returns>
private static ThrottleOutPacketTypeFlags CategoryToFlag(int i)
{
ThrottleOutPacketType category = (ThrottleOutPacketType)i;
/*
* Land = 1,
/// <summary>Wind data</summary>
Wind = 2,
/// <summary>Cloud data</summary>
Cloud = 3,
/// <summary>Any packets that do not fit into the other throttles</summary>
Task = 4,
/// <summary>Texture assets</summary>
Texture = 5,
/// <summary>Non-texture assets</summary>
Asset = 6,
/// <summary>Avatar and primitive data</summary>
/// <remarks>This is a sub-category of Task</remarks>
State = 7,
*/
switch (category)
{
case ThrottleOutPacketType.Land:
return ThrottleOutPacketTypeFlags.Land;
case ThrottleOutPacketType.Wind:
return ThrottleOutPacketTypeFlags.Wind;
case ThrottleOutPacketType.Cloud:
return ThrottleOutPacketTypeFlags.Cloud;
case ThrottleOutPacketType.Task:
return ThrottleOutPacketTypeFlags.Task;
case ThrottleOutPacketType.Texture:
return ThrottleOutPacketTypeFlags.Texture;
case ThrottleOutPacketType.Asset:
return ThrottleOutPacketTypeFlags.Asset;
case ThrottleOutPacketType.State:
return ThrottleOutPacketTypeFlags.State;
default:
return 0;
}
}
/// <summary>
/// if we have any leftover bandwidth, check for queues that have packets still in them
/// and equally distribute remaining bandwidth among queues
/// </summary>
/// <returns>True if a dynamic adjustment was made, false if not</returns>
public bool PerformDynamicThrottleAdjustment()
{
//return false;
if (m_throttle.Content == 0 || _emptyBucketHints.Count == 0)
{
_emptyBucketHints.Clear();
return false;
}
int addnlAmount = m_throttle.Content / _emptyBucketHints.Count;
foreach (int i in _emptyBucketHints)
{
m_throttleCategories[i].SpareBurst = addnlAmount;
}
_emptyBucketHints.Clear();
return true;
}
}
}
| |
// 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.Reflection;
using System.Reflection.Emit;
using Xunit;
namespace System.Linq.Expressions.Tests
{
public static class BinaryLogicalTests
{
//TODO: Need tests on the short-circuit and non-short-circuit nature of the two forms.
#region Test methods
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckBoolAndTest(bool useInterpreter)
{
bool[] array = new bool[] { true, false };
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < array.Length; j++)
{
VerifyBoolAnd(array[i], array[j], useInterpreter);
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckBoolAndAlsoTest(bool useInterpreter)
{
bool[] array = new bool[] { true, false };
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < array.Length; j++)
{
VerifyBoolAndAlso(array[i], array[j], useInterpreter);
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckBoolOrTest(bool useInterpreter)
{
bool[] array = new bool[] { true, false };
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < array.Length; j++)
{
VerifyBoolOr(array[i], array[j], useInterpreter);
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckBoolOrElseTest(bool useInterpreter)
{
bool[] array = new bool[] { true, false };
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < array.Length; j++)
{
VerifyBoolOrElse(array[i], array[j], useInterpreter);
}
}
}
#endregion
#region Test verifiers
private static void VerifyBoolAnd(bool a, bool b, bool useInterpreter)
{
Expression<Func<bool>> e =
Expression.Lambda<Func<bool>>(
Expression.And(
Expression.Constant(a, typeof(bool)),
Expression.Constant(b, typeof(bool))),
Enumerable.Empty<ParameterExpression>());
Func<bool> f = e.Compile(useInterpreter);
Assert.Equal(a & b, f());
}
private static void VerifyBoolAndAlso(bool a, bool b, bool useInterpreter)
{
Expression<Func<bool>> e =
Expression.Lambda<Func<bool>>(
Expression.AndAlso(
Expression.Constant(a, typeof(bool)),
Expression.Constant(b, typeof(bool))),
Enumerable.Empty<ParameterExpression>());
Func<bool> f = e.Compile(useInterpreter);
Assert.Equal(a && b, f());
}
private static void VerifyBoolOr(bool a, bool b, bool useInterpreter)
{
Expression<Func<bool>> e =
Expression.Lambda<Func<bool>>(
Expression.Or(
Expression.Constant(a, typeof(bool)),
Expression.Constant(b, typeof(bool))),
Enumerable.Empty<ParameterExpression>());
Func<bool> f = e.Compile(useInterpreter);
Assert.Equal(a | b, f());
}
private static void VerifyBoolOrElse(bool a, bool b, bool useInterpreter)
{
Expression<Func<bool>> e =
Expression.Lambda<Func<bool>>(
Expression.OrElse(
Expression.Constant(a, typeof(bool)),
Expression.Constant(b, typeof(bool))),
Enumerable.Empty<ParameterExpression>());
Func<bool> f = e.Compile(useInterpreter);
Assert.Equal(a || b, f());
}
#endregion
public static IEnumerable<object[]> AndAlso_TestData()
{
yield return new object[] { 5, 3, 1, true };
yield return new object[] { 0, 3, 0, false };
yield return new object[] { 5, 0, 0, true };
}
[Theory]
[PerCompilationType(nameof(AndAlso_TestData))]
public static void AndAlso_UserDefinedOperator(int leftValue, int rightValue, int expectedValue, bool calledMethod, bool useInterpreter)
{
TrueFalseClass left = new TrueFalseClass(leftValue);
TrueFalseClass right = new TrueFalseClass(rightValue);
BinaryExpression expression = Expression.AndAlso(Expression.Constant(left), Expression.Constant(right));
Func<TrueFalseClass> lambda = Expression.Lambda<Func<TrueFalseClass>>(expression).Compile(useInterpreter);
Assert.Equal(expectedValue, lambda().Value);
// AndAlso only evaluates the false operator of left
Assert.Equal(0, left.TrueCallCount);
Assert.Equal(1, left.FalseCallCount);
Assert.Equal(0, right.TrueCallCount);
Assert.Equal(0, right.FalseCallCount);
// AndAlso only evaluates the operator if left is not false
Assert.Equal(calledMethod ? 1 : 0, left.OperatorCallCount);
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public static void AndAlso_UserDefinedOperator_HasMethodNotOperator(bool useInterpreter)
{
BinaryExpression expression = Expression.AndAlso(Expression.Constant(new NamedMethods(5)), Expression.Constant(new NamedMethods(3)));
Func<NamedMethods> lambda = Expression.Lambda<Func<NamedMethods>>(expression).Compile(useInterpreter);
Assert.Equal(1, lambda().Value);
}
[Theory]
[PerCompilationType(nameof(AndAlso_TestData))]
public static void AndAlso_Method(int leftValue, int rightValue, int expectedValue, bool calledMethod, bool useInterpreter)
{
MethodInfo method = typeof(TrueFalseClass).GetMethod(nameof(TrueFalseClass.AndMethod));
TrueFalseClass left = new TrueFalseClass(leftValue);
TrueFalseClass right = new TrueFalseClass(rightValue);
BinaryExpression expression = Expression.AndAlso(Expression.Constant(left), Expression.Constant(right), method);
Func<TrueFalseClass> lambda = Expression.Lambda<Func<TrueFalseClass>>(expression).Compile(useInterpreter);
Assert.Equal(expectedValue, lambda().Value);
// AndAlso only evaluates the false operator of left
Assert.Equal(0, left.TrueCallCount);
Assert.Equal(1, left.FalseCallCount);
Assert.Equal(0, right.TrueCallCount);
Assert.Equal(0, right.FalseCallCount);
// AndAlso only evaluates the method if left is not false
Assert.Equal(0, left.OperatorCallCount);
Assert.Equal(calledMethod ? 1 : 0, left.MethodCallCount);
}
public static IEnumerable<object[]> OrElse_TestData()
{
yield return new object[] { 5, 3, 5, false };
yield return new object[] { 0, 3, 3, true };
yield return new object[] { 5, 0, 5, false };
}
[Theory]
[PerCompilationType(nameof(OrElse_TestData))]
public static void OrElse_UserDefinedOperator(int leftValue, int rightValue, int expectedValue, bool calledMethod, bool useInterpreter)
{
TrueFalseClass left = new TrueFalseClass(leftValue);
TrueFalseClass right = new TrueFalseClass(rightValue);
BinaryExpression expression = Expression.OrElse(Expression.Constant(left), Expression.Constant(right));
Func<TrueFalseClass> lambda = Expression.Lambda<Func<TrueFalseClass>>(expression).Compile(useInterpreter);
Assert.Equal(expectedValue, lambda().Value);
// OrElse only evaluates the true operator of left
Assert.Equal(1, left.TrueCallCount);
Assert.Equal(0, left.FalseCallCount);
Assert.Equal(0, right.TrueCallCount);
Assert.Equal(0, right.FalseCallCount);
// OrElse only evaluates the operator if left is not true
Assert.Equal(calledMethod ? 1 : 0, left.OperatorCallCount);
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public static void OrElse_UserDefinedOperator_HasMethodNotOperator(bool useInterpreter)
{
BinaryExpression expression = Expression.OrElse(Expression.Constant(new NamedMethods(0)), Expression.Constant(new NamedMethods(3)));
Func<NamedMethods> lambda = Expression.Lambda<Func<NamedMethods>>(expression).Compile(useInterpreter);
Assert.Equal(3, lambda().Value);
}
[Theory]
[PerCompilationType(nameof(OrElse_TestData))]
public static void OrElse_Method(int leftValue, int rightValue, int expectedValue, bool calledMethod, bool useInterpreter)
{
MethodInfo method = typeof(TrueFalseClass).GetMethod(nameof(TrueFalseClass.OrMethod));
TrueFalseClass left = new TrueFalseClass(leftValue);
TrueFalseClass right = new TrueFalseClass(rightValue);
BinaryExpression expression = Expression.OrElse(Expression.Constant(left), Expression.Constant(right), method);
Func<TrueFalseClass> lambda = Expression.Lambda<Func<TrueFalseClass>>(expression).Compile(useInterpreter);
Assert.Equal(expectedValue, lambda().Value);
// OrElse only evaluates the true operator of left
Assert.Equal(1, left.TrueCallCount);
Assert.Equal(0, left.FalseCallCount);
Assert.Equal(0, right.TrueCallCount);
Assert.Equal(0, right.FalseCallCount);
// OrElse only evaluates the method if left is not true
Assert.Equal(0, left.OperatorCallCount);
Assert.Equal(calledMethod ? 1 : 0, left.MethodCallCount);
}
[Fact]
public static void AndAlso_CannotReduce()
{
Expression exp = Expression.AndAlso(Expression.Constant(true), Expression.Constant(false));
Assert.False(exp.CanReduce);
Assert.Same(exp, exp.Reduce());
Assert.Throws<ArgumentException>(null, () => exp.ReduceAndCheck());
}
[Fact]
public static void OrElse_CannotReduce()
{
Expression exp = Expression.OrElse(Expression.Constant(true), Expression.Constant(false));
Assert.False(exp.CanReduce);
Assert.Same(exp, exp.Reduce());
Assert.Throws<ArgumentException>(null, () => exp.ReduceAndCheck());
}
[Fact]
public static void AndAlso_LeftNull_ThrowsArgumentNullException()
{
Assert.Throws<ArgumentNullException>("left", () => Expression.AndAlso(null, Expression.Constant(true)));
Assert.Throws<ArgumentNullException>("left", () => Expression.AndAlso(null, Expression.Constant(true), null));
}
[Fact]
public static void OrElse_LeftNull_ThrowsArgumentNullException()
{
Assert.Throws<ArgumentNullException>("left", () => Expression.OrElse(null, Expression.Constant(true)));
Assert.Throws<ArgumentNullException>("left", () => Expression.OrElse(null, Expression.Constant(true), null));
}
[Fact]
public static void AndAlso_RightNull_ThrowsArgumentNullException()
{
Assert.Throws<ArgumentNullException>("right", () => Expression.AndAlso(Expression.Constant(true), null));
Assert.Throws<ArgumentNullException>("right", () => Expression.AndAlso(Expression.Constant(true), null, null));
}
[Fact]
public static void OrElse_RightNull_ThrowsArgumentNullException()
{
Assert.Throws<ArgumentNullException>("right", () => Expression.OrElse(Expression.Constant(true), null));
Assert.Throws<ArgumentNullException>("right", () => Expression.OrElse(Expression.Constant(true), null, null));
}
[Fact]
public static void AndAlso_BinaryOperatorNotDefined_ThrowsInvalidOperationException()
{
Assert.Throws<InvalidOperationException>(() => Expression.AndAlso(Expression.Constant(5), Expression.Constant("hello")));
Assert.Throws<InvalidOperationException>(() => Expression.AndAlso(Expression.Constant(5), Expression.Constant("hello"), null));
}
[Fact]
public static void OrElse_BinaryOperatorNotDefined_ThrowsInvalidOperationException()
{
Assert.Throws<InvalidOperationException>(() => Expression.OrElse(Expression.Constant(5), Expression.Constant("hello")));
Assert.Throws<InvalidOperationException>(() => Expression.OrElse(Expression.Constant(5), Expression.Constant("hello"), null));
}
public static IEnumerable<object[]> InvalidMethod_TestData()
{
yield return new object[] { typeof(NonGenericClass).GetMethod(nameof(NonGenericClass.InstanceMethod)) };
yield return new object[] { typeof(NonGenericClass).GetMethod(nameof(NonGenericClass.StaticVoidMethod)) };
}
[Theory]
[ClassData(typeof(OpenGenericMethodsData))]
[MemberData(nameof(InvalidMethod_TestData))]
public static void InvalidMethod_ThrowsArgumentException(MethodInfo method)
{
Assert.Throws<ArgumentException>("method", () => Expression.AndAlso(Expression.Constant(5), Expression.Constant(5), method));
Assert.Throws<ArgumentException>("method", () => Expression.OrElse(Expression.Constant(5), Expression.Constant(5), method));
}
[Theory]
[InlineData(typeof(NonGenericClass), nameof(NonGenericClass.StaticIntMethod0))]
[InlineData(typeof(NonGenericClass), nameof(NonGenericClass.StaticIntMethod1))]
[InlineData(typeof(NonGenericClass), nameof(NonGenericClass.StaticIntMethod3))]
public static void Method_DoesntHaveTwoParameters_ThrowsArgumentException(Type type, string methodName)
{
MethodInfo method = type.GetMethod(methodName);
Assert.Throws<ArgumentException>("method", () => Expression.AndAlso(Expression.Constant(5), Expression.Constant(5), method));
Assert.Throws<ArgumentException>("method", () => Expression.OrElse(Expression.Constant(5), Expression.Constant(5), method));
}
[Fact]
public static void AndAlso_Method_ExpressionDoesntMatchMethodParameters_ThrowsInvalidOperationException()
{
MethodInfo method = typeof(NonGenericClass).GetMethod(nameof(NonGenericClass.StaticIntMethod2Valid));
Assert.Throws<InvalidOperationException>(() => Expression.AndAlso(Expression.Constant("abc"), Expression.Constant(5), method));
Assert.Throws<InvalidOperationException>(() => Expression.AndAlso(Expression.Constant(5), Expression.Constant("abc"), method));
}
[Fact]
public static void OrElse_ExpressionDoesntMatchMethodParameters_ThrowsInvalidOperationException()
{
MethodInfo method = typeof(NonGenericClass).GetMethod(nameof(NonGenericClass.StaticIntMethod2Valid));
Assert.Throws<InvalidOperationException>(() => Expression.AndAlso(Expression.Constant("abc"), Expression.Constant(5), method));
Assert.Throws<InvalidOperationException>(() => Expression.AndAlso(Expression.Constant(5), Expression.Constant("abc"), method));
}
[Fact]
public static void MethodParametersNotEqual_ThrowsArgumentException()
{
MethodInfo method = typeof(NonGenericClass).GetMethod(nameof(NonGenericClass.StaticIntMethod2Invalid1));
Assert.Throws<ArgumentException>(null, () => Expression.AndAlso(Expression.Constant(5), Expression.Constant("abc"), method));
Assert.Throws<ArgumentException>(null, () => Expression.OrElse(Expression.Constant(5), Expression.Constant("abc"), method));
}
[Fact]
public static void Method_ReturnTypeNotEqualToParameterTypes_ThrowsArgumentException()
{
MethodInfo method = typeof(NonGenericClass).GetMethod(nameof(NonGenericClass.StaticIntMethod2Invalid2));
Assert.Throws<ArgumentException>(null, () => Expression.AndAlso(Expression.Constant(5), Expression.Constant(5), method));
Assert.Throws<ArgumentException>(null, () => Expression.OrElse(Expression.Constant(5), Expression.Constant(5), method));
}
[Fact]
public static void MethodDeclaringTypeHasNoTrueFalseOperator_ThrowsArgumentException()
{
MethodInfo method = typeof(NonGenericClass).GetMethod(nameof(NonGenericClass.StaticIntMethod2Valid));
Assert.Throws<ArgumentException>(null, () => Expression.AndAlso(Expression.Constant(5), Expression.Constant(5), method));
Assert.Throws<ArgumentException>(null, () => Expression.OrElse(Expression.Constant(5), Expression.Constant(5), method));
}
#if FEATURE_COMPILE
[Fact]
public static void AndAlso_NoMethod_NotStatic_ThrowsInvalidOperationException()
{
TypeBuilder type = GetTypeBuilder();
MethodBuilder andOperator = type.DefineMethod("op_BitwiseAnd", MethodAttributes.Public, type, new Type[] { type, type });
andOperator.GetILGenerator().Emit(OpCodes.Ret);
Type createdType = type.CreateTypeInfo();
object obj = Activator.CreateInstance(createdType);
Assert.Throws<InvalidOperationException>(() => Expression.AndAlso(Expression.Constant(obj), Expression.Constant(obj)));
}
[Fact]
public static void OrElse_NoMethod_NotStatic_ThrowsInvalidOperationException()
{
TypeBuilder type = GetTypeBuilder();
MethodBuilder andOperator = type.DefineMethod("op_BitwiseOr", MethodAttributes.Public, type, new Type[] { type, type });
andOperator.GetILGenerator().Emit(OpCodes.Ret);
Type createdType = type.CreateTypeInfo();
object obj = Activator.CreateInstance(createdType);
Assert.Throws<InvalidOperationException>(() => Expression.OrElse(Expression.Constant(obj), Expression.Constant(obj)));
}
[Fact]
public static void AndAlso_NoMethod_VoidReturnType_ThrowsArgumentException()
{
TypeBuilder type = GetTypeBuilder();
MethodBuilder andOperator = type.DefineMethod("op_BitwiseAnd", MethodAttributes.Public | MethodAttributes.Static, typeof(void), new Type[] { type, type });
andOperator.GetILGenerator().Emit(OpCodes.Ret);
Type createdType = type.CreateTypeInfo();
object obj = Activator.CreateInstance(createdType);
Assert.Throws<ArgumentException>("method", () => Expression.AndAlso(Expression.Constant(obj), Expression.Constant(obj)));
}
[Fact]
public static void OrElse_NoMethod_VoidReturnType_ThrowsArgumentException()
{
TypeBuilder type = GetTypeBuilder();
MethodBuilder andOperator = type.DefineMethod("op_BitwiseOr", MethodAttributes.Public | MethodAttributes.Static, typeof(void), new Type[] { type, type });
andOperator.GetILGenerator().Emit(OpCodes.Ret);
Type createdType = type.CreateTypeInfo();
object obj = Activator.CreateInstance(createdType);
Assert.Throws<ArgumentException>("method", () => Expression.OrElse(Expression.Constant(obj), Expression.Constant(obj)));
}
[Theory]
[InlineData(0)]
[InlineData(1)]
[InlineData(3)]
public static void AndAlso_NoMethod_DoesntHaveTwoParameters_ThrowsInvalidOperationException(int parameterCount)
{
TypeBuilder type = GetTypeBuilder();
MethodBuilder andOperator = type.DefineMethod("op_BitwiseAnd", MethodAttributes.Public | MethodAttributes.Static, type, Enumerable.Repeat(type, parameterCount).ToArray());
andOperator.GetILGenerator().Emit(OpCodes.Ret);
Type createdType = type.CreateTypeInfo();
object obj = Activator.CreateInstance(createdType);
Assert.Throws<InvalidOperationException>(() => Expression.AndAlso(Expression.Constant(obj), Expression.Constant(obj)));
}
[Theory]
[InlineData(0)]
[InlineData(1)]
[InlineData(3)]
public static void OrElse_NoMethod_DoesntHaveTwoParameters_ThrowsInvalidOperationException(int parameterCount)
{
TypeBuilder type = GetTypeBuilder();
MethodBuilder andOperator = type.DefineMethod("op_BitwiseOr", MethodAttributes.Public | MethodAttributes.Static, type, Enumerable.Repeat(type, parameterCount).ToArray());
andOperator.GetILGenerator().Emit(OpCodes.Ret);
Type createdType = type.CreateTypeInfo();
object obj = Activator.CreateInstance(createdType);
Assert.Throws<InvalidOperationException>(() => Expression.OrElse(Expression.Constant(obj), Expression.Constant(obj)));
}
[Fact]
public static void AndAlso_NoMethod_ExpressionDoesntMatchMethodParameters_ThrowsInvalidOperationException()
{
TypeBuilder type = GetTypeBuilder();
MethodBuilder andOperator = type.DefineMethod("op_BitwiseAnd", MethodAttributes.Public | MethodAttributes.Static, type, new Type[] { typeof(int), type });
andOperator.GetILGenerator().Emit(OpCodes.Ret);
Type createdType = type.CreateTypeInfo();
object obj = Activator.CreateInstance(createdType);
Assert.Throws<InvalidOperationException>(() => Expression.AndAlso(Expression.Constant(obj), Expression.Constant(obj)));
}
[Fact]
public static void OrElse_NoMethod_ExpressionDoesntMatchMethodParameters_ThrowsInvalidOperationException()
{
TypeBuilder type = GetTypeBuilder();
MethodBuilder andOperator = type.DefineMethod("op_BitwiseOr", MethodAttributes.Public | MethodAttributes.Static, type, new Type[] { typeof(int), type });
andOperator.GetILGenerator().Emit(OpCodes.Ret);
Type createdType = type.CreateTypeInfo();
object obj = Activator.CreateInstance(createdType);
Assert.Throws<InvalidOperationException>(() => Expression.OrElse(Expression.Constant(obj), Expression.Constant(obj)));
}
[Fact]
public static void AndAlso_NoMethod_ReturnTypeNotEqualToParameterTypes_ThrowsArgumentException()
{
TypeBuilder type = GetTypeBuilder();
MethodBuilder andOperator = type.DefineMethod("op_BitwiseAnd", MethodAttributes.Public | MethodAttributes.Static, typeof(int), new Type[] { type, type });
andOperator.GetILGenerator().Emit(OpCodes.Ret);
Type createdType = type.CreateTypeInfo();
object obj = Activator.CreateInstance(createdType);
Assert.Throws<ArgumentException>(null, () => Expression.AndAlso(Expression.Constant(obj), Expression.Constant(obj)));
}
[Fact]
public static void OrElse_NoMethod_ReturnTypeNotEqualToParameterTypes_ThrowsArgumentException()
{
TypeBuilder type = GetTypeBuilder();
MethodBuilder andOperator = type.DefineMethod("op_BitwiseOr", MethodAttributes.Public | MethodAttributes.Static, typeof(int), new Type[] { type, type });
andOperator.GetILGenerator().Emit(OpCodes.Ret);
Type createdType = type.CreateTypeInfo();
object obj = Activator.CreateInstance(createdType);
Assert.Throws<ArgumentException>(null, () => Expression.OrElse(Expression.Constant(obj), Expression.Constant(obj)));
}
public static IEnumerable<object[]> Operator_IncorrectMethod_TestData()
{
// Does not return bool
TypeBuilder typeBuilder1 = GetTypeBuilder();
yield return new object[] { typeBuilder1, typeof(void), new Type[] { typeBuilder1 } };
// Parameter is not assignable from left
yield return new object[] { GetTypeBuilder(), typeof(bool), new Type[] { typeof(int) } };
// Has two parameters
TypeBuilder typeBuilder2 = GetTypeBuilder();
yield return new object[] { typeBuilder2, typeof(bool), new Type[] { typeBuilder2, typeBuilder2 } };
// Has no parameters
yield return new object[] { GetTypeBuilder(), typeof(bool), new Type[0] };
}
[Theory]
[MemberData(nameof(Operator_IncorrectMethod_TestData))]
public static void Method_TrueOperatorIncorrectMethod_ThrowsArgumentException(TypeBuilder builder, Type returnType, Type[] parameterTypes)
{
MethodBuilder opTrue = builder.DefineMethod("op_True", MethodAttributes.SpecialName | MethodAttributes.Static, returnType, parameterTypes);
opTrue.GetILGenerator().Emit(OpCodes.Ret);
MethodBuilder opFalse = builder.DefineMethod("op_False", MethodAttributes.SpecialName | MethodAttributes.Static, typeof(bool), new Type[] { builder });
opFalse.GetILGenerator().Emit(OpCodes.Ret);
MethodBuilder method = builder.DefineMethod("Method", MethodAttributes.Public | MethodAttributes.Static, builder, new Type[] { builder, builder });
method.GetILGenerator().Emit(OpCodes.Ret);
TypeInfo createdType = builder.CreateTypeInfo();
object obj = Activator.CreateInstance(createdType);
MethodInfo createdMethod = createdType.GetMethod("Method");
Assert.Throws<ArgumentException>(null, () => Expression.AndAlso(Expression.Constant(obj), Expression.Constant(obj), createdMethod));
Assert.Throws<ArgumentException>(null, () => Expression.OrElse(Expression.Constant(obj), Expression.Constant(obj), createdMethod));
}
[Theory]
[MemberData(nameof(Operator_IncorrectMethod_TestData))]
public static void Method_FalseOperatorIncorrectMethod_ThrowsArgumentException(TypeBuilder builder, Type returnType, Type[]parameterTypes)
{
MethodBuilder opTrue = builder.DefineMethod("op_True", MethodAttributes.SpecialName | MethodAttributes.Static, typeof(bool), new Type[] { builder });
opTrue.GetILGenerator().Emit(OpCodes.Ret);
MethodBuilder opFalse = builder.DefineMethod("op_False", MethodAttributes.SpecialName | MethodAttributes.Static, returnType, parameterTypes);
opFalse.GetILGenerator().Emit(OpCodes.Ret);
MethodBuilder method = builder.DefineMethod("Method", MethodAttributes.Public | MethodAttributes.Static, builder, new Type[] { builder, builder });
method.GetILGenerator().Emit(OpCodes.Ret);
TypeInfo createdType = builder.CreateTypeInfo();
object obj = Activator.CreateInstance(createdType);
MethodInfo createdMethod = createdType.GetMethod("Method");
Assert.Throws<ArgumentException>(null, () => Expression.AndAlso(Expression.Constant(obj), Expression.Constant(obj), createdMethod));
Assert.Throws<ArgumentException>(null, () => Expression.OrElse(Expression.Constant(obj), Expression.Constant(obj), createdMethod));
}
[Theory]
[MemberData(nameof(Operator_IncorrectMethod_TestData))]
public static void AndAlso_NoMethod_TrueOperatorIncorrectMethod_ThrowsArgumentException(TypeBuilder builder, Type returnType, Type[] parameterTypes)
{
MethodBuilder opTrue = builder.DefineMethod("op_True", MethodAttributes.SpecialName | MethodAttributes.Static, returnType, parameterTypes);
opTrue.GetILGenerator().Emit(OpCodes.Ret);
MethodBuilder opFalse = builder.DefineMethod("op_False", MethodAttributes.SpecialName | MethodAttributes.Static, typeof(bool), new Type[] { builder });
opFalse.GetILGenerator().Emit(OpCodes.Ret);
MethodBuilder method = builder.DefineMethod("op_BitwiseAnd", MethodAttributes.Public | MethodAttributes.Static, builder, new Type[] { builder, builder });
method.GetILGenerator().Emit(OpCodes.Ret);
TypeInfo createdType = builder.CreateTypeInfo();
object obj = Activator.CreateInstance(createdType);
Assert.Throws<ArgumentException>(null, () => Expression.AndAlso(Expression.Constant(obj), Expression.Constant(obj)));
}
[Theory]
[MemberData(nameof(Operator_IncorrectMethod_TestData))]
public static void OrElse_NoMethod_TrueOperatorIncorrectMethod_ThrowsArgumentException(TypeBuilder builder, Type returnType, Type[] parameterTypes)
{
MethodBuilder opTrue = builder.DefineMethod("op_True", MethodAttributes.SpecialName | MethodAttributes.Static, returnType, parameterTypes);
opTrue.GetILGenerator().Emit(OpCodes.Ret);
MethodBuilder opFalse = builder.DefineMethod("op_False", MethodAttributes.SpecialName | MethodAttributes.Static, typeof(bool), new Type[] { builder });
opFalse.GetILGenerator().Emit(OpCodes.Ret);
MethodBuilder method = builder.DefineMethod("op_BitwiseOr", MethodAttributes.Public | MethodAttributes.Static, builder, new Type[] { builder, builder });
method.GetILGenerator().Emit(OpCodes.Ret);
TypeInfo createdType = builder.CreateTypeInfo();
object obj = Activator.CreateInstance(createdType);
Assert.Throws<ArgumentException>(null, () => Expression.OrElse(Expression.Constant(obj), Expression.Constant(obj)));
}
[Theory]
[InlineData("op_True")]
[InlineData("op_False")]
public static void Method_NoTrueFalseOperator_ThrowsArgumentException(string name)
{
AssemblyBuilder assembly = AssemblyBuilder.DefineDynamicAssembly(new AssemblyName("Name"), AssemblyBuilderAccess.Run);
ModuleBuilder module = assembly.DefineDynamicModule("Name");
TypeBuilder builder = module.DefineType("Type");
MethodBuilder opTrue = builder.DefineMethod(name, MethodAttributes.SpecialName | MethodAttributes.Static, typeof(bool), new Type[] { builder });
opTrue.GetILGenerator().Emit(OpCodes.Ret);
MethodBuilder method = builder.DefineMethod("Method", MethodAttributes.Public | MethodAttributes.Static, builder, new Type[] { builder, builder });
method.GetILGenerator().Emit(OpCodes.Ret);
TypeInfo createdType = builder.CreateTypeInfo();
object obj = Activator.CreateInstance(createdType);
MethodInfo createdMethod = createdType.GetMethod("Method");
Assert.Throws<ArgumentException>(null, () => Expression.AndAlso(Expression.Constant(obj), Expression.Constant(obj), createdMethod));
Assert.Throws<ArgumentException>(null, () => Expression.OrElse(Expression.Constant(obj), Expression.Constant(obj), createdMethod));
}
[Theory]
[InlineData("op_True")]
[InlineData("op_False")]
public static void AndAlso_NoMethod_NoTrueFalseOperator_ThrowsArgumentException(string name)
{
AssemblyBuilder assembly = AssemblyBuilder.DefineDynamicAssembly(new AssemblyName("Name"), AssemblyBuilderAccess.Run);
ModuleBuilder module = assembly.DefineDynamicModule("Name");
TypeBuilder builder = module.DefineType("Type");
MethodBuilder opTrue = builder.DefineMethod(name, MethodAttributes.SpecialName | MethodAttributes.Static, typeof(bool), new Type[] { builder });
opTrue.GetILGenerator().Emit(OpCodes.Ret);
MethodBuilder method = builder.DefineMethod("op_BitwiseAnd", MethodAttributes.Public | MethodAttributes.Static, builder, new Type[] { builder, builder });
method.GetILGenerator().Emit(OpCodes.Ret);
TypeInfo createdType = builder.CreateTypeInfo();
object obj = Activator.CreateInstance(createdType);
Assert.Throws<ArgumentException>(null, () => Expression.AndAlso(Expression.Constant(obj), Expression.Constant(obj)));
}
[Theory]
[InlineData("op_True")]
[InlineData("op_False")]
public static void OrElse_NoMethod_NoTrueFalseOperator_ThrowsArgumentException(string name)
{
AssemblyBuilder assembly = AssemblyBuilder.DefineDynamicAssembly(new AssemblyName("Name"), AssemblyBuilderAccess.Run);
ModuleBuilder module = assembly.DefineDynamicModule("Name");
TypeBuilder builder = module.DefineType("Type");
MethodBuilder opTrue = builder.DefineMethod(name, MethodAttributes.SpecialName | MethodAttributes.Static, typeof(bool), new Type[] { builder });
opTrue.GetILGenerator().Emit(OpCodes.Ret);
MethodBuilder method = builder.DefineMethod("op_BitwiseOr", MethodAttributes.Public | MethodAttributes.Static, builder, new Type[] { builder, builder });
method.GetILGenerator().Emit(OpCodes.Ret);
TypeInfo createdType = builder.CreateTypeInfo();
object obj = Activator.CreateInstance(createdType);
Assert.Throws<ArgumentException>(null, () => Expression.OrElse(Expression.Constant(obj), Expression.Constant(obj)));
}
[Fact]
public static void Method_ParamsDontMatchOperator_ThrowsInvalidOperationException()
{
TypeBuilder builder = GetTypeBuilder();
MethodBuilder opTrue = builder.DefineMethod("op_True", MethodAttributes.SpecialName | MethodAttributes.Static, typeof(bool), new Type[] { builder });
opTrue.GetILGenerator().Emit(OpCodes.Ret);
MethodBuilder opFalse = builder.DefineMethod("op_False", MethodAttributes.SpecialName | MethodAttributes.Static, typeof(bool), new Type[] { builder });
opFalse.GetILGenerator().Emit(OpCodes.Ret);
MethodBuilder method = builder.DefineMethod("Method", MethodAttributes.Public | MethodAttributes.Static, typeof(int), new Type[] { typeof(int), typeof(int) });
method.GetILGenerator().Emit(OpCodes.Ret);
TypeInfo createdType = builder.CreateTypeInfo();
MethodInfo createdMethod = createdType.GetMethod("Method");
Assert.Throws<InvalidOperationException>(() => Expression.AndAlso(Expression.Constant(5), Expression.Constant(5), createdMethod));
Assert.Throws<InvalidOperationException>(() => Expression.OrElse(Expression.Constant(5), Expression.Constant(5), createdMethod));
}
[Fact]
public static void AndAlso_NoMethod_ParamsDontMatchOperator_ThrowsInvalidOperationException()
{
TypeBuilder builder = GetTypeBuilder();
MethodBuilder opTrue = builder.DefineMethod("op_True", MethodAttributes.SpecialName | MethodAttributes.Static, typeof(bool), new Type[] { builder });
opTrue.GetILGenerator().Emit(OpCodes.Ret);
MethodBuilder opFalse = builder.DefineMethod("op_False", MethodAttributes.SpecialName | MethodAttributes.Static, typeof(bool), new Type[] { builder });
opFalse.GetILGenerator().Emit(OpCodes.Ret);
MethodBuilder method = builder.DefineMethod("op_BitwiseAnd", MethodAttributes.Public | MethodAttributes.Static, typeof(int), new Type[] { typeof(int), typeof(int) });
method.GetILGenerator().Emit(OpCodes.Ret);
TypeInfo createdType = builder.CreateTypeInfo();
Assert.Throws<InvalidOperationException>(() => Expression.OrElse(Expression.Constant(5), Expression.Constant(5)));
}
[Fact]
public static void OrElse_NoMethod_ParamsDontMatchOperator_ThrowsInvalidOperationException()
{
TypeBuilder builder = GetTypeBuilder();
MethodBuilder opTrue = builder.DefineMethod("op_True", MethodAttributes.SpecialName | MethodAttributes.Static, typeof(bool), new Type[] { builder });
opTrue.GetILGenerator().Emit(OpCodes.Ret);
MethodBuilder opFalse = builder.DefineMethod("op_False", MethodAttributes.SpecialName | MethodAttributes.Static, typeof(bool), new Type[] { builder });
opFalse.GetILGenerator().Emit(OpCodes.Ret);
MethodBuilder method = builder.DefineMethod("op_BitwiseOr", MethodAttributes.Public | MethodAttributes.Static, typeof(int), new Type[] { typeof(int), typeof(int) });
method.GetILGenerator().Emit(OpCodes.Ret);
TypeInfo createdType = builder.CreateTypeInfo();
Assert.Throws<InvalidOperationException>(() => Expression.OrElse(Expression.Constant(5), Expression.Constant(5)));
}
#endif
[Fact]
public static void ImplicitConversionToBool_ThrowsArgumentException()
{
MethodInfo method = typeof(ClassWithImplicitBoolOperator).GetMethod(nameof(ClassWithImplicitBoolOperator.ConversionMethod));
Assert.Throws<ArgumentException>(null, () => Expression.AndAlso(Expression.Constant(new ClassWithImplicitBoolOperator()), Expression.Constant(new ClassWithImplicitBoolOperator()), method));
Assert.Throws<ArgumentException>(null, () => Expression.OrElse(Expression.Constant(new ClassWithImplicitBoolOperator()), Expression.Constant(new ClassWithImplicitBoolOperator()), method));
}
[Theory]
[ClassData(typeof(UnreadableExpressionsData))]
public static void AndAlso_LeftIsWriteOnly_ThrowsArgumentException(Expression unreadableExpression)
{
Assert.Throws<ArgumentException>("left", () => Expression.AndAlso(unreadableExpression, Expression.Constant(true)));
}
[Theory]
[ClassData(typeof(UnreadableExpressionsData))]
public static void AndAlso_RightIsWriteOnly_ThrowsArgumentException(Expression unreadableExpression)
{
Assert.Throws<ArgumentException>("right", () => Expression.AndAlso(Expression.Constant(true), unreadableExpression));
}
[Theory]
[ClassData(typeof(UnreadableExpressionsData))]
public static void OrElse_LeftIsWriteOnly_ThrowsArgumentException(Expression unreadableExpression)
{
Assert.Throws<ArgumentException>("left", () => Expression.OrElse(unreadableExpression, Expression.Constant(true)));
}
[Theory]
[ClassData(typeof(UnreadableExpressionsData))]
public static void OrElse_RightIsWriteOnly_ThrowsArgumentException(Expression unreadableExpression)
{
Assert.Throws<ArgumentException>("right", () => Expression.OrElse(Expression.Constant(false), unreadableExpression));
}
[Fact]
public static void ToStringTest()
{
// NB: These were && and || in .NET 3.5 but shipped as AndAlso and OrElse in .NET 4.0; we kept the latter.
BinaryExpression e1 = Expression.AndAlso(Expression.Parameter(typeof(bool), "a"), Expression.Parameter(typeof(bool), "b"));
Assert.Equal("(a AndAlso b)", e1.ToString());
BinaryExpression e2 = Expression.OrElse(Expression.Parameter(typeof(bool), "a"), Expression.Parameter(typeof(bool), "b"));
Assert.Equal("(a OrElse b)", e2.ToString());
}
#if FEATURE_COMPILE
[Fact]
public static void AndAlsoGlobalMethod()
{
MethodInfo method = GlobalMethod(typeof(int), new[] { typeof(int), typeof(int) });
Assert.Throws<ArgumentException>(() => Expression.AndAlso(Expression.Constant(1), Expression.Constant(2), method));
}
[Fact]
public static void OrElseGlobalMethod()
{
MethodInfo method = GlobalMethod(typeof(int), new [] { typeof(int), typeof(int) });
Assert.Throws<ArgumentException>(() => Expression.OrElse(Expression.Constant(1), Expression.Constant(2), method));
}
private static TypeBuilder GetTypeBuilder()
{
AssemblyBuilder assembly = AssemblyBuilder.DefineDynamicAssembly(new AssemblyName("Name"), AssemblyBuilderAccess.Run);
ModuleBuilder module = assembly.DefineDynamicModule("Name");
return module.DefineType("Type");
}
private static MethodInfo GlobalMethod(Type returnType, Type[] parameterTypes)
{
ModuleBuilder module = AssemblyBuilder.DefineDynamicAssembly(new AssemblyName("Name"), AssemblyBuilderAccess.Run).DefineDynamicModule("Module");
MethodBuilder globalMethod = module.DefineGlobalMethod("GlobalMethod", MethodAttributes.Public | MethodAttributes.Static, returnType, parameterTypes);
globalMethod.GetILGenerator().Emit(OpCodes.Ret);
module.CreateGlobalFunctions();
return module.GetMethod(globalMethod.Name);
}
#endif
public class NonGenericClass
{
public void InstanceMethod() { }
public static void StaticVoidMethod() { }
public static int StaticIntMethod0() => 0;
public static int StaticIntMethod1(int i) => 0;
public static int StaticIntMethod3(int i1, int i2, int i3) => 0;
public static int StaticIntMethod2Valid(int i1, int i2) => 0;
public static int StaticIntMethod2Invalid1(int i1, string i2) => 0;
public static string StaticIntMethod2Invalid2(int i1, int i2) => "abc";
}
public class TrueFalseClass
{
public int TrueCallCount { get; set; }
public int FalseCallCount { get; set; }
public int OperatorCallCount { get; set; }
public int MethodCallCount { get; set; }
public TrueFalseClass(int value) { Value = value; }
public int Value { get; }
public static bool operator true(TrueFalseClass c)
{
c.TrueCallCount++;
return c.Value != 0;
}
public static bool operator false(TrueFalseClass c)
{
c.FalseCallCount++;
return c.Value == 0;
}
public static TrueFalseClass operator &(TrueFalseClass c1, TrueFalseClass c2)
{
c1.OperatorCallCount++;
return new TrueFalseClass(c1.Value & c2.Value);
}
public static TrueFalseClass AndMethod(TrueFalseClass c1, TrueFalseClass c2)
{
c1.MethodCallCount++;
return new TrueFalseClass(c1.Value & c2.Value);
}
public static TrueFalseClass operator |(TrueFalseClass c1, TrueFalseClass c2)
{
c1.OperatorCallCount++;
return new TrueFalseClass(c1.Value | c2.Value);
}
public static TrueFalseClass OrMethod(TrueFalseClass c1, TrueFalseClass c2)
{
c1.MethodCallCount++;
return new TrueFalseClass(c1.Value | c2.Value);
}
}
public class NamedMethods
{
public NamedMethods(int value) { Value = value; }
public int Value { get; }
public static bool operator true(NamedMethods c) => c.Value != 0;
public static bool operator false(NamedMethods c) => c.Value == 0;
public static NamedMethods op_BitwiseAnd(NamedMethods c1, NamedMethods c2) => new NamedMethods(c1.Value & c2.Value);
public static NamedMethods op_BitwiseOr(NamedMethods c1, NamedMethods c2) => new NamedMethods(c1.Value | c2.Value);
}
public class ClassWithImplicitBoolOperator
{
public static ClassWithImplicitBoolOperator ConversionMethod(ClassWithImplicitBoolOperator bool1, ClassWithImplicitBoolOperator bool2)
{
return bool1;
}
public static implicit operator bool(ClassWithImplicitBoolOperator boolClass) => true;
}
}
}
| |
#region License
/*
/// Copyright 2002-2010 the original author or authors.
///
/// Licensed under the Apache License, Version 2.0 (the "License");
/// you may not use this file except in compliance with the License.
/// You may obtain a copy of the License at
///
/// http://www.apache.org/licenses/LICENSE-2.0
///
/// Unless required by applicable law or agreed to in writing, software
/// distributed under the License is distributed on an "AS IS" BASIS,
/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
/// See the License for the specific language governing permissions and
/// limitations under the License.
*/
#endregion
using System;
using System.Collections;
using System.Reflection;
using NUnit.Framework;
using Spring.Context;
using Spring.Context.Support;
using Spring.Objects.Factory;
using Spring.Objects.Factory.Config;
using Spring.Objects.Factory.Support;
namespace Spring.Testing.NUnit
{
/// <summary>
/// Convenient superclass for tests depending on a Spring context.
/// The test instance itself is populated by Dependency Injection.
/// </summary>
///
/// <remarks>
/// <p>Really for integration testing, not unit testing.
/// You should <i>not</i> normally use the Spring container
/// for unit tests: simply populate your objects in plain NUnit tests!</p>
///
/// <p>This supports two modes of populating the test:
/// <ul>
/// <li>Via Property Dependency Injection. Simply express dependencies on objects
/// in the test fixture, and they will be satisfied by autowiring by type.</li>
/// <li>Via Field Injection. Declare protected variables of the required type
/// which match named beans in the context. This is autowire by name,
/// rather than type. This approach is based on an approach originated by
/// Ara Abrahmian. Property Dependency Injection is the default: set the
/// "populateProtectedVariables" property to true in the constructor to switch
/// on Field Injection.</li>
/// </ul></p>
///
/// <p>This class will normally cache contexts based on a <i>context key</i>:
/// normally the config locations String array describing the Spring resource
/// descriptors making up the context. Unless the <code>SetDirty()</code> method
/// is called by a test, the context will not be reloaded, even across different
/// subclasses of this test. This is particularly beneficial if your context is
/// slow to construct, for example if you are using Hibernate and the time taken
/// to load the mappings is an issue.</p>
///
/// <p>If you don't want this behavior, you can override the <code>ContextKey</code>
/// property, most likely to return the test class. In conjunction with this you would
/// probably override the <code>GetContext</code> method, which by default loads
/// the locations specified by the <code>ConfigLocations</code> property.</p>
///
/// <p><b>WARNING:</b> When doing integration tests from within VS.NET, only use
/// assembly resource URLs. Else, you may see misleading failures when changing
/// context locations.</p>
/// </remarks>
///
/// <author>Rod Johnson</author>
/// <author>Rob Harrop</author>
/// <author>Rick Evans</author>
/// <author>Aleksandar Seovic (.NET)</author>
public abstract class AbstractDependencyInjectionSpringContextTests : AbstractSpringContextTests
{
private bool populateProtectedVariables = false;
private AutoWiringMode autowireMode = AutoWiringMode.ByType;
private bool dependencyCheck = true;
/// <summary>
/// Application context this test will run against.
/// </summary>
protected IConfigurableApplicationContext applicationContext;
/// <summary>
/// Holds names of the fields that should be used for field injection.
/// </summary>
protected string[] managedVariableNames;
private int loadCount = 0;
/// <summary>
/// Default constructor for AbstractDependencyInjectionSpringContextTests.
/// </summary>
public AbstractDependencyInjectionSpringContextTests()
{}
/// <summary>
/// Gets or sets a flag specifying whether to populate protected
/// variables of this test case.
/// </summary>
/// <value>
/// A flag specifying whether to populate protected variables of this test case.
/// Default is <b>false</b>.
/// </value>
public bool PopulateProtectedVariables
{
get { return populateProtectedVariables; }
set { populateProtectedVariables = value; }
}
/// <summary>
/// Gets or sets the autowire mode for test properties set by Dependency Injection.
/// </summary>
/// <value>
/// The autowire mode for test properties set by Dependency Injection.
/// The default is <see cref="AutoWiringMode.ByType"/>.
/// </value>
public AutoWiringMode AutowireMode
{
get { return autowireMode; }
set { autowireMode = value; }
}
/// <summary>
/// Gets or sets a flag specifying whether or not dependency checking
/// should be performed for test properties set by Dependency Injection.
/// </summary>
/// <value>
/// <p>A flag specifying whether or not dependency checking
/// should be performed for test properties set by Dependency Injection.</p>
/// <p>The default is <b>true</b>, meaning that tests cannot be run
/// unless all properties are populated.</p>
/// </value>
public bool DependencyCheck
{
get { return dependencyCheck; }
set { dependencyCheck = value; }
}
/// <summary>
/// Gets the current number of context load attempts.
/// </summary>
public int LoadCount
{
get { return loadCount; }
}
/// <summary>
/// Called to say that the "applicationContext" instance variable is dirty and
/// should be reloaded. We need to do this if a test has modified the context
/// (for example, by replacing an object definition).
/// </summary>
public void SetDirty()
{
SetDirty(ConfigLocations);
}
/// <summary>
/// Test setup method.
/// </summary>
[SetUp]
public virtual void SetUp()
{
this.applicationContext = GetContext(ContextKey);
InjectDependencies();
try
{
OnSetUp();
}
catch (Exception ex)
{
logger.Error("Setup error", ex);
throw;
}
}
/// <summary>
/// Inject dependencies into 'this' instance (that is, this test instance).
/// </summary>
/// <remarks>
/// <p>The default implementation populates protected variables if the
/// <see cref="PopulateProtectedVariables"/> property is set, else
/// uses autowiring if autowiring is switched on (which it is by default).</p>
/// <p>You can certainly override this method if you want to totally control
/// how dependencies are injected into 'this' instance.</p>
/// </remarks>
protected virtual void InjectDependencies()
{
if (PopulateProtectedVariables)
{
if (this.managedVariableNames == null)
{
InitManagedVariableNames();
}
InjectProtectedVariables();
}
else if (AutowireMode != AutoWiringMode.No)
{
IConfigurableListableObjectFactory factory = this.applicationContext.ObjectFactory;
((AbstractObjectFactory) factory).IgnoreDependencyType(typeof(AutoWiringMode));
factory.AutowireObjectProperties(this, AutowireMode, DependencyCheck);
}
}
/// <summary>
/// Gets a key for this context. Usually based on config locations, but
/// a subclass overriding buildContext() might want to return its class.
/// </summary>
protected virtual object ContextKey
{
get { return ConfigLocations; }
}
/// <summary>
/// Loads application context from the specified resource locations.
/// </summary>
/// <param name="locations">Resources to load object definitions from.</param>
protected override IConfigurableApplicationContext LoadContextLocations(string[] locations)
{
++this.loadCount;
return base.LoadContextLocations(locations);
}
/// <summary>
/// Retrieves the names of the fields that should be used for field injection.
/// </summary>
protected virtual void InitManagedVariableNames()
{
ArrayList managedVarNames = new ArrayList();
Type type = GetType();
do
{
FieldInfo[] fields =
type.GetFields(BindingFlags.DeclaredOnly | BindingFlags.NonPublic | BindingFlags.Instance);
if (logger.IsDebugEnabled)
{
logger.Debug("Found " + fields.Length + " fields on " + type);
}
for (int i = 0; i < fields.Length; i++)
{
FieldInfo field = fields[i];
if (logger.IsDebugEnabled)
{
logger.Debug("Candidate field: " + field);
}
if (IsProtectedInstanceField(field))
{
object oldValue = field.GetValue(this);
if (oldValue == null)
{
managedVarNames.Add(field.Name);
if (logger.IsDebugEnabled)
{
logger.Debug("Added managed variable '" + field.Name + "'");
}
}
else
{
if (logger.IsDebugEnabled)
{
logger.Debug("Rejected managed variable '" + field.Name + "'");
}
}
}
}
type = type.BaseType;
} while (type != typeof (AbstractDependencyInjectionSpringContextTests));
this.managedVariableNames = (string[]) managedVarNames.ToArray(typeof (string));
}
private static bool IsProtectedInstanceField(FieldInfo field)
{
return field.IsFamily;
}
/// <summary>
/// Injects protected fields using Field Injection.
/// </summary>
protected virtual void InjectProtectedVariables()
{
for (int i = 0; i < this.managedVariableNames.Length; i++)
{
string fieldName = this.managedVariableNames[i];
Object obj = null;
try
{
FieldInfo field = GetType().GetField(fieldName, BindingFlags.NonPublic | BindingFlags.Instance);
if (field != null)
{
BeforeProtectedVariableInjection(field);
obj = this.applicationContext.GetObject(fieldName, field.FieldType);
field.SetValue(this, obj);
if (logger.IsDebugEnabled)
{
logger.Debug("Populated field: " + field);
}
}
else
{
if (logger.IsWarnEnabled)
{
logger.Warn("No field with name '" + fieldName + "'");
}
}
}
catch (NoSuchObjectDefinitionException)
{
if (logger.IsWarnEnabled)
{
logger.Warn("No object definition with name '" + fieldName + "'");
}
}
}
}
/// <summary>
/// Called right before a field is being injected
/// </summary>
protected virtual void BeforeProtectedVariableInjection(FieldInfo fieldInfo)
{
}
/// <summary>
/// Subclasses can override this method in order to
/// add custom test setup logic after the context has been created and dependencies injected.
/// Called from this class's [SetUp] method.
/// </summary>
protected virtual void OnSetUp()
{}
/// <summary>
/// Test teardown method.
/// </summary>
[TearDown]
public void TearDown()
{
try
{
OnTearDown();
}
catch (Exception ex)
{
logger.Error("OnTearDown error", ex);
}
}
/// <summary>
/// Subclasses can override this method in order to
/// add custom test teardown logic. Called from this class's [TearDown] method.
/// </summary>
protected virtual void OnTearDown()
{}
/// <summary>
/// Subclasses must implement this property to return the locations of their
/// config files. A plain path will be treated as a file system location.
/// </summary>
/// <value>An array of config locations</value>
protected abstract string[] ConfigLocations { get; }
}
}
| |
/*
Copyright (c) 2004-2009 Krzysztof Ostrowski. All rights reserved.
Redistribution and use in source and binary forms,
with or without modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following
disclaimer in the documentation and/or other materials provided
with the distribution.
THIS SOFTWARE IS PROVIDED "AS IS" BY THE ABOVE COPYRIGHT HOLDER(S)
AND ALL OTHER CONTRIBUTORS 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 ABOVE COPYRIGHT HOLDER(S) OR ANY OTHER
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.Text;
using System.Reflection;
namespace QS.Fx.Printing
{
/// <summary>
/// The class used to display objects in a human-friendly manner.
/// </summary>
public static class Printable
{
/// <summary>
/// Create a human-friendly string representing the given object, using the annotations that drive the printing output.
/// </summary>
/// <param name="printedObject">The object to display.</param>
/// <returns>The display string.</returns>
public static string ToString(object printedObject)
{
if (printedObject == null)
return "null";
else
{
System.Type type = printedObject.GetType();
object[] attributes = type.GetCustomAttributes(typeof(PrintableAttribute), false);
PrintingStyle style = (attributes.Length > 0) ? (attributes[0] as PrintableAttribute).Style : PrintingStyle.Undefined;
return ToString(printedObject, style, PrintableAttribute.DefaultStyle, 0, false);
}
}
public static string ToString(
object printedObject, QS.Fx.Printing.PrintingStyle preferredStyle, QS.Fx.Printing.PrintingStyle defaultStyle, uint indentationLevel, bool indentFirst)
{
if (printedObject is System.Collections.IDictionary)
{
StringBuilder s = new StringBuilder();
s.Append("(");
bool isfirst2 = true;
foreach (System.Collections.DictionaryEntry element in ((System.Collections.IDictionary)printedObject))
{
if (isfirst2)
isfirst2 = false;
else
s.Append(", ");
s.Append(ToString(element.Key, preferredStyle, defaultStyle, indentationLevel, indentFirst));
s.Append(" : ");
s.Append(ToString(element.Value, preferredStyle, defaultStyle, indentationLevel, indentFirst));
}
s.Append(")");
return s.ToString();
}
else if (printedObject is System.Collections.ICollection)
{
StringBuilder s = new StringBuilder();
s.Append("(");
bool isfirst2 = true;
foreach (object element in ((System.Collections.ICollection)printedObject))
{
if (isfirst2)
isfirst2 = false;
else
s.Append(", ");
s.Append(ToString(element, preferredStyle, defaultStyle, indentationLevel, indentFirst));
}
s.Append(")");
return s.ToString();
}
else
{
switch (preferredStyle)
{
case PrintingStyle.Native:
return (printedObject != null) ? printedObject.ToString() : "null";
case PrintingStyle.Compact:
return ToString_Compact(printedObject);
case PrintingStyle.Expanded:
return ToString_Expanded(printedObject, indentationLevel, indentFirst);
case PrintingStyle.Undefined:
default:
{
switch (defaultStyle)
{
case PrintingStyle.Compact:
return ToString_Compact(printedObject);
case PrintingStyle.Expanded:
return ToString_Expanded(printedObject, indentationLevel, indentFirst);
case PrintingStyle.Native:
case PrintingStyle.Undefined:
default:
return (printedObject != null) ? printedObject.ToString() : "null";
}
}
}
}
}
private static string ToString_Compact(object printedObject)
{
if (printedObject == null)
return "null";
else if (printedObject.GetType().GetCustomAttributes(typeof(PrintableAttribute), false).Length > 0)
{
StringBuilder s = new StringBuilder();
System.Type type = printedObject.GetType();
object[] attributes = type.GetCustomAttributes(typeof(PrintableAttribute), false);
string name = null;
SelectionOption option = SelectionOption.Implicit;
if (attributes.Length > 0)
{
PrintableAttribute attribute = attributes[0] as PrintableAttribute;
name = attribute.Name;
option = attribute.SelectionOption;
}
s.Append(name != null ? name : type.Name);
s.Append("(");
bool isfirst = true;
foreach (FieldInfo info in type.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic))
{
if ((option == SelectionOption.Implicit &&
info.GetCustomAttributes(typeof(NonPrintableAttribute), true).Length == 0) ||
(option == SelectionOption.Explicit &&
info.GetCustomAttributes(typeof(PrintableAttribute), true).Length > 0))
{
if (isfirst)
isfirst = false;
else
s.Append(", ");
attributes = info.GetCustomAttributes(typeof(PrintableAttribute), false);
name = (attributes.Length > 0) ? (attributes[0] as PrintableAttribute).Name : null;
s.Append(name != null ? name : info.Name);
s.Append("=");
// s.Append(ToString_Compact(info.GetValue(printedObject)));
s.AppendLine(ToString(info.GetValue(printedObject), (attributes[0] as PrintableAttribute).Style, PrintingStyle.Compact, 0, false));
}
}
foreach (PropertyInfo info in type.GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic))
{
if ((option == SelectionOption.Implicit &&
info.GetCustomAttributes(typeof(NonPrintableAttribute), true).Length == 0) ||
(option == SelectionOption.Explicit &&
info.GetCustomAttributes(typeof(PrintableAttribute), true).Length > 0))
{
if (isfirst)
isfirst = false;
else
s.Append(", ");
attributes = info.GetCustomAttributes(typeof(PrintableAttribute), false);
name = (attributes.Length > 0) ? (attributes[0] as PrintableAttribute).Name : null;
s.Append(name != null ? name : info.Name);
s.Append("=");
s.AppendLine(ToString(info.GetValue(printedObject, null), (attributes[0] as PrintableAttribute).Style, PrintingStyle.Compact, 0, false));
}
}
s.Append(")");
return s.ToString();
}
else if (printedObject is System.Collections.IDictionary)
{
StringBuilder s = new StringBuilder();
s.Append("(");
bool isfirst2 = true;
foreach (System.Collections.DictionaryEntry element in ((System.Collections.IDictionary)printedObject))
{
if (isfirst2)
isfirst2 = false;
else
s.Append(", ");
s.Append(ToString_Compact(element.Key));
s.Append(" : ");
s.Append(ToString_Compact(element.Value));
}
s.Append(")");
return s.ToString();
}
else if (printedObject is System.Collections.ICollection)
{
StringBuilder s = new StringBuilder();
// s.Append(printedObject.GetType().Name);
s.Append("(");
bool isfirst2 = true;
foreach (object element in ((System.Collections.ICollection)printedObject))
{
if (isfirst2)
isfirst2 = false;
else
s.Append(", ");
s.Append(ToString_Compact(element));
}
s.Append(")");
return s.ToString();
}
else if (printedObject is System.Delegate)
{
StringBuilder s = new StringBuilder();
s.Append("delegate(");
System.Delegate d = printedObject as System.Delegate;
if (d == null)
s.Append("null");
else
{
if (d.Target == null)
s.Append("null");
else
{
s.Append(ToString_Compact(d.Target));
s.Append(" : ");
s.Append(d.Target.GetType().ToString());
}
s.Append(", ");
if (d.Method == null)
s.Append("null");
else
s.Append(d.Method.Name);
}
s.Append(")");
return s.ToString();
}
else
return printedObject.ToString();
}
private const uint IndentationSpaces = 2;
private static string ToString_Expanded(object printedObject, uint indentationLevel, bool indentFirst)
{
StringBuilder s = new StringBuilder();
if (indentFirst)
s.Append(' ', (int) (indentationLevel * IndentationSpaces));
if (printedObject == null)
{
s.Append("null");
}
else if (printedObject.GetType().GetCustomAttributes(typeof(PrintableAttribute), false).Length > 0)
{
System.Type type = printedObject.GetType();
object[] attributes = type.GetCustomAttributes(typeof(PrintableAttribute), false);
string name = null;
SelectionOption option = SelectionOption.Implicit;
PrintingStyle _printingstyle = PrintingStyle.Expanded;
if (attributes.Length > 0)
{
PrintableAttribute attribute = attributes[0] as PrintableAttribute;
name = attribute.Name;
option = attribute.SelectionOption;
_printingstyle = attribute.Style;
}
if (_printingstyle == PrintingStyle.Native)
s.Append(printedObject.ToString());
else
{
s.AppendLine(name != null ? name : type.Name);
s.Append(' ', (int)(indentationLevel * IndentationSpaces));
s.AppendLine("{");
foreach (FieldInfo info in type.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic))
{
if ((option == SelectionOption.Implicit &&
info.GetCustomAttributes(typeof(NonPrintableAttribute), true).Length == 0) ||
(option == SelectionOption.Explicit &&
info.GetCustomAttributes(typeof(PrintableAttribute), true).Length > 0))
{
attributes = info.GetCustomAttributes(typeof(PrintableAttribute), false);
name = (attributes.Length > 0) ? (attributes[0] as PrintableAttribute).Name : null;
s.Append(' ', (int)((indentationLevel + 1) * IndentationSpaces));
s.Append(name != null ? name : info.Name);
s.Append(" = ");
s.AppendLine(ToString(info.GetValue(printedObject), (attributes.Length > 0) ? (attributes[0] as PrintableAttribute).Style : PrintingStyle.Undefined,
PrintingStyle.Expanded, indentationLevel + 1, false));
}
}
foreach (PropertyInfo info in type.GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic))
{
if ((option == SelectionOption.Implicit &&
info.GetCustomAttributes(typeof(NonPrintableAttribute), true).Length == 0) ||
(option == SelectionOption.Explicit &&
info.GetCustomAttributes(typeof(PrintableAttribute), true).Length > 0))
{
attributes = info.GetCustomAttributes(typeof(PrintableAttribute), false);
name = (attributes.Length > 0) ? (attributes[0] as PrintableAttribute).Name : null;
s.Append(' ', (int)((indentationLevel + 1) * IndentationSpaces));
s.Append(name != null ? name : info.Name);
s.Append(" = ");
s.AppendLine(ToString(info.GetValue(printedObject, null),
(attributes.Length > 0) ? (attributes[0] as PrintableAttribute).Style : PrintingStyle.Undefined,
PrintingStyle.Expanded, indentationLevel + 1, false));
}
}
s.Append(' ', (int)(indentationLevel * IndentationSpaces));
s.Append("}");
}
}
else if (printedObject is System.Collections.IDictionary)
{
s.AppendLine("dictionary");
s.Append(' ', (int)(indentationLevel * IndentationSpaces));
s.AppendLine("{");
foreach (System.Collections.DictionaryEntry element in ((System.Collections.IDictionary)printedObject))
{
s.Append(' ', (int)((indentationLevel + 1) * IndentationSpaces));
s.Append(ToString_Compact(element.Key));
s.Append(" : ");
s.AppendLine(ToString_Expanded(element.Value, indentationLevel + 2, false));
}
s.Append(' ', (int)(indentationLevel * IndentationSpaces));
s.Append("}");
}
else if (printedObject is System.Collections.ICollection)
{
s.AppendLine("collection");
s.Append(' ', (int)(indentationLevel * IndentationSpaces));
s.AppendLine("{");
foreach (object element in ((System.Collections.ICollection)printedObject))
s.AppendLine(ToString_Expanded(element, indentationLevel + 1, true));
s.Append(' ', (int)(indentationLevel * IndentationSpaces));
s.Append("}");
}
else if (printedObject is System.Delegate)
{
System.Delegate d = printedObject as System.Delegate;
s.AppendLine("delegate");
s.Append(' ', (int)(indentationLevel * IndentationSpaces));
s.AppendLine("{");
s.Append(' ', (int)((indentationLevel + 1) * IndentationSpaces));
s.Append("target = ");
s.AppendLine(ToString_Compact(d.Target));
s.Append(' ', (int)((indentationLevel + 1) * IndentationSpaces));
s.Append("method = ");
s.AppendLine((d.Method == null) ? "null" : d.Method.Name);
s.Append(' ', (int)(indentationLevel * IndentationSpaces));
s.Append("}");
}
else
{
s.Append(printedObject.ToString());
}
return s.ToString();
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Microsoft.Win32.SafeHandles;
using System.Buffers;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Runtime.InteropServices;
using System.Threading;
namespace System.Net.Sockets
{
internal static class SocketPal
{
public const bool SupportsMultipleConnectAttempts = true;
private static void MicrosecondsToTimeValue(long microseconds, ref Interop.Winsock.TimeValue socketTime)
{
const int microcnv = 1000000;
socketTime.Seconds = (int)(microseconds / microcnv);
socketTime.Microseconds = (int)(microseconds % microcnv);
}
public static void Initialize()
{
// Ensure that WSAStartup has been called once per process.
// The System.Net.NameResolution contract is responsible for the initialization.
Dns.GetHostName();
}
public static SocketError GetLastSocketError()
{
int win32Error = Marshal.GetLastWin32Error();
Debug.Assert(win32Error != 0, "Expected non-0 error");
return (SocketError)win32Error;
}
public static SocketError CreateSocket(AddressFamily addressFamily, SocketType socketType, ProtocolType protocolType, out SafeSocketHandle socket)
{
socket = SafeSocketHandle.CreateWSASocket(addressFamily, socketType, protocolType);
return socket.IsInvalid ? GetLastSocketError() : SocketError.Success;
}
public static SocketError SetBlocking(SafeSocketHandle handle, bool shouldBlock, out bool willBlock)
{
int intBlocking = shouldBlock ? 0 : -1;
SocketError errorCode;
errorCode = Interop.Winsock.ioctlsocket(
handle,
Interop.Winsock.IoctlSocketConstants.FIONBIO,
ref intBlocking);
if (errorCode == SocketError.SocketError)
{
errorCode = GetLastSocketError();
}
willBlock = intBlocking == 0;
return errorCode;
}
public static SocketError GetSockName(SafeSocketHandle handle, byte[] buffer, ref int nameLen)
{
SocketError errorCode = Interop.Winsock.getsockname(handle, buffer, ref nameLen);
return errorCode == SocketError.SocketError ? GetLastSocketError() : SocketError.Success;
}
public static SocketError GetAvailable(SafeSocketHandle handle, out int available)
{
int value = 0;
SocketError errorCode = Interop.Winsock.ioctlsocket(
handle,
Interop.Winsock.IoctlSocketConstants.FIONREAD,
ref value);
available = value;
return errorCode == SocketError.SocketError ? GetLastSocketError() : SocketError.Success;
}
public static SocketError GetPeerName(SafeSocketHandle handle, byte[] buffer, ref int nameLen)
{
SocketError errorCode = Interop.Winsock.getpeername(handle, buffer, ref nameLen);
return errorCode == SocketError.SocketError ? GetLastSocketError() : SocketError.Success;
}
public static SocketError Bind(SafeSocketHandle handle, ProtocolType socketProtocolType, byte[] buffer, int nameLen)
{
SocketError errorCode = Interop.Winsock.bind(handle, buffer, nameLen);
return errorCode == SocketError.SocketError ? GetLastSocketError() : SocketError.Success;
}
public static SocketError Listen(SafeSocketHandle handle, int backlog)
{
SocketError errorCode = Interop.Winsock.listen(handle, backlog);
return errorCode == SocketError.SocketError ? GetLastSocketError() : SocketError.Success;
}
public static SocketError Accept(SafeSocketHandle handle, byte[] buffer, ref int nameLen, out SafeSocketHandle socket)
{
socket = SafeSocketHandle.Accept(handle, buffer, ref nameLen);
return socket.IsInvalid ? GetLastSocketError() : SocketError.Success;
}
public static SocketError Connect(SafeSocketHandle handle, byte[] peerAddress, int peerAddressLen)
{
SocketError errorCode = Interop.Winsock.WSAConnect(
handle.DangerousGetHandle(),
peerAddress,
peerAddressLen,
IntPtr.Zero,
IntPtr.Zero,
IntPtr.Zero,
IntPtr.Zero);
return errorCode == SocketError.SocketError ? GetLastSocketError() : SocketError.Success;
}
public static SocketError Send(SafeSocketHandle handle, IList<ArraySegment<byte>> buffers, SocketFlags socketFlags, out int bytesTransferred)
{
const int StackThreshold = 16; // arbitrary limit to avoid too much space on stack (note: may be over-sized, that's OK - length passed separately)
int count = buffers.Count;
bool useStack = count <= StackThreshold;
WSABuffer[] leasedWSA = null;
GCHandle[] leasedGC = null;
Span<WSABuffer> WSABuffers = stackalloc WSABuffer[0];
Span<GCHandle> objectsToPin = stackalloc GCHandle[0];
if (useStack)
{
WSABuffers = stackalloc WSABuffer[StackThreshold];
objectsToPin = stackalloc GCHandle[StackThreshold];
}
else
{
WSABuffers = leasedWSA = ArrayPool<WSABuffer>.Shared.Rent(count);
objectsToPin = leasedGC = ArrayPool<GCHandle>.Shared.Rent(count);
}
objectsToPin = objectsToPin.Slice(0, count);
objectsToPin.Clear(); // note: touched in finally
try
{
for (int i = 0; i < count; ++i)
{
ArraySegment<byte> buffer = buffers[i];
RangeValidationHelpers.ValidateSegment(buffer);
objectsToPin[i] = GCHandle.Alloc(buffer.Array, GCHandleType.Pinned);
WSABuffers[i].Length = buffer.Count;
WSABuffers[i].Pointer = Marshal.UnsafeAddrOfPinnedArrayElement(buffer.Array, buffer.Offset);
}
unsafe
{
SocketError errorCode = Interop.Winsock.WSASend(
handle.DangerousGetHandle(),
WSABuffers,
count,
out bytesTransferred,
socketFlags,
null,
IntPtr.Zero);
if (errorCode == SocketError.SocketError)
{
errorCode = GetLastSocketError();
}
return errorCode;
}
}
finally
{
for (int i = 0; i < count; ++i)
{
if (objectsToPin[i].IsAllocated)
{
objectsToPin[i].Free();
}
}
if (!useStack)
{
ArrayPool<WSABuffer>.Shared.Return(leasedWSA);
ArrayPool<GCHandle>.Shared.Return(leasedGC);
}
}
}
public static unsafe SocketError Send(SafeSocketHandle handle, byte[] buffer, int offset, int size, SocketFlags socketFlags, out int bytesTransferred) =>
Send(handle, new ReadOnlySpan<byte>(buffer, offset, size), socketFlags, out bytesTransferred);
public static unsafe SocketError Send(SafeSocketHandle handle, ReadOnlySpan<byte> buffer, SocketFlags socketFlags, out int bytesTransferred)
{
int bytesSent;
fixed (byte* bufferPtr = &MemoryMarshal.GetReference(buffer))
{
bytesSent = Interop.Winsock.send(handle.DangerousGetHandle(), bufferPtr, buffer.Length, socketFlags);
}
if (bytesSent == (int)SocketError.SocketError)
{
bytesTransferred = 0;
return GetLastSocketError();
}
bytesTransferred = bytesSent;
return SocketError.Success;
}
public static unsafe SocketError SendFile(SafeSocketHandle handle, SafeFileHandle fileHandle, byte[] preBuffer, byte[] postBuffer, TransmitFileOptions flags)
{
fixed (byte* prePinnedBuffer = preBuffer)
fixed (byte* postPinnedBuffer = postBuffer)
{
bool success = TransmitFileHelper(handle, fileHandle, null, preBuffer, postBuffer, flags);
return (success ? SocketError.Success : SocketPal.GetLastSocketError());
}
}
public static unsafe SocketError SendTo(SafeSocketHandle handle, byte[] buffer, int offset, int size, SocketFlags socketFlags, byte[] peerAddress, int peerAddressSize, out int bytesTransferred)
{
int bytesSent;
if (buffer.Length == 0)
{
bytesSent = Interop.Winsock.sendto(
handle.DangerousGetHandle(),
null,
0,
socketFlags,
peerAddress,
peerAddressSize);
}
else
{
fixed (byte* pinnedBuffer = &buffer[0])
{
bytesSent = Interop.Winsock.sendto(
handle.DangerousGetHandle(),
pinnedBuffer + offset,
size,
socketFlags,
peerAddress,
peerAddressSize);
}
}
if (bytesSent == (int)SocketError.SocketError)
{
bytesTransferred = 0;
return GetLastSocketError();
}
bytesTransferred = bytesSent;
return SocketError.Success;
}
public static SocketError Receive(SafeSocketHandle handle, IList<ArraySegment<byte>> buffers, ref SocketFlags socketFlags, out int bytesTransferred)
{
const int StackThreshold = 16; // arbitrary limit to avoid too much space on stack (note: may be over-sized, that's OK - length passed separately)
int count = buffers.Count;
bool useStack = count <= StackThreshold;
WSABuffer[] leasedWSA = null;
GCHandle[] leasedGC = null;
Span<WSABuffer> WSABuffers = stackalloc WSABuffer[0];
Span<GCHandle> objectsToPin = stackalloc GCHandle[0];
if (useStack)
{
WSABuffers = stackalloc WSABuffer[StackThreshold];
objectsToPin = stackalloc GCHandle[StackThreshold];
}
else
{
WSABuffers = leasedWSA = ArrayPool<WSABuffer>.Shared.Rent(count);
objectsToPin = leasedGC = ArrayPool<GCHandle>.Shared.Rent(count);
}
objectsToPin = objectsToPin.Slice(0, count);
objectsToPin.Clear(); // note: touched in finally
try
{
for (int i = 0; i < count; ++i)
{
ArraySegment<byte> buffer = buffers[i];
RangeValidationHelpers.ValidateSegment(buffer);
objectsToPin[i] = GCHandle.Alloc(buffer.Array, GCHandleType.Pinned);
WSABuffers[i].Length = buffer.Count;
WSABuffers[i].Pointer = Marshal.UnsafeAddrOfPinnedArrayElement(buffer.Array, buffer.Offset);
}
unsafe
{
SocketError errorCode = Interop.Winsock.WSARecv(
handle.DangerousGetHandle(),
WSABuffers,
count,
out bytesTransferred,
ref socketFlags,
null,
IntPtr.Zero);
if (errorCode == SocketError.SocketError)
{
errorCode = GetLastSocketError();
}
return errorCode;
}
}
finally
{
for (int i = 0; i < count; ++i)
{
if (objectsToPin[i].IsAllocated)
{
objectsToPin[i].Free();
}
}
if (!useStack)
{
ArrayPool<WSABuffer>.Shared.Return(leasedWSA);
ArrayPool<GCHandle>.Shared.Return(leasedGC);
}
}
}
public static unsafe SocketError Receive(SafeSocketHandle handle, byte[] buffer, int offset, int size, SocketFlags socketFlags, out int bytesTransferred) =>
Receive(handle, new Span<byte>(buffer, offset, size), socketFlags, out bytesTransferred);
public static unsafe SocketError Receive(SafeSocketHandle handle, Span<byte> buffer, SocketFlags socketFlags, out int bytesTransferred)
{
int bytesReceived;
fixed (byte* bufferPtr = &MemoryMarshal.GetReference(buffer))
{
bytesReceived = Interop.Winsock.recv(handle.DangerousGetHandle(), bufferPtr, buffer.Length, socketFlags);
}
if (bytesReceived == (int)SocketError.SocketError)
{
bytesTransferred = 0;
return GetLastSocketError();
}
bytesTransferred = bytesReceived;
return SocketError.Success;
}
public static unsafe IPPacketInformation GetIPPacketInformation(Interop.Winsock.ControlData* controlBuffer)
{
IPAddress address = controlBuffer->length == UIntPtr.Zero ? IPAddress.None : new IPAddress((long)controlBuffer->address);
return new IPPacketInformation(address, (int)controlBuffer->index);
}
public static unsafe IPPacketInformation GetIPPacketInformation(Interop.Winsock.ControlDataIPv6* controlBuffer)
{
IPAddress address = controlBuffer->length != UIntPtr.Zero ?
new IPAddress(new ReadOnlySpan<byte>(controlBuffer->address, Interop.Winsock.IPv6AddressLength)) :
IPAddress.IPv6None;
return new IPPacketInformation(address, (int)controlBuffer->index);
}
public static unsafe SocketError ReceiveMessageFrom(Socket socket, SafeSocketHandle handle, byte[] buffer, int offset, int size, ref SocketFlags socketFlags, Internals.SocketAddress socketAddress, out Internals.SocketAddress receiveAddress, out IPPacketInformation ipPacketInformation, out int bytesTransferred)
{
bool ipv4, ipv6;
Socket.GetIPProtocolInformation(socket.AddressFamily, socketAddress, out ipv4, out ipv6);
bytesTransferred = 0;
receiveAddress = socketAddress;
ipPacketInformation = default(IPPacketInformation);
fixed (byte* ptrBuffer = buffer)
fixed (byte* ptrSocketAddress = socketAddress.Buffer)
{
Interop.Winsock.WSAMsg wsaMsg;
wsaMsg.socketAddress = (IntPtr)ptrSocketAddress;
wsaMsg.addressLength = (uint)socketAddress.Size;
wsaMsg.flags = socketFlags;
WSABuffer wsaBuffer;
wsaBuffer.Length = size;
wsaBuffer.Pointer = (IntPtr)(ptrBuffer + offset);
wsaMsg.buffers = (IntPtr)(&wsaBuffer);
wsaMsg.count = 1;
if (ipv4)
{
Interop.Winsock.ControlData controlBuffer;
wsaMsg.controlBuffer.Pointer = (IntPtr)(&controlBuffer);
wsaMsg.controlBuffer.Length = sizeof(Interop.Winsock.ControlData);
if (socket.WSARecvMsgBlocking(
handle.DangerousGetHandle(),
(IntPtr)(&wsaMsg),
out bytesTransferred,
IntPtr.Zero,
IntPtr.Zero) == SocketError.SocketError)
{
return GetLastSocketError();
}
ipPacketInformation = GetIPPacketInformation(&controlBuffer);
}
else if (ipv6)
{
Interop.Winsock.ControlDataIPv6 controlBuffer;
wsaMsg.controlBuffer.Pointer = (IntPtr)(&controlBuffer);
wsaMsg.controlBuffer.Length = sizeof(Interop.Winsock.ControlDataIPv6);
if (socket.WSARecvMsgBlocking(
handle.DangerousGetHandle(),
(IntPtr)(&wsaMsg),
out bytesTransferred,
IntPtr.Zero,
IntPtr.Zero) == SocketError.SocketError)
{
return GetLastSocketError();
}
ipPacketInformation = GetIPPacketInformation(&controlBuffer);
}
else
{
wsaMsg.controlBuffer.Pointer = IntPtr.Zero;
wsaMsg.controlBuffer.Length = 0;
if (socket.WSARecvMsgBlocking(
handle.DangerousGetHandle(),
(IntPtr)(&wsaMsg),
out bytesTransferred,
IntPtr.Zero,
IntPtr.Zero) == SocketError.SocketError)
{
return GetLastSocketError();
}
}
socketFlags = wsaMsg.flags;
}
return SocketError.Success;
}
public static unsafe SocketError ReceiveFrom(SafeSocketHandle handle, byte[] buffer, int offset, int size, SocketFlags socketFlags, byte[] socketAddress, ref int addressLength, out int bytesTransferred)
{
int bytesReceived;
if (buffer.Length == 0)
{
bytesReceived = Interop.Winsock.recvfrom(handle.DangerousGetHandle(), null, 0, socketFlags, socketAddress, ref addressLength);
}
else
{
fixed (byte* pinnedBuffer = &buffer[0])
{
bytesReceived = Interop.Winsock.recvfrom(handle.DangerousGetHandle(), pinnedBuffer + offset, size, socketFlags, socketAddress, ref addressLength);
}
}
if (bytesReceived == (int)SocketError.SocketError)
{
bytesTransferred = 0;
return GetLastSocketError();
}
bytesTransferred = bytesReceived;
return SocketError.Success;
}
public static SocketError WindowsIoctl(SafeSocketHandle handle, int ioControlCode, byte[] optionInValue, byte[] optionOutValue, out int optionLength)
{
if (ioControlCode == Interop.Winsock.IoctlSocketConstants.FIONBIO)
{
throw new InvalidOperationException(SR.net_sockets_useblocking);
}
SocketError errorCode = Interop.Winsock.WSAIoctl_Blocking(
handle.DangerousGetHandle(),
ioControlCode,
optionInValue,
optionInValue != null ? optionInValue.Length : 0,
optionOutValue,
optionOutValue != null ? optionOutValue.Length : 0,
out optionLength,
IntPtr.Zero,
IntPtr.Zero);
return errorCode == SocketError.SocketError ? GetLastSocketError() : SocketError.Success;
}
public static unsafe SocketError SetSockOpt(SafeSocketHandle handle, SocketOptionLevel optionLevel, SocketOptionName optionName, int optionValue)
{
SocketError errorCode;
if (optionLevel == SocketOptionLevel.Tcp &&
(optionName == SocketOptionName.TcpKeepAliveTime || optionName == SocketOptionName.TcpKeepAliveInterval) &&
IOControlKeepAlive.IsNeeded)
{
errorCode = IOControlKeepAlive.Set(handle, optionName, optionValue);
}
else
{
errorCode = Interop.Winsock.setsockopt(
handle,
optionLevel,
optionName,
ref optionValue,
sizeof(int));
}
return errorCode == SocketError.SocketError ? GetLastSocketError() : SocketError.Success;
}
public static SocketError SetSockOpt(SafeSocketHandle handle, SocketOptionLevel optionLevel, SocketOptionName optionName, byte[] optionValue)
{
SocketError errorCode;
if (optionLevel == SocketOptionLevel.Tcp &&
(optionName == SocketOptionName.TcpKeepAliveTime || optionName == SocketOptionName.TcpKeepAliveInterval) &&
IOControlKeepAlive.IsNeeded)
{
return IOControlKeepAlive.Set(handle, optionName, optionValue);
}
else
{
errorCode = Interop.Winsock.setsockopt(
handle,
optionLevel,
optionName,
optionValue,
optionValue != null ? optionValue.Length : 0);
return errorCode == SocketError.SocketError ? GetLastSocketError() : SocketError.Success;
}
}
public static void SetReceivingDualModeIPv4PacketInformation(Socket socket)
{
socket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.PacketInformation, true);
}
public static SocketError SetMulticastOption(SafeSocketHandle handle, SocketOptionName optionName, MulticastOption optionValue)
{
Interop.Winsock.IPMulticastRequest ipmr = new Interop.Winsock.IPMulticastRequest();
#pragma warning disable CS0618 // Address is marked obsolete
ipmr.MulticastAddress = unchecked((int)optionValue.Group.Address);
#pragma warning restore CS0618
if (optionValue.LocalAddress != null)
{
#pragma warning disable CS0618 // Address is marked obsolete
ipmr.InterfaceAddress = unchecked((int)optionValue.LocalAddress.Address);
#pragma warning restore CS0618
}
else
{ //this structure works w/ interfaces as well
int ifIndex = IPAddress.HostToNetworkOrder(optionValue.InterfaceIndex);
ipmr.InterfaceAddress = unchecked((int)ifIndex);
}
#if BIGENDIAN
ipmr.MulticastAddress = (int) (((uint) ipmr.MulticastAddress << 24) |
(((uint) ipmr.MulticastAddress & 0x0000FF00) << 8) |
(((uint) ipmr.MulticastAddress >> 8) & 0x0000FF00) |
((uint) ipmr.MulticastAddress >> 24));
if (optionValue.LocalAddress != null)
{
ipmr.InterfaceAddress = (int) (((uint) ipmr.InterfaceAddress << 24) |
(((uint) ipmr.InterfaceAddress & 0x0000FF00) << 8) |
(((uint) ipmr.InterfaceAddress >> 8) & 0x0000FF00) |
((uint) ipmr.InterfaceAddress >> 24));
}
#endif
// This can throw ObjectDisposedException.
SocketError errorCode = Interop.Winsock.setsockopt(
handle,
SocketOptionLevel.IP,
optionName,
ref ipmr,
Interop.Winsock.IPMulticastRequest.Size);
return errorCode == SocketError.SocketError ? GetLastSocketError() : SocketError.Success;
}
public static SocketError SetIPv6MulticastOption(SafeSocketHandle handle, SocketOptionName optionName, IPv6MulticastOption optionValue)
{
Interop.Winsock.IPv6MulticastRequest ipmr = new Interop.Winsock.IPv6MulticastRequest();
ipmr.MulticastAddress = optionValue.Group.GetAddressBytes();
ipmr.InterfaceIndex = unchecked((int)optionValue.InterfaceIndex);
// This can throw ObjectDisposedException.
SocketError errorCode = Interop.Winsock.setsockopt(
handle,
SocketOptionLevel.IPv6,
optionName,
ref ipmr,
Interop.Winsock.IPv6MulticastRequest.Size);
return errorCode == SocketError.SocketError ? GetLastSocketError() : SocketError.Success;
}
public static SocketError SetLingerOption(SafeSocketHandle handle, LingerOption optionValue)
{
Interop.Winsock.Linger lngopt = new Interop.Winsock.Linger();
lngopt.OnOff = optionValue.Enabled ? (ushort)1 : (ushort)0;
lngopt.Time = (ushort)optionValue.LingerTime;
// This can throw ObjectDisposedException.
SocketError errorCode = Interop.Winsock.setsockopt(
handle,
SocketOptionLevel.Socket,
SocketOptionName.Linger,
ref lngopt,
4);
return errorCode == SocketError.SocketError ? GetLastSocketError() : SocketError.Success;
}
public static void SetIPProtectionLevel(Socket socket, SocketOptionLevel optionLevel, int protectionLevel)
{
socket.SetSocketOption(optionLevel, SocketOptionName.IPProtectionLevel, protectionLevel);
}
public static SocketError GetSockOpt(SafeSocketHandle handle, SocketOptionLevel optionLevel, SocketOptionName optionName, out int optionValue)
{
if (optionLevel == SocketOptionLevel.Tcp &&
(optionName == SocketOptionName.TcpKeepAliveTime || optionName == SocketOptionName.TcpKeepAliveInterval) &&
IOControlKeepAlive.IsNeeded)
{
optionValue = IOControlKeepAlive.Get(handle, optionName);
return SocketError.Success;
}
int optionLength = 4; // sizeof(int)
SocketError errorCode = Interop.Winsock.getsockopt(
handle,
optionLevel,
optionName,
out optionValue,
ref optionLength);
return errorCode == SocketError.SocketError ? GetLastSocketError() : SocketError.Success;
}
public static SocketError GetSockOpt(SafeSocketHandle handle, SocketOptionLevel optionLevel, SocketOptionName optionName, byte[] optionValue, ref int optionLength)
{
if (optionLevel == SocketOptionLevel.Tcp &&
(optionName == SocketOptionName.TcpKeepAliveTime || optionName == SocketOptionName.TcpKeepAliveInterval) &&
IOControlKeepAlive.IsNeeded)
{
return IOControlKeepAlive.Get(handle, optionName, optionValue, ref optionLength);
}
SocketError errorCode = Interop.Winsock.getsockopt(
handle,
optionLevel,
optionName,
optionValue,
ref optionLength);
return errorCode == SocketError.SocketError ? GetLastSocketError() : SocketError.Success;
}
public static SocketError GetMulticastOption(SafeSocketHandle handle, SocketOptionName optionName, out MulticastOption optionValue)
{
Interop.Winsock.IPMulticastRequest ipmr = new Interop.Winsock.IPMulticastRequest();
int optlen = Interop.Winsock.IPMulticastRequest.Size;
// This can throw ObjectDisposedException.
SocketError errorCode = Interop.Winsock.getsockopt(
handle,
SocketOptionLevel.IP,
optionName,
out ipmr,
ref optlen);
if (errorCode == SocketError.SocketError)
{
optionValue = default(MulticastOption);
return GetLastSocketError();
}
#if BIGENDIAN
ipmr.MulticastAddress = (int) (((uint) ipmr.MulticastAddress << 24) |
(((uint) ipmr.MulticastAddress & 0x0000FF00) << 8) |
(((uint) ipmr.MulticastAddress >> 8) & 0x0000FF00) |
((uint) ipmr.MulticastAddress >> 24));
ipmr.InterfaceAddress = (int) (((uint) ipmr.InterfaceAddress << 24) |
(((uint) ipmr.InterfaceAddress & 0x0000FF00) << 8) |
(((uint) ipmr.InterfaceAddress >> 8) & 0x0000FF00) |
((uint) ipmr.InterfaceAddress >> 24));
#endif // BIGENDIAN
IPAddress multicastAddr = new IPAddress(ipmr.MulticastAddress);
IPAddress multicastIntr = new IPAddress(ipmr.InterfaceAddress);
optionValue = new MulticastOption(multicastAddr, multicastIntr);
return SocketError.Success;
}
public static SocketError GetIPv6MulticastOption(SafeSocketHandle handle, SocketOptionName optionName, out IPv6MulticastOption optionValue)
{
Interop.Winsock.IPv6MulticastRequest ipmr = new Interop.Winsock.IPv6MulticastRequest();
int optlen = Interop.Winsock.IPv6MulticastRequest.Size;
// This can throw ObjectDisposedException.
SocketError errorCode = Interop.Winsock.getsockopt(
handle,
SocketOptionLevel.IP,
optionName,
out ipmr,
ref optlen);
if (errorCode == SocketError.SocketError)
{
optionValue = default(IPv6MulticastOption);
return GetLastSocketError();
}
optionValue = new IPv6MulticastOption(new IPAddress(ipmr.MulticastAddress), ipmr.InterfaceIndex);
return SocketError.Success;
}
public static SocketError GetLingerOption(SafeSocketHandle handle, out LingerOption optionValue)
{
Interop.Winsock.Linger lngopt = new Interop.Winsock.Linger();
int optlen = 4;
// This can throw ObjectDisposedException.
SocketError errorCode = Interop.Winsock.getsockopt(
handle,
SocketOptionLevel.Socket,
SocketOptionName.Linger,
out lngopt,
ref optlen);
if (errorCode == SocketError.SocketError)
{
optionValue = default(LingerOption);
return GetLastSocketError();
}
optionValue = new LingerOption(lngopt.OnOff != 0, (int)lngopt.Time);
return SocketError.Success;
}
public static unsafe SocketError Poll(SafeSocketHandle handle, int microseconds, SelectMode mode, out bool status)
{
IntPtr rawHandle = handle.DangerousGetHandle();
IntPtr* fileDescriptorSet = stackalloc IntPtr[2] { (IntPtr)1, rawHandle };
Interop.Winsock.TimeValue IOwait = new Interop.Winsock.TimeValue();
// A negative timeout value implies an indefinite wait.
int socketCount;
if (microseconds != -1)
{
MicrosecondsToTimeValue((long)(uint)microseconds, ref IOwait);
socketCount =
Interop.Winsock.select(
0,
mode == SelectMode.SelectRead ? fileDescriptorSet : null,
mode == SelectMode.SelectWrite ? fileDescriptorSet : null,
mode == SelectMode.SelectError ? fileDescriptorSet : null,
ref IOwait);
}
else
{
socketCount =
Interop.Winsock.select(
0,
mode == SelectMode.SelectRead ? fileDescriptorSet : null,
mode == SelectMode.SelectWrite ? fileDescriptorSet : null,
mode == SelectMode.SelectError ? fileDescriptorSet : null,
IntPtr.Zero);
}
if ((SocketError)socketCount == SocketError.SocketError)
{
status = false;
return GetLastSocketError();
}
status = (int)fileDescriptorSet[0] != 0 && fileDescriptorSet[1] == rawHandle;
return SocketError.Success;
}
public static unsafe SocketError Select(IList checkRead, IList checkWrite, IList checkError, int microseconds)
{
const int StackThreshold = 64; // arbitrary limit to avoid too much space on stack
bool ShouldStackAlloc(IList list, ref IntPtr[] lease, out Span<IntPtr> span)
{
int count;
if (list == null || (count = list.Count) == 0)
{
span = default;
return false;
}
if (count >= StackThreshold) // note on >= : the first element is reserved for internal length
{
span = lease = ArrayPool<IntPtr>.Shared.Rent(count + 1);
return false;
}
span = default;
return true;
}
IntPtr[] leaseRead = null, leaseWrite = null, leaseError = null;
try
{
Span<IntPtr> readfileDescriptorSet = ShouldStackAlloc(checkRead, ref leaseRead, out var tmp) ? stackalloc IntPtr[StackThreshold] : tmp;
Socket.SocketListToFileDescriptorSet(checkRead, readfileDescriptorSet);
Span<IntPtr> writefileDescriptorSet = ShouldStackAlloc(checkWrite, ref leaseWrite, out tmp) ? stackalloc IntPtr[StackThreshold] : tmp;
Socket.SocketListToFileDescriptorSet(checkWrite, writefileDescriptorSet);
Span<IntPtr> errfileDescriptorSet = ShouldStackAlloc(checkError, ref leaseError, out tmp) ? stackalloc IntPtr[StackThreshold] : tmp;
Socket.SocketListToFileDescriptorSet(checkError, errfileDescriptorSet);
// This code used to erroneously pass a non-null timeval structure containing zeroes
// to select() when the caller specified (-1) for the microseconds parameter. That
// caused select to actually have a *zero* timeout instead of an infinite timeout
// turning the operation into a non-blocking poll.
//
// Now we pass a null timeval struct when microseconds is (-1).
//
// Negative microsecond values that weren't exactly (-1) were originally successfully
// converted to a timeval struct containing unsigned non-zero integers. This code
// retains that behavior so that any app working around the original bug with,
// for example, (-2) specified for microseconds, will continue to get the same behavior.
int socketCount;
fixed (IntPtr* readPtr = &MemoryMarshal.GetReference(readfileDescriptorSet))
fixed (IntPtr* writePtr = &MemoryMarshal.GetReference(writefileDescriptorSet))
fixed (IntPtr* errPtr = &MemoryMarshal.GetReference(errfileDescriptorSet))
{
if (microseconds != -1)
{
Interop.Winsock.TimeValue IOwait = new Interop.Winsock.TimeValue();
MicrosecondsToTimeValue((long)(uint)microseconds, ref IOwait);
socketCount =
Interop.Winsock.select(
0, // ignored value
readPtr,
writePtr,
errPtr,
ref IOwait);
}
else
{
socketCount =
Interop.Winsock.select(
0, // ignored value
readPtr,
writePtr,
errPtr,
IntPtr.Zero);
}
}
if (NetEventSource.IsEnabled)
NetEventSource.Info(null, $"Interop.Winsock.select returns socketCount:{socketCount}");
if ((SocketError)socketCount == SocketError.SocketError)
{
return GetLastSocketError();
}
Socket.SelectFileDescriptor(checkRead, readfileDescriptorSet);
Socket.SelectFileDescriptor(checkWrite, writefileDescriptorSet);
Socket.SelectFileDescriptor(checkError, errfileDescriptorSet);
return SocketError.Success;
}
finally
{
if (leaseRead != null) ArrayPool<IntPtr>.Shared.Return(leaseRead);
if (leaseWrite != null) ArrayPool<IntPtr>.Shared.Return(leaseWrite);
if (leaseError != null) ArrayPool<IntPtr>.Shared.Return(leaseError);
}
}
public static SocketError Shutdown(SafeSocketHandle handle, bool isConnected, bool isDisconnected, SocketShutdown how)
{
SocketError err = Interop.Winsock.shutdown(handle, (int)how);
if (err != SocketError.SocketError)
{
return SocketError.Success;
}
err = GetLastSocketError();
Debug.Assert(err != SocketError.NotConnected || (!isConnected && !isDisconnected));
return err;
}
public static unsafe SocketError ConnectAsync(Socket socket, SafeSocketHandle handle, byte[] socketAddress, int socketAddressLen, ConnectOverlappedAsyncResult asyncResult)
{
// This will pin the socketAddress buffer.
asyncResult.SetUnmanagedStructures(socketAddress);
try
{
int ignoreBytesSent;
bool success = socket.ConnectEx(
handle,
Marshal.UnsafeAddrOfPinnedArrayElement(socketAddress, 0),
socketAddressLen,
IntPtr.Zero,
0,
out ignoreBytesSent,
asyncResult.DangerousOverlappedPointer); // SafeHandle was just created in SetUnmanagedStructures
return asyncResult.ProcessOverlappedResult(success, 0);
}
catch
{
asyncResult.ReleaseUnmanagedStructures();
throw;
}
}
public static unsafe SocketError SendAsync(SafeSocketHandle handle, byte[] buffer, int offset, int count, SocketFlags socketFlags, OverlappedAsyncResult asyncResult)
{
// Set up unmanaged structures for overlapped WSASend.
asyncResult.SetUnmanagedStructures(buffer, offset, count, null);
try
{
int bytesTransferred;
SocketError errorCode = Interop.Winsock.WSASend(
handle,
ref asyncResult._singleBuffer,
1, // There is only ever 1 buffer being sent.
out bytesTransferred,
socketFlags,
asyncResult.DangerousOverlappedPointer, // SafeHandle was just created in SetUnmanagedStructures
IntPtr.Zero);
return asyncResult.ProcessOverlappedResult(errorCode == SocketError.Success, bytesTransferred);
}
catch
{
asyncResult.ReleaseUnmanagedStructures();
throw;
}
}
public static unsafe SocketError SendAsync(SafeSocketHandle handle, IList<ArraySegment<byte>> buffers, SocketFlags socketFlags, OverlappedAsyncResult asyncResult)
{
// Set up asyncResult for overlapped WSASend.
asyncResult.SetUnmanagedStructures(buffers);
try
{
int bytesTransferred;
SocketError errorCode = Interop.Winsock.WSASend(
handle,
asyncResult._wsaBuffers,
asyncResult._wsaBuffers.Length,
out bytesTransferred,
socketFlags,
asyncResult.DangerousOverlappedPointer, // SafeHandle was just created in SetUnmanagedStructures
IntPtr.Zero);
return asyncResult.ProcessOverlappedResult(errorCode == SocketError.Success, bytesTransferred);
}
catch
{
asyncResult.ReleaseUnmanagedStructures();
throw;
}
}
// This assumes preBuffer/postBuffer are pinned already
private static unsafe bool TransmitFileHelper(
SafeHandle socket,
SafeHandle fileHandle,
NativeOverlapped* overlapped,
byte[] preBuffer,
byte[] postBuffer,
TransmitFileOptions flags)
{
bool needTransmitFileBuffers = false;
Interop.Mswsock.TransmitFileBuffers transmitFileBuffers = default(Interop.Mswsock.TransmitFileBuffers);
if (preBuffer != null && preBuffer.Length > 0)
{
needTransmitFileBuffers = true;
transmitFileBuffers.Head = Marshal.UnsafeAddrOfPinnedArrayElement(preBuffer, 0);
transmitFileBuffers.HeadLength = preBuffer.Length;
}
if (postBuffer != null && postBuffer.Length > 0)
{
needTransmitFileBuffers = true;
transmitFileBuffers.Tail = Marshal.UnsafeAddrOfPinnedArrayElement(postBuffer, 0);
transmitFileBuffers.TailLength = postBuffer.Length;
}
bool success = Interop.Mswsock.TransmitFile(socket, fileHandle, 0, 0, overlapped,
needTransmitFileBuffers ? &transmitFileBuffers : null, flags);
return success;
}
public static unsafe SocketError SendFileAsync(SafeSocketHandle handle, FileStream fileStream, byte[] preBuffer, byte[] postBuffer, TransmitFileOptions flags, TransmitFileAsyncResult asyncResult)
{
asyncResult.SetUnmanagedStructures(fileStream, preBuffer, postBuffer, (flags & (TransmitFileOptions.Disconnect | TransmitFileOptions.ReuseSocket)) != 0);
try
{
bool success = TransmitFileHelper(
handle,
fileStream?.SafeFileHandle,
asyncResult.DangerousOverlappedPointer, // SafeHandle was just created in SetUnmanagedStructures
preBuffer,
postBuffer,
flags);
return asyncResult.ProcessOverlappedResult(success, 0);
}
catch
{
asyncResult.ReleaseUnmanagedStructures();
throw;
}
}
public static unsafe SocketError SendToAsync(SafeSocketHandle handle, byte[] buffer, int offset, int count, SocketFlags socketFlags, Internals.SocketAddress socketAddress, OverlappedAsyncResult asyncResult)
{
// Set up asyncResult for overlapped WSASendTo.
asyncResult.SetUnmanagedStructures(buffer, offset, count, socketAddress);
try
{
int bytesTransferred;
SocketError errorCode = Interop.Winsock.WSASendTo(
handle,
ref asyncResult._singleBuffer,
1, // There is only ever 1 buffer being sent.
out bytesTransferred,
socketFlags,
asyncResult.GetSocketAddressPtr(),
asyncResult.SocketAddress.Size,
asyncResult.DangerousOverlappedPointer, // SafeHandle was just created in SetUnmanagedStructures
IntPtr.Zero);
return asyncResult.ProcessOverlappedResult(errorCode == SocketError.Success, bytesTransferred);
}
catch
{
asyncResult.ReleaseUnmanagedStructures();
throw;
}
}
public static unsafe SocketError ReceiveAsync(SafeSocketHandle handle, byte[] buffer, int offset, int count, SocketFlags socketFlags, OverlappedAsyncResult asyncResult)
{
// Set up asyncResult for overlapped WSARecv.
asyncResult.SetUnmanagedStructures(buffer, offset, count, null);
try
{
int bytesTransferred;
SocketError errorCode = Interop.Winsock.WSARecv(
handle,
ref asyncResult._singleBuffer,
1,
out bytesTransferred,
ref socketFlags,
asyncResult.DangerousOverlappedPointer, // SafeHandle was just created in SetUnmanagedStructures
IntPtr.Zero);
return asyncResult.ProcessOverlappedResult(errorCode == SocketError.Success, bytesTransferred);
}
catch
{
asyncResult.ReleaseUnmanagedStructures();
throw;
}
}
public static unsafe SocketError ReceiveAsync(SafeSocketHandle handle, IList<ArraySegment<byte>> buffers, SocketFlags socketFlags, OverlappedAsyncResult asyncResult)
{
// Set up asyncResult for overlapped WSASend.
asyncResult.SetUnmanagedStructures(buffers);
try
{
int bytesTransferred;
SocketError errorCode = Interop.Winsock.WSARecv(
handle,
asyncResult._wsaBuffers,
asyncResult._wsaBuffers.Length,
out bytesTransferred,
ref socketFlags,
asyncResult.DangerousOverlappedPointer, // SafeHandle was just created in SetUnmanagedStructures
IntPtr.Zero);
return asyncResult.ProcessOverlappedResult(errorCode == SocketError.Success, bytesTransferred);
}
catch
{
asyncResult.ReleaseUnmanagedStructures();
throw;
}
}
public static unsafe SocketError ReceiveFromAsync(SafeSocketHandle handle, byte[] buffer, int offset, int count, SocketFlags socketFlags, Internals.SocketAddress socketAddress, OverlappedAsyncResult asyncResult)
{
// Set up asyncResult for overlapped WSARecvFrom.
asyncResult.SetUnmanagedStructures(buffer, offset, count, socketAddress);
try
{
int bytesTransferred;
SocketError errorCode = Interop.Winsock.WSARecvFrom(
handle,
ref asyncResult._singleBuffer,
1,
out bytesTransferred,
ref socketFlags,
asyncResult.GetSocketAddressPtr(),
asyncResult.GetSocketAddressSizePtr(),
asyncResult.DangerousOverlappedPointer, // SafeHandle was just created in SetUnmanagedStructures
IntPtr.Zero);
return asyncResult.ProcessOverlappedResult(errorCode == SocketError.Success, bytesTransferred);
}
catch
{
asyncResult.ReleaseUnmanagedStructures();
throw;
}
}
public static unsafe SocketError ReceiveMessageFromAsync(Socket socket, SafeSocketHandle handle, byte[] buffer, int offset, int count, SocketFlags socketFlags, Internals.SocketAddress socketAddress, ReceiveMessageOverlappedAsyncResult asyncResult)
{
asyncResult.SetUnmanagedStructures(buffer, offset, count, socketAddress, socketFlags);
try
{
int bytesTransfered;
SocketError errorCode = (SocketError)socket.WSARecvMsg(
handle,
Marshal.UnsafeAddrOfPinnedArrayElement(asyncResult._messageBuffer, 0),
out bytesTransfered,
asyncResult.DangerousOverlappedPointer, // SafeHandle was just created in SetUnmanagedStructures
IntPtr.Zero);
return asyncResult.ProcessOverlappedResult(errorCode == SocketError.Success, bytesTransfered);
}
catch
{
asyncResult.ReleaseUnmanagedStructures();
throw;
}
}
public static unsafe SocketError AcceptAsync(Socket socket, SafeSocketHandle handle, SafeSocketHandle acceptHandle, int receiveSize, int socketAddressSize, AcceptOverlappedAsyncResult asyncResult)
{
// The buffer needs to contain the requested data plus room for two sockaddrs and 16 bytes
// of associated data for each.
int addressBufferSize = socketAddressSize + 16;
byte[] buffer = new byte[receiveSize + ((addressBufferSize) * 2)];
// Set up asyncResult for overlapped AcceptEx.
// This call will use completion ports on WinNT.
asyncResult.SetUnmanagedStructures(buffer, addressBufferSize);
try
{
// This can throw ObjectDisposedException.
int bytesTransferred;
bool success = socket.AcceptEx(
handle,
acceptHandle,
Marshal.UnsafeAddrOfPinnedArrayElement(asyncResult.Buffer, 0),
receiveSize,
addressBufferSize,
addressBufferSize,
out bytesTransferred,
asyncResult.DangerousOverlappedPointer); // SafeHandle was just created in SetUnmanagedStructures
return asyncResult.ProcessOverlappedResult(success, 0);
}
catch
{
asyncResult.ReleaseUnmanagedStructures();
throw;
}
}
public static void CheckDualModeReceiveSupport(Socket socket)
{
// Dual-mode sockets support received packet info on Windows.
}
internal static unsafe SocketError DisconnectAsync(Socket socket, SafeSocketHandle handle, bool reuseSocket, DisconnectOverlappedAsyncResult asyncResult)
{
asyncResult.SetUnmanagedStructures(null);
try
{
// This can throw ObjectDisposedException
bool success = socket.DisconnectEx(
handle,
asyncResult.DangerousOverlappedPointer, // SafeHandle was just created in SetUnmanagedStructures
(int)(reuseSocket ? TransmitFileOptions.ReuseSocket : 0),
0);
return asyncResult.ProcessOverlappedResult(success, 0);
}
catch
{
asyncResult.ReleaseUnmanagedStructures();
throw;
}
}
internal static SocketError Disconnect(Socket socket, SafeSocketHandle handle, bool reuseSocket)
{
SocketError errorCode = SocketError.Success;
// This can throw ObjectDisposedException (handle, and retrieving the delegate).
if (!socket.DisconnectExBlocking(handle, IntPtr.Zero, (int)(reuseSocket ? TransmitFileOptions.ReuseSocket : 0), 0))
{
errorCode = GetLastSocketError();
}
return errorCode;
}
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
using System.Threading;
using log4net;
using Nini.Config;
using Nwc.XmlRpc;
using Mono.Addins;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Services.Interfaces;
using OpenSim.Services.Connectors.Hypergrid;
using FriendInfo = OpenSim.Services.Interfaces.FriendInfo;
using PresenceInfo = OpenSim.Services.Interfaces.PresenceInfo;
using GridRegion = OpenSim.Services.Interfaces.GridRegion;
namespace OpenSim.Region.CoreModules.Avatar.Friends
{
[Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "HGFriendsModule")]
public class HGFriendsModule : FriendsModule, ISharedRegionModule, IFriendsModule, IFriendsSimConnector
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private int m_levelHGFriends = 0;
IUserManagement m_uMan;
public IUserManagement UserManagementModule
{
get
{
if (m_uMan == null)
m_uMan = m_Scenes[0].RequestModuleInterface<IUserManagement>();
return m_uMan;
}
}
protected HGFriendsServicesConnector m_HGFriendsConnector = new HGFriendsServicesConnector();
protected HGStatusNotifier m_StatusNotifier;
#region ISharedRegionModule
public override string Name
{
get { return "HGFriendsModule"; }
}
public override void AddRegion(Scene scene)
{
if (!m_Enabled)
return;
base.AddRegion(scene);
scene.RegisterModuleInterface<IFriendsSimConnector>(this);
}
public override void RegionLoaded(Scene scene)
{
if (!m_Enabled)
return;
if (m_StatusNotifier == null)
m_StatusNotifier = new HGStatusNotifier(this);
}
protected override void InitModule(IConfigSource config)
{
base.InitModule(config);
// Additionally to the base method
IConfig friendsConfig = config.Configs["HGFriendsModule"];
if (friendsConfig != null)
{
m_levelHGFriends = friendsConfig.GetInt("LevelHGFriends", 0);
// TODO: read in all config variables pertaining to
// HG friendship permissions
}
}
#endregion
#region IFriendsSimConnector
/// <summary>
/// Notify the user that the friend's status changed
/// </summary>
/// <param name="userID">user to be notified</param>
/// <param name="friendID">friend whose status changed</param>
/// <param name="online">status</param>
/// <returns></returns>
public bool StatusNotify(UUID friendID, UUID userID, bool online)
{
return LocalStatusNotification(friendID, userID, online);
}
#endregion
protected override void OnInstantMessage(IClientAPI client, GridInstantMessage im)
{
if ((InstantMessageDialog)im.dialog == InstantMessageDialog.FriendshipOffered)
{
// we got a friendship offer
UUID principalID = new UUID(im.fromAgentID);
UUID friendID = new UUID(im.toAgentID);
// Check if friendID is foreigner and if principalID has the permission
// to request friendships with foreigners. If not, return immediately.
if (!UserManagementModule.IsLocalGridUser(friendID))
{
ScenePresence avatar = null;
((Scene)client.Scene).TryGetScenePresence(principalID, out avatar);
if (avatar == null)
return;
if (avatar.UserLevel < m_levelHGFriends)
{
client.SendAgentAlertMessage("Unable to send friendship invitation to foreigner. Insufficient permissions.", false);
return;
}
}
}
base.OnInstantMessage(client, im);
}
protected override void OnApproveFriendRequest(IClientAPI client, UUID friendID, List<UUID> callingCardFolders)
{
// Update the local cache. Yes, we need to do it right here
// because the HGFriendsService placed something on the DB
// from under the sim
base.OnApproveFriendRequest(client, friendID, callingCardFolders);
}
protected override bool CacheFriends(IClientAPI client)
{
// m_log.DebugFormat("[HGFRIENDS MODULE]: Entered CacheFriends for {0}", client.Name);
if (base.CacheFriends(client))
{
UUID agentID = client.AgentId;
// we do this only for the root agent
if (m_Friends[agentID].Refcount == 1)
{
// We need to preload the user management cache with the names
// of foreign friends, just like we do with SOPs' creators
foreach (FriendInfo finfo in m_Friends[agentID].Friends)
{
if (finfo.TheirFlags != -1)
{
UUID id;
if (!UUID.TryParse(finfo.Friend, out id))
{
string url = string.Empty, first = string.Empty, last = string.Empty, tmp = string.Empty;
if (Util.ParseUniversalUserIdentifier(finfo.Friend, out id, out url, out first, out last, out tmp))
{
IUserManagement uMan = m_Scenes[0].RequestModuleInterface<IUserManagement>();
uMan.AddUser(id, url + ";" + first + " " + last);
}
}
}
}
// m_log.DebugFormat("[HGFRIENDS MODULE]: Exiting CacheFriends for {0} since detected root agent", client.Name);
return true;
}
}
// m_log.DebugFormat("[HGFRIENDS MODULE]: Exiting CacheFriends for {0} since detected not root agent", client.Name);
return false;
}
public override bool SendFriendsOnlineIfNeeded(IClientAPI client)
{
// m_log.DebugFormat("[HGFRIENDS MODULE]: Entering SendFriendsOnlineIfNeeded for {0}", client.Name);
if (base.SendFriendsOnlineIfNeeded(client))
{
AgentCircuitData aCircuit = ((Scene)client.Scene).AuthenticateHandler.GetAgentCircuitData(client.AgentId);
if (aCircuit != null && (aCircuit.teleportFlags & (uint)Constants.TeleportFlags.ViaHGLogin) != 0)
{
UserAccount account = m_Scenes[0].UserAccountService.GetUserAccount(client.Scene.RegionInfo.ScopeID, client.AgentId);
if (account == null) // foreign
{
FriendInfo[] friends = GetFriendsFromCache(client.AgentId);
foreach (FriendInfo f in friends)
{
client.SendChangeUserRights(new UUID(f.Friend), client.AgentId, f.TheirFlags);
}
}
}
}
// m_log.DebugFormat("[HGFRIENDS MODULE]: Exiting SendFriendsOnlineIfNeeded for {0}", client.Name);
return false;
}
protected override void GetOnlineFriends(UUID userID, List<string> friendList, /*collector*/ List<UUID> online)
{
// m_log.DebugFormat("[HGFRIENDS MODULE]: Entering GetOnlineFriends for {0}", userID);
List<string> fList = new List<string>();
foreach (string s in friendList)
{
if (s.Length < 36)
m_log.WarnFormat(
"[HGFRIENDS MODULE]: Ignoring friend {0} ({1} chars) for {2} since identifier too short",
s, s.Length, userID);
else
fList.Add(s.Substring(0, 36));
}
PresenceInfo[] presence = PresenceService.GetAgents(fList.ToArray());
foreach (PresenceInfo pi in presence)
{
UUID presenceID;
if (UUID.TryParse(pi.UserID, out presenceID))
online.Add(presenceID);
}
// m_log.DebugFormat("[HGFRIENDS MODULE]: Exiting GetOnlineFriends for {0}", userID);
}
protected override void StatusNotify(List<FriendInfo> friendList, UUID userID, bool online)
{
// m_log.DebugFormat("[HGFRIENDS MODULE]: Entering StatusNotify for {0}", userID);
// First, let's divide the friends on a per-domain basis
Dictionary<string, List<FriendInfo>> friendsPerDomain = new Dictionary<string, List<FriendInfo>>();
foreach (FriendInfo friend in friendList)
{
UUID friendID;
if (UUID.TryParse(friend.Friend, out friendID))
{
if (!friendsPerDomain.ContainsKey("local"))
friendsPerDomain["local"] = new List<FriendInfo>();
friendsPerDomain["local"].Add(friend);
}
else
{
// it's a foreign friend
string url = string.Empty, tmp = string.Empty;
if (Util.ParseUniversalUserIdentifier(friend.Friend, out friendID, out url, out tmp, out tmp, out tmp))
{
// Let's try our luck in the local sim. Who knows, maybe it's here
if (LocalStatusNotification(userID, friendID, online))
continue;
if (!friendsPerDomain.ContainsKey(url))
friendsPerDomain[url] = new List<FriendInfo>();
friendsPerDomain[url].Add(friend);
}
}
}
// For the local friends, just call the base method
// Let's do this first of all
if (friendsPerDomain.ContainsKey("local"))
base.StatusNotify(friendsPerDomain["local"], userID, online);
m_StatusNotifier.Notify(userID, friendsPerDomain, online);
// m_log.DebugFormat("[HGFRIENDS MODULE]: Exiting StatusNotify for {0}", userID);
}
protected override bool GetAgentInfo(UUID scopeID, string fid, out UUID agentID, out string first, out string last)
{
first = "Unknown"; last = "User";
if (base.GetAgentInfo(scopeID, fid, out agentID, out first, out last))
return true;
// fid is not a UUID...
string url = string.Empty, tmp = string.Empty, f = string.Empty, l = string.Empty;
if (Util.ParseUniversalUserIdentifier(fid, out agentID, out url, out f, out l, out tmp))
{
if (!agentID.Equals(UUID.Zero))
{
m_uMan.AddUser(agentID, f, l, url);
string name = m_uMan.GetUserName(agentID);
string[] parts = name.Trim().Split(new char[] { ' ' });
if (parts.Length == 2)
{
first = parts[0];
last = parts[1];
}
else
{
first = f;
last = l;
}
return true;
}
}
return false;
}
protected override string GetFriendshipRequesterName(UUID agentID)
{
return m_uMan.GetUserName(agentID);
}
protected override string FriendshipMessage(string friendID)
{
UUID id;
if (UUID.TryParse(friendID, out id))
return base.FriendshipMessage(friendID);
return "Please confirm this friendship you made while you were away.";
}
protected override FriendInfo GetFriend(FriendInfo[] friends, UUID friendID)
{
foreach (FriendInfo fi in friends)
{
if (fi.Friend.StartsWith(friendID.ToString()))
return fi;
}
return null;
}
public override FriendInfo[] GetFriendsFromService(IClientAPI client)
{
// m_log.DebugFormat("[HGFRIENDS MODULE]: Entering GetFriendsFromService for {0}", client.Name);
Boolean agentIsLocal = true;
if (UserManagementModule != null)
agentIsLocal = UserManagementModule.IsLocalGridUser(client.AgentId);
if (agentIsLocal)
return base.GetFriendsFromService(client);
FriendInfo[] finfos = new FriendInfo[0];
// Foreigner
AgentCircuitData agentClientCircuit = ((Scene)(client.Scene)).AuthenticateHandler.GetAgentCircuitData(client.CircuitCode);
if (agentClientCircuit != null)
{
//[XXX] string agentUUI = Util.ProduceUserUniversalIdentifier(agentClientCircuit);
finfos = FriendsService.GetFriends(client.AgentId.ToString());
m_log.DebugFormat("[HGFRIENDS MODULE]: Fetched {0} local friends for visitor {1}", finfos.Length, client.AgentId.ToString());
}
// m_log.DebugFormat("[HGFRIENDS MODULE]: Exiting GetFriendsFromService for {0}", client.Name);
return finfos;
}
protected override bool StoreRights(UUID agentID, UUID friendID, int rights)
{
Boolean agentIsLocal = true;
Boolean friendIsLocal = true;
if (UserManagementModule != null)
{
agentIsLocal = UserManagementModule.IsLocalGridUser(agentID);
friendIsLocal = UserManagementModule.IsLocalGridUser(friendID);
}
// Are they both local users?
if (agentIsLocal && friendIsLocal)
{
// local grid users
return base.StoreRights(agentID, friendID, rights);
}
if (agentIsLocal) // agent is local, friend is foreigner
{
FriendInfo[] finfos = GetFriendsFromCache(agentID);
FriendInfo finfo = GetFriend(finfos, friendID);
if (finfo != null)
{
FriendsService.StoreFriend(agentID.ToString(), finfo.Friend, rights);
return true;
}
}
if (friendIsLocal) // agent is foreigner, friend is local
{
string agentUUI = GetUUI(friendID, agentID);
if (agentUUI != string.Empty)
{
FriendsService.StoreFriend(agentUUI, friendID.ToString(), rights);
return true;
}
}
return false;
}
protected override void StoreBackwards(UUID friendID, UUID agentID)
{
bool agentIsLocal = true;
// bool friendIsLocal = true;
if (UserManagementModule != null)
{
agentIsLocal = UserManagementModule.IsLocalGridUser(agentID);
// friendIsLocal = UserManagementModule.IsLocalGridUser(friendID);
}
// Is the requester a local user?
if (agentIsLocal)
{
// local grid users
m_log.DebugFormat("[HGFRIENDS MODULE]: Friendship requester is local. Storing backwards.");
base.StoreBackwards(friendID, agentID);
return;
}
// no provision for this temporary friendship state when user is not local
//FriendsService.StoreFriend(friendID.ToString(), agentID.ToString(), 0);
}
protected override void StoreFriendships(UUID agentID, UUID friendID)
{
Boolean agentIsLocal = true;
Boolean friendIsLocal = true;
if (UserManagementModule != null)
{
agentIsLocal = UserManagementModule.IsLocalGridUser(agentID);
friendIsLocal = UserManagementModule.IsLocalGridUser(friendID);
}
// Are they both local users?
if (agentIsLocal && friendIsLocal)
{
// local grid users
m_log.DebugFormat("[HGFRIENDS MODULE]: Users are both local");
base.StoreFriendships(agentID, friendID);
return;
}
// ok, at least one of them is foreigner, let's get their data
IClientAPI agentClient = LocateClientObject(agentID);
IClientAPI friendClient = LocateClientObject(friendID);
AgentCircuitData agentClientCircuit = null;
AgentCircuitData friendClientCircuit = null;
string agentUUI = string.Empty;
string friendUUI = string.Empty;
string agentFriendService = string.Empty;
string friendFriendService = string.Empty;
if (agentClient != null)
{
agentClientCircuit = ((Scene)(agentClient.Scene)).AuthenticateHandler.GetAgentCircuitData(agentClient.CircuitCode);
agentUUI = Util.ProduceUserUniversalIdentifier(agentClientCircuit);
agentFriendService = agentClientCircuit.ServiceURLs["FriendsServerURI"].ToString();
RecacheFriends(agentClient);
}
if (friendClient != null)
{
friendClientCircuit = ((Scene)(friendClient.Scene)).AuthenticateHandler.GetAgentCircuitData(friendClient.CircuitCode);
friendUUI = Util.ProduceUserUniversalIdentifier(friendClientCircuit);
friendFriendService = friendClientCircuit.ServiceURLs["FriendsServerURI"].ToString();
RecacheFriends(friendClient);
}
m_log.DebugFormat("[HGFRIENDS MODULE] HG Friendship! thisUUI={0}; friendUUI={1}; foreignThisFriendService={2}; foreignFriendFriendService={3}",
agentUUI, friendUUI, agentFriendService, friendFriendService);
// Generate a random 8-character hex number that will sign this friendship
string secret = UUID.Random().ToString().Substring(0, 8);
string theFriendUUID = friendUUI + ";" + secret;
string agentUUID = agentUUI + ";" + secret;
if (agentIsLocal) // agent is local, 'friend' is foreigner
{
// This may happen when the agent returned home, in which case the friend is not there
// We need to look for its information in the friends list itself
FriendInfo[] finfos = null;
bool confirming = false;
if (friendUUI == string.Empty)
{
finfos = GetFriendsFromCache(agentID);
foreach (FriendInfo finfo in finfos)
{
if (finfo.TheirFlags == -1)
{
if (finfo.Friend.StartsWith(friendID.ToString()))
{
friendUUI = finfo.Friend;
theFriendUUID = friendUUI;
UUID utmp = UUID.Zero;
string url = String.Empty;
string first = String.Empty;
string last = String.Empty;
// If it's confirming the friendship, we already have the full UUI with the secret
if (Util.ParseUniversalUserIdentifier(theFriendUUID, out utmp, out url, out first, out last, out secret))
{
agentUUID = agentUUI + ";" + secret;
m_uMan.AddUser(utmp, first, last, url);
}
confirming = true;
break;
}
}
}
if (!confirming)
{
friendUUI = m_uMan.GetUserUUI(friendID);
theFriendUUID = friendUUI + ";" + secret;
}
friendFriendService = m_uMan.GetUserServerURL(friendID, "FriendsServerURI");
// m_log.DebugFormat("[HGFRIENDS MODULE] HG Friendship! thisUUI={0}; friendUUI={1}; foreignThisFriendService={2}; foreignFriendFriendService={3}",
// agentUUI, friendUUI, agentFriendService, friendFriendService);
}
// Delete any previous friendship relations
DeletePreviousRelations(agentID, friendID);
// store in the local friends service a reference to the foreign friend
FriendsService.StoreFriend(agentID.ToString(), theFriendUUID, 1);
// and also the converse
FriendsService.StoreFriend(theFriendUUID, agentID.ToString(), 1);
//if (!confirming)
//{
// store in the foreign friends service a reference to the local agent
HGFriendsServicesConnector friendsConn = null;
if (friendClientCircuit != null) // the friend is here, validate session
friendsConn = new HGFriendsServicesConnector(friendFriendService, friendClientCircuit.SessionID, friendClientCircuit.ServiceSessionID);
else // the friend is not here, he initiated the request in his home world
friendsConn = new HGFriendsServicesConnector(friendFriendService);
friendsConn.NewFriendship(friendID, agentUUID);
//}
}
else if (friendIsLocal) // 'friend' is local, agent is foreigner
{
// Delete any previous friendship relations
DeletePreviousRelations(agentID, friendID);
// store in the local friends service a reference to the foreign agent
FriendsService.StoreFriend(friendID.ToString(), agentUUI + ";" + secret, 1);
// and also the converse
FriendsService.StoreFriend(agentUUI + ";" + secret, friendID.ToString(), 1);
if (agentClientCircuit != null)
{
// store in the foreign friends service a reference to the local agent
HGFriendsServicesConnector friendsConn = new HGFriendsServicesConnector(agentFriendService, agentClientCircuit.SessionID, agentClientCircuit.ServiceSessionID);
friendsConn.NewFriendship(agentID, friendUUI + ";" + secret);
}
}
else // They're both foreigners!
{
HGFriendsServicesConnector friendsConn;
if (agentClientCircuit != null)
{
friendsConn = new HGFriendsServicesConnector(agentFriendService, agentClientCircuit.SessionID, agentClientCircuit.ServiceSessionID);
friendsConn.NewFriendship(agentID, friendUUI + ";" + secret);
}
if (friendClientCircuit != null)
{
friendsConn = new HGFriendsServicesConnector(friendFriendService, friendClientCircuit.SessionID, friendClientCircuit.ServiceSessionID);
friendsConn.NewFriendship(friendID, agentUUI + ";" + secret);
}
}
// my brain hurts now
}
private void DeletePreviousRelations(UUID a1, UUID a2)
{
// Delete any previous friendship relations
FriendInfo[] finfos = null;
FriendInfo f = null;
finfos = GetFriendsFromCache(a1);
if (finfos != null)
{
f = GetFriend(finfos, a2);
if (f != null)
{
FriendsService.Delete(a1, f.Friend);
// and also the converse
FriendsService.Delete(f.Friend, a1.ToString());
}
}
finfos = GetFriendsFromCache(a2);
if (finfos != null)
{
f = GetFriend(finfos, a1);
if (f != null)
{
FriendsService.Delete(a2, f.Friend);
// and also the converse
FriendsService.Delete(f.Friend, a2.ToString());
}
}
}
protected override bool DeleteFriendship(UUID agentID, UUID exfriendID)
{
Boolean agentIsLocal = true;
Boolean friendIsLocal = true;
if (UserManagementModule != null)
{
agentIsLocal = UserManagementModule.IsLocalGridUser(agentID);
friendIsLocal = UserManagementModule.IsLocalGridUser(exfriendID);
}
// Are they both local users?
if (agentIsLocal && friendIsLocal)
{
// local grid users
return base.DeleteFriendship(agentID, exfriendID);
}
// ok, at least one of them is foreigner, let's get their data
string agentUUI = string.Empty;
string friendUUI = string.Empty;
if (agentIsLocal) // agent is local, 'friend' is foreigner
{
// We need to look for its information in the friends list itself
FriendInfo[] finfos = GetFriendsFromCache(agentID);
FriendInfo finfo = GetFriend(finfos, exfriendID);
if (finfo != null)
{
friendUUI = finfo.Friend;
// delete in the local friends service the reference to the foreign friend
FriendsService.Delete(agentID, friendUUI);
// and also the converse
FriendsService.Delete(friendUUI, agentID.ToString());
// notify the exfriend's service
Util.FireAndForget(delegate { Delete(exfriendID, agentID, friendUUI); });
m_log.DebugFormat("[HGFRIENDS MODULE]: {0} terminated {1}", agentID, friendUUI);
return true;
}
}
else if (friendIsLocal) // agent is foreigner, 'friend' is local
{
agentUUI = GetUUI(exfriendID, agentID);
if (agentUUI != string.Empty)
{
// delete in the local friends service the reference to the foreign agent
FriendsService.Delete(exfriendID, agentUUI);
// and also the converse
FriendsService.Delete(agentUUI, exfriendID.ToString());
// notify the agent's service?
Util.FireAndForget(delegate { Delete(agentID, exfriendID, agentUUI); });
m_log.DebugFormat("[HGFRIENDS MODULE]: {0} terminated {1}", agentUUI, exfriendID);
return true;
}
}
//else They're both foreigners! Can't handle this
return false;
}
private string GetUUI(UUID localUser, UUID foreignUser)
{
// Let's see if the user is here by any chance
FriendInfo[] finfos = GetFriendsFromCache(localUser);
if (finfos != EMPTY_FRIENDS) // friend is here, cool
{
FriendInfo finfo = GetFriend(finfos, foreignUser);
if (finfo != null)
{
return finfo.Friend;
}
}
else // user is not currently on this sim, need to get from the service
{
finfos = FriendsService.GetFriends(localUser);
foreach (FriendInfo finfo in finfos)
{
if (finfo.Friend.StartsWith(foreignUser.ToString())) // found it!
{
return finfo.Friend;
}
}
}
return string.Empty;
}
private void Delete(UUID foreignUser, UUID localUser, string uui)
{
UUID id;
string url = string.Empty, secret = string.Empty, tmp = string.Empty;
if (Util.ParseUniversalUserIdentifier(uui, out id, out url, out tmp, out tmp, out secret))
{
m_log.DebugFormat("[HGFRIENDS MODULE]: Deleting friendship from {0}", url);
HGFriendsServicesConnector friendConn = new HGFriendsServicesConnector(url);
friendConn.DeleteFriendship(foreignUser, localUser, secret);
}
}
protected override bool ForwardFriendshipOffer(UUID agentID, UUID friendID, GridInstantMessage im)
{
if (base.ForwardFriendshipOffer(agentID, friendID, im))
return true;
// OK, that didn't work, so let's try to find this user somewhere
if (!m_uMan.IsLocalGridUser(friendID))
{
string friendsURL = m_uMan.GetUserServerURL(friendID, "FriendsServerURI");
if (friendsURL != string.Empty)
{
m_log.DebugFormat("[HGFRIENDS MODULE]: Forwading friendship from {0} to {1} @ {2}", agentID, friendID, friendsURL);
GridRegion region = new GridRegion();
region.ServerURI = friendsURL;
string name = im.fromAgentName;
if (m_uMan.IsLocalGridUser(agentID))
{
IClientAPI agentClient = LocateClientObject(agentID);
AgentCircuitData agentClientCircuit = ((Scene)(agentClient.Scene)).AuthenticateHandler.GetAgentCircuitData(agentClient.CircuitCode);
string agentHomeService = string.Empty;
try
{
agentHomeService = agentClientCircuit.ServiceURLs["HomeURI"].ToString();
string lastname = "@" + new Uri(agentHomeService).Authority;
string firstname = im.fromAgentName.Replace(" ", ".");
name = firstname + lastname;
}
catch (KeyNotFoundException)
{
m_log.DebugFormat("[HGFRIENDS MODULE]: Key HomeURI not found for user {0}", agentID);
return false;
}
catch (NullReferenceException)
{
m_log.DebugFormat("[HGFRIENDS MODULE]: Null HomeUri for local user {0}", agentID);
return false;
}
catch (UriFormatException)
{
m_log.DebugFormat("[HGFRIENDS MODULE]: Malformed HomeUri {0} for local user {1}", agentHomeService, agentID);
return false;
}
}
m_HGFriendsConnector.FriendshipOffered(region, agentID, friendID, im.message, name);
return true;
}
}
return false;
}
public override bool LocalFriendshipOffered(UUID toID, GridInstantMessage im)
{
if (base.LocalFriendshipOffered(toID, im))
{
if (im.fromAgentName.Contains("@"))
{
string[] parts = im.fromAgentName.Split(new char[] { '@' });
if (parts.Length == 2)
{
string[] fl = parts[0].Trim().Split(new char[] { '.' });
if (fl.Length == 2)
m_uMan.AddUser(new UUID(im.fromAgentID), fl[0], fl[1], "http://" + parts[1]);
else
m_uMan.AddUser(new UUID(im.fromAgentID), fl[0], "", "http://" + parts[1]);
}
}
return true;
}
return false;
}
}
}
| |
#region Usings
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using Stomp.Net.Messaging;
using Stomp.Net.Stomp.Commands;
using Stomp.Net.Util;
using Stomp.Net.Utilities;
#endregion
namespace Stomp.Net.Stomp
{
/// <summary>
/// An object capable of receiving messages from some destination
/// </summary>
public class MessageConsumer : Disposable, IMessageConsumer, IDispatcher
{
#region Properties
public Exception FailureError { get; set; }
#endregion
#region Ctor
// Constructor internal to prevent clients from creating an instance.
internal MessageConsumer( Session session, ConsumerId id, IDestination destination, String name, String selector, Int32 prefetch, Boolean noLocal )
{
if ( destination == null )
throw new InvalidDestinationException( "Consumer cannot receive on null Destinations." );
_session = session;
RedeliveryPolicy = _session.Connection.RedeliveryPolicy;
ConsumerInfo = new()
{
ConsumerId = id,
Destination = Destination.Transform( destination ),
SubscriptionName = name,
Selector = selector,
PrefetchSize = prefetch,
MaximumPendingMessageLimit = session.Connection.PrefetchPolicy.MaximumPendingMessageLimit,
NoLocal = noLocal,
DispatchAsync = session.DispatchAsync,
Retroactive = session.Retroactive,
Exclusive = session.Exclusive,
Priority = session.Priority,
AckMode = session.AcknowledgementMode
};
// Removed unused consumer. options (ConsumerInfo => "consumer.")
// TODO: Implement settings?
// Removed unused message consumer. options (this => "consumer.nms.")
// TODO: Implement settings?
}
#endregion
public void Dispatch( MessageDispatch dispatch )
{
var listener = _listener;
try
{
lock ( _syncRoot )
{
if ( _clearDispatchList )
{
// we are reconnecting so lets flush the in progress messages
_clearDispatchList = false;
_unconsumedMessages.Clear();
// on resumption a pending delivered ACK will be out of sync with
// re-deliveries.
_pendingAck = null;
}
if ( !_unconsumedMessages.Stopped )
if ( listener != null && _unconsumedMessages.Started )
{
var message = CreateStompMessage( dispatch );
BeforeMessageIsConsumed( dispatch );
try
{
var expired = !IgnoreExpiration && message.IsExpired();
if ( !expired )
listener( message );
AfterMessageIsConsumed( dispatch, expired );
}
catch ( Exception e )
{
if ( _session.IsAutoAcknowledge || _session.IsIndividualAcknowledge )
{
// Redeliver the message
}
else
// Transacted or Client ACK: Deliver the next message.
AfterMessageIsConsumed( dispatch, false );
if ( Tracer.IsErrorEnabled )
Tracer.Error( ConsumerInfo.ConsumerId + " Exception while processing message: " + e );
}
}
else
_unconsumedMessages.Enqueue( dispatch );
}
if ( ++_dispatchedCount % 1000 != 0 )
return;
_dispatchedCount = 0;
Thread.Sleep( 1 );
}
catch ( Exception e )
{
_session.Connection.OnSessionException( _session, e );
}
}
public Boolean Iterate()
{
if ( _listener == null )
return false;
var dispatch = _unconsumedMessages.DequeueNoWait();
if ( dispatch == null )
return false;
try
{
var message = CreateStompMessage( dispatch );
BeforeMessageIsConsumed( dispatch );
// ReSharper disable once PossibleNullReferenceException
_listener( message );
AfterMessageIsConsumed( dispatch, false );
}
catch ( StompException ex )
{
_session.Connection.OnSessionException( _session, ex );
}
return true;
}
public void Start()
{
if ( _unconsumedMessages.Stopped )
return;
_started.Value = true;
_unconsumedMessages.Start();
_session.Executor.Wakeup();
}
#region Override of Disposable
/// <summary>
/// Method invoked when the instance gets disposed.
/// </summary>
protected override void Disposed()
{
try
{
Close();
}
catch
{
// Ignore network errors.
}
}
#endregion
internal void Acknowledge()
{
lock ( _dispatchedMessages )
{
// Acknowledge all messages so far.
var ack = MakeAckForAllDeliveredMessages();
if ( ack == null )
return; // no msgs
if ( _session.IsTransacted )
{
_session.DoStartTransaction();
ack.TransactionId = _session.TransactionContext.TransactionId;
}
_session.SendAck( ack );
_pendingAck = null;
// Adjust the counters
_deliveredCounter = Math.Max( 0, _deliveredCounter - _dispatchedMessages.Count );
_additionalWindowSize = Math.Max( 0, _additionalWindowSize - _dispatchedMessages.Count );
if ( !_session.IsTransacted )
_dispatchedMessages.Clear();
}
}
internal void ClearMessagesInProgress()
{
if ( !_inProgressClearRequiredFlag )
return;
lock ( _unconsumedMessages )
if ( _inProgressClearRequiredFlag )
{
_unconsumedMessages.Clear();
_synchronizationRegistered = false;
// allow dispatch on this connection to resume
_inProgressClearRequiredFlag = false;
}
}
internal void InProgressClearRequired()
{
_inProgressClearRequiredFlag = true;
// deal with delivered messages async to avoid lock contention with in progress acks
_clearDispatchList = true;
}
internal void Rollback()
{
lock ( _syncRoot )
lock ( _dispatchedMessages )
{
if ( _dispatchedMessages.Count == 0 )
return;
// Only increase the redelivery delay after the first redelivery..
var lastMd = _dispatchedMessages.First();
var currentRedeliveryCount = lastMd.Message.RedeliveryCounter;
_redeliveryDelay = RedeliveryPolicy.RedeliveryDelay( currentRedeliveryCount );
foreach ( var dispatch in _dispatchedMessages )
dispatch.Message.OnMessageRollback();
if ( RedeliveryPolicy.MaximumRedeliveries >= 0 &&
lastMd.Message.RedeliveryCounter > RedeliveryPolicy.MaximumRedeliveries )
_redeliveryDelay = 0;
else
{
// stop the delivery of messages.
_unconsumedMessages.Stop();
foreach ( var dispatch in _dispatchedMessages )
_unconsumedMessages.Enqueue( dispatch, true );
if ( _redeliveryDelay > 0 && !_unconsumedMessages.Stopped )
{
var deadline = DateTime.Now.AddMilliseconds( _redeliveryDelay );
ThreadPool.QueueUserWorkItem( RollbackHelper, deadline );
}
else
Start();
}
_deliveredCounter -= _dispatchedMessages.Count;
_dispatchedMessages.Clear();
}
// Only redispatch if there's an async _listener otherwise a synchronous
// consumer will pull them from the local queue.
if ( _listener != null )
_session.Redispatch( _unconsumedMessages );
}
// ReSharper disable once InconsistentNaming
private event Action<IBytesMessage> _listener;
private void AckLater( MessageDispatch dispatch )
{
// Don't acknowledge now, but we may need to let the broker know the
// consumer got the message to expand the pre-fetch window
if ( _session.IsTransacted )
{
_session.DoStartTransaction();
if ( !_synchronizationRegistered )
{
_synchronizationRegistered = true;
_session.TransactionContext.AddSynchronization( new MessageConsumerSynchronization( this ) );
}
}
_deliveredCounter++;
var oldPendingAck = _pendingAck;
_pendingAck = new()
{
AckType = (Byte) AckType.ConsumedAck,
ConsumerId = ConsumerInfo.ConsumerId,
Destination = dispatch.Destination,
LastMessageId = dispatch.Message.MessageId,
MessageCount = _deliveredCounter
};
if ( _session.IsTransacted && _session.TransactionContext.InTransaction )
_pendingAck.TransactionId = _session.TransactionContext.TransactionId;
if ( oldPendingAck == null )
_pendingAck.FirstMessageId = _pendingAck.LastMessageId;
if ( !( 0.5 * ConsumerInfo.PrefetchSize <= _deliveredCounter - _additionalWindowSize ) )
return;
_session.SendAck( _pendingAck );
_pendingAck = null;
_deliveredCounter = 0;
_additionalWindowSize = 0;
}
private void BeforeMessageIsConsumed( MessageDispatch dispatch )
{
lock ( _dispatchedMessages )
_dispatchedMessages.Insert( 0, dispatch );
if ( _session.IsTransacted )
AckLater( dispatch );
}
private void Commit()
{
lock ( _dispatchedMessages )
_dispatchedMessages.Clear();
_redeliveryDelay = 0;
}
private BytesMessage CreateStompMessage( MessageDispatch dispatch )
{
if ( dispatch.Message.Clone() is not BytesMessage message )
throw new($"Message was null => {dispatch.Message}");
message.Connection = _session.Connection;
if ( _session.IsClientAcknowledge )
message.Acknowledger += DoClientAcknowledge;
else if ( _session.IsIndividualAcknowledge )
message.Acknowledger += DoIndividualAcknowledge;
else
message.Acknowledger += DoNothingAcknowledge;
return message;
}
private void DoClientAcknowledge( BytesMessage message )
{
CheckClosed();
_session.Acknowledge();
}
private void DoIndividualAcknowledge( BytesMessage message )
{
MessageDispatch dispatch = null;
lock ( _dispatchedMessages )
foreach ( var originalDispatch in _dispatchedMessages.Where( originalDispatch => originalDispatch.Message.MessageId.Equals( message.MessageId ) ) )
{
dispatch = originalDispatch;
_dispatchedMessages.Remove( originalDispatch );
break;
}
if ( dispatch == null )
{
if ( Tracer.IsWarnEnabled )
Tracer.Warn( $"Attempt to Ack MessageId[{message.MessageId}] failed because the original dispatch is not in the Dispatch List" );
return;
}
var ack = new MessageAck
{
AckType = (Byte) AckType.IndividualAck,
ConsumerId = ConsumerInfo.ConsumerId,
Destination = dispatch.Destination,
LastMessageId = dispatch.Message.MessageId,
MessageCount = 1
};
_session.SendAck( ack );
}
private static void DoNothingAcknowledge( BytesMessage message )
{
}
private MessageAck MakeAckForAllDeliveredMessages()
{
lock ( _dispatchedMessages )
{
if ( _dispatchedMessages.Count == 0 )
return null;
var dispatch = _dispatchedMessages.First();
var ack = new MessageAck
{
AckType = (Byte) AckType.ConsumedAck,
ConsumerId = ConsumerInfo.ConsumerId,
Destination = dispatch.Destination,
LastMessageId = dispatch.Message.MessageId,
MessageCount = _dispatchedMessages.Count,
FirstMessageId = _dispatchedMessages.First()
.Message.MessageId
};
return ack;
}
}
private void RollbackHelper( Object arg )
{
try
{
var waitTime = (DateTime) arg - DateTime.Now;
if ( waitTime.CompareTo( TimeSpan.Zero ) > 0 )
Thread.Sleep( (Int32) waitTime.TotalMilliseconds );
Start();
}
catch ( Exception e )
{
if ( !_unconsumedMessages.Stopped )
_session.Connection.OnSessionException( _session, e );
}
}
#region Fields
private readonly Atomic<Boolean> _deliveringAcks = new();
private readonly List<MessageDispatch> _dispatchedMessages = new();
private readonly Atomic<Boolean> _started = new();
private readonly Object _syncRoot = new();
private readonly MessageDispatchChannel _unconsumedMessages = new();
private Int32 _additionalWindowSize;
private Boolean _clearDispatchList;
private Int32 _deliveredCounter;
private Int32 _dispatchedCount;
private Boolean _inProgressClearRequiredFlag;
private MessageAck _pendingAck;
private Int64 _redeliveryDelay;
private Session _session;
private volatile Boolean _synchronizationRegistered;
#endregion
#region Property Accessors
public ConsumerId ConsumerId => ConsumerInfo.ConsumerId;
public ConsumerInfo ConsumerInfo { get; }
private Int32 PrefetchSize => ConsumerInfo.PrefetchSize;
private IRedeliveryPolicy RedeliveryPolicy { get; }
private Boolean IgnoreExpiration { get; } = false;
#endregion
#region IMessageConsumer Members
public event Action<IBytesMessage> Listener
{
add
{
CheckClosed();
if ( PrefetchSize == 0 )
throw new StompException( "Cannot set Asynchronous Listener on a Consumer with a zero Prefetch size" );
var wasStarted = _session.Started;
if ( wasStarted )
_session.Stop();
_listener += value;
_session.Redispatch( _unconsumedMessages );
if ( wasStarted )
_session.Start();
}
remove => _listener -= value;
}
/// <summary>
/// If a message is available within the timeout duration it is returned otherwise this method returns null
/// </summary>
/// <param name="timeout">An optimal timeout, if not specified infinity will be used.</param>
/// <returns>Returns the received message, or null in case of a timeout.</returns>
public IBytesMessage Receive( TimeSpan? timeout = null )
{
timeout ??= TimeSpan.FromMilliseconds( Timeout.Infinite );
CheckClosed();
CheckMessageListener();
var dispatch = Dequeue( timeout.Value );
if ( dispatch == null )
return null;
BeforeMessageIsConsumed( dispatch );
AfterMessageIsConsumed( dispatch, false );
return CreateStompMessage( dispatch );
}
/// <summary>
/// Closes the message consumer.
/// </summary>
/// <remarks>
/// Clients should close message consumers them when they are not needed.
/// This call blocks until a receive or message listener in progress has completed.
/// A blocked message consumer receive call returns null when this message consumer is closed.
/// </remarks>
public void Close()
{
if ( _unconsumedMessages.Stopped )
return;
// In case of transaction => close the consumer after the transaction has completed
if ( _session.IsTransacted && _session.TransactionContext.InTransaction )
_session.TransactionContext.AddSynchronization( new ConsumerCloseSynchronization( this ) );
else
CloseInternal();
}
#endregion
#region Private Members
/// <summary>
/// Used to get an enqueued message from the unconsumedMessages list. The
/// amount of time this method blocks is based on the timeout value. if
/// timeout == Timeout.Infinite then it blocks until a message is received.
/// if timeout == 0 then it tries to not block at all, it returns a
/// message if it is available if timeout > 0 then it blocks up to timeout
/// amount of time. Expired messages will consumed by this method.
/// </summary>
private MessageDispatch Dequeue( TimeSpan timeout )
{
// Calculate the deadline
DateTime deadline;
if ( timeout > TimeSpan.Zero )
deadline = DateTime.Now + timeout;
else
deadline = DateTime.MaxValue;
while ( true )
{
// Check if deadline is reached
if ( DateTime.Now > deadline )
return null;
// Fetch the message
var dispatch = _unconsumedMessages.Dequeue( timeout );
if ( dispatch == null )
{
if ( FailureError != null )
throw FailureError.Create();
return null;
}
if ( dispatch.Message == null )
return null;
if ( IgnoreExpiration || !dispatch.Message.IsExpired() )
return dispatch;
if ( Tracer.IsWarnEnabled )
Tracer.Warn( $"{ConsumerInfo.ConsumerId} received expired message: {dispatch.Message.MessageId}" );
BeforeMessageIsConsumed( dispatch );
AfterMessageIsConsumed( dispatch, true );
return null;
}
}
/// <summary>
/// Closes the consumer, for real.
/// </summary>
private void CloseInternal()
{
if ( _unconsumedMessages.Stopped )
return;
if ( !_session.IsTransacted )
lock ( _dispatchedMessages )
_dispatchedMessages.Clear();
_unconsumedMessages.Stop();
_session.DisposeOf( ConsumerInfo.ConsumerId );
var removeCommand = new RemoveInfo
{
ObjectId = ConsumerInfo.ConsumerId
};
_session.Connection.Oneway( removeCommand );
_session = null;
}
/// <summary>
/// Checks if the message dispatcher is still open.
/// </summary>
private void CheckClosed()
{
if ( _unconsumedMessages.Stopped )
throw new StompException( "The Consumer has been Stopped" );
}
/// <summary>
/// Checks if the consumer should publish message event or not.
/// </summary>
/// <remarks>
/// You can not perform a manual receive on a consumer with a event listener.
/// </remarks>
private void CheckMessageListener()
{
if ( _listener != null )
throw new StompException( "Cannot perform a Synchronous Receive when there is a registered asynchronous _listener." );
}
/// <summary>
/// Handles the ACK of the given message.
/// </summary>
/// <param name="dispatch">The message.</param>
/// <param name="expired">A value indicating whether the message was expired or not.</param>
private void AfterMessageIsConsumed( MessageDispatch dispatch, Boolean expired )
{
if ( _unconsumedMessages.Stopped )
return;
// Message was expired
if ( expired )
{
lock ( _dispatchedMessages )
_dispatchedMessages.Remove( dispatch );
return;
}
// Do noting
if ( _session.IsClientAcknowledge || _session.IsIndividualAcknowledge || _session.IsTransacted )
return;
if ( !_session.IsAutoAcknowledge )
throw new StompException( "Invalid session state." );
if ( !_deliveringAcks.CompareAndSet( false, true ) )
return;
lock ( _dispatchedMessages )
if ( _dispatchedMessages.Count > 0 )
{
var ack = new MessageAck
{
AckType = (Byte) AckType.ConsumedAck,
ConsumerId = ConsumerInfo.ConsumerId,
Destination = dispatch.Destination,
LastMessageId = dispatch.Message.MessageId,
MessageCount = 1
};
_session.SendAck( ack );
}
_deliveringAcks.Value = false;
_dispatchedMessages.Clear();
throw new StompException( "Invalid session state." );
}
#endregion
#region Nested ISyncronization Types
private class MessageConsumerSynchronization : ISynchronization
{
#region Fields
private readonly MessageConsumer _consumer;
#endregion
#region Ctor
public MessageConsumerSynchronization( MessageConsumer consumer ) => _consumer = consumer;
#endregion
public void AfterCommit()
{
_consumer.Commit();
_consumer._synchronizationRegistered = false;
}
public void AfterRollback()
{
_consumer.Rollback();
_consumer._synchronizationRegistered = false;
}
public void BeforeEnd()
{
_consumer.Acknowledge();
_consumer._synchronizationRegistered = false;
}
}
private class ConsumerCloseSynchronization : ISynchronization
{
#region Fields
private readonly MessageConsumer _consumer;
#endregion
#region Ctor
public ConsumerCloseSynchronization( MessageConsumer consumer ) => _consumer = consumer;
#endregion
public void AfterCommit() =>
_consumer.CloseInternal();
public void AfterRollback()
=> _consumer.CloseInternal();
public void BeforeEnd()
{
}
}
#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.
/******************************************************************************
* 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.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
namespace JIT.HardwareIntrinsics.General
{
public static partial class Program
{
private static void GetAndWithLowerAndUpperInt16()
{
var test = new VectorGetAndWithLowerAndUpper__GetAndWithLowerAndUpperInt16();
// Validates basic functionality works
test.RunBasicScenario();
// Validates calling via reflection works
test.RunReflectionScenario();
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class VectorGetAndWithLowerAndUpper__GetAndWithLowerAndUpperInt16
{
private static readonly int LargestVectorSize = 32;
private static readonly int ElementCount = Unsafe.SizeOf<Vector256<Int16>>() / sizeof(Int16);
public bool Succeeded { get; set; } = true;
public void RunBasicScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario));
Int16[] values = new Int16[ElementCount];
for (int i = 0; i < ElementCount; i++)
{
values[i] = TestLibrary.Generator.GetInt16();
}
Vector256<Int16> 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]);
Vector128<Int16> lowerResult = value.GetLower();
Vector128<Int16> upperResult = value.GetUpper();
ValidateGetResult(lowerResult, upperResult, values);
Vector256<Int16> result = value.WithLower(upperResult);
result = result.WithUpper(lowerResult);
ValidateWithResult(result, values);
}
public void RunReflectionScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario));
Int16[] values = new Int16[ElementCount];
for (int i = 0; i < ElementCount; i++)
{
values[i] = TestLibrary.Generator.GetInt16();
}
Vector256<Int16> 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]);
object lowerResult = typeof(Vector256)
.GetMethod(nameof(Vector256.GetLower))
.MakeGenericMethod(typeof(Int16))
.Invoke(null, new object[] { value });
object upperResult = typeof(Vector256)
.GetMethod(nameof(Vector256.GetUpper))
.MakeGenericMethod(typeof(Int16))
.Invoke(null, new object[] { value });
ValidateGetResult((Vector128<Int16>)(lowerResult), (Vector128<Int16>)(upperResult), values);
object result = typeof(Vector256)
.GetMethod(nameof(Vector256.WithLower))
.MakeGenericMethod(typeof(Int16))
.Invoke(null, new object[] { value, upperResult });
result = typeof(Vector256)
.GetMethod(nameof(Vector256.WithUpper))
.MakeGenericMethod(typeof(Int16))
.Invoke(null, new object[] { result, lowerResult });
ValidateWithResult((Vector256<Int16>)(result), values);
}
private void ValidateGetResult(Vector128<Int16> lowerResult, Vector128<Int16> upperResult, Int16[] values, [CallerMemberName] string method = "")
{
Int16[] lowerElements = new Int16[ElementCount / 2];
Unsafe.WriteUnaligned(ref Unsafe.As<Int16, byte>(ref lowerElements[0]), lowerResult);
Int16[] upperElements = new Int16[ElementCount / 2];
Unsafe.WriteUnaligned(ref Unsafe.As<Int16, byte>(ref upperElements[0]), upperResult);
ValidateGetResult(lowerElements, upperElements, values, method);
}
private void ValidateGetResult(Int16[] lowerResult, Int16[] upperResult, Int16[] values, [CallerMemberName] string method = "")
{
bool succeeded = true;
for (int i = 0; i < ElementCount / 2; i++)
{
if (lowerResult[i] != values[i])
{
succeeded = false;
break;
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"Vector256<Int16>.GetLower(): {method} failed:");
TestLibrary.TestFramework.LogInformation($" value: ({string.Join(", ", values)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", lowerResult)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
succeeded = true;
for (int i = ElementCount / 2; i < ElementCount; i++)
{
if (upperResult[i - (ElementCount / 2)] != values[i])
{
succeeded = false;
break;
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"Vector256<Int16>.GetUpper(): {method} failed:");
TestLibrary.TestFramework.LogInformation($" value: ({string.Join(", ", values)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", upperResult)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
private void ValidateWithResult(Vector256<Int16> result, Int16[] values, [CallerMemberName] string method = "")
{
Int16[] resultElements = new Int16[ElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Int16, byte>(ref resultElements[0]), result);
ValidateWithResult(resultElements, values, method);
}
private void ValidateWithResult(Int16[] result, Int16[] values, [CallerMemberName] string method = "")
{
bool succeeded = true;
for (int i = 0; i < ElementCount / 2; i++)
{
if (result[i] != values[i + (ElementCount / 2)])
{
succeeded = false;
break;
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"Vector256<Int16.WithLower(): {method} failed:");
TestLibrary.TestFramework.LogInformation($" value: ({string.Join(", ", values)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
succeeded = true;
for (int i = ElementCount / 2; i < ElementCount; i++)
{
if (result[i] != values[i - (ElementCount / 2)])
{
succeeded = false;
break;
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"Vector256<Int16.WithUpper(): {method} failed:");
TestLibrary.TestFramework.LogInformation($" value: ({string.Join(", ", values)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.Extensions.Logging;
using Orleans.CodeGenerator.Compatibility;
using Orleans.CodeGenerator.Utilities;
namespace Orleans.CodeGenerator.Analysis
{
internal class CompilationAnalyzer
{
private readonly ILogger log;
private readonly WellKnownTypes wellKnownTypes;
private readonly INamedTypeSymbol serializableAttribute;
private readonly INamedTypeSymbol knownBaseTypeAttribute;
private readonly INamedTypeSymbol knownAssemblyAttribute;
private readonly INamedTypeSymbol considerForCodeGenerationAttribute;
private readonly Compilation compilation;
/// <summary>
/// Assemblies whose declared types are all considered serializable.
/// </summary>
private readonly HashSet<IAssemblySymbol> assembliesWithForcedSerializability = new HashSet<IAssemblySymbol>();
/// <summary>
/// Types whose sub-types are all considered serializable.
/// </summary>
private readonly HashSet<INamedTypeSymbol> knownBaseTypes = new HashSet<INamedTypeSymbol>();
/// <summary>
/// Types which were observed in a grain interface.
/// </summary>
private readonly HashSet<ITypeSymbol> dependencyTypes = new HashSet<ITypeSymbol>();
private readonly HashSet<INamedTypeSymbol> grainInterfacesToProcess = new HashSet<INamedTypeSymbol>();
private readonly HashSet<INamedTypeSymbol> grainClassesToProcess = new HashSet<INamedTypeSymbol>();
private readonly HashSet<INamedTypeSymbol> serializationTypesToProcess = new HashSet<INamedTypeSymbol>();
private readonly HashSet<INamedTypeSymbol> fieldOfSerializableType = new HashSet<INamedTypeSymbol>();
public CompilationAnalyzer(ILogger log, WellKnownTypes wellKnownTypes, Compilation compilation)
{
this.log = log;
this.wellKnownTypes = wellKnownTypes;
this.serializableAttribute = wellKnownTypes.SerializableAttribute;
this.knownBaseTypeAttribute = wellKnownTypes.KnownBaseTypeAttribute;
this.knownAssemblyAttribute = wellKnownTypes.KnownAssemblyAttribute;
this.considerForCodeGenerationAttribute = wellKnownTypes.ConsiderForCodeGenerationAttribute;
this.compilation = compilation;
}
public HashSet<INamedTypeSymbol> CodeGenerationRequiredTypes { get; } = new HashSet<INamedTypeSymbol>();
/// <summary>
/// All assemblies referenced by this compilation.
/// </summary>
public HashSet<IAssemblySymbol> ReferencedAssemblies = new HashSet<IAssemblySymbol>();
/// <summary>
/// Assemblies which should be excluded from code generation (eg, because they already contain generated code).
/// </summary>
public HashSet<IAssemblySymbol> AssembliesExcludedFromCodeGeneration = new HashSet<IAssemblySymbol>();
/// <summary>
/// Assemblies which should be excluded from metadata generation.
/// </summary>
public HashSet<IAssemblySymbol> AssembliesExcludedFromMetadataGeneration = new HashSet<IAssemblySymbol>();
public HashSet<IAssemblySymbol> KnownAssemblies { get; } = new HashSet<IAssemblySymbol>();
public HashSet<INamedTypeSymbol> KnownTypes { get; } = new HashSet<INamedTypeSymbol>();
public (IEnumerable<INamedTypeSymbol> grainClasses, IEnumerable<INamedTypeSymbol> grainInterfaces, IEnumerable<INamedTypeSymbol> types) GetTypesToProcess() =>
(this.grainClassesToProcess, this.grainInterfacesToProcess, this.GetSerializationTypesToProcess());
private IEnumerable<INamedTypeSymbol> GetSerializationTypesToProcess()
{
var done = new HashSet<INamedTypeSymbol>();
var remaining = new HashSet<INamedTypeSymbol>();
while (done.Count != this.serializationTypesToProcess.Count)
{
remaining.Clear();
foreach (var type in this.serializationTypesToProcess)
{
if (done.Add(type)) remaining.Add(type);
}
foreach (var type in remaining)
{
yield return type;
}
}
}
public bool IsSerializable(INamedTypeSymbol type)
{
var result = false;
if (type.IsSerializable || type.HasAttribute(this.serializableAttribute))
{
if (log.IsEnabled(LogLevel.Debug)) log.LogTrace($"Type {type} has [Serializable] attribute.");
result = true;
}
if (!result && this.assembliesWithForcedSerializability.Contains(type.ContainingAssembly))
{
if (log.IsEnabled(LogLevel.Debug)) log.LogTrace($"Type {type} is declared in an assembly in which all types are considered serializable");
result = true;
}
if (!result && this.KnownTypes.Contains(type))
{
if (log.IsEnabled(LogLevel.Debug)) log.LogTrace($"Type {type} is a known type");
result = true;
}
if (!result && this.dependencyTypes.Contains(type))
{
if (log.IsEnabled(LogLevel.Debug)) log.LogTrace($"Type {type} was discovered on a grain method signature or in another serializable type");
result = true;
}
if (!result)
{
for (var current = type; current != null; current = current.BaseType)
{
if (!knownBaseTypes.Contains(current)) continue;
if (log.IsEnabled(LogLevel.Debug)) log.LogTrace($"Type {type} has a known base type");
result = true;
}
}
if (!result)
{
foreach (var iface in type.AllInterfaces)
{
if (!knownBaseTypes.Contains(iface)) continue;
if (log.IsEnabled(LogLevel.Debug)) log.LogTrace($"Type {type} has a known base interface");
result = true;
}
}
if (!result && this.fieldOfSerializableType.Contains(type))
{
if (log.IsEnabled(LogLevel.Debug)) log.LogTrace($"Type {type} is used in a field of another serializable type");
result = true;
}
if (!result)
{
if (log.IsEnabled(LogLevel.Trace)) log.LogTrace($"Type {type} is not serializable");
}
else
{
foreach (var field in type.GetInstanceMembers<IFieldSymbol>())
{
ExpandGenericArguments(field.Type);
}
void ExpandGenericArguments(ITypeSymbol typeSymbol)
{
if (typeSymbol is INamedTypeSymbol named && this.fieldOfSerializableType.Add(named))
{
InspectType(named);
foreach (var param in named.GetHierarchyTypeArguments())
{
ExpandGenericArguments(param);
}
}
}
}
return result;
}
public bool IsFromKnownAssembly(ITypeSymbol type) => this.KnownAssemblies.Contains(type.OriginalDefinition.ContainingAssembly);
private void InspectGrainInterface(INamedTypeSymbol type)
{
this.serializationTypesToProcess.Add(type);
this.grainInterfacesToProcess.Add(type);
foreach (var method in type.GetInstanceMembers<IMethodSymbol>())
{
var awaitable = IsAwaitable(method);
if (!awaitable && !method.ReturnsVoid)
{
var message = $"Grain interface {type} has method {method} which returns a non-awaitable type {method.ReturnType}."
+ " All grain interface methods must return awaitable types."
+ $" Did you mean to return Task<{method.ReturnType}>?";
this.log.LogError(message);
throw new InvalidOperationException(message);
}
if (method.ReturnType is INamedTypeSymbol returnType)
{
foreach (var named in ExpandType(returnType).OfType<INamedTypeSymbol>())
{
this.AddDependencyType(named);
this.serializationTypesToProcess.Add(named);
}
}
foreach (var param in method.Parameters)
{
if (param.Type is INamedTypeSymbol parameterType)
{
foreach (var named in ExpandType(parameterType).OfType<INamedTypeSymbol>())
{
this.AddDependencyType(named);
this.serializationTypesToProcess.Add(named);
}
}
}
}
bool IsAwaitable(IMethodSymbol method)
{
foreach (var member in method.ReturnType.GetMembers("GetAwaiter"))
{
if (member.IsStatic) continue;
if (member is IMethodSymbol m && HasZeroParameters(m))
{
return true;
}
}
return false;
bool HasZeroParameters(IMethodSymbol m) => m.Parameters.Length == 0 && m.TypeParameters.Length == 0;
}
}
private static IEnumerable<ITypeSymbol> ExpandType(ITypeSymbol symbol)
{
return ExpandTypeInternal(symbol, new HashSet<ITypeSymbol>());
IEnumerable<ITypeSymbol> ExpandTypeInternal(ITypeSymbol s, HashSet<ITypeSymbol> emitted)
{
if (!emitted.Add(s)) yield break;
yield return s;
switch (s)
{
case IArrayTypeSymbol array:
foreach (var t in ExpandTypeInternal(array.ElementType, emitted)) yield return t;
break;
case INamedTypeSymbol named:
foreach (var p in named.TypeArguments)
foreach (var t in ExpandTypeInternal(p, emitted))
yield return t;
break;
}
if (s.BaseType != null)
{
foreach (var t in ExpandTypeInternal(s.BaseType, emitted)) yield return t;
}
}
}
public void InspectType(INamedTypeSymbol type)
{
if (type.HasAttribute(knownBaseTypeAttribute)) this.AddKnownBaseType(type);
if (this.wellKnownTypes.IsGrainInterface(type)) this.InspectGrainInterface(type);
if (this.wellKnownTypes.IsGrainClass(type)) this.grainClassesToProcess.Add(type);
this.serializationTypesToProcess.Add(type);
}
public void Analyze()
{
foreach (var reference in this.compilation.References)
{
if (!(this.compilation.GetAssemblyOrModuleSymbol(reference) is IAssemblySymbol asm)) continue;
this.ReferencedAssemblies.Add(asm);
}
// Recursively all assemblies considered known from the inspected assembly.
ExpandKnownAssemblies(compilation.Assembly);
// Add all types considered known from each known assembly.
ExpandKnownTypes(this.KnownAssemblies);
this.ExpandAssembliesWithGeneratedCode();
void ExpandKnownAssemblies(IAssemblySymbol asm)
{
if (!this.KnownAssemblies.Add(asm))
{
return;
}
if (!asm.GetAttributes(this.knownAssemblyAttribute, out var attrs)) return;
foreach (var attr in attrs)
{
var param = attr.ConstructorArguments.First();
if (param.Kind != TypedConstantKind.Type)
{
throw new ArgumentException($"Unrecognized argument type in attribute [{attr.AttributeClass.Name}({param.ToCSharpString()})]");
}
var type = (ITypeSymbol)param.Value;
if (log.IsEnabled(LogLevel.Debug)) log.LogDebug($"Known assembly {type.ContainingAssembly} from assembly {asm}");
// Check if the attribute has the TreatTypesAsSerializable property set.
var prop = attr.NamedArguments.Where(a => a.Key.Equals("TreatTypesAsSerializable")).Select(a => a.Value).FirstOrDefault();
if (prop.Type != null)
{
var treatAsSerializable = (bool)prop.Value;
if (treatAsSerializable)
{
// When checking if a type in this assembly is serializable, always respond that it is.
this.AddAssemblyWithForcedSerializability(asm);
}
}
// Recurse on the assemblies which the type was declared in.
ExpandKnownAssemblies(type.OriginalDefinition.ContainingAssembly);
}
}
void ExpandKnownTypes(IEnumerable<IAssemblySymbol> asm)
{
foreach (var a in asm)
{
if (!a.GetAttributes(this.considerForCodeGenerationAttribute, out var attrs)) continue;
foreach (var attr in attrs)
{
var typeParam = attr.ConstructorArguments.First();
if (typeParam.Kind != TypedConstantKind.Type)
{
throw new ArgumentException($"Unrecognized argument type in attribute [{attr.AttributeClass.Name}({typeParam.ToCSharpString()})]");
}
var type = (INamedTypeSymbol)typeParam.Value;
this.KnownTypes.Add(type);
var throwOnFailure = false;
var throwOnFailureParam = attr.ConstructorArguments.Skip(1).FirstOrDefault();
if (throwOnFailureParam.Type != null)
{
throwOnFailure = (bool)throwOnFailureParam.Value;
if (throwOnFailure) this.CodeGenerationRequiredTypes.Add(type);
}
if (log.IsEnabled(LogLevel.Debug)) log.LogDebug($"Known type {type}, Throw on failure: {throwOnFailure}");
}
}
}
}
private void ExpandAssembliesWithGeneratedCode()
{
foreach (var asm in this.ReferencedAssemblies)
{
if (!asm.GetAttributes(this.wellKnownTypes.OrleansCodeGenerationTargetAttribute, out var attrs)) continue;
this.AssembliesExcludedFromMetadataGeneration.Add(asm);
this.AssembliesExcludedFromCodeGeneration.Add(asm);
foreach (var attr in attrs)
{
var assemblyName = attr.ConstructorArguments[0].Value as string;
bool metadataOnly;
if (attr.ConstructorArguments.Length >= 2 && attr.ConstructorArguments[1].Value is bool val)
{
metadataOnly = val;
}
else
{
metadataOnly = false;
}
if (string.IsNullOrWhiteSpace(assemblyName)) continue;
foreach (var candidate in this.ReferencedAssemblies)
{
bool hasGeneratedCode;
if (string.Equals(assemblyName, candidate.Identity.Name, StringComparison.OrdinalIgnoreCase))
{
hasGeneratedCode = true;
}
else if (string.Equals(assemblyName, candidate.Identity.GetDisplayName()))
{
hasGeneratedCode = true;
}
else if (string.Equals(assemblyName, candidate.Identity.GetDisplayName(fullKey: true)))
{
hasGeneratedCode = true;
}
else
{
hasGeneratedCode = false;
}
if (hasGeneratedCode)
{
this.AssembliesExcludedFromMetadataGeneration.Add(candidate);
if (!metadataOnly)
{
this.AssembliesExcludedFromCodeGeneration.Add(candidate);
}
break;
}
}
}
}
}
public void AddAssemblyWithForcedSerializability(IAssemblySymbol asm) => this.assembliesWithForcedSerializability.Add(asm);
public void AddKnownBaseType(INamedTypeSymbol type)
{
if (log.IsEnabled(LogLevel.Debug)) this.log.LogDebug($"Added known base type {type}");
this.knownBaseTypes.Add(type);
}
public void AddDependencyType(ITypeSymbol type)
{
if (!(type is INamedTypeSymbol named)) return;
if (named.IsGenericType && !named.IsUnboundGenericType)
{
var unbound = named.ConstructUnboundGenericType();
if (unbound.Equals(this.wellKnownTypes.Task_1))
{
return;
}
}
this.dependencyTypes.Add(type);
}
}
}
| |
#region Licence...
/*
The MIT License (MIT)
Copyright (c) 2014 Oleg Shilo
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 Licence...
using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;
using IO = System.IO;
namespace WixSharp
{
/// <summary>
/// Defines directory to be installed on target system.
/// <para>
/// Use this class to define file/directory structure of the deployment solution.
/// </para>
/// You can use predefined Wix# environment constants for well-known installation locations. They are directly mapped
/// to the corresponding WiX constants:
/// <para>For the full list of the constants consult WiX documentation or use <c>Compiler.GetMappedWixConstants</c>
/// to explore them programatically./</para>
/// <para>
/// <para><c>Wix#</c> - <c>WiX</c></para>
/// <para>%WindowsFolder% - [WindowsFolder]</para>
/// <para>%ProgramFiles% - [ProgramFilesFolder]</para>
/// <para>%ProgramMenu% - [ProgramMenuFolder]</para>
/// <para>%CommonAppDataFolder% - [CommonAppDataFolder]</para>
/// <para>%AppDataFolder% - [AppDataFolder]</para>
/// <para>%CommonFilesFolder% - [CommonFilesFolder]</para>
/// <para>%LocalAppDataFolder% - [LocalAppDataFolder]</para>
/// <para>%ProgramFiles64Folder% - [ProgramFiles64Folder]</para>
/// <para>%System64Folder% - [System64Folder]</para>
/// <para>%SystemFolder% - [SystemFolder]</para>
/// <para>%TempFolder% - [TempFolder]</para>
/// <para>%Desktop% - [DesktopFolder]</para>
/// <para>...</para>
/// </para>
/// </summary>
/// <example>The following is an example of defining installation directory <c>Progam Files/My Company/My Product</c>
/// containing a single file <c>MyApp.exe</c> and subdirectory <c>Documentation</c> with <c>UserManual.pdf</c> file.
/// <code>
/// var project = new Project("MyProduct",
///
/// new Dir(@"%ProgramFiles%\My Company\My Product",
/// new File(@"Release\MyApp.exe"),
/// new Dir("Documentation",
/// new File(@"Release\UserManual.pdf")),
/// ...
/// </code>
/// </example>
public partial class Dir : WixEntity
{
Dir lastDir;
/// <summary>
/// Initializes a new instance of the <see cref="Dir"/> class.
/// </summary>
public Dir()
{
}
/// <summary>
/// Initializes a new instance of the <see cref="Dir"/> class with properties/fields initialized with specified parameters
/// </summary>
/// <param name="id">The explicit <see cref="Id"></see> to be associated with <see cref="Dir"/> instance.</param>
/// <param name="targetPath">The name of the directory. Note if the directory is a root installation directory <c>targetPath</c> must
/// be specified as a full path. However if the directory is a nested installation directory the name must be a directory name only.</param>
/// <param name="items">Any <see cref="WixEntity"/> which can be contained by directory (e.g. file, subdirectory).</param>
public Dir(Id id, string targetPath, params WixEntity[] items)
{
lastDir = ProcessTargetPath(targetPath);
lastDir.AddItems(items);
lastDir.Id = id;
}
/// <summary>
/// Initializes a new instance of the <see cref="Dir"/> class with properties/fields initialized with specified parameters
/// </summary>
/// <param name="targetPath">The name of the directory. Note if the directory is a root installation directory <c>targetPath</c> must
/// be specified as a full path. However if the directory is a nested installation directory the name must be a directory name only.</param>
/// <param name="items">Any <see cref="WixEntity"/> which can be contained by directory (e.g. file, subdirectory).</param>
public Dir(string targetPath, params WixEntity[] items)
{
lastDir = ProcessTargetPath(targetPath);
lastDir.AddItems(items);
}
/// <summary>
/// Initializes a new instance of the <see cref="Dir"/> class with properties/fields initialized with specified parameters
/// </summary>
/// <param name="feature"><see cref="Feature"></see> the directory should be included in.</param>
/// <param name="targetPath">The name of the directory. Note if the directory is a root installation directory <c>targetPath</c> must
/// be specified as a full path. However if the directory is a nested installation directory the name must be a directory name only.</param>
/// <param name="items">Any <see cref="WixEntity"/> which can be contained by directory (e.g. file, subdirectory).</param>
public Dir(Feature feature, string targetPath, params WixEntity[] items)
{
lastDir = ProcessTargetPath(targetPath);
lastDir.AddItems(items);
lastDir.Feature = feature;
}
internal bool HasItemsToInstall()
{
return Files.Any() || FileCollections.Any() || Shortcuts.Any();
}
static internal string[] ToFlatPathTree(string path)
{
List<string> retval = new List<string>();
foreach (var dir in path.Split("\\/".ToCharArray()))
{
string lastItem = retval.LastOrDefault();
if (lastItem == null)
retval.Add(dir);
else
retval.Add(lastItem + "\\" + dir);
}
return retval.ToArray();
}
internal Dir(Feature feature, string targetPath, Project project)
{
//create nested Dirs on-fly but reuse already existing ones in the project
var nestedDirs = targetPath.Split("\\/".ToCharArray());
Dir lastFound = null;
string lastMatching = null;
string[] flatTree = ToFlatPathTree(targetPath);
foreach (string path in flatTree)
{
var existingDir = project.FindDir(path);
if (existingDir != null)
{
lastFound = existingDir;
lastMatching = path;
}
else
{
if (lastFound != null)
{
Dir currDir = lastFound;
string[] newSubDirs = targetPath.Substring(lastMatching.Length + 1).Split("\\/".ToCharArray());
for (int i = 0; i < newSubDirs.Length; i++)
{
Dir nextSubDir = new Dir(newSubDirs[i]);
currDir.Dirs = new Dir[] { nextSubDir };
currDir = nextSubDir;
}
currDir.Feature = feature;
}
else
{
lastDir = ProcessTargetPath(targetPath);
lastDir.Feature = feature;
}
break;
}
}
}
/// <summary>
/// Initializes a new instance of the <see cref="Dir"/> class with properties/fields initialized with specified parameters.
/// </summary>
/// <param name="id">The explicit <see cref="Id"></see> to be associated with <see cref="Dir"/> instance.</param>
/// <param name="feature"><see cref="Feature"></see> the directory should be included in.</param>
/// <param name="targetPath">The name of the directory. Note if the directory is a root installation directory <c>targetPath</c> must
/// be specified as a full path. However if the directory is a nested installation directory the name must be a directory name only.</param>
/// <param name="items">Any <see cref="WixEntity"/> which can be contained by directory (e.g. file, subdirectory).</param>
public Dir(Id id, Feature feature, string targetPath, params WixEntity[] items)
{
this.Feature = feature;
lastDir = ProcessTargetPath(targetPath);
lastDir.AddItems(items);
lastDir.Id = id;
lastDir.Feature = feature;
}
/// <summary>
/// Collection of the contained nested <see cref="Dir"/>s (subdirectories).
/// </summary>
public Dir[] Dirs = new Dir[0];
internal Dir AutoParent;
internal Dir GetRootAutoParent()
{
Dir result = this.AutoParent;
while (result != null)
{
if (result.AutoParent == null)
break;
else
result = result.AutoParent;
}
return result;
}
internal bool IsAutoParent()
{
return Dirs.Any(x => x.AutoParent == this);
}
/// <summary>
/// Collection of the contained <see cref="File"/>s.
/// </summary>
public File[] Files = new File[0];
/// <summary>
/// Collection of the <see cref="DirFiles"/> objects. <see cref="DirFiles"/> type is used to specify files
/// contained by a specific directory with wildcard character pattern.
/// Files in subdirectories are not included.
/// <para>
/// <see cref="DirFiles"/> type is related to but not identical to <see cref="Files"/>, which defines files of
/// not only a single level directory but all subdirectories as well.
/// </para>
/// </summary>
public DirFiles[] DirFileCollections = new DirFiles[0];
/// <summary>
/// Collection of the <see cref="Files"/> objects. <see cref="Files"/> type is used to specify files
/// contained by a specific directory and all subdirectories with wildcard character pattern.
/// <para>
/// <see cref="Files"/> type is related to but not identical to <see cref="DirFiles"/>, which defines only files
/// of a single level directory.
/// </para>
/// </summary>
public Files[] FileCollections = new Files[0];
/// <summary>
/// Collection of WiX/MSI <see cref="ODBCDataSource"/> objects to be created during the installed.
/// </summary>
public ODBCDataSource[] ODBCDataSources = new ODBCDataSource[0];
/// <summary>
/// Collection of WiX/MSI <see cref="IISVirtualDir"/> objects to be created during the installed.
/// </summary>
public IISVirtualDir[] IISVirtualDirs = new IISVirtualDir[0];
/// <summary>
/// Collection of the user defined <see cref="IGenericEntity"/> items.
/// </summary>
public IGenericEntity[] GenericItems = new IGenericEntity[0];
/// <summary>
/// Collection of the contained <see cref="Merge"/> modules.
/// </summary>
public Merge[] MergeModules = new Merge[0];
/// <summary>
/// Collection of the contained <see cref="ExeFileShortcut"/>s.
/// </summary>
public ExeFileShortcut[] Shortcuts = new ExeFileShortcut[0];
/// <summary>
/// Collection of directory permissions to be applied to this directory.
/// </summary>
public DirPermission[] Permissions = new DirPermission[0];
/// <summary>
/// Indicates if the directory is an installation directory.
/// <para>
/// Wix# assigns a dedicated WiX UI property WIXUI_INSTALLDIR
/// to the Id value of the directory, which is marked by user as <see cref="Dir.IsInstallDir"/> or the directory
/// with the designated Dir Id value defined by Compiler.AutoGeneration.InstallDirDefaultId ('INSTALLDIR' by default).
/// </para>
/// </summary>
public bool IsInstallDir
{
internal get
{
return this.isInstallDir;
}
set
{
// It's important to recognize that 'this' can be a composite Dir that has been unfolded into
// a branch of the child dirs (e.g. new Dir(@"%ProgramFiles%\CustomActionTest"). If it is the case then
// the intention of the user when he uses initializer to set IsInstallDir is to set it for the directory itself
// when it is a single directory or to the lats leaf of the unfolded tree of the composite dir.
// Getter should always return the own actual value as it is used by the compiler to decide if the dir
//should be assigned INSTALLDIR value
if (lastDir != null)
lastDir.isInstallDir = value;
else
this.isInstallDir = value;
}
}
bool isInstallDir;
///// <summary>
///// Defines the launch <see cref="Condition"/>, which is to be checked during the installation to
///// determine if the directory should be installed.
///// </summary>
//public Condition Condition;
/// <summary>
/// Returns the WiX <c>Directory</c> as a string.
/// </summary>
/// <returns>A string representing the directory.</returns>
public new string ToString()
{
return Name;
}
Dir ProcessTargetPath(string targetPath)
{
Dir currDir = this;
if (System.IO.Path.IsPathRooted(targetPath))
{
this.Name = targetPath;
}
else
{
//create nested Dirs on-fly
var nestedDirs = targetPath.Split("\\/".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
this.Name = nestedDirs.First();
for (int i = 1; i < nestedDirs.Length; i++)
{
Dir nextSubDir = new Dir(nestedDirs[i]);
nextSubDir.AutoParent = currDir;
//currDir.MoveAttributesTo(nextSubDir); //attributes may not be set at this stage
currDir.Dirs = new Dir[] { nextSubDir };
currDir = nextSubDir;
}
}
return currDir;
}
void AddItems(WixEntity[] items)
{
var files = new List<File>();
var dirs = new List<Dir>();
var fileCollections = new List<DirFiles>();
var dirItemsCollections = new List<Files>();
var shortcuts = new List<ExeFileShortcut>();
var genericItems = new List<IGenericEntity>();
var mergeModules = new List<Merge>();
var dirPermissions = new List<DirPermission>();
var odbcSources = new List<ODBCDataSource>();
var iisVirtualDirs = new List<IISVirtualDir>();
foreach (WixEntity item in items)
if (item is Dir)
dirs.Add(item as Dir);
else if (item is File)
files.Add(item as File);
else if (item is DirFiles)
fileCollections.Add(item as DirFiles);
else if (item is Files)
dirItemsCollections.Add(item as Files);
else if (item is IGenericEntity)
genericItems.Add(item as IGenericEntity);
else if (item is ExeFileShortcut)
shortcuts.Add(item as ExeFileShortcut);
else if (item is Merge)
mergeModules.Add(item as Merge);
else if (item is DirPermission)
dirPermissions.Add(item as DirPermission);
else if (item is ODBCDataSource)
odbcSources.Add(item as ODBCDataSource);
else if (item is IISVirtualDir)
iisVirtualDirs.Add(item as IISVirtualDir);
else
throw new Exception(item.GetType().Name + " is not expected to be a child of WixSharp.Dir");
Files = files.ToArray();
Dirs = dirs.ToArray();
DirFileCollections = fileCollections.ToArray();
FileCollections = dirItemsCollections.ToArray();
Shortcuts = shortcuts.ToArray();
GenericItems = genericItems.ToArray();
MergeModules = mergeModules.ToArray();
Permissions = dirPermissions.ToArray();
ODBCDataSources = odbcSources.ToArray();
IISVirtualDirs = iisVirtualDirs.ToArray();
}
}
}
| |
using System;
using System.Text;
using System.Diagnostics;
using NS_IDraw;
using fu=System.Int32;
using Curve=NS_GMath.I_CurveD;
using LCurve=NS_GMath.I_LCurveD;
namespace NS_GMath
{
public class VecD : I_Drawable, I_Transformable, I_BBox
{
/*
* MEMBERS
*/
double x;
double y;
/*
* PROPERTIES
*/
public double X
{
get { return this.x; }
set { this.x=value; }
}
public double Y
{
get { return this.y; }
set { this.y=value; }
}
public double Norm
{
get { return Math.Sqrt(this.x*this.x+this.y*this.y); }
}
public fu FUX
{
// TODO: check !!!
get { return (int)Math.Round(this.x); }
}
public fu FUY
{
// TODO: check !!!
get { return (int)Math.Round(this.y); }
}
public bool IsFU
{
get
{
return ((Math.Abs(this.X-this.FUX)<MConsts.EPS_DEC)&&
(Math.Abs(this.Y-this.FUY)<MConsts.EPS_DEC));
}
}
/*
* CONSTRUCTORS
*/
public VecD(double x, double y)
{
this.x=x;
this.y=y;
}
public VecD(VecD vec)
{
this.x=vec.X;
this.y=vec.Y;
}
/*
* OPERATORS
*/
public static VecD operator+ (VecD vecA, VecD vecB)
{
return (new VecD(vecA.X+vecB.X, vecA.Y+vecB.Y));
}
public static VecD operator- (VecD vecA, VecD vecB)
{
return (new VecD(vecA.X-vecB.X,vecA.Y-vecB.Y));
}
public static VecD operator* (double factor, VecD vec)
{
return (new VecD(factor*vec.X, factor*vec.Y));
}
public static bool operator== (VecD vecA, VecD vecB)
{
if (((object)vecA==null)||((object)vecB==null))
return false;
return ((vecA-vecB).Norm<MConsts.EPS_DEC);
}
public static bool operator!= (VecD vecA, VecD vecB)
{
return (!(vecA==vecB));
}
/*
* METHODS
*/
public VecD Copy()
{
return new VecD(this);
}
public void FURound(out bool isChanged)
{
double xOld=this.x;
double yOld=this.y;
this.x=this.FUX;
this.y=this.FUY;
isChanged=((this.x!=xOld)||(this.y!=yOld));
}
public void From(VecD vec)
{
this.x=vec.X;
this.y=vec.Y;
}
public void From(double x, double y)
{
this.x=x;
this.y=y;
}
public double Dot(VecD vec)
{
return (this.x*vec.X+this.y*vec.Y);
}
public double Cross(VecD vec)
{
return (this.x*vec.Y-this.y*vec.X);
}
public double Dist(VecD vec)
{
return (this-vec).Norm;
}
bool Perp(LCurve lrs, out Param param)
{
/*
* MEANING: perpendicular to the parametric range
* [-Infinity, Infinity]
*/
param=null;
if (lrs.IsDegen)
{
throw new ExceptionGMath("VecD","Perp",null);
//return false;
}
VecD start=lrs.Start;
VecD end=lrs.End;
double length=(end-start).Norm;
VecD tang=lrs.DirTang;
param = new Param(((this-start).Dot(tang))/((end-start).Dot(tang)));
return true;
}
bool Perp(Bez2D bez, out Param[] pars)
{
/*
* MEANING: perpendicular to the parametric range
* [-Infinity, Infinity] for NON-DEGENERATED,
* NON-FLAT bezier
*/
pars=null;
Param parM;
if (bez.IsDegen)
{
throw new ExceptionGMath("VecD","Perp",null);
//return false;
}
if (bez.IsSeg(out parM)||bez.IsSelfInters(out parM))
{
throw new ExceptionGMath("VecD","Perp",null);
//return false;
}
VecD[] pcf;
bez.PowerCoeff(out pcf);
double a = 2*(pcf[2].Dot(pcf[2]));
double b = 3*(pcf[2].Dot(pcf[1]));
double c = pcf[1].Dot(pcf[1])+2*((pcf[0]-(this)).Dot(pcf[2]));
double d = (pcf[0]-(this)).Dot(pcf[1]);
int numRootReal;
double[] root;
Equation.RootsReal(a,b,c,d,out numRootReal,out root);
pars=new Param[root.Length];
for (int iRoot=0; iRoot<root.Length; iRoot++)
{
pars[iRoot]=new Param(root[iRoot]);
}
return true;
}
public bool Project(LCurve lcurve, out Param param, out VecD pnt)
{
/*
* MEANING: the NEAREST point in the PARAMETRIC RANGE
* of the curve
*
* ASSUMPTIONS: the curve may be not reduced
*/
param=null;
pnt=null;
if (lcurve.IsDegen)
{
SegD seg=lcurve as SegD;
if (seg==null)
{
throw new ExceptionGMath("VecD","Project",null);
//return false;
}
param=new Param(Param.Degen);
pnt=seg.Middle;
return true;
}
this.Perp(lcurve, out param);
param.Clip(lcurve.ParamStart,lcurve.ParamEnd);
pnt=lcurve.Evaluate(param);
return true;
}
public bool ProjectGeneral(Bez2D bez, out Param[] pars, out VecD pnt)
{
/*
* MEANING: parameter (or parameters) of the nearest point
* in range [0,1]
*
* ASSUMPTIONS: bezier can be non-reduced
* bezier can be self-intersecting
*
*/
pars=null;
pnt=null;
Param parM;
if (!bez.IsSelfInters(out parM))
{
Param par;
if (!this.Project(bez,out par,out pnt))
return false;
if (par!=null)
{
pars=new Param[1];
pars[0]=par;
}
return true;
}
double valM=parM.Val;
if (parM<0)
{
Bez2D bezRev=new Bez2D(bez);
bezRev.Reverse();
if (!this.ProjectGeneral(bezRev,out pars,out pnt))
return false;
if (pars!=null)
{
for (int iPar=0; iPar<pars.Length; iPar++)
{
pars[iPar].Reverse(1);
}
}
return true;
}
SegD support=bez.SupportFlat();
Param parSupport;
if (!this.Project(support,out parSupport, out pnt))
return false;
if (!bez.ParamFromSupport(parSupport,out pars))
return false;
return true;
}
public bool Project(Bez2D bez, out Param par, out VecD pnt)
{
/*
* MEANING: the NEAREST point in the RANGE [0,1]
* ASSUMPTION: - bezier can be non-reduced
* - bezier is NOT self-intersecting
*/
par=null;
pnt=null;
Param parM;
if (bez.IsSelfInters(out parM))
{
throw new ExceptionGMath("VecD","Project(bez)",null);
//return false;
}
if (bez.IsDegen)
{
par=new Param(Param.Degen);
pnt=bez.Middle;
return true;
}
if (bez.IsSeg(out parM))
{
SegD seg=bez.Reduced as SegD;
this.Project(seg,out par,out pnt);
bez.ParamFromSeg(par);
return true;
}
// case of non-flat Bezier
Param[] parsPerp;
if (!this.Perp(bez, out parsPerp))
return false;
double distS=this.Dist(bez.Start);
double distE=this.Dist(bez.End);
double distMin=Math.Min(distS,distE);
double parMin=(distS<=distE)? 0.0: 1.0;
if (parsPerp!=null)
{
for (int iPerp=0; iPerp<parsPerp.Length; iPerp++)
{
if (bez.IsEvaluableStrict(parsPerp[iPerp]))
{
double distPerp=this.Dist(bez.Evaluate(parsPerp[iPerp]));
if (distPerp<distMin)
{
distMin=distPerp;
parMin=parsPerp[iPerp];
}
}
}
}
par=parMin;
pnt=bez.Evaluate(parMin);
return true;
}
bool InverseOn(Bez2D bez, out bool isOn, out Param par)
{
/*
* MEANING: inverse point which is known to lie on the
* bezier in range [-Infinity, Infinity]
*
* ASSUMPTIONS: bez is IRREDUCABLE && NOT S/I
*
*/
isOn=false;
par=null;
Param parM;
if ((bez.IsDegen)||(bez.IsSeg(out parM))||(bez.IsSelfInters(out parM)))
{
throw new ExceptionGMath("VecD","InverseOn(bez)",null);
//return false;
}
VecD[] cfBez;
bez.PowerCoeff(out cfBez);
double dev=(cfBez[2].Cross(this-cfBez[0]))*
(cfBez[2].Cross(this-cfBez[0]))-
(cfBez[2].Cross(cfBez[1]))*
((this-cfBez[0]).Cross(cfBez[1]));
if (Math.Abs(dev)<MConsts.EPS_DEC)
{
isOn=true;
par=(cfBez[2].Cross(this-cfBez[0]))/(cfBez[2].Cross(cfBez[1]));
}
return true;
}
bool InverseOn(LCurve lrs, out bool isOn, out Param par)
{
/*
* MEANING: inverse point which is known to lie on the
* lrs in range [-Infinity, Infinity]
*
* ASSUMPTIONS: lrs is non-degenerated
*
*/
isOn=false;
par=null;
if (lrs.IsDegen)
{
throw new ExceptionGMath("VecD","InverseOn(lrs)",null);
//return false;
}
this.Inverse(lrs, out par);
if (this.Dist(lrs.Evaluate(par))<MConsts.EPS_DEC)
{
isOn=true;
}
else
{
par=null;
}
return true;
}
public bool InverseOn(Curve curve, out bool isOn, out Param par)
{
isOn=false;
par=null;
if (curve is LCurve)
{
return this.InverseOn(curve as LCurve, out isOn, out par);
}
if (curve is Bez2D)
{
return this.InverseOn(curve as Bez2D, out isOn, out par);
}
throw new ExceptionGMath("VecD","InverseOn","NOT IMPLEMENTED");
//return false;
}
public bool Inverse(Bez2D bez, out Param par)
{
/*
* MEANING:
* - Parameter of the nearest point in range
* [-Infinity, Infinity]
* ASSUMPTIONS:
* - Bezier is REDUCED
* - Works for any bezier if the nearest point belongs
* to support
* - Works for non S/I bezier if the nearest point lies
* without the support
*/
par=null;
Param parM;
if (!bez.IsSelfInters(out parM))
{
Param[] parsPerp;
if (!this.Perp(bez, out parsPerp))
return false;
double distMin=MConsts.Infinity;
for (int iPar=0; iPar<parsPerp.Length; iPar++)
{
double distCur=this.Dist(bez.Evaluate(parsPerp[iPar]));
if (distCur<distMin)
{
distMin=distCur;
par=parsPerp[iPar];
}
}
return true;
}
// bezier is s/i
Param[] parsProj;
VecD pnt;
if (!this.ProjectGeneral(bez, out parsProj, out pnt))
return false;
if (this.Dist(pnt)>MConsts.EPS_DEC)
{
throw new ExceptionGMath("VecD","Inverse(bez)",null);
//return false;
}
par=parsProj[0];
return true;
}
public bool Inverse(LCurve lrs, out Param par)
{
/*
* MEANING:
* - Parameter of the nearest point in range
* [-Infinity, Infinity]
* ASSUMPTIONS:
* - LRS is NON-DEGENERSTED
*/
return (this.Perp(lrs,out par));
}
public bool Inverse(Curve curve, out Param par)
{
par=null;
if (curve is LCurve)
{
return (this.Inverse(curve as LCurve,out par));
}
if (curve is Bez2D)
{
return (this.Inverse(curve as Bez2D,out par));
}
throw new ExceptionGMath("VecD","Inverse(curve)","NOT IMPLEMENTED");
//return false;
}
/*
* METHODS: I_DRAWABLE
*/
public void Draw(I_Draw i_Draw, DrawParam dp)
{
DrawParamVec dpVec=dp as DrawParamVec;
if (dpVec!=null)
{
i_Draw.DrawPnt(this.x, this.y,
dpVec.ScrRad, dpVec.StrColor, dpVec.ScrWidth, dpVec.ToFill);
}
}
/*
* METHODS : GENERAL
*/
public void Clear()
{
this.x=0.0;
this.y=0.0;
}
public override bool Equals(object obj)
{
VecD vec=obj as VecD;
if (vec==null)
return false;
return ((this.x==vec.X)&&(this.y==vec.Y));
}
public override int GetHashCode()
{
return (int)(this.x+this.y);
}
public override string ToString()
{
StringBuilder strBuilder=new StringBuilder();
strBuilder.Append("VecI=("+this.x+","+this.y+")");
return strBuilder.ToString();
}
/*
* METHODS: GEOMETRICAL
*/
public void Transform(MatrixD m)
{
// vector * matrix
this.x=m[0,0]*this.x+m[1,0]*this.y+m[2,0];
this.y=m[0,1]*this.x+m[1,1]*this.y+m[2,1];
}
public VecD Transformed(MatrixD m)
{
VecD vec=new VecD(this);
vec.Transform(m);
return vec;
}
public BoxD BBox
{
get
{
return new BoxD(this.x,this.y,this.x,this.y);
}
}
/*
* CASTINGS
*/
/*
public static implicit operator PointF(VecD vecD)
{
PointF pnt=new PointF((float)vecD.X, (float)vecD.Y);
return pnt;
}
*/
}
}
| |
using System;
using Microsoft.SPOT;
using Skewworks.NETMF.Graphics;
using Skewworks.NETMF.Resources;
namespace Skewworks.NETMF.Controls
{
[Serializable]
public class Shortcut : Control
{
#region Enumerations
public enum ImageTypes
{
Bitmap = 0,
Image32 = 1,
}
#endregion
#region Variables
private Image32 _img;
private Bitmap _bmp;
private string _target;
private string _title;
private Font _font;
private ImageTypes _imgType;
private readonly int _tT;
#endregion
#region Constructor
public Shortcut(string name, Bitmap image, string title, string target, int x, int y)
{
Name = name;
// ReSharper disable DoNotCallOverridableMethodsInConstructor
X = x;
Y = y;
if (image.Width >= 48)
{
Width = 100;
Height = 75;
_tT = 52;
}
else
{
Width = 66;
Height = 50;
_tT = 36;
}
// ReSharper restore DoNotCallOverridableMethodsInConstructor
_imgType = ImageTypes.Bitmap;
_bmp = image;
_title = title;
_target = target;
UpdateFont();
}
public Shortcut(string name, Image32 image, string title, string target, int x, int y)
{
Name = name;
// ReSharper disable DoNotCallOverridableMethodsInConstructor
X = x;
Y = y;
if (image.Width >= 48)
{
Width = 100;
Height = 75;
_tT = 52;
}
else
{
Width = 66;
Height = 50;
_tT = 36;
}
// ReSharper restore DoNotCallOverridableMethodsInConstructor
_imgType = ImageTypes.Image32;
_img = image;
_title = title;
_target = target;
UpdateFont();
}
#endregion
#region Properties
public object Image
{
get
{
if (_imgType == ImageTypes.Bitmap)
{
return _bmp;
}
return _img;
}
set
{
if (_img == value)
{
return;
}
var img = value as Image32;
if (img != null)
{
_img = img;
_bmp = null;
_imgType = ImageTypes.Image32;
}
else
{
_bmp = (Bitmap)value;
_img = null;
_imgType = ImageTypes.Bitmap;
}
Invalidate();
}
}
public ImageTypes ImageType
{
get { return _imgType; }
}
public string Target
{
get { return _target; }
set { _target = value; }
}
public string Title
{
get { return _title; }
set
{
if (_title == value)
return;
_title = value;
UpdateFont();
Invalidate();
}
}
#endregion
#region GUI
// ReSharper disable RedundantAssignment
protected override void OnRender(int x, int y, int width, int height)
// ReSharper restore RedundantAssignment
{
int tH = FontManager.ComputeExtentEx(_font, _title).Height;
int aH = Height - _tT;
x = Left;
y = Top;
if (_imgType == ImageTypes.Bitmap)
Core.Screen.DrawImage(x + (Width / 2 - _bmp.Width / 2), y, _bmp, 0, 0, _bmp.Width, _bmp.Height);
else
_img.Draw(Core.Screen, x + (Width / 2 - _img.Width / 2), y);
if (Parent.ActiveChild == this)
{
Core.Screen.DrawRectangle(0, 0, x, y + _tT, Width, aH, 0, 0, Core.SystemColors.SelectionColor, 0, 0, Core.SystemColors.SelectionColor, 0, 0, 160);
Core.Screen.DrawTextInRect(_title, x + 2, y + _tT + (aH / 2 - tH / 2), Width - 4, tH, Bitmap.DT_AlignmentCenter + Bitmap.DT_TrimmingCharacterEllipsis,
Core.SystemColors.SelectedFontColor, _font);
}
else
{
Core.Screen.DrawRectangle(0, 0, x, y + _tT, Width, aH, 0, 0, Core.SystemColors.AltSelectionColor, 0, 0, Core.SystemColors.AltSelectionColor, 0, 0, 160);
Core.Screen.DrawTextInRect(_title, x + 2, y + _tT + (aH / 2 - tH / 2), Width - 4, tH, Bitmap.DT_AlignmentCenter + Bitmap.DT_TrimmingCharacterEllipsis,
Core.SystemColors.AltSelectedFontColor, _font);
}
}
public void RenderToBuffer(Bitmap buffer)
{
if (_imgType == ImageTypes.Image32)
_img.Draw(buffer, buffer.Width / 2 - _img.Width / 2, 0);
else
buffer.DrawImage(buffer.Width / 2 - _bmp.Width / 2, 0, _bmp, 0, 0, _bmp.Width, _bmp.Height);
buffer.DrawRectangle(0, 0, 0, _tT, buffer.Width, buffer.Height - _tT, 0, 0, Core.SystemColors.SelectionColor, 0, 0, Core.SystemColors.SelectionColor, 0, 0, 160);
int tH = FontManager.ComputeExtentEx(_font, _title).Height;
int aH = Height - _tT;
buffer.DrawTextInRect(_title, 2, _tT + (aH / 2 - tH / 2), Width - 4, tH, Bitmap.DT_AlignmentCenter + Bitmap.DT_TrimmingCharacterEllipsis,
Core.SystemColors.SelectedFontColor, _font);
}
#endregion
#region Private Methods
private void UpdateFont()
{
if (Fonts.Droid16.Height <= Height - _tT && FontManager.ComputeExtentEx(Fonts.Droid16, _title).Width < Width - 4)
_font = Fonts.Droid16;
else if (Fonts.Droid12.Height <= Height - _tT && FontManager.ComputeExtentEx(Fonts.Droid12, _title).Width < Width - 4)
_font = Fonts.Droid12;
else if (Fonts.Droid11.Height <= Height - _tT && FontManager.ComputeExtentEx(Fonts.Droid11, _title).Width < Width - 4)
_font = Fonts.Droid11;
else if (Fonts.Droid9.Height <= Height - _tT && FontManager.ComputeExtentEx(Fonts.Droid9, _title).Width < Width - 4)
_font = Fonts.Droid9;
else
_font = Fonts.Droid8;
}
#endregion
}
}
| |
using System;
using System.Collections;
using System.Security.Principal;
using System.Web;
using System.Web.UI.WebControls;
using Appleseed.Framework;
using Appleseed.Framework.Settings;
using Appleseed.Framework.Settings.Cache;
using Appleseed.Framework.Site.Configuration;
using Appleseed.Framework.Site.Data;
using Appleseed.Framework.Users.Data;
using Appleseed.Framework.Web.UI;
using System.Collections.Generic;
using Appleseed.Framework.Providers.AppleseedRoleProvider;
using Appleseed.Framework.Providers.AppleseedSiteMapProvider;
namespace Appleseed.Admin
{
public partial class AddPage : EditItemPage
{
#region Page_Load
/// <summary>
/// The Page_Load server event handler on this page is used
/// to populate a tab's layout settings on the page
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="T:System.EventArgs"/> instance containing the event data.</param>
private void Page_Load(object sender, EventArgs e)
{
// If first visit to the page, update all entries
if (!Page.IsPostBack)
{
msgError.Visible = false;
BindData();
}
}
#endregion
#region Events
/// <summary>
/// The cancelButton_Click is used to return to the
/// previous page if present
/// Created by Mike Stone 30/12/2004
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="T:System.EventArgs"/> instance containing the event data.</param>
private void cancelButton_Click(object sender, EventArgs e)
{
string returnPage =
HttpUrlBuilder.BuildUrl("~/DesktopDefault.aspx", int.Parse(Request.QueryString["returntabid"]));
Response.Redirect(returnPage);
}
/// <summary>
/// The SaveButton_Click is used to commit the tab/page
/// information from the form to the database.
/// Created by Mike Stone 29/12/2004
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="T:System.EventArgs"/> instance containing the event data.</param>
private void SaveButton_Click(object sender, EventArgs e)
{
//Only Save if Input Data is Valid
int NewPageID = 0;
string returnPage;
if (Page.IsValid == true)
{
try
{
NewPageID = SavePageData();
// Flush all tab navigation cache keys. Very important for recovery the changes
// made in all languages and not get a error if user change the tab parent.
// [email protected] (05/10/2004)
// Copied to here 29/12/2004 by Mike Stone
CurrentCache.RemoveAll("_PageNavigationSettings_");
//Jump to Page option
if (cb_JumpToPage.Checked == true)
{
// Redirect to New Form - Mike Stone 19/12/2004
returnPage =
HttpUrlBuilder.BuildUrl("~/" + HttpUrlBuilder.DefaultPage, NewPageID,
"SelectedPageID=" + NewPageID.ToString());
}
else
{
// Do NOT Redirect to New Form - Mike Stone 19/12/2004
// I guess every .aspx page needs to have a module tied to it.
// or you will get an error about edit access denied.
// Fix: RBP-594 by mike stone added returntabid to url.
returnPage =
HttpUrlBuilder.BuildUrl("~/DesktopModules/CoreModules/Pages/AddPage.aspx",
"mID=" + Request.QueryString["mID"] + "&returntabid=" +
Request.QueryString["returntabid"]);
}
Response.Redirect(returnPage);
}
catch
{
lblErrorNotAllowed.Visible = true;
}
}
}
#endregion
#region Methods
/// <summary>
/// The SavePageData helper method is used to persist the
/// current tab settings to the database.
/// </summary>
/// <returns></returns>
private int SavePageData()
{
// Construct Authorized User Roles string
string authorizedRoles = "";
foreach ( ListItem item in authRoles.Items ) {
if ( item.Selected == true ) {
authorizedRoles = authorizedRoles + item.Text + ";";
}
}
// Add Page info in the database
int NewPageID =
new PagesDB().AddPage(this.PortalSettings.PortalID, Int32.Parse(parentPage.SelectedItem.Value), tabName.Text,
990000, authorizedRoles, showMobile.Checked, mobilePageName.Text);
//Clear SiteMaps Cache
AppleseedSiteMapProvider.ClearAllAppleseedSiteMapCaches();
// Update custom settings in the database
EditTable.UpdateControls();
return NewPageID;
}
/// <summary>
/// The BindData helper method is used to update the tab's
/// layout panes with the current configuration information
/// </summary>
private void BindData() {
PageSettings tab = this.PortalSettings.ActivePage;
// Populate Page Names, etc.
tabName.Text = "New Page";
mobilePageName.Text = "";
showMobile.Checked = false;
// Populate the "ParentPage" Data
PagesDB t = new PagesDB();
IList<PageItem> items = t.GetPagesParent( this.PortalSettings.PortalID, PageID );
parentPage.DataSource = items;
parentPage.DataBind();
// Translate
if ( parentPage.Items.FindByText( " ROOT_LEVEL" ) != null )
parentPage.Items.FindByText( " ROOT_LEVEL" ).Text =
General.GetString( "ROOT_LEVEL", "Root Level", parentPage );
// Populate checkbox list with all security roles for this portal
// and "check" the ones already configured for this tab
UsersDB users = new UsersDB();
IList<AppleseedRole> roles = users.GetPortalRoles( this.PortalSettings.PortalAlias );
// Clear existing items in checkboxlist
authRoles.Items.Clear();
foreach ( AppleseedRole role in roles ) {
ListItem item = new ListItem();
item.Text = role.Name;
item.Value = role.Id.ToString();
if ( ( tab.AuthorizedRoles.LastIndexOf( item.Text ) ) > -1 )
item.Selected = true;
authRoles.Items.Add( item );
}
}
#endregion
#region Web Form Designer generated code
/// <summary>
/// Raises the Init event.
/// </summary>
/// <param name="e">An <see cref="T:System.EventArgs"></see> that contains the event data.</param>
protected override void OnInit(EventArgs e)
{
this.saveButton.Click += new EventHandler(this.SaveButton_Click);
this.CancelButton.Click += new EventHandler(this.cancelButton_Click);
this.Load += new EventHandler(this.Page_Load);
//Confirm delete
if (!(ClientScript.IsClientScriptBlockRegistered("confirmDelete")))
{
string[] s = {"CONFIRM_DELETE"};
ClientScript.RegisterClientScriptBlock(this.GetType(), "confirmDelete",
PortalSettings.GetStringResource(
"CONFIRM_DELETE_SCRIPT", s));
}
base.OnInit(e);
}
#endregion
}
}
| |
//------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//------------------------------------------------------------
namespace System.ServiceModel.Channels
{
using System;
using System.IO;
using System.Runtime;
using System.Threading;
using System.Threading.Tasks;
using System.Xml;
sealed class XmlByteStreamWriter : XmlDictionaryWriter
{
bool ownsStream;
ByteStreamWriterState state;
Stream stream;
XmlWriterSettings settings;
public XmlByteStreamWriter(Stream stream, bool ownsStream)
{
Fx.Assert(stream != null, "stream is null");
this.stream = stream;
this.ownsStream = ownsStream;
this.state = ByteStreamWriterState.Start;
}
public override WriteState WriteState
{
get { return ByteStreamWriterStateToWriteState(this.state); }
}
public override XmlWriterSettings Settings
{
get
{
if (settings == null)
{
XmlWriterSettings newSettings = new XmlWriterSettings()
{
Async = true
};
Interlocked.CompareExchange<XmlWriterSettings>(ref this.settings, newSettings, null);
}
return this.settings;
}
}
public override void Close()
{
if (this.state != ByteStreamWriterState.Closed)
{
try
{
if (ownsStream)
{
this.stream.Close();
}
this.stream = null;
}
finally
{
this.state = ByteStreamWriterState.Closed;
}
}
}
void EnsureWriteBase64State(byte[] buffer, int index, int count)
{
ThrowIfClosed();
ByteStreamMessageUtility.EnsureByteBoundaries(buffer, index, count, false);
if (this.state != ByteStreamWriterState.Content && this.state != ByteStreamWriterState.StartElement)
{
throw FxTrace.Exception.AsError(
new InvalidOperationException(SR.XmlWriterMustBeInElement(ByteStreamWriterStateToWriteState(this.state))));
}
}
public override void Flush()
{
ThrowIfClosed();
this.stream.Flush();
}
void InternalWriteEndElement()
{
ThrowIfClosed();
if (this.state != ByteStreamWriterState.StartElement && this.state != ByteStreamWriterState.Content)
{
throw FxTrace.Exception.AsError(
new InvalidOperationException(SR.XmlUnexpectedEndElement));
}
this.state = ByteStreamWriterState.EndElement;
}
public override string LookupPrefix(string ns)
{
if (ns == string.Empty)
{
return string.Empty;
}
else if (ns == ByteStreamMessageUtility.XmlNamespace)
{
return "xml";
}
else if (ns == ByteStreamMessageUtility.XmlNamespaceNamespace)
{
return "xmlns";
}
else
{
return null;
}
}
public override void WriteBase64(byte[] buffer, int index, int count)
{
EnsureWriteBase64State(buffer, index, count);
this.stream.Write(buffer, index, count);
this.state = ByteStreamWriterState.Content;
}
public override Task WriteBase64Async(byte[] buffer, int index, int count)
{
return Task.Factory.FromAsync(this.BeginWriteBase64, this.EndWriteBase64, buffer, index, count, null);
}
internal IAsyncResult BeginWriteBase64(byte[] buffer, int index, int count, AsyncCallback callback, object state)
{
EnsureWriteBase64State(buffer, index, count);
return new WriteBase64AsyncResult(buffer, index, count, this, callback, state);
}
internal void EndWriteBase64(IAsyncResult result)
{
WriteBase64AsyncResult.End(result);
}
class WriteBase64AsyncResult : AsyncResult
{
XmlByteStreamWriter writer;
public WriteBase64AsyncResult(byte[] buffer, int index, int count, XmlByteStreamWriter writer, AsyncCallback callback, object state)
: base(callback, state)
{
this.writer = writer;
IAsyncResult result = writer.stream.BeginWrite(buffer, index, count, PrepareAsyncCompletion(HandleWriteBase64), this);
bool completeSelf = SyncContinue(result);
if (completeSelf)
{
this.Complete(true);
}
}
static bool HandleWriteBase64(IAsyncResult result)
{
WriteBase64AsyncResult thisPtr = (WriteBase64AsyncResult)result.AsyncState;
thisPtr.writer.stream.EndWrite(result);
thisPtr.writer.state = ByteStreamWriterState.Content;
return true;
}
public static void End(IAsyncResult result)
{
AsyncResult.End<WriteBase64AsyncResult>(result);
}
}
public override void WriteCData(string text)
{
throw FxTrace.Exception.AsError(new NotSupportedException());
}
public override void WriteCharEntity(char ch)
{
throw FxTrace.Exception.AsError(new NotSupportedException());
}
public override void WriteChars(char[] buffer, int index, int count)
{
throw FxTrace.Exception.AsError(new NotSupportedException());
}
public override void WriteComment(string text)
{
throw FxTrace.Exception.AsError(new NotSupportedException());
}
public override void WriteDocType(string name, string pubid, string sysid, string subset)
{
throw FxTrace.Exception.AsError(new NotSupportedException());
}
public override void WriteEndAttribute()
{
throw FxTrace.Exception.AsError(new NotSupportedException());
}
public override void WriteEndDocument()
{
return;
}
public override void WriteEndElement()
{
this.InternalWriteEndElement();
}
public override void WriteEntityRef(string name)
{
throw FxTrace.Exception.AsError(new NotSupportedException());
}
public override void WriteFullEndElement()
{
this.InternalWriteEndElement();
}
public override void WriteProcessingInstruction(string name, string text)
{
throw FxTrace.Exception.AsError(new NotSupportedException());
}
public override void WriteRaw(string data)
{
throw FxTrace.Exception.AsError(new NotSupportedException());
}
public override void WriteRaw(char[] buffer, int index, int count)
{
throw FxTrace.Exception.AsError(new NotSupportedException());
}
public override void WriteStartAttribute(string prefix, string localName, string ns)
{
throw FxTrace.Exception.AsError(new NotSupportedException());
}
public override void WriteStartDocument(bool standalone)
{
ThrowIfClosed();
}
public override void WriteStartDocument()
{
ThrowIfClosed();
}
public override void WriteStartElement(string prefix, string localName, string ns)
{
ThrowIfClosed();
if (this.state != ByteStreamWriterState.Start)
{
throw FxTrace.Exception.AsError(
new InvalidOperationException(SR.ByteStreamWriteStartElementAlreadyCalled));
}
if (!string.IsNullOrEmpty(prefix) || !string.IsNullOrEmpty(ns) || localName != ByteStreamMessageUtility.StreamElementName)
{
throw FxTrace.Exception.AsError(
new XmlException(SR.XmlStartElementNameExpected(ByteStreamMessageUtility.StreamElementName, localName)));
}
this.state = ByteStreamWriterState.StartElement;
}
public override void WriteString(string text)
{
// no state checks here - WriteBase64 will take care of this.
byte[] buffer = Convert.FromBase64String(text);
WriteBase64(buffer, 0, buffer.Length);
}
public override void WriteSurrogateCharEntity(char lowChar, char highChar)
{
throw FxTrace.Exception.AsError(new NotSupportedException());
}
public override void WriteWhitespace(string ws)
{
throw FxTrace.Exception.AsError(new NotSupportedException());
}
void ThrowIfClosed()
{
if (this.state == ByteStreamWriterState.Closed)
{
throw FxTrace.Exception.AsError(
new InvalidOperationException(SR.XmlWriterClosed));
}
}
static WriteState ByteStreamWriterStateToWriteState(ByteStreamWriterState byteStreamWriterState)
{
// Converts the internal ByteStreamWriterState to an Xml WriteState
switch (byteStreamWriterState)
{
case ByteStreamWriterState.Start:
return WriteState.Start;
case ByteStreamWriterState.StartElement:
return WriteState.Element;
case ByteStreamWriterState.Content:
return WriteState.Content;
case ByteStreamWriterState.EndElement:
return WriteState.Element;
case ByteStreamWriterState.Closed:
return WriteState.Closed;
default:
return WriteState.Error;
}
}
enum ByteStreamWriterState
{
Start,
StartElement,
Content,
EndElement,
Closed
}
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Reflection;
using System.Text.RegularExpressions;
using System.Threading;
using System.Web;
using log4net;
using Nwc.XmlRpc;
using OpenMetaverse;
using OpenMetaverse.StructuredData;
using OpenSim.Framework;
using OpenSim.Framework.Communications.Cache;
using OpenSim.Framework.Statistics;
using OpenSim.Services.Interfaces;
namespace OpenSim.Framework.Communications.Services
{
public abstract class LoginService
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
protected string m_welcomeMessage = "Welcome to OpenSim";
protected int m_minLoginLevel = 0;
protected UserManagerBase m_userManager = null;
protected Mutex m_loginMutex = new Mutex(false);
/// <summary>
/// Used during login to send the skeleton of the OpenSim Library to the client.
/// </summary>
protected LibraryRootFolder m_libraryRootFolder;
protected uint m_defaultHomeX;
protected uint m_defaultHomeY;
protected bool m_warn_already_logged = true;
/// <summary>
/// Used by the login service to make requests to the inventory service.
/// </summary>
protected IInterServiceInventoryServices m_interInventoryService;
// Hack
protected IInventoryService m_InventoryService;
/// <summary>
/// Constructor
/// </summary>
/// <param name="userManager"></param>
/// <param name="libraryRootFolder"></param>
/// <param name="welcomeMess"></param>
public LoginService(UserManagerBase userManager, LibraryRootFolder libraryRootFolder,
string welcomeMess)
{
m_userManager = userManager;
m_libraryRootFolder = libraryRootFolder;
if (welcomeMess != String.Empty)
{
m_welcomeMessage = welcomeMess;
}
}
/// <summary>
/// If the user is already logged in, try to notify the region that the user they've got is dead.
/// </summary>
/// <param name="theUser"></param>
public virtual void LogOffUser(UserProfileData theUser, string message)
{
}
/// <summary>
/// Called when we receive the client's initial XMLRPC login_to_simulator request message
/// </summary>
/// <param name="request">The XMLRPC request</param>
/// <returns>The response to send</returns>
public virtual XmlRpcResponse XmlRpcLoginMethod(XmlRpcRequest request, IPEndPoint remoteClient)
{
// Temporary fix
m_loginMutex.WaitOne();
try
{
//CFK: CustomizeResponse contains sufficient strings to alleviate the need for this.
//CKF: m_log.Info("[LOGIN]: Attempting login now...");
XmlRpcResponse response = new XmlRpcResponse();
Hashtable requestData = (Hashtable)request.Params[0];
SniffLoginKey((Uri)request.Params[2], requestData);
bool GoodXML = (requestData.Contains("first") && requestData.Contains("last") &&
(requestData.Contains("passwd") || requestData.Contains("web_login_key")));
string startLocationRequest = "last";
UserProfileData userProfile;
LoginResponse logResponse = new LoginResponse();
string firstname;
string lastname;
if (GoodXML)
{
if (requestData.Contains("start"))
{
startLocationRequest = (string)requestData["start"];
}
firstname = (string)requestData["first"];
lastname = (string)requestData["last"];
m_log.InfoFormat(
"[LOGIN BEGIN]: XMLRPC Received login request message from user '{0}' '{1}'",
firstname, lastname);
string clientVersion = "Unknown";
if (requestData.Contains("version"))
{
clientVersion = (string)requestData["version"];
}
m_log.DebugFormat(
"[LOGIN]: XMLRPC Client is {0}, start location is {1}", clientVersion, startLocationRequest);
if (!TryAuthenticateXmlRpcLogin(request, firstname, lastname, out userProfile))
{
return logResponse.CreateLoginFailedResponse();
}
}
else
{
m_log.Info(
"[LOGIN END]: XMLRPC login_to_simulator login message did not contain all the required data");
return logResponse.CreateGridErrorResponse();
}
if (userProfile.GodLevel < m_minLoginLevel)
{
return logResponse.CreateLoginBlockedResponse();
}
else
{
// If we already have a session...
if (userProfile.CurrentAgent != null && userProfile.CurrentAgent.AgentOnline)
{
//TODO: The following statements can cause trouble:
// If agentOnline could not turn from true back to false normally
// because of some problem, for instance, the crashment of server or client,
// the user cannot log in any longer.
userProfile.CurrentAgent.AgentOnline = false;
m_userManager.CommitAgent(ref userProfile);
// try to tell the region that their user is dead.
LogOffUser(userProfile, " XMLRPC You were logged off because you logged in from another location");
if (m_warn_already_logged)
{
// This is behavior for for grid, reject login
m_log.InfoFormat(
"[LOGIN END]: XMLRPC Notifying user {0} {1} that they are already logged in",
firstname, lastname);
return logResponse.CreateAlreadyLoggedInResponse();
}
else
{
// This is behavior for standalone (silent logout of last hung session)
m_log.InfoFormat(
"[LOGIN]: XMLRPC User {0} {1} is already logged in, not notifying user, kicking old presence and starting new login.",
firstname, lastname);
}
}
// Otherwise...
// Create a new agent session
// XXYY we don't need this
//m_userManager.ResetAttachments(userProfile.ID);
CreateAgent(userProfile, request);
// We need to commit the agent right here, even though the userProfile info is not complete
// at this point. There is another commit further down.
// This is for the new sessionID to be stored so that the region can check it for session authentication.
// CustomiseResponse->PrepareLoginToRegion
CommitAgent(ref userProfile);
try
{
UUID agentID = userProfile.ID;
InventoryData inventData = null;
try
{
inventData = GetInventorySkeleton(agentID);
}
catch (Exception e)
{
m_log.ErrorFormat(
"[LOGIN END]: Error retrieving inventory skeleton of agent {0} - {1}",
agentID, e);
// Let's not panic
if (!AllowLoginWithoutInventory())
return logResponse.CreateLoginInventoryFailedResponse();
}
if (inventData != null)
{
ArrayList AgentInventoryArray = inventData.InventoryArray;
Hashtable InventoryRootHash = new Hashtable();
InventoryRootHash["folder_id"] = inventData.RootFolderID.ToString();
ArrayList InventoryRoot = new ArrayList();
InventoryRoot.Add(InventoryRootHash);
userProfile.RootInventoryFolderID = inventData.RootFolderID;
logResponse.InventoryRoot = InventoryRoot;
logResponse.InventorySkeleton = AgentInventoryArray;
}
// Inventory Library Section
Hashtable InventoryLibRootHash = new Hashtable();
InventoryLibRootHash["folder_id"] = "00000112-000f-0000-0000-000100bba000";
ArrayList InventoryLibRoot = new ArrayList();
InventoryLibRoot.Add(InventoryLibRootHash);
logResponse.InventoryLibRoot = InventoryLibRoot;
logResponse.InventoryLibraryOwner = GetLibraryOwner();
logResponse.InventoryLibrary = GetInventoryLibrary();
logResponse.CircuitCode = Util.RandomClass.Next();
logResponse.Lastname = userProfile.SurName;
logResponse.Firstname = userProfile.FirstName;
logResponse.AgentID = agentID;
logResponse.SessionID = userProfile.CurrentAgent.SessionID;
logResponse.SecureSessionID = userProfile.CurrentAgent.SecureSessionID;
logResponse.Message = GetMessage();
logResponse.BuddList = ConvertFriendListItem(m_userManager.GetUserFriendList(agentID));
logResponse.StartLocation = startLocationRequest;
if (CustomiseResponse(logResponse, userProfile, startLocationRequest, remoteClient))
{
userProfile.LastLogin = userProfile.CurrentAgent.LoginTime;
CommitAgent(ref userProfile);
// If we reach this point, then the login has successfully logged onto the grid
if (StatsManager.UserStats != null)
StatsManager.UserStats.AddSuccessfulLogin();
m_log.DebugFormat(
"[LOGIN END]: XMLRPC Authentication of user {0} {1} successful. Sending response to client.",
firstname, lastname);
return logResponse.ToXmlRpcResponse();
}
else
{
m_log.ErrorFormat("[LOGIN END]: XMLRPC informing user {0} {1} that login failed due to an unavailable region", firstname, lastname);
return logResponse.CreateDeadRegionResponse();
}
}
catch (Exception e)
{
m_log.Error("[LOGIN END]: XMLRPC Login failed, " + e);
m_log.Error(e.StackTrace);
}
}
m_log.Info("[LOGIN END]: XMLRPC Login failed. Sending back blank XMLRPC response");
return response;
}
finally
{
m_loginMutex.ReleaseMutex();
}
}
protected virtual bool TryAuthenticateXmlRpcLogin(
XmlRpcRequest request, string firstname, string lastname, out UserProfileData userProfile)
{
Hashtable requestData = (Hashtable)request.Params[0];
userProfile = GetTheUser(firstname, lastname);
if (userProfile == null)
{
m_log.Debug("[LOGIN END]: XMLRPC Could not find a profile for " + firstname + " " + lastname);
return false;
}
else
{
if (requestData.Contains("passwd"))
{
string passwd = (string)requestData["passwd"];
bool authenticated = AuthenticateUser(userProfile, passwd);
if (!authenticated)
m_log.DebugFormat("[LOGIN END]: XMLRPC User {0} {1} failed password authentication",
firstname, lastname);
return authenticated;
}
if (requestData.Contains("web_login_key"))
{
try
{
UUID webloginkey = new UUID((string)requestData["web_login_key"]);
bool authenticated = AuthenticateUser(userProfile, webloginkey);
if (!authenticated)
m_log.DebugFormat("[LOGIN END]: XMLRPC User {0} {1} failed web login key authentication",
firstname, lastname);
return authenticated;
}
catch (Exception e)
{
m_log.DebugFormat(
"[LOGIN END]: XMLRPC Bad web_login_key: {0} for user {1} {2}, exception {3}",
requestData["web_login_key"], firstname, lastname, e);
return false;
}
}
m_log.DebugFormat(
"[LOGIN END]: XMLRPC login request for {0} {1} contained neither a password nor a web login key",
firstname, lastname);
}
return false;
}
protected virtual bool TryAuthenticateLLSDLogin(string firstname, string lastname, string passwd, out UserProfileData userProfile)
{
bool GoodLogin = false;
userProfile = GetTheUser(firstname, lastname);
if (userProfile == null)
{
m_log.Info("[LOGIN]: LLSD Could not find a profile for " + firstname + " " + lastname);
return false;
}
GoodLogin = AuthenticateUser(userProfile, passwd);
return GoodLogin;
}
/// <summary>
/// Called when we receive the client's initial LLSD login_to_simulator request message
/// </summary>
/// <param name="request">The LLSD request</param>
/// <returns>The response to send</returns>
public OSD LLSDLoginMethod(OSD request, IPEndPoint remoteClient)
{
// Temporary fix
m_loginMutex.WaitOne();
try
{
// bool GoodLogin = false;
string startLocationRequest = "last";
UserProfileData userProfile = null;
LoginResponse logResponse = new LoginResponse();
if (request.Type == OSDType.Map)
{
OSDMap map = (OSDMap)request;
if (map.ContainsKey("first") && map.ContainsKey("last") && map.ContainsKey("passwd"))
{
string firstname = map["first"].AsString();
string lastname = map["last"].AsString();
string passwd = map["passwd"].AsString();
if (map.ContainsKey("start"))
{
m_log.Info("[LOGIN]: LLSD StartLocation Requested: " + map["start"].AsString());
startLocationRequest = map["start"].AsString();
}
m_log.Info("[LOGIN]: LLSD Login Requested for: '" + firstname + "' '" + lastname + "' / " + passwd);
if (!TryAuthenticateLLSDLogin(firstname, lastname, passwd, out userProfile))
{
return logResponse.CreateLoginFailedResponseLLSD();
}
}
else
return logResponse.CreateLoginFailedResponseLLSD();
}
else
return logResponse.CreateLoginFailedResponseLLSD();
if (userProfile.GodLevel < m_minLoginLevel)
{
return logResponse.CreateLoginBlockedResponseLLSD();
}
else
{
// If we already have a session...
if (userProfile.CurrentAgent != null && userProfile.CurrentAgent.AgentOnline)
{
userProfile.CurrentAgent.AgentOnline = false;
m_userManager.CommitAgent(ref userProfile);
// try to tell the region that their user is dead.
LogOffUser(userProfile, " LLSD You were logged off because you logged in from another location");
if (m_warn_already_logged)
{
// This is behavior for for grid, reject login
m_log.InfoFormat(
"[LOGIN END]: LLSD Notifying user {0} {1} that they are already logged in",
userProfile.FirstName, userProfile.SurName);
userProfile.CurrentAgent = null;
return logResponse.CreateAlreadyLoggedInResponseLLSD();
}
else
{
// This is behavior for standalone (silent logout of last hung session)
m_log.InfoFormat(
"[LOGIN]: LLSD User {0} {1} is already logged in, not notifying user, kicking old presence and starting new login.",
userProfile.FirstName, userProfile.SurName);
}
}
// Otherwise...
// Create a new agent session
// XXYY We don't need this
//m_userManager.ResetAttachments(userProfile.ID);
CreateAgent(userProfile, request);
// We need to commit the agent right here, even though the userProfile info is not complete
// at this point. There is another commit further down.
// This is for the new sessionID to be stored so that the region can check it for session authentication.
// CustomiseResponse->PrepareLoginToRegion
CommitAgent(ref userProfile);
try
{
UUID agentID = userProfile.ID;
//InventoryData inventData = GetInventorySkeleton(agentID);
InventoryData inventData = null;
try
{
inventData = GetInventorySkeleton(agentID);
}
catch (Exception e)
{
m_log.ErrorFormat(
"[LOGIN END]: LLSD Error retrieving inventory skeleton of agent {0}, {1} - {2}",
agentID, e.GetType(), e.Message);
return logResponse.CreateLoginFailedResponseLLSD();// .CreateLoginInventoryFailedResponseLLSD ();
}
ArrayList AgentInventoryArray = inventData.InventoryArray;
Hashtable InventoryRootHash = new Hashtable();
InventoryRootHash["folder_id"] = inventData.RootFolderID.ToString();
ArrayList InventoryRoot = new ArrayList();
InventoryRoot.Add(InventoryRootHash);
userProfile.RootInventoryFolderID = inventData.RootFolderID;
// Inventory Library Section
Hashtable InventoryLibRootHash = new Hashtable();
InventoryLibRootHash["folder_id"] = "00000112-000f-0000-0000-000100bba000";
ArrayList InventoryLibRoot = new ArrayList();
InventoryLibRoot.Add(InventoryLibRootHash);
logResponse.InventoryLibRoot = InventoryLibRoot;
logResponse.InventoryLibraryOwner = GetLibraryOwner();
logResponse.InventoryRoot = InventoryRoot;
logResponse.InventorySkeleton = AgentInventoryArray;
logResponse.InventoryLibrary = GetInventoryLibrary();
logResponse.CircuitCode = (Int32)Util.RandomClass.Next();
logResponse.Lastname = userProfile.SurName;
logResponse.Firstname = userProfile.FirstName;
logResponse.AgentID = agentID;
logResponse.SessionID = userProfile.CurrentAgent.SessionID;
logResponse.SecureSessionID = userProfile.CurrentAgent.SecureSessionID;
logResponse.Message = GetMessage();
logResponse.BuddList = ConvertFriendListItem(m_userManager.GetUserFriendList(agentID));
logResponse.StartLocation = startLocationRequest;
try
{
CustomiseResponse(logResponse, userProfile, startLocationRequest, remoteClient);
}
catch (Exception ex)
{
m_log.Info("[LOGIN]: LLSD " + ex.ToString());
return logResponse.CreateDeadRegionResponseLLSD();
}
userProfile.LastLogin = userProfile.CurrentAgent.LoginTime;
CommitAgent(ref userProfile);
// If we reach this point, then the login has successfully logged onto the grid
if (StatsManager.UserStats != null)
StatsManager.UserStats.AddSuccessfulLogin();
m_log.DebugFormat(
"[LOGIN END]: LLSD Authentication of user {0} {1} successful. Sending response to client.",
userProfile.FirstName, userProfile.SurName);
return logResponse.ToLLSDResponse();
}
catch (Exception ex)
{
m_log.Info("[LOGIN]: LLSD " + ex.ToString());
return logResponse.CreateFailedResponseLLSD();
}
}
}
finally
{
m_loginMutex.ReleaseMutex();
}
}
public Hashtable ProcessHTMLLogin(Hashtable keysvals)
{
// Matches all unspecified characters
// Currently specified,; lowercase letters, upper case letters, numbers, underline
// period, space, parens, and dash.
Regex wfcut = new Regex("[^a-zA-Z0-9_\\.\\$ \\(\\)\\-]");
Hashtable returnactions = new Hashtable();
int statuscode = 200;
string firstname = String.Empty;
string lastname = String.Empty;
string location = String.Empty;
string region = String.Empty;
string grid = String.Empty;
string channel = String.Empty;
string version = String.Empty;
string lang = String.Empty;
string password = String.Empty;
string errormessages = String.Empty;
// the client requires the HTML form field be named 'username'
// however, the data it sends when it loads the first time is 'firstname'
// another one of those little nuances.
if (keysvals.Contains("firstname"))
firstname = wfcut.Replace((string)keysvals["firstname"], String.Empty, 99999);
if (keysvals.Contains("username"))
firstname = wfcut.Replace((string)keysvals["username"], String.Empty, 99999);
if (keysvals.Contains("lastname"))
lastname = wfcut.Replace((string)keysvals["lastname"], String.Empty, 99999);
if (keysvals.Contains("location"))
location = wfcut.Replace((string)keysvals["location"], String.Empty, 99999);
if (keysvals.Contains("region"))
region = wfcut.Replace((string)keysvals["region"], String.Empty, 99999);
if (keysvals.Contains("grid"))
grid = wfcut.Replace((string)keysvals["grid"], String.Empty, 99999);
if (keysvals.Contains("channel"))
channel = wfcut.Replace((string)keysvals["channel"], String.Empty, 99999);
if (keysvals.Contains("version"))
version = wfcut.Replace((string)keysvals["version"], String.Empty, 99999);
if (keysvals.Contains("lang"))
lang = wfcut.Replace((string)keysvals["lang"], String.Empty, 99999);
if (keysvals.Contains("password"))
password = wfcut.Replace((string)keysvals["password"], String.Empty, 99999);
// load our login form.
string loginform = GetLoginForm(firstname, lastname, location, region, grid, channel, version, lang, password, errormessages);
if (keysvals.ContainsKey("show_login_form"))
{
UserProfileData user = GetTheUser(firstname, lastname);
bool goodweblogin = false;
if (user != null)
goodweblogin = AuthenticateUser(user, password);
if (goodweblogin)
{
UUID webloginkey = UUID.Random();
m_userManager.StoreWebLoginKey(user.ID, webloginkey);
//statuscode = 301;
// string redirectURL = "about:blank?redirect-http-hack=" +
// HttpUtility.UrlEncode("secondlife:///app/login?first_name=" + firstname + "&last_name=" +
// lastname +
// "&location=" + location + "&grid=Other&web_login_key=" + webloginkey.ToString());
//m_log.Info("[WEB]: R:" + redirectURL);
returnactions["int_response_code"] = statuscode;
//returnactions["str_redirect_location"] = redirectURL;
//returnactions["str_response_string"] = "<HTML><BODY>GoodLogin</BODY></HTML>";
returnactions["str_response_string"] = webloginkey.ToString();
}
else
{
errormessages = "The Username and password supplied did not match our records. Check your caps lock and try again";
loginform = GetLoginForm(firstname, lastname, location, region, grid, channel, version, lang, password, errormessages);
returnactions["int_response_code"] = statuscode;
returnactions["str_response_string"] = loginform;
}
}
else
{
returnactions["int_response_code"] = statuscode;
returnactions["str_response_string"] = loginform;
}
return returnactions;
}
public string GetLoginForm(string firstname, string lastname, string location, string region,
string grid, string channel, string version, string lang,
string password, string errormessages)
{
// inject our values in the form at the markers
string loginform = String.Empty;
string file = Path.Combine(Util.configDir(), "http_loginform.html");
if (!File.Exists(file))
{
loginform = GetDefaultLoginForm();
}
else
{
StreamReader sr = File.OpenText(file);
loginform = sr.ReadToEnd();
sr.Close();
}
loginform = loginform.Replace("[$firstname]", firstname);
loginform = loginform.Replace("[$lastname]", lastname);
loginform = loginform.Replace("[$location]", location);
loginform = loginform.Replace("[$region]", region);
loginform = loginform.Replace("[$grid]", grid);
loginform = loginform.Replace("[$channel]", channel);
loginform = loginform.Replace("[$version]", version);
loginform = loginform.Replace("[$lang]", lang);
loginform = loginform.Replace("[$password]", password);
loginform = loginform.Replace("[$errors]", errormessages);
return loginform;
}
public string GetDefaultLoginForm()
{
string responseString =
"<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">";
responseString += "<html xmlns=\"http://www.w3.org/1999/xhtml\">";
responseString += "<head>";
responseString += "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />";
responseString += "<meta http-equiv=\"cache-control\" content=\"no-cache\">";
responseString += "<meta http-equiv=\"Pragma\" content=\"no-cache\">";
responseString += "<title>OpenSim Login</title>";
responseString += "<body><br />";
responseString += "<div id=\"login_box\">";
responseString += "<form action=\"/go.cgi\" method=\"GET\" id=\"login-form\">";
responseString += "<div id=\"message\">[$errors]</div>";
responseString += "<fieldset id=\"firstname\">";
responseString += "<legend>First Name:</legend>";
responseString += "<input type=\"text\" id=\"firstname_input\" size=\"15\" maxlength=\"100\" name=\"username\" value=\"[$firstname]\" />";
responseString += "</fieldset>";
responseString += "<fieldset id=\"lastname\">";
responseString += "<legend>Last Name:</legend>";
responseString += "<input type=\"text\" size=\"15\" maxlength=\"100\" name=\"lastname\" value=\"[$lastname]\" />";
responseString += "</fieldset>";
responseString += "<fieldset id=\"password\">";
responseString += "<legend>Password:</legend>";
responseString += "<table cellspacing=\"0\" cellpadding=\"0\" border=\"0\">";
responseString += "<tr>";
responseString += "<td colspan=\"2\"><input type=\"password\" size=\"15\" maxlength=\"100\" name=\"password\" value=\"[$password]\" /></td>";
responseString += "</tr>";
responseString += "<tr>";
responseString += "<td valign=\"middle\"><input type=\"checkbox\" name=\"remember_password\" id=\"remember_password\" [$remember_password] style=\"margin-left:0px;\"/></td>";
responseString += "<td><label for=\"remember_password\">Remember password</label></td>";
responseString += "</tr>";
responseString += "</table>";
responseString += "</fieldset>";
responseString += "<input type=\"hidden\" name=\"show_login_form\" value=\"FALSE\" />";
responseString += "<input type=\"hidden\" name=\"method\" value=\"login\" />";
responseString += "<input type=\"hidden\" id=\"grid\" name=\"grid\" value=\"[$grid]\" />";
responseString += "<input type=\"hidden\" id=\"region\" name=\"region\" value=\"[$region]\" />";
responseString += "<input type=\"hidden\" id=\"location\" name=\"location\" value=\"[$location]\" />";
responseString += "<input type=\"hidden\" id=\"channel\" name=\"channel\" value=\"[$channel]\" />";
responseString += "<input type=\"hidden\" id=\"version\" name=\"version\" value=\"[$version]\" />";
responseString += "<input type=\"hidden\" id=\"lang\" name=\"lang\" value=\"[$lang]\" />";
responseString += "<div id=\"submitbtn\">";
responseString += "<input class=\"input_over\" type=\"submit\" value=\"Connect\" />";
responseString += "</div>";
responseString += "<div id=\"connecting\" style=\"visibility:hidden\"> Connecting...</div>";
responseString += "<div id=\"helplinks\"><!---";
responseString += "<a href=\"#join now link\" target=\"_blank\"></a> | ";
responseString += "<a href=\"#forgot password link\" target=\"_blank\"></a>";
responseString += "---></div>";
responseString += "<div id=\"channelinfo\"> [$channel] | [$version]=[$lang]</div>";
responseString += "</form>";
responseString += "<script language=\"JavaScript\">";
responseString += "document.getElementById('firstname_input').focus();";
responseString += "</script>";
responseString += "</div>";
responseString += "</div>";
responseString += "</body>";
responseString += "</html>";
return responseString;
}
/// <summary>
/// Saves a target agent to the database
/// </summary>
/// <param name="profile">The users profile</param>
/// <returns>Successful?</returns>
public bool CommitAgent(ref UserProfileData profile)
{
return m_userManager.CommitAgent(ref profile);
}
/// <summary>
/// Checks a user against it's password hash
/// </summary>
/// <param name="profile">The users profile</param>
/// <param name="password">The supplied password</param>
/// <returns>Authenticated?</returns>
public virtual bool AuthenticateUser(UserProfileData profile, string password)
{
bool passwordSuccess = false;
//m_log.InfoFormat("[LOGIN]: Authenticating {0} {1} ({2})", profile.FirstName, profile.SurName, profile.ID);
// Web Login method seems to also occasionally send the hashed password itself
// we do this to get our hash in a form that the server password code can consume
// when the web-login-form submits the password in the clear (supposed to be over SSL!)
if (!password.StartsWith("$1$"))
password = "$1$" + Util.Md5Hash(password);
password = password.Remove(0, 3); //remove $1$
string s = Util.Md5Hash(password + ":" + profile.PasswordSalt);
// Testing...
//m_log.Info("[LOGIN]: SubHash:" + s + " userprofile:" + profile.passwordHash);
//m_log.Info("[LOGIN]: userprofile:" + profile.passwordHash + " SubCT:" + password);
passwordSuccess = (profile.PasswordHash.Equals(s.ToString(), StringComparison.InvariantCultureIgnoreCase)
|| profile.PasswordHash.Equals(password, StringComparison.InvariantCulture));
return passwordSuccess;
}
public virtual bool AuthenticateUser(UserProfileData profile, UUID webloginkey)
{
bool passwordSuccess = false;
m_log.InfoFormat("[LOGIN]: Authenticating {0} {1} ({2})", profile.FirstName, profile.SurName, profile.ID);
// Match web login key unless it's the default weblogin key UUID.Zero
passwordSuccess = ((profile.WebLoginKey == webloginkey) && profile.WebLoginKey != UUID.Zero);
return passwordSuccess;
}
/// <summary>
///
/// </summary>
/// <param name="profile"></param>
/// <param name="request"></param>
public void CreateAgent(UserProfileData profile, XmlRpcRequest request)
{
m_userManager.CreateAgent(profile, request);
}
public void CreateAgent(UserProfileData profile, OSD request)
{
m_userManager.CreateAgent(profile, request);
}
/// <summary>
///
/// </summary>
/// <param name="firstname"></param>
/// <param name="lastname"></param>
/// <returns></returns>
public virtual UserProfileData GetTheUser(string firstname, string lastname)
{
return m_userManager.GetUserProfile(firstname, lastname);
}
/// <summary>
///
/// </summary>
/// <returns></returns>
public virtual string GetMessage()
{
return m_welcomeMessage;
}
private static LoginResponse.BuddyList ConvertFriendListItem(List<FriendListItem> LFL)
{
LoginResponse.BuddyList buddylistreturn = new LoginResponse.BuddyList();
foreach (FriendListItem fl in LFL)
{
LoginResponse.BuddyList.BuddyInfo buddyitem = new LoginResponse.BuddyList.BuddyInfo(fl.Friend);
buddyitem.BuddyID = fl.Friend;
buddyitem.BuddyRightsHave = (int)fl.FriendListOwnerPerms;
buddyitem.BuddyRightsGiven = (int)fl.FriendPerms;
buddylistreturn.AddNewBuddy(buddyitem);
}
return buddylistreturn;
}
/// <summary>
/// Converts the inventory library skeleton into the form required by the rpc request.
/// </summary>
/// <returns></returns>
protected virtual ArrayList GetInventoryLibrary()
{
Dictionary<UUID, InventoryFolderImpl> rootFolders
= m_libraryRootFolder.RequestSelfAndDescendentFolders();
ArrayList folderHashes = new ArrayList();
foreach (InventoryFolderBase folder in rootFolders.Values)
{
Hashtable TempHash = new Hashtable();
TempHash["name"] = folder.Name;
TempHash["parent_id"] = folder.ParentID.ToString();
TempHash["version"] = (Int32)folder.Version;
TempHash["type_default"] = (Int32)folder.Type;
TempHash["folder_id"] = folder.ID.ToString();
folderHashes.Add(TempHash);
}
return folderHashes;
}
/// <summary>
///
/// </summary>
/// <returns></returns>
protected virtual ArrayList GetLibraryOwner()
{
//for now create random inventory library owner
Hashtable TempHash = new Hashtable();
TempHash["agent_id"] = "11111111-1111-0000-0000-000100bba000";
ArrayList inventoryLibOwner = new ArrayList();
inventoryLibOwner.Add(TempHash);
return inventoryLibOwner;
}
public class InventoryData
{
public ArrayList InventoryArray = null;
public UUID RootFolderID = UUID.Zero;
public InventoryData(ArrayList invList, UUID rootID)
{
InventoryArray = invList;
RootFolderID = rootID;
}
}
protected void SniffLoginKey(Uri uri, Hashtable requestData)
{
string uri_str = uri.ToString();
string[] parts = uri_str.Split(new char[] { '=' });
if (parts.Length > 1)
{
string web_login_key = parts[1];
requestData.Add("web_login_key", web_login_key);
m_log.InfoFormat("[LOGIN]: Login with web_login_key {0}", web_login_key);
}
}
/// <summary>
/// Customises the login response and fills in missing values. This method also tells the login region to
/// expect a client connection.
/// </summary>
/// <param name="response">The existing response</param>
/// <param name="theUser">The user profile</param>
/// <param name="startLocationRequest">The requested start location</param>
/// <returns>true on success, false if the region was not successfully told to expect a user connection</returns>
public bool CustomiseResponse(LoginResponse response, UserProfileData theUser, string startLocationRequest, IPEndPoint client)
{
// add active gestures to login-response
AddActiveGestures(response, theUser);
// HomeLocation
RegionInfo homeInfo = null;
// use the homeRegionID if it is stored already. If not, use the regionHandle as before
UUID homeRegionId = theUser.HomeRegionID;
ulong homeRegionHandle = theUser.HomeRegion;
if (homeRegionId != UUID.Zero)
{
homeInfo = GetRegionInfo(homeRegionId);
}
else
{
homeInfo = GetRegionInfo(homeRegionHandle);
}
if (homeInfo != null)
{
response.Home =
string.Format(
"{{'region_handle':[r{0},r{1}], 'position':[r{2},r{3},r{4}], 'look_at':[r{5},r{6},r{7}]}}",
(homeInfo.RegionLocX * Constants.RegionSize),
(homeInfo.RegionLocY * Constants.RegionSize),
theUser.HomeLocation.X, theUser.HomeLocation.Y, theUser.HomeLocation.Z,
theUser.HomeLookAt.X, theUser.HomeLookAt.Y, theUser.HomeLookAt.Z);
}
else
{
m_log.InfoFormat("not found the region at {0} {1}", theUser.HomeRegionX, theUser.HomeRegionY);
// Emergency mode: Home-region isn't available, so we can't request the region info.
// Use the stored home regionHandle instead.
// NOTE: If the home-region moves, this will be wrong until the users update their user-profile again
ulong regionX = homeRegionHandle >> 32;
ulong regionY = homeRegionHandle & 0xffffffff;
response.Home =
string.Format(
"{{'region_handle':[r{0},r{1}], 'position':[r{2},r{3},r{4}], 'look_at':[r{5},r{6},r{7}]}}",
regionX, regionY,
theUser.HomeLocation.X, theUser.HomeLocation.Y, theUser.HomeLocation.Z,
theUser.HomeLookAt.X, theUser.HomeLookAt.Y, theUser.HomeLookAt.Z);
m_log.InfoFormat("[LOGIN] Home region of user {0} {1} is not available; using computed region position {2} {3}",
theUser.FirstName, theUser.SurName,
regionX, regionY);
}
// StartLocation
RegionInfo regionInfo = null;
if (startLocationRequest == "home")
{
regionInfo = homeInfo;
theUser.CurrentAgent.Position = theUser.HomeLocation;
response.LookAt = String.Format("[r{0},r{1},r{2}]", theUser.HomeLookAt.X.ToString(),
theUser.HomeLookAt.Y.ToString(), theUser.HomeLookAt.Z.ToString());
}
else if (startLocationRequest == "last")
{
UUID lastRegion = theUser.CurrentAgent.Region;
regionInfo = GetRegionInfo(lastRegion);
response.LookAt = String.Format("[r{0},r{1},r{2}]", theUser.CurrentAgent.LookAt.X.ToString(),
theUser.CurrentAgent.LookAt.Y.ToString(), theUser.CurrentAgent.LookAt.Z.ToString());
}
else
{
Regex reURI = new Regex(@"^uri:(?<region>[^&]+)&(?<x>\d+)&(?<y>\d+)&(?<z>\d+)$");
Match uriMatch = reURI.Match(startLocationRequest);
if (uriMatch == null)
{
m_log.InfoFormat("[LOGIN]: Got Custom Login URL {0}, but can't process it", startLocationRequest);
}
else
{
string region = uriMatch.Groups["region"].ToString();
regionInfo = RequestClosestRegion(region);
if (regionInfo == null)
{
m_log.InfoFormat("[LOGIN]: Got Custom Login URL {0}, can't locate region {1}", startLocationRequest, region);
}
else
{
theUser.CurrentAgent.Position = new Vector3(float.Parse(uriMatch.Groups["x"].Value),
float.Parse(uriMatch.Groups["y"].Value), float.Parse(uriMatch.Groups["z"].Value));
}
}
response.LookAt = "[r0,r1,r0]";
// can be: last, home, safe, url
response.StartLocation = "url";
}
if ((regionInfo != null) && (PrepareLoginToRegion(regionInfo, theUser, response, client)))
{
return true;
}
// Get the default region handle
ulong defaultHandle = Utils.UIntsToLong(m_defaultHomeX * Constants.RegionSize, m_defaultHomeY * Constants.RegionSize);
// If we haven't already tried the default region, reset regionInfo
if (regionInfo != null && defaultHandle != regionInfo.RegionHandle)
regionInfo = null;
if (regionInfo == null)
{
m_log.Error("[LOGIN]: Sending user to default region " + defaultHandle + " instead");
regionInfo = GetRegionInfo(defaultHandle);
}
if (regionInfo == null)
{
m_log.ErrorFormat("[LOGIN]: Sending user to any region");
regionInfo = RequestClosestRegion(String.Empty);
}
theUser.CurrentAgent.Position = new Vector3(128f, 128f, 0f);
response.StartLocation = "safe";
return PrepareLoginToRegion(regionInfo, theUser, response, client);
}
protected abstract RegionInfo RequestClosestRegion(string region);
protected abstract RegionInfo GetRegionInfo(ulong homeRegionHandle);
protected abstract RegionInfo GetRegionInfo(UUID homeRegionId);
/// <summary>
/// Prepare a login to the given region. This involves both telling the region to expect a connection
/// and appropriately customising the response to the user.
/// </summary>
/// <param name="sim"></param>
/// <param name="user"></param>
/// <param name="response"></param>
/// <param name="remoteClient"></param>
/// <returns>true if the region was successfully contacted, false otherwise</returns>
protected abstract bool PrepareLoginToRegion(
RegionInfo regionInfo, UserProfileData user, LoginResponse response, IPEndPoint client);
/// <summary>
/// Add active gestures of the user to the login response.
/// </summary>
/// <param name="response">
/// A <see cref="LoginResponse"/>
/// </param>
/// <param name="theUser">
/// A <see cref="UserProfileData"/>
/// </param>
protected void AddActiveGestures(LoginResponse response, UserProfileData theUser)
{
List<InventoryItemBase> gestures = null;
try
{
if (m_InventoryService != null)
gestures = m_InventoryService.GetActiveGestures(theUser.ID);
else
gestures = m_interInventoryService.GetActiveGestures(theUser.ID);
}
catch (Exception e)
{
m_log.Debug("[LOGIN]: Unable to retrieve active gestures from inventory server. Reason: " + e.Message);
}
//m_log.DebugFormat("[LOGIN]: AddActiveGestures, found {0}", gestures == null ? 0 : gestures.Count);
ArrayList list = new ArrayList();
if (gestures != null)
{
foreach (InventoryItemBase gesture in gestures)
{
Hashtable item = new Hashtable();
item["item_id"] = gesture.ID.ToString();
item["asset_id"] = gesture.AssetID.ToString();
list.Add(item);
}
}
response.ActiveGestures = list;
}
/// <summary>
/// Get the initial login inventory skeleton (in other words, the folder structure) for the given user.
/// </summary>
/// <param name="userID"></param>
/// <returns></returns>
/// <exception cref='System.Exception'>This will be thrown if there is a problem with the inventory service</exception>
protected InventoryData GetInventorySkeleton(UUID userID)
{
List<InventoryFolderBase> folders = null;
if (m_InventoryService != null)
{
folders = m_InventoryService.GetInventorySkeleton(userID);
}
else
{
folders = m_interInventoryService.GetInventorySkeleton(userID);
}
// If we have user auth but no inventory folders for some reason, create a new set of folders.
if (folders == null || folders.Count == 0)
{
m_log.InfoFormat(
"[LOGIN]: A root inventory folder for user {0} was not found. Requesting creation.", userID);
// Although the create user function creates a new agent inventory along with a new user profile, some
// tools are creating the user profile directly in the database without creating the inventory. At
// this time we'll accomodate them by lazily creating the user inventory now if it doesn't already
// exist.
if (m_interInventoryService != null)
{
if (!m_interInventoryService.CreateNewUserInventory(userID))
{
throw new Exception(
String.Format(
"The inventory creation request for user {0} did not succeed."
+ " Please contact your inventory service provider for more information.",
userID));
}
}
else if ((m_InventoryService != null) && !m_InventoryService.CreateUserInventory(userID))
{
throw new Exception(
String.Format(
"The inventory creation request for user {0} did not succeed."
+ " Please contact your inventory service provider for more information.",
userID));
}
m_log.InfoFormat("[LOGIN]: A new inventory skeleton was successfully created for user {0}", userID);
if (m_InventoryService != null)
folders = m_InventoryService.GetInventorySkeleton(userID);
else
folders = m_interInventoryService.GetInventorySkeleton(userID);
if (folders == null || folders.Count == 0)
{
throw new Exception(
String.Format(
"A root inventory folder for user {0} could not be retrieved from the inventory service",
userID));
}
}
UUID rootID = UUID.Zero;
ArrayList AgentInventoryArray = new ArrayList();
Hashtable TempHash;
foreach (InventoryFolderBase InvFolder in folders)
{
if (InvFolder.ParentID == UUID.Zero)
{
rootID = InvFolder.ID;
}
TempHash = new Hashtable();
TempHash["name"] = InvFolder.Name;
TempHash["parent_id"] = InvFolder.ParentID.ToString();
TempHash["version"] = (Int32)InvFolder.Version;
TempHash["type_default"] = (Int32)InvFolder.Type;
TempHash["folder_id"] = InvFolder.ID.ToString();
AgentInventoryArray.Add(TempHash);
}
return new InventoryData(AgentInventoryArray, rootID);
}
protected virtual bool AllowLoginWithoutInventory()
{
return false;
}
public XmlRpcResponse XmlRPCCheckAuthSession(XmlRpcRequest request, IPEndPoint remoteClient)
{
XmlRpcResponse response = new XmlRpcResponse();
Hashtable requestData = (Hashtable)request.Params[0];
string authed = "FALSE";
if (requestData.Contains("avatar_uuid") && requestData.Contains("session_id"))
{
UUID guess_aid;
UUID guess_sid;
UUID.TryParse((string)requestData["avatar_uuid"], out guess_aid);
if (guess_aid == UUID.Zero)
{
return Util.CreateUnknownUserErrorResponse();
}
UUID.TryParse((string)requestData["session_id"], out guess_sid);
if (guess_sid == UUID.Zero)
{
return Util.CreateUnknownUserErrorResponse();
}
if (m_userManager.VerifySession(guess_aid, guess_sid))
{
authed = "TRUE";
m_log.InfoFormat("[UserManager]: CheckAuthSession TRUE for user {0}", guess_aid);
}
else
{
m_log.InfoFormat("[UserManager]: CheckAuthSession FALSE");
return Util.CreateUnknownUserErrorResponse();
}
}
Hashtable responseData = new Hashtable();
responseData["auth_session"] = authed;
response.Value = responseData;
return response;
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System;
using System.Collections.Specialized;
using System.Collections.Generic;
using System.Management.Automation;
using System.Management.Automation.Internal;
namespace Microsoft.PowerShell.Commands.Internal.Format
{
/// <summary>
/// OutCommand base implementation
/// it manages the formatting protocol and it writes to a generic
/// screen host.
/// </summary>
internal class OutCommandInner : ImplementationCommandBase
{
#region tracer
[TraceSource("format_out_OutCommandInner", "OutCommandInner")]
internal static PSTraceSource tracer = PSTraceSource.GetTracer("format_out_OutCommandInner", "OutCommandInner");
#endregion tracer
internal override void BeginProcessing()
{
base.BeginProcessing();
_formatObjectDeserializer = new FormatObjectDeserializer(this.TerminatingErrorContext);
// hook up the event handlers for the context manager object
_ctxManager.contextCreation = new FormatMessagesContextManager.FormatContextCreationCallback(this.CreateOutputContext);
_ctxManager.fs = new FormatMessagesContextManager.FormatStartCallback(this.ProcessFormatStart);
_ctxManager.fe = new FormatMessagesContextManager.FormatEndCallback(this.ProcessFormatEnd);
_ctxManager.gs = new FormatMessagesContextManager.GroupStartCallback(this.ProcessGroupStart);
_ctxManager.ge = new FormatMessagesContextManager.GroupEndCallback(this.ProcessGroupEnd);
_ctxManager.payload = new FormatMessagesContextManager.PayloadCallback(this.ProcessPayload);
}
/// <summary>
/// Execution entry point override
/// we assume that a LineOutput interface instance already has been acquired
///
/// IMPORTANT: it assumes the presence of a pre-processing formatting command.
/// </summary>
internal override void ProcessRecord()
{
PSObject so = this.ReadObject();
if (so == null || so == AutomationNull.Value)
return;
// try to process the object
if (ProcessObject(so))
return;
// send to the formatter for preprocessing
Array results = ApplyFormatting(so);
if (results != null)
{
foreach (object r in results)
{
PSObject obj = PSObjectHelper.AsPSObject(r);
obj.IsHelpObject = so.IsHelpObject;
ProcessObject(obj);
}
}
}
internal override void EndProcessing()
{
base.EndProcessing();
if (_command != null)
{
// shut down the command processor, if we ever used it
Array results = _command.ShutDown();
if (results != null)
{
foreach (object o in results)
{
ProcessObject(PSObjectHelper.AsPSObject(o));
}
}
}
if (this.LineOutput.RequiresBuffering)
{
// we need to notify the interface implementor that
// we are about to do the playback
LineOutput.DoPlayBackCall playBackCall = new LineOutput.DoPlayBackCall(this.DrainCache);
this.LineOutput.ExecuteBufferPlayBack(playBackCall);
}
else
{
// we drain the cache ourselves
DrainCache();
}
}
private void DrainCache()
{
if (_cache != null)
{
// drain the cache, since we are shutting down
List<PacketInfoData> unprocessedObjects = _cache.Drain();
if (unprocessedObjects != null)
{
foreach (object obj in unprocessedObjects)
{
_ctxManager.Process(obj);
}
}
}
}
private bool ProcessObject(PSObject so)
{
object o = _formatObjectDeserializer.Deserialize(so);
// Console.WriteLine("OutCommandInner.Execute() retrieved object {0}, of type {1}", o.ToString(), o.GetType());
if (NeedsPreprocessing(o))
{
return false;
}
// instantiate the cache if not done yet
if (_cache == null)
{
_cache = new FormattedObjectsCache(this.LineOutput.RequiresBuffering);
}
// no need for formatting, just process the object
FormatStartData formatStart = o as FormatStartData;
if (formatStart != null)
{
// get autosize flag from object
// turn on group caching
if (formatStart.autosizeInfo != null)
{
FormattedObjectsCache.ProcessCachedGroupNotification callBack = new FormattedObjectsCache.ProcessCachedGroupNotification(ProcessCachedGroup);
_cache.EnableGroupCaching(callBack, formatStart.autosizeInfo.objectCount);
}
else
{
// If the format info doesn't define column widths, then auto-size based on the first ten elements
TableHeaderInfo headerInfo = formatStart.shapeInfo as TableHeaderInfo;
if ((headerInfo != null) &&
(headerInfo.tableColumnInfoList.Count > 0) &&
(headerInfo.tableColumnInfoList[0].width == 0))
{
FormattedObjectsCache.ProcessCachedGroupNotification callBack = new FormattedObjectsCache.ProcessCachedGroupNotification(ProcessCachedGroup);
_cache.EnableGroupCaching(callBack, TimeSpan.FromMilliseconds(300));
}
}
}
// Console.WriteLine("OutCommandInner.Execute() calling ctxManager.Process({0})",o.ToString());
List<PacketInfoData> info = _cache.Add((PacketInfoData)o);
if (info != null)
{
for (int k = 0; k < info.Count; k++)
_ctxManager.Process(info[k]);
}
return true;
}
/// <summary>
/// Helper to return what shape we have to use to format the output.
/// </summary>
private FormatShape ActiveFormattingShape
{
get
{
// we assume that the format context
// contains the information
FormatShape shape = FormatShape.Table; // default
FormatOutputContext foc = this.FormatContext;
if (foc == null || foc.Data.shapeInfo == null)
return shape;
if (foc.Data.shapeInfo is TableHeaderInfo)
return FormatShape.Table;
if (foc.Data.shapeInfo is ListViewHeaderInfo)
return FormatShape.List;
if (foc.Data.shapeInfo is WideViewHeaderInfo)
return FormatShape.Wide;
if (foc.Data.shapeInfo is ComplexViewHeaderInfo)
return FormatShape.Complex;
return shape;
}
}
protected override void InternalDispose()
{
base.InternalDispose();
if (_command != null)
{
_command.Dispose();
_command = null;
}
}
/// <summary>
/// Enum describing the state for the output finite state machine.
/// </summary>
private enum FormattingState
{
/// <summary>
/// We are in the clear state: no formatting in process.
/// </summary>
Reset,
/// <summary>
/// We received a Format Start message, but we are not inside a group.
/// </summary>
Formatting,
/// <summary>
/// We are inside a group because we received a Group Start.
/// </summary>
InsideGroup
}
/// <summary>
/// Toggle to signal if we are in a formatting sequence.
/// </summary>
private FormattingState _currentFormattingState = FormattingState.Reset;
/// <summary>
/// Instance of a command wrapper to execute the
/// default formatter when needed.
/// </summary>
private CommandWrapper _command;
/// <summary>
/// Enumeration to drive the preprocessing stage.
/// </summary>
private enum PreprocessingState { raw, processed, error }
private const int DefaultConsoleWidth = 120;
private const int DefaultConsoleHeight = int.MaxValue;
internal const int StackAllocThreshold = 120;
/// <summary>
/// Test if an object coming from the pipeline needs to be
/// preprocessed by the default formatter.
/// </summary>
/// <param name="o">Object to examine for formatting.</param>
/// <returns>Whether the object needs to be shunted to preprocessing.</returns>
private bool NeedsPreprocessing(object o)
{
FormatEntryData fed = o as FormatEntryData;
if (fed != null)
{
// we got an already pre-processed object
if (!fed.outOfBand)
{
// we allow out of band data in any state
ValidateCurrentFormattingState(FormattingState.InsideGroup, o);
}
return false;
}
else if (o is FormatStartData)
{
// when encountering FormatStartDate out of sequence,
// pretend that the previous formatting directives were properly closed
if (_currentFormattingState == FormattingState.InsideGroup)
{
this.EndProcessing();
this.BeginProcessing();
}
// we got a Fs message, we enter a sequence
ValidateCurrentFormattingState(FormattingState.Reset, o);
_currentFormattingState = FormattingState.Formatting;
return false;
}
else if (o is FormatEndData)
{
// we got a Fe message, we exit a sequence
ValidateCurrentFormattingState(FormattingState.Formatting, o);
_currentFormattingState = FormattingState.Reset;
return false;
}
else if (o is GroupStartData)
{
ValidateCurrentFormattingState(FormattingState.Formatting, o);
_currentFormattingState = FormattingState.InsideGroup;
return false;
}
else if (o is GroupEndData)
{
ValidateCurrentFormattingState(FormattingState.InsideGroup, o);
_currentFormattingState = FormattingState.Formatting;
return false;
}
// this is a raw object
return true;
}
private void ValidateCurrentFormattingState(FormattingState expectedFormattingState, object obj)
{
// check if we are in the expected formatting state
if (_currentFormattingState != expectedFormattingState)
{
// we are not in the expected state, some message is out of sequence,
// need to abort the command
string violatingCommand = "format-*";
StartData sdObj = obj as StartData;
if (sdObj != null)
{
if (sdObj.shapeInfo is WideViewHeaderInfo)
{
violatingCommand = "format-wide";
}
else if (sdObj.shapeInfo is TableHeaderInfo)
{
violatingCommand = "format-table";
}
else if (sdObj.shapeInfo is ListViewHeaderInfo)
{
violatingCommand = "format-list";
}
else if (sdObj.shapeInfo is ComplexViewHeaderInfo)
{
violatingCommand = "format-complex";
}
}
string msg = StringUtil.Format(FormatAndOut_out_xxx.OutLineOutput_OutOfSequencePacket,
obj.GetType().FullName, violatingCommand);
ErrorRecord errorRecord = new ErrorRecord(
new InvalidOperationException(),
"ConsoleLineOutputOutOfSequencePacket",
ErrorCategory.InvalidData,
null);
errorRecord.ErrorDetails = new ErrorDetails(msg);
this.TerminatingErrorContext.ThrowTerminatingError(errorRecord);
}
}
/// <summary>
/// Shunt object to the formatting pipeline for preprocessing.
/// </summary>
/// <param name="o">Object to be preprocessed.</param>
/// <returns>Array of objects returned by the preprocessing step.</returns>
private Array ApplyFormatting(object o)
{
if (_command == null)
{
_command = new CommandWrapper();
_command.Initialize(this.OuterCmdlet().Context, "format-default", typeof(FormatDefaultCommand));
}
return _command.Process(o);
}
/// <summary>
/// Class factory for output context.
/// </summary>
/// <param name="parentContext">Parent context in the stack.</param>
/// <param name="formatInfoData">Fromat info data received from the pipeline.</param>
/// <returns></returns>
private FormatMessagesContextManager.OutputContext CreateOutputContext(
FormatMessagesContextManager.OutputContext parentContext,
FormatInfoData formatInfoData)
{
FormatStartData formatStartData = formatInfoData as FormatStartData;
// initialize the format context
if (formatStartData != null)
{
FormatOutputContext foc = new FormatOutputContext(parentContext, formatStartData);
return foc;
}
GroupStartData gsd = formatInfoData as GroupStartData;
// we are starting a group, initialize the group context
if (gsd != null)
{
GroupOutputContext goc = null;
switch (ActiveFormattingShape)
{
case FormatShape.Table:
{
goc = new TableOutputContext(this, parentContext, gsd);
break;
}
case FormatShape.List:
{
goc = new ListOutputContext(this, parentContext, gsd);
break;
}
case FormatShape.Wide:
{
goc = new WideOutputContext(this, parentContext, gsd);
break;
}
case FormatShape.Complex:
{
goc = new ComplexOutputContext(this, parentContext, gsd);
break;
}
default:
{
Diagnostics.Assert(false, "Invalid shape. This should never happen");
}
break;
}
goc.Initialize();
return goc;
}
return null;
}
/// <summary>
/// Callback for Fs processing.
/// </summary>
/// <param name="c">The context containing the Fs entry.</param>
private void ProcessFormatStart(FormatMessagesContextManager.OutputContext c)
{
// we just add an empty line to the display
this.LineOutput.WriteLine(string.Empty);
}
/// <summary>
/// Callback for Fe processing.
/// </summary>
/// <param name="fe">Fe notification message.</param>
/// <param name="c">Current context, with Fs in it.</param>
private void ProcessFormatEnd(FormatEndData fe, FormatMessagesContextManager.OutputContext c)
{
// Console.WriteLine("ProcessFormatEnd");
// we just add an empty line to the display
this.LineOutput.WriteLine(string.Empty);
}
/// <summary>
/// Callback for Gs processing.
/// </summary>
/// <param name="c">The context containing the Gs entry.</param>
private void ProcessGroupStart(FormatMessagesContextManager.OutputContext c)
{
// Console.WriteLine("ProcessGroupStart");
GroupOutputContext goc = (GroupOutputContext)c;
if (goc.Data.groupingEntry != null)
{
_lo.WriteLine(string.Empty);
ComplexWriter writer = new ComplexWriter();
writer.Initialize(_lo, _lo.ColumnNumber);
writer.WriteObject(goc.Data.groupingEntry.formatValueList);
}
goc.GroupStart();
}
/// <summary>
/// Callback for Ge processing.
/// </summary>
/// <param name="ge">Ge notification message.</param>
/// <param name="c">Current context, with Gs in it.</param>
private void ProcessGroupEnd(GroupEndData ge, FormatMessagesContextManager.OutputContext c)
{
// Console.WriteLine("ProcessGroupEnd");
GroupOutputContext goc = (GroupOutputContext)c;
goc.GroupEnd();
}
/// <summary>
/// Process the current payload object.
/// </summary>
/// <param name="fed">FormatEntryData to process.</param>
/// <param name="c">Currently active context.</param>
private void ProcessPayload(FormatEntryData fed, FormatMessagesContextManager.OutputContext c)
{
// we assume FormatEntryData as a standard wrapper
if (fed == null)
{
PSTraceSource.NewArgumentNullException("fed");
}
if (fed.formatEntryInfo == null)
{
PSTraceSource.NewArgumentNullException("fed.formatEntryInfo");
}
WriteStreamType oldWSState = _lo.WriteStream;
try
{
_lo.WriteStream = fed.writeStream;
if (c == null)
{
ProcessOutOfBandPayload(fed);
}
else
{
GroupOutputContext goc = (GroupOutputContext)c;
goc.ProcessPayload(fed);
}
}
finally
{
_lo.WriteStream = oldWSState;
}
}
private void ProcessOutOfBandPayload(FormatEntryData fed)
{
// try if it is raw text
RawTextFormatEntry rte = fed.formatEntryInfo as RawTextFormatEntry;
if (rte != null)
{
if (fed.isHelpObject)
{
ComplexWriter complexWriter = new ComplexWriter();
complexWriter.Initialize(_lo, _lo.ColumnNumber);
complexWriter.WriteString(rte.text);
}
else
{
_lo.WriteLine(rte.text);
}
return;
}
// try if it is a complex entry
ComplexViewEntry cve = fed.formatEntryInfo as ComplexViewEntry;
if (cve != null && cve.formatValueList != null)
{
ComplexWriter complexWriter = new ComplexWriter();
complexWriter.Initialize(_lo, int.MaxValue);
complexWriter.WriteObject(cve.formatValueList);
return;
}
// try if it is a list view
ListViewEntry lve = fed.formatEntryInfo as ListViewEntry;
if (lve != null && lve.listViewFieldList != null)
{
ListWriter listWriter = new ListWriter();
_lo.WriteLine(string.Empty);
string[] properties = ListOutputContext.GetProperties(lve);
listWriter.Initialize(properties, _lo.ColumnNumber, _lo.DisplayCells);
string[] values = ListOutputContext.GetValues(lve);
listWriter.WriteProperties(values, _lo);
_lo.WriteLine(string.Empty);
return;
}
}
/// <summary>
/// The screen host associated with this outputter.
/// </summary>
private LineOutput _lo = null;
internal LineOutput LineOutput
{
set { _lo = value; }
get { return _lo; }
}
private ShapeInfo ShapeInfoOnFormatContext
{
get
{
FormatOutputContext foc = this.FormatContext;
if (foc == null)
return null;
return foc.Data.shapeInfo;
}
}
/// <summary>
/// Retrieve the active FormatOutputContext on the stack
/// by walking up to the top of the stack.
/// </summary>
private FormatOutputContext FormatContext
{
get
{
for (FormatMessagesContextManager.OutputContext oc = _ctxManager.ActiveOutputContext; oc != null; oc = oc.ParentContext)
{
FormatOutputContext foc = oc as FormatOutputContext;
if (foc != null)
return foc;
}
return null;
}
}
/// <summary>
/// Context manager instance to guide the message traversal.
/// </summary>
private FormatMessagesContextManager _ctxManager = new FormatMessagesContextManager();
private FormattedObjectsCache _cache = null;
/// <summary>
/// Handler for processing the caching notification and responsible for
/// setting the value of the formatting hint.
/// </summary>
/// <param name="formatStartData"></param>
/// <param name="objects"></param>
private void ProcessCachedGroup(FormatStartData formatStartData, List<PacketInfoData> objects)
{
_formattingHint = null;
TableHeaderInfo thi = formatStartData.shapeInfo as TableHeaderInfo;
if (thi != null)
{
ProcessCachedGroupOnTable(thi, objects);
return;
}
WideViewHeaderInfo wvhi = formatStartData.shapeInfo as WideViewHeaderInfo;
if (wvhi != null)
{
ProcessCachedGroupOnWide(wvhi, objects);
return;
}
}
private void ProcessCachedGroupOnTable(TableHeaderInfo thi, List<PacketInfoData> objects)
{
if (thi.tableColumnInfoList.Count == 0)
return;
int[] widths = new int[thi.tableColumnInfoList.Count];
for (int k = 0; k < thi.tableColumnInfoList.Count; k++)
{
string label = thi.tableColumnInfoList[k].label;
if (string.IsNullOrEmpty(label))
label = thi.tableColumnInfoList[k].propertyName;
if (string.IsNullOrEmpty(label))
widths[k] = 0;
else
widths[k] = _lo.DisplayCells.Length(label);
}
int cellCount; // scratch variable
foreach (PacketInfoData o in objects)
{
if (o is FormatEntryData fed)
{
TableRowEntry tre = fed.formatEntryInfo as TableRowEntry;
int kk = 0;
foreach (FormatPropertyField fpf in tre.formatPropertyFieldList)
{
cellCount = _lo.DisplayCells.Length(fpf.propertyValue);
if (widths[kk] < cellCount)
widths[kk] = cellCount;
kk++;
}
}
}
TableFormattingHint hint = new TableFormattingHint();
hint.columnWidths = widths;
_formattingHint = hint;
}
private void ProcessCachedGroupOnWide(WideViewHeaderInfo wvhi, List<PacketInfoData> objects)
{
if (wvhi.columns != 0)
{
// columns forced on the client
return;
}
int maxLen = 0;
int cellCount; // scratch variable
foreach (PacketInfoData o in objects)
{
if (o is FormatEntryData fed)
{
WideViewEntry wve = fed.formatEntryInfo as WideViewEntry;
FormatPropertyField fpf = wve.formatPropertyField as FormatPropertyField;
if (!string.IsNullOrEmpty(fpf.propertyValue))
{
cellCount = _lo.DisplayCells.Length(fpf.propertyValue);
if (cellCount > maxLen)
maxLen = cellCount;
}
}
}
WideFormattingHint hint = new WideFormattingHint();
hint.maxWidth = maxLen;
_formattingHint = hint;
}
/// <summary>
/// Tables and Wides need to use spaces for padding to maintain table look even if console window is resized.
/// For all other output, we use int.MaxValue if the user didn't explicitly specify a width.
/// If we detect that int.MaxValue is used, first we try to get the current console window width.
/// However, if we can't read that (for example, implicit remoting has no console window), we default
/// to something reasonable: 120 columns.
/// </summary>
private static int GetConsoleWindowWidth(int columnNumber)
{
if (InternalTestHooks.SetConsoleWidthToZero)
{
return DefaultConsoleWidth;
}
if (columnNumber == int.MaxValue)
{
try
{
// if Console width is set to 0, the default width is returned so that the output string is not null.
// This can happen in environments where TERM is not set.
return (Console.WindowWidth != 0) ? Console.WindowWidth : DefaultConsoleWidth;
}
catch
{
return DefaultConsoleWidth;
}
}
return columnNumber;
}
/// <summary>
/// Return the console height.null If not available (like when remoting), treat as Int.MaxValue.
/// </summary>
private static int GetConsoleWindowHeight(int rowNumber)
{
if (InternalTestHooks.SetConsoleHeightToZero)
{
return DefaultConsoleHeight;
}
if (rowNumber <= 0)
{
try
{
// if Console height is set to 0, the default height is returned.
// This can happen in environments where TERM is not set.
return (Console.WindowHeight > 0) ? Console.WindowHeight : DefaultConsoleHeight;
}
catch
{
return DefaultConsoleHeight;
}
}
return rowNumber;
}
/// <summary>
/// Base class for all the formatting hints.
/// </summary>
private abstract class FormattingHint
{
}
/// <summary>
/// Hint for format-table.
/// </summary>
private sealed class TableFormattingHint : FormattingHint
{
internal int[] columnWidths = null;
}
/// <summary>
/// Hint for format-wide.
/// </summary>
private sealed class WideFormattingHint : FormattingHint
{
internal int maxWidth = 0;
}
/// <summary>
/// Variable holding the autosize hint (set by the caching code and reset by the hint consumer.
/// </summary>
private FormattingHint _formattingHint = null;
/// <summary>
/// Helper for consuming the formatting hint.
/// </summary>
/// <returns></returns>
private FormattingHint RetrieveFormattingHint()
{
FormattingHint fh = _formattingHint;
_formattingHint = null;
return fh;
}
private FormatObjectDeserializer _formatObjectDeserializer;
/// <summary>
/// Context for the outer scope of the format sequence.
/// </summary>
private class FormatOutputContext : FormatMessagesContextManager.OutputContext
{
/// <summary>
/// Construct a context to push on the stack.
/// </summary>
/// <param name="parentContext">Parent context in the stack.</param>
/// <param name="formatData">Format data to put in the context.</param>
internal FormatOutputContext(FormatMessagesContextManager.OutputContext parentContext, FormatStartData formatData)
: base(parentContext)
{
Data = formatData;
}
/// <summary>
/// Retrieve the format data in the context.
/// </summary>
internal FormatStartData Data { get; } = null;
}
/// <summary>
/// Context for the currently active group.
/// </summary>
private abstract class GroupOutputContext : FormatMessagesContextManager.OutputContext
{
/// <summary>
/// Construct a context to push on the stack.
/// </summary>
internal GroupOutputContext(OutCommandInner cmd,
FormatMessagesContextManager.OutputContext parentContext,
GroupStartData formatData)
: base(parentContext)
{
InnerCommand = cmd;
Data = formatData;
}
/// <summary>
/// Called at creation time, overrides will initialize here, e.g.
/// column widths, etc.
/// </summary>
internal virtual void Initialize() { }
/// <summary>
/// Called when a group of data is started, overridden will do
/// things such as headers, etc...
/// </summary>
internal virtual void GroupStart() { }
/// <summary>
/// Called when the end of a group is reached, overrides will do
/// things such as group footers.
/// </summary>
internal virtual void GroupEnd() { }
/// <summary>
/// Called when there is an entry to process, overrides will do
/// things such as writing a row in a table.
/// </summary>
/// <param name="fed">FormatEntryData to process.</param>
internal virtual void ProcessPayload(FormatEntryData fed) { }
/// <summary>
/// Retrieve the format data in the context.
/// </summary>
internal GroupStartData Data { get; } = null;
protected OutCommandInner InnerCommand { get; }
}
private class TableOutputContextBase : GroupOutputContext
{
/// <summary>
/// Construct a context to push on the stack.
/// </summary>
/// <param name="cmd">Reference to the OutCommandInner instance who owns this instance.</param>
/// <param name="parentContext">Parent context in the stack.</param>
/// <param name="formatData">Format data to put in the context.</param>
internal TableOutputContextBase(OutCommandInner cmd,
FormatMessagesContextManager.OutputContext parentContext,
GroupStartData formatData)
: base(cmd, parentContext, formatData)
{
}
/// <summary>
/// Get the table writer for this context.
/// </summary>
protected TableWriter Writer { get { return _tableWriter; } }
/// <summary>
/// Helper class to properly write a table using text output.
/// </summary>
private TableWriter _tableWriter = new TableWriter();
}
private sealed class TableOutputContext : TableOutputContextBase
{
private int _rowCount = 0;
private int _consoleHeight = -1;
private int _consoleWidth = -1;
private const int WhitespaceAndPagerLineCount = 2;
private bool _repeatHeader = false;
/// <summary>
/// Construct a context to push on the stack.
/// </summary>
/// <param name="cmd">Reference to the OutCommandInner instance who owns this instance.</param>
/// <param name="parentContext">Parent context in the stack.</param>
/// <param name="formatData">Format data to put in the context.</param>
internal TableOutputContext(OutCommandInner cmd,
FormatMessagesContextManager.OutputContext parentContext,
GroupStartData formatData)
: base(cmd, parentContext, formatData)
{
if (parentContext is FormatOutputContext foc)
{
if (foc.Data.shapeInfo is TableHeaderInfo thi)
{
_repeatHeader = thi.repeatHeader;
}
}
}
/// <summary>
/// Initialize column widths.
/// </summary>
internal override void Initialize()
{
TableFormattingHint tableHint = this.InnerCommand.RetrieveFormattingHint() as TableFormattingHint;
int[] columnWidthsHint = null;
// We expect that console width is less then 120.
if (tableHint != null)
{
columnWidthsHint = tableHint.columnWidths;
}
_consoleHeight = GetConsoleWindowHeight(this.InnerCommand._lo.RowNumber);
_consoleWidth = GetConsoleWindowWidth(this.InnerCommand._lo.ColumnNumber);
int columns = this.CurrentTableHeaderInfo.tableColumnInfoList.Count;
if (columns == 0)
{
return;
}
// create arrays for widths and alignment
Span<int> columnWidths = columns <= StackAllocThreshold ? stackalloc int[columns] : new int[columns];
Span<int> alignment = columns <= StackAllocThreshold ? stackalloc int[columns] : new int[columns];
int k = 0;
foreach (TableColumnInfo tci in this.CurrentTableHeaderInfo.tableColumnInfoList)
{
columnWidths[k] = (columnWidthsHint != null) ? columnWidthsHint[k] : tci.width;
alignment[k] = tci.alignment;
k++;
}
this.Writer.Initialize(0, _consoleWidth, columnWidths, alignment, this.CurrentTableHeaderInfo.hideHeader);
}
/// <summary>
/// Write the headers.
/// </summary>
internal override void GroupStart()
{
int columns = this.CurrentTableHeaderInfo.tableColumnInfoList.Count;
if (columns == 0)
{
return;
}
string[] properties = new string[columns];
int k = 0;
foreach (TableColumnInfo tci in this.CurrentTableHeaderInfo.tableColumnInfoList)
{
properties[k++] = tci.label ?? tci.propertyName;
}
_rowCount += this.Writer.GenerateHeader(properties, this.InnerCommand._lo);
}
/// <summary>
/// Write a row into the table.
/// </summary>
/// <param name="fed">FormatEntryData to process.</param>
internal override void ProcessPayload(FormatEntryData fed)
{
int headerColumns = this.CurrentTableHeaderInfo.tableColumnInfoList.Count;
if (headerColumns == 0)
{
return;
}
if (_repeatHeader && _rowCount >= _consoleHeight - WhitespaceAndPagerLineCount)
{
this.InnerCommand._lo.WriteLine(string.Empty);
_rowCount = this.Writer.GenerateHeader(null, this.InnerCommand._lo);
}
TableRowEntry tre = fed.formatEntryInfo as TableRowEntry;
// need to make sure we have matching counts: the header count will have to prevail
string[] values = new string[headerColumns];
Span<int> alignment = headerColumns <= StackAllocThreshold ? stackalloc int[headerColumns] : new int[headerColumns];
int fieldCount = tre.formatPropertyFieldList.Count;
for (int k = 0; k < headerColumns; k++)
{
if (k < fieldCount)
{
values[k] = tre.formatPropertyFieldList[k].propertyValue;
alignment[k] = tre.formatPropertyFieldList[k].alignment;
}
else
{
values[k] = string.Empty;
alignment[k] = TextAlignment.Left; // hard coded default
}
}
this.Writer.GenerateRow(values, this.InnerCommand._lo, tre.multiLine, alignment, InnerCommand._lo.DisplayCells, generatedRows: null);
_rowCount++;
}
private TableHeaderInfo CurrentTableHeaderInfo
{
get
{
return (TableHeaderInfo)this.InnerCommand.ShapeInfoOnFormatContext;
}
}
}
private sealed class ListOutputContext : GroupOutputContext
{
/// <summary>
/// Construct a context to push on the stack.
/// </summary>
/// <param name="cmd">Reference to the OutCommandInner instance who owns this instance.</param>
/// <param name="parentContext">Parent context in the stack.</param>
/// <param name="formatData">Format data to put in the context.</param>
internal ListOutputContext(OutCommandInner cmd,
FormatMessagesContextManager.OutputContext parentContext,
GroupStartData formatData)
: base(cmd, parentContext, formatData)
{
}
/// <summary>
/// Initialize column widths.
/// </summary>
internal override void Initialize()
{
}
private void InternalInitialize(ListViewEntry lve)
{
_properties = GetProperties(lve);
_listWriter.Initialize(_properties, this.InnerCommand._lo.ColumnNumber, InnerCommand._lo.DisplayCells);
}
internal static string[] GetProperties(ListViewEntry lve)
{
StringCollection props = new StringCollection();
foreach (ListViewField lvf in lve.listViewFieldList)
{
props.Add(lvf.label ?? lvf.propertyName);
}
if (props.Count == 0)
return null;
string[] retVal = new string[props.Count];
props.CopyTo(retVal, 0);
return retVal;
}
internal static string[] GetValues(ListViewEntry lve)
{
StringCollection vals = new StringCollection();
foreach (ListViewField lvf in lve.listViewFieldList)
{
vals.Add(lvf.formatPropertyField.propertyValue);
}
if (vals.Count == 0)
return null;
string[] retVal = new string[vals.Count];
vals.CopyTo(retVal, 0);
return retVal;
}
/// <summary>
/// Write the headers.
/// </summary>
internal override void GroupStart()
{
}
/// <summary>
/// Write a row into the list.
/// </summary>
/// <param name="fed">FormatEntryData to process.</param>
internal override void ProcessPayload(FormatEntryData fed)
{
ListViewEntry lve = fed.formatEntryInfo as ListViewEntry;
InternalInitialize(lve);
string[] values = GetValues(lve);
_listWriter.WriteProperties(values, this.InnerCommand._lo);
this.InnerCommand._lo.WriteLine(string.Empty);
}
/// <summary>
/// Property list currently active.
/// </summary>
private string[] _properties = null;
/// <summary>
/// Writer to do the actual formatting.
/// </summary>
private ListWriter _listWriter = new ListWriter();
}
private sealed class WideOutputContext : TableOutputContextBase
{
/// <summary>
/// Construct a context to push on the stack.
/// </summary>
/// <param name="cmd">Reference to the OutCommandInner instance who owns this instance.</param>
/// <param name="parentContext">Parent context in the stack.</param>
/// <param name="formatData">Format data to put in the context.</param>
internal WideOutputContext(OutCommandInner cmd,
FormatMessagesContextManager.OutputContext parentContext,
GroupStartData formatData)
: base(cmd, parentContext, formatData)
{
}
private StringValuesBuffer _buffer = null;
/// <summary>
/// Initialize column widths.
/// </summary>
internal override void Initialize()
{
// set the hard wider default, to be used if no other info is available
int itemsPerRow = 2;
// get the header info and the view hint
WideFormattingHint hint = this.InnerCommand.RetrieveFormattingHint() as WideFormattingHint;
int columnsOnTheScreen = GetConsoleWindowWidth(this.InnerCommand._lo.ColumnNumber);
// give a preference to the hint, if there
if (hint != null && hint.maxWidth > 0)
{
itemsPerRow = TableWriter.ComputeWideViewBestItemsPerRowFit(hint.maxWidth, columnsOnTheScreen);
}
else if (this.CurrentWideHeaderInfo.columns > 0)
{
itemsPerRow = this.CurrentWideHeaderInfo.columns;
}
// create a buffer object to hold partial rows
_buffer = new StringValuesBuffer(itemsPerRow);
// initialize the writer
Span<int> columnWidths = itemsPerRow <= StackAllocThreshold ? stackalloc int[itemsPerRow] : new int[itemsPerRow];
Span<int> alignment = itemsPerRow <= StackAllocThreshold ? stackalloc int[itemsPerRow] : new int[itemsPerRow];
for (int k = 0; k < itemsPerRow; k++)
{
columnWidths[k] = 0; // autosize
alignment[k] = TextAlignment.Left;
}
this.Writer.Initialize(0, columnsOnTheScreen, columnWidths, alignment, false, GetConsoleWindowHeight(this.InnerCommand._lo.RowNumber));
}
/// <summary>
/// Write the headers.
/// </summary>
internal override void GroupStart()
{
}
/// <summary>
/// Called when the end of a group is reached, flush the
/// write buffer.
/// </summary>
internal override void GroupEnd()
{
WriteStringBuffer();
}
/// <summary>
/// Write a row into the table.
/// </summary>
/// <param name="fed">FormatEntryData to process.</param>
internal override void ProcessPayload(FormatEntryData fed)
{
WideViewEntry wve = fed.formatEntryInfo as WideViewEntry;
FormatPropertyField fpf = wve.formatPropertyField as FormatPropertyField;
_buffer.Add(fpf.propertyValue);
if (_buffer.IsFull)
{
WriteStringBuffer();
}
}
private WideViewHeaderInfo CurrentWideHeaderInfo
{
get
{
return (WideViewHeaderInfo)this.InnerCommand.ShapeInfoOnFormatContext;
}
}
private void WriteStringBuffer()
{
if (_buffer.IsEmpty)
{
return;
}
string[] values = new string[_buffer.Length];
for (int k = 0; k < values.Length; k++)
{
if (k < _buffer.CurrentCount)
values[k] = _buffer[k];
else
values[k] = string.Empty;
}
this.Writer.GenerateRow(values, this.InnerCommand._lo, false, null, InnerCommand._lo.DisplayCells, generatedRows: null);
_buffer.Reset();
}
/// <summary>
/// Helper class to accumulate the display values so that when the end
/// of a line is reached, a full line can be composed.
/// </summary>
private class StringValuesBuffer
{
/// <summary>
/// Construct the buffer.
/// </summary>
/// <param name="size">Number of entries to cache.</param>
internal StringValuesBuffer(int size)
{
_arr = new string[size];
Reset();
}
/// <summary>
/// Get the size of the buffer.
/// </summary>
internal int Length { get { return _arr.Length; } }
/// <summary>
/// Get the current number of entries in the buffer.
/// </summary>
internal int CurrentCount { get { return _lastEmptySpot; } }
/// <summary>
/// Check if the buffer is full.
/// </summary>
internal bool IsFull
{
get { return _lastEmptySpot == _arr.Length; }
}
/// <summary>
/// Check if the buffer is empty.
/// </summary>
internal bool IsEmpty
{
get { return _lastEmptySpot == 0; }
}
/// <summary>
/// Indexer to access the k-th item in the buffer.
/// </summary>
internal string this[int k] { get { return _arr[k]; } }
/// <summary>
/// Add an item to the buffer.
/// </summary>
/// <param name="s">String to add.</param>
internal void Add(string s)
{
_arr[_lastEmptySpot++] = s;
}
/// <summary>
/// Reset the buffer.
/// </summary>
internal void Reset()
{
_lastEmptySpot = 0;
for (int k = 0; k < _arr.Length; k++)
_arr[k] = null;
}
private string[] _arr;
private int _lastEmptySpot;
}
}
private sealed class ComplexOutputContext : GroupOutputContext
{
/// <summary>
/// Construct a context to push on the stack.
/// </summary>
/// <param name="cmd">Reference to the OutCommandInner instance who owns this instance.</param>
/// <param name="parentContext">Parent context in the stack.</param>
/// <param name="formatData">Format data to put in the context.</param>
internal ComplexOutputContext(OutCommandInner cmd,
FormatMessagesContextManager.OutputContext parentContext,
GroupStartData formatData)
: base(cmd, parentContext, formatData)
{
}
internal override void Initialize()
{
_writer.Initialize(this.InnerCommand._lo,
this.InnerCommand._lo.ColumnNumber);
}
/// <summary>
/// Write a row into the list.
/// </summary>
/// <param name="fed">FormatEntryData to process.</param>
internal override void ProcessPayload(FormatEntryData fed)
{
ComplexViewEntry cve = fed.formatEntryInfo as ComplexViewEntry;
if (cve == null || cve.formatValueList == null)
return;
_writer.WriteObject(cve.formatValueList);
}
private ComplexWriter _writer = new ComplexWriter();
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Linq;
using ModestTree;
#if !NOT_UNITY3D
using UnityEngine;
#endif
namespace Zenject
{
public static class TypeAnalyzer
{
static Dictionary<Type, ZenjectTypeInfo> _typeInfo = new Dictionary<Type, ZenjectTypeInfo>();
public static ZenjectTypeInfo GetInfo<T>()
{
return GetInfo(typeof(T));
}
public static ZenjectTypeInfo GetInfo(Type type)
{
Assert.That(!type.IsAbstract(),
"Tried to analyze abstract type '{0}'. This is not currently allowed.", type.Name());
ZenjectTypeInfo info;
#if ZEN_MULTITHREADING
lock (_typeInfo)
#endif
{
if (!_typeInfo.TryGetValue(type, out info))
{
info = CreateTypeInfo(type);
_typeInfo.Add(type, info);
}
}
return info;
}
static ZenjectTypeInfo CreateTypeInfo(Type type)
{
var constructor = GetInjectConstructor(type);
return new ZenjectTypeInfo(
type,
GetPostInjectMethods(type),
constructor,
GetFieldInjectables(type).ToList(),
GetPropertyInjectables(type).ToList(),
GetConstructorInjectables(type, constructor).ToList());
}
static IEnumerable<InjectableInfo> GetConstructorInjectables(Type parentType, ConstructorInfo constructorInfo)
{
if (constructorInfo == null)
{
return Enumerable.Empty<InjectableInfo>();
}
return constructorInfo.GetParameters().Select(
paramInfo => CreateInjectableInfoForParam(parentType, paramInfo));
}
static InjectableInfo CreateInjectableInfoForParam(
Type parentType, ParameterInfo paramInfo)
{
var injectAttributes = paramInfo.AllAttributes<InjectAttributeBase>().ToList();
Assert.That(injectAttributes.Count <= 1,
"Found multiple 'Inject' attributes on type parameter '{0}' of type '{1}'. Parameter should only have one", paramInfo.Name, parentType.Name());
var injectAttr = injectAttributes.SingleOrDefault();
object identifier = null;
bool isOptional = false;
InjectSources sourceType = InjectSources.Any;
if (injectAttr != null)
{
identifier = injectAttr.Id;
isOptional = injectAttr.Optional;
sourceType = injectAttr.Source;
}
bool isOptionalWithADefaultValue = (paramInfo.Attributes & ParameterAttributes.HasDefault) == ParameterAttributes.HasDefault;
return new InjectableInfo(
isOptionalWithADefaultValue || isOptional,
identifier,
paramInfo.Name,
paramInfo.ParameterType,
parentType,
null,
isOptionalWithADefaultValue ? paramInfo.DefaultValue : null,
sourceType);
}
static List<PostInjectableInfo> GetPostInjectMethods(Type type)
{
// Note that unlike with fields and properties we use GetCustomAttributes
// This is so that we can ignore inherited attributes, which is necessary
// otherwise a base class method marked with [Inject] would cause all overridden
// derived methods to be added as well
var methods = type.GetAllInstanceMethods()
.Where(x => x.GetCustomAttributes(typeof(InjectAttribute), false).Any()).ToList();
var heirarchyList = type.Yield().Concat(type.GetParentTypes()).Reverse().ToList();
// Order by base classes first
// This is how constructors work so it makes more sense
var values = methods.OrderBy(x => heirarchyList.IndexOf(x.DeclaringType));
var postInjectInfos = new List<PostInjectableInfo>();
foreach (var methodInfo in values)
{
var paramsInfo = methodInfo.GetParameters();
var injectAttr = methodInfo.AllAttributes<InjectAttribute>().Single();
Assert.That(!injectAttr.Optional && injectAttr.Id == null && injectAttr.Source == InjectSources.Any,
"Parameters of InjectAttribute do not apply to constructors and methods");
postInjectInfos.Add(
new PostInjectableInfo(
methodInfo,
paramsInfo.Select(paramInfo =>
CreateInjectableInfoForParam(type, paramInfo)).ToList()));
}
return postInjectInfos;
}
static IEnumerable<InjectableInfo> GetPropertyInjectables(Type type)
{
var propInfos = type.GetAllInstanceProperties()
.Where(x => x.HasAttribute(typeof(InjectAttributeBase)));
foreach (var propInfo in propInfos)
{
yield return CreateForMember(propInfo, type);
}
}
static IEnumerable<InjectableInfo> GetFieldInjectables(Type type)
{
var fieldInfos = type.GetAllInstanceFields()
.Where(x => x.HasAttribute(typeof(InjectAttributeBase)));
foreach (var fieldInfo in fieldInfos)
{
yield return CreateForMember(fieldInfo, type);
}
}
static InjectableInfo CreateForMember(MemberInfo memInfo, Type parentType)
{
var injectAttributes = memInfo.AllAttributes<InjectAttributeBase>().ToList();
Assert.That(injectAttributes.Count <= 1,
"Found multiple 'Inject' attributes on type field '{0}' of type '{1}'. Field should only container one Inject attribute", memInfo.Name, parentType.Name());
var injectAttr = injectAttributes.SingleOrDefault();
object identifier = null;
bool isOptional = false;
InjectSources sourceType = InjectSources.Any;
if (injectAttr != null)
{
identifier = injectAttr.Id;
isOptional = injectAttr.Optional;
sourceType = injectAttr.Source;
}
Type memberType;
Action<object, object> setter;
if (memInfo is FieldInfo)
{
var fieldInfo = (FieldInfo)memInfo;
setter = ((object injectable, object value) => fieldInfo.SetValue(injectable, value));
memberType = fieldInfo.FieldType;
}
else
{
Assert.That(memInfo is PropertyInfo);
var propInfo = (PropertyInfo)memInfo;
setter = ((object injectable, object value) => propInfo.SetValue(injectable, value, null));
memberType = propInfo.PropertyType;
}
return new InjectableInfo(
isOptional,
identifier,
memInfo.Name,
memberType,
parentType,
setter,
null,
sourceType);
}
static ConstructorInfo GetInjectConstructor(Type parentType)
{
var constructors = parentType.Constructors();
#if (UNITY_WSA && ENABLE_DOTNET) && !UNITY_EDITOR
// WP8 generates a dummy constructor with signature (internal Classname(UIntPtr dummy))
// So just ignore that
constructors = constructors.Where(c => !IsWp8GeneratedConstructor(c)).ToArray();
#endif
if (constructors.IsEmpty())
{
return null;
}
if (constructors.HasMoreThan(1))
{
// This will return null if there is more than one constructor and none are marked with the [Inject] attribute
return (from c in constructors where c.HasAttribute<InjectAttribute>() select c).SingleOrDefault();
}
return constructors[0];
}
#if (UNITY_WSA && ENABLE_DOTNET) && !UNITY_EDITOR
static bool IsWp8GeneratedConstructor(ConstructorInfo c)
{
ParameterInfo[] args = c.GetParameters();
return ( (args.Length == 1) && args[0].ParameterType == typeof(UIntPtr) && (args[0].Name == null || args[0].Name == "dummy") ) ||
( (args.Length == 2) && args[0].ParameterType == typeof(UIntPtr) && (args[0].Name == null) && args[1].ParameterType == typeof(Int64*) && (args[1].Name == null) );
}
#endif
}
}
| |
//------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//------------------------------------------------------------
namespace System.ServiceModel.Channels
{
using System;
using System.Runtime;
using System.ServiceModel;
using System.ServiceModel.Security;
using System.ServiceModel.Diagnostics;
abstract class ClientReliableChannelBinder<TChannel> : ReliableChannelBinder<TChannel>,
IClientReliableChannelBinder
where TChannel : class, IChannel
{
ChannelParameterCollection channelParameters;
IChannelFactory<TChannel> factory;
EndpointAddress to;
Uri via;
protected ClientReliableChannelBinder(EndpointAddress to, Uri via, IChannelFactory<TChannel> factory,
MaskingMode maskingMode, TolerateFaultsMode faultMode, ChannelParameterCollection channelParameters,
TimeSpan defaultCloseTimeout, TimeSpan defaultSendTimeout)
: base(factory.CreateChannel(to, via), maskingMode, faultMode,
defaultCloseTimeout, defaultSendTimeout)
{
if (channelParameters == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("channelParameters");
}
this.to = to;
this.via = via;
this.factory = factory;
this.channelParameters = channelParameters;
}
// The server side must get a message to determine where the channel should go, thus it is
// pointless to create a channel for the sake of receiving on the client side. Also, since
// the client side can create channels there receive may enter an infinite loop if open
// persistently throws.
protected override bool CanGetChannelForReceive
{
get
{
return false;
}
}
public override bool CanSendAsynchronously
{
get
{
return true;
}
}
public override ChannelParameterCollection ChannelParameters
{
get
{
return this.channelParameters;
}
}
protected override bool MustCloseChannel
{
get
{
return true;
}
}
protected override bool MustOpenChannel
{
get
{
return true;
}
}
public Uri Via
{
get
{
return this.via;
}
}
public IAsyncResult BeginRequest(Message message, TimeSpan timeout, AsyncCallback callback,
object state)
{
return this.BeginRequest(message, timeout, this.DefaultMaskingMode, callback, state);
}
public IAsyncResult BeginRequest(Message message, TimeSpan timeout, MaskingMode maskingMode,
AsyncCallback callback, object state)
{
RequestAsyncResult result = new RequestAsyncResult(this, callback, state);
result.Start(message, timeout, maskingMode);
return result;
}
protected override IAsyncResult BeginTryGetChannel(TimeSpan timeout,
AsyncCallback callback, object state)
{
CommunicationState currentState = this.State;
TChannel channel;
if ((currentState == CommunicationState.Created)
|| (currentState == CommunicationState.Opening)
|| (currentState == CommunicationState.Opened))
{
channel = this.factory.CreateChannel(this.to, this.via);
}
else
{
channel = null;
}
return new CompletedAsyncResult<TChannel>(channel, callback, state);
}
public static IClientReliableChannelBinder CreateBinder(EndpointAddress to, Uri via,
IChannelFactory<TChannel> factory, MaskingMode maskingMode, TolerateFaultsMode faultMode,
ChannelParameterCollection channelParameters,
TimeSpan defaultCloseTimeout, TimeSpan defaultSendTimeout)
{
Type type = typeof(TChannel);
if (type == typeof(IDuplexChannel))
{
return new DuplexClientReliableChannelBinder(to, via, (IChannelFactory<IDuplexChannel>)(object)factory, maskingMode,
channelParameters, defaultCloseTimeout, defaultSendTimeout);
}
else if (type == typeof(IDuplexSessionChannel))
{
return new DuplexSessionClientReliableChannelBinder(to, via, (IChannelFactory<IDuplexSessionChannel>)(object)factory, maskingMode,
faultMode, channelParameters, defaultCloseTimeout, defaultSendTimeout);
}
else if (type == typeof(IRequestChannel))
{
return new RequestClientReliableChannelBinder(to, via, (IChannelFactory<IRequestChannel>)(object)factory, maskingMode,
channelParameters, defaultCloseTimeout, defaultSendTimeout);
}
else if (type == typeof(IRequestSessionChannel))
{
return new RequestSessionClientReliableChannelBinder(to, via, (IChannelFactory<IRequestSessionChannel>)(object)factory, maskingMode,
faultMode, channelParameters, defaultCloseTimeout, defaultSendTimeout);
}
else
{
throw Fx.AssertAndThrow("ClientReliableChannelBinder supports creation of IDuplexChannel, IDuplexSessionChannel, IRequestChannel, and IRequestSessionChannel only.");
}
}
public Message EndRequest(IAsyncResult result)
{
return RequestAsyncResult.End(result);
}
protected override bool EndTryGetChannel(IAsyncResult result)
{
TChannel channel = CompletedAsyncResult<TChannel>.End(result);
if (channel != null && !this.Synchronizer.SetChannel(channel))
{
channel.Abort();
}
return true;
}
public bool EnsureChannelForRequest()
{
return this.Synchronizer.EnsureChannel();
}
protected override void OnAbort()
{
}
protected override IAsyncResult OnBeginClose(TimeSpan timeout, AsyncCallback callback,
object state)
{
return new CompletedAsyncResult(callback, state);
}
protected override IAsyncResult OnBeginOpen(TimeSpan timeout, AsyncCallback callback,
object state)
{
return new CompletedAsyncResult(callback, state);
}
protected virtual IAsyncResult OnBeginRequest(TChannel channel, Message message,
TimeSpan timeout, MaskingMode maskingMode, AsyncCallback callback, object state)
{
throw Fx.AssertAndThrow("The derived class does not support the OnBeginRequest operation.");
}
protected override void OnClose(TimeSpan timeout)
{
}
protected override void OnEndClose(IAsyncResult result)
{
CompletedAsyncResult.End(result);
}
protected override void OnEndOpen(IAsyncResult result)
{
CompletedAsyncResult.End(result);
}
protected virtual Message OnEndRequest(TChannel channel, MaskingMode maskingMode,
IAsyncResult result)
{
throw Fx.AssertAndThrow("The derived class does not support the OnEndRequest operation.");
}
protected override void OnOpen(TimeSpan timeout)
{
}
protected virtual Message OnRequest(TChannel channel, Message message, TimeSpan timeout,
MaskingMode maskingMode)
{
throw Fx.AssertAndThrow("The derived class does not support the OnRequest operation.");
}
public Message Request(Message message, TimeSpan timeout)
{
return this.Request(message, timeout, this.DefaultMaskingMode);
}
public Message Request(Message message, TimeSpan timeout, MaskingMode maskingMode)
{
if (!this.ValidateOutputOperation(message, timeout, maskingMode))
{
return null;
}
bool autoAborted = false;
try
{
TimeoutHelper timeoutHelper = new TimeoutHelper(timeout);
TChannel channel;
if (!this.Synchronizer.TryGetChannelForOutput(timeoutHelper.RemainingTime(), maskingMode,
out channel))
{
if (!ReliableChannelBinderHelper.MaskHandled(maskingMode))
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
new TimeoutException(SR.GetString(SR.TimeoutOnRequest, timeout)));
}
return null;
}
if (channel == null)
{
return null;
}
try
{
return this.OnRequest(channel, message, timeoutHelper.RemainingTime(),
maskingMode);
}
finally
{
autoAborted = this.Synchronizer.Aborting;
this.Synchronizer.ReturnChannel();
}
}
catch (Exception e)
{
if (Fx.IsFatal(e))
throw;
if (!this.HandleException(e, maskingMode, autoAborted))
{
throw;
}
else
{
return null;
}
}
}
protected override bool TryGetChannel(TimeSpan timeout)
{
CommunicationState currentState = this.State;
TChannel channel = null;
if ((currentState == CommunicationState.Created)
|| (currentState == CommunicationState.Opening)
|| (currentState == CommunicationState.Opened))
{
channel = this.factory.CreateChannel(this.to, this.via);
if (!this.Synchronizer.SetChannel(channel))
{
channel.Abort();
}
}
else
{
channel = null;
}
return true;
}
abstract class DuplexClientReliableChannelBinder<TDuplexChannel>
: ClientReliableChannelBinder<TDuplexChannel>
where TDuplexChannel : class, IDuplexChannel
{
public DuplexClientReliableChannelBinder(EndpointAddress to, Uri via,
IChannelFactory<TDuplexChannel> factory, MaskingMode maskingMode, TolerateFaultsMode faultMode,
ChannelParameterCollection channelParameters,
TimeSpan defaultCloseTimeout, TimeSpan defaultSendTimeout)
: base(to, via, factory, maskingMode, faultMode, channelParameters, defaultCloseTimeout,
defaultSendTimeout)
{
}
public override EndpointAddress LocalAddress
{
get
{
IDuplexChannel channel = this.Synchronizer.CurrentChannel;
if (channel == null)
return null;
else
return channel.LocalAddress;
}
}
public override EndpointAddress RemoteAddress
{
get
{
IDuplexChannel channel = this.Synchronizer.CurrentChannel;
if (channel == null)
return null;
else
return channel.RemoteAddress;
}
}
protected override IAsyncResult OnBeginSend(TDuplexChannel channel, Message message,
TimeSpan timeout, AsyncCallback callback, object state)
{
return channel.BeginSend(message, timeout, callback, state);
}
protected override IAsyncResult OnBeginTryReceive(TDuplexChannel channel,
TimeSpan timeout, AsyncCallback callback, object state)
{
return channel.BeginTryReceive(timeout, callback, state);
}
protected override void OnEndSend(TDuplexChannel channel, IAsyncResult result)
{
channel.EndSend(result);
}
protected override bool OnEndTryReceive(TDuplexChannel channel, IAsyncResult result,
out RequestContext requestContext)
{
Message message;
bool success = channel.EndTryReceive(result, out message);
if (success && message == null)
{
this.OnReadNullMessage();
}
requestContext = this.WrapMessage(message);
return success;
}
protected virtual void OnReadNullMessage()
{
}
protected override void OnSend(TDuplexChannel channel, Message message,
TimeSpan timeout)
{
channel.Send(message, timeout);
}
protected override bool OnTryReceive(TDuplexChannel channel, TimeSpan timeout,
out RequestContext requestContext)
{
Message message;
bool success = channel.TryReceive(timeout, out message);
if (success && message == null)
{
this.OnReadNullMessage();
}
requestContext = this.WrapMessage(message);
return success;
}
}
sealed class DuplexClientReliableChannelBinder
: DuplexClientReliableChannelBinder<IDuplexChannel>
{
public DuplexClientReliableChannelBinder(EndpointAddress to, Uri via,
IChannelFactory<IDuplexChannel> factory, MaskingMode maskingMode,
ChannelParameterCollection channelParameters,
TimeSpan defaultCloseTimeout, TimeSpan defaultSendTimeout)
: base(to, via, factory, maskingMode, TolerateFaultsMode.Never, channelParameters,
defaultCloseTimeout, defaultSendTimeout)
{
}
public override bool HasSession
{
get
{
return false;
}
}
public override ISession GetInnerSession()
{
return null;
}
protected override bool HasSecuritySession(IDuplexChannel channel)
{
return false;
}
}
sealed class DuplexSessionClientReliableChannelBinder
: DuplexClientReliableChannelBinder<IDuplexSessionChannel>
{
public DuplexSessionClientReliableChannelBinder(EndpointAddress to, Uri via,
IChannelFactory<IDuplexSessionChannel> factory, MaskingMode maskingMode, TolerateFaultsMode faultMode,
ChannelParameterCollection channelParameters,
TimeSpan defaultCloseTimeout, TimeSpan defaultSendTimeout)
: base(to, via, factory, maskingMode, faultMode, channelParameters, defaultCloseTimeout,
defaultSendTimeout)
{
}
public override bool HasSession
{
get
{
return true;
}
}
public override ISession GetInnerSession()
{
return this.Synchronizer.CurrentChannel.Session;
}
protected override IAsyncResult BeginCloseChannel(IDuplexSessionChannel channel,
TimeSpan timeout, AsyncCallback callback, object state)
{
return ReliableChannelBinderHelper.BeginCloseDuplexSessionChannel(this, channel,
timeout, callback, state);
}
protected override void CloseChannel(IDuplexSessionChannel channel, TimeSpan timeout)
{
ReliableChannelBinderHelper.CloseDuplexSessionChannel(this, channel, timeout);
}
protected override void EndCloseChannel(IDuplexSessionChannel channel,
IAsyncResult result)
{
ReliableChannelBinderHelper.EndCloseDuplexSessionChannel(channel, result);
}
protected override bool HasSecuritySession(IDuplexSessionChannel channel)
{
return channel.Session is ISecuritySession;
}
protected override void OnReadNullMessage()
{
this.Synchronizer.OnReadEof();
}
}
abstract class RequestClientReliableChannelBinder<TRequestChannel>
: ClientReliableChannelBinder<TRequestChannel>
where TRequestChannel : class, IRequestChannel
{
InputQueue<Message> inputMessages;
public RequestClientReliableChannelBinder(EndpointAddress to, Uri via,
IChannelFactory<TRequestChannel> factory, MaskingMode maskingMode, TolerateFaultsMode faultMode,
ChannelParameterCollection channelParameters,
TimeSpan defaultCloseTimeout, TimeSpan defaultSendTimeout)
: base(to, via, factory, maskingMode, faultMode, channelParameters, defaultCloseTimeout,
defaultSendTimeout)
{
}
public override IAsyncResult BeginTryReceive(TimeSpan timeout, AsyncCallback callback,
object state)
{
return this.GetInputMessages().BeginDequeue(timeout, callback, state);
}
public override bool EndTryReceive(IAsyncResult result,
out RequestContext requestContext)
{
Message message;
bool success = this.GetInputMessages().EndDequeue(result, out message);
requestContext = this.WrapMessage(message);
return success;
}
protected void EnqueueMessageIfNotNull(Message message)
{
if (message != null)
{
this.GetInputMessages().EnqueueAndDispatch(message);
}
}
InputQueue<Message> GetInputMessages()
{
lock (this.ThisLock)
{
if (this.State == CommunicationState.Created)
{
throw Fx.AssertAndThrow("The method GetInputMessages() cannot be called when the binder is in the Created state.");
}
if (this.State == CommunicationState.Opening)
{
throw Fx.AssertAndThrow("The method GetInputMessages() cannot be called when the binder is in the Opening state.");
}
if (this.inputMessages == null)
{
this.inputMessages = TraceUtility.CreateInputQueue<Message>();
}
}
return this.inputMessages;
}
public override EndpointAddress LocalAddress
{
get
{
return EndpointAddress.AnonymousAddress;
}
}
public override EndpointAddress RemoteAddress
{
get
{
IRequestChannel channel = this.Synchronizer.CurrentChannel;
if (channel == null)
return null;
else
return channel.RemoteAddress;
}
}
protected override IAsyncResult OnBeginRequest(TRequestChannel channel,
Message message, TimeSpan timeout, MaskingMode maskingMode,
AsyncCallback callback, object state)
{
return channel.BeginRequest(message, timeout, callback, state);
}
protected override IAsyncResult OnBeginSend(TRequestChannel channel, Message message,
TimeSpan timeout, AsyncCallback callback, object state)
{
return channel.BeginRequest(message, timeout, callback, state);
}
protected override Message OnEndRequest(TRequestChannel channel,
MaskingMode maskingMode, IAsyncResult result)
{
return channel.EndRequest(result);
}
protected override void OnEndSend(TRequestChannel channel, IAsyncResult result)
{
Message message = channel.EndRequest(result);
this.EnqueueMessageIfNotNull(message);
}
protected override Message OnRequest(TRequestChannel channel, Message message,
TimeSpan timeout, MaskingMode maskingMode)
{
return channel.Request(message, timeout);
}
protected override void OnSend(TRequestChannel channel, Message message,
TimeSpan timeout)
{
message = channel.Request(message, timeout);
this.EnqueueMessageIfNotNull(message);
}
protected override void OnShutdown()
{
if (this.inputMessages != null)
{
this.inputMessages.Close();
}
}
public override bool TryReceive(TimeSpan timeout, out RequestContext requestContext)
{
Message message;
bool success = this.GetInputMessages().Dequeue(timeout, out message);
requestContext = this.WrapMessage(message);
return success;
}
}
sealed class RequestAsyncResult
: ReliableChannelBinder<TChannel>.OutputAsyncResult<ClientReliableChannelBinder<TChannel>>
{
Message reply;
public RequestAsyncResult(ClientReliableChannelBinder<TChannel> binder,
AsyncCallback callback, object state)
: base(binder, callback, state)
{
}
protected override IAsyncResult BeginOutput(
ClientReliableChannelBinder<TChannel> binder, TChannel channel, Message message,
TimeSpan timeout, MaskingMode maskingMode, AsyncCallback callback, object state)
{
return binder.OnBeginRequest(channel, message, timeout, maskingMode, callback,
state);
}
public static Message End(IAsyncResult result)
{
RequestAsyncResult requestResult = AsyncResult.End<RequestAsyncResult>(result);
return requestResult.reply;
}
protected override void EndOutput(ClientReliableChannelBinder<TChannel> binder,
TChannel channel, MaskingMode maskingMode, IAsyncResult result)
{
this.reply = binder.OnEndRequest(channel, maskingMode, result);
}
protected override string GetTimeoutString(TimeSpan timeout)
{
return SR.GetString(SR.TimeoutOnRequest, timeout);
}
}
sealed class RequestClientReliableChannelBinder
: RequestClientReliableChannelBinder<IRequestChannel>
{
public RequestClientReliableChannelBinder(EndpointAddress to, Uri via,
IChannelFactory<IRequestChannel> factory, MaskingMode maskingMode,
ChannelParameterCollection channelParameters,
TimeSpan defaultCloseTimeout, TimeSpan defaultSendTimeout)
: base(to, via, factory, maskingMode, TolerateFaultsMode.Never, channelParameters,
defaultCloseTimeout, defaultSendTimeout)
{
}
public override bool HasSession
{
get
{
return false;
}
}
public override ISession GetInnerSession()
{
return null;
}
protected override bool HasSecuritySession(IRequestChannel channel)
{
return false;
}
}
sealed class RequestSessionClientReliableChannelBinder
: RequestClientReliableChannelBinder<IRequestSessionChannel>
{
public RequestSessionClientReliableChannelBinder(EndpointAddress to, Uri via,
IChannelFactory<IRequestSessionChannel> factory, MaskingMode maskingMode, TolerateFaultsMode faultMode,
ChannelParameterCollection channelParameters,
TimeSpan defaultCloseTimeout, TimeSpan defaultSendTimeout)
: base(to, via, factory, maskingMode, faultMode, channelParameters, defaultCloseTimeout,
defaultSendTimeout)
{
}
public override bool HasSession
{
get
{
return true;
}
}
public override ISession GetInnerSession()
{
return this.Synchronizer.CurrentChannel.Session;
}
protected override bool HasSecuritySession(IRequestSessionChannel channel)
{
return channel.Session is ISecuritySession;
}
}
}
}
| |
/*
* 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:
*
* 1) Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2) Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* 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;
using System.Collections.Generic;
namespace XenAPI
{
/// <summary>
/// A type of virtual GPU
/// First published in XenServer 6.2 SP1 Tech-Preview.
/// </summary>
public partial class VGPU_type : XenObject<VGPU_type>
{
public VGPU_type()
{
}
public VGPU_type(string uuid,
string vendor_name,
string model_name,
long framebuffer_size,
long max_heads,
long max_resolution_x,
long max_resolution_y,
List<XenRef<PGPU>> supported_on_PGPUs,
List<XenRef<PGPU>> enabled_on_PGPUs,
List<XenRef<VGPU>> VGPUs,
List<XenRef<GPU_group>> supported_on_GPU_groups,
List<XenRef<GPU_group>> enabled_on_GPU_groups,
vgpu_type_implementation implementation,
string identifier,
bool experimental)
{
this.uuid = uuid;
this.vendor_name = vendor_name;
this.model_name = model_name;
this.framebuffer_size = framebuffer_size;
this.max_heads = max_heads;
this.max_resolution_x = max_resolution_x;
this.max_resolution_y = max_resolution_y;
this.supported_on_PGPUs = supported_on_PGPUs;
this.enabled_on_PGPUs = enabled_on_PGPUs;
this.VGPUs = VGPUs;
this.supported_on_GPU_groups = supported_on_GPU_groups;
this.enabled_on_GPU_groups = enabled_on_GPU_groups;
this.implementation = implementation;
this.identifier = identifier;
this.experimental = experimental;
}
/// <summary>
/// Creates a new VGPU_type from a Proxy_VGPU_type.
/// </summary>
/// <param name="proxy"></param>
public VGPU_type(Proxy_VGPU_type proxy)
{
this.UpdateFromProxy(proxy);
}
public override void UpdateFrom(VGPU_type update)
{
uuid = update.uuid;
vendor_name = update.vendor_name;
model_name = update.model_name;
framebuffer_size = update.framebuffer_size;
max_heads = update.max_heads;
max_resolution_x = update.max_resolution_x;
max_resolution_y = update.max_resolution_y;
supported_on_PGPUs = update.supported_on_PGPUs;
enabled_on_PGPUs = update.enabled_on_PGPUs;
VGPUs = update.VGPUs;
supported_on_GPU_groups = update.supported_on_GPU_groups;
enabled_on_GPU_groups = update.enabled_on_GPU_groups;
implementation = update.implementation;
identifier = update.identifier;
experimental = update.experimental;
}
internal void UpdateFromProxy(Proxy_VGPU_type proxy)
{
uuid = proxy.uuid == null ? null : (string)proxy.uuid;
vendor_name = proxy.vendor_name == null ? null : (string)proxy.vendor_name;
model_name = proxy.model_name == null ? null : (string)proxy.model_name;
framebuffer_size = proxy.framebuffer_size == null ? 0 : long.Parse((string)proxy.framebuffer_size);
max_heads = proxy.max_heads == null ? 0 : long.Parse((string)proxy.max_heads);
max_resolution_x = proxy.max_resolution_x == null ? 0 : long.Parse((string)proxy.max_resolution_x);
max_resolution_y = proxy.max_resolution_y == null ? 0 : long.Parse((string)proxy.max_resolution_y);
supported_on_PGPUs = proxy.supported_on_PGPUs == null ? null : XenRef<PGPU>.Create(proxy.supported_on_PGPUs);
enabled_on_PGPUs = proxy.enabled_on_PGPUs == null ? null : XenRef<PGPU>.Create(proxy.enabled_on_PGPUs);
VGPUs = proxy.VGPUs == null ? null : XenRef<VGPU>.Create(proxy.VGPUs);
supported_on_GPU_groups = proxy.supported_on_GPU_groups == null ? null : XenRef<GPU_group>.Create(proxy.supported_on_GPU_groups);
enabled_on_GPU_groups = proxy.enabled_on_GPU_groups == null ? null : XenRef<GPU_group>.Create(proxy.enabled_on_GPU_groups);
implementation = proxy.implementation == null ? (vgpu_type_implementation) 0 : (vgpu_type_implementation)Helper.EnumParseDefault(typeof(vgpu_type_implementation), (string)proxy.implementation);
identifier = proxy.identifier == null ? null : (string)proxy.identifier;
experimental = (bool)proxy.experimental;
}
public Proxy_VGPU_type ToProxy()
{
Proxy_VGPU_type result_ = new Proxy_VGPU_type();
result_.uuid = uuid ?? "";
result_.vendor_name = vendor_name ?? "";
result_.model_name = model_name ?? "";
result_.framebuffer_size = framebuffer_size.ToString();
result_.max_heads = max_heads.ToString();
result_.max_resolution_x = max_resolution_x.ToString();
result_.max_resolution_y = max_resolution_y.ToString();
result_.supported_on_PGPUs = (supported_on_PGPUs != null) ? Helper.RefListToStringArray(supported_on_PGPUs) : new string[] {};
result_.enabled_on_PGPUs = (enabled_on_PGPUs != null) ? Helper.RefListToStringArray(enabled_on_PGPUs) : new string[] {};
result_.VGPUs = (VGPUs != null) ? Helper.RefListToStringArray(VGPUs) : new string[] {};
result_.supported_on_GPU_groups = (supported_on_GPU_groups != null) ? Helper.RefListToStringArray(supported_on_GPU_groups) : new string[] {};
result_.enabled_on_GPU_groups = (enabled_on_GPU_groups != null) ? Helper.RefListToStringArray(enabled_on_GPU_groups) : new string[] {};
result_.implementation = vgpu_type_implementation_helper.ToString(implementation);
result_.identifier = identifier ?? "";
result_.experimental = experimental;
return result_;
}
/// <summary>
/// Creates a new VGPU_type from a Hashtable.
/// </summary>
/// <param name="table"></param>
public VGPU_type(Hashtable table)
{
uuid = Marshalling.ParseString(table, "uuid");
vendor_name = Marshalling.ParseString(table, "vendor_name");
model_name = Marshalling.ParseString(table, "model_name");
framebuffer_size = Marshalling.ParseLong(table, "framebuffer_size");
max_heads = Marshalling.ParseLong(table, "max_heads");
max_resolution_x = Marshalling.ParseLong(table, "max_resolution_x");
max_resolution_y = Marshalling.ParseLong(table, "max_resolution_y");
supported_on_PGPUs = Marshalling.ParseSetRef<PGPU>(table, "supported_on_PGPUs");
enabled_on_PGPUs = Marshalling.ParseSetRef<PGPU>(table, "enabled_on_PGPUs");
VGPUs = Marshalling.ParseSetRef<VGPU>(table, "VGPUs");
supported_on_GPU_groups = Marshalling.ParseSetRef<GPU_group>(table, "supported_on_GPU_groups");
enabled_on_GPU_groups = Marshalling.ParseSetRef<GPU_group>(table, "enabled_on_GPU_groups");
implementation = (vgpu_type_implementation)Helper.EnumParseDefault(typeof(vgpu_type_implementation), Marshalling.ParseString(table, "implementation"));
identifier = Marshalling.ParseString(table, "identifier");
experimental = Marshalling.ParseBool(table, "experimental");
}
public bool DeepEquals(VGPU_type other)
{
if (ReferenceEquals(null, other))
return false;
if (ReferenceEquals(this, other))
return true;
return Helper.AreEqual2(this._uuid, other._uuid) &&
Helper.AreEqual2(this._vendor_name, other._vendor_name) &&
Helper.AreEqual2(this._model_name, other._model_name) &&
Helper.AreEqual2(this._framebuffer_size, other._framebuffer_size) &&
Helper.AreEqual2(this._max_heads, other._max_heads) &&
Helper.AreEqual2(this._max_resolution_x, other._max_resolution_x) &&
Helper.AreEqual2(this._max_resolution_y, other._max_resolution_y) &&
Helper.AreEqual2(this._supported_on_PGPUs, other._supported_on_PGPUs) &&
Helper.AreEqual2(this._enabled_on_PGPUs, other._enabled_on_PGPUs) &&
Helper.AreEqual2(this._VGPUs, other._VGPUs) &&
Helper.AreEqual2(this._supported_on_GPU_groups, other._supported_on_GPU_groups) &&
Helper.AreEqual2(this._enabled_on_GPU_groups, other._enabled_on_GPU_groups) &&
Helper.AreEqual2(this._implementation, other._implementation) &&
Helper.AreEqual2(this._identifier, other._identifier) &&
Helper.AreEqual2(this._experimental, other._experimental);
}
public override string SaveChanges(Session session, string opaqueRef, VGPU_type server)
{
if (opaqueRef == null)
{
System.Diagnostics.Debug.Assert(false, "Cannot create instances of this type on the server");
return "";
}
else
{
throw new InvalidOperationException("This type has no read/write properties");
}
}
/// <summary>
/// Get a record containing the current state of the given VGPU_type.
/// First published in XenServer 6.2 SP1 Tech-Preview.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vgpu_type">The opaque_ref of the given vgpu_type</param>
public static VGPU_type get_record(Session session, string _vgpu_type)
{
return new VGPU_type((Proxy_VGPU_type)session.proxy.vgpu_type_get_record(session.uuid, _vgpu_type ?? "").parse());
}
/// <summary>
/// Get a reference to the VGPU_type instance with the specified UUID.
/// First published in XenServer 6.2 SP1 Tech-Preview.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_uuid">UUID of object to return</param>
public static XenRef<VGPU_type> get_by_uuid(Session session, string _uuid)
{
return XenRef<VGPU_type>.Create(session.proxy.vgpu_type_get_by_uuid(session.uuid, _uuid ?? "").parse());
}
/// <summary>
/// Get the uuid field of the given VGPU_type.
/// First published in XenServer 6.2 SP1 Tech-Preview.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vgpu_type">The opaque_ref of the given vgpu_type</param>
public static string get_uuid(Session session, string _vgpu_type)
{
return (string)session.proxy.vgpu_type_get_uuid(session.uuid, _vgpu_type ?? "").parse();
}
/// <summary>
/// Get the vendor_name field of the given VGPU_type.
/// First published in XenServer 6.2 SP1 Tech-Preview.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vgpu_type">The opaque_ref of the given vgpu_type</param>
public static string get_vendor_name(Session session, string _vgpu_type)
{
return (string)session.proxy.vgpu_type_get_vendor_name(session.uuid, _vgpu_type ?? "").parse();
}
/// <summary>
/// Get the model_name field of the given VGPU_type.
/// First published in XenServer 6.2 SP1 Tech-Preview.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vgpu_type">The opaque_ref of the given vgpu_type</param>
public static string get_model_name(Session session, string _vgpu_type)
{
return (string)session.proxy.vgpu_type_get_model_name(session.uuid, _vgpu_type ?? "").parse();
}
/// <summary>
/// Get the framebuffer_size field of the given VGPU_type.
/// First published in XenServer 6.2 SP1 Tech-Preview.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vgpu_type">The opaque_ref of the given vgpu_type</param>
public static long get_framebuffer_size(Session session, string _vgpu_type)
{
return long.Parse((string)session.proxy.vgpu_type_get_framebuffer_size(session.uuid, _vgpu_type ?? "").parse());
}
/// <summary>
/// Get the max_heads field of the given VGPU_type.
/// First published in XenServer 6.2 SP1 Tech-Preview.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vgpu_type">The opaque_ref of the given vgpu_type</param>
public static long get_max_heads(Session session, string _vgpu_type)
{
return long.Parse((string)session.proxy.vgpu_type_get_max_heads(session.uuid, _vgpu_type ?? "").parse());
}
/// <summary>
/// Get the max_resolution_x field of the given VGPU_type.
/// First published in XenServer 6.2 SP1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vgpu_type">The opaque_ref of the given vgpu_type</param>
public static long get_max_resolution_x(Session session, string _vgpu_type)
{
return long.Parse((string)session.proxy.vgpu_type_get_max_resolution_x(session.uuid, _vgpu_type ?? "").parse());
}
/// <summary>
/// Get the max_resolution_y field of the given VGPU_type.
/// First published in XenServer 6.2 SP1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vgpu_type">The opaque_ref of the given vgpu_type</param>
public static long get_max_resolution_y(Session session, string _vgpu_type)
{
return long.Parse((string)session.proxy.vgpu_type_get_max_resolution_y(session.uuid, _vgpu_type ?? "").parse());
}
/// <summary>
/// Get the supported_on_PGPUs field of the given VGPU_type.
/// First published in XenServer 6.2 SP1 Tech-Preview.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vgpu_type">The opaque_ref of the given vgpu_type</param>
public static List<XenRef<PGPU>> get_supported_on_PGPUs(Session session, string _vgpu_type)
{
return XenRef<PGPU>.Create(session.proxy.vgpu_type_get_supported_on_pgpus(session.uuid, _vgpu_type ?? "").parse());
}
/// <summary>
/// Get the enabled_on_PGPUs field of the given VGPU_type.
/// First published in XenServer 6.2 SP1 Tech-Preview.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vgpu_type">The opaque_ref of the given vgpu_type</param>
public static List<XenRef<PGPU>> get_enabled_on_PGPUs(Session session, string _vgpu_type)
{
return XenRef<PGPU>.Create(session.proxy.vgpu_type_get_enabled_on_pgpus(session.uuid, _vgpu_type ?? "").parse());
}
/// <summary>
/// Get the VGPUs field of the given VGPU_type.
/// First published in XenServer 6.2 SP1 Tech-Preview.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vgpu_type">The opaque_ref of the given vgpu_type</param>
public static List<XenRef<VGPU>> get_VGPUs(Session session, string _vgpu_type)
{
return XenRef<VGPU>.Create(session.proxy.vgpu_type_get_vgpus(session.uuid, _vgpu_type ?? "").parse());
}
/// <summary>
/// Get the supported_on_GPU_groups field of the given VGPU_type.
/// First published in XenServer 6.2 SP1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vgpu_type">The opaque_ref of the given vgpu_type</param>
public static List<XenRef<GPU_group>> get_supported_on_GPU_groups(Session session, string _vgpu_type)
{
return XenRef<GPU_group>.Create(session.proxy.vgpu_type_get_supported_on_gpu_groups(session.uuid, _vgpu_type ?? "").parse());
}
/// <summary>
/// Get the enabled_on_GPU_groups field of the given VGPU_type.
/// First published in XenServer 6.2 SP1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vgpu_type">The opaque_ref of the given vgpu_type</param>
public static List<XenRef<GPU_group>> get_enabled_on_GPU_groups(Session session, string _vgpu_type)
{
return XenRef<GPU_group>.Create(session.proxy.vgpu_type_get_enabled_on_gpu_groups(session.uuid, _vgpu_type ?? "").parse());
}
/// <summary>
/// Get the implementation field of the given VGPU_type.
/// First published in XenServer 7.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vgpu_type">The opaque_ref of the given vgpu_type</param>
public static vgpu_type_implementation get_implementation(Session session, string _vgpu_type)
{
return (vgpu_type_implementation)Helper.EnumParseDefault(typeof(vgpu_type_implementation), (string)session.proxy.vgpu_type_get_implementation(session.uuid, _vgpu_type ?? "").parse());
}
/// <summary>
/// Get the identifier field of the given VGPU_type.
/// First published in XenServer 7.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vgpu_type">The opaque_ref of the given vgpu_type</param>
public static string get_identifier(Session session, string _vgpu_type)
{
return (string)session.proxy.vgpu_type_get_identifier(session.uuid, _vgpu_type ?? "").parse();
}
/// <summary>
/// Get the experimental field of the given VGPU_type.
/// First published in XenServer 7.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vgpu_type">The opaque_ref of the given vgpu_type</param>
public static bool get_experimental(Session session, string _vgpu_type)
{
return (bool)session.proxy.vgpu_type_get_experimental(session.uuid, _vgpu_type ?? "").parse();
}
/// <summary>
/// Return a list of all the VGPU_types known to the system.
/// First published in XenServer 6.2 SP1 Tech-Preview.
/// </summary>
/// <param name="session">The session</param>
public static List<XenRef<VGPU_type>> get_all(Session session)
{
return XenRef<VGPU_type>.Create(session.proxy.vgpu_type_get_all(session.uuid).parse());
}
/// <summary>
/// Get all the VGPU_type Records at once, in a single XML RPC call
/// First published in XenServer 6.2 SP1 Tech-Preview.
/// </summary>
/// <param name="session">The session</param>
public static Dictionary<XenRef<VGPU_type>, VGPU_type> get_all_records(Session session)
{
return XenRef<VGPU_type>.Create<Proxy_VGPU_type>(session.proxy.vgpu_type_get_all_records(session.uuid).parse());
}
/// <summary>
/// Unique identifier/object reference
/// </summary>
public virtual string uuid
{
get { return _uuid; }
set
{
if (!Helper.AreEqual(value, _uuid))
{
_uuid = value;
Changed = true;
NotifyPropertyChanged("uuid");
}
}
}
private string _uuid;
/// <summary>
/// Name of VGPU vendor
/// </summary>
public virtual string vendor_name
{
get { return _vendor_name; }
set
{
if (!Helper.AreEqual(value, _vendor_name))
{
_vendor_name = value;
Changed = true;
NotifyPropertyChanged("vendor_name");
}
}
}
private string _vendor_name;
/// <summary>
/// Model name associated with the VGPU type
/// </summary>
public virtual string model_name
{
get { return _model_name; }
set
{
if (!Helper.AreEqual(value, _model_name))
{
_model_name = value;
Changed = true;
NotifyPropertyChanged("model_name");
}
}
}
private string _model_name;
/// <summary>
/// Framebuffer size of the VGPU type, in bytes
/// </summary>
public virtual long framebuffer_size
{
get { return _framebuffer_size; }
set
{
if (!Helper.AreEqual(value, _framebuffer_size))
{
_framebuffer_size = value;
Changed = true;
NotifyPropertyChanged("framebuffer_size");
}
}
}
private long _framebuffer_size;
/// <summary>
/// Maximum number of displays supported by the VGPU type
/// </summary>
public virtual long max_heads
{
get { return _max_heads; }
set
{
if (!Helper.AreEqual(value, _max_heads))
{
_max_heads = value;
Changed = true;
NotifyPropertyChanged("max_heads");
}
}
}
private long _max_heads;
/// <summary>
/// Maximum resolution (width) supported by the VGPU type
/// First published in XenServer 6.2 SP1.
/// </summary>
public virtual long max_resolution_x
{
get { return _max_resolution_x; }
set
{
if (!Helper.AreEqual(value, _max_resolution_x))
{
_max_resolution_x = value;
Changed = true;
NotifyPropertyChanged("max_resolution_x");
}
}
}
private long _max_resolution_x;
/// <summary>
/// Maximum resolution (height) supported by the VGPU type
/// First published in XenServer 6.2 SP1.
/// </summary>
public virtual long max_resolution_y
{
get { return _max_resolution_y; }
set
{
if (!Helper.AreEqual(value, _max_resolution_y))
{
_max_resolution_y = value;
Changed = true;
NotifyPropertyChanged("max_resolution_y");
}
}
}
private long _max_resolution_y;
/// <summary>
/// List of PGPUs that support this VGPU type
/// </summary>
public virtual List<XenRef<PGPU>> supported_on_PGPUs
{
get { return _supported_on_PGPUs; }
set
{
if (!Helper.AreEqual(value, _supported_on_PGPUs))
{
_supported_on_PGPUs = value;
Changed = true;
NotifyPropertyChanged("supported_on_PGPUs");
}
}
}
private List<XenRef<PGPU>> _supported_on_PGPUs;
/// <summary>
/// List of PGPUs that have this VGPU type enabled
/// </summary>
public virtual List<XenRef<PGPU>> enabled_on_PGPUs
{
get { return _enabled_on_PGPUs; }
set
{
if (!Helper.AreEqual(value, _enabled_on_PGPUs))
{
_enabled_on_PGPUs = value;
Changed = true;
NotifyPropertyChanged("enabled_on_PGPUs");
}
}
}
private List<XenRef<PGPU>> _enabled_on_PGPUs;
/// <summary>
/// List of VGPUs of this type
/// </summary>
public virtual List<XenRef<VGPU>> VGPUs
{
get { return _VGPUs; }
set
{
if (!Helper.AreEqual(value, _VGPUs))
{
_VGPUs = value;
Changed = true;
NotifyPropertyChanged("VGPUs");
}
}
}
private List<XenRef<VGPU>> _VGPUs;
/// <summary>
/// List of GPU groups in which at least one PGPU supports this VGPU type
/// First published in XenServer 6.2 SP1.
/// </summary>
public virtual List<XenRef<GPU_group>> supported_on_GPU_groups
{
get { return _supported_on_GPU_groups; }
set
{
if (!Helper.AreEqual(value, _supported_on_GPU_groups))
{
_supported_on_GPU_groups = value;
Changed = true;
NotifyPropertyChanged("supported_on_GPU_groups");
}
}
}
private List<XenRef<GPU_group>> _supported_on_GPU_groups;
/// <summary>
/// List of GPU groups in which at least one have this VGPU type enabled
/// First published in XenServer 6.2 SP1.
/// </summary>
public virtual List<XenRef<GPU_group>> enabled_on_GPU_groups
{
get { return _enabled_on_GPU_groups; }
set
{
if (!Helper.AreEqual(value, _enabled_on_GPU_groups))
{
_enabled_on_GPU_groups = value;
Changed = true;
NotifyPropertyChanged("enabled_on_GPU_groups");
}
}
}
private List<XenRef<GPU_group>> _enabled_on_GPU_groups;
/// <summary>
/// The internal implementation of this VGPU type
/// First published in XenServer 7.0.
/// </summary>
public virtual vgpu_type_implementation implementation
{
get { return _implementation; }
set
{
if (!Helper.AreEqual(value, _implementation))
{
_implementation = value;
Changed = true;
NotifyPropertyChanged("implementation");
}
}
}
private vgpu_type_implementation _implementation;
/// <summary>
/// Key used to identify VGPU types and avoid creating duplicates - this field is used internally and not intended for interpretation by API clients
/// First published in XenServer 7.0.
/// </summary>
public virtual string identifier
{
get { return _identifier; }
set
{
if (!Helper.AreEqual(value, _identifier))
{
_identifier = value;
Changed = true;
NotifyPropertyChanged("identifier");
}
}
}
private string _identifier;
/// <summary>
/// Indicates whether VGPUs of this type should be considered experimental
/// First published in XenServer 7.0.
/// </summary>
public virtual bool experimental
{
get { return _experimental; }
set
{
if (!Helper.AreEqual(value, _experimental))
{
_experimental = value;
Changed = true;
NotifyPropertyChanged("experimental");
}
}
}
private bool _experimental;
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Globalization;
using System.Web;
using System.Web.Security;
using System.Web.SessionState;
using Microsoft.ApplicationBlocks.Data;
using ILPathways.Business;
namespace ILPathways.DAL
{
/// <summary>
/// Data access manager for GroupMember
/// </summary>
public class GroupMemberManager : BaseDataManager
{
static string className = "GroupMemberManager";
/// <summary>
/// Base procedures
/// </summary>
const string GET_PROC = "[AppGroup.MemberGet]";
const string SELECT_PROC = "[AppGroup.MemberSelect]";
const string SEARCH_PROC = "[AppGroup.MemberSearch]";
const string DELETE_PROC = "[AppGroup.MemberDelete]";
const string INSERT_PROC = "[AppGroup.MemberInsert]";
const string UPDATE_PROC = "[AppGroup.MemberUpdate]";
/// <summary>
/// Default constructor
/// </summary>
public GroupMemberManager()
{ }//
/// <summary>
/// struct for transporting Group_MemberRelationship
/// </summary>
[Serializable]
public struct Group_MemberRelationship
{
public int GroupId;
public int UserId;
public int GroupCategoryId;
public string Status;
public DateTime Created;
public string Message;
}
#region ====== Core Methods ===============================================
/// <summary>
/// Delete an GroupMember record - first use the group code to lookup the GroupMember in order to get Id
/// </summary>
/// <param name="userId"></param>
/// <param name="groupCode"></param>
/// <param name="statusMessage"></param>
/// <returns></returns>
public static bool Delete( int userId, string groupCode, ref string statusMessage )
{
int pId = 0;
int groupId = 0;
GroupMember mbr = Get( pId, userId, groupId, groupCode );
if ( mbr == null || mbr.Id == 0 )
{
//??
return false;
} else
{
return Delete( mbr.Id, ref statusMessage );
}
}//
/// <summary>
/// Delete an GroupMember record
/// </summary>
/// <param name="pId"></param>
/// <param name="statusMessage"></param>
/// <returns></returns>
public static bool Delete( int pId, ref string statusMessage )
{
string connectionString = GatewayConnection();
bool successful = false;
SqlParameter[] sqlParameters = new SqlParameter[ 1 ];
sqlParameters[ 0 ] = new SqlParameter( "@id", SqlDbType.Int );
sqlParameters[ 0 ].Value = pId;
try
{
SqlHelper.ExecuteNonQuery( connectionString, CommandType.StoredProcedure, DELETE_PROC, sqlParameters );
successful = true;
} catch ( Exception ex )
{
LogError( ex, className + ".Delete() " );
statusMessage = className + "- Unsuccessful: Delete(): " + ex.Message.ToString();
successful = false;
}
return successful;
}//
/// <summary>
/// Add an GroupMember record - first use the group code to lookup the groupId
/// </summary>
/// <param name="entity"></param>
/// <param name="groupCode"></param>
/// <param name="statusMessage"></param>
/// <returns></returns>
public static int Create( GroupMember entity, string groupCode, ref string statusMessage )
{
AppGroup group = GroupManager.GetByCode( groupCode );
if ( group == null || group.Id == 0 )
{
//??
statusMessage = className + "- Unsuccessful: Create(): Error the related AppGroup was not found (using a group code of: " + groupCode + ")";
return 0;
} else
{
entity.GroupId = group.Id;
return Create( entity, ref statusMessage );
}
}//
/// <summary>
/// Add an GroupMember record
/// </summary>
/// <param name="entity"></param>
/// <param name="statusMessage"></param>
/// <returns></returns>
public static int Create( GroupMember entity, ref string statusMessage )
{
string connectionString = GatewayConnection();
int newId = 0;
try
{
#region parameters
SqlParameter[] sqlParameters = new SqlParameter[ 7 ];
sqlParameters[ 0 ] = new SqlParameter( "@GroupId", entity.GroupId );
sqlParameters[ 1 ] = new SqlParameter( "@UserId", entity.UserId );
sqlParameters[ 2 ] = new SqlParameter( "@Status", entity.Status );
sqlParameters[ 3 ] = new SqlParameter( "@Category", entity.Category );
sqlParameters[ 4 ] = new SqlParameter( "@IsActive", entity.IsActive );
sqlParameters[ 5 ] = new SqlParameter( "@Comment", entity.Comment );
sqlParameters[ 6 ] = new SqlParameter( "@CreatedById", entity.CreatedById );
#endregion
SqlDataReader dr = SqlHelper.ExecuteReader( connectionString, CommandType.StoredProcedure, INSERT_PROC, sqlParameters );
if ( dr.HasRows )
{
dr.Read();
newId = int.Parse( dr[ 0 ].ToString() );
}
dr.Close();
dr = null;
statusMessage = "successful";
} catch ( Exception ex )
{
LogError( ex, className + ".Insert() " );
statusMessage = className + "- Unsuccessful: Insert(): " + ex.Message.ToString();
entity.Message = statusMessage;
entity.IsValid = false;
}
return newId;
}
/// <summary>
/// /// Update an GroupMember record
/// </summary>
/// <param name="entity"></param>
/// <returns></returns>
public static string Update( GroupMember entity )
{
string message = "successful";
#region parameters
SqlParameter[] sqlParameters = new SqlParameter[ 6 ];
sqlParameters[ 0 ] = new SqlParameter( "@ID", entity.Id);
sqlParameters[ 1 ] = new SqlParameter( "@Status", entity.Status );
sqlParameters[ 2 ] = new SqlParameter( "@Category", entity.Category );
sqlParameters[ 3 ] = new SqlParameter( "@IsActive", entity.IsActive );
sqlParameters[ 4 ] = new SqlParameter( "@Comment", entity.Comment );
sqlParameters[ 5 ] = new SqlParameter( "@LastUpdatedById", entity.LastUpdatedById );
#endregion
try
{
SqlHelper.ExecuteNonQuery( GatewayConnection(), UPDATE_PROC, sqlParameters );
message = "successful";
} catch ( Exception ex )
{
LogError( ex, className + ".Update() " );
message = className + "- Unsuccessful: Update(): " + ex.Message.ToString();
entity.Message = message;
entity.IsValid = false;
}
return message;
}//
#endregion
#region ====== Retrieval Methods ===============================================
/// <summary>
/// Get GroupMember record by Id
/// </summary>
/// <param name="pId"></param>
/// <returns></returns>
public static GroupMember Get( int pId )
{
int userId = 0;
int groupId = 0;
string groupCode = "";
return Get( pId, userId, groupId, groupCode );
}//
/// <summary>
/// Get GroupMember record by userId and group code
/// </summary>
/// <param name="userId"></param>
/// <param name="groupCode"></param>
/// <returns></returns>
public static GroupMember GetByGroupCode( string groupCode )
{
int userId = 0;
int pId = 0;
int groupId = 0;
return Get( pId, userId, groupId, groupCode );
}//
public static GroupMember GetByGroupCode( int userId, string groupCode )
{
int pId = 0;
int groupId = 0;
return Get( pId, userId, groupId, groupCode );
}//
/// <summary>
/// Get GroupMember record by userId and group Id
/// </summary>
/// <param name="userId"></param>
/// <param name="groupId"></param>
/// <returns></returns>
public static GroupMember GetByGroupId( int userId, int groupId )
{
int pId = 0;
string groupCode = "";
return Get( pId, userId, groupId, groupCode );
}//
/// <summary>
/// Get GroupMember record by Id or userId and (group Id or group code)
/// </summary>
/// <param name="pId"></param>
/// <param name="userId"></param>
/// <param name="groupId"></param>
/// <param name="groupCode"></param>
/// <returns></returns>
private static GroupMember Get( int pId, int userId, int groupId, string groupCode )
{
string connectionString = GatewayConnectionRO();
GroupMember entity = new GroupMember();
try
{
SqlParameter[] sqlParameters = new SqlParameter[ 4 ];
sqlParameters[ 0 ] = new SqlParameter( "@Id", pId );
sqlParameters[ 1 ] = new SqlParameter( "@UserId", userId );
sqlParameters[ 2 ] = new SqlParameter( "@GroupId", groupId );
sqlParameters[ 3 ] = new SqlParameter( "@GroupCode", groupCode );
SqlDataReader dr = SqlHelper.ExecuteReader( connectionString, GET_PROC, sqlParameters );
if ( dr.HasRows )
{
// it should return only one record.
while ( dr.Read() )
{
entity = Fill( dr );
}
} else
{
entity.Message = "Record not found";
entity.IsValid = false;
}
dr.Close();
dr = null;
return entity;
} catch ( Exception ex )
{
LogError( ex, className + ".Get() " );
entity.Message = className + "- Unsuccessful: Get(): " + ex.ToString();
entity.IsValid = false;
return entity;
}
}//
/// <summary>
/// Return true if user is a member of a group for the provided group id
/// </summary>
/// <param name="groupId"></param>
/// <param name="userid"></param>
/// <returns></returns>
public static bool IsAGroupMember( int groupId, int userid )
{
string groupCode = "";
return IsAGroupMember( groupId, userid, groupCode );
}//
/// <summary>
/// Return true if user is a member of the target group based on group code
/// </summary>
/// <param name="groupCode"></param>
/// <param name="userid"></param>
/// <returns></returns>
public static bool IsAGroupMember( string groupCode, int userid )
{
int groupId = 0;
return IsAGroupMember( groupId, userid, groupCode );
}//
/// <summary>
/// Return true if user is a member of the target group
/// </summary>
/// <param name="groupId"></param>
/// <param name="userid"></param>
/// <param name="groupCode"></param>
/// <param name="programCode"></param>
/// <returns></returns>
private static bool IsAGroupMember( int groupId, int userid, string groupCode )
{
bool isMember = false;
int createdById = 0;
try
{
DataSet ds = Select( groupId, userid, groupCode, createdById );
if ( DoesDataSetHaveRows(ds) == true)
isMember = true;
} catch ( Exception ex )
{
LogError( ex, className + ".IsGroupMember(" + userid + ") exception " );
}
return isMember;
}//
/// <summary>
/// Select GroupMember related data using passed groupId
/// </summary>
/// <param name="groupId"></param>
/// <returns></returns>
public static DataSet Select( int groupId )
{
int createdById = 0;
return Select( groupId, 0, "", createdById );
}//
/// <summary>
/// Select GroupMember related data using passed parameters
/// - where userid is owner
/// - where userid is a team member of the group (id is provided)
/// - where userid is a team member of any group (id is zero)
/// - where groups of a particular type are wanted (groupCode)
/// - future may be to filter on privileges, etc.
/// </summary>
/// <param name="userid"></param>
/// <param name="groupId"></param>
/// <param name="groupCode"></param>
/// <param name="orgId"></param>
/// <returns></returns>
public static DataSet Select( int groupId, int userid, string groupCode )
{
int createdById = 0;
return Select( groupId, userid, groupCode, createdById );
}//
/// <summary>
/// Select GroupMember related data using passed parameters
/// - where userid is owner
/// - where userid is a team member of the group (id is provided)
/// - where userid is a team member of any group (id is zero)
/// - where groups of a particular type are wanted (groupCode)
/// - future may be to filter on privileges, etc.
/// </summary>
/// <param name="userid"></param>
/// <param name="groupId"></param>
/// <param name="groupCode"></param>
/// <param name="orgId"></param>
/// <param name="createdById">Use to only retrieve customers that were created by this userid</param>
/// <param name="programCode"></param>
/// <returns></returns>
public static DataSet Select( int groupId, int userid, string groupCode, int createdById)
{
string connectionString = GatewayConnectionRO();
SqlParameter[] sqlParameters = new SqlParameter[ 4 ];
sqlParameters[ 0 ] = new SqlParameter( "@GroupId", groupId );
sqlParameters[ 1 ] = new SqlParameter( "@userId", userid );
sqlParameters[ 2 ] = new SqlParameter( "@GroupCode", groupCode );
sqlParameters[ 3 ] = new SqlParameter( "@CreatedById", createdById );
DataSet ds = new DataSet();
try
{
ds = SqlHelper.ExecuteDataset( connectionString, CommandType.StoredProcedure, SELECT_PROC, sqlParameters );
if ( ds.HasErrors )
{
return null;
}
return ds;
} catch ( Exception ex )
{
LogError( ex, className + ".Select() " );
return null;
}
}
/// <summary>
/// return true if user is a valid approver for the organization
/// </summary>
/// <param name="pOrgId"></param>
/// <param name="userId"></param>
/// <returns></returns>
public static bool IsUserAnOrgApprover( int pOrgId, int userId )
{
bool isValid = false;
List<GroupMember> list = OrgApproversSelect( pOrgId );
if ( list != null && list.Count > 0 )
{
foreach ( GroupMember item in list )
{
if ( item.UserId == userId )
{
isValid = true;
break;
}
}
}
return isValid;
}
public static List<GroupMember> OrgApproversSelect( int orgId )
{
List<GroupMember> collection = new List<GroupMember>();
string connectionString = GatewayConnectionRO();
SqlParameter[] sqlParameters = new SqlParameter[ 1 ];
sqlParameters[ 0 ] = new SqlParameter( "@OrgId", orgId );
DataSet ds = new DataSet();
try
{
ds = SqlHelper.ExecuteDataset( connectionString, CommandType.StoredProcedure, "[AppGroup.OrgApproversSelect]", sqlParameters );
if ( DoesDataSetHaveRows( ds ) )
{
foreach ( DataRow dr in ds.Tables[ 0 ].Rows )
{
GroupMember entity = Fill( dr );
collection.Add( entity );
}
}
return collection;
}
catch ( Exception ex )
{
LogError( ex, className + ".OrgApproversSelect() " );
return null;
}
}
/// <summary>
/// Select Group Members
/// </summary>
/// <param name="pGroupId"></param>
/// <param name="pUserid"></param>
/// <param name="pGroupCode"></param>
/// <param name="pCreatedById"></param>
/// <param name="pStartPageIndex"></param>
/// <param name="pMaximumRows"></param>
/// <param name="pTotalRows"></param>
/// <returns></returns>
public static DataSet Search( int pGroupId, int pUserid, string pGroupCode, int pCreatedById, int pStartPageIndex, int pMaximumRows, ref int pTotalRows )
{
string booleanOperator = "AND";
string filter = "";
//construct filter
if ( pGroupId > 0 )
filter = FormatSearchItem( filter, "GroupId", pGroupId.ToString(), booleanOperator );
if ( pUserid > 0 )
filter = FormatSearchItem( filter, "ContactId", pUserid.ToString(), booleanOperator );
if ( pGroupCode.Trim().Length > 0 )
filter = FormatSearchItem( filter, "GroupCode", pGroupCode, booleanOperator );
if ( pCreatedById > 0 )
filter = FormatSearchItem( filter, "gm.CreatedById", pCreatedById.ToString(), booleanOperator );
return Search( filter, "", pStartPageIndex, pMaximumRows, ref pTotalRows );
}
/// <summary>
/// Select Group Members
/// </summary>
/// <param name="pFilter"></param>
/// <param name="pStartPageIndex"></param>
/// <param name="pMaximumRows"></param>
/// <param name="pTotalRows"></param>
/// <returns></returns>
public static DataSet Search( string pFilter, string pSortOrder, int pStartPageIndex, int pMaximumRows, ref int pTotalRows )
{
string connectionString = GatewayConnectionRO();
if ( pFilter.Length > 0 )
pFilter = " Where " + pFilter;
SqlParameter[] sqlParameters = new SqlParameter[ 5 ];
sqlParameters[ 0 ] = new SqlParameter( "@Filter", pFilter );
sqlParameters[ 1 ] = new SqlParameter( "@SortOrder", pSortOrder );
sqlParameters[ 2 ] = new SqlParameter( "@StartPageIndex", pStartPageIndex);
sqlParameters[ 3 ] = new SqlParameter( "@PageSize", pMaximumRows);
sqlParameters[ 4 ] = new SqlParameter( "@TotalRows", SqlDbType.Int );
sqlParameters[ 4 ].Direction = ParameterDirection.Output;
DataSet ds = new DataSet();
try
{
ds = SqlHelper.ExecuteDataset( connectionString, CommandType.StoredProcedure, SEARCH_PROC, sqlParameters );
string rows = sqlParameters[ 3 ].Value.ToString();
try
{
pTotalRows = Int32.Parse( rows );
}
catch
{
pTotalRows = 0;
}
if ( ds.HasErrors )
{
return null;
}
return ds;
}
catch ( Exception ex )
{
LogError( ex, className + ".Search() " );
return null;
}
}
/// <summary>
/// future use
/// </summary>
/// <param name="pFilter"></param>
/// <param name="pOrderBy"></param>
/// <param name="pStartPageIndex"></param>
/// <param name="pMaximumRows"></param>
/// <param name="pTotalRows"></param>
/// <returns></returns>
private static DataSet ExternalGroupMember_Search( string pFilter, string pOrderBy, int pStartPageIndex, int pMaximumRows, ref int pTotalRows )
{
string connectionString = GatewayConnectionRO();
if ( pFilter.Length > 0 )
pFilter = " Where " + pFilter;
SqlParameter[] sqlParameters = new SqlParameter[ 5 ];
sqlParameters[ 0 ] = new SqlParameter( "@Filter", pFilter );
sqlParameters[ 1 ] = new SqlParameter( "@OrderBy", pOrderBy );
sqlParameters[ 2 ] = new SqlParameter( "@StartPageIndex", SqlDbType.Int );
sqlParameters[ 2 ].Value = pStartPageIndex;
sqlParameters[ 3 ] = new SqlParameter( "@PageSize", SqlDbType.Int );
sqlParameters[ 3 ].Value = pMaximumRows;
sqlParameters[ 4 ] = new SqlParameter( "@TotalRows", SqlDbType.Int );
sqlParameters[ 4 ].Direction = ParameterDirection.Output;
DataSet ds = new DataSet();
try
{
ds = SqlHelper.ExecuteDataset( connectionString, CommandType.StoredProcedure, "[AppGroup.ExternalGroupMember_Search]", sqlParameters );
string rows = sqlParameters[ 4 ].Value.ToString();
try
{
pTotalRows = Int32.Parse( rows );
} catch
{
pTotalRows = 0;
}
if ( ds.HasErrors )
{
return null;
}
return ds;
} catch ( Exception ex )
{
LogError( ex, className + ".ExternalGroupMember_Search() " );
return null;
}
}
#endregion
#region ====== Helper Methods ===============================================
/// <summary>
/// Select Group Members
/// </summary>
/// <param name="pFilter"></param>
/// <param name="pStartPageIndex"></param>
/// <param name="pMaximumRows"></param>
/// <param name="pTotalRows"></param>
/// <returns></returns>
public static DataSet GroupOrgMbrSearch( string pFilter, string pSortOrder, int pStartPageIndex, int pMaximumRows, ref int pTotalRows )
{
string connectionString = GatewayConnectionRO();
if ( pFilter.Length > 0 )
pFilter = " Where " + pFilter;
SqlParameter[] sqlParameters = new SqlParameter[ 5 ];
sqlParameters[ 0 ] = new SqlParameter( "@Filter", pFilter );
sqlParameters[ 1 ] = new SqlParameter( "@SortOrder", pSortOrder );
sqlParameters[ 2 ] = new SqlParameter( "@StartPageIndex", pStartPageIndex );
sqlParameters[ 3 ] = new SqlParameter( "@PageSize", pMaximumRows );
sqlParameters[ 4 ] = new SqlParameter( "@TotalRows", SqlDbType.Int );
sqlParameters[ 4 ].Direction = ParameterDirection.Output;
DataSet ds = new DataSet();
try
{
ds = SqlHelper.ExecuteDataset( connectionString, CommandType.StoredProcedure, "[AppGroup.OrgMemberSearch]", sqlParameters );
string rows = sqlParameters[ 3 ].Value.ToString();
try
{
pTotalRows = Int32.Parse( rows );
}
catch
{
pTotalRows = 0;
}
if ( ds.HasErrors )
{
return null;
}
return ds;
}
catch ( Exception ex )
{
LogError( ex, className + ".GroupOrgMbrSearch() " );
return null;
}
}
#endregion
#region ====== Helper Methods ===============================================
/// <summary>
/// Fill an GroupMember object from a data reader
/// </summary>
/// <param name="dr">SqlDataReader</param>
/// <returns>GroupMember</returns>
public static GroupMember Fill( SqlDataReader dr )
{
GroupMember entity = new GroupMember();
entity.IsValid = true;
entity.GroupId = GetRowColumn( dr, "groupId", 0 );
entity.UserId = GetRowColumn( dr, "UserId", 0 );
entity.Id = GetRowColumn( dr, "id", 0 );
entity.Status = GetRowColumn( dr, "status", "" );
entity.Category = GetRowColumn( dr, "category", "" );
entity.Comment = GetRowColumn( dr, "comment", "" );
entity.IsActive = GetRowColumn( dr, "isActive", false );
entity.Created = GetRowColumn( dr, "created", System.DateTime.MinValue );
entity.LastUpdated = GetRowColumn( dr, "lastUpdated", System.DateTime.MinValue );
entity.CreatedById = GetRowColumn( dr, "CreatedById", 0 );
entity.LastUpdatedById = GetRowColumn( dr, "LastUpdatedById", 0 );
//get associated AppUser
//if ( entity.UserId > 0 )
//{
// AppUser user = new UserManager().Get( entity.UserId );
// if ( user != null && user.IsValid )
// {
// entity.RelatedAppUser = user;
// entity.FullName = user.FullName();
// entity.SortName = user.SortName();
// }
//} else
//{
// entity.FullName = GetRowColumn( dr, "FullName", "" );
// entity.SortName = GetRowColumn( dr, "SortName", "" );
//}
entity.FullName = GetRowColumn( dr, "FullName", "" );
entity.SortName = GetRowColumn( dr, "SortName", "" );
entity.UserEmail = GetRowColumn( dr, "UserEmail", "" );
//additional derived properties
entity.GroupName = GetRowColumn( dr, "GroupName", "" );
entity.GroupCode = GetRowColumn( dr, "GroupCode", "" );
return entity;
}//
public static GroupMember Fill( DataRow dr )
{
GroupMember entity = new GroupMember();
entity.IsValid = true;
entity.GroupId = GetRowColumn( dr, "groupId", 0 );
entity.UserId = GetRowColumn( dr, "UserId", 0 );
entity.Id = GetRowColumn( dr, "id", 0 );
entity.Status = GetRowColumn( dr, "status", "" );
entity.Category = GetRowColumn( dr, "category", "" );
entity.Comment = GetRowColumn( dr, "comment", "" );
entity.IsActive = GetRowColumn( dr, "isActive", false );
entity.Created = GetRowColumn( dr, "created", System.DateTime.MinValue );
entity.LastUpdated = GetRowColumn( dr, "lastUpdated", System.DateTime.MinValue );
entity.CreatedById = GetRowColumn( dr, "CreatedById", 0 );
entity.LastUpdatedById = GetRowColumn( dr, "LastUpdatedById", 0 );
//get associated AppUser
//if ( entity.UserId > 0 )
//{
// AppUser user = new UserManager().Get( entity.UserId );
// if ( user != null && user.IsValid )
// {
// entity.RelatedAppUser = user;
// entity.FullName = user.FullName();
// entity.SortName = user.SortName();
// }
//} else
//{
// entity.FullName = GetRowColumn( dr, "FullName", "" );
// entity.SortName = GetRowColumn( dr, "SortName", "" );
//}
entity.FullName = GetRowColumn( dr, "FullName", "" );
entity.SortName = GetRowColumn( dr, "SortName", "" );
entity.UserEmail = GetRowColumn( dr, "UserEmail", "" );
//additional derived properties
entity.GroupName = GetRowColumn( dr, "GroupName", "" );
entity.GroupCode = GetRowColumn( dr, "GroupCode", "" );
return entity;
}//
#endregion
}
}
| |
using System;
using System.Collections;
using System.Data;
using PCSComProduct.Items.DS;
using PCSComUtils.MasterSetup.DS;
using PCSComUtils.PCSExc;
using PCSComUtils.Common;
using PCSComProcurement.Purchase.DS;
namespace PCSComProcurement.Purchase.BO
{
public interface IPOItemVendorCrossReferenceBO
{
DataSet List(int pintVendorID, int pintVedorLocID, int pintCCNID);
object GetPartyInfo(int pintPartyID);
DataTable GetAllLocation(int pintPartyID);
DataTable GetRows(string pstrTableName, string pstrExpression);
object GetProductInfo(int pintProductID);
object GetObjectVO(int pintPartyID, int pintProductID);
int AddAndReturnID(object pObjectDetail);
void DeleteItemVendor(int pintPartyID, int pintProductID);
}
/// <summary>
/// Summary description for .
/// </summary>
public class POItemVendorCrossReferenceBO :IPOItemVendorCrossReferenceBO
{
private const string THIS = "PCSComProcurement.Purchase.BO.POItemVendorCrossReferenceBO";
public POItemVendorCrossReferenceBO()
{
//
// TODO: Add constructor logic here
//
}
public void Add(object pObjectDetail)
{
// TODO:
}
public void Delete(object pObjectVO)
{
// TODO:
}
public object GetObjectVO(int pintID, string VOclass)
{
// TODO:
return null;
}
//**************************************************************************
/// <Description>
/// update object
/// </Description>
/// <Inputs>
/// object
/// </Inputs>
/// <Outputs>
///
/// </Outputs>
/// <Returns>
/// N/A
/// </Returns>
/// <Authors>
/// DungLA
/// </Authors>
/// <History>
/// 05-Apr-2005
/// </History>
/// <Notes>
/// </Notes>
//**************************************************************************
public void Update(object pObjectDetail)
{
try
{
PO_ItemVendorReferenceDS dsItemVendor = new PO_ItemVendorReferenceDS();
dsItemVendor.Update(pObjectDetail);
}
catch (PCSException ex)
{
throw ex;
}
catch (Exception ex)
{
throw ex;
}
}
public void UpdateDataSet(DataSet dstData)
{
// TODO:
}
//**************************************************************************
/// <Description>
/// list all record in ItemVedorCrossReference table by VendorID, VendorLocationID
/// </Description>
/// <Inputs>
/// VendorID, VendorLocID, CCNID
/// </Inputs>
/// <Outputs>
///
/// </Outputs>
/// <Returns>
/// DataSet
/// </Returns>
/// <Authors>
/// DungLA
/// </Authors>
/// <History>
/// 04-Apr-2005
/// </History>
/// <Notes>
/// </Notes>
//**************************************************************************
public DataSet List(int pintVendorID, int pintVedorLocID, int pintCCNID)
{
try
{
PO_ItemVendorReferenceDS dsVendorCross = new PO_ItemVendorReferenceDS();
return dsVendorCross.List(pintVendorID, pintVedorLocID, pintCCNID);
}
catch (PCSException ex)
{
throw ex;
}
catch (Exception ex)
{
throw ex;
}
}
//**************************************************************************
/// <Description>
/// list Party Information
/// </Description>
/// <Inputs>
/// VendorID
/// </Inputs>
/// <Outputs>
///
/// </Outputs>
/// <Returns>
/// object
/// </Returns>
/// <Authors>
/// DungLA
/// </Authors>
/// <History>
/// 04-Apr-2005
/// </History>
/// <Notes>
/// </Notes>
//**************************************************************************
public object GetPartyInfo(int pintPartyID)
{
try
{
MST_PartyDS dsParty = new MST_PartyDS();
return dsParty.GetObjectVO(pintPartyID);
}
catch (PCSException ex)
{
throw ex;
}
catch (Exception ex)
{
throw ex;
}
}
//**************************************************************************
/// <Description>
/// list all location of specified Party
/// </Description>
/// <Inputs>
/// PartyID
/// </Inputs>
/// <Outputs>
///
/// </Outputs>
/// <Returns>
/// DataTable
/// </Returns>
/// <Authors>
/// DungLA
/// </Authors>
/// <History>
/// 04-Apr-2005
/// </History>
/// <Notes>
/// </Notes>
//**************************************************************************
public DataTable GetAllLocation(int pintPartyID)
{
try
{
MST_PartyLocationDS dsPartyLocation = new MST_PartyLocationDS();
return dsPartyLocation.ListPartyLocation(pintPartyID).Tables[0];
}
catch (PCSException ex)
{
throw ex;
}
catch (Exception ex)
{
throw ex;
}
}
//**************************************************************************
/// <Description>
/// This method uses to get ITM_ProductVO object
/// </Description>
/// <Inputs>
/// int Id
/// </Inputs>
/// <Outputs>
///
/// </Outputs>
/// <Returns>
/// ITM_ProductVO
/// </Returns>
/// <Authors>
/// DungLa
/// </Authors>
/// <History>
/// 10-Mar-2005
/// </History>
/// <Notes>
/// </Notes>
//**************************************************************************
public object GetProductInfo(int pintProductID)
{
try
{
ITM_ProductDS dsProduct = new ITM_ProductDS();
return dsProduct.GetProductInfo(pintProductID);
}
catch (PCSException ex)
{
throw ex;
}
catch (Exception ex)
{
throw ex;
}
}
//**************************************************************************
/// <Description>
/// This method uses to get ItemVendorCrossReference object
/// </Description>
/// <Inputs>
/// PartyID, ProductID
/// </Inputs>
/// <Outputs>
///
/// </Outputs>
/// <Returns>
/// object
/// </Returns>
/// <Authors>
/// DungLa
/// </Authors>
/// <History>
/// 05-Apr-2005
/// </History>
/// <Notes>
/// </Notes>
//**************************************************************************
public object GetObjectVO(int pintPartyID, int pintProductID)
{
try
{
PO_ItemVendorReferenceDS dsItemVendor = new PO_ItemVendorReferenceDS();
return dsItemVendor.GetObjectVO(pintPartyID, pintProductID);
}
catch (PCSException ex)
{
throw ex;
}
catch (Exception ex)
{
throw ex;
}
}
//**************************************************************************
/// <Description>
/// This method uses to add new object and return new ID
/// </Description>
/// <Inputs>
/// object
/// </Inputs>
/// <Outputs>
///
/// </Outputs>
/// <Returns>
/// new ID
/// </Returns>
/// <Authors>
/// DungLa
/// </Authors>
/// <History>
/// 05-Apr-2005
/// </History>
/// <Notes>
/// </Notes>
//**************************************************************************
public int AddAndReturnID(object pObjectDetail)
{
try
{
PO_ItemVendorReferenceDS dsItemVendor = new PO_ItemVendorReferenceDS();
return dsItemVendor.AddAndReturnID(pObjectDetail);
}
catch (PCSException ex)
{
throw ex;
}
catch (Exception ex)
{
throw ex;
}
}
//**************************************************************************
/// <Description>
/// This method is used to get the DataTable result
/// from a specific table with a specific search field key
/// This function will be used on form that need to search for ID from Code, Name
/// such as Product Code, or Product description
/// </Description>
/// <Inputs>
/// TableName, Expression
/// </Inputs>
/// <Outputs>
///
/// </Outputs>
/// <Returns>
/// DataTable
/// </Returns>
/// <Authors>
/// DungLa
/// </Authors>
/// <History>
/// 07-Apr-2005
/// </History>
/// <Notes>
/// </Notes>
//**************************************************************************
public DataTable GetRows(string pstrTableName, string pstrExpression)
{
try
{
PO_ItemVendorReferenceDS dsItemVendor = new PO_ItemVendorReferenceDS();
return dsItemVendor.GetRows(pstrTableName, pstrExpression);
}
catch (PCSException ex)
{
throw ex;
}
catch (Exception ex)
{
throw ex;
}
}
public void DeleteItemVendor(int pintPartyID, int pintProductID)
{
try
{
PO_ItemVendorReferenceDS objPO_ItemVendorReferenceDS = new PO_ItemVendorReferenceDS();
objPO_ItemVendorReferenceDS.DeleteItemVendor(pintPartyID,pintProductID);
}
catch (PCSException ex)
{
throw ex;
}
catch (Exception ex)
{
throw ex;
}
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using Buildalyzer.Environment;
using LibGit2Sharp;
using Microsoft.Build.Construction;
using Microsoft.Build.Framework;
using NUnit.Framework;
using Shouldly;
namespace Buildalyzer.Tests.Integration
{
[TestFixture]
[NonParallelizable]
public class OpenSourceProjectsFixture
{
private const bool BinaryLog = false;
private static readonly EnvironmentPreference[] Preferences =
{
#if Is_Windows
EnvironmentPreference.Framework,
#endif
EnvironmentPreference.Core
};
private static readonly TestRepository[] Repositories =
{
new TestRepository("https://github.com/cake-build/cake"),
new TestRepository("https://github.com/statiqdev/Statiq.Framework.git")
};
public class TestRepository
{
public EnvironmentPreference? Preference { get; }
public string Url { get; }
public string[] Excluded { get; }
public TestRepository(string url, params string[] excluded)
: this(null, url, excluded)
{
}
public TestRepository(EnvironmentPreference? preference, string url, params string[] excluded)
{
Preference = preference;
Url = url;
Excluded = excluded?.Select(x => x.Replace('\\', Path.DirectorySeparatorChar)).ToArray() ?? Array.Empty<string>();
}
public override string ToString() => Url;
}
private static readonly List<object[]> ProjectTestCases = new List<object[]>();
// Do setup in a static constructor since the TestCaseSource depends on it
// See https://stackoverflow.com/a/40507964/807064
static OpenSourceProjectsFixture()
{
foreach (TestRepository repository in Repositories)
{
string path = GetRepositoryPath(repository.Url);
CloneRepository(repository.Url, path);
}
// Iterate all repositories
foreach (TestRepository repository in Repositories)
{
// Iterate all available preferences
foreach (EnvironmentPreference preference in Preferences)
{
// Only build the desired preferences
if (!repository.Preference.HasValue || repository.Preference.Value == preference)
{
// Iterate all solution files in the repository
foreach (string solutionPath in
Directory.EnumerateFiles(GetRepositoryPath(repository.Url), "*.sln", SearchOption.AllDirectories))
{
// Exclude any solution files we don't want to build
if (!repository.Excluded.Any(x => solutionPath.EndsWith(x)))
{
// Get all the projects in this solution
SolutionFile solutionFile = SolutionFile.Parse(solutionPath);
foreach (string projectPath in
solutionFile.ProjectsInOrder
.Where(x => AnalyzerManager.SupportedProjectTypes.Contains(x.ProjectType))
.Select(x => x.AbsolutePath))
{
// Exclude any project files we don't want to build
if (!repository.Excluded.Any(x => projectPath.EndsWith(x)))
{
ProjectTestCases.Add(new object[]
{
preference,
solutionPath,
projectPath
});
}
}
}
}
}
}
}
}
[TestCaseSource(nameof(ProjectTestCases))]
public void CompilesProject(EnvironmentPreference preference, string solutionPath, string projectPath)
{
// Given
StringWriter log = new StringWriter();
AnalyzerManager manager = new AnalyzerManager(solutionPath, new AnalyzerManagerOptions
{
LogWriter = log
});
IProjectAnalyzer analyzer = manager.GetProject(projectPath);
EnvironmentOptions options = new EnvironmentOptions
{
Preference = preference
};
// Set some environment variables to make it seem like we're not in a CI build
// Sometimes this messes up libraries like SourceLink since we're building as part of a test and not for CI
options.EnvironmentVariables.Add("APPVEYOR", "False");
options.EnvironmentVariables.Add("ContinuousIntegrationBuild", null);
options.EnvironmentVariables.Add("CI", "False");
options.EnvironmentVariables.Add("CI_LINUX", "False");
options.EnvironmentVariables.Add("CI_WINDOWS", "False");
// When
DeleteProjectDirectory(analyzer.ProjectFile.Path, "obj");
DeleteProjectDirectory(analyzer.ProjectFile.Path, "bin");
analyzer.IgnoreFaultyImports = false;
#pragma warning disable 0162
if (BinaryLog)
{
analyzer.AddBinaryLogger($@"C:\Temp\{Path.GetFileNameWithoutExtension(solutionPath)}.{Path.GetFileNameWithoutExtension(analyzer.ProjectFile.Path)}.core.binlog");
}
#pragma warning restore 0162
#if Is_Windows
IAnalyzerResults results = analyzer.Build(options);
#else
// On non-Windows platforms we have to remove the .NET Framework target frameworks and only build .NET Core target frameworks
// See https://github.com/dotnet/sdk/issues/826
string[] excludedTargetFrameworks = new[] { "net2", "net3", "net4", "portable" };
string[] targetFrameworks = analyzer.ProjectFile.TargetFrameworks.Where(x => !excludedTargetFrameworks.Any(y => x.StartsWith(y))).ToArray();
if (targetFrameworks.Length == 0)
{
Assert.Ignore();
}
IAnalyzerResults results = analyzer.Build(targetFrameworks, options);
#endif
// Then
results.Count.ShouldBeGreaterThan(0, log.ToString());
results.OverallSuccess.ShouldBeTrue(log.ToString());
results.ShouldAllBe(x => x.Succeeded, log.ToString());
}
private static void CloneRepository(string repository, string path)
{
if (!Directory.Exists(path))
{
TestContext.Progress.WriteLine($"Cloning {path}");
Directory.CreateDirectory(path);
string clonedPath = Repository.Clone(repository, path);
TestContext.Progress.WriteLine($"Cloned into {clonedPath}");
}
else if (!Repository.IsValid(path))
{
TestContext.Progress.WriteLine($"Recloning {path}");
Directory.Delete(path, true);
Thread.Sleep(1000);
Directory.CreateDirectory(path);
string clonedPath = Repository.Clone(repository, path);
TestContext.Progress.WriteLine($"Cloned into {clonedPath}");
}
else
{
TestContext.Progress.WriteLine($"Updating {path}");
Repository repo = new Repository(path);
foreach (Remote remote in repo.Network.Remotes)
{
IEnumerable<string> refSpecs = remote.FetchRefSpecs.Select(x => x.Specification);
Commands.Fetch(repo, remote.Name, refSpecs, null, string.Empty);
}
}
}
private static string GetRepositoryPath(string repository)
{
string path = Path.GetFullPath(
Path.Combine(
Path.GetDirectoryName(typeof(OpenSourceProjectsFixture).Assembly.Location),
@"..\..\..\..\repos\" + Path.GetFileNameWithoutExtension(repository)));
return path.Replace('\\', Path.DirectorySeparatorChar);
}
private static void DeleteProjectDirectory(string projectPath, string directory)
{
string path = Path.Combine(Path.GetDirectoryName(projectPath), directory);
if (Directory.Exists(path))
{
Directory.Delete(path, true);
}
}
}
}
| |
// 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.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Threading;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CodeGeneration;
using Microsoft.CodeAnalysis.Editing;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.GenerateType
{
internal abstract partial class AbstractGenerateTypeService<TService, TSimpleNameSyntax, TObjectCreationExpressionSyntax, TExpressionSyntax, TTypeDeclarationSyntax, TArgumentSyntax>
{
internal abstract IMethodSymbol GetDelegatingConstructor(
SemanticDocument document,
TObjectCreationExpressionSyntax objectCreation,
INamedTypeSymbol namedType,
ISet<IMethodSymbol> candidates,
CancellationToken cancellationToken);
private partial class Editor
{
private INamedTypeSymbol GenerateNamedType()
{
return CodeGenerationSymbolFactory.CreateNamedTypeSymbol(
DetermineAttributes(),
DetermineAccessibility(),
DetermineModifiers(),
DetermineTypeKind(),
DetermineName(),
DetermineTypeParameters(),
DetermineBaseType(),
DetermineInterfaces(),
members: DetermineMembers());
}
private INamedTypeSymbol GenerateNamedType(GenerateTypeOptionsResult options)
{
if (options.TypeKind == TypeKind.Delegate)
{
return CodeGenerationSymbolFactory.CreateDelegateTypeSymbol(
DetermineAttributes(),
options.Accessibility,
DetermineModifiers(),
DetermineReturnType(options),
returnsByRef: false,
name: options.TypeName,
typeParameters: DetermineTypeParameters(options),
parameters: DetermineParameters(options));
}
return CodeGenerationSymbolFactory.CreateNamedTypeSymbol(
DetermineAttributes(),
options.Accessibility,
DetermineModifiers(),
options.TypeKind,
options.TypeName,
DetermineTypeParameters(),
DetermineBaseType(),
DetermineInterfaces(),
members: DetermineMembers(options));
}
private ITypeSymbol DetermineReturnType(GenerateTypeOptionsResult options)
{
if (_state.DelegateMethodSymbol == null ||
_state.DelegateMethodSymbol.ReturnType == null ||
_state.DelegateMethodSymbol.ReturnType is IErrorTypeSymbol)
{
// Since we cannot determine the return type, we are returning void
return _state.Compilation.GetSpecialType(SpecialType.System_Void);
}
else
{
return _state.DelegateMethodSymbol.ReturnType;
}
}
private ImmutableArray<ITypeParameterSymbol> DetermineTypeParameters(GenerateTypeOptionsResult options)
{
if (_state.DelegateMethodSymbol != null)
{
return _state.DelegateMethodSymbol.TypeParameters;
}
// If the delegate symbol cannot be determined then
return DetermineTypeParameters();
}
private ImmutableArray<IParameterSymbol> DetermineParameters(GenerateTypeOptionsResult options)
{
if (_state.DelegateMethodSymbol != null)
{
return _state.DelegateMethodSymbol.Parameters;
}
return default(ImmutableArray<IParameterSymbol>);
}
private ImmutableArray<ISymbol> DetermineMembers(GenerateTypeOptionsResult options = null)
{
var members = ArrayBuilder<ISymbol>.GetInstance();
AddMembers(members, options);
if (_state.IsException)
{
AddExceptionConstructors(members);
}
return members.ToImmutableAndFree();
}
private void AddMembers(ArrayBuilder<ISymbol> members, GenerateTypeOptionsResult options = null)
{
AddProperties(members);
if (!_service.TryGetArgumentList(_state.ObjectCreationExpressionOpt, out var argumentList))
{
return;
}
var parameterTypes = GetArgumentTypes(argumentList);
// Don't generate this constructor if it would conflict with a default exception
// constructor. Default exception constructors will be added automatically by our
// caller.
if (_state.IsException &&
_state.BaseTypeOrInterfaceOpt.InstanceConstructors.Any(
c => c.Parameters.Select(p => p.Type).SequenceEqual(parameterTypes)))
{
return;
}
// If there's an accessible base constructor that would accept these types, then
// just call into that instead of generating fields.
if (_state.BaseTypeOrInterfaceOpt != null)
{
if (_state.BaseTypeOrInterfaceOpt.TypeKind == TypeKind.Interface && argumentList.Count == 0)
{
// No need to add the default constructor if our base type is going to be
// 'object'. We get that constructor for free.
return;
}
var accessibleInstanceConstructors = _state.BaseTypeOrInterfaceOpt.InstanceConstructors.Where(
IsSymbolAccessible).ToSet();
if (accessibleInstanceConstructors.Any())
{
var delegatedConstructor = _service.GetDelegatingConstructor(
_document,
_state.ObjectCreationExpressionOpt,
_state.BaseTypeOrInterfaceOpt,
accessibleInstanceConstructors,
_cancellationToken);
if (delegatedConstructor != null)
{
// There was a best match. Call it directly.
AddBaseDelegatingConstructor(delegatedConstructor, members);
return;
}
}
}
// Otherwise, just generate a normal constructor that assigns any provided
// parameters into fields.
AddFieldDelegatingConstructor(argumentList, members, options);
}
private void AddProperties(ArrayBuilder<ISymbol> members)
{
var typeInference = _document.Project.LanguageServices.GetService<ITypeInferenceService>();
foreach (var property in _state.PropertiesToGenerate)
{
if (_service.TryGenerateProperty(property, _document.SemanticModel, typeInference, _cancellationToken, out var generatedProperty))
{
members.Add(generatedProperty);
}
}
}
private void AddBaseDelegatingConstructor(
IMethodSymbol methodSymbol,
ArrayBuilder<ISymbol> members)
{
// If we're generating a constructor to delegate into the no-param base constructor
// then we can just elide the constructor entirely.
if (methodSymbol.Parameters.Length == 0)
{
return;
}
var factory = _document.Project.LanguageServices.GetService<SyntaxGenerator>();
members.Add(factory.CreateBaseDelegatingConstructor(
methodSymbol, DetermineName()));
}
private void AddFieldDelegatingConstructor(
IList<TArgumentSyntax> argumentList, ArrayBuilder<ISymbol> members, GenerateTypeOptionsResult options = null)
{
var factory = _document.Project.LanguageServices.GetService<SyntaxGenerator>();
var syntaxFactsService = _document.Project.LanguageServices.GetService<ISyntaxFactsService>();
var availableTypeParameters = _service.GetAvailableTypeParameters(_state, _document.SemanticModel, _intoNamespace, _cancellationToken);
var parameterTypes = GetArgumentTypes(argumentList);
var parameterNames = _service.GenerateParameterNames(_document.SemanticModel, argumentList);
var parameters = ArrayBuilder<IParameterSymbol>.GetInstance();
var parameterToExistingFieldMap = new Dictionary<string, ISymbol>();
var parameterToNewFieldMap = new Dictionary<string, string>();
var syntaxFacts = _document.Project.LanguageServices.GetService<ISyntaxFactsService>();
for (var i = 0; i < parameterNames.Count; i++)
{
var refKind = syntaxFacts.GetRefKindOfArgument(argumentList[i]);
var parameterName = parameterNames[i];
var parameterType = parameterTypes[i];
parameterType = parameterType.RemoveUnavailableTypeParameters(
_document.SemanticModel.Compilation, availableTypeParameters);
if (!TryFindMatchingField(parameterName, parameterType, parameterToExistingFieldMap, caseSensitive: true))
{
if (!TryFindMatchingField(parameterName, parameterType, parameterToExistingFieldMap, caseSensitive: false))
{
parameterToNewFieldMap[parameterName.BestNameForParameter] = parameterName.NameBasedOnArgument;
}
}
parameters.Add(CodeGenerationSymbolFactory.CreateParameterSymbol(
attributes: default(ImmutableArray<AttributeData>),
refKind: refKind,
isParams: false,
type: parameterType,
name: parameterName.BestNameForParameter));
}
// Empty Constructor for Struct is not allowed
if (!(parameters.Count == 0 && options != null && (options.TypeKind == TypeKind.Struct || options.TypeKind == TypeKind.Structure)))
{
members.AddRange(factory.CreateFieldDelegatingConstructor(
_document.SemanticModel.Compilation,
DetermineName(), null, parameters.ToImmutable(),
parameterToExistingFieldMap, parameterToNewFieldMap,
addNullChecks: false, preferThrowExpression: false,
cancellationToken: _cancellationToken));
}
parameters.Free();
}
private void AddExceptionConstructors(ArrayBuilder<ISymbol> members)
{
var factory = _document.Project.LanguageServices.GetService<SyntaxGenerator>();
var exceptionType = _document.SemanticModel.Compilation.ExceptionType();
var constructors =
exceptionType.InstanceConstructors
.Where(c => c.DeclaredAccessibility == Accessibility.Public || c.DeclaredAccessibility == Accessibility.Protected)
.Select(c => CodeGenerationSymbolFactory.CreateConstructorSymbol(
attributes: default(ImmutableArray<AttributeData>),
accessibility: c.DeclaredAccessibility,
modifiers: default(DeclarationModifiers),
typeName: DetermineName(),
parameters: c.Parameters,
statements: default(ImmutableArray<SyntaxNode>),
baseConstructorArguments: c.Parameters.Length == 0
? default(ImmutableArray<SyntaxNode>)
: factory.CreateArguments(c.Parameters)));
members.AddRange(constructors);
}
private ImmutableArray<AttributeData> DetermineAttributes()
{
if (_state.IsException)
{
var serializableType = _document.SemanticModel.Compilation.SerializableAttributeType();
if (serializableType != null)
{
var attribute = CodeGenerationSymbolFactory.CreateAttributeData(serializableType);
return ImmutableArray.Create(attribute);
}
}
return default(ImmutableArray<AttributeData>);
}
private Accessibility DetermineAccessibility()
{
return _service.GetAccessibility(_state, _document.SemanticModel, _intoNamespace, _cancellationToken);
}
private DeclarationModifiers DetermineModifiers()
{
return default(DeclarationModifiers);
}
private INamedTypeSymbol DetermineBaseType()
{
if (_state.BaseTypeOrInterfaceOpt == null || _state.BaseTypeOrInterfaceOpt.TypeKind == TypeKind.Interface)
{
return null;
}
return RemoveUnavailableTypeParameters(_state.BaseTypeOrInterfaceOpt);
}
private ImmutableArray<INamedTypeSymbol> DetermineInterfaces()
{
if (_state.BaseTypeOrInterfaceOpt != null && _state.BaseTypeOrInterfaceOpt.TypeKind == TypeKind.Interface)
{
var type = RemoveUnavailableTypeParameters(_state.BaseTypeOrInterfaceOpt);
if (type != null)
{
return ImmutableArray.Create(type);
}
}
return ImmutableArray<INamedTypeSymbol>.Empty;
}
private INamedTypeSymbol RemoveUnavailableTypeParameters(INamedTypeSymbol type)
{
return type.RemoveUnavailableTypeParameters(
_document.SemanticModel.Compilation, GetAvailableTypeParameters()) as INamedTypeSymbol;
}
private string DetermineName()
{
return GetTypeName(_state);
}
private ImmutableArray<ITypeParameterSymbol> DetermineTypeParameters()
=> _service.GetTypeParameters(_state, _document.SemanticModel, _cancellationToken);
private TypeKind DetermineTypeKind()
{
return _state.IsStruct
? TypeKind.Struct
: _state.IsInterface
? TypeKind.Interface
: TypeKind.Class;
}
protected IList<ITypeParameterSymbol> GetAvailableTypeParameters()
{
var availableInnerTypeParameters = _service.GetTypeParameters(_state, _document.SemanticModel, _cancellationToken);
var availableOuterTypeParameters = !_intoNamespace && _state.TypeToGenerateInOpt != null
? _state.TypeToGenerateInOpt.GetAllTypeParameters()
: SpecializedCollections.EmptyEnumerable<ITypeParameterSymbol>();
return availableOuterTypeParameters.Concat(availableInnerTypeParameters).ToList();
}
}
internal abstract bool TryGenerateProperty(TSimpleNameSyntax propertyName, SemanticModel semanticModel, ITypeInferenceService typeInference, CancellationToken cancellationToken, out IPropertySymbol property);
}
}
| |
/***************************************************************************************************************************************
* Copyright (C) 2001-2012 LearnLift USA *
* Contact: Learnlift USA, 12 Greenway Plaza, Suite 1510, Houston, Texas 77046, [email protected] *
* *
* This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License *
* as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. *
* *
* This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty *
* of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. *
* *
* You should have received a copy of the GNU Lesser General Public License along with this library; if not, *
* write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA *
***************************************************************************************************************************************/
using System;
using System.Collections.Generic;
using System.Text;
using MLifter.DAL.Interfaces;
using MLifter.DAL.DB;
namespace MLifter.BusinessLayer
{
/// <summary>
/// Business layer implementation of ISettings.
/// </summary>
/// <remarks>Documented by Dev03, 2009-01-15</remarks>
class Settings : ISettings
{
private IDictionary dictionary;
private ISettings defaultSettings
{
get
{
return dictionary.DefaultSettings;
}
}
private ISettings userSettings
{
get
{
return dictionary.UserSettings;
}
}
internal Settings(IDictionary dictionary)
{
this.dictionary = dictionary;
}
#region ISettings Members
public IQueryDirections QueryDirections
{
get
{
return new QueryDirections(defaultSettings.QueryDirections, userSettings.QueryDirections);
}
set
{
userSettings.QueryDirections = value;
}
}
public IQueryType QueryTypes
{
get
{
return new QueryType(defaultSettings.QueryTypes, userSettings.QueryTypes);
}
set
{
userSettings.QueryTypes = value;
}
}
public IQueryMultipleChoiceOptions MultipleChoiceOptions
{
get
{
return new QueryMultipleChoiceOptions(defaultSettings.MultipleChoiceOptions, userSettings.MultipleChoiceOptions);
}
set
{
userSettings.MultipleChoiceOptions = value;
}
}
public IGradeTyping GradeTyping
{
get
{
return new GradeTyping(defaultSettings.GradeTyping, userSettings.GradeTyping);
}
set
{
userSettings.GradeTyping = value;
}
}
public IGradeSynonyms GradeSynonyms
{
get
{
return new GradeSynonyms(defaultSettings.GradeSynonyms, userSettings.GradeSynonyms);
}
set
{
userSettings.GradeSynonyms = value;
}
}
public ICardStyle Style
{
get
{
return defaultSettings.Style;
}
set
{
defaultSettings.Style = value;
}
}
public CompiledTransform? QuestionStylesheet
{
get
{
return userSettings.QuestionStylesheet ?? defaultSettings.QuestionStylesheet;
}
set
{
userSettings.QuestionStylesheet = value;
}
}
public CompiledTransform? AnswerStylesheet
{
get
{
return userSettings.AnswerStylesheet ?? defaultSettings.AnswerStylesheet;
}
set
{
userSettings.AnswerStylesheet = value;
}
}
public bool? AutoplayAudio
{
get
{
return userSettings.AutoplayAudio ?? defaultSettings.AutoplayAudio;
}
set
{
userSettings.AutoplayAudio = value;
}
}
public bool? CaseSensitive
{
get
{
return userSettings.CaseSensitive ?? defaultSettings.CaseSensitive;
}
set
{
userSettings.CaseSensitive = value;
}
}
public bool? IgnoreAccentChars
{
get
{
return userSettings.IgnoreAccentChars ?? defaultSettings.IgnoreAccentChars;
}
set
{
userSettings.IgnoreAccentChars = value;
}
}
public bool? ConfirmDemote
{
get
{
return userSettings.ConfirmDemote ?? defaultSettings.ConfirmDemote;
}
set
{
userSettings.ConfirmDemote = value;
}
}
public bool? EnableCommentary
{
get
{
return userSettings.EnableCommentary ?? defaultSettings.EnableCommentary;
}
set
{
userSettings.EnableCommentary = value;
}
}
public bool? CorrectOnTheFly
{
get
{
return userSettings.CorrectOnTheFly ?? defaultSettings.CorrectOnTheFly;
}
set
{
userSettings.CorrectOnTheFly = value;
}
}
public bool? EnableTimer
{
get
{
return userSettings.EnableTimer ?? defaultSettings.EnableTimer;
}
set
{
userSettings.EnableTimer = value;
}
}
public bool? RandomPool
{
get
{
return userSettings.RandomPool ?? defaultSettings.RandomPool;
}
set
{
userSettings.RandomPool = value;
}
}
public bool? SelfAssessment
{
get
{
return userSettings.SelfAssessment ?? defaultSettings.SelfAssessment;
}
set
{
userSettings.SelfAssessment = value;
}
}
public bool? ShowImages
{
get
{
return userSettings.ShowImages ?? defaultSettings.ShowImages;
}
set
{
userSettings.ShowImages = value;
}
}
public bool? PoolEmptyMessageShown
{
get
{
return userSettings.PoolEmptyMessageShown ?? defaultSettings.PoolEmptyMessageShown;
}
set
{
userSettings.PoolEmptyMessageShown = value;
}
}
public bool? UseLMStylesheets
{
get
{
return userSettings.UseLMStylesheets ?? defaultSettings.UseLMStylesheets;
}
set
{
userSettings.UseLMStylesheets = value;
}
}
public bool? AutoBoxSize
{
get
{
return userSettings.AutoBoxSize ?? defaultSettings.AutoBoxSize;
}
set
{
userSettings.AutoBoxSize = value;
}
}
public string StripChars
{
get
{
return userSettings.StripChars != string.Empty ? userSettings.StripChars : defaultSettings.StripChars;
}
set
{
userSettings.StripChars = value;
}
}
public System.Globalization.CultureInfo QuestionCulture
{
get
{
return userSettings.QuestionCulture ?? defaultSettings.QuestionCulture;
}
set
{
userSettings.QuestionCulture = value;
}
}
public System.Globalization.CultureInfo AnswerCulture
{
get
{
return userSettings.AnswerCulture ?? defaultSettings.AnswerCulture;
}
set
{
userSettings.AnswerCulture = value;
}
}
public string QuestionCaption
{
get
{
return userSettings.QuestionCaption != string.Empty ? userSettings.QuestionCaption : defaultSettings.QuestionCaption;
}
set
{
userSettings.QuestionCaption = value;
}
}
public string AnswerCaption
{
get
{
return userSettings.AnswerCaption != string.Empty ? userSettings.AnswerCaption : defaultSettings.AnswerCaption;
}
set
{
userSettings.AnswerCaption = value;
}
}
public Dictionary<CommentarySoundIdentifier, IMedia> CommentarySounds
{
get
{
return defaultSettings.CommentarySounds;
}
set
{
defaultSettings.CommentarySounds = value;
}
}
public IMedia Logo
{
get
{
return userSettings.Logo ?? defaultSettings.Logo;
}
set
{
userSettings.Logo = value;
}
}
public bool? ShowStatistics
{
get
{
return userSettings.ShowStatistics ?? defaultSettings.ShowStatistics;
}
set
{
userSettings.ShowStatistics = value;
}
}
public bool? SkipCorrectAnswers
{
get
{
return userSettings.SkipCorrectAnswers ?? defaultSettings.SkipCorrectAnswers;
}
set
{
userSettings.SkipCorrectAnswers = value;
}
}
public ISnoozeOptions SnoozeOptions
{
get
{
return new SnoozeOptions(defaultSettings.SnoozeOptions, userSettings.SnoozeOptions);
}
set
{
userSettings.SnoozeOptions = value;
}
}
public IList<int> SelectedLearnChapters
{
get
{
return userSettings.SelectedLearnChapters ?? defaultSettings.SelectedLearnChapters;
}
set
{
userSettings.SelectedLearnChapters = value;
}
}
#endregion
#region ICopy Members
public void CopyTo(MLifter.DAL.Tools.ICopy target, MLifter.DAL.Tools.CopyToProgress progressDelegate)
{
throw new Exception("The method or operation is not implemented.");
}
#endregion
#region IParent Members
public MLifter.DAL.Tools.ParentClass Parent
{
get { throw new Exception("The method or operation is not implemented."); }
}
#endregion
#region ISecurity Members
public bool HasPermission(string permissionName)
{
throw new NotImplementedException();
}
public List<SecurityFramework.PermissionInfo> GetPermissions()
{
throw new NotImplementedException();
}
#endregion
}
class QueryDirections : IQueryDirections
{
private IQueryDirections defaultSettings;
private IQueryDirections userSettings;
public QueryDirections(IQueryDirections defaultSettings, IQueryDirections userSettings)
{
this.defaultSettings = defaultSettings;
this.userSettings = userSettings;
}
public override bool Equals(object obj)
{
return QueryDirectionsHelper.Compare(this, obj);
}
public override int GetHashCode()
{
return base.GetHashCode();
}
#region IQueryDirections Members
public bool? Question2Answer
{
get
{
return userSettings.Question2Answer ?? defaultSettings.Question2Answer;
}
set
{
userSettings.Question2Answer = value;
}
}
public bool? Answer2Question
{
get
{
return userSettings.Answer2Question ?? defaultSettings.Answer2Question;
}
set
{
userSettings.Answer2Question = value;
}
}
public bool? Mixed
{
get
{
return userSettings.Mixed ?? defaultSettings.Mixed;
}
set
{
userSettings.Mixed = value;
}
}
#endregion
#region ICopy Members
public void CopyTo(MLifter.DAL.Tools.ICopy target, MLifter.DAL.Tools.CopyToProgress progressDelegate)
{
throw new Exception("The method or operation is not implemented.");
}
#endregion
#region IParent Members
public MLifter.DAL.Tools.ParentClass Parent
{
get { throw new Exception("The method or operation is not implemented."); }
}
#endregion
}
class QueryType : IQueryType
{
private IQueryType defaultSettings;
private IQueryType userSettings;
public QueryType(IQueryType defaultSettings, IQueryType userSettings)
{
this.defaultSettings = defaultSettings;
this.userSettings = userSettings;
}
public override bool Equals(object obj)
{
return QueryTypeHelper.Compare(this, obj);
}
public override int GetHashCode()
{
return base.GetHashCode();
}
#region IQueryType Members
public bool? ImageRecognition
{
get
{
return userSettings.ImageRecognition ?? defaultSettings.ImageRecognition;
}
set
{
userSettings.ImageRecognition = value;
}
}
public bool? ListeningComprehension
{
get
{
return userSettings.ListeningComprehension ?? defaultSettings.ListeningComprehension;
}
set
{
userSettings.ListeningComprehension = value;
}
}
public bool? MultipleChoice
{
get
{
return userSettings.MultipleChoice ?? defaultSettings.MultipleChoice;
}
set
{
userSettings.MultipleChoice = value;
}
}
public bool? Sentence
{
get
{
return userSettings.Sentence ?? defaultSettings.Sentence;
}
set
{
userSettings.Sentence = value;
}
}
public bool? Word
{
get
{
return userSettings.Word ?? defaultSettings.Word;
}
set
{
userSettings.Word = value;
}
}
#endregion
#region ICopy Members
public void CopyTo(MLifter.DAL.Tools.ICopy target, MLifter.DAL.Tools.CopyToProgress progressDelegate)
{
throw new Exception("The method or operation is not implemented.");
}
#endregion
#region IParent Members
public MLifter.DAL.Tools.ParentClass Parent
{
get { throw new Exception("The method or operation is not implemented."); }
}
#endregion
}
/// <summary>
/// The BL IQueryMultipleChoiceOptions implementation
/// </summary>
/// <remarks>Documented by Dev08, 2009-04-10</remarks>
class QueryMultipleChoiceOptions : IQueryMultipleChoiceOptions
{
private bool workAsContainer = false;
private IQueryMultipleChoiceOptions defaultSettings;
private IQueryMultipleChoiceOptions userSettings;
/// <summary>
/// Initializes a new instance of the <see cref="QueryMultipleChoiceOptions"/> class.
/// </summary>
/// <param name="defaultSettings">The default settings.</param>
/// <param name="userSettings">The user settings.</param>
/// <remarks>Documented by Dev08, 2009-04-10</remarks>
public QueryMultipleChoiceOptions(IQueryMultipleChoiceOptions defaultSettings, IQueryMultipleChoiceOptions userSettings)
{
this.defaultSettings = defaultSettings;
this.userSettings = userSettings;
}
/// <summary>
/// Initializes a new instance of the <see cref="QueryMultipleChoiceOptions"/> class.
/// With this constructor, this can be used like a container class.
/// </summary>
/// <remarks>Documented by Dev08, 2009-04-10</remarks>
public QueryMultipleChoiceOptions()
{
workAsContainer = true;
}
public override bool Equals(object obj)
{
return QueryMultipleChoiceOptionsHelper.Compare(this, obj);
}
public override int GetHashCode()
{
return base.GetHashCode();
}
#region IQueryMultipleChoiceOptions Members
private bool? allowRandomDistractors;
public bool? AllowRandomDistractors
{
get
{
if (workAsContainer)
return allowRandomDistractors;
else
return userSettings.AllowRandomDistractors ?? defaultSettings.AllowRandomDistractors;
}
set
{
if (workAsContainer)
allowRandomDistractors = value;
else
userSettings.AllowRandomDistractors = value;
}
}
private bool? allowMultipleCorrectAnswers;
public bool? AllowMultipleCorrectAnswers
{
get
{
if (workAsContainer)
return allowMultipleCorrectAnswers;
else
return userSettings.AllowMultipleCorrectAnswers ?? defaultSettings.AllowMultipleCorrectAnswers;
}
set
{
if (workAsContainer)
allowMultipleCorrectAnswers = value;
else
userSettings.AllowMultipleCorrectAnswers = value;
}
}
private int? numberOfChoices;
public int? NumberOfChoices
{
get
{
if (workAsContainer)
return numberOfChoices;
else
return userSettings.NumberOfChoices ?? defaultSettings.NumberOfChoices;
}
set
{
if (workAsContainer)
numberOfChoices = value;
else
userSettings.NumberOfChoices = value;
}
}
private int? maxNumberOfCorrectAnswers;
public int? MaxNumberOfCorrectAnswers
{
get
{
if (workAsContainer)
return maxNumberOfCorrectAnswers;
else
return userSettings.MaxNumberOfCorrectAnswers ?? defaultSettings.MaxNumberOfCorrectAnswers;
}
set
{
if (workAsContainer)
maxNumberOfCorrectAnswers = value;
else
userSettings.MaxNumberOfCorrectAnswers = value;
}
}
#endregion
#region ICopy Members
public void CopyTo(MLifter.DAL.Tools.ICopy target, MLifter.DAL.Tools.CopyToProgress progressDelegate)
{
throw new Exception("The method or operation is not implemented.");
}
#endregion
#region IParent Members
public MLifter.DAL.Tools.ParentClass Parent
{
get { throw new Exception("The method or operation is not implemented."); }
}
#endregion
}
class GradeTyping : IGradeTyping
{
private IGradeTyping defaultSettings;
private IGradeTyping userSettings;
public GradeTyping(IGradeTyping defaultSettings, IGradeTyping userSettings)
{
this.defaultSettings = defaultSettings;
this.userSettings = userSettings;
}
public override bool Equals(object obj)
{
return GradeTypingHelper.Compare(this, obj);
}
public override int GetHashCode()
{
return base.GetHashCode();
}
#region IGradeTyping Members
public bool? AllCorrect
{
get
{
return userSettings.AllCorrect ?? defaultSettings.AllCorrect;
}
set
{
userSettings.AllCorrect = value;
}
}
public bool? HalfCorrect
{
get
{
return userSettings.HalfCorrect ?? defaultSettings.HalfCorrect;
}
set
{
userSettings.HalfCorrect = value;
}
}
public bool? NoneCorrect
{
get
{
return userSettings.NoneCorrect ?? defaultSettings.NoneCorrect;
}
set
{
userSettings.NoneCorrect = value;
}
}
public bool? Prompt
{
get
{
return userSettings.Prompt ?? defaultSettings.Prompt;
}
set
{
userSettings.Prompt = value;
}
}
#endregion
#region ICopy Members
public void CopyTo(MLifter.DAL.Tools.ICopy target, MLifter.DAL.Tools.CopyToProgress progressDelegate)
{
throw new Exception("The method or operation is not implemented.");
}
#endregion
#region IParent Members
public MLifter.DAL.Tools.ParentClass Parent
{
get { throw new Exception("The method or operation is not implemented."); }
}
#endregion
}
class GradeSynonyms : IGradeSynonyms
{
private IGradeSynonyms defaultSettings;
private IGradeSynonyms userSettings;
public GradeSynonyms(IGradeSynonyms defaultSettings, IGradeSynonyms userSettings)
{
this.defaultSettings = defaultSettings;
this.userSettings = userSettings;
}
public override bool Equals(object obj)
{
return GradeSynonymsHelper.Compare(this, obj);
}
public override int GetHashCode()
{
return base.GetHashCode();
}
#region IGradeSynonyms Members
public bool? AllKnown
{
get
{
return userSettings.AllKnown ?? defaultSettings.AllKnown;
}
set
{
userSettings.AllKnown = value;
}
}
public bool? HalfKnown
{
get
{
return userSettings.HalfKnown ?? defaultSettings.HalfKnown;
}
set
{
userSettings.HalfKnown = value;
}
}
public bool? OneKnown
{
get
{
return userSettings.OneKnown ?? defaultSettings.OneKnown;
}
set
{
userSettings.OneKnown = value;
}
}
public bool? FirstKnown
{
get
{
return userSettings.FirstKnown ?? defaultSettings.FirstKnown;
}
set
{
userSettings.FirstKnown = value;
}
}
public bool? Prompt
{
get
{
return userSettings.Prompt ?? defaultSettings.Prompt;
}
set
{
userSettings.Prompt = value;
}
}
#endregion
#region ICopy Members
public void CopyTo(MLifter.DAL.Tools.ICopy target, MLifter.DAL.Tools.CopyToProgress progressDelegate)
{
throw new Exception("The method or operation is not implemented.");
}
#endregion
#region IParent Members
public MLifter.DAL.Tools.ParentClass Parent
{
get { throw new Exception("The method or operation is not implemented."); }
}
#endregion
}
class SnoozeOptions : ISnoozeOptions
{
private ISnoozeOptions defaultSettings;
private ISnoozeOptions userSettings;
public SnoozeOptions(ISnoozeOptions defaultSettings, ISnoozeOptions userSettings)
{
this.defaultSettings = defaultSettings;
this.userSettings = userSettings;
}
public override bool Equals(object obj)
{
return SnoozeOptionsHelper.Compare(this, obj);
}
public override int GetHashCode()
{
return base.GetHashCode();
}
#region ISnoozeOptions Members
public void DisableCards()
{
userSettings.DisableCards();
}
public void DisableRights()
{
userSettings.DisableRights();
}
public void DisableTime()
{
userSettings.DisableTime();
}
public void EnableCards(int cards)
{
userSettings.EnableCards(cards);
}
public void EnableRights(int rights)
{
userSettings.EnableRights(rights);
}
public void EnableTime(int time)
{
userSettings.EnableTime(time);
}
public bool? IsCardsEnabled
{
get
{
return userSettings.IsCardsEnabled ?? defaultSettings.IsCardsEnabled;
}
set
{
userSettings.IsCardsEnabled = value;
}
}
public bool? IsRightsEnabled
{
get
{
return userSettings.IsRightsEnabled ?? defaultSettings.IsRightsEnabled;
}
set
{
userSettings.IsRightsEnabled = value;
}
}
public bool? IsTimeEnabled
{
get
{
return userSettings.IsTimeEnabled ?? defaultSettings.IsTimeEnabled;
}
set
{
userSettings.IsTimeEnabled = value;
}
}
public void SetSnoozeTimes(int lower_time, int upper_time)
{
userSettings.SetSnoozeTimes(lower_time, upper_time);
}
public ESnoozeMode? SnoozeMode
{
get
{
return userSettings.SnoozeMode ?? defaultSettings.SnoozeMode;
}
set
{
userSettings.SnoozeMode = value;
}
}
public int? SnoozeCards
{
get
{
return userSettings.SnoozeCards ?? defaultSettings.SnoozeCards;
}
set
{
userSettings.SnoozeCards = value;
}
}
public int? SnoozeRights
{
get
{
return userSettings.SnoozeRights ?? defaultSettings.SnoozeRights;
}
set
{
userSettings.SnoozeRights = value;
}
}
public int? SnoozeTime
{
get
{
return userSettings.SnoozeTime ?? defaultSettings.SnoozeTime;
}
set
{
userSettings.SnoozeTime = value;
}
}
public int? SnoozeHigh
{
get
{
return userSettings.SnoozeHigh ?? defaultSettings.SnoozeHigh;
}
set
{
userSettings.SnoozeHigh = value;
}
}
public int? SnoozeLow
{
get
{
return userSettings.SnoozeLow ?? defaultSettings.SnoozeLow;
}
set
{
userSettings.SnoozeLow = value;
}
}
#endregion
#region ICopy Members
public void CopyTo(MLifter.DAL.Tools.ICopy target, MLifter.DAL.Tools.CopyToProgress progressDelegate)
{
throw new Exception("The method or operation is not implemented.");
}
#endregion
#region IParent Members
public MLifter.DAL.Tools.ParentClass Parent
{
get { throw new Exception("The method or operation is not implemented."); }
}
#endregion
}
}
| |
//
// Copyright (C) 2010 Jackson Harper ([email protected])
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
//
using System;
using System.IO;
using System.Text;
using System.Net;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using Manos.IO;
using Manos.Collections;
namespace Manos.Http
{
public class HttpTransaction : IHttpTransaction, IDisposable
{
public static HttpTransaction BeginTransaction (HttpServer server, ITcpSocket socket, HttpConnectionCallback cb, bool closeOnEnd = false)
{
HttpTransaction transaction = new HttpTransaction (server, socket, cb, closeOnEnd);
return transaction;
}
private bool aborted;
private bool closeOnEnd;
private bool wantClose, responseFinished;
private GCHandle gc_handle;
public HttpTransaction (HttpServer server, ITcpSocket socket, HttpConnectionCallback callback, bool closeOnEnd = false)
{
Server = server;
Socket = socket;
this.closeOnEnd = closeOnEnd;
Context = server.Context;
ConnectionCallback = callback;
gc_handle = GCHandle.Alloc (this);
Request = new HttpRequest (this, socket);
Request.Read (Close);
}
public void Dispose ()
{
if (Socket != null)
Socket.Close ();
// Technically the IOStream should call our Close method, but lets be sure
if (gc_handle.IsAllocated)
gc_handle.Free ();
}
public Context Context {
get;
private set;
}
public HttpServer Server {
get;
private set;
}
public ITcpSocket Socket {
get;
private set;
}
public HttpConnectionCallback ConnectionCallback {
get;
private set;
}
public IHttpRequest Request {
get;
private set;
}
public IHttpResponse Response {
get;
private set;
}
public bool Aborted {
get { return aborted; }
}
public bool ResponseReady {
get;
private set;
}
// Force the server to disconnect
public bool NoKeepAlive {
get;
set;
}
public void Abort (int status, string message, params object [] p)
{
aborted = true;
}
public void Close ()
{
if (!responseFinished) {
wantClose = true;
} else {
if (gc_handle.IsAllocated)
gc_handle.Free ();
if (Request != null)
Request.Dispose ();
if (Response != null)
Response.Dispose ();
Socket = null;
Request = null;
Response = null;
}
}
public void Run ()
{
ConnectionCallback (this);
}
public void OnRequestReady ()
{
try {
Response = new HttpResponse (Context, Request, Socket);
ResponseReady = true;
if (closeOnEnd)
Response.OnEnd += () => Response.Complete (OnResponseFinished);
Server.RunTransaction (this);
} catch (Exception e) {
Console.WriteLine ("Exception while running transaction");
Console.WriteLine (e);
}
}
public void OnResponseFinished ()
{
Socket.GetSocketStream ().Write (ResponseFinishedCallback ());
}
IEnumerable<ByteBuffer> ResponseFinishedCallback ()
{
IBaseWatcher handler = null;
handler = Server.Context.CreateIdleWatcher (delegate {
handler.Dispose ();
responseFinished = true;
bool disconnect = true;
if (!NoKeepAlive) {
string dis;
if (Request.MinorVersion > 0 && Request.Headers.TryGetValue ("Connection", out dis))
disconnect = (dis == "close");
}
if (disconnect) {
Socket.Close ();
if (wantClose) {
Close ();
}
} else {
responseFinished = false;
wantClose = false;
Request.Read (Close);
}
});
handler.Start ();
yield break;
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using Microsoft.PowerShell.CrossCompatibility.Data;
namespace Microsoft.PowerShell.CrossCompatibility
{
/// <summary>
/// API to combine PowerShell compatibility profiles together.
/// Currently this only supports unions, used to generate a union profile
/// so that commands and types can be identified as being in some profile but not a configured one.
/// </summary>
public static class ProfileCombination
{
/// <summary>
/// Combine a list of compatibility profiles together so that any assembly, module,
/// type, command, etc. available in one is listed in the final result.
/// </summary>
/// <param name="profileId">The profile ID to assign to the generated union profile.</param>
/// <param name="profiles">The profiles to union together to generate the result.</param>
/// <returns>The deep union of all the given profiles, with the configured ID.</returns>
public static CompatibilityProfileData UnionMany(string profileId, IEnumerable<CompatibilityProfileData> profiles)
{
CompatibilityProfileData unionProfile = CombineProfiles(profiles, Union);
unionProfile.Platform = null;
unionProfile.Id = profileId;
unionProfile.ConstituentProfiles = profiles.Select(p => p.Id).ToArray();
return unionProfile;
}
private static object Union(CompatibilityProfileData thisProfile, CompatibilityProfileData thatProfile)
{
Union(thisProfile.Runtime, thatProfile.Runtime);
return thisProfile;
}
private static object Union(RuntimeData thisRuntime, RuntimeData thatRuntime)
{
foreach (KeyValuePair<string, JsonDictionary<Version, ModuleData>> moduleVersions in thatRuntime.Modules)
{
if (!thisRuntime.Modules.ContainsKey(moduleVersions.Key))
{
thisRuntime.Modules.Add(moduleVersions.Key, moduleVersions.Value);
continue;
}
thisRuntime.Modules[moduleVersions.Key] = DictionaryUnion(thisRuntime.Modules[moduleVersions.Key], moduleVersions.Value, Union);
}
thisRuntime.NativeCommands = StringDictionaryUnion(thisRuntime.NativeCommands, thatRuntime.NativeCommands, ArrayUnion);
thisRuntime.Common = (CommonPowerShellData)Union(thisRuntime.Common, thatRuntime.Common);
Union(thisRuntime.Types, thatRuntime.Types);
return thisRuntime;
}
private static object Union(CommonPowerShellData thisCommon, CommonPowerShellData thatCommon)
{
if (thatCommon == null)
{
return thisCommon;
}
if (thisCommon == null)
{
return thatCommon.Clone();
}
thisCommon.ParameterAliases = StringDictionaryUnion(thisCommon.ParameterAliases, thatCommon.ParameterAliases);
thisCommon.Parameters = StringDictionaryUnion(thisCommon.Parameters, thatCommon.Parameters, Union);
return thisCommon;
}
private static object Union(ModuleData thisModule, ModuleData thatModule)
{
thisModule.Aliases = StringDictionaryUnion(thisModule.Aliases, thatModule.Aliases);
thisModule.Variables = ArrayUnion(thisModule.Variables, thatModule.Variables);
thisModule.Cmdlets = StringDictionaryUnion(thisModule.Cmdlets, thatModule.Cmdlets, Union);
thisModule.Functions = StringDictionaryUnion(thisModule.Functions, thatModule.Functions, Union);
return thisModule;
}
private static object Union(CommandData thisCommand, CommandData thatCommand)
{
thisCommand.OutputType = ArrayUnion(thisCommand.OutputType, thatCommand.OutputType);
thisCommand.ParameterSets = ArrayUnion(thisCommand.ParameterSets, thatCommand.ParameterSets);
thisCommand.ParameterAliases = StringDictionaryUnion(thisCommand.ParameterAliases, thatCommand.ParameterAliases);
thisCommand.Parameters = StringDictionaryUnion(thisCommand.Parameters, thatCommand.Parameters, Union);
return thisCommand;
}
private static object Union(ParameterData thisParameter, ParameterData thatParameter)
{
thisParameter.ParameterSets = StringDictionaryUnion(thisParameter.ParameterSets, thatParameter.ParameterSets, Union);
return thisParameter;
}
private static object Union(ParameterSetData thisParameterSet, ParameterSetData thatParameterSet)
{
thisParameterSet.Flags = ArrayUnion(thisParameterSet.Flags, thatParameterSet.Flags);
return thisParameterSet;
}
private static object Union(AvailableTypeData thisTypes, AvailableTypeData thatTypes)
{
thisTypes.Assemblies = DictionaryUnion(thisTypes.Assemblies, thatTypes.Assemblies, Union);
thisTypes.TypeAccelerators = StringDictionaryUnion(thisTypes.TypeAccelerators, thatTypes.TypeAccelerators);
return thisTypes;
}
private static object Union(AssemblyData thisAssembly, AssemblyData thatAssembly)
{
Union(thisAssembly.AssemblyName, thatAssembly.AssemblyName);
if (thatAssembly.Types != null)
{
if (thisAssembly.Types == null)
{
thisAssembly.Types = new JsonDictionary<string, JsonDictionary<string, TypeData>>();
}
foreach (KeyValuePair<string, JsonDictionary<string, TypeData>> nspace in thatAssembly.Types)
{
if (!thisAssembly.Types.ContainsKey(nspace.Key))
{
thisAssembly.Types.Add(nspace.Key, nspace.Value);
continue;
}
thisAssembly.Types[nspace.Key] = DictionaryUnion(thisAssembly.Types[nspace.Key], nspace.Value, Union);
}
}
return thisAssembly;
}
private static object Union(AssemblyNameData thisAsmName, AssemblyNameData thatAsmName)
{
if (thatAsmName.Version > thisAsmName.Version)
{
thisAsmName.Version = thatAsmName.Version;
}
if (thisAsmName.PublicKeyToken == null && thatAsmName.PublicKeyToken != null)
{
thisAsmName.PublicKeyToken = thatAsmName.PublicKeyToken;
}
return thisAsmName;
}
private static object Union(TypeData thisType, TypeData thatType)
{
thisType.Instance = (MemberData)Union(thisType.Instance, thatType.Instance);
thisType.Static = (MemberData)Union(thisType.Static, thatType.Static);
return thisType;
}
private static object Union(MemberData thisMembers, MemberData thatMembers)
{
if (thatMembers == null)
{
return thisMembers;
}
if (thisMembers == null)
{
return thatMembers.Clone();
}
thisMembers.Indexers = ArrayUnion(thisMembers.Indexers, thatMembers.Indexers);
thisMembers.Constructors = ParameterUnion(thisMembers.Constructors, thatMembers.Constructors);
thisMembers.Events = DictionaryUnion(thisMembers.Events, thatMembers.Events);
thisMembers.Fields = DictionaryUnion(thisMembers.Fields, thatMembers.Fields);
thisMembers.Methods = DictionaryUnion(thisMembers.Methods, thatMembers.Methods, Union);
thisMembers.NestedTypes = DictionaryUnion(thisMembers.NestedTypes, thatMembers.NestedTypes, Union);
thisMembers.Properties = DictionaryUnion(thisMembers.Properties, thatMembers.Properties, Union);
return thisMembers;
}
private static object Union(PropertyData thisProperty, PropertyData thatProperty)
{
thisProperty.Accessors = ArrayUnion(thisProperty.Accessors, thatProperty.Accessors);
return thisProperty;
}
private static object Union(MethodData thisMethod, MethodData thatMethod)
{
thisMethod.OverloadParameters = ParameterUnion(thisMethod.OverloadParameters, thatMethod.OverloadParameters);
return thisMethod;
}
private static CompatibilityProfileData CombineProfiles(IEnumerable<CompatibilityProfileData> profiles, Func<CompatibilityProfileData, CompatibilityProfileData, object> combinator)
{
IEnumerator<CompatibilityProfileData> profileEnumerator = profiles.GetEnumerator();
if (!profileEnumerator.MoveNext())
{
return null;
}
CompatibilityProfileData mutProfileBase = (CompatibilityProfileData)profileEnumerator.Current.Clone();
while(profileEnumerator.MoveNext())
{
mutProfileBase = (CompatibilityProfileData)combinator(mutProfileBase, profileEnumerator.Current);
}
return mutProfileBase;
}
private static T[] ArrayUnion<T>(T[] thisArray, T[] thatArray)
{
if (thatArray == null)
{
return thisArray;
}
bool canClone = typeof(ICloneable).IsAssignableFrom(typeof(T));
var clonedThat = new T[thatArray.Length];
if (canClone)
{
for (int i = 0; i < thatArray.Length; i++)
{
clonedThat[i] = (T)((dynamic)thatArray[i]).Clone();
}
}
else
{
for (int i = 0; i < thatArray.Length; i++)
{
clonedThat[i] = (T)thatArray[i];
}
}
if (thisArray == null)
{
return clonedThat;
}
return thisArray.Union(thatArray).ToArray();
}
private static string[][] ParameterUnion(string[][] thisParameters, string[][] thatParameters)
{
if (thatParameters == null)
{
return thisParameters;
}
if (thisParameters == null)
{
return thatParameters.Select(arr => (string[])arr.Clone()).ToArray();
}
var parameters = new HashSet<string[]>(thisParameters, new ParameterListComparer());
foreach (string[] thatParameter in thatParameters)
{
parameters.Add(thatParameter);
}
return parameters.ToArray();
}
private static JsonCaseInsensitiveStringDictionary<TValue> StringDictionaryUnion<TValue>(
JsonCaseInsensitiveStringDictionary<TValue> thisStringDict,
JsonCaseInsensitiveStringDictionary<TValue> thatStringDict,
Func<TValue, TValue, object> valueUnionizer = null)
where TValue : ICloneable
{
if (thatStringDict == null)
{
return thisStringDict;
}
if (thisStringDict == null)
{
return (JsonCaseInsensitiveStringDictionary<TValue>)thatStringDict.Clone();
}
foreach (KeyValuePair<string, TValue> item in thatStringDict)
{
if (!thisStringDict.ContainsKey(item.Key))
{
thisStringDict.Add(item.Key, item.Value);
continue;
}
if (valueUnionizer != null)
{
thisStringDict[item.Key] = (TValue)valueUnionizer(thisStringDict[item.Key], item.Value);
}
}
return thisStringDict;
}
private static JsonDictionary<K, V> DictionaryUnion<K, V>(
JsonDictionary<K, V> thisDict,
JsonDictionary<K, V> thatDict,
Func<V, V, object> valueUnionizer = null)
where K : ICloneable where V : ICloneable
{
if (thatDict == null)
{
return thisDict;
}
if (thisDict == null)
{
return (JsonDictionary<K, V>)thatDict.Clone();
}
foreach (KeyValuePair<K, V> item in thatDict)
{
if (!thisDict.ContainsKey(item.Key))
{
thisDict.Add(item.Key, item.Value);
continue;
}
if (valueUnionizer != null)
{
thisDict[item.Key] = (V)valueUnionizer(thisDict[item.Key], item.Value);
}
}
return thisDict;
}
private static KeyValuePair<Version, ModuleData> UnionVersionedModules(IReadOnlyCollection<KeyValuePair<Version, ModuleData>> modules)
{
ModuleData unionedModule = null;
Version version = null;
bool firstModule = true;
foreach (KeyValuePair<Version, ModuleData> modVersion in modules)
{
if (firstModule)
{
version = modVersion.Key;
unionedModule = (ModuleData)modVersion.Value.Clone();
firstModule = false;
continue;
}
version = version >= modVersion.Key ? version : modVersion.Key;
unionedModule = (ModuleData)Union(unionedModule, modVersion.Value);
}
return new KeyValuePair<Version, ModuleData>(version, unionedModule);
}
private struct ParameterListComparer : IEqualityComparer<string[]>
{
public bool Equals(string[] x, string[] y)
{
if (x == y)
{
return true;
}
if (x == null || y == null)
{
return false;
}
if (x.Length != y.Length)
{
return false;
}
for (int i = 0; i < x.Length; i++)
{
if (x[i] != y[i])
{
return false;
}
}
return true;
}
public int GetHashCode(string[] obj)
{
if (obj == null)
{
return 0;
}
int hc = 1;
foreach (string s in obj)
{
unchecked
{
hc = 31 * hc + (s?.GetHashCode() ?? 0);
}
}
return hc;
}
}
}
}
| |
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
namespace Microsoft.Zelig.CodeGeneration.IR.CompilationSteps.Handlers
{
using System;
using System.Collections.Generic;
using Microsoft.Zelig.Runtime.TypeSystem;
public class OperatorHandlers_HighLevelToMidLevel
{
//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//
//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//
//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//
[CompilationSteps.PhaseFilter( typeof(Phases.HighLevelToMidLevelConversion) )]
[CompilationSteps.OperatorHandler( typeof(LeaveControlOperator) )]
private static void Handle_LeaveControlOperator( PhaseExecution.NotificationContext nc )
{
LeaveControlOperator op = (LeaveControlOperator)nc.CurrentOperator;
UnconditionalControlOperator opNew = UnconditionalControlOperator.New( op.DebugInfo, op.TargetBranch );
op.SubstituteWithOperator( opNew, Operator.SubstitutionFlags.Default );
nc.MarkAsModified();
}
//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//
//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//
//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//
private static VariableExpression LoadVirtualMethodPointer(
PhaseExecution.NotificationContext nc,
InstanceCallOperator call,
Expression target,
MethodRepresentation method)
{
TypeSystemForCodeTransformation typeSystem = nc.TypeSystem;
Debugging.DebugInfo debugInfo = call.DebugInfo;
TemporaryVariableExpression methodPointer;
if ( method.OwnerType is InterfaceTypeRepresentation )
{
// Load MethodPointers for interface.
MethodRepresentation mdVTableGetInterface = typeSystem.WellKnownMethods.VTable_GetInterface;
TemporaryVariableExpression methodPointers = nc.AllocateTemporary( mdVTableGetInterface.ReturnType );
Expression[] rhs = typeSystem.AddTypePointerToArgumentsOfStaticMethod( mdVTableGetInterface, target, typeSystem.GetVTable( method.OwnerType ) );
CallOperator newCall = StaticCallOperator.New( debugInfo, CallOperator.CallKind.Direct, mdVTableGetInterface, VariableExpression.ToArray( methodPointers ), rhs );
call.AddOperatorBefore( newCall );
// Load the code pointer from the list. No null or range check, we know both will always pass.
int idx = method.FindInterfaceTableIndex();
methodPointer = nc.AllocateTemporary( methodPointers.Type.ContainedType );
call.AddOperatorBefore( LoadElementOperator.New( debugInfo, methodPointer, methodPointers, typeSystem.CreateConstant( idx ), null, false ) );
}
else
{
// Load the target object's VTable.
MethodRepresentation mdVTableGet = typeSystem.WellKnownMethods.VTable_Get;
TemporaryVariableExpression tmpVTable = nc.AllocateTemporary( mdVTableGet.OwnerType );
Expression[] rhs = typeSystem.AddTypePointerToArgumentsOfStaticMethod( mdVTableGet, target );
CallOperator newCall = StaticCallOperator.New( debugInfo, CallOperator.CallKind.Direct, mdVTableGet, VariableExpression.ToArray( tmpVTable ), rhs );
call.AddOperatorBefore( newCall );
// Get method code pointers. The VTable can never be null here, so don't add null-checks.
FieldRepresentation fdMethodPointers = typeSystem.WellKnownFields.VTable_MethodPointers;
TemporaryVariableExpression methodPointers = nc.AllocateTemporary( fdMethodPointers.FieldType );
call.AddOperatorBefore( LoadInstanceFieldOperator.New( debugInfo, fdMethodPointers, methodPointers, tmpVTable, false ) );
// Load the code pointer from the list. No null or range check, we know both will always pass.
int index = method.FindVirtualTableIndex();
methodPointer = nc.AllocateTemporary( methodPointers.Type.ContainedType );
call.AddOperatorBefore( LoadElementOperator.New( debugInfo, methodPointer, methodPointers, typeSystem.CreateConstant( index ), null, false ) );
}
return methodPointer;
}
//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//
//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//
//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//
[CompilationSteps.PhaseFilter( typeof(Phases.HighLevelToMidLevelConversion) )]
[CompilationSteps.OperatorHandler( typeof(InstanceCallOperator) )]
private static void Handle_Convert_VirtualCallOperator( PhaseExecution.NotificationContext nc )
{
InstanceCallOperator op = (InstanceCallOperator)nc.CurrentOperator;
TypeSystemForCodeTransformation typeSystem = nc.TypeSystem;
if(op.CallType == CallOperator.CallKind.Virtual)
{
if(MethodTransformations.AttemptDevirtualization( typeSystem, op ))
{
nc.MarkAsModified();
return;
}
VariableExpression methodPointer = LoadVirtualMethodPointer( nc, op, op.FirstArgument, op.TargetMethod );
Expression[] rhs = ArrayUtility.InsertAtHeadOfNotNullArray( op.Arguments, methodPointer );
CallOperator call = IndirectCallOperator.New( op.DebugInfo, op.TargetMethod, op.Results, rhs, true, false );
op.SubstituteWithOperator( call, Operator.SubstitutionFlags.CopyAnnotations );
nc.MarkAsModified();
}
}
//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//
//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//
//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//
[CompilationSteps.PhaseFilter( typeof(Phases.HighLevelToMidLevelConversion) )]
[CompilationSteps.OperatorHandler( typeof(MethodRepresentationOperator) )]
private static void Handle_Convert_DelegateCreation( PhaseExecution.NotificationContext nc )
{
ControlFlowGraphStateForCodeTransformation cfg = nc.CurrentCFG;
MethodRepresentationOperator op = (MethodRepresentationOperator)nc.CurrentOperator;
MethodRepresentation mdDelegate = op.Method;
VariableExpression mdPtr = op.FirstResult;
Operator def = cfg.FindSingleDefinition( mdPtr );
InstanceCallOperator call = cfg.FindSingleUse ( mdPtr ) as InstanceCallOperator;
if(def != null && call != null)
{
TypeSystemForCodeTransformation typeSystem = nc.TypeSystem;
WellKnownMethods wkm = typeSystem.WellKnownMethods;
Debugging.DebugInfo debugInfo = call.DebugInfo;
Expression dlg = call.FirstArgument;
Expression target = call.SecondArgument;
Expression exCode;
CallOperator newCall;
Expression[] rhs;
if(op.Arguments.Length == 0)
{
//
// Direct method.
//
CodePointer cp = typeSystem.CreateCodePointer( mdDelegate );
WellKnownTypes wkt = typeSystem.WellKnownTypes;
exCode = typeSystem.CreateConstant( wkt.Microsoft_Zelig_Runtime_TypeSystem_CodePointer, cp );
}
else
{
//
// Virtual method.
//
Expression source = op.FirstArgument;
if(source != target)
{
throw TypeConsistencyErrorException.Create( "Cannot create an instance delegate on '{0}' when the method comes from '{1}'", target, source );
}
exCode = LoadVirtualMethodPointer( nc, call, target, mdDelegate );
}
foreach( MethodRepresentation mdParent in call.TargetMethod.OwnerType.Extends.Methods )
{
if( mdParent is ConstructorMethodRepresentation )
{
rhs = new Expression[ ] { dlg, target, exCode };
newCall = InstanceCallOperator.New( debugInfo, CallOperator.CallKind.Direct, mdParent, call.Results, rhs, true );
call.SubstituteWithOperator( newCall, Operator.SubstitutionFlags.CopyAnnotations );
//
// Make sure we get rid of the LDFTN/LDVIRTFTN operators.
//
op.Delete( );
nc.StopScan( );
return;
}
}
}
throw TypeConsistencyErrorException.Create( "Unsupported delegate creation at {0}", op );
}
//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//
//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//
//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//
[CompilationSteps.PhaseFilter( typeof(Phases.HighLevelToMidLevelConversion) )]
[CompilationSteps.OperatorHandler( typeof(FieldOperator) )]
private static void Handle_FieldOperator( PhaseExecution.NotificationContext nc )
{
TypeSystemForCodeTransformation ts = nc.TypeSystem;
FieldOperator op = (FieldOperator)nc.CurrentOperator;
ControlFlowGraphStateForCodeTransformation cfg = nc.CurrentCFG;
Debugging.DebugInfo debugInfo = op.DebugInfo;
FieldRepresentation fd = op.Field;
{
CustomAttributeRepresentation caFd;
if(ts.RegisterAttributes.TryGetValue( fd, out caFd ))
{
TypeRepresentation tdField = fd.FieldType;
if(tdField is ScalarTypeRepresentation)
{
//
// Scalar fields are handled normally.
//
}
else if(ts.MemoryMappedBitFieldPeripherals.ContainsKey( tdField ))
{
//
// Bitfields are handled normally.
//
}
else
{
TypeRepresentation tdTarget;
if(tdField is ArrayReferenceTypeRepresentation)
{
tdTarget = tdField.ContainedType;
}
else
{
tdTarget = tdField;
}
if(ts.MemoryMappedPeripherals.ContainsKey( tdTarget ) == false)
{
if(tdTarget is ScalarTypeRepresentation)
{
//
// Accept memory-mapped arrays of scalar types.
//
}
else if(ts.MemoryMappedBitFieldPeripherals.ContainsKey( tdTarget ))
{
//
// Arrays of bitfields are handled normally.
//
}
else
{
throw TypeConsistencyErrorException.Create( "Cannot use type '{0}' for Register field '{1}'", tdField.FullNameWithAbbreviation, fd.ToShortString() );
}
}
Operator opNew;
uint offset = (uint)caFd.GetNamedArg( "Offset" );
if(op is LoadInstanceFieldAddressOperator)
{
throw TypeConsistencyErrorException.Create( "Cannot take the address of section '{0}' of memory-mapped peripheral '{1}'", fd.Name, fd.OwnerType.FullNameWithAbbreviation );
}
else if(op is LoadInstanceFieldOperator)
{
opNew = BinaryOperator.New( debugInfo, BinaryOperator.ALU.ADD, false, false, op.FirstResult, op.FirstArgument, nc.TypeSystem.CreateConstant( offset ) );
opNew.AddAnnotation( NotNullAnnotation .Create( ts ) );
opNew.AddAnnotation( MemoryMappedPeripheralAnnotation.Create( ts, caFd ) );
}
else if(op is StoreInstanceFieldOperator)
{
throw TypeConsistencyErrorException.Create( "Cannot update reference to section '{0}' of memory-mapped peripheral '{1}'", fd.Name, fd.OwnerType.FullNameWithAbbreviation );
}
else
{
throw TypeConsistencyErrorException.Create( "Unexpected operator {0} at phase {1}", op, nc.Phase );
}
CHECKS.ASSERT( opNew.MayThrow == false, "Failed to lower call operator {0}", op );
op.SubstituteWithOperator( opNew, Operator.SubstitutionFlags.CopyAnnotations );
nc.MarkAsModified();
return;
}
}
}
{
BitFieldDefinition bfDef;
if(ts.BitFieldRegisterAttributes.TryGetValue( fd, out bfDef ))
{
if((fd.FieldType is ScalarTypeRepresentation) == false)
{
throw TypeConsistencyErrorException.Create( "Unexpected operator {0} at phase {1}", op, nc.Phase );
}
bool fLoad;
if(op is LoadInstanceFieldAddressOperator)
{
throw TypeConsistencyErrorException.Create( "Cannot take the address of section '{0}' of memory-mapped peripheral '{1}'", fd.Name, fd.OwnerType.FullNameWithAbbreviation );
}
else if(op is LoadInstanceFieldOperator)
{
fLoad = true;
}
else if(op is StoreInstanceFieldOperator)
{
fLoad = false;
}
else
{
throw TypeConsistencyErrorException.Create( "Unexpected operator {0} at phase {1}", op, nc.Phase );
}
//--//
bool fSigned = fd.FieldType.IsSigned;
TypeRepresentation td = fd.OwnerType;
CustomAttributeRepresentation caTd = ts.MemoryMappedBitFieldPeripherals[td];
TypeRepresentation tdPhysical = caTd.GetNamedArg< TypeRepresentation >( "PhysicalType" );
VariableExpression tmp = nc.CurrentCFG.AllocateTemporary( tdPhysical, null );
Operator opNew;
op.AddOperatorBefore( LoadIndirectOperator.New( debugInfo, tdPhysical, tmp, op.FirstArgument, null, fd.Offset, true, false ) );
if(bfDef.Sections.Length == 1)
{
var sec = bfDef.Sections[0];
uint position = sec.Position;
uint size = sec.Size;
Runtime.BitFieldModifier modifiers = sec.Modifiers;
//--//
uint mask = (1u << (int)size) - 1u;
uint maskShifted = mask << (int)position;
if(fLoad)
{
if(position == 0 && fSigned == false)
{
//
// TODO: Add ability to verify with Platform Abstraction if it's possible to encode the constant in a single instruction.
//
opNew = BinaryOperator.New( debugInfo, BinaryOperator.ALU.AND, false, false, op.FirstResult, tmp, ts.CreateConstant( mask ) );
}
else
{
//
// We need to load the physical register, and extract the bitfield, which we achieve with a left/right shift pair.
//
VariableExpression tmp2 = nc.CurrentCFG.AllocateTemporary( tdPhysical, null );
op.AddOperatorBefore( BinaryOperator.New( debugInfo, BinaryOperator.ALU.SHL, false , false, tmp2 , tmp , ts.CreateConstant( 32 - (position + size) ) ) );
opNew = BinaryOperator.New( debugInfo, BinaryOperator.ALU.SHR, fSigned, false, op.FirstResult, tmp2, ts.CreateConstant( 32 - size ) );
}
}
else
{
if(size == 1 && op.SecondArgument is ConstantExpression)
{
//
// Setting/clearing a single bit. No need to perform complex masking.
//
ConstantExpression ex = (ConstantExpression)op.SecondArgument;
ulong val;
if(ex.GetAsUnsignedInteger( out val ) == false)
{
throw TypeConsistencyErrorException.Create( "Expecting a numeric constant, got '{0}'", ex );
}
VariableExpression tmp2 = nc.CurrentCFG.AllocateTemporary( tdPhysical, null );
if((val & 1) != 0)
{
ConstantExpression exMask = ts.CreateConstant( maskShifted );
op.AddOperatorBefore( BinaryOperator.New( debugInfo, BinaryOperator.ALU.OR, false, false, tmp2, tmp, exMask ) );
}
else
{
ConstantExpression exMaskNot = ts.CreateConstant( ~maskShifted );
op.AddOperatorBefore( BinaryOperator.New( debugInfo, BinaryOperator.ALU.AND, false, false, tmp2, tmp, exMaskNot ) );
}
opNew = StoreIndirectOperator.New( debugInfo, td, op.FirstArgument, tmp2, null, fd.Offset, false );
}
else
{
//
// We need to load the physical register, shift it and mask it, then mask and merge with the new value, and finally write it back.
//
VariableExpression tmp2 = nc.CurrentCFG.AllocateTemporary( tdPhysical, null );
VariableExpression tmp3 = nc.CurrentCFG.AllocateTemporary( tdPhysical, null );
VariableExpression tmp4 = nc.CurrentCFG.AllocateTemporary( tdPhysical, null );
VariableExpression tmp5 = nc.CurrentCFG.AllocateTemporary( tdPhysical, null );
ConstantExpression exMask = ts.CreateConstant( maskShifted );
ConstantExpression exMaskNot = ts.CreateConstant( ~maskShifted );
op.AddOperatorBefore( BinaryOperator.New( debugInfo, BinaryOperator.ALU.SHL, false, false, tmp2, op.SecondArgument, ts.CreateConstant( position ) ) );
op.AddOperatorBefore( BinaryOperator.New( debugInfo, BinaryOperator.ALU.AND, false, false, tmp3, tmp2 , exMask ) );
op.AddOperatorBefore( BinaryOperator.New( debugInfo, BinaryOperator.ALU.AND, false, false, tmp4, tmp , exMaskNot ) );
op.AddOperatorBefore( BinaryOperator.New( debugInfo, BinaryOperator.ALU.OR , false, false, tmp5, tmp3 , tmp4 ) );
opNew = StoreIndirectOperator.New( debugInfo, td, op.FirstArgument, tmp5, null, fd.Offset, false );
}
}
}
else
{
uint totalSize = bfDef.TotalSize;
VariableExpression lastVar = null;
foreach(var sec in bfDef.Sections)
{
uint position = sec.Position;
uint size = sec.Size;
uint offset = sec.Offset;
Runtime.BitFieldModifier modifiers = sec.Modifiers;
//--//
uint mask = (1u << (int)size) - 1u;
uint maskShifted = mask << (int)position;
VariableExpression newVar = nc.CurrentCFG.AllocateTemporary( tdPhysical, null );
if(fLoad)
{
bool fLastSection = (offset + size == totalSize);
bool fSigned2 = fSigned && fLastSection;
VariableExpression newVarUnshifted = nc.CurrentCFG.AllocateTemporary( tdPhysical, null );
if(position == 0 && fSigned2 == false)
{
//
// TODO: Add ability to verify with Platform Abstraction if it's possible to encode the constant in a single instruction.
//
op.AddOperatorBefore( BinaryOperator.New( debugInfo, BinaryOperator.ALU.AND, false, false, newVarUnshifted, tmp, ts.CreateConstant( mask ) ) );
}
else
{
//
// We need to load the physical register, and extract the bitfield, which we achieve with a left/right shift pair.
//
VariableExpression tmp2 = nc.CurrentCFG.AllocateTemporary( tdPhysical, null );
op.AddOperatorBefore( BinaryOperator.New( debugInfo, BinaryOperator.ALU.SHL, false , false, tmp2 , tmp , ts.CreateConstant( 32 - (position + size) ) ) );
op.AddOperatorBefore( BinaryOperator.New( debugInfo, BinaryOperator.ALU.SHR, fSigned2, false, newVarUnshifted, tmp2, ts.CreateConstant( 32 - size ) ) );
}
op.AddOperatorBefore( BinaryOperator.New( debugInfo, BinaryOperator.ALU.SHL, false, false, newVar, newVarUnshifted, ts.CreateConstant( offset ) ) );
if(lastVar != null)
{
VariableExpression mergeVar = nc.CurrentCFG.AllocateTemporary( tdPhysical, null );
op.AddOperatorBefore( BinaryOperator.New( debugInfo, BinaryOperator.ALU.OR, false, false, mergeVar, lastVar, newVar ) );
lastVar = mergeVar;
}
else
{
lastVar = newVar;
}
}
else
{
if(size == 1 && op.SecondArgument is ConstantExpression)
{
//
// Setting/clearing a single bit. No need to perform complex masking.
//
ConstantExpression ex = (ConstantExpression)op.SecondArgument;
ulong val;
if(ex.GetAsUnsignedInteger( out val ) == false)
{
throw TypeConsistencyErrorException.Create( "Expecting a numeric constant, got '{0}'", ex );
}
if((val & (1u << (int)offset)) != 0)
{
ConstantExpression exMask = ts.CreateConstant( maskShifted );
op.AddOperatorBefore( BinaryOperator.New( debugInfo, BinaryOperator.ALU.OR, false, false, newVar, tmp, exMask ) );
}
else
{
ConstantExpression exMaskNot = ts.CreateConstant( ~maskShifted );
op.AddOperatorBefore( BinaryOperator.New( debugInfo, BinaryOperator.ALU.AND, false, false, newVar, tmp, exMaskNot ) );
}
}
else
{
//
// We need to load the physical register, shift it and mask it, then mask and merge with the new value, and finally write it back.
//
VariableExpression tmp2 = nc.CurrentCFG.AllocateTemporary( tdPhysical, null );
VariableExpression tmp3 = nc.CurrentCFG.AllocateTemporary( tdPhysical, null );
VariableExpression tmp4 = nc.CurrentCFG.AllocateTemporary( tdPhysical, null );
ConstantExpression exMask = ts.CreateConstant( maskShifted );
ConstantExpression exMaskNot = ts.CreateConstant( ~maskShifted );
if(position > offset)
{
op.AddOperatorBefore( BinaryOperator.New( debugInfo, BinaryOperator.ALU.SHL, false, false, tmp2, op.SecondArgument, ts.CreateConstant( position - offset ) ) );
}
else
{
op.AddOperatorBefore( BinaryOperator.New( debugInfo, BinaryOperator.ALU.SHR, false, false, tmp2, op.SecondArgument, ts.CreateConstant( offset - position ) ) );
}
op.AddOperatorBefore( BinaryOperator.New( debugInfo, BinaryOperator.ALU.AND, false, false, tmp3 , tmp2, exMask ) );
op.AddOperatorBefore( BinaryOperator.New( debugInfo, BinaryOperator.ALU.AND, false, false, tmp4 , tmp , exMaskNot ) );
op.AddOperatorBefore( BinaryOperator.New( debugInfo, BinaryOperator.ALU.OR , false, false, newVar, tmp3, tmp4 ) );
}
lastVar = newVar;
tmp = lastVar;
}
}
if(fLoad)
{
opNew = SingleAssignmentOperator.New( debugInfo, op.FirstResult, lastVar );
}
else
{
opNew = StoreIndirectOperator.New( debugInfo, td, op.FirstArgument, lastVar, null, fd.Offset, false );
}
}
CHECKS.ASSERT( opNew.MayThrow == false, "Failed to lower call operator {0}", op );
op.SubstituteWithOperator( opNew, Operator.SubstitutionFlags.CopyAnnotations );
nc.MarkAsModified();
return;
}
}
if(op.MayThrow)
{
FieldOperator opNew;
op.AddOperatorBefore( NullCheckOperator.New( debugInfo, op.FirstArgument ) );
if(op is LoadInstanceFieldAddressOperator)
{
opNew = LoadInstanceFieldAddressOperator.New( debugInfo, fd, op.FirstResult, op.FirstArgument, false );
opNew.AddAnnotation( NotNullAnnotation.Create( ts ) );
}
else if(op is LoadInstanceFieldOperator)
{
opNew = LoadInstanceFieldOperator.New( debugInfo, fd, op.FirstResult, op.FirstArgument, false );
}
else if(op is StoreInstanceFieldOperator)
{
opNew = StoreInstanceFieldOperator.New( debugInfo, fd, op.FirstArgument, op.SecondArgument, false );
}
else
{
throw TypeConsistencyErrorException.Create( "Unexpected operator {0} at phase {1}", op, nc.Phase );
}
CHECKS.ASSERT( opNew.MayThrow == false, "Failed to lower call operator {0}", op );
op.SubstituteWithOperator( opNew, Operator.SubstitutionFlags.CopyAnnotations );
op = opNew;
nc.MarkAsModified();
}
if(op is LoadInstanceFieldOperator)
{
if((fd.Flags & FieldRepresentation.Attributes.NeverNull) != 0)
{
if(op.AddAnnotation( NotNullAnnotation.Create( ts ) ))
{
nc.MarkAsModified();
}
}
if((fd.Flags & FieldRepresentation.Attributes.HasFixedSize) != 0)
{
if(op.AddAnnotation( FixedLengthArrayAnnotation.Create( ts, fd.FixedSize ) ))
{
nc.MarkAsModified();
}
}
}
}
//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//
//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//
//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//
[CompilationSteps.PhaseFilter( typeof(Phases.HighLevelToMidLevelConversion) )]
[CompilationSteps.OperatorHandler( typeof(ElementOperator) )]
private static void Handle_ElementOperator( PhaseExecution.NotificationContext nc )
{
TypeSystemForCodeTransformation ts = nc.TypeSystem;
ElementOperator op = (ElementOperator)nc.CurrentOperator;
Debugging.DebugInfo debugInfo = op.DebugInfo;
Expression exArray = op.FirstArgument;
TypeRepresentation tdElement = exArray.Type.ContainedType;
MemoryMappedPeripheralAnnotation anMemoryMapped = null;
if(exArray is VariableExpression)
{
foreach(Operator arrayDef in nc.CurrentCFG.DataFlow_DefinitionChains[exArray.SpanningTreeIndex])
{
MemoryMappedPeripheralAnnotation an = arrayDef.GetAnnotation< MemoryMappedPeripheralAnnotation >();
if(an != null)
{
if(tdElement is ScalarTypeRepresentation)
{
anMemoryMapped = an;
break;
}
if(ts.MemoryMappedBitFieldPeripherals.ContainsKey( tdElement ))
{
anMemoryMapped = an;
break;
}
//--//
CustomAttributeRepresentation ca;
if(ts.MemoryMappedPeripherals.TryGetValue( tdElement, out ca ))
{
uint size = (uint)ca.GetNamedArg( "Length" );
if(op is LoadElementAddressOperator)
{
throw TypeConsistencyErrorException.Create( "Cannot take the address of an array of memory-mapped sections '{0}'", tdElement.FullNameWithAbbreviation );
}
else if(op is LoadElementOperator)
{
TemporaryVariableExpression tmpOffset = nc.AllocateTemporary( nc.TypeSystem.WellKnownTypes.System_UInt32 );
Operator opNew;
opNew = BinaryOperator.New( debugInfo, BinaryOperator.ALU.MUL, false, false, tmpOffset, op.SecondArgument, nc.TypeSystem.CreateConstant( size ) );
op.AddOperatorBefore( opNew );
opNew = BinaryOperator.New( debugInfo, BinaryOperator.ALU.ADD, false, false, op.FirstResult, exArray, tmpOffset );
opNew.AddAnnotation( NotNullAnnotation .Create( ts ) );
opNew.AddAnnotation( MemoryMappedPeripheralAnnotation.Create( ts, ca ) );
CHECKS.ASSERT( opNew.MayThrow == false, "Failed to lower call operator {0}", op );
op.SubstituteWithOperator( opNew, Operator.SubstitutionFlags.CopyAnnotations );
nc.MarkAsModified();
return;
}
else if(op is StoreElementOperator)
{
throw TypeConsistencyErrorException.Create( "Cannot update reference to an array of memory-mapped sections '{0}'", tdElement.FullNameWithAbbreviation );
}
else
{
throw TypeConsistencyErrorException.Create( "Unexpected operator {0} at phase {1}", op, nc.Phase );
}
}
}
}
}
if(op.MayThrow)
{
ElementOperator opNew;
if(anMemoryMapped == null)
{
op.AddOperatorBefore( NullCheckOperator .New( debugInfo, op.FirstArgument ) );
op.AddOperatorBefore( OutOfBoundCheckOperator.New( debugInfo, op.FirstArgument, op.SecondArgument ) );
}
if(op is LoadElementAddressOperator)
{
opNew = LoadElementAddressOperator.New( debugInfo, op.FirstResult, op.FirstArgument, op.SecondArgument, op.AccessPath, false );
opNew.AddAnnotation( NotNullAnnotation.Create( ts ) );
}
else if(op is LoadElementOperator)
{
opNew = LoadElementOperator.New( debugInfo, op.FirstResult, op.FirstArgument, op.SecondArgument, op.AccessPath, false );
}
else if(op is StoreElementOperator)
{
opNew = StoreElementOperator.New( debugInfo, op.FirstArgument, op.SecondArgument, op.ThirdArgument, op.AccessPath, false );
}
else
{
throw TypeConsistencyErrorException.Create( "Unexpected operator {0} at phase {1}", op, nc.Phase );
}
if(anMemoryMapped != null)
{
opNew.AddAnnotation( anMemoryMapped );
}
CHECKS.ASSERT( opNew.MayThrow == false, "Failed to lower call operator {0}", op );
op.SubstituteWithOperator( opNew, Operator.SubstitutionFlags.CopyAnnotations );
nc.MarkAsModified();
}
}
//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//
//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//
//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//
[CompilationSteps.PhaseFilter( typeof(Phases.HighLevelToMidLevelConversion) )]
[CompilationSteps.OperatorHandler( typeof(IndirectOperator) )]
private static void Handle_IndirectOperator( PhaseExecution.NotificationContext nc )
{
IndirectOperator op = (IndirectOperator)nc.CurrentOperator;
if(op.MayThrow)
{
Debugging.DebugInfo debugInfo = op.DebugInfo;
bool fIsVolatile = op.MayMutateExistingStorage;
Operator opNew;
op.AddOperatorBefore( NullCheckOperator.New( debugInfo, op.FirstArgument ) );
if(op is LoadIndirectOperator)
{
opNew = LoadIndirectOperator.New( debugInfo, op.Type, op.FirstResult, op.FirstArgument, op.AccessPath, op.Offset, fIsVolatile, false );
}
else if(op is StoreIndirectOperator)
{
opNew = StoreIndirectOperator.New( debugInfo, op.Type, op.FirstArgument, op.SecondArgument, op.AccessPath, op.Offset, false );
}
else
{
throw TypeConsistencyErrorException.Create( "Unexpected operator {0} at phase {1}", op, nc.Phase );
}
CHECKS.ASSERT( opNew.MayThrow == false, "Failed to lower call operator {0}", op );
op.SubstituteWithOperator( opNew, Operator.SubstitutionFlags.CopyAnnotations );
nc.MarkAsModified();
}
}
//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//
//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//
//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//
[CompilationSteps.PhaseFilter( typeof(Phases.HighLevelToMidLevelConversion) )]
[CompilationSteps.OperatorHandler( typeof(CallOperator) )]
private static void Handle_CallOperator( PhaseExecution.NotificationContext nc )
{
CallOperator op = (CallOperator)nc.CurrentOperator;
if(nc.TypeSystem.GetLevel( op )> Operator.OperatorLevel.ConcreteTypes_NoExceptions)
{
Debugging.DebugInfo debugInfo = op.DebugInfo;
CallOperator opNew;
if(op is InstanceCallOperator)
{
op.AddOperatorBefore( NullCheckOperator.New( debugInfo, op.FirstArgument ) );
opNew = InstanceCallOperator.New( debugInfo, op.CallType, op.TargetMethod, op.Results, op.Arguments, false );
}
else if(op is IndirectCallOperator)
{
op.AddOperatorBefore( NullCheckOperator.New( debugInfo, op.FirstArgument ) );
if(op.TargetMethod is InstanceMethodRepresentation)
{
op.AddOperatorBefore( NullCheckOperator.New( debugInfo, op.SecondArgument ) );
}
bool isInstanceCall = ((IndirectCallOperator)op).IsInstanceCall;
opNew = IndirectCallOperator.New(debugInfo, op.TargetMethod, op.Results, op.Arguments, isInstanceCall, false);
}
else
{
throw TypeConsistencyErrorException.Create( "Unexpected operator {0} at phase {1}", op, nc.Phase );
}
CHECKS.ASSERT( nc.TypeSystem.GetLevel( opNew )<= Operator.OperatorLevel.ConcreteTypes_NoExceptions, "Failed to lower call operator {0}", op );
op.SubstituteWithOperator( opNew, Operator.SubstitutionFlags.CopyAnnotations );
nc.MarkAsModified();
}
}
}
}
| |
using J2N.Threading.Atomic;
using System;
using System.Collections.Generic;
using System.Globalization;
namespace YAF.Lucene.Net.Codecs.Lucene40
{
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using BinaryDocValues = YAF.Lucene.Net.Index.BinaryDocValues;
using IBits = YAF.Lucene.Net.Util.IBits;
using BytesRef = YAF.Lucene.Net.Util.BytesRef;
using CompoundFileDirectory = YAF.Lucene.Net.Store.CompoundFileDirectory;
using CorruptIndexException = YAF.Lucene.Net.Index.CorruptIndexException;
using Directory = YAF.Lucene.Net.Store.Directory;
using FieldInfo = YAF.Lucene.Net.Index.FieldInfo;
using IndexFileNames = YAF.Lucene.Net.Index.IndexFileNames;
using IndexInput = YAF.Lucene.Net.Store.IndexInput;
using IOUtils = YAF.Lucene.Net.Util.IOUtils;
//using LegacyDocValuesType = YAF.Lucene.Net.Codecs.Lucene40.LegacyDocValuesType;
using NumericDocValues = YAF.Lucene.Net.Index.NumericDocValues;
using PackedInt32s = YAF.Lucene.Net.Util.Packed.PackedInt32s;
using PagedBytes = YAF.Lucene.Net.Util.PagedBytes;
using RamUsageEstimator = YAF.Lucene.Net.Util.RamUsageEstimator;
using SegmentReadState = YAF.Lucene.Net.Index.SegmentReadState;
using SortedDocValues = YAF.Lucene.Net.Index.SortedDocValues;
using SortedSetDocValues = YAF.Lucene.Net.Index.SortedSetDocValues;
/// <summary>
/// Reads the 4.0 format of norms/docvalues.
/// <para/>
/// @lucene.experimental
/// </summary>
[Obsolete("Only for reading old 4.0 and 4.1 segments")]
internal sealed class Lucene40DocValuesReader : DocValuesProducer
{
private readonly Directory dir;
private readonly SegmentReadState state;
private readonly string legacyKey;
private static readonly string segmentSuffix = "dv";
// ram instances we have already loaded
private readonly IDictionary<int, NumericDocValues> numericInstances = new Dictionary<int, NumericDocValues>();
private readonly IDictionary<int, BinaryDocValues> binaryInstances = new Dictionary<int, BinaryDocValues>();
private readonly IDictionary<int, SortedDocValues> sortedInstances = new Dictionary<int, SortedDocValues>();
private readonly AtomicInt64 ramBytesUsed;
internal Lucene40DocValuesReader(SegmentReadState state, string filename, string legacyKey)
{
this.state = state;
this.legacyKey = legacyKey;
this.dir = new CompoundFileDirectory(state.Directory, filename, state.Context, false);
ramBytesUsed = new AtomicInt64(RamUsageEstimator.ShallowSizeOf(this.GetType()));
}
public override NumericDocValues GetNumeric(FieldInfo field)
{
lock (this)
{
NumericDocValues instance;
if (!numericInstances.TryGetValue(field.Number, out instance))
{
string fileName = IndexFileNames.SegmentFileName(state.SegmentInfo.Name + "_" + Convert.ToString(field.Number, CultureInfo.InvariantCulture), segmentSuffix, "dat");
IndexInput input = dir.OpenInput(fileName, state.Context);
bool success = false;
try
{
var type = field.GetAttribute(legacyKey).ToLegacyDocValuesType();
//switch (Enum.Parse(typeof(LegacyDocValuesType), field.GetAttribute(LegacyKey)))
//{
if (type == LegacyDocValuesType.VAR_INTS)
{
instance = LoadVarInt32sField(field, input);
}
else if (type == LegacyDocValuesType.FIXED_INTS_8)
{
instance = LoadByteField(field, input);
}
else if (type == LegacyDocValuesType.FIXED_INTS_16)
{
instance = LoadInt16Field(field, input);
}
else if (type == LegacyDocValuesType.FIXED_INTS_32)
{
instance = LoadInt32Field(field, input);
}
else if (type == LegacyDocValuesType.FIXED_INTS_64)
{
instance = LoadInt64Field(field, input);
}
else if (type == LegacyDocValuesType.FLOAT_32)
{
instance = LoadSingleField(field, input);
}
else if (type == LegacyDocValuesType.FLOAT_64)
{
instance = LoadDoubleField(field, input);
}
else
{
throw new InvalidOperationException();
}
CodecUtil.CheckEOF(input);
success = true;
}
finally
{
if (success)
{
IOUtils.Dispose(input);
}
else
{
IOUtils.DisposeWhileHandlingException(input);
}
}
numericInstances[field.Number] = instance;
}
return instance;
}
}
/// <summary>
/// NOTE: This was loadVarIntsField() in Lucene.
/// </summary>
private NumericDocValues LoadVarInt32sField(FieldInfo field, IndexInput input)
{
CodecUtil.CheckHeader(input, Lucene40DocValuesFormat.VAR_INTS_CODEC_NAME, Lucene40DocValuesFormat.VAR_INTS_VERSION_START, Lucene40DocValuesFormat.VAR_INTS_VERSION_CURRENT);
var header = (sbyte)input.ReadByte();
if (header == Lucene40DocValuesFormat.VAR_INTS_FIXED_64)
{
int maxDoc = state.SegmentInfo.DocCount;
var values = new long[maxDoc];
for (int i = 0; i < values.Length; i++)
{
values[i] = input.ReadInt64();
}
ramBytesUsed.AddAndGet(RamUsageEstimator.SizeOf(values));
return new NumericDocValuesAnonymousInnerClassHelper(values);
}
else if (header == Lucene40DocValuesFormat.VAR_INTS_PACKED)
{
long minValue = input.ReadInt64();
long defaultValue = input.ReadInt64();
PackedInt32s.Reader reader = PackedInt32s.GetReader(input);
ramBytesUsed.AddAndGet(reader.RamBytesUsed());
return new NumericDocValuesAnonymousInnerClassHelper2(minValue, defaultValue, reader);
}
else
{
throw new CorruptIndexException("invalid VAR_INTS header byte: " + header + " (resource=" + input + ")");
}
}
private class NumericDocValuesAnonymousInnerClassHelper : NumericDocValues
{
private readonly long[] values;
public NumericDocValuesAnonymousInnerClassHelper(long[] values)
{
this.values = values;
}
public override long Get(int docID)
{
return values[docID];
}
}
private class NumericDocValuesAnonymousInnerClassHelper2 : NumericDocValues
{
private readonly long minValue;
private readonly long defaultValue;
private readonly PackedInt32s.Reader reader;
public NumericDocValuesAnonymousInnerClassHelper2(long minValue, long defaultValue, PackedInt32s.Reader reader)
{
this.minValue = minValue;
this.defaultValue = defaultValue;
this.reader = reader;
}
public override long Get(int docID)
{
long value = reader.Get(docID);
if (value == defaultValue)
{
return 0;
}
else
{
return minValue + value;
}
}
}
private NumericDocValues LoadByteField(FieldInfo field, IndexInput input)
{
CodecUtil.CheckHeader(input, Lucene40DocValuesFormat.INTS_CODEC_NAME, Lucene40DocValuesFormat.INTS_VERSION_START, Lucene40DocValuesFormat.INTS_VERSION_CURRENT);
int valueSize = input.ReadInt32();
if (valueSize != 1)
{
throw new CorruptIndexException("invalid valueSize: " + valueSize);
}
int maxDoc = state.SegmentInfo.DocCount;
var values = new byte[maxDoc];
input.ReadBytes(values, 0, values.Length);
ramBytesUsed.AddAndGet(RamUsageEstimator.SizeOf(values));
return new NumericDocValuesAnonymousInnerClassHelper3(values);
}
private class NumericDocValuesAnonymousInnerClassHelper3 : NumericDocValues
{
private readonly byte[] values;
public NumericDocValuesAnonymousInnerClassHelper3(byte[] values)
{
this.values = values;
}
public override long Get(int docID)
{
return (sbyte)values[docID];
}
}
/// <summary>
/// NOTE: This was loadShortField() in Lucene.
/// </summary>
private NumericDocValues LoadInt16Field(FieldInfo field, IndexInput input)
{
CodecUtil.CheckHeader(input, Lucene40DocValuesFormat.INTS_CODEC_NAME, Lucene40DocValuesFormat.INTS_VERSION_START, Lucene40DocValuesFormat.INTS_VERSION_CURRENT);
int valueSize = input.ReadInt32();
if (valueSize != 2)
{
throw new CorruptIndexException("invalid valueSize: " + valueSize);
}
int maxDoc = state.SegmentInfo.DocCount;
short[] values = new short[maxDoc];
for (int i = 0; i < values.Length; i++)
{
values[i] = input.ReadInt16();
}
ramBytesUsed.AddAndGet(RamUsageEstimator.SizeOf(values));
return new NumericDocValuesAnonymousInnerClassHelper4(values);
}
private class NumericDocValuesAnonymousInnerClassHelper4 : NumericDocValues
{
private readonly short[] values;
public NumericDocValuesAnonymousInnerClassHelper4(short[] values)
{
this.values = values;
}
public override long Get(int docID)
{
return values[docID];
}
}
/// <summary>
/// NOTE: This was loadIntField() in Lucene.
/// </summary>
private NumericDocValues LoadInt32Field(FieldInfo field, IndexInput input)
{
CodecUtil.CheckHeader(input, Lucene40DocValuesFormat.INTS_CODEC_NAME, Lucene40DocValuesFormat.INTS_VERSION_START, Lucene40DocValuesFormat.INTS_VERSION_CURRENT);
int valueSize = input.ReadInt32();
if (valueSize != 4)
{
throw new CorruptIndexException("invalid valueSize: " + valueSize);
}
int maxDoc = state.SegmentInfo.DocCount;
var values = new int[maxDoc];
for (int i = 0; i < values.Length; i++)
{
values[i] = input.ReadInt32();
}
ramBytesUsed.AddAndGet(RamUsageEstimator.SizeOf(values));
return new NumericDocValuesAnonymousInnerClassHelper5(values);
}
private class NumericDocValuesAnonymousInnerClassHelper5 : NumericDocValues
{
private readonly int[] values;
public NumericDocValuesAnonymousInnerClassHelper5(int[] values)
{
this.values = values;
}
public override long Get(int docID)
{
return values[docID];
}
}
/// <summary>
/// NOTE: This was loadLongField() in Lucene.
/// </summary>
private NumericDocValues LoadInt64Field(FieldInfo field, IndexInput input)
{
CodecUtil.CheckHeader(input, Lucene40DocValuesFormat.INTS_CODEC_NAME, Lucene40DocValuesFormat.INTS_VERSION_START, Lucene40DocValuesFormat.INTS_VERSION_CURRENT);
int valueSize = input.ReadInt32();
if (valueSize != 8)
{
throw new CorruptIndexException("invalid valueSize: " + valueSize);
}
int maxDoc = state.SegmentInfo.DocCount;
long[] values = new long[maxDoc];
for (int i = 0; i < values.Length; i++)
{
values[i] = input.ReadInt64();
}
ramBytesUsed.AddAndGet(RamUsageEstimator.SizeOf(values));
return new NumericDocValuesAnonymousInnerClassHelper6(values);
}
private class NumericDocValuesAnonymousInnerClassHelper6 : NumericDocValues
{
private readonly long[] values;
public NumericDocValuesAnonymousInnerClassHelper6(long[] values)
{
this.values = values;
}
public override long Get(int docID)
{
return values[docID];
}
}
/// <summary>
/// NOTE: This was loadFloatField() in Lucene.
/// </summary>
private NumericDocValues LoadSingleField(FieldInfo field, IndexInput input)
{
CodecUtil.CheckHeader(input, Lucene40DocValuesFormat.FLOATS_CODEC_NAME, Lucene40DocValuesFormat.FLOATS_VERSION_START, Lucene40DocValuesFormat.FLOATS_VERSION_CURRENT);
int valueSize = input.ReadInt32();
if (valueSize != 4)
{
throw new CorruptIndexException("invalid valueSize: " + valueSize);
}
int maxDoc = state.SegmentInfo.DocCount;
int[] values = new int[maxDoc];
for (int i = 0; i < values.Length; i++)
{
values[i] = input.ReadInt32();
}
ramBytesUsed.AddAndGet(RamUsageEstimator.SizeOf(values));
return new NumericDocValuesAnonymousInnerClassHelper7(values);
}
private class NumericDocValuesAnonymousInnerClassHelper7 : NumericDocValues
{
private readonly int[] values;
public NumericDocValuesAnonymousInnerClassHelper7(int[] values)
{
this.values = values;
}
public override long Get(int docID)
{
return values[docID];
}
}
private NumericDocValues LoadDoubleField(FieldInfo field, IndexInput input)
{
CodecUtil.CheckHeader(input, Lucene40DocValuesFormat.FLOATS_CODEC_NAME, Lucene40DocValuesFormat.FLOATS_VERSION_START, Lucene40DocValuesFormat.FLOATS_VERSION_CURRENT);
int valueSize = input.ReadInt32();
if (valueSize != 8)
{
throw new CorruptIndexException("invalid valueSize: " + valueSize);
}
int maxDoc = state.SegmentInfo.DocCount;
long[] values = new long[maxDoc];
for (int i = 0; i < values.Length; i++)
{
values[i] = input.ReadInt64();
}
ramBytesUsed.AddAndGet(RamUsageEstimator.SizeOf(values));
return new NumericDocValuesAnonymousInnerClassHelper8(values);
}
private class NumericDocValuesAnonymousInnerClassHelper8 : NumericDocValues
{
private readonly long[] values;
public NumericDocValuesAnonymousInnerClassHelper8(long[] values)
{
this.values = values;
}
public override long Get(int docID)
{
return values[docID];
}
}
public override BinaryDocValues GetBinary(FieldInfo field)
{
lock (this)
{
BinaryDocValues instance;
if (!binaryInstances.TryGetValue(field.Number, out instance))
{
var type = field.GetAttribute(legacyKey).ToLegacyDocValuesType();
if (type == LegacyDocValuesType.BYTES_FIXED_STRAIGHT)
{
instance = LoadBytesFixedStraight(field);
}
else if (type == LegacyDocValuesType.BYTES_VAR_STRAIGHT)
{
instance = LoadBytesVarStraight(field);
}
else if (type == LegacyDocValuesType.BYTES_FIXED_DEREF)
{
instance = LoadBytesFixedDeref(field);
}
else if (type == LegacyDocValuesType.BYTES_VAR_DEREF)
{
instance = LoadBytesVarDeref(field);
}
else
{
throw new InvalidOperationException();
}
binaryInstances[field.Number] = instance;
}
return instance;
}
}
private BinaryDocValues LoadBytesFixedStraight(FieldInfo field)
{
string fileName = IndexFileNames.SegmentFileName(state.SegmentInfo.Name + "_" + Convert.ToString(field.Number, CultureInfo.InvariantCulture), segmentSuffix, "dat");
IndexInput input = dir.OpenInput(fileName, state.Context);
bool success = false;
try
{
CodecUtil.CheckHeader(input, Lucene40DocValuesFormat.BYTES_FIXED_STRAIGHT_CODEC_NAME, Lucene40DocValuesFormat.BYTES_FIXED_STRAIGHT_VERSION_START, Lucene40DocValuesFormat.BYTES_FIXED_STRAIGHT_VERSION_CURRENT);
int fixedLength = input.ReadInt32();
var bytes = new PagedBytes(16);
bytes.Copy(input, fixedLength * (long)state.SegmentInfo.DocCount);
PagedBytes.Reader bytesReader = bytes.Freeze(true);
CodecUtil.CheckEOF(input);
success = true;
ramBytesUsed.AddAndGet(bytes.RamBytesUsed());
return new BinaryDocValuesAnonymousInnerClassHelper(fixedLength, bytesReader);
}
finally
{
if (success)
{
IOUtils.Dispose(input);
}
else
{
IOUtils.DisposeWhileHandlingException(input);
}
}
}
private class BinaryDocValuesAnonymousInnerClassHelper : BinaryDocValues
{
private readonly int fixedLength;
private readonly PagedBytes.Reader bytesReader;
public BinaryDocValuesAnonymousInnerClassHelper(int fixedLength, PagedBytes.Reader bytesReader)
{
this.fixedLength = fixedLength;
this.bytesReader = bytesReader;
}
public override void Get(int docID, BytesRef result)
{
bytesReader.FillSlice(result, fixedLength * (long)docID, fixedLength);
}
}
private BinaryDocValues LoadBytesVarStraight(FieldInfo field)
{
string dataName = IndexFileNames.SegmentFileName(state.SegmentInfo.Name + "_" + Convert.ToString(field.Number, CultureInfo.InvariantCulture), segmentSuffix, "dat");
string indexName = IndexFileNames.SegmentFileName(state.SegmentInfo.Name + "_" + Convert.ToString(field.Number, CultureInfo.InvariantCulture), segmentSuffix, "idx");
IndexInput data = null;
IndexInput index = null;
bool success = false;
try
{
data = dir.OpenInput(dataName, state.Context);
CodecUtil.CheckHeader(data, Lucene40DocValuesFormat.BYTES_VAR_STRAIGHT_CODEC_NAME_DAT, Lucene40DocValuesFormat.BYTES_VAR_STRAIGHT_VERSION_START, Lucene40DocValuesFormat.BYTES_VAR_STRAIGHT_VERSION_CURRENT);
index = dir.OpenInput(indexName, state.Context);
CodecUtil.CheckHeader(index, Lucene40DocValuesFormat.BYTES_VAR_STRAIGHT_CODEC_NAME_IDX, Lucene40DocValuesFormat.BYTES_VAR_STRAIGHT_VERSION_START, Lucene40DocValuesFormat.BYTES_VAR_STRAIGHT_VERSION_CURRENT);
long totalBytes = index.ReadVInt64();
PagedBytes bytes = new PagedBytes(16);
bytes.Copy(data, totalBytes);
PagedBytes.Reader bytesReader = bytes.Freeze(true);
PackedInt32s.Reader reader = PackedInt32s.GetReader(index);
CodecUtil.CheckEOF(data);
CodecUtil.CheckEOF(index);
success = true;
ramBytesUsed.AddAndGet(bytes.RamBytesUsed() + reader.RamBytesUsed());
return new BinaryDocValuesAnonymousInnerClassHelper2(bytesReader, reader);
}
finally
{
if (success)
{
IOUtils.Dispose(data, index);
}
else
{
IOUtils.DisposeWhileHandlingException(data, index);
}
}
}
private class BinaryDocValuesAnonymousInnerClassHelper2 : BinaryDocValues
{
private readonly PagedBytes.Reader bytesReader;
private readonly PackedInt32s.Reader reader;
public BinaryDocValuesAnonymousInnerClassHelper2(PagedBytes.Reader bytesReader, PackedInt32s.Reader reader)
{
this.bytesReader = bytesReader;
this.reader = reader;
}
public override void Get(int docID, BytesRef result)
{
long startAddress = reader.Get(docID);
long endAddress = reader.Get(docID + 1);
bytesReader.FillSlice(result, startAddress, (int)(endAddress - startAddress));
}
}
private BinaryDocValues LoadBytesFixedDeref(FieldInfo field)
{
string dataName = IndexFileNames.SegmentFileName(state.SegmentInfo.Name + "_" + Convert.ToString(field.Number, CultureInfo.InvariantCulture), segmentSuffix, "dat");
string indexName = IndexFileNames.SegmentFileName(state.SegmentInfo.Name + "_" + Convert.ToString(field.Number, CultureInfo.InvariantCulture), segmentSuffix, "idx");
IndexInput data = null;
IndexInput index = null;
bool success = false;
try
{
data = dir.OpenInput(dataName, state.Context);
CodecUtil.CheckHeader(data, Lucene40DocValuesFormat.BYTES_FIXED_DEREF_CODEC_NAME_DAT, Lucene40DocValuesFormat.BYTES_FIXED_DEREF_VERSION_START, Lucene40DocValuesFormat.BYTES_FIXED_DEREF_VERSION_CURRENT);
index = dir.OpenInput(indexName, state.Context);
CodecUtil.CheckHeader(index, Lucene40DocValuesFormat.BYTES_FIXED_DEREF_CODEC_NAME_IDX, Lucene40DocValuesFormat.BYTES_FIXED_DEREF_VERSION_START, Lucene40DocValuesFormat.BYTES_FIXED_DEREF_VERSION_CURRENT);
int fixedLength = data.ReadInt32();
int valueCount = index.ReadInt32();
PagedBytes bytes = new PagedBytes(16);
bytes.Copy(data, fixedLength * (long)valueCount);
PagedBytes.Reader bytesReader = bytes.Freeze(true);
PackedInt32s.Reader reader = PackedInt32s.GetReader(index);
CodecUtil.CheckEOF(data);
CodecUtil.CheckEOF(index);
ramBytesUsed.AddAndGet(bytes.RamBytesUsed() + reader.RamBytesUsed());
success = true;
return new BinaryDocValuesAnonymousInnerClassHelper3(fixedLength, bytesReader, reader);
}
finally
{
if (success)
{
IOUtils.Dispose(data, index);
}
else
{
IOUtils.DisposeWhileHandlingException(data, index);
}
}
}
private class BinaryDocValuesAnonymousInnerClassHelper3 : BinaryDocValues
{
private readonly int fixedLength;
private readonly PagedBytes.Reader bytesReader;
private readonly PackedInt32s.Reader reader;
public BinaryDocValuesAnonymousInnerClassHelper3(int fixedLength, PagedBytes.Reader bytesReader, PackedInt32s.Reader reader)
{
this.fixedLength = fixedLength;
this.bytesReader = bytesReader;
this.reader = reader;
}
public override void Get(int docID, BytesRef result)
{
long offset = fixedLength * reader.Get(docID);
bytesReader.FillSlice(result, offset, fixedLength);
}
}
private BinaryDocValues LoadBytesVarDeref(FieldInfo field)
{
string dataName = IndexFileNames.SegmentFileName(state.SegmentInfo.Name + "_" + Convert.ToString(field.Number, CultureInfo.InvariantCulture), segmentSuffix, "dat");
string indexName = IndexFileNames.SegmentFileName(state.SegmentInfo.Name + "_" + Convert.ToString(field.Number, CultureInfo.InvariantCulture), segmentSuffix, "idx");
IndexInput data = null;
IndexInput index = null;
bool success = false;
try
{
data = dir.OpenInput(dataName, state.Context);
CodecUtil.CheckHeader(data, Lucene40DocValuesFormat.BYTES_VAR_DEREF_CODEC_NAME_DAT, Lucene40DocValuesFormat.BYTES_VAR_DEREF_VERSION_START, Lucene40DocValuesFormat.BYTES_VAR_DEREF_VERSION_CURRENT);
index = dir.OpenInput(indexName, state.Context);
CodecUtil.CheckHeader(index, Lucene40DocValuesFormat.BYTES_VAR_DEREF_CODEC_NAME_IDX, Lucene40DocValuesFormat.BYTES_VAR_DEREF_VERSION_START, Lucene40DocValuesFormat.BYTES_VAR_DEREF_VERSION_CURRENT);
long totalBytes = index.ReadInt64();
PagedBytes bytes = new PagedBytes(16);
bytes.Copy(data, totalBytes);
PagedBytes.Reader bytesReader = bytes.Freeze(true);
PackedInt32s.Reader reader = PackedInt32s.GetReader(index);
CodecUtil.CheckEOF(data);
CodecUtil.CheckEOF(index);
ramBytesUsed.AddAndGet(bytes.RamBytesUsed() + reader.RamBytesUsed());
success = true;
return new BinaryDocValuesAnonymousInnerClassHelper4(bytesReader, reader);
}
finally
{
if (success)
{
IOUtils.Dispose(data, index);
}
else
{
IOUtils.DisposeWhileHandlingException(data, index);
}
}
}
private class BinaryDocValuesAnonymousInnerClassHelper4 : BinaryDocValues
{
private readonly PagedBytes.Reader bytesReader;
private readonly PackedInt32s.Reader reader;
public BinaryDocValuesAnonymousInnerClassHelper4(PagedBytes.Reader bytesReader, PackedInt32s.Reader reader)
{
this.bytesReader = bytesReader;
this.reader = reader;
}
public override void Get(int docID, BytesRef result)
{
long startAddress = reader.Get(docID);
BytesRef lengthBytes = new BytesRef();
bytesReader.FillSlice(lengthBytes, startAddress, 1);
var code = lengthBytes.Bytes[lengthBytes.Offset];
if ((code & 128) == 0)
{
// length is 1 byte
bytesReader.FillSlice(result, startAddress + 1, (int)code);
}
else
{
bytesReader.FillSlice(lengthBytes, startAddress + 1, 1);
int length = ((code & 0x7f) << 8) | (lengthBytes.Bytes[lengthBytes.Offset] & 0xff);
bytesReader.FillSlice(result, startAddress + 2, length);
}
}
}
public override SortedDocValues GetSorted(FieldInfo field)
{
lock (this)
{
SortedDocValues instance;
if (!sortedInstances.TryGetValue(field.Number, out instance))
{
string dataName = IndexFileNames.SegmentFileName(state.SegmentInfo.Name + "_" + Convert.ToString(field.Number, CultureInfo.InvariantCulture), segmentSuffix, "dat");
string indexName = IndexFileNames.SegmentFileName(state.SegmentInfo.Name + "_" + Convert.ToString(field.Number, CultureInfo.InvariantCulture), segmentSuffix, "idx");
IndexInput data = null;
IndexInput index = null;
bool success = false;
try
{
data = dir.OpenInput(dataName, state.Context);
index = dir.OpenInput(indexName, state.Context);
var type = field.GetAttribute(legacyKey).ToLegacyDocValuesType();
if (type == LegacyDocValuesType.BYTES_FIXED_SORTED)
{
instance = LoadBytesFixedSorted(field, data, index);
}
else if (type == LegacyDocValuesType.BYTES_VAR_SORTED)
{
instance = LoadBytesVarSorted(field, data, index);
}
else
{
throw new InvalidOperationException();
}
CodecUtil.CheckEOF(data);
CodecUtil.CheckEOF(index);
success = true;
}
finally
{
if (success)
{
IOUtils.Dispose(data, index);
}
else
{
IOUtils.DisposeWhileHandlingException(data, index);
}
}
sortedInstances[field.Number] = instance;
}
return instance;
}
}
private SortedDocValues LoadBytesFixedSorted(FieldInfo field, IndexInput data, IndexInput index)
{
CodecUtil.CheckHeader(data, Lucene40DocValuesFormat.BYTES_FIXED_SORTED_CODEC_NAME_DAT, Lucene40DocValuesFormat.BYTES_FIXED_SORTED_VERSION_START, Lucene40DocValuesFormat.BYTES_FIXED_SORTED_VERSION_CURRENT);
CodecUtil.CheckHeader(index, Lucene40DocValuesFormat.BYTES_FIXED_SORTED_CODEC_NAME_IDX, Lucene40DocValuesFormat.BYTES_FIXED_SORTED_VERSION_START, Lucene40DocValuesFormat.BYTES_FIXED_SORTED_VERSION_CURRENT);
int fixedLength = data.ReadInt32();
int valueCount = index.ReadInt32();
PagedBytes bytes = new PagedBytes(16);
bytes.Copy(data, fixedLength * (long)valueCount);
PagedBytes.Reader bytesReader = bytes.Freeze(true);
PackedInt32s.Reader reader = PackedInt32s.GetReader(index);
ramBytesUsed.AddAndGet(bytes.RamBytesUsed() + reader.RamBytesUsed());
return CorrectBuggyOrds(new SortedDocValuesAnonymousInnerClassHelper(fixedLength, valueCount, bytesReader, reader));
}
private class SortedDocValuesAnonymousInnerClassHelper : SortedDocValues
{
private readonly int fixedLength;
private readonly int valueCount;
private readonly PagedBytes.Reader bytesReader;
private readonly PackedInt32s.Reader reader;
public SortedDocValuesAnonymousInnerClassHelper(int fixedLength, int valueCount, PagedBytes.Reader bytesReader, PackedInt32s.Reader reader)
{
this.fixedLength = fixedLength;
this.valueCount = valueCount;
this.bytesReader = bytesReader;
this.reader = reader;
}
public override int GetOrd(int docID)
{
return (int)reader.Get(docID);
}
public override void LookupOrd(int ord, BytesRef result)
{
bytesReader.FillSlice(result, fixedLength * (long)ord, fixedLength);
}
public override int ValueCount
{
get
{
return valueCount;
}
}
}
private SortedDocValues LoadBytesVarSorted(FieldInfo field, IndexInput data, IndexInput index)
{
CodecUtil.CheckHeader(data, Lucene40DocValuesFormat.BYTES_VAR_SORTED_CODEC_NAME_DAT, Lucene40DocValuesFormat.BYTES_VAR_SORTED_VERSION_START, Lucene40DocValuesFormat.BYTES_VAR_SORTED_VERSION_CURRENT);
CodecUtil.CheckHeader(index, Lucene40DocValuesFormat.BYTES_VAR_SORTED_CODEC_NAME_IDX, Lucene40DocValuesFormat.BYTES_VAR_SORTED_VERSION_START, Lucene40DocValuesFormat.BYTES_VAR_SORTED_VERSION_CURRENT);
long maxAddress = index.ReadInt64();
PagedBytes bytes = new PagedBytes(16);
bytes.Copy(data, maxAddress);
PagedBytes.Reader bytesReader = bytes.Freeze(true);
PackedInt32s.Reader addressReader = PackedInt32s.GetReader(index);
PackedInt32s.Reader ordsReader = PackedInt32s.GetReader(index);
int valueCount = addressReader.Count - 1;
ramBytesUsed.AddAndGet(bytes.RamBytesUsed() + addressReader.RamBytesUsed() + ordsReader.RamBytesUsed());
return CorrectBuggyOrds(new SortedDocValuesAnonymousInnerClassHelper2(bytesReader, addressReader, ordsReader, valueCount));
}
private class SortedDocValuesAnonymousInnerClassHelper2 : SortedDocValues
{
private readonly PagedBytes.Reader bytesReader;
private readonly PackedInt32s.Reader addressReader;
private readonly PackedInt32s.Reader ordsReader;
private readonly int valueCount;
public SortedDocValuesAnonymousInnerClassHelper2(PagedBytes.Reader bytesReader, PackedInt32s.Reader addressReader, PackedInt32s.Reader ordsReader, int valueCount)
{
this.bytesReader = bytesReader;
this.addressReader = addressReader;
this.ordsReader = ordsReader;
this.valueCount = valueCount;
}
public override int GetOrd(int docID)
{
return (int)ordsReader.Get(docID);
}
public override void LookupOrd(int ord, BytesRef result)
{
long startAddress = addressReader.Get(ord);
long endAddress = addressReader.Get(ord + 1);
bytesReader.FillSlice(result, startAddress, (int)(endAddress - startAddress));
}
public override int ValueCount
{
get
{
return valueCount;
}
}
}
// detects and corrects LUCENE-4717 in old indexes
private SortedDocValues CorrectBuggyOrds(SortedDocValues @in)
{
int maxDoc = state.SegmentInfo.DocCount;
for (int i = 0; i < maxDoc; i++)
{
if (@in.GetOrd(i) == 0)
{
return @in; // ok
}
}
// we had ord holes, return an ord-shifting-impl that corrects the bug
return new SortedDocValuesAnonymousInnerClassHelper3(@in);
}
private class SortedDocValuesAnonymousInnerClassHelper3 : SortedDocValues
{
private readonly SortedDocValues @in;
public SortedDocValuesAnonymousInnerClassHelper3(SortedDocValues @in)
{
this.@in = @in;
}
public override int GetOrd(int docID)
{
return @in.GetOrd(docID) - 1;
}
public override void LookupOrd(int ord, BytesRef result)
{
@in.LookupOrd(ord + 1, result);
}
public override int ValueCount
{
get
{
return @in.ValueCount - 1;
}
}
}
public override SortedSetDocValues GetSortedSet(FieldInfo field)
{
throw new InvalidOperationException("Lucene 4.0 does not support SortedSet: how did you pull this off?");
}
public override IBits GetDocsWithField(FieldInfo field)
{
return new Lucene.Net.Util.Bits.MatchAllBits(state.SegmentInfo.DocCount);
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
dir.Dispose();
}
}
public override long RamBytesUsed() => ramBytesUsed;
public override void CheckIntegrity() { }
}
}
| |
// 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.Logic
{
using System;
using System.Linq;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Rest;
using Microsoft.Rest.Serialization;
using Newtonsoft.Json;
using Microsoft.Rest.Azure;
using Models;
/// <summary>
/// IntegrationAccountCertificatesOperations operations.
/// </summary>
internal partial class IntegrationAccountCertificatesOperations : IServiceOperations<LogicManagementClient>, IIntegrationAccountCertificatesOperations
{
/// <summary>
/// Initializes a new instance of the IntegrationAccountCertificatesOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
/// <exception cref="ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
internal IntegrationAccountCertificatesOperations(LogicManagementClient client)
{
if (client == null)
{
throw new ArgumentNullException("client");
}
this.Client = client;
}
/// <summary>
/// Gets a reference to the LogicManagementClient
/// </summary>
public LogicManagementClient Client { get; private set; }
/// <summary>
/// Gets a list of integration account certificates.
/// </summary>
/// <param name='resourceGroupName'>
/// The resource group name.
/// </param>
/// <param name='integrationAccountName'>
/// The integration account name.
/// </param>
/// <param name='top'>
/// The number of items to be included in the result.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IPage<IntegrationAccountCertificate>>> ListWithHttpMessagesAsync(string resourceGroupName, string integrationAccountName, int? top = default(int?), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (this.Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (integrationAccountName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "integrationAccountName");
}
string apiVersion = "2015-08-01-preview";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("integrationAccountName", integrationAccountName);
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("top", top);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "List", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Logic/integrationAccounts/{integrationAccountName}/certificates").ToString();
_url = _url.Replace("{subscriptionId}", Uri.EscapeDataString(this.Client.SubscriptionId));
_url = _url.Replace("{resourceGroupName}", Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{integrationAccountName}", Uri.EscapeDataString(integrationAccountName));
List<string> _queryParameters = new List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(apiVersion)));
}
if (top != null)
{
_queryParameters.Add(string.Format("$top={0}", Uri.EscapeDataString(SafeJsonConvert.SerializeObject(top, this.Client.SerializationSettings).Trim('"'))));
}
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", 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)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IPage<IntegrationAccountCertificate>>();
_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 = SafeJsonConvert.DeserializeObject<Page<IntegrationAccountCertificate>>(_responseContent, this.Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Gets an integration account certificate.
/// </summary>
/// <param name='resourceGroupName'>
/// The resource group name.
/// </param>
/// <param name='integrationAccountName'>
/// The integration account name.
/// </param>
/// <param name='certificateName'>
/// The integration account certificate name.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IntegrationAccountCertificate>> GetWithHttpMessagesAsync(string resourceGroupName, string integrationAccountName, string certificateName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (this.Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (integrationAccountName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "integrationAccountName");
}
if (certificateName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "certificateName");
}
string apiVersion = "2015-08-01-preview";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("integrationAccountName", integrationAccountName);
tracingParameters.Add("certificateName", certificateName);
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Logic/integrationAccounts/{integrationAccountName}/certificates/{certificateName}").ToString();
_url = _url.Replace("{subscriptionId}", Uri.EscapeDataString(this.Client.SubscriptionId));
_url = _url.Replace("{resourceGroupName}", Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{integrationAccountName}", Uri.EscapeDataString(integrationAccountName));
_url = _url.Replace("{certificateName}", Uri.EscapeDataString(certificateName));
List<string> _queryParameters = new List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(apiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", 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)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IntegrationAccountCertificate>();
_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 = SafeJsonConvert.DeserializeObject<IntegrationAccountCertificate>(_responseContent, this.Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Creates or updates an integration account certificate.
/// </summary>
/// <param name='resourceGroupName'>
/// The resource group name.
/// </param>
/// <param name='integrationAccountName'>
/// The integration account name.
/// </param>
/// <param name='certificateName'>
/// The integration account certificate name.
/// </param>
/// <param name='certificate'>
/// The integration account certificate.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IntegrationAccountCertificate>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string integrationAccountName, string certificateName, IntegrationAccountCertificate certificate, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (this.Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (integrationAccountName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "integrationAccountName");
}
if (certificateName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "certificateName");
}
if (certificate == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "certificate");
}
string apiVersion = "2015-08-01-preview";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("integrationAccountName", integrationAccountName);
tracingParameters.Add("certificateName", certificateName);
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("certificate", certificate);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "CreateOrUpdate", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Logic/integrationAccounts/{integrationAccountName}/certificates/{certificateName}").ToString();
_url = _url.Replace("{subscriptionId}", Uri.EscapeDataString(this.Client.SubscriptionId));
_url = _url.Replace("{resourceGroupName}", Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{integrationAccountName}", Uri.EscapeDataString(integrationAccountName));
_url = _url.Replace("{certificateName}", Uri.EscapeDataString(certificateName));
List<string> _queryParameters = new List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(apiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("PUT");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
if(certificate != null)
{
_requestContent = SafeJsonConvert.SerializeObject(certificate, this.Client.SerializationSettings);
_httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8);
_httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
}
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200 && (int)_statusCode != 201)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IntegrationAccountCertificate>();
_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 = SafeJsonConvert.DeserializeObject<IntegrationAccountCertificate>(_responseContent, this.Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
// Deserialize Response
if ((int)_statusCode == 201)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = SafeJsonConvert.DeserializeObject<IntegrationAccountCertificate>(_responseContent, this.Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Deletes an integration account certificate.
/// </summary>
/// <param name='resourceGroupName'>
/// The resource group name.
/// </param>
/// <param name='integrationAccountName'>
/// The integration account name.
/// </param>
/// <param name='certificateName'>
/// The integration account certificate name.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string integrationAccountName, string certificateName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (this.Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (integrationAccountName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "integrationAccountName");
}
if (certificateName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "certificateName");
}
string apiVersion = "2015-08-01-preview";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("integrationAccountName", integrationAccountName);
tracingParameters.Add("certificateName", certificateName);
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "Delete", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Logic/integrationAccounts/{integrationAccountName}/certificates/{certificateName}").ToString();
_url = _url.Replace("{subscriptionId}", Uri.EscapeDataString(this.Client.SubscriptionId));
_url = _url.Replace("{resourceGroupName}", Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{integrationAccountName}", Uri.EscapeDataString(integrationAccountName));
_url = _url.Replace("{certificateName}", Uri.EscapeDataString(certificateName));
List<string> _queryParameters = new List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(apiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("DELETE");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", 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)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200 && (int)_statusCode != 204)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
if (_httpResponse.Content != null) {
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
}
else {
_responseContent = string.Empty;
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Gets a list of integration account certificates.
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IPage<IntegrationAccountCertificate>>> ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (nextPageLink == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("nextPageLink", nextPageLink);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "ListNext", tracingParameters);
}
// Construct URL
string _url = "{nextLink}";
_url = _url.Replace("{nextLink}", nextPageLink);
List<string> _queryParameters = new List<string>();
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", 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)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IPage<IntegrationAccountCertificate>>();
_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 = SafeJsonConvert.DeserializeObject<Page<IntegrationAccountCertificate>>(_responseContent, this.Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
| |
using UnityEngine;
using System.Collections;
using AsyncRPGSharedLib.Environment;
public class WidgetEventDispatcher
{
private enum eMouseButton
{
left= 0,
right= 1,
middle= 2
}
private WidgetGroup m_rootWidgetGroup;
private Point2d m_mousePosition;
private bool m_mouseIsDragging;
private bool m_mouseWasDown;
private IWidget m_mouseDownIWidget;
private IWidget m_mouseOverIWidget;
public WidgetEventDispatcher()
{
m_mousePosition = new Point2d();
m_rootWidgetGroup = null;
m_mouseOverIWidget = null;
m_mouseDownIWidget = null;
m_mouseIsDragging = false;
m_mouseWasDown = false;
}
public IWidget MouseOverWidget
{
get { return m_mouseOverIWidget; }
}
public bool LogEnabled
{
get
{
return Debug.isDebugBuild ? DebugRegistry.TestToggle("ui.event.log") : false;
}
}
public void Start(WidgetGroup widgetGroup)
{
Point2d newMousePosition = GetMousePosition();
m_rootWidgetGroup = widgetGroup;
m_mousePosition.Set(newMousePosition.x, newMousePosition.y);
m_mouseOverIWidget = m_rootWidgetGroup.FindChildIWidgetContainingPoint(m_mousePosition);
m_mouseIsDragging = false;
m_mouseWasDown = Input.GetMouseButton((int)eMouseButton.left);
if (Debug.isDebugBuild)
{
DebugRegistry.SetToggle("ui.event.log", false);
}
}
public void Update()
{
Point2d mousePosition = GetMousePosition();
float mouseScrollAmount= Input.GetAxis("Mouse ScrollWheel");
bool mouseIsDown = Input.GetMouseButton((int)eMouseButton.left);
if (mousePosition.x != m_mousePosition.x || mousePosition.y != m_mousePosition.y)
{
OnMouseMove(mousePosition.x, mousePosition.y);
}
if (mouseScrollAmount != 0.0f)
{
OnMouseWheel(mouseScrollAmount);
}
if (!m_mouseWasDown && mouseIsDown)
{
OnMouseDown();
}
else if (m_mouseWasDown && !mouseIsDown)
{
OnMouseUp();
}
m_mouseWasDown = mouseIsDown;
}
public void OnDestroy()
{
m_mouseOverIWidget = null;
}
// Unity Mouse Event Handlers
private void OnMouseUp()
{
m_mouseIsDragging = false;
if (m_mouseOverIWidget != null)
{
{
WidgetEvent.MouseUpEventParameters eventParameters =
new WidgetEvent.MouseUpEventParameters
{
worldX = m_mousePosition.x,
worldY = m_mousePosition.y,
localX = m_mousePosition.x - m_mouseOverIWidget.WorldX,
localY = m_mousePosition.y - m_mouseOverIWidget.WorldY
};
if (LogEnabled)
{
Debug.Log("[MouseUp] on Widget " + m_mouseOverIWidget.GetType().Name);
}
// Notify the widget that the mouse was released
(m_mouseOverIWidget as IWidgetEventListener).OnWidgetEvent(
new WidgetEvent(WidgetEvent.eEventType.mouseUp, m_mouseOverIWidget, eventParameters));
}
// Notify the widget if we clicked on it
if (m_mouseOverIWidget == m_mouseDownIWidget)
{
WidgetEvent.MouseClickEventParameters eventParameters =
new WidgetEvent.MouseClickEventParameters
{
worldX = m_mousePosition.x,
worldY = m_mousePosition.y,
localX = m_mousePosition.x - m_mouseOverIWidget.WorldX,
localY = m_mousePosition.y - m_mouseOverIWidget.WorldY
};
if (LogEnabled)
{
Debug.Log("[MouseClick] on Widget " + m_mouseOverIWidget.GetType().Name);
}
(m_mouseOverIWidget as IWidgetEventListener).OnWidgetEvent(
new WidgetEvent(WidgetEvent.eEventType.mouseClick, m_mouseOverIWidget, eventParameters));
}
}
m_mouseDownIWidget = null;
}
private void OnMouseDown()
{
m_mouseIsDragging = true;
// Notify the widget of a drag event
if (m_mouseOverIWidget != null)
{
WidgetEvent.MouseDownEventParameters eventParameters =
new WidgetEvent.MouseDownEventParameters {
worldX= m_mousePosition.x,
worldY= m_mousePosition.y,
localX= m_mousePosition.x - m_mouseOverIWidget.WorldX,
localY= m_mousePosition.y - m_mouseOverIWidget.WorldY };
if (LogEnabled)
{
Debug.Log("[MouseDown] on Widget " + m_mouseOverIWidget.GetType().Name);
}
(m_mouseOverIWidget as IWidgetEventListener).OnWidgetEvent(
new WidgetEvent(WidgetEvent.eEventType.mouseDown, m_mouseOverIWidget, eventParameters));
m_mouseDownIWidget = m_mouseOverIWidget;
}
}
private void OnMouseMove(float newMouseX, float newMouseY)
{
float mouseDeltaX = newMouseX - m_mousePosition.x;
float mouseDeltaY = newMouseY - m_mousePosition.y;
//Debug.Log("Mouse: " + newMouseX.ToString() + ", " + newMouseY.ToString());
m_mousePosition.Set(newMouseX, newMouseY);
// Notify the widget of a drag event
if (m_mouseOverIWidget != null)
{
if (m_mouseIsDragging)
{
if (LogEnabled)
{
Debug.Log("[MouseDrag] on Widget " + m_mouseOverIWidget.GetType().Name);
}
(m_mouseOverIWidget as IWidgetEventListener).OnWidgetEvent(
new WidgetEvent(
WidgetEvent.eEventType.mouseDrag,
m_mouseOverIWidget,
new WidgetEvent.MouseDragEventParameters { deltaX= mouseDeltaX, deltaY= mouseDeltaY } ));
}
else
{
if (LogEnabled)
{
Debug.Log("[MouseMove] on Widget " + m_mouseOverIWidget.GetType().Name);
}
(m_mouseOverIWidget as IWidgetEventListener).OnWidgetEvent(
new WidgetEvent(
WidgetEvent.eEventType.mouseMove,
m_mouseOverIWidget,
new WidgetEvent.MouseMoveEventParameters { deltaX= mouseDeltaX, deltaY= mouseDeltaY } ));
}
}
{
IWidget newMouseOverWidget = m_rootWidgetGroup.FindChildIWidgetContainingPoint(m_mousePosition);
// See if we have moved over a new widget
if (newMouseOverWidget != m_mouseOverIWidget)
{
// Notify the old widget the cursor left
if (m_mouseOverIWidget != null)
{
if (LogEnabled)
{
Debug.Log("[MouseOut] on Widget " + m_mouseOverIWidget.GetType().Name);
}
(m_mouseOverIWidget as IWidgetEventListener).OnWidgetEvent(
new WidgetEvent(
WidgetEvent.eEventType.mouseOut,
m_mouseOverIWidget,
null));
}
// Notify the new mouse over widget we entered
if (newMouseOverWidget != null)
{
if (LogEnabled)
{
Debug.Log("[MouseOver] on Widget " + newMouseOverWidget.GetType().Name);
}
(newMouseOverWidget as IWidgetEventListener).OnWidgetEvent(
new WidgetEvent(
WidgetEvent.eEventType.mouseOver,
newMouseOverWidget,
null));
}
// Remember the new mouse over widget
m_mouseOverIWidget = newMouseOverWidget;
}
}
}
private void OnMouseWheel(float scrollDelta)
{
if (m_mouseOverIWidget != null)
{
if (LogEnabled)
{
Debug.Log("[MouseWheel] on Widget " + m_mouseOverIWidget.GetType().Name);
}
(m_mouseOverIWidget as IWidgetEventListener).OnWidgetEvent(
new WidgetEvent(
WidgetEvent.eEventType.mouseWheel,
m_mouseOverIWidget,
new WidgetEvent.MousWheelEventParameters {delta= scrollDelta} ));
}
}
public static Point2d GetMousePosition()
{
Vector3 unityMousePosition = Input.mousePosition;
Point2d gameMousePosition = new Point2d(unityMousePosition.x, Screen.height - unityMousePosition.y);
return gameMousePosition;
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using Xunit;
using System;
using System.Collections;
using System.Collections.Specialized;
namespace System.Collections.Specialized.Tests
{
public class KeysCollectionCopyToTests
{
private String _strErr = "Error!";
[Fact]
public void Test01()
{
MyNameObjectCollection noc = new MyNameObjectCollection();
Array array = null;
ArrayList ArrayValues = new ArrayList();
Random rand = new Random(-55);
int n = 0;
String key1 = "key1";
String key2 = "key2";
Foo val1 = new Foo();
Foo val2 = new Foo();
// [] Copy a collection to middle of target array.
// Set up initial collection
n = rand.Next(10, 1000);
for (int i = 0; i < n; i++)
{
noc.Add("key_" + i.ToString(), new Foo());
}
// Set up initial array
n = noc.Count + rand.Next(20, 100);
array = Array.CreateInstance(typeof(String), n);
ArrayValues.Clear();
for (int i = 0; i < n; i++)
{
String v = "arrayvalue_" + i.ToString();
array.SetValue(v, i);
ArrayValues.Add(v);
}
// Copy the collection
int offset = 10;
((ICollection)noc.Keys).CopyTo(array, offset);
for (int i = 0; i < noc.Count; i++)
{
ArrayValues[i + offset] = noc.GetKey(i);
}
// Check array
CheckArray(array, ArrayValues);
// [] Verify copy is distinct from original collection.
// Clear initial collection
noc.Clear();
// Verify copy is not cleared
CheckArray(array, ArrayValues);
// [] Fill whole array (index=0)
// Set up initial collection
noc = new MyNameObjectCollection();
n = rand.Next(10, 1000);
for (int i = 0; i < n; i++)
{
noc.Add("key_" + i.ToString(), new Foo());
}
// Set up initial array
n = noc.Count;
array = Array.CreateInstance(typeof(String), n);
ArrayValues.Clear();
for (int i = 0; i < n; i++)
{
String v = "arrayvalue_" + i.ToString();
array.SetValue(v, i);
ArrayValues.Add(v);
}
// Copy the collection
((ICollection)noc.Keys).CopyTo(array, 0);
for (int i = 0; i < noc.Count; i++)
{
ArrayValues[i] = noc.GetKey(i);
}
// Check array
CheckArray(array, ArrayValues);
// [] index = max index in array
// Set up initial collection
noc.Clear();
noc.Add("key1", new Foo());
// Set up initial array
n = noc.Count + rand.Next(1, 100);
array = Array.CreateInstance(typeof(String), n);
ArrayValues.Clear();
for (int i = 0; i < n; i++)
{
String v = "arrayvalue_" + i.ToString();
array.SetValue(v, i);
ArrayValues.Add(v);
}
// Copy the collection
offset = ArrayValues.Count - 1;
((ICollection)noc.Keys).CopyTo(array, offset);
ArrayValues[offset] = noc.GetKey(0);
// Retrieve values
CheckArray(array, ArrayValues);
// [] Target array is zero-length.
array = Array.CreateInstance(typeof(String), 0);
noc = new MyNameObjectCollection();
noc.Add(key1, val1);
noc.Add(key2, val2);
Assert.Throws<ArgumentException>(() => { ((ICollection)noc.Keys).CopyTo(array, 0); });
// [] Call on an empty collection (to zero-length array).
noc = new MyNameObjectCollection();
array = Array.CreateInstance(typeof(String), 0);
// Copy the collection
((ICollection)noc.Keys).CopyTo(array, 0);
// [] Call on an empty collection.
noc = new MyNameObjectCollection();
array = Array.CreateInstance(typeof(String), 16);
// Copy the collection
((ICollection)noc.Keys).CopyTo(array, 0);
// Retrieve elements
foreach (String v in array)
{
if (v != null)
{
Assert.False(true, _strErr + "Value is incorrect. array should be null");
}
}
// [] Call with array = null
noc = new MyNameObjectCollection();
Assert.Throws<ArgumentNullException>(() => { ((ICollection)noc.Keys).CopyTo(null, 0); });
// [] Target array is multidimensional.
array = new string[20, 2];
noc = new MyNameObjectCollection();
noc.Add(key1, val1);
noc.Add(key2, val2);
Assert.Throws<ArgumentException>(() => { ((ICollection)noc.Keys).CopyTo(array, 16); });
// [] Target array is of incompatible type.
array = Array.CreateInstance(typeof(Foo), 10);
noc = new MyNameObjectCollection();
noc.Add(key1, val1);
noc.Add(key2, val2);
Assert.Throws<InvalidCastException>(() => { ((ICollection)noc.Keys).CopyTo(array, 1); });
// [] index = array length
n = rand.Next(10, 100);
array = Array.CreateInstance(typeof(String), n);
noc = new MyNameObjectCollection();
noc.Add(key1, val1);
noc.Add(key2, val2);
Assert.Throws<ArgumentException>(() => { ((ICollection)noc.Keys).CopyTo(array, n); });
// [] index > array length
n = rand.Next(10, 100);
array = Array.CreateInstance(typeof(String), n);
noc = new MyNameObjectCollection();
noc.Add(key1, val1);
noc.Add(key2, val2);
Assert.Throws<ArgumentException>(() => { ((ICollection)noc.Keys).CopyTo(array, n + 1); });
// [] index = Int32.MaxValue
array = Array.CreateInstance(typeof(String), 10);
noc = new MyNameObjectCollection();
noc.Add(key1, val1);
noc.Add(key2, val2);
Assert.Throws<ArgumentException>(() => { ((ICollection)noc.Keys).CopyTo(array, Int32.MaxValue); });
// [] index < 0
array = Array.CreateInstance(typeof(String), 10);
noc = new MyNameObjectCollection();
noc.Add(key1, val1);
noc.Add(key2, val2);
Assert.Throws<ArgumentOutOfRangeException>(() => { ((ICollection)noc.Keys).CopyTo(array, -1); });
// [] index is valid but collection doesn't fit in available space
noc = new MyNameObjectCollection();
// Set up initial collection
n = rand.Next(10, 1000);
for (int i = 0; i < n; i++)
{
noc.Add("key_" + i.ToString(), new Foo());
}
// Set up initial array
n = noc.Count + 20;
array = Array.CreateInstance(typeof(Foo), n);
Assert.Throws<ArgumentException>(() => { ((ICollection)noc.Keys).CopyTo(array, 30); }); // array is only 20 bigger than collection
// [] index is negative
noc = new MyNameObjectCollection();
// Set up initial collection
n = rand.Next(10, 1000);
for (int i = 0; i < n; i++)
{
noc.Add("key_" + i.ToString(), new Foo());
}
// Set up initial array
n = noc.Count + 20;
array = Array.CreateInstance(typeof(Foo), n);
Assert.Throws<ArgumentOutOfRangeException>(() => { ((ICollection)noc.Keys).CopyTo(array, -1); });
// [] All keys are null
noc = new MyNameObjectCollection();
noc.Add(null, new Foo());
noc.Add(null, new Foo());
noc.Add(null, null);
noc.Add(null, new Foo());
if (noc.Count != 4)
{
Assert.False(true, _strErr + "Elements were not added correctly");
}
array = Array.CreateInstance(typeof(String), 16);
// Copy the collection
((ICollection)noc.Keys).CopyTo(array, 0);
// Retrieve elements
foreach (String v in array)
{
if (v != null)
{
Assert.False(true, _strErr + "Value is incorrect. array should be null");
}
}
}
void CheckArray(Array array, ArrayList expected)
{
if (array.Length != expected.Count)
{
Assert.False(true, string.Format(_strErr + "Array length != {0}. Length == {1}", expected.Count, array.Length));
}
for (int i = 0; i < expected.Count; i++)
{
if (((String[])array)[i] != (String)expected[i])
{
Assert.False(true, string.Format("Value {0} is incorrect. array[{0}]={1}, should be {2}", i, ((String[])array)[i], (String)expected[i]));
}
}
}
}
}
| |
//
// Copyright (c) 2004-2020 Jaroslaw Kowalski <[email protected]>, 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.
//
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Reflection;
using JetBrains.Annotations;
using NLog.Common;
using NLog.Filters;
using NLog.Internal;
using NLog.Layouts;
using NLog.Targets;
using NLog.Targets.Wrappers;
using NLog.Time;
namespace NLog.Config
{
/// <summary>
/// Loads NLog configuration from <see cref="ILoggingConfigurationElement"/>
/// </summary>
public abstract class LoggingConfigurationParser : LoggingConfiguration
{
private ConfigurationItemFactory _configurationItemFactory;
/// <summary>
/// Constructor
/// </summary>
/// <param name="logFactory"></param>
protected LoggingConfigurationParser(LogFactory logFactory)
: base(logFactory)
{
}
/// <summary>
/// Loads NLog configuration from provided config section
/// </summary>
/// <param name="nlogConfig"></param>
/// <param name="basePath"></param>
protected void LoadConfig(ILoggingConfigurationElement nlogConfig, string basePath)
{
InternalLogger.Trace("ParseNLogConfig");
nlogConfig.AssertName("nlog");
SetNLogElementSettings(nlogConfig);
var children = nlogConfig.Children.ToList();
//first load the extensions, as the can be used in other elements (targets etc)
var extensionsChilds = children.Where(child => child.MatchesName("extensions")).ToList();
foreach (var extensionsChild in extensionsChilds)
{
ParseExtensionsElement(extensionsChild, basePath);
}
var rulesList = new List<ILoggingConfigurationElement>();
//parse all other direct elements
foreach (var child in children)
{
if (child.MatchesName("rules"))
{
//postpone parsing <rules> to the end
rulesList.Add(child);
}
else if (child.MatchesName("extensions"))
{
//already parsed
}
else if (!ParseNLogSection(child))
{
InternalLogger.Warn("Skipping unknown 'NLog' child node: {0}", child.Name);
}
}
foreach (var ruleChild in rulesList)
{
ParseRulesElement(ruleChild, LoggingRules);
}
}
private void SetNLogElementSettings(ILoggingConfigurationElement nlogConfig)
{
var sortedList = CreateUniqueSortedListFromConfig(nlogConfig);
bool? parseMessageTemplates = null;
bool internalLoggerEnabled = false;
foreach (var configItem in sortedList)
{
switch (configItem.Key.ToUpperInvariant())
{
case "THROWEXCEPTIONS":
LogFactory.ThrowExceptions = ParseBooleanValue(configItem.Key, configItem.Value, LogFactory.ThrowExceptions);
break;
case "THROWCONFIGEXCEPTIONS":
LogFactory.ThrowConfigExceptions = ParseNullableBooleanValue(configItem.Key, configItem.Value, false);
break;
case "INTERNALLOGLEVEL":
InternalLogger.LogLevel = ParseLogLevelSafe(configItem.Key, configItem.Value, InternalLogger.LogLevel);
internalLoggerEnabled = InternalLogger.LogLevel != LogLevel.Off;
break;
case "USEINVARIANTCULTURE":
if (ParseBooleanValue(configItem.Key, configItem.Value, false))
DefaultCultureInfo = CultureInfo.InvariantCulture;
break;
#pragma warning disable 618
case "EXCEPTIONLOGGINGOLDSTYLE":
ExceptionLoggingOldStyle = ParseBooleanValue(configItem.Key, configItem.Value, ExceptionLoggingOldStyle);
break;
#pragma warning restore 618
case "KEEPVARIABLESONRELOAD":
LogFactory.KeepVariablesOnReload = ParseBooleanValue(configItem.Key, configItem.Value, LogFactory.KeepVariablesOnReload);
break;
case "INTERNALLOGTOCONSOLE":
InternalLogger.LogToConsole = ParseBooleanValue(configItem.Key, configItem.Value, InternalLogger.LogToConsole);
break;
case "INTERNALLOGTOCONSOLEERROR":
InternalLogger.LogToConsoleError = ParseBooleanValue(configItem.Key, configItem.Value, InternalLogger.LogToConsoleError);
break;
case "INTERNALLOGFILE":
var internalLogFile = configItem.Value?.Trim();
if (!string.IsNullOrEmpty(internalLogFile))
{
internalLogFile = ExpandFilePathVariables(internalLogFile);
InternalLogger.LogFile = internalLogFile;
}
break;
#if !SILVERLIGHT && !__IOS__ && !__ANDROID__
case "INTERNALLOGTOTRACE":
InternalLogger.LogToTrace = ParseBooleanValue(configItem.Key, configItem.Value, InternalLogger.LogToTrace);
break;
#endif
case "INTERNALLOGINCLUDETIMESTAMP":
InternalLogger.IncludeTimestamp = ParseBooleanValue(configItem.Key, configItem.Value, InternalLogger.IncludeTimestamp);
break;
case "GLOBALTHRESHOLD":
LogFactory.GlobalThreshold = ParseLogLevelSafe(configItem.Key, configItem.Value, LogFactory.GlobalThreshold);
break; // expanding variables not possible here, they are created later
case "PARSEMESSAGETEMPLATES":
parseMessageTemplates = ParseNullableBooleanValue(configItem.Key, configItem.Value, true);
break;
case "AUTOSHUTDOWN":
LogFactory.AutoShutdown = ParseBooleanValue(configItem.Key, configItem.Value, true);
break;
case "AUTORELOAD":
break; // Ignore here, used by other logic
default:
InternalLogger.Debug("Skipping unknown 'NLog' property {0}={1}", configItem.Key, configItem.Value);
break;
}
}
if (!internalLoggerEnabled && !InternalLogger.HasActiveLoggers())
{
InternalLogger.LogLevel = LogLevel.Off; // Reduce overhead of the InternalLogger when not configured
}
_configurationItemFactory = ConfigurationItemFactory.Default;
_configurationItemFactory.ParseMessageTemplates = parseMessageTemplates;
}
/// <summary>
/// Builds list with unique keys, using last value of duplicates. High priority keys placed first.
/// </summary>
/// <param name="nlogConfig"></param>
/// <returns></returns>
private static IList<KeyValuePair<string, string>> CreateUniqueSortedListFromConfig(ILoggingConfigurationElement nlogConfig)
{
var dict = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
foreach (var configItem in nlogConfig.Values)
{
if (!string.IsNullOrEmpty(configItem.Key))
{
string key = configItem.Key.Trim();
if (dict.ContainsKey(key))
{
InternalLogger.Debug("Skipping duplicate value for 'NLog' property {0}. Value={1}", configItem.Key, dict[key]);
}
dict[key] = configItem.Value;
}
}
var sortedList = new List<KeyValuePair<string, string>>(dict.Count);
AddHighPrioritySetting("ThrowExceptions");
AddHighPrioritySetting("ThrowConfigExceptions");
AddHighPrioritySetting("InternalLogLevel");
AddHighPrioritySetting("InternalLogFile");
AddHighPrioritySetting("InternalLogToConsole");
foreach (var configItem in dict)
{
sortedList.Add(configItem);
}
return sortedList;
void AddHighPrioritySetting(string settingName)
{
if (dict.ContainsKey(settingName))
{
sortedList.Add(new KeyValuePair<string, string>(settingName, dict[settingName]));
dict.Remove(settingName);
}
}
}
private static string ExpandFilePathVariables(string internalLogFile)
{
try
{
#if !SILVERLIGHT
if (ContainsSubStringIgnoreCase(internalLogFile, "${currentdir}", out string currentDirToken))
internalLogFile = internalLogFile.Replace(currentDirToken, System.IO.Directory.GetCurrentDirectory() + System.IO.Path.DirectorySeparatorChar.ToString());
if (ContainsSubStringIgnoreCase(internalLogFile, "${basedir}", out string baseDirToken))
internalLogFile = internalLogFile.Replace(baseDirToken, LogFactory.CurrentAppDomain.BaseDirectory + System.IO.Path.DirectorySeparatorChar.ToString());
if (ContainsSubStringIgnoreCase(internalLogFile, "${tempdir}", out string tempDirToken))
internalLogFile = internalLogFile.Replace(tempDirToken, System.IO.Path.GetTempPath() + System.IO.Path.DirectorySeparatorChar.ToString());
#if !NETSTANDARD1_3
if (ContainsSubStringIgnoreCase(internalLogFile, "${processdir}", out string processDirToken))
internalLogFile = internalLogFile.Replace(processDirToken, System.IO.Path.GetDirectoryName(ProcessIDHelper.Instance.CurrentProcessFilePath) + System.IO.Path.DirectorySeparatorChar.ToString());
#endif
if (internalLogFile.IndexOf("%", StringComparison.OrdinalIgnoreCase) >= 0)
internalLogFile = Environment.ExpandEnvironmentVariables(internalLogFile);
#endif
return internalLogFile;
}
catch
{
return internalLogFile;
}
}
private static bool ContainsSubStringIgnoreCase(string haystack, string needle, out string result)
{
int needlePos = haystack.IndexOf(needle, StringComparison.OrdinalIgnoreCase);
result = needlePos >= 0 ? haystack.Substring(needlePos, needle.Length) : null;
return result != null;
}
/// <summary>
/// Parse loglevel, but don't throw if exception throwing is disabled
/// </summary>
/// <param name="attributeName">Name of attribute for logging.</param>
/// <param name="attributeValue">Value of parse.</param>
/// <param name="default">Used if there is an exception</param>
/// <returns></returns>
private LogLevel ParseLogLevelSafe(string attributeName, string attributeValue, LogLevel @default)
{
try
{
var internalLogLevel = LogLevel.FromString(attributeValue?.Trim());
return internalLogLevel;
}
catch (Exception exception)
{
if (exception.MustBeRethrownImmediately())
throw;
const string message = "attribute '{0}': '{1}' isn't valid LogLevel. {2} will be used.";
var configException =
new NLogConfigurationException(exception, message, attributeName, attributeValue, @default);
if (MustThrowConfigException(configException))
throw configException;
return @default;
}
}
/// <summary>
/// Parses a single config section within the NLog-config
/// </summary>
/// <param name="configSection"></param>
/// <returns>Section was recognized</returns>
protected virtual bool ParseNLogSection(ILoggingConfigurationElement configSection)
{
switch (configSection.Name?.Trim().ToUpperInvariant())
{
case "TIME":
ParseTimeElement(configSection);
return true;
case "VARIABLE":
ParseVariableElement(configSection);
return true;
case "VARIABLES":
ParseVariablesElement(configSection);
return true;
case "APPENDERS":
case "TARGETS":
ParseTargetsElement(configSection);
return true;
}
return false;
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability",
"CA2001:AvoidCallingProblematicMethods", MessageId = "System.Reflection.Assembly.LoadFrom",
Justification = "Need to load external assembly.")]
private void ParseExtensionsElement(ILoggingConfigurationElement extensionsElement, string baseDirectory)
{
extensionsElement.AssertName("extensions");
foreach (var childItem in extensionsElement.Children)
{
string prefix = null;
string type = null;
string assemblyFile = null;
string assemblyName = null;
foreach (var childProperty in childItem.Values)
{
if (MatchesName(childProperty.Key, "prefix"))
{
prefix = childProperty.Value + ".";
}
else if (MatchesName(childProperty.Key, "type"))
{
type = childProperty.Value;
}
else if (MatchesName(childProperty.Key, "assemblyFile"))
{
assemblyFile = childProperty.Value;
}
else if (MatchesName(childProperty.Key, "assembly"))
{
assemblyName = childProperty.Value;
}
else
{
InternalLogger.Debug("Skipping unknown property {0} for element {1} in section {2}",
childProperty.Key, childItem.Name, extensionsElement.Name);
}
}
if (!StringHelpers.IsNullOrWhiteSpace(type))
{
RegisterExtension(type, prefix);
}
#if !NETSTANDARD1_3
if (!StringHelpers.IsNullOrWhiteSpace(assemblyFile))
{
ParseExtensionWithAssemblyFile(baseDirectory, assemblyFile, prefix);
continue;
}
#endif
if (!StringHelpers.IsNullOrWhiteSpace(assemblyName))
{
ParseExtensionWithAssembly(assemblyName, prefix);
}
}
}
private void RegisterExtension(string type, string itemNamePrefix)
{
try
{
_configurationItemFactory.RegisterType(Type.GetType(type, true), itemNamePrefix);
}
catch (Exception exception)
{
if (exception.MustBeRethrownImmediately())
throw;
var configException =
new NLogConfigurationException("Error loading extensions: " + type, exception);
if (MustThrowConfigException(configException))
throw configException;
}
}
#if !NETSTANDARD1_3
private void ParseExtensionWithAssemblyFile(string baseDirectory, string assemblyFile, string prefix)
{
try
{
Assembly asm = AssemblyHelpers.LoadFromPath(assemblyFile, baseDirectory);
_configurationItemFactory.RegisterItemsFromAssembly(asm, prefix);
}
catch (Exception exception)
{
if (exception.MustBeRethrownImmediately())
throw;
var configException =
new NLogConfigurationException("Error loading extensions: " + assemblyFile, exception);
if (MustThrowConfigException(configException))
throw configException;
}
}
#endif
private void ParseExtensionWithAssembly(string assemblyName, string prefix)
{
try
{
Assembly asm = AssemblyHelpers.LoadFromName(assemblyName);
_configurationItemFactory.RegisterItemsFromAssembly(asm, prefix);
}
catch (Exception exception)
{
if (exception.MustBeRethrownImmediately())
throw;
var configException =
new NLogConfigurationException("Error loading extensions: " + assemblyName, exception);
if (MustThrowConfigException(configException))
throw configException;
}
}
private void ParseVariableElement(ILoggingConfigurationElement variableElement)
{
string variableName = null;
string variableValue = null;
foreach (var childProperty in variableElement.Values)
{
if (MatchesName(childProperty.Key, "name"))
variableName = childProperty.Value;
else if (MatchesName(childProperty.Key, "value"))
variableValue = childProperty.Value;
else
InternalLogger.Debug("Skipping unknown property {0} for element {1} in section {2}",
childProperty.Key, variableElement.Name, "variables");
}
if (!AssertNonEmptyValue(variableName, "name", variableElement.Name, "variables"))
return;
if (!AssertNotNullValue(variableValue, "value", variableElement.Name, "variables"))
return;
string value = ExpandSimpleVariables(variableValue);
Variables[variableName] = value;
}
private void ParseVariablesElement(ILoggingConfigurationElement variableElement)
{
variableElement.AssertName("variables");
foreach (var childItem in variableElement.Children)
{
ParseVariableElement(childItem);
}
}
private void ParseTimeElement(ILoggingConfigurationElement timeElement)
{
timeElement.AssertName("time");
string timeSourceType = null;
foreach (var childProperty in timeElement.Values)
{
if (MatchesName(childProperty.Key, "type"))
timeSourceType = childProperty.Value;
else
InternalLogger.Debug("Skipping unknown property {0} for element {1} in section {2}",
childProperty.Key, timeElement.Name, timeElement.Name);
}
if (!AssertNonEmptyValue(timeSourceType, "type", timeElement.Name, string.Empty))
return;
TimeSource newTimeSource = _configurationItemFactory.TimeSources.CreateInstance(timeSourceType);
ConfigureObjectFromAttributes(newTimeSource, timeElement, true);
InternalLogger.Info("Selecting time source {0}", newTimeSource);
TimeSource.Current = newTimeSource;
}
[ContractAnnotation("value:notnull => true")]
private static bool AssertNotNullValue(string value, string propertyName, string elementName, string sectionName)
{
if (value != null)
return true;
return AssertNonEmptyValue(string.Empty, propertyName, elementName, sectionName);
}
[ContractAnnotation("value:null => false")]
private static bool AssertNonEmptyValue(string value, string propertyName, string elementName, string sectionName)
{
if (!StringHelpers.IsNullOrWhiteSpace(value))
return true;
if (LogManager.ThrowConfigExceptions ?? LogManager.ThrowExceptions)
throw new NLogConfigurationException(
$"Expected property {propertyName} on element name: {elementName} in section: {sectionName}");
InternalLogger.Warn("Skipping element name: {0} in section: {1} because property {2} is blank", elementName,
sectionName, propertyName);
return false;
}
/// <summary>
/// Parse {Rules} xml element
/// </summary>
/// <param name="rulesElement"></param>
/// <param name="rulesCollection">Rules are added to this parameter.</param>
private void ParseRulesElement(ILoggingConfigurationElement rulesElement, IList<LoggingRule> rulesCollection)
{
InternalLogger.Trace("ParseRulesElement");
rulesElement.AssertName("rules");
foreach (var childItem in rulesElement.Children)
{
LoggingRule loggingRule = ParseRuleElement(childItem);
if (loggingRule != null)
{
lock (rulesCollection)
{
rulesCollection.Add(loggingRule);
}
}
}
}
private LogLevel LogLevelFromString(string text)
{
return LogLevel.FromString(ExpandSimpleVariables(text).Trim());
}
/// <summary>
/// Parse {Logger} xml element
/// </summary>
/// <param name="loggerElement"></param>
private LoggingRule ParseRuleElement(ILoggingConfigurationElement loggerElement)
{
string minLevel = null;
string maxLevel = null;
string enableLevels = null;
string ruleName = null;
string namePattern = null;
bool enabled = true;
bool final = false;
string writeTargets = null;
foreach (var childProperty in loggerElement.Values)
{
switch (childProperty.Key?.Trim().ToUpperInvariant())
{
case "NAME":
if (loggerElement.MatchesName("logger"))
namePattern = childProperty.Value; // Legacy Style
else
ruleName = childProperty.Value;
break;
case "RULENAME":
ruleName = childProperty.Value; // Legacy Style
break;
case "LOGGER":
namePattern = childProperty.Value;
break;
case "ENABLED":
enabled = ParseBooleanValue(childProperty.Key, childProperty.Value, true);
break;
case "APPENDTO":
writeTargets = childProperty.Value;
break;
case "WRITETO":
writeTargets = childProperty.Value;
break;
case "FINAL":
final = ParseBooleanValue(childProperty.Key, childProperty.Value, false);
break;
case "LEVEL":
enableLevels = childProperty.Value;
break;
case "LEVELS":
enableLevels = StringHelpers.IsNullOrWhiteSpace(childProperty.Value) ? "," : childProperty.Value;
break;
case "MINLEVEL":
minLevel = childProperty.Value;
break;
case "MAXLEVEL":
maxLevel = childProperty.Value;
break;
default:
InternalLogger.Debug("Skipping unknown property {0} for element {1} in section {2}",
childProperty.Key, loggerElement.Name, "rules");
break;
}
}
if (string.IsNullOrEmpty(ruleName) && string.IsNullOrEmpty(namePattern) &&
string.IsNullOrEmpty(writeTargets) && !final)
{
InternalLogger.Debug("Logging rule without name or filter or targets is ignored");
return null;
}
namePattern = namePattern ?? "*";
if (!enabled)
{
InternalLogger.Debug("Logging rule {0} with filter `{1}` is disabled", ruleName, namePattern);
return null;
}
var rule = new LoggingRule(ruleName)
{
LoggerNamePattern = namePattern,
Final = final,
};
EnableLevelsForRule(rule, enableLevels, minLevel, maxLevel);
ParseLoggingRuleTargets(writeTargets, rule);
ParseLoggingRuleChildren(loggerElement, rule);
return rule;
}
private void EnableLevelsForRule(LoggingRule rule, string enableLevels, string minLevel, string maxLevel)
{
if (enableLevels != null)
{
enableLevels = ExpandSimpleVariables(enableLevels);
if (enableLevels.IndexOf('{') >= 0)
{
SimpleLayout simpleLayout = ParseLevelLayout(enableLevels);
rule.EnableLoggingForLevels(simpleLayout);
}
else
{
if (enableLevels.IndexOf(',') >= 0)
{
IEnumerable<LogLevel> logLevels = ParseLevels(enableLevels);
foreach (var logLevel in logLevels)
rule.EnableLoggingForLevel(logLevel);
}
else
{
rule.EnableLoggingForLevel(LogLevelFromString(enableLevels));
}
}
}
else
{
minLevel = minLevel != null ? ExpandSimpleVariables(minLevel) : minLevel;
maxLevel = maxLevel != null ? ExpandSimpleVariables(maxLevel) : maxLevel;
if (minLevel?.IndexOf('{') >= 0 || maxLevel?.IndexOf('{') >= 0)
{
SimpleLayout minLevelLayout = ParseLevelLayout(minLevel);
SimpleLayout maxLevelLayout = ParseLevelLayout(maxLevel);
rule.EnableLoggingForRange(minLevelLayout, maxLevelLayout);
}
else
{
LogLevel minLogLevel = minLevel != null ? LogLevelFromString(minLevel) : LogLevel.MinLevel;
LogLevel maxLogLevel = maxLevel != null ? LogLevelFromString(maxLevel) : LogLevel.MaxLevel;
rule.SetLoggingLevels(minLogLevel, maxLogLevel);
}
}
}
private SimpleLayout ParseLevelLayout(string levelLayout)
{
SimpleLayout simpleLayout = !StringHelpers.IsNullOrWhiteSpace(levelLayout) ? new SimpleLayout(levelLayout, _configurationItemFactory) : null;
simpleLayout?.Initialize(this);
return simpleLayout;
}
private IEnumerable<LogLevel> ParseLevels(string enableLevels)
{
string[] tokens = enableLevels.SplitAndTrimTokens(',');
var logLevels = tokens.Select(LogLevelFromString);
return logLevels;
}
private void ParseLoggingRuleTargets(string writeTargets, LoggingRule rule)
{
if (string.IsNullOrEmpty(writeTargets))
return;
foreach (string targetName in writeTargets.SplitAndTrimTokens(','))
{
Target target = FindTargetByName(targetName);
if (target != null)
{
rule.Targets.Add(target);
}
else
{
var configException =
new NLogConfigurationException($"Target '{targetName}' not found for logging rule: {(string.IsNullOrEmpty(rule.RuleName) ? rule.LoggerNamePattern : rule.RuleName)}.");
if (MustThrowConfigException(configException))
throw configException;
}
}
}
private void ParseLoggingRuleChildren(ILoggingConfigurationElement loggerElement, LoggingRule rule)
{
foreach (var child in loggerElement.Children)
{
LoggingRule childRule = null;
if (child.MatchesName("filters"))
{
ParseFilters(rule, child);
}
else if (child.MatchesName("logger") && loggerElement.MatchesName("logger"))
{
childRule = ParseRuleElement(child);
}
else if (child.MatchesName("rule") && loggerElement.MatchesName("rule"))
{
childRule = ParseRuleElement(child);
}
else
{
InternalLogger.Debug("Skipping unknown child {0} for element {1} in section {2}", child.Name,
loggerElement.Name, "rules");
}
if (childRule != null)
{
lock (rule.ChildRules)
{
rule.ChildRules.Add(childRule);
}
}
}
}
private void ParseFilters(LoggingRule rule, ILoggingConfigurationElement filtersElement)
{
filtersElement.AssertName("filters");
var defaultActionResult = filtersElement.GetOptionalValue("defaultAction", null);
if (defaultActionResult != null)
{
PropertyHelper.SetPropertyFromString(rule, nameof(rule.DefaultFilterResult), defaultActionResult,
_configurationItemFactory);
}
foreach (var filterElement in filtersElement.Children)
{
string name = filterElement.Name;
Filter filter = _configurationItemFactory.Filters.CreateInstance(name);
ConfigureObjectFromAttributes(filter, filterElement, false);
rule.Filters.Add(filter);
}
}
private void ParseTargetsElement(ILoggingConfigurationElement targetsElement)
{
targetsElement.AssertName("targets", "appenders");
var asyncItem = targetsElement.Values.FirstOrDefault(configItem => MatchesName(configItem.Key, "async"));
bool asyncWrap = !string.IsNullOrEmpty(asyncItem.Value) &&
ParseBooleanValue(asyncItem.Key, asyncItem.Value, false);
ILoggingConfigurationElement defaultWrapperElement = null;
var typeNameToDefaultTargetParameters =
new Dictionary<string, ILoggingConfigurationElement>(StringComparer.OrdinalIgnoreCase);
foreach (var targetElement in targetsElement.Children)
{
string targetTypeName = targetElement.GetConfigItemTypeAttribute();
string targetValueName = targetElement.GetOptionalValue("name", null);
Target newTarget = null;
if (!string.IsNullOrEmpty(targetValueName))
targetValueName = $"{targetElement.Name}(Name={targetValueName})";
else
targetValueName = targetElement.Name;
switch (targetElement.Name?.Trim().ToUpperInvariant())
{
case "DEFAULT-WRAPPER":
if (AssertNonEmptyValue(targetTypeName, "type", targetValueName, targetsElement.Name))
{
defaultWrapperElement = targetElement;
}
break;
case "DEFAULT-TARGET-PARAMETERS":
if (AssertNonEmptyValue(targetTypeName, "type", targetValueName, targetsElement.Name))
{
ParseDefaultTargetParameters(targetElement, targetTypeName, typeNameToDefaultTargetParameters);
}
break;
case "TARGET":
case "APPENDER":
case "WRAPPER":
case "WRAPPER-TARGET":
case "COMPOUND-TARGET":
if (AssertNonEmptyValue(targetTypeName, "type", targetValueName, targetsElement.Name))
{
newTarget = CreateTargetType(targetTypeName);
if (newTarget != null)
{
ParseTargetElement(newTarget, targetElement, typeNameToDefaultTargetParameters);
}
}
break;
default:
InternalLogger.Debug("Skipping unknown element {0} in section {1}", targetValueName,
targetsElement.Name);
break;
}
if (newTarget != null)
{
if (asyncWrap)
{
newTarget = WrapWithAsyncTargetWrapper(newTarget);
}
if (defaultWrapperElement != null)
{
newTarget = WrapWithDefaultWrapper(newTarget, defaultWrapperElement);
}
InternalLogger.Info("Adding target {0}(Name={1})", newTarget.GetType().Name, newTarget.Name);
AddTarget(newTarget.Name, newTarget);
}
}
}
private Target CreateTargetType(string targetTypeName)
{
Target newTarget = null;
try
{
newTarget = _configurationItemFactory.Targets.CreateInstance(targetTypeName);
if (newTarget == null)
throw new NLogConfigurationException($"Factory returned null for target type: {targetTypeName}");
}
catch (Exception ex)
{
if (ex.MustBeRethrownImmediately())
throw;
var configException = new NLogConfigurationException($"Failed to create target type: {targetTypeName}", ex);
if (MustThrowConfigException(configException))
throw configException;
}
return newTarget;
}
void ParseDefaultTargetParameters(ILoggingConfigurationElement defaultTargetElement, string targetType,
Dictionary<string, ILoggingConfigurationElement> typeNameToDefaultTargetParameters)
{
typeNameToDefaultTargetParameters[targetType.Trim()] = defaultTargetElement;
}
private void ParseTargetElement(Target target, ILoggingConfigurationElement targetElement,
Dictionary<string, ILoggingConfigurationElement> typeNameToDefaultTargetParameters = null)
{
string targetTypeName = targetElement.GetConfigItemTypeAttribute("targets");
ILoggingConfigurationElement defaults;
if (typeNameToDefaultTargetParameters != null &&
typeNameToDefaultTargetParameters.TryGetValue(targetTypeName, out defaults))
{
ParseTargetElement(target, defaults, null);
}
var compound = target as CompoundTargetBase;
var wrapper = target as WrapperTargetBase;
ConfigureObjectFromAttributes(target, targetElement, true);
foreach (var childElement in targetElement.Children)
{
string name = childElement.Name;
if (compound != null &&
ParseCompoundTarget(typeNameToDefaultTargetParameters, name, childElement, compound, null))
{
continue;
}
if (wrapper != null &&
ParseTargetWrapper(typeNameToDefaultTargetParameters, name, childElement, wrapper))
{
continue;
}
SetPropertyFromElement(target, childElement, targetElement);
}
}
private bool ParseTargetWrapper(
Dictionary<string, ILoggingConfigurationElement> typeNameToDefaultTargetParameters, string name,
ILoggingConfigurationElement childElement,
WrapperTargetBase wrapper)
{
if (IsTargetRefElement(name))
{
var targetName = childElement.GetRequiredValue("name", GetName(wrapper));
Target newTarget = FindTargetByName(targetName);
if (newTarget == null)
{
var configException = new NLogConfigurationException($"Referenced target '{targetName}' not found.");
if (MustThrowConfigException(configException))
throw configException;
}
wrapper.WrappedTarget = newTarget;
return true;
}
if (IsTargetElement(name))
{
string targetTypeName = childElement.GetConfigItemTypeAttribute(GetName(wrapper));
Target newTarget = CreateTargetType(targetTypeName);
if (newTarget != null)
{
ParseTargetElement(newTarget, childElement, typeNameToDefaultTargetParameters);
if (newTarget.Name != null)
{
// if the new target has name, register it
AddTarget(newTarget.Name, newTarget);
}
if (wrapper.WrappedTarget != null)
{
var configException = new NLogConfigurationException($"Failed to assign wrapped target {targetTypeName}, because target {wrapper.Name} already has one.");
if (MustThrowConfigException(configException))
throw configException;
}
}
wrapper.WrappedTarget = newTarget;
return true;
}
return false;
}
private bool ParseCompoundTarget(
Dictionary<string, ILoggingConfigurationElement> typeNameToDefaultTargetParameters, string name,
ILoggingConfigurationElement childElement,
CompoundTargetBase compound, string targetName)
{
if (MatchesName(name, "targets") || MatchesName(name, "appenders"))
{
foreach (var child in childElement.Children)
{
ParseCompoundTarget(typeNameToDefaultTargetParameters, child.Name, child, compound, null);
}
return true;
}
if (IsTargetRefElement(name))
{
targetName = childElement.GetRequiredValue("name", GetName(compound));
Target newTarget = FindTargetByName(targetName);
if (newTarget == null)
{
throw new NLogConfigurationException("Referenced target '" + targetName + "' not found.");
}
compound.Targets.Add(newTarget);
return true;
}
if (IsTargetElement(name))
{
string targetTypeName = childElement.GetConfigItemTypeAttribute(GetName(compound));
Target newTarget = CreateTargetType(targetTypeName);
if (newTarget != null)
{
if (targetName != null)
newTarget.Name = targetName;
ParseTargetElement(newTarget, childElement, typeNameToDefaultTargetParameters);
if (newTarget.Name != null)
{
// if the new target has name, register it
AddTarget(newTarget.Name, newTarget);
}
compound.Targets.Add(newTarget);
}
return true;
}
return false;
}
private void ConfigureObjectFromAttributes(object targetObject, ILoggingConfigurationElement element, bool ignoreType)
{
foreach (var kvp in element.Values)
{
string childName = kvp.Key;
string childValue = kvp.Value;
if (ignoreType && MatchesName(childName, "type"))
{
continue;
}
try
{
PropertyHelper.SetPropertyFromString(targetObject, childName, ExpandSimpleVariables(childValue),
_configurationItemFactory);
}
catch (Exception ex)
{
InternalLogger.Warn(ex, "Error when setting '{0}' on attibute '{1}'", childValue, childName);
throw;
}
}
}
private void SetPropertyFromElement(object o, ILoggingConfigurationElement childElement, ILoggingConfigurationElement parentElement)
{
if (!PropertyHelper.TryGetPropertyInfo(o, childElement.Name, out var propInfo))
{
InternalLogger.Debug("Skipping unknown element {0} in section {1}. Not matching any property on {2} - {3}", childElement.Name, parentElement.Name, o, o?.GetType());
return;
}
if (AddArrayItemFromElement(o, propInfo, childElement))
{
return;
}
if (SetLayoutFromElement(o, propInfo, childElement))
{
return;
}
if (SetFilterFromElement(o, propInfo, childElement))
{
return;
}
SetItemFromElement(o, propInfo, childElement);
}
private bool AddArrayItemFromElement(object o, PropertyInfo propInfo, ILoggingConfigurationElement element)
{
Type elementType = PropertyHelper.GetArrayItemType(propInfo);
if (elementType != null)
{
IList propertyValue = (IList)propInfo.GetValue(o, null);
if (string.Equals(propInfo.Name, element.Name, StringComparison.OrdinalIgnoreCase))
{
var children = element.Children.ToList();
if (children.Count > 0)
{
foreach (var child in children)
{
propertyValue.Add(ParseArrayItemFromElement(elementType, child));
}
return true;
}
}
object arrayItem = ParseArrayItemFromElement(elementType, element);
propertyValue.Add(arrayItem);
return true;
}
return false;
}
private object ParseArrayItemFromElement(Type elementType, ILoggingConfigurationElement element)
{
object arrayItem = TryCreateLayoutInstance(element, elementType);
// arrayItem is not a layout
if (arrayItem == null)
arrayItem = FactoryHelper.CreateInstance(elementType);
ConfigureObjectFromAttributes(arrayItem, element, true);
ConfigureObjectFromElement(arrayItem, element);
return arrayItem;
}
private bool SetLayoutFromElement(object o, PropertyInfo propInfo, ILoggingConfigurationElement element)
{
var layout = TryCreateLayoutInstance(element, propInfo.PropertyType);
// and is a Layout and 'type' attribute has been specified
if (layout != null)
{
SetItemOnProperty(o, propInfo, element, layout);
return true;
}
return false;
}
private bool SetFilterFromElement(object o, PropertyInfo propInfo, ILoggingConfigurationElement element)
{
var type = propInfo.PropertyType;
Filter filter = TryCreateFilterInstance(element, type);
// and is a Filter and 'type' attribute has been specified
if (filter != null)
{
SetItemOnProperty(o, propInfo, element, filter);
return true;
}
return false;
}
private Layout TryCreateLayoutInstance(ILoggingConfigurationElement element, Type type)
{
return TryCreateInstance(element, type, _configurationItemFactory.Layouts);
}
private Filter TryCreateFilterInstance(ILoggingConfigurationElement element, Type type)
{
return TryCreateInstance(element, type, _configurationItemFactory.Filters);
}
private T TryCreateInstance<T>(ILoggingConfigurationElement element, Type type, INamedItemFactory<T, Type> factory)
where T : class
{
// Check if correct type
if (!IsAssignableFrom<T>(type))
return null;
// Check if the 'type' attribute has been specified
string layoutTypeName = element.GetConfigItemTypeAttribute();
if (layoutTypeName == null)
return null;
return factory.CreateInstance(ExpandSimpleVariables(layoutTypeName));
}
private static bool IsAssignableFrom<T>(Type type)
{
return typeof(T).IsAssignableFrom(type);
}
private void SetItemOnProperty(object o, PropertyInfo propInfo, ILoggingConfigurationElement element, object properyValue)
{
ConfigureObjectFromAttributes(properyValue, element, true);
ConfigureObjectFromElement(properyValue, element);
propInfo.SetValue(o, properyValue, null);
}
private void SetItemFromElement(object o, PropertyInfo propInfo, ILoggingConfigurationElement element)
{
object item = propInfo.GetValue(o, null);
ConfigureObjectFromAttributes(item, element, true);
ConfigureObjectFromElement(item, element);
}
private void ConfigureObjectFromElement(object targetObject, ILoggingConfigurationElement element)
{
foreach (var child in element.Children)
{
SetPropertyFromElement(targetObject, child, element);
}
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability",
"CA2000:Dispose objects before losing scope", Justification = "Target is disposed elsewhere.")]
private static Target WrapWithAsyncTargetWrapper(Target target)
{
#if !NET3_5 && !SILVERLIGHT4
if (target is AsyncTaskTarget)
{
InternalLogger.Debug("Skip wrapping target '{0}' with AsyncTargetWrapper", target.Name);
return target;
}
#endif
var asyncTargetWrapper = new AsyncTargetWrapper();
asyncTargetWrapper.WrappedTarget = target;
asyncTargetWrapper.Name = target.Name;
target.Name = target.Name + "_wrapped";
InternalLogger.Debug("Wrapping target '{0}' with AsyncTargetWrapper and renaming to '{1}",
asyncTargetWrapper.Name, target.Name);
target = asyncTargetWrapper;
return target;
}
private Target WrapWithDefaultWrapper(Target target, ILoggingConfigurationElement defaultParameters)
{
string wrapperTypeName = defaultParameters.GetConfigItemTypeAttribute("targets");
Target wrapperTargetInstance = CreateTargetType(wrapperTypeName);
WrapperTargetBase wtb = wrapperTargetInstance as WrapperTargetBase;
if (wtb == null)
{
throw new NLogConfigurationException("Target type specified on <default-wrapper /> is not a wrapper.");
}
ParseTargetElement(wrapperTargetInstance, defaultParameters);
while (wtb.WrappedTarget != null)
{
wtb = wtb.WrappedTarget as WrapperTargetBase;
if (wtb == null)
{
throw new NLogConfigurationException(
"Child target type specified on <default-wrapper /> is not a wrapper.");
}
}
#if !NET3_5 && !SILVERLIGHT4
if (target is AsyncTaskTarget && wrapperTargetInstance is AsyncTargetWrapper && ReferenceEquals(wrapperTargetInstance, wtb))
{
InternalLogger.Debug("Skip wrapping target '{0}' with AsyncTargetWrapper", target.Name);
return target;
}
#endif
wtb.WrappedTarget = target;
wrapperTargetInstance.Name = target.Name;
target.Name = target.Name + "_wrapped";
InternalLogger.Debug("Wrapping target '{0}' with '{1}' and renaming to '{2}", wrapperTargetInstance.Name,
wrapperTargetInstance.GetType().Name, target.Name);
return wrapperTargetInstance;
}
/// <summary>
/// Parse boolean
/// </summary>
/// <param name="propertyName">Name of the property for logging.</param>
/// <param name="value">value to parse</param>
/// <param name="defaultValue">Default value to return if the parse failed</param>
/// <returns>Boolean attribute value or default.</returns>
private bool ParseBooleanValue(string propertyName, string value, bool defaultValue)
{
try
{
return Convert.ToBoolean(value?.Trim(), CultureInfo.InvariantCulture);
}
catch (Exception exception)
{
if (exception.MustBeRethrownImmediately())
throw;
var configException = new NLogConfigurationException(exception, $"'{propertyName}' hasn't a valid boolean value '{value}'. {defaultValue} will be used");
if (MustThrowConfigException(configException))
throw configException;
return defaultValue;
}
}
private bool? ParseNullableBooleanValue(string propertyName, string value, bool defaultValue)
{
return StringHelpers.IsNullOrWhiteSpace(value)
? (bool?)null
: ParseBooleanValue(propertyName, value, defaultValue);
}
private bool MustThrowConfigException(NLogConfigurationException configException)
{
if (configException.MustBeRethrown())
return true; // Global LogManager says throw
if (LogFactory.ThrowConfigExceptions ?? LogFactory.ThrowExceptions)
return true; // Local LogFactory says throw
return false;
}
private static bool MatchesName(string key, string expectedKey)
{
return string.Equals(key?.Trim(), expectedKey, StringComparison.OrdinalIgnoreCase);
}
private static bool IsTargetElement(string name)
{
return name.Equals("target", StringComparison.OrdinalIgnoreCase)
|| name.Equals("wrapper", StringComparison.OrdinalIgnoreCase)
|| name.Equals("wrapper-target", StringComparison.OrdinalIgnoreCase)
|| name.Equals("compound-target", StringComparison.OrdinalIgnoreCase);
}
private static bool IsTargetRefElement(string name)
{
return name.Equals("target-ref", StringComparison.OrdinalIgnoreCase)
|| name.Equals("wrapper-target-ref", StringComparison.OrdinalIgnoreCase)
|| name.Equals("compound-target-ref", StringComparison.OrdinalIgnoreCase);
}
private static string GetName(Target target)
{
return string.IsNullOrEmpty(target.Name) ? target.GetType().Name : target.Name;
}
}
}
| |
// Copyright (c) .NET Foundation and contributors. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Microsoft.DotNet.ProjectModel.Compilation;
using Microsoft.DotNet.ProjectModel.Graph;
using Microsoft.DotNet.ProjectModel.Resolution;
using Microsoft.DotNet.Tools.Test.Utilities;
using NuGet.LibraryModel;
using NuGet.ProjectModel;
using FluentAssertions;
using Xunit;
namespace Microsoft.DotNet.ProjectModel.Tests
{
public class LibraryExporterPackageTests
{
private const string PackagePath = "PackagePath";
private const string HashPath = "PackageHashPath";
private PackageDescription CreateDescription(
LockFileTargetLibrary target = null,
LockFileLibrary package = null,
string hashPath = null)
{
return new PackageDescription(
PackagePath,
hashPath ?? HashPath,
package ?? new LockFileLibrary(),
target ?? new LockFileTargetLibrary(),
new List<ProjectLibraryDependency>(), compatible: true, resolved: true);
}
[Fact]
public void ExportsPackageNativeLibraries()
{
var description = CreateDescription(
new LockFileTargetLibrary()
{
NativeLibraries = new List<LockFileItem>()
{
{ new LockFileItem("lib/Native.so") }
}
});
var result = ExportSingle(description);
result.NativeLibraryGroups.Should().HaveCount(1);
var libraryAsset = result.NativeLibraryGroups.GetDefaultAssets().First();
libraryAsset.Name.Should().Be("Native");
libraryAsset.Transform.Should().BeNull();
libraryAsset.RelativePath.Should().Be("lib/Native.so");
libraryAsset.ResolvedPath.Should().Be(Path.Combine(PackagePath, "lib/Native.so"));
}
[Fact]
public void ExportsPackageCompilationAssebmlies()
{
var description = CreateDescription(
new LockFileTargetLibrary()
{
CompileTimeAssemblies = new List<LockFileItem>()
{
{ new LockFileItem("ref/Native.dll") }
}
});
var result = ExportSingle(description);
result.CompilationAssemblies.Should().HaveCount(1);
var libraryAsset = result.CompilationAssemblies.First();
libraryAsset.Name.Should().Be("Native");
libraryAsset.Transform.Should().BeNull();
libraryAsset.RelativePath.Should().Be("ref/Native.dll");
libraryAsset.ResolvedPath.Should().Be(Path.Combine(PackagePath, "ref/Native.dll"));
}
[Fact]
public void ExportsPackageRuntimeAssebmlies()
{
var description = CreateDescription(
new LockFileTargetLibrary()
{
RuntimeAssemblies = new List<LockFileItem>()
{
{ new LockFileItem("ref/Native.dll") }
}
});
var result = ExportSingle(description);
result.RuntimeAssemblyGroups.Should().HaveCount(1);
var libraryAsset = result.RuntimeAssemblyGroups.GetDefaultAssets().First();
libraryAsset.Name.Should().Be("Native");
libraryAsset.Transform.Should().BeNull();
libraryAsset.RelativePath.Should().Be("ref/Native.dll");
libraryAsset.ResolvedPath.Should().Be(Path.Combine(PackagePath, "ref/Native.dll"));
}
[Fact]
public void ExportsPackageRuntimeTargets()
{
var description = CreateDescription(
new LockFileTargetLibrary()
{
RuntimeTargets = new List<LockFileRuntimeTarget>()
{
new LockFileRuntimeTarget("native/native.dylib", "osx", "native"),
new LockFileRuntimeTarget("lib/Something.OSX.dll", "osx", "runtime")
}
});
var result = ExportSingle(description);
result.RuntimeAssemblyGroups.Should().HaveCount(2);
result.RuntimeAssemblyGroups.First(g => g.Runtime == string.Empty).Assets.Should().HaveCount(0);
result.RuntimeAssemblyGroups.First(g => g.Runtime == "osx").Assets.Should().HaveCount(1);
result.NativeLibraryGroups.Should().HaveCount(2);
result.NativeLibraryGroups.First(g => g.Runtime == string.Empty).Assets.Should().HaveCount(0);
result.NativeLibraryGroups.First(g => g.Runtime == "osx").Assets.Should().HaveCount(1);
var nativeAsset = result.NativeLibraryGroups.GetRuntimeAssets("osx").First();
nativeAsset.Name.Should().Be("native");
nativeAsset.Transform.Should().BeNull();
nativeAsset.RelativePath.Should().Be("native/native.dylib");
nativeAsset.ResolvedPath.Should().Be(Path.Combine(PackagePath, "native/native.dylib"));
var runtimeAsset = result.RuntimeAssemblyGroups.GetRuntimeAssets("osx").First();
runtimeAsset.Name.Should().Be("Something.OSX");
runtimeAsset.Transform.Should().BeNull();
runtimeAsset.RelativePath.Should().Be("lib/Something.OSX.dll");
runtimeAsset.ResolvedPath.Should().Be(Path.Combine(PackagePath, "lib/Something.OSX.dll"));
}
[Fact]
public void ExportsPackageResourceAssemblies()
{
var enUsResource = new LockFileItem("resources/en-US/Res.dll");
enUsResource.Properties.Add("locale", "en-US");
var ruRuResource = new LockFileItem("resources/ru-RU/Res.dll");
ruRuResource.Properties.Add("locale", "ru-RU");
var description = CreateDescription(
new LockFileTargetLibrary()
{
ResourceAssemblies = new List<LockFileItem>()
{
enUsResource,
ruRuResource
}
});
var result = ExportSingle(description);
result.ResourceAssemblies.Should().HaveCount(2);
var asset = result.ResourceAssemblies.Should().Contain(g => g.Locale == "en-US").Subject.Asset;
asset.Name.Should().Be("Res");
asset.Transform.Should().BeNull();
asset.RelativePath.Should().Be("resources/en-US/Res.dll");
asset.ResolvedPath.Should().Be(Path.Combine(PackagePath, "resources/en-US/Res.dll"));
asset = result.ResourceAssemblies.Should().Contain(g => g.Locale == "ru-RU").Subject.Asset;
asset.Name.Should().Be("Res");
asset.Transform.Should().BeNull();
asset.RelativePath.Should().Be("resources/ru-RU/Res.dll");
asset.ResolvedPath.Should().Be(Path.Combine(PackagePath, "resources/ru-RU/Res.dll"));
}
[Fact]
public void ExportsSources()
{
var lockFileLibrary = new LockFileLibrary();
lockFileLibrary.Files.Add(Path.Combine("shared", "file.cs"));
var description = CreateDescription(package: lockFileLibrary);
var result = ExportSingle(description);
result.SourceReferences.Should().HaveCount(1);
var libraryAsset = result.SourceReferences.First();
libraryAsset.Name.Should().Be("file");
libraryAsset.Transform.Should().BeNull();
libraryAsset.RelativePath.Should().Be(Path.Combine("shared", "file.cs"));
libraryAsset.ResolvedPath.Should().Be(Path.Combine(PackagePath, "shared", "file.cs"));
}
[Fact]
public void ExportsCopyToOutputContentFiles()
{
var description = CreateDescription(
new LockFileTargetLibrary()
{
ContentFiles = new List<LockFileContentFile>()
{
new LockFileContentFile(Path.Combine("content", "file.txt"))
{
CopyToOutput = true,
OutputPath = Path.Combine("Out","Path.txt"),
PPOutputPath = "something"
}
}
});
var result = ExportSingle(description);
result.RuntimeAssets.Should().HaveCount(1);
var libraryAsset = result.RuntimeAssets.First();
libraryAsset.Transform.Should().NotBeNull();
libraryAsset.RelativePath.Should().Be(Path.Combine("Out", "Path.txt"));
libraryAsset.ResolvedPath.Should().Be(Path.Combine(PackagePath, "content", "file.txt"));
}
[Fact]
public void ExportsResourceContentFiles()
{
var description = CreateDescription(
new LockFileTargetLibrary()
{
ContentFiles = new List<LockFileContentFile>()
{
new LockFileContentFile(Path.Combine("content", "file.txt"))
{
BuildAction = BuildAction.EmbeddedResource,
PPOutputPath = "something"
}
}
});
var result = ExportSingle(description);
result.EmbeddedResources.Should().HaveCount(1);
var libraryAsset = result.EmbeddedResources.First();
libraryAsset.Transform.Should().NotBeNull();
libraryAsset.RelativePath.Should().Be(Path.Combine("content", "file.txt"));
libraryAsset.ResolvedPath.Should().Be(Path.Combine(PackagePath, "content", "file.txt"));
}
[Fact]
public void ExportsCompileContentFiles()
{
var description = CreateDescription(
new LockFileTargetLibrary()
{
ContentFiles = new List<LockFileContentFile>()
{
new LockFileContentFile(Path.Combine("content", "file.cs"))
{
BuildAction = BuildAction.Compile,
PPOutputPath = "something"
}
}
});
var result = ExportSingle(description);
result.SourceReferences.Should().HaveCount(1);
var libraryAsset = result.SourceReferences.First();
libraryAsset.Transform.Should().NotBeNull();
libraryAsset.RelativePath.Should().Be(Path.Combine("content", "file.cs"));
libraryAsset.ResolvedPath.Should().Be(Path.Combine(PackagePath, "content", "file.cs"));
}
[Fact]
public void SelectsContentFilesOfProjectCodeLanguage()
{
var description = CreateDescription(
new LockFileTargetLibrary()
{
ContentFiles = new List<LockFileContentFile>()
{
new LockFileContentFile(Path.Combine("content", "file.cs"))
{
BuildAction = BuildAction.Compile,
PPOutputPath = "something",
CodeLanguage = "cs"
},
new LockFileContentFile(Path.Combine("content", "file.vb"))
{
BuildAction = BuildAction.Compile,
PPOutputPath = "something",
CodeLanguage = "vb"
},
new LockFileContentFile(Path.Combine("content", "file.any"))
{
BuildAction = BuildAction.Compile,
PPOutputPath = "something",
}
}
});
var result = ExportSingle(description);
result.SourceReferences.Should().HaveCount(1);
var libraryAsset = result.SourceReferences.First();
libraryAsset.Transform.Should().NotBeNull();
libraryAsset.RelativePath.Should().Be(Path.Combine("content", "file.cs"));
libraryAsset.ResolvedPath.Should().Be(Path.Combine(PackagePath, "content", "file.cs"));
}
[Fact]
public void SelectsContentFilesWithNoLanguageIfProjectLanguageNotMathed()
{
var description = CreateDescription(
new LockFileTargetLibrary()
{
ContentFiles = new List<LockFileContentFile>()
{
new LockFileContentFile(Path.Combine("content", "file.vb"))
{
BuildAction = BuildAction.Compile,
PPOutputPath = "something",
CodeLanguage = "vb"
},
new LockFileContentFile(Path.Combine("content", "file.any"))
{
BuildAction = BuildAction.Compile,
PPOutputPath = "something",
}
}
});
var result = ExportSingle(description);
result.SourceReferences.Should().HaveCount(1);
var libraryAsset = result.SourceReferences.First();
libraryAsset.Transform.Should().NotBeNull();
libraryAsset.RelativePath.Should().Be(Path.Combine("content", "file.any"));
libraryAsset.ResolvedPath.Should().Be(Path.Combine(PackagePath, "content", "file.any"));
}
private LibraryExport ExportSingle(LibraryDescription description = null)
{
var rootProject = new Project()
{
Name = "RootProject",
_defaultCompilerOptions = new CommonCompilerOptions
{
CompilerName = "csc"
}
};
var rootProjectDescription = new ProjectDescription(
new LibraryRange(),
rootProject,
new ProjectLibraryDependency[] { },
new TargetFrameworkInformation(),
true);
if (description == null)
{
description = rootProjectDescription;
}
else
{
description.Parents.Add(rootProjectDescription);
}
var libraryManager = new LibraryManager(new[] { description }, new DiagnosticMessage[] { }, "");
var allExports = new LibraryExporter(rootProjectDescription, libraryManager, "config", "runtime", null, "basepath", "solutionroot").GetAllExports();
var export = allExports.Single();
return export;
}
}
}
| |
// Graph Engine
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE.md file in the project root for full license information.
//
using System;
using System.Collections.Concurrent;
using System.Linq;
using System.CodeDom.Compiler;
using System.IO;
using System.Security.Permissions;
using System.Reflection;
using Trinity;
using System.Threading;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using System.Collections.Generic;
using FanoutSearch.LIKQ;
using System.Linq.Expressions;
using Trinity.Storage;
using Microsoft.CodeAnalysis.CSharp.Scripting;
using Microsoft.CodeAnalysis.Scripting;
namespace FanoutSearch
{
internal class LambdaDSLSyntaxErrorException : Exception
{
private SyntaxNode m_errorSyntaxNode;
private static string FormatMessage(string message, SyntaxNode node)
{
if (message == null) message = "Syntax error";
return message + ": " + node.GetText().ToString();
}
public LambdaDSLSyntaxErrorException(string message, SyntaxNode node) :
base(FormatMessage(message, node))
{
m_errorSyntaxNode = node;
}
public LambdaDSLSyntaxErrorException(SyntaxNode node) :
base(FormatMessage(null, node))
{
m_errorSyntaxNode = node;
}
}
//TODO JsonDSL and LambdaDSL could share ExpressionBuilder.
//Each DSL should provide ExpressionBuilder-compatible interfaces
//that report the purpose of the syntax node, thus hiding the
//details of a DSL's syntax.
public static class LambdaDSL
{
private class FSDescCallchainElement
{
public string Method;
public List<ArgumentSyntax> Arguments;
public InvocationExpressionSyntax SyntaxNode;
}
#region constants
private const string c_code_header = @"
public static class FanoutSearchDescriptorEvaluator
{
public static void _evaluate()
{";
private const string c_code_footer = @"
}
}
";
private static string s_LIKQ_Prolog = "MAG";
private static string s_LIKQ_StartFrom = "StartFrom";
private static string s_LIKQ_VisitNode = "VisitNode";
private static string s_LIKQ_FollowEdge = "FollowEdge";
private static string s_LIKQ_Action = "Action";
private static string s_LIKQ_FanoutSearch = "FanoutSearch";
#endregion
#region helpers
private static void ThrowIf(bool condition, string message, SyntaxNode syntaxNode)
{
if (condition) throw new LambdaDSLSyntaxErrorException(message, syntaxNode);
}
private static T Get<T>(object obj, string message = null) where T : class
{
var ret = obj as T;
ThrowIf(ret == null, message, obj as SyntaxNode);
return ret;
}
private static T TryGet<T>(object obj) where T : class
{
return obj as T;
}
private class FanoutSearchActionRewritter : CSharpSyntaxRewriter
{
public override SyntaxNode VisitMemberAccessExpression(MemberAccessExpressionSyntax node)
{
do
{
var expr = TryGet<IdentifierNameSyntax>(node.Expression);
if (expr == null) break;
if (expr.GetText().ToString() != s_LIKQ_Action) break;
// Action.[expr] => FanoutSearch.Action.[expr]
return SyntaxFactory.MemberAccessExpression(SyntaxKind.SimpleMemberAccessExpression,
SyntaxFactory.MemberAccessExpression(SyntaxKind.SimpleMemberAccessExpression,
SyntaxFactory.IdentifierName(s_LIKQ_FanoutSearch),
SyntaxFactory.IdentifierName(s_LIKQ_Action)),
node.Name);
} while (false);
return base.VisitMemberAccessExpression(node);
}
}
#endregion
/// <summary>
/// The prolog is "___".StartFrom(...)....
/// </summary>
private static void CheckProlog(IdentifierNameSyntax identifierNameSyntax)
{
bool prolog_valid = false;
if (identifierNameSyntax.Identifier.Text == s_LIKQ_Prolog)
{
prolog_valid = true;
}
ThrowIf(!prolog_valid, "Invalid prolog", identifierNameSyntax);
}
private static List<FSDescCallchainElement> GetFanoutSearchDescriptorCallChain(InvocationExpressionSyntax callchain_root)
{
List<FSDescCallchainElement> callchain = new List<FSDescCallchainElement>();
InvocationExpressionSyntax invocation = callchain_root;
while (invocation != null)
{
// Each invocation MUST be a member access, so there aren't dangling invocations like 'StartFrom(0)', without an identifier as prolog.
MemberAccessExpressionSyntax member = Get<MemberAccessExpressionSyntax>(invocation.Expression);
callchain.Add(new FSDescCallchainElement
{
Arguments = invocation.ArgumentList.Arguments.ToList(),
Method = member.Name.Identifier.Text,
SyntaxNode = invocation
});
invocation = member.Expression as InvocationExpressionSyntax;
if (member.Expression is IdentifierNameSyntax)
{
CheckProlog(member.Expression as IdentifierNameSyntax);
}
}
ThrowIf(callchain.Count == 0, "The query string does not contain an expression.", callchain_root);
callchain.Reverse();
return callchain;
}
private static FanoutSearchDescriptor ConstructFanoutSearchDescriptor(List<FSDescCallchainElement> fs_callchain)
{
FanoutSearchDescriptor fs_desc = ConstructFanoutSearchOrigin(fs_callchain.First());
for (int idx = 1; idx < fs_callchain.Count; ++idx)
{
FSDescCallchainElement visitNode = fs_callchain[idx];
FSDescCallchainElement followEdge = null;
FanoutSearch.Action defaultAction = Action.Continue;
if (visitNode.Method == s_LIKQ_FollowEdge)
{
ThrowIf(++idx >= fs_callchain.Count, "The query expression cannot end with '" + s_LIKQ_FollowEdge + "'", visitNode.SyntaxNode);
followEdge = visitNode;
visitNode = fs_callchain[idx];
if (visitNode.Method == s_LIKQ_FollowEdge)
{
// two consequtive FollowEdge, use default traverse action.
--idx;
visitNode = null;
}
}
if (idx + 1 >= fs_callchain.Count)
{
// The last element should have default action Action.Return
defaultAction = Action.Return;
}
ThrowIf(visitNode.Method != s_LIKQ_VisitNode, "Expecting '" + s_LIKQ_VisitNode + "'", visitNode.SyntaxNode);
fs_desc = ConstructFanoutSearchBody(fs_desc, visitNode, followEdge, defaultAction);
}
return fs_desc;
}
private static FanoutSearchDescriptor ConstructFanoutSearchBody(FanoutSearchDescriptor current, FSDescCallchainElement visitNode, FSDescCallchainElement followEdge, Action defaultTraverseAction)
{
List<string> follow_edge_set = ConstructFollowEdgeSet(followEdge);
EdgeTypeDescriptor ets = current.FollowEdge(follow_edge_set.ToArray());
if (visitNode == null)
{
return ets.VisitNode(defaultTraverseAction);
}
else if (visitNode.Arguments.Count == 1)
{
return ets.VisitNode(ConstructVisitNodeAction(visitNode.Arguments[0].Expression));
}
else /*if (visitNode.Arguments.Count > 1)*/
{
return ets.VisitNode(
ConstructVisitNodeAction(visitNode.Arguments[0].Expression),
ConstructCollection<string>(visitNode.Arguments[1].Expression) /*select*/);
}
}
/// <summary>
/// Analyse expressions of form new[] { .., .., ....}, or new List[T] { .., .., .. }, or new T[] {..., ...}
/// Support string collection, or numerical collection
/// </summary>
/// <typeparam name="T">
/// Only supports string and long
/// </typeparam>
private static IEnumerable<T> ConstructCollection<T>(ExpressionSyntax collectionSyntax)
{
InitializerExpressionSyntax initializer = null;
SyntaxKind element_type_kind = SyntaxKind.VoidKeyword;
SyntaxKind element_literal_kind = SyntaxKind.VoidKeyword;
if (typeof(T) == typeof(long))
{
element_type_kind = SyntaxKind.LongKeyword;
element_literal_kind = SyntaxKind.NumericLiteralExpression;
}
else if (typeof(T) == typeof(string))
{
element_type_kind = SyntaxKind.StringKeyword;
element_literal_kind = SyntaxKind.StringLiteralExpression;
}
else
{
goto throw_invalid_element_type;
}
switch (collectionSyntax.Kind())
{
case SyntaxKind.ObjectCreationExpression:
/*List<T>*/
var list_expr = Get<ObjectCreationExpressionSyntax>(collectionSyntax);
var list_type = Get<GenericNameSyntax>(list_expr.Type);
ThrowIf(list_type.Arity != 1, null, syntaxNode: list_type);
var list_type_arg = Get<PredefinedTypeSyntax>(list_type.TypeArgumentList.Arguments[0]);
ThrowIf(!list_type_arg.Keyword.IsKind(element_type_kind), "Invalid collection element type", syntaxNode: list_type_arg);
initializer = list_expr.Initializer;
break;
case SyntaxKind.ImplicitArrayCreationExpression:
/*Implicit array*/
initializer = Get<InitializerExpressionSyntax>((collectionSyntax as ImplicitArrayCreationExpressionSyntax).Initializer);
break;
case SyntaxKind.ArrayCreationExpression:
/*Array*/
var array_expr = Get<ArrayCreationExpressionSyntax>(collectionSyntax);
initializer = Get<InitializerExpressionSyntax>(array_expr.Initializer);
var array_type = Get<PredefinedTypeSyntax>(array_expr.Type.ElementType);
ThrowIf(!array_type.Keyword.IsKind(element_type_kind), "Invalid collection element type", syntaxNode: array_type);
break;
default:
throw new LambdaDSLSyntaxErrorException(collectionSyntax);
}
foreach (var element in initializer.Expressions)
{
var literal = Get<LiteralExpressionSyntax>(element);
ThrowIf(!literal.IsKind(element_literal_kind), "Invalid collection element type", literal);
yield return (T)(dynamic)literal.Token.Value;
}
yield break;
throw_invalid_element_type:
throw new LambdaDSLSyntaxErrorException("Invalid collection element type", collectionSyntax);
}
private static Expression<Func<ICellAccessor, Action>> ConstructVisitNodeAction(ExpressionSyntax traverseAction)
{
/***********************************************
* Syntax: (VISITNODE)
*
* 1. VisitNode(FanoutSearch.Action action, IEnumerable<string> select = null)
* 2. VisitNode(Expression<Func<ICellAccessor, FanoutSearch.Action>> action, IEnumerable<string> select = null)
*
* The select part is handled by the caller.
***********************************************/
var action_expr = TryGet<MemberAccessExpressionSyntax>(traverseAction);
var lambda_expression = TryGet<LambdaExpressionSyntax>(traverseAction);
Expression<Func<ICellAccessor, Action>> ret = null;
if (action_expr != null)
{
// Action enum
var id_expr = Get<IdentifierNameSyntax>(action_expr.Expression);
if (id_expr.ToString() != s_LIKQ_Action) goto throw_badtype;
Action result_action;
ThrowIf(!Enum.TryParse(action_expr.Name.ToString(), out result_action), "Invalid traverse action", action_expr);
return ExpressionBuilder.WrapAction(result_action);
}
else
{
if (lambda_expression == null) goto throw_badtype;
// FanoutSearch.Action is ambiguous with with System.Action
var action_visitor = new FanoutSearchActionRewritter();
lambda_expression = action_visitor.Visit(lambda_expression) as LambdaExpressionSyntax;
ScriptOptions scriptOptions = ScriptOptions.Default;
var mscorlib = typeof(System.Object).Assembly;
var systemCore = typeof(System.Linq.Enumerable).Assembly;
var expression = typeof(Expression).Assembly;
var fanout = typeof(FanoutSearchModule).Assembly;
var trinity = typeof(Trinity.Global).Assembly;
scriptOptions = scriptOptions.AddReferences(mscorlib, systemCore, expression, fanout, trinity);
scriptOptions = scriptOptions.AddImports(
"System",
"System.Linq",
"System.Linq.Expressions",
"System.Collections.Generic",
"FanoutSearch",
"FanoutSearch.LIKQ",
"Trinity",
"Trinity.Storage");
try
{
// Allocate a cancellation token source, which signals after our timeout setting (if we do have timeout setting)
CancellationToken cancel_token = default(CancellationToken);
if (FanoutSearchModule._QueryTimeoutEnabled())
{
checked
{
cancel_token = new CancellationTokenSource((int)FanoutSearchModule.GetQueryTimeout()).Token;
}
}
// It is guaranteed that the lambda_expression is really a lambda.
// Evaluating a lambda and expecting an expression tree to be obtained now.
var eval_task = CSharpScript.EvaluateAsync<Expression<Func<ICellAccessor, Action>>>(lambda_expression.ToString(), scriptOptions, cancellationToken: cancel_token);
eval_task.Wait();
ret = eval_task.Result;
}
catch (ArithmeticException) { /* that's a fault not an error */ throw; }
catch { /*swallow roslyn scripting engine exceptions.*/ }
ThrowIf(null == ret, "Invalid lambda expression.", traverseAction);
return ret;
}
throw_badtype:
ThrowIf(true, "Expecting an argument of type FanoutSearch.Action, or a lambda expression.", traverseAction);
return null;//not going to happen
}
private static List<string> ConstructFollowEdgeSet(FSDescCallchainElement followEdge)
{
/***********************************************
* Syntax:
*
* FollowEdge(params string[] edgeTypes)
***********************************************/
var ret = new List<string>();
if (followEdge == null) return ret;
foreach (var arg in followEdge.Arguments)
{
var edge = Get<LiteralExpressionSyntax>(arg.Expression, "Expecting a string");
ThrowIf(!edge.IsKind(SyntaxKind.StringLiteralExpression), "Expecting a string", arg);
ret.Add(edge.Token.ValueText);
}
// * means wildcard.
if (ret.Any(_ => _ == "*")) { ret.Clear(); }
return ret;
}
private static FanoutSearchDescriptor ConstructFanoutSearchOrigin(FSDescCallchainElement origin)
{
/***********************************************
* Syntax:
*
* 1. StartFrom(long cellid, IEnumerable<string> select = null)
* 2. StartFrom(IEnumerable<long> cellid, IEnumerable<string> select = null)
* 3. StartFrom(string queryObject, IEnumerable<string> select = null)
***********************************************/
ThrowIf(origin.Method != s_LIKQ_StartFrom, "Expecting " + s_LIKQ_StartFrom, origin.SyntaxNode);
FanoutSearchDescriptor fs_desc = new FanoutSearchDescriptor("");
fs_desc.m_origin_query = null;
ThrowIf(origin.Arguments.Count < 1 || origin.Arguments.Count > 2, "Expecting 1 or 2 arguments", origin.SyntaxNode);
ExpressionSyntax origin_cell_query = origin.Arguments[0].Expression;
ExpressionSyntax selection = origin.Arguments.Count < 2 ? null : origin.Arguments[1].Expression;
switch (origin_cell_query.Kind())
{
case SyntaxKind.ObjectCreationExpression:
case SyntaxKind.ImplicitArrayCreationExpression:
case SyntaxKind.ArrayCreationExpression:
fs_desc.m_origin = ConstructCollection<long>(origin_cell_query).ToList();
break;
case SyntaxKind.NumericLiteralExpression:
{
var origin_cellid = Get<LiteralExpressionSyntax>(origin_cell_query);
long cell_id = 0;
var parse_result = long.TryParse(origin_cellid.Token.ValueText, out cell_id);
ThrowIf(!parse_result, "Expecting a cell id", origin_cell_query);
fs_desc.m_origin = new List<long> { cell_id };
break;
}
case SyntaxKind.StringLiteralExpression:
fs_desc.m_origin_query = (origin_cell_query as LiteralExpressionSyntax).Token.ValueText;
break;
default:
throw new LambdaDSLSyntaxErrorException("Invalid starting node argument", origin_cell_query);
}
if (selection != null)
{
fs_desc.m_selectFields.Add(ConstructCollection<string>(selection).ToList());
}
return fs_desc;
}
private static InvocationExpressionSyntax GetFanoutSearchDescriptorExpression(string expr)
{
var tree = Get<SyntaxTree>(CSharpSyntaxTree.ParseText(c_code_header + expr + c_code_footer));
var root = Get<CompilationUnitSyntax>(tree.GetRoot());
ThrowIf(root.ChildNodes().Count() != 1, null, root);
var class_declaration = Get<ClassDeclarationSyntax>(root.ChildNodes().First());
ThrowIf(class_declaration.ChildNodes().Count() != 1, null, class_declaration);
var method_declaration = Get<MethodDeclarationSyntax>(class_declaration.Members.FirstOrDefault());
ThrowIf(method_declaration.ExpressionBody != null, null, method_declaration);
var method_body = Get<BlockSyntax>(method_declaration.Body);
ThrowIf(method_body.Statements.Count != 1, "The query string contains too many statements.", method_body);
var fs_desc_stmt = Get<StatementSyntax>(method_body.Statements.First());
ThrowIf(fs_desc_stmt.ChildNodes().Count() != 1, "The query string contains too many expressions.", fs_desc_stmt);
var invocation = Get<InvocationExpressionSyntax>(fs_desc_stmt.ChildNodes().First());
return invocation;
}
public static FanoutSearchDescriptor Evaluate(string expr)
{
try
{
var fs_invocation_expr = GetFanoutSearchDescriptorExpression(expr);
//if we could use LIKQ to match such patterns...
var fs_callchain = GetFanoutSearchDescriptorCallChain(fs_invocation_expr);
var fs_desc = ConstructFanoutSearchDescriptor(fs_callchain);
var checker = new TraverseActionSecurityChecker();
fs_desc.m_traverseActions.ForEach(_ => checker.Visit(_));
return fs_desc;
}
catch (LambdaDSLSyntaxErrorException ex)
{
throw new FanoutSearchQueryException(ex.Message);
}
}
public static void SetDialect(string prolog, string startFrom, string visitNode, string followEdge, string action)
{
s_LIKQ_Prolog = prolog;
s_LIKQ_StartFrom = startFrom;
s_LIKQ_VisitNode = visitNode;
s_LIKQ_FollowEdge = followEdge;
s_LIKQ_Action = action;
}
}
}
| |
using System;
using System.Text;
using Org.BouncyCastle.Utilities;
namespace Org.BouncyCastle.Asn1.X509
{
/**
* <pre>
* IssuingDistributionPoint ::= SEQUENCE {
* distributionPoint [0] DistributionPointName OPTIONAL,
* onlyContainsUserCerts [1] BOOLEAN DEFAULT FALSE,
* onlyContainsCACerts [2] BOOLEAN DEFAULT FALSE,
* onlySomeReasons [3] ReasonFlags OPTIONAL,
* indirectCRL [4] BOOLEAN DEFAULT FALSE,
* onlyContainsAttributeCerts [5] BOOLEAN DEFAULT FALSE }
* </pre>
*/
public class IssuingDistributionPoint
: Asn1Encodable
{
private readonly DistributionPointName _distributionPoint;
private readonly bool _onlyContainsUserCerts;
private readonly bool _onlyContainsCACerts;
private readonly ReasonFlags _onlySomeReasons;
private readonly bool _indirectCRL;
private readonly bool _onlyContainsAttributeCerts;
private readonly Asn1Sequence seq;
public static IssuingDistributionPoint GetInstance(
Asn1TaggedObject obj,
bool explicitly)
{
return GetInstance(Asn1Sequence.GetInstance(obj, explicitly));
}
public static IssuingDistributionPoint GetInstance(
object obj)
{
if (obj == null || obj is IssuingDistributionPoint)
{
return (IssuingDistributionPoint) obj;
}
if (obj is Asn1Sequence)
{
return new IssuingDistributionPoint((Asn1Sequence) obj);
}
throw new ArgumentException("unknown object in factory: " + obj.GetType().Name, "obj");
}
/**
* Constructor from given details.
*
* @param distributionPoint
* May contain an URI as pointer to most current CRL.
* @param onlyContainsUserCerts Covers revocation information for end certificates.
* @param onlyContainsCACerts Covers revocation information for CA certificates.
*
* @param onlySomeReasons
* Which revocation reasons does this point cover.
* @param indirectCRL
* If <code>true</code> then the CRL contains revocation
* information about certificates ssued by other CAs.
* @param onlyContainsAttributeCerts Covers revocation information for attribute certificates.
*/
public IssuingDistributionPoint(
DistributionPointName distributionPoint,
bool onlyContainsUserCerts,
bool onlyContainsCACerts,
ReasonFlags onlySomeReasons,
bool indirectCRL,
bool onlyContainsAttributeCerts)
{
this._distributionPoint = distributionPoint;
this._indirectCRL = indirectCRL;
this._onlyContainsAttributeCerts = onlyContainsAttributeCerts;
this._onlyContainsCACerts = onlyContainsCACerts;
this._onlyContainsUserCerts = onlyContainsUserCerts;
this._onlySomeReasons = onlySomeReasons;
Asn1EncodableVector vec = new Asn1EncodableVector();
if (distributionPoint != null)
{ // CHOICE item so explicitly tagged
vec.Add(new DerTaggedObject(true, 0, distributionPoint));
}
if (onlyContainsUserCerts)
{
vec.Add(new DerTaggedObject(false, 1, DerBoolean.True));
}
if (onlyContainsCACerts)
{
vec.Add(new DerTaggedObject(false, 2, DerBoolean.True));
}
if (onlySomeReasons != null)
{
vec.Add(new DerTaggedObject(false, 3, onlySomeReasons));
}
if (indirectCRL)
{
vec.Add(new DerTaggedObject(false, 4, DerBoolean.True));
}
if (onlyContainsAttributeCerts)
{
vec.Add(new DerTaggedObject(false, 5, DerBoolean.True));
}
seq = new DerSequence(vec);
}
/**
* Constructor from Asn1Sequence
*/
private IssuingDistributionPoint(
Asn1Sequence seq)
{
this.seq = seq;
for (int i = 0; i != seq.Count; i++)
{
Asn1TaggedObject o = Asn1TaggedObject.GetInstance(seq[i]);
switch (o.TagNo)
{
case 0:
// CHOICE so explicit
_distributionPoint = DistributionPointName.GetInstance(o, true);
break;
case 1:
_onlyContainsUserCerts = DerBoolean.GetInstance(o, false).IsTrue;
break;
case 2:
_onlyContainsCACerts = DerBoolean.GetInstance(o, false).IsTrue;
break;
case 3:
_onlySomeReasons = new ReasonFlags(ReasonFlags.GetInstance(o, false));
break;
case 4:
_indirectCRL = DerBoolean.GetInstance(o, false).IsTrue;
break;
case 5:
_onlyContainsAttributeCerts = DerBoolean.GetInstance(o, false).IsTrue;
break;
default:
throw new ArgumentException("unknown tag in IssuingDistributionPoint");
}
}
}
public bool OnlyContainsUserCerts
{
get { return _onlyContainsUserCerts; }
}
public bool OnlyContainsCACerts
{
get { return _onlyContainsCACerts; }
}
public bool IsIndirectCrl
{
get { return _indirectCRL; }
}
public bool OnlyContainsAttributeCerts
{
get { return _onlyContainsAttributeCerts; }
}
/**
* @return Returns the distributionPoint.
*/
public DistributionPointName DistributionPoint
{
get { return _distributionPoint; }
}
/**
* @return Returns the onlySomeReasons.
*/
public ReasonFlags OnlySomeReasons
{
get { return _onlySomeReasons; }
}
public override Asn1Object ToAsn1Object()
{
return seq;
}
public override string ToString()
{
string sep = Platform.NewLine;
StringBuilder buf = new StringBuilder();
buf.Append("IssuingDistributionPoint: [");
buf.Append(sep);
if (_distributionPoint != null)
{
appendObject(buf, sep, "distributionPoint", _distributionPoint.ToString());
}
if (_onlyContainsUserCerts)
{
appendObject(buf, sep, "onlyContainsUserCerts", _onlyContainsUserCerts.ToString());
}
if (_onlyContainsCACerts)
{
appendObject(buf, sep, "onlyContainsCACerts", _onlyContainsCACerts.ToString());
}
if (_onlySomeReasons != null)
{
appendObject(buf, sep, "onlySomeReasons", _onlySomeReasons.ToString());
}
if (_onlyContainsAttributeCerts)
{
appendObject(buf, sep, "onlyContainsAttributeCerts", _onlyContainsAttributeCerts.ToString());
}
if (_indirectCRL)
{
appendObject(buf, sep, "indirectCRL", _indirectCRL.ToString());
}
buf.Append("]");
buf.Append(sep);
return buf.ToString();
}
private void appendObject(
StringBuilder buf,
string sep,
string name,
string val)
{
string indent = " ";
buf.Append(indent);
buf.Append(name);
buf.Append(":");
buf.Append(sep);
buf.Append(indent);
buf.Append(indent);
buf.Append(val);
buf.Append(sep);
}
}
}
| |
namespace Shopify.Tests {
using NUnit.Framework;
using System;
using System.Collections.Generic;
using Shopify.Unity;
using Shopify.Unity.SDK;
using Shopify.Unity.GraphQL;
using Shopify.Unity.MiniJSON;
class CollectionTestQueries {
public static QueryRootQuery query1 = (new QueryRootQuery()).
products(p => p.
edges(e => e.
node(n => n.
title()
).
cursor()
).
pageInfo(pi => pi.
hasNextPage()
),
first: 1
);
public static QueryRootQuery query2 = (new QueryRootQuery()).
products(p => p.
edges(e => e.
node(n => n.
title()
).
cursor()
).
pageInfo(pi => pi.
hasNextPage()
),
first: 1, after: "first page"
);
public static List<QueryRootQuery> queries = new List<QueryRootQuery> {query1, query2};
}
class CollectionTestLoader : BaseLoader {
public CollectionTestLoader() : base("someshop.myshopify.com", "1234") {}
public override void Load(string query, LoaderResponseHandler callback) {
if (query == CollectionTestQueries.query1.ToString()) {
callback(@"{""data"":{
""products"": {
""edges"": [
{
""node"": {
""title"": ""Product1""
},
""cursor"": ""first page""
}
],
""pageInfo"": {
""hasNextPage"": true
}
}
}}", null);
} else if (query == CollectionTestQueries.query2.ToString()) {
callback(@"{""data"":{
""products"": {
""edges"": [
{
""node"": {
""title"": ""Product2""
},
""cursor"": ""second page""
}
],
""pageInfo"": {
""hasNextPage"": false
}
}
}}", null);
}
}
public override void SetHeader(string key, string value) {
// No-op
}
public override string SDKVariantName() {
return "collection-test-loader";
}
}
[TestFixture]
public class TestRelay {
[Test]
public void TestCastConnectionToList() {
string stringJSON = @"{
""edges"": [
{
""node"": {
""title"": ""Product 1""
}
},
{
""node"": {
""title"": ""Product 2""
}
}
]
}";
ProductConnection connection = new ProductConnection((Dictionary<string, object>) Json.Deserialize(stringJSON));
List<Product> products = (List<Product>) connection;
bool couldIterateOverConnection = false;
foreach (Product product in products) {
couldIterateOverConnection = true;
}
Assert.IsNotNull(products, "products is not null");
Assert.AreEqual(2, products.Count, "products list has two products");
Assert.AreEqual("Product 2", products[1].title(), "List had data");
Assert.IsTrue(couldIterateOverConnection, "could iterate over connection");
}
[Test]
public void TestAddingToConnection() {
string responseString1 = @"{
""edges"": [
{
""node"": {
""title"": ""product1""
},
""cursor"": ""0""
}
],
""pageInfo"": {
""hasNextPage"": true
}
}";
string responseString2 = @"{
""edges"": [
{
""node"": {
""title"": ""product2""
},
""cursor"": ""1""
}
],
""pageInfo"": {
""hasNextPage"": false
}
}";
Dictionary<string, object> response1 = (Dictionary<string, object>) Json.Deserialize(responseString1);
Dictionary<string, object> response2 = (Dictionary<string, object>) Json.Deserialize(responseString2);
ProductConnection queryResponse1 = new ProductConnection(response1);
ProductConnection queryResponse2 = new ProductConnection(response2);
queryResponse1.AddFromConnection(queryResponse2);
Assert.AreEqual(2, queryResponse1.edges().Count);
Assert.AreEqual("product1", queryResponse1.edges()[0].node().title());
Assert.AreEqual("product2", queryResponse1.edges()[1].node().title());
Assert.AreEqual(false, queryResponse1.pageInfo().hasNextPage());
// the following are to test whether original response was not mutated
Assert.AreEqual(1, ((List<object>) response1["edges"]).Count);
Assert.AreEqual("product1", ((Dictionary<string,object>) ((Dictionary<string,object>) ((List<object>) response1["edges"])[0])["node"])["title"]);
}
[Test]
public void TestAddingToConnectionUnitialized() {
string responseString2 = @"{
""edges"": [
{
""node"": {
""title"": ""product1""
},
""cursor"": ""0""
}
],
""pageInfo"": {
""hasNextPage"": true
}
}";
Dictionary<string, object> response2 = (Dictionary<string, object>) Json.Deserialize(responseString2);
Dictionary<string,object> response1 = new Dictionary<string,object>();
ProductConnection queryResponse1 = new ProductConnection(response1);
ProductConnection queryResponse2 = new ProductConnection(response2);
queryResponse1.AddFromConnection(queryResponse2);
Assert.AreEqual(1, queryResponse1.edges().Count);
Assert.AreEqual("product1", queryResponse1.edges()[0].node().title());
Assert.AreEqual(true, queryResponse1.pageInfo().hasNextPage());
}
[Test]
public void TestConnectionLoader() {
int countRequests = 0;
ConnectionLoader ConnectionLoader = new ConnectionLoader(new QueryLoader(new CollectionTestLoader()));
List<QueryResponse> responsesToRequestQuery = new List<QueryResponse>();
QueryResponse mergedResponse = null;
ConnectionLoader.QueryConnection(
(response) => {
responsesToRequestQuery.Add(response);
if (countRequests < CollectionTestQueries.queries.Count) {
countRequests++;
return CollectionTestQueries.queries[countRequests - 1];
} else {
return null;
}
},
(response) => {
return ((QueryRoot) response).products();
},
(response) => {
mergedResponse = response;
}
);
Assert.AreEqual(3, responsesToRequestQuery.Count);
Assert.AreEqual(null, responsesToRequestQuery[0]);
Assert.AreEqual("Product1", responsesToRequestQuery[1].data.products().edges()[0].node().title());
Assert.AreEqual("Product2", responsesToRequestQuery[2].data.products().edges()[0].node().title());
Assert.AreEqual(2, countRequests);
Assert.AreEqual(2, mergedResponse.data.products().edges().Count);
}
}
}
| |
// The MIT License (MIT)
//
// CoreTweet - A .NET Twitter Library supporting Twitter API 1.1
// Copyright (c) 2013-2015 CoreTweet Development Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
using System.Collections.Generic;
using CoreTweet.Core;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace CoreTweet.Streaming
{
/// <summary>
/// Provides disconnect codes in Twitter Streaming API.
/// </summary>
public enum DisconnectCode
{
/// <summary>
/// The feed was shutdown (possibly a machine restart)
/// </summary>
Shutdown = 1,
/// <summary>
/// The same endpoint was connected too many times.
/// </summary>
DuplicateStream,
/// <summary>
/// Control streams was used to close a stream (applies to sitestreams).
/// </summary>
ControlRequest,
/// <summary>
/// The client was reading too slowly and was disconnected by the server.
/// </summary>
Stall,
/// <summary>
/// The client appeared to have initiated a disconnect.
/// </summary>
Normal,
/// <summary>
/// An oauth token was revoked for a user (applies to site and userstreams).
/// </summary>
TokenRevoked,
/// <summary>
/// The same credentials were used to connect a new stream and the oldest was disconnected.
/// </summary>
AdminLogout,
/// <summary>
/// <para>Reserved for internal use.</para>
/// <para>Will not be delivered to external clients.</para>
/// </summary>
Reserved,
/// <summary>
/// The stream connected with a negative count parameter and was disconnected after all backfill was delivered.
/// </summary>
MaxMessageLimit,
/// <summary>
/// An internal issue disconnected the stream.
/// </summary>
StreamException,
/// <summary>
/// An internal issue disconnected the stream.
/// </summary>
BrokerStall,
/// <summary>
/// <para>The host the stream was connected to became overloaded and streams were disconnected to balance load.</para>
/// <para>Reconnect as usual.</para>
/// </summary>
ShedLoad
}
/// <summary>
/// Provides event codes in Twitter Streaming API.
/// </summary>
public enum EventCode
{
/// <summary>
/// The user revokes his access token.
/// </summary>
AccessRevoked,
/// <summary>
/// The user blocks a user.
/// </summary>
Block,
/// <summary>
/// The user unblocks a user.
/// </summary>
Unblock,
/// <summary>
/// The user favorites a Tweet.
/// </summary>
Favorite,
/// <summary>
/// The user unfavorites a Tweet.
/// </summary>
Unfavorite,
/// <summary>
/// The user follows a user.
/// </summary>
Follow,
/// <summary>
/// The user unfollows a user.
/// </summary>
Unfollow,
/// <summary>
/// The user creates a List.
/// </summary>
ListCreated,
/// <summary>
/// The user destroys a List.
/// </summary>
ListDestroyed,
/// <summary>
/// The user updates a List.
/// </summary>
ListUpdated,
/// <summary>
/// The user adds a user to a List.
/// </summary>
ListMemberAdded,
/// <summary>
/// The user removes a user from a List.
/// </summary>
ListMemberRemoved,
/// <summary>
/// The user subscribes a List.
/// </summary>
ListUserSubscribed,
/// <summary>
/// The user unsubscribes a List.
/// </summary>
ListUserUnsubscribed,
/// <summary>
/// The user updates a List.
/// </summary>
UserUpdate,
/// <summary>
/// The user mutes a user.
/// </summary>
Mute,
/// <summary>
/// The user unmutes a user.
/// </summary>
Unmute,
/// <summary>
/// The user favorites a retweet.
/// </summary>
FavoritedRetweet,
/// <summary>
/// The user retweets a retweet.
/// </summary>
RetweetedRetweet,
/// <summary>
/// The user quotes a Tweet.
/// </summary>
QuotedTweet
}
/// <summary>
/// Provides message types in Twitter Streaming API.
/// </summary>
public enum MessageType
{
/// <summary>
/// The message indicates the Tweet has been deleted.
/// </summary>
DeleteStatus,
/// <summary>
/// The message indicates the Direct Message has been deleted.
/// </summary>
DeleteDirectMessage,
/// <summary>
/// The message indicates that geolocated data must be stripped from a range of Tweets.
/// </summary>
ScrubGeo,
/// <summary>
/// The message indicates that the indicated tweet has had their content withheld.
/// </summary>
StatusWithheld,
/// <summary>
/// The message indicates that indicated user has had their content withheld.
/// </summary>
UserWithheld,
/// <summary>
/// The message indicates that the user has been deleted.
/// </summary>
UserDelete,
/// <summary>
/// The message indicates that the user has canceled the deletion.
/// </summary>
//TODO: need investigation
UserUndelete,
/// <summary>
/// The message indicates that the user has been suspended.
/// </summary>
UserSuspend,
/// <summary>
/// The message indicates that the streams may be shut down for a variety of reasons.
/// </summary>
Disconnect,
/// <summary>
/// <para>The message indicates the current health of the connection.</para>
/// <para>This can be only sent when connected to a stream using the stall_warnings parameter.</para>
/// </summary>
Warning,
/// <summary>
/// The message is about non-Tweet events.
/// </summary>
Event,
/// <summary>
/// <para>The message is sent to identify the target of each message.</para>
/// <para>In Site Streams, an additional wrapper is placed around every message, except for blank keep-alive lines.</para>
/// </summary>
Envelopes,
/// <summary>
/// The message is a new Tweet.
/// </summary>
Create,
/// <summary>
/// The message is a new Direct Message.
/// </summary>
DirectMesssage,
/// <summary>
/// <para>The message is a list of the user's friends.</para>
/// <para>Twitter sends a preamble before starting regular message delivery upon establishing a User Stream connection.</para>
/// </summary>
Friends,
/// <summary>
/// The message indicates that a filtered stream has matched more Tweets than its current rate limit allows to be delivered.
/// </summary>
Limit,
/// <summary>
/// The message is sent to modify the Site Streams connection without reconnecting.
/// </summary>
Control,
/// <summary>
/// The message is in raw JSON format.
/// </summary>
RawJson
}
/// <summary>
/// Represents a streaming message. This class is an abstract class.
/// </summary>
public abstract class StreamingMessage : CoreBase
{
/// <summary>
/// Gets the type of the message.
/// </summary>
public MessageType Type => this.GetMessageType();
/// <summary>
/// Gets or sets the raw JSON.
/// </summary>
public string Json { get; set; }
/// <summary>
/// Gets the type of the message.
/// </summary>
/// <returns>The type of the message.</returns>
protected abstract MessageType GetMessageType();
/// <summary>
/// Converts the JSON to a <see cref="StreamingMessage"/> object.
/// </summary>
/// <param name="x">The JSON value.</param>
/// <returns>The <see cref="StreamingMessage"/> object.</returns>
public static StreamingMessage Parse(string x)
{
try
{
var j = JObject.Parse(x);
StreamingMessage m;
if(j["text"] != null)
m = StatusMessage.Parse(j);
else if(j["direct_message"] != null)
m = CoreBase.Convert<DirectMessageMessage>(x);
else if(j["friends"] != null)
m = CoreBase.Convert<FriendsMessage>(x);
else if(j["event"] != null)
m = EventMessage.Parse(j);
else if(j["for_user"] != null)
m = EnvelopesMessage.Parse(j);
else if(j["control"] != null)
m = CoreBase.Convert<ControlMessage>(x);
else
m = ExtractRoot(j);
m.Json = x;
return m;
}
catch(ParsingException)
{
throw;
}
catch(Exception e)
{
throw new ParsingException("on streaming, cannot parse the json", x, e);
}
}
static StreamingMessage ExtractRoot(JObject jo)
{
JToken jt;
if(jo.TryGetValue("disconnect", out jt))
return jt.ToObject<DisconnectMessage>();
if(jo.TryGetValue("warning", out jt))
return jt.ToObject<WarningMessage>();
if(jo.TryGetValue("control", out jt))
return jt.ToObject<ControlMessage>();
if(jo.TryGetValue("delete", out jt))
{
JToken status;
DeleteMessage id;
if (((JObject)jt).TryGetValue("status", out status))
{
id = status.ToObject<DeleteMessage>();
id.messageType = MessageType.DeleteStatus;
}
else
{
id = jt["direct_message"].ToObject<DeleteMessage>();
id.messageType = MessageType.DeleteDirectMessage;
}
var timestamp = jt["timestamp_ms"];
if (timestamp != null)
id.Timestamp = InternalUtils.GetUnixTimeMs(long.Parse((string)timestamp));
return id;
}
if(jo.TryGetValue("scrub_geo", out jt))
{
return jt.ToObject<ScrubGeoMessage>();
}
if(jo.TryGetValue("limit", out jt))
{
return jt.ToObject<LimitMessage>();
}
if(jo.TryGetValue("status_withheld", out jt))
{
return jt.ToObject<StatusWithheldMessage>();
}
if(jo.TryGetValue("user_withheld", out jt))
{
return jt.ToObject<UserWithheldMessage>();
}
if(jo.TryGetValue("user_delete", out jt))
{
var m = jt.ToObject<UserMessage>();
m.messageType = MessageType.UserDelete;
return m;
}
if(jo.TryGetValue("user_undelete", out jt))
{
var m = jt.ToObject<UserMessage>();
m.messageType = MessageType.UserUndelete;
return m;
}
if(jo.TryGetValue("user_suspend", out jt))
{
// user_suspend doesn't have 'timestamp_ms' field
var m = jt.ToObject<UserMessage>();
m.messageType = MessageType.UserSuspend;
return m;
}
throw new ParsingException("on streaming, cannot parse the json: unsupported type", jo.ToString(Formatting.Indented), null);
}
}
/// <summary>
/// Represents a streaming message containing a timestamp.
/// </summary>
public abstract class TimestampMessage : StreamingMessage
{
/// <summary>
/// Gets or sets the timestamp.
/// </summary>
[JsonProperty("timestamp_ms")]
[JsonConverter(typeof(TimestampConverter))]
public DateTimeOffset Timestamp { get; set; }
}
/// <summary>
/// Represents a status message.
/// </summary>
public class StatusMessage : TimestampMessage
{
/// <summary>
/// Gets or sets the status.
/// </summary>
public Status Status { get; set; }
/// <summary>
/// Gets the type of the message.
/// </summary>
/// <returns>The type of the message.</returns>
protected override MessageType GetMessageType()
{
return MessageType.Create;
}
internal static StatusMessage Parse(JObject j)
{
var m = new StatusMessage()
{
Status = j.ToObject<Status>()
};
var timestamp = j["timestamp_ms"];
if (timestamp != null)
m.Timestamp = InternalUtils.GetUnixTimeMs(long.Parse((string)timestamp));
return m;
}
}
/// <summary>
/// Represents a Direct message message.
/// </summary>
public class DirectMessageMessage : StreamingMessage
{
/// <summary>
/// The direct message.
/// </summary>
/// <value>The direct message.</value>
[JsonProperty("direct_message")]
public DirectMessage DirectMessage { get; set; }
/// <summary>
/// Gets the type of the message.
/// </summary>
/// <returns>The type of the message.</returns>
protected override MessageType GetMessageType()
{
return MessageType.DirectMesssage;
}
}
/// <summary>
/// Represents a message contains ids of friends.
/// </summary>
[JsonObject]
public class FriendsMessage : StreamingMessage,IEnumerable<long>
{
/// <summary>
/// Gets or sets the ids of friends.
/// </summary>
[JsonProperty("friends")]
public long[] Friends { get; set; }
/// <summary>
/// Gets the type of the message.
/// </summary>
/// <returns>The type of the message.</returns>
protected override MessageType GetMessageType()
{
return MessageType.Friends;
}
/// <summary>
/// Returns an enumerator that iterates through a collection.
/// </summary>
/// <returns>An IEnumerator object that can be used to iterate through the collection.</returns>
public IEnumerator<long> GetEnumerator()
{
return ((IEnumerable<long>)Friends).GetEnumerator();
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return Friends.GetEnumerator();
}
}
/// <summary>
/// Represents the message with the rate limit.
/// </summary>
public class LimitMessage : TimestampMessage
{
/// <summary>
/// Gets or sets a total count of the number of undelivered Tweets since the connection was opened.
/// </summary>
[JsonProperty("track")]
public int Track { get; set; }
/// <summary>
/// Gets the type of the message.
/// </summary>
/// <returns>The type of the message.</returns>
protected override MessageType GetMessageType()
{
return MessageType.Limit;
}
}
/// <summary>
/// Represents a delete message of a status or a direct message.
/// </summary>
public class DeleteMessage : TimestampMessage
{
/// <summary>
/// Gets or sets the ID.
/// </summary>
[JsonProperty("id")]
public long Id { get; set; }
/// <summary>
/// Gets or sets the ID of the user.
/// </summary>
[JsonProperty("user_id")]
public long UserId { get; set; }
internal MessageType messageType { get; set; }
/// <summary>
/// Gets the type of the message.
/// </summary>
/// <returns>The type of the message.</returns>
protected override MessageType GetMessageType()
{
return messageType;
}
}
/// <summary>
/// Represents a scrub-get message.
/// </summary>
public class ScrubGeoMessage : TimestampMessage
{
/// <summary>
/// Gets or sets the ID of the user.
/// </summary>
[JsonProperty("user_id")]
public long UserId { get; set; }
/// <summary>
/// Gets or sets the ID of the status.
/// </summary>
//TODO: improve this comment
[JsonProperty("up_to_status_id")]
public long UpToStatusId { get; set; }
/// <summary>
/// Gets the type of the message.
/// </summary>
/// <returns>The type of the message.</returns>
protected override MessageType GetMessageType()
{
return MessageType.ScrubGeo;
}
}
/// <summary>
/// Represents a withheld message.
/// </summary>
public class UserWithheldMessage : TimestampMessage
{
/// <summary>
/// Gets or sets the ID.
/// </summary>
[JsonProperty("id")]
public long Id { get; set; }
/// <summary>
/// Gets or sets the withhelds in countries.
/// </summary>
[JsonProperty("withheld_in_countries")]
public string[] WithheldInCountries { get; set; }
/// <summary>
/// Gets the type of the message.
/// </summary>
/// <returns>The type of the message.</returns>
protected override MessageType GetMessageType()
{
return MessageType.UserWithheld;
}
}
/// <summary>
/// Represents a withheld message.
/// </summary>
public class StatusWithheldMessage : TimestampMessage
{
/// <summary>
/// Gets or sets the ID.
/// </summary>
[JsonProperty("id")]
public long Id { get; set; }
/// <summary>
/// Gets or sets the ID of the user.
/// </summary>
[JsonProperty("user_id")]
public long UserId { get; set; }
/// <summary>
/// Gets or sets the withhelds in countries.
/// </summary>
[JsonProperty("withheld_in_countries")]
public string[] WithheldInCountries { get; set; }
/// <summary>
/// Gets the type of the message.
/// </summary>
/// <returns>The type of the message.</returns>
protected override MessageType GetMessageType()
{
return MessageType.StatusWithheld;
}
}
/// <summary>
/// Represents a message contains the ID of an user.
/// </summary>
public class UserMessage : TimestampMessage
{
/// <summary>
/// Gets or sets the ID of the user.
/// </summary>
[JsonProperty("id")]
public long Id { get; set; }
internal MessageType messageType { get; set; }
/// <summary>
/// Gets the type of the message.
/// </summary>
/// <returns>The type of the message.</returns>
protected override MessageType GetMessageType()
{
return messageType;
}
}
/// <summary>
/// Represents the message published when Twitter disconnects the stream.
/// </summary>
public class DisconnectMessage : StreamingMessage
{
/// <summary>
/// Gets or sets the disconnect code.
/// </summary>
[JsonProperty("code")]
public DisconnectCode Code { get; set; }
/// <summary>
/// Gets or sets the stream name of current stream.
/// </summary>
[JsonProperty("stream_name")]
public string StreamName { get; set; }
/// <summary>
/// Gets or sets the human readable message of the reason.
/// </summary>
[JsonProperty("reason")]
public string Reason { get; set; }
/// <summary>
/// Gets the type of the message.
/// </summary>
/// <returns>The type of the message.</returns>
protected override MessageType GetMessageType()
{
return MessageType.Disconnect;
}
}
/// <summary>
/// Represents a warning message.
/// </summary>
public class WarningMessage : TimestampMessage
{
/// <summary>
/// Gets or sets the warning code.
/// </summary>
[JsonProperty("code")]
public string Code { get; set; }
/// <summary>
/// Gets or sets the warning message.
/// </summary>
[JsonProperty("message")]
public string Message { get; set; }
/// <summary>
/// Gets or sets the percentage of the stall messages
/// </summary>
[JsonProperty("percent_full")]
public int? PercentFull { get; set; }
/// <summary>
/// Gets or sets the target user ID.
/// </summary>
[JsonProperty("user_id")]
public long? UserId { get; set; }
/// <summary>
/// Gets the type of the message.
/// </summary>
/// <returns>The type of the message.</returns>
protected override MessageType GetMessageType()
{
return MessageType.Warning;
}
}
/// <summary>
/// Provides the event target type.
/// </summary>
public enum EventTargetType
{
/// <summary>
/// The event is about a List.
/// </summary>
List,
/// <summary>
/// The event is about a Tweet.
/// </summary>
Status,
/// <summary>
/// The event is that the user revoked his access token.
/// </summary>
AccessRevocation,
/// <summary>
/// The event is unknown.
/// </summary>
Null
}
/// <summary>
/// Represents a revoked token.
/// </summary>
public class AccessRevocation
{
/// <summary>
/// The client application.
/// </summary>
[JsonProperty("client_application")]
public ClientApplication ClientApplication { get; set; }
/// <summary>
/// The revoked access token.
/// </summary>
[JsonProperty("token")]
public string Token { get; set; }
}
/// <summary>
/// Represents a client application.
/// </summary>
public class ClientApplication
{
/// <summary>
/// Gets or sets the URL of the application's publicly accessible home page.
/// </summary>
[JsonProperty("url")]
public string Url { get; set; }
/// <summary>
/// Gets or sets the ID.
/// </summary>
[JsonProperty("id")]
public long Id { get; set; } // int is better?
/// <summary>
/// Gets or sets the consumer key.
/// </summary>
[JsonProperty("consumer_key")]
public string ConsumerKey { get; set; }
/// <summary>
/// Gets or sets the application name.
/// </summary>
[JsonProperty("name")]
public string Name { get; set; }
}
/// <summary>
/// Represents an event message.
/// </summary>
public class EventMessage : StreamingMessage
{
/// <summary>
/// Gets or sets the target user.
/// </summary>
public User Target { get; set; }
/// <summary>
/// Gets or sets the source.
/// </summary>
public User Source { get; set; }
/// <summary>
/// Gets or sets the event code.
/// </summary>
public EventCode Event { get; set; }
/// <summary>
/// Gets or sets the type of target.
/// </summary>
public EventTargetType TargetType { get; set; }
/// <summary>
/// Gets or sets the target status.
/// </summary>
public Status TargetStatus { get; set; }
/// <summary>
/// Gets or sets the target List.
/// </summary>
public List TargetList { get; set; }
/// <summary>
/// Gets or sets the target access token.
/// </summary>
public AccessRevocation TargetToken { get; set; }
/// <summary>
/// Gets or sets the time when the event happened.
/// </summary>
public DateTimeOffset CreatedAt { get; set; }
/// <summary>
/// Gets the type of the message.
/// </summary>
/// <returns>The type of the message.</returns>
protected override MessageType GetMessageType()
{
return MessageType.Event;
}
internal static EventMessage Parse(JObject j)
{
var e = new EventMessage();
e.Target = j["target"].ToObject<User>();
e.Source = j["source"].ToObject<User>();
e.Event = (EventCode)Enum.Parse(typeof(EventCode),
((string)j["event"])
.Replace("objectType", "")
.Replace("_",""),
true);
e.CreatedAt = DateTimeOffset.ParseExact((string)j["created_at"], "ddd MMM dd HH:mm:ss K yyyy",
System.Globalization.DateTimeFormatInfo.InvariantInfo,
System.Globalization.DateTimeStyles.AllowWhiteSpaces);
var eventstr = (string)j["event"];
e.TargetType = eventstr.Contains("list")
? EventTargetType.List
: (eventstr.Contains("favorite") || eventstr.Contains("tweet"))
? EventTargetType.Status
: e.Event == EventCode.AccessRevoked
? EventTargetType.AccessRevocation
: EventTargetType.Null;
switch(e.TargetType)
{
case EventTargetType.Status:
e.TargetStatus = j["target_object"].ToObject<Status>();
break;
case EventTargetType.List:
e.TargetList = j["target_object"].ToObject<List>();
break;
case EventTargetType.AccessRevocation:
e.TargetToken = j["target_object"].ToObject<AccessRevocation>();
break;
}
return e;
}
}
/// <summary>
/// Provides an envelopes message.
/// </summary>
public class EnvelopesMessage : StreamingMessage
{
/// <summary>
/// Gets or sets the ID of the user.
/// </summary>
public long ForUser { get; set; }
/// <summary>
/// Gets or sets the message.
/// </summary>
public StreamingMessage Message { get; set; }
/// <summary>
/// Gets the type of the message.
/// </summary>
/// <returns>The type of the message.</returns>
protected override MessageType GetMessageType()
{
return MessageType.Envelopes;
}
internal static EnvelopesMessage Parse(JObject j)
{
return new EnvelopesMessage()
{
ForUser = (long)j["for_user"],
Message = StreamingMessage.Parse(j["message"].ToString(Formatting.None))
};
}
}
/// <summary>
/// Represents a control message.
/// </summary>
public class ControlMessage : StreamingMessage
{
/// <summary>
/// Gets or sets the URI.
/// </summary>
[JsonProperty("control_uri")]
public string ControlUri { get; set; }
/// <summary>
/// Gets the type of the message.
/// </summary>
/// <returns>The type of the message.</returns>
protected override MessageType GetMessageType()
{
return MessageType.Control;
}
}
/// <summary>
/// Represents a raw JSON message. This message means an exception was thrown when parsing.
/// </summary>
public class RawJsonMessage : StreamingMessage
{
/// <summary>
/// Gets the exception when parsing.
/// </summary>
public ParsingException Exception { get; private set; }
internal static RawJsonMessage Create(string json, ParsingException exception)
{
return new RawJsonMessage
{
Json = json,
Exception = exception
};
}
/// <summary>
/// Gets the type of the message.
/// </summary>
/// <returns>The type of the message.</returns>
protected override MessageType GetMessageType()
{
return MessageType.RawJson;
}
}
}
| |
// 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.
// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
//
// ConcurrentStack.cs
//
// A lock-free, concurrent stack primitive, and its associated debugger view type.
//
// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading;
namespace System.Collections.Concurrent
{
// A stack that uses CAS operations internally to maintain thread-safety in a lock-free
// manner. Attempting to push or pop concurrently from the stack will not trigger waiting,
// although some optimistic concurrency and retry is used, possibly leading to lack of
// fairness and/or livelock. The stack uses spinning and backoff to add some randomization,
// in hopes of statistically decreasing the possibility of livelock.
//
// Note that we currently allocate a new node on every push. This avoids having to worry
// about potential ABA issues, since the CLR GC ensures that a memory address cannot be
// reused before all references to it have died.
/// <summary>
/// Represents a thread-safe last-in, first-out collection of objects.
/// </summary>
/// <typeparam name="T">Specifies the type of elements in the stack.</typeparam>
/// <remarks>
/// All public and protected members of <see cref="ConcurrentStack{T}"/> are thread-safe and may be used
/// concurrently from multiple threads.
/// </remarks>
[DebuggerDisplay("Count = {Count}")]
[DebuggerTypeProxy(typeof(IProducerConsumerCollectionDebugView<>))]
public class ConcurrentStack<T> : IProducerConsumerCollection<T>, IReadOnlyCollection<T>
{
/// <summary>
/// A simple (internal) node type used to store elements of concurrent stacks and queues.
/// </summary>
private class Node
{
internal readonly T _value; // Value of the node.
internal Node _next; // Next pointer.
/// <summary>
/// Constructs a new node with the specified value and no next node.
/// </summary>
/// <param name="value">The value of the node.</param>
internal Node(T value)
{
_value = value;
_next = null;
}
}
private volatile Node _head; // The stack is a singly linked list, and only remembers the head.
private const int BACKOFF_MAX_YIELDS = 8; // Arbitrary number to cap backoff.
/// <summary>
/// Initializes a new instance of the <see cref="ConcurrentStack{T}"/>
/// class.
/// </summary>
public ConcurrentStack()
{
}
/// <summary>
/// Initializes a new instance of the <see cref="ConcurrentStack{T}"/>
/// class that contains elements copied from the specified collection
/// </summary>
/// <param name="collection">The collection whose elements are copied to the new <see
/// cref="ConcurrentStack{T}"/>.</param>
/// <exception cref="T:System.ArgumentNullException">The <paramref name="collection"/> argument is
/// null.</exception>
public ConcurrentStack(IEnumerable<T> collection)
{
if (collection == null)
{
throw new ArgumentNullException(nameof(collection));
}
InitializeFromCollection(collection);
}
/// <summary>
/// Initializes the contents of the stack from an existing collection.
/// </summary>
/// <param name="collection">A collection from which to copy elements.</param>
private void InitializeFromCollection(IEnumerable<T> collection)
{
// We just copy the contents of the collection to our stack.
Node lastNode = null;
foreach (T element in collection)
{
Node newNode = new Node(element);
newNode._next = lastNode;
lastNode = newNode;
}
_head = lastNode;
}
/// <summary>
/// Gets a value that indicates whether the <see cref="ConcurrentStack{T}"/> is empty.
/// </summary>
/// <value>true if the <see cref="ConcurrentStack{T}"/> is empty; otherwise, false.</value>
/// <remarks>
/// For determining whether the collection contains any items, use of this property is recommended
/// rather than retrieving the number of items from the <see cref="Count"/> property and comparing it
/// to 0. However, as this collection is intended to be accessed concurrently, it may be the case
/// that another thread will modify the collection after <see cref="IsEmpty"/> returns, thus invalidating
/// the result.
/// </remarks>
public bool IsEmpty
{
// Checks whether the stack is empty. Clearly the answer may be out of date even prior to
// the function returning (i.e. if another thread concurrently adds to the stack). It does
// guarantee, however, that, if another thread does not mutate the stack, a subsequent call
// to TryPop will return true -- i.e. it will also read the stack as non-empty.
get { return _head == null; }
}
/// <summary>
/// Gets the number of elements contained in the <see cref="ConcurrentStack{T}"/>.
/// </summary>
/// <value>The number of elements contained in the <see cref="ConcurrentStack{T}"/>.</value>
/// <remarks>
/// For determining whether the collection contains any items, use of the <see cref="IsEmpty"/>
/// property is recommended rather than retrieving the number of items from the <see cref="Count"/>
/// property and comparing it to 0.
/// </remarks>
public int Count
{
// Counts the number of entries in the stack. This is an O(n) operation. The answer may be out
// of date before returning, but guarantees to return a count that was once valid. Conceptually,
// the implementation snaps a copy of the list and then counts the entries, though physically
// this is not what actually happens.
get
{
int count = 0;
// Just whip through the list and tally up the number of nodes. We rely on the fact that
// node next pointers are immutable after being enqueued for the first time, even as
// they are being dequeued. If we ever changed this (e.g. to pool nodes somehow),
// we'd need to revisit this implementation.
for (Node curr = _head; curr != null; curr = curr._next)
{
count++; //we don't handle overflow, to be consistent with existing generic collection types in CLR
}
return count;
}
}
/// <summary>
/// Gets a value indicating whether access to the <see cref="T:System.Collections.ICollection"/> is
/// synchronized with the SyncRoot.
/// </summary>
/// <value>true if access to the <see cref="T:System.Collections.ICollection"/> is synchronized
/// with the SyncRoot; otherwise, false. For <see cref="ConcurrentStack{T}"/>, this property always
/// returns false.</value>
bool ICollection.IsSynchronized
{
// Gets a value indicating whether access to this collection is synchronized. Always returns
// false. The reason is subtle. While access is in face thread safe, it's not the case that
// locking on the SyncRoot would have prevented concurrent pushes and pops, as this property
// would typically indicate; that's because we internally use CAS operations vs. true locks.
get { return false; }
}
/// <summary>
/// Gets an object that can be used to synchronize access to the <see
/// cref="T:System.Collections.ICollection"/>. This property is not supported.
/// </summary>
/// <exception cref="T:System.NotSupportedException">The SyncRoot property is not supported</exception>
object ICollection.SyncRoot
{
get
{
throw new NotSupportedException(SR.ConcurrentCollection_SyncRoot_NotSupported);
}
}
/// <summary>
/// Removes all objects from the <see cref="ConcurrentStack{T}"/>.
/// </summary>
public void Clear()
{
// Clear the list by setting the head to null. We don't need to use an atomic
// operation for this: anybody who is mutating the head by pushing or popping
// will need to use an atomic operation to guarantee they serialize and don't
// overwrite our setting of the head to null.
_head = null;
}
/// <summary>
/// Copies the elements of the <see cref="T:System.Collections.ICollection"/> to an <see
/// cref="T:System.Array"/>, starting at a particular
/// <see cref="T:System.Array"/> index.
/// </summary>
/// <param name="array">The one-dimensional <see cref="T:System.Array"/> that is the destination of
/// the elements copied from the
/// <see cref="ConcurrentStack{T}"/>. The <see cref="T:System.Array"/> must
/// have zero-based indexing.</param>
/// <param name="index">The zero-based index in <paramref name="array"/> at which copying
/// begins.</param>
/// <exception cref="ArgumentNullException"><paramref name="array"/> is a null reference (Nothing in
/// Visual Basic).</exception>
/// <exception cref="ArgumentOutOfRangeException"><paramref name="index"/> is less than
/// zero.</exception>
/// <exception cref="ArgumentException">
/// <paramref name="array"/> is multidimensional. -or-
/// <paramref name="array"/> does not have zero-based indexing. -or-
/// <paramref name="index"/> is equal to or greater than the length of the <paramref name="array"/>
/// -or- The number of elements in the source <see cref="T:System.Collections.ICollection"/> is
/// greater than the available space from <paramref name="index"/> to the end of the destination
/// <paramref name="array"/>. -or- The type of the source <see
/// cref="T:System.Collections.ICollection"/> cannot be cast automatically to the type of the
/// destination <paramref name="array"/>.
/// </exception>
void ICollection.CopyTo(Array array, int index)
{
// Validate arguments.
if (array == null)
{
throw new ArgumentNullException(nameof(array));
}
// We must be careful not to corrupt the array, so we will first accumulate an
// internal list of elements that we will then copy to the array. This requires
// some extra allocation, but is necessary since we don't know up front whether
// the array is sufficiently large to hold the stack's contents.
((ICollection)ToList()).CopyTo(array, index);
}
/// <summary>
/// Copies the <see cref="ConcurrentStack{T}"/> elements to an existing one-dimensional <see
/// cref="T:System.Array"/>, starting at the specified array index.
/// </summary>
/// <param name="array">The one-dimensional <see cref="T:System.Array"/> that is the destination of
/// the elements copied from the
/// <see cref="ConcurrentStack{T}"/>. The <see cref="T:System.Array"/> must have zero-based
/// indexing.</param>
/// <param name="index">The zero-based index in <paramref name="array"/> at which copying
/// begins.</param>
/// <exception cref="ArgumentNullException"><paramref name="array"/> is a null reference (Nothing in
/// Visual Basic).</exception>
/// <exception cref="ArgumentOutOfRangeException"><paramref name="index"/> is less than
/// zero.</exception>
/// <exception cref="ArgumentException"><paramref name="index"/> is equal to or greater than the
/// length of the <paramref name="array"/>
/// -or- The number of elements in the source <see cref="ConcurrentStack{T}"/> is greater than the
/// available space from <paramref name="index"/> to the end of the destination <paramref
/// name="array"/>.
/// </exception>
public void CopyTo(T[] array, int index)
{
if (array == null)
{
throw new ArgumentNullException(nameof(array));
}
// We must be careful not to corrupt the array, so we will first accumulate an
// internal list of elements that we will then copy to the array. This requires
// some extra allocation, but is necessary since we don't know up front whether
// the array is sufficiently large to hold the stack's contents.
ToList().CopyTo(array, index);
}
#pragma warning disable 0420 // No warning for Interlocked.xxx if compiled with new managed compiler (Roslyn)
/// <summary>
/// Inserts an object at the top of the <see cref="ConcurrentStack{T}"/>.
/// </summary>
/// <param name="item">The object to push onto the <see cref="ConcurrentStack{T}"/>. The value can be
/// a null reference (Nothing in Visual Basic) for reference types.
/// </param>
public void Push(T item)
{
// Pushes a node onto the front of the stack thread-safely. Internally, this simply
// swaps the current head pointer using a (thread safe) CAS operation to accomplish
// lock freedom. If the CAS fails, we add some back off to statistically decrease
// contention at the head, and then go back around and retry.
Node newNode = new Node(item);
newNode._next = _head;
if (Interlocked.CompareExchange(ref _head, newNode, newNode._next) == newNode._next)
{
return;
}
// If we failed, go to the slow path and loop around until we succeed.
PushCore(newNode, newNode);
}
/// <summary>
/// Inserts multiple objects at the top of the <see cref="ConcurrentStack{T}"/> atomically.
/// </summary>
/// <param name="items">The objects to push onto the <see cref="ConcurrentStack{T}"/>.</param>
/// <exception cref="ArgumentNullException"><paramref name="items"/> is a null reference
/// (Nothing in Visual Basic).</exception>
/// <remarks>
/// When adding multiple items to the stack, using PushRange is a more efficient
/// mechanism than using <see cref="Push"/> one item at a time. Additionally, PushRange
/// guarantees that all of the elements will be added atomically, meaning that no other threads will
/// be able to inject elements between the elements being pushed. Items at lower indices in
/// the <paramref name="items"/> array will be pushed before items at higher indices.
/// </remarks>
public void PushRange(T[] items)
{
if (items == null)
{
throw new ArgumentNullException(nameof(items));
}
PushRange(items, 0, items.Length);
}
/// <summary>
/// Inserts multiple objects at the top of the <see cref="ConcurrentStack{T}"/> atomically.
/// </summary>
/// <param name="items">The objects to push onto the <see cref="ConcurrentStack{T}"/>.</param>
/// <param name="startIndex">The zero-based offset in <paramref name="items"/> at which to begin
/// inserting elements onto the top of the <see cref="ConcurrentStack{T}"/>.</param>
/// <param name="count">The number of elements to be inserted onto the top of the <see
/// cref="ConcurrentStack{T}"/>.</param>
/// <exception cref="ArgumentNullException"><paramref name="items"/> is a null reference
/// (Nothing in Visual Basic).</exception>
/// <exception cref="ArgumentOutOfRangeException"><paramref name="startIndex"/> or <paramref
/// name="count"/> is negative. Or <paramref name="startIndex"/> is greater than or equal to the length
/// of <paramref name="items"/>.</exception>
/// <exception cref="ArgumentException"><paramref name="startIndex"/> + <paramref name="count"/> is
/// greater than the length of <paramref name="items"/>.</exception>
/// <remarks>
/// When adding multiple items to the stack, using PushRange is a more efficient
/// mechanism than using <see cref="Push"/> one item at a time. Additionally, PushRange
/// guarantees that all of the elements will be added atomically, meaning that no other threads will
/// be able to inject elements between the elements being pushed. Items at lower indices in the
/// <paramref name="items"/> array will be pushed before items at higher indices.
/// </remarks>
public void PushRange(T[] items, int startIndex, int count)
{
ValidatePushPopRangeInput(items, startIndex, count);
// No op if the count is zero
if (count == 0)
return;
Node head, tail;
head = tail = new Node(items[startIndex]);
for (int i = startIndex + 1; i < startIndex + count; i++)
{
Node node = new Node(items[i]);
node._next = head;
head = node;
}
tail._next = _head;
if (Interlocked.CompareExchange(ref _head, head, tail._next) == tail._next)
{
return;
}
// If we failed, go to the slow path and loop around until we succeed.
PushCore(head, tail);
}
/// <summary>
/// Push one or many nodes into the stack, if head and tails are equal then push one node to the stack other wise push the list between head
/// and tail to the stack
/// </summary>
/// <param name="head">The head pointer to the new list</param>
/// <param name="tail">The tail pointer to the new list</param>
private void PushCore(Node head, Node tail)
{
SpinWait spin = new SpinWait();
// Keep trying to CAS the existing head with the new node until we succeed.
do
{
spin.SpinOnce();
// Reread the head and link our new node.
tail._next = _head;
}
while (Interlocked.CompareExchange(
ref _head, head, tail._next) != tail._next);
#if FEATURE_TRACING
if (CDSCollectionETWBCLProvider.Log.IsEnabled())
{
CDSCollectionETWBCLProvider.Log.ConcurrentStack_FastPushFailed(spin.Count);
}
#endif
}
/// <summary>
/// Local helper function to validate the Pop Push range methods input
/// </summary>
private static void ValidatePushPopRangeInput(T[] items, int startIndex, int count)
{
if (items == null)
{
throw new ArgumentNullException(nameof(items));
}
if (count < 0)
{
throw new ArgumentOutOfRangeException(nameof(count), SR.ConcurrentStack_PushPopRange_CountOutOfRange);
}
int length = items.Length;
if (startIndex >= length || startIndex < 0)
{
throw new ArgumentOutOfRangeException(nameof(startIndex), SR.ConcurrentStack_PushPopRange_StartOutOfRange);
}
if (length - count < startIndex) //instead of (startIndex + count > items.Length) to prevent overflow
{
throw new ArgumentException(SR.ConcurrentStack_PushPopRange_InvalidCount);
}
}
/// <summary>
/// Attempts to add an object to the <see
/// cref="T:System.Collections.Concurrent.IProducerConsumerCollection{T}"/>.
/// </summary>
/// <param name="item">The object to add to the <see
/// cref="T:System.Collections.Concurrent.IProducerConsumerCollection{T}"/>. The value can be a null
/// reference (Nothing in Visual Basic) for reference types.
/// </param>
/// <returns>true if the object was added successfully; otherwise, false.</returns>
/// <remarks>For <see cref="ConcurrentStack{T}"/>, this operation
/// will always insert the object onto the top of the <see cref="ConcurrentStack{T}"/>
/// and return true.</remarks>
bool IProducerConsumerCollection<T>.TryAdd(T item)
{
Push(item);
return true;
}
/// <summary>
/// Attempts to return an object from the top of the <see cref="ConcurrentStack{T}"/>
/// without removing it.
/// </summary>
/// <param name="result">When this method returns, <paramref name="result"/> contains an object from
/// the top of the <see cref="T:System.Collections.Concurrent.ConcurrentStack{T}"/> or an
/// unspecified value if the operation failed.</param>
/// <returns>true if and object was returned successfully; otherwise, false.</returns>
public bool TryPeek(out T result)
{
Node head = _head;
// If the stack is empty, return false; else return the element and true.
if (head == null)
{
result = default(T);
return false;
}
else
{
result = head._value;
return true;
}
}
/// <summary>
/// Attempts to pop and return the object at the top of the <see cref="ConcurrentStack{T}"/>.
/// </summary>
/// <param name="result">
/// When this method returns, if the operation was successful, <paramref name="result"/> contains the
/// object removed. If no object was available to be removed, the value is unspecified.
/// </param>
/// <returns>true if an element was removed and returned from the top of the <see
/// cref="ConcurrentStack{T}"/>
/// successfully; otherwise, false.</returns>
public bool TryPop(out T result)
{
Node head = _head;
//stack is empty
if (head == null)
{
result = default(T);
return false;
}
if (Interlocked.CompareExchange(ref _head, head._next, head) == head)
{
result = head._value;
return true;
}
// Fall through to the slow path.
return TryPopCore(out result);
}
/// <summary>
/// Attempts to pop and return multiple objects from the top of the <see cref="ConcurrentStack{T}"/>
/// atomically.
/// </summary>
/// <param name="items">
/// The <see cref="T:System.Array"/> to which objects popped from the top of the <see
/// cref="ConcurrentStack{T}"/> will be added.
/// </param>
/// <returns>The number of objects successfully popped from the top of the <see
/// cref="ConcurrentStack{T}"/> and inserted in
/// <paramref name="items"/>.</returns>
/// <exception cref="ArgumentNullException"><paramref name="items"/> is a null argument (Nothing
/// in Visual Basic).</exception>
/// <remarks>
/// When popping multiple items, if there is little contention on the stack, using
/// TryPopRange can be more efficient than using <see cref="TryPop"/>
/// once per item to be removed. Nodes fill the <paramref name="items"/>
/// with the first node to be popped at the startIndex, the second node to be popped
/// at startIndex + 1, and so on.
/// </remarks>
public int TryPopRange(T[] items)
{
if (items == null)
{
throw new ArgumentNullException(nameof(items));
}
return TryPopRange(items, 0, items.Length);
}
/// <summary>
/// Attempts to pop and return multiple objects from the top of the <see cref="ConcurrentStack{T}"/>
/// atomically.
/// </summary>
/// <param name="items">
/// The <see cref="T:System.Array"/> to which objects popped from the top of the <see
/// cref="ConcurrentStack{T}"/> will be added.
/// </param>
/// <param name="startIndex">The zero-based offset in <paramref name="items"/> at which to begin
/// inserting elements from the top of the <see cref="ConcurrentStack{T}"/>.</param>
/// <param name="count">The number of elements to be popped from top of the <see
/// cref="ConcurrentStack{T}"/> and inserted into <paramref name="items"/>.</param>
/// <returns>The number of objects successfully popped from the top of
/// the <see cref="ConcurrentStack{T}"/> and inserted in <paramref name="items"/>.</returns>
/// <exception cref="ArgumentNullException"><paramref name="items"/> is a null reference
/// (Nothing in Visual Basic).</exception>
/// <exception cref="ArgumentOutOfRangeException"><paramref name="startIndex"/> or <paramref
/// name="count"/> is negative. Or <paramref name="startIndex"/> is greater than or equal to the length
/// of <paramref name="items"/>.</exception>
/// <exception cref="ArgumentException"><paramref name="startIndex"/> + <paramref name="count"/> is
/// greater than the length of <paramref name="items"/>.</exception>
/// <remarks>
/// When popping multiple items, if there is little contention on the stack, using
/// TryPopRange can be more efficient than using <see cref="TryPop"/>
/// once per item to be removed. Nodes fill the <paramref name="items"/>
/// with the first node to be popped at the startIndex, the second node to be popped
/// at startIndex + 1, and so on.
/// </remarks>
public int TryPopRange(T[] items, int startIndex, int count)
{
ValidatePushPopRangeInput(items, startIndex, count);
// No op if the count is zero
if (count == 0)
return 0;
Node poppedHead;
int nodesCount = TryPopCore(count, out poppedHead);
if (nodesCount > 0)
{
CopyRemovedItems(poppedHead, items, startIndex, nodesCount);
}
return nodesCount;
}
/// <summary>
/// Local helper function to Pop an item from the stack, slow path
/// </summary>
/// <param name="result">The popped item</param>
/// <returns>True if succeeded, false otherwise</returns>
private bool TryPopCore(out T result)
{
Node poppedNode;
if (TryPopCore(1, out poppedNode) == 1)
{
result = poppedNode._value;
return true;
}
result = default(T);
return false;
}
/// <summary>
/// Slow path helper for TryPop. This method assumes an initial attempt to pop an element
/// has already occurred and failed, so it begins spinning right away.
/// </summary>
/// <param name="count">The number of items to pop.</param>
/// <param name="poppedHead">
/// When this method returns, if the pop succeeded, contains the removed object. If no object was
/// available to be removed, the value is unspecified. This parameter is passed uninitialized.
/// </param>
/// <returns>The number of objects successfully popped from the top of
/// the <see cref="ConcurrentStack{T}"/>.</returns>
private int TryPopCore(int count, out Node poppedHead)
{
SpinWait spin = new SpinWait();
// Try to CAS the head with its current next. We stop when we succeed or
// when we notice that the stack is empty, whichever comes first.
Node head;
Node next;
int backoff = 1;
Random r = new Random(Environment.TickCount & Int32.MaxValue); // avoid the case where TickCount could return Int32.MinValue
while (true)
{
head = _head;
// Is the stack empty?
if (head == null)
{
#if FEATURE_TRACING
if (count == 1 && CDSCollectionETWBCLProvider.Log.IsEnabled())
{
CDSCollectionETWBCLProvider.Log.ConcurrentStack_FastPopFailed(spin.Count);
}
#endif
poppedHead = null;
return 0;
}
next = head;
int nodesCount = 1;
for (; nodesCount < count && next._next != null; nodesCount++)
{
next = next._next;
}
// Try to swap the new head. If we succeed, break out of the loop.
if (Interlocked.CompareExchange(ref _head, next._next, head) == head)
{
#if FEATURE_TRACING
if (count == 1 && CDSCollectionETWBCLProvider.Log.IsEnabled())
{
CDSCollectionETWBCLProvider.Log.ConcurrentStack_FastPopFailed(spin.Count);
}
#endif
// Return the popped Node.
poppedHead = head;
return nodesCount;
}
// We failed to CAS the new head. Spin briefly and retry.
for (int i = 0; i < backoff; i++)
{
spin.SpinOnce();
}
backoff = spin.NextSpinWillYield ? r.Next(1, BACKOFF_MAX_YIELDS) : backoff * 2;
}
}
#pragma warning restore 0420
/// <summary>
/// Local helper function to copy the poped elements into a given collection
/// </summary>
/// <param name="head">The head of the list to be copied</param>
/// <param name="collection">The collection to place the popped items in</param>
/// <param name="startIndex">the beginning of index of where to place the popped items</param>
/// <param name="nodesCount">The number of nodes.</param>
private static void CopyRemovedItems(Node head, T[] collection, int startIndex, int nodesCount)
{
Node current = head;
for (int i = startIndex; i < startIndex + nodesCount; i++)
{
collection[i] = current._value;
current = current._next;
}
}
/// <summary>
/// Attempts to remove and return an object from the <see
/// cref="T:System.Collections.Concurrent.IProducerConsumerCollection{T}"/>.
/// </summary>
/// <param name="item">
/// When this method returns, if the operation was successful, <paramref name="item"/> contains the
/// object removed. If no object was available to be removed, the value is unspecified.
/// </param>
/// <returns>true if an element was removed and returned successfully; otherwise, false.</returns>
/// <remarks>For <see cref="ConcurrentStack{T}"/>, this operation will attempt to pope the object at
/// the top of the <see cref="ConcurrentStack{T}"/>.
/// </remarks>
bool IProducerConsumerCollection<T>.TryTake(out T item)
{
return TryPop(out item);
}
/// <summary>
/// Copies the items stored in the <see cref="ConcurrentStack{T}"/> to a new array.
/// </summary>
/// <returns>A new array containing a snapshot of elements copied from the <see
/// cref="ConcurrentStack{T}"/>.</returns>
public T[] ToArray()
{
Node curr = _head;
return curr == null ?
Array.Empty<T>() :
ToList(curr).ToArray();
}
/// <summary>
/// Returns an array containing a snapshot of the list's contents, using
/// the target list node as the head of a region in the list.
/// </summary>
/// <returns>A list of the stack's contents.</returns>
private List<T> ToList()
{
return ToList(_head);
}
/// <summary>
/// Returns an array containing a snapshot of the list's contents starting at the specified node.
/// </summary>
/// <returns>A list of the stack's contents starting at the specified node.</returns>
private List<T> ToList(Node curr)
{
List<T> list = new List<T>();
while (curr != null)
{
list.Add(curr._value);
curr = curr._next;
}
return list;
}
/// <summary>
/// Returns an enumerator that iterates through the <see cref="ConcurrentStack{T}"/>.
/// </summary>
/// <returns>An enumerator for the <see cref="ConcurrentStack{T}"/>.</returns>
/// <remarks>
/// The enumeration represents a moment-in-time snapshot of the contents
/// of the stack. It does not reflect any updates to the collection after
/// <see cref="GetEnumerator"/> was called. The enumerator is safe to use
/// concurrently with reads from and writes to the stack.
/// </remarks>
public IEnumerator<T> GetEnumerator()
{
// Returns an enumerator for the stack. This effectively takes a snapshot
// of the stack's contents at the time of the call, i.e. subsequent modifications
// (pushes or pops) will not be reflected in the enumerator's contents.
//If we put yield-return here, the iterator will be lazily evaluated. As a result a snapshot of
//the stack is not taken when GetEnumerator is initialized but when MoveNext() is first called.
//This is inconsistent with existing generic collections. In order to prevent it, we capture the
//value of _head in a buffer and call out to a helper method
return GetEnumerator(_head);
}
private IEnumerator<T> GetEnumerator(Node head)
{
Node current = head;
while (current != null)
{
yield return current._value;
current = current._next;
}
}
/// <summary>
/// Returns an enumerator that iterates through a collection.
/// </summary>
/// <returns>An <see cref="T:System.Collections.IEnumerator"/> that can be used to iterate through
/// the collection.</returns>
/// <remarks>
/// The enumeration represents a moment-in-time snapshot of the contents of the stack. It does not
/// reflect any updates to the collection after
/// <see cref="GetEnumerator"/> was called. The enumerator is safe to use concurrently with reads
/// from and writes to the stack.
/// </remarks>
IEnumerator IEnumerable.GetEnumerator()
{
return ((IEnumerable<T>)this).GetEnumerator();
}
}
}
| |
#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: SampleHistoryTestingParallel.SampleHistoryTestingParallelPublic
File: MainWindow.xaml.cs
Created: 2015, 11, 11, 2:32 PM
Copyright 2010 by StockSharp, LLC
*******************************************************************************************/
#endregion S# License
namespace SampleHistoryTestingParallel
{
using System;
using System.IO;
using System.Linq;
using System.Windows;
using System.Windows.Media;
using Ecng.Xaml;
using Ecng.Common;
using StockSharp.Algo;
using StockSharp.Algo.Candles;
using StockSharp.Algo.Storages;
using StockSharp.Algo.Strategies;
using StockSharp.Algo.Strategies.Testing;
using StockSharp.Algo.Testing;
using StockSharp.Algo.Indicators;
using StockSharp.BusinessEntities;
using StockSharp.Logging;
using StockSharp.Messages;
using StockSharp.Xaml.Charting;
using StockSharp.Localization;
public partial class MainWindow
{
private DateTime _startEmulationTime;
public MainWindow()
{
InitializeComponent();
HistoryPath.Folder = @"..\..\..\HistoryData\".ToFullPath();
}
private void StartBtnClick(object sender, RoutedEventArgs e)
{
if (HistoryPath.Folder.IsEmpty() || !Directory.Exists(HistoryPath.Folder))
{
MessageBox.Show(this, LocalizedStrings.Str3014);
return;
}
if (Math.Abs(TestingProcess.Value - 0) > double.Epsilon)
{
MessageBox.Show(this, LocalizedStrings.Str3015);
return;
}
var logManager = new LogManager();
var fileLogListener = new FileLogListener("sample.log");
logManager.Listeners.Add(fileLogListener);
// SMA periods
var periods = new[]
{
new Tuple<int, int, Color>(80, 10, Colors.DarkGreen),
new Tuple<int, int, Color>(70, 8, Colors.Red),
new Tuple<int, int, Color>(60, 6, Colors.DarkBlue)
};
// storage to historical data
var storageRegistry = new StorageRegistry
{
// set historical path
DefaultDrive = new LocalMarketDataDrive(HistoryPath.Folder)
};
var timeFrame = TimeSpan.FromMinutes(5);
// create test security
var security = new Security
{
Id = "RIZ2@FORTS", // sec id has the same name as folder with historical data
Code = "RIZ2",
Name = "RTS-12.12",
Board = ExchangeBoard.Forts,
};
var startTime = new DateTime(2012, 10, 1);
var stopTime = new DateTime(2012, 10, 31);
var level1Info = new Level1ChangeMessage
{
SecurityId = security.ToSecurityId(),
ServerTime = startTime,
}
.TryAdd(Level1Fields.PriceStep, 10m)
.TryAdd(Level1Fields.StepPrice, 6m)
.TryAdd(Level1Fields.MinPrice, 10m)
.TryAdd(Level1Fields.MaxPrice, 1000000m)
.TryAdd(Level1Fields.MarginBuy, 10000m)
.TryAdd(Level1Fields.MarginSell, 10000m);
// test portfolio
var portfolio = new Portfolio
{
Name = "test account",
BeginValue = 1000000,
};
// create backtesting connector
var batchEmulation = new BatchEmulation(new[] { security }, new[] { portfolio }, storageRegistry)
{
EmulationSettings =
{
MarketTimeChangedInterval = timeFrame,
StartTime = startTime,
StopTime = stopTime,
// count of parallel testing strategies
BatchSize = periods.Length,
}
};
// handle historical time for update ProgressBar
batchEmulation.ProgressChanged += (curr, total) => this.GuiAsync(() => TestingProcess.Value = total);
batchEmulation.StateChanged += (oldState, newState) =>
{
if (batchEmulation.State != EmulationStates.Stopped)
return;
this.GuiAsync(() =>
{
if (batchEmulation.IsFinished)
{
TestingProcess.Value = TestingProcess.Maximum;
MessageBox.Show(this, LocalizedStrings.Str3024.Put(DateTime.Now - _startEmulationTime));
}
else
MessageBox.Show(this, LocalizedStrings.cancelled);
});
};
// get emulation connector
var connector = batchEmulation.EmulationConnector;
logManager.Sources.Add(connector);
connector.NewSecurities += securities =>
{
if (securities.All(s => s != security))
return;
// fill level1 values
connector.SendInMessage(level1Info);
connector.RegisterMarketDepth(new TrendMarketDepthGenerator(connector.GetSecurityId(security))
{
// order book freq refresh is 1 sec
Interval = TimeSpan.FromSeconds(1),
});
};
TestingProcess.Maximum = 100;
TestingProcess.Value = 0;
_startEmulationTime = DateTime.Now;
var strategies = periods
.Select(period =>
{
var candleManager = new CandleManager(connector);
var series = new CandleSeries(typeof(TimeFrameCandle), security, timeFrame);
// create strategy based SMA
var strategy = new SmaStrategy(candleManager, series, new SimpleMovingAverage { Length = period.Item1 }, new SimpleMovingAverage { Length = period.Item2 })
{
Volume = 1,
Security = security,
Portfolio = portfolio,
Connector = connector,
// by default interval is 1 min,
// it is excessively for time range with several months
UnrealizedPnLInterval = ((stopTime - startTime).Ticks / 1000).To<TimeSpan>()
};
strategy.SetCandleManager(candleManager);
var curveItems = Curve.CreateCurve(LocalizedStrings.Str3026Params.Put(period.Item1, period.Item2), period.Item3);
strategy.PnLChanged += () =>
{
var data = new EquityData
{
Time = strategy.CurrentTime,
Value = strategy.PnL,
};
this.GuiAsync(() => curveItems.Add(data));
};
Stat.AddStrategies(new[] { strategy });
return strategy;
});
// start emulation
batchEmulation.Start(strategies);
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// Licensed under the MIT License. See LICENSE.txt in the project root for license information.
using System;
using System.Linq;
using System.Collections.Generic;
using System.Reflection;
using Windows.Foundation;
using Windows.UI;
using Microsoft.VisualStudio.TestPlatform.UnitTestFramework;
using Microsoft.Graphics.Canvas;
using Microsoft.Graphics.Canvas.Effects;
#if WINDOWS_UWP
using Windows.Graphics.Effects;
using System.Numerics;
#else
using Microsoft.Graphics.Canvas.DirectX;
using Microsoft.Graphics.Canvas.Numerics;
#endif
using NativeComponent;
namespace test.managed
{
[TestClass]
public class EffectTests
{
[TestMethod]
public void ReflectOverAllEffects()
{
var assembly = typeof(GaussianBlurEffect).GetTypeInfo().Assembly;
var effectTypes = from type in assembly.DefinedTypes
where type.ImplementedInterfaces.Contains(typeof(IGraphicsEffect))
select type;
foreach (var effectType in effectTypes)
{
IGraphicsEffect effect = (IGraphicsEffect)Activator.CreateInstance(effectType.AsType());
TestEffectSources(effectType, effect);
TestEffectProperties(effectType, effect);
}
}
static void TestEffectSources(TypeInfo effectType, IGraphicsEffect effect)
{
var sourceProperties = (from property in effectType.DeclaredProperties
where property.PropertyType == typeof(IGraphicsEffectSource)
select property).ToList();
// Should have the same number of strongly typed properties as the effect has sources.
Assert.AreEqual(sourceProperties.Count, EffectAccessor.GetSourceCount(effect));
// Initial source values should all be null.
for (int i = 0; i < EffectAccessor.GetSourceCount(effect); i++)
{
Assert.IsNull(EffectAccessor.GetSource(effect, i));
Assert.IsNull(sourceProperties[i].GetValue(effect));
}
var testValue1 = new GaussianBlurEffect();
var testValue2 = new ShadowEffect();
var whichIndexIsProperty = new List<int>();
// Changing strongly typed properties should change the sources reported by IGraphicsEffectD2D1Interop.
for (int i = 0; i < EffectAccessor.GetSourceCount(effect); i++)
{
// Change a property value, and see which source changes.
sourceProperties[i].SetValue(effect, testValue1);
int whichIndexIsThis = 0;
while (EffectAccessor.GetSource(effect, whichIndexIsThis) != testValue1)
{
whichIndexIsThis++;
Assert.IsTrue(whichIndexIsThis < EffectAccessor.GetSourceCount(effect));
}
whichIndexIsProperty.Add(whichIndexIsThis);
// Change the same property value again, and make sure the same source changes.
sourceProperties[i].SetValue(effect, testValue2);
Assert.AreSame(testValue2, EffectAccessor.GetSource(effect, whichIndexIsThis));
// Change the property value to null.
sourceProperties[i].SetValue(effect, null);
Assert.IsNull(EffectAccessor.GetSource(effect, whichIndexIsThis));
}
// Should not have any duplicate property mappings.
Assert.AreEqual(whichIndexIsProperty.Count, whichIndexIsProperty.Distinct().Count());
}
static void TestEffectProperties(TypeInfo effectType, IGraphicsEffect effect)
{
var properties = (from property in effectType.DeclaredProperties
where property.Name != "Name"
where property.Name != "Sources"
where property.PropertyType != typeof(IGraphicsEffectSource)
select property).ToList();
IList<object> effectProperties = new ViewIndexerAsList<object>(() => EffectAccessor.GetPropertyCount(effect),
i => EffectAccessor.GetProperty(effect, i));
FilterOutCustomizedEffectProperties(effectType.AsType(), ref properties, ref effectProperties);
// Should have the same number of strongly typed properties as elements in the properties collection.
Assert.AreEqual(properties.Count, effectProperties.Count);
// Store the initial property values.
var initialValues = effectProperties.ToList();
var whichIndexIsProperty = new List<int>();
// Changing strongly typed properties should change the properties collection.
for (int i = 0; i < effectProperties.Count; i++)
{
object testValue1 = GetArbitraryTestValue(properties[i].PropertyType, true);
object testValue2 = GetArbitraryTestValue(properties[i].PropertyType, false);
// Change a property value, and see which collection properties match the result.
properties[i].SetValue(effect, testValue1);
var matches1 = (from j in Enumerable.Range(0, effectProperties.Count)
where BoxedValuesAreEqual(effectProperties[j], Box(testValue1, properties[i]), properties[i])
select j).ToList();
// Change the same property to a different value, and see which collection properties match now.
properties[i].SetValue(effect, testValue2);
var matches2 = (from j in Enumerable.Range(0, effectProperties.Count)
where BoxedValuesAreEqual(effectProperties[j], Box(testValue2, properties[i]), properties[i])
select j).ToList();
// There should be one and only one property that matched both times. If not,
// either we don't have 1 <-> 1 mapping between strongly typed properties and
// collection indices, or something went wrong during the boxing type conversions.
var intersection = matches1.Intersect(matches2);
Assert.AreEqual(1, intersection.Count());
int whichIndexIsThis = intersection.Single();
whichIndexIsProperty.Add(whichIndexIsThis);
// Change the property value back to its initial state.
properties[i].SetValue(effect, Unbox(initialValues[whichIndexIsThis], properties[i]));
Assert.IsTrue(BoxedValuesAreEqual(initialValues[whichIndexIsThis], effectProperties[whichIndexIsThis], properties[i]));
// Validate that IGraphicsEffectD2D1Interop agrees with what we think the type and index of this property is.
int mappingIndex;
EffectPropertyMapping mapping;
EffectAccessor.GetNamedPropertyMapping(effect, properties[i].Name, out mappingIndex, out mapping);
int expectedMappingIndex = whichIndexIsThis;
if (effectProperties is FilteredViewOfList<object>)
expectedMappingIndex = ((FilteredViewOfList<object>)effectProperties).GetOriginalIndex(expectedMappingIndex);
Assert.AreEqual(expectedMappingIndex, mappingIndex);
var expectedMapping = GetExpectedPropertyMapping(properties[i], effectProperties[whichIndexIsThis]);
Assert.AreEqual(expectedMapping, mapping);
}
// Should not have any duplicate property mappings.
Assert.AreEqual(whichIndexIsProperty.Count, whichIndexIsProperty.Distinct().Count());
}
static object Box(object value, PropertyInfo property)
{
if (value is int ||
value is bool ||
value is float[])
{
return value;
}
else if (value is float)
{
if (NeedsRadianToDegreeConversion(property))
{
return (float)value * 180f / (float)Math.PI;
}
else
{
return value;
}
}
else if (value is Enum)
{
return (uint)(int)value;
}
else if (value is Vector2)
{
var v = (Vector2)value;
return new float[] { v.X, v.Y };
}
else if (value is Vector3)
{
var v = (Vector3)value;
return new float[] { v.X, v.Y, v.Z };
}
else if (value is Vector4)
{
var v = (Vector4)value;
return new float[] { v.X, v.Y, v.Z, v.W };
}
else if (value is Matrix3x2)
{
var m = (Matrix3x2)value;
return new float[]
{
m.M11, m.M12,
m.M21, m.M22,
m.M31, m.M32
};
}
else if (value is Matrix4x4)
{
var m = (Matrix4x4)value;
return new float[]
{
m.M11, m.M12, m.M13, m.M14,
m.M21, m.M22, m.M23, m.M24,
m.M31, m.M32, m.M33, m.M34,
m.M41, m.M42, m.M43, m.M44,
};
}
else if (value is Matrix5x4)
{
var m = (Matrix5x4)value;
return new float[]
{
m.M11, m.M12, m.M13, m.M14,
m.M21, m.M22, m.M23, m.M24,
m.M31, m.M32, m.M33, m.M34,
m.M41, m.M42, m.M43, m.M44,
m.M51, m.M52, m.M53, m.M54,
};
}
else if (value is Rect)
{
var r = (Rect)value;
return new float[]
{
(float)r.Left,
(float)r.Top,
(float)r.Right,
(float)r.Bottom,
};
}
else if (value is Color)
{
var c = (Color)value;
return new float[]
{
(float)c.R / 255,
(float)c.G / 255,
(float)c.B / 255,
(float)c.A / 255,
};
}
else
{
throw new NotSupportedException("Unsupported Box type " + value.GetType());
}
}
static object Unbox(object value, PropertyInfo property)
{
Type type = property.PropertyType;
if (type == typeof(int) ||
type == typeof(bool) ||
type == typeof(float[]))
{
return value;
}
else if (type == typeof(float))
{
if (NeedsRadianToDegreeConversion(property))
{
return (float)value * (float)Math.PI / 180f;
}
else
{
return value;
}
}
else if (type.GetTypeInfo().IsEnum)
{
return GetEnumValues(type).GetValue((int)(uint)value);
}
else if (type == typeof(Vector2))
{
var a = (float[])value;
Assert.AreEqual(2, a.Length);
return new Vector2
{
X = a[0],
Y = a[1],
};
}
else if (type == typeof(Vector3))
{
var a = (float[])value;
Assert.AreEqual(3, a.Length);
return new Vector3
{
X = a[0],
Y = a[1],
Z = a[2],
};
}
else if (type == typeof(Vector4))
{
var a = (float[])value;
Assert.AreEqual(4, a.Length);
return new Vector4
{
X = a[0],
Y = a[1],
Z = a[2],
W = a[3],
};
}
else if (type == typeof(Matrix3x2))
{
var a = (float[])value;
Assert.AreEqual(6, a.Length);
return new Matrix3x2
{
M11 = a[0], M12 = a[1],
M21 = a[2], M22 = a[3],
M31 = a[4], M32 = a[5],
};
}
else if (type == typeof(Matrix4x4))
{
var a = (float[])value;
Assert.AreEqual(16, a.Length);
return new Matrix4x4
{
M11 = a[0], M12 = a[1], M13 = a[2], M14 = a[3],
M21 = a[4], M22 = a[5], M23 = a[6], M24 = a[7],
M31 = a[8], M32 = a[9], M33 = a[10], M34 = a[11],
M41 = a[12], M42 = a[13], M43 = a[14], M44 = a[15],
};
}
else if (type == typeof(Matrix5x4))
{
var a = (float[])value;
Assert.AreEqual(20, a.Length);
return new Matrix5x4
{
M11 = a[0], M12 = a[1], M13 = a[2], M14 = a[3],
M21 = a[4], M22 = a[5], M23 = a[6], M24 = a[7],
M31 = a[8], M32 = a[9], M33 = a[10], M34 = a[11],
M41 = a[12], M42 = a[13], M43 = a[14], M44 = a[15],
M51 = a[16], M52 = a[17], M53 = a[18], M54 = a[19],
};
}
else if (type == typeof(Rect))
{
var a = (float[])value;
Assert.AreEqual(4, a.Length);
return new Rect(new Point(a[0], a[1]),
new Point(a[2], a[3]));
}
else if (type == typeof(Color))
{
var a = ConvertRgbToRgba((float[])value);
Assert.AreEqual(4, a.Length);
return Color.FromArgb((byte)(a[3] * 255),
(byte)(a[0] * 255),
(byte)(a[1] * 255),
(byte)(a[2] * 255));
}
else
{
throw new NotSupportedException("Unsupported Unbox type " + type);
}
}
static bool BoxedValuesAreEqual(object value1, object value2, PropertyInfo property)
{
if (value1.GetType() != value2.GetType())
{
return false;
}
if (value1 is int ||
value1 is uint ||
value1 is bool)
{
return value1.Equals(value2);
}
else if (value1 is float)
{
return Math.Abs((float)value1 - (float)value2) < 0.000001;
}
else if (value1 is float[])
{
float[] a1 = (float[])value1;
float[] a2 = (float[])value2;
if (property.PropertyType == typeof(Color))
{
a1 = ConvertRgbToRgba(a1);
a2 = ConvertRgbToRgba(a2);
}
return a1.SequenceEqual(a2);
}
else
{
throw new NotSupportedException("Unsupported BoxedValuesAreEqual type " + value1.GetType());
}
}
static void AssertPropertyValuesAreEqual(object value1, object value2)
{
if (value1 is float[] && value2 is float[])
{
Assert.IsTrue((value1 as float[]).SequenceEqual(value2 as float[]));
}
else if (value1 is float)
{
Assert.IsTrue(Math.Abs((float)value1 - (float)value2) < 0.000001);
}
else
{
Assert.AreEqual(value1, value2);
}
}
static float[] ConvertRgbToRgba(float[] value)
{
if (value.Length == 3)
{
return value.Concat(new float[] { 1 }).ToArray();
}
else
{
return value;
}
}
static float[] ConvertRgbaToRgb(float[] value)
{
return value.Take(3).ToArray();
}
static bool NeedsRadianToDegreeConversion(PropertyInfo property)
{
string[] anglePropertyNames =
{
"Angle",
"Azimuth",
"Elevation",
"LimitingConeAngle",
};
return anglePropertyNames.Contains(property.Name);
}
static EffectPropertyMapping GetExpectedPropertyMapping(PropertyInfo property, object propertyValue)
{
if (NeedsRadianToDegreeConversion(property))
{
return EffectPropertyMapping.RadiansToDegrees;
}
else if (property.PropertyType == typeof(Rect))
{
return EffectPropertyMapping.RectToVector4;
}
else if (property.PropertyType == typeof(Color))
{
return ((float[])propertyValue).Length == 3 ? EffectPropertyMapping.ColorToVector3 :
EffectPropertyMapping.ColorToVector4;
}
else
{
return EffectPropertyMapping.Direct;
}
}
static object GetArbitraryTestValue(Type type, bool whichOne)
{
if (type == typeof(int))
{
return whichOne ? 2 : 7;
}
else if (type == typeof(float))
{
return whichOne ? 0.5f : 0.75f;
}
else if (type == typeof(bool))
{
return whichOne;
}
else if (type.GetTypeInfo().IsEnum)
{
return GetEnumValues(type).GetValue(whichOne ? 0 : 1);
}
else if (type == typeof(Vector2))
{
return whichOne ? new Vector2 { X = 0.25f, Y = 0.75f } :
new Vector2 { X = 0.5f, Y = 0.125f };
}
else if (type == typeof(Vector3))
{
return whichOne ? new Vector3 { X = 1, Y = 2, Z = 3 } :
new Vector3 { X = 4, Y = 5, Z = 6 };
}
else if (type == typeof(Vector4))
{
return whichOne ? new Vector4 { X = 1, Y = 2, Z = 3, W = 4 } :
new Vector4 { X = 5, Y = 6, Z = 7, W = 8 };
}
else if (type == typeof(Matrix3x2))
{
return whichOne ? new Matrix3x2
{
M11 = 1, M12 = 2,
M21 = 3, M22 = 4,
M31 = 5, M32 = 6
} :
new Matrix3x2
{
M11 = 7, M12 = 8,
M21 = 9, M22 = 10,
M31 = 11, M32 = 12
};
}
else if (type == typeof(Matrix4x4))
{
return whichOne ? new Matrix4x4
{
M11 = 1, M12 = 2, M13 = 3, M14 = 4,
M21 = 5, M22 = 6, M23 = 7, M24 = 8,
M31 = 9, M32 = 10, M33 = 11, M34 = 12,
M41 = 13, M42 = 14, M43 = 15, M44 = 16
} :
new Matrix4x4
{
M11 = 11, M12 = 12, M13 = 13, M14 = 14,
M21 = 15, M22 = 16, M23 = 17, M24 = 18,
M31 = 19, M32 = 20, M33 = 21, M34 = 22,
M41 = 23, M42 = 24, M43 = 25, M44 = 26
};
}
else if (type == typeof(Matrix5x4))
{
return whichOne ? new Matrix5x4
{
M11 = 1, M12 = 2, M13 = 3, M14 = 4,
M21 = 5, M22 = 6, M23 = 7, M24 = 8,
M31 = 9, M32 = 10, M33 = 11, M34 = 12,
M41 = 13, M42 = 14, M43 = 15, M44 = 16,
M51 = 17, M52 = 18, M53 = 19, M54 = 20
} :
new Matrix5x4
{
M11 = 11, M12 = 12, M13 = 13, M14 = 14,
M21 = 15, M22 = 16, M23 = 17, M24 = 18,
M31 = 19, M32 = 20, M33 = 21, M34 = 22,
M41 = 23, M42 = 24, M43 = 25, M44 = 26,
M51 = 27, M52 = 28, M53 = 29, M54 = 30
};
}
else if (type == typeof(Rect))
{
return whichOne ? new Rect(1, 2, 3, 4) :
new Rect(10, 20, 5, 6);
}
else if (type == typeof(Color))
{
return whichOne ? Colors.CornflowerBlue : Colors.Crimson;
}
else if (type == typeof(float[]))
{
return whichOne ? new float[] { 1, 2, 3 } :
new float[] { 4, 5, 6, 7, 8, 9 };
}
else
{
throw new NotSupportedException("Unsupported GetArbitraryTestValue type " + type);
}
}
// Replacement for Enum.GetValues, to work around VS2015 .NET Native reflection bug.
static object[] GetEnumValues(Type type)
{
Assert.IsTrue(type.GetTypeInfo().IsEnum);
var values = from field in type.GetTypeInfo().DeclaredFields
where field.IsStatic
orderby field.GetValue(null)
select field.GetValue(null);
return values.ToArray();
}
static void FilterOutCustomizedEffectProperties(Type effectType, ref List<PropertyInfo> properties, ref IList<object> effectProperties)
{
// Customized properties that our general purpose reflection based property test won't understand.
string[] propertiesToRemove;
int[] indexMapping;
if (effectType == typeof(ArithmeticCompositeEffect))
{
// ArithmeticCompositeEffect has strange customized properties.
// Win2D exposes what D2D treats as a single Vector4 as 4 separate float properties.
propertiesToRemove = new string[]
{
"MultiplyAmount",
"Source1Amount",
"Source2Amount",
"Offset"
};
indexMapping = new int[] { 1 };
}
else if (effectType == typeof(ColorMatrixEffect))
{
// ColorMatrixEffect.AlphaMode has special logic to remap enum values between WinRT and D2D.
propertiesToRemove = new string[] { "AlphaMode", };
indexMapping = new int[] { 0, 2 };
}
#if WINDOWS_UWP
else if (effectType == typeof(SepiaEffect))
{
// SepiaEffect.AlphaMode has special logic to remap enum values between WinRT and D2D.
propertiesToRemove = new string[] { "AlphaMode", };
indexMapping = new int[] { 0 };
}
else if (effectType == typeof(EdgeDetectionEffect))
{
// EdgeDetectionEffect.AlphaMode has special logic to remap enum values between WinRT and D2D.
propertiesToRemove = new string[] { "AlphaMode", };
indexMapping = new int[] { 0, 1, 2, 3 };
}
else if (effectType == typeof(HighlightsAndShadowsEffect))
{
// HighlightsAndShadowsEffect.SourceIsLinearGamma projects an enum value as a bool.
propertiesToRemove = new string[] { "SourceIsLinearGamma", };
indexMapping = new int[] { 0, 1, 2, 4 };
}
#endif // WINDOWS_UWP
else
{
// Other effects do not need special filtering.
return;
}
// Hide the customized properties, so ReflectOverAllEffects test won't see them.
properties = properties.Where(p => !propertiesToRemove.Contains(p.Name)).ToList();
effectProperties = new FilteredViewOfList<object>(effectProperties, indexMapping);
}
class FilteredViewOfList<T> : IList<T>
{
IList<T> underlyingList;
IList<int> indexMapping;
public FilteredViewOfList(IList<T> underlyingList, IList<int> indexMapping)
{
this.underlyingList = underlyingList;
this.indexMapping = indexMapping;
}
public int Count
{
get { return indexMapping.Count; }
}
public T this[int index]
{
get { return underlyingList[indexMapping[index]]; }
set { underlyingList[indexMapping[index]] = value; }
}
public void CopyTo(T[] array, int arrayIndex)
{
for (int i = 0; i < Count; i++)
{
array[arrayIndex + i] = this[i];
}
}
public int GetOriginalIndex(int index)
{
return indexMapping[index];
}
public void Add(T item) { throw new NotImplementedException(); }
public void Clear() { throw new NotImplementedException(); }
public bool Contains(T item) { throw new NotImplementedException(); }
public int IndexOf(T item) { throw new NotImplementedException(); }
public void Insert(int index, T item) { throw new NotImplementedException(); }
public bool IsReadOnly { get { throw new NotImplementedException(); } }
public bool Remove(T item) { throw new NotImplementedException(); }
public void RemoveAt(int index) { throw new NotImplementedException(); }
public IEnumerator<T> GetEnumerator() { throw new NotImplementedException(); }
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { throw new NotImplementedException(); }
}
class ViewIndexerAsList<T> : IList<T>
{
Func<int> getCount;
Func<int, T> getItem;
public ViewIndexerAsList(Func<int> getCount, Func<int, T> getItem)
{
this.getCount = getCount;
this.getItem = getItem;
}
public int Count
{
get { return getCount(); }
}
public T this[int index]
{
get { return getItem(index); }
set { throw new NotImplementedException(); }
}
public void CopyTo(T[] array, int arrayIndex)
{
for (int i = 0; i < Count; i++)
{
array[arrayIndex + i] = getItem(i);
}
}
public void Add(T item) { throw new NotImplementedException(); }
public void Clear() { throw new NotImplementedException(); }
public bool Contains(T item) { throw new NotImplementedException(); }
public int IndexOf(T item) { throw new NotImplementedException(); }
public void Insert(int index, T item) { throw new NotImplementedException(); }
public bool IsReadOnly { get { throw new NotImplementedException(); } }
public bool Remove(T item) { throw new NotImplementedException(); }
public void RemoveAt(int index) { throw new NotImplementedException(); }
public IEnumerator<T> GetEnumerator() { throw new NotImplementedException(); }
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { throw new NotImplementedException(); }
}
[TestMethod]
public void ArithmeticCompositeEffectCustomizations()
{
var effect = new ArithmeticCompositeEffect();
// Verify defaults.
Assert.AreEqual(1.0f, effect.MultiplyAmount);
Assert.AreEqual(0.0f, effect.Source1Amount);
Assert.AreEqual(0.0f, effect.Source2Amount);
Assert.AreEqual(0.0f, effect.Offset);
Assert.IsTrue(((float[])EffectAccessor.GetProperty(effect, 0)).SequenceEqual(new float[] { 1, 0, 0, 0 }));
// Change properties one at a time, and verify that the boxed value changes to match.
effect.MultiplyAmount = 23;
Assert.IsTrue(((float[])EffectAccessor.GetProperty(effect, 0)).SequenceEqual(new float[] { 23, 0, 0, 0 }));
effect.Source1Amount = 42;
Assert.IsTrue(((float[])EffectAccessor.GetProperty(effect, 0)).SequenceEqual(new float[] { 23, 42, 0, 0 }));
effect.Source2Amount = -1;
Assert.IsTrue(((float[])EffectAccessor.GetProperty(effect, 0)).SequenceEqual(new float[] { 23, 42, -1, 0 }));
effect.Offset = 100;
Assert.IsTrue(((float[])EffectAccessor.GetProperty(effect, 0)).SequenceEqual(new float[] { 23, 42, -1, 100 }));
// Validate that IGraphicsEffectD2D1Interop reports the right customizations.
int index;
EffectPropertyMapping mapping;
EffectAccessor.GetNamedPropertyMapping(effect, "MultiplyAmount", out index, out mapping);
Assert.AreEqual(0, index);
Assert.AreEqual(EffectPropertyMapping.VectorX, mapping);
EffectAccessor.GetNamedPropertyMapping(effect, "Source1Amount", out index, out mapping);
Assert.AreEqual(0, index);
Assert.AreEqual(EffectPropertyMapping.VectorY, mapping);
EffectAccessor.GetNamedPropertyMapping(effect, "Source2Amount", out index, out mapping);
Assert.AreEqual(0, index);
Assert.AreEqual(EffectPropertyMapping.VectorZ, mapping);
EffectAccessor.GetNamedPropertyMapping(effect, "Offset", out index, out mapping);
Assert.AreEqual(0, index);
Assert.AreEqual(EffectPropertyMapping.VectorW, mapping);
}
const uint D2D1_ALPHA_MODE_PREMULTIPLIED = 1;
const uint D2D1_ALPHA_MODE_STRAIGHT = 2;
[TestMethod]
public void ColorMatrixEffectCustomizations()
{
var effect = new ColorMatrixEffect();
// Verify defaults.
Assert.AreEqual(CanvasAlphaMode.Premultiplied, effect.AlphaMode);
Assert.AreEqual(D2D1_ALPHA_MODE_PREMULTIPLIED, EffectAccessor.GetProperty(effect, 1));
// Change the property, and verify that the boxed value changes to match.
effect.AlphaMode = CanvasAlphaMode.Straight;
Assert.AreEqual(D2D1_ALPHA_MODE_STRAIGHT, EffectAccessor.GetProperty(effect, 1));
effect.AlphaMode = CanvasAlphaMode.Premultiplied;
Assert.AreEqual(D2D1_ALPHA_MODE_PREMULTIPLIED, EffectAccessor.GetProperty(effect, 1));
// Verify unsupported value throws.
Assert.ThrowsException<ArgumentException>(() => { effect.AlphaMode = CanvasAlphaMode.Ignore; });
Assert.AreEqual(CanvasAlphaMode.Premultiplied, effect.AlphaMode);
// Validate that IGraphicsEffectD2D1Interop reports the right customizations.
int index;
EffectPropertyMapping mapping;
EffectAccessor.GetNamedPropertyMapping(effect, "AlphaMode", out index, out mapping);
Assert.AreEqual(1, index);
Assert.AreEqual(EffectPropertyMapping.ColorMatrixAlphaMode, mapping);
}
#if WINDOWS_UWP
[TestMethod]
public void SepiaEffectCustomizations()
{
var effect = new SepiaEffect();
// Verify defaults.
Assert.AreEqual(CanvasAlphaMode.Premultiplied, effect.AlphaMode);
Assert.AreEqual(D2D1_ALPHA_MODE_PREMULTIPLIED, EffectAccessor.GetProperty(effect, 1));
// Change the property, and verify that the boxed value changes to match.
effect.AlphaMode = CanvasAlphaMode.Straight;
Assert.AreEqual(D2D1_ALPHA_MODE_STRAIGHT, EffectAccessor.GetProperty(effect, 1));
effect.AlphaMode = CanvasAlphaMode.Premultiplied;
Assert.AreEqual(D2D1_ALPHA_MODE_PREMULTIPLIED, EffectAccessor.GetProperty(effect, 1));
// Verify unsupported value throws.
Assert.ThrowsException<ArgumentException>(() => { effect.AlphaMode = CanvasAlphaMode.Ignore; });
Assert.AreEqual(CanvasAlphaMode.Premultiplied, effect.AlphaMode);
// Validate that IGraphicsEffectD2D1Interop reports the right customizations.
int index;
EffectPropertyMapping mapping;
EffectAccessor.GetNamedPropertyMapping(effect, "AlphaMode", out index, out mapping);
Assert.AreEqual(1, index);
Assert.AreEqual(EffectPropertyMapping.ColorMatrixAlphaMode, mapping);
}
[TestMethod]
public void EdgeDetectionEffectCustomizations()
{
var effect = new EdgeDetectionEffect();
// Verify defaults.
Assert.AreEqual(CanvasAlphaMode.Premultiplied, effect.AlphaMode);
Assert.AreEqual(D2D1_ALPHA_MODE_PREMULTIPLIED, EffectAccessor.GetProperty(effect, 4));
// Change the property, and verify that the boxed value changes to match.
effect.AlphaMode = CanvasAlphaMode.Straight;
Assert.AreEqual(D2D1_ALPHA_MODE_STRAIGHT, EffectAccessor.GetProperty(effect, 4));
effect.AlphaMode = CanvasAlphaMode.Premultiplied;
Assert.AreEqual(D2D1_ALPHA_MODE_PREMULTIPLIED, EffectAccessor.GetProperty(effect, 4));
// Verify unsupported value throws.
Assert.ThrowsException<ArgumentException>(() => { effect.AlphaMode = CanvasAlphaMode.Ignore; });
Assert.AreEqual(CanvasAlphaMode.Premultiplied, effect.AlphaMode);
// Validate that IGraphicsEffectD2D1Interop reports the right customizations.
int index;
EffectPropertyMapping mapping;
EffectAccessor.GetNamedPropertyMapping(effect, "AlphaMode", out index, out mapping);
Assert.AreEqual(4, index);
Assert.AreEqual(EffectPropertyMapping.ColorMatrixAlphaMode, mapping);
}
[TestMethod]
public void HighlightsAndShadowsEffectCustomizations()
{
const uint D2D1_HIGHLIGHTSANDSHADOWS_INPUT_GAMMA_LINEAR = 0;
const uint D2D1_HIGHLIGHTSANDSHADOWS_INPUT_GAMMA_SRGB = 1;
var effect = new HighlightsAndShadowsEffect();
// Verify defaults.
Assert.IsFalse(effect.SourceIsLinearGamma);
Assert.AreEqual(D2D1_HIGHLIGHTSANDSHADOWS_INPUT_GAMMA_SRGB, EffectAccessor.GetProperty(effect, 3));
// Change the property, and verify that the boxed value changes to match.
effect.SourceIsLinearGamma = true;
Assert.IsTrue(effect.SourceIsLinearGamma);
Assert.AreEqual(D2D1_HIGHLIGHTSANDSHADOWS_INPUT_GAMMA_LINEAR, EffectAccessor.GetProperty(effect, 3));
effect.SourceIsLinearGamma = false;
Assert.IsFalse(effect.SourceIsLinearGamma);
Assert.AreEqual(D2D1_HIGHLIGHTSANDSHADOWS_INPUT_GAMMA_SRGB, EffectAccessor.GetProperty(effect, 3));
// Validate that IGraphicsEffectD2D1Interop reports the right customizations.
int index;
EffectPropertyMapping mapping;
EffectAccessor.GetNamedPropertyMapping(effect, "SourceIsLinearGamma", out index, out mapping);
Assert.AreEqual(3, index);
Assert.AreEqual(EffectPropertyMapping.Unknown, mapping);
}
[TestMethod]
public void StraightenEffectDoesNotSupportHighQualityInterpolation()
{
var effect = new StraightenEffect();
var supportedModes = from mode in Enum.GetValues(typeof(CanvasImageInterpolation)).Cast<CanvasImageInterpolation>()
where mode != CanvasImageInterpolation.HighQualityCubic
select mode;
foreach (var interpolationMode in supportedModes)
{
effect.InterpolationMode = interpolationMode;
Assert.AreEqual(interpolationMode, effect.InterpolationMode);
}
Assert.ThrowsException<ArgumentException>(() =>
{
effect.InterpolationMode = CanvasImageInterpolation.HighQualityCubic;
});
}
#endif // WINDOWS_UWP
[TestMethod]
public void Transform3DEffectDoesNotSupportHighQualityInterpolation()
{
var effect = new Transform3DEffect();
var supportedModes = from mode in Enum.GetValues(typeof(CanvasImageInterpolation)).Cast<CanvasImageInterpolation>()
where mode != CanvasImageInterpolation.HighQualityCubic
select mode;
foreach (var interpolationMode in supportedModes)
{
effect.InterpolationMode = interpolationMode;
Assert.AreEqual(interpolationMode, effect.InterpolationMode);
}
Assert.ThrowsException<ArgumentException>(() =>
{
effect.InterpolationMode = CanvasImageInterpolation.HighQualityCubic;
});
}
[TestMethod]
public void Transform2DEffectSupportsAllInterpolationModes()
{
var effect = new Transform2DEffect();
foreach (var interpolationMode in Enum.GetValues(typeof(CanvasImageInterpolation)).Cast<CanvasImageInterpolation>())
{
effect.InterpolationMode = interpolationMode;
Assert.AreEqual(interpolationMode, effect.InterpolationMode);
}
}
class NotACanvasImage : IGraphicsEffectSource { }
void VerifyExceptionMessage(string expected, string sourceMessage)
{
// Exception messages contain something like
// "Invalid pointer\r\n\r\nEffect source #0 is null",
// The 'invalid pointer' part is locale
// dependent and is stripped out.
string delimiterString = "\r\n\r\n";
int delimiterPosition = sourceMessage.LastIndexOf(delimiterString);
string exceptionMessage = sourceMessage.Substring(delimiterPosition + delimiterString.Length);
Assert.AreEqual(expected, exceptionMessage);
}
[TestMethod]
public void EffectExceptionMessages()
{
var effect = new GaussianBlurEffect();
using (var device = new CanvasDevice())
using (var renderTarget = new CanvasRenderTarget(device, 1, 1, 96))
using (var drawingSession = renderTarget.CreateDrawingSession())
{
// Null source.
try
{
drawingSession.DrawImage(effect);
Assert.Fail("should throw");
}
catch (NullReferenceException e)
{
VerifyExceptionMessage("Effect source #0 is null.", e.Message);
}
// Invalid source type.
effect.Source = new NotACanvasImage();
try
{
drawingSession.DrawImage(effect);
Assert.Fail("should throw");
}
catch (InvalidCastException e)
{
VerifyExceptionMessage("Effect source #0 is an unsupported type. To draw an effect using Win2D, all its sources must be Win2D ICanvasImage objects.", e.Message);
}
}
}
[TestMethod]
public void EffectPropertyDefaults()
{
// We have customised the default value of DpiCompensationEffect border mode property.
Assert.AreEqual(EffectBorderMode.Hard, new DpiCompensationEffect().BorderMode);
// Other effects should still have the standard D2D default value.
Assert.AreEqual(EffectBorderMode.Soft, new GaussianBlurEffect().BorderMode);
Assert.AreEqual(EffectBorderMode.Soft, new Transform3DEffect().BorderMode);
}
[TestMethod]
public void EffectName()
{
var effect = new GaussianBlurEffect();
Assert.AreEqual(string.Empty, effect.Name);
effect.Name = "hello";
Assert.AreEqual("hello", effect.Name);
effect.Name = "world";
Assert.AreEqual("world", effect.Name);
effect.Name = string.Empty;
Assert.AreEqual(string.Empty, effect.Name);
Assert.ThrowsException<ArgumentNullException>(() => { effect.Name = null; });
}
}
}
| |
using System;
using System.Data;
using System.Data.SqlClient;
using Csla;
using Csla.Data;
namespace ParentLoad.Business.ERLevel
{
/// <summary>
/// A09_CityColl (editable child list).<br/>
/// This is a generated base class of <see cref="A09_CityColl"/> business object.
/// </summary>
/// <remarks>
/// This class is child of <see cref="A08_Region"/> editable child object.<br/>
/// The items of the collection are <see cref="A10_City"/> objects.
/// </remarks>
[Serializable]
public partial class A09_CityColl : BusinessListBase<A09_CityColl, A10_City>
{
#region Collection Business Methods
/// <summary>
/// Removes a <see cref="A10_City"/> item from the collection.
/// </summary>
/// <param name="city_ID">The City_ID of the item to be removed.</param>
public void Remove(int city_ID)
{
foreach (var a10_City in this)
{
if (a10_City.City_ID == city_ID)
{
Remove(a10_City);
break;
}
}
}
/// <summary>
/// Determines whether a <see cref="A10_City"/> item is in the collection.
/// </summary>
/// <param name="city_ID">The City_ID of the item to search for.</param>
/// <returns><c>true</c> if the A10_City is a collection item; otherwise, <c>false</c>.</returns>
public bool Contains(int city_ID)
{
foreach (var a10_City in this)
{
if (a10_City.City_ID == city_ID)
{
return true;
}
}
return false;
}
/// <summary>
/// Determines whether a <see cref="A10_City"/> item is in the collection's DeletedList.
/// </summary>
/// <param name="city_ID">The City_ID of the item to search for.</param>
/// <returns><c>true</c> if the A10_City is a deleted collection item; otherwise, <c>false</c>.</returns>
public bool ContainsDeleted(int city_ID)
{
foreach (var a10_City in DeletedList)
{
if (a10_City.City_ID == city_ID)
{
return true;
}
}
return false;
}
#endregion
#region Find Methods
/// <summary>
/// Finds a <see cref="A10_City"/> item of the <see cref="A09_CityColl"/> collection, based on item key properties.
/// </summary>
/// <param name="city_ID">The City_ID.</param>
/// <returns>A <see cref="A10_City"/> object.</returns>
public A10_City FindA10_CityByParentProperties(int city_ID)
{
for (var i = 0; i < this.Count; i++)
{
if (this[i].City_ID.Equals(city_ID))
{
return this[i];
}
}
return null;
}
#endregion
#region Factory Methods
/// <summary>
/// Factory method. Creates a new <see cref="A09_CityColl"/> collection.
/// </summary>
/// <returns>A reference to the created <see cref="A09_CityColl"/> collection.</returns>
internal static A09_CityColl NewA09_CityColl()
{
return DataPortal.CreateChild<A09_CityColl>();
}
/// <summary>
/// Factory method. Loads a <see cref="A09_CityColl"/> object from the given SafeDataReader.
/// </summary>
/// <param name="dr">The SafeDataReader to use.</param>
/// <returns>A reference to the fetched <see cref="A09_CityColl"/> object.</returns>
internal static A09_CityColl GetA09_CityColl(SafeDataReader dr)
{
A09_CityColl obj = new A09_CityColl();
// show the framework that this is a child object
obj.MarkAsChild();
obj.Fetch(dr);
return obj;
}
#endregion
#region Constructor
/// <summary>
/// Initializes a new instance of the <see cref="A09_CityColl"/> class.
/// </summary>
/// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks>
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public A09_CityColl()
{
// Use factory methods and do not use direct creation.
// show the framework that this is a child object
MarkAsChild();
var rlce = RaiseListChangedEvents;
RaiseListChangedEvents = false;
AllowNew = true;
AllowEdit = true;
AllowRemove = true;
RaiseListChangedEvents = rlce;
}
#endregion
#region Data Access
/// <summary>
/// Loads all <see cref="A09_CityColl"/> collection items from the given SafeDataReader.
/// </summary>
/// <param name="dr">The SafeDataReader to use.</param>
private void Fetch(SafeDataReader dr)
{
var rlce = RaiseListChangedEvents;
RaiseListChangedEvents = false;
var args = new DataPortalHookArgs(dr);
OnFetchPre(args);
while (dr.Read())
{
Add(A10_City.GetA10_City(dr));
}
OnFetchPost(args);
RaiseListChangedEvents = rlce;
}
/// <summary>
/// Loads <see cref="A10_City"/> items on the A09_CityObjects collection.
/// </summary>
/// <param name="collection">The grand parent <see cref="A07_RegionColl"/> collection.</param>
internal void LoadItems(A07_RegionColl collection)
{
foreach (var item in this)
{
var obj = collection.FindA08_RegionByParentProperties(item.parent_Region_ID);
var rlce = obj.A09_CityObjects.RaiseListChangedEvents;
obj.A09_CityObjects.RaiseListChangedEvents = false;
obj.A09_CityObjects.Add(item);
obj.A09_CityObjects.RaiseListChangedEvents = rlce;
}
}
#endregion
#region DataPortal Hooks
/// <summary>
/// Occurs after setting query parameters and before the fetch operation.
/// </summary>
partial void OnFetchPre(DataPortalHookArgs args);
/// <summary>
/// Occurs after the fetch operation (object or collection is fully loaded and set up).
/// </summary>
partial void OnFetchPost(DataPortalHookArgs args);
#endregion
}
}
| |
// 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.Runtime.InteropServices;
using System.Text;
using OpenLiveWriter.Interop.Com;
namespace OpenLiveWriter.Interop.Windows
{
/// <summary>
/// Imports from Shell32.dll
/// </summary>
public class Shell32
{
[DllImport("shell32.dll", CharSet = CharSet.Unicode)]
public static extern bool PathYetAnotherMakeUniqueName(
StringBuilder pszUniqueName,
string pszPath,
string pszShort,
string pszFileSpec);
[DllImport("shell32.dll")]
public static extern bool PathIsSlow(string pszFile, int attr);
[DllImport("shell32.dll")]
public static extern IntPtr FindExecutable(string lpFile, string lpDirectory,
[Out] StringBuilder lpResult);
[DllImport("Shell32.dll")]
public static extern int SHGetInstanceExplorer(
out IntPtr ppunk);
[DllImport("Shell32.dll")]
public static extern int SHGetSpecialFolderLocation(
IntPtr hwndOwner, int nFolder, out IntPtr ppidl);
[DllImport("Shell32.dll")]
public static extern Int32 SHGetFolderLocation(
IntPtr hwndOwner, Int32 nFolder, IntPtr hToken, UInt32 dwReserved, out IntPtr ppidl);
[DllImport("Shell32.dll")]
public static extern Int32 SHGetKnownFolderIDList(
ref Guid rfid, UInt32 dwFlags, IntPtr hToken, out IntPtr ppidl);
[DllImport("Shell32.dll")]
public static extern void ILFree(IntPtr pidl);
[DllImport("Shell32.dll", CharSet = CharSet.Unicode)]
public static extern void SHAddToRecentDocs(uint uFlags, [MarshalAs(UnmanagedType.LPTStr)]string pv);
[DllImport("Shell32.dll", CharSet = CharSet.Unicode)]
public static extern bool SHGetPathFromIDList(IntPtr pidl,
[MarshalAs(UnmanagedType.LPWStr)] StringBuilder pszPath);
[DllImport("Shell32.dll")]
public static extern int SHGetMalloc(out IntPtr ppMalloc);
[DllImport("Shell32.dll")]
public static extern int SHCreateDirectory(
IntPtr hwnd,
[MarshalAs(UnmanagedType.LPWStr)] string pszPath);
[DllImport("shell32.dll", CharSet = CharSet.Unicode,
SetLastError = true)]
public static extern int SHCreateItemFromParsingName(
[MarshalAs(UnmanagedType.LPWStr)] string path,
// The following parameter is not used - binding context.
IntPtr pbc,
ref Guid riid,
[MarshalAs(UnmanagedType.Interface)] out IShellItem2 shellItem);
/// <summary>
/// Gets the HIcon for the icon associated with a file
/// </summary>
[DllImport("Shell32.dll")]
public static extern IntPtr ExtractAssociatedIcon(
IntPtr hInst,
string lpIconPath,
ref short lpiIcon
);
/// <summary>
/// Retrieves an icon from an icon, exe, or dll file by index
/// </summary>
[DllImport("Shell32.dll")]
public static extern IntPtr ExtractIcon(
IntPtr hInst,
string lpszExeFileName,
Int32 nIconIndex
);
[DllImport("shell32.dll", SetLastError = true)]
public static extern IntPtr SHGetFileInfo(string pszPath, uint dwFileAttributes, ref SHFILEINFO psfi, uint cbSizeFileInfo, uint uFlags);
[DllImport("shell32.dll")]
public static extern void SetCurrentProcessExplicitAppUserModelID(
[MarshalAs(UnmanagedType.LPWStr)] string AppID);
[DllImport("shell32.dll")]
public static extern void GetCurrentProcessExplicitAppUserModelID(
[Out(), MarshalAs(UnmanagedType.LPWStr)] out string AppID);
[DllImport("shell32.dll")]
public static extern int SHGetPropertyStoreForWindow(
IntPtr hwnd,
ref Guid iid /*IID_IPropertyStore*/,
[Out(), MarshalAs(UnmanagedType.Interface)]
out IPropertyStore propertyStore);
/// <summary>
/// Indicate flags that modify the property store object retrieved by methods
/// that create a property store, such as IShellItem2::GetPropertyStore or
/// IPropertyStoreFactory::GetPropertyStore.
/// </summary>
[Flags]
public enum GETPROPERTYSTOREFLAGS : uint
{
/// <summary>
/// Meaning to a calling process: Return a read-only property store that contains all
/// properties. Slow items (offline files) are not opened.
/// Combination with other flags: Can be overridden by other flags.
/// </summary>
GPS_DEFAULT = 0,
/// <summary>
/// Meaning to a calling process: Include only properties directly from the property
/// handler, which opens the file on the disk, network, or device. Meaning to a file
/// folder: Only include properties directly from the handler.
///
/// Meaning to other folders: When delegating to a file folder, pass this flag on
/// to the file folder; do not do any multiplexing (MUX). When not delegating to a
/// file folder, ignore this flag instead of returning a failure code.
///
/// Combination with other flags: Cannot be combined with GPS_TEMPORARY,
/// GPS_FASTPROPERTIESONLY, or GPS_BESTEFFORT.
/// </summary>
GPS_HANDLERPROPERTIESONLY = 0x1,
/// <summary>
/// Meaning to a calling process: Can write properties to the item.
/// Note: The store may contain fewer properties than a read-only store.
///
/// Meaning to a file folder: ReadWrite.
///
/// Meaning to other folders: ReadWrite. Note: When using default MUX,
/// return a single unmultiplexed store because the default MUX does not support ReadWrite.
///
/// Combination with other flags: Cannot be combined with GPS_TEMPORARY, GPS_FASTPROPERTIESONLY,
/// GPS_BESTEFFORT, or GPS_DELAYCREATION. Implies GPS_HANDLERPROPERTIESONLY.
/// </summary>
GPS_READWRITE = 0x2,
/// <summary>
/// Meaning to a calling process: Provides a writable store, with no initial properties,
/// that exists for the lifetime of the Shell item instance; basically, a property bag
/// attached to the item instance.
///
/// Meaning to a file folder: Not applicable. Handled by the Shell item.
///
/// Meaning to other folders: Not applicable. Handled by the Shell item.
///
/// Combination with other flags: Cannot be combined with any other flag. Implies GPS_READWRITE
/// </summary>
GPS_TEMPORARY = 0x4,
/// <summary>
/// Meaning to a calling process: Provides a store that does not involve reading from the
/// disk or network. Note: Some values may be different, or missing, compared to a store
/// without this flag.
///
/// Meaning to a file folder: Include the "innate" and "fallback" stores only. Do not load the handler.
///
/// Meaning to other folders: Include only properties that are available in memory or can
/// be computed very quickly (no properties from disk, network, or peripheral IO devices).
/// This is normally only data sources from the IDLIST. When delegating to other folders, pass this flag on to them.
///
/// Combination with other flags: Cannot be combined with GPS_TEMPORARY, GPS_READWRITE,
/// GPS_HANDLERPROPERTIESONLY, or GPS_DELAYCREATION.
/// </summary>
GPS_FASTPROPERTIESONLY = 0x8,
/// <summary>
/// Meaning to a calling process: Open a slow item (offline file) if necessary.
/// Meaning to a file folder: Retrieve a file from offline storage, if necessary.
/// Note: Without this flag, the handler is not created for offline files.
///
/// Meaning to other folders: Do not return any properties that are very slow.
///
/// Combination with other flags: Cannot be combined with GPS_TEMPORARY or GPS_FASTPROPERTIESONLY.
/// </summary>
GPS_OPENSLOWITEM = 0x10,
/// <summary>
/// Meaning to a calling process: Delay memory-intensive operations, such as file access, until
/// a property is requested that requires such access.
///
/// Meaning to a file folder: Do not create the handler until needed; for example, either
/// GetCount/GetAt or GetValue, where the innate store does not satisfy the request.
/// Note: GetValue might fail due to file access problems.
///
/// Meaning to other folders: If the folder has memory-intensive properties, such as
/// delegating to a file folder or network access, it can optimize performance by
/// supporting IDelayedPropertyStoreFactory and splitting up its properties into a
/// fast and a slow store. It can then use delayed MUX to recombine them.
///
/// Combination with other flags: Cannot be combined with GPS_TEMPORARY or
/// GPS_READWRITE
/// </summary>
GPS_DELAYCREATION = 0x20,
/// <summary>
/// Meaning to a calling process: Succeed at getting the store, even if some
/// properties are not returned. Note: Some values may be different, or missing,
/// compared to a store without this flag.
///
/// Meaning to a file folder: Succeed and return a store, even if the handler or
/// innate store has an error during creation. Only fail if substores fail.
///
/// Meaning to other folders: Succeed on getting the store, even if some properties
/// are not returned.
///
/// Combination with other flags: Cannot be combined with GPS_TEMPORARY,
/// GPS_READWRITE, or GPS_HANDLERPROPERTIESONLY.
/// </summary>
GPS_BESTEFFORT = 0x40,
/// <summary>
/// Mask for valid GETPROPERTYSTOREFLAGS values.
/// </summary>
GPS_MASK_VALID = 0xff,
}
[Flags]
public enum SFGAO : uint
{
/// <summary>
/// The specified items can be copied.
/// </summary>
SFGAO_CANCOPY = 0x00000001,
/// <summary>
/// The specified items can be moved.
/// </summary>
SFGAO_CANMOVE = 0x00000002,
/// <summary>
/// Shortcuts can be created for the specified items. This flag has the same value as DROPEFFECT.
/// The normal use of this flag is to add a Create Shortcut item to the shortcut menu that is displayed
/// during drag-and-drop operations. However, SFGAO_CANLINK also adds a Create Shortcut item to the Microsoft
/// Windows Explorer's File menu and to normal shortcut menus.
/// If this item is selected, your application's IContextMenu::InvokeCommand is invoked with the lpVerb
/// member of the CMINVOKECOMMANDINFO structure set to "link." Your application is responsible for creating the link.
/// </summary>
SFGAO_CANLINK = 0x00000004,
/// <summary>
/// The specified items can be bound to an IStorage interface through IShellFolder::BindToObject.
/// </summary>
SFGAO_STORAGE = 0x00000008,
/// <summary>
/// The specified items can be renamed.
/// </summary>
SFGAO_CANRENAME = 0x00000010,
/// <summary>
/// The specified items can be deleted.
/// </summary>
SFGAO_CANDELETE = 0x00000020,
/// <summary>
/// The specified items have property sheets.
/// </summary>
SFGAO_HASPROPSHEET = 0x00000040,
/// <summary>
/// The specified items are drop targets.
/// </summary>
SFGAO_DROPTARGET = 0x00000100,
/// <summary>
/// This flag is a mask for the capability flags.
/// </summary>
SFGAO_CAPABILITYMASK = 0x00000177,
/// <summary>
/// Windows 7 and later. The specified items are system items.
/// </summary>
SFGAO_SYSTEM = 0x00001000,
/// <summary>
/// The specified items are encrypted.
/// </summary>
SFGAO_ENCRYPTED = 0x00002000,
/// <summary>
/// Indicates that accessing the object = through IStream or other storage interfaces,
/// is a slow operation.
/// Applications should avoid accessing items flagged with SFGAO_ISSLOW.
/// </summary>
SFGAO_ISSLOW = 0x00004000,
/// <summary>
/// The specified items are ghosted icons.
/// </summary>
SFGAO_GHOSTED = 0x00008000,
/// <summary>
/// The specified items are shortcuts.
/// </summary>
SFGAO_LINK = 0x00010000,
/// <summary>
/// The specified folder objects are shared.
/// </summary>
SFGAO_SHARE = 0x00020000,
/// <summary>
/// The specified items are read-only. In the case of folders, this means
/// that new items cannot be created in those folders.
/// </summary>
SFGAO_READONLY = 0x00040000,
/// <summary>
/// The item is hidden and should not be displayed unless the
/// Show hidden files and folders option is enabled in Folder Settings.
/// </summary>
SFGAO_HIDDEN = 0x00080000,
/// <summary>
/// This flag is a mask for the display attributes.
/// </summary>
SFGAO_DISPLAYATTRMASK = 0x000FC000,
/// <summary>
/// The specified folders contain one or more file system folders.
/// </summary>
SFGAO_FILESYSANCESTOR = 0x10000000,
/// <summary>
/// The specified items are folders.
/// </summary>
SFGAO_FOLDER = 0x20000000,
/// <summary>
/// The specified folders or file objects are part of the file system
/// that is, they are files, directories, or root directories).
/// </summary>
SFGAO_FILESYSTEM = 0x40000000,
/// <summary>
/// The specified folders have subfolders = and are, therefore,
/// expandable in the left pane of Windows Explorer).
/// </summary>
SFGAO_HASSUBFOLDER = 0x80000000,
/// <summary>
/// This flag is a mask for the contents attributes.
/// </summary>
SFGAO_CONTENTSMASK = 0x80000000,
/// <summary>
/// When specified as input, SFGAO_VALIDATE instructs the folder to validate that the items
/// pointed to by the contents of apidl exist. If one or more of those items do not exist,
/// IShellFolder::GetAttributesOf returns a failure code.
/// When used with the file system folder, SFGAO_VALIDATE instructs the folder to discard cached
/// properties retrieved by clients of IShellFolder2::GetDetailsEx that may
/// have accumulated for the specified items.
/// </summary>
SFGAO_VALIDATE = 0x01000000,
/// <summary>
/// The specified items are on removable media or are themselves removable devices.
/// </summary>
SFGAO_REMOVABLE = 0x02000000,
/// <summary>
/// The specified items are compressed.
/// </summary>
SFGAO_COMPRESSED = 0x04000000,
/// <summary>
/// The specified items can be browsed in place.
/// </summary>
SFGAO_BROWSABLE = 0x08000000,
/// <summary>
/// The items are nonenumerated items.
/// </summary>
SFGAO_NONENUMERATED = 0x00100000,
/// <summary>
/// The objects contain new content.
/// </summary>
SFGAO_NEWCONTENT = 0x00200000,
/// <summary>
/// It is possible to create monikers for the specified file objects or folders.
/// </summary>
SFGAO_CANMONIKER = 0x00400000,
/// <summary>
/// Not supported.
/// </summary>
SFGAO_HASSTORAGE = 0x00400000,
/// <summary>
/// Indicates that the item has a stream associated with it that can be accessed
/// by a call to IShellFolder::BindToObject with IID_IStream in the riid parameter.
/// </summary>
SFGAO_STREAM = 0x00400000,
/// <summary>
/// Children of this item are accessible through IStream or IStorage.
/// Those children are flagged with SFGAO_STORAGE or SFGAO_STREAM.
/// </summary>
SFGAO_STORAGEANCESTOR = 0x00800000,
/// <summary>
/// This flag is a mask for the storage capability attributes.
/// </summary>
SFGAO_STORAGECAPMASK = 0x70C50008,
/// <summary>
/// Mask used by PKEY_SFGAOFlags to remove certain values that are considered
/// to cause slow calculations or lack context.
/// Equal to SFGAO_VALIDATE | SFGAO_ISSLOW | SFGAO_HASSUBFOLDER.
/// </summary>
SFGAO_PKEYSFGAOMASK = 0x81044000,
}
public enum KNOWNDESTCATEGORY
{
KDC_FREQUENT = 1,
KDC_RECENT
}
public enum SIGDN : uint
{
SIGDN_NORMALDISPLAY = 0x00000000, // SHGDN_NORMAL
SIGDN_PARENTRELATIVEPARSING = 0x80018001, // SHGDN_INFOLDER | SHGDN_FORPARSING
SIGDN_DESKTOPABSOLUTEPARSING = 0x80028000, // SHGDN_FORPARSING
SIGDN_PARENTRELATIVEEDITING = 0x80031001, // SHGDN_INFOLDER | SHGDN_FOREDITING
SIGDN_DESKTOPABSOLUTEEDITING = 0x8004c000, // SHGDN_FORPARSING | SHGDN_FORADDRESSBAR
SIGDN_FILESYSPATH = 0x80058000, // SHGDN_FORPARSING
SIGDN_URL = 0x80068000, // SHGDN_FORPARSING
SIGDN_PARENTRELATIVEFORADDRESSBAR = 0x8007c001, // SHGDN_INFOLDER | SHGDN_FORPARSING | SHGDN_FORADDRESSBAR
SIGDN_PARENTRELATIVE = 0x80080001 // SHGDN_INFOLDER
}
public enum SICHINTF : uint
{
SICHINT_DISPLAY = 0x00000000,
SICHINT_CANONICAL = 0x10000000,
SICHINT_TEST_FILESYSPATH_IF_NOT_EQUAL = 0x20000000,
SICHINT_ALLFIELDS = 0x80000000
}
// IID GUID strings for relevant Shell COM interfaces.
public const string IShellItem = "43826D1E-E718-42EE-BC55-A1E261C37BFE";
public const string IShellItem2 = "7E9FB0D3-919F-4307-AB2E-9B1860310C93";
internal const string IShellFolder = "000214E6-0000-0000-C000-000000000046";
internal const string IShellFolder2 = "93F2F68C-1D1B-11D3-A30E-00C04F79ABD1";
internal const string IShellLinkW = "000214F9-0000-0000-C000-000000000046";
internal const string CShellLink = "00021401-0000-0000-C000-000000000046";
public const string IPropertyStore = "886D8EEB-8CF2-4446-8D02-CDBA1DBDCF99";
public static Guid IObjectArray = new Guid("92CA9DCD-5622-4BBA-A805-5E9F541BD8C9");
}
public struct SHARD
{
public const uint PIDL = 0x00000001;
public const uint PATHA = 0x00000002;
public const uint PATHW = 0x00000003;
}
public struct CSIDL
{
public const int SENDTO = 0x0009;
}
public struct FILEDESCRIPTOR_HEADER
{
public int dwFlags;
public Guid clsid;
public SIZEL sizel;
public POINTL pointl;
public int dwFileAttributes;
public System.Runtime.InteropServices.ComTypes.FILETIME ftCreationTime;
public System.Runtime.InteropServices.ComTypes.FILETIME ftLastAccessTime;
public System.Runtime.InteropServices.ComTypes.FILETIME ftLastWriteTime;
public int nFileSizeHigh;
public int nFileSizeLow;
}
public struct SHGFI
{
public const uint ICON = 0x100;
public const uint LARGEICON = 0x0; // 'Large icon
public const uint SMALLICON = 0x1; // 'Small icon
public const uint USEFILEATTRIBUTES = 0x000000010;
public const uint ADDOVERLAYS = 0x000000020;
public const uint LINKOVERLAY = 0x000008000; // Show shortcut overlay
}
[StructLayout(LayoutKind.Sequential)]
public struct SHFILEINFO
{
public IntPtr hIcon;
public IntPtr iIcon;
public uint dwAttributes;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)]
public string szDisplayName;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 80)]
public string szTypeName;
};
public struct DROPFILES
{
public uint pFiles;
public POINT pt;
[MarshalAs(UnmanagedType.Bool)]
public bool fNC;
[MarshalAs(UnmanagedType.Bool)]
public bool fWide;
} ;
// ShellExecute and FindExecutable error codes
public struct SE_ERR
{
public const int FNF = 2; // file not found
public const int NOASSOC = 31; // no association available
public const int OOM = 8; // out of memory
}
/// <summary>
/// Flags controlling the appearance of a window
/// </summary>
public enum WindowShowCommand : uint
{
/// <summary>
/// Hides the window and activates another window.
/// </summary>
Hide = 0,
/// <summary>
/// Activates and displays the window (including restoring
/// it to its original size and position).
/// </summary>
Normal = 1,
/// <summary>
/// Minimizes the window.
/// </summary>
Minimized = 2,
/// <summary>
/// Maximizes the window.
/// </summary>
Maximized = 3,
/// <summary>
/// Similar to <see cref="Normal"/>, except that the window
/// is not activated.
/// </summary>
ShowNoActivate = 4,
/// <summary>
/// Activates the window and displays it in its current size
/// and position.
/// </summary>
Show = 5,
/// <summary>
/// Minimizes the window and activates the next top-level window.
/// </summary>
Minimize = 6,
/// <summary>
/// Minimizes the window and does not activate it.
/// </summary>
ShowMinimizedNoActivate = 7,
/// <summary>
/// Similar to <see cref="Normal"/>, except that the window is not
/// activated.
/// </summary>
ShowNA = 8,
/// <summary>
/// Activates and displays the window, restoring it to its original
/// size and position.
/// </summary>
Restore = 9,
/// <summary>
/// Sets the show state based on the initial value specified when
/// the process was created.
/// </summary>
Default = 10,
/// <summary>
/// Minimizes a window, even if the thread owning the window is not
/// responding. Use this only to minimize windows from a different
/// thread.
/// </summary>
ForceMinimize = 11
}
}
| |
//-----------------------------------------------------------------------
// <copyright file="ReadOnlyBindingListBase.cs" company="Marimer LLC">
// Copyright (c) Marimer LLC. All rights reserved.
// Website: https://cslanet.com
// </copyright>
// <summary>This is the base class from which readonly collections</summary>
//-----------------------------------------------------------------------
#if NETFX_CORE
using System;
namespace Csla
{
/// <summary>
/// This is the base class from which readonly collections
/// of readonly objects should be derived.
/// </summary>
/// <typeparam name="T">Type of the list class.</typeparam>
/// <typeparam name="C">Type of child objects contained in the list.</typeparam>
[Serializable]
public abstract class ReadOnlyBindingListBase<T, C> : ReadOnlyListBase<T, C>
where T : ReadOnlyBindingListBase<T, C>
{ }
}
#else
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq.Expressions;
using Csla.Properties;
namespace Csla
{
/// <summary>
/// This is the base class from which readonly collections
/// of readonly objects should be derived.
/// </summary>
/// <typeparam name="T">Type of the list class.</typeparam>
/// <typeparam name="C">Type of child objects contained in the list.</typeparam>
[System.Diagnostics.CodeAnalysis.SuppressMessage(
"Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")]
[Serializable()]
public abstract class ReadOnlyBindingListBase<T, C> :
Core.ReadOnlyBindingList<C>, Csla.Core.IReadOnlyCollection,
ICloneable, Server.IDataPortalTarget, Core.IUseApplicationContext
where T : ReadOnlyBindingListBase<T, C>
{
private ApplicationContext ApplicationContext { get; set; }
ApplicationContext Core.IUseApplicationContext.ApplicationContext
{
get => ApplicationContext;
set
{
ApplicationContext = value;
Initialize();
}
}
/// <summary>
/// Creates an instance of the type.
/// </summary>
protected ReadOnlyBindingListBase()
{ }
#region Initialize
/// <summary>
/// Override this method to set up event handlers so user
/// code in a partial class can respond to events raised by
/// generated code.
/// </summary>
protected virtual void Initialize()
{ /* allows subclass to initialize events before any other activity occurs */ }
#endregion
#region ICloneable
object ICloneable.Clone()
{
return GetClone();
}
/// <summary>
/// Creates a clone of the object.
/// </summary>
/// <returns>A new object containing the exact data of the original object.</returns>
[EditorBrowsable(EditorBrowsableState.Advanced)]
protected virtual object GetClone()
{
return Core.ObjectCloner.GetInstance(ApplicationContext).Clone(this);
}
/// <summary>
/// Creates a clone of the object.
/// </summary>
/// <returns>
/// A new object containing the exact data of the original object.
/// </returns>
public T Clone()
{
return (T)GetClone();
}
#endregion
#region Data Access
private void DataPortal_Update()
{
throw new NotSupportedException(Resources.UpdateNotSupportedException);
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "criteria")]
[Delete]
private void DataPortal_Delete(object criteria)
{
throw new NotSupportedException(Resources.DeleteNotSupportedException);
}
/// <summary>
/// Called by the server-side DataPortal prior to calling the
/// requested DataPortal_xyz method.
/// </summary>
/// <param name="e">The DataPortalContext object passed to the DataPortal.</param>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", MessageId = "Member")]
[EditorBrowsable(EditorBrowsableState.Advanced)]
protected virtual void DataPortal_OnDataPortalInvoke(DataPortalEventArgs e)
{
}
/// <summary>
/// Called by the server-side DataPortal after calling the
/// requested DataPortal_xyz method.
/// </summary>
/// <param name="e">The DataPortalContext object passed to the DataPortal.</param>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", MessageId = "Member")]
[EditorBrowsable(EditorBrowsableState.Advanced)]
protected virtual void DataPortal_OnDataPortalInvokeComplete(DataPortalEventArgs e)
{
}
/// <summary>
/// Called by the server-side DataPortal if an exception
/// occurs during data access.
/// </summary>
/// <param name="e">The DataPortalContext object passed to the DataPortal.</param>
/// <param name="ex">The Exception thrown during data access.</param>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", MessageId = "Member")]
[EditorBrowsable(EditorBrowsableState.Advanced)]
protected virtual void DataPortal_OnDataPortalException(DataPortalEventArgs e, Exception ex)
{
}
/// <summary>
/// Called by the server-side DataPortal prior to calling the
/// requested DataPortal_XYZ method.
/// </summary>
/// <param name="e">The DataPortalContext object passed to the DataPortal.</param>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", MessageId = "Member")]
[EditorBrowsable(EditorBrowsableState.Advanced)]
protected virtual void Child_OnDataPortalInvoke(DataPortalEventArgs e)
{
}
/// <summary>
/// Called by the server-side DataPortal after calling the
/// requested DataPortal_XYZ method.
/// </summary>
/// <param name="e">The DataPortalContext object passed to the DataPortal.</param>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", MessageId = "Member")]
[EditorBrowsable(EditorBrowsableState.Advanced)]
protected virtual void Child_OnDataPortalInvokeComplete(DataPortalEventArgs e)
{
}
/// <summary>
/// Called by the server-side DataPortal if an exception
/// occurs during data access.
/// </summary>
/// <param name="e">The DataPortalContext object passed to the DataPortal.</param>
/// <param name="ex">The Exception thrown during data access.</param>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", MessageId = "Member")]
[EditorBrowsable(EditorBrowsableState.Advanced)]
protected virtual void Child_OnDataPortalException(DataPortalEventArgs e, Exception ex)
{
}
#endregion
#region ToArray
/// <summary>
/// Get an array containing all items in the list.
/// </summary>
public C[] ToArray()
{
List<C> result = new List<C>();
foreach (C item in this)
result.Add(item);
return result.ToArray();
}
#endregion
#region IDataPortalTarget Members
void Csla.Server.IDataPortalTarget.CheckRules()
{ }
void Csla.Server.IDataPortalTarget.MarkAsChild()
{ }
void Csla.Server.IDataPortalTarget.MarkNew()
{ }
void Csla.Server.IDataPortalTarget.MarkOld()
{ }
void Csla.Server.IDataPortalTarget.DataPortal_OnDataPortalInvoke(DataPortalEventArgs e)
{
this.DataPortal_OnDataPortalInvoke(e);
}
void Csla.Server.IDataPortalTarget.DataPortal_OnDataPortalInvokeComplete(DataPortalEventArgs e)
{
this.DataPortal_OnDataPortalInvokeComplete(e);
}
void Csla.Server.IDataPortalTarget.DataPortal_OnDataPortalException(DataPortalEventArgs e, Exception ex)
{
this.DataPortal_OnDataPortalException(e, ex);
}
void Csla.Server.IDataPortalTarget.Child_OnDataPortalInvoke(DataPortalEventArgs e)
{
this.Child_OnDataPortalInvoke(e);
}
void Csla.Server.IDataPortalTarget.Child_OnDataPortalInvokeComplete(DataPortalEventArgs e)
{
this.Child_OnDataPortalInvokeComplete(e);
}
void Csla.Server.IDataPortalTarget.Child_OnDataPortalException(DataPortalEventArgs e, Exception ex)
{
this.Child_OnDataPortalException(e, ex);
}
#endregion
}
}
#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.
using System.Diagnostics;
using System.Dynamic.Utils;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.CompilerServices;
using static System.Linq.Expressions.CachedReflectionInfo;
namespace System.Linq.Expressions.Compiler
{
internal partial class LambdaCompiler
{
private void EmitQuoteUnaryExpression(Expression expr)
{
EmitQuote((UnaryExpression)expr);
}
private void EmitQuote(UnaryExpression quote)
{
// emit the quoted expression as a runtime constant
EmitConstant(quote.Operand, quote.Type);
// Heuristic: only emit the tree rewrite logic if we have hoisted
// locals.
if (_scope.NearestHoistedLocals != null)
{
// HoistedLocals is internal so emit as System.Object
EmitConstant(_scope.NearestHoistedLocals, typeof(object));
_scope.EmitGet(_scope.NearestHoistedLocals.SelfVariable);
_ilg.Emit(OpCodes.Call, RuntimeOps_Quote);
if (quote.Type != typeof(Expression))
{
_ilg.Emit(OpCodes.Castclass, quote.Type);
}
}
}
private void EmitThrowUnaryExpression(Expression expr)
{
EmitThrow((UnaryExpression)expr, CompilationFlags.EmitAsDefaultType);
}
private void EmitThrow(UnaryExpression expr, CompilationFlags flags)
{
if (expr.Operand == null)
{
CheckRethrow();
_ilg.Emit(OpCodes.Rethrow);
}
else
{
EmitExpression(expr.Operand);
_ilg.Emit(OpCodes.Throw);
}
EmitUnreachable(expr, flags);
}
private void EmitUnaryExpression(Expression expr, CompilationFlags flags)
{
EmitUnary((UnaryExpression)expr, flags);
}
private void EmitUnary(UnaryExpression node, CompilationFlags flags)
{
if (node.Method != null)
{
EmitUnaryMethod(node, flags);
}
else if (node.NodeType == ExpressionType.NegateChecked && TypeUtils.IsInteger(node.Operand.Type))
{
EmitExpression(node.Operand);
LocalBuilder loc = GetLocal(node.Operand.Type);
_ilg.Emit(OpCodes.Stloc, loc);
_ilg.EmitInt(0);
_ilg.EmitConvertToType(typeof(int), node.Operand.Type, false);
_ilg.Emit(OpCodes.Ldloc, loc);
FreeLocal(loc);
EmitBinaryOperator(ExpressionType.SubtractChecked, node.Operand.Type, node.Operand.Type, node.Type, false);
}
else
{
EmitExpression(node.Operand);
EmitUnaryOperator(node.NodeType, node.Operand.Type, node.Type);
}
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")]
private void EmitUnaryOperator(ExpressionType op, Type operandType, Type resultType)
{
bool operandIsNullable = TypeUtils.IsNullableType(operandType);
if (op == ExpressionType.ArrayLength)
{
_ilg.Emit(OpCodes.Ldlen);
return;
}
if (operandIsNullable)
{
switch (op)
{
case ExpressionType.Not:
{
if (operandType != typeof(bool?))
{
goto case ExpressionType.Negate;
}
Label labEnd = _ilg.DefineLabel();
LocalBuilder loc = GetLocal(operandType);
// store values (reverse order since they are already on the stack)
_ilg.Emit(OpCodes.Stloc, loc);
// test for null
_ilg.Emit(OpCodes.Ldloca, loc);
_ilg.EmitHasValue(operandType);
_ilg.Emit(OpCodes.Brfalse_S, labEnd);
// do op on non-null value
_ilg.Emit(OpCodes.Ldloca, loc);
_ilg.EmitGetValueOrDefault(operandType);
Type nnOperandType = TypeUtils.GetNonNullableType(operandType);
EmitUnaryOperator(op, nnOperandType, typeof(bool));
// construct result
ConstructorInfo ci = resultType.GetConstructor(ArrayOfType_Bool);
_ilg.Emit(OpCodes.Newobj, ci);
_ilg.Emit(OpCodes.Stloc, loc);
_ilg.MarkLabel(labEnd);
_ilg.Emit(OpCodes.Ldloc, loc);
FreeLocal(loc);
return;
}
case ExpressionType.UnaryPlus:
case ExpressionType.NegateChecked:
case ExpressionType.Negate:
case ExpressionType.Increment:
case ExpressionType.Decrement:
case ExpressionType.OnesComplement:
case ExpressionType.IsFalse:
case ExpressionType.IsTrue:
{
Debug.Assert(TypeUtils.AreEquivalent(operandType, resultType));
Label labIfNull = _ilg.DefineLabel();
Label labEnd = _ilg.DefineLabel();
LocalBuilder loc = GetLocal(operandType);
// check for null
_ilg.Emit(OpCodes.Stloc, loc);
_ilg.Emit(OpCodes.Ldloca, loc);
_ilg.EmitHasValue(operandType);
_ilg.Emit(OpCodes.Brfalse_S, labIfNull);
// apply operator to non-null value
_ilg.Emit(OpCodes.Ldloca, loc);
_ilg.EmitGetValueOrDefault(operandType);
Type nnOperandType = TypeUtils.GetNonNullableType(resultType);
EmitUnaryOperator(op, nnOperandType, nnOperandType);
// construct result
ConstructorInfo ci = resultType.GetConstructor(new Type[] { nnOperandType });
_ilg.Emit(OpCodes.Newobj, ci);
_ilg.Emit(OpCodes.Stloc, loc);
_ilg.Emit(OpCodes.Br_S, labEnd);
// if null then create a default one
_ilg.MarkLabel(labIfNull);
_ilg.Emit(OpCodes.Ldloca, loc);
_ilg.Emit(OpCodes.Initobj, resultType);
_ilg.MarkLabel(labEnd);
_ilg.Emit(OpCodes.Ldloc, loc);
FreeLocal(loc);
return;
}
case ExpressionType.TypeAs:
_ilg.Emit(OpCodes.Box, operandType);
_ilg.Emit(OpCodes.Isinst, resultType);
if (TypeUtils.IsNullableType(resultType))
{
_ilg.Emit(OpCodes.Unbox_Any, resultType);
}
return;
default:
throw Error.UnhandledUnary(op);
}
}
else
{
switch (op)
{
case ExpressionType.Not:
if (operandType == typeof(bool))
{
_ilg.Emit(OpCodes.Ldc_I4_0);
_ilg.Emit(OpCodes.Ceq);
}
else
{
_ilg.Emit(OpCodes.Not);
}
break;
case ExpressionType.OnesComplement:
_ilg.Emit(OpCodes.Not);
break;
case ExpressionType.IsFalse:
_ilg.Emit(OpCodes.Ldc_I4_0);
_ilg.Emit(OpCodes.Ceq);
// Not an arithmetic operation -> no conversion
return;
case ExpressionType.IsTrue:
_ilg.Emit(OpCodes.Ldc_I4_1);
_ilg.Emit(OpCodes.Ceq);
// Not an arithmetic operation -> no conversion
return;
case ExpressionType.UnaryPlus:
_ilg.Emit(OpCodes.Nop);
break;
case ExpressionType.Negate:
case ExpressionType.NegateChecked:
_ilg.Emit(OpCodes.Neg);
break;
case ExpressionType.TypeAs:
if (operandType.GetTypeInfo().IsValueType)
{
_ilg.Emit(OpCodes.Box, operandType);
}
_ilg.Emit(OpCodes.Isinst, resultType);
if (TypeUtils.IsNullableType(resultType))
{
_ilg.Emit(OpCodes.Unbox_Any, resultType);
}
// Not an arithmetic operation -> no conversion
return;
case ExpressionType.Increment:
EmitConstantOne(resultType);
_ilg.Emit(OpCodes.Add);
break;
case ExpressionType.Decrement:
EmitConstantOne(resultType);
_ilg.Emit(OpCodes.Sub);
break;
default:
throw Error.UnhandledUnary(op);
}
EmitConvertArithmeticResult(op, resultType);
}
}
private void EmitConstantOne(Type type)
{
switch (type.GetTypeCode())
{
case TypeCode.UInt16:
case TypeCode.UInt32:
case TypeCode.Int16:
case TypeCode.Int32:
_ilg.Emit(OpCodes.Ldc_I4_1);
break;
case TypeCode.Int64:
case TypeCode.UInt64:
_ilg.Emit(OpCodes.Ldc_I8, (long)1);
break;
case TypeCode.Single:
_ilg.Emit(OpCodes.Ldc_R4, 1.0f);
break;
case TypeCode.Double:
_ilg.Emit(OpCodes.Ldc_R8, 1.0d);
break;
default:
// we only have to worry about arithmetic types, see
// TypeUtils.IsArithmetic
throw ContractUtils.Unreachable;
}
}
private void EmitUnboxUnaryExpression(Expression expr)
{
var node = (UnaryExpression)expr;
Debug.Assert(node.Type.GetTypeInfo().IsValueType);
// Unbox_Any leaves the value on the stack
EmitExpression(node.Operand);
_ilg.Emit(OpCodes.Unbox_Any, node.Type);
}
private void EmitConvertUnaryExpression(Expression expr, CompilationFlags flags)
{
EmitConvert((UnaryExpression)expr, flags);
}
private void EmitConvert(UnaryExpression node, CompilationFlags flags)
{
if (node.Method != null)
{
// User-defined conversions are only lifted if both source and
// destination types are value types. The C# compiler gets this wrong.
// In C#, if you have an implicit conversion from int->MyClass and you
// "lift" the conversion to int?->MyClass then a null int? goes to a
// null MyClass. This is contrary to the specification, which states
// that the correct behaviour is to unwrap the int?, throw an exception
// if it is null, and then call the conversion.
//
// We cannot fix this in C# but there is no reason why we need to
// propagate this behavior into the expression tree API. Unfortunately
// this means that when the C# compiler generates the lambda
// (int? i)=>(MyClass)i, we will get different results for converting
// that lambda to a delegate directly and converting that lambda to
// an expression tree and then compiling it. We can live with this
// discrepancy however.
if (node.IsLifted && (!node.Type.GetTypeInfo().IsValueType || !node.Operand.Type.GetTypeInfo().IsValueType))
{
ParameterInfo[] pis = node.Method.GetParametersCached();
Debug.Assert(pis != null && pis.Length == 1);
Type paramType = pis[0].ParameterType;
if (paramType.IsByRef)
{
paramType = paramType.GetElementType();
}
UnaryExpression e = Expression.Convert(
Expression.Call(
node.Method,
Expression.Convert(node.Operand, pis[0].ParameterType)
),
node.Type
);
EmitConvert(e, flags);
}
else
{
EmitUnaryMethod(node, flags);
}
}
else if (node.Type == typeof(void))
{
EmitExpressionAsVoid(node.Operand, flags);
}
else
{
if (TypeUtils.AreEquivalent(node.Operand.Type, node.Type))
{
EmitExpression(node.Operand, flags);
}
else
{
// A conversion is emitted after emitting the operand, no tail call is emitted
EmitExpression(node.Operand);
_ilg.EmitConvertToType(node.Operand.Type, node.Type, node.NodeType == ExpressionType.ConvertChecked);
}
}
}
private void EmitUnaryMethod(UnaryExpression node, CompilationFlags flags)
{
if (node.IsLifted)
{
ParameterExpression v = Expression.Variable(TypeUtils.GetNonNullableType(node.Operand.Type), null);
MethodCallExpression mc = Expression.Call(node.Method, v);
Type resultType = TypeUtils.GetNullableType(mc.Type);
EmitLift(node.NodeType, resultType, mc, new ParameterExpression[] { v }, new Expression[] { node.Operand });
_ilg.EmitConvertToType(resultType, node.Type, false);
}
else
{
EmitMethodCallExpression(Expression.Call(node.Method, node.Operand), flags);
}
}
}
}
| |
// 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.Threading.Tasks;
using Xunit;
namespace System.Net.Sockets.Tests
{
public abstract class Accept<T> : SocketTestHelperBase<T> where T : SocketHelperBase, new()
{
[OuterLoop] // TODO: Issue #11345
[Theory]
[MemberData(nameof(Loopbacks))]
public async Task Accept_Success(IPAddress listenAt)
{
using (Socket listen = new Socket(listenAt.AddressFamily, SocketType.Stream, ProtocolType.Tcp))
{
int port = listen.BindToAnonymousPort(listenAt);
listen.Listen(1);
Task<Socket> acceptTask = AcceptAsync(listen);
Assert.False(acceptTask.IsCompleted);
using (Socket client = new Socket(listenAt.AddressFamily, SocketType.Stream, ProtocolType.Tcp))
{
await ConnectAsync(client, new IPEndPoint(listenAt, port));
Socket accept = await acceptTask;
Assert.NotNull(accept);
Assert.True(accept.Connected);
Assert.Equal(client.LocalEndPoint, accept.RemoteEndPoint);
Assert.Equal(accept.LocalEndPoint, client.RemoteEndPoint);
}
}
}
[OuterLoop] // TODO: Issue #11345
[Theory]
[InlineData(2)]
[InlineData(5)]
public async Task Accept_ConcurrentAcceptsBeforeConnects_Success(int numberAccepts)
{
using (Socket listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
{
listener.Bind(new IPEndPoint(IPAddress.Loopback, 0));
Listen(listener, numberAccepts);
var clients = new Socket[numberAccepts];
var servers = new Task<Socket>[numberAccepts];
try
{
for (int i = 0; i < numberAccepts; i++)
{
clients[i] = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
servers[i] = AcceptAsync(listener);
}
foreach (Socket client in clients)
{
await ConnectAsync(client, listener.LocalEndPoint);
}
await Task.WhenAll(servers);
Assert.All(servers, s => Assert.Equal(TaskStatus.RanToCompletion, s.Status));
Assert.All(servers, s => Assert.NotNull(s.Result));
Assert.All(servers, s => Assert.True(s.Result.Connected));
}
finally
{
foreach (Socket client in clients)
{
client?.Dispose();
}
foreach (Task<Socket> server in servers)
{
if (server?.Status == TaskStatus.RanToCompletion)
{
server.Result.Dispose();
}
}
}
}
}
[OuterLoop] // TODO: Issue #11345
[Theory]
[InlineData(2)]
[InlineData(5)]
public async Task Accept_ConcurrentAcceptsAfterConnects_Success(int numberAccepts)
{
using (Socket listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
{
listener.Bind(new IPEndPoint(IPAddress.Loopback, 0));
Listen(listener, numberAccepts);
var clients = new Socket[numberAccepts];
var clientConnects = new Task[numberAccepts];
var servers = new Task<Socket>[numberAccepts];
try
{
for (int i = 0; i < numberAccepts; i++)
{
clients[i] = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
clientConnects[i] = ConnectAsync(clients[i], listener.LocalEndPoint);
}
for (int i = 0; i < numberAccepts; i++)
{
servers[i] = AcceptAsync(listener);
}
await Task.WhenAll(clientConnects);
Assert.All(clientConnects, c => Assert.Equal(TaskStatus.RanToCompletion, c.Status));
await Task.WhenAll(servers);
Assert.All(servers, s => Assert.Equal(TaskStatus.RanToCompletion, s.Status));
Assert.All(servers, s => Assert.NotNull(s.Result));
Assert.All(servers, s => Assert.True(s.Result.Connected));
}
finally
{
foreach (Socket client in clients)
{
client?.Dispose();
}
foreach (Task<Socket> server in servers)
{
if (server?.Status == TaskStatus.RanToCompletion)
{
server.Result.Dispose();
}
}
}
}
}
[OuterLoop] // TODO: Issue #11345
[Fact]
[ActiveIssue(17209, TestPlatforms.AnyUnix)]
public async Task Accept_WithTargetSocket_Success()
{
if (!SupportsAcceptIntoExistingSocket)
return;
using (Socket listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
using (Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
using (Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
{
int port = listener.BindToAnonymousPort(IPAddress.Loopback);
listener.Listen(1);
Task<Socket> acceptTask = AcceptAsync(listener, server);
client.Connect(IPAddress.Loopback, port);
Socket accepted = await acceptTask;
Assert.Same(server, accepted);
Assert.True(accepted.Connected);
}
}
[ActiveIssue(22808, TargetFrameworkMonikers.NetFramework)]
[ActiveIssue(17209, TestPlatforms.AnyUnix)]
[OuterLoop] // TODO: Issue #11345
[Theory]
[InlineData(false)]
[InlineData(true)]
public async Task Accept_WithTargetSocket_ReuseAfterDisconnect_Success(bool reuseSocket)
{
if (!SupportsAcceptIntoExistingSocket)
return;
// APM mode fails currently. Issue: #22764
if (typeof(T) == typeof(SocketHelperApm))
return;
using (var listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
using (var server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
{
int port = listener.BindToAnonymousPort(IPAddress.Loopback);
listener.Listen(1);
using (var client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
{
Task<Socket> acceptTask = AcceptAsync(listener, server);
client.Connect(IPAddress.Loopback, port);
Socket accepted = await acceptTask;
Assert.Same(server, accepted);
Assert.True(accepted.Connected);
}
server.Disconnect(reuseSocket);
Assert.False(server.Connected);
if (reuseSocket)
{
using (var client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
{
Task<Socket> acceptTask = AcceptAsync(listener, server);
client.Connect(IPAddress.Loopback, port);
Socket accepted = await acceptTask;
Assert.Same(server, accepted);
Assert.True(accepted.Connected);
}
}
else
{
SocketException se = await Assert.ThrowsAsync<SocketException>(() => AcceptAsync(listener, server));
Assert.Equal(SocketError.InvalidArgument, se.SocketErrorCode);
}
}
}
[OuterLoop] // TODO: Issue #11345
[Fact]
[ActiveIssue(17209, TestPlatforms.AnyUnix)]
public void Accept_WithAlreadyBoundTargetSocket_Fails()
{
if (!SupportsAcceptIntoExistingSocket)
return;
using (Socket listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
using (Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
using (Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
{
int port = listener.BindToAnonymousPort(IPAddress.Loopback);
listener.Listen(1);
server.BindToAnonymousPort(IPAddress.Loopback);
Assert.Throws<InvalidOperationException>(() => { AcceptAsync(listener, server); });
}
}
[OuterLoop] // TODO: Issue #11345
[Fact]
[ActiveIssue(17209, TestPlatforms.AnyUnix)]
public async Task Accept_WithInUseTargetSocket_Fails()
{
if (!SupportsAcceptIntoExistingSocket)
return;
using (Socket listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
using (Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
using (Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
{
int port = listener.BindToAnonymousPort(IPAddress.Loopback);
listener.Listen(1);
Task<Socket> acceptTask = AcceptAsync(listener, server);
client.Connect(IPAddress.Loopback, port);
Socket accepted = await acceptTask;
Assert.Same(server, accepted);
Assert.True(accepted.Connected);
Assert.Throws<InvalidOperationException>(() => { AcceptAsync(listener, server); });
}
}
[Fact]
public async Task AcceptAsync_MultipleAcceptsThenDispose_AcceptsThrowAfterDispose()
{
if (UsesSync)
{
return;
}
for (int i = 0; i < 100; i++)
{
using (var listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
{
listener.Bind(new IPEndPoint(IPAddress.Loopback, 0));
listener.Listen(2);
Task accept1 = AcceptAsync(listener);
Task accept2 = AcceptAsync(listener);
listener.Dispose();
await Assert.ThrowsAnyAsync<Exception>(() => accept1);
await Assert.ThrowsAnyAsync<Exception>(() => accept2);
}
}
}
}
public sealed class AcceptSync : Accept<SocketHelperArraySync> { }
public sealed class AcceptSyncForceNonBlocking : Accept<SocketHelperSyncForceNonBlocking> { }
public sealed class AcceptApm : Accept<SocketHelperApm> { }
public sealed class AcceptTask : Accept<SocketHelperTask> { }
public sealed class AcceptEap : Accept<SocketHelperEap> { }
}
| |
using System;
using System.IO;
using System.Windows.Forms;
using DevExpress.XtraBars;
using DevExpress.XtraEditors;
namespace VitaliiPianykh.FileWall.Client
{
public sealed partial class FormMain : DevExpress.XtraBars.Ribbon.RibbonForm, IFormMain
{
private FormMainPage _selectedPage;
public FormMain()
{
InitializeComponent();
}
#region Buttons events handling
// Handler for all "close" buttons.
private void buttonClose_ItemClick(object sender, ItemClickEventArgs e)
{
OnShowMainClicked();
}
#region Main page
private void buttonMain_ItemClick(object sender, ItemClickEventArgs e)
{
OnShowMainClicked();
}
private void buttonShowRules_ItemClick(object sender, ItemClickEventArgs e)
{
if (ShowRulesClicked != null)
ShowRulesClicked(this, EventArgs.Empty);
}
private void buttonPreferences_ItemClick(object sender, ItemClickEventArgs e)
{
if (ShowPreferencesClicked != null)
ShowPreferencesClicked(this, EventArgs.Empty);
}
private void buttonShowEvents_ItemClick(object sender, ItemClickEventArgs e)
{
if (ShowEventsClicked != null)
ShowEventsClicked(this, EventArgs.Empty);
}
private void buttonExitAndShutdown_ItemClick(object sender, ItemClickEventArgs e)
{
OnExitAndShutDownClicked();
}
#endregion
#region Rules page
private void buttonRefreshRules_ItemClick(object sender, ItemClickEventArgs e)
{
if (RefreshRulesClicked != null)
RefreshRulesClicked(this, EventArgs.Empty);
}
#endregion
#region Events Page
private void buttonRefreshEvents_ItemClick(object sender, ItemClickEventArgs e)
{
if (RefreshEventsClicked != null)
RefreshEventsClicked(this, EventArgs.Empty);
}
private void buttonClearEvents_ItemClick(object sender, ItemClickEventArgs e)
{
if (ClearEventsClicked != null)
ClearEventsClicked(this, EventArgs.Empty);
}
private void checkAutoRefreshEvents_CheckedChanged(object sender, ItemClickEventArgs e)
{
if (AutoRefreshEventsCheckChanged != null)
AutoRefreshEventsCheckChanged(this, EventArgs.Empty);
}
private void buttonShowEventDetail_ItemClick(object sender, ItemClickEventArgs e)
{
if (ShowEventDetailsClicked != null)
ShowEventDetailsClicked(this, EventArgs.Empty);
}
private void buttonSaveEvents_ItemClick(object sender, ItemClickEventArgs e)
{
if (dialogSaveEvents.ShowDialog() == DialogResult.Cancel)
return;
var ea = new ExportEventsEventArgs();
if (ExportEventsClicked != null)
ExportEventsClicked(this, ea);
File.WriteAllText(dialogSaveEvents.FileName, ea.CSV);
}
#endregion
#endregion
#region Mininimizing to tray functionality
private void FormMain_VisibleChanged(object sender, EventArgs e)
{
if (Visible)
OnShowMainClicked();
else
// Remove all controls from client area.
clientPanel.Controls.Clear();
}
private void FormMain_Shown(object sender, EventArgs e)
{
Hide();
}
private void FormMain_FormClosing(object sender, FormClosingEventArgs e)
{
if (e.CloseReason != CloseReason.UserClosing)
return;
Hide();
e.Cancel = true;
}
private void notifyIcon_DoubleClick(object sender, EventArgs e)
{
Show();
Focus();
Activate();
}
private void toolStripMenuItemShow_Click(object sender, EventArgs e)
{
Show();
Focus();
Activate();
}
private void toolStripMenuItemShutdown_Click(object sender, EventArgs e)
{
OnExitAndShutDownClicked();
}
#endregion
#region Implementation of IFormMain
public event EventHandler ShowMainClicked;
public event EventHandler ShowRulesClicked;
public event EventHandler ShowPreferencesClicked;
public event EventHandler ShowEventsClicked;
public event EventHandler CloseAllClicked;
public event EventHandler RefreshRulesClicked;
public event EventHandler RefreshEventsClicked;
public event EventHandler ShowEventDetailsClicked;
public event EventHandler ClearEventsClicked;
public event EventHandler AutoRefreshEventsCheckChanged;
public event EventHandler<ExportEventsEventArgs> ExportEventsClicked;
public event EventHandler ExitAndShutDownClicked;
public object DisplayedControl
{
get
{
if (clientPanel.Controls.Count == 0)
return null;
return clientPanel.Controls[0];
}
private set
{
clientPanel.Controls.Clear();
if (value != null)
clientPanel.Controls.Add((Control) value);
}
}
private MainViewControl _MainViewControl;
private RulesetGrid _RulesetGrid;
private PreferencesControl _PreferencesControl;
private LogViewControl _LogViewControl;
public FormMainPage SelectedPage
{
get { return _selectedPage; }
set
{
switch (value)
{
case FormMainPage.Main:
if(_MainViewControl == null) // Cache controls.
_MainViewControl = new MainViewControl { Dock = DockStyle.Fill };
DisplayedControl = _MainViewControl;
ribbon.SelectedPage = ribbonPageMain;
ribbonPageRules.Visible = false;
ribbonPagePreferences.Visible = false;
ribbonPageEvents.Visible = false;
pageCategoryRules.Visible = false;
pageCategoryPreferences.Visible = false;
pageCategoryEvents.Visible = false;
break;
case FormMainPage.Rules:
if (_RulesetGrid == null) // Cache controls.
_RulesetGrid = new RulesetGrid() { Dock = DockStyle.Fill };
DisplayedControl = _RulesetGrid;
ribbonPageRules.Visible = true;
pageCategoryRules.Visible = true;
ribbon.SelectedPage = ribbonPageRules;
break;
case FormMainPage.Preferences:
if (_PreferencesControl == null) // Cache controls.
_PreferencesControl = new PreferencesControl { Dock = DockStyle.Fill };
DisplayedControl = _PreferencesControl;
ribbonPagePreferences.Visible = true;
pageCategoryPreferences.Visible = true;
ribbon.SelectedPage = ribbonPagePreferences;
break;
case FormMainPage.Events:
if (_LogViewControl == null) // Cache controls.
_LogViewControl = new LogViewControl { Dock = DockStyle.Fill };
DisplayedControl = _LogViewControl;
ribbonPageEvents.Visible = true;
pageCategoryEvents.Visible = true;
ribbon.SelectedPage = ribbonPageEvents;
break;
}
_selectedPage = value;
}
}
public bool AutoRefreshEvents { get { return checkAutoRefreshEvents.Checked; } }
public void ShowMessageBox(string message)
{
XtraMessageBox.Show(message, Text, MessageBoxButtons.OK, MessageBoxIcon.Information);
}
#endregion
#region Event invokators
private void OnShowMainClicked()
{
if (ShowMainClicked != null)
ShowMainClicked(this, EventArgs.Empty);
}
private void OnExitAndShutDownClicked()
{
if (ExitAndShutDownClicked != null)
ExitAndShutDownClicked(this, EventArgs.Empty);
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Input.Touch;
using Microsoft.Xna.Framework.Media;
using CosmosCombat.AI;
using System.IO.IsolatedStorage;
using System.Xml;
using System.Reflection;
namespace CosmosCombat
{
public enum SelectionState
{
Selection,Target
}
public enum GameState
{
Loading,MainMenu,Game,Pause,LevelSelection,Options,Credits,AfterGame,Tutorial
}
/// <summary>
/// This is the main type for your game
/// </summary>
public class GameBase : Microsoft.Xna.Framework.Game
{
GraphicsDeviceManager graphics;
SpriteBatch spriteBatch;
Texture2D Fleet;
Texture2D BG;
Texture2D MainMenuBorders;
Texture2D Logo;
Texture2D BlackBoarder;
Texture2D[] Planet;
Texture2D MuteChecked;
Texture2D MuteUnchecked;
Texture2D MuteEffectsChecked;
Texture2D MuteEffectsUnchecked;
Texture2D Victory;
Texture2D Defeat;
bool Won;
Texture2D Shadow;
Texture2D Silhoute;
Texture2D Tutorial;
int CurrentTutorial=1;
SpriteFont GameFont;
Song Soundtrack;
GameManger Manager;
GameState GameState;
MenuManager Menu;
MenuManager PauseMenu;
MenuManager LevelSelection;
MenuManager OptionsMenu;
List<Planet> Selected = new List<Planet>();
SelectionState SelectionState;
AI.AI Ai;
Random rnd = new Random();
bool SoundTracksEnabled;
int PlanetsDiscovered=1;
int CurrentPlanet = 1;
public GameBase()
{
graphics = new GraphicsDeviceManager(this);
Content.RootDirectory = "Content";
graphics.PreferredBackBufferFormat = SurfaceFormat.Color;
graphics.PreferredBackBufferWidth = 800;
graphics.PreferredBackBufferHeight = 480;
graphics.IsFullScreen = true;
graphics.PreferMultiSampling = true;
graphics.SupportedOrientations = DisplayOrientation.LandscapeLeft;
// Frame rate is 30 fps by default for Windows Phone.
//TargetElapsedTime = TimeSpan.FromTicks(333333);
// Extend battery life under lock.
InactiveSleepTime = TimeSpan.FromSeconds(1);
}
/// <summary>
/// Allows the game to perform any initialization it needs to before starting to run.
/// This is where it can query for any required services and load any non-graphic
/// related content. Calling base.Initialize will enumerate through any components
/// and initialize them as well.
/// </summary>
protected override void Initialize()
{
// TODO: Add your initialization logic here
Manager = new GameManger();
Menu = new MenuManager();
PauseMenu = new MenuManager();
SelectionState = SelectionState.Selection;
GameState = GameState.MainMenu;
Ai = new EasyAI();
SoundTracksEnabled = MediaPlayer.GameHasControl;
base.Initialize();
}
/// <summary>
/// LoadContent will be called once per game and is the place to load
/// all of your content.
/// </summary>
protected override void LoadContent()
{
// Create a new SpriteBatch, which can be used to draw textures.
spriteBatch = new SpriteBatch(GraphicsDevice);
GameFont = Content.Load<SpriteFont>("GameFont");
Fleet = Content.Load<Texture2D>("plane_white");
BG = Content.Load<Texture2D>(String.Format("Backgrounds\\bg{0}",rnd.Next(1,7)));
MainMenuBorders = Content.Load<Texture2D>("Menues\\menu");
Planet = new Texture2D[3];
for (int i = 1; i <= 3; i++)
{
Planet[i-1] = Content.Load<Texture2D>(String.Format("Planets\\new_p{0}",i));
}
Logo = Content.Load<Texture2D>("logo");
Tutorial = Content.Load<Texture2D>("Tutorials\\tutorial1");
Shadow = Content.Load<Texture2D>("Planets\\shadow");
MuteUnchecked = Content.Load<Texture2D>("Menues\\mute_music_unchecked");
//MuteEffectsUnchecked = Content.Load<Texture2D>("Menues\\mute_effects_unchecked");
MuteChecked = Content.Load<Texture2D>("Menues\\Click\\mute_music_checked");
//MuteEffectsChecked = Content.Load<Texture2D>("Menues\\Click\\mute_effects_checked");
Silhoute = Content.Load<Texture2D>("selected3");
Defeat = Content.Load<Texture2D>("defeat");
Victory = Content.Load<Texture2D>("victory");
Color[] Black = new Color[800 * (Logo.Height+20)];
for (int i = 0; i < Black.Length; i++)
{
Black[i] = Color.Black;
}
BlackBoarder = new Texture2D(GraphicsDevice, 800, Logo.Height + 20);
BlackBoarder.SetData(Black);
if (SoundTracksEnabled)
{
MediaPlayer.MediaStateChanged += new EventHandler<EventArgs>(MediaPlayer_MediaStateChanged);
Soundtrack = Content.Load<Song>(String.Format("Sound\\SoundTrack{0}", rnd.Next(1, 4)));
MediaPlayer.Play(Soundtrack);
}
#region Buttons Create
Button button_continue = new Button(Content.Load<Texture2D>("Menues\\bt_continue"), Content.Load<Texture2D>("Menues\\Click\\bt_continue_red"), new Vector2(400,130));
button_continue.OnClick += ContinuePress;
Button button_newgame = new Button(Content.Load<Texture2D>("Menues\\bt_newgame"), Content.Load<Texture2D>("Menues\\Click\\bt_newgame_red"), new Vector2(400, 200));
button_newgame.OnClick += NewGamePress;
Button button_options = new Button(Content.Load<Texture2D>("Menues\\bt_options"), Content.Load<Texture2D>("Menues\\Click\\bt_options_red"), new Vector2(400, 270));
button_options.OnClick = GoToOptionsPress;
Button button_credits = new Button(Content.Load<Texture2D>("Menues\\bt_credits"), Content.Load<Texture2D>("Menues\\Click\\bt_credits_red"), new Vector2(400, 340));
button_credits.OnClick = CreditsPress;
Button button_pause_continue = new Button(Content.Load<Texture2D>("Menues\\bt_continue"), Content.Load<Texture2D>("Menues\\Click\\bt_continue_red"), new Vector2(400, 130));
button_pause_continue.OnClick += UnpausePress;
Menu.Buttons.Add(button_continue);
Menu.Buttons.Add(button_newgame);
Menu.Buttons.Add(button_options);
Menu.Buttons.Add(button_credits);
PauseMenu.Buttons.Add(button_pause_continue);
LevelSelection = new MenuManager();
for (int i = 1; i <= 7; i++)
{
string file=String.Format("LevelButtons\\lvl{0}", i);
Texture2D Texture = Content.Load<Texture2D>(file);
Button button = new Button(Texture,Texture,new Vector2(i*105f -26.25f,110));
button.Scale = 0.90f;
button.Tag = i;
button.OnClick = LevelSelectionButtonClick;
LevelSelection.Buttons.Add(button);
}
for (int i = 1; i <= 7; i++)
{
string file = String.Format("LevelButtons\\lvl{0}", i + 7);
Texture2D Texture = Content.Load<Texture2D>(file);
Button button = new Button(Texture, Texture, new Vector2(i * 105f-26.25f, 210));
button.Scale = 0.90f;
button.Tag = i+7;
button.OnClick = LevelSelectionButtonClick;
LevelSelection.Buttons.Add(button);
}
for (int i = 1; i <= 6; i++)
{
string file = String.Format("LevelButtons\\lvl{0}", i + 14);
Texture2D Texture = Content.Load<Texture2D>(file);
Button button = new Button(Texture, Texture, new Vector2(i * 105f + 26.25f, 310));
button.Scale = 0.90f;
button.Tag = i + 14;
button.OnClick = LevelSelectionButtonClick;
LevelSelection.Buttons.Add(button);
}
string f = String.Format("LevelButtons\\lvl{0}", 21);
Texture2D t = Content.Load<Texture2D>(f);
Button b = new Button(t, t, new Vector2(400, 420));
b.Scale = 1f;
b.Tag = 21;
b.OnClick = LevelSelectionButtonClick;
LevelSelection.Buttons.Add(b);
LevelSelection.Overlay = Content.Load<Texture2D>("lvl_completed");
LevelSelection.OverlayOrigin = new Vector2(58, 58);
OptionsMenu = new MenuManager();
Button muteMusic = new Button(MuteUnchecked, MuteUnchecked, new Vector2(400, 130));
muteMusic.OnClick = MuteMusic;
muteMusic.Tag = 0;
//Button muteEffects = new Button(MuteEffectsUnchecked, MuteEffectsUnchecked, new Vector2(400, 170));
//muteEffects.OnClick = MuteEffects;
//muteEffects.Tag = 0;
//OptionsMenu.Buttons.Add(muteEffects);
OptionsMenu.Buttons.Add(muteMusic);
#endregion
// TODO: use this.Content to load your game content here
}
void MediaPlayer_MediaStateChanged(object sender, EventArgs e)
{
if (MediaPlayer.State == MediaState.Stopped||MediaPlayer.State==MediaState.Paused)
{
Soundtrack = Content.Load<Song>(String.Format("Sound\\SoundTrack{0}",rnd.Next(1,4)));
MediaPlayer.Play(Soundtrack);
}
}
List<Planet> LoadMap(string map)
{
List<Planet> mapPlanets = new List<Planet>();
XmlReader xmlReader = XmlReader.Create(map);
xmlReader.ReadStartElement();
while (xmlReader.Read())
{
/*Read planet header*/
if (xmlReader.LocalName == "Planet" && xmlReader.IsStartElement())
{
/*Read the ID element*/
xmlReader.Read();
xmlReader.MoveToElement();
xmlReader.ReadStartElement("ID");
int ID = xmlReader.ReadContentAsInt();
/*Read the owner element*/
xmlReader.Read();
xmlReader.MoveToElement();
xmlReader.ReadStartElement("Owner");
string owner = xmlReader.ReadContentAsString();
/*Read the forces element*/
xmlReader.Read();
xmlReader.MoveToElement();
xmlReader.ReadStartElement("Forces");
int forces = xmlReader.ReadContentAsInt();
/*Read the growth element*/
xmlReader.Read();
xmlReader.MoveToElement();
xmlReader.ReadStartElement("Growth");
int growth = xmlReader.ReadContentAsInt();
/*Read the growth cooldown element*/
xmlReader.Read();
xmlReader.MoveToElement();
xmlReader.ReadStartElement("GrowthCooldown");
int growthcd = xmlReader.ReadContentAsInt();
/*Read the size element*/
xmlReader.Read();
xmlReader.MoveToElement();
xmlReader.ReadStartElement("Size");
float size = xmlReader.ReadContentAsFloat();
/*Read the Position element*/
xmlReader.Read();
xmlReader.MoveToElement();
xmlReader.ReadStartElement("Position");
Vector2 Position = new Vector2();
/*Read the X element*/
xmlReader.Read();
xmlReader.MoveToElement();
xmlReader.ReadStartElement("X");
Position.X = xmlReader.ReadContentAsInt();
/*Read the Y element*/
xmlReader.Read();
xmlReader.MoveToElement();
xmlReader.ReadStartElement("Y");
Position.Y = xmlReader.ReadContentAsInt();
Planet p = new Planet();
p.ID = ID;
p.Position = Position;
p.Growth = growth;
p.GrowthCounter = p.GrowthReset = growthcd;
p.Owner=(PlayerType)Enum.Parse(typeof(PlayerType),owner,false);
p.Forces.Add(p.Owner, forces);
p.PlanetSize = size;
p.InStateOfWar = false;
if (p.PlanetSize <= 0.45f)
p.Texture = Planet[0];
else if (p.PlanetSize >= 0.45f && p.PlanetSize <= 0.7f)
p.Texture = Planet[2];
else
p.Texture = Planet[1];
mapPlanets.Add(p);
}
}
return mapPlanets;
}
/// <summary>
/// UnloadContent will be called once per game and is the place to unload
/// all content.
/// </summary>
protected override void UnloadContent()
{
// TODO: Unload any non ContentManager content here
}
/// <summary>
/// Allows the game to run logic such as updating the world,
/// checking for collisions, gathering input, and playing audio.
/// </summary>
/// <param name="gameTime">Provides a snapshot of timing values.</param>
protected override void Update(GameTime gameTime)
{
// Allows the game to exit
if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
if (GameState == GameState.Game)
{
GameState = GameState.Pause;
}
else if (GameState == GameState.AfterGame)
{
GameState = GameState.LevelSelection;
}
else if (GameState == GameState.Pause || GameState == GameState.LevelSelection || GameState == GameState.Options || GameState == GameState.Credits||GameState==GameState.Tutorial)
{
GameState = GameState.MainMenu;
}
else
{
this.Exit();
}
switch (GameState)
{
case CosmosCombat.GameState.Game:
UpdateGame();
break;
case CosmosCombat.GameState.MainMenu:
UpdateMainMenu();
break;
case CosmosCombat.GameState.LevelSelection:
UpdateLevelSelection();
break;
case CosmosCombat.GameState.Pause:
UpdatePause();
break;
case CosmosCombat.GameState.Options:
UpdateOptions();
break;
case CosmosCombat.GameState.AfterGame:
UpdateAfterLevel();
break;
case CosmosCombat.GameState.Tutorial:
UpdateTutorial();
break;
}
base.Update(gameTime);
}
protected override void OnExiting(object sender, EventArgs args)
{
SaveProgress();
base.OnExiting(sender, args);
}
void LoadProgress()
{
IsolatedStorageFile file = IsolatedStorageFile.GetUserStoreForApplication();
bool Exists=file.FileExists("CosmosCombatSave.xml");
if (Exists)
{
IsolatedStorageFileStream stream = file.OpenFile("CosmosCombatSave.xml", System.IO.FileMode.Open);
XmlReader xmlReader = XmlReader.Create(stream);
xmlReader.ReadStartElement();
while (xmlReader.Read())
{
/*Read planet header*/
if (xmlReader.LocalName == "SaveData" && xmlReader.IsStartElement())
{
xmlReader.Read();
xmlReader.MoveToElement();
xmlReader.ReadStartElement("Discovered");
PlanetsDiscovered = xmlReader.ReadContentAsInt();
}
}
stream.Close();
return;
}
else
{
PlanetsDiscovered = 1;
}
}
void SaveProgress()
{
IsolatedStorageFile file = IsolatedStorageFile.GetUserStoreForApplication();
IsolatedStorageFileStream stream= file.OpenFile("CosmosCombatSave.xml", System.IO.FileMode.Create);
XmlWriterSettings settings = new XmlWriterSettings();
settings.Indent = true;
XmlWriter writer = XmlWriter.Create(stream, settings);
writer.WriteStartElement("Save");
writer.WriteStartElement("SaveData");
writer.WriteElementString("Discovered", PlanetsDiscovered.ToString());
writer.WriteEndElement();
writer.WriteFullEndElement();
writer.Flush();
writer.Close();
stream.Close();
}
void ContinuePress(object sender, EventArgs e)
{
LoadProgress();
foreach (Button button in LevelSelection.Buttons)
{
if (button.Tag > PlanetsDiscovered)
button.Draw = false;
if (button.Tag < PlanetsDiscovered)
button.DrawOverlay = true;
else
button.DrawOverlay = false;
}
GameState = GameState.LevelSelection;
}
void NewGamePress(object sender, EventArgs e)
{
PlanetsDiscovered = 1;
foreach (Button button in LevelSelection.Buttons)
{
if (button.Tag > PlanetsDiscovered)
button.Draw = false;
if (button.Tag < PlanetsDiscovered)
button.DrawOverlay = true;
else
button.DrawOverlay = false;
}
GameState = GameState.LevelSelection;
}
void LevelDone()
{
Won = false;
if (Manager.GetLooser() == PlayerType.AI)
{
Won = true;
if(CurrentPlanet + 1>PlanetsDiscovered)
PlanetsDiscovered = CurrentPlanet + 1;
foreach (Button button in LevelSelection.Buttons)
{
if (button.Tag > PlanetsDiscovered)
button.Draw = false;
else
button.Draw = true;
if (button.Tag < PlanetsDiscovered)
button.DrawOverlay = true;
}
}
SaveProgress();
GameState = GameState.AfterGame;
}
void CreditsPress(object sender, EventArgs e)
{
GameState = GameState.Credits;
}
void GoToOptionsPress(object sender, EventArgs e)
{
GameState = GameState.Options;
}
void LevelSelectionButtonClick(object sender, EventArgs e)
{
BG = Content.Load<Texture2D>(String.Format("Backgrounds\\bg{0}", rnd.Next(1, 7)));
Manager.State.Planets.Clear();
Manager.State.Fleets.Clear();
Selected.Clear();
Manager.State.AIPlanets.Clear();
Manager.State.NeutralPlanets.Clear();
Manager.State.PlayerPlanets.Clear();
Button b = sender as Button;
if(b.Tag!=21)
Manager.State.Planets.AddRange(LoadMap(String.Format("Maps\\map{0}.xml", b.Tag)));
else
{
if(rnd.NextDouble()<0.1)
Manager.State.Planets.AddRange(LoadMap(String.Format("Maps\\map{0}.xml", 22)));
else
Manager.State.Planets.AddRange(LoadMap(String.Format("Maps\\map{0}.xml", b.Tag)));
}
CurrentPlanet = b.Tag;
GameState = GameState.Game;
if (CurrentPlanet <= 7)
{
Manager.AIAttackBias = 0.5f;
Manager.PlayerAttackBias = 1.5f;
Ai = new EasyAI();
}
else if (CurrentPlanet > 7 && CurrentPlanet <= 14)
{
Manager.AIAttackBias = 0.75f;
Manager.PlayerAttackBias = 1.25f;
Ai = new MediumAI();
}
else if (CurrentPlanet > 14 && CurrentPlanet <= 20)
{
Manager.AIAttackBias = 1f;
Manager.PlayerAttackBias = 1;
Ai = new HardAI();
}
else
{
Manager.AIAttackBias = 1.25f;
Manager.PlayerAttackBias = 1f;
Ai = new InsaneAI();
}
if (CurrentPlanet == 1)
GameState = GameState.Tutorial;
}
void UnpausePress(object sender, EventArgs e)
{
GameState = GameState.Game;
}
void MuteMusic(object sender, EventArgs e)
{
Button b = sender as Button;
if (b.Tag == 0)
{
b.Normal = MuteChecked;
b.Click = MuteChecked;
b.Tag = 1;
if (SoundTracksEnabled)
{
MediaPlayer.IsMuted = true;
}
}
else
{
b.Normal = MuteUnchecked;
b.Click = MuteUnchecked;
b.Tag = 0;
if (SoundTracksEnabled)
{
MediaPlayer.IsMuted = false;
}
}
}
void MuteEffects(object sender, EventArgs e)
{
Button b = sender as Button;
if (b.Tag == 0)
{
b.Normal = MuteEffectsChecked;
b.Click = MuteEffectsChecked;
b.Tag = 1;
}
else
{
b.Normal = MuteEffectsUnchecked;
b.Click = MuteEffectsUnchecked;
b.Tag = 0;
}
}
protected void UpdateMainMenu()
{
Menu.Update(new Rectangle(-200, -200, 0, 0), false);
TouchCollection touchCollection = TouchPanel.GetState();
foreach (TouchLocation tl in touchCollection)
{
if (tl.State == TouchLocationState.Moved)
{
Menu.Update(new Rectangle((int)tl.Position.X,(int)tl.Position.Y,20,20),false);
}
else if (tl.State == TouchLocationState.Released)
{
Menu.Update(new Rectangle((int)tl.Position.X, (int)tl.Position.Y, 20, 20), true);
}
}
}
protected void UpdatePause()
{
PauseMenu.Update(new Rectangle(-200, -200, 0, 0), false);
TouchCollection touchCollection = TouchPanel.GetState();
foreach (TouchLocation tl in touchCollection)
{
if (tl.State == TouchLocationState.Moved)
{
PauseMenu.Update(new Rectangle((int)tl.Position.X, (int)tl.Position.Y, 20, 20), false);
}
else if (tl.State == TouchLocationState.Released)
{
PauseMenu.Update(new Rectangle((int)tl.Position.X, (int)tl.Position.Y, 20, 20), true);
}
}
}
protected void UpdateGame()
{
TouchCollection touchCollection = TouchPanel.GetState();
foreach (TouchLocation tl in touchCollection)
{
if (tl.State == TouchLocationState.Moved)
{
if (SelectionState == SelectionState.Selection)
{
foreach (Planet planet in Manager.State.Planets)
{
if (planet.Owner == PlayerType.Player && Vector2.Distance(tl.Position, planet.Position) < planet.PlanetSize * 64)
{
if (Selected.Contains(planet))
continue;
Selected.Add(planet);
break;
}
}
}
}
else if (tl.State == TouchLocationState.Released)
{
if (SelectionState == SelectionState.Selection)
{
SelectionState = SelectionState.Target;
continue;
}
foreach (Planet planet in Manager.State.Planets)
{
if (Vector2.Distance(tl.Position, planet.Position) < planet.PlanetSize * 64 && Selected.Count > 0)
{
foreach (Planet selected in Selected)
//if (selected.Owner == PlayerType.Player)
//{
Manager.SendFleet(selected.Forces[PlayerType.Player] / 2, selected, planet);
//}
break;
}
}
SelectionState = SelectionState.Selection;
Selected.Clear();
}
}
Ai.Update(Manager.State, Manager);
Manager.Update();
List<Planet> NotOwned = new List<Planet>();
foreach (Planet p in Selected)
{
if (p.Owner != PlayerType.Player)
NotOwned.Add(p);
}
foreach (Planet p in NotOwned)
{
Selected.Remove(p);
}
if (Manager.GameEnd())
{
LevelDone();
}
}
protected void UpdateLevelSelection()
{
LevelSelection.Update(new Rectangle(-200, -200, 0, 0), false);
TouchCollection touchCollection = TouchPanel.GetState();
foreach (TouchLocation tl in touchCollection)
{
if (tl.State == TouchLocationState.Moved)
{
LevelSelection.Update(new Rectangle((int)tl.Position.X, (int)tl.Position.Y, 20, 20), false);
}
else if (tl.State == TouchLocationState.Released)
{
LevelSelection.Update(new Rectangle((int)tl.Position.X, (int)tl.Position.Y, 20, 20), true);
}
}
}
protected void UpdateOptions()
{
OptionsMenu.Update(new Rectangle(-200, -200, 0, 0), false);
TouchCollection touchCollection = TouchPanel.GetState();
foreach (TouchLocation tl in touchCollection)
{
if (tl.State == TouchLocationState.Moved)
{
OptionsMenu.Update(new Rectangle((int)tl.Position.X, (int)tl.Position.Y, 20, 20), false);
}
else if (tl.State == TouchLocationState.Released)
{
OptionsMenu.Update(new Rectangle((int)tl.Position.X, (int)tl.Position.Y, 20, 20), true);
}
}
}
protected void UpdateAfterLevel()
{
TouchCollection touchCollection = TouchPanel.GetState();
foreach (TouchLocation tl in touchCollection)
{
if (tl.State == TouchLocationState.Released)
{
GameState = GameState.LevelSelection;
}
}
}
protected void UpdateTutorial()
{
TouchCollection touchCollection = TouchPanel.GetState();
foreach (TouchLocation tl in touchCollection)
{
if (tl.State == TouchLocationState.Pressed)
{
CurrentTutorial++;
if (CurrentTutorial > 6)
{
GameState = GameState.Game;
CurrentTutorial = 1;
Tutorial = Content.Load<Texture2D>(String.Format("Tutorials\\tutorial{0}", CurrentTutorial));
}
else
{
Tutorial = Content.Load<Texture2D>(String.Format("Tutorials\\tutorial{0}", CurrentTutorial));
}
}
}
}
/// <summary>
/// This is called when the game should draw itself.
/// </summary>
/// <param name="gameTime">Provides a snapshot of timing values.</param>
protected override void Draw(GameTime gameTime)
{
GraphicsDevice.Clear(Color.Black);
spriteBatch.Begin(SpriteSortMode.Deferred,BlendState.AlphaBlend);
switch (GameState)
{
case CosmosCombat.GameState.Game:
DrawGame();
break;
case CosmosCombat.GameState.MainMenu:
DrawMainMenu();
break;
case CosmosCombat.GameState.Pause:
DrawPause();
break;
case CosmosCombat.GameState.LevelSelection:
DrawLevelSelection();
break;
case CosmosCombat.GameState.Options:
DrawOptions();
break;
case CosmosCombat.GameState.Credits:
DrawCredits();
break;
case CosmosCombat.GameState.AfterGame:
DrawAfterLevel();
break;
case CosmosCombat.GameState.Tutorial:
DrawTutorial();
break;
}
spriteBatch.End();
base.Draw(gameTime);
}
protected void DrawGame()
{
spriteBatch.Draw(BG, Vector2.Zero, Color.White);
foreach (Planet planet in Manager.State.Planets)
{
Color DrawColor = Color.White;
switch (planet.Owner)
{
case PlayerType.Neutral:
DrawColor = Color.White;
break;
case PlayerType.Player:
DrawColor = Color.LightGreen;
break;
case PlayerType.AI:
DrawColor = Color.DarkRed;
break;
}
spriteBatch.Draw(Shadow, planet.Position, null, Color.White, 0f, new Vector2(72, 72), planet.PlanetSize, SpriteEffects.None, 1f);
spriteBatch.Draw(planet.Texture, planet.Position, null, DrawColor, 0f, new Vector2(62, 62), planet.PlanetSize, SpriteEffects.None, 1f);
if (!planet.InStateOfWar)
spriteBatch.DrawString(GameFont, planet.Forces[planet.Owner].ToString(), planet.Position, DrawColor);
else
{
spriteBatch.DrawString(GameFont, "WAR!", planet.Position - GameFont.MeasureString("WAR!") / 2, Color.Red);
spriteBatch.DrawString(GameFont, planet.Forces[PlayerType.AI].ToString(), planet.Position + new Vector2(62, -62), Color.DarkRed);
spriteBatch.DrawString(GameFont, planet.Forces[PlayerType.Player].ToString(), planet.Position - new Vector2(62, -62) - GameFont.MeasureString(planet.Forces[PlayerType.Player].ToString()), Color.LightGreen);
}
}
foreach (Fleet fleet in Manager.State.Fleets)
{
Color DrawColor = Color.White;
switch (fleet.Owner)
{
case PlayerType.Neutral:
DrawColor = Color.White;
break;
case PlayerType.Player:
DrawColor = Color.LightGreen;
break;
case PlayerType.AI:
DrawColor = Color.DarkRed;
break;
}
spriteBatch.Draw(Fleet, fleet.Position, null, DrawColor, fleet.Rotation, new Vector2(32, 32), 0.25f, SpriteEffects.None, 0f);
foreach (Vector2 p in fleet.Positions)
{
spriteBatch.Draw(Fleet, p + fleet.Position, null, DrawColor, fleet.Rotation, new Vector2(32, 32), 0.25f, SpriteEffects.None, 0f);
}
}
spriteBatch.End();
spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend);
foreach (Planet planet in Manager.State.Planets)
{
if (Selected.Contains(planet))
{
spriteBatch.Draw(Silhoute, planet.Position, null, Color.White, 0f, new Vector2(128, 128), planet.PlanetSize, SpriteEffects.None, 0f);
}
}
}
protected void DrawPause()
{
DrawGame();
spriteBatch.Draw(BlackBoarder, Vector2.Zero, Color.White);
spriteBatch.Draw(Logo, new Vector2(288.5f, 10), Color.White);
spriteBatch.Draw(MainMenuBorders, new Vector2(400, 240), null, Color.White, 0f, new Vector2(151, 176.5f), 1f, SpriteEffects.None, 1f);
PauseMenu.Draw(spriteBatch);
}
protected void DrawMainMenu()
{
spriteBatch.Draw(BG, Vector2.Zero, Color.White);
spriteBatch.Draw(BlackBoarder, Vector2.Zero, Color.White);
spriteBatch.Draw(Logo, new Vector2(288.5f,10), Color.White);
spriteBatch.Draw(MainMenuBorders, new Vector2(400, 240), null, Color.White, 0f, new Vector2(151,176.5f), 1f, SpriteEffects.None, 1f);
Menu.Draw(spriteBatch);
}
protected void DrawLevelSelection()
{
spriteBatch.Draw(BG, Vector2.Zero, Color.White);
spriteBatch.Draw(BlackBoarder, Vector2.Zero, Color.White);
spriteBatch.Draw(Logo, new Vector2(288.5f, 10), Color.White);
LevelSelection.Draw(spriteBatch);
}
protected void DrawOptions()
{
spriteBatch.Draw(BG, Vector2.Zero, Color.White);
spriteBatch.Draw(BlackBoarder, Vector2.Zero, Color.White);
spriteBatch.Draw(Logo, new Vector2(288.5f, 10), Color.White);
spriteBatch.Draw(MainMenuBorders, new Vector2(400, 240), null, Color.White, 0f, new Vector2(151, 176.5f), 1f, SpriteEffects.None, 1f);
OptionsMenu.Draw(spriteBatch);
}
protected void DrawCredits()
{
spriteBatch.Draw(BG, Vector2.Zero, Color.White);
spriteBatch.Draw(BlackBoarder, Vector2.Zero, Color.White);
spriteBatch.Draw(Logo, new Vector2(288.5f, 10), Color.White);
string CreditsString="Programming by: Pavlo Malynin\nDesign by: Constantine Malynin\nContact Email: [email protected]\nTwitter: @CosmosCombat";
spriteBatch.DrawString(GameFont, CreditsString, new Vector2(400,150), Color.LightBlue,0f,GameFont.MeasureString(CreditsString)/2,1f,SpriteEffects.None,0f);
string Version = Assembly.GetExecutingAssembly().FullName.Split('=')[1].Split(',')[0];
spriteBatch.DrawString(GameFont, Version, new Vector2(800, 480), Color.LightBlue, 0f, GameFont.MeasureString(Version), 1f, SpriteEffects.None, 0f);
}
protected void DrawAfterLevel()
{
spriteBatch.Draw(BG, Vector2.Zero, Color.White);
spriteBatch.Draw(BlackBoarder, Vector2.Zero, Color.White);
spriteBatch.Draw(Logo, new Vector2(288.5f, 10), Color.White);
if (Won)
{
spriteBatch.Draw(Victory, new Vector2(400, 240), null, Color.White, 0f, new Vector2(95, 22), 1f, SpriteEffects.None, 0f);
}
else
{
spriteBatch.Draw(Defeat, new Vector2(400, 240), null, Color.White, 0f, new Vector2(77.5f, 21), 1f, SpriteEffects.None, 0f);
}
}
protected void DrawTutorial()
{
spriteBatch.Draw(Tutorial, Vector2.Zero, Color.White);
}
}
}
| |
using Bridge.Test.NUnit;
using System;
namespace Bridge.ClientTest.SimpleTypes
{
[Category(Constants.MODULE_VERSION)]
[TestFixture(TestNameFormat = "Version - {0}")]
public class TestVersion
{
[Test(ExpectedCount = 42)]
public static void TestConstructors()
{
var v1 = new Version();
Assert.True(v1 != null, "v1 created");
Assert.AreEqual(0, v1.Major, "v1.Major 0");
Assert.AreEqual(0, v1.Minor, "v1.Minor 0");
Assert.AreEqual(-1, v1.Build, "v1.Build -1");
Assert.AreEqual(-1, v1.Revision, "v1.Revision -1");
Assert.AreEqual(-1, v1.MajorRevision, "v1.MajorRevision -1");
Assert.AreEqual(-1, v1.MinorRevision, "v1.MinorRevision -1");
var v2 = new Version("2.4.1128.2");
Assert.True(v2 != null, "v2 created");
Assert.AreEqual(2, v2.Major, "v2.Major 2");
Assert.AreEqual(4, v2.Minor, "v2.Minor 4");
Assert.AreEqual(1128, v2.Build, "v2.Build 1128");
Assert.AreEqual(2, v2.Revision, "v2.Revision 2");
Assert.AreEqual(0, v2.MajorRevision, "v2.MajorRevision 0");
Assert.AreEqual(2, v2.MinorRevision, "v2.MinorRevision 2");
var v3 = new Version("2.4.1128.65537");
Assert.True(v3 != null, "v3 created");
Assert.AreEqual(2, v3.Major, "v3.Major 2");
Assert.AreEqual(4, v3.Minor, "v3.Minor 4");
Assert.AreEqual(1128, v3.Build, "v3.Build 1128");
Assert.AreEqual(65537, v3.Revision, "v3.Revision 65537");
Assert.AreEqual(1, v3.MajorRevision, "v3.MajorRevision 1");
Assert.AreEqual(1, v3.MinorRevision, "v3.MinorRevision 1");
var v4 = new Version(20, 10);
Assert.True(v4 != null, "v4 created");
Assert.AreEqual(20, v4.Major, "v4.Major 20");
Assert.AreEqual(10, v4.Minor, "v4.Minor 10");
Assert.AreEqual(-1, v4.Build, "v4.Build -1");
Assert.AreEqual(-1, v4.Revision, "v4.Revision -1");
Assert.AreEqual(-1, v4.MajorRevision, "v4.MajorRevision -1");
Assert.AreEqual(-1, v4.MinorRevision, "v4.MinorRevision -1");
var v5 = new Version(200, 100, 300);
Assert.True(v5 != null, "v5 created");
Assert.AreEqual(200, v5.Major, "v5.Major 200");
Assert.AreEqual(100, v5.Minor, "v5.Minor 100");
Assert.AreEqual(300, v5.Build, "v5.Build 300");
Assert.AreEqual(-1, v5.Revision, "v5.Revision -1");
Assert.AreEqual(-1, v5.MajorRevision, "v5.MajorRevision -1");
Assert.AreEqual(-1, v5.MinorRevision, "v5.MinorRevision -1");
var v6 = new Version(2000, 1000, 3000, (345 << 16) + 4000);
Assert.True(v6 != null, "v6 created");
Assert.AreEqual(2000, v6.Major, "v6.Major 2000");
Assert.AreEqual(1000, v6.Minor, "v6.Minor 1000");
Assert.AreEqual(3000, v6.Build, "v6.Build 3000");
Assert.AreEqual(22613920, v6.Revision, "v6.Revision (345 << 16) + 4000 = 22613920");
Assert.AreEqual(345, v6.MajorRevision, "v6.MajorRevision 345");
Assert.AreEqual(4000, v6.MinorRevision, "v6.MinorRevision 4");
}
[Test(ExpectedCount = 13)]
public static void TestCloneCompare()
{
var v1 = new Version(1, 2, 3, (4 << 16) + 5);
var o = v1.Clone();
Assert.True(o != null, "v1 Cloned");
var v2 = o as Version;
Assert.True(v2 != null, "v1 Cloned as Version");
Assert.AreEqual(1, v2.Major, "v2.Major 1");
Assert.AreEqual(2, v2.Minor, "v2.Minor 2");
Assert.AreEqual(3, v2.Build, "v2.Build 3");
Assert.AreEqual(262149, v2.Revision, "v2.Revision (4 << 16) + 5 = 262149");
Assert.AreEqual(4, v2.MajorRevision, "v2.MajorRevision 4");
Assert.AreEqual(5, v2.MinorRevision, "v2.MinorRevision 5");
var v3 = new Version(1, 2, 2, (4 << 16) + 5);
Assert.AreEqual(1, v1.CompareTo(v3), "v1.CompareTo(v3)");
var v4 = new Version(1, 3, 3, (4 << 16) + 5);
Assert.AreEqual(-1, v1.CompareTo(v4), "v1.CompareTo(v4)");
Assert.AreEqual(0, v1.CompareTo(o), "v1.CompareTo(o)");
Assert.AreEqual(0, v1.CompareTo(v2), "v1.CompareTo(v2)");
Assert.AreNotEqual(0, v1.CompareTo(null), "v1.CompareTo(null)");
}
[Test(ExpectedCount = 9)]
public static void TestEqualsGetHashCode()
{
var v1 = new Version(100, 200, 300, (400 << 16) + 500);
var v2 = new Version(100, 200, 300, (400 << 16) + 500);
var v3 = new Version(101, 200, 300, (400 << 16) + 500);
var o = new object();
object o2 = v2;
Assert.True(v1.Equals(v2), "v1.Equals(v2)");
Assert.False(v1.Equals(v3), "v1.Equals(v3)");
Assert.False(v1.Equals(o), "v1.Equals(o)");
Assert.False(v1.Equals(null), "v1.Equals(null)");
Assert.False(v1.Equals(100), "v1.Equals(100)");
Assert.True(v1.Equals(o2), "v1.Equals(o2)");
Assert.AreEqual(1283637748, v1.GetHashCode(), "v1.GetHashCode()");
Assert.AreEqual(1283637748, v2.GetHashCode(), "v2.GetHashCode()");
Assert.AreEqual(1552073204, v3.GetHashCode(), "v3.GetHashCode()");
}
[Test(ExpectedCount = 10)]
public static void TestToString()
{
var v1 = new Version("2.4.1128.65537");
var v2 = new Version(100, 200, 300, (400 << 16) + 500);
var v3 = new Version(100, 200, 300);
var v4 = new Version(100, 200);
var v5 = new Version();
Assert.AreEqual("2.4.1128.65537", v1.ToString(), "c1.ToString()");
Assert.AreEqual("100.200.300.26214900", v2.ToString(), "c2.ToString()");
Assert.AreEqual("100.200.300", v3.ToString(), "c3.ToString()");
Assert.AreEqual("100.200", v4.ToString(), "c4.ToString()");
Assert.AreEqual("0.0", v5.ToString(), "c5.ToString()");
Assert.AreEqual("2", v1.ToString(1), "c1.ToString(1)");
Assert.AreEqual("2.4", v1.ToString(2), "c1.ToString(2)");
Assert.AreEqual("2.4.1128", v1.ToString(3), "c1.ToString(3)");
Assert.AreEqual("2.4.1128.65537", v1.ToString(4), "c1.ToString(4)");
Assert.Throws(() =>
{
v1.ToString(5);
}, "c1.ToString(5)");
}
[Test(ExpectedCount = 6)]
public static void TestParse()
{
var s1 = "105.1.1128.65547";
var v1 = new Version(s1);
Assert.AreEqual(v1.ToString(), Version.Parse(s1).ToString(), "Version.Parse(s1)");
var s2 = "105.1";
var v2 = new Version(s2);
Assert.AreEqual(v2.ToString(), Version.Parse(s2).ToString(), "Version.Parse(s2)");
Assert.Throws(() =>
{
Version.Parse("12,123.23.12");
}, "Version.Parse(\"12,123.23.12\")");
Version vp1;
var b1 = Version.TryParse("12,123.23.12", out vp1);
Assert.AreEqual(false, b1, "b1");
Version vp2;
var b2 = Version.TryParse("12.3.2.1", out vp2);
Assert.AreEqual(true, b2, "b2");
Assert.AreEqual("12.3.2.1", vp2.ToString(), "vp2.ToString()");
}
[Test(ExpectedCount = 30)]
public static void TestOperators()
{
var v1 = new Version(1, 2, 3, (4 << 16) + 5);
var v2 = new Version(1, 2, 3, (4 << 16) + 5);
var v3 = new Version(1, 3, 3, (4 << 16) + 5);
Assert.True(v1 == v2, "v1 == v2");
Assert.False(v1 != v2, "v1 != v2");
Assert.False(v1 > v2, "v1 > v2");
Assert.True(v1 >= v2, "v1 >= v2");
Assert.False(v1 < v2, "v1 < v2");
Assert.True(v1 <= v2, "v1 <= v2");
Assert.False(v1 == v3, "v1 == v3");
Assert.True(v1 != v3, "v1 != v3");
Assert.False(v1 > v3, "v1 > v3");
Assert.False(v1 >= v3, "v1 >= v3");
Assert.True(v1 < v3, "v1 < v3");
Assert.True(v1 <= v3, "v1 <= v3");
Assert.False(v1 == null, "v1 == null");
Assert.True(v1 != null, "v1 != null");
Assert.Throws<ArgumentNullException>(() => { var b = v1 > null; }, "v1 > null");
Assert.Throws<ArgumentNullException>(() => { var b = v1 >= null; }, "v1 >= null");
Assert.False(v1 < null, "v1 < null");
Assert.False(v1 <= null, "v1 <= null");
Assert.False(null == v3, "null == v3");
Assert.True(null != v3, "null != v3");
Assert.False(null > v3, "null > v3");
Assert.False(null >= v3, "null >= v3");
Assert.Throws<ArgumentNullException>(() => { var b = null < v3; }, "null < v3");
Assert.Throws<ArgumentNullException>(() => { var b = null <= v3; }, "null <= v3");
Version v4 = null;
Version v5 = null;
Assert.True(v4 == v5, "v4 == v5");
Assert.False(v4 != v5, "v4 != v5");
Assert.Throws<ArgumentNullException>(() => { var b = v4 > v5; }, "v4 > v5");
Assert.Throws<ArgumentNullException>(() => { var b = v4 >= v5; }, "v4 >= v5");
Assert.Throws<ArgumentNullException>(() => { var b = v4 < v5; }, "v4 < v5");
Assert.Throws<ArgumentNullException>(() => { var b = v4 <= v5; }, "v4 <= v5");
}
}
}
| |
// 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: Convenient wrapper for an array, an offset, and
** a count. Ideally used in streams & collections.
** Net Classes will consume an array of these.
**
**
===========================================================*/
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
namespace System
{
// Note: users should make sure they copy the fields out of an ArraySegment onto their stack
// then validate that the fields describe valid bounds within the array. This must be done
// because assignments to value types are not atomic, and also because one thread reading
// three fields from an ArraySegment may not see the same ArraySegment from one call to another
// (ie, users could assign a new value to the old location).
[Serializable]
[System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")]
public struct ArraySegment<T> : IList<T>, IReadOnlyList<T>
{
// Do not replace the array allocation with Array.Empty. We don't want to have the overhead of
// instantiating another generic type in addition to ArraySegment<T> for new type parameters.
public static ArraySegment<T> Empty { get; } = new ArraySegment<T>(new T[0]);
private readonly T[] _array; // Do not rename (binary serialization)
private readonly int _offset; // Do not rename (binary serialization)
private readonly int _count; // Do not rename (binary serialization)
public ArraySegment(T[] array)
{
if (array == null)
throw new ArgumentNullException(nameof(array));
_array = array;
_offset = 0;
_count = array.Length;
}
public ArraySegment(T[] array, int offset, int count)
{
if (array == null)
throw new ArgumentNullException(nameof(array));
if (offset < 0)
throw new ArgumentOutOfRangeException(nameof(offset), SR.ArgumentOutOfRange_NeedNonNegNum);
if (count < 0)
throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum);
if (array.Length - offset < count)
throw new ArgumentException(SR.Argument_InvalidOffLen);
_array = array;
_offset = offset;
_count = count;
}
public T[] Array => _array;
public int Offset => _offset;
public int Count => _count;
public T this[int index]
{
get
{
if ((uint)index >= (uint)_count)
{
throw new ArgumentOutOfRangeException(nameof(index));
}
return _array[_offset + index];
}
set
{
if ((uint)index >= (uint)_count)
{
throw new ArgumentOutOfRangeException(nameof(index));
}
_array[_offset + index] = value;
}
}
public Enumerator GetEnumerator()
{
ThrowInvalidOperationIfDefault();
return new Enumerator(this);
}
public override int GetHashCode()
{
if (_array == null)
{
return 0;
}
int hash = 5381;
hash = System.Numerics.Hashing.HashHelpers.Combine(hash, _offset);
hash = System.Numerics.Hashing.HashHelpers.Combine(hash, _count);
// The array hash is expected to be an evenly-distributed mixture of bits,
// so rather than adding the cost of another rotation we just xor it.
hash ^= _array.GetHashCode();
return hash;
}
public void CopyTo(T[] destination) => CopyTo(destination, 0);
public void CopyTo(T[] destination, int destinationIndex)
{
ThrowInvalidOperationIfDefault();
System.Array.Copy(_array, _offset, destination, destinationIndex, _count);
}
public void CopyTo(ArraySegment<T> destination)
{
ThrowInvalidOperationIfDefault();
destination.ThrowInvalidOperationIfDefault();
if (_count > destination._count)
{
ThrowHelper.ThrowArgumentException_DestinationTooShort();
}
System.Array.Copy(_array, _offset, destination._array, destination._offset, _count);
}
public override bool Equals(Object obj)
{
if (obj is ArraySegment<T>)
return Equals((ArraySegment<T>)obj);
else
return false;
}
public bool Equals(ArraySegment<T> obj)
{
return obj._array == _array && obj._offset == _offset && obj._count == _count;
}
public ArraySegment<T> Slice(int index)
{
ThrowInvalidOperationIfDefault();
if ((uint)index > (uint)_count)
{
throw new ArgumentOutOfRangeException(nameof(index));
}
return new ArraySegment<T>(_array, _offset + index, _count - index);
}
public ArraySegment<T> Slice(int index, int count)
{
ThrowInvalidOperationIfDefault();
if ((uint)index > (uint)_count || (uint)count > (uint)(_count - index))
{
throw new ArgumentOutOfRangeException(nameof(index));
}
return new ArraySegment<T>(_array, _offset + index, count);
}
public T[] ToArray()
{
ThrowInvalidOperationIfDefault();
if (_count == 0)
{
return Empty._array;
}
var array = new T[_count];
System.Array.Copy(_array, _offset, array, 0, _count);
return array;
}
public static bool operator ==(ArraySegment<T> a, ArraySegment<T> b)
{
return a.Equals(b);
}
public static bool operator !=(ArraySegment<T> a, ArraySegment<T> b)
{
return !(a == b);
}
public static implicit operator ArraySegment<T>(T[] array) => new ArraySegment<T>(array);
#region IList<T>
T IList<T>.this[int index]
{
get
{
ThrowInvalidOperationIfDefault();
if (index < 0 || index >= _count)
throw new ArgumentOutOfRangeException(nameof(index));
return _array[_offset + index];
}
set
{
ThrowInvalidOperationIfDefault();
if (index < 0 || index >= _count)
throw new ArgumentOutOfRangeException(nameof(index));
_array[_offset + index] = value;
}
}
int IList<T>.IndexOf(T item)
{
ThrowInvalidOperationIfDefault();
int index = System.Array.IndexOf<T>(_array, item, _offset, _count);
Debug.Assert(index == -1 ||
(index >= _offset && index < _offset + _count));
return index >= 0 ? index - _offset : -1;
}
void IList<T>.Insert(int index, T item)
{
throw new NotSupportedException();
}
void IList<T>.RemoveAt(int index)
{
throw new NotSupportedException();
}
#endregion
#region IReadOnlyList<T>
T IReadOnlyList<T>.this[int index]
{
get
{
ThrowInvalidOperationIfDefault();
if (index < 0 || index >= _count)
throw new ArgumentOutOfRangeException(nameof(index));
return _array[_offset + index];
}
}
#endregion IReadOnlyList<T>
#region ICollection<T>
bool ICollection<T>.IsReadOnly
{
get
{
// the indexer setter does not throw an exception although IsReadOnly is true.
// This is to match the behavior of arrays.
return true;
}
}
void ICollection<T>.Add(T item)
{
throw new NotSupportedException();
}
void ICollection<T>.Clear()
{
throw new NotSupportedException();
}
bool ICollection<T>.Contains(T item)
{
ThrowInvalidOperationIfDefault();
int index = System.Array.IndexOf<T>(_array, item, _offset, _count);
Debug.Assert(index == -1 ||
(index >= _offset && index < _offset + _count));
return index >= 0;
}
void ICollection<T>.CopyTo(T[] array, int arrayIndex)
{
ThrowInvalidOperationIfDefault();
System.Array.Copy(_array, _offset, array, arrayIndex, _count);
}
bool ICollection<T>.Remove(T item)
{
throw new NotSupportedException();
}
#endregion
#region IEnumerable<T>
IEnumerator<T> IEnumerable<T>.GetEnumerator() => GetEnumerator();
#endregion
#region IEnumerable
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
#endregion
private void ThrowInvalidOperationIfDefault()
{
if (_array == null)
{
throw new InvalidOperationException(SR.InvalidOperation_NullArray);
}
}
public struct Enumerator : IEnumerator<T>
{
private readonly T[] _array;
private readonly int _start;
private readonly int _end; // cache Offset + Count, since it's a little slow
private int _current;
internal Enumerator(ArraySegment<T> arraySegment)
{
Debug.Assert(arraySegment.Array != null);
Debug.Assert(arraySegment.Offset >= 0);
Debug.Assert(arraySegment.Count >= 0);
Debug.Assert(arraySegment.Offset + arraySegment.Count <= arraySegment.Array.Length);
_array = arraySegment._array;
_start = arraySegment._offset;
_end = _start + arraySegment._count;
_current = _start - 1;
}
public bool MoveNext()
{
if (_current < _end)
{
_current++;
return (_current < _end);
}
return false;
}
public T Current
{
get
{
if (_current < _start)
throw new InvalidOperationException(SR.InvalidOperation_EnumNotStarted);
if (_current >= _end)
throw new InvalidOperationException(SR.InvalidOperation_EnumEnded);
return _array[_current];
}
}
object IEnumerator.Current => Current;
void IEnumerator.Reset()
{
_current = _start - 1;
}
public void Dispose()
{
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Reflection;
using Xunit;
namespace System.Linq.Expressions.Tests
{
public static class BinaryNullablePowerTests
{
#region Test methods
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckNullableBytePowerTest(bool useInterpreter)
{
byte?[] array = new byte?[] { null, 0, 1, byte.MaxValue };
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < array.Length; j++)
{
VerifyNullableBytePower(array[i], array[j], useInterpreter);
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckNullableSBytePowerTest(bool useInterpreter)
{
sbyte?[] array = new sbyte?[] { null, 0, 1, -1, sbyte.MinValue, sbyte.MaxValue };
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < array.Length; j++)
{
VerifyNullableSBytePower(array[i], array[j], useInterpreter);
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckNullableUShortPowerTest(bool useInterpreter)
{
ushort?[] array = new ushort?[] { null, 0, 1, ushort.MaxValue };
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < array.Length; j++)
{
VerifyNullableUShortPower(array[i], array[j], useInterpreter);
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckNullableShortPowerTest(bool useInterpreter)
{
short?[] array = new short?[] { null, 0, 1, -1, short.MinValue, short.MaxValue };
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < array.Length; j++)
{
VerifyNullableShortPower(array[i], array[j], useInterpreter);
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckNullableUIntPowerTest(bool useInterpreter)
{
uint?[] array = new uint?[] { null, 0, 1, uint.MaxValue };
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < array.Length; j++)
{
VerifyNullableUIntPower(array[i], array[j], useInterpreter);
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckNullableIntPowerTest(bool useInterpreter)
{
int?[] array = new int?[] { null, 0, 1, -1, int.MinValue, int.MaxValue };
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < array.Length; j++)
{
VerifyNullableIntPower(array[i], array[j], useInterpreter);
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckNullableULongPowerTest(bool useInterpreter)
{
ulong?[] array = new ulong?[] { null, 0, 1, ulong.MaxValue };
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < array.Length; j++)
{
VerifyNullableULongPower(array[i], array[j], useInterpreter);
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckNullableLongPowerTest(bool useInterpreter)
{
long?[] array = new long?[] { null, 0, 1, -1, long.MinValue, long.MaxValue };
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < array.Length; j++)
{
VerifyNullableLongPower(array[i], array[j], useInterpreter);
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckNullableFloatPowerTest(bool useInterpreter)
{
float?[] array = new float?[] { null, 0, 1, -1, float.MinValue, float.MaxValue, float.Epsilon, float.NegativeInfinity, float.PositiveInfinity, float.NaN };
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < array.Length; j++)
{
VerifyNullableFloatPower(array[i], array[j], useInterpreter);
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckNullableDoublePowerTest(bool useInterpreter)
{
double?[] array = new double?[] { null, 0, 1, -1, double.MinValue, double.MaxValue, double.Epsilon, double.NegativeInfinity, double.PositiveInfinity, double.NaN };
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < array.Length; j++)
{
VerifyNullableDoublePower(array[i], array[j], useInterpreter);
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckNullableDecimalPowerTest(bool useInterpreter)
{
decimal?[] array = new decimal?[] { null, decimal.Zero, decimal.One, decimal.MinusOne, decimal.MinValue, decimal.MaxValue };
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < array.Length; j++)
{
VerifyNullableDecimalPower(array[i], array[j], useInterpreter);
}
}
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CheckNullableCharPowerTest(bool useInterpreter)
{
char?[] array = new char?[] { null, '\0', '\b', 'A', '\uffff' };
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < array.Length; j++)
{
VerifyNullableCharPower(array[i], array[j], useInterpreter);
}
}
}
#endregion
#region Test verifiers
private static void VerifyNullableBytePower(byte? a, byte? b, bool useInterpreter)
{
Expression<Func<byte?>> e =
Expression.Lambda<Func<byte?>>(
Expression.Power(
Expression.Constant(a, typeof(byte?)),
Expression.Constant(b, typeof(byte?)),
typeof(BinaryNullablePowerTests).GetTypeInfo().GetDeclaredMethod("PowerByte")
));
Func<byte?> f = e.Compile(useInterpreter);
if (a.HasValue & b.HasValue)
Assert.Equal(PowerByte(a.GetValueOrDefault(), b.GetValueOrDefault()), f());
else
Assert.Null(f());
}
private static void VerifyNullableSBytePower(sbyte? a, sbyte? b, bool useInterpreter)
{
Expression<Func<sbyte?>> e =
Expression.Lambda<Func<sbyte?>>(
Expression.Power(
Expression.Constant(a, typeof(sbyte?)),
Expression.Constant(b, typeof(sbyte?)),
typeof(BinaryNullablePowerTests).GetTypeInfo().GetDeclaredMethod("PowerSByte")
));
Func<sbyte?> f = e.Compile(useInterpreter);
if (a.HasValue & b.HasValue)
Assert.Equal(PowerSByte(a.GetValueOrDefault(), b.GetValueOrDefault()), f());
else
Assert.Null(f());
}
private static void VerifyNullableUShortPower(ushort? a, ushort? b, bool useInterpreter)
{
Expression<Func<ushort?>> e =
Expression.Lambda<Func<ushort?>>(
Expression.Power(
Expression.Constant(a, typeof(ushort?)),
Expression.Constant(b, typeof(ushort?)),
typeof(BinaryNullablePowerTests).GetTypeInfo().GetDeclaredMethod("PowerUShort")
));
Func<ushort?> f = e.Compile(useInterpreter);
if (a.HasValue & b.HasValue)
Assert.Equal(PowerUShort(a.GetValueOrDefault(), b.GetValueOrDefault()), f());
else
Assert.Null(f());
}
private static void VerifyNullableShortPower(short? a, short? b, bool useInterpreter)
{
Expression<Func<short?>> e =
Expression.Lambda<Func<short?>>(
Expression.Power(
Expression.Constant(a, typeof(short?)),
Expression.Constant(b, typeof(short?)),
typeof(BinaryNullablePowerTests).GetTypeInfo().GetDeclaredMethod("PowerShort")
));
Func<short?> f = e.Compile(useInterpreter);
if (a.HasValue & b.HasValue)
Assert.Equal(PowerShort(a.GetValueOrDefault(), b.GetValueOrDefault()), f());
else
Assert.Null(f());
}
private static void VerifyNullableUIntPower(uint? a, uint? b, bool useInterpreter)
{
Expression<Func<uint?>> e =
Expression.Lambda<Func<uint?>>(
Expression.Power(
Expression.Constant(a, typeof(uint?)),
Expression.Constant(b, typeof(uint?)),
typeof(BinaryNullablePowerTests).GetTypeInfo().GetDeclaredMethod("PowerUInt")
));
Func<uint?> f = e.Compile(useInterpreter);
if (a.HasValue & b.HasValue)
Assert.Equal(PowerUInt(a.GetValueOrDefault(), b.GetValueOrDefault()), f());
else
Assert.Null(f());
}
private static void VerifyNullableIntPower(int? a, int? b, bool useInterpreter)
{
Expression<Func<int?>> e =
Expression.Lambda<Func<int?>>(
Expression.Power(
Expression.Constant(a, typeof(int?)),
Expression.Constant(b, typeof(int?)),
typeof(BinaryNullablePowerTests).GetTypeInfo().GetDeclaredMethod("PowerInt")
));
Func<int?> f = e.Compile(useInterpreter);
if (a.HasValue & b.HasValue)
Assert.Equal(PowerInt(a.GetValueOrDefault(), b.GetValueOrDefault()), f());
else
Assert.Null(f());
}
private static void VerifyNullableULongPower(ulong? a, ulong? b, bool useInterpreter)
{
Expression<Func<ulong?>> e =
Expression.Lambda<Func<ulong?>>(
Expression.Power(
Expression.Constant(a, typeof(ulong?)),
Expression.Constant(b, typeof(ulong?)),
typeof(BinaryNullablePowerTests).GetTypeInfo().GetDeclaredMethod("PowerULong")
));
Func<ulong?> f = e.Compile(useInterpreter);
if (a.HasValue & b.HasValue)
Assert.Equal(PowerULong(a.GetValueOrDefault(), b.GetValueOrDefault()), f());
else
Assert.Null(f());
}
private static void VerifyNullableLongPower(long? a, long? b, bool useInterpreter)
{
Expression<Func<long?>> e =
Expression.Lambda<Func<long?>>(
Expression.Power(
Expression.Constant(a, typeof(long?)),
Expression.Constant(b, typeof(long?)),
typeof(BinaryNullablePowerTests).GetTypeInfo().GetDeclaredMethod("PowerLong")
));
Func<long?> f = e.Compile(useInterpreter);
if (a.HasValue & b.HasValue)
Assert.Equal(PowerLong(a.GetValueOrDefault(), b.GetValueOrDefault()), f());
else
Assert.Null(f());
}
private static void VerifyNullableFloatPower(float? a, float? b, bool useInterpreter)
{
Expression<Func<float?>> e =
Expression.Lambda<Func<float?>>(
Expression.Power(
Expression.Constant(a, typeof(float?)),
Expression.Constant(b, typeof(float?)),
typeof(BinaryNullablePowerTests).GetTypeInfo().GetDeclaredMethod("PowerFloat")
));
Func<float?> f = e.Compile(useInterpreter);
if (a.HasValue & b.HasValue)
Assert.Equal(PowerFloat(a.GetValueOrDefault(), b.GetValueOrDefault()), f());
else
Assert.Null(f());
}
private static void VerifyNullableDoublePower(double? a, double? b, bool useInterpreter)
{
Expression<Func<double?>> e =
Expression.Lambda<Func<double?>>(
Expression.Power(
Expression.Constant(a, typeof(double?)),
Expression.Constant(b, typeof(double?)),
typeof(BinaryNullablePowerTests).GetTypeInfo().GetDeclaredMethod("PowerDouble")
));
Func<double?> f = e.Compile(useInterpreter);
if (a.HasValue & b.HasValue)
Assert.Equal(PowerDouble(a.GetValueOrDefault(), b.GetValueOrDefault()), f());
else
Assert.Null(f());
}
private static void VerifyNullableDecimalPower(decimal? a, decimal? b, bool useInterpreter)
{
Expression<Func<decimal?>> e =
Expression.Lambda<Func<decimal?>>(
Expression.Power(
Expression.Constant(a, typeof(decimal?)),
Expression.Constant(b, typeof(decimal?)),
typeof(BinaryNullablePowerTests).GetTypeInfo().GetDeclaredMethod("PowerDecimal")
));
Func<decimal?> f = e.Compile(useInterpreter);
if (a.HasValue & b.HasValue)
{
decimal expected = 0;
try
{
expected = PowerDecimal(a.GetValueOrDefault(), b.GetValueOrDefault());
}
catch (OverflowException)
{
Assert.Throws<OverflowException>(() => f());
return;
}
Assert.Equal(expected, f());
}
else
Assert.Null(f());
}
private static void VerifyNullableCharPower(char? a, char? b, bool useInterpreter)
{
Expression<Func<char?>> e =
Expression.Lambda<Func<char?>>(
Expression.Power(
Expression.Constant(a, typeof(char?)),
Expression.Constant(b, typeof(char?)),
typeof(BinaryNullablePowerTests).GetTypeInfo().GetDeclaredMethod("PowerChar")
));
Func<char?> f = e.Compile(useInterpreter);
if (a.HasValue & b.HasValue)
Assert.Equal(PowerChar(a.GetValueOrDefault(), b.GetValueOrDefault()), f());
else
Assert.Null(f());
}
#endregion
#region Helper methods
public static byte PowerByte(byte a, byte b)
{
return (byte)Math.Pow(a, b);
}
public static sbyte PowerSByte(sbyte a, sbyte b)
{
return (sbyte)Math.Pow(a, b);
}
public static ushort PowerUShort(ushort a, ushort b)
{
return (ushort)Math.Pow(a, b);
}
public static short PowerShort(short a, short b)
{
return (short)Math.Pow(a, b);
}
public static uint PowerUInt(uint a, uint b)
{
return (uint)Math.Pow(a, b);
}
public static int PowerInt(int a, int b)
{
return (int)Math.Pow(a, b);
}
public static ulong PowerULong(ulong a, ulong b)
{
return (ulong)Math.Pow(a, b);
}
public static long PowerLong(long a, long b)
{
return (long)Math.Pow(a, b);
}
public static float PowerFloat(float a, float b)
{
return (float)Math.Pow(a, b);
}
public static double PowerDouble(double a, double b)
{
return Math.Pow(a, b);
}
public static decimal PowerDecimal(decimal a, decimal b)
{
return (decimal)Math.Pow((double)a, (double)b);
}
public static char PowerChar(char a, char b)
{
return (char)Math.Pow(a, b);
}
#endregion
}
}
| |
// <copyright company="Simply Code Ltd.">
// Copyright (c) Simply Code Ltd. All rights reserved.
// Licensed under the MIT License.
// See LICENSE file in the project root for full license information.
// </copyright>
namespace PackIt.Plan
{
using System.Diagnostics.CodeAnalysis;
using PackIt.Helpers.Enums;
/// <summary> A limit. </summary>
[ExcludeFromCodeCoverage]
public class Limit
{
/// <summary> Gets or sets a value indicating whether the design. </summary>
///
/// <value> True if design, false if not. </value>
public bool Design { get; set; }
/// <summary> Gets or sets the type of the material. </summary>
///
/// <value> The type of the material. </value>
public MaterialType MaterialType { get; set; }
/// <summary> Gets or sets the material code. </summary>
///
/// <value> The material code. </value>
public string MaterialCode { get; set; }
/// <summary> Gets or sets the material code minimum. </summary>
///
/// <value> The material code minimum. </value>
public string MaterialCodeMin { get; set; }
/// <summary> Gets or sets the type of the design. </summary>
///
/// <value> The type of the design. </value>
public DesignType DesignType { get; set; }
/// <summary> Gets or sets the design code. </summary>
///
/// <value> The design code. </value>
public string DesignCode { get; set; }
/// <summary> Gets or sets the design code minimum. </summary>
///
/// <value> The design code minimum. </value>
public string DesignCodeMin { get; set; }
/// <summary> Gets or sets the type of the quality. </summary>
///
/// <value> The type of the quality. </value>
public QualityType QualityType { get; set; }
/// <summary> Gets or sets the quality code. </summary>
///
/// <value> The quality code. </value>
public string QualityCode { get; set; }
/// <summary> Gets or sets the quality code minimum. </summary>
///
/// <value> The quality code minimum. </value>
public string QualityCodeMin { get; set; }
/// <summary> Gets or sets the usage. </summary>
///
/// <value> The usage. </value>
public UsageType Usage { get; set; }
/// <summary> Gets or sets a value indicating whether the inverted. </summary>
///
/// <value> True if inverted, false if not. </value>
public bool Inverted { get; set; }
/// <summary> Gets or sets the number of layers. </summary>
///
/// <value> The number of layers. </value>
public long LayerCount { get; set; }
/// <summary> Gets or sets the layer start. </summary>
///
/// <value> The layer start. </value>
public long LayerStart { get; set; }
/// <summary> Gets or sets the layer step. </summary>
///
/// <value> The layer step. </value>
public long LayerStep { get; set; }
/// <summary> Gets or sets the quality caliper. </summary>
///
/// <value> The quality caliper. </value>
public double QualityCaliper { get; set; }
/// <summary> Gets or sets the quality density. </summary>
///
/// <value> The quality density. </value>
public double QualityDensity { get; set; }
/// <summary> Gets or sets the length minimum. </summary>
///
/// <value> The length minimum. </value>
public double LengthMin { get; set; }
/// <summary> Gets or sets the length maximum. </summary>
///
/// <value> The length maximum. </value>
public double LengthMax { get; set; }
/// <summary> Gets or sets the breadth minimum. </summary>
///
/// <value> The breadth minimum. </value>
public double BreadthMin { get; set; }
/// <summary> Gets or sets the breadth maximum. </summary>
///
/// <value> The breadth maximum. </value>
public double BreadthMax { get; set; }
/// <summary> Gets or sets the height minimum. </summary>
///
/// <value> The height minimum. </value>
public double HeightMin { get; set; }
/// <summary> Gets or sets the height maximum. </summary>
///
/// <value> The height maximum. </value>
public double HeightMax { get; set; }
/// <summary> Gets or sets the caliper minimum. </summary>
///
/// <value> The caliper minimum. </value>
public double CaliperMin { get; set; }
/// <summary> Gets or sets the caliper maximum. </summary>
///
/// <value> The caliper maximum. </value>
public double CaliperMax { get; set; }
/// <summary> Gets or sets the packing gap x coordinate. </summary>
///
/// <value> The packing gap x coordinate. </value>
public double PackingGapX { get; set; }
/// <summary> Gets or sets the packing gap y coordinate. </summary>
///
/// <value> The packing gap y coordinate. </value>
public double PackingGapY { get; set; }
/// <summary> Gets or sets the packing gap z coordinate. </summary>
///
/// <value> The packing gap z coordinate. </value>
public double PackingGapZ { get; set; }
/// <summary> Gets or sets the safety factor minimum. </summary>
///
/// <value> The safety factor minimum. </value>
public double SafetyFactorMin { get; set; }
/// <summary> Gets or sets the safety factor maximum. </summary>
///
/// <value> The safety factor maximum. </value>
public double SafetyFactorMax { get; set; }
/// <summary> Gets or sets the front placement. </summary>
///
/// <value> The front placement. </value>
public long FrontPlacement { get; set; }
/// <summary> Gets or sets the back placement. </summary>
///
/// <value> The back placement. </value>
public long BackPlacement { get; set; }
/// <summary> Gets or sets the left placement. </summary>
///
/// <value> The left placement. </value>
public long LeftPlacement { get; set; }
/// <summary> Gets or sets the right placement. </summary>
///
/// <value> The right placement. </value>
public long RightPlacement { get; set; }
/// <summary> Gets or sets the top placement. </summary>
///
/// <value> The top placement. </value>
public long TopPlacement { get; set; }
/// <summary> Gets or sets the bottom placement. </summary>
///
/// <value> The bottom placement. </value>
public long BottomPlacement { get; set; }
/// <summary> Gets or sets the length thicknesses. </summary>
///
/// <value> The length thicknesses. </value>
public long LengthThicknesses { get; set; }
/// <summary> Gets or sets the length sink change. </summary>
///
/// <value> The length sink change. </value>
public long LengthSinkChange { get; set; }
/// <summary> Gets or sets the breadth thicknesses. </summary>
///
/// <value> The breadth thicknesses. </value>
public long BreadthThicknesses { get; set; }
/// <summary> Gets or sets the breadth sink change. </summary>
///
/// <value> The breadth sink change. </value>
public long BreadthSinkChange { get; set; }
/// <summary> Gets or sets the height thicknesses. </summary>
///
/// <value> The height thicknesses. </value>
public long HeightThicknesses { get; set; }
/// <summary> Gets or sets the height sink change. </summary>
///
/// <value> The height sink change. </value>
public long HeightSinkChange { get; set; }
/// <summary> Gets or sets the type of the costing. </summary>
///
/// <value> The type of the costing. </value>
public CostType CostingType { get; set; }
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
namespace HmLib.Binary
{
using Abstractions;
public class HmBinaryMessageReader : IMessageReader
{
private readonly HmBinaryStreamReader _stream;
public HmBinaryMessageReader(Stream input)
{
_reader = InitialReader;
_stream = new HmBinaryStreamReader(input);
}
public ReadState ReadState { get; private set; }
public MessageType MessageType { get; private set; }
private bool _containsHeaders;
private int _expectedHeaderLength;
private int _headersRead = 0;
private int _headerOffset;
private int _expectedBodyEnd;
public int ItemCount { get; private set; }
public string PropertyName { get; private set; }
public string StringValue { get; private set; }
public int IntValue { get; private set; }
public double DoubleValue { get; private set; }
public bool BooleanValue { get; private set; }
public ContentType? ValueType { get; private set; }
private Func<bool> _reader;
public bool Read()
{
return _reader();
}
private bool InitialReader()
{
if (ReadPacketType())
{
ReadState = ReadState.Message;
_reader = ReadInteractive;
return true;
}
_reader = ErrorReader;
return false;
}
private bool EndOfFileReader()
{
return false;
}
private bool ErrorReader()
{
return false;
}
private Stack<Tuple<bool, int>> _collectionDepth = new Stack<Tuple<bool, int>>();
private bool _readKeyValuePairs;
private int _itemsToReadInCurrentCollection;
private void BeginCollection()
{
//store current state
_collectionDepth.Push(Tuple.Create(_readKeyValuePairs, _itemsToReadInCurrentCollection));
_itemsToReadInCurrentCollection = ItemCount;
_readKeyValuePairs = ValueType == ContentType.Struct;
}
private void EndItem()
{
_itemsToReadInCurrentCollection--;
if (_itemsToReadInCurrentCollection == 0)
{
var tmp = _collectionDepth.Pop();
_readKeyValuePairs = tmp.Item1;
_itemsToReadInCurrentCollection = tmp.Item2;
EndItem();
}
}
private bool ReadInteractive()
{
switch (ReadState)
{
case ReadState.Body:
if (_stream.BytesRead < _expectedBodyEnd)
{
ReadBody();
}
else
{
MoveToEof();
}
return true;
case ReadState.Message:
if (_containsHeaders)
{
MoveToHeaders();
}
else
{
MoveToContent();
}
return true;
case ReadState.Headers:
if (_headersRead < ItemCount)
{
ReadHeader();
if (_headersRead < ItemCount)
{
return true;
}
}
var actualBytesRead = _stream.BytesRead - _headerOffset;
if (_expectedHeaderLength != actualBytesRead)
{
_reader = ErrorReader;
throw new ProtocolException(string.Format("Expected a header of length {0} bytes, instead read {1} bytes.", _expectedHeaderLength, actualBytesRead));
}
MoveToContent();
return true;
}
return false;
}
private void ReadHeader()
{
_headersRead++;
PropertyName = _stream.ReadString();
ValueType = ContentType.String;
StringValue = _stream.ReadString();
}
private IEnumerable<ContentType> ReadValueType()
{
if (MessageType == MessageType.Request)
{
//request method
yield return ContentType.String;
//request params
yield return ContentType.Array;
}
while (_expectedBodyEnd > _stream.BytesRead)
{
var contentType = _stream.ReadContentType();
yield return contentType;
}
}
private void ReadBody()
{
if (_readKeyValuePairs)
{
PropertyName = _stream.ReadString();
}
if (!_typeReader.MoveNext())
{
MoveToEof();
return;
}
ValueType = _typeReader.Current;
if (ValueType == ContentType.Array || ValueType == ContentType.Struct)
{
ItemCount = _stream.ReadInt32();
BeginCollection();
return;
}
if (ValueType == ContentType.String || ValueType == ContentType.Base64)
{
StringValue = _stream.ReadString();
}
else if (ValueType == ContentType.Int)
{
IntValue = _stream.ReadInt32();
}
else if (ValueType == ContentType.Float)
{
DoubleValue = _stream.ReadDouble();
}
else if (ValueType == ContentType.Boolean)
{
BooleanValue = _stream.ReadBoolean();
}
else
{
throw new NotImplementedException();
}
EndItem();
}
private bool ReadPacketType()
{
var header = _stream.ReadBytes(3);
if (!Packet.PacketHeader.SequenceEqual(header))
{
return false;
}
var packetType = _stream.ReadByte();
switch (packetType)
{
case Packet.ErrorMessage:
MessageType = MessageType.Error;
return true;
case Packet.ResponseMessage:
MessageType = MessageType.Response;
return true;
case Packet.RequestMessage:
MessageType = MessageType.Request;
return true;
case Packet.RequestMessageWithHeaders:
MessageType = MessageType.Request;
_containsHeaders = true;
return true;
case Packet.ResponseMessageWithHeaders:
MessageType = MessageType.Response;
_containsHeaders = true;
return true;
default:
return false;
}
}
private void MoveToEof()
{
_reader = EndOfFileReader;
ReadState = ReadState.EndOfFile;
if (_stream.BytesRead != _expectedBodyEnd)
{
throw new ProtocolException(string.Format("The response is incomplete or corrupted. Expected {0} bytes, read {1} bytes.", _expectedBodyEnd, _stream.BytesRead));
}
}
private void MoveToHeaders()
{
ReadState = ReadState.Headers;
_expectedHeaderLength = _stream.ReadInt32();
_headerOffset = (int)_stream.BytesRead;
ItemCount = _stream.ReadInt32();
}
private IEnumerator<ContentType> _typeReader;
private void MoveToContent()
{
var expectedBodyLength = _stream.ReadInt32();
var bodyOffset = (int)_stream.BytesRead;
_expectedBodyEnd = bodyOffset + expectedBodyLength;
if (expectedBodyLength == 0)
{
MoveToEof();
return;
}
_typeReader = ReadValueType().GetEnumerator();
ReadState = ReadState.Body;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.IO;
using System.Net.Security;
using System.Net.Test.Common;
using System.Runtime.InteropServices;
using System.Security.Authentication;
using System.Threading.Tasks;
using Xunit;
namespace System.Net.Http.Functional.Tests
{
using Configuration = System.Net.Test.Common.Configuration;
[SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "SslProtocols not supported on UAP")]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "dotnet/corefx #16805")]
public partial class HttpClientHandler_SslProtocols_Test : HttpClientTestBase
{
[Fact]
public void DefaultProtocols_MatchesExpected()
{
using (HttpClientHandler handler = CreateHttpClientHandler())
{
Assert.Equal(SslProtocols.None, handler.SslProtocols);
}
}
[Theory]
[InlineData(SslProtocols.None)]
[InlineData(SslProtocols.Tls)]
[InlineData(SslProtocols.Tls11)]
[InlineData(SslProtocols.Tls12)]
[InlineData(SslProtocols.Tls | SslProtocols.Tls11)]
[InlineData(SslProtocols.Tls11 | SslProtocols.Tls12)]
[InlineData(SslProtocols.Tls | SslProtocols.Tls12)]
[InlineData(SslProtocols.Tls | SslProtocols.Tls11 | SslProtocols.Tls12)]
public void SetGetProtocols_Roundtrips(SslProtocols protocols)
{
using (HttpClientHandler handler = CreateHttpClientHandler())
{
handler.SslProtocols = protocols;
Assert.Equal(protocols, handler.SslProtocols);
}
}
[OuterLoop] // TODO: Issue #11345
[Fact]
public async Task SetProtocols_AfterRequest_ThrowsException()
{
if (!BackendSupportsSslConfiguration)
{
return;
}
using (HttpClientHandler handler = CreateHttpClientHandler())
using (var client = new HttpClient(handler))
{
handler.ServerCertificateCustomValidationCallback = TestHelper.AllowAllCertificates;
await LoopbackServer.CreateServerAsync(async (server, url) =>
{
await TestHelper.WhenAllCompletedOrAnyFailed(
server.AcceptConnectionSendResponseAndCloseAsync(),
client.GetAsync(url));
});
Assert.Throws<InvalidOperationException>(() => handler.SslProtocols = SslProtocols.Tls12);
}
}
[OuterLoop] // TODO: Issue #11345
[Theory]
[InlineData(~SslProtocols.None)]
#pragma warning disable 0618 // obsolete warning
[InlineData(SslProtocols.Ssl2)]
[InlineData(SslProtocols.Ssl3)]
[InlineData(SslProtocols.Ssl2 | SslProtocols.Ssl3)]
[InlineData(SslProtocols.Ssl2 | SslProtocols.Ssl3 | SslProtocols.Tls | SslProtocols.Tls11 | SslProtocols.Tls12)]
#pragma warning restore 0618
public void DisabledProtocols_SetSslProtocols_ThrowsException(SslProtocols disabledProtocols)
{
using (HttpClientHandler handler = CreateHttpClientHandler())
{
Assert.Throws<NotSupportedException>(() => handler.SslProtocols = disabledProtocols);
}
}
[OuterLoop] // TODO: Issue #11345
[Theory]
[InlineData(SslProtocols.Tls, false)]
[InlineData(SslProtocols.Tls, true)]
[InlineData(SslProtocols.Tls11, false)]
[InlineData(SslProtocols.Tls11, true)]
[InlineData(SslProtocols.Tls12, false)]
[InlineData(SslProtocols.Tls12, true)]
public async Task GetAsync_AllowedSSLVersion_Succeeds(SslProtocols acceptedProtocol, bool requestOnlyThisProtocol)
{
if (!BackendSupportsSslConfiguration)
{
return;
}
if (UseSocketsHttpHandler)
{
// TODO #26186: SocketsHttpHandler is failing on some OSes.
return;
}
using (HttpClientHandler handler = CreateHttpClientHandler())
using (var client = new HttpClient(handler))
{
handler.ServerCertificateCustomValidationCallback = TestHelper.AllowAllCertificates;
if (requestOnlyThisProtocol)
{
handler.SslProtocols = acceptedProtocol;
}
var options = new LoopbackServer.Options { UseSsl = true, SslProtocols = acceptedProtocol };
await LoopbackServer.CreateServerAsync(async (server, url) =>
{
await TestHelper.WhenAllCompletedOrAnyFailed(
server.AcceptConnectionSendResponseAndCloseAsync(),
client.GetAsync(url));
}, options);
}
}
public static readonly object[][] SupportedSSLVersionServers =
{
new object[] {SslProtocols.Tls, Configuration.Http.TLSv10RemoteServer},
new object[] {SslProtocols.Tls11, Configuration.Http.TLSv11RemoteServer},
new object[] {SslProtocols.Tls12, Configuration.Http.TLSv12RemoteServer},
};
// This test is logically the same as the above test, albeit using remote servers
// instead of local ones. We're keeping it for now (as outerloop) because it helps
// to validate against another SSL implementation that what we mean by a particular
// TLS version matches that other implementation.
[OuterLoop("Avoid www.ssllabs.com dependency in innerloop.")]
[Theory]
[MemberData(nameof(SupportedSSLVersionServers))]
public async Task GetAsync_SupportedSSLVersion_Succeeds(SslProtocols sslProtocols, string url)
{
if (UseSocketsHttpHandler)
{
// TODO #26186: SocketsHttpHandler is failing on some OSes.
return;
}
using (HttpClientHandler handler = CreateHttpClientHandler())
{
if (PlatformDetection.IsRedHatFamily7)
{
// Default protocol selection is always TLSv1 on Centos7 libcurl 7.29.0
// Hence, set the specific protocol on HttpClient that is required by test
handler.SslProtocols = sslProtocols;
}
using (var client = new HttpClient(handler))
{
(await RemoteServerQuery.Run(() => client.GetAsync(url), remoteServerExceptionWrapper, url)).Dispose();
}
}
}
public Func<Exception, bool> remoteServerExceptionWrapper = (exception) =>
{
Type exceptionType = exception.GetType();
if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
{
// On linux, taskcanceledexception is thrown.
return exceptionType.Equals(typeof(TaskCanceledException));
}
else
{
// The internal exceptions return operation timed out.
return exceptionType.Equals(typeof(HttpRequestException)) && exception.InnerException.Message.Contains("timed out");
}
};
public static readonly object[][] NotSupportedSSLVersionServers =
{
new object[] {"SSLv2", Configuration.Http.SSLv2RemoteServer},
new object[] {"SSLv3", Configuration.Http.SSLv3RemoteServer},
};
// It would be easy to remove the dependency on these remote servers if we didn't
// explicitly disallow creating SslStream with SSLv2/3. Since we explicitly throw
// when trying to use such an SslStream, we can't stand up a localhost server that
// only speaks those protocols.
[OuterLoop("Avoid www.ssllabs.com dependency in innerloop.")]
[Theory]
[MemberData(nameof(NotSupportedSSLVersionServers))]
public async Task GetAsync_UnsupportedSSLVersion_Throws(string name, string url)
{
if (!SSLv3DisabledByDefault)
{
return;
}
if (UseSocketsHttpHandler && !PlatformDetection.IsWindows10Version1607OrGreater)
{
// On Windows, https://github.com/dotnet/corefx/issues/21925#issuecomment-313408314
// On Linux, an older version of OpenSSL may permit negotiating SSLv3.
return;
}
using (HttpClient client = CreateHttpClient())
{
await Assert.ThrowsAsync<HttpRequestException>(() => RemoteServerQuery.Run(() => client.GetAsync(url), remoteServerExceptionWrapper, url));
}
}
[OuterLoop] // TODO: Issue #11345
[ConditionalFact(nameof(SslDefaultsToTls12))]
public async Task GetAsync_NoSpecifiedProtocol_DefaultsToTls12()
{
if (!BackendSupportsSslConfiguration)
{
return;
}
using (HttpClientHandler handler = CreateHttpClientHandler())
using (var client = new HttpClient(handler))
{
handler.ServerCertificateCustomValidationCallback = TestHelper.AllowAllCertificates;
var options = new LoopbackServer.Options { UseSsl = true };
await LoopbackServer.CreateServerAsync(async (server, url) =>
{
await TestHelper.WhenAllCompletedOrAnyFailed(
client.GetAsync(url),
server.AcceptConnectionAsync(async connection =>
{
Assert.Equal(SslProtocols.Tls12, Assert.IsType<SslStream>(connection.Stream).SslProtocol);
await connection.ReadRequestHeaderAndSendResponseAsync();
}));
}, options);
}
}
[OuterLoop] // TODO: Issue #11345
[Theory]
[InlineData(SslProtocols.Tls11, SslProtocols.Tls, typeof(IOException))]
[InlineData(SslProtocols.Tls12, SslProtocols.Tls11, typeof(IOException))]
[InlineData(SslProtocols.Tls, SslProtocols.Tls12, typeof(AuthenticationException))]
public async Task GetAsync_AllowedSSLVersionDiffersFromServer_ThrowsException(
SslProtocols allowedProtocol, SslProtocols acceptedProtocol, Type exceptedServerException)
{
if (PlatformDetection.IsUbuntu1804)
{
//ActiveIssue #27023: [Ubuntu18.04] Tests failed:
return;
}
if (!BackendSupportsSslConfiguration)
return;
using (HttpClientHandler handler = CreateHttpClientHandler())
using (var client = new HttpClient(handler))
{
handler.SslProtocols = allowedProtocol;
handler.ServerCertificateCustomValidationCallback = TestHelper.AllowAllCertificates;
var options = new LoopbackServer.Options { UseSsl = true, SslProtocols = acceptedProtocol };
await LoopbackServer.CreateServerAsync(async (server, url) =>
{
await TestHelper.WhenAllCompletedOrAnyFailed(
Assert.ThrowsAsync(exceptedServerException, () => server.AcceptConnectionSendResponseAndCloseAsync()),
Assert.ThrowsAsync<HttpRequestException>(() => client.GetAsync(url)));
}, options);
}
}
[OuterLoop] // TODO: Issue #11345
[ActiveIssue(8538, TestPlatforms.Windows)]
[Fact]
public async Task GetAsync_DisallowTls10_AllowTls11_AllowTls12()
{
if (PlatformDetection.IsUbuntu1804)
{
//ActiveIssue #27023: [Ubuntu18.04] Tests failed:
return;
}
using (HttpClientHandler handler = CreateHttpClientHandler())
using (var client = new HttpClient(handler))
{
handler.SslProtocols = SslProtocols.Tls11 | SslProtocols.Tls12;
handler.ServerCertificateCustomValidationCallback = TestHelper.AllowAllCertificates;
if (BackendSupportsSslConfiguration)
{
LoopbackServer.Options options = new LoopbackServer.Options { UseSsl = true };
options.SslProtocols = SslProtocols.Tls;
await LoopbackServer.CreateServerAsync(async (server, url) =>
{
await TestHelper.WhenAllCompletedOrAnyFailed(
Assert.ThrowsAsync<IOException>(() => server.AcceptConnectionSendResponseAndCloseAsync()),
Assert.ThrowsAsync<HttpRequestException>(() => client.GetAsync(url)));
}, options);
foreach (var prot in new[] { SslProtocols.Tls11, SslProtocols.Tls12 })
{
options.SslProtocols = prot;
await LoopbackServer.CreateServerAsync(async (server, url) =>
{
await TestHelper.WhenAllCompletedOrAnyFailed(
server.AcceptConnectionSendResponseAndCloseAsync(),
client.GetAsync(url));
}, options);
}
}
else
{
await Assert.ThrowsAnyAsync<NotSupportedException>(() => client.GetAsync($"http://{Guid.NewGuid().ToString()}/"));
}
}
}
private static bool SslDefaultsToTls12 => !PlatformDetection.IsWindows7;
// TLS 1.2 may not be enabled on Win7
// https://technet.microsoft.com/en-us/library/dn786418.aspx#BKMK_SchannelTR_TLS12
}
}
| |
/* ====================================================================
Copyright (C) 2004-2008 fyiReporting Software, LLC
Copyright (C) 2011 Peter Gill <[email protected]>
This file is part of the fyiReporting RDL project.
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 additional information, email [email protected] or visit
the website www.fyiReporting.com.
*/
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.Drawing.Printing;
using System.IO;
using System.Xml;
using fyiReporting.RDL;
using fyiReporting.RdlDesign.Resources;
using fyiReporting.RdlViewer;
namespace fyiReporting.RdlDesign
{
/// <summary>
/// RdlReader is a application for displaying reports based on RDL.
/// </summary>
internal partial class MDIChild
{
public delegate void RdlChangeHandler(object sender, EventArgs e);
public event RdlChangeHandler OnSelectionChanged;
public event RdlChangeHandler OnSelectionMoved;
public event RdlChangeHandler OnReportItemInserted;
public event RdlChangeHandler OnDesignTabChanged;
public event DesignCtl.OpenSubreportEventHandler OnOpenSubreport;
public event DesignCtl.HeightEventHandler OnHeightChanged;
Uri _SourceFile;
// TabPage for this MDI Child
private MDIChild() { }
public MDIChild(int width, int height)
{
this.InitializeComponent();
this.SuspendLayout();
//
// rdlDesigner
//
this.rdlDesigner.Name = "rdlDesigner";
this.rdlDesigner.Size = new System.Drawing.Size(width, height);
//
// MDIChild
//
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.ClientSize = new System.Drawing.Size(width, height);
this.Name = "";
this.Text = "";
this.Closing += new System.ComponentModel.CancelEventHandler(this.MDIChild_Closing);
this.ResumeLayout(false);
}
internal TabPage Tab
{
get { return _Tab; }
set { _Tab = value; }
}
public RdlEditPreview Editor
{
get
{
return rdlDesigner.CanEdit ? rdlDesigner : null; // only return when it can edit
}
}
public RdlEditPreview RdlEditor
{
get
{
return rdlDesigner; // always return
}
}
public void ShowEditLines(bool bShow)
{
rdlDesigner.ShowEditLines(bShow);
}
internal void ShowPreviewWaitDialog(bool bShow)
{
rdlDesigner.ShowPreviewWaitDialog(bShow);
}
internal bool ShowReportItemOutline
{
get { return rdlDesigner.ShowReportItemOutline; }
set { rdlDesigner.ShowReportItemOutline = value; }
}
public string CurrentInsert
{
get { return rdlDesigner.CurrentInsert; }
set
{
rdlDesigner.CurrentInsert = value;
}
}
public int CurrentLine
{
get { return rdlDesigner.CurrentLine; }
}
public int CurrentCh
{
get { return rdlDesigner.CurrentCh; }
}
internal string DesignTab
{
get { return rdlDesigner.DesignTab; }
set { rdlDesigner.DesignTab = value; }
}
internal DesignXmlDraw DrawCtl
{
get { return rdlDesigner.DrawCtl; }
}
public XmlDocument ReportDocument
{
get { return rdlDesigner.ReportDocument; }
}
internal void SetFocus()
{
rdlDesigner.SetFocus();
}
public StyleInfo SelectedStyle
{
get { return rdlDesigner.SelectedStyle; }
}
public string SelectionName
{
get { return rdlDesigner.SelectionName; }
}
public PointF SelectionPosition
{
get { return rdlDesigner.SelectionPosition; }
}
public SizeF SelectionSize
{
get { return rdlDesigner.SelectionSize; }
}
public void ApplyStyleToSelected(string name, string v)
{
rdlDesigner.ApplyStyleToSelected(name, v);
}
public bool FileSave()
{
Uri file = SourceFile;
if (file == null || file.LocalPath == "") // if no file name then do SaveAs
{
return FileSaveAs();
}
string rdl = GetRdlText();
return FileSave(file, rdl);
}
private bool FileSave(Uri file, string rdl)
{
bool bOK = true;
try
{
using (StreamWriter writer = new StreamWriter(file.LocalPath))
{
writer.Write(rdl);
// editRDL.ClearUndo();
// editRDL.Modified = false;
// SetTitle();
// statusBar.Text = "Saved " + curFileName;
}
}
catch (Exception ae)
{
bOK = false;
MessageBox.Show(ae.Message + "\r\n" + ae.StackTrace);
// statusBar.Text = "Save of file '" + curFileName + "' failed";
}
if (bOK)
this.Modified = false;
return bOK;
}
public bool Export(fyiReporting.RDL.OutputPresentationType type)
{
SaveFileDialog sfd = new SaveFileDialog();
sfd.Title = string.Format(Strings.MDIChild_Export_ExportTitleFormat, type.ToString().ToUpper());
switch (type)
{
case OutputPresentationType.CSV:
sfd.Filter = Strings.MDIChild_Export_CSV;
break;
case OutputPresentationType.XML:
sfd.Filter = Strings.MDIChild_Export_XML;
break;
case OutputPresentationType.PDF:
case OutputPresentationType.PDFOldStyle:
sfd.Filter = Strings.MDIChild_Export_PDF;
break;
case OutputPresentationType.TIF:
sfd.Filter = Strings.MDIChild_Export_TIF;
break;
case OutputPresentationType.RTF:
sfd.Filter = Strings.MDIChild_Export_RTF;
break;
case OutputPresentationType.Word:
sfd.Filter = Strings.MDIChild_Export_DOC;
break;
case OutputPresentationType.Excel:
sfd.Filter = Strings.MDIChild_Export_Excel;
break;
case OutputPresentationType.HTML:
sfd.Filter = Strings.MDIChild_Export_Web_Page;
break;
case OutputPresentationType.MHTML:
sfd.Filter = Strings.MDIChild_Export_MHT;
break;
default:
throw new Exception(Strings.MDIChild_Error_AllowedExportTypes);
}
sfd.FilterIndex = 1;
if (SourceFile != null)
{
sfd.FileName = Path.GetFileNameWithoutExtension(SourceFile.LocalPath) + "." + type;
}
else
{
sfd.FileName = "*." + type;
}
try
{
if (sfd.ShowDialog(this) != DialogResult.OK)
return false;
// save the report in the requested rendered format
bool rc = true;
// tif can be either in color or black and white; ask user what they want
if (type == OutputPresentationType.TIF)
{
DialogResult dr = MessageBox.Show(this, Strings.MDIChild_ShowF_WantDisplayColorsInTIF, Strings.MDIChild_ShowF_Export, MessageBoxButtons.YesNoCancel);
if (dr == DialogResult.No)
type = OutputPresentationType.TIFBW;
else if (dr == DialogResult.Cancel)
return false;
}
try { SaveAs(sfd.FileName, type); }
catch (Exception ex)
{
MessageBox.Show(this,
ex.Message, Strings.MDIChild_ShowG_ExportError,
MessageBoxButtons.OK, MessageBoxIcon.Error);
rc = false;
}
return rc;
}
finally
{
sfd.Dispose();
}
}
public bool FileSaveAs()
{
SaveFileDialog sfd = new SaveFileDialog();
sfd.Filter = Strings.MDIChild_FileSaveAs_RDLFilter;
sfd.FilterIndex = 1;
Uri file = SourceFile;
sfd.FileName = file == null ? "*.rdl" : file.LocalPath;
try
{
if (sfd.ShowDialog(this) != DialogResult.OK)
return false;
// User wants to save!
string rdl = GetRdlText();
if (FileSave(new Uri(sfd.FileName), rdl))
{ // Save was successful
Text = sfd.FileName;
Tab.Text = Path.GetFileName(sfd.FileName);
_SourceFile = new Uri(sfd.FileName);
Tab.ToolTipText = sfd.FileName;
return true;
}
}
finally
{
sfd.Dispose();
}
return false;
}
public string GetRdlText()
{
return this.rdlDesigner.GetRdlText();
}
public bool Modified
{
get { return rdlDesigner.Modified; }
set
{
rdlDesigner.Modified = value;
SetTitle();
}
}
/// <summary>
/// The RDL file that should be displayed.
/// </summary>
public Uri SourceFile
{
get { return _SourceFile; }
set
{
_SourceFile = value;
string rdl = GetRdlSource();
this.rdlDesigner.SetRdlText(rdl == null ? "" : rdl);
}
}
public string SourceRdl
{
get { return this.rdlDesigner.GetRdlText(); }
set { this.rdlDesigner.SetRdlText(value); }
}
private string GetRdlSource()
{
StreamReader fs = null;
string prog = null;
try
{
fs = new StreamReader(_SourceFile.LocalPath);
prog = fs.ReadToEnd();
}
finally
{
if (fs != null)
fs.Close();
}
return prog;
}
/// <summary>
/// Number of pages in the report.
/// </summary>
public int PageCount
{
get { return this.rdlDesigner.PageCount; }
}
/// <summary>
/// Current page in view on report
/// </summary>
public int PageCurrent
{
get { return this.rdlDesigner.PageCurrent; }
}
/// <summary>
/// Page height of the report.
/// </summary>
public float PageHeight
{
get { return this.rdlDesigner.PageHeight; }
}
/// <summary>
/// Turns the Selection Tool on in report preview
/// </summary>
public bool SelectionTool
{
get
{
return this.rdlDesigner.SelectionTool;
}
set
{
this.rdlDesigner.SelectionTool = value;
}
}
/// <summary>
/// Page width of the report.
/// </summary>
public float PageWidth
{
get { return this.rdlDesigner.PageWidth; }
}
/// <summary>
/// Zoom
/// </summary>
public float Zoom
{
get { return this.rdlDesigner.Zoom; }
set { this.rdlDesigner.Zoom = value; }
}
/// <summary>
/// ZoomMode
/// </summary>
public ZoomEnum ZoomMode
{
get { return this.rdlDesigner.ZoomMode; }
set { this.rdlDesigner.ZoomMode = value; }
}
/// <summary>
/// Print the report.
/// </summary>
public void Print(PrintDocument pd)
{
this.rdlDesigner.Print(pd);
}
public void SaveAs(string filename, OutputPresentationType type)
{
rdlDesigner.SaveAs(filename, type);
}
private void MDIChild_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
if (!OkToClose())
{
e.Cancel = true;
return;
}
if (Tab == null)
return;
Control ctl = Tab.Parent;
ctl.Controls.Remove(Tab);
Tab.Tag = null; // this is the Tab reference to this
Tab = null;
}
public bool OkToClose()
{
if (!Modified)
return true;
DialogResult r =
MessageBox.Show(this, String.Format(Strings.MDIChild_ShowH_WantSaveChanges,
_SourceFile == null ? Strings.MDIChild_ShowH_Untitled : Path.GetFileName(_SourceFile.LocalPath)),
Strings.MDIChild_ShowH_fyiReportingDesigner,
MessageBoxButtons.YesNoCancel,
MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button3);
bool bOK = true;
if (r == DialogResult.Cancel)
bOK = false;
else if (r == DialogResult.Yes)
{
if (!FileSave())
bOK = false;
}
return bOK;
}
private void rdlDesigner_RdlChanged(object sender, System.EventArgs e)
{
SetTitle();
}
private void rdlDesigner_HeightChanged(object sender, HeightEventArgs e)
{
if (OnHeightChanged != null)
OnHeightChanged(this, e);
}
private void rdlDesigner_SelectionChanged(object sender, System.EventArgs e)
{
if (OnSelectionChanged != null)
OnSelectionChanged(this, e);
}
private void rdlDesigner_DesignTabChanged(object sender, System.EventArgs e)
{
if (OnDesignTabChanged != null)
OnDesignTabChanged(this, e);
}
private void rdlDesigner_ReportItemInserted(object sender, System.EventArgs e)
{
if (OnReportItemInserted != null)
OnReportItemInserted(this, e);
}
private void rdlDesigner_SelectionMoved(object sender, System.EventArgs e)
{
if (OnSelectionMoved != null)
OnSelectionMoved(this, e);
}
private void rdlDesigner_OpenSubreport(object sender, SubReportEventArgs e)
{
if (OnOpenSubreport != null)
{
OnOpenSubreport(this, e);
}
}
private void SetTitle()
{
string title = this.Text;
if (title.Length < 1)
return;
char m = title[title.Length - 1];
if (this.Modified)
{
if (m != '*')
title = title + "*";
}
else if (m == '*')
title = title.Substring(0, title.Length - 1);
if (title != this.Text)
this.Text = title;
return;
}
public fyiReporting.RdlViewer.RdlViewer Viewer
{
get { return rdlDesigner.Viewer; }
}
private void MDIChild_Load(object sender, EventArgs e)
{
}
}
}
| |
// 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
// Original XmlUnit license
/*
******************************************************************
Copyright (c) 2001, Jeff Martin, Tim Bacon
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 the xmlunit.sourceforge.net 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 MbUnit.Framework
{
using MbUnit.Framework.Xml;
using System.IO;
using System;
/// <summary>
/// Class containing generic assert methods for XML markup
/// </summary>
public sealed class XmlAssert{
private XmlAssert()
{}
/// <summary>
/// Asserts that two pieces of XML are similar.
/// </summary>
/// <param name="controlTextReader">The control text reader.</param>
/// <param name="testTextReader">The test text reader.</param>
public static void XmlEquals(TextReader controlTextReader, TextReader testTextReader) {
XmlEquals(new XmlDiff(controlTextReader, testTextReader));
}
/// <summary>
/// Asserts that two pieces of XML are similar.
/// </summary>
/// <param name="controlText">The control text.</param>
/// <param name="testText">The test text.</param>
public static void XmlEquals(string controlText, string testText) {
XmlEquals(new XmlDiff(controlText, testText));
}
/// <summary>
/// Asserts that two pieces of XML are similar.
/// </summary>
/// <param name="controlInput">The control input.</param>
/// <param name="testInput">The test input.</param>
public static void XmlEquals(XmlInput controlInput, XmlInput testInput) {
XmlEquals(new XmlDiff(controlInput, testInput));
}
/// <summary>
/// Asserts that two pieces of XML are identical.
/// </summary>
/// <param name="controlTextReader">The control text reader.</param>
/// <param name="testTextReader">The test text reader.</param>
public static void XmlIdentical(TextReader controlTextReader, TextReader testTextReader) {
XmlIdentical(new XmlDiff(controlTextReader, testTextReader));
}
/// <summary>
/// Asserts that two pieces of XML are identical.
/// </summary>
/// <param name="controlText">The control text.</param>
/// <param name="testText">The test text.</param>
public static void XmlIdentical(string controlText, string testText) {
XmlIdentical(new XmlDiff(controlText, testText));
}
/// <summary>
/// Asserts that two pieces of XML are identical.
/// </summary>
/// <param name="controlInput">The control input.</param>
/// <param name="testInput">The test input.</param>
public static void XmlIdentical(XmlInput controlInput, XmlInput testInput) {
XmlIdentical(new XmlDiff(controlInput, testInput));
}
/// <summary>
/// Asserts that two pieces of XMl are similar given their diff
/// </summary>
/// <param name="xmlDiff">The XML diff.</param>
public static void XmlEquals(XmlDiff xmlDiff) {
XmlEquals(xmlDiff, true);
}
/// <summary>
/// Asserts that two pieces of XMl are not similar given their diff
/// </summary>
/// <param name="xmlDiff">The XML diff.</param>
public static void XmlNotEquals(XmlDiff xmlDiff) {
XmlEquals(xmlDiff, false);
}
/// <summary>
/// Asserts that two pieces of XML are similar (or not) given their diff and a boolean value
/// </summary>
/// <param name="xmlDiff">The XML diff.</param>
/// <param name="equal">if set to <c>true</c> the assert passes if the XML is similar.
/// if <c>false</c>, the assert passes if the XML is not similar</param>
private static void XmlEquals(XmlDiff xmlDiff, bool equal)
{
DiffResult diffResult = xmlDiff.Compare();
Assert.AreEqual(equal, diffResult.Equal, FailMessage(equal, xmlDiff.OptionalDescription));
}
private static string FailMessage(bool equal, string optionalDescription)
{
if (optionalDescription == null || optionalDescription.Equals("") || optionalDescription.Equals(DiffConfiguration.DEFAULT_DESCRIPTION))
return (equal == true) ? "Xml does not match" : "Xml matches but should be different";
else
return optionalDescription;
}
/// <summary>
/// Asserts that two pieces of XML are identical given their diff
/// </summary>
/// <param name="xmlDiff">The XML diff.</param>
public static void XmlIdentical(XmlDiff xmlDiff) {
XmlIdentical(xmlDiff, true);
}
/// <summary>
/// Asserts that two pieces of XML are not identical given their diff
/// </summary>
/// <param name="xmlDiff">The XML diff.</param>
public static void XmlNotIdentical(XmlDiff xmlDiff) {
XmlIdentical(xmlDiff, false);
}
/// <summary>
/// Asserts that two pieces of XML are identical (or not) given their diff and a boolean value
/// </summary>
/// <param name="xmlDiff">The XML diff.</param>
/// <param name="identical">if set to <c>true</c> the assert passes if the XML is identical.
/// if <c>false</c>, the assert passes if the XML is not identical</param>
private static void XmlIdentical(XmlDiff xmlDiff, bool identical) {
DiffResult diffResult = xmlDiff.Compare();
Assert.AreEqual(identical, diffResult.Identical,xmlDiff.OptionalDescription);
}
/// <summary>
/// Asserts that <paramref name="someXml"/> is valid XML.
/// </summary>
/// <param name="someXml">The XMl to test</param>
public static void XmlValid(string someXml) {
XmlValid(new XmlInput(someXml));
}
/// <summary>
/// Asserts that <paramref name="someXml"/> is valid XML given a <paramref name="baseURI"/>
/// </summary>
/// <param name="someXml">The XML to test.</param>
/// <param name="baseURI">The base URI.</param>
public static void XmlValid(string someXml, string baseURI) {
XmlValid(new XmlInput(someXml, baseURI));
}
/// <summary>
/// Asserts that some XML is valid.
/// </summary>
/// <param name="reader">A <see cref="TextReader"/> pointing to the XML to test.</param>
public static void XmlValid(TextReader reader) {
XmlValid(new XmlInput(reader));
}
/// <summary>
/// Asserts that some XML is valid given a <paramref name="baseURI"/>
/// </summary>
/// <param name="reader">A <see cref="TextReader"/> pointing to the XML to test.</param>
/// <param name="baseURI">The base URI.</param>
public static void XmlValid(TextReader reader, string baseURI) {
XmlValid(new XmlInput(reader, baseURI));
}
/// <summary>
/// Asserts that some XML is valid.
/// </summary>
/// <param name="xmlInput">The XML input.</param>
public static void XmlValid(XmlInput xmlInput) {
Validator validator = new Validator(xmlInput);
XmlValid(validator);
}
/// <summary>
/// Asserts that some XML is valid.
/// </summary>
/// <param name="validator">A <see cref="Validator"/> object containing the XML to validate</param>
public static void XmlValid(Validator validator) {
Assert.AreEqual(true, validator.IsValid,validator.ValidationMessage);
}
/// <summary>
/// Assert that an XPath expression matches at least one node in someXml
/// </summary>
/// <param name="anXPathExpression">An X path expression.</param>
/// <param name="inXml">The XML being tested.</param>
public static void XPathExists(string anXPathExpression, string inXml) {
XPathExists(anXPathExpression, new XmlInput(inXml));
}
/// <summary>
/// Assert that an XPath expression matches at least one node in someXml
/// </summary>
/// <param name="anXPathExpression">An X path expression.</param>
/// <param name="inXml">A reader ontot eh XML being tested</param>
public static void XPathExists(string anXPathExpression, TextReader inXml) {
XPathExists(anXPathExpression, new XmlInput(inXml));
}
/// <summary>
/// Assert that an XPath expression matches at least one node in someXml
/// </summary>
/// <param name="anXPathExpression">An X path expression.</param>
/// <param name="inXml">The XML to test.</param>
public static void XPathExists(string anXPathExpression, XmlInput inXml) {
XPath xpath = new XPath(anXPathExpression);
Assert.AreEqual(true, xpath.XPathExists(inXml));
}
/// <summary>
/// Asserts that the flattened String obtained by executing an Xpath on some XML is a particular value
/// </summary>
/// <param name="anXPathExpression">An X path expression.</param>
/// <param name="inXml">The XML to test.</param>
/// <param name="expectedValue">The expected value.</param>
public static void XPathEvaluatesTo(string anXPathExpression, string inXml,
string expectedValue) {
XPathEvaluatesTo(anXPathExpression, new XmlInput(inXml), expectedValue);
}
/// <summary>
/// Asserts that the flattened String obtained by executing an Xpath on some XML is a particular value
/// </summary>
/// <param name="anXPathExpression">An X path expression.</param>
/// <param name="inXml">The XML to test.</param>
/// <param name="expectedValue">The expected value.</param>
public static void XPathEvaluatesTo(string anXPathExpression, TextReader inXml,
string expectedValue) {
XPathEvaluatesTo(anXPathExpression, new XmlInput(inXml), expectedValue);
}
/// <summary>
/// Asserts that the flattened String obtained by executing an Xpath on some XML is a particular value
/// </summary>
/// <param name="anXPathExpression">An X path expression.</param>
/// <param name="inXml">The XML to test.</param>
/// <param name="expectedValue">The expected value.</param>
public static void XPathEvaluatesTo(string anXPathExpression, XmlInput inXml,
string expectedValue) {
XPath xpath = new XPath(anXPathExpression);
Assert.AreEqual(expectedValue, xpath.EvaluateXPath(inXml));
}
/// <summary>
/// Asserts that the results of an XSL transform on some XML are the expected result
/// </summary>
/// <param name="xslTransform">The XSL transform.</param>
/// <param name="xmlToTransform">The XML to transform.</param>
/// <param name="expectedResult">The expected result.</param>
public static void XslTransformResults(string xslTransform, string xmlToTransform, string expectedResult) {
XmlInput xsl = new XmlInput(xslTransform);
XmlInput xml2 = new XmlInput(xmlToTransform);
XmlInput xmlEx = new XmlInput(expectedResult);
XslTransformResults(xsl, xml2, xmlEx);
}
/// <summary>
/// Asserts that the results of an XSL transform on some XML are the expected result
/// </summary>
/// <param name="xslTransform">The XSL transform.</param>
/// <param name="xmlToTransform">The XML to transform.</param>
/// <param name="expectedResult">The expected result.</param>
public static void XslTransformResults(XmlInput xslTransform, XmlInput xmlToTransform, XmlInput expectedResult) {
Xslt xslt = new Xslt(xslTransform);
XmlOutput output = xslt.Transform(xmlToTransform);
XmlEquals(expectedResult, output.AsXml());
}
}
}
| |
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Documents;
using System.Windows.Media;
namespace MaterialDesignThemes.Wpf
{
/// <summary>
/// Helper properties for working with text fields.
/// </summary>
public static class TextFieldAssist
{
/// <summary>
/// The text box view margin property
/// </summary>
public static readonly DependencyProperty TextBoxViewMarginProperty = DependencyProperty.RegisterAttached(
"TextBoxViewMargin",
typeof(Thickness),
typeof(TextFieldAssist),
new FrameworkPropertyMetadata(new Thickness(double.NegativeInfinity), FrameworkPropertyMetadataOptions.Inherits, TextBoxViewMarginPropertyChangedCallback));
/// <summary>
/// Sets the text box view margin.
/// </summary>
/// <param name="element">The element.</param>
/// <param name="value">The value.</param>
public static void SetTextBoxViewMargin(DependencyObject element, Thickness value) => element.SetValue(TextBoxViewMarginProperty, value);
/// <summary>
/// Gets the text box view margin.
/// </summary>
/// <param name="element">The element.</param>
/// <returns>
/// The <see cref="Thickness" />.
/// </returns>
public static Thickness GetTextBoxViewMargin(DependencyObject element) => (Thickness)element.GetValue(TextBoxViewMarginProperty);
/// <summary>
/// Controls the visibility of the underline decoration.
/// </summary>
public static readonly DependencyProperty DecorationVisibilityProperty = DependencyProperty.RegisterAttached(
"DecorationVisibility", typeof(Visibility), typeof(TextFieldAssist), new PropertyMetadata(default(Visibility)));
/// <summary>
/// Controls the visibility of the underline decoration.
/// </summary>
public static void SetDecorationVisibility(DependencyObject element, Visibility value) => element.SetValue(DecorationVisibilityProperty, value);
/// <summary>
/// Controls the visibility of the underline decoration.
/// </summary>
/// <param name="element"></param>
/// <returns></returns>
public static Visibility GetDecorationVisibility(DependencyObject element) => (Visibility)element.GetValue(DecorationVisibilityProperty);
/// <summary>
/// The attached WPF property for getting or setting the <see cref="Brush"/> value for an underline decoration.
/// </summary>
public static readonly DependencyProperty UnderlineBrushProperty = DependencyProperty.RegisterAttached(
"UnderlineBrush", typeof(Brush), typeof(TextFieldAssist), new PropertyMetadata(Brushes.Transparent));
/// <summary>
/// Sets the <see cref="Brush"/> used for underline decoration.
/// </summary>
/// <param name="element"></param>
/// <param name="value"></param>
public static void SetUnderlineBrush(DependencyObject element, Brush value) => element.SetValue(UnderlineBrushProperty, value);
/// <summary>
/// Gets the <see cref="Brush"/> used for underline decoration.
/// </summary>
/// <param name="element"></param>
public static Brush GetUnderlineBrush(DependencyObject element) => (Brush)element.GetValue(UnderlineBrushProperty);
/// <summary>
/// Controls the visbility of the text field box.
/// </summary>
public static readonly DependencyProperty HasFilledTextFieldProperty = DependencyProperty.RegisterAttached(
"HasFilledTextField", typeof(bool), typeof(TextFieldAssist), new PropertyMetadata(false));
public static void SetHasFilledTextField(DependencyObject element, bool value) => element.SetValue(HasFilledTextFieldProperty, value);
public static bool GetHasFilledTextField(DependencyObject element) => (bool)element.GetValue(HasFilledTextFieldProperty);
/// <summary>
/// Controls the visibility of the text field area box.
/// </summary>
public static readonly DependencyProperty HasOutlinedTextFieldProperty = DependencyProperty.RegisterAttached(
"HasOutlinedTextField", typeof(bool), typeof(TextFieldAssist), new PropertyMetadata(false));
public static void SetHasOutlinedTextField(DependencyObject element, bool value) => element.SetValue(HasOutlinedTextFieldProperty, value);
public static bool GetHasOutlinedTextField(DependencyObject element) => (bool)element.GetValue(HasOutlinedTextFieldProperty);
/// <summary>
/// Controls the corner radius of the surrounding box.
/// </summary>
public static readonly DependencyProperty TextFieldCornerRadiusProperty = DependencyProperty.RegisterAttached(
"TextFieldCornerRadius", typeof(CornerRadius), typeof(TextFieldAssist), new PropertyMetadata(new CornerRadius(0.0)));
public static void SetTextFieldCornerRadius(DependencyObject element, CornerRadius value) => element.SetValue(TextFieldCornerRadiusProperty, value);
public static CornerRadius GetTextFieldCornerRadius(DependencyObject element) => (CornerRadius)element.GetValue(TextFieldCornerRadiusProperty);
/// <summary>
/// Controls the corner radius of the bottom line of the surrounding box.
/// </summary>
public static readonly DependencyProperty UnderlineCornerRadiusProperty = DependencyProperty.RegisterAttached(
"UnderlineCornerRadius", typeof(CornerRadius), typeof(TextFieldAssist), new PropertyMetadata(new CornerRadius(0.0)));
public static void SetUnderlineCornerRadius(DependencyObject element, CornerRadius value) => element.SetValue(UnderlineCornerRadiusProperty, value);
public static CornerRadius GetUnderlineCornerRadius(DependencyObject element) => (CornerRadius)element.GetValue(UnderlineCornerRadiusProperty);
/// <summary>
/// Controls the highlighting style of a text box.
/// </summary>
public static readonly DependencyProperty NewSpecHighlightingEnabledProperty = DependencyProperty.RegisterAttached(
"NewSpecHighlightingEnabled", typeof(bool), typeof(TextFieldAssist), new PropertyMetadata(false));
public static void SetNewSpecHighlightingEnabled(DependencyObject element, bool value) => element.SetValue(NewSpecHighlightingEnabledProperty, value);
public static bool GetNewSpecHighlightingEnabled(DependencyObject element) => (bool)element.GetValue(NewSpecHighlightingEnabledProperty);
/// <summary>
/// Enables a ripple effect on focusing the text box.
/// </summary>
public static readonly DependencyProperty RippleOnFocusEnabledProperty = DependencyProperty.RegisterAttached(
"RippleOnFocusEnabled", typeof(bool), typeof(TextFieldAssist), new PropertyMetadata(false));
public static void SetRippleOnFocusEnabled(DependencyObject element, bool value) => element.SetValue(RippleOnFocusEnabledProperty, value);
public static bool GetRippleOnFocusEnabled(DependencyObject element) => (bool)element.GetValue(RippleOnFocusEnabledProperty);
/// <summary>
/// Automatically inserts spelling suggestions into the text box context menu.
/// </summary>
public static readonly DependencyProperty IncludeSpellingSuggestionsProperty = DependencyProperty.RegisterAttached(
"IncludeSpellingSuggestions", typeof(bool), typeof(TextFieldAssist), new PropertyMetadata(default(bool), IncludeSpellingSuggestionsChanged));
public static void SetIncludeSpellingSuggestions(TextBoxBase element, bool value) => element.SetValue(IncludeSpellingSuggestionsProperty, value);
public static bool GetIncludeSpellingSuggestions(TextBoxBase element) => (bool)element.GetValue(IncludeSpellingSuggestionsProperty);
/// <summary>
/// SuffixText dependency property
/// </summary>
public static readonly DependencyProperty SuffixTextProperty = DependencyProperty.RegisterAttached(
"SuffixText", typeof(string), typeof(TextFieldAssist), new PropertyMetadata(default(string?)));
public static void SetSuffixText(DependencyObject element, string? value)
=> element.SetValue(SuffixTextProperty, value);
public static string? GetSuffixText(DependencyObject element)
=> (string?)element.GetValue(SuffixTextProperty);
/// <summary>
/// PrefixText dependency property
/// </summary>
public static readonly DependencyProperty PrefixTextProperty = DependencyProperty.RegisterAttached(
"PrefixText", typeof(string), typeof(TextFieldAssist), new PropertyMetadata(default(string?)));
public static void SetPrefixText(DependencyObject element, string? value)
=> element.SetValue(PrefixTextProperty, value);
public static string? GetPrefixText(DependencyObject element)
=> (string?)element.GetValue(PrefixTextProperty);
/// <summary>
/// Controls the visbility of the clear button.
/// </summary>
public static readonly DependencyProperty HasClearButtonProperty = DependencyProperty.RegisterAttached(
"HasClearButton", typeof(bool), typeof(TextFieldAssist), new PropertyMetadata(false, HasClearButtonChanged));
public static void SetHasClearButton(DependencyObject element, bool value)
=> element.SetValue(HasClearButtonProperty, value);
public static bool GetHasClearButton(DependencyObject element)
=> (bool)element.GetValue(HasClearButtonProperty);
/// <summary>
/// Controls visibility of the leading icon
/// </summary>
public static readonly DependencyProperty HasLeadingIconProperty = DependencyProperty.RegisterAttached(
"HasLeadingIcon", typeof(bool), typeof(TextFieldAssist), new PropertyMetadata(default(bool)));
public static void SetHasLeadingIcon(DependencyObject element, bool value)
=> element.SetValue(HasLeadingIconProperty, value);
public static bool GetHasLeadingIcon(DependencyObject element)
=> (bool)element.GetValue(HasLeadingIconProperty);
/// <summary>
/// Controls the leading icon
/// </summary>
public static readonly DependencyProperty LeadingIconProperty = DependencyProperty.RegisterAttached(
"LeadingIcon", typeof(PackIconKind), typeof(TextFieldAssist), new PropertyMetadata());
public static void SetLeadingIcon(DependencyObject element, PackIconKind value)
=> element.SetValue(LeadingIconProperty, value);
public static PackIconKind GetLeadingIcon(DependencyObject element)
=> (PackIconKind)element.GetValue(LeadingIconProperty);
/// <summary>
/// Controls the size of the leading icon
/// </summary>
public static readonly DependencyProperty LeadingIconSizeProperty = DependencyProperty.RegisterAttached(
"LeadingIconSize", typeof(double), typeof(TextFieldAssist), new PropertyMetadata(20.0));
public static void SetLeadingIconSize(DependencyObject element, double value)
=> element.SetValue(LeadingIconSizeProperty, value);
public static double GetLeadingIconSize(DependencyObject element)
=> (double)element.GetValue(LeadingIconSizeProperty);
/// <summary>
/// Controls visibility of the trailing icon
/// </summary>
public static readonly DependencyProperty HasTrailingIconProperty = DependencyProperty.RegisterAttached(
"HasTrailingIcon", typeof(bool), typeof(TextFieldAssist), new PropertyMetadata(default(bool)));
public static void SetHasTrailingIcon(DependencyObject element, bool value)
=> element.SetValue(HasTrailingIconProperty, value);
public static bool GetHasTrailingIcon(DependencyObject element)
=> (bool)element.GetValue(HasTrailingIconProperty);
/// <summary>
/// Controls the trailing icon
/// </summary>
public static readonly DependencyProperty TrailingIconProperty = DependencyProperty.RegisterAttached(
"TrailingIcon", typeof(PackIconKind), typeof(TextFieldAssist), new PropertyMetadata());
public static void SetTrailingIcon(DependencyObject element, PackIconKind value)
=> element.SetValue(TrailingIconProperty, value);
public static PackIconKind GetTrailingIcon(DependencyObject element)
=> (PackIconKind)element.GetValue(TrailingIconProperty);
/// <summary>
/// Controls the size of the trailing icon
/// </summary>
public static readonly DependencyProperty TrailingIconSizeProperty = DependencyProperty.RegisterAttached(
"TrailingIconSize", typeof(double), typeof(TextFieldAssist), new PropertyMetadata(20.0));
public static void SetTrailingIconSize(DependencyObject element, double value)
=> element.SetValue(TrailingIconSizeProperty, value);
public static double GetTrailingIconSize(DependencyObject element)
=> (double)element.GetValue(TrailingIconSizeProperty);
public static Style GetCharacterCounterStyle(DependencyObject obj) => (Style)obj.GetValue(CharacterCounterStyleProperty);
public static void SetCharacterCounterStyle(DependencyObject obj, Style value) => obj.SetValue(CharacterCounterStyleProperty, value);
public static readonly DependencyProperty CharacterCounterStyleProperty =
DependencyProperty.RegisterAttached("CharacterCounterStyle", typeof(Style), typeof(TextFieldAssist), new PropertyMetadata(null));
public static Visibility GetCharacterCounterVisibility(DependencyObject obj)
=> (Visibility)obj.GetValue(CharacterCounterVisibilityProperty);
public static void SetCharacterCounterVisibility(DependencyObject obj, Visibility value)
=> obj.SetValue(CharacterCounterVisibilityProperty, value);
public static readonly DependencyProperty CharacterCounterVisibilityProperty =
DependencyProperty.RegisterAttached("CharacterCounterVisibility", typeof(Visibility), typeof(TextFieldAssist),
new PropertyMetadata(Visibility.Visible));
#region Methods
private static void IncludeSpellingSuggestionsChanged(DependencyObject element, DependencyPropertyChangedEventArgs e)
{
if (element is TextBoxBase textBox)
{
if ((bool)e.NewValue)
{
textBox.ContextMenuOpening += TextBoxOnContextMenuOpening;
textBox.ContextMenuClosing += TextBoxOnContextMenuClosing;
}
else
{
textBox.ContextMenuOpening -= TextBoxOnContextMenuOpening;
textBox.ContextMenuClosing -= TextBoxOnContextMenuClosing;
}
}
}
private static void TextBoxOnContextMenuOpening(object sender, ContextMenuEventArgs e)
{
var textBoxBase = sender as TextBoxBase;
ContextMenu? contextMenu = textBoxBase?.ContextMenu;
if (contextMenu is null) return;
RemoveSpellingSuggestions(contextMenu);
if (!SpellCheck.GetIsEnabled(textBoxBase)) return;
SpellingError? spellingError = GetSpellingError(textBoxBase);
if (spellingError != null)
{
Style? spellingSuggestionStyle =
contextMenu.TryFindResource(Spelling.SuggestionMenuItemStyleKey) as Style;
int insertionIndex = 0;
bool hasSuggestion = false;
foreach (string suggestion in spellingError.Suggestions)
{
hasSuggestion = true;
var menuItem = new MenuItem
{
CommandTarget = textBoxBase,
Command = EditingCommands.CorrectSpellingError,
CommandParameter = suggestion,
Style = spellingSuggestionStyle,
Tag = typeof(Spelling)
};
contextMenu.Items.Insert(insertionIndex++, menuItem);
}
if (!hasSuggestion)
{
contextMenu.Items.Insert(insertionIndex++, new MenuItem
{
Style = contextMenu.TryFindResource(Spelling.NoSuggestionsMenuItemStyleKey) as Style,
Tag = typeof(Spelling)
});
}
contextMenu.Items.Insert(insertionIndex++, new Separator
{
Style = contextMenu.TryFindResource(Spelling.SeparatorStyleKey) as Style,
Tag = typeof(Spelling)
});
contextMenu.Items.Insert(insertionIndex++, new MenuItem
{
Command = EditingCommands.IgnoreSpellingError,
CommandTarget = textBoxBase,
Style = contextMenu.TryFindResource(Spelling.IgnoreAllMenuItemStyleKey) as Style,
Tag = typeof(Spelling)
});
contextMenu.Items.Insert(insertionIndex, new Separator
{
Style = contextMenu.TryFindResource(Spelling.SeparatorStyleKey) as Style,
Tag = typeof(Spelling)
});
}
}
private static SpellingError? GetSpellingError(TextBoxBase? textBoxBase)
{
if (textBoxBase is TextBox textBox)
{
return textBox.GetSpellingError(textBox.CaretIndex);
}
if (textBoxBase is RichTextBox richTextBox)
{
return richTextBox.GetSpellingError(richTextBox.CaretPosition);
}
return null;
}
private static void TextBoxOnContextMenuClosing(object sender, ContextMenuEventArgs e)
{
var contextMenu = (sender as TextBoxBase)?.ContextMenu;
if (contextMenu != null)
{
RemoveSpellingSuggestions(contextMenu);
}
}
private static void RemoveSpellingSuggestions(ContextMenu menu)
{
foreach (FrameworkElement item in (from item in menu.Items.OfType<FrameworkElement>()
where ReferenceEquals(item.Tag, typeof(Spelling))
select item).ToList())
{
menu.Items.Remove(item);
}
}
private static void HasClearButtonChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var box = d as Control; //could be a text box or password box
if (box == null)
{
return;
}
if (box.IsLoaded)
SetClearHandler(box);
else
box.Loaded += (sender, args) =>
SetClearHandler(box);
}
private static void SetClearHandler(Control box)
{
var bValue = GetHasClearButton(box);
var clearButton = box.Template.FindName("PART_ClearButton", box) as Button;
if (clearButton != null)
{
RoutedEventHandler handler = (sender, args) =>
{
(box as TextBox)?.SetCurrentValue(TextBox.TextProperty, null);
(box as ComboBox)?.SetCurrentValue(ComboBox.TextProperty, null);
if (box is PasswordBox passwordBox)
{
passwordBox.Password = null;
}
};
if (bValue)
clearButton.Click += handler;
else
clearButton.Click -= handler;
}
}
/// <summary>
/// Applies the text box view margin.
/// </summary>
/// <param name="textBox">The text box.</param>
/// <param name="margin">The margin.</param>
private static void ApplyTextBoxViewMargin(Control textBox, Thickness margin)
{
if (margin.Equals(new Thickness(double.NegativeInfinity))
|| textBox.Template is null)
{
return;
}
if (textBox is ComboBox
&& textBox.Template.FindName("PART_EditableTextBox", textBox) is TextBox editableTextBox)
{
textBox = editableTextBox;
if (textBox.Template is null) return;
textBox.ApplyTemplate();
}
if (textBox.Template.FindName("PART_ContentHost", textBox) is ScrollViewer scrollViewer
&& scrollViewer.Content is FrameworkElement frameworkElement)
{
frameworkElement.Margin = margin;
}
}
/// <summary>
/// The text box view margin property changed callback.
/// </summary>
/// <param name="dependencyObject">The dependency object.</param>
/// <param name="dependencyPropertyChangedEventArgs">The dependency property changed event args.</param>
private static void TextBoxViewMarginPropertyChangedCallback(
DependencyObject dependencyObject,
DependencyPropertyChangedEventArgs dependencyPropertyChangedEventArgs)
{
if (dependencyObject is not Control box)
{
return;
}
if (box.IsLoaded)
{
ApplyTextBoxViewMargin(box, (Thickness)dependencyPropertyChangedEventArgs.NewValue);
}
box.Loaded += (sender, args) =>
{
var textBox = (Control)sender;
ApplyTextBoxViewMargin(textBox, GetTextBoxViewMargin(textBox));
};
}
#endregion
}
}
| |
using Microsoft.IdentityModel.S2S.Protocols.OAuth2;
using Microsoft.IdentityModel.Tokens;
using Microsoft.SharePoint.Client;
using System;
using System.Net;
using System.Security.Principal;
using System.Web;
using System.Web.Configuration;
namespace Contoso.Core.PeoplePickerWeb
{
/// <summary>
/// Encapsulates all the information from SharePoint.
/// </summary>
public abstract class SharePointContext
{
public const string SPHostUrlKey = "SPHostUrl";
public const string SPAppWebUrlKey = "SPAppWebUrl";
public const string SPLanguageKey = "SPLanguage";
public const string SPClientTagKey = "SPClientTag";
public const string SPProductNumberKey = "SPProductNumber";
protected static readonly TimeSpan AccessTokenLifetimeTolerance = TimeSpan.FromMinutes(5.0);
private readonly Uri spHostUrl;
private readonly Uri spAppWebUrl;
private readonly string spLanguage;
private readonly string spClientTag;
private readonly string spProductNumber;
// <AccessTokenString, UtcExpiresOn>
protected Tuple<string, DateTime> userAccessTokenForSPHost;
protected Tuple<string, DateTime> userAccessTokenForSPAppWeb;
protected Tuple<string, DateTime> appOnlyAccessTokenForSPHost;
protected Tuple<string, DateTime> appOnlyAccessTokenForSPAppWeb;
/// <summary>
/// Gets the SharePoint host url from QueryString of the specified HTTP request.
/// </summary>
/// <param name="httpRequest">The specified HTTP request.</param>
/// <returns>The SharePoint host url. Returns <c>null</c> if the HTTP request doesn't contain the SharePoint host url.</returns>
public static Uri GetSPHostUrl(HttpRequestBase httpRequest)
{
if (httpRequest == null)
{
throw new ArgumentNullException("httpRequest");
}
string spHostUrlString = TokenHelper.EnsureTrailingSlash(httpRequest.QueryString[SPHostUrlKey]);
Uri spHostUrl;
if (Uri.TryCreate(spHostUrlString, UriKind.Absolute, out spHostUrl) &&
(spHostUrl.Scheme == Uri.UriSchemeHttp || spHostUrl.Scheme == Uri.UriSchemeHttps))
{
return spHostUrl;
}
return null;
}
/// <summary>
/// Gets the SharePoint host url from QueryString of the specified HTTP request.
/// </summary>
/// <param name="httpRequest">The specified HTTP request.</param>
/// <returns>The SharePoint host url. Returns <c>null</c> if the HTTP request doesn't contain the SharePoint host url.</returns>
public static Uri GetSPHostUrl(HttpRequest httpRequest)
{
return GetSPHostUrl(new HttpRequestWrapper(httpRequest));
}
/// <summary>
/// The SharePoint host url.
/// </summary>
public Uri SPHostUrl
{
get { return this.spHostUrl; }
}
/// <summary>
/// The SharePoint app web url.
/// </summary>
public Uri SPAppWebUrl
{
get { return this.spAppWebUrl; }
}
/// <summary>
/// The SharePoint language.
/// </summary>
public string SPLanguage
{
get { return this.spLanguage; }
}
/// <summary>
/// The SharePoint client tag.
/// </summary>
public string SPClientTag
{
get { return this.spClientTag; }
}
/// <summary>
/// The SharePoint product number.
/// </summary>
public string SPProductNumber
{
get { return this.spProductNumber; }
}
/// <summary>
/// The user access token for the SharePoint host.
/// </summary>
public abstract string UserAccessTokenForSPHost
{
get;
}
/// <summary>
/// The user access token for the SharePoint app web.
/// </summary>
public abstract string UserAccessTokenForSPAppWeb
{
get;
}
/// <summary>
/// The app only access token for the SharePoint host.
/// </summary>
public abstract string AppOnlyAccessTokenForSPHost
{
get;
}
/// <summary>
/// The app only access token for the SharePoint app web.
/// </summary>
public abstract string AppOnlyAccessTokenForSPAppWeb
{
get;
}
/// <summary>
/// Constructor.
/// </summary>
/// <param name="spHostUrl">The SharePoint host url.</param>
/// <param name="spAppWebUrl">The SharePoint app web url.</param>
/// <param name="spLanguage">The SharePoint language.</param>
/// <param name="spClientTag">The SharePoint client tag.</param>
/// <param name="spProductNumber">The SharePoint product number.</param>
protected SharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber)
{
if (spHostUrl == null)
{
throw new ArgumentNullException("spHostUrl");
}
if (string.IsNullOrEmpty(spLanguage))
{
throw new ArgumentNullException("spLanguage");
}
if (string.IsNullOrEmpty(spClientTag))
{
throw new ArgumentNullException("spClientTag");
}
if (string.IsNullOrEmpty(spProductNumber))
{
throw new ArgumentNullException("spProductNumber");
}
this.spHostUrl = spHostUrl;
this.spAppWebUrl = spAppWebUrl;
this.spLanguage = spLanguage;
this.spClientTag = spClientTag;
this.spProductNumber = spProductNumber;
}
/// <summary>
/// Creates a user ClientContext for the SharePoint host.
/// </summary>
/// <returns>A ClientContext instance.</returns>
public ClientContext CreateUserClientContextForSPHost()
{
return CreateClientContext(this.SPHostUrl, this.UserAccessTokenForSPHost);
}
/// <summary>
/// Creates a user ClientContext for the SharePoint app web.
/// </summary>
/// <returns>A ClientContext instance.</returns>
public ClientContext CreateUserClientContextForSPAppWeb()
{
return CreateClientContext(this.SPAppWebUrl, this.UserAccessTokenForSPAppWeb);
}
/// <summary>
/// Creates app only ClientContext for the SharePoint host.
/// </summary>
/// <returns>A ClientContext instance.</returns>
public ClientContext CreateAppOnlyClientContextForSPHost()
{
return CreateClientContext(this.SPHostUrl, this.AppOnlyAccessTokenForSPHost);
}
/// <summary>
/// Creates an app only ClientContext for the SharePoint app web.
/// </summary>
/// <returns>A ClientContext instance.</returns>
public ClientContext CreateAppOnlyClientContextForSPAppWeb()
{
return CreateClientContext(this.SPAppWebUrl, this.AppOnlyAccessTokenForSPAppWeb);
}
/// <summary>
/// Gets the database connection string from SharePoint for autohosted app.
/// </summary>
/// <returns>The database connection string. Returns <c>null</c> if the app is not autohosted or there is no database.</returns>
public string GetDatabaseConnectionString()
{
string dbConnectionString = null;
using (ClientContext clientContext = CreateAppOnlyClientContextForSPHost())
{
if (clientContext != null)
{
var result = AppInstance.RetrieveAppDatabaseConnectionString(clientContext);
clientContext.ExecuteQuery();
dbConnectionString = result.Value;
}
}
if (dbConnectionString == null)
{
const string LocalDBInstanceForDebuggingKey = "LocalDBInstanceForDebugging";
var dbConnectionStringSettings = WebConfigurationManager.ConnectionStrings[LocalDBInstanceForDebuggingKey];
dbConnectionString = dbConnectionStringSettings != null ? dbConnectionStringSettings.ConnectionString : null;
}
return dbConnectionString;
}
/// <summary>
/// Determines if the specified access token is valid.
/// It considers an access token as not valid if it is null, or it has expired.
/// </summary>
/// <param name="accessToken">The access token to verify.</param>
/// <returns>True if the access token is valid.</returns>
protected static bool IsAccessTokenValid(Tuple<string, DateTime> accessToken)
{
return accessToken != null &&
!string.IsNullOrEmpty(accessToken.Item1) &&
accessToken.Item2 > DateTime.UtcNow;
}
/// <summary>
/// Creates a ClientContext with the specified SharePoint site url and the access token.
/// </summary>
/// <param name="spSiteUrl">The site url.</param>
/// <param name="accessToken">The access token.</param>
/// <returns>A ClientContext instance.</returns>
private static ClientContext CreateClientContext(Uri spSiteUrl, string accessToken)
{
if (spSiteUrl != null && !string.IsNullOrEmpty(accessToken))
{
return TokenHelper.GetClientContextWithAccessToken(spSiteUrl.AbsoluteUri, accessToken);
}
return null;
}
}
/// <summary>
/// Redirection status.
/// </summary>
public enum RedirectionStatus
{
Ok,
ShouldRedirect,
CanNotRedirect
}
/// <summary>
/// Provides SharePointContext instances.
/// </summary>
public abstract class SharePointContextProvider
{
private static SharePointContextProvider current;
/// <summary>
/// The current SharePointContextProvider instance.
/// </summary>
public static SharePointContextProvider Current
{
get { return SharePointContextProvider.current; }
}
/// <summary>
/// Initializes the default SharePointContextProvider instance.
/// </summary>
static SharePointContextProvider()
{
if (!TokenHelper.IsHighTrustApp())
{
SharePointContextProvider.current = new SharePointAcsContextProvider();
}
else
{
SharePointContextProvider.current = new SharePointHighTrustContextProvider();
}
}
/// <summary>
/// Registers the specified SharePointContextProvider instance as current.
/// It should be called by Application_Start() in Global.asax.
/// </summary>
/// <param name="provider">The SharePointContextProvider to be set as current.</param>
public static void Register(SharePointContextProvider provider)
{
if (provider == null)
{
throw new ArgumentNullException("provider");
}
SharePointContextProvider.current = provider;
}
/// <summary>
/// Checks if it is necessary to redirect to SharePoint for user to authenticate.
/// </summary>
/// <param name="httpContext">The HTTP context.</param>
/// <param name="redirectUrl">The redirect url to SharePoint if the status is ShouldRedirect. <c>Null</c> if the status is Ok or CanNotRedirect.</param>
/// <returns>Redirection status.</returns>
public static RedirectionStatus CheckRedirectionStatus(HttpContextBase httpContext, out Uri redirectUrl)
{
if (httpContext == null)
{
throw new ArgumentNullException("httpContext");
}
redirectUrl = null;
if (SharePointContextProvider.Current.GetSharePointContext(httpContext) != null)
{
return RedirectionStatus.Ok;
}
const string SPHasRedirectedToSharePointKey = "SPHasRedirectedToSharePoint";
if (!string.IsNullOrEmpty(httpContext.Request.QueryString[SPHasRedirectedToSharePointKey]))
{
return RedirectionStatus.CanNotRedirect;
}
Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request);
if (spHostUrl == null)
{
return RedirectionStatus.CanNotRedirect;
}
if (StringComparer.OrdinalIgnoreCase.Equals(httpContext.Request.HttpMethod, "POST"))
{
return RedirectionStatus.CanNotRedirect;
}
Uri requestUrl = httpContext.Request.Url;
var queryNameValueCollection = HttpUtility.ParseQueryString(requestUrl.Query);
// Removes the values that are included in {StandardTokens}, as {StandardTokens} will be inserted at the beginning of the query string.
queryNameValueCollection.Remove(SharePointContext.SPHostUrlKey);
queryNameValueCollection.Remove(SharePointContext.SPAppWebUrlKey);
queryNameValueCollection.Remove(SharePointContext.SPLanguageKey);
queryNameValueCollection.Remove(SharePointContext.SPClientTagKey);
queryNameValueCollection.Remove(SharePointContext.SPProductNumberKey);
// Adds SPHasRedirectedToSharePoint=1.
queryNameValueCollection.Add(SPHasRedirectedToSharePointKey, "1");
UriBuilder returnUrlBuilder = new UriBuilder(requestUrl);
returnUrlBuilder.Query = queryNameValueCollection.ToString();
// Inserts StandardTokens.
const string StandardTokens = "{StandardTokens}";
string returnUrlString = returnUrlBuilder.Uri.AbsoluteUri;
returnUrlString = returnUrlString.Insert(returnUrlString.IndexOf("?") + 1, StandardTokens + "&");
// Constructs redirect url.
string redirectUrlString = TokenHelper.GetAppContextTokenRequestUrl(spHostUrl.AbsoluteUri, Uri.EscapeDataString(returnUrlString));
redirectUrl = new Uri(redirectUrlString, UriKind.Absolute);
return RedirectionStatus.ShouldRedirect;
}
/// <summary>
/// Checks if it is necessary to redirect to SharePoint for user to authenticate.
/// </summary>
/// <param name="httpContext">The HTTP context.</param>
/// <param name="redirectUrl">The redirect url to SharePoint if the status is ShouldRedirect. <c>Null</c> if the status is Ok or CanNotRedirect.</param>
/// <returns>Redirection status.</returns>
public static RedirectionStatus CheckRedirectionStatus(HttpContext httpContext, out Uri redirectUrl)
{
return CheckRedirectionStatus(new HttpContextWrapper(httpContext), out redirectUrl);
}
/// <summary>
/// Creates a SharePointContext instance with the specified HTTP request.
/// </summary>
/// <param name="httpRequest">The HTTP request.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns>
public SharePointContext CreateSharePointContext(HttpRequestBase httpRequest)
{
if (httpRequest == null)
{
throw new ArgumentNullException("httpRequest");
}
// SPHostUrl
Uri spHostUrl = SharePointContext.GetSPHostUrl(httpRequest);
if (spHostUrl == null)
{
return null;
}
// SPAppWebUrl
string spAppWebUrlString = TokenHelper.EnsureTrailingSlash(httpRequest.QueryString[SharePointContext.SPAppWebUrlKey]);
Uri spAppWebUrl;
if (!Uri.TryCreate(spAppWebUrlString, UriKind.Absolute, out spAppWebUrl) ||
!(spAppWebUrl.Scheme == Uri.UriSchemeHttp || spAppWebUrl.Scheme == Uri.UriSchemeHttps))
{
spAppWebUrl = null;
}
// SPLanguage
string spLanguage = httpRequest.QueryString[SharePointContext.SPLanguageKey];
if (string.IsNullOrEmpty(spLanguage))
{
return null;
}
// SPClientTag
string spClientTag = httpRequest.QueryString[SharePointContext.SPClientTagKey];
if (string.IsNullOrEmpty(spClientTag))
{
return null;
}
// SPProductNumber
string spProductNumber = httpRequest.QueryString[SharePointContext.SPProductNumberKey];
if (string.IsNullOrEmpty(spProductNumber))
{
return null;
}
return CreateSharePointContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, httpRequest);
}
/// <summary>
/// Creates a SharePointContext instance with the specified HTTP request.
/// </summary>
/// <param name="httpRequest">The HTTP request.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns>
public SharePointContext CreateSharePointContext(HttpRequest httpRequest)
{
return CreateSharePointContext(new HttpRequestWrapper(httpRequest));
}
/// <summary>
/// Gets a SharePointContext instance associated with the specified HTTP context.
/// </summary>
/// <param name="httpContext">The HTTP context.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if not found and a new instance can't be created.</returns>
public SharePointContext GetSharePointContext(HttpContextBase httpContext)
{
if (httpContext == null)
{
throw new ArgumentNullException("httpContext");
}
Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request);
if (spHostUrl == null)
{
return null;
}
SharePointContext spContext = LoadSharePointContext(httpContext);
if (spContext == null || !ValidateSharePointContext(spContext, httpContext))
{
spContext = CreateSharePointContext(httpContext.Request);
if (spContext != null)
{
SaveSharePointContext(spContext, httpContext);
}
}
return spContext;
}
/// <summary>
/// Gets a SharePointContext instance associated with the specified HTTP context.
/// </summary>
/// <param name="httpContext">The HTTP context.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if not found and a new instance can't be created.</returns>
public SharePointContext GetSharePointContext(HttpContext httpContext)
{
return GetSharePointContext(new HttpContextWrapper(httpContext));
}
/// <summary>
/// Creates a SharePointContext instance.
/// </summary>
/// <param name="spHostUrl">The SharePoint host url.</param>
/// <param name="spAppWebUrl">The SharePoint app web url.</param>
/// <param name="spLanguage">The SharePoint language.</param>
/// <param name="spClientTag">The SharePoint client tag.</param>
/// <param name="spProductNumber">The SharePoint product number.</param>
/// <param name="httpRequest">The HTTP request.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns>
protected abstract SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest);
/// <summary>
/// Validates if the given SharePointContext can be used with the specified HTTP context.
/// </summary>
/// <param name="spContext">The SharePointContext.</param>
/// <param name="httpContext">The HTTP context.</param>
/// <returns>True if the given SharePointContext can be used with the specified HTTP context.</returns>
protected abstract bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext);
/// <summary>
/// Loads the SharePointContext instance associated with the specified HTTP context.
/// </summary>
/// <param name="httpContext">The HTTP context.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if not found.</returns>
protected abstract SharePointContext LoadSharePointContext(HttpContextBase httpContext);
/// <summary>
/// Saves the specified SharePointContext instance associated with the specified HTTP context.
/// <c>null</c> is accepted for clearing the SharePointContext instance associated with the HTTP context.
/// </summary>
/// <param name="spContext">The SharePointContext instance to be saved, or <c>null</c>.</param>
/// <param name="httpContext">The HTTP context.</param>
protected abstract void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext);
}
#region ACS
/// <summary>
/// Encapsulates all the information from SharePoint in ACS mode.
/// </summary>
public class SharePointAcsContext : SharePointContext
{
private readonly string contextToken;
private readonly SharePointContextToken contextTokenObj;
/// <summary>
/// The context token.
/// </summary>
public string ContextToken
{
get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextToken : null; }
}
/// <summary>
/// The context token's "CacheKey" claim.
/// </summary>
public string CacheKey
{
get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextTokenObj.CacheKey : null; }
}
/// <summary>
/// The context token's "refreshtoken" claim.
/// </summary>
public string RefreshToken
{
get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextTokenObj.RefreshToken : null; }
}
public override string UserAccessTokenForSPHost
{
get
{
return GetAccessTokenString(ref this.userAccessTokenForSPHost,
() => TokenHelper.GetAccessToken(this.contextTokenObj, this.SPHostUrl.Authority));
}
}
public override string UserAccessTokenForSPAppWeb
{
get
{
if (this.SPAppWebUrl == null)
{
return null;
}
return GetAccessTokenString(ref this.userAccessTokenForSPAppWeb,
() => TokenHelper.GetAccessToken(this.contextTokenObj, this.SPAppWebUrl.Authority));
}
}
public override string AppOnlyAccessTokenForSPHost
{
get
{
return GetAccessTokenString(ref this.appOnlyAccessTokenForSPHost,
() => TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, this.SPHostUrl.Authority, TokenHelper.GetRealmFromTargetUrl(this.SPHostUrl)));
}
}
public override string AppOnlyAccessTokenForSPAppWeb
{
get
{
if (this.SPAppWebUrl == null)
{
return null;
}
return GetAccessTokenString(ref this.appOnlyAccessTokenForSPAppWeb,
() => TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, this.SPAppWebUrl.Authority, TokenHelper.GetRealmFromTargetUrl(this.SPAppWebUrl)));
}
}
public SharePointAcsContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, string contextToken, SharePointContextToken contextTokenObj)
: base(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber)
{
if (string.IsNullOrEmpty(contextToken))
{
throw new ArgumentNullException("contextToken");
}
if (contextTokenObj == null)
{
throw new ArgumentNullException("contextTokenObj");
}
this.contextToken = contextToken;
this.contextTokenObj = contextTokenObj;
}
/// <summary>
/// Ensures the access token is valid and returns it.
/// </summary>
/// <param name="accessToken">The access token to verify.</param>
/// <param name="tokenRenewalHandler">The token renewal handler.</param>
/// <returns>The access token string.</returns>
private static string GetAccessTokenString(ref Tuple<string, DateTime> accessToken, Func<OAuth2AccessTokenResponse> tokenRenewalHandler)
{
RenewAccessTokenIfNeeded(ref accessToken, tokenRenewalHandler);
return IsAccessTokenValid(accessToken) ? accessToken.Item1 : null;
}
/// <summary>
/// Renews the access token if it is not valid.
/// </summary>
/// <param name="accessToken">The access token to renew.</param>
/// <param name="tokenRenewalHandler">The token renewal handler.</param>
private static void RenewAccessTokenIfNeeded(ref Tuple<string, DateTime> accessToken, Func<OAuth2AccessTokenResponse> tokenRenewalHandler)
{
if (IsAccessTokenValid(accessToken))
{
return;
}
try
{
OAuth2AccessTokenResponse oAuth2AccessTokenResponse = tokenRenewalHandler();
DateTime expiresOn = oAuth2AccessTokenResponse.ExpiresOn;
if ((expiresOn - oAuth2AccessTokenResponse.NotBefore) > AccessTokenLifetimeTolerance)
{
// Make the access token get renewed a bit earlier than the time when it expires
// so that the calls to SharePoint with it will have enough time to complete successfully.
expiresOn -= AccessTokenLifetimeTolerance;
}
accessToken = Tuple.Create(oAuth2AccessTokenResponse.AccessToken, expiresOn);
}
catch (WebException)
{
}
}
}
/// <summary>
/// Default provider for SharePointAcsContext.
/// </summary>
public class SharePointAcsContextProvider : SharePointContextProvider
{
private const string SPContextKey = "SPContext";
private const string SPCacheKeyKey = "SPCacheKey";
protected override SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest)
{
string contextTokenString = TokenHelper.GetContextTokenFromRequest(httpRequest);
if (string.IsNullOrEmpty(contextTokenString))
{
return null;
}
SharePointContextToken contextToken = null;
try
{
contextToken = TokenHelper.ReadAndValidateContextToken(contextTokenString, httpRequest.Url.Authority);
}
catch (WebException)
{
return null;
}
catch (AudienceUriValidationFailedException)
{
return null;
}
return new SharePointAcsContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, contextTokenString, contextToken);
}
protected override bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext)
{
SharePointAcsContext spAcsContext = spContext as SharePointAcsContext;
if (spAcsContext != null)
{
Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request);
string contextToken = TokenHelper.GetContextTokenFromRequest(httpContext.Request);
HttpCookie spCacheKeyCookie = httpContext.Request.Cookies[SPCacheKeyKey];
string spCacheKey = spCacheKeyCookie != null ? spCacheKeyCookie.Value : null;
return spHostUrl == spAcsContext.SPHostUrl &&
!string.IsNullOrEmpty(spAcsContext.CacheKey) &&
spCacheKey == spAcsContext.CacheKey &&
!string.IsNullOrEmpty(spAcsContext.ContextToken) &&
(string.IsNullOrEmpty(contextToken) || contextToken == spAcsContext.ContextToken);
}
return false;
}
protected override SharePointContext LoadSharePointContext(HttpContextBase httpContext)
{
return httpContext.Session[SPContextKey] as SharePointAcsContext;
}
protected override void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext)
{
SharePointAcsContext spAcsContext = spContext as SharePointAcsContext;
if (spAcsContext != null)
{
HttpCookie spCacheKeyCookie = new HttpCookie(SPCacheKeyKey)
{
Value = spAcsContext.CacheKey,
Secure = true,
HttpOnly = true
};
httpContext.Response.AppendCookie(spCacheKeyCookie);
}
httpContext.Session[SPContextKey] = spAcsContext;
}
}
#endregion ACS
#region HighTrust
/// <summary>
/// Encapsulates all the information from SharePoint in HighTrust mode.
/// </summary>
public class SharePointHighTrustContext : SharePointContext
{
private readonly WindowsIdentity logonUserIdentity;
/// <summary>
/// The Windows identity for the current user.
/// </summary>
public WindowsIdentity LogonUserIdentity
{
get { return this.logonUserIdentity; }
}
public override string UserAccessTokenForSPHost
{
get
{
return GetAccessTokenString(ref this.userAccessTokenForSPHost,
() => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPHostUrl, this.LogonUserIdentity));
}
}
public override string UserAccessTokenForSPAppWeb
{
get
{
if (this.SPAppWebUrl == null)
{
return null;
}
return GetAccessTokenString(ref this.userAccessTokenForSPAppWeb,
() => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPAppWebUrl, this.LogonUserIdentity));
}
}
public override string AppOnlyAccessTokenForSPHost
{
get
{
return GetAccessTokenString(ref this.appOnlyAccessTokenForSPHost,
() => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPHostUrl, null));
}
}
public override string AppOnlyAccessTokenForSPAppWeb
{
get
{
if (this.SPAppWebUrl == null)
{
return null;
}
return GetAccessTokenString(ref this.appOnlyAccessTokenForSPAppWeb,
() => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPAppWebUrl, null));
}
}
public SharePointHighTrustContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, WindowsIdentity logonUserIdentity)
: base(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber)
{
if (logonUserIdentity == null)
{
throw new ArgumentNullException("logonUserIdentity");
}
this.logonUserIdentity = logonUserIdentity;
}
/// <summary>
/// Ensures the access token is valid and returns it.
/// </summary>
/// <param name="accessToken">The access token to verify.</param>
/// <param name="tokenRenewalHandler">The token renewal handler.</param>
/// <returns>The access token string.</returns>
private static string GetAccessTokenString(ref Tuple<string, DateTime> accessToken, Func<string> tokenRenewalHandler)
{
RenewAccessTokenIfNeeded(ref accessToken, tokenRenewalHandler);
return IsAccessTokenValid(accessToken) ? accessToken.Item1 : null;
}
/// <summary>
/// Renews the access token if it is not valid.
/// </summary>
/// <param name="accessToken">The access token to renew.</param>
/// <param name="tokenRenewalHandler">The token renewal handler.</param>
private static void RenewAccessTokenIfNeeded(ref Tuple<string, DateTime> accessToken, Func<string> tokenRenewalHandler)
{
if (IsAccessTokenValid(accessToken))
{
return;
}
DateTime expiresOn = DateTime.UtcNow.Add(TokenHelper.HighTrustAccessTokenLifetime);
if (TokenHelper.HighTrustAccessTokenLifetime > AccessTokenLifetimeTolerance)
{
// Make the access token get renewed a bit earlier than the time when it expires
// so that the calls to SharePoint with it will have enough time to complete successfully.
expiresOn -= AccessTokenLifetimeTolerance;
}
accessToken = Tuple.Create(tokenRenewalHandler(), expiresOn);
}
}
/// <summary>
/// Default provider for SharePointHighTrustContext.
/// </summary>
public class SharePointHighTrustContextProvider : SharePointContextProvider
{
private const string SPContextKey = "SPContext";
protected override SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest)
{
WindowsIdentity logonUserIdentity = httpRequest.LogonUserIdentity;
if (logonUserIdentity == null || !logonUserIdentity.IsAuthenticated || logonUserIdentity.IsGuest || logonUserIdentity.User == null)
{
return null;
}
return new SharePointHighTrustContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, logonUserIdentity);
}
protected override bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext)
{
SharePointHighTrustContext spHighTrustContext = spContext as SharePointHighTrustContext;
if (spHighTrustContext != null)
{
Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request);
WindowsIdentity logonUserIdentity = httpContext.Request.LogonUserIdentity;
return spHostUrl == spHighTrustContext.SPHostUrl &&
logonUserIdentity != null &&
logonUserIdentity.IsAuthenticated &&
!logonUserIdentity.IsGuest &&
logonUserIdentity.User == spHighTrustContext.LogonUserIdentity.User;
}
return false;
}
protected override SharePointContext LoadSharePointContext(HttpContextBase httpContext)
{
return httpContext.Session[SPContextKey] as SharePointHighTrustContext;
}
protected override void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext)
{
httpContext.Session[SPContextKey] = spContext as SharePointHighTrustContext;
}
}
#endregion HighTrust
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
namespace Rotate
{
internal class App
{
public static int s_weightCount = 1;
private class BaseNode
{
private byte _BASEPAD_0;
private char _BASEPAD_1;
private uint _BASEPAD_2;
private String _BASEPAD_3;
private char _BASEPAD_4;
private String _BASEPAD_5;
public BaseNode()
{
_BASEPAD_0 = 63;
_BASEPAD_1 = 'f';
_BASEPAD_2 = 64;
_BASEPAD_3 = "20808";
_BASEPAD_4 = '*';
_BASEPAD_5 = "11051";
}
public virtual void VerifyValid()
{
if (_BASEPAD_0 != 63) throw new Exception("m_BASEPAD_0");
if (_BASEPAD_1 != 'f') throw new Exception("m_BASEPAD_1");
if (_BASEPAD_2 != 64) throw new Exception("m_BASEPAD_2");
if (_BASEPAD_3 != "20808") throw new Exception("m_BASEPAD_3");
if (_BASEPAD_4 != '*') throw new Exception("m_BASEPAD_4");
if (_BASEPAD_5 != "11051") throw new Exception("m_BASEPAD_5");
}
}
private class Node : BaseNode
{
private uint _PREPAD_0;
private String _PREPAD_1;
private char _PREPAD_2;
private byte _PREPAD_3;
private char _PREPAD_4;
private char _PREPAD_5;
private char _PREPAD_6;
private int _PREPAD_7;
private int _PREPAD_8;
public Node m_leftChild;
private uint _MID1PAD_0;
private int _MID1PAD_1;
private int _MID1PAD_2;
private String _MID1PAD_3;
private String _MID1PAD_4;
private uint _MID1PAD_5;
private int _MID1PAD_6;
private uint _MID1PAD_7;
private String _MID1PAD_8;
private String _MID1PAD_9;
private ushort _MID1PAD_10;
private uint _MID1PAD_11;
private char _MID1PAD_12;
private uint _MID1PAD_13;
private String _MID1PAD_14;
private int _MID1PAD_15;
private char _MID1PAD_16;
public int m_weight;
private byte _MID2PAD_0;
private char _MID2PAD_1;
private ulong _MID2PAD_2;
private ushort _MID2PAD_3;
private String _MID2PAD_4;
private String _MID2PAD_5;
private byte _MID2PAD_6;
private ushort _MID2PAD_7;
private String _MID2PAD_8;
private String _MID2PAD_9;
private char _MID2PAD_10;
private int _MID2PAD_11;
private byte _MID2PAD_12;
private String _MID2PAD_13;
private char _MID2PAD_14;
private ushort _MID2PAD_15;
private String _MID2PAD_16;
public Node m_rightChild;
private String _AFTERPAD_0;
private ushort _AFTERPAD_1;
private uint _AFTERPAD_2;
private String _AFTERPAD_3;
private int _AFTERPAD_4;
private char _AFTERPAD_5;
private ulong _AFTERPAD_6;
private byte _AFTERPAD_7;
private byte _AFTERPAD_8;
private String _AFTERPAD_9;
private ushort _AFTERPAD_10;
public Node()
{
m_weight = s_weightCount++;
_PREPAD_0 = 33;
_PREPAD_1 = "26819";
_PREPAD_2 = 'l';
_PREPAD_3 = 220;
_PREPAD_4 = '^';
_PREPAD_5 = '`';
_PREPAD_6 = 'o';
_PREPAD_7 = 162;
_PREPAD_8 = 171;
_MID1PAD_0 = 98;
_MID1PAD_1 = 90;
_MID1PAD_2 = 121;
_MID1PAD_3 = "9109";
_MID1PAD_4 = "6459";
_MID1PAD_5 = 124;
_MID1PAD_6 = 74;
_MID1PAD_7 = 113;
_MID1PAD_8 = "1720";
_MID1PAD_9 = "15021";
_MID1PAD_10 = 39;
_MID1PAD_11 = 133;
_MID1PAD_12 = 'N';
_MID1PAD_13 = 235;
_MID1PAD_14 = "22271";
_MID1PAD_15 = 55;
_MID1PAD_16 = 'G';
_MID2PAD_0 = 173;
_MID2PAD_1 = '';
_MID2PAD_2 = 94;
_MID2PAD_3 = 229;
_MID2PAD_4 = "13459";
_MID2PAD_5 = "8381";
_MID2PAD_6 = 54;
_MID2PAD_7 = 215;
_MID2PAD_8 = "14415";
_MID2PAD_9 = "30092";
_MID2PAD_10 = 'S';
_MID2PAD_11 = 250;
_MID2PAD_12 = 247;
_MID2PAD_13 = "3600";
_MID2PAD_14 = 'k';
_MID2PAD_15 = 229;
_MID2PAD_16 = "18373";
_AFTERPAD_0 = "18816";
_AFTERPAD_1 = 98;
_AFTERPAD_2 = 25;
_AFTERPAD_3 = "3802";
_AFTERPAD_4 = 217;
_AFTERPAD_5 = '*';
_AFTERPAD_6 = 140;
_AFTERPAD_7 = 74;
_AFTERPAD_8 = 91;
_AFTERPAD_9 = "18469";
_AFTERPAD_10 = 77;
}
public override void VerifyValid()
{
base.VerifyValid();
if (_PREPAD_0 != 33) throw new Exception("m_PREPAD_0");
if (_PREPAD_1 != "26819") throw new Exception("m_PREPAD_1");
if (_PREPAD_2 != 'l') throw new Exception("m_PREPAD_2");
if (_PREPAD_3 != 220) throw new Exception("m_PREPAD_3");
if (_PREPAD_4 != '^') throw new Exception("m_PREPAD_4");
if (_PREPAD_5 != '`') throw new Exception("m_PREPAD_5");
if (_PREPAD_6 != 'o') throw new Exception("m_PREPAD_6");
if (_PREPAD_7 != 162) throw new Exception("m_PREPAD_7");
if (_PREPAD_8 != 171) throw new Exception("m_PREPAD_8");
if (_MID1PAD_0 != 98) throw new Exception("m_MID1PAD_0");
if (_MID1PAD_1 != 90) throw new Exception("m_MID1PAD_1");
if (_MID1PAD_2 != 121) throw new Exception("m_MID1PAD_2");
if (_MID1PAD_3 != "9109") throw new Exception("m_MID1PAD_3");
if (_MID1PAD_4 != "6459") throw new Exception("m_MID1PAD_4");
if (_MID1PAD_5 != 124) throw new Exception("m_MID1PAD_5");
if (_MID1PAD_6 != 74) throw new Exception("m_MID1PAD_6");
if (_MID1PAD_7 != 113) throw new Exception("m_MID1PAD_7");
if (_MID1PAD_8 != "1720") throw new Exception("m_MID1PAD_8");
if (_MID1PAD_9 != "15021") throw new Exception("m_MID1PAD_9");
if (_MID1PAD_10 != 39) throw new Exception("m_MID1PAD_10");
if (_MID1PAD_11 != 133) throw new Exception("m_MID1PAD_11");
if (_MID1PAD_12 != 'N') throw new Exception("m_MID1PAD_12");
if (_MID1PAD_13 != 235) throw new Exception("m_MID1PAD_13");
if (_MID1PAD_14 != "22271") throw new Exception("m_MID1PAD_14");
if (_MID1PAD_15 != 55) throw new Exception("m_MID1PAD_15");
if (_MID1PAD_16 != 'G') throw new Exception("m_MID1PAD_16");
if (_MID2PAD_0 != 173) throw new Exception("m_MID2PAD_0");
if (_MID2PAD_1 != '') throw new Exception("m_MID2PAD_1");
if (_MID2PAD_2 != 94) throw new Exception("m_MID2PAD_2");
if (_MID2PAD_3 != 229) throw new Exception("m_MID2PAD_3");
if (_MID2PAD_4 != "13459") throw new Exception("m_MID2PAD_4");
if (_MID2PAD_5 != "8381") throw new Exception("m_MID2PAD_5");
if (_MID2PAD_6 != 54) throw new Exception("m_MID2PAD_6");
if (_MID2PAD_7 != 215) throw new Exception("m_MID2PAD_7");
if (_MID2PAD_8 != "14415") throw new Exception("m_MID2PAD_8");
if (_MID2PAD_9 != "30092") throw new Exception("m_MID2PAD_9");
if (_MID2PAD_10 != 'S') throw new Exception("m_MID2PAD_10");
if (_MID2PAD_11 != 250) throw new Exception("m_MID2PAD_11");
if (_MID2PAD_12 != 247) throw new Exception("m_MID2PAD_12");
if (_MID2PAD_13 != "3600") throw new Exception("m_MID2PAD_13");
if (_MID2PAD_14 != 'k') throw new Exception("m_MID2PAD_14");
if (_MID2PAD_15 != 229) throw new Exception("m_MID2PAD_15");
if (_MID2PAD_16 != "18373") throw new Exception("m_MID2PAD_16");
if (_AFTERPAD_0 != "18816") throw new Exception("m_AFTERPAD_0");
if (_AFTERPAD_1 != 98) throw new Exception("m_AFTERPAD_1");
if (_AFTERPAD_2 != 25) throw new Exception("m_AFTERPAD_2");
if (_AFTERPAD_3 != "3802") throw new Exception("m_AFTERPAD_3");
if (_AFTERPAD_4 != 217) throw new Exception("m_AFTERPAD_4");
if (_AFTERPAD_5 != '*') throw new Exception("m_AFTERPAD_5");
if (_AFTERPAD_6 != 140) throw new Exception("m_AFTERPAD_6");
if (_AFTERPAD_7 != 74) throw new Exception("m_AFTERPAD_7");
if (_AFTERPAD_8 != 91) throw new Exception("m_AFTERPAD_8");
if (_AFTERPAD_9 != "18469") throw new Exception("m_AFTERPAD_9");
if (_AFTERPAD_10 != 77) throw new Exception("m_AFTERPAD_10");
}
public virtual Node growTree(int maxHeight, String indent)
{
//Console.WriteLine(indent + m_weight.ToString());
if (maxHeight > 0)
{
m_leftChild = new Node();
m_leftChild.growTree(maxHeight - 1, indent + " ");
m_rightChild = new Node();
m_rightChild.growTree(maxHeight - 1, indent + " ");
}
else
m_leftChild = m_rightChild = null;
return this;
}
public virtual void rotateTree(ref int leftWeight, ref int rightWeight)
{
//Console.WriteLine("rotateTree(" + m_weight.ToString() + ")");
VerifyValid();
// create node objects for children
Node newLeftChild = null, newRightChild = null;
if (m_leftChild != null)
{
newRightChild = new Node();
newRightChild.m_leftChild = m_leftChild.m_leftChild;
newRightChild.m_rightChild = m_leftChild.m_rightChild;
newRightChild.m_weight = m_leftChild.m_weight;
}
if (m_rightChild != null)
{
newLeftChild = new Node();
newLeftChild.m_leftChild = m_rightChild.m_leftChild;
newLeftChild.m_rightChild = m_rightChild.m_rightChild;
newLeftChild.m_weight = m_rightChild.m_weight;
}
// replace children
m_leftChild = newLeftChild;
m_rightChild = newRightChild;
for (int I = 0; I < 32; I++) { int[] u = new int[1024]; }
// verify all valid
if (m_rightChild != null)
{
if (m_rightChild.m_leftChild != null &&
m_rightChild.m_rightChild != null)
{
m_rightChild.m_leftChild.VerifyValid();
m_rightChild.m_rightChild.VerifyValid();
m_rightChild.rotateTree(
ref m_rightChild.m_leftChild.m_weight,
ref m_rightChild.m_rightChild.m_weight);
}
else
{
int minus1 = -1;
m_rightChild.rotateTree(ref minus1, ref minus1);
}
if (leftWeight != m_rightChild.m_weight)
{
Console.WriteLine("left weight do not match.");
throw new Exception();
}
}
if (m_leftChild != null)
{
if (m_leftChild.m_leftChild != null &&
m_leftChild.m_rightChild != null)
{
m_leftChild.m_leftChild.VerifyValid();
m_leftChild.m_rightChild.VerifyValid();
m_leftChild.rotateTree(
ref m_leftChild.m_leftChild.m_weight,
ref m_leftChild.m_rightChild.m_weight);
}
else
{
int minus1 = -1;
m_leftChild.rotateTree(ref minus1, ref minus1);
}
if (rightWeight != m_leftChild.m_weight)
{
Console.WriteLine("right weight do not match.");
throw new Exception();
}
}
}
}
private static int Main()
{
try
{
Node root = new Node();
root.growTree(6, "").rotateTree(
ref root.m_leftChild.m_weight,
ref root.m_rightChild.m_weight);
}
catch (Exception)
{
Console.WriteLine("*** FAILED ***");
return 1;
}
Console.WriteLine("*** PASSED ***");
return 100;
}
}
}
| |
// 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.Security.Cryptography.Asn1;
using System.Security.Cryptography.Pkcs.Asn1;
using System.Security.Cryptography.X509Certificates;
using Internal.Cryptography;
namespace System.Security.Cryptography.Pkcs
{
internal partial class CmsSignature
{
static partial void PrepareRegistrationRsa(Dictionary<string, CmsSignature> lookup)
{
lookup.Add(Oids.Rsa, new RSAPkcs1CmsSignature(null, null));
lookup.Add(Oids.RsaPkcs1Sha1, new RSAPkcs1CmsSignature(Oids.RsaPkcs1Sha1, HashAlgorithmName.SHA1));
lookup.Add(Oids.RsaPkcs1Sha256, new RSAPkcs1CmsSignature(Oids.RsaPkcs1Sha256, HashAlgorithmName.SHA256));
lookup.Add(Oids.RsaPkcs1Sha384, new RSAPkcs1CmsSignature(Oids.RsaPkcs1Sha384, HashAlgorithmName.SHA384));
lookup.Add(Oids.RsaPkcs1Sha512, new RSAPkcs1CmsSignature(Oids.RsaPkcs1Sha512, HashAlgorithmName.SHA512));
lookup.Add(Oids.RsaPss, new RSAPssCmsSignature());
}
private abstract class RSACmsSignature : CmsSignature
{
private readonly string _signatureAlgorithm;
private readonly HashAlgorithmName? _expectedDigest;
protected RSACmsSignature(string signatureAlgorithm, HashAlgorithmName? expectedDigest)
{
_signatureAlgorithm = signatureAlgorithm;
_expectedDigest = expectedDigest;
}
protected override bool VerifyKeyType(AsymmetricAlgorithm key)
{
return (key as RSA) != null;
}
internal override bool VerifySignature(
#if netcoreapp || netcoreapp30 || netstandard21
ReadOnlySpan<byte> valueHash,
ReadOnlyMemory<byte> signature,
#else
byte[] valueHash,
byte[] signature,
#endif
string digestAlgorithmOid,
HashAlgorithmName digestAlgorithmName,
ReadOnlyMemory<byte>? signatureParameters,
X509Certificate2 certificate)
{
if (_expectedDigest.HasValue && _expectedDigest.Value != digestAlgorithmName)
{
throw new CryptographicException(
SR.Format(
SR.Cryptography_Cms_InvalidSignerHashForSignatureAlg,
digestAlgorithmOid,
_signatureAlgorithm));
}
RSASignaturePadding padding = GetSignaturePadding(
signatureParameters,
digestAlgorithmOid,
digestAlgorithmName,
valueHash.Length);
RSA publicKey = certificate.GetRSAPublicKey();
if (publicKey == null)
{
return false;
}
return publicKey.VerifyHash(
valueHash,
#if netcoreapp || netcoreapp30 || netstandard21
signature.Span,
#else
signature,
#endif
digestAlgorithmName,
padding);
}
protected abstract RSASignaturePadding GetSignaturePadding(
ReadOnlyMemory<byte>? signatureParameters,
string digestAlgorithmOid,
HashAlgorithmName digestAlgorithmName,
int digestValueLength);
}
private sealed class RSAPkcs1CmsSignature : RSACmsSignature
{
public RSAPkcs1CmsSignature(string signatureAlgorithm, HashAlgorithmName? expectedDigest)
: base(signatureAlgorithm, expectedDigest)
{
}
protected override RSASignaturePadding GetSignaturePadding(
ReadOnlyMemory<byte>? signatureParameters,
string digestAlgorithmOid,
HashAlgorithmName digestAlgorithmName,
int digestValueLength)
{
if (signatureParameters == null)
{
return RSASignaturePadding.Pkcs1;
}
Span<byte> expectedParameters = stackalloc byte[2];
expectedParameters[0] = 0x05;
expectedParameters[1] = 0x00;
if (expectedParameters.SequenceEqual(signatureParameters.Value.Span))
{
return RSASignaturePadding.Pkcs1;
}
throw new CryptographicException(SR.Cryptography_Pkcs_InvalidSignatureParameters);
}
protected override bool Sign(
#if netcoreapp || netcoreapp30 || netstandard21
ReadOnlySpan<byte> dataHash,
#else
byte[] dataHash,
#endif
HashAlgorithmName hashAlgorithmName,
X509Certificate2 certificate,
AsymmetricAlgorithm key,
bool silent,
out Oid signatureAlgorithm,
out byte[] signatureValue)
{
RSA certPublicKey = certificate.GetRSAPublicKey();
// If there's no private key, fall back to the public key for a "no private key" exception.
RSA privateKey = key as RSA ??
PkcsPal.Instance.GetPrivateKeyForSigning<RSA>(certificate, silent) ??
certPublicKey;
if (privateKey == null)
{
signatureAlgorithm = null;
signatureValue = null;
return false;
}
signatureAlgorithm = new Oid(Oids.Rsa, Oids.Rsa);
#if netcoreapp || netcoreapp30 || netstandard21
byte[] signature = new byte[privateKey.KeySize / 8];
bool signed = privateKey.TrySignHash(
dataHash,
signature,
hashAlgorithmName,
RSASignaturePadding.Pkcs1,
out int bytesWritten);
if (signed && signature.Length == bytesWritten)
{
signatureValue = signature;
if (key != null && !certPublicKey.VerifyHash(dataHash, signatureValue, hashAlgorithmName, RSASignaturePadding.Pkcs1))
{
// key did not match certificate
signatureValue = null;
return false;
}
return true;
}
#endif
signatureValue = privateKey.SignHash(
#if netcoreapp || netcoreapp30 || netstandard21
dataHash.ToArray(),
#else
dataHash,
#endif
hashAlgorithmName,
RSASignaturePadding.Pkcs1);
if (key != null && !certPublicKey.VerifyHash(dataHash, signatureValue, hashAlgorithmName, RSASignaturePadding.Pkcs1))
{
// key did not match certificate
signatureValue = null;
return false;
}
return true;
}
}
private class RSAPssCmsSignature : RSACmsSignature
{
public RSAPssCmsSignature() : base(null, null)
{
}
protected override RSASignaturePadding GetSignaturePadding(
ReadOnlyMemory<byte>? signatureParameters,
string digestAlgorithmOid,
HashAlgorithmName digestAlgorithmName,
int digestValueLength)
{
if (signatureParameters == null)
{
throw new CryptographicException(SR.Cryptography_Pkcs_PssParametersMissing);
}
PssParamsAsn pssParams = PssParamsAsn.Decode(signatureParameters.Value, AsnEncodingRules.DER);
if (pssParams.HashAlgorithm.Algorithm.Value != digestAlgorithmOid)
{
throw new CryptographicException(
SR.Format(
SR.Cryptography_Pkcs_PssParametersHashMismatch,
pssParams.HashAlgorithm.Algorithm.Value,
digestAlgorithmOid));
}
if (pssParams.TrailerField != 1)
{
throw new CryptographicException(SR.Cryptography_Pkcs_InvalidSignatureParameters);
}
if (pssParams.SaltLength != digestValueLength)
{
throw new CryptographicException(
SR.Format(
SR.Cryptography_Pkcs_PssParametersSaltMismatch,
pssParams.SaltLength,
digestAlgorithmName.Name));
}
if (pssParams.MaskGenAlgorithm.Algorithm.Value != Oids.Mgf1)
{
throw new CryptographicException(
SR.Cryptography_Pkcs_PssParametersMgfNotSupported,
pssParams.MaskGenAlgorithm.Algorithm.Value);
}
if (pssParams.MaskGenAlgorithm.Parameters == null)
{
throw new CryptographicException(SR.Cryptography_Pkcs_InvalidSignatureParameters);
}
AlgorithmIdentifierAsn mgfParams = AlgorithmIdentifierAsn.Decode(
pssParams.MaskGenAlgorithm.Parameters.Value,
AsnEncodingRules.DER);
if (mgfParams.Algorithm.Value != digestAlgorithmOid)
{
throw new CryptographicException(
SR.Format(
SR.Cryptography_Pkcs_PssParametersMgfHashMismatch,
mgfParams.Algorithm.Value,
digestAlgorithmOid));
}
// When RSASignaturePadding supports custom salt sizes this return will look different.
return RSASignaturePadding.Pss;
}
protected override bool Sign(
#if netcoreapp || netcoreapp30 || netstandard21
ReadOnlySpan<byte> dataHash,
#else
byte[] dataHash,
#endif
HashAlgorithmName hashAlgorithmName,
X509Certificate2 certificate,
AsymmetricAlgorithm key,
bool silent,
out Oid signatureAlgorithm,
out byte[] signatureValue)
{
Debug.Fail("RSA-PSS requires building parameters, which has no API.");
throw new CryptographicException();
}
}
}
}
| |
// Code generated by Microsoft (R) AutoRest Code Generator 1.1.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace ApplicationGateway
{
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// Extension methods for SubnetsOperations.
/// </summary>
public static partial class SubnetsOperationsExtensions
{
/// <summary>
/// Deletes the specified subnet.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkName'>
/// The name of the virtual network.
/// </param>
/// <param name='subnetName'>
/// The name of the subnet.
/// </param>
public static void Delete(this ISubnetsOperations operations, string resourceGroupName, string virtualNetworkName, string subnetName)
{
operations.DeleteAsync(resourceGroupName, virtualNetworkName, subnetName).GetAwaiter().GetResult();
}
/// <summary>
/// Deletes the specified subnet.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkName'>
/// The name of the virtual network.
/// </param>
/// <param name='subnetName'>
/// The name of the subnet.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task DeleteAsync(this ISubnetsOperations operations, string resourceGroupName, string virtualNetworkName, string subnetName, CancellationToken cancellationToken = default(CancellationToken))
{
(await operations.DeleteWithHttpMessagesAsync(resourceGroupName, virtualNetworkName, subnetName, null, cancellationToken).ConfigureAwait(false)).Dispose();
}
/// <summary>
/// Gets the specified subnet by virtual network and resource group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkName'>
/// The name of the virtual network.
/// </param>
/// <param name='subnetName'>
/// The name of the subnet.
/// </param>
/// <param name='expand'>
/// Expands referenced resources.
/// </param>
public static Subnet Get(this ISubnetsOperations operations, string resourceGroupName, string virtualNetworkName, string subnetName, string expand = default(string))
{
return operations.GetAsync(resourceGroupName, virtualNetworkName, subnetName, expand).GetAwaiter().GetResult();
}
/// <summary>
/// Gets the specified subnet by virtual network and resource group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkName'>
/// The name of the virtual network.
/// </param>
/// <param name='subnetName'>
/// The name of the subnet.
/// </param>
/// <param name='expand'>
/// Expands referenced resources.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<Subnet> GetAsync(this ISubnetsOperations operations, string resourceGroupName, string virtualNetworkName, string subnetName, string expand = default(string), CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetWithHttpMessagesAsync(resourceGroupName, virtualNetworkName, subnetName, expand, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Creates or updates a subnet in the specified virtual network.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkName'>
/// The name of the virtual network.
/// </param>
/// <param name='subnetName'>
/// The name of the subnet.
/// </param>
/// <param name='subnetParameters'>
/// Parameters supplied to the create or update subnet operation.
/// </param>
public static Subnet CreateOrUpdate(this ISubnetsOperations operations, string resourceGroupName, string virtualNetworkName, string subnetName, Subnet subnetParameters)
{
return operations.CreateOrUpdateAsync(resourceGroupName, virtualNetworkName, subnetName, subnetParameters).GetAwaiter().GetResult();
}
/// <summary>
/// Creates or updates a subnet in the specified virtual network.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkName'>
/// The name of the virtual network.
/// </param>
/// <param name='subnetName'>
/// The name of the subnet.
/// </param>
/// <param name='subnetParameters'>
/// Parameters supplied to the create or update subnet operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<Subnet> CreateOrUpdateAsync(this ISubnetsOperations operations, string resourceGroupName, string virtualNetworkName, string subnetName, Subnet subnetParameters, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.CreateOrUpdateWithHttpMessagesAsync(resourceGroupName, virtualNetworkName, subnetName, subnetParameters, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Gets all subnets in a virtual network.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkName'>
/// The name of the virtual network.
/// </param>
public static IPage<Subnet> List(this ISubnetsOperations operations, string resourceGroupName, string virtualNetworkName)
{
return operations.ListAsync(resourceGroupName, virtualNetworkName).GetAwaiter().GetResult();
}
/// <summary>
/// Gets all subnets in a virtual network.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkName'>
/// The name of the virtual network.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<Subnet>> ListAsync(this ISubnetsOperations operations, string resourceGroupName, string virtualNetworkName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListWithHttpMessagesAsync(resourceGroupName, virtualNetworkName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Deletes the specified subnet.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkName'>
/// The name of the virtual network.
/// </param>
/// <param name='subnetName'>
/// The name of the subnet.
/// </param>
public static void BeginDelete(this ISubnetsOperations operations, string resourceGroupName, string virtualNetworkName, string subnetName)
{
operations.BeginDeleteAsync(resourceGroupName, virtualNetworkName, subnetName).GetAwaiter().GetResult();
}
/// <summary>
/// Deletes the specified subnet.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkName'>
/// The name of the virtual network.
/// </param>
/// <param name='subnetName'>
/// The name of the subnet.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task BeginDeleteAsync(this ISubnetsOperations operations, string resourceGroupName, string virtualNetworkName, string subnetName, CancellationToken cancellationToken = default(CancellationToken))
{
(await operations.BeginDeleteWithHttpMessagesAsync(resourceGroupName, virtualNetworkName, subnetName, null, cancellationToken).ConfigureAwait(false)).Dispose();
}
/// <summary>
/// Creates or updates a subnet in the specified virtual network.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkName'>
/// The name of the virtual network.
/// </param>
/// <param name='subnetName'>
/// The name of the subnet.
/// </param>
/// <param name='subnetParameters'>
/// Parameters supplied to the create or update subnet operation.
/// </param>
public static Subnet BeginCreateOrUpdate(this ISubnetsOperations operations, string resourceGroupName, string virtualNetworkName, string subnetName, Subnet subnetParameters)
{
return operations.BeginCreateOrUpdateAsync(resourceGroupName, virtualNetworkName, subnetName, subnetParameters).GetAwaiter().GetResult();
}
/// <summary>
/// Creates or updates a subnet in the specified virtual network.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='virtualNetworkName'>
/// The name of the virtual network.
/// </param>
/// <param name='subnetName'>
/// The name of the subnet.
/// </param>
/// <param name='subnetParameters'>
/// Parameters supplied to the create or update subnet operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<Subnet> BeginCreateOrUpdateAsync(this ISubnetsOperations operations, string resourceGroupName, string virtualNetworkName, string subnetName, Subnet subnetParameters, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.BeginCreateOrUpdateWithHttpMessagesAsync(resourceGroupName, virtualNetworkName, subnetName, subnetParameters, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Gets all subnets in a virtual network.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
public static IPage<Subnet> ListNext(this ISubnetsOperations operations, string nextPageLink)
{
return operations.ListNextAsync(nextPageLink).GetAwaiter().GetResult();
}
/// <summary>
/// Gets all subnets in a virtual network.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<Subnet>> ListNextAsync(this ISubnetsOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
using System.Reflection;
using System.Runtime.Serialization;
using System.Web.Http;
using System.Web.Http.Description;
using System.Xml.Serialization;
using Newtonsoft.Json;
namespace FantasyAuctionWebRole.Areas.HelpPage.ModelDescriptions
{
/// <summary>
/// Generates model descriptions for given types.
/// </summary>
public class ModelDescriptionGenerator
{
// Modify this to support more data annotation attributes.
private readonly IDictionary<Type, Func<object, string>> AnnotationTextGenerator = new Dictionary<Type, Func<object, string>>
{
{ typeof(RequiredAttribute), a => "Required" },
{ typeof(RangeAttribute), a =>
{
RangeAttribute range = (RangeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum);
}
},
{ typeof(MaxLengthAttribute), a =>
{
MaxLengthAttribute maxLength = (MaxLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length);
}
},
{ typeof(MinLengthAttribute), a =>
{
MinLengthAttribute minLength = (MinLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length);
}
},
{ typeof(StringLengthAttribute), a =>
{
StringLengthAttribute strLength = (StringLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength);
}
},
{ typeof(DataTypeAttribute), a =>
{
DataTypeAttribute dataType = (DataTypeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString());
}
},
{ typeof(RegularExpressionAttribute), a =>
{
RegularExpressionAttribute regularExpression = (RegularExpressionAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}", regularExpression.Pattern);
}
},
};
// Modify this to add more default documentations.
private readonly IDictionary<Type, string> DefaultTypeDocumentation = new Dictionary<Type, string>
{
{ typeof(Int16), "integer" },
{ typeof(Int32), "integer" },
{ typeof(Int64), "integer" },
{ typeof(UInt16), "unsigned integer" },
{ typeof(UInt32), "unsigned integer" },
{ typeof(UInt64), "unsigned integer" },
{ typeof(Byte), "byte" },
{ typeof(Char), "character" },
{ typeof(SByte), "signed byte" },
{ typeof(Uri), "URI" },
{ typeof(Single), "decimal number" },
{ typeof(Double), "decimal number" },
{ typeof(Decimal), "decimal number" },
{ typeof(String), "string" },
{ typeof(Guid), "globally unique identifier" },
{ typeof(TimeSpan), "time interval" },
{ typeof(DateTime), "date" },
{ typeof(DateTimeOffset), "date" },
{ typeof(Boolean), "boolean" },
};
private Lazy<IModelDocumentationProvider> _documentationProvider;
public ModelDescriptionGenerator(HttpConfiguration config)
{
if (config == null)
{
throw new ArgumentNullException("config");
}
_documentationProvider = new Lazy<IModelDocumentationProvider>(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider);
GeneratedModels = new Dictionary<string, ModelDescription>(StringComparer.OrdinalIgnoreCase);
}
public Dictionary<string, ModelDescription> GeneratedModels { get; private set; }
private IModelDocumentationProvider DocumentationProvider
{
get
{
return _documentationProvider.Value;
}
}
public ModelDescription GetOrCreateModelDescription(Type modelType)
{
if (modelType == null)
{
throw new ArgumentNullException("modelType");
}
Type underlyingType = Nullable.GetUnderlyingType(modelType);
if (underlyingType != null)
{
modelType = underlyingType;
}
ModelDescription modelDescription;
string modelName = ModelNameHelper.GetModelName(modelType);
if (GeneratedModels.TryGetValue(modelName, out modelDescription))
{
if (modelType != modelDescription.ModelType)
{
throw new InvalidOperationException(
String.Format(
CultureInfo.CurrentCulture,
"A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " +
"Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.",
modelName,
modelDescription.ModelType.FullName,
modelType.FullName));
}
return modelDescription;
}
if (DefaultTypeDocumentation.ContainsKey(modelType))
{
return GenerateSimpleTypeModelDescription(modelType);
}
if (modelType.IsEnum)
{
return GenerateEnumTypeModelDescription(modelType);
}
if (modelType.IsGenericType)
{
Type[] genericArguments = modelType.GetGenericArguments();
if (genericArguments.Length == 1)
{
Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments);
if (enumerableType.IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, genericArguments[0]);
}
}
if (genericArguments.Length == 2)
{
Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments);
if (dictionaryType.IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments);
if (keyValuePairType.IsAssignableFrom(modelType))
{
return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
}
}
if (modelType.IsArray)
{
Type elementType = modelType.GetElementType();
return GenerateCollectionModelDescription(modelType, elementType);
}
if (modelType == typeof(NameValueCollection))
{
return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string));
}
if (typeof(IDictionary).IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object));
}
if (typeof(IEnumerable).IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, typeof(object));
}
return GenerateComplexTypeModelDescription(modelType);
}
// Change this to provide different name for the member.
private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute)
{
JsonPropertyAttribute jsonProperty = member.GetCustomAttribute<JsonPropertyAttribute>();
if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName))
{
return jsonProperty.PropertyName;
}
if (hasDataContractAttribute)
{
DataMemberAttribute dataMember = member.GetCustomAttribute<DataMemberAttribute>();
if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name))
{
return dataMember.Name;
}
}
return member.Name;
}
private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute)
{
JsonIgnoreAttribute jsonIgnore = member.GetCustomAttribute<JsonIgnoreAttribute>();
XmlIgnoreAttribute xmlIgnore = member.GetCustomAttribute<XmlIgnoreAttribute>();
IgnoreDataMemberAttribute ignoreDataMember = member.GetCustomAttribute<IgnoreDataMemberAttribute>();
NonSerializedAttribute nonSerialized = member.GetCustomAttribute<NonSerializedAttribute>();
ApiExplorerSettingsAttribute apiExplorerSetting = member.GetCustomAttribute<ApiExplorerSettingsAttribute>();
bool hasMemberAttribute = member.DeclaringType.IsEnum ?
member.GetCustomAttribute<EnumMemberAttribute>() != null :
member.GetCustomAttribute<DataMemberAttribute>() != null;
// Display member only if all the followings are true:
// no JsonIgnoreAttribute
// no XmlIgnoreAttribute
// no IgnoreDataMemberAttribute
// no NonSerializedAttribute
// no ApiExplorerSettingsAttribute with IgnoreApi set to true
// no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute
return jsonIgnore == null &&
xmlIgnore == null &&
ignoreDataMember == null &&
nonSerialized == null &&
(apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) &&
(!hasDataContractAttribute || hasMemberAttribute);
}
private string CreateDefaultDocumentation(Type type)
{
string documentation;
if (DefaultTypeDocumentation.TryGetValue(type, out documentation))
{
return documentation;
}
if (DocumentationProvider != null)
{
documentation = DocumentationProvider.GetDocumentation(type);
}
return documentation;
}
private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel)
{
List<ParameterAnnotation> annotations = new List<ParameterAnnotation>();
IEnumerable<Attribute> attributes = property.GetCustomAttributes();
foreach (Attribute attribute in attributes)
{
Func<object, string> textGenerator;
if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator))
{
annotations.Add(
new ParameterAnnotation
{
AnnotationAttribute = attribute,
Documentation = textGenerator(attribute)
});
}
}
// Rearrange the annotations
annotations.Sort((x, y) =>
{
// Special-case RequiredAttribute so that it shows up on top
if (x.AnnotationAttribute is RequiredAttribute)
{
return -1;
}
if (y.AnnotationAttribute is RequiredAttribute)
{
return 1;
}
// Sort the rest based on alphabetic order of the documentation
return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase);
});
foreach (ParameterAnnotation annotation in annotations)
{
propertyModel.Annotations.Add(annotation);
}
}
private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType)
{
ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType);
if (collectionModelDescription != null)
{
return new CollectionModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
ElementDescription = collectionModelDescription
};
}
return null;
}
private ModelDescription GenerateComplexTypeModelDescription(Type modelType)
{
ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(complexModelDescription.Name, complexModelDescription);
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (PropertyInfo property in properties)
{
if (ShouldDisplayMember(property, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(property, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(property);
}
GenerateAnnotations(property, propertyModel);
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType);
}
}
FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance);
foreach (FieldInfo field in fields)
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(field, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(field);
}
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType);
}
}
return complexModelDescription;
}
private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new DictionaryModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType)
{
EnumTypeModelDescription enumDescription = new EnumTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static))
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
EnumValueDescription enumValue = new EnumValueDescription
{
Name = field.Name,
Value = field.GetRawConstantValue().ToString()
};
if (DocumentationProvider != null)
{
enumValue.Documentation = DocumentationProvider.GetDocumentation(field);
}
enumDescription.Values.Add(enumValue);
}
}
GeneratedModels.Add(enumDescription.Name, enumDescription);
return enumDescription;
}
private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new KeyValuePairModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private ModelDescription GenerateSimpleTypeModelDescription(Type modelType)
{
SimpleTypeModelDescription simpleModelDescription = new SimpleTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription);
return simpleModelDescription;
}
}
}
| |
/*=============================================================================
FileSystemEnumerator.cs: Lazy enumerator for finding files in subdirectories.
Copyright (c) 2006 Carl Daniel. Distributed under the Boost
Software License, Version 1.0. (See accompanying file
LICENSE.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
=============================================================================*/
// ---------------------------------------------------------------------------
// FileSystemEnumerator implementation
// ---------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.ConstrainedExecution;
using System.Runtime.InteropServices;
using System.Security.Permissions;
using System.Text.RegularExpressions;
namespace FindFiles
{
namespace Win32
{
/// <summary>
/// Structure that maps to WIN32_FIND_DATA
/// </summary>
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
internal sealed class FindData
{
public int fileAttributes;
public int creationTime_lowDateTime;
public int creationTime_highDateTime;
public int lastAccessTime_lowDateTime;
public int lastAccessTime_highDateTime;
public int lastWriteTime_lowDateTime;
public int lastWriteTime_highDateTime;
public int nFileSizeHigh;
public int nFileSizeLow;
public int dwReserved0;
public int dwReserved1;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)]
public String fileName;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 14)]
public String alternateFileName;
}
/// <summary>
/// SafeHandle class for holding find handles
/// </summary>
internal sealed class SafeFindHandle : Microsoft.Win32.SafeHandles.SafeHandleMinusOneIsInvalid
{
/// <summary>
/// Constructor
/// </summary>
public SafeFindHandle()
: base(true)
{
}
/// <summary>
/// Release the find handle
/// </summary>
/// <returns>true if the handle was released</returns>
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
protected override bool ReleaseHandle()
{
return SafeNativeMethods.FindClose(handle);
}
}
/// <summary>
/// Wrapper for P/Invoke methods used by FileSystemEnumerator
/// </summary>
[SecurityPermissionAttribute(SecurityAction.Assert, UnmanagedCode = true)]
internal static class SafeNativeMethods
{
[DllImport("Kernel32.dll", CharSet = CharSet.Auto)]
public static extern SafeFindHandle FindFirstFile(String fileName, [In, Out] FindData findFileData);
[DllImport("kernel32", CharSet = CharSet.Auto)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool FindNextFile(SafeFindHandle hFindFile, [In, Out] FindData lpFindFileData);
[DllImport("kernel32", CharSet = CharSet.Auto)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool FindClose(IntPtr hFindFile);
}
}
/// <summary>
/// File system enumerator. This class provides an easy to use, efficient mechanism for searching a list of
/// directories for files matching a list of file specifications. The search is done incrementally as matches
/// are consumed, so the overhead before processing the first match is always kept to a minimum.
/// </summary>
public sealed class FileSystemEnumerator : IDisposable
{
/// <summary>
/// Information that's kept in our stack for simulated recursion
/// </summary>
private struct SearchInfo
{
/// <summary>
/// Find handle returned by FindFirstFile
/// </summary>
public Win32.SafeFindHandle Handle;
/// <summary>
/// Path that was searched to yield the find handle.
/// </summary>
public string Path;
/// <summary>
/// Constructor
/// </summary>
/// <param name="h">Find handle returned by FindFirstFile.</param>
/// <param name="p">Path corresponding to find handle.</param>
public SearchInfo(Win32.SafeFindHandle h, string p)
{
Handle = h;
Path = p;
}
}
/// <summary>
/// Stack of open scopes. This is a member (instead of a local variable)
/// to allow Dispose to close any open find handles if the object is disposed
/// before the enumeration is completed.
/// </summary>
private Stack<SearchInfo> m_scopes;
/// <summary>
/// Array of paths to be searched.
/// </summary>
private string[] m_paths;
/// <summary>
/// Array of regular expressions that will detect matching files.
/// </summary>
private List<Regex> m_fileSpecs;
/// <summary>
/// If true, sub-directories are searched.
/// </summary>
private bool m_includeSubDirs;
#region IDisposable implementation
/// <summary>
/// IDisposable.Dispose
/// </summary>
public void Dispose()
{
while (m_scopes.Count > 0)
{
SearchInfo si = m_scopes.Pop();
si.Handle.Close();
}
}
#endregion
/// <summary>
/// Constructor.
/// </summary>
/// <param name="pathsToSearch">Semicolon- or comma-delimitted list of paths to search.</param>
/// <param name="fileTypesToMatch">Semicolon- or comma-delimitted list of wildcard filespecs to match.</param>
/// <param name="includeSubDirs">If true, subdirectories are searched.</param>
public FileSystemEnumerator(string pathsToSearch, string fileTypesToMatch, bool includeSubDirs)
{
m_scopes = new Stack<SearchInfo>();
// check for nulls
if (null == pathsToSearch)
throw new ArgumentNullException("pathsToSearch");
if (null == fileTypesToMatch)
throw new ArgumentNullException("fileTypesToMatch");
// make sure spec doesn't contain invalid characters
if (fileTypesToMatch.IndexOfAny(new char[] { ':', '<', '>', '/', '\\' }) >= 0)
throw new ArgumentException("invalid cahracters in wildcard pattern", "fileTypesToMatch");
m_includeSubDirs = includeSubDirs;
m_paths = pathsToSearch.Split(new char[] { ';', ',' });
string[] specs = fileTypesToMatch.Split(new char[] { ';', ',' });
m_fileSpecs = new List<Regex>(specs.Length);
foreach (string spec in specs)
{
// trim whitespace off file spec and convert Win32 wildcards to regular expressions
string pattern = spec
.Trim()
.Replace(".", @"\.")
.Replace("*", @".*")
.Replace("?", @".?")
;
m_fileSpecs.Add(
new Regex("^" + pattern + "$", RegexOptions.IgnoreCase)
);
}
}
/// <summary>
/// Get an enumerator that returns all of the files that match the wildcards that
/// are in any of the directories to be searched.
/// </summary>
/// <returns>An IEnumerable that returns all matching files one by one.</returns>
/// <remarks>The enumerator that is returned finds files using a lazy algorithm that
/// searches directories incrementally as matches are consumed.</remarks>
public IEnumerable<FileInfo> Matches()
{
foreach (string rootPath in m_paths)
{
string path = rootPath.Trim();
// we "recurse" into a new directory by jumping to this spot
top:
// check security - ensure that caller has rights to read this directory
new FileIOPermission(FileIOPermissionAccess.PathDiscovery, Path.Combine(path, ".")).Demand();
// now that security is checked, go read the directory
Win32.FindData findData = new Win32.FindData();
Win32.SafeFindHandle handle = Win32.SafeNativeMethods.FindFirstFile(Path.Combine(path, "*"), findData);
m_scopes.Push(new SearchInfo(handle, path));
bool restart = false;
// we "return" from a sub-directory by jumping to this spot
restart:
if (!handle.IsInvalid)
{
do
{
// if we restarted the loop (unwound a recursion), fetch the next match
if (restart)
{
restart = false;
continue;
}
// don't match . or ..
if (findData.fileName.Equals(@".") || findData.fileName.Equals(@".."))
continue;
if ((findData.fileAttributes & (int)FileAttributes.Directory) != 0)
{
if (m_includeSubDirs)
{
// it's a directory - recurse into it
path = Path.Combine(path, findData.fileName);
goto top;
}
}
else
{
// it's a file, see if any of the filespecs matches it
foreach (Regex fileSpec in m_fileSpecs)
{
// if this spec matches, return this file's info
if (fileSpec.IsMatch(findData.fileName))
yield return new FileInfo(Path.Combine(path, findData.fileName));
}
}
} while (Win32.SafeNativeMethods.FindNextFile(handle, findData));
// close this find handle
handle.Close();
// unwind the stack - are we still in a recursion?
m_scopes.Pop();
if (m_scopes.Count > 0)
{
SearchInfo si = m_scopes.Peek();
handle = si.Handle;
path = si.Path;
restart = true;
goto restart;
}
}
}
}
}
}
| |
// Copyright (c) 2015, Outercurve Foundation.
// 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 the Outercurve Foundation 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 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.Text;
using System.Web.Services.Protocols;
using WebsitePanel.Server.Utils;
using WebsitePanel.Providers.Utils;
using Microsoft.Win32;
namespace WebsitePanel.Providers.Statistics
{
public class SmarterStats : HostingServiceProviderBase, IStatisticsServer
{
#region Properties
protected string SmarterUrl
{
get { return ProviderSettings["SmarterUrl"]; }
}
protected string Username
{
get { return ProviderSettings["Username"]; }
}
protected string Password
{
get { return ProviderSettings["Password"]; }
}
protected int ServerId
{
get { try { return Int32.Parse(ProviderSettings["ServerID"]); } catch { return 1; } }
}
protected string LogFormat
{
get { return ProviderSettings["LogFormat"]; }
}
protected string LogWildcard
{
get { return ProviderSettings["LogWildcard"]; }
}
protected int LogDeleteDays
{
get { try { return Int32.Parse(ProviderSettings["LogDeleteDays"]); } catch { return 0; } }
}
protected string SmarterLogsPath
{
get { return FileUtils.EvaluateSystemVariables(ProviderSettings["SmarterLogsPath"]); }
}
protected int SmarterLogDeleteMonths
{
get { try { return Int32.Parse(ProviderSettings["SmarterLogDeleteMonths"]); } catch { return 0; } }
}
protected int TimeZoneId
{
get { try { return Int32.Parse(ProviderSettings["TimeZoneId"]); } catch { return 1; } }
}
protected string StatisticsUrl
{
get { return ProviderSettings["StatisticsUrl"]; }
}
#endregion
#region IStatistics methods
public virtual StatsServer[] GetServers()
{
ServerAdmin srvAdmin = new ServerAdmin();
PrepareProxy(srvAdmin);
ServerInfoArrayResult result = srvAdmin.GetServers(Username, Password);
if (result.Servers == null)
return new StatsServer[] { };
StatsServer[] servers = new StatsServer[result.Servers.Length];
for (int i = 0; i < servers.Length; i++)
{
servers[i] = new StatsServer();
servers[i].ServerId = result.Servers[i].ServerID;
servers[i].Name = result.Servers[i].Name;
servers[i].Ip = result.Servers[i].IP;
}
return servers;
}
public virtual string GetSiteId(string siteName)
{
SiteAdmin stAdmin = new SiteAdmin();
PrepareProxy(stAdmin);
SiteInfoArrayResult result = stAdmin.GetAllSites(Username, Password, false);
if (result.Sites == null)
return null;
foreach (SiteInfo site in result.Sites)
{
if (String.Compare(siteName, site.DomainName, 0) == 0)
return site.SiteID.ToString();
}
return null;
}
public virtual string[] GetSites()
{
List<string> sites = new List<string>();
SiteAdmin stAdmin = new SiteAdmin();
PrepareProxy(stAdmin);
SiteInfoArrayResult result = stAdmin.GetAllSites(Username, Password, false);
if (result.Sites == null)
return sites.ToArray();
foreach (SiteInfo site in result.Sites)
sites.Add(site.DomainName);
return sites.ToArray();
}
public virtual StatsSite GetSite(string siteId)
{
SiteAdmin stAdmin = new SiteAdmin();
PrepareProxy(stAdmin);
int sid = Int32.Parse(siteId);
SiteInfoResult result = stAdmin.GetSite(Username, Password, sid);
if (result.Site == null)
return null;
StatsSite site = new StatsSite();
site.Name = result.Site.DomainName;
site.ExportPath = result.Site.ExportPath;
site.ExportPathUrl = result.Site.ExportPathURL;
site.LogDirectory = result.Site.LogDirectory;
site.TimeZoneId = TimeZoneId;
site.Status = result.Site.SiteStatus;
// process stats URL
string url = null;
if (!String.IsNullOrEmpty(StatisticsUrl))
{
url = StringUtils.ReplaceStringVariable(StatisticsUrl, "domain_name", site.Name);
url = StringUtils.ReplaceStringVariable(url, "site_id", siteId);
}
// get site users
UserAdmin usrAdmin = new UserAdmin();
PrepareProxy(usrAdmin);
UserInfoResultArray usrResult = usrAdmin.GetUsers(Username, Password, sid);
if (usrResult.user != null)
{
site.Users = new StatsUser[usrResult.user.Length];
for (int i = 0; i < site.Users.Length; i++)
{
site.Users[i] = new StatsUser();
site.Users[i].Username = usrResult.user[i].UserName;
site.Users[i].Password = usrResult.user[i].Password;
site.Users[i].FirstName = usrResult.user[i].FirstName;
site.Users[i].LastName = usrResult.user[i].LastName;
site.Users[i].IsAdmin = usrResult.user[i].IsAdmin;
site.Users[i].IsOwner = usrResult.user[i].IsSiteOwner;
}
if (site.Users.Length > 0 && !String.IsNullOrEmpty(url))
{
url = StringUtils.ReplaceStringVariable(url, "username", site.Users[0].Username);
url = StringUtils.ReplaceStringVariable(url, "password", site.Users[0].Password);
}
}
site.StatisticsUrl = url;
return site;
}
public virtual string AddSite(StatsSite site)
{
// generate unique SiteID
//int iSiteId = site.Name.GetHashCode();
//if (iSiteId < 0)
// iSiteId *= -1;
//string siteId = iSiteId.ToString();
// create logs folder if not exists
//if (!FileUtils.DirectoryExists(site.LogDirectory))
// FileUtils.CreateDirectory(site.LogDirectory);
// add site
SiteAdmin stAdmin = new SiteAdmin();
PrepareProxy(stAdmin);
if (site.Users == null || site.Users.Length == 0)
throw new Exception("At least one user (site owner) should be specified when creating new statistics site");
string ownerUsername = site.Users[0].Username.ToLower();
GenericResult1 result = stAdmin.AddSite(Username, Password,
site.Users[0].Username, site.Users[0].Password, site.Users[0].FirstName, site.Users[0].LastName,
ServerId, 0, site.Name, site.LogDirectory, LogFormat, LogWildcard, LogDeleteDays,
SmarterLogsPath, SmarterLogDeleteMonths, "", "", TimeZoneId);
if (!result.Result)
throw new Exception("Error creating statistics site: " + result.Message);
string siteId = GetSiteId(site.Name);
int iSiteId = Int32.Parse(siteId);
// add other users
UserAdmin usrAdmin = new UserAdmin();
PrepareProxy(usrAdmin);
foreach (StatsUser user in site.Users)
{
if (user.Username.ToLower() != ownerUsername)
{
// add user
GenericResult2 r = usrAdmin.AddUser(Username, Password, iSiteId,
user.Username, user.Password, user.FirstName, user.LastName, user.IsAdmin);
if (!r.Result)
throw new Exception("Error adding site user: " + r.Message);
}
}
return siteId;
}
public virtual void UpdateSite(StatsSite site)
{
// update site
SiteAdmin stAdmin = new SiteAdmin();
PrepareProxy(stAdmin);
int siteId = Int32.Parse(site.SiteId);
// get original site
SiteInfoResult siteResult = stAdmin.GetSite(Username, Password, siteId);
if (siteResult.Site == null)
return;
SiteInfo origSite = siteResult.Site;
// update site with only required properties
GenericResult1 result = stAdmin.UpdateSite(Username, Password, siteId, site.Name, origSite.LogDirectory,
origSite.LogFormat, origSite.LogWildcard, origSite.LogDaysBeforeDelete,
origSite.SmarterLogDirectory, origSite.SmarterLogMonthsBeforeDelete, origSite.ExportPath, origSite.ExportPathURL,
origSite.TimeZoneID);
if (!result.Result)
throw new Exception("Error updating statistics site: " + result.Message);
// update site users
UserAdmin usrAdmin = new UserAdmin();
PrepareProxy(usrAdmin);
// get original users
if (site.Users != null)
{
List<string> origUsers = new List<string>();
List<string> newUsers = new List<string>();
string ownerUsername = null;
UserInfoResultArray usrResult = usrAdmin.GetUsers(Username, Password, siteId);
foreach (UserInfo user in usrResult.user)
{
// add to original users
origUsers.Add(user.UserName.ToLower());
// remember owner (he can't be deleted)
if (user.IsSiteOwner)
ownerUsername = user.UserName.ToLower();
}
// add, update users
foreach (StatsUser user in site.Users)
{
if (!origUsers.Contains(user.Username.ToLower()))
{
// add user
GenericResult2 r = usrAdmin.AddUser(Username, Password, siteId,
user.Username, user.Password, user.FirstName, user.LastName, user.IsAdmin);
if (!r.Result)
throw new Exception("Error adding site user: " + r.Message);
}
else
{
// update user
GenericResult2 r = usrAdmin.UpdateUser(Username, Password, siteId,
user.Username, user.Password, user.FirstName, user.LastName, user.IsAdmin);
if (!r.Result)
throw new Exception("Error updating site user: " + r.Message);
}
// add to new users list
newUsers.Add(user.Username.ToLower());
}
// delete users
foreach (string username in origUsers)
{
if (!newUsers.Contains(username) && username != ownerUsername)
{
// delete user
GenericResult2 r = usrAdmin.DeleteUser(Username, Password, siteId, username);
}
}
}
}
public virtual void DeleteSite(string siteId)
{
// delete site
SiteAdmin stAdmin = new SiteAdmin();
PrepareProxy(stAdmin);
int sid = Int32.Parse(siteId);
GenericResult1 result = stAdmin.DeleteSite(Username, Password, sid, true);
if (!result.Result)
throw new Exception("Error deleting statistics site: " + result.Message);
}
#endregion
#region IHostingServiceProvider methods
public override void DeleteServiceItems(ServiceProviderItem[] items)
{
foreach (ServiceProviderItem item in items)
{
if (item is StatsSite)
{
try
{
DeleteSite(((StatsSite)item).SiteId);
}
catch (Exception ex)
{
Log.WriteError(String.Format("Error deleting '{0}' {1}", item.Name, item.GetType().Name), ex);
}
}
}
}
#endregion
#region Helper Methods
public void PrepareProxy(SoapHttpClientProtocol proxy)
{
string smarterUrl = SmarterUrl;
int idx = proxy.Url.LastIndexOf("/");
// strip the last slash if any
if (smarterUrl[smarterUrl.Length - 1] == '/')
smarterUrl = smarterUrl.Substring(0, smarterUrl.Length - 1);
proxy.Url = smarterUrl + proxy.Url.Substring(idx);
}
#endregion
public override bool IsInstalled()
{
string productName = null;
string productVersion = null;
String[] names = null;
RegistryKey HKLM = Registry.LocalMachine;
RegistryKey key = HKLM.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall");
if (key != null)
{
names = key.GetSubKeyNames();
foreach (string s in names)
{
RegistryKey subkey = HKLM.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\" + s);
if (subkey != null)
{
if (!String.IsNullOrEmpty((string) subkey.GetValue("DisplayName")))
{
productName = (string) subkey.GetValue("DisplayName");
}
if (productName != null)
if (productName.Equals("SmarterStats") || productName.Equals("SmarterStats Service"))
{
productVersion = (string) subkey.GetValue("DisplayVersion");
break;
}
}
}
if (!String.IsNullOrEmpty(productVersion))
{
string[] split = productVersion.Split(new char[] {'.'});
return split[0].Equals("3");
}
}
//checking x64 platform
key = HKLM.OpenSubKey(@"SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall");
if (key != null)
{
names = key.GetSubKeyNames();
foreach (string s in names)
{
RegistryKey subkey =
HKLM.OpenSubKey(@"SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\" + s);
if (subkey != null)
{
if (!String.IsNullOrEmpty((string) subkey.GetValue("DisplayName")))
{
productName = (string) subkey.GetValue("DisplayName");
}
if (productName != null)
if (productName.Equals("SmarterStats") || productName.Equals("SmarterStats Service"))
{
productVersion = (string) subkey.GetValue("DisplayVersion");
break;
}
}
}
if (!String.IsNullOrEmpty(productVersion))
{
string[] split = productVersion.Split(new char[] {'.'});
return split[0].Equals("3");
}
}
return false;
}
}
}
| |
//
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using Hyak.Common;
using Microsoft.Azure;
using Microsoft.Azure.Management.Automation;
using Microsoft.Azure.Management.Automation.Models;
using Newtonsoft.Json.Linq;
namespace Microsoft.Azure.Management.Automation
{
/// <summary>
/// Service operation for automation schedules. (see
/// http://aka.ms/azureautomationsdk/scheduleoperations for more
/// information)
/// </summary>
internal partial class ScheduleOperations : IServiceOperations<AutomationManagementClient>, IScheduleOperations
{
/// <summary>
/// Initializes a new instance of the ScheduleOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
internal ScheduleOperations(AutomationManagementClient client)
{
this._client = client;
}
private AutomationManagementClient _client;
/// <summary>
/// Gets a reference to the
/// Microsoft.Azure.Management.Automation.AutomationManagementClient.
/// </summary>
public AutomationManagementClient Client
{
get { return this._client; }
}
/// <summary>
/// Create a schedule. (see
/// http://aka.ms/azureautomationsdk/scheduleoperations for more
/// information)
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group
/// </param>
/// <param name='automationAccount'>
/// Required. The automation account name.
/// </param>
/// <param name='parameters'>
/// Required. The parameters supplied to the create or update schedule
/// operation.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The response model for the create or update schedule operation.
/// </returns>
public async Task<ScheduleCreateOrUpdateResponse> CreateOrUpdateAsync(string resourceGroupName, string automationAccount, ScheduleCreateOrUpdateParameters parameters, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (automationAccount == null)
{
throw new ArgumentNullException("automationAccount");
}
if (parameters == null)
{
throw new ArgumentNullException("parameters");
}
if (parameters.Name == null)
{
throw new ArgumentNullException("parameters.Name");
}
if (parameters.Properties == null)
{
throw new ArgumentNullException("parameters.Properties");
}
if (parameters.Properties.Frequency == null)
{
throw new ArgumentNullException("parameters.Properties.Frequency");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("automationAccount", automationAccount);
tracingParameters.Add("parameters", parameters);
TracingAdapter.Enter(invocationId, this, "CreateOrUpdateAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/resourceGroups/";
url = url + Uri.EscapeDataString(resourceGroupName);
url = url + "/providers/";
if (this.Client.ResourceNamespace != null)
{
url = url + Uri.EscapeDataString(this.Client.ResourceNamespace);
}
url = url + "/automationAccounts/";
url = url + Uri.EscapeDataString(automationAccount);
url = url + "/schedules/";
url = url + Uri.EscapeDataString(parameters.Name);
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2015-01-01-preview");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Put;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("Accept", "application/json");
httpRequest.Headers.Add("x-ms-version", "2014-06-01");
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Serialize Request
string requestContent = null;
JToken requestDoc = null;
JObject scheduleCreateOrUpdateParametersValue = new JObject();
requestDoc = scheduleCreateOrUpdateParametersValue;
scheduleCreateOrUpdateParametersValue["name"] = parameters.Name;
JObject propertiesValue = new JObject();
scheduleCreateOrUpdateParametersValue["properties"] = propertiesValue;
if (parameters.Properties.Description != null)
{
propertiesValue["description"] = parameters.Properties.Description;
}
propertiesValue["startTime"] = parameters.Properties.StartTime;
if (parameters.Properties.ExpiryTime != null)
{
propertiesValue["expiryTime"] = parameters.Properties.ExpiryTime.Value;
}
if (parameters.Properties.Interval != null)
{
propertiesValue["interval"] = parameters.Properties.Interval.Value;
}
propertiesValue["frequency"] = parameters.Properties.Frequency;
requestContent = requestDoc.ToString(Newtonsoft.Json.Formatting.Indented);
httpRequest.Content = new StringContent(requestContent, Encoding.UTF8);
httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK && statusCode != HttpStatusCode.Created)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, requestContent, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
ScheduleCreateOrUpdateResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK || statusCode == HttpStatusCode.Created)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new ScheduleCreateOrUpdateResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
Schedule scheduleInstance = new Schedule();
result.Schedule = scheduleInstance;
JToken nameValue = responseDoc["name"];
if (nameValue != null && nameValue.Type != JTokenType.Null)
{
string nameInstance = ((string)nameValue);
scheduleInstance.Name = nameInstance;
}
JToken propertiesValue2 = responseDoc["properties"];
if (propertiesValue2 != null && propertiesValue2.Type != JTokenType.Null)
{
ScheduleProperties propertiesInstance = new ScheduleProperties();
scheduleInstance.Properties = propertiesInstance;
JToken startTimeValue = propertiesValue2["startTime"];
if (startTimeValue != null && startTimeValue.Type != JTokenType.Null)
{
DateTimeOffset startTimeInstance = ((DateTimeOffset)startTimeValue);
propertiesInstance.StartTime = startTimeInstance;
}
JToken expiryTimeValue = propertiesValue2["expiryTime"];
if (expiryTimeValue != null && expiryTimeValue.Type != JTokenType.Null)
{
DateTimeOffset expiryTimeInstance = ((DateTimeOffset)expiryTimeValue);
propertiesInstance.ExpiryTime = expiryTimeInstance;
}
JToken isEnabledValue = propertiesValue2["isEnabled"];
if (isEnabledValue != null && isEnabledValue.Type != JTokenType.Null)
{
bool isEnabledInstance = ((bool)isEnabledValue);
propertiesInstance.IsEnabled = isEnabledInstance;
}
JToken nextRunValue = propertiesValue2["nextRun"];
if (nextRunValue != null && nextRunValue.Type != JTokenType.Null)
{
DateTimeOffset nextRunInstance = ((DateTimeOffset)nextRunValue);
propertiesInstance.NextRun = nextRunInstance;
}
JToken intervalValue = propertiesValue2["interval"];
if (intervalValue != null && intervalValue.Type != JTokenType.Null)
{
byte intervalInstance = ((byte)intervalValue);
propertiesInstance.Interval = intervalInstance;
}
JToken frequencyValue = propertiesValue2["frequency"];
if (frequencyValue != null && frequencyValue.Type != JTokenType.Null)
{
string frequencyInstance = ((string)frequencyValue);
propertiesInstance.Frequency = frequencyInstance;
}
JToken creationTimeValue = propertiesValue2["creationTime"];
if (creationTimeValue != null && creationTimeValue.Type != JTokenType.Null)
{
DateTimeOffset creationTimeInstance = ((DateTimeOffset)creationTimeValue);
propertiesInstance.CreationTime = creationTimeInstance;
}
JToken lastModifiedTimeValue = propertiesValue2["lastModifiedTime"];
if (lastModifiedTimeValue != null && lastModifiedTimeValue.Type != JTokenType.Null)
{
DateTimeOffset lastModifiedTimeInstance = ((DateTimeOffset)lastModifiedTimeValue);
propertiesInstance.LastModifiedTime = lastModifiedTimeInstance;
}
JToken descriptionValue = propertiesValue2["description"];
if (descriptionValue != null && descriptionValue.Type != JTokenType.Null)
{
string descriptionInstance = ((string)descriptionValue);
propertiesInstance.Description = descriptionInstance;
}
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Delete the schedule identified by schedule name. (see
/// http://aka.ms/azureautomationsdk/scheduleoperations for more
/// information)
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group
/// </param>
/// <param name='automationAccount'>
/// Required. The automation account name.
/// </param>
/// <param name='scheduleName'>
/// Required. The schedule name.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public async Task<AzureOperationResponse> DeleteAsync(string resourceGroupName, string automationAccount, string scheduleName, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (automationAccount == null)
{
throw new ArgumentNullException("automationAccount");
}
if (scheduleName == null)
{
throw new ArgumentNullException("scheduleName");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("automationAccount", automationAccount);
tracingParameters.Add("scheduleName", scheduleName);
TracingAdapter.Enter(invocationId, this, "DeleteAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/resourceGroups/";
url = url + Uri.EscapeDataString(resourceGroupName);
url = url + "/providers/";
if (this.Client.ResourceNamespace != null)
{
url = url + Uri.EscapeDataString(this.Client.ResourceNamespace);
}
url = url + "/automationAccounts/";
url = url + Uri.EscapeDataString(automationAccount);
url = url + "/schedules/";
url = url + Uri.EscapeDataString(scheduleName);
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2015-01-01-preview");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Delete;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("Accept", "application/json");
httpRequest.Headers.Add("x-ms-version", "2014-06-01");
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
AzureOperationResponse result = null;
// Deserialize Response
result = new AzureOperationResponse();
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Retrieve the schedule identified by schedule name. (see
/// http://aka.ms/azureautomationsdk/scheduleoperations for more
/// information)
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group
/// </param>
/// <param name='automationAccount'>
/// Required. The automation account name.
/// </param>
/// <param name='scheduleName'>
/// Required. The schedule name.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The response model for the get schedule operation.
/// </returns>
public async Task<ScheduleGetResponse> GetAsync(string resourceGroupName, string automationAccount, string scheduleName, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (automationAccount == null)
{
throw new ArgumentNullException("automationAccount");
}
if (scheduleName == null)
{
throw new ArgumentNullException("scheduleName");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("automationAccount", automationAccount);
tracingParameters.Add("scheduleName", scheduleName);
TracingAdapter.Enter(invocationId, this, "GetAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/resourceGroups/";
url = url + Uri.EscapeDataString(resourceGroupName);
url = url + "/providers/";
if (this.Client.ResourceNamespace != null)
{
url = url + Uri.EscapeDataString(this.Client.ResourceNamespace);
}
url = url + "/automationAccounts/";
url = url + Uri.EscapeDataString(automationAccount);
url = url + "/schedules/";
url = url + Uri.EscapeDataString(scheduleName);
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2015-01-01-preview");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("Accept", "application/json");
httpRequest.Headers.Add("x-ms-version", "2014-06-01");
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
ScheduleGetResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new ScheduleGetResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
Schedule scheduleInstance = new Schedule();
result.Schedule = scheduleInstance;
JToken nameValue = responseDoc["name"];
if (nameValue != null && nameValue.Type != JTokenType.Null)
{
string nameInstance = ((string)nameValue);
scheduleInstance.Name = nameInstance;
}
JToken propertiesValue = responseDoc["properties"];
if (propertiesValue != null && propertiesValue.Type != JTokenType.Null)
{
ScheduleProperties propertiesInstance = new ScheduleProperties();
scheduleInstance.Properties = propertiesInstance;
JToken startTimeValue = propertiesValue["startTime"];
if (startTimeValue != null && startTimeValue.Type != JTokenType.Null)
{
DateTimeOffset startTimeInstance = ((DateTimeOffset)startTimeValue);
propertiesInstance.StartTime = startTimeInstance;
}
JToken expiryTimeValue = propertiesValue["expiryTime"];
if (expiryTimeValue != null && expiryTimeValue.Type != JTokenType.Null)
{
DateTimeOffset expiryTimeInstance = ((DateTimeOffset)expiryTimeValue);
propertiesInstance.ExpiryTime = expiryTimeInstance;
}
JToken isEnabledValue = propertiesValue["isEnabled"];
if (isEnabledValue != null && isEnabledValue.Type != JTokenType.Null)
{
bool isEnabledInstance = ((bool)isEnabledValue);
propertiesInstance.IsEnabled = isEnabledInstance;
}
JToken nextRunValue = propertiesValue["nextRun"];
if (nextRunValue != null && nextRunValue.Type != JTokenType.Null)
{
DateTimeOffset nextRunInstance = ((DateTimeOffset)nextRunValue);
propertiesInstance.NextRun = nextRunInstance;
}
JToken intervalValue = propertiesValue["interval"];
if (intervalValue != null && intervalValue.Type != JTokenType.Null)
{
byte intervalInstance = ((byte)intervalValue);
propertiesInstance.Interval = intervalInstance;
}
JToken frequencyValue = propertiesValue["frequency"];
if (frequencyValue != null && frequencyValue.Type != JTokenType.Null)
{
string frequencyInstance = ((string)frequencyValue);
propertiesInstance.Frequency = frequencyInstance;
}
JToken creationTimeValue = propertiesValue["creationTime"];
if (creationTimeValue != null && creationTimeValue.Type != JTokenType.Null)
{
DateTimeOffset creationTimeInstance = ((DateTimeOffset)creationTimeValue);
propertiesInstance.CreationTime = creationTimeInstance;
}
JToken lastModifiedTimeValue = propertiesValue["lastModifiedTime"];
if (lastModifiedTimeValue != null && lastModifiedTimeValue.Type != JTokenType.Null)
{
DateTimeOffset lastModifiedTimeInstance = ((DateTimeOffset)lastModifiedTimeValue);
propertiesInstance.LastModifiedTime = lastModifiedTimeInstance;
}
JToken descriptionValue = propertiesValue["description"];
if (descriptionValue != null && descriptionValue.Type != JTokenType.Null)
{
string descriptionInstance = ((string)descriptionValue);
propertiesInstance.Description = descriptionInstance;
}
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Retrieve a list of schedules. (see
/// http://aka.ms/azureautomationsdk/scheduleoperations for more
/// information)
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group
/// </param>
/// <param name='automationAccount'>
/// Required. The automation account name.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The response model for the list schedule operation.
/// </returns>
public async Task<ScheduleListResponse> ListAsync(string resourceGroupName, string automationAccount, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (automationAccount == null)
{
throw new ArgumentNullException("automationAccount");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("automationAccount", automationAccount);
TracingAdapter.Enter(invocationId, this, "ListAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/resourceGroups/";
url = url + Uri.EscapeDataString(resourceGroupName);
url = url + "/providers/";
if (this.Client.ResourceNamespace != null)
{
url = url + Uri.EscapeDataString(this.Client.ResourceNamespace);
}
url = url + "/automationAccounts/";
url = url + Uri.EscapeDataString(automationAccount);
url = url + "/schedules";
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2015-01-01-preview");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("Accept", "application/json");
httpRequest.Headers.Add("ocp-referer", url);
httpRequest.Headers.Add("x-ms-version", "2014-06-01");
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
ScheduleListResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new ScheduleListResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
JToken valueArray = responseDoc["value"];
if (valueArray != null && valueArray.Type != JTokenType.Null)
{
foreach (JToken valueValue in ((JArray)valueArray))
{
Schedule scheduleInstance = new Schedule();
result.Schedules.Add(scheduleInstance);
JToken nameValue = valueValue["name"];
if (nameValue != null && nameValue.Type != JTokenType.Null)
{
string nameInstance = ((string)nameValue);
scheduleInstance.Name = nameInstance;
}
JToken propertiesValue = valueValue["properties"];
if (propertiesValue != null && propertiesValue.Type != JTokenType.Null)
{
ScheduleProperties propertiesInstance = new ScheduleProperties();
scheduleInstance.Properties = propertiesInstance;
JToken startTimeValue = propertiesValue["startTime"];
if (startTimeValue != null && startTimeValue.Type != JTokenType.Null)
{
DateTimeOffset startTimeInstance = ((DateTimeOffset)startTimeValue);
propertiesInstance.StartTime = startTimeInstance;
}
JToken expiryTimeValue = propertiesValue["expiryTime"];
if (expiryTimeValue != null && expiryTimeValue.Type != JTokenType.Null)
{
DateTimeOffset expiryTimeInstance = ((DateTimeOffset)expiryTimeValue);
propertiesInstance.ExpiryTime = expiryTimeInstance;
}
JToken isEnabledValue = propertiesValue["isEnabled"];
if (isEnabledValue != null && isEnabledValue.Type != JTokenType.Null)
{
bool isEnabledInstance = ((bool)isEnabledValue);
propertiesInstance.IsEnabled = isEnabledInstance;
}
JToken nextRunValue = propertiesValue["nextRun"];
if (nextRunValue != null && nextRunValue.Type != JTokenType.Null)
{
DateTimeOffset nextRunInstance = ((DateTimeOffset)nextRunValue);
propertiesInstance.NextRun = nextRunInstance;
}
JToken intervalValue = propertiesValue["interval"];
if (intervalValue != null && intervalValue.Type != JTokenType.Null)
{
byte intervalInstance = ((byte)intervalValue);
propertiesInstance.Interval = intervalInstance;
}
JToken frequencyValue = propertiesValue["frequency"];
if (frequencyValue != null && frequencyValue.Type != JTokenType.Null)
{
string frequencyInstance = ((string)frequencyValue);
propertiesInstance.Frequency = frequencyInstance;
}
JToken creationTimeValue = propertiesValue["creationTime"];
if (creationTimeValue != null && creationTimeValue.Type != JTokenType.Null)
{
DateTimeOffset creationTimeInstance = ((DateTimeOffset)creationTimeValue);
propertiesInstance.CreationTime = creationTimeInstance;
}
JToken lastModifiedTimeValue = propertiesValue["lastModifiedTime"];
if (lastModifiedTimeValue != null && lastModifiedTimeValue.Type != JTokenType.Null)
{
DateTimeOffset lastModifiedTimeInstance = ((DateTimeOffset)lastModifiedTimeValue);
propertiesInstance.LastModifiedTime = lastModifiedTimeInstance;
}
JToken descriptionValue = propertiesValue["description"];
if (descriptionValue != null && descriptionValue.Type != JTokenType.Null)
{
string descriptionInstance = ((string)descriptionValue);
propertiesInstance.Description = descriptionInstance;
}
}
}
}
JToken odatanextLinkValue = responseDoc["odata.nextLink"];
if (odatanextLinkValue != null && odatanextLinkValue.Type != JTokenType.Null)
{
string odatanextLinkInstance = Regex.Match(((string)odatanextLinkValue), "^.*[&\\?]\\$skiptoken=([^&]*)(&.*)?").Groups[1].Value;
result.SkipToken = odatanextLinkInstance;
}
JToken nextLinkValue = responseDoc["nextLink"];
if (nextLinkValue != null && nextLinkValue.Type != JTokenType.Null)
{
string nextLinkInstance = ((string)nextLinkValue);
result.NextLink = nextLinkInstance;
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Retrieve next list of schedules. (see
/// http://aka.ms/azureautomationsdk/scheduleoperations for more
/// information)
/// </summary>
/// <param name='nextLink'>
/// Required. The link to retrieve next set of items.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The response model for the list schedule operation.
/// </returns>
public async Task<ScheduleListResponse> ListNextAsync(string nextLink, CancellationToken cancellationToken)
{
// Validate
if (nextLink == null)
{
throw new ArgumentNullException("nextLink");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("nextLink", nextLink);
TracingAdapter.Enter(invocationId, this, "ListNextAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + nextLink;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("Accept", "application/json");
httpRequest.Headers.Add("ocp-referer", url);
httpRequest.Headers.Add("x-ms-version", "2014-06-01");
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
ScheduleListResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new ScheduleListResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
JToken valueArray = responseDoc["value"];
if (valueArray != null && valueArray.Type != JTokenType.Null)
{
foreach (JToken valueValue in ((JArray)valueArray))
{
Schedule scheduleInstance = new Schedule();
result.Schedules.Add(scheduleInstance);
JToken nameValue = valueValue["name"];
if (nameValue != null && nameValue.Type != JTokenType.Null)
{
string nameInstance = ((string)nameValue);
scheduleInstance.Name = nameInstance;
}
JToken propertiesValue = valueValue["properties"];
if (propertiesValue != null && propertiesValue.Type != JTokenType.Null)
{
ScheduleProperties propertiesInstance = new ScheduleProperties();
scheduleInstance.Properties = propertiesInstance;
JToken startTimeValue = propertiesValue["startTime"];
if (startTimeValue != null && startTimeValue.Type != JTokenType.Null)
{
DateTimeOffset startTimeInstance = ((DateTimeOffset)startTimeValue);
propertiesInstance.StartTime = startTimeInstance;
}
JToken expiryTimeValue = propertiesValue["expiryTime"];
if (expiryTimeValue != null && expiryTimeValue.Type != JTokenType.Null)
{
DateTimeOffset expiryTimeInstance = ((DateTimeOffset)expiryTimeValue);
propertiesInstance.ExpiryTime = expiryTimeInstance;
}
JToken isEnabledValue = propertiesValue["isEnabled"];
if (isEnabledValue != null && isEnabledValue.Type != JTokenType.Null)
{
bool isEnabledInstance = ((bool)isEnabledValue);
propertiesInstance.IsEnabled = isEnabledInstance;
}
JToken nextRunValue = propertiesValue["nextRun"];
if (nextRunValue != null && nextRunValue.Type != JTokenType.Null)
{
DateTimeOffset nextRunInstance = ((DateTimeOffset)nextRunValue);
propertiesInstance.NextRun = nextRunInstance;
}
JToken intervalValue = propertiesValue["interval"];
if (intervalValue != null && intervalValue.Type != JTokenType.Null)
{
byte intervalInstance = ((byte)intervalValue);
propertiesInstance.Interval = intervalInstance;
}
JToken frequencyValue = propertiesValue["frequency"];
if (frequencyValue != null && frequencyValue.Type != JTokenType.Null)
{
string frequencyInstance = ((string)frequencyValue);
propertiesInstance.Frequency = frequencyInstance;
}
JToken creationTimeValue = propertiesValue["creationTime"];
if (creationTimeValue != null && creationTimeValue.Type != JTokenType.Null)
{
DateTimeOffset creationTimeInstance = ((DateTimeOffset)creationTimeValue);
propertiesInstance.CreationTime = creationTimeInstance;
}
JToken lastModifiedTimeValue = propertiesValue["lastModifiedTime"];
if (lastModifiedTimeValue != null && lastModifiedTimeValue.Type != JTokenType.Null)
{
DateTimeOffset lastModifiedTimeInstance = ((DateTimeOffset)lastModifiedTimeValue);
propertiesInstance.LastModifiedTime = lastModifiedTimeInstance;
}
JToken descriptionValue = propertiesValue["description"];
if (descriptionValue != null && descriptionValue.Type != JTokenType.Null)
{
string descriptionInstance = ((string)descriptionValue);
propertiesInstance.Description = descriptionInstance;
}
}
}
}
JToken odatanextLinkValue = responseDoc["odata.nextLink"];
if (odatanextLinkValue != null && odatanextLinkValue.Type != JTokenType.Null)
{
string odatanextLinkInstance = Regex.Match(((string)odatanextLinkValue), "^.*[&\\?]\\$skiptoken=([^&]*)(&.*)?").Groups[1].Value;
result.SkipToken = odatanextLinkInstance;
}
JToken nextLinkValue = responseDoc["nextLink"];
if (nextLinkValue != null && nextLinkValue.Type != JTokenType.Null)
{
string nextLinkInstance = ((string)nextLinkValue);
result.NextLink = nextLinkInstance;
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Update the schedule identified by schedule name. (see
/// http://aka.ms/azureautomationsdk/scheduleoperations for more
/// information)
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group
/// </param>
/// <param name='automationAccount'>
/// Required. The automation account name.
/// </param>
/// <param name='parameters'>
/// Required. The parameters supplied to the patch schedule operation.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public async Task<AzureOperationResponse> PatchAsync(string resourceGroupName, string automationAccount, SchedulePatchParameters parameters, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (automationAccount == null)
{
throw new ArgumentNullException("automationAccount");
}
if (parameters == null)
{
throw new ArgumentNullException("parameters");
}
if (parameters.Name == null)
{
throw new ArgumentNullException("parameters.Name");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("automationAccount", automationAccount);
tracingParameters.Add("parameters", parameters);
TracingAdapter.Enter(invocationId, this, "PatchAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/resourceGroups/";
url = url + Uri.EscapeDataString(resourceGroupName);
url = url + "/providers/";
if (this.Client.ResourceNamespace != null)
{
url = url + Uri.EscapeDataString(this.Client.ResourceNamespace);
}
url = url + "/automationAccounts/";
url = url + Uri.EscapeDataString(automationAccount);
url = url + "/schedules/";
url = url + Uri.EscapeDataString(parameters.Name);
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2015-01-01-preview");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = new HttpMethod("PATCH");
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("Accept", "application/json");
httpRequest.Headers.Add("x-ms-version", "2014-06-01");
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Serialize Request
string requestContent = null;
JToken requestDoc = null;
JObject schedulePatchParametersValue = new JObject();
requestDoc = schedulePatchParametersValue;
schedulePatchParametersValue["name"] = parameters.Name;
if (parameters.Properties != null)
{
JObject propertiesValue = new JObject();
schedulePatchParametersValue["properties"] = propertiesValue;
if (parameters.Properties.Description != null)
{
propertiesValue["description"] = parameters.Properties.Description;
}
if (parameters.Properties.IsEnabled != null)
{
propertiesValue["isEnabled"] = parameters.Properties.IsEnabled.Value;
}
}
requestContent = requestDoc.ToString(Newtonsoft.Json.Formatting.Indented);
httpRequest.Content = new StringContent(requestContent, Encoding.UTF8);
httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, requestContent, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
AzureOperationResponse result = null;
// Deserialize Response
result = new AzureOperationResponse();
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
}
}
| |
/* ====================================================================
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==================================================================== */
namespace NPOI.HSSF.Model
{
using System;
using System.Text;
using System.Collections;
using NPOI.HSSF.Record;
using NPOI.HSSF.Record.Aggregates;
using NPOI.HSSF.Record.AutoFilter;
using System.Collections.Generic;
using NPOI.HSSF.Record.PivotTable;
/**
* Finds correct insert positions for records in workbook streams<p/>
*
* See OOO excelfileformat.pdf sec. 4.2.5 'Record Order in a BIFF8 Workbook Stream'
*
* @author Josh Micich
*/
internal class RecordOrderer
{
// TODO - simplify logic using a generalised record ordering
private RecordOrderer()
{
// no instances of this class
}
/**
* Adds the specified new record in the correct place in sheet records list
*
*/
public static void AddNewSheetRecord(List<RecordBase> sheetRecords, RecordBase newRecord)
{
int index = FindSheetInsertPos(sheetRecords, newRecord.GetType());
sheetRecords.Insert(index, newRecord);
}
private static int FindSheetInsertPos(List<RecordBase> records, Type recClass)
{
if (recClass == typeof(DataValidityTable))
{
return FindDataValidationTableInsertPos(records);
}
if (recClass == typeof(MergedCellsTable))
{
return FindInsertPosForNewMergedRecordTable(records);
}
if (recClass == typeof(ConditionalFormattingTable))
{
return FindInsertPosForNewCondFormatTable(records);
}
if (recClass == typeof(GutsRecord))
{
return GetGutsRecordInsertPos(records);
}
if (recClass == typeof(PageSettingsBlock))
{
return GetPageBreakRecordInsertPos(records);
}
if (recClass == typeof(WorksheetProtectionBlock))
{
return GetWorksheetProtectionBlockInsertPos(records);
}
throw new InvalidOperationException("Unexpected record class (" + recClass.Name + ")");
}
/// <summary>
/// Finds the index where the protection block should be inserted
/// </summary>
/// <param name="records">the records for this sheet</param>
/// <returns></returns>
/// <remark>
/// + BOF
/// o INDEX
/// o Calculation Settings Block
/// o PRINTHEADERS
/// o PRINTGRIDLINES
/// o GRIDSET
/// o GUTS
/// o DEFAULTROWHEIGHT
/// o SHEETPR
/// o Page Settings Block
/// o Worksheet Protection Block
/// o DEFCOLWIDTH
/// oo COLINFO
/// o SORT
/// + DIMENSION
/// </remark>
private static int GetWorksheetProtectionBlockInsertPos(List<RecordBase> records)
{
int i = GetDimensionsIndex(records);
while (i > 0)
{
i--;
Object rb = records[i];
if (!IsProtectionSubsequentRecord(rb))
{
return i + 1;
}
}
throw new InvalidOperationException("did not find insert pos for protection block");
}
/// <summary>
/// These records may occur between the 'Worksheet Protection Block' and DIMENSION:
/// </summary>
/// <param name="rb"></param>
/// <returns></returns>
/// <remarks>
/// o DEFCOLWIDTH
/// oo COLINFO
/// o SORT
/// </remarks>
private static bool IsProtectionSubsequentRecord(Object rb)
{
if (rb is ColumnInfoRecordsAggregate)
{
return true; // oo COLINFO
}
if (rb is Record)
{
Record record = (Record)rb;
switch (record.Sid)
{
case DefaultColWidthRecord.sid:
case UnknownRecord.SORT_0090:
return true;
}
}
return false;
}
private static int GetPageBreakRecordInsertPos(List<RecordBase> records)
{
int dimensionsIndex = GetDimensionsIndex(records);
int i = dimensionsIndex - 1;
while (i > 0)
{
i--;
RecordBase rb = records[i];
if (IsPageBreakPriorRecord(rb))
{
return i + 1;
}
}
throw new InvalidOperationException("Did not Find insert point for GUTS");
}
private static bool IsPageBreakPriorRecord(RecordBase rb)
{
if (rb is Record)
{
Record record = (Record)rb;
switch (record.Sid)
{
case BOFRecord.sid:
case IndexRecord.sid:
// calc settings block
case UncalcedRecord.sid:
case CalcCountRecord.sid:
case CalcModeRecord.sid:
case PrecisionRecord.sid:
case RefModeRecord.sid:
case DeltaRecord.sid:
case IterationRecord.sid:
case DateWindow1904Record.sid:
case SaveRecalcRecord.sid:
// end calc settings
case PrintHeadersRecord.sid:
case PrintGridlinesRecord.sid:
case GridsetRecord.sid:
case DefaultRowHeightRecord.sid:
case UnknownRecord.SHEETPR_0081:
return true;
// next is the 'Worksheet Protection Block'
}
}
return false;
}
/// <summary>
/// Find correct position to add new CFHeader record
/// </summary>
/// <param name="records"></param>
/// <returns></returns>
private static int FindInsertPosForNewCondFormatTable(List<RecordBase> records)
{
for (int i = records.Count - 2; i >= 0; i--)
{ // -2 to skip EOF record
Object rb = records[i];
if (rb is MergedCellsTable)
{
return i + 1;
}
if (rb is DataValidityTable)
{
continue;
}
Record rec = (Record)rb;
switch (rec.Sid)
{
case WindowTwoRecord.sid:
case SCLRecord.sid:
case PaneRecord.sid:
case SelectionRecord.sid:
case UnknownRecord.STANDARDWIDTH_0099:
// MergedCellsTable usually here
case UnknownRecord.LABELRANGES_015F:
case UnknownRecord.PHONETICPR_00EF:
// ConditionalFormattingTable goes here
return i + 1;
// HyperlinkTable (not aggregated by POI yet)
// DataValidityTable
}
}
throw new InvalidOperationException("Did not Find Window2 record");
}
private static int FindInsertPosForNewMergedRecordTable(List<RecordBase> records)
{
for (int i = records.Count - 2; i >= 0; i--)
{ // -2 to skip EOF record
Object rb = records[i];
if (!(rb is Record))
{
// DataValidityTable, ConditionalFormattingTable,
// even PageSettingsBlock (which doesn't normally appear after 'View Settings')
continue;
}
Record rec = (Record)rb;
switch (rec.Sid)
{
// 'View Settings' (4 records)
case WindowTwoRecord.sid:
case SCLRecord.sid:
case PaneRecord.sid:
case SelectionRecord.sid:
case UnknownRecord.STANDARDWIDTH_0099:
return i + 1;
}
}
throw new InvalidOperationException("Did not Find Window2 record");
}
/**
* Finds the index where the sheet validations header record should be inserted
* @param records the records for this sheet
*
* + WINDOW2
* o SCL
* o PANE
* oo SELECTION
* o STANDARDWIDTH
* oo MERGEDCELLS
* o LABELRANGES
* o PHONETICPR
* o Conditional Formatting Table
* o Hyperlink Table
* o Data Validity Table
* o SHEETLAYOUT
* o SHEETPROTECTION
* o RANGEPROTECTION
* + EOF
*/
private static int FindDataValidationTableInsertPos(List<RecordBase> records)
{
int i = records.Count - 1;
if (!(records[i] is EOFRecord))
{
throw new InvalidOperationException("Last sheet record should be EOFRecord");
}
while (i > 0)
{
i--;
RecordBase rb = records[i];
if (IsDVTPriorRecord(rb))
{
Record nextRec = (Record)records[i + 1];
if (!IsDVTSubsequentRecord(nextRec.Sid))
{
throw new InvalidOperationException("Unexpected (" + nextRec.GetType().Name
+ ") found after (" + rb.GetType().Name + ")");
}
return i + 1;
}
Record rec = (Record)rb;
if (!IsDVTSubsequentRecord(rec.Sid))
{
throw new InvalidOperationException("Unexpected (" + rec.GetType().Name
+ ") while looking for DV Table insert pos");
}
}
return 0;
}
private static bool IsDVTPriorRecord(RecordBase rb)
{
if (rb is MergedCellsTable || rb is ConditionalFormattingTable)
{
return true;
}
short sid = ((Record)rb).Sid;
switch (sid)
{
case WindowTwoRecord.sid:
case UnknownRecord.SCL_00A0:
case PaneRecord.sid:
case SelectionRecord.sid:
case UnknownRecord.STANDARDWIDTH_0099:
// MergedCellsTable
case UnknownRecord.LABELRANGES_015F:
case UnknownRecord.PHONETICPR_00EF:
// ConditionalFormattingTable
case HyperlinkRecord.sid:
case UnknownRecord.QUICKTIP_0800:
return true;
}
return false;
}
private static bool IsDVTSubsequentRecord(short sid)
{
switch (sid)
{
//case UnknownRecord.SHEETEXT_0862:
case SheetExtRecord.sid:
case UnknownRecord.SHEETPROTECTION_0867:
//case UnknownRecord.RANGEPROTECTION_0868:
case FeatRecord.sid:
case EOFRecord.sid:
return true;
}
return false;
}
/**
* DIMENSIONS record is always present
*/
private static int GetDimensionsIndex(List<RecordBase> records)
{
int nRecs = records.Count;
for (int i = 0; i < nRecs; i++)
{
if (records[i] is DimensionsRecord)
{
return i;
}
}
// worksheet stream is seriously broken
throw new InvalidOperationException("DimensionsRecord not found");
}
private static int GetGutsRecordInsertPos(List<RecordBase> records)
{
int dimensionsIndex = GetDimensionsIndex(records);
int i = dimensionsIndex - 1;
while (i > 0)
{
i--;
RecordBase rb = records[i];
if (IsGutsPriorRecord(rb))
{
return i + 1;
}
}
throw new InvalidOperationException("Did not Find insert point for GUTS");
}
private static bool IsGutsPriorRecord(RecordBase rb)
{
if (rb is Record)
{
Record record = (Record)rb;
switch (record.Sid)
{
case BOFRecord.sid:
case IndexRecord.sid:
// calc settings block
case UncalcedRecord.sid:
case CalcCountRecord.sid:
case CalcModeRecord.sid:
case PrecisionRecord.sid:
case RefModeRecord.sid:
case DeltaRecord.sid:
case IterationRecord.sid:
case DateWindow1904Record.sid:
case SaveRecalcRecord.sid:
// end calc settings
case PrintHeadersRecord.sid:
case PrintGridlinesRecord.sid:
case GridsetRecord.sid:
return true;
// DefaultRowHeightRecord.sid is next
}
}
return false;
}
/// <summary>
/// if the specified record ID terminates a sequence of Row block records
/// It is assumed that at least one row or cell value record has been found prior to the current
/// record
/// </summary>
/// <param name="sid"></param>
/// <returns></returns>
public static bool IsEndOfRowBlock(int sid)
{
switch (sid)
{
case ViewDefinitionRecord.sid: // should have been prefixed with DrawingRecord (0x00EC), but bug 46280 seems to allow this
case DrawingRecord.sid:
case DrawingSelectionRecord.sid:
case ObjRecord.sid:
case TextObjectRecord.sid:
case GutsRecord.sid: // see Bugzilla 50426
case WindowOneRecord.sid:
// should really be part of workbook stream, but some apps seem to put this before WINDOW2
case WindowTwoRecord.sid:
return true;
case DVALRecord.sid:
return true;
case EOFRecord.sid:
// WINDOW2 should always be present, so shouldn't have got this far
throw new InvalidOperationException("Found EOFRecord before WindowTwoRecord was encountered");
}
return PageSettingsBlock.IsComponentRecord(sid);
}
/// <summary>
/// Whether the specified record id normally appears in the row blocks section of the sheet records
/// </summary>
/// <param name="sid"></param>
/// <returns></returns>
public static bool IsRowBlockRecord(int sid)
{
switch (sid)
{
case RowRecord.sid:
case BlankRecord.sid:
case BoolErrRecord.sid:
case FormulaRecord.sid:
case LabelRecord.sid:
case LabelSSTRecord.sid:
case NumberRecord.sid:
case RKRecord.sid:
case ArrayRecord.sid:
case SharedFormulaRecord.sid:
case TableRecord.sid:
return true;
}
return false;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace System {
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.Diagnostics.Contracts;
using System.Runtime.Serialization;
using System.Runtime.CompilerServices;
[Serializable]
[System.Runtime.InteropServices.ComVisible(true)]
public abstract class StringComparer : IComparer, IEqualityComparer, IComparer<string>, IEqualityComparer<string>{
private static readonly StringComparer _invariantCulture = new CultureAwareComparer(CultureInfo.InvariantCulture, false);
private static readonly StringComparer _invariantCultureIgnoreCase = new CultureAwareComparer(CultureInfo.InvariantCulture, true);
private static readonly StringComparer _ordinal = new OrdinalComparer(false);
private static readonly StringComparer _ordinalIgnoreCase = new OrdinalComparer(true);
public static StringComparer InvariantCulture {
get {
Contract.Ensures(Contract.Result<StringComparer>() != null);
return _invariantCulture;
}
}
public static StringComparer InvariantCultureIgnoreCase {
get {
Contract.Ensures(Contract.Result<StringComparer>() != null);
return _invariantCultureIgnoreCase;
}
}
public static StringComparer CurrentCulture {
get {
Contract.Ensures(Contract.Result<StringComparer>() != null);
return new CultureAwareComparer(CultureInfo.CurrentCulture, false);
}
}
public static StringComparer CurrentCultureIgnoreCase {
get {
Contract.Ensures(Contract.Result<StringComparer>() != null);
return new CultureAwareComparer(CultureInfo.CurrentCulture, true);
}
}
public static StringComparer Ordinal {
get {
Contract.Ensures(Contract.Result<StringComparer>() != null);
return _ordinal;
}
}
public static StringComparer OrdinalIgnoreCase {
get {
Contract.Ensures(Contract.Result<StringComparer>() != null);
return _ordinalIgnoreCase;
}
}
// Convert a StringComparison to a StringComparer
public static StringComparer FromComparison(StringComparison comparisonType)
{
switch (comparisonType)
{
case StringComparison.CurrentCulture:
return CurrentCulture;
case StringComparison.CurrentCultureIgnoreCase:
return CurrentCultureIgnoreCase;
case StringComparison.InvariantCulture:
return InvariantCulture;
case StringComparison.InvariantCultureIgnoreCase:
return InvariantCultureIgnoreCase;
case StringComparison.Ordinal:
return Ordinal;
case StringComparison.OrdinalIgnoreCase:
return OrdinalIgnoreCase;
default:
throw new ArgumentException(Environment.GetResourceString("NotSupported_StringComparison"), nameof(comparisonType));
}
}
public static StringComparer Create(CultureInfo culture, bool ignoreCase) {
if( culture == null) {
throw new ArgumentNullException(nameof(culture));
}
Contract.Ensures(Contract.Result<StringComparer>() != null);
Contract.EndContractBlock();
return new CultureAwareComparer(culture, ignoreCase);
}
public int Compare(object x, object y) {
if (x == y) return 0;
if (x == null) return -1;
if (y == null) return 1;
String sa = x as String;
if (sa != null) {
String sb = y as String;
if( sb != null) {
return Compare(sa, sb);
}
}
IComparable ia = x as IComparable;
if (ia != null) {
return ia.CompareTo(y);
}
throw new ArgumentException(Environment.GetResourceString("Argument_ImplementIComparable"));
}
public new bool Equals(Object x, Object y) {
if (x == y) return true;
if (x == null || y == null) return false;
String sa = x as String;
if (sa != null) {
String sb = y as String;
if( sb != null) {
return Equals(sa, sb);
}
}
return x.Equals(y);
}
public int GetHashCode(object obj) {
if( obj == null) {
throw new ArgumentNullException(nameof(obj));
}
Contract.EndContractBlock();
string s = obj as string;
if( s != null) {
return GetHashCode(s);
}
return obj.GetHashCode();
}
public abstract int Compare(String x, String y);
public abstract bool Equals(String x, String y);
public abstract int GetHashCode(string obj);
}
[Serializable]
internal sealed class CultureAwareComparer : StringComparer
#if FEATURE_RANDOMIZED_STRING_HASHING
, IWellKnownStringEqualityComparer
#endif
{
private CompareInfo _compareInfo;
private bool _ignoreCase;
internal CultureAwareComparer(CultureInfo culture, bool ignoreCase) {
_compareInfo = culture.CompareInfo;
_ignoreCase = ignoreCase;
}
internal CultureAwareComparer(CompareInfo compareInfo, bool ignoreCase) {
_compareInfo = compareInfo;
_ignoreCase = ignoreCase;
}
public override int Compare(string x, string y) {
if (Object.ReferenceEquals(x, y)) return 0;
if (x == null) return -1;
if (y == null) return 1;
return _compareInfo.Compare(x, y, _ignoreCase? CompareOptions.IgnoreCase : CompareOptions.None);
}
public override bool Equals(string x, string y) {
if (Object.ReferenceEquals(x ,y)) return true;
if (x == null || y == null) return false;
return (_compareInfo.Compare(x, y, _ignoreCase? CompareOptions.IgnoreCase : CompareOptions.None) == 0);
}
public override int GetHashCode(string obj) {
if( obj == null) {
throw new ArgumentNullException(nameof(obj));
}
Contract.EndContractBlock();
CompareOptions options = CompareOptions.None;
if( _ignoreCase) {
options |= CompareOptions.IgnoreCase;
}
return _compareInfo.GetHashCodeOfString(obj, options);
}
// Equals method for the comparer itself.
public override bool Equals(Object obj){
CultureAwareComparer comparer = obj as CultureAwareComparer;
if( comparer == null) {
return false;
}
return (this._ignoreCase == comparer._ignoreCase) && (this._compareInfo.Equals(comparer._compareInfo));
}
public override int GetHashCode() {
int hashCode = _compareInfo.GetHashCode() ;
return _ignoreCase ? (~hashCode) : hashCode;
}
#if FEATURE_RANDOMIZED_STRING_HASHING
IEqualityComparer IWellKnownStringEqualityComparer.GetRandomizedEqualityComparer() {
return new CultureAwareRandomizedComparer(_compareInfo, _ignoreCase);
}
IEqualityComparer IWellKnownStringEqualityComparer.GetEqualityComparerForSerialization() {
return this;
}
#endif
}
#if FEATURE_RANDOMIZED_STRING_HASHING
internal sealed class CultureAwareRandomizedComparer : StringComparer, IWellKnownStringEqualityComparer {
private CompareInfo _compareInfo;
private bool _ignoreCase;
private long _entropy;
internal CultureAwareRandomizedComparer(CompareInfo compareInfo, bool ignoreCase) {
_compareInfo = compareInfo;
_ignoreCase = ignoreCase;
_entropy = HashHelpers.GetEntropy();
}
public override int Compare(string x, string y) {
if (Object.ReferenceEquals(x, y)) return 0;
if (x == null) return -1;
if (y == null) return 1;
return _compareInfo.Compare(x, y, _ignoreCase? CompareOptions.IgnoreCase : CompareOptions.None);
}
public override bool Equals(string x, string y) {
if (Object.ReferenceEquals(x ,y)) return true;
if (x == null || y == null) return false;
return (_compareInfo.Compare(x, y, _ignoreCase? CompareOptions.IgnoreCase : CompareOptions.None) == 0);
}
public override int GetHashCode(string obj) {
if( obj == null) {
throw new ArgumentNullException(nameof(obj));
}
Contract.EndContractBlock();
CompareOptions options = CompareOptions.None;
if( _ignoreCase) {
options |= CompareOptions.IgnoreCase;
}
#if FEATURE_COREFX_GLOBALIZATION
return _compareInfo.GetHashCodeOfStringCore(obj, options, true, _entropy);
#else
return _compareInfo.GetHashCodeOfString(obj, options, true, _entropy);
#endif
}
// Equals method for the comparer itself.
public override bool Equals(Object obj){
CultureAwareRandomizedComparer comparer = obj as CultureAwareRandomizedComparer;
if( comparer == null) {
return false;
}
return (this._ignoreCase == comparer._ignoreCase) && (this._compareInfo.Equals(comparer._compareInfo)) && (this._entropy == comparer._entropy);
}
public override int GetHashCode() {
int hashCode = _compareInfo.GetHashCode() ;
return ((_ignoreCase ? (~hashCode) : hashCode) ^ ((int) (_entropy & 0x7FFFFFFF)));
}
IEqualityComparer IWellKnownStringEqualityComparer.GetRandomizedEqualityComparer() {
return new CultureAwareRandomizedComparer(_compareInfo, _ignoreCase);
}
// We want to serialize the old comparer.
IEqualityComparer IWellKnownStringEqualityComparer.GetEqualityComparerForSerialization() {
return new CultureAwareComparer(_compareInfo, _ignoreCase);
}
}
#endif
// Provide x more optimal implementation of ordinal comparison.
[Serializable]
internal sealed class OrdinalComparer : StringComparer
#if FEATURE_RANDOMIZED_STRING_HASHING
, IWellKnownStringEqualityComparer
#endif
{
private bool _ignoreCase;
internal OrdinalComparer(bool ignoreCase) {
_ignoreCase = ignoreCase;
}
public override int Compare(string x, string y) {
if (Object.ReferenceEquals(x, y)) return 0;
if (x == null) return -1;
if (y == null) return 1;
if( _ignoreCase) {
return String.Compare(x, y, StringComparison.OrdinalIgnoreCase);
}
return String.CompareOrdinal(x, y);
}
public override bool Equals(string x, string y) {
if (Object.ReferenceEquals(x ,y)) return true;
if (x == null || y == null) return false;
if( _ignoreCase) {
if( x.Length != y.Length) {
return false;
}
return (String.Compare(x, y, StringComparison.OrdinalIgnoreCase) == 0);
}
return x.Equals(y);
}
public override int GetHashCode(string obj) {
if( obj == null) {
throw new ArgumentNullException(nameof(obj));
}
Contract.EndContractBlock();
if( _ignoreCase) {
return TextInfo.GetHashCodeOrdinalIgnoreCase(obj);
}
return obj.GetHashCode();
}
// Equals method for the comparer itself.
public override bool Equals(Object obj){
OrdinalComparer comparer = obj as OrdinalComparer;
if( comparer == null) {
return false;
}
return (this._ignoreCase == comparer._ignoreCase);
}
public override int GetHashCode() {
string name = "OrdinalComparer";
int hashCode = name.GetHashCode();
return _ignoreCase ? (~hashCode) : hashCode;
}
#if FEATURE_RANDOMIZED_STRING_HASHING
IEqualityComparer IWellKnownStringEqualityComparer.GetRandomizedEqualityComparer() {
return new OrdinalRandomizedComparer(_ignoreCase);
}
IEqualityComparer IWellKnownStringEqualityComparer.GetEqualityComparerForSerialization() {
return this;
}
#endif
}
#if FEATURE_RANDOMIZED_STRING_HASHING
internal sealed class OrdinalRandomizedComparer : StringComparer, IWellKnownStringEqualityComparer {
private bool _ignoreCase;
private long _entropy;
internal OrdinalRandomizedComparer(bool ignoreCase) {
_ignoreCase = ignoreCase;
_entropy = HashHelpers.GetEntropy();
}
public override int Compare(string x, string y) {
if (Object.ReferenceEquals(x, y)) return 0;
if (x == null) return -1;
if (y == null) return 1;
if( _ignoreCase) {
return String.Compare(x, y, StringComparison.OrdinalIgnoreCase);
}
return String.CompareOrdinal(x, y);
}
public override bool Equals(string x, string y) {
if (Object.ReferenceEquals(x ,y)) return true;
if (x == null || y == null) return false;
if( _ignoreCase) {
if( x.Length != y.Length) {
return false;
}
return (String.Compare(x, y, StringComparison.OrdinalIgnoreCase) == 0);
}
return x.Equals(y);
}
public override int GetHashCode(string obj) {
if( obj == null) {
throw new ArgumentNullException(nameof(obj));
}
Contract.EndContractBlock();
if( _ignoreCase) {
#if FEATURE_COREFX_GLOBALIZATION
return CultureInfo.InvariantCulture.CompareInfo.GetHashCodeOfStringCore(obj, CompareOptions.IgnoreCase, true, _entropy);
#else
return TextInfo.GetHashCodeOrdinalIgnoreCase(obj, true, _entropy);
#endif
}
return String.InternalMarvin32HashString(obj, obj.Length, _entropy);
}
// Equals method for the comparer itself.
public override bool Equals(Object obj){
OrdinalRandomizedComparer comparer = obj as OrdinalRandomizedComparer;
if( comparer == null) {
return false;
}
return (this._ignoreCase == comparer._ignoreCase) && (this._entropy == comparer._entropy);
}
public override int GetHashCode() {
string name = "OrdinalRandomizedComparer";
int hashCode = name.GetHashCode();
return ((_ignoreCase ? (~hashCode) : hashCode) ^ ((int) (_entropy & 0x7FFFFFFF)));
}
IEqualityComparer IWellKnownStringEqualityComparer.GetRandomizedEqualityComparer() {
return new OrdinalRandomizedComparer(_ignoreCase);
}
// We want to serialize the old comparer.
IEqualityComparer IWellKnownStringEqualityComparer.GetEqualityComparerForSerialization() {
return new OrdinalComparer(_ignoreCase);
}
}
// This interface is implemented by string comparers in the framework that can opt into
// randomized hashing behaviors.
internal interface IWellKnownStringEqualityComparer {
// Get an IEqualityComparer that has the same equality comparision rules as "this" but uses Randomized Hashing.
IEqualityComparer GetRandomizedEqualityComparer();
// Get an IEqaulityComparer that can be serailzied (e.g., it exists in older versions).
IEqualityComparer GetEqualityComparerForSerialization();
}
#endif
}
| |
/*
Myrtille: A native HTML4/5 Remote Desktop Protocol client.
Copyright(c) 2014-2021 Cedric Coste
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 System.Configuration;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Web;
using System.Web.Configuration;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using Myrtille.Helpers;
using Myrtille.Services.Contracts;
using Myrtille.Web.Properties;
namespace Myrtille.Web
{
public partial class Default : Page
{
private MFAAuthenticationClient _mfaAuthClient = new MFAAuthenticationClient();
private EnterpriseClient _enterpriseClient = new EnterpriseClient();
private ConnectionClient _connectionClient = new ConnectionClient(Settings.Default.ConnectionServiceUrl);
private bool _allowRemoteClipboard;
private bool _allowFileTransfer;
private bool _allowPrintDownload;
private bool _allowSessionSharing;
private bool _allowAudioPlayback;
private bool _allowShareSessionUrl;
private bool _clientIPTracking;
private bool _toolbarEnabled;
private bool _loginEnabled;
private string _loginUrl;
private bool _httpSessionUseUri;
private bool _authorizedRequest = true;
private bool _localAdmin;
private EnterpriseSession _enterpriseSession;
protected RemoteSession RemoteSession;
/// <summary>
/// page init
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void Page_Init(
object sender,
EventArgs e)
{
// remote clipboard
if (!bool.TryParse(ConfigurationManager.AppSettings["AllowRemoteClipboard"], out _allowRemoteClipboard))
{
_allowRemoteClipboard = true;
}
// file transfer
if (!bool.TryParse(ConfigurationManager.AppSettings["AllowFileTransfer"], out _allowFileTransfer))
{
_allowFileTransfer = true;
}
// print download
if (!bool.TryParse(ConfigurationManager.AppSettings["AllowPrintDownload"], out _allowPrintDownload))
{
_allowPrintDownload = true;
}
// session sharing
if (!bool.TryParse(ConfigurationManager.AppSettings["AllowSessionSharing"], out _allowSessionSharing))
{
_allowSessionSharing = true;
}
// audio playback
if (!bool.TryParse(ConfigurationManager.AppSettings["AllowAudioPlayback"], out _allowAudioPlayback))
{
_allowAudioPlayback = true;
}
// share session by url (session spoofing protection if disabled)
if (!bool.TryParse(ConfigurationManager.AppSettings["AllowShareSessionUrl"], out _allowShareSessionUrl))
{
_allowShareSessionUrl = true;
}
// client ip tracking
if (!bool.TryParse(ConfigurationManager.AppSettings["ClientIPTracking"], out _clientIPTracking))
{
_clientIPTracking = false;
}
// toolbar control
if (!bool.TryParse(ConfigurationManager.AppSettings["ToolbarEnabled"], out _toolbarEnabled))
{
_toolbarEnabled = true;
}
// connect from a login page or url
if (!bool.TryParse(ConfigurationManager.AppSettings["LoginEnabled"], out _loginEnabled))
{
_loginEnabled = true;
}
// if enabled, url of the login page
if (_loginEnabled)
{
_loginUrl = ConfigurationManager.AppSettings["LoginUrl"];
}
// cookieless session
var sessionStateSection = (SessionStateSection)ConfigurationManager.GetSection("system.web/sessionState");
_httpSessionUseUri = sessionStateSection.Cookieless == HttpCookieMode.UseUri;
}
/// <summary>
/// page load (postback data is now available)
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void Page_Load(
object sender,
EventArgs e)
{
// client ip protection
if (_clientIPTracking)
{
var clientIP = ClientIPHelper.ClientIPFromRequest(new HttpContextWrapper(HttpContext.Current).Request, true, new string[] { });
if (Session[HttpSessionStateVariables.ClientIP.ToString()] == null)
{
Session[HttpSessionStateVariables.ClientIP.ToString()] = clientIP;
}
else if (!((string)Session[HttpSessionStateVariables.ClientIP.ToString()]).Equals(clientIP))
{
System.Diagnostics.Trace.TraceWarning("Failed to validate the client ip");
_authorizedRequest = false;
UpdateControls();
return;
}
}
// session spoofing protection
if (_httpSessionUseUri)
{
if (Request.Cookies[HttpRequestCookies.ClientKey.ToString()] == null)
{
if (Session[HttpSessionStateVariables.ClientKey.ToString()] == null || _allowShareSessionUrl)
{
var cookie = new HttpCookie(HttpRequestCookies.ClientKey.ToString());
cookie.Value = Guid.NewGuid().ToString();
cookie.Path = "/";
Response.Cookies.Add(cookie);
}
else
{
System.Diagnostics.Trace.TraceWarning("Failed to validate the client key: missing key");
_authorizedRequest = false;
UpdateControls();
return;
}
}
else
{
var clientKey = Request.Cookies[HttpRequestCookies.ClientKey.ToString()].Value;
if (Session[HttpSessionStateVariables.ClientKey.ToString()] == null)
{
Session[HttpSessionStateVariables.ClientKey.ToString()] = clientKey;
}
else if (!((string)Session[HttpSessionStateVariables.ClientKey.ToString()]).Equals(clientKey) && !_allowShareSessionUrl)
{
System.Diagnostics.Trace.TraceWarning("Failed to validate the client key: key mismatch");
_authorizedRequest = false;
UpdateControls();
return;
}
}
}
// retrieve the active enterprise session, if any
if (Session[HttpSessionStateVariables.EnterpriseSession.ToString()] != null)
{
try
{
_enterpriseSession = (EnterpriseSession)Session[HttpSessionStateVariables.EnterpriseSession.ToString()];
}
catch (Exception exc)
{
System.Diagnostics.Trace.TraceError("Failed to retrieve the active enterprise session ({0})", exc);
}
}
// retrieve the active remote session, if any
if (Session[HttpSessionStateVariables.RemoteSession.ToString()] != null)
{
try
{
RemoteSession = (RemoteSession)Session[HttpSessionStateVariables.RemoteSession.ToString()];
// if using a connection service, send the connection state
if (Session.SessionID.Equals(RemoteSession.OwnerSessionID) && RemoteSession.ConnectionService)
{
_connectionClient.SetConnectionState(RemoteSession.Id, string.IsNullOrEmpty(RemoteSession.VMAddress) ? RemoteSession.ServerAddress : RemoteSession.VMAddress, GuidHelper.ConvertFromString(RemoteSession.VMGuid), RemoteSession.State);
}
if (RemoteSession.State == RemoteSessionState.Disconnected)
{
// if connecting from a login page or url, show any connection failure into a dialog box
// otherwise, this is delegated to the connection API used and its related UI
if (_loginEnabled)
{
// handle connection failure
var script = string.Format("handleRemoteSessionExit({0});", RemoteSession.ExitCode);
// redirect to login page
if (!string.IsNullOrEmpty(_loginUrl))
{
script += string.Format("window.location.href = '{0}';", _loginUrl);
}
ClientScript.RegisterClientScriptBlock(GetType(), Guid.NewGuid().ToString(), script, true);
}
// cleanup
Session[HttpSessionStateVariables.RemoteSession.ToString()] = null;
if (Session[HttpSessionStateVariables.GuestInfo.ToString()] != null)
{
Session[HttpSessionStateVariables.GuestInfo.ToString()] = null;
}
RemoteSession = null;
}
}
catch (Exception exc)
{
System.Diagnostics.Trace.TraceError("Failed to retrieve the active remote session ({0})", exc);
}
}
// retrieve a shared remote session from url, if any
else if (!string.IsNullOrEmpty(Request["gid"]))
{
var guestId = Guid.Empty;
if (Guid.TryParse(Request["gid"], out guestId))
{
var sharingInfo = GetSharingInfo(guestId);
if (sharingInfo != null)
{
Session[HttpSessionStateVariables.RemoteSession.ToString()] = sharingInfo.RemoteSession;
Session[HttpSessionStateVariables.GuestInfo.ToString()] = sharingInfo.GuestInfo;
try
{
// remove the shared session guid from url
Response.Redirect("~/", true);
}
catch (ThreadAbortException)
{
// occurs because the response is ended after redirect
}
}
}
}
if (_httpSessionUseUri)
{
// if running myrtille into an iframe, the iframe url is registered (into a cookie) after the remote session is connected
// this is necessary to prevent a new http session from being generated for the iframe if the page is reloaded, due to the missing http session id into the iframe url (!)
// multiple iframes (on the same page), like multiple connections/tabs, requires cookieless="UseUri" for sessionState into web.config
// problem is, there can be many cases where the cookie is not removed after the remote session is disconnected (network issue, server down, etc?)
// if the page is reloaded, the iframe will use it's previously registered http session... which may not exist anymore or have its active remote session disconnected
// if that happens, unregister the iframe url (from the cookie) and reload the page; that will provide a new connection identifier to the iframe and reconnect it
if (!string.IsNullOrEmpty(Request["fid"]) && RemoteSession == null)
{
if (Request.Cookies[Request["fid"]] != null)
{
// remove the cookie for the given iframe
Response.Cookies[Request["fid"]].Expires = DateTime.Now.AddDays(-1);
// reload the page
ClientScript.RegisterClientScriptBlock(GetType(), Guid.NewGuid().ToString(), "parent.location.href = parent.location.href;", true);
}
}
}
// local admin
if (_enterpriseSession == null && RemoteSession == null && _enterpriseClient.GetMode() == EnterpriseMode.Local && !string.IsNullOrEmpty(Request["mode"]) && Request["mode"].Equals("admin"))
{
_localAdmin = true;
}
// postback events may redirect after execution; UI is updated from there
if (!IsPostBack)
{
UpdateControls();
}
// disable the browser cache; in addition to a "noCache" dummy param, with current time, on long-polling and xhr requests
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.Cache.SetNoStore();
}
/// <summary>
/// force remove the .net viewstate hidden fields from page (large bunch of unwanted data in url)
/// </summary>
/// <param name="writer"></param>
protected override void Render(
HtmlTextWriter writer)
{
var sb = new StringBuilder();
var sw = new StringWriter(sb);
var tw = new HtmlTextWriter(sw);
base.Render(tw);
var html = sb.ToString();
html = Regex.Replace(html, "<input[^>]*id=\"(__VIEWSTATE)\"[^>]*>", string.Empty, RegexOptions.IgnoreCase);
html = Regex.Replace(html, "<input[^>]*id=\"(__VIEWSTATEGENERATOR)\"[^>]*>", string.Empty, RegexOptions.IgnoreCase);
writer.Write(html);
}
/// <summary>
/// update the UI
/// </summary>
private void UpdateControls()
{
// remote session toolbar
if (RemoteSession != null && (RemoteSession.State == RemoteSessionState.Connecting || RemoteSession.State == RemoteSessionState.Connected))
{
if (_toolbarEnabled)
{
// interacting with the remote session is available to guests with control access, but only the remote session owner should have control on the remote session itself
var controlEnabled = Session.SessionID.Equals(RemoteSession.OwnerSessionID) || (Session[HttpSessionStateVariables.GuestInfo.ToString()] != null && ((GuestInfo)Session[HttpSessionStateVariables.GuestInfo.ToString()]).Control);
toolbar.Visible = true;
toolbarToggle.Visible = true;
serverInfo.Value = !string.IsNullOrEmpty(RemoteSession.VMGuid) ? RemoteSession.VMGuid : (!string.IsNullOrEmpty(RemoteSession.HostName) ? RemoteSession.HostName : RemoteSession.ServerAddress);
userInfo.Value = !string.IsNullOrEmpty(RemoteSession.VMGuid) || RemoteSession.SecurityProtocol == SecurityProtocol.rdp ? string.Empty : (string.IsNullOrEmpty(RemoteSession.UserDomain) ? RemoteSession.UserName : string.Format("{0}\\{1}", RemoteSession.UserDomain, RemoteSession.UserName));
userInfo.Visible = !string.IsNullOrEmpty(userInfo.Value);
scale.Value = RemoteSession.BrowserResize == BrowserResize.Scale ? "Scale ON" : "Scale OFF";
scale.Disabled = !Session.SessionID.Equals(RemoteSession.OwnerSessionID) || RemoteSession.HostType == HostType.SSH;
reconnect.Value = RemoteSession.BrowserResize == BrowserResize.Reconnect ? "Reconnect ON" : "Reconnect OFF";
reconnect.Disabled = !Session.SessionID.Equals(RemoteSession.OwnerSessionID) || RemoteSession.HostType == HostType.SSH;
keyboard.Disabled = !controlEnabled || (!string.IsNullOrEmpty(RemoteSession.VMGuid) && !RemoteSession.VMEnhancedMode);
osk.Disabled = !controlEnabled || RemoteSession.HostType == HostType.SSH;
clipboard.Disabled = !controlEnabled || RemoteSession.HostType == HostType.SSH || !RemoteSession.AllowRemoteClipboard || (!string.IsNullOrEmpty(RemoteSession.VMGuid) && !RemoteSession.VMEnhancedMode);
files.Disabled = !Session.SessionID.Equals(RemoteSession.OwnerSessionID) || RemoteSession.HostType == HostType.SSH || !RemoteSession.AllowFileTransfer || (RemoteSession.ServerAddress.ToLower() != "localhost" && RemoteSession.ServerAddress != "127.0.0.1" && RemoteSession.ServerAddress != "[::1]" && RemoteSession.ServerAddress != Request.Url.Host && string.IsNullOrEmpty(RemoteSession.UserDomain)) || !string.IsNullOrEmpty(RemoteSession.VMGuid);
cad.Disabled = !controlEnabled || RemoteSession.HostType == HostType.SSH;
mrc.Disabled = !controlEnabled || RemoteSession.HostType == HostType.SSH;
vswipe.Disabled = !controlEnabled || RemoteSession.HostType == HostType.SSH;
share.Disabled = !Session.SessionID.Equals(RemoteSession.OwnerSessionID) || !RemoteSession.AllowSessionSharing;
disconnect.Disabled = !Session.SessionID.Equals(RemoteSession.OwnerSessionID);
imageQuality.Disabled = !Session.SessionID.Equals(RemoteSession.OwnerSessionID) || RemoteSession.HostType == HostType.SSH;
}
}
// hosts list
else if (_enterpriseSession != null && _enterpriseSession.AuthenticationErrorCode == EnterpriseAuthenticationErrorCode.NONE)
{
hosts.Visible = true;
enterpriseUserInfo.Value = string.IsNullOrEmpty(_enterpriseSession.Domain) ? _enterpriseSession.UserName : string.Format("{0}\\{1}", _enterpriseSession.Domain, _enterpriseSession.UserName);
enterpriseUserInfo.Visible = !string.IsNullOrEmpty(enterpriseUserInfo.Value);
newRDPHost.Visible = _enterpriseSession.IsAdmin;
newSSHHost.Visible = _enterpriseSession.IsAdmin;
hostsList.DataSource = _enterpriseClient.GetSessionHosts(_enterpriseSession.SessionID);
hostsList.DataBind();
}
// login screen
else
{
// connection params are sent when the login form is submitted, either through http post (the default form method) or http get (querystring)
login.Visible = _loginEnabled;
// MFA
if (_mfaAuthClient.GetState())
{
mfaDiv.Visible = true;
mfaProvider.InnerText = _mfaAuthClient.GetPromptLabel();
mfaProvider.HRef = _mfaAuthClient.GetProviderURL();
}
// enterprise mode
if (_enterpriseClient.GetMode() == EnterpriseMode.Domain || _localAdmin)
{
hostConnectDiv.Visible = false;
adminDiv.Visible = _localAdmin;
if (adminDiv.Visible)
{
adminText.InnerText = "Home";
adminUrl.HRef = "~/";
}
}
// standard mode
else
{
connect.Attributes["onclick"] = "initDisplay();";
adminDiv.Visible = _enterpriseClient.GetMode() == EnterpriseMode.Local;
}
}
}
/// <summary>
/// enterprise mode from url: load the enterprise session (from querystring param) and proceed to connection; the user is non admin and the url is only usable once
/// enterprise mode from login: authenticate the user against the enterprise active directory and list the servers available to the user; the user is admin if member of the "EnterpriseAdminGroup" defined into myrtille services config
/// standard mode: connect the specified server; authentication is delegated to the remote server or connection broker (if applicable)
/// if MFA is enabled and not already processed, authenticate the user against the configured MFA provider (OTP preferred)
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void ConnectButtonClick(
object sender,
EventArgs e)
{
if (!_authorizedRequest)
return;
// one time usage enterprise session url
if (_enterpriseSession == null && Request["SI"] != null && Request["SD"] != null && Request["SK"] != null)
{
CreateEnterpriseSessionFromUrl();
}
// MFA (OTP passcode)
if (_enterpriseSession == null && _mfaAuthClient.GetState())
{
var clientIP = ClientIPHelper.ClientIPFromRequest(new HttpContextWrapper(HttpContext.Current).Request, true, new string[] { });
if (!_mfaAuthClient.Authenticate(user.Value, mfaPassword.Value, clientIP))
{
connectError.InnerText = "MFA Authentication failed!";
UpdateControls();
return;
}
}
// enterprise mode from login
if (_enterpriseSession == null && (_enterpriseClient.GetMode() == EnterpriseMode.Domain || _localAdmin))
{
CreateEnterpriseSessionFromLogin();
}
// connection from:
// > standard mode
// > enterprise mode: hosts list
// > enterprise mode: one time session url
else
{
// the display size is required to start a remote session
// if missing, the client will provide it automatically
if (string.IsNullOrEmpty(width.Value) || string.IsNullOrEmpty(height.Value))
{
return;
}
// connect
if (ConnectRemoteServer())
{
// in enterprise mode from login, a new http session id was already generated (no need to do it each time an host is connected!)
// in standard mode or enterprise mode from url, a new http session id must be generated
if (_enterpriseSession == null || Request["SI"] != null)
{
// session fixation protection
if (_httpSessionUseUri)
{
// generate a new http session id
RemoteSession.OwnerSessionID = HttpSessionHelper.RegenerateSessionId();
}
}
try
{
// standard mode: switch to http get (standard login) or remove the connection params from url (auto-connect / start program from url)
// enterprise mode: remove the host id from url
Response.Redirect("~/", true);
}
catch (ThreadAbortException)
{
// occurs because the response is ended after redirect
}
}
// connection failed from the hosts list or from a one time session url
else if (_enterpriseSession != null && Request["SD"] != null)
{
try
{
// remove the host id from url
Response.Redirect("~/", true);
}
catch (ThreadAbortException)
{
// occurs because the response is ended after redirect
}
}
}
}
/// <summary>
/// connect the remote server
/// </summary>
/// <remarks>
/// authentication is delegated to the remote server or connection broker (if applicable)
/// </remarks>
private bool ConnectRemoteServer()
{
// connection parameters
string loginHostName = null;
var loginHostType = (HostType)Convert.ToInt32(hostType.Value);
var loginProtocol = (SecurityProtocol)securityProtocol.SelectedIndex;
var loginServer = string.IsNullOrEmpty(server.Value) ? "localhost" : server.Value;
var loginVMGuid = vmGuid.Value;
var loginVMAddress = string.Empty;
var loginVMEnhancedMode = vmEnhancedMode.Checked;
var loginDomain = domain.Value;
var loginUser = user.Value;
var loginPassword = string.IsNullOrEmpty(passwordHash.Value) ? password.Value : CryptoHelper.RDP_Decrypt(passwordHash.Value);
var startProgram = program.Value;
// allowed features
var allowRemoteClipboard = _allowRemoteClipboard;
var allowFileTransfer = _allowFileTransfer;
var allowPrintDownload = _allowPrintDownload;
var allowSessionSharing = _allowSessionSharing;
var allowAudioPlayback = _allowAudioPlayback;
// sharing parameters
int maxActiveGuests = int.MaxValue;
var connectionId = Guid.NewGuid();
// connect an host from the hosts list or from a one time session url
if (_enterpriseSession != null && (!string.IsNullOrEmpty(Request["SD"])))
{
long hostId;
if (!long.TryParse(Request["SD"], out hostId))
{
hostId = 0;
}
try
{
// retrieve the host connection details
var connection = _enterpriseClient.GetSessionConnectionDetails(_enterpriseSession.SessionID, hostId, _enterpriseSession.SessionKey);
if (connection == null)
{
System.Diagnostics.Trace.TraceInformation("Unable to retrieve host {0} connection details (invalid host or one time session url already used?)", hostId);
return false;
}
loginHostName = connection.HostName;
loginHostType = connection.HostType;
loginProtocol = connection.Protocol;
loginServer = !string.IsNullOrEmpty(connection.HostAddress) ? connection.HostAddress : connection.HostName;
loginVMGuid = connection.VMGuid;
loginVMEnhancedMode = connection.VMEnhancedMode;
loginDomain = connection.Domain;
loginUser = connection.Username;
loginPassword = CryptoHelper.RDP_Decrypt(connection.Password);
startProgram = connection.StartRemoteProgram;
}
catch (Exception exc)
{
System.Diagnostics.Trace.TraceError("Failed to retrieve host {0} connection details ({1})", hostId, exc);
return false;
}
}
// by using a connection service on a backend (connection API), the connection details can be hidden from querystring and mapped to a connection identifier
else if (!string.IsNullOrEmpty(Request["cid"]))
{
if (!Guid.TryParse(Request["cid"], out connectionId))
{
System.Diagnostics.Trace.TraceInformation("Invalid connection id {0}", Request["cid"]);
return false;
}
try
{
// retrieve the connection details
var connection = _connectionClient.GetConnectionInfo(connectionId);
if (connection == null)
{
System.Diagnostics.Trace.TraceInformation("Unable to retrieve connection info {0}", connectionId);
return false;
}
// ensure the user is allowed to connect the host
if (!_connectionClient.IsUserAllowedToConnectHost(connection.User.Domain, connection.User.UserName, connection.Host.IPAddress, connection.VM != null ? connection.VM.Guid : Guid.Empty))
{
System.Diagnostics.Trace.TraceInformation("User: domain={0}, name={1} is not allowed to connect host {2}", connection.User.Domain, connection.User.UserName, connection.Host.IPAddress);
return false;
}
loginHostType = connection.Host.HostType;
loginProtocol = connection.Host.SecurityProtocol;
loginServer = connection.Host.IPAddress;
loginVMGuid = connection.VM != null ? connection.VM.Guid.ToString() : string.Empty;
loginVMAddress = connection.VM != null ? connection.VM.IPAddress : string.Empty;
loginVMEnhancedMode = connection.VM != null ? connection.VM.EnhancedMode : false;
loginDomain = connection.User.Domain;
loginUser = connection.User.UserName;
loginPassword = connection.User.Password;
startProgram = connection.StartProgram;
allowRemoteClipboard = allowRemoteClipboard && connection.AllowRemoteClipboard;
allowFileTransfer = allowFileTransfer && connection.AllowFileTransfer;
allowPrintDownload = allowPrintDownload && connection.AllowPrintDownload;
allowSessionSharing = allowSessionSharing && connection.MaxActiveGuests > 0;
allowAudioPlayback = allowAudioPlayback && connection.AllowAudioPlayback;
maxActiveGuests = connection.MaxActiveGuests;
}
catch (Exception exc)
{
System.Diagnostics.Trace.TraceError("Failed to retrieve connection info {0} ({1})", connectionId, exc);
return false;
}
}
// if the connection from login screen or url is disabled, the connection must be done either by using a connection API or from the enterprise mode
else if (!_loginEnabled)
{
return false;
}
// remove any active remote session (disconnected?)
if (RemoteSession != null)
{
// unset the remote session for the current http session
Session[HttpSessionStateVariables.RemoteSession.ToString()] = null;
RemoteSession = null;
}
// create a new remote session
try
{
Application.Lock();
// create the remote session
RemoteSession = new RemoteSession(
connectionId,
loginHostName,
loginHostType,
loginProtocol,
loginServer,
loginVMGuid,
loginVMAddress,
loginVMEnhancedMode,
!string.IsNullOrEmpty(loginDomain) ? loginDomain : AccountHelper.GetDomain(loginUser, loginPassword),
AccountHelper.GetUserName(loginUser),
loginPassword,
int.Parse(width.Value),
int.Parse(height.Value),
startProgram,
allowRemoteClipboard,
allowFileTransfer,
allowPrintDownload,
allowSessionSharing,
allowAudioPlayback,
maxActiveGuests,
Session.SessionID,
(string)Session[HttpSessionStateVariables.ClientKey.ToString()],
Request["cid"] != null
);
// bind the remote session to the current http session
Session[HttpSessionStateVariables.RemoteSession.ToString()] = RemoteSession;
// register the remote session at the application level
var remoteSessions = (IDictionary<Guid, RemoteSession>)Application[HttpApplicationStateVariables.RemoteSessions.ToString()];
remoteSessions.Add(RemoteSession.Id, RemoteSession);
}
catch (Exception exc)
{
System.Diagnostics.Trace.TraceError("Failed to create remote session ({0})", exc);
RemoteSession = null;
}
finally
{
Application.UnLock();
}
// connect it
if (RemoteSession != null)
{
RemoteSession.State = RemoteSessionState.Connecting;
}
else
{
connectError.InnerText = "Failed to create remote session!";
return false;
}
return true;
}
#region enterprise mode
/// <summary>
/// create an enterprise session from a one time url
/// </summary>
private void CreateEnterpriseSessionFromUrl()
{
try
{
// create enterprise session from querystring params
_enterpriseSession = new EnterpriseSession
{
IsAdmin = false, // simple host connection only (no hosts management)
SessionID = Request["SI"],
SessionKey = Request["SK"],
SingleUseConnection = true
};
// bind the enterprise session to the current http session
Session[HttpSessionStateVariables.EnterpriseSession.ToString()] = _enterpriseSession;
// session fixation protection
if (_httpSessionUseUri)
{
// generate a new http session id
HttpSessionHelper.RegenerateSessionId();
}
}
catch (Exception exc)
{
System.Diagnostics.Trace.TraceError("Failed to create enterprise session from url ({0})", exc);
}
}
/// <summary>
/// authenticate the user against the enterprise active directory and list the servers available to the user
/// </summary>
private void CreateEnterpriseSessionFromLogin()
{
try
{
// authenticate the user
_enterpriseSession = _enterpriseClient.Authenticate(user.Value, password.Value);
if (_enterpriseSession == null || _enterpriseSession.AuthenticationErrorCode != EnterpriseAuthenticationErrorCode.NONE)
{
if (_enterpriseSession == null)
{
connectError.InnerText = EnterpriseAuthenticationErrorHelper.GetErrorDescription(EnterpriseAuthenticationErrorCode.UNKNOWN_ERROR);
}
else if (_enterpriseSession.AuthenticationErrorCode == EnterpriseAuthenticationErrorCode.PASSWORD_EXPIRED)
{
ClientScript.RegisterClientScriptBlock(GetType(), Guid.NewGuid().ToString(), "window.onload = function() { " + string.Format("openPopup('changePasswordPopup', 'EnterpriseChangePassword.aspx?userName={0}" + (_localAdmin ? "&mode=admin" : string.Empty) + "');", user.Value) + " }", true);
}
else
{
connectError.InnerText = EnterpriseAuthenticationErrorHelper.GetErrorDescription(_enterpriseSession.AuthenticationErrorCode);
}
UpdateControls();
return;
}
// bind the enterprise session to the current http session
Session[HttpSessionStateVariables.EnterpriseSession.ToString()] = _enterpriseSession;
// session fixation protection
if (_httpSessionUseUri)
{
// generate a new http session id
HttpSessionHelper.RegenerateSessionId();
}
// redirect to the hosts list
Response.Redirect("~/", true);
}
catch (ThreadAbortException)
{
// occurs because the response is ended after redirect
}
catch (Exception exc)
{
System.Diagnostics.Trace.TraceError("Failed to create enterprise session from login ({0})", exc);
}
}
/// <summary>
/// populate the enterprise session hosts list
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void hostsList_ItemDataBound(
object sender,
RepeaterItemEventArgs e)
{
try
{
var host = e.Item.DataItem as EnterpriseHost;
if (host.PromptForCredentials || string.IsNullOrEmpty(_enterpriseSession.Domain))
{
var hostLink = e.Item.FindControl("hostLink") as HtmlAnchor;
hostLink.HRef = null;
hostLink.Attributes["onclick"] = string.Format("openPopup('editCredentialPopup', 'CredentialsPrompt.aspx?hostId={0}');", host.HostID);
hostLink.Attributes["class"] = "hostLink";
}
else
{
var hostLink = e.Item.FindControl("hostLink") as HtmlAnchor;
hostLink.HRef = string.Format("?SD={0}&__EVENTTARGET=&__EVENTARGUMENT=&connect=Connect%21", host.HostID);
hostLink.Attributes["class"] = "hostLink";
}
var hostName = e.Item.FindControl("hostName") as HtmlGenericControl;
hostName.InnerText = (_enterpriseSession.IsAdmin ? "Edit " : string.Empty) + host.HostName;
if (_enterpriseSession.IsAdmin)
{
hostName.Attributes["class"] = "hostName";
hostName.Attributes["title"] = "edit";
hostName.Attributes["onclick"] = string.Format("openPopup('editHostPopup', 'EditHost.aspx?hostId={0}');", host.HostID);
}
}
catch (Exception exc)
{
System.Diagnostics.Trace.TraceError("Failed to populate hosts for the enterprise session {0} ({1})", _enterpriseSession.SessionID, exc);
}
}
/// <summary>
/// logout the enterprise session
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void LogoutButtonClick(
object sender,
EventArgs e)
{
if (!_authorizedRequest)
return;
if (_enterpriseSession == null)
return;
try
{
// logout the enterprise session
_enterpriseClient.Logout(_enterpriseSession.SessionID);
Session[HttpSessionStateVariables.EnterpriseSession.ToString()] = null;
_enterpriseSession = null;
// redirect to the login screen
Response.Redirect("~/", true);
}
catch (ThreadAbortException)
{
// occurs because the response is ended after redirect
}
catch (Exception exc)
{
System.Diagnostics.Trace.TraceError("Failed to logout the enterprise session {0} ({1})", _enterpriseSession.SessionID, exc);
}
}
#endregion
#region session sharing
/// <summary>
/// retrieve a shared remote session information
/// </summary>
/// <param name="guestId"></param>
/// <returns></returns>
private SharingInfo GetSharingInfo(
Guid guestId)
{
SharingInfo sharingInfo = null;
try
{
Application.Lock();
var sharedSessions = (IDictionary<Guid, SharingInfo>)Application[HttpApplicationStateVariables.SharedRemoteSessions.ToString()];
if (!sharedSessions.ContainsKey(guestId))
{
connectError.InnerText = "Invalid sharing link";
}
else
{
sharingInfo = sharedSessions[guestId];
if (sharingInfo.GuestInfo.Active)
{
connectError.InnerText = "The sharing link was already used";
sharingInfo = null;
}
else if (sharingInfo.RemoteSession.State != RemoteSessionState.Connected)
{
connectError.InnerText = "The session is not connected";
sharingInfo = null;
}
else if (sharingInfo.RemoteSession.ActiveGuests >= sharingInfo.RemoteSession.MaxActiveGuests)
{
connectError.InnerText = "The maximum number of active guests was reached for the session";
sharingInfo = null;
}
else
{
sharingInfo.HttpSession = Session;
sharingInfo.RemoteSession.ActiveGuests++;
sharingInfo.GuestInfo.Active = true;
}
}
}
catch (Exception exc)
{
System.Diagnostics.Trace.TraceError("Failed to retrieve the shared remote session for guest {0} ({1})", guestId, exc);
}
finally
{
Application.UnLock();
}
return sharingInfo;
}
#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;
using System.Collections.Generic;
using System.Net;
using System.Reflection;
using log4net;
using Nini.Config;
using Nwc.XmlRpc;
using Mono.Addins;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Framework.Servers;
using OpenSim.Framework.Servers.HttpServer;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Services.Interfaces;
namespace OpenSim.Region.OptionalModules.World.MoneyModule
{
/// <summary>
/// This is only the functionality required to make the functionality associated with money work
/// (such as land transfers). There is no money code here! Use FORGE as an example for money code.
/// Demo Economy/Money Module. This is a purposely crippled module!
/// // To land transfer you need to add:
/// -helperuri http://serveraddress:port/
/// to the command line parameters you use to start up your client
/// This commonly looks like -helperuri http://127.0.0.1:9000/
///
/// </summary>
[Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "SampleMoneyModule")]
public class SampleMoneyModule : IMoneyModule, ISharedRegionModule
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
/// <summary>
/// Where Stipends come from and Fees go to.
/// </summary>
// private UUID EconomyBaseAccount = UUID.Zero;
private float EnergyEfficiency = 0f;
// private ObjectPaid handerOnObjectPaid;
private bool m_enabled = true;
private bool m_sellEnabled = false;
private IConfigSource m_gConfig;
/// <summary>
/// Region UUIDS indexed by AgentID
/// </summary>
/// <summary>
/// Scenes by Region Handle
/// </summary>
private Dictionary<ulong, Scene> m_scenel = new Dictionary<ulong, Scene>();
// private int m_stipend = 1000;
private int ObjectCount = 0;
private int PriceEnergyUnit = 0;
private int PriceGroupCreate = 0;
private int PriceObjectClaim = 0;
private float PriceObjectRent = 0f;
private float PriceObjectScaleFactor = 0f;
private int PriceParcelClaim = 0;
private float PriceParcelClaimFactor = 0f;
private int PriceParcelRent = 0;
private int PricePublicObjectDecay = 0;
private int PricePublicObjectDelete = 0;
private int PriceRentLight = 0;
private int PriceUpload = 0;
private int TeleportMinPrice = 0;
private float TeleportPriceExponent = 0f;
#region IMoneyModule Members
public event ObjectPaid OnObjectPaid;
public int UploadCharge
{
get { return 0; }
}
public int GroupCreationCharge
{
get { return 0; }
}
/// <summary>
/// Called on startup so the module can be configured.
/// </summary>
/// <param name="config">Configuration source.</param>
public void Initialise(IConfigSource config)
{
m_gConfig = config;
IConfig startupConfig = m_gConfig.Configs["Startup"];
IConfig economyConfig = m_gConfig.Configs["Economy"];
ReadConfigAndPopulate(startupConfig, "Startup");
ReadConfigAndPopulate(economyConfig, "Economy");
}
public void AddRegion(Scene scene)
{
if (m_enabled)
{
scene.RegisterModuleInterface<IMoneyModule>(this);
IHttpServer httpServer = MainServer.Instance;
lock (m_scenel)
{
if (m_scenel.Count == 0)
{
// XMLRPCHandler = scene;
// To use the following you need to add:
// -helperuri <ADDRESS TO HERE OR grid MONEY SERVER>
// to the command line parameters you use to start up your client
// This commonly looks like -helperuri http://127.0.0.1:9000/
// Local Server.. enables functionality only.
httpServer.AddXmlRPCHandler("getCurrencyQuote", quote_func);
httpServer.AddXmlRPCHandler("buyCurrency", buy_func);
httpServer.AddXmlRPCHandler("preflightBuyLandPrep", preflightBuyLandPrep_func);
httpServer.AddXmlRPCHandler("buyLandPrep", landBuy_func);
}
if (m_scenel.ContainsKey(scene.RegionInfo.RegionHandle))
{
m_scenel[scene.RegionInfo.RegionHandle] = scene;
}
else
{
m_scenel.Add(scene.RegionInfo.RegionHandle, scene);
}
}
scene.EventManager.OnNewClient += OnNewClient;
scene.EventManager.OnMoneyTransfer += MoneyTransferAction;
scene.EventManager.OnClientClosed += ClientClosed;
scene.EventManager.OnAvatarEnteringNewParcel += AvatarEnteringParcel;
scene.EventManager.OnMakeChildAgent += MakeChildAgent;
scene.EventManager.OnClientClosed += ClientLoggedOut;
scene.EventManager.OnValidateLandBuy += ValidateLandBuy;
scene.EventManager.OnLandBuy += processLandBuy;
}
}
public void RemoveRegion(Scene scene)
{
}
public void RegionLoaded(Scene scene)
{
}
// Please do not refactor these to be just one method
// Existing implementations need the distinction
//
public void ApplyCharge(UUID agentID, int amount, string text)
{
}
public void ApplyUploadCharge(UUID agentID, int amount, string text)
{
}
public bool ObjectGiveMoney(UUID objectID, UUID fromID, UUID toID, int amount)
{
string description = String.Format("Object {0} pays {1}", resolveObjectName(objectID), resolveAgentName(toID));
bool give_result = doMoneyTransfer(fromID, toID, amount, 2, description);
BalanceUpdate(fromID, toID, give_result, description);
return give_result;
}
public void PostInitialise()
{
}
public void Close()
{
}
public Type ReplaceableInterface
{
get { return typeof(IMoneyModule); }
}
public string Name
{
get { return "BetaGridLikeMoneyModule"; }
}
#endregion
/// <summary>
/// Parse Configuration
/// </summary>
/// <param name="scene"></param>
/// <param name="startupConfig"></param>
/// <param name="config"></param>
private void ReadConfigAndPopulate(IConfig startupConfig, string config)
{
if (config == "Startup" && startupConfig != null)
{
m_enabled = (startupConfig.GetString("economymodule", "BetaGridLikeMoneyModule") == "BetaGridLikeMoneyModule");
}
if (config == "Economy" && startupConfig != null)
{
PriceEnergyUnit = startupConfig.GetInt("PriceEnergyUnit", 100);
PriceObjectClaim = startupConfig.GetInt("PriceObjectClaim", 10);
PricePublicObjectDecay = startupConfig.GetInt("PricePublicObjectDecay", 4);
PricePublicObjectDelete = startupConfig.GetInt("PricePublicObjectDelete", 4);
PriceParcelClaim = startupConfig.GetInt("PriceParcelClaim", 1);
PriceParcelClaimFactor = startupConfig.GetFloat("PriceParcelClaimFactor", 1f);
PriceUpload = startupConfig.GetInt("PriceUpload", 0);
PriceRentLight = startupConfig.GetInt("PriceRentLight", 5);
TeleportMinPrice = startupConfig.GetInt("TeleportMinPrice", 2);
TeleportPriceExponent = startupConfig.GetFloat("TeleportPriceExponent", 2f);
EnergyEfficiency = startupConfig.GetFloat("EnergyEfficiency", 1);
PriceObjectRent = startupConfig.GetFloat("PriceObjectRent", 1);
PriceObjectScaleFactor = startupConfig.GetFloat("PriceObjectScaleFactor", 10);
PriceParcelRent = startupConfig.GetInt("PriceParcelRent", 1);
PriceGroupCreate = startupConfig.GetInt("PriceGroupCreate", -1);
m_sellEnabled = startupConfig.GetBoolean("SellEnabled", false);
}
}
private void GetClientFunds(IClientAPI client)
{
CheckExistAndRefreshFunds(client.AgentId);
}
/// <summary>
/// New Client Event Handler
/// </summary>
/// <param name="client"></param>
private void OnNewClient(IClientAPI client)
{
GetClientFunds(client);
// Subscribe to Money messages
client.OnEconomyDataRequest += EconomyDataRequestHandler;
client.OnMoneyBalanceRequest += SendMoneyBalance;
client.OnRequestPayPrice += requestPayPrice;
client.OnObjectBuy += ObjectBuy;
client.OnLogout += ClientClosed;
}
/// <summary>
/// Transfer money
/// </summary>
/// <param name="Sender"></param>
/// <param name="Receiver"></param>
/// <param name="amount"></param>
/// <returns></returns>
private bool doMoneyTransfer(UUID Sender, UUID Receiver, int amount, int transactiontype, string description)
{
bool result = true;
return result;
}
/// <summary>
/// Sends the the stored money balance to the client
/// </summary>
/// <param name="client"></param>
/// <param name="agentID"></param>
/// <param name="SessionID"></param>
/// <param name="TransactionID"></param>
public void SendMoneyBalance(IClientAPI client, UUID agentID, UUID SessionID, UUID TransactionID)
{
if (client.AgentId == agentID && client.SessionId == SessionID)
{
int returnfunds = 0;
try
{
returnfunds = GetFundsForAgentID(agentID);
}
catch (Exception e)
{
client.SendAlertMessage(e.Message + " ");
}
client.SendMoneyBalance(TransactionID, true, new byte[0], returnfunds);
}
else
{
client.SendAlertMessage("Unable to send your money balance to you!");
}
}
private SceneObjectPart findPrim(UUID objectID)
{
lock (m_scenel)
{
foreach (Scene s in m_scenel.Values)
{
SceneObjectPart part = s.GetSceneObjectPart(objectID);
if (part != null)
{
return part;
}
}
}
return null;
}
private string resolveObjectName(UUID objectID)
{
SceneObjectPart part = findPrim(objectID);
if (part != null)
{
return part.Name;
}
return String.Empty;
}
private string resolveAgentName(UUID agentID)
{
// try avatar username surname
Scene scene = GetRandomScene();
UserAccount account = scene.UserAccountService.GetUserAccount(scene.RegionInfo.ScopeID, agentID);
if (account != null)
{
string avatarname = account.FirstName + " " + account.LastName;
return avatarname;
}
else
{
m_log.ErrorFormat(
"[MONEY]: Could not resolve user {0}",
agentID);
}
return String.Empty;
}
private void BalanceUpdate(UUID senderID, UUID receiverID, bool transactionresult, string description)
{
IClientAPI sender = LocateClientObject(senderID);
IClientAPI receiver = LocateClientObject(receiverID);
if (senderID != receiverID)
{
if (sender != null)
{
sender.SendMoneyBalance(UUID.Random(), transactionresult, Utils.StringToBytes(description), GetFundsForAgentID(senderID));
}
if (receiver != null)
{
receiver.SendMoneyBalance(UUID.Random(), transactionresult, Utils.StringToBytes(description), GetFundsForAgentID(receiverID));
}
}
}
/// <summary>
/// XMLRPC handler to send alert message and sound to client
/// </summary>
public XmlRpcResponse UserAlert(XmlRpcRequest request, IPEndPoint remoteClient)
{
XmlRpcResponse ret = new XmlRpcResponse();
Hashtable retparam = new Hashtable();
Hashtable requestData = (Hashtable) request.Params[0];
UUID agentId;
UUID soundId;
UUID regionId;
UUID.TryParse((string) requestData["agentId"], out agentId);
UUID.TryParse((string) requestData["soundId"], out soundId);
UUID.TryParse((string) requestData["regionId"], out regionId);
string text = (string) requestData["text"];
string secret = (string) requestData["secret"];
Scene userScene = GetSceneByUUID(regionId);
if (userScene != null)
{
if (userScene.RegionInfo.regionSecret == secret)
{
IClientAPI client = LocateClientObject(agentId);
if (client != null)
{
if (soundId != UUID.Zero)
client.SendPlayAttachedSound(soundId, UUID.Zero, UUID.Zero, 1.0f, 0);
client.SendBlueBoxMessage(UUID.Zero, "", text);
retparam.Add("success", true);
}
else
{
retparam.Add("success", false);
}
}
else
{
retparam.Add("success", false);
}
}
ret.Value = retparam;
return ret;
}
# region Standalone box enablers only
public XmlRpcResponse quote_func(XmlRpcRequest request, IPEndPoint remoteClient)
{
// Hashtable requestData = (Hashtable) request.Params[0];
// UUID agentId = UUID.Zero;
int amount = 0;
Hashtable quoteResponse = new Hashtable();
XmlRpcResponse returnval = new XmlRpcResponse();
Hashtable currencyResponse = new Hashtable();
currencyResponse.Add("estimatedCost", 0);
currencyResponse.Add("currencyBuy", amount);
quoteResponse.Add("success", true);
quoteResponse.Add("currency", currencyResponse);
quoteResponse.Add("confirm", "asdfad9fj39ma9fj");
returnval.Value = quoteResponse;
return returnval;
}
public XmlRpcResponse buy_func(XmlRpcRequest request, IPEndPoint remoteClient)
{
// Hashtable requestData = (Hashtable) request.Params[0];
// UUID agentId = UUID.Zero;
// int amount = 0;
XmlRpcResponse returnval = new XmlRpcResponse();
Hashtable returnresp = new Hashtable();
returnresp.Add("success", true);
returnval.Value = returnresp;
return returnval;
}
public XmlRpcResponse preflightBuyLandPrep_func(XmlRpcRequest request, IPEndPoint remoteClient)
{
XmlRpcResponse ret = new XmlRpcResponse();
Hashtable retparam = new Hashtable();
Hashtable membershiplevels = new Hashtable();
ArrayList levels = new ArrayList();
Hashtable level = new Hashtable();
level.Add("id", "00000000-0000-0000-0000-000000000000");
level.Add("description", "some level");
levels.Add(level);
//membershiplevels.Add("levels",levels);
Hashtable landuse = new Hashtable();
landuse.Add("upgrade", false);
landuse.Add("action", "http://invaliddomaininvalid.com/");
Hashtable currency = new Hashtable();
currency.Add("estimatedCost", 0);
Hashtable membership = new Hashtable();
membershiplevels.Add("upgrade", false);
membershiplevels.Add("action", "http://invaliddomaininvalid.com/");
membershiplevels.Add("levels", membershiplevels);
retparam.Add("success", true);
retparam.Add("currency", currency);
retparam.Add("membership", membership);
retparam.Add("landuse", landuse);
retparam.Add("confirm", "asdfajsdkfjasdkfjalsdfjasdf");
ret.Value = retparam;
return ret;
}
public XmlRpcResponse landBuy_func(XmlRpcRequest request, IPEndPoint remoteClient)
{
XmlRpcResponse ret = new XmlRpcResponse();
Hashtable retparam = new Hashtable();
// Hashtable requestData = (Hashtable) request.Params[0];
// UUID agentId = UUID.Zero;
// int amount = 0;
retparam.Add("success", true);
ret.Value = retparam;
return ret;
}
#endregion
#region local Fund Management
/// <summary>
/// Ensures that the agent accounting data is set up in this instance.
/// </summary>
/// <param name="agentID"></param>
private void CheckExistAndRefreshFunds(UUID agentID)
{
}
/// <summary>
/// Gets the amount of Funds for an agent
/// </summary>
/// <param name="AgentID"></param>
/// <returns></returns>
private int GetFundsForAgentID(UUID AgentID)
{
int returnfunds = 0;
return returnfunds;
}
// private void SetLocalFundsForAgentID(UUID AgentID, int amount)
// {
// }
#endregion
#region Utility Helpers
/// <summary>
/// Locates a IClientAPI for the client specified
/// </summary>
/// <param name="AgentID"></param>
/// <returns></returns>
private IClientAPI LocateClientObject(UUID AgentID)
{
ScenePresence tPresence = null;
IClientAPI rclient = null;
lock (m_scenel)
{
foreach (Scene _scene in m_scenel.Values)
{
tPresence = _scene.GetScenePresence(AgentID);
if (tPresence != null)
{
if (!tPresence.IsChildAgent)
{
rclient = tPresence.ControllingClient;
}
}
if (rclient != null)
{
return rclient;
}
}
}
return null;
}
private Scene LocateSceneClientIn(UUID AgentId)
{
lock (m_scenel)
{
foreach (Scene _scene in m_scenel.Values)
{
ScenePresence tPresence = _scene.GetScenePresence(AgentId);
if (tPresence != null)
{
if (!tPresence.IsChildAgent)
{
return _scene;
}
}
}
}
return null;
}
/// <summary>
/// Utility function Gets a Random scene in the instance. For when which scene exactly you're doing something with doesn't matter
/// </summary>
/// <returns></returns>
public Scene GetRandomScene()
{
lock (m_scenel)
{
foreach (Scene rs in m_scenel.Values)
return rs;
}
return null;
}
/// <summary>
/// Utility function to get a Scene by RegionID in a module
/// </summary>
/// <param name="RegionID"></param>
/// <returns></returns>
public Scene GetSceneByUUID(UUID RegionID)
{
lock (m_scenel)
{
foreach (Scene rs in m_scenel.Values)
{
if (rs.RegionInfo.originRegionID == RegionID)
{
return rs;
}
}
}
return null;
}
#endregion
#region event Handlers
public void requestPayPrice(IClientAPI client, UUID objectID)
{
Scene scene = LocateSceneClientIn(client.AgentId);
if (scene == null)
return;
SceneObjectPart task = scene.GetSceneObjectPart(objectID);
if (task == null)
return;
SceneObjectGroup group = task.ParentGroup;
SceneObjectPart root = group.RootPart;
client.SendPayPrice(objectID, root.PayPrice);
}
/// <summary>
/// When the client closes the connection we remove their accounting
/// info from memory to free up resources.
/// </summary>
/// <param name="AgentID">UUID of agent</param>
/// <param name="scene">Scene the agent was connected to.</param>
/// <see cref="OpenSim.Region.Framework.Scenes.EventManager.ClientClosed"/>
public void ClientClosed(UUID AgentID, Scene scene)
{
}
/// <summary>
/// Event called Economy Data Request handler.
/// </summary>
/// <param name="agentId"></param>
public void EconomyDataRequestHandler(UUID agentId)
{
IClientAPI user = LocateClientObject(agentId);
if (user != null)
{
Scene s = LocateSceneClientIn(user.AgentId);
user.SendEconomyData(EnergyEfficiency, s.RegionInfo.ObjectCapacity, ObjectCount, PriceEnergyUnit, PriceGroupCreate,
PriceObjectClaim, PriceObjectRent, PriceObjectScaleFactor, PriceParcelClaim, PriceParcelClaimFactor,
PriceParcelRent, PricePublicObjectDecay, PricePublicObjectDelete, PriceRentLight, PriceUpload,
TeleportMinPrice, TeleportPriceExponent);
}
}
private void ValidateLandBuy(Object osender, EventManager.LandBuyArgs e)
{
lock (e)
{
e.economyValidated = true;
}
}
private void processLandBuy(Object osender, EventManager.LandBuyArgs e)
{
}
/// <summary>
/// THis method gets called when someone pays someone else as a gift.
/// </summary>
/// <param name="osender"></param>
/// <param name="e"></param>
private void MoneyTransferAction(Object osender, EventManager.MoneyTransferArgs e)
{
}
/// <summary>
/// Event Handler for when a root agent becomes a child agent
/// </summary>
/// <param name="avatar"></param>
private void MakeChildAgent(ScenePresence avatar)
{
}
/// <summary>
/// Event Handler for when the client logs out.
/// </summary>
/// <param name="AgentId"></param>
private void ClientLoggedOut(UUID AgentId, Scene scene)
{
}
/// <summary>
/// Call this when the client disconnects.
/// </summary>
/// <param name="client"></param>
public void ClientClosed(IClientAPI client)
{
ClientClosed(client.AgentId, null);
}
/// <summary>
/// Event Handler for when an Avatar enters one of the parcels in the simulator.
/// </summary>
/// <param name="avatar"></param>
/// <param name="localLandID"></param>
/// <param name="regionID"></param>
private void AvatarEnteringParcel(ScenePresence avatar, int localLandID, UUID regionID)
{
//m_log.Info("[FRIEND]: " + avatar.Name + " status:" + (!avatar.IsChildAgent).ToString());
}
public int GetBalance(UUID agentID)
{
return 0;
}
// Please do not refactor these to be just one method
// Existing implementations need the distinction
//
public bool UploadCovered(UUID agentID, int amount)
{
return true;
}
public bool AmountCovered(UUID agentID, int amount)
{
return true;
}
#endregion
public void ObjectBuy(IClientAPI remoteClient, UUID agentID,
UUID sessionID, UUID groupID, UUID categoryID,
uint localID, byte saleType, int salePrice)
{
if (!m_sellEnabled)
{
remoteClient.SendBlueBoxMessage(UUID.Zero, "", "Buying is not implemented in this version");
return;
}
if (salePrice != 0)
{
remoteClient.SendBlueBoxMessage(UUID.Zero, "", "Buying anything for a price other than zero is not implemented");
return;
}
Scene s = LocateSceneClientIn(remoteClient.AgentId);
// Implmenting base sale data checking here so the default OpenSimulator implementation isn't useless
// combined with other implementations. We're actually validating that the client is sending the data
// that it should. In theory, the client should already know what to send here because it'll see it when it
// gets the object data. If the data sent by the client doesn't match the object, the viewer probably has an
// old idea of what the object properties are. Viewer developer Hazim informed us that the base module
// didn't check the client sent data against the object do any. Since the base modules are the
// 'crowning glory' examples of good practice..
// Validate that the object exists in the scene the user is in
SceneObjectPart part = s.GetSceneObjectPart(localID);
if (part == null)
{
remoteClient.SendAgentAlertMessage("Unable to buy now. The object was not found.", false);
return;
}
// Validate that the client sent the price that the object is being sold for
if (part.SalePrice != salePrice)
{
remoteClient.SendAgentAlertMessage("Cannot buy at this price. Buy Failed. If you continue to get this relog.", false);
return;
}
// Validate that the client sent the proper sale type the object has set
if (part.ObjectSaleType != saleType)
{
remoteClient.SendAgentAlertMessage("Cannot buy this way. Buy Failed. If you continue to get this relog.", false);
return;
}
IBuySellModule module = s.RequestModuleInterface<IBuySellModule>();
if (module != null)
module.BuyObject(remoteClient, categoryID, localID, saleType, salePrice);
}
}
public enum TransactionType : int
{
SystemGenerated = 0,
RegionMoneyRequest = 1,
Gift = 2,
Purchase = 3
}
}
| |
// 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.
// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
//
// IntersectQueryOperator.cs
//
// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading;
namespace System.Linq.Parallel
{
/// <summary>
/// Operator that yields the intersection of two data sources.
/// </summary>
/// <typeparam name="TInputOutput"></typeparam>
internal sealed class IntersectQueryOperator<TInputOutput> :
BinaryQueryOperator<TInputOutput, TInputOutput, TInputOutput>
{
private readonly IEqualityComparer<TInputOutput> _comparer; // An equality comparer.
//---------------------------------------------------------------------------------------
// Constructs a new intersection operator.
//
internal IntersectQueryOperator(ParallelQuery<TInputOutput> left, ParallelQuery<TInputOutput> right, IEqualityComparer<TInputOutput> comparer)
: base(left, right)
{
Debug.Assert(left != null && right != null, "child data sources cannot be null");
_comparer = comparer;
_outputOrdered = LeftChild.OutputOrdered;
SetOrdinalIndex(OrdinalIndexState.Shuffled);
}
internal override QueryResults<TInputOutput> Open(
QuerySettings settings, bool preferStriping)
{
// We just open our child operators, left and then right. Do not propagate the preferStriping value, but
// instead explicitly set it to false. Regardless of whether the parent prefers striping or range
// partitioning, the output will be hash-partitioned.
QueryResults<TInputOutput> leftChildResults = LeftChild.Open(settings, false);
QueryResults<TInputOutput> rightChildResults = RightChild.Open(settings, false);
return new BinaryQueryOperatorResults(leftChildResults, rightChildResults, this, settings, false);
}
public override void WrapPartitionedStream<TLeftKey, TRightKey>(
PartitionedStream<TInputOutput, TLeftKey> leftPartitionedStream, PartitionedStream<TInputOutput, TRightKey> rightPartitionedStream,
IPartitionedStreamRecipient<TInputOutput> outputRecipient, bool preferStriping, QuerySettings settings)
{
Debug.Assert(leftPartitionedStream.PartitionCount == rightPartitionedStream.PartitionCount);
if (OutputOrdered)
{
WrapPartitionedStreamHelper<TLeftKey, TRightKey>(
ExchangeUtilities.HashRepartitionOrdered<TInputOutput, NoKeyMemoizationRequired, TLeftKey>(
leftPartitionedStream, null, null, _comparer, settings.CancellationState.MergedCancellationToken),
rightPartitionedStream, outputRecipient, settings.CancellationState.MergedCancellationToken);
}
else
{
WrapPartitionedStreamHelper<int, TRightKey>(
ExchangeUtilities.HashRepartition<TInputOutput, NoKeyMemoizationRequired, TLeftKey>(
leftPartitionedStream, null, null, _comparer, settings.CancellationState.MergedCancellationToken),
rightPartitionedStream, outputRecipient, settings.CancellationState.MergedCancellationToken);
}
}
//---------------------------------------------------------------------------------------
// This is a helper method. WrapPartitionedStream decides what type TLeftKey is going
// to be, and then call this method with that key as a generic parameter.
//
private void WrapPartitionedStreamHelper<TLeftKey, TRightKey>(
PartitionedStream<Pair<TInputOutput, NoKeyMemoizationRequired>, TLeftKey> leftHashStream, PartitionedStream<TInputOutput, TRightKey> rightPartitionedStream,
IPartitionedStreamRecipient<TInputOutput> outputRecipient, CancellationToken cancellationToken)
{
int partitionCount = leftHashStream.PartitionCount;
PartitionedStream<Pair<TInputOutput, NoKeyMemoizationRequired>, int> rightHashStream =
ExchangeUtilities.HashRepartition<TInputOutput, NoKeyMemoizationRequired, TRightKey>(
rightPartitionedStream, null, null, _comparer, cancellationToken);
PartitionedStream<TInputOutput, TLeftKey> outputStream =
new PartitionedStream<TInputOutput, TLeftKey>(partitionCount, leftHashStream.KeyComparer, OrdinalIndexState.Shuffled);
for (int i = 0; i < partitionCount; i++)
{
if (OutputOrdered)
{
outputStream[i] = new OrderedIntersectQueryOperatorEnumerator<TLeftKey>(
leftHashStream[i], rightHashStream[i], _comparer, leftHashStream.KeyComparer, cancellationToken);
}
else
{
outputStream[i] = (QueryOperatorEnumerator<TInputOutput, TLeftKey>)(object)
new IntersectQueryOperatorEnumerator<TLeftKey>(leftHashStream[i], rightHashStream[i], _comparer, cancellationToken);
}
}
outputRecipient.Receive(outputStream);
}
//---------------------------------------------------------------------------------------
// Whether this operator performs a premature merge that would not be performed in
// a similar sequential operation (i.e., in LINQ to Objects).
//
internal override bool LimitsParallelism
{
get { return false; }
}
//---------------------------------------------------------------------------------------
// This enumerator performs the intersection operation incrementally. It does this by
// maintaining a history -- in the form of a set -- of all data already seen. It then
// only returns elements that are seen twice (returning each one only once).
//
class IntersectQueryOperatorEnumerator<TLeftKey> : QueryOperatorEnumerator<TInputOutput, int>
{
private QueryOperatorEnumerator<Pair<TInputOutput, NoKeyMemoizationRequired>, TLeftKey> _leftSource; // Left data source.
private QueryOperatorEnumerator<Pair<TInputOutput, NoKeyMemoizationRequired>, int> _rightSource; // Right data source.
private IEqualityComparer<TInputOutput> _comparer; // Comparer to use for equality/hash-coding.
private Set<TInputOutput> _hashLookup; // The hash lookup, used to produce the intersection.
private CancellationToken _cancellationToken;
private Shared<int> _outputLoopCount;
//---------------------------------------------------------------------------------------
// Instantiates a new intersection operator.
//
internal IntersectQueryOperatorEnumerator(
QueryOperatorEnumerator<Pair<TInputOutput, NoKeyMemoizationRequired>, TLeftKey> leftSource,
QueryOperatorEnumerator<Pair<TInputOutput, NoKeyMemoizationRequired>, int> rightSource,
IEqualityComparer<TInputOutput> comparer, CancellationToken cancellationToken)
{
Debug.Assert(leftSource != null);
Debug.Assert(rightSource != null);
_leftSource = leftSource;
_rightSource = rightSource;
_comparer = comparer;
_cancellationToken = cancellationToken;
}
//---------------------------------------------------------------------------------------
// Walks the two data sources, left and then right, to produce the intersection.
//
internal override bool MoveNext(ref TInputOutput currentElement, ref int currentKey)
{
Debug.Assert(_leftSource != null);
Debug.Assert(_rightSource != null);
// Build the set out of the right data source, if we haven't already.
if (_hashLookup == null)
{
_outputLoopCount = new Shared<int>(0);
_hashLookup = new Set<TInputOutput>(_comparer);
Pair<TInputOutput, NoKeyMemoizationRequired> rightElement = default(Pair<TInputOutput, NoKeyMemoizationRequired>);
int rightKeyUnused = default(int);
int i = 0;
while (_rightSource.MoveNext(ref rightElement, ref rightKeyUnused))
{
if ((i++ & CancellationState.POLL_INTERVAL) == 0)
CancellationState.ThrowIfCanceled(_cancellationToken);
_hashLookup.Add(rightElement.First);
}
}
// Now iterate over the left data source, looking for matches.
Pair<TInputOutput, NoKeyMemoizationRequired> leftElement = default(Pair<TInputOutput, NoKeyMemoizationRequired>);
TLeftKey keyUnused = default(TLeftKey);
while (_leftSource.MoveNext(ref leftElement, ref keyUnused))
{
if ((_outputLoopCount.Value++ & CancellationState.POLL_INTERVAL) == 0)
CancellationState.ThrowIfCanceled(_cancellationToken);
// If we found the element in our set, and if we haven't returned it yet,
// we can yield it to the caller. We also mark it so we know we've returned
// it once already and never will again.
if (_hashLookup.Remove(leftElement.First))
{
currentElement = leftElement.First;
#if DEBUG
currentKey = unchecked((int)0xdeadbeef);
#endif
return true;
}
}
return false;
}
protected override void Dispose(bool disposing)
{
Debug.Assert(_leftSource != null && _rightSource != null);
_leftSource.Dispose();
_rightSource.Dispose();
}
}
//---------------------------------------------------------------------------------------
// Returns an enumerable that represents the query executing sequentially.
//
internal override IEnumerable<TInputOutput> AsSequentialQuery(CancellationToken token)
{
IEnumerable<TInputOutput> wrappedLeftChild = CancellableEnumerable.Wrap(LeftChild.AsSequentialQuery(token), token);
IEnumerable<TInputOutput> wrappedRightChild = CancellableEnumerable.Wrap(RightChild.AsSequentialQuery(token), token);
return wrappedLeftChild.Intersect(wrappedRightChild, _comparer);
}
class OrderedIntersectQueryOperatorEnumerator<TLeftKey> : QueryOperatorEnumerator<TInputOutput, TLeftKey>
{
private QueryOperatorEnumerator<Pair<TInputOutput, NoKeyMemoizationRequired>, TLeftKey> _leftSource; // Left data source.
private QueryOperatorEnumerator<Pair<TInputOutput, NoKeyMemoizationRequired>, int> _rightSource; // Right data source.
private IEqualityComparer<Wrapper<TInputOutput>> _comparer; // Comparer to use for equality/hash-coding.
private IComparer<TLeftKey> _leftKeyComparer; // Comparer to use to determine ordering of order keys.
private Dictionary<Wrapper<TInputOutput>, Pair<TInputOutput, TLeftKey>> _hashLookup; // The hash lookup, used to produce the intersection.
private CancellationToken _cancellationToken;
//---------------------------------------------------------------------------------------
// Instantiates a new intersection operator.
//
internal OrderedIntersectQueryOperatorEnumerator(
QueryOperatorEnumerator<Pair<TInputOutput, NoKeyMemoizationRequired>, TLeftKey> leftSource,
QueryOperatorEnumerator<Pair<TInputOutput, NoKeyMemoizationRequired>, int> rightSource,
IEqualityComparer<TInputOutput> comparer, IComparer<TLeftKey> leftKeyComparer,
CancellationToken cancellationToken)
{
Debug.Assert(leftSource != null);
Debug.Assert(rightSource != null);
_leftSource = leftSource;
_rightSource = rightSource;
_comparer = new WrapperEqualityComparer<TInputOutput>(comparer);
_leftKeyComparer = leftKeyComparer;
_cancellationToken = cancellationToken;
}
//---------------------------------------------------------------------------------------
// Walks the two data sources, left and then right, to produce the intersection.
//
internal override bool MoveNext(ref TInputOutput currentElement, ref TLeftKey currentKey)
{
Debug.Assert(_leftSource != null);
Debug.Assert(_rightSource != null);
// Build the set out of the left data source, if we haven't already.
int i = 0;
if (_hashLookup == null)
{
_hashLookup = new Dictionary<Wrapper<TInputOutput>, Pair<TInputOutput, TLeftKey>>(_comparer);
Pair<TInputOutput, NoKeyMemoizationRequired> leftElement = default(Pair<TInputOutput, NoKeyMemoizationRequired>);
TLeftKey leftKey = default(TLeftKey);
while (_leftSource.MoveNext(ref leftElement, ref leftKey))
{
if ((i++ & CancellationState.POLL_INTERVAL) == 0)
CancellationState.ThrowIfCanceled(_cancellationToken);
// For each element, we track the smallest order key for that element that we saw so far
Pair<TInputOutput, TLeftKey> oldEntry;
Wrapper<TInputOutput> wrappedLeftElem = new Wrapper<TInputOutput>(leftElement.First);
// If this is the first occurrence of this element, or the order key is lower than all keys we saw previously,
// update the order key for this element.
if (!_hashLookup.TryGetValue(wrappedLeftElem, out oldEntry) || _leftKeyComparer.Compare(leftKey, oldEntry.Second) < 0)
{
// For each "elem" value, we store the smallest key, and the element value that had that key.
// Note that even though two element values are "equal" according to the EqualityComparer,
// we still cannot choose arbitrarily which of the two to yield.
_hashLookup[wrappedLeftElem] = new Pair<TInputOutput, TLeftKey>(leftElement.First, leftKey);
}
}
}
// Now iterate over the right data source, looking for matches.
Pair<TInputOutput, NoKeyMemoizationRequired> rightElement = default(Pair<TInputOutput, NoKeyMemoizationRequired>);
int rightKeyUnused = default(int);
while (_rightSource.MoveNext(ref rightElement, ref rightKeyUnused))
{
if ((i++ & CancellationState.POLL_INTERVAL) == 0)
CancellationState.ThrowIfCanceled(_cancellationToken);
// If we found the element in our set, and if we haven't returned it yet,
// we can yield it to the caller. We also mark it so we know we've returned
// it once already and never will again.
Pair<TInputOutput, TLeftKey> entry;
Wrapper<TInputOutput> wrappedRightElem = new Wrapper<TInputOutput>(rightElement.First);
if (_hashLookup.TryGetValue(wrappedRightElem, out entry))
{
currentElement = entry.First;
currentKey = entry.Second;
_hashLookup.Remove(new Wrapper<TInputOutput>(entry.First));
return true;
}
}
return false;
}
protected override void Dispose(bool disposing)
{
Debug.Assert(_leftSource != null && _rightSource != null);
_leftSource.Dispose();
_rightSource.Dispose();
}
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.CodeGeneration;
using Microsoft.CodeAnalysis.Editing;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Shared.Utilities;
using Microsoft.CodeAnalysis.Simplification;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.ImplementInterface
{
internal abstract partial class AbstractImplementInterfaceService
{
internal partial class ImplementInterfaceCodeAction : CodeAction
{
protected readonly bool Explicitly;
protected readonly bool Abstractly;
protected readonly ISymbol ThroughMember;
protected readonly Document Document;
protected readonly State State;
protected readonly AbstractImplementInterfaceService Service;
private readonly string _equivalenceKey;
internal ImplementInterfaceCodeAction(
AbstractImplementInterfaceService service,
Document document,
State state,
bool explicitly,
bool abstractly,
ISymbol throughMember)
{
this.Service = service;
this.Document = document;
this.State = state;
this.Abstractly = abstractly;
this.Explicitly = explicitly;
this.ThroughMember = throughMember;
_equivalenceKey = ComputeEquivalenceKey(state, explicitly, abstractly, throughMember, this.GetType().FullName);
}
public static ImplementInterfaceCodeAction CreateImplementAbstractlyCodeAction(
AbstractImplementInterfaceService service,
Document document,
State state)
{
return new ImplementInterfaceCodeAction(service, document, state, explicitly: false, abstractly: true, throughMember: null);
}
public static ImplementInterfaceCodeAction CreateImplementCodeAction(
AbstractImplementInterfaceService service,
Document document,
State state)
{
return new ImplementInterfaceCodeAction(service, document, state, explicitly: false, abstractly: false, throughMember: null);
}
public static ImplementInterfaceCodeAction CreateImplementExplicitlyCodeAction(
AbstractImplementInterfaceService service,
Document document,
State state)
{
return new ImplementInterfaceCodeAction(service, document, state, explicitly: true, abstractly: false, throughMember: null);
}
public static ImplementInterfaceCodeAction CreateImplementThroughMemberCodeAction(
AbstractImplementInterfaceService service,
Document document,
State state,
ISymbol throughMember)
{
return new ImplementInterfaceCodeAction(service, document, state, explicitly: false, abstractly: false, throughMember: throughMember);
}
public override string Title
{
get
{
if (Explicitly)
{
return FeaturesResources.ImplementInterfaceExplicitly;
}
else if (Abstractly)
{
return FeaturesResources.ImplementInterfaceAbstractly;
}
else if (ThroughMember != null)
{
return string.Format(FeaturesResources.ImplementInterfaceThrough, GetDescription(ThroughMember));
}
else
{
return FeaturesResources.ImplementInterface;
}
}
}
private static string ComputeEquivalenceKey(
State state,
bool explicitly,
bool abstractly,
ISymbol throughMember,
string codeActionTypeName)
{
var interfaceType = state.InterfaceTypes.First();
var typeName = interfaceType.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat);
var assemblyName = interfaceType.ContainingAssembly.Name;
return GetCodeActionEquivalenceKey(assemblyName, typeName, explicitly, abstractly, throughMember, codeActionTypeName);
}
// internal for testing purposes.
internal static string GetCodeActionEquivalenceKey(
string interfaceTypeAssemblyName,
string interfaceTypeFullyQualifiedName,
bool explicitly,
bool abstractly,
ISymbol throughMember,
string codeActionTypeName)
{
if (throughMember != null)
{
return null;
}
return explicitly.ToString() + ";" +
abstractly.ToString() + ";" +
interfaceTypeAssemblyName + ";" +
interfaceTypeFullyQualifiedName + ";" +
codeActionTypeName;
}
public override string EquivalenceKey
{
get
{
return _equivalenceKey;
}
}
private static string GetDescription(ISymbol throughMember)
{
return throughMember.TypeSwitch(
(IFieldSymbol field) => field.Name,
(IPropertySymbol property) => property.Name,
_ => Contract.FailWithReturn<string>());
}
protected override Task<Document> GetChangedDocumentAsync(CancellationToken cancellationToken)
{
return GetUpdatedDocumentAsync(cancellationToken);
}
public Task<Document> GetUpdatedDocumentAsync(CancellationToken cancellationToken)
{
var unimplementedMembers = Explicitly ? State.UnimplementedExplicitMembers : State.UnimplementedMembers;
return GetUpdatedDocumentAsync(Document, unimplementedMembers, State.ClassOrStructType, State.ClassOrStructDecl, cancellationToken);
}
public virtual async Task<Document> GetUpdatedDocumentAsync(
Document document,
IList<Tuple<INamedTypeSymbol, IList<ISymbol>>> unimplementedMembers,
INamedTypeSymbol classOrStructType,
SyntaxNode classOrStructDecl,
CancellationToken cancellationToken)
{
var result = document;
var compilation = await result.Project.GetCompilationAsync(cancellationToken).ConfigureAwait(false);
var memberDefinitions = GenerateMembers(
compilation,
unimplementedMembers,
cancellationToken);
result = await CodeGenerator.AddMemberDeclarationsAsync(
result.Project.Solution, classOrStructType, memberDefinitions,
new CodeGenerationOptions(contextLocation: classOrStructDecl.GetLocation()),
cancellationToken).ConfigureAwait(false);
return result;
}
private IList<ISymbol> GenerateMembers(
Compilation compilation,
IList<Tuple<INamedTypeSymbol, IList<ISymbol>>> unimplementedMembers,
CancellationToken cancellationToken)
{
// As we go along generating members we may end up with conflicts. For example, say
// you have "interface IFoo { string Bar { get; } }" and "interface IQuux { int Bar
// { get; } }" and we need to implement both 'Bar' methods. The second will have to
// be explicitly implemented as it will conflict with the first. So we need to keep
// track of what we've actually implemented so that we can check further interface
// members against both the actual type and that list.
//
// Similarly, if you have two interfaces with the same member, then we don't want to
// implement that member twice.
//
// Note: if we implement a method explicitly then we do *not* add it to this list.
// That's because later members won't conflict with it even if they have the same
// signature otherwise. i.e. if we chose to implement IFoo.Bar explicitly, then we
// could implement IQuux.Bar implicitly (and vice versa).
var implementedVisibleMembers = new List<ISymbol>();
var implementedMembers = new List<ISymbol>();
foreach (var tuple in unimplementedMembers)
{
var interfaceType = tuple.Item1;
var unimplementedInterfaceMembers = tuple.Item2;
foreach (var unimplementedInterfaceMember in unimplementedInterfaceMembers)
{
var member = GenerateMember(compilation, unimplementedInterfaceMember, implementedVisibleMembers, cancellationToken);
if (member != null)
{
implementedMembers.Add(member);
if (!(member.ExplicitInterfaceImplementations().Any() && Service.HasHiddenExplicitImplementation))
{
implementedVisibleMembers.Add(member);
}
}
}
}
return implementedMembers;
}
private bool IsReservedName(string name)
{
return
IdentifiersMatch(State.ClassOrStructType.Name, name) ||
State.ClassOrStructType.TypeParameters.Any(t => IdentifiersMatch(t.Name, name));
}
private string DetermineMemberName(ISymbol member, List<ISymbol> implementedVisibleMembers)
{
if (HasConflictingMember(member, implementedVisibleMembers))
{
var memberNames = State.ClassOrStructType.GetAccessibleMembersInThisAndBaseTypes<ISymbol>(State.ClassOrStructType).Select(m => m.Name);
return NameGenerator.GenerateUniqueName(
string.Format("{0}_{1}", member.ContainingType.Name, member.Name),
n => !memberNames.Contains(n) &&
!implementedVisibleMembers.Any(m => IdentifiersMatch(m.Name, n)) &&
!IsReservedName(n));
}
return member.Name;
}
private ISymbol GenerateMember(
Compilation compilation,
ISymbol member,
List<ISymbol> implementedVisibleMembers,
CancellationToken cancellationToken)
{
// First check if we already generate a member that matches the member we want to
// generate. This can happen in C# when you have interfaces that have the same
// method, and you are implementing implicitly. For example:
//
// interface IFoo { void Foo(); }
//
// interface IBar : IFoo { new void Foo(); }
//
// class C : IBar
//
// In this case we only want to generate 'Foo' once.
if (HasMatchingMember(implementedVisibleMembers, member))
{
return null;
}
var memberName = DetermineMemberName(member, implementedVisibleMembers);
// See if we need to generate an invisible member. If we do, then reset the name
// back to what then member wants it to be.
var generateInvisibleMember = GenerateInvisibleMember(member, memberName);
memberName = generateInvisibleMember ? member.Name : memberName;
var generateAbstractly = !generateInvisibleMember && Abstractly;
// Check if we need to add 'new' to the signature we're adding. We only need to do this
// if we're not generating something explicit and we have a naming conflict with
// something in our base class hierarchy.
var addNew = !generateInvisibleMember && HasNameConflict(member, memberName, State.ClassOrStructType.GetBaseTypes());
// Check if we need to add 'unsafe' to the signature we're generating.
var syntaxFacts = Document.GetLanguageService<ISyntaxFactsService>();
var addUnsafe = member.IsUnsafe() && !syntaxFacts.IsUnsafeContext(State.Location);
return GenerateMember(compilation, member, memberName, generateInvisibleMember, generateAbstractly, addNew, addUnsafe, cancellationToken);
}
private bool GenerateInvisibleMember(ISymbol member, string memberName)
{
if (Service.HasHiddenExplicitImplementation)
{
// User asked for an explicit (i.e. invisible) member.
if (Explicitly)
{
return true;
}
// Have to create an invisible member if we have constraints we can't express
// with a visible member.
if (HasUnexpressibleConstraint(member))
{
return true;
}
// If we had a conflict with a member of the same name, then we have to generate
// as an invisible member.
if (member.Name != memberName)
{
return true;
}
}
// Can't generate an invisible member if the language doesn't support it.
return false;
}
private bool HasUnexpressibleConstraint(ISymbol member)
{
// interface IFoo<T> { void Bar<U>() where U : T; }
//
// class A : IFoo<int> { }
//
// In this case we cannot generate an implement method for Bar. That's because we'd
// need to say "where U : int" and that's disallowed by the language. So we must
// generate something explicit here.
if (member.Kind != SymbolKind.Method)
{
return false;
}
var method = member as IMethodSymbol;
return method.TypeParameters.Any(IsUnexpressibleTypeParameter);
}
private static bool IsUnexpressibleTypeParameter(ITypeParameterSymbol typeParameter)
{
var condition1 = typeParameter.ConstraintTypes.Count(t => t.TypeKind == TypeKind.Class) >= 2;
var condition2 = typeParameter.ConstraintTypes.Any(ts => ts.IsUnexpressibleTypeParameterConstraint());
var condition3 = typeParameter.HasReferenceTypeConstraint && typeParameter.ConstraintTypes.Any(ts => ts.IsReferenceType && ts.SpecialType != SpecialType.System_Object);
return condition1 || condition2 || condition3;
}
private ISymbol GenerateMember(
Compilation compilation,
ISymbol member,
string memberName,
bool generateInvisibly,
bool generateAbstractly,
bool addNew,
bool addUnsafe,
CancellationToken cancellationToken)
{
var factory = this.Document.GetLanguageService<SyntaxGenerator>();
var modifiers = new DeclarationModifiers(isAbstract: generateAbstractly, isNew: addNew, isUnsafe: addUnsafe);
var useExplicitInterfaceSymbol = generateInvisibly || !Service.CanImplementImplicitly;
var accessibility = member.Name == memberName ? Accessibility.Public : Accessibility.Private;
if (member.Kind == SymbolKind.Method)
{
var method = (IMethodSymbol)member;
return GenerateMethod(compilation, method, accessibility, modifiers, generateAbstractly, useExplicitInterfaceSymbol, memberName, cancellationToken);
}
else if (member.Kind == SymbolKind.Property)
{
var property = (IPropertySymbol)member;
return GenerateProperty(compilation, property, accessibility, modifiers, generateAbstractly, useExplicitInterfaceSymbol, memberName, cancellationToken);
}
else if (member.Kind == SymbolKind.Event)
{
var @event = (IEventSymbol)member;
var accessor = CodeGenerationSymbolFactory.CreateAccessorSymbol(
attributes: null,
accessibility: Accessibility.NotApplicable,
statements: factory.CreateThrowNotImplementedStatementBlock(compilation));
return CodeGenerationSymbolFactory.CreateEventSymbol(
@event,
accessibility: accessibility,
modifiers: modifiers,
explicitInterfaceSymbol: useExplicitInterfaceSymbol ? @event : null,
name: memberName,
addMethod: generateInvisibly ? accessor : null,
removeMethod: generateInvisibly ? accessor : null);
}
return null;
}
private SyntaxNode CreateThroughExpression(SyntaxGenerator factory)
{
var through = ThroughMember.IsStatic
? GenerateName(factory, State.ClassOrStructType.IsGenericType)
: factory.ThisExpression();
through = factory.MemberAccessExpression(
through, factory.IdentifierName(ThroughMember.Name));
var throughMemberType = ThroughMember.GetMemberType();
if ((State.InterfaceTypes != null) && (throughMemberType != null))
{
// In the case of 'implement interface through field / property' , we need to know what
// interface we are implementing so that we can insert casts to this interface on every
// usage of the field in the generated code. Without these casts we would end up generating
// code that fails compilation in certain situations.
//
// For example consider the following code.
// class C : IReadOnlyList<int> { int[] field; }
// When applying the 'implement interface through field' code fix in the above example,
// we need to generate the following code to implement the Count property on IReadOnlyList<int>
// class C : IReadOnlyList<int> { int[] field; int Count { get { ((IReadOnlyList<int>)field).Count; } ...}
// as opposed to the following code which will fail to compile (because the array field
// doesn't have a property named .Count) -
// class C : IReadOnlyList<int> { int[] field; int Count { get { field.Count; } ...}
//
// The 'InterfaceTypes' property on the state object always contains only one item
// in the case of C# i.e. it will contain exactly the interface we are trying to implement.
// This is also the case most of the time in the case of VB, except in certain error conditions
// (recursive / circular cases) where the span of the squiggle for the corresponding
// diagnostic (BC30149) changes and 'InterfaceTypes' ends up including all interfaces
// in the Implements clause. For the purposes of inserting the above cast, we ignore the
// uncommon case and optimize for the common one - in other words, we only apply the cast
// in cases where we can unambiguously figure out which interface we are trying to implement.
var interfaceBeingImplemented = State.InterfaceTypes.SingleOrDefault();
if ((interfaceBeingImplemented != null) && (!throughMemberType.Equals(interfaceBeingImplemented)))
{
through = factory.CastExpression(interfaceBeingImplemented,
through.WithAdditionalAnnotations(Simplifier.Annotation));
var facts = this.Document.GetLanguageService<ISyntaxFactsService>();
through = facts.Parenthesize(through);
}
}
return through.WithAdditionalAnnotations(Simplifier.Annotation);
}
private SyntaxNode GenerateName(SyntaxGenerator factory, bool isGenericType)
{
return isGenericType
? factory.GenericName(State.ClassOrStructType.Name, State.ClassOrStructType.TypeArguments)
: factory.IdentifierName(State.ClassOrStructType.Name);
}
private bool HasNameConflict(
ISymbol member,
string memberName,
IEnumerable<INamedTypeSymbol> baseTypes)
{
// There's a naming conflict if any member in the base types chain is accessible to
// us, has our name. Note: a simple name won't conflict with a generic name (and
// vice versa). A method only conflicts with another method if they have the same
// parameter signature (return type is irrelevant).
return
baseTypes.Any(ts => ts.GetMembers(memberName)
.Where(m => m.IsAccessibleWithin(State.ClassOrStructType))
.Any(m => HasNameConflict(member, memberName, m)));
}
private static bool HasNameConflict(
ISymbol member,
string memberName,
ISymbol baseMember)
{
Contract.Requires(memberName == baseMember.Name);
if (member.Kind == SymbolKind.Method && baseMember.Kind == SymbolKind.Method)
{
// A method only conflicts with another method if they have the same parameter
// signature (return type is irrelevant).
var method1 = (IMethodSymbol)member;
var method2 = (IMethodSymbol)baseMember;
if (method1.MethodKind == MethodKind.Ordinary &&
method2.MethodKind == MethodKind.Ordinary &&
method1.TypeParameters.Length == method2.TypeParameters.Length)
{
return method1.Parameters.Select(p => p.Type)
.SequenceEqual(method2.Parameters.Select(p => p.Type));
}
}
// Any non method members with the same name simple name conflict.
return true;
}
private bool IdentifiersMatch(string identifier1, string identifier2)
{
return this.IsCaseSensitive
? identifier1 == identifier2
: StringComparer.OrdinalIgnoreCase.Equals(identifier1, identifier2);
}
private bool IsCaseSensitive
{
get
{
return this.Document.GetLanguageService<ISyntaxFactsService>().IsCaseSensitive;
}
}
private bool HasMatchingMember(List<ISymbol> implementedVisibleMembers, ISymbol member)
{
// If this is a language that doesn't support implicit implementation then no
// implemented members will ever match. For example, if you have:
//
// Interface IFoo : sub Foo() : End Interface
//
// Interface IBar : Inherits IFoo : Shadows Sub Foo() : End Interface
//
// Class C : Implements IBar
//
// We'll first end up generating:
//
// Public Sub Foo() Implements IFoo.Foo
//
// However, that same method won't be viable for IBar.Foo (unlike C#) because it
// explicitly specifies its interface).
if (!Service.CanImplementImplicitly)
{
return false;
}
return implementedVisibleMembers.Any(m => MembersMatch(m, member));
}
private bool MembersMatch(ISymbol member1, ISymbol member2)
{
if (member1.Kind != member2.Kind)
{
return false;
}
if (member1.DeclaredAccessibility != member2.DeclaredAccessibility ||
member1.IsStatic != member2.IsStatic)
{
return false;
}
if (member1.ExplicitInterfaceImplementations().Any() || member2.ExplicitInterfaceImplementations().Any())
{
return false;
}
return SignatureComparer.Instance.HaveSameSignatureAndConstraintsAndReturnTypeAndAccessors(
member1, member2, this.IsCaseSensitive);
}
}
}
}
| |
using System;
using System.IO;
using Org.BouncyCastle.Apache.Bzip2;
using Org.BouncyCastle.Utilities.Zlib;
namespace Org.BouncyCastle.Bcpg.OpenPgp
{
/// <remarks>Class for producing compressed data packets.</remarks>
public class PgpCompressedDataGenerator : IStreamGenerator
{
private readonly CompressionAlgorithmTag _algorithm;
private readonly int _compression;
private Stream _dOut;
private BcpgOutputStream _pkOut;
public PgpCompressedDataGenerator(CompressionAlgorithmTag algorithm)
: this(algorithm, JZlib.Z_DEFAULT_COMPRESSION)
{
}
public PgpCompressedDataGenerator(CompressionAlgorithmTag algorithm, int compression)
{
switch (algorithm)
{
case CompressionAlgorithmTag.Uncompressed:
case CompressionAlgorithmTag.Zip:
case CompressionAlgorithmTag.ZLib:
case CompressionAlgorithmTag.BZip2:
break;
default:
throw new ArgumentException(@"unknown compression algorithm", "algorithm");
}
if (compression != JZlib.Z_DEFAULT_COMPRESSION)
{
if ((compression < JZlib.Z_NO_COMPRESSION) || (compression > JZlib.Z_BEST_COMPRESSION))
{
throw new ArgumentException("unknown compression level: " + compression);
}
}
_algorithm = algorithm;
_compression = compression;
}
/// <summary>
/// <p>
/// Return an output stream which will save the data being written to
/// the compressed object.
/// </p>
/// <p>
/// The stream created can be closed off by either calling Close()
/// on the stream or Close() on the generator. Closing the returned
/// stream does not close off the Stream parameter <c>outStr</c>.
/// </p>
/// </summary>
/// <param name="outStr">Stream to be used for output.</param>
/// <returns>A Stream for output of the compressed data.</returns>
/// <exception cref="ArgumentNullException"></exception>
/// <exception cref="InvalidOperationException"></exception>
/// <exception cref="IOException"></exception>
public Stream Open(Stream outStr)
{
if (_dOut != null)
throw new InvalidOperationException("generator already in open state");
if (outStr == null)
throw new ArgumentNullException("outStr");
this._pkOut = new BcpgOutputStream(outStr, PacketTag.CompressedData);
this.DoOpen();
return new WrappedGeneratorStream(this, _dOut);
}
/// <summary>
/// <p>
/// Return an output stream which will compress the data as it is written to it.
/// The stream will be written out in chunks according to the size of the passed in buffer.
/// </p>
/// <p>
/// The stream created can be closed off by either calling Close()
/// on the stream or Close() on the generator. Closing the returned
/// stream does not close off the Stream parameter <c>outStr</c>.
/// </p>
/// <p>
/// <b>Note</b>: if the buffer is not a power of 2 in length only the largest power of 2
/// bytes worth of the buffer will be used.
/// </p>
/// <p>
/// <b>Note</b>: using this may break compatibility with RFC 1991 compliant tools.
/// Only recent OpenPGP implementations are capable of accepting these streams.
/// </p>
/// </summary>
/// <param name="outStr">Stream to be used for output.</param>
/// <param name="buffer">The buffer to use.</param>
/// <returns>A Stream for output of the compressed data.</returns>
/// <exception cref="ArgumentNullException"></exception>
/// <exception cref="InvalidOperationException"></exception>
/// <exception cref="IOException"></exception>
/// <exception cref="PgpException"></exception>
public Stream Open(Stream outStr, byte[] buffer)
{
if (_dOut != null)
throw new InvalidOperationException("generator already in open state");
if (outStr == null)
throw new ArgumentNullException("outStr");
if (buffer == null)
throw new ArgumentNullException("buffer");
_pkOut = new BcpgOutputStream(outStr, PacketTag.CompressedData, buffer);
this.DoOpen();
return new WrappedGeneratorStream(this, _dOut);
}
private void DoOpen()
{
_pkOut.WriteByte((byte)_algorithm);
switch (_algorithm)
{
case CompressionAlgorithmTag.Uncompressed:
_dOut = _pkOut;
break;
case CompressionAlgorithmTag.Zip:
_dOut = new SafeZOutputStream(_pkOut, _compression, true);
break;
case CompressionAlgorithmTag.ZLib:
_dOut = new SafeZOutputStream(_pkOut, _compression, false);
break;
case CompressionAlgorithmTag.BZip2:
_dOut = new SafeCBZip2OutputStream(_pkOut);
break;
default:
// Constructor should guard against this possibility
throw new InvalidOperationException();
}
}
/// <summary>Close the compressed object.</summary>summary>
public void Close()
{
if (_dOut == null)
return;
if (_dOut != _pkOut)
{
_dOut.Flush();
#if !NETFX_CORE
_dOut.Close();
#endif
}
_dOut = null;
_pkOut.Finish();
_pkOut.Flush();
_pkOut = null;
}
private class SafeCBZip2OutputStream : CBZip2OutputStream
{
public SafeCBZip2OutputStream(Stream output)
: base(output)
{
}
#if !NETFX_CORE
public override void Close()
{
this.Finish();
}
#else
protected override void Dispose(bool disposing)
{
this.Finish();
base.Dispose(disposing);
}
#endif
}
private class SafeZOutputStream : ZOutputStream
{
public SafeZOutputStream(Stream output, int level, bool nowrap)
: base(output, level, nowrap)
{
}
#if !NETFX_CORE
public override void Close()
{
this.Finish();
this.End();
}
#endif
}
}
}
| |
// Code generated by a Template
using System;
using System.Linq.Expressions;
using DNX.Helpers.Maths;
using DNX.Helpers.Maths.BuiltInTypes;
using DNX.Helpers.Reflection;
namespace DNX.Helpers.Validation
{
/// <summary>
/// Guard Extensions.
/// </summary>
public static partial class Guard
{
/// <summary>
/// Ensures the expression evaluates to greater than the specified minimum
/// </summary>
/// <param name="exp">The exp.</param>
/// <param name="min">The minimum.</param>
public static void IsGreaterThan(Expression<Func<float>> exp, float min)
{
IsGreaterThan(exp, exp.Compile().Invoke(), min);
}
/// <summary>
/// Ensures the expression and corresponding value evaluates to greater than the specified minimum
/// </summary>
/// <param name="exp">The exp.</param>
/// <param name="val">The value.</param>
/// <param name="min">The minimum.</param>
/// <exception cref="System.ArgumentOutOfRangeException"></exception>
public static void IsGreaterThan(Expression<Func<float>> exp, float val, float min)
{
if (val > min)
{
return;
}
var memberName = ExpressionExtensions.GetMemberName(exp);
throw new ArgumentOutOfRangeException(
memberName,
val,
string.Format("{0} must be greater than {1}",
memberName,
min
)
);
}
/// <summary>
/// Ensures the expression evaluates to greater than or equal to the specified minimum
/// </summary>
/// <param name="exp">The exp.</param>
/// <param name="min">The minimum.</param>
public static void IsGreaterThanOrEqualTo(Expression<Func<float>> exp, float min)
{
IsGreaterThanOrEqualTo(exp, exp.Compile().Invoke(), min);
}
/// <summary>
/// Ensures the expression and corresponding value evaluates to greater than or equal to the specified minimum
/// </summary>
/// <param name="exp">The exp.</param>
/// <param name="val">The value.</param>
/// <param name="min">The minimum.</param>
/// <exception cref="System.ArgumentOutOfRangeException"></exception>
public static void IsGreaterThanOrEqualTo(Expression<Func<float>> exp, float val, float min)
{
if (val >= min)
{
return;
}
var memberName = ExpressionExtensions.GetMemberName(exp);
throw new ArgumentOutOfRangeException(
memberName,
val,
string.Format("{0} must be greater than or equal to {1}",
memberName,
min
)
);
}
/// <summary>
/// Ensures the expression evaluates to less than the specified minimum
/// </summary>
/// <param name="exp">The exp.</param>
/// <param name="max">The maximum.</param>
public static void IsLessThan(Expression<Func<float>> exp, float max)
{
IsLessThan(exp, exp.Compile().Invoke(), max);
}
/// <summary>
/// Ensures the expression and corresponding value evaluates to less than the specified minimum
/// </summary>
/// <param name="exp">The exp.</param>
/// <param name="val">The value.</param>
/// <param name="max">The minimum.</param>
/// <exception cref="System.ArgumentOutOfRangeException"></exception>
public static void IsLessThan(Expression<Func<float>> exp, float val, float max)
{
if (val < max)
{
return;
}
var memberName = ExpressionExtensions.GetMemberName(exp);
throw new ArgumentOutOfRangeException(
memberName,
val,
string.Format("{0} must be less than {1}",
memberName,
max
)
);
}
/// <summary>
/// Ensures the expression evaluates to less than or equal to the specified minimum
/// </summary>
/// <param name="exp">The exp.</param>
/// <param name="max">The maximum.</param>
public static void IsLessThanOrEqualTo(Expression<Func<float>> exp, float max)
{
IsLessThanOrEqualTo(exp, exp.Compile().Invoke(), max);
}
/// <summary>
/// Ensures the expression and corresponding value evaluates to less than or equal to the specified minimum
/// </summary>
/// <param name="exp">The exp.</param>
/// <param name="val">The value.</param>
/// <param name="max">The maximum.</param>
/// <exception cref="System.ArgumentOutOfRangeException"></exception>
public static void IsLessThanOrEqualTo(Expression<Func<float>> exp, float val, float max)
{
if (val <= max)
{
return;
}
var memberName = ExpressionExtensions.GetMemberName(exp);
throw new ArgumentOutOfRangeException(
memberName,
val,
string.Format("{0} must be less than or equal to {1}",
memberName,
max
)
);
}
/// <summary>
/// Ensures the expression evaluates to between the specified values
/// </summary>
/// <param name="exp">The linq expression of the argument to check</param>
/// <param name="min">minimum allowed value</param>
/// <param name="max">maximum allowed value</param>
public static void IsBetween(Expression<Func<float>> exp, float min, float max)
{
IsBetween(exp, min, max, IsBetweenBoundsType.Inclusive);
}
/// <summary>
/// Ensures the expression and corresponding value evaluates to between the specified values
/// </summary>
/// <param name="exp">The exp.</param>
/// <param name="min">The minimum.</param>
/// <param name="max">The maximum.</param>
/// <param name="boundsType">Type of the bounds.</param>
public static void IsBetween(Expression<Func<float>> exp, float min, float max, IsBetweenBoundsType boundsType)
{
IsBetween(exp, min, max, false, boundsType);
}
/// <summary>
/// Ensures the expression evaluates to between the specified values
/// </summary>
/// <param name="exp">The exp.</param>
/// <param name="bound1">The bound1.</param>
/// <param name="bound2">The bound2.</param>
/// <param name="allowEitherOrder">if set to <c>true</c> [allow either order].</param>
/// <param name="boundsType">Type of the bounds.</param>
public static void IsBetween(Expression<Func<float>> exp, float bound1, float bound2, bool allowEitherOrder, IsBetweenBoundsType boundsType)
{
IsBetween(exp, exp.Compile().Invoke(), bound1, bound2, allowEitherOrder, boundsType);
}
/// <summary>
/// Ensures the expression and corresponding value evaluates to between the specified values
/// </summary>
/// <param name="exp">The exp.</param>
/// <param name="val">The value.</param>
/// <param name="bound1">The bound1.</param>
/// <param name="bound2">The bound2.</param>
/// <param name="allowEitherOrder">if set to <c>true</c> [allow either order].</param>
/// <param name="boundsType">Type of the bounds.</param>
/// <exception cref="ArgumentOutOfRangeException"></exception>
/// <exception cref="System.ArgumentOutOfRangeException"></exception>
public static void IsBetween(Expression<Func<float>> exp, float val, float bound1, float bound2, bool allowEitherOrder, IsBetweenBoundsType boundsType)
{
if (val.IsBetween(bound1, bound2, allowEitherOrder, boundsType))
{
return;
}
var memberName = ExpressionExtensions.GetMemberName(exp);
throw new ArgumentOutOfRangeException(
memberName,
val,
string.Format("{0} must be {1}",
memberName,
string.Format(boundsType.GetLimitDescriptionFormat(),
MathsFloatExtensions.GetLowerBound(bound1, bound2, allowEitherOrder),
MathsFloatExtensions.GetUpperBound(bound1, bound2, allowEitherOrder)
)
)
);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using Scribble.CodeSnippets.Models;
namespace Scribble.CodeSnippets
{
public class DocumentFileProcessor
{
const string LineEnding = "\r\n";
readonly string docsFolder;
public DocumentFileProcessor(string docsFolder)
{
this.docsFolder = docsFolder;
}
public DocumentProcessResult Apply(ICollection<CodeSnippet> snippets)
{
var result = new DocumentProcessResult();
var inputFiles = new[] { "*.md", "*.mdown", "*.markdown" }.SelectMany(
extension => Directory.GetFiles(docsFolder, extension, SearchOption.AllDirectories))
.ToArray();
result.Count = inputFiles.Count();
foreach (var inputFile in inputFiles)
{
var fileResult = Apply(snippets, inputFile);
if (fileResult.RequiredSnippets.Any())
{
// give up if we can't continue
result.Include(fileResult.RequiredSnippets);
return result;
}
result.Include(fileResult.Snippets);
File.WriteAllText(inputFile, fileResult.Text);
}
return result;
}
public static FileProcessResult Apply(ICollection<CodeSnippet> snippets, string inputFile)
{
var result = new FileProcessResult();
var baselineText = File.ReadAllText(inputFile);
var missingKeys = CheckMissingKeys(snippets, baselineText);
if (missingKeys.Any())
{
foreach (var missingKey in missingKeys)
{
missingKey.File = inputFile;
}
result.RequiredSnippets = missingKeys;
result.Text = baselineText;
return result;
}
foreach (var snippet in snippets)
{
// TODO: this won't change the text
// if a snippet is unchanged
// so we need more context
var output = ProcessMatch(snippet.Key, snippet.Value, baselineText);
if (!string.Equals(output, baselineText))
{
// we may have added in a snippet
result.Snippets.Add(snippet);
}
baselineText = output;
}
result.Text = baselineText;
return result;
}
static CodeSnippetReference[] CheckMissingKeys(IEnumerable<CodeSnippet> snippets, string baselineText)
{
var foundKeys = snippets.Select(m => m.Key);
var matches = Regex.Matches(baselineText, @"<!--[\s]*import[\s]*(?<key>[\w-]*)[\s]*-->");
var expectedKeysGroups = matches.Cast<Match>().Select(m => m.Groups["key"]);
var expectedKeys = expectedKeysGroups.Select(k => {
var index = k.Index;
var lineCount = baselineText.Substring(0, index)
.Count(c => c == '\n') + 1;
return new CodeSnippetReference { LineNumber = lineCount, Key = k.Value };
});
return expectedKeys.Where(k => !foundKeys.Contains(k.Key)).ToArray();
}
static string ProcessMatch(string key, string value, string baseLineText)
{
var lookup = string.Format("<!-- import {0} -->", key);
var codeSnippet = FormatTextAsCodeSnippet(value, lookup);
var startIndex = 0;
var indexOf = IndexOfOrdinal(baseLineText, lookup, startIndex);
while (indexOf > -1)
{
var endOfLine = IndexOfOrdinal(baseLineText, LineEnding, indexOf + lookup.Length);
if (endOfLine > -1)
{
const string blankLine = LineEnding + LineEnding;
var endOfNextLine = IndexOfOrdinal(baseLineText, blankLine, endOfLine);
if (endOfNextLine > -1)
{
var start = endOfLine + 2;
var end = (endOfNextLine + 4) - start;
baseLineText = baseLineText.Remove(start, end);
}
else
{
if (endOfLine != baseLineText.Length)
{
endOfNextLine = baseLineText.Length;
baseLineText = baseLineText.Remove(endOfLine, endOfNextLine - endOfLine);
}
}
}
startIndex = indexOf + lookup.Length;
baseLineText = baseLineText.Remove(indexOf, lookup.Length)
.Insert(indexOf, codeSnippet);
indexOf = IndexOfOrdinal(baseLineText, lookup, startIndex);
}
return baseLineText;
}
static string FormatTextAsCodeSnippet(string value, string lookup)
{
var valueWithoutEndings = value.TrimEnd('\r', '\n');
var linesInFile = valueWithoutEndings
.Split(new[] { LineEnding }, StringSplitOptions.None)
.Select(l => l.Replace("\t", " "))
.ToArray();
var whiteSpaceStartValues = linesInFile.Select(SpacesAtStartOfString)
.Where(count => count > 0)
.ToArray();
var minWhiteSpace = whiteSpaceStartValues.Any()
? whiteSpaceStartValues.Min()
: 0;
var processedLines = string.Join(LineEnding,
linesInFile.Select(l => TrimWhiteSpace(l, minWhiteSpace, 4)));
return string.Format("{0}{2}{1}{2}", lookup, processedLines, LineEnding);
}
// as soon as we find a non-space character, bail out
static int SpacesAtStartOfString(string s)
{
if (s.Length == 0)
return -1;
for (var i = 0; i < s.Length; i++)
{
if (s[i] != ' ')
return i;
}
return s.Length;
}
static string TrimWhiteSpace(string input, int removeCount, int insertCount)
{
var temp = string.Copy(input);
if (removeCount > 0 && temp.Length >= removeCount)
{
temp = temp.Substring(removeCount);
}
var sb = new StringBuilder();
for (var i = 0; i < insertCount; i++)
{
sb.Append(' ');
}
sb.Append(temp);
return sb.ToString();
}
static int IndexOfOrdinal(string text, string value, int startIndex)
{
return text.IndexOf(value, startIndex, StringComparison.Ordinal);
}
}
}
| |
using System;
using System.IO;
using ATL.Logging;
using System.Collections.Generic;
using System.Text;
using Commons;
using static ATL.ChannelsArrangements;
namespace ATL.AudioData.IO
{
/// <summary>
/// Class for Windows Media Audio 7,8 and 9 files manipulation (extension : .WMA)
/// </summary>
class WMA : MetaDataIO, IAudioDataIO
{
private const string ZONE_CONTENT_DESCRIPTION = "contentDescription";
private const string ZONE_EXTENDED_CONTENT_DESCRIPTION = "extContentDescription";
private const string ZONE_EXTENDED_HEADER_METADATA = "extHeaderMeta";
private const string ZONE_EXTENDED_HEADER_METADATA_LIBRARY = "extHeaderMetaLibrary";
// Object IDs
private static readonly byte[] WMA_HEADER_ID = new byte[16] { 48, 38, 178, 117, 142, 102, 207, 17, 166, 217, 0, 170, 0, 98, 206, 108 };
private static readonly byte[] WMA_HEADER_EXTENSION_ID = new byte[16] { 0xB5, 0x03, 0xBF, 0x5F, 0x2E, 0xA9, 0xCF, 0x11, 0x8E, 0xE3, 0x00, 0xc0, 0x0c, 0x20, 0x53, 0x65 };
private static readonly byte[] WMA_METADATA_OBJECT_ID = new byte[16] { 0xEA, 0xCB, 0xF8, 0xC5, 0xAF, 0x5B, 0x77, 0x48, 0x84, 0x67, 0xAA, 0x8C, 0x44, 0xFA, 0x4C, 0xCA };
private static readonly byte[] WMA_METADATA_LIBRARY_OBJECT_ID = new byte[16] { 0x94, 0x1C, 0x23, 0x44, 0x98, 0x94, 0xD1, 0x49, 0xA1, 0x41, 0x1D, 0x13, 0x4E, 0x45, 0x70, 0x54 };
private static readonly byte[] WMA_FILE_PROPERTIES_ID = new byte[16] { 161, 220, 171, 140, 71, 169, 207, 17, 142, 228, 0, 192, 12, 32, 83, 101 };
private static readonly byte[] WMA_STREAM_PROPERTIES_ID = new byte[16] { 145, 7, 220, 183, 183, 169, 207, 17, 142, 230, 0, 192, 12, 32, 83, 101 };
private static readonly byte[] WMA_CONTENT_DESCRIPTION_ID = new byte[16] { 51, 38, 178, 117, 142, 102, 207, 17, 166, 217, 0, 170, 0, 98, 206, 108 };
private static readonly byte[] WMA_EXTENDED_CONTENT_DESCRIPTION_ID = new byte[16] { 64, 164, 208, 210, 7, 227, 210, 17, 151, 240, 0, 160, 201, 94, 168, 80 };
private static readonly byte[] WMA_LANGUAGE_LIST_OBJECT_ID = new byte[16] { 0xA9, 0x46, 0x43, 0x7C, 0xE0, 0xEF, 0xFC, 0x4B, 0xB2, 0x29, 0x39, 0x3E, 0xDE, 0x41, 0x5C, 0x85 };
// Format IDs
private const int WMA_ID = 0x161;
private const int WMA_PRO_ID = 0x162;
private const int WMA_LOSSLESS_ID = 0x163;
private const int WMA_GSM_CBR_ID = 0x7A21;
private const int WMA_GSM_VBR_ID = 0x7A22;
// Max. number of characters in tag field
private const byte WMA_MAX_STRING_SIZE = 250;
// File data - for internal use
private class FileData
{
public long HeaderSize;
public int FormatTag; // Format ID tag
public ushort Channels; // Number of channels
public int SampleRate; // Sample rate (hz)
public uint ObjectCount; // Number of high-level objects
public long ObjectListOffset; // Offset of the high-level objects list
public FileData() { Reset(); }
public void Reset()
{
HeaderSize = 0;
FormatTag = 0;
Channels = 0;
SampleRate = 0;
ObjectCount = 0;
ObjectListOffset = -1;
}
}
private FileData fileData;
private ChannelsArrangement channelsArrangement;
private int sampleRate;
private bool isVBR;
private bool isLossless;
private double bitrate;
private double duration;
private static IDictionary<string, byte> frameMapping; // Mapping between WMA frame codes and ATL frame codes
private static IList<string> embeddedFields; // Field that are embedded in standard ASF description, and do not need to be written in any other frame
private static IDictionary<string, ushort> frameClasses; // Mapping between WMA frame codes and frame classes that aren't class 0 (Unicode string)
private IList<string> languages; // Optional language index described in the WMA header
private AudioDataManager.SizeInfo sizeInfo;
private string filePath;
/* Unused for now
public bool IsStreamed
{
get { return true; }
}
*/
// ---------- INFORMATIVE INTERFACE IMPLEMENTATIONS & MANDATORY OVERRIDES
// IAudioDataIO
public int SampleRate // Sample rate (hz)
{
get { return this.sampleRate; }
}
public bool IsVBR
{
get { return this.isVBR; }
}
public int CodecFamily
{
get
{
return isLossless ? AudioDataIOFactory.CF_LOSSLESS : AudioDataIOFactory.CF_LOSSY;
}
}
public string FileName { get { return filePath; } }
public double BitRate { get { return bitrate; } }
public double Duration { get { return duration; } }
public ChannelsArrangement ChannelsArrangement
{
get { return channelsArrangement; }
}
public bool IsMetaSupported(int metaDataType)
{
return (metaDataType == MetaDataIOFactory.TAG_ID3V1) || (metaDataType == MetaDataIOFactory.TAG_ID3V2) || (metaDataType == MetaDataIOFactory.TAG_APE) || (metaDataType == MetaDataIOFactory.TAG_NATIVE);
}
protected override byte getFrameMapping(string zone, string ID, byte tagVersion)
{
byte supportedMetaId = 255;
// Finds the ATL field identifier according to the ID3v2 version
if (frameMapping.ContainsKey(ID)) supportedMetaId = frameMapping[ID];
return supportedMetaId;
}
// IMetaDataIO
protected override int getDefaultTagOffset()
{
return TO_BUILTIN;
}
protected override int getImplementedTagType()
{
return MetaDataIOFactory.TAG_NATIVE;
}
protected override byte ratingConvention
{
get { return RC_ASF; }
}
// ---------- CONSTRUCTORS & INITIALIZERS
static WMA()
{
// NB : WM/TITLE, WM/AUTHOR, WM/COPYRIGHT, WM/DESCRIPTION and WM/RATING are not WMA extended fields; therefore
// their ID will not appear as is in the WMA header.
// Their info is contained in the standard Content Description block at the very beginning of the file
frameMapping = new Dictionary<string, byte>
{
{ "WM/TITLE", TagData.TAG_FIELD_TITLE },
{ "WM/AlbumTitle", TagData.TAG_FIELD_ALBUM },
{ "WM/AUTHOR", TagData.TAG_FIELD_ARTIST },
{ "WM/COPYRIGHT", TagData.TAG_FIELD_COPYRIGHT },
{ "WM/DESCRIPTION", TagData.TAG_FIELD_COMMENT },
{ "WM/Year", TagData.TAG_FIELD_RECORDING_YEAR },
{ "WM/Genre", TagData.TAG_FIELD_GENRE },
{ "WM/TrackNumber", TagData.TAG_FIELD_TRACK_NUMBER_TOTAL },
{ "WM/PartOfSet", TagData.TAG_FIELD_DISC_NUMBER_TOTAL },
{ "WM/RATING", TagData.TAG_FIELD_RATING },
{ "WM/SharedUserRating", TagData.TAG_FIELD_RATING },
{ "WM/Composer", TagData.TAG_FIELD_COMPOSER },
{ "WM/AlbumArtist", TagData.TAG_FIELD_ALBUM_ARTIST },
{ "WM/Conductor", TagData.TAG_FIELD_CONDUCTOR }
};
embeddedFields = new List<string>
{
{ "WM/TITLE" },
{ "WM/AUTHOR" },
{ "WM/COPYRIGHT" },
{ "WM/DESCRIPTION" },
{ "WM/RATING" }
};
frameClasses = new Dictionary<string, ushort>(); // To be further populated while reading
frameClasses.Add("WM/SharedUserRating", 3);
}
private void resetData()
{
sampleRate = 0;
isVBR = false;
isLossless = false;
bitrate = 0;
duration = 0;
ResetData();
}
public WMA(string filePath)
{
this.filePath = filePath;
resetData();
}
// ---------- SUPPORT METHODS
private static void addFrameClass(string frameCode, ushort frameClass)
{
if (!frameClasses.ContainsKey(frameCode)) frameClasses.Add(frameCode, frameClass);
}
private void cacheLanguageIndex(Stream source)
{
if (null == languages)
{
long position, initialPosition;
ulong objectSize;
byte[] bytes;
languages = new List<string>();
initialPosition = source.Position;
source.Seek(fileData.ObjectListOffset, SeekOrigin.Begin);
BinaryReader r = new BinaryReader(source);
for (int i = 0; i < fileData.ObjectCount; i++)
{
position = source.Position;
bytes = r.ReadBytes(16);
objectSize = r.ReadUInt64();
// Language index (optional; one only -- useful to map language codes to extended header tag information)
if (StreamUtils.ArrEqualsArr(WMA_LANGUAGE_LIST_OBJECT_ID, bytes))
{
ushort nbLanguages = r.ReadUInt16();
byte strLen;
for (int j = 0; j < nbLanguages; j++)
{
strLen = r.ReadByte();
long position2 = source.Position;
if (strLen > 2) languages.Add(Utils.StripEndingZeroChars(Encoding.Unicode.GetString(r.ReadBytes(strLen))));
source.Seek(position2 + strLen, SeekOrigin.Begin);
}
}
source.Seek(position + (long)objectSize, SeekOrigin.Begin);
}
source.Seek(initialPosition, SeekOrigin.Begin);
}
}
private ushort encodeLanguage(Stream source, string languageCode)
{
if (null == languages) cacheLanguageIndex(source);
if (0 == languages.Count)
{
return 0;
}
else
{
return (ushort)languages.IndexOf(languageCode);
}
}
private string decodeLanguage(Stream source, ushort languageIndex)
{
if (null == languages) cacheLanguageIndex(source);
if (languages.Count > 0)
{
if (languageIndex < languages.Count)
{
return languages[languageIndex];
}
else
{
return languages[0]; // Index out of bounds
}
}
else
{
return "";
}
}
private void readContentDescription(BinaryReader source, MetaDataIO.ReadTagParams readTagParams)
{
ushort[] fieldSize = new ushort[5];
string fieldValue;
// Read standard field sizes
for (int i = 0; i < 5; i++) fieldSize[i] = source.ReadUInt16();
// Read standard field values
for (int i = 0; i < 5; i++)
{
if (fieldSize[i] > 0)
{
// Read field value
fieldValue = StreamUtils.ReadNullTerminatedString(source, Encoding.Unicode);
// Set corresponding tag field if supported
switch (i)
{
case 0: SetMetaField("WM/TITLE", fieldValue, readTagParams.ReadAllMetaFrames, ZONE_CONTENT_DESCRIPTION); break;
case 1: SetMetaField("WM/AUTHOR", fieldValue, readTagParams.ReadAllMetaFrames, ZONE_CONTENT_DESCRIPTION); break;
case 2: SetMetaField("WM/COPYRIGHT", fieldValue, readTagParams.ReadAllMetaFrames, ZONE_CONTENT_DESCRIPTION); break;
case 3: SetMetaField("WM/DESCRIPTION", fieldValue, readTagParams.ReadAllMetaFrames, ZONE_CONTENT_DESCRIPTION); break;
case 4: SetMetaField("WM/RATING", fieldValue, readTagParams.ReadAllMetaFrames, ZONE_CONTENT_DESCRIPTION); break;
}
}
}
}
private void readHeaderExtended(BinaryReader source, long sizePosition1, ulong size1, long sizePosition2, ulong size2, MetaDataIO.ReadTagParams readTagParams)
{
byte[] headerExtensionObjectId;
ulong headerExtensionObjectSize = 0;
long position, framePosition, sizePosition3, dataPosition;
ulong limit;
ushort streamNumber, languageIndex;
source.BaseStream.Seek(16, SeekOrigin.Current); // Reserved field 1
source.BaseStream.Seek(2, SeekOrigin.Current); // Reserved field 2
sizePosition3 = source.BaseStream.Position;
uint headerExtendedSize = source.ReadUInt32(); // Size of actual data
// Looping through header extension objects
position = source.BaseStream.Position;
limit = (ulong)position + headerExtendedSize;
while ((ulong)position < limit)
{
framePosition = source.BaseStream.Position;
headerExtensionObjectId = source.ReadBytes(16);
headerExtensionObjectSize = source.ReadUInt64();
// Additional metadata (Optional frames)
if (StreamUtils.ArrEqualsArr(WMA_METADATA_OBJECT_ID, headerExtensionObjectId) || StreamUtils.ArrEqualsArr(WMA_METADATA_LIBRARY_OBJECT_ID, headerExtensionObjectId))
{
ushort nameSize; // Length (in bytes) of Name field
ushort fieldDataType; // Type of data stored in current field
int fieldDataSize; // Size of data stored in current field
string fieldName; // Name of current field
ushort nbObjects = source.ReadUInt16();
bool isLibraryObject = StreamUtils.ArrEqualsArr(WMA_METADATA_LIBRARY_OBJECT_ID, headerExtensionObjectId);
string zoneCode = isLibraryObject ? ZONE_EXTENDED_HEADER_METADATA_LIBRARY : ZONE_EXTENDED_HEADER_METADATA;
structureHelper.AddZone(framePosition, (int)headerExtensionObjectSize, zoneCode);
// Store frame information for future editing, since current frame is optional
if (readTagParams.PrepareForWriting)
{
structureHelper.AddSize(sizePosition1, size1, zoneCode);
structureHelper.AddSize(sizePosition2, size2, zoneCode);
structureHelper.AddSize(sizePosition3, headerExtendedSize, zoneCode);
}
for (int i = 0; i < nbObjects; i++)
{
languageIndex = source.ReadUInt16();
streamNumber = source.ReadUInt16();
nameSize = source.ReadUInt16();
fieldDataType = source.ReadUInt16();
fieldDataSize = source.ReadInt32();
fieldName = Utils.StripEndingZeroChars(Encoding.Unicode.GetString(source.ReadBytes(nameSize)));
dataPosition = source.BaseStream.Position;
readTagField(source, zoneCode, fieldName, fieldDataType, fieldDataSize, readTagParams, true, languageIndex, streamNumber);
source.BaseStream.Seek(dataPosition + fieldDataSize, SeekOrigin.Begin);
}
}
source.BaseStream.Seek(position + (long)headerExtensionObjectSize, SeekOrigin.Begin);
position = source.BaseStream.Position;
}
// Add absent zone definitions for further editing
if (readTagParams.PrepareForWriting)
{
if (!structureHelper.ZoneNames.Contains(ZONE_EXTENDED_HEADER_METADATA))
{
structureHelper.AddZone(source.BaseStream.Position, 0, ZONE_EXTENDED_HEADER_METADATA);
structureHelper.AddSize(sizePosition1, size1, ZONE_EXTENDED_HEADER_METADATA);
structureHelper.AddSize(sizePosition2, size2, ZONE_EXTENDED_HEADER_METADATA);
structureHelper.AddSize(sizePosition3, headerExtendedSize, ZONE_EXTENDED_HEADER_METADATA);
}
if (!structureHelper.ZoneNames.Contains(ZONE_EXTENDED_HEADER_METADATA_LIBRARY))
{
structureHelper.AddZone(source.BaseStream.Position, 0, ZONE_EXTENDED_HEADER_METADATA_LIBRARY);
structureHelper.AddSize(sizePosition1, size1, ZONE_EXTENDED_HEADER_METADATA_LIBRARY);
structureHelper.AddSize(sizePosition2, size2, ZONE_EXTENDED_HEADER_METADATA_LIBRARY);
structureHelper.AddSize(sizePosition3, headerExtendedSize, ZONE_EXTENDED_HEADER_METADATA_LIBRARY);
}
}
}
private void readExtendedContentDescription(BinaryReader source, MetaDataIO.ReadTagParams readTagParams)
{
long dataPosition;
ushort fieldCount;
ushort dataSize;
ushort dataType;
string fieldName;
// Read extended tag data
fieldCount = source.ReadUInt16();
for (int iterator1 = 0; iterator1 < fieldCount; iterator1++)
{
// Read field name
dataSize = source.ReadUInt16();
fieldName = Utils.StripEndingZeroChars(Encoding.Unicode.GetString(source.ReadBytes(dataSize)));
// Read value data type
dataType = source.ReadUInt16();
dataSize = source.ReadUInt16();
dataPosition = source.BaseStream.Position;
readTagField(source, ZONE_EXTENDED_CONTENT_DESCRIPTION, fieldName, dataType, dataSize, readTagParams);
source.BaseStream.Seek(dataPosition + dataSize, SeekOrigin.Begin);
}
}
public void readTagField(BinaryReader source, string zoneCode, string fieldName, ushort fieldDataType, int fieldDataSize, ReadTagParams readTagParams, bool isExtendedHeader = false, ushort languageIndex = 0, ushort streamNumber = 0)
{
string fieldValue = "";
bool setMeta = true;
addFrameClass(fieldName, fieldDataType);
if (0 == fieldDataType) // Unicode string
{
fieldValue = Utils.StripEndingZeroChars(Encoding.Unicode.GetString(source.ReadBytes(fieldDataSize)));
}
else if (1 == fieldDataType) // Byte array
{
if (fieldName.ToUpper().Equals("WM/PICTURE"))
{
byte picCode = source.ReadByte();
// TODO factorize : abstract PictureTypeDecoder + unsupported / supported decision in MetaDataIO ?
PictureInfo.PIC_TYPE picType = ID3v2.DecodeID3v2PictureType(picCode);
int picturePosition;
if (picType.Equals(PictureInfo.PIC_TYPE.Unsupported))
{
addPictureToken(MetaDataIOFactory.TAG_NATIVE, picCode);
picturePosition = takePicturePosition(MetaDataIOFactory.TAG_NATIVE, picCode);
}
else
{
addPictureToken(picType);
picturePosition = takePicturePosition(picType);
}
if (readTagParams.ReadPictures || readTagParams.PictureStreamHandler != null)
{
int picSize = source.ReadInt32();
string mimeType = StreamUtils.ReadNullTerminatedString(source, Encoding.Unicode);
string description = StreamUtils.ReadNullTerminatedString(source, Encoding.Unicode);
PictureInfo picInfo = new PictureInfo(ImageUtils.GetImageFormatFromMimeType(mimeType), picType, getImplementedTagType(), picCode, picturePosition);
picInfo.Description = description;
picInfo.PictureData = new byte[picSize];
source.BaseStream.Read(picInfo.PictureData, 0, picSize);
tagData.Pictures.Add(picInfo);
if (readTagParams.PictureStreamHandler != null)
{
MemoryStream mem = new MemoryStream(picInfo.PictureData);
readTagParams.PictureStreamHandler(ref mem, picInfo.PicType, picInfo.NativeFormat, picInfo.TagType, picInfo.NativePicCode, picInfo.Position);
mem.Close();
}
}
setMeta = false;
}
else
{
source.BaseStream.Seek(fieldDataSize, SeekOrigin.Current);
}
}
else if (2 == fieldDataType) // 16-bit Boolean (metadata); 32-bit Boolean (extended header)
{
if (isExtendedHeader) fieldValue = source.ReadUInt32().ToString();
else fieldValue = source.ReadUInt16().ToString();
}
else if (3 == fieldDataType) // 32-bit unsigned integer
{
uint intValue = source.ReadUInt32();
if (fieldName.Equals("WM/GENRE", StringComparison.OrdinalIgnoreCase)) intValue++;
fieldValue = intValue.ToString();
}
else if (4 == fieldDataType) // 64-bit unsigned integer
{
fieldValue = source.ReadUInt64().ToString();
}
else if (5 == fieldDataType) // 16-bit unsigned integer
{
fieldValue = source.ReadUInt16().ToString();
}
else if (6 == fieldDataType) // 128-bit GUID; unused for now
{
source.BaseStream.Seek(fieldDataSize, SeekOrigin.Current);
}
if (setMeta) SetMetaField(fieldName.Trim(), fieldValue, readTagParams.ReadAllMetaFrames, zoneCode, 0, streamNumber, decodeLanguage(source.BaseStream, languageIndex));
}
private bool readData(BinaryReader source, ReadTagParams readTagParams)
{
Stream fs = source.BaseStream;
byte[] ID;
uint objectCount;
ulong headerSize, objectSize;
long initialPos, position;
long countPosition, sizePosition1, sizePosition2;
bool result = false;
if (languages != null) languages.Clear();
fs.Seek(sizeInfo.ID3v2Size, SeekOrigin.Begin);
initialPos = fs.Position;
// Check for existing header
ID = source.ReadBytes(16);
// Header (mandatory; one only)
if (StreamUtils.ArrEqualsArr(WMA_HEADER_ID, ID))
{
sizePosition1 = fs.Position;
headerSize = source.ReadUInt64();
countPosition = fs.Position;
objectCount = source.ReadUInt32();
fs.Seek(2, SeekOrigin.Current); // Reserved data
fileData.ObjectCount = objectCount;
fileData.ObjectListOffset = fs.Position;
// Read all objects in header and get needed data
for (int i = 0; i < objectCount; i++)
{
position = fs.Position;
ID = source.ReadBytes(16);
sizePosition2 = fs.Position;
objectSize = source.ReadUInt64();
// File properties (mandatory; one only)
if (StreamUtils.ArrEqualsArr(WMA_FILE_PROPERTIES_ID, ID))
{
source.BaseStream.Seek(40, SeekOrigin.Current);
duration = source.ReadUInt64() / 10000.0; // Play duration (100-nanoseconds)
source.BaseStream.Seek(8, SeekOrigin.Current); // Send duration; unused for now
duration -= source.ReadUInt64(); // Preroll duration (ms)
}
// Stream properties (mandatory; one per stream)
else if (StreamUtils.ArrEqualsArr(WMA_STREAM_PROPERTIES_ID, ID))
{
source.BaseStream.Seek(54, SeekOrigin.Current);
fileData.FormatTag = source.ReadUInt16();
fileData.Channels = source.ReadUInt16();
fileData.SampleRate = source.ReadInt32();
}
// Content description (optional; one only)
// -> standard, pre-defined metadata
else if (StreamUtils.ArrEqualsArr(WMA_CONTENT_DESCRIPTION_ID, ID) && readTagParams.ReadTag)
{
tagExists = true;
structureHelper.AddZone(position, (int)objectSize, ZONE_CONTENT_DESCRIPTION);
// Store frame information for future editing, since current frame is optional
if (readTagParams.PrepareForWriting)
{
structureHelper.AddSize(sizePosition1, headerSize, ZONE_CONTENT_DESCRIPTION);
structureHelper.AddCounter(countPosition, objectCount, ZONE_CONTENT_DESCRIPTION);
}
readContentDescription(source, readTagParams);
}
// Extended content description (optional; one only)
// -> extended, dynamic metadata
else if (StreamUtils.ArrEqualsArr(WMA_EXTENDED_CONTENT_DESCRIPTION_ID, ID) && readTagParams.ReadTag)
{
tagExists = true;
structureHelper.AddZone(position, (int)objectSize, ZONE_EXTENDED_CONTENT_DESCRIPTION);
// Store frame information for future editing, since current frame is optional
if (readTagParams.PrepareForWriting)
{
structureHelper.AddSize(sizePosition1, headerSize, ZONE_EXTENDED_CONTENT_DESCRIPTION);
structureHelper.AddCounter(countPosition, objectCount, ZONE_EXTENDED_CONTENT_DESCRIPTION);
}
readExtendedContentDescription(source, readTagParams);
}
// Header extension (mandatory; one only)
// -> extended, dynamic additional metadata such as additional embedded pictures (any picture after the 1st one stored in extended content)
else if (StreamUtils.ArrEqualsArr(WMA_HEADER_EXTENSION_ID, ID) && readTagParams.ReadTag)
{
readHeaderExtended(source, sizePosition1, headerSize, sizePosition2, objectSize, readTagParams);
}
fs.Seek(position + (long)objectSize, SeekOrigin.Begin);
}
// Add absent zone definitions for further editing
if (readTagParams.PrepareForWriting)
{
if (!structureHelper.ZoneNames.Contains(ZONE_CONTENT_DESCRIPTION))
{
structureHelper.AddZone(fs.Position, 0, ZONE_CONTENT_DESCRIPTION);
structureHelper.AddSize(sizePosition1, headerSize, ZONE_CONTENT_DESCRIPTION);
structureHelper.AddCounter(countPosition, objectCount, ZONE_CONTENT_DESCRIPTION);
}
if (!structureHelper.ZoneNames.Contains(ZONE_EXTENDED_CONTENT_DESCRIPTION))
{
structureHelper.AddZone(fs.Position, 0, ZONE_EXTENDED_CONTENT_DESCRIPTION);
structureHelper.AddSize(sizePosition1, headerSize, ZONE_EXTENDED_CONTENT_DESCRIPTION);
structureHelper.AddCounter(countPosition, objectCount, ZONE_EXTENDED_CONTENT_DESCRIPTION);
}
}
result = true;
}
fileData.HeaderSize = fs.Position - initialPos;
return result;
}
private bool isValid(FileData Data)
{
return (Data.Channels > 0) && (Data.SampleRate >= 8000) && (Data.SampleRate <= 96000);
}
public bool Read(BinaryReader source, AudioDataManager.SizeInfo sizeInfo, MetaDataIO.ReadTagParams readTagParams)
{
this.sizeInfo = sizeInfo;
return read(source, readTagParams);
}
protected override bool read(BinaryReader source, MetaDataIO.ReadTagParams readTagParams)
{
fileData = new FileData();
resetData();
bool result = readData(source, readTagParams);
// Process data if loaded and valid
if (result && isValid(fileData))
{
channelsArrangement = ChannelsArrangements.GuessFromChannelNumber(fileData.Channels);
sampleRate = fileData.SampleRate;
bitrate = (sizeInfo.FileSize - sizeInfo.TotalTagSize - fileData.HeaderSize) * 8.0 / duration;
isVBR = (WMA_GSM_VBR_ID == fileData.FormatTag);
isLossless = (WMA_LOSSLESS_ID == fileData.FormatTag);
}
return result;
}
protected override int write(TagData tag, BinaryWriter w, string zone)
{
if (ZONE_CONTENT_DESCRIPTION.Equals(zone)) return writeContentDescription(tag, w);
else if (ZONE_EXTENDED_HEADER_METADATA.Equals(zone)) return writeExtendedHeaderMeta(tag, w);
else if (ZONE_EXTENDED_HEADER_METADATA_LIBRARY.Equals(zone)) return writeExtendedHeaderMetaLibrary(tag, w);
else if (ZONE_EXTENDED_CONTENT_DESCRIPTION.Equals(zone)) return writeExtendedContentDescription(tag, w);
else return 0;
}
private int writeContentDescription(TagData tag, BinaryWriter w)
{
long beginPos, frameSizePos, finalFramePos;
beginPos = w.BaseStream.Position;
w.Write(WMA_CONTENT_DESCRIPTION_ID);
frameSizePos = w.BaseStream.Position;
w.Write((ulong)0); // Frame size placeholder to be rewritten at the end of the method
string title = "";
string author = "";
string copyright = "";
string comment = "";
string rating = "";
IDictionary<byte, String> map = tag.ToMap();
// Supported textual fields
foreach (byte frameType in map.Keys)
{
if (map[frameType].Length > 0) // No frame with empty value
{
if (TagData.TAG_FIELD_TITLE.Equals(frameType)) title = map[frameType];
else if (TagData.TAG_FIELD_ARTIST.Equals(frameType)) author = map[frameType];
else if (TagData.TAG_FIELD_COPYRIGHT.Equals(frameType)) copyright = map[frameType];
else if (TagData.TAG_FIELD_COMMENT.Equals(frameType)) comment = map[frameType];
else if (TagData.TAG_FIELD_RATING.Equals(frameType)) rating = map[frameType];
}
}
// Read standard field sizes (+1 for last null characher; x2 for unicode)
if (title.Length > 0) w.Write((ushort)((title.Length + 1) * 2)); else w.Write((ushort)0);
if (author.Length > 0) w.Write((ushort)((author.Length + 1) * 2)); else w.Write((ushort)0);
if (copyright.Length > 0) w.Write((ushort)((copyright.Length + 1) * 2)); else w.Write((ushort)0);
if (comment.Length > 0) w.Write((ushort)((comment.Length + 1) * 2)); else w.Write((ushort)0);
if (rating.Length > 0) w.Write((ushort)((rating.Length + 1) * 2)); else w.Write((ushort)0);
if (title.Length > 0) w.Write(Encoding.Unicode.GetBytes(title + '\0'));
if (author.Length > 0) w.Write(Encoding.Unicode.GetBytes(author + '\0'));
if (copyright.Length > 0) w.Write(Encoding.Unicode.GetBytes(copyright + '\0'));
if (comment.Length > 0) w.Write(Encoding.Unicode.GetBytes(comment + '\0'));
if (rating.Length > 0) w.Write(Encoding.Unicode.GetBytes(rating + '\0'));
// Go back to frame size locations to write their actual size
finalFramePos = w.BaseStream.Position;
w.BaseStream.Seek(frameSizePos, SeekOrigin.Begin);
w.Write(Convert.ToUInt64(finalFramePos - beginPos));
w.BaseStream.Seek(finalFramePos, SeekOrigin.Begin);
return ((title.Length > 0) ? 1 : 0) + ((author.Length > 0) ? 1 : 0) + ((copyright.Length > 0) ? 1 : 0) + ((comment.Length > 0) ? 1 : 0) + ((rating.Length > 0) ? 1 : 0);
}
private int writeExtendedContentDescription(TagData tag, BinaryWriter w)
{
long beginPos, frameSizePos, counterPos, finalFramePos;
ushort counter = 0;
bool doWritePicture;
beginPos = w.BaseStream.Position;
w.Write(WMA_EXTENDED_CONTENT_DESCRIPTION_ID);
frameSizePos = w.BaseStream.Position;
w.Write((ulong)0); // Frame size placeholder to be rewritten at the end of the method
counterPos = w.BaseStream.Position;
w.Write((ushort)0); // Counter placeholder to be rewritten at the end of the method
IDictionary<byte, String> map = tag.ToMap();
// Supported textual fields
foreach (byte frameType in map.Keys)
{
foreach (string s in frameMapping.Keys)
{
if (!embeddedFields.Contains(s) && frameType == frameMapping[s])
{
if (map[frameType].Length > 0) // No frame with empty value
{
string value = formatBeforeWriting(frameType, tag, map);
writeTextFrame(w, s, value);
counter++;
}
break;
}
}
}
// Other textual fields
foreach (MetaFieldInfo fieldInfo in tag.AdditionalFields)
{
if ((fieldInfo.TagType.Equals(MetaDataIOFactory.TAG_ANY) || fieldInfo.TagType.Equals(getImplementedTagType())) && !fieldInfo.MarkedForDeletion && (ZONE_EXTENDED_CONTENT_DESCRIPTION.Equals(fieldInfo.Zone) || "".Equals(fieldInfo.Zone)))
{
writeTextFrame(w, fieldInfo.NativeFieldCode, fieldInfo.Value);
counter++;
}
}
// Picture fields
foreach (PictureInfo picInfo in tag.Pictures)
{
// Picture has either to be supported, or to come from the right tag standard
doWritePicture = !picInfo.PicType.Equals(PictureInfo.PIC_TYPE.Unsupported);
if (!doWritePicture) doWritePicture = (getImplementedTagType() == picInfo.TagType);
// It also has not to be marked for deletion
doWritePicture = doWritePicture && (!picInfo.MarkedForDeletion);
if (doWritePicture && picInfo.PictureData.Length + 50 <= ushort.MaxValue)
{
writePictureFrame(w, picInfo.PictureData, picInfo.NativeFormat, ImageUtils.GetMimeTypeFromImageFormat(picInfo.NativeFormat), picInfo.PicType.Equals(PictureInfo.PIC_TYPE.Unsupported) ? (byte)picInfo.NativePicCode : ID3v2.EncodeID3v2PictureType(picInfo.PicType), picInfo.Description);
counter++;
}
}
// Go back to frame size locations to write their actual size
finalFramePos = w.BaseStream.Position;
w.BaseStream.Seek(frameSizePos, SeekOrigin.Begin);
w.Write(Convert.ToUInt64(finalFramePos - beginPos));
w.BaseStream.Seek(counterPos, SeekOrigin.Begin);
w.Write(counter);
w.BaseStream.Seek(finalFramePos, SeekOrigin.Begin);
return counter;
}
private int writeExtendedHeaderMeta(TagData tag, BinaryWriter w)
{
long beginPos, frameSizePos, counterPos, finalFramePos;
ushort counter;
beginPos = w.BaseStream.Position;
w.Write(WMA_METADATA_OBJECT_ID);
frameSizePos = w.BaseStream.Position;
w.Write((ulong)0); // Frame size placeholder to be rewritten at the end of the method
counterPos = w.BaseStream.Position;
w.Write((ushort)0); // Counter placeholder to be rewritten at the end of the method
counter = writeExtendedMeta(tag, w);
// Go back to frame size locations to write their actual size
finalFramePos = w.BaseStream.Position;
w.BaseStream.Seek(frameSizePos, SeekOrigin.Begin);
w.Write(Convert.ToUInt64(finalFramePos - beginPos));
w.BaseStream.Seek(counterPos, SeekOrigin.Begin);
w.Write(counter);
w.BaseStream.Seek(finalFramePos, SeekOrigin.Begin);
return counter;
}
private int writeExtendedHeaderMetaLibrary(TagData tag, BinaryWriter w)
{
long beginPos, frameSizePos, counterPos, finalFramePos;
ushort counter;
beginPos = w.BaseStream.Position;
w.Write(WMA_METADATA_LIBRARY_OBJECT_ID);
frameSizePos = w.BaseStream.Position;
w.Write((ulong)0); // Frame size placeholder to be rewritten at the end of the method
counterPos = w.BaseStream.Position;
w.Write((ushort)0); // Counter placeholder to be rewritten at the end of the method
counter = writeExtendedMeta(tag, w, true);
// Go back to frame size locations to write their actual size
finalFramePos = w.BaseStream.Position;
w.BaseStream.Seek(frameSizePos, SeekOrigin.Begin);
w.Write(Convert.ToUInt64(finalFramePos - beginPos));
w.BaseStream.Seek(counterPos, SeekOrigin.Begin);
w.Write(counter);
w.BaseStream.Seek(finalFramePos, SeekOrigin.Begin);
return counter;
}
private ushort writeExtendedMeta(TagData tag, BinaryWriter w, bool isExtendedMetaLibrary = false)
{
bool doWritePicture;
ushort counter = 0;
IDictionary<byte, String> map = tag.ToMap();
// Supported textual fields : all current supported fields are located in extended content description frame
// Other textual fields
foreach (MetaFieldInfo fieldInfo in tag.AdditionalFields)
{
if ((fieldInfo.TagType.Equals(MetaDataIOFactory.TAG_ANY) || fieldInfo.TagType.Equals(getImplementedTagType())) && !fieldInfo.MarkedForDeletion)
{
if ((ZONE_EXTENDED_HEADER_METADATA.Equals(fieldInfo.Zone) && !isExtendedMetaLibrary) || (ZONE_EXTENDED_HEADER_METADATA_LIBRARY.Equals(fieldInfo.Zone) && isExtendedMetaLibrary))
{
writeTextFrame(w, fieldInfo.NativeFieldCode, fieldInfo.Value, true, encodeLanguage(w.BaseStream, fieldInfo.Language), fieldInfo.StreamNumber);
counter++;
}
}
}
// Picture fields (exclusively written in Metadata Library Object zone)
if (isExtendedMetaLibrary)
{
foreach (PictureInfo picInfo in tag.Pictures)
{
// Picture has either to be supported, or to come from the right tag standard
doWritePicture = !picInfo.PicType.Equals(PictureInfo.PIC_TYPE.Unsupported);
if (!doWritePicture) doWritePicture = (getImplementedTagType() == picInfo.TagType);
// It also has not to be marked for deletion
doWritePicture = doWritePicture && (!picInfo.MarkedForDeletion);
if (doWritePicture && picInfo.PictureData.Length + 50 > ushort.MaxValue)
{
writePictureFrame(w, picInfo.PictureData, picInfo.NativeFormat, ImageUtils.GetMimeTypeFromImageFormat(picInfo.NativeFormat), picInfo.PicType.Equals(PictureInfo.PIC_TYPE.Unsupported) ? (byte)picInfo.NativePicCode : ID3v2.EncodeID3v2PictureType(picInfo.PicType), picInfo.Description, true);
counter++;
}
}
}
return counter;
}
private void writeTextFrame(BinaryWriter writer, string frameCode, string text, bool isExtendedHeader = false, ushort languageIndex = 0, ushort streamNumber = 0)
{
long dataSizePos, dataPos, finalFramePos;
byte[] nameBytes = Encoding.Unicode.GetBytes(frameCode + '\0');
ushort nameSize = (ushort)nameBytes.Length;
if (isExtendedHeader)
{
writer.Write(languageIndex); // Metadata object : Reserved / Metadata library object : Language list index
writer.Write(streamNumber); // Corresponding stream number
}
// Name length and name
writer.Write(nameSize);
if (!isExtendedHeader) writer.Write(nameBytes);
ushort frameClass = 0;
if (frameClasses.ContainsKey(frameCode)) frameClass = frameClasses[frameCode];
writer.Write(frameClass);
dataSizePos = writer.BaseStream.Position;
// Data size placeholder to be rewritten in a few lines
if (isExtendedHeader)
{
writer.Write((uint)0);
}
else
{
writer.Write((ushort)0);
}
if (isExtendedHeader) writer.Write(nameBytes);
dataPos = writer.BaseStream.Position;
if (0 == frameClass) // Unicode string
{
writer.Write(Encoding.Unicode.GetBytes(text + '\0'));
}
else if (1 == frameClass) // Byte array
{
// Only used for embedded pictures
}
else if (2 == frameClass) // 32-bit boolean; 16-bit boolean if in extended header
{
if (isExtendedHeader) writer.Write(Utils.ToBoolean(text) ? (ushort)1 : (ushort)0);
else writer.Write(Utils.ToBoolean(text) ? (uint)1 : (uint)0);
}
else if (3 == frameClass) // 32-bit unsigned integer
{
writer.Write(Convert.ToUInt32(text));
}
else if (4 == frameClass) // 64-bit unsigned integer
{
writer.Write(Convert.ToUInt64(text));
}
else if (5 == frameClass) // 16-bit unsigned integer
{
writer.Write(Convert.ToUInt16(text));
}
else if (6 == frameClass) // 128-bit GUID
{
// Unused for now
}
// Go back to frame size locations to write their actual size
finalFramePos = writer.BaseStream.Position;
writer.BaseStream.Seek(dataSizePos, SeekOrigin.Begin);
if (!isExtendedHeader)
{
writer.Write(Convert.ToUInt16(finalFramePos - dataPos));
}
else
{
writer.Write(Convert.ToUInt32(finalFramePos - dataPos));
}
writer.BaseStream.Seek(finalFramePos, SeekOrigin.Begin);
}
private void writePictureFrame(BinaryWriter writer, byte[] pictureData, ImageFormat picFormat, string mimeType, byte pictureTypeCode, string description, bool isExtendedHeader = false, ushort languageIndex = 0, ushort streamNumber = 0)
{
long dataSizePos, dataPos, finalFramePos;
byte[] nameBytes = Encoding.Unicode.GetBytes("WM/Picture" + '\0');
ushort nameSize = (ushort)nameBytes.Length;
if (isExtendedHeader)
{
writer.Write(languageIndex); // Metadata object : Reserved / Metadata library object : Language list index
writer.Write(streamNumber); // Corresponding stream number
}
// Name length and name
writer.Write(nameSize);
if (!isExtendedHeader) writer.Write(nameBytes);
ushort frameClass = 1;
writer.Write(frameClass);
dataSizePos = writer.BaseStream.Position;
// Data size placeholder to be rewritten in a few lines
if (isExtendedHeader)
{
writer.Write((uint)0);
}
else
{
writer.Write((ushort)0);
}
if (isExtendedHeader)
{
writer.Write(nameBytes);
}
dataPos = writer.BaseStream.Position;
writer.Write(pictureTypeCode);
writer.Write(pictureData.Length);
writer.Write(Encoding.Unicode.GetBytes(mimeType + '\0'));
writer.Write(Encoding.Unicode.GetBytes(description + '\0')); // Picture description
writer.Write(pictureData);
// Go back to frame size locations to write their actual size
finalFramePos = writer.BaseStream.Position;
writer.BaseStream.Seek(dataSizePos, SeekOrigin.Begin);
if (isExtendedHeader)
{
writer.Write(Convert.ToUInt32(finalFramePos - dataPos));
}
else
{
writer.Write(Convert.ToUInt16(finalFramePos - dataPos));
}
writer.BaseStream.Seek(finalFramePos, SeekOrigin.Begin);
}
// Specific implementation for conservation of non-WM/xxx fields
public override bool Remove(BinaryWriter w)
{
if (Settings.ASF_keepNonWMFieldsWhenRemovingTag)
{
TagData tag = new TagData();
foreach (byte b in frameMapping.Values)
{
tag.IntegrateValue(b, "");
}
foreach (MetaFieldInfo fieldInfo in GetAdditionalFields())
{
if (fieldInfo.NativeFieldCode.ToUpper().StartsWith("WM/"))
{
MetaFieldInfo emptyFieldInfo = new MetaFieldInfo(fieldInfo);
emptyFieldInfo.MarkedForDeletion = true;
tag.AdditionalFields.Add(emptyFieldInfo);
}
}
BinaryReader r = new BinaryReader(w.BaseStream);
return Write(r, w, tag);
}
else
{
return base.Remove(w);
}
}
}
}
| |
#region License
//
// Copyright (c) 2018, Fluent Migrator Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#endregion
using FluentMigrator.Runner.Generators.MySql;
using NUnit.Framework;
using Shouldly;
namespace FluentMigrator.Tests.Unit.Generators.MySql5
{
[TestFixture]
public class MySql5TableTests
{
protected MySql4Generator Generator;
[SetUp]
public void Setup()
{
Generator = new MySql5Generator();
}
[Test]
public void CanCreateTableWithCustomColumnTypeWithCustomSchema()
{
var expression = GeneratorTestHelper.GetCreateTableExpression();
expression.Columns[0].IsPrimaryKey = true;
expression.Columns[1].Type = null;
expression.Columns[1].CustomType = "[timestamp]";
expression.SchemaName = "TestSchema";
var result = Generator.Generate(expression);
result.ShouldBe("CREATE TABLE `TestTable1` (`TestColumn1` NVARCHAR(255) NOT NULL, `TestColumn2` [timestamp] NOT NULL, PRIMARY KEY (`TestColumn1`)) ENGINE = INNODB");
}
[Test]
public void CanCreateTableWithCustomColumnTypeWithDefaultSchema()
{
var expression = GeneratorTestHelper.GetCreateTableExpression();
expression.Columns[0].IsPrimaryKey = true;
expression.Columns[1].Type = null;
expression.Columns[1].CustomType = "[timestamp]";
var result = Generator.Generate(expression);
result.ShouldBe("CREATE TABLE `TestTable1` (`TestColumn1` NVARCHAR(255) NOT NULL, `TestColumn2` [timestamp] NOT NULL, PRIMARY KEY (`TestColumn1`)) ENGINE = INNODB");
}
[Test]
public void CanCreateTableWithCustomSchema()
{
var expression = GeneratorTestHelper.GetCreateTableExpression();
expression.SchemaName = "TestSchema";
var result = Generator.Generate(expression);
result.ShouldBe("CREATE TABLE `TestTable1` (`TestColumn1` NVARCHAR(255) NOT NULL, `TestColumn2` INTEGER NOT NULL) ENGINE = INNODB");
}
[Test]
public void CanCreateTableWithDefaultSchema()
{
var expression = GeneratorTestHelper.GetCreateTableExpression();
var result = Generator.Generate(expression);
result.ShouldBe("CREATE TABLE `TestTable1` (`TestColumn1` NVARCHAR(255) NOT NULL, `TestColumn2` INTEGER NOT NULL) ENGINE = INNODB");
}
[Test]
public void CanCreateTableWithDefaultValueExplicitlySetToNullWithCustomSchema()
{
var expression = GeneratorTestHelper.GetCreateTableWithDefaultValue();
expression.Columns[0].DefaultValue = null;
expression.Columns[0].TableName = expression.TableName;
expression.SchemaName = "TestSchema";
var result = Generator.Generate(expression);
result.ShouldBe("CREATE TABLE `TestTable1` (`TestColumn1` NVARCHAR(255) NOT NULL DEFAULT NULL, `TestColumn2` INTEGER NOT NULL DEFAULT 0) ENGINE = INNODB");
}
[Test]
public void CanCreateTableWithDefaultValueExplicitlySetToNullWithDefaultSchema()
{
var expression = GeneratorTestHelper.GetCreateTableWithDefaultValue();
expression.Columns[0].DefaultValue = null;
expression.Columns[0].TableName = expression.TableName;
var result = Generator.Generate(expression);
result.ShouldBe("CREATE TABLE `TestTable1` (`TestColumn1` NVARCHAR(255) NOT NULL DEFAULT NULL, `TestColumn2` INTEGER NOT NULL DEFAULT 0) ENGINE = INNODB");
}
[Test]
public void CanCreateTableWithDefaultValueWithCustomSchema()
{
var expression = GeneratorTestHelper.GetCreateTableWithDefaultValue();
expression.SchemaName = "TestSchema";
var result = Generator.Generate(expression);
result.ShouldBe("CREATE TABLE `TestTable1` (`TestColumn1` NVARCHAR(255) NOT NULL DEFAULT 'Default', `TestColumn2` INTEGER NOT NULL DEFAULT 0) ENGINE = INNODB");
}
[Test]
public void CanCreateTableWithDefaultValueWithDefaultSchema()
{
var expression = GeneratorTestHelper.GetCreateTableWithDefaultValue();
var result = Generator.Generate(expression);
result.ShouldBe("CREATE TABLE `TestTable1` (`TestColumn1` NVARCHAR(255) NOT NULL DEFAULT 'Default', `TestColumn2` INTEGER NOT NULL DEFAULT 0) ENGINE = INNODB");
}
[Test]
public void CanCreateTableWithMultiColumnPrimaryKeyWithCustomSchema()
{
var expression = GeneratorTestHelper.GetCreateTableWithMultiColumnPrimaryKeyExpression();
expression.SchemaName = "TestSchema";
var result = Generator.Generate(expression);
result.ShouldBe("CREATE TABLE `TestTable1` (`TestColumn1` NVARCHAR(255) NOT NULL, `TestColumn2` INTEGER NOT NULL, PRIMARY KEY (`TestColumn1`, `TestColumn2`)) ENGINE = INNODB");
}
[Test]
public void CanCreateTableWithMultiColumnPrimaryKeyWithDefaultSchema()
{
var expression = GeneratorTestHelper.GetCreateTableWithMultiColumnPrimaryKeyExpression();
var result = Generator.Generate(expression);
result.ShouldBe("CREATE TABLE `TestTable1` (`TestColumn1` NVARCHAR(255) NOT NULL, `TestColumn2` INTEGER NOT NULL, PRIMARY KEY (`TestColumn1`, `TestColumn2`)) ENGINE = INNODB");
}
[Test]
public void CanCreateTableWithNamedMultiColumnPrimaryKeyWithCustomSchema()
{
var expression = GeneratorTestHelper.GetCreateTableWithNamedMultiColumnPrimaryKeyExpression();
expression.SchemaName = "TestSchema";
var result = Generator.Generate(expression);
result.ShouldBe("CREATE TABLE `TestTable1` (`TestColumn1` NVARCHAR(255) NOT NULL, `TestColumn2` INTEGER NOT NULL, CONSTRAINT `TestKey` PRIMARY KEY (`TestColumn1`, `TestColumn2`)) ENGINE = INNODB");
}
[Test]
public void CanCreateTableWithNamedMultiColumnPrimaryKeyWithDefaultSchema()
{
var expression = GeneratorTestHelper.GetCreateTableWithNamedMultiColumnPrimaryKeyExpression();
var result = Generator.Generate(expression);
result.ShouldBe("CREATE TABLE `TestTable1` (`TestColumn1` NVARCHAR(255) NOT NULL, `TestColumn2` INTEGER NOT NULL, CONSTRAINT `TestKey` PRIMARY KEY (`TestColumn1`, `TestColumn2`)) ENGINE = INNODB");
}
[Test]
public void CanCreateTableWithNamedPrimaryKeyWithCustomSchema()
{
var expression = GeneratorTestHelper.GetCreateTableWithNamedPrimaryKeyExpression();
expression.SchemaName = "TestSchema";
var result = Generator.Generate(expression);
result.ShouldBe("CREATE TABLE `TestTable1` (`TestColumn1` NVARCHAR(255) NOT NULL, `TestColumn2` INTEGER NOT NULL, CONSTRAINT `TestKey` PRIMARY KEY (`TestColumn1`)) ENGINE = INNODB");
}
[Test]
public void CanCreateTableWithNamedPrimaryKeyWithDefaultSchema()
{
var expression = GeneratorTestHelper.GetCreateTableWithNamedPrimaryKeyExpression();
var result = Generator.Generate(expression);
result.ShouldBe("CREATE TABLE `TestTable1` (`TestColumn1` NVARCHAR(255) NOT NULL, `TestColumn2` INTEGER NOT NULL, CONSTRAINT `TestKey` PRIMARY KEY (`TestColumn1`)) ENGINE = INNODB");
}
[Test]
public void CanCreateTableWithNullableFieldWithCustomSchema()
{
var expression = GeneratorTestHelper.GetCreateTableExpression();
expression.Columns[0].IsNullable = true;
expression.SchemaName = "TestSchema";
var result = Generator.Generate(expression);
result.ShouldBe("CREATE TABLE `TestTable1` (`TestColumn1` NVARCHAR(255), `TestColumn2` INTEGER NOT NULL) ENGINE = INNODB");
}
[Test]
public void CanCreateTableWithNullableFieldWithDefaultSchema()
{
var expression = GeneratorTestHelper.GetCreateTableExpression();
expression.Columns[0].IsNullable = true;
var result = Generator.Generate(expression);
result.ShouldBe("CREATE TABLE `TestTable1` (`TestColumn1` NVARCHAR(255), `TestColumn2` INTEGER NOT NULL) ENGINE = INNODB");
}
[Test]
public void CanCreateTableWithPrimaryKeyWithCustomSchema()
{
var expression = GeneratorTestHelper.GetCreateTableWithPrimaryKeyExpression();
expression.SchemaName = "TestSchema";
var result = Generator.Generate(expression);
result.ShouldBe("CREATE TABLE `TestTable1` (`TestColumn1` NVARCHAR(255) NOT NULL, `TestColumn2` INTEGER NOT NULL, PRIMARY KEY (`TestColumn1`)) ENGINE = INNODB");
}
[Test]
public void CanCreateTableWithPrimaryKeyWithDefaultSchema()
{
var expression = GeneratorTestHelper.GetCreateTableWithPrimaryKeyExpression();
var result = Generator.Generate(expression);
result.ShouldBe("CREATE TABLE `TestTable1` (`TestColumn1` NVARCHAR(255) NOT NULL, `TestColumn2` INTEGER NOT NULL, PRIMARY KEY (`TestColumn1`)) ENGINE = INNODB");
}
[Test]
public void CanCreateTableWithDescriptionAndColumnDescriptions()
{
var expression = GeneratorTestHelper.GetCreateTableWithTableDescriptionAndColumnDescriptions();
var result = Generator.Generate(expression);
result.ShouldBe("CREATE TABLE `TestTable1` (`TestColumn1` NVARCHAR(255) COMMENT 'TestColumn1Description', `TestColumn2` INTEGER NOT NULL COMMENT 'TestColumn2Description') COMMENT 'TestDescription' ENGINE = INNODB");
}
}
}
| |
#region Usings
using System;
using System.IO;
using System.Collections.Generic;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Rhovlyn.Engine.Util;
using Rhovlyn.Engine.Managers;
#endregion
namespace Rhovlyn.Engine.Maps
{
public class Map
{
private Dictionary< Point , MapObject > mapobjects;
public static readonly int TILE_WIDTH = 64;
public static readonly int TILE_HEIGHT = 64;
public Color Background { get; set; }
public Rectangle MapArea { get { return mapArea; } }
public AreaMap<MapObject> AreaMap { get { return this.areamap; } }
private Rectangle mapArea;
protected AreaMap<MapObject> areamap;
protected MapObject[] lastTiles;
protected Rectangle lastCamera = Rectangle.Empty;
private bool ReqestAreaMapUpdate { get; set; }
private bool ReqestDrawMapUpdate { get; set; }
#region Constructor
public Map(string path, TextureManager textures)
{
areamap = new AreaMap<MapObject>();
mapobjects = new Dictionary<Point, MapObject>();
lastTiles = new MapObject[0];
this.Load(path, textures);
}
public Map()
{
areamap = new AreaMap<MapObject>();
lastTiles = new MapObject[0];
mapobjects = new Dictionary<Point, MapObject>();
}
~Map()
{
this.mapobjects.Clear();
}
#endregion
#region Methods
/// <summary>
/// Load map from a stream, does not override current Map
/// </summary>
/// <param name="stream">Stream.</param>
public bool Load(Stream stream, TextureManager textures)
{
mapArea = Rectangle.Empty;
using (var reader = new StreamReader(stream))
{
try
{
while (!reader.EndOfStream)
{
var line = reader.ReadLine();
if (line.IndexOf("#") != -1)
line = line.Substring(0, line.IndexOf("#"));
line.Trim();
if (string.IsNullOrEmpty(line))
continue;
//Loads Texture File
if (line.StartsWith("@"))
{
line = line.Substring(1);
//Load a Texture list
if (line.StartsWith("include:"))
{
var obj = line.Substring("include:".Length);
textures.Load(IO.Path.ResolvePath(obj));
}
/* TODO: Alternate Method to load a Sprite list for a Map
// Load a sprite list
if (line.StartsWith("sprites:"))
{
var obj = line.Substring("sprites:".Length);
Sprites.Load(IO.Path.ResolvePath(obj), Textures);
}
*/
//Hard check for a texture
if (line.StartsWith("require:"))
{
var obj = line.Substring("require:".Length);
foreach (var tex in obj.Split(','))
{
if (!textures.Exists(tex))
{
//TODO : Make a exception class for this
throw new Exception("Failed to meet the require texture " + tex);
}
}
}
if (line.StartsWith("background:"))
{
Background = Parser.Parse<Color>(line.Substring("background:".Length));
}
}
else if (line.StartsWith("<") && line.EndsWith(">"))
{
continue;
}
else
{
//Load a Map object
// Example x,y,Texture Name[,Texture Index]
// Eg. 0,0,wood
// Creates an object at 0,0 with texture "wood"
var args = line.Split(',');
if (args.Length < 3)
continue;
int x = int.Parse(args[0]);
int y = int.Parse(args[1]);
var tex = args[2];
//Check if Texture index is defined
if (args.Length > 3)
{
var obj = new MapObject(new Vector2(x * TILE_WIDTH, y * TILE_HEIGHT), textures[tex]);
int index = int.Parse(args[3]);
obj.Frameindex = index;
this.Add(new Point(x, y), obj);
this.areamap.Add(obj);
}
else
{
var obj = new MapObject(new Vector2(x * TILE_WIDTH, y * TILE_HEIGHT), textures[tex]);
this.Add(new Point(x, y), obj);
this.areamap.Add(obj);
}
}
}
}
catch (IOException ex)
{
Console.WriteLine(ex);
return false;
}
}
return true;
}
public bool Save(string filepath, int blocksize = 8)
{
List<string> required = new List<string>();
this.UpdateAreaMap(true);
int rect_width = blocksize * TILE_WIDTH;
int rect_height = blocksize * TILE_HEIGHT;
int counter = 0;
using (StreamWriter writer = new StreamWriter(new FileStream(filepath, FileMode.Create)))
{
writer.WriteLine(String.Format("@background:{0},{1},{2}",
new Object[] { this.Background.R, this.Background.G, this.Background.B }));
for (int x = this.MapArea.Left; x < this.MapArea.Right; x += rect_width)
{
for (int y = this.MapArea.Top; y < this.MapArea.Bottom; y += rect_height)
{
var area = new Rectangle(x, y, rect_width, rect_height);
var objs = this.areamap.Get(area);
if (objs.Length == 0)
continue;
writer.WriteLine(String.Format("<{0},{1},{2},{3}>",
new Object[] { area.X, area.Y, area.Width, area.Height }));
foreach (var obj in objs)
{
// x,y,Texture Name[,Texture Index]
writer.WriteLine(String.Format("{0},{1},{2},{3}",
new Object[] { obj.Position.X / TILE_WIDTH, obj.Position.Y / TILE_HEIGHT, obj.SpriteMap.Texture.Name, obj.Frameindex }));
counter++;
if (!required.Contains(obj.TextureName))
required.Add(obj.TextureName);
}
}
}
writer.Flush();
}
Console.WriteLine("Wrote " + counter + " out of " + this.mapobjects.Count);
return true;
}
/// <summary>
/// Add the given Map Object to the map
/// </summary>
/// <param name="pt">Point.</param>
/// <param name="obj">Object.</param>
public bool Add(Point pt, MapObject obj)
{
if (mapobjects.ContainsKey(pt))
return false;
this.mapobjects.Add(pt, obj);
if (!this.MapArea.Contains(obj.Area))
{
ReqestAreaMapUpdate = true;
}
areamap.Add(obj);
return true;
}
/// <summary>
/// Load a map from a file
/// </summary>
/// <remark>
/// Does clear current map.
/// </remark>
/// <param name="path">Path.</param>
public bool Load(string path, TextureManager textures)
{
return this.Load(IO.Path.ResolvePath(path), textures);
}
/// <summary>
/// Unload all Map Tiles in an area
/// </summary>
/// <param name="area">Area.</param>
public void Unload(Rectangle area)
{
foreach (var t in PointsUnderArea(area))
{
this.mapobjects.Remove(t);
}
ReqestAreaMapUpdate = true;
}
/// <summary>
/// Draw the Map
/// </summary>
/// <param name="gameTime">Game time</param>
/// <param name="spriteBatch">Sprite batch to draw to</param>
/// <param name="camera">Camera of the map</param>
public virtual void Draw(GameTime gameTime, SpriteBatch spriteBatch, Camera camera)
{
UpdateCamera(camera);
foreach (var obj in lastTiles)
{
obj.Draw(gameTime, spriteBatch, camera);
}
#if RENDER_AREAMAP
areamap.Draw(spriteBatch, camera);
#endif
}
public virtual void Update(GameTime gameTime)
{
if (ReqestAreaMapUpdate)
{
this.UpdateAreaMap(true);
ReqestAreaMapUpdate = false;
}
foreach (var obj in lastTiles)
{
obj.Update(gameTime);
}
}
public void UpdateCamera(Camera camera)
{
if (lastCamera != NormaliseRect(camera.Bounds) || this.ReqestDrawMapUpdate)
{
lastTiles = areamap.Get(camera.Bounds);
lastCamera = camera.Bounds;
this.ReqestDrawMapUpdate = false;
}
}
/// <summary>
/// Updates the bounds of the map
/// </summary>
public void UpdateAreaOfMap()
{
mapArea = Rectangle.Empty;
foreach (var obj in mapobjects.Values)
{
mapArea = Rectangle.Union(MapArea, obj.Area);
}
}
/// <summary>
/// Updates the Area Map object.
/// </summary>
/// <remark>
/// Should be used after editting the Map objects
/// </remark>
public void UpdateAreaMap(bool UpdateAreaOfMap = true)
{
if (UpdateAreaOfMap)
this.UpdateAreaOfMap();
areamap = new AreaMap<MapObject>(this.MapArea);
foreach (var obj in mapobjects.Values)
{
if (!areamap.Add(obj))
{
throw new Exception("Didn't add object");
}
}
this.ReqestDrawMapUpdate = true;
}
/// <summary>
/// Get all Map Objects in the Area
/// </summary>
/// <returns>The Map Objects in the area</returns>
/// <param name="area">Area</param>
public MapObject[] TilesInArea(Rectangle area)
{
List<MapObject> output = new List<MapObject>();
foreach (var pt in PointsUnderArea(area))
{
if (mapobjects.ContainsKey(pt))
{
output.Add(mapobjects[pt]);
}
}
return output.ToArray();
}
/// <summary>
/// Determines if the given area in completely on the map
/// </summary>
/// <returns><c>true</c> if area give is completely on the map ; otherwise, <c>false</c>.</returns>
/// <param name="area">Area to check</param>
public bool IsOnMap(Rectangle area)
{
foreach (var pt in PointsUnderArea(area))
{
if (!mapobjects.ContainsKey(pt))
{
return false;
}
}
return true;
}
public static Rectangle NormaliseRect(Rectangle input)
{
var ax = (float)input.X / (float)TILE_WIDTH;
var ay = (float)input.Y / (float)TILE_HEIGHT;
var aw = Math.Ceiling((float)input.Width / (float)TILE_WIDTH + ax);
var ah = Math.Ceiling((float)input.Height / (float)TILE_HEIGHT + ay);
ax = (float)Math.Floor(ax);
ay = (float)Math.Floor(ay);
return new Rectangle((int)ax, (int)ay, (int)aw, (int)ah);
}
/// <summary>
/// Get all of the Map Points in the given area
/// </summary>
/// <returns>The Map Points in the given area</returns>
/// <param name="area">Area</param>
public static Point[] PointsUnderArea(Rectangle area)
{
List<Point> output = new List<Point>();
//Get the X,Y,W,H in terms of Map Objects
double ax = (double)area.X / (double)TILE_WIDTH;
double ay = (double)area.Y / (double)TILE_HEIGHT;
double aw = Math.Ceiling((double)area.Width / (double)TILE_WIDTH + ax);
double ah = Math.Ceiling((double)area.Height / (double)TILE_HEIGHT + ay);
ax = Math.Floor(ax);
ay = Math.Floor(ay);
for (double x = ax; x < aw; x++)
{
for (double y = ay; y < ah; y++)
{
var pt = new Point((int)x, (int)y);
if (!output.Contains(pt))
output.Add(pt);
}
}
return output.ToArray();
}
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.Common;
using System.Diagnostics;
using System.Globalization;
using System.Runtime.Serialization;
using System.Security.Permissions;
using System.Text;
namespace System.Data.Odbc
{
[DefaultProperty("Driver")]
[System.ComponentModel.TypeConverterAttribute(typeof(OdbcConnectionStringBuilder.OdbcConnectionStringBuilderConverter))]
public sealed class OdbcConnectionStringBuilder : DbConnectionStringBuilder
{
private enum Keywords
{ // must maintain same ordering as _validKeywords array
// NamedConnection,
Dsn,
Driver,
}
private static readonly string[] s_validKeywords;
private static readonly Dictionary<string, Keywords> s_keywords;
private string[] _knownKeywords;
private string _dsn = DbConnectionStringDefaults.Dsn;
// private string _namedConnection = DbConnectionStringDefaults.NamedConnection;
private string _driver = DbConnectionStringDefaults.Driver;
static OdbcConnectionStringBuilder()
{
string[] validKeywords = new string[2];
validKeywords[(int)Keywords.Driver] = DbConnectionStringKeywords.Driver;
validKeywords[(int)Keywords.Dsn] = DbConnectionStringKeywords.Dsn;
// validKeywords[(int)Keywords.NamedConnection] = DbConnectionStringKeywords.NamedConnection;
s_validKeywords = validKeywords;
Dictionary<string, Keywords> hash = new Dictionary<string, Keywords>(2, StringComparer.OrdinalIgnoreCase);
hash.Add(DbConnectionStringKeywords.Driver, Keywords.Driver);
hash.Add(DbConnectionStringKeywords.Dsn, Keywords.Dsn);
// hash.Add(DbConnectionStringKeywords.NamedConnection, Keywords.NamedConnection);
Debug.Assert(2 == hash.Count, "initial expected size is incorrect");
s_keywords = hash;
}
public OdbcConnectionStringBuilder() : this((string)null)
{
}
public OdbcConnectionStringBuilder(string connectionString) : base(true)
{
if (!ADP.IsEmpty(connectionString))
{
ConnectionString = connectionString;
}
}
public override object this[string keyword]
{
get
{
ADP.CheckArgumentNull(keyword, "keyword");
Keywords index;
if (s_keywords.TryGetValue(keyword, out index))
{
return GetAt(index);
}
else
{
return base[keyword];
}
}
set
{
ADP.CheckArgumentNull(keyword, "keyword");
if (null != value)
{
Keywords index;
if (s_keywords.TryGetValue(keyword, out index))
{
switch (index)
{
case Keywords.Driver: Driver = ConvertToString(value); break;
case Keywords.Dsn: Dsn = ConvertToString(value); break;
// case Keywords.NamedConnection: NamedConnection = ConvertToString(value); break;
default:
Debug.Assert(false, "unexpected keyword");
throw ADP.KeywordNotSupported(keyword);
}
}
else
{
base[keyword] = value;
ClearPropertyDescriptors();
_knownKeywords = null;
}
}
else
{
Remove(keyword);
}
}
}
[DisplayName(DbConnectionStringKeywords.Driver)]
[ResCategoryAttribute(Res.DataCategory_Source)]
[ResDescriptionAttribute(Res.DbConnectionString_Driver)]
[RefreshPropertiesAttribute(RefreshProperties.All)]
public string Driver
{
get { return _driver; }
set
{
SetValue(DbConnectionStringKeywords.Driver, value);
_driver = value;
}
}
[DisplayName(DbConnectionStringKeywords.Dsn)]
[ResCategoryAttribute(Res.DataCategory_NamedConnectionString)]
[ResDescriptionAttribute(Res.DbConnectionString_DSN)]
[RefreshPropertiesAttribute(RefreshProperties.All)]
public string Dsn
{
get { return _dsn; }
set
{
SetValue(DbConnectionStringKeywords.Dsn, value);
_dsn = value;
}
}
/*
[DisplayName(DbConnectionStringKeywords.NamedConnection)]
[ResCategoryAttribute(Res.DataCategory_NamedConnectionString)]
[ResDescriptionAttribute(Res.DbConnectionString_NamedConnection)]
[RefreshPropertiesAttribute(RefreshProperties.All)]
[TypeConverter(typeof(NamedConnectionStringConverter))]
public string NamedConnection {
get { return _namedConnection; }
set {
SetValue(DbConnectionStringKeywords.NamedConnection, value);
_namedConnection = value;
}
}
*/
public override ICollection Keys
{
get
{
string[] knownKeywords = _knownKeywords;
if (null == knownKeywords)
{
knownKeywords = s_validKeywords;
int count = 0;
foreach (string keyword in base.Keys)
{
bool flag = true;
foreach (string s in knownKeywords)
{
if (s == keyword)
{
flag = false;
break;
}
}
if (flag)
{
count++;
}
}
if (0 < count)
{
string[] tmp = new string[knownKeywords.Length + count];
knownKeywords.CopyTo(tmp, 0);
int index = knownKeywords.Length;
foreach (string keyword in base.Keys)
{
bool flag = true;
foreach (string s in knownKeywords)
{
if (s == keyword)
{
flag = false;
break;
}
}
if (flag)
{
tmp[index++] = keyword;
}
}
knownKeywords = tmp;
}
_knownKeywords = knownKeywords;
}
return new System.Data.Common.ReadOnlyCollection<string>(knownKeywords);
}
}
public override void Clear()
{
base.Clear();
for (int i = 0; i < s_validKeywords.Length; ++i)
{
Reset((Keywords)i);
}
_knownKeywords = s_validKeywords;
}
public override bool ContainsKey(string keyword)
{
ADP.CheckArgumentNull(keyword, "keyword");
return s_keywords.ContainsKey(keyword) || base.ContainsKey(keyword);
}
private static string ConvertToString(object value)
{
return DbConnectionStringBuilderUtil.ConvertToString(value);
}
private object GetAt(Keywords index)
{
switch (index)
{
case Keywords.Driver: return Driver;
case Keywords.Dsn: return Dsn;
// case Keywords.NamedConnection: return NamedConnection;
default:
Debug.Assert(false, "unexpected keyword");
throw ADP.KeywordNotSupported(s_validKeywords[(int)index]);
}
}
/*
protected override void GetProperties(Hashtable propertyDescriptors) {
object value;
if (TryGetValue(DbConnectionStringSynonyms.TRUSTEDCONNECTION, out value)) {
bool trusted = false;
if (value is bool) {
trusted = (bool)value;
}
else if ((value is string) && !Boolean.TryParse((string)value, out trusted)) {
trusted = false;
}
if (trusted) {
Attribute[] attributes = new Attribute[] {
BrowsableAttribute.Yes,
RefreshPropertiesAttribute.All,
};
DbConnectionStringBuilderDescriptor descriptor;
descriptor = new DbConnectionStringBuilderDescriptor(DbConnectionStringSynonyms.TRUSTEDCONNECTION,
this.GetType(), typeof(bool), false, attributes);
descriptor.RefreshOnChange = true;
propertyDescriptors[DbConnectionStringSynonyms.TRUSTEDCONNECTION] = descriptor;
if (ContainsKey(DbConnectionStringSynonyms.Pwd)) {
descriptor = new DbConnectionStringBuilderDescriptor(DbConnectionStringSynonyms.Pwd,
this.GetType(), typeof(string), true, attributes);
propertyDescriptors[DbConnectionStringSynonyms.Pwd] = descriptor;
}
if (ContainsKey(DbConnectionStringSynonyms.UID)) {
descriptor = new DbConnectionStringBuilderDescriptor(DbConnectionStringSynonyms.UID,
this.GetType(), typeof(string), true, attributes);
propertyDescriptors[DbConnectionStringSynonyms.UID] = descriptor;
}
}
}
base.GetProperties(propertyDescriptors);
}
*/
public override bool Remove(string keyword)
{
ADP.CheckArgumentNull(keyword, "keyword");
if (base.Remove(keyword))
{
Keywords index;
if (s_keywords.TryGetValue(keyword, out index))
{
Reset(index);
}
else
{
ClearPropertyDescriptors();
_knownKeywords = null;
}
return true;
}
return false;
}
private void Reset(Keywords index)
{
switch (index)
{
case Keywords.Driver:
_driver = DbConnectionStringDefaults.Driver;
break;
case Keywords.Dsn:
_dsn = DbConnectionStringDefaults.Dsn;
break;
// case Keywords.NamedConnection:
// _namedConnection = DbConnectionStringDefaults.NamedConnection;
// break;
default:
Debug.Assert(false, "unexpected keyword");
throw ADP.KeywordNotSupported(s_validKeywords[(int)index]);
}
}
private void SetValue(string keyword, string value)
{
ADP.CheckArgumentNull(value, keyword);
base[keyword] = value;
}
public override bool TryGetValue(string keyword, out object value)
{
ADP.CheckArgumentNull(keyword, "keyword");
Keywords index;
if (s_keywords.TryGetValue(keyword, out index))
{
value = GetAt(index);
return true;
}
return base.TryGetValue(keyword, out value);
}
internal sealed class OdbcConnectionStringBuilderConverter : ExpandableObjectConverter
{
// converter classes should have public ctor
public OdbcConnectionStringBuilderConverter()
{
}
override public bool CanConvertTo(ITypeDescriptorContext context, Type destinationType)
{
if (typeof(System.ComponentModel.Design.Serialization.InstanceDescriptor) == destinationType)
{
return true;
}
return base.CanConvertTo(context, destinationType);
}
override public object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType)
{
if (destinationType == null)
{
throw ADP.ArgumentNull("destinationType");
}
if (typeof(System.ComponentModel.Design.Serialization.InstanceDescriptor) == destinationType)
{
OdbcConnectionStringBuilder obj = (value as OdbcConnectionStringBuilder);
if (null != obj)
{
return ConvertToInstanceDescriptor(obj);
}
}
return base.ConvertTo(context, culture, value, destinationType);
}
private System.ComponentModel.Design.Serialization.InstanceDescriptor ConvertToInstanceDescriptor(OdbcConnectionStringBuilder options)
{
Type[] ctorParams = new Type[] { typeof(string) };
object[] ctorValues = new object[] { options.ConnectionString };
System.Reflection.ConstructorInfo ctor = typeof(OdbcConnectionStringBuilder).GetConstructor(ctorParams);
return new System.ComponentModel.Design.Serialization.InstanceDescriptor(ctor, ctorValues);
}
}
}
}
| |
using System;
using System.Linq;
using System.ComponentModel.DataAnnotations;
using Csla;
using System.ComponentModel;
using System.Threading.Tasks;
namespace ProjectTracker.Library
{
[Serializable()]
public class ResourceEdit : CslaBaseTypes.BusinessBase<ResourceEdit>
{
public static readonly PropertyInfo<byte[]> TimeStampProperty = RegisterProperty<byte[]>(c => c.TimeStamp);
[Browsable(false)]
[EditorBrowsable(EditorBrowsableState.Never)]
public byte[] TimeStamp
{
get { return GetProperty(TimeStampProperty); }
set { SetProperty(TimeStampProperty, value); }
}
public static readonly PropertyInfo<int> IdProperty = RegisterProperty<int>(c => c.Id);
[Display(Name = "Resource id")]
public int Id
{
get { return GetProperty(IdProperty); }
set { SetProperty(IdProperty, value); }
}
public static readonly PropertyInfo<string> LastNameProperty =
RegisterProperty<string>(c => c.LastName);
[Display(Name = "Last name")]
[Required]
[StringLength(50)]
public string LastName
{
get { return GetProperty(LastNameProperty); }
set { SetProperty(LastNameProperty, value); }
}
public static readonly PropertyInfo<string> FirstNameProperty =
RegisterProperty<string>(c => c.FirstName);
[Display(Name = "First name")]
[Required]
[StringLength(50)]
public string FirstName
{
get { return GetProperty(FirstNameProperty); }
set { SetProperty(FirstNameProperty, value); }
}
[Display(Name = "Full name")]
public string FullName
{
get { return LastName + ", " + FirstName; }
}
public static readonly PropertyInfo<ResourceAssignments> AssignmentsProperty =
RegisterProperty<ResourceAssignments>(c => c.Assignments, RelationshipTypes.Child);
public ResourceAssignments Assignments
{
get { return GetProperty(AssignmentsProperty); }
private set { LoadProperty(AssignmentsProperty, value); }
}
public override string ToString()
{
return Id.ToString();
}
protected override void AddBusinessRules()
{
base.AddBusinessRules();
BusinessRules.AddRule(new Csla.Rules.CommonRules.IsInRole(Csla.Rules.AuthorizationActions.WriteProperty, LastNameProperty, "ProjectManager"));
BusinessRules.AddRule(new Csla.Rules.CommonRules.IsInRole(Csla.Rules.AuthorizationActions.WriteProperty, FirstNameProperty, "ProjectManager"));
BusinessRules.AddRule(new NoDuplicateProject { PrimaryProperty = AssignmentsProperty });
}
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public static void AddObjectAuthorizationRules()
{
Csla.Rules.BusinessRules.AddRule(typeof(ResourceEdit), new Csla.Rules.CommonRules.IsInRole(Csla.Rules.AuthorizationActions.CreateObject, "ProjectManager"));
Csla.Rules.BusinessRules.AddRule(typeof(ResourceEdit), new Csla.Rules.CommonRules.IsInRole(Csla.Rules.AuthorizationActions.EditObject, "ProjectManager"));
Csla.Rules.BusinessRules.AddRule(typeof(ResourceEdit), new Csla.Rules.CommonRules.IsInRole(Csla.Rules.AuthorizationActions.DeleteObject, "ProjectManager", "Administrator"));
}
protected override void OnChildChanged(Csla.Core.ChildChangedEventArgs e)
{
if (e.ChildObject is ResourceAssignments)
{
BusinessRules.CheckRules(AssignmentsProperty);
OnPropertyChanged(AssignmentsProperty);
}
base.OnChildChanged(e);
}
private class NoDuplicateProject : Csla.Rules.BusinessRule
{
protected override void Execute(Csla.Rules.IRuleContext context)
{
var target = (ResourceEdit)context.Target;
foreach (var item in target.Assignments)
{
var count = target.Assignments.Count(r => r.ProjectId == item.ProjectId);
if (count > 1)
{
context.AddErrorResult("Duplicate projects not allowed");
return;
}
}
}
}
public static async Task<ResourceEdit> NewResourceEditAsync()
{
return await DataPortal.CreateAsync<ResourceEdit>();
}
public static async Task<ResourceEdit> GetResourceEditAsync(int id)
{
return await DataPortal.FetchAsync<ResourceEdit>(id);
}
public static async Task<bool> ExistsAsync(int id)
{
var cmd = new ResourceExistsCommand(id);
cmd = await DataPortal.ExecuteAsync(cmd);
return cmd.ResourceExists;
}
public static void NewResourceEdit(EventHandler<DataPortalResult<ResourceEdit>> callback)
{
DataPortal.BeginCreate<ResourceEdit>(callback);
}
public static void GetResourceEdit(int id, EventHandler<DataPortalResult<ResourceEdit>> callback)
{
DataPortal.BeginFetch<ResourceEdit>(id, callback);
}
public static ResourceEdit NewResourceEdit()
{
return DataPortal.Create<ResourceEdit>();
}
public static ResourceEdit GetResourceEdit(int id)
{
return DataPortal.Fetch<ResourceEdit>(id);
}
public static void DeleteResourceEdit(int id)
{
DataPortal.Delete<ResourceEdit>(id);
}
public static bool Exists(int id)
{
var cmd = new ResourceExistsCommand(id);
cmd = DataPortal.Execute(cmd);
return cmd.ResourceExists;
}
[RunLocal]
protected override void DataPortal_Create()
{
LoadProperty(AssignmentsProperty, DataPortal.CreateChild<ResourceAssignments>());
base.DataPortal_Create();
}
private void DataPortal_Fetch(int id)
{
using (var ctx = ProjectTracker.Dal.DalFactory.GetManager())
{
var dal = ctx.GetProvider<ProjectTracker.Dal.IResourceDal>();
var data = dal.Fetch(id);
using (BypassPropertyChecks)
{
Id = data.Id;
FirstName = data.FirstName;
LastName = data.LastName;
TimeStamp = data.LastChanged;
Assignments = DataPortal.FetchChild<ResourceAssignments>(id);
}
}
}
protected override void DataPortal_Insert()
{
using (var ctx = ProjectTracker.Dal.DalFactory.GetManager())
{
var dal = ctx.GetProvider<ProjectTracker.Dal.IResourceDal>();
using (BypassPropertyChecks)
{
var item = new ProjectTracker.Dal.ResourceDto
{
FirstName = this.FirstName,
LastName = this.LastName
};
dal.Insert(item);
Id = item.Id;
TimeStamp = item.LastChanged;
}
FieldManager.UpdateChildren(this);
}
}
protected override void DataPortal_Update()
{
using (var ctx = ProjectTracker.Dal.DalFactory.GetManager())
{
var dal = ctx.GetProvider<ProjectTracker.Dal.IResourceDal>();
using (BypassPropertyChecks)
{
var item = new ProjectTracker.Dal.ResourceDto
{
Id = this.Id,
FirstName = this.FirstName,
LastName = this.LastName,
LastChanged = this.TimeStamp
};
dal.Update(item);
TimeStamp = item.LastChanged;
}
FieldManager.UpdateChildren(this);
}
}
protected override void DataPortal_DeleteSelf()
{
using (BypassPropertyChecks)
DataPortal_Delete(this.Id);
}
private void DataPortal_Delete(int id)
{
using (var ctx = ProjectTracker.Dal.DalFactory.GetManager())
{
Assignments.Clear();
FieldManager.UpdateChildren(this);
var dal = ctx.GetProvider<ProjectTracker.Dal.IResourceDal>();
dal.Delete(id);
}
}
}
}
| |
using UnityEditor;
using UnityEngine;
using System.Collections.Generic;
[CanEditMultipleObjects]
[CustomEditor(typeof(tk2dTextMesh))]
class tk2dTextMeshEditor : Editor
{
tk2dGenericIndexItem[] allFonts = null; // all generators
string[] allFontNames = null;
Vector2 gradientScroll;
// Word wrap on text area - almost impossible to use otherwise
GUIStyle _textAreaStyle = null;
GUIStyle textAreaStyle
{
get {
if (_textAreaStyle == null)
{
_textAreaStyle = new GUIStyle(EditorStyles.textField);
_textAreaStyle.wordWrap = true;
}
return _textAreaStyle;
}
}
tk2dTextMesh[] targetTextMeshes = new tk2dTextMesh[0];
void OnEnable() {
targetTextMeshes = new tk2dTextMesh[targets.Length];
for (int i = 0; i < targets.Length; ++i) {
targetTextMeshes[i] = targets[i] as tk2dTextMesh;
}
}
void OnDestroy() {
tk2dEditorSkin.Done();
}
// Draws the word wrap GUI
void DrawWordWrapSceneGUI(tk2dTextMesh textMesh)
{
tk2dFontData font = textMesh.font;
Transform transform = textMesh.transform;
int px = textMesh.wordWrapWidth;
Vector3 p0 = transform.position;
float width = font.texelSize.x * px * transform.localScale.x;
bool drawRightHandle = true;
bool drawLeftHandle = false;
switch (textMesh.anchor)
{
case TextAnchor.LowerCenter: case TextAnchor.MiddleCenter: case TextAnchor.UpperCenter:
drawLeftHandle = true;
p0 -= width * 0.5f * transform.right;
break;
case TextAnchor.LowerRight: case TextAnchor.MiddleRight: case TextAnchor.UpperRight:
drawLeftHandle = true;
drawRightHandle = false;
p0 -= width * transform.right;
break;
}
Vector3 p1 = p0 + width * transform.right;
Handles.color = new Color32(255, 255, 255, 24);
float subPin = font.texelSize.y * 2048;
Handles.DrawLine(p0, p1);
Handles.DrawLine(p0 - subPin * transform.up, p0 + subPin * transform.up);
Handles.DrawLine(p1 - subPin * transform.up, p1 + subPin * transform.up);
Handles.color = Color.white;
Vector3 pin = transform.up * font.texelSize.y * 10.0f;
Handles.DrawLine(p0 - pin, p0 + pin);
Handles.DrawLine(p1 - pin, p1 + pin);
if (drawRightHandle)
{
Vector3 newp1 = Handles.Slider(p1, transform.right, HandleUtility.GetHandleSize(p1), Handles.ArrowCap, 0.0f);
if (newp1 != p1)
{
Undo.RegisterUndo(textMesh, "TextMesh Wrap Length");
int newPx = (int)Mathf.Round((newp1 - p0).magnitude / (font.texelSize.x * transform.localScale.x));
newPx = Mathf.Max(newPx, 0);
textMesh.wordWrapWidth = newPx;
textMesh.Commit();
}
}
if (drawLeftHandle)
{
Vector3 newp0 = Handles.Slider(p0, -transform.right, HandleUtility.GetHandleSize(p0), Handles.ArrowCap, 0.0f);
if (newp0 != p0)
{
Undo.RegisterUndo(textMesh, "TextMesh Wrap Length");
int newPx = (int)Mathf.Round((p1 - newp0).magnitude / (font.texelSize.x * transform.localScale.x));
newPx = Mathf.Max(newPx, 0);
textMesh.wordWrapWidth = newPx;
textMesh.Commit();
}
}
}
public void OnSceneGUI()
{
tk2dTextMesh textMesh = (tk2dTextMesh)target;
if (textMesh.formatting && textMesh.wordWrapWidth > 0)
{
DrawWordWrapSceneGUI(textMesh);
}
if (tk2dPreferences.inst.enableSpriteHandles == true) {
MeshFilter meshFilter = textMesh.GetComponent<MeshFilter>();
if (!meshFilter || meshFilter.sharedMesh == null) {
return;
}
Transform t = textMesh.transform;
Bounds b = meshFilter.sharedMesh.bounds;
Rect localRect = new Rect(b.min.x, b.min.y, b.size.x, b.size.y);
// Draw rect outline
Handles.color = new Color(1,1,1,0.5f);
tk2dSceneHelper.DrawRect (localRect, t);
Handles.BeginGUI ();
// Resize handles
if (tk2dSceneHelper.RectControlsToggle ()) {
EditorGUI.BeginChangeCheck ();
Rect resizeRect = tk2dSceneHelper.RectControl (132546, localRect, t);
if (EditorGUI.EndChangeCheck ()) {
Vector3 newScale = new Vector3 (textMesh.scale.x * (resizeRect.width / localRect.width),
textMesh.scale.y * (resizeRect.height / localRect.height));
float scaleMin = 0.001f;
if (textMesh.scale.x > 0.0f && newScale.x < scaleMin) newScale.x = scaleMin;
if (textMesh.scale.x < 0.0f && newScale.x > -scaleMin) newScale.x = -scaleMin;
if (textMesh.scale.y > 0.0f && newScale.y < scaleMin) newScale.y = scaleMin;
if (textMesh.scale.y < 0.0f && newScale.y > -scaleMin) newScale.y = -scaleMin;
if (newScale != textMesh.scale) {
Undo.RegisterUndo (new Object[] {t, textMesh}, "Resize");
float factorX = (Mathf.Abs (textMesh.scale.x) > Mathf.Epsilon) ? (newScale.x / textMesh.scale.x) : 0.0f;
float factorY = (Mathf.Abs (textMesh.scale.y) > Mathf.Epsilon) ? (newScale.y / textMesh.scale.y) : 0.0f;
Vector3 offset = new Vector3(resizeRect.xMin - localRect.xMin * factorX,
resizeRect.yMin - localRect.yMin * factorY, 0.0f);
Vector3 newPosition = t.TransformPoint (offset);
if (newPosition != t.position) {
t.position = newPosition;
}
textMesh.scale = newScale;
textMesh.Commit ();
EditorUtility.SetDirty(textMesh);
}
}
}
// Rotate handles
if (!tk2dSceneHelper.RectControlsToggle ()) {
EditorGUI.BeginChangeCheck();
float theta = tk2dSceneHelper.RectRotateControl (645231, localRect, t, new List<int>());
if (EditorGUI.EndChangeCheck()) {
Undo.RegisterUndo (t, "Rotate");
if (Mathf.Abs(theta) > Mathf.Epsilon) {
t.Rotate(t.forward, theta);
}
}
}
Handles.EndGUI ();
// Sprite selecting
tk2dSceneHelper.HandleSelectSprites();
// Move targeted sprites
tk2dSceneHelper.HandleMoveSprites(t, localRect);
}
}
void UndoableAction( System.Action<tk2dTextMesh> action ) {
Undo.RegisterUndo(targetTextMeshes, "Inspector");
foreach (tk2dTextMesh tm in targetTextMeshes) {
action(tm);
}
}
static bool showInlineStylingHelp = false;
public override void OnInspectorGUI()
{
tk2dTextMesh textMesh = (tk2dTextMesh)target;
EditorGUIUtility.LookLikeControls(80, 50);
// maybe cache this if its too slow later
if (allFonts == null || allFontNames == null)
{
tk2dGenericIndexItem[] indexFonts = tk2dEditorUtility.GetOrCreateIndex().GetFonts();
List<tk2dGenericIndexItem> filteredFonts = new List<tk2dGenericIndexItem>();
foreach (var f in indexFonts)
if (!f.managed) filteredFonts.Add(f);
allFonts = filteredFonts.ToArray();
allFontNames = new string[allFonts.Length];
for (int i = 0; i < allFonts.Length; ++i)
allFontNames[i] = allFonts[i].AssetName;
}
if (allFonts != null)
{
if (textMesh.font == null)
{
textMesh.font = allFonts[0].GetAsset<tk2dFont>().data;
}
int currId = -1;
string guid = AssetDatabase.AssetPathToGUID(AssetDatabase.GetAssetPath(textMesh.font));
for (int i = 0; i < allFonts.Length; ++i)
{
if (allFonts[i].dataGUID == guid)
{
currId = i;
}
}
int newId = EditorGUILayout.Popup("Font", currId, allFontNames);
if (newId != currId)
{
UndoableAction( tm => tm.font = allFonts[newId].GetAsset<tk2dFont>().data );
GUI.changed = true;
}
EditorGUILayout.BeginHorizontal();
int newMaxChars = Mathf.Clamp( EditorGUILayout.IntField("Max Chars", textMesh.maxChars), 1, 16000 );
if (newMaxChars != textMesh.maxChars) {
UndoableAction( tm => tm.maxChars = newMaxChars );
}
if (GUILayout.Button("Fit", GUILayout.MaxWidth(32.0f)))
{
UndoableAction( tm => tm.maxChars = tm.NumTotalCharacters() );
GUI.changed = true;
}
EditorGUILayout.EndHorizontal();
bool newFormatting = EditorGUILayout.BeginToggleGroup("Formatting", textMesh.formatting);
if (newFormatting != textMesh.formatting) {
UndoableAction( tm => tm.formatting = newFormatting );
GUI.changed = true;
}
GUILayout.BeginHorizontal();
++EditorGUI.indentLevel;
if (textMesh.wordWrapWidth == 0)
{
EditorGUILayout.PrefixLabel("Word Wrap");
if (GUILayout.Button("Enable", EditorStyles.miniButton, GUILayout.ExpandWidth(false)))
{
UndoableAction( tm => tm.wordWrapWidth = (tm.wordWrapWidth == 0) ? 500 : tm.wordWrapWidth );
GUI.changed = true;
}
}
else
{
int newWordWrapWidth = EditorGUILayout.IntField("Word Wrap", textMesh.wordWrapWidth);
if (newWordWrapWidth != textMesh.wordWrapWidth) {
UndoableAction( tm => tm.wordWrapWidth = newWordWrapWidth );
}
if (GUILayout.Button("Disable", EditorStyles.miniButton, GUILayout.ExpandWidth(false)))
{
UndoableAction( tm => tm.wordWrapWidth = 0 );
GUI.changed = true;
}
}
--EditorGUI.indentLevel;
GUILayout.EndHorizontal();
EditorGUILayout.EndToggleGroup();
GUILayout.BeginHorizontal ();
bool newInlineStyling = EditorGUILayout.Toggle("Inline Styling", textMesh.inlineStyling);
if (newInlineStyling != textMesh.inlineStyling) {
UndoableAction( tm => tm.inlineStyling = newInlineStyling );
}
if (textMesh.inlineStyling) {
showInlineStylingHelp = GUILayout.Toggle(showInlineStylingHelp, "?", EditorStyles.miniButton, GUILayout.ExpandWidth(false));
}
GUILayout.EndHorizontal ();
if (textMesh.inlineStyling && showInlineStylingHelp)
{
Color bg = GUI.backgroundColor;
GUI.backgroundColor = new Color32(154, 176, 203, 255);
string message = "Inline style commands\n\n" +
"^cRGBA - set color\n" +
"^gRGBARGBA - set top and bottom colors\n" +
" RGBA = single digit hex values (0 - f)\n\n" +
"^CRRGGBBAA - set color\n" +
"^GRRGGBBAARRGGBBAA - set top and bottom colors\n" +
" RRGGBBAA = 2 digit hex values (00 - ff)\n\n" +
((textMesh.font.textureGradients && textMesh.font.gradientCount > 0) ?
"^0-9 - select gradient\n" : "") +
"^^ - print ^";
tk2dGuiUtility.InfoBox( message, tk2dGuiUtility.WarningLevel.Info );
GUI.backgroundColor = bg;
}
GUILayout.BeginHorizontal();
EditorGUILayout.PrefixLabel("Text");
string newText = EditorGUILayout.TextArea(textMesh.text, textAreaStyle, GUILayout.Height(64));
if (newText != textMesh.text) {
UndoableAction( tm => tm.text = newText );
GUI.changed = true;
}
GUILayout.EndHorizontal();
TextAnchor newTextAnchor = (TextAnchor)EditorGUILayout.EnumPopup("Anchor", textMesh.anchor);
if (newTextAnchor != textMesh.anchor) UndoableAction( tm => tm.anchor = newTextAnchor );
bool newKerning = EditorGUILayout.Toggle("Kerning", textMesh.kerning);
if (newKerning != textMesh.kerning) UndoableAction( tm => tm.kerning = newKerning );
float newSpacing = EditorGUILayout.FloatField("Spacing", textMesh.Spacing);
if (newSpacing != textMesh.Spacing) UndoableAction( tm => tm.Spacing = newSpacing );
float newLineSpacing = EditorGUILayout.FloatField("Line Spacing", textMesh.LineSpacing);
if (newLineSpacing != textMesh.LineSpacing) UndoableAction( tm => tm.LineSpacing = newLineSpacing );
Vector3 newScale = EditorGUILayout.Vector3Field("Scale", textMesh.scale);
if (newScale != textMesh.scale) UndoableAction( tm => tm.scale = newScale );
if (textMesh.font.textureGradients && textMesh.font.gradientCount > 0)
{
GUILayout.BeginHorizontal();
EditorGUILayout.PrefixLabel("TextureGradient");
// Draw gradient scroller
bool drawGradientScroller = true;
if (drawGradientScroller)
{
textMesh.textureGradient = textMesh.textureGradient % textMesh.font.gradientCount;
gradientScroll = EditorGUILayout.BeginScrollView(gradientScroll, GUILayout.ExpandHeight(false));
Rect r = GUILayoutUtility.GetRect(textMesh.font.gradientTexture.width, textMesh.font.gradientTexture.height, GUILayout.ExpandWidth(false), GUILayout.ExpandHeight(false));
GUI.DrawTexture(r, textMesh.font.gradientTexture);
Rect hr = r;
hr.width /= textMesh.font.gradientCount;
hr.x += hr.width * textMesh.textureGradient;
float ox = hr.width / 8;
float oy = hr.height / 8;
Vector3[] rectVerts = { new Vector3(hr.x + 0.5f + ox, hr.y + oy, 0), new Vector3(hr.x + hr.width - ox, hr.y + oy, 0), new Vector3(hr.x + hr.width - ox, hr.y + hr.height - 0.5f - oy, 0), new Vector3(hr.x + ox, hr.y + hr.height - 0.5f - oy, 0) };
Handles.DrawSolidRectangleWithOutline(rectVerts, new Color(0,0,0,0.2f), new Color(0,0,0,1));
if (GUIUtility.hotControl == 0 && Event.current.type == EventType.MouseDown && r.Contains(Event.current.mousePosition))
{
int newTextureGradient = (int)(Event.current.mousePosition.x / (textMesh.font.gradientTexture.width / textMesh.font.gradientCount));
if (newTextureGradient != textMesh.textureGradient) {
UndoableAction( delegate(tk2dTextMesh tm) {
if (tm.useGUILayout && tm.font != null && newTextureGradient < tm.font.gradientCount) {
tm.textureGradient = newTextureGradient;
}
} );
}
GUI.changed = true;
}
EditorGUILayout.EndScrollView();
}
GUILayout.EndHorizontal();
}
EditorGUILayout.BeginHorizontal();
if (GUILayout.Button("HFlip"))
{
UndoableAction( delegate(tk2dTextMesh tm) {
Vector3 s = tm.scale;
s.x *= -1.0f;
tm.scale = s;
} );
GUI.changed = true;
}
if (GUILayout.Button("VFlip"))
{
UndoableAction( delegate(tk2dTextMesh tm) {
Vector3 s = tm.scale;
s.y *= -1.0f;
tm.scale = s;
} );
GUI.changed = true;
}
EditorGUILayout.EndHorizontal();
EditorGUILayout.BeginHorizontal();
if (GUILayout.Button("Bake Scale"))
{
Undo.RegisterSceneUndo("Bake Scale");
tk2dScaleUtility.Bake(textMesh.transform);
GUI.changed = true;
}
GUIContent pixelPerfectButton = new GUIContent("1:1", "Make Pixel Perfect");
if ( GUILayout.Button(pixelPerfectButton ))
{
if (tk2dPixelPerfectHelper.inst) tk2dPixelPerfectHelper.inst.Setup();
UndoableAction( tm => tm.MakePixelPerfect() );
GUI.changed = true;
}
EditorGUILayout.EndHorizontal();
if (textMesh.font && !textMesh.font.inst.isPacked)
{
bool newUseGradient = EditorGUILayout.Toggle("Use Gradient", textMesh.useGradient);
if (newUseGradient != textMesh.useGradient) {
UndoableAction( tm => tm.useGradient = newUseGradient );
}
if (textMesh.useGradient)
{
Color newColor = EditorGUILayout.ColorField("Top Color", textMesh.color);
if (newColor != textMesh.color) UndoableAction( tm => tm.color = newColor );
Color newColor2 = EditorGUILayout.ColorField("Bottom Color", textMesh.color2);
if (newColor2 != textMesh.color2) UndoableAction( tm => tm.color2 = newColor2 );
}
else
{
Color newColor = EditorGUILayout.ColorField("Color", textMesh.color);
if (newColor != textMesh.color) UndoableAction( tm => tm.color = newColor );
}
}
if (GUI.changed)
{
foreach (tk2dTextMesh tm in targetTextMeshes) {
tm.ForceBuild();
EditorUtility.SetDirty(tm);
}
}
}
}
[MenuItem("GameObject/Create Other/tk2d/TextMesh", false, 13905)]
static void DoCreateTextMesh()
{
tk2dFontData fontData = null;
// Find reference in scene
tk2dTextMesh dupeMesh = GameObject.FindObjectOfType(typeof(tk2dTextMesh)) as tk2dTextMesh;
if (dupeMesh)
fontData = dupeMesh.font;
// Find in library
if (fontData == null)
{
tk2dGenericIndexItem[] allFontEntries = tk2dEditorUtility.GetOrCreateIndex().GetFonts();
foreach (var v in allFontEntries)
{
if (v.managed) continue;
tk2dFontData data = v.GetData<tk2dFontData>();
if (data != null)
{
fontData = data;
break;
}
}
}
if (fontData == null)
{
EditorUtility.DisplayDialog("Create TextMesh", "Unable to create text mesh as no Fonts have been found.", "Ok");
return;
}
GameObject go = tk2dEditorUtility.CreateGameObjectInScene("TextMesh");
tk2dTextMesh textMesh = go.AddComponent<tk2dTextMesh>();
textMesh.font = fontData;
textMesh.text = "New TextMesh";
textMesh.Commit();
Selection.activeGameObject = go;
Undo.RegisterCreatedObjectUndo(go, "Create TextMesh");
}
}
| |
/*
* Copyright 2021 Google LLC All Rights Reserved.
* Use of this source code is governed by a BSD-style
* license that can be found in the LICENSE file or at
* https://developers.google.com/open-source/licenses/bsd
*/
// <auto-generated>
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/rpc/status.proto
// </auto-generated>
#pragma warning disable 1591, 0612, 3021
#region Designer generated code
using pb = global::Google.Protobuf;
using pbc = global::Google.Protobuf.Collections;
using pbr = global::Google.Protobuf.Reflection;
using scg = global::System.Collections.Generic;
namespace Google.Rpc {
/// <summary>Holder for reflection information generated from google/rpc/status.proto</summary>
public static partial class StatusReflection {
#region Descriptor
/// <summary>File descriptor for google/rpc/status.proto</summary>
public static pbr::FileDescriptor Descriptor {
get { return descriptor; }
}
private static pbr::FileDescriptor descriptor;
static StatusReflection() {
byte[] descriptorData = global::System.Convert.FromBase64String(
string.Concat(
"Chdnb29nbGUvcnBjL3N0YXR1cy5wcm90bxIKZ29vZ2xlLnJwYxoZZ29vZ2xl",
"L3Byb3RvYnVmL2FueS5wcm90byJOCgZTdGF0dXMSDAoEY29kZRgBIAEoBRIP",
"CgdtZXNzYWdlGAIgASgJEiUKB2RldGFpbHMYAyADKAsyFC5nb29nbGUucHJv",
"dG9idWYuQW55QmEKDmNvbS5nb29nbGUucnBjQgtTdGF0dXNQcm90b1ABWjdn",
"b29nbGUuZ29sYW5nLm9yZy9nZW5wcm90by9nb29nbGVhcGlzL3JwYy9zdGF0",
"dXM7c3RhdHVz+AEBogIDUlBDYgZwcm90bzM="));
descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData,
new pbr::FileDescriptor[] { global::Google.Protobuf.WellKnownTypes.AnyReflection.Descriptor, },
new pbr::GeneratedClrTypeInfo(null, null, new pbr::GeneratedClrTypeInfo[] {
new pbr::GeneratedClrTypeInfo(typeof(global::Google.Rpc.Status), global::Google.Rpc.Status.Parser, new[]{ "Code", "Message", "Details" }, null, null, null, null)
}));
}
#endregion
}
#region Messages
/// <summary>
/// The `Status` type defines a logical error model that is suitable for
/// different programming environments, including REST APIs and RPC APIs. It is
/// used by [gRPC](https://github.com/grpc). Each `Status` message contains
/// three pieces of data: error code, error message, and error details.
///
/// You can find out more about this error model and how to work with it in the
/// [API Design Guide](https://cloud.google.com/apis/design/errors).
/// </summary>
public sealed partial class Status : pb::IMessage<Status>
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
, pb::IBufferMessage
#endif
{
private static readonly pb::MessageParser<Status> _parser = new pb::MessageParser<Status>(() => new Status());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public static pb::MessageParser<Status> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public static pbr::MessageDescriptor Descriptor {
get { return global::Google.Rpc.StatusReflection.Descriptor.MessageTypes[0]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public Status() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public Status(Status other) : this() {
code_ = other.code_;
message_ = other.message_;
details_ = other.details_.Clone();
_unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public Status Clone() {
return new Status(this);
}
/// <summary>Field number for the "code" field.</summary>
public const int CodeFieldNumber = 1;
private int code_;
/// <summary>
/// The status code, which should be an enum value of [google.rpc.Code][google.rpc.Code].
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public int Code {
get { return code_; }
set {
code_ = value;
}
}
/// <summary>Field number for the "message" field.</summary>
public const int MessageFieldNumber = 2;
private string message_ = "";
/// <summary>
/// A developer-facing error message, which should be in English. Any
/// user-facing error message should be localized and sent in the
/// [google.rpc.Status.details][google.rpc.Status.details] field, or localized by the client.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public string Message {
get { return message_; }
set {
message_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "details" field.</summary>
public const int DetailsFieldNumber = 3;
private static readonly pb::FieldCodec<global::Google.Protobuf.WellKnownTypes.Any> _repeated_details_codec
= pb::FieldCodec.ForMessage(26, global::Google.Protobuf.WellKnownTypes.Any.Parser);
private readonly pbc::RepeatedField<global::Google.Protobuf.WellKnownTypes.Any> details_ = new pbc::RepeatedField<global::Google.Protobuf.WellKnownTypes.Any>();
/// <summary>
/// A list of messages that carry the error details. There is a common set of
/// message types for APIs to use.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public pbc::RepeatedField<global::Google.Protobuf.WellKnownTypes.Any> Details {
get { return details_; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public override bool Equals(object other) {
return Equals(other as Status);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public bool Equals(Status other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (Code != other.Code) return false;
if (Message != other.Message) return false;
if(!details_.Equals(other.details_)) return false;
return Equals(_unknownFields, other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public override int GetHashCode() {
int hash = 1;
if (Code != 0) hash ^= Code.GetHashCode();
if (Message.Length != 0) hash ^= Message.GetHashCode();
hash ^= details_.GetHashCode();
if (_unknownFields != null) {
hash ^= _unknownFields.GetHashCode();
}
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public void WriteTo(pb::CodedOutputStream output) {
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
output.WriteRawMessage(this);
#else
if (Code != 0) {
output.WriteRawTag(8);
output.WriteInt32(Code);
}
if (Message.Length != 0) {
output.WriteRawTag(18);
output.WriteString(Message);
}
details_.WriteTo(output, _repeated_details_codec);
if (_unknownFields != null) {
_unknownFields.WriteTo(output);
}
#endif
}
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) {
if (Code != 0) {
output.WriteRawTag(8);
output.WriteInt32(Code);
}
if (Message.Length != 0) {
output.WriteRawTag(18);
output.WriteString(Message);
}
details_.WriteTo(ref output, _repeated_details_codec);
if (_unknownFields != null) {
_unknownFields.WriteTo(ref output);
}
}
#endif
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public int CalculateSize() {
int size = 0;
if (Code != 0) {
size += 1 + pb::CodedOutputStream.ComputeInt32Size(Code);
}
if (Message.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(Message);
}
size += details_.CalculateSize(_repeated_details_codec);
if (_unknownFields != null) {
size += _unknownFields.CalculateSize();
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public void MergeFrom(Status other) {
if (other == null) {
return;
}
if (other.Code != 0) {
Code = other.Code;
}
if (other.Message.Length != 0) {
Message = other.Message;
}
details_.Add(other.details_);
_unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public void MergeFrom(pb::CodedInputStream input) {
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
input.ReadRawMessage(this);
#else
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
_unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
break;
case 8: {
Code = input.ReadInt32();
break;
}
case 18: {
Message = input.ReadString();
break;
}
case 26: {
details_.AddEntriesFrom(input, _repeated_details_codec);
break;
}
}
}
#endif
}
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
_unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
case 8: {
Code = input.ReadInt32();
break;
}
case 18: {
Message = input.ReadString();
break;
}
case 26: {
details_.AddEntriesFrom(ref input, _repeated_details_codec);
break;
}
}
}
}
#endif
}
#endregion
}
#endregion Designer generated code
| |
using System;
using System.Collections.Generic;
using System.Text;
using NUnit.Extensions.Forms;
using NUnit.Framework;
using EIDSS.GISControl.Common.Data.Providers;
using bv.common.db.Core;
using SharpMap.Styles;
using SharpMap.Geometries;
using System.Data.SqlClient;
using System.Drawing;
using System.Drawing.Drawing2D;
using Point = SharpMap.Geometries.Point;
namespace EIDSS.Tests.GIS
{
//[TestFixture]
public class GisUserLayerTests : BaseTests
{
string connStr = ConnectionManager.DefaultInstance.ConnectionString;
[TearDown]
new public void TearDown()
{
CleanTables();
}
private void CleanTables()
{
string cleanQuery = "DELETE FROM dbo.gisUserFeature; DELETE FROM dbo.gisUserLayer;";
using(SqlConnection connection=new SqlConnection(connStr))
{
connection.Open();
using (SqlCommand cmd = new SqlCommand(cleanQuery, connection))
cmd.ExecuteNonQuery();
connection.Close();
}
}
//------------- UserLayers
[Test]
[Ignore("Wait DB")]
public void GetAllLayers()
{
EditableMsSql.GetUserLayer(connStr, 5);
CleanTables();
List<UserDbLayerInfo> layers = EditableMsSql.GetUserLayers(connStr);
Assert.AreEqual(layers.Count, 0);
}
[Test]
[Ignore("Wait DB")]
public void CreateUserLayer()
{
//generate layer name
string layerName = "Layer" + Guid.NewGuid();
//create new layer
UserDbLayerInfo info=new UserDbLayerInfo(layerName, new VectorStyle());
EditableMsSql.AddUserLayer(connStr, info);
//check layer exists (not very good - need check in table directly)
List<UserDbLayerInfo> layers = EditableMsSql.GetUserLayers(connStr);
Assert.IsTrue(layers.Exists(delegate(UserDbLayerInfo layer) { return (layer.Name == layerName); }));
}
[Test]
[Ignore("Wait DB")]
[ExpectedException(typeof(SqlException))]
public void CreateUserLayer_NameDuplicate()
{
//generate layer name
string layerName = "Layer" + Guid.NewGuid();
//create new layer
UserDbLayerInfo info = new UserDbLayerInfo(layerName, new VectorStyle());
EditableMsSql.AddUserLayer(connStr, info);
//check layer exists (not very good - need check in table directly)
List<UserDbLayerInfo> layers = EditableMsSql.GetUserLayers(connStr);
Assert.IsTrue(layers.Exists(delegate(UserDbLayerInfo layer) { return (layer.Name == layerName); }));
//add layer with duplicate name - must be ex
EditableMsSql.AddUserLayer(connStr, info);
}
[Test]
[Ignore("Wait DB")]
public void DeleteUserLayer()
{
//generate layer name
string layerName = "Layer" + Guid.NewGuid();
//create new layer
UserDbLayerInfo info = new UserDbLayerInfo(layerName, new VectorStyle());
EditableMsSql.AddUserLayer(connStr, info);
//check layer exists (not very good - need check in table directly)
List<UserDbLayerInfo> layers = EditableMsSql.GetUserLayers(connStr);
Assert.IsTrue(layers.Exists(delegate(UserDbLayerInfo layer) { return (layer.Name == layerName); }));
//delete layer
info=layers.Find(delegate(UserDbLayerInfo layer) { return (layer.Name == layerName); });
EditableMsSql.RemoveUserLayer(connStr, info);
//check layer exists (not very good - need check in table directly)
layers = EditableMsSql.GetUserLayers(connStr);
Assert.IsFalse(layers.Exists(delegate(UserDbLayerInfo layer) { return (layer.Name == layerName); }));
}
[Test]
[Ignore("Wait DB")]
public void UpdateUserLayer()
{
//generate layer name
string layerName = "Layer" + Guid.NewGuid();
//create new layer
UserDbLayerInfo info = new UserDbLayerInfo(layerName, new VectorStyle());
EditableMsSql.AddUserLayer(connStr, info);
//check layer exists (not very good - need check in table directly)
List<UserDbLayerInfo> layers = EditableMsSql.GetUserLayers(connStr);
Assert.IsTrue(layers.Exists(delegate(UserDbLayerInfo layer) { return (layer.Name == layerName); }));
//check default values
info = layers.Find(delegate(UserDbLayerInfo layer) { return (layer.Name == layerName); });
Assert.IsNull(info.Description);
DateTime lastUpdated = info.LastUpdate;
//set new values and update
string layerNameNew = layerName+Guid.NewGuid();
info.Name = layerNameNew;
info.LayerStyle.Outline.DashCap = DashCap.Triangle;
info.Description = connStr; //for sample
EditableMsSql.UpdateUserLayer(connStr,info);
//check updated values
layers = EditableMsSql.GetUserLayers(connStr);
//check name update
Assert.IsTrue(layers.Exists(delegate(UserDbLayerInfo layer) { return (layer.Name == layerNameNew); })); //layer with new name must be exists
Assert.IsFalse(layers.Exists(delegate(UserDbLayerInfo layer) { return (layer.Name == layerName); })); //and with old name - not
info = layers.Find(delegate(UserDbLayerInfo layer) { return (layer.Name == layerNameNew); });
//check style update
Assert.AreEqual(info.LayerStyle.Outline.DashCap, DashCap.Triangle);
//check description update
Assert.AreEqual(info.Description, connStr);
//check lastupdate date
Assert.AreNotEqual(info.LastUpdate,lastUpdated);
}
//------------- UserFeatures
[Test]
[Ignore("Wait DB")]
public void AddGeoms()
{
//generate layer name
string layerName = "Layer" + Guid.NewGuid();
//create new layer
UserDbLayerInfo info = new UserDbLayerInfo(layerName, new VectorStyle());
EditableMsSql.AddUserLayer(connStr, info);
//check layer exists (not very good - need check in table directly)
List<UserDbLayerInfo> layers = EditableMsSql.GetUserLayers(connStr);
Assert.IsTrue(layers.Exists(delegate(UserDbLayerInfo layer) { return (layer.Name == layerName); }));
//get added layer
info = layers.Find(delegate(UserDbLayerInfo layer) { return (layer.Name == layerName); });
//check layer features count
EditableMsSql userLayer = new EditableMsSql(connStr, info.LayerId);
int countInLayer=userLayer.GetFeatureCount();
Assert.AreEqual(countInLayer, 0);
//add new features
int countNewFeatures = 10;
string featName = "Test";
string featDesc = "Test desc";
Geometry featGeom = new Point(5, 5);
float featRadius = 100;
for (int i = 0; i < countNewFeatures; i++)
{
UserDbFeature feature = new UserDbFeature(featName, featDesc, featGeom, featRadius);
userLayer.AddUserFeature(feature);
}
//check layer features count
countInLayer = userLayer.GetFeatureCount();
Assert.AreEqual(countInLayer, countNewFeatures);
//check features
List<long> ids=userLayer.GetObjectIDsInView(userLayer.GetExtents().Grow(100, 100));
foreach (long id in ids)
{
UserDbFeature feat = userLayer.GetUserFeature(id);
Assert.AreEqual(feat.Name, featName);
Assert.AreEqual(feat.Description, featDesc);
Assert.AreEqual(feat.Geometry, featGeom);
Assert.AreEqual(feat.Radius, featRadius);
Assert.AreEqual(feat.LayerId, info.LayerId);
}
}
[Test]
[Ignore("Wait DB")]
public void UpdGeoms()
{
//generate layer name
string layerName = "Layer" + Guid.NewGuid();
//create new layer
UserDbLayerInfo info = new UserDbLayerInfo(layerName, new VectorStyle());
EditableMsSql.AddUserLayer(connStr, info);
//check layer exists (not very good - need check in table directly)
List<UserDbLayerInfo> layers = EditableMsSql.GetUserLayers(connStr);
Assert.IsTrue(layers.Exists(delegate(UserDbLayerInfo layer) { return (layer.Name == layerName); }));
//get added layer
info = layers.Find(delegate(UserDbLayerInfo layer) { return (layer.Name == layerName); });
//check layer features count
EditableMsSql userLayer = new EditableMsSql(connStr, info.LayerId);
int countInLayer = userLayer.GetFeatureCount();
Assert.AreEqual(countInLayer, 0);
//add new feature
string featName = "Test";
string featDesc = "Test desc";
Geometry featGeom = new Point(5, 5);
float featRadius = 100;
UserDbFeature feature = new UserDbFeature(featName, featDesc, featGeom, featRadius);
userLayer.AddUserFeature(feature);
//check layer features count
countInLayer = userLayer.GetFeatureCount();
Assert.AreEqual(countInLayer, 1); //only one added feat
//check feature
List<long> ids = userLayer.GetObjectIDsInView(userLayer.GetExtents().Grow(100, 100));
UserDbFeature feat = userLayer.GetUserFeature(ids[0]);
Assert.AreEqual(feat.Name, featName);
Assert.AreEqual(feat.Description, featDesc);
Assert.AreEqual(feat.Geometry, featGeom);
Assert.AreEqual(feat.Radius, featRadius);
Assert.AreEqual(feat.LayerId, info.LayerId);
//set new value
feat.Name = featName = "TestUpd";
feat.Description = featDesc = "TestUpd desc";
feat.Geometry = featGeom = new Point(10, 10);
feat.Radius = featRadius = 200;
userLayer.UpdateUserFeature(feat);
//check layer features count
countInLayer = userLayer.GetFeatureCount();
Assert.AreEqual(countInLayer, 1); //only one added feat
//check updated feature
ids = userLayer.GetObjectIDsInView(userLayer.GetExtents().Grow(100, 100));
feat = userLayer.GetUserFeature(ids[0]);
Assert.AreEqual(feat.Name, featName);
Assert.AreEqual(feat.Description, featDesc);
Assert.AreEqual(feat.Geometry, featGeom);
Assert.AreEqual(feat.Radius, featRadius);
Assert.AreEqual(feat.LayerId, info.LayerId);
}
[Test]
[Ignore("Wait DB")]
public void DelGeoms()
{
//generate layer name
string layerName = "Layer" + Guid.NewGuid();
//create new layer
UserDbLayerInfo info = new UserDbLayerInfo(layerName, new VectorStyle());
EditableMsSql.AddUserLayer(connStr, info);
//check layer exists (not very good - need check in table directly)
List<UserDbLayerInfo> layers = EditableMsSql.GetUserLayers(connStr);
Assert.IsTrue(layers.Exists(delegate(UserDbLayerInfo layer) { return (layer.Name == layerName); }));
//get added layer
info = layers.Find(delegate(UserDbLayerInfo layer) { return (layer.Name == layerName); });
//check layer features count
EditableMsSql userLayer = new EditableMsSql(connStr, info.LayerId);
int countInLayer = userLayer.GetFeatureCount();
Assert.AreEqual(countInLayer, 0);
//add new features
int countNewFeatures = 10;
string featName = "Test";
string featDesc = "Test desc";
Geometry featGeom = new Point(5, 5);
float featRadius = 100;
for (int i = 0; i < countNewFeatures; i++)
{
UserDbFeature feature = new UserDbFeature(featName, featDesc, featGeom, featRadius);
userLayer.AddUserFeature(feature);
}
//check layer features count
countInLayer = userLayer.GetFeatureCount();
Assert.AreEqual(countInLayer, countNewFeatures);
//delete all features
List<long> ids = userLayer.GetObjectIDsInView(userLayer.GetExtents().Grow(100, 100));
foreach (long id in ids)
userLayer.RemoveUserFeature(id);
//check layer features count
countInLayer = userLayer.GetFeatureCount();
Assert.AreEqual(countInLayer, 0); //all maust be deleted
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
/*============================================================
**
** Class: Random
**
**
** Purpose: A random number generator.
**
**
===========================================================*/
using System;
using System.Runtime;
using System.Runtime.CompilerServices;
using System.Globalization;
using System.Diagnostics.Contracts;
namespace System
{
public class Random
{
//
// Private Constants
//
private const int MBIG = Int32.MaxValue;
private const int MSEED = 161803398;
private const int MZ = 0;
//
// Member Variables
//
private int inext;
private int inextp;
private int[] SeedArray = new int[56];
//
// Public Constants
//
//
// Native Declarations
//
//
// Constructors
//
public Random()
: this(Environment.TickCount)
{
}
public Random(int Seed)
{
int ii;
int mj, mk;
//Initialize our Seed array.
int subtraction = (Seed == Int32.MinValue) ? Int32.MaxValue : Math.Abs(Seed);
mj = MSEED - subtraction;
SeedArray[55] = mj;
mk = 1;
for (int i = 1; i < 55; i++)
{ //Apparently the range [1..55] is special (Knuth) and so we're wasting the 0'th position.
ii = (21 * i) % 55;
SeedArray[ii] = mk;
mk = mj - mk;
if (mk < 0) mk += MBIG;
mj = SeedArray[ii];
}
for (int k = 1; k < 5; k++)
{
for (int i = 1; i < 56; i++)
{
SeedArray[i] -= SeedArray[1 + (i + 30) % 55];
if (SeedArray[i] < 0) SeedArray[i] += MBIG;
}
}
inext = 0;
inextp = 21;
Seed = 1;
}
//
// Package Private Methods
//
/*====================================Sample====================================
**Action: Return a new random number [0..1) and reSeed the Seed array.
**Returns: A double [0..1)
**Arguments: None
**Exceptions: None
==============================================================================*/
protected virtual double Sample()
{
//Including this division at the end gives us significantly improved
//random number distribution.
return (InternalSample() * (1.0 / MBIG));
}
private int InternalSample()
{
int retVal;
int locINext = inext;
int locINextp = inextp;
if (++locINext >= 56) locINext = 1;
if (++locINextp >= 56) locINextp = 1;
retVal = SeedArray[locINext] - SeedArray[locINextp];
if (retVal == MBIG) retVal--;
if (retVal < 0) retVal += MBIG;
SeedArray[locINext] = retVal;
inext = locINext;
inextp = locINextp;
return retVal;
}
//
// Public Instance Methods
//
/*=====================================Next=====================================
**Returns: An int [0..Int32.MaxValue)
**Arguments: None
**Exceptions: None.
==============================================================================*/
public virtual int Next()
{
return InternalSample();
}
private double GetSampleForLargeRange()
{
// The distribution of double value returned by Sample
// is not distributed well enough for a large range.
// If we use Sample for a range [Int32.MinValue..Int32.MaxValue)
// We will end up getting even numbers only.
int result = InternalSample();
// Note we can't use addition here. The distribution will be bad if we do that.
bool negative = (InternalSample() % 2 == 0) ? true : false; // decide the sign based on second sample
if (negative)
{
result = -result;
}
double d = result;
d += (Int32.MaxValue - 1); // get a number in range [0 .. 2 * Int32MaxValue - 1)
d /= 2 * (uint)Int32.MaxValue - 1;
return d;
}
/*=====================================Next=====================================
**Returns: An int [minvalue..maxvalue)
**Arguments: minValue -- the least legal value for the Random number.
** maxValue -- One greater than the greatest legal return value.
**Exceptions: None.
==============================================================================*/
public virtual int Next(int minValue, int maxValue)
{
if (minValue > maxValue)
{
throw new ArgumentOutOfRangeException("minValue", SR.Format(SR.Argument_MinMaxValue, "minValue", "maxValue"));
}
Contract.EndContractBlock();
long range = (long)maxValue - minValue;
if (range <= (long)Int32.MaxValue)
{
return ((int)(Sample() * range) + minValue);
}
else
{
return (int)((long)(GetSampleForLargeRange() * range) + minValue);
}
}
/*=====================================Next=====================================
**Returns: An int [0..maxValue)
**Arguments: maxValue -- One more than the greatest legal return value.
**Exceptions: None.
==============================================================================*/
public virtual int Next(int maxValue)
{
if (maxValue < 0)
{
throw new ArgumentOutOfRangeException("maxValue", SR.Format(SR.ArgumentOutOfRange_MustBePositive, "maxValue"));
}
Contract.EndContractBlock();
return (int)(Sample() * maxValue);
}
/*=====================================Next=====================================
**Returns: A double [0..1)
**Arguments: None
**Exceptions: None
==============================================================================*/
public virtual double NextDouble()
{
return Sample();
}
/*==================================NextBytes===================================
**Action: Fills the byte array with random bytes [0..0x7f]. The entire array is filled.
**Returns:Void
**Arugments: buffer -- the array to be filled.
**Exceptions: None
==============================================================================*/
public virtual void NextBytes(byte[] buffer)
{
if (buffer == null) throw new ArgumentNullException("buffer");
Contract.EndContractBlock();
for (int i = 0; i < buffer.Length; i++)
{
buffer[i] = (byte)(InternalSample() % (Byte.MaxValue + 1));
}
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Reflection;
namespace RabbitFarm.WebAPI.Areas.HelpPage
{
/// <summary>
/// This class will create an object of a given type and populate it with sample data.
/// </summary>
public class ObjectGenerator
{
internal const int DefaultCollectionSize = 2;
private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator();
/// <summary>
/// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types:
/// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc.
/// Complex types: POCO types.
/// Nullables: <see cref="Nullable{T}"/>.
/// Arrays: arrays of simple types or complex types.
/// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/>
/// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc
/// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>.
/// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>.
/// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>An object of the given type.</returns>
public object GenerateObject(Type type)
{
return GenerateObject(type, new Dictionary<Type, object>());
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")]
private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
try
{
if (SimpleTypeObjectGenerator.CanGenerateObject(type))
{
return SimpleObjectGenerator.GenerateObject(type);
}
if (type.IsArray)
{
return GenerateArray(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsGenericType)
{
return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IDictionary))
{
return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IDictionary).IsAssignableFrom(type))
{
return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IList) ||
type == typeof(IEnumerable) ||
type == typeof(ICollection))
{
return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IList).IsAssignableFrom(type))
{
return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IQueryable))
{
return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsEnum)
{
return GenerateEnum(type);
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
}
catch
{
// Returns null if anything fails
return null;
}
return null;
}
private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences)
{
Type genericTypeDefinition = type.GetGenericTypeDefinition();
if (genericTypeDefinition == typeof(Nullable<>))
{
return GenerateNullable(type, createdObjectReferences);
}
if (genericTypeDefinition == typeof(KeyValuePair<,>))
{
return GenerateKeyValuePair(type, createdObjectReferences);
}
if (IsTuple(genericTypeDefinition))
{
return GenerateTuple(type, createdObjectReferences);
}
Type[] genericArguments = type.GetGenericArguments();
if (genericArguments.Length == 1)
{
if (genericTypeDefinition == typeof(IList<>) ||
genericTypeDefinition == typeof(IEnumerable<>) ||
genericTypeDefinition == typeof(ICollection<>))
{
Type collectionType = typeof(List<>).MakeGenericType(genericArguments);
return GenerateCollection(collectionType, collectionSize, createdObjectReferences);
}
if (genericTypeDefinition == typeof(IQueryable<>))
{
return GenerateQueryable(type, collectionSize, createdObjectReferences);
}
Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]);
if (closedCollectionType.IsAssignableFrom(type))
{
return GenerateCollection(type, collectionSize, createdObjectReferences);
}
}
if (genericArguments.Length == 2)
{
if (genericTypeDefinition == typeof(IDictionary<,>))
{
Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments);
return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences);
}
Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]);
if (closedDictionaryType.IsAssignableFrom(type))
{
return GenerateDictionary(type, collectionSize, createdObjectReferences);
}
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
return null;
}
private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = type.GetGenericArguments();
object[] parameterValues = new object[genericArgs.Length];
bool failedToCreateTuple = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < genericArgs.Length; i++)
{
parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences);
failedToCreateTuple &= parameterValues[i] == null;
}
if (failedToCreateTuple)
{
return null;
}
object result = Activator.CreateInstance(type, parameterValues);
return result;
}
private static bool IsTuple(Type genericTypeDefinition)
{
return genericTypeDefinition == typeof(Tuple<>) ||
genericTypeDefinition == typeof(Tuple<,>) ||
genericTypeDefinition == typeof(Tuple<,,>) ||
genericTypeDefinition == typeof(Tuple<,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,,>);
}
private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = keyValuePairType.GetGenericArguments();
Type typeK = genericArgs[0];
Type typeV = genericArgs[1];
ObjectGenerator objectGenerator = new ObjectGenerator();
object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences);
object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences);
if (keyObject == null && valueObject == null)
{
// Failed to create key and values
return null;
}
object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject);
return result;
}
private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = arrayType.GetElementType();
Array result = Array.CreateInstance(type, size);
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
result.SetValue(element, i);
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type typeK = typeof(object);
Type typeV = typeof(object);
if (dictionaryType.IsGenericType)
{
Type[] genericArgs = dictionaryType.GetGenericArguments();
typeK = genericArgs[0];
typeV = genericArgs[1];
}
object result = Activator.CreateInstance(dictionaryType);
MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd");
MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey");
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences);
if (newKey == null)
{
// Cannot generate a valid key
return null;
}
bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey });
if (!containsKey)
{
object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences);
addMethod.Invoke(result, new object[] { newKey, newValue });
}
}
return result;
}
private static object GenerateEnum(Type enumType)
{
Array possibleValues = Enum.GetValues(enumType);
if (possibleValues.Length > 0)
{
return possibleValues.GetValue(0);
}
return null;
}
private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences)
{
bool isGeneric = queryableType.IsGenericType;
object list;
if (isGeneric)
{
Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments());
list = GenerateCollection(listType, size, createdObjectReferences);
}
else
{
list = GenerateArray(typeof(object[]), size, createdObjectReferences);
}
if (list == null)
{
return null;
}
if (isGeneric)
{
Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments());
MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType });
return asQueryableMethod.Invoke(null, new[] { list });
}
return Queryable.AsQueryable((IEnumerable)list);
}
private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = collectionType.IsGenericType ?
collectionType.GetGenericArguments()[0] :
typeof(object);
object result = Activator.CreateInstance(collectionType);
MethodInfo addMethod = collectionType.GetMethod("Add");
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
addMethod.Invoke(result, new object[] { element });
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences)
{
Type type = nullableType.GetGenericArguments()[0];
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type, createdObjectReferences);
}
private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
object result = null;
if (createdObjectReferences.TryGetValue(type, out result))
{
// The object has been created already, just return it. This will handle the circular reference case.
return result;
}
if (type.IsValueType)
{
result = Activator.CreateInstance(type);
}
else
{
ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes);
if (defaultCtor == null)
{
// Cannot instantiate the type because it doesn't have a default constructor
return null;
}
result = defaultCtor.Invoke(new object[0]);
}
createdObjectReferences.Add(type, result);
SetPublicProperties(type, result, createdObjectReferences);
SetPublicFields(type, result, createdObjectReferences);
return result;
}
private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (PropertyInfo property in properties)
{
if (property.CanWrite)
{
object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences);
property.SetValue(obj, propertyValue, null);
}
}
}
private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (FieldInfo field in fields)
{
object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences);
field.SetValue(obj, fieldValue);
}
}
private class SimpleTypeObjectGenerator
{
private long _index = 0;
private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators();
[SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")]
private static Dictionary<Type, Func<long, object>> InitializeGenerators()
{
return new Dictionary<Type, Func<long, object>>
{
{ typeof(Boolean), index => true },
{ typeof(Byte), index => (Byte)64 },
{ typeof(Char), index => (Char)65 },
{ typeof(DateTime), index => DateTime.Now },
{ typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) },
{ typeof(DBNull), index => DBNull.Value },
{ typeof(Decimal), index => (Decimal)index },
{ typeof(Double), index => (Double)(index + 0.1) },
{ typeof(Guid), index => Guid.NewGuid() },
{ typeof(Int16), index => (Int16)(index % Int16.MaxValue) },
{ typeof(Int32), index => (Int32)(index % Int32.MaxValue) },
{ typeof(Int64), index => (Int64)index },
{ typeof(Object), index => new object() },
{ typeof(SByte), index => (SByte)64 },
{ typeof(Single), index => (Single)(index + 0.1) },
{
typeof(String), index =>
{
return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index);
}
},
{
typeof(TimeSpan), index =>
{
return TimeSpan.FromTicks(1234567);
}
},
{ typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) },
{ typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) },
{ typeof(UInt64), index => (UInt64)index },
{
typeof(Uri), index =>
{
return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index));
}
},
};
}
public static bool CanGenerateObject(Type type)
{
return DefaultGenerators.ContainsKey(type);
}
public object GenerateObject(Type type)
{
return DefaultGenerators[type](++_index);
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.IO;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Boogie;
using Microsoft.Boogie.GraphUtil;
using Microsoft.Boogie.VCExprAST;
using VC;
using Microsoft.Basetypes;
using BType = Microsoft.Boogie.Type;
namespace CfiVerifier
{
public class Slicer : StandardVisitor
{
private Program prog;
private Implementation impl;
private AssertCmd source_assert;
private Expr return_instrumentation_address = null;
private List<Function> call_trigger_functions = new List<Function>();
private HashSet<Cmd> keep_set;
private Dictionary<Cmd, HashSet<Variable>> live_set;
public Slicer(Program prog)
{
Utils.Assert(prog.Implementations.Count() == 1, "Expecting a single implementation");
this.impl = prog.Implementations.ElementAt(0);
this.prog = prog;
this.live_set = new Dictionary<Cmd, HashSet<Variable>>();
this.keep_set = new HashSet<Cmd>();
bool prevPIE = CommandLineOptions.Clo.PruneInfeasibleEdges;
CommandLineOptions.Clo.PruneInfeasibleEdges = true;
impl.PruneUnreachableBlocks();
CommandLineOptions.Clo.PruneInfeasibleEdges = prevPIE;
foreach (Block b in this.impl.Blocks)
{
foreach (Cmd c in b.Cmds)
{
this.live_set.Add(c, new HashSet<Variable>());
if (c is AssertCmd)
{
if (QKeyValue.FindBoolAttribute((c as AssertCmd).Attributes, "source_assert"))
{
this.source_assert = c as AssertCmd;
}
}
/* This command sets this.return_instrumentation_address if the source_assert is a
* return type instrumentation with the corresponding attributes set; commenting
* this function ensures that triggers for call instrumentation are not sliced away */
IdentifyReturnInstrumentationAddress(c);
}
}
Utils.Assert(this.source_assert != null, "Unable to find source assertion");
this.keep_set.Add(this.source_assert);
this.live_set[this.source_assert] = GetReferencedVars(this.source_assert);
/* This performs data-flow analysis to remove most of the instructions in the program which do not have
* information flowing into the source_assert; this generally affects only AssignCmd's*/
PerformTaintAnalysisAlternate();
/* This removes unused policy axioms; in almost all cases, this will remove ALL policy axioms. The exception
* is when the source_assert itself asserts that an address is a policy; in this case, all but the corresponding
* axiom will be removed */
SlicePolicyAxioms();
SliceRequires();
}
private void PerformTaintAnalysisAlternate()
{
bool fixed_point = false;
ICFG cfg = new ICFG(this.impl);
while (!fixed_point)
{
fixed_point = true;
foreach (Block b in this.impl.Blocks.AsEnumerable().Reverse())
{
if (!b.Cmds.Any())
{
continue;
}
fixed_point &= !PerformCommandAnalysis(b.Cmds);
foreach (Cmd pred_cmd in FindPredCmds(b, cfg))
{
fixed_point &= !PerformCommandAnalysis(new List<Cmd> { pred_cmd, b.Cmds.First() });
}
}
}
}
private HashSet<Cmd> FindPredCmds(Block b, ICFG cfg)
{
HashSet<Cmd> pred_cmds = new HashSet<Cmd>();
List<Block> pred_blocks = cfg.predEdges[b].ToList();
List<Block> visited_blocks = new List<Block> { b };
Block current_block;
while (pred_blocks.Any())
{
current_block = pred_blocks.First();
pred_blocks.Remove(current_block);
if (current_block.Cmds.Any())
{
pred_cmds.Add(current_block.Cmds.Last());
}
else
{
pred_blocks.AddRange(cfg.predEdges[current_block].Except(visited_blocks));
}
visited_blocks.Add(current_block);
}
return pred_cmds;
}
private bool PerformCommandAnalysis(List<Cmd> cmds)
{
int size_before;
bool keep_before, changed = false;
Cmd this_cmd, prev_cmd;
for (int i = cmds.Count - 1; i > 0; i--)
{
this_cmd = cmds.ElementAt(i);
prev_cmd = cmds.ElementAt(i - 1);
size_before = this.live_set[prev_cmd].Count;
keep_before = this.keep_set.Contains(prev_cmd);
AssignCmd as_assign_cmd = prev_cmd is AssignCmd ? prev_cmd as AssignCmd : null;
HashSet<Variable> to_union = new HashSet<Variable>(this.live_set[this_cmd]);
Variable assign_cmd_lhs_var = null;
if (as_assign_cmd != null)
{
assign_cmd_lhs_var = GetReferencedVars(as_assign_cmd.Lhss.First().AsExpr).First();
to_union.Remove(assign_cmd_lhs_var);
}
this.live_set[prev_cmd].UnionWith(to_union);
if (as_assign_cmd != null)
{
Utils.Assert(as_assign_cmd.Lhss.Count == 1);
Utils.Assert(assign_cmd_lhs_var != null);
HashSet<Variable> assign_cmd_rhs_vars = new HashSet<Variable>();
foreach (Expr rhs_expr in as_assign_cmd.Rhss)
{
assign_cmd_rhs_vars.UnionWith(GetReferencedVars(rhs_expr));
}
if (this.live_set[this_cmd].Contains(assign_cmd_lhs_var))
{
this.live_set[prev_cmd].UnionWith(assign_cmd_rhs_vars);
this.keep_set.Add(prev_cmd);
}
}
if (prev_cmd is AssumeCmd /*&& !QKeyValue.FindBoolAttribute((prev_cmd as AssumeCmd).Attributes, "partition")*/)
{
this.live_set[prev_cmd].UnionWith(GetReferencedVars(prev_cmd));
this.keep_set.Add(prev_cmd);
}
if (prev_cmd is HavocCmd)
{
this.live_set[prev_cmd].ExceptWith(GetReferencedVars(prev_cmd));
this.keep_set.Add(prev_cmd);
}
Utils.Assert(this.live_set[prev_cmd].Count >= size_before);
if (this.live_set[prev_cmd].Count > size_before || this.keep_set.Contains(prev_cmd) != keep_before) {
changed = true;
}
}
return changed;
}
private HashSet<Variable> GetReferencedVars(Cmd c)
{
if (c is AssignCmd)
{
HashSet<Variable> referenced_vars = new HashSet<Variable>();
Utils.Assert((c as AssignCmd).Lhss.Count == 1);
referenced_vars.UnionWith(GetReferencedVars((c as AssignCmd).Lhss.First().AsExpr));
foreach (Expr rhs in (c as AssignCmd).Rhss)
{
referenced_vars.UnionWith(GetReferencedVars(rhs));
}
return referenced_vars;
}
else if (c is AssertCmd)
{
return GetReferencedVars((c as AssertCmd).Expr);
}
else if (c is AssumeCmd)
{
return GetReferencedVars((c as AssumeCmd).Expr);
}
else if (c is HavocCmd)
{
return new HashSet<Variable>((c as HavocCmd).Vars.Select(i => i.Decl));
}
Utils.Assert(false, "Unhandled Cmd type: " + c.GetType().ToString());
return null;
}
private HashSet<Variable> GetReferencedVars(Expr e)
{
HashSet<Variable> referenced_vars = new HashSet<Variable>();
if (e is NAryExpr)
{
foreach (Expr sub_e in (e as NAryExpr).Args)
referenced_vars.UnionWith(GetReferencedVars(sub_e));
return referenced_vars;
}
else if (e is IdentifierExpr)
{
Variable var = (e as IdentifierExpr).Decl;
referenced_vars.Add(var);
return referenced_vars;
}
else if (e is BvExtractExpr)
{
referenced_vars.UnionWith(GetReferencedVars((e as BvExtractExpr).Bitvector));
return referenced_vars;
}
else if (e is BvConcatExpr)
{
referenced_vars.UnionWith(GetReferencedVars((e as BvConcatExpr).E0));
referenced_vars.UnionWith(GetReferencedVars((e as BvConcatExpr).E1));
return referenced_vars;
}
else if (e is ForallExpr)
{
referenced_vars.UnionWith(GetReferencedVars((e as ForallExpr).Body));
(e as ForallExpr).Dummies.ForEach(i => referenced_vars.Remove(i));
return referenced_vars;
}
else if (e is LiteralExpr || e is OldExpr)
{
return referenced_vars;
}
Utils.Assert(false, "Unhandled Expr type detected: " + e.GetType().ToString());
return null;
}
private void SlicePolicyAxioms()
{
LiteralExpr policy_target = null;
if (this.source_assert.Expr is NAryExpr && ((this.source_assert.Expr) as NAryExpr).Fun.FunctionName == "policy") {
Utils.Assert(((this.source_assert.Expr) as NAryExpr).Args.Count == 1, "Expecting \"policy\" axiom with a single argument");
if (!(((this.source_assert.Expr) as NAryExpr).Args.First() is LiteralExpr)) {
return;
}
policy_target = ((this.source_assert.Expr) as NAryExpr).Args.First() as LiteralExpr;
}
foreach (Declaration d in this.prog.TopLevelDeclarations.ToList())
{
if (d is Axiom && (d as Axiom).Expr is NAryExpr && ((d as Axiom).Expr as NAryExpr).Fun.FunctionName == "policy")
{
if (policy_target != null && policy_target.ToString().Equals(((d as Axiom).Expr as NAryExpr).Args.First().ToString()))
{
continue;
}
else
{
this.prog.RemoveTopLevelDeclaration(d);
}
}
}
}
private void SliceRequires()
{
Procedure dll_func_proc = this.prog.Procedures.Where(i => i.Name == "dll_func").First();
Utils.Assert(dll_func_proc != null, "Did not find dll_func procedure in given program!");
foreach (Requires r in dll_func_proc.Requires.ToList())
{
Expr reqAddress = GetRequiresAddress(r);
if (this.return_instrumentation_address != null && reqAddress != null
&& reqAddress.ComputeHashCode() != this.return_instrumentation_address.ComputeHashCode())
{
dll_func_proc.Requires.Remove(r);
}
}
}
private NAryExpr GetRequiresAddress(Requires r)
{
if (!(r.Condition is NAryExpr))
{
return null;
}
NAryExpr conditionNary = r.Condition as NAryExpr;
string conditionFuncName = conditionNary.Fun.FunctionName;
if (conditionFuncName.Equals("!"))
{
if (conditionNary.Args.Count != 1 || !(conditionNary.Args.First() is NAryExpr))
{
return null;
}
NAryExpr innerConditionNary = conditionNary.Args.First() as NAryExpr;
if (innerConditionNary.Fun.FunctionName != "writable"
|| !((innerConditionNary.Args.Last() as NAryExpr).Fun.FunctionName.Equals("MINUS_64")))
{
return null;
}
return innerConditionNary.Args.Last() as NAryExpr;
}
else if (conditionFuncName.Equals("T"))
{
if (!((conditionNary.Args.First()) as NAryExpr).Fun.FunctionName.Equals("MINUS_64"))
{
return null;
}
return conditionNary.Args.First() as NAryExpr;
}
return null;
}
private void IdentifyReturnInstrumentationAddress(Cmd c)
{
if (c is AssertCmd)
{
Expr return_instrumentation_addr = QKeyValue.FindExprAttribute((c as AssertCmd).Attributes, "return_instrumentation");
if (return_instrumentation_addr != null)
{
Utils.Assert(this.return_instrumentation_address == null);
this.return_instrumentation_address = return_instrumentation_addr;
}
}
else if (c is AssumeCmd)
{
string trigger_func_name = QKeyValue.FindStringAttribute((c as AssumeCmd).Attributes, "call_func_trigger_declaration");
if (trigger_func_name != null)
{
this.call_trigger_functions.Add(Utils.FindFunctionInProgram(this.prog, trigger_func_name));
}
}
}
public override List<Cmd> VisitCmdSeq(List<Cmd> cmdSeq)
{
List<Cmd> newCmdSeq = new List<Cmd>();
List<System.Type> removedCmdTypes = new List<System.Type>() {typeof(AssignCmd)};
foreach (Cmd c in cmdSeq)
{
string fresh_func_name;
if (this.return_instrumentation_address != null && c is AssumeCmd
&& (fresh_func_name = QKeyValue.FindStringAttribute((c as AssumeCmd).Attributes, "call_func_trigger_declaration")) != null)
{
Function fresh_func = this.call_trigger_functions.Where(i => i.Name.Equals(fresh_func_name)).First();
Utils.Assert(fresh_func != null);
newCmdSeq.Add(new AssumeCmd(Token.NoToken, new NAryExpr(Token.NoToken, new FunctionCall(fresh_func), new List<Expr> { this.return_instrumentation_address })));
}
else if (!removedCmdTypes.Contains(c.GetType()) || this.keep_set.Contains(c))
{
newCmdSeq.Add(c);
}
}
return base.VisitCmdSeq(newCmdSeq);
}
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) Under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for Additional information regarding copyright ownership.
* The ASF licenses this file to You Under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed Under the License is distributed on an "AS Is" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations Under the License.
*/
/*
* Created on May 19, 2005
*
*/
namespace NPOI.SS.Formula.Functions
{
using System;
/**
* @author Amol S. Deshmukh < amolweb at ya hoo dot com >
* This class Is an extension to the standard math library
* provided by java.lang.Math class. It follows the Math class
* in that it has a private constructor and all static methods.
*/
internal class MathX
{
private MathX() { }
/**
* Returns a value rounded to p digits after decimal.
* If p Is negative, then the number Is rounded to
* places to the left of the decimal point. eg.
* 10.23 rounded to -1 will give: 10. If p Is zero,
* the returned value Is rounded to the nearest integral
* value.
* If n Is negative, the resulting value Is obtained
* as the round value of absolute value of n multiplied
* by the sign value of n (@see MathX.sign(double d)).
* Thus, -0.6666666 rounded to p=0 will give -1 not 0.
* If n Is NaN, returned value Is NaN.
* @param n
* @param p
*/
public static double round(double n, int p)
{
double retval;
if (double.IsNaN(n) || double.IsInfinity(n))
{
retval = double.NaN;
}
else
{
//if (p != 0)
//{
decimal temp = (decimal)Math.Pow(10, p);
retval = (double)(Math.Round((decimal)n * temp) / temp);
//}
//else
//{
// retval = Math.Round(n);
//}
}
return retval;
}
/**
* Returns a value rounded-up to p digits after decimal.
* If p Is negative, then the number Is rounded to
* places to the left of the decimal point. eg.
* 10.23 rounded to -1 will give: 20. If p Is zero,
* the returned value Is rounded to the nearest integral
* value.
* If n Is negative, the resulting value Is obtained
* as the round-up value of absolute value of n multiplied
* by the sign value of n (@see MathX.sign(double d)).
* Thus, -0.2 rounded-up to p=0 will give -1 not 0.
* If n Is NaN, returned value Is NaN.
* @param n
* @param p
*/
public static double roundUp(double n, int p)
{
double retval;
if (double.IsNaN(n) || double.IsInfinity(n))
{
retval = double.NaN;
}
else
{
if (p != 0)
{
double temp = Math.Pow(10, p);
double nat = Math.Abs(n * temp);
retval = sign(n) *
((nat == (long)nat)
? nat / temp
: Math.Round(nat + 0.5) / temp);
}
else
{
double na = Math.Abs(n);
retval = sign(n) *
((na == (long)na)
? na
: (long)na + 1);
}
}
return retval;
}
/**
* Returns a value rounded to p digits after decimal.
* If p Is negative, then the number Is rounded to
* places to the left of the decimal point. eg.
* 10.23 rounded to -1 will give: 10. If p Is zero,
* the returned value Is rounded to the nearest integral
* value.
* If n Is negative, the resulting value Is obtained
* as the round-up value of absolute value of n multiplied
* by the sign value of n (@see MathX.sign(double d)).
* Thus, -0.8 rounded-down to p=0 will give 0 not -1.
* If n Is NaN, returned value Is NaN.
* @param n
* @param p
*/
public static double roundDown(double n, int p)
{
double retval;
if (double.IsNaN(n) || double.IsInfinity(n))
{
retval = double.NaN;
}
else
{
if (p != 0)
{
double temp = Math.Pow(10, p);
retval = sign(n) * Math.Round((Math.Abs(n) * temp) - 0.5, MidpointRounding.AwayFromZero) / temp;
}
else
{
retval = (long)n;
}
}
return retval;
}
/*
* If d < 0, returns short -1
* <br/>
* If d > 0, returns short 1
* <br/>
* If d == 0, returns short 0
* If d Is NaN, then 1 will be returned. It Is the responsibility
* of caller to Check for d IsNaN if some other value Is desired.
* @param d
*/
public static short sign(double d)
{
return (short)((d == 0)
? 0
: (d < 0)
? -1
: 1);
}
/**
* average of all values
* @param values
*/
public static double average(double[] values)
{
double ave = 0;
double sum = 0;
for (int i = 0, iSize = values.Length; i < iSize; i++)
{
sum += values[i];
}
ave = sum / values.Length;
return ave;
}
/**
* sum of all values
* @param values
*/
public static double sum(double[] values)
{
double sum = 0;
for (int i = 0, iSize = values.Length; i < iSize; i++)
{
sum += values[i];
}
return sum;
}
/**
* sum of squares of all values
* @param values
*/
public static double sumsq(double[] values)
{
double sumsq = 0;
for (int i = 0, iSize = values.Length; i < iSize; i++)
{
sumsq += values[i] * values[i];
}
return sumsq;
}
/**
* product of all values
* @param values
*/
public static double product(double[] values)
{
double product = 0;
if (values != null && values.Length > 0)
{
product = 1;
for (int i = 0, iSize = values.Length; i < iSize; i++)
{
product *= values[i];
}
}
return product;
}
/**
* min of all values. If supplied array Is zero Length,
* double.POSITIVE_INFINITY Is returned.
* @param values
*/
public static double min(double[] values)
{
double min = double.PositiveInfinity;
for (int i = 0, iSize = values.Length; i < iSize; i++)
{
min = Math.Min(min, values[i]);
}
return min;
}
/**
* min of all values. If supplied array Is zero Length,
* double.NEGATIVE_INFINITY Is returned.
* @param values
*/
public static double max(double[] values)
{
double max = double.NegativeInfinity;
for (int i = 0, iSize = values.Length; i < iSize; i++)
{
max = Math.Max(max, values[i]);
}
return max;
}
/**
* Note: this function Is different from java.lang.Math.floor(..).
*
* When n and s are "valid" arguments, the returned value Is: Math.floor(n/s) * s;
* <br/>
* n and s are invalid if any of following conditions are true:
* <ul>
* <li>s Is zero</li>
* <li>n Is negative and s Is positive</li>
* <li>n Is positive and s Is negative</li>
* </ul>
* In all such cases, double.NaN Is returned.
* @param n
* @param s
*/
public static double floor(double n, double s)
{
double f;
if ((n < 0 && s > 0) || (n > 0 && s < 0) || (s == 0 && n != 0))
{
f = double.NaN;
}
else
{
f = (n == 0 || s == 0) ? 0 : Math.Floor(n / s) * s;
}
return f;
}
/**
* Note: this function Is different from java.lang.Math.ceil(..).
*
* When n and s are "valid" arguments, the returned value Is: Math.ceiling(n/s) * s;
* <br/>
* n and s are invalid if any of following conditions are true:
* <ul>
* <li>s Is zero</li>
* <li>n Is negative and s Is positive</li>
* <li>n Is positive and s Is negative</li>
* </ul>
* In all such cases, double.NaN Is returned.
* @param n
* @param s
*/
public static double ceiling(double n, double s)
{
double c;
if ((n < 0 && s > 0) || (n > 0 && s < 0))
{
c = double.NaN;
}
else
{
c = (n == 0 || s == 0) ? 0 : Math.Ceiling(n / s) * s;
}
return c;
}
/**
* <br/> for all n >= 1; factorial n = n * (n-1) * (n-2) * ... * 1
* <br/> else if n == 0; factorial n = 1
* <br/> else if n < 0; factorial n = double.NaN
* <br/> Loss of precision can occur if n Is large enough.
* If n Is large so that the resulting value would be greater
* than double.MAX_VALUE; double.POSITIVE_INFINITY Is returned.
* If n < 0, double.NaN Is returned.
* @param n
*/
public static double factorial(int n)
{
double d = 1;
if (n >= 0)
{
if (n <= 170)
{
for (int i = 1; i <= n; i++)
{
d *= i;
}
}
else
{
d = double.PositiveInfinity;
}
}
else
{
d = double.NaN;
}
return d;
}
/**
* returns the remainder resulting from operation:
* n / d.
* <br/> The result has the sign of the divisor.
* <br/> Examples:
* <ul>
* <li>mod(3.4, 2) = 1.4</li>
* <li>mod(-3.4, 2) = 0.6</li>
* <li>mod(-3.4, -2) = -1.4</li>
* <li>mod(3.4, -2) = -0.6</li>
* </ul>
* If d == 0, result Is NaN
* @param n
* @param d
*/
public static double mod(double n, double d)
{
double result = 0;
if (d == 0)
{
result = double.NaN;
}
else if (sign(n) == sign(d))
{
//double t = Math.Abs(n / d);
//t = t - (long)t;
//result = sign(d) * Math.Abs(t * d);
result = n % d;
}
else
{
//double t = Math.Abs(n / d);
//t = t - (long)t;
//t = Math.Ceiling(t) - t;
//result = sign(d) * Math.Abs(t * d);
result = ((n % d) + d) % d;
}
return result;
}
/**
* inverse hyperbolic cosine
* @param d
*/
public static double acosh(double d)
{
return Math.Log(Math.Sqrt(Math.Pow(d, 2) - 1) + d);
}
/**
* inverse hyperbolic sine
* @param d
*/
public static double asinh(double d)
{
double d2 = d * d;
return Math.Log(Math.Sqrt(d * d + 1) + d);
}
/**
* inverse hyperbolic tangent
* @param d
*/
public static double atanh(double d)
{
return Math.Log((1 + d) / (1 - d)) / 2;
}
/**
* hyperbolic cosine
* @param d
*/
public static double cosh(double d)
{
double ePowX = Math.Pow(Math.E, d);
double ePowNegX = Math.Pow(Math.E, -d);
d = (ePowX + ePowNegX) / 2;
return d;
}
/**
* hyperbolic sine
* @param d
*/
public static double sinh(double d)
{
double ePowX = Math.Pow(Math.E, d);
double ePowNegX = Math.Pow(Math.E, -d);
d = (ePowX - ePowNegX) / 2;
return d;
}
/**
* hyperbolic tangent
* @param d
*/
public static double tanh(double d)
{
double ePowX = Math.Pow(Math.E, d);
double ePowNegX = Math.Pow(Math.E, -d);
d = (ePowX - ePowNegX) / (ePowX + ePowNegX);
return d;
}
/**
* returns the sum of product of corresponding double value in each
* subarray. It Is the responsibility of the caller to Ensure that
* all the subarrays are of equal Length. If the subarrays are
* not of equal Length, the return value can be Unpredictable.
* @param arrays
*/
public static double sumproduct(double[][] arrays)
{
double d = 0;
try
{
int narr = arrays.Length;
int arrlen = arrays[0].Length;
for (int j = 0; j < arrlen; j++)
{
double t = 1;
for (int i = 0; i < narr; i++)
{
t *= arrays[i][j];
}
d += t;
}
}
catch (IndexOutOfRangeException)
{
d = double.NaN;
}
return d;
}
/**
* returns the sum of difference of squares of corresponding double
* value in each subarray: ie. sigma (xarr[i]^2-yarr[i]^2)
* <br/>
* It Is the responsibility of the caller
* to Ensure that the two subarrays are of equal Length. If the
* subarrays are not of equal Length, the return value can be
* Unpredictable.
* @param xarr
* @param yarr
*/
public static double sumx2my2(double[] xarr, double[] yarr)
{
double d = 0;
try
{
for (int i = 0, iSize = xarr.Length; i < iSize; i++)
{
d += (xarr[i] + yarr[i]) * (xarr[i] - yarr[i]);
}
}
catch (IndexOutOfRangeException)
{
d = double.NaN;
}
return d;
}
/**
* returns the sum of sum of squares of corresponding double
* value in each subarray: ie. sigma (xarr[i]^2 + yarr[i]^2)
* <br/>
* It Is the responsibility of the caller
* to Ensure that the two subarrays are of equal Length. If the
* subarrays are not of equal Length, the return value can be
* Unpredictable.
* @param xarr
* @param yarr
*/
public static double sumx2py2(double[] xarr, double[] yarr)
{
double d = 0;
try
{
for (int i = 0, iSize = xarr.Length; i < iSize; i++)
{
d += (xarr[i] * xarr[i]) + (yarr[i] * yarr[i]);
}
}
catch (IndexOutOfRangeException )
{
d = double.NaN;
}
return d;
}
/**
* returns the sum of squares of difference of corresponding double
* value in each subarray: ie. sigma ( (xarr[i]-yarr[i])^2 )
* <br/>
* It Is the responsibility of the caller
* to Ensure that the two subarrays are of equal Length. If the
* subarrays are not of equal Length, the return value can be
* Unpredictable.
* @param xarr
* @param yarr
*/
public static double sumxmy2(double[] xarr, double[] yarr)
{
double d = 0;
try
{
for (int i = 0, iSize = xarr.Length; i < iSize; i++)
{
double t = (xarr[i] - yarr[i]);
d += t * t;
}
}
catch (IndexOutOfRangeException )
{
d = double.NaN;
}
return d;
}
/**
* returns the total number of combinations possible when
* k items are chosen out of total of n items. If the number
* Is too large, loss of precision may occur (since returned
* value Is double). If the returned value Is larger than
* double.MAX_VALUE, double.POSITIVE_INFINITY Is returned.
* If either of the parameters Is negative, double.NaN Is returned.
* @param n
* @param k
*/
public static double nChooseK(int n, int k)
{
double d = 1;
if (n < 0 || k < 0 || n < k)
{
d = double.NaN;
}
else
{
int minnk = Math.Min(n - k, k);
int maxnk = Math.Max(n - k, k);
for (int i = maxnk; i < n; i++)
{
d *= i + 1;
}
d /= factorial(minnk);
}
return d;
}
}
}
| |
//-----------------------------------------------------------------------------
// Copyright (c) 2012 GarageGames, LLC
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
//-----------------------------------------------------------------------------
// Provide default values for all World Editor settings. These make use of
// the EditorSettings instance of the Settings class, as defined in the Tools
// package onStart().
EditorSettings.beginGroup( "WorldEditor", true );
EditorSettings.setDefaultValue( "currentEditor", "WorldEditorInspectorPlugin" );
EditorSettings.setDefaultValue( "dropType", "screenCenter" );
EditorSettings.setDefaultValue( "undoLimit", "40" );
EditorSettings.setDefaultValue( "forceLoadDAE", "0" );
EditorSettings.setDefaultValue( "displayType", $EditTsCtrl::DisplayTypePerspective );
EditorSettings.setDefaultValue( "orthoFOV", "50" );
EditorSettings.setDefaultValue( "orthoShowGrid", "1" );
EditorSettings.setDefaultValue( "currentEditor", "WorldEditorInspectorPlugin" );
EditorSettings.setDefaultValue( "newLevelFile", "tools/levels/BlankRoom.mis" );
EditorSettings.setDefaultValue( "newGameObjectDir", "scripts/server/gameObjects" );
if( isFile( "C:/Program Files/Torsion/Torsion.exe" ) )
EditorSettings.setDefaultValue( "torsionPath", "C:/Program Files/Torsion/Torsion.exe" );
else if( isFile( "C:/Program Files (x86)/Torsion/Torsion.exe" ) )
EditorSettings.setDefaultValue( "torsionPath", "C:/Program Files (x86)/Torsion/Torsion.exe" );
else
EditorSettings.setDefaultValue( "torsionPath", "" );
EditorSettings.beginGroup( "ObjectIcons" );
EditorSettings.setDefaultValue( "fadeIcons", "1" );
EditorSettings.setDefaultValue( "fadeIconsStartDist", "8" );
EditorSettings.setDefaultValue( "fadeIconsEndDist", "20" );
EditorSettings.setDefaultValue( "fadeIconsStartAlpha", "255" );
EditorSettings.setDefaultValue( "fadeIconsEndAlpha", "0" );
EditorSettings.endGroup();
EditorSettings.beginGroup( "Grid" );
EditorSettings.setDefaultValue( "gridSize", "1" );
EditorSettings.setDefaultValue( "gridSnap", "0" );
EditorSettings.setDefaultValue( "gridColor", "102 102 102 100" );
EditorSettings.setDefaultValue( "gridOriginColor", "255 255 255 100" );
EditorSettings.setDefaultValue( "gridMinorColor", "51 51 51 100" );
EditorSettings.endGroup();
EditorSettings.beginGroup( "Tools" );
EditorSettings.setDefaultValue( "snapGround", "0" );
EditorSettings.setDefaultValue( "snapSoft", "0" );
EditorSettings.setDefaultValue( "snapSoftSize", "2.0" );
EditorSettings.setDefaultValue( "boundingBoxCollision", "0" );
EditorSettings.setDefaultValue( "objectsUseBoxCenter", "1" );
EditorSettings.setDefaultValue( "dropAtScreenCenterScalar","1.0" );
EditorSettings.setDefaultValue( "dropAtScreenCenterMax", "100.0" );
EditorSettings.endGroup();
EditorSettings.beginGroup( "Render" );
EditorSettings.setDefaultValue( "renderObjHandle", "1" );
EditorSettings.setDefaultValue( "renderObjText", "1" );
EditorSettings.setDefaultValue( "renderPopupBackground", "1" );
EditorSettings.setDefaultValue( "renderSelectionBox", "1" ); //<-- Does not currently render
EditorSettings.setDefaultValue( "showMousePopupInfo", "1" );
//EditorSettings.setDefaultValue( "visibleDistanceScale", "1" );
EditorSettings.endGroup();
EditorSettings.beginGroup( "Color" );
EditorSettings.setDefaultValue( "dragRectColor", "255 255 0 255" );
EditorSettings.setDefaultValue( "objectTextColor", "255 255 255 255" );
EditorSettings.setDefaultValue( "objMouseOverColor", "0 255 0 255" ); //<-- Currently ignored by editor (always white)
EditorSettings.setDefaultValue( "objMouseOverSelectColor", "0 0 255 255" ); //<-- Currently ignored by editor (always white)
EditorSettings.setDefaultValue( "objSelectColor", "255 0 0 255" ); //<-- Currently ignored by editor (always white)
EditorSettings.setDefaultValue( "popupBackgroundColor", "100 100 100 255" );
EditorSettings.setDefaultValue( "popupTextColor", "255 255 0 255" );
EditorSettings.setDefaultValue( "raceSelectColor", "0 0 100 100" ); //<-- What is this used for?
EditorSettings.setDefaultValue( "selectionBoxColor", "255 255 0 255" ); //<-- Does not currently render
EditorSettings.setDefaultValue( "uvEditorHandleColor", "1" ); //<-- Index into color popup
EditorSettings.endGroup();
EditorSettings.beginGroup( "Images" );
EditorSettings.setDefaultValue( "defaultHandle", "tools/worldEditor/images/DefaultHandle" );
EditorSettings.setDefaultValue( "lockedHandle", "tools/worldEditor/images/LockedHandle" );
EditorSettings.setDefaultValue( "selectHandle", "tools/worldEditor/images/SelectHandle" );
EditorSettings.endGroup();
EditorSettings.beginGroup( "Docs" );
EditorSettings.setDefaultValue( "documentationLocal", "../../../Documentation/Official Documentation.html" );
EditorSettings.setDefaultValue( "documentationReference", "../../../Documentation/Torque 3D - Script Manual.chm");
EditorSettings.setDefaultValue( "documentationURL", "http://www.garagegames.com/products/torque-3d/documentation/user" );
EditorSettings.setDefaultValue( "forumURL", "http://www.garagegames.com/products/torque-3d/forums" );
EditorSettings.endGroup();
EditorSettings.endGroup(); // WorldEditor
//-------------------------------------
// After setting up the default value, this field should be altered immediately
// after successfully using such functionality such as Open... or Save As...
EditorSettings.beginGroup( "LevelInformation" );
EditorSettings.setDefaultValue( "levelsDirectory", "levels" );
EditorSettings.endGroup();
//-------------------------------------
EditorSettings.beginGroup( "AxisGizmo", true );
EditorSettings.setDefaultValue( "axisGizmoMaxScreenLen", "100" ); //<-- What is this used for?
EditorSettings.setDefaultValue( "rotationSnap", "15" ); //<-- Not currently used
EditorSettings.setDefaultValue( "snapRotations", "0" ); //<-- Not currently used
EditorSettings.setDefaultValue( "mouseRotateScalar", "0.8" );
EditorSettings.setDefaultValue( "mouseScaleScalar", "0.8" );
EditorSettings.setDefaultValue( "renderWhenUsed", "0" );
EditorSettings.setDefaultValue( "renderInfoText", "1" );
EditorSettings.beginGroup( "Grid" );
EditorSettings.setDefaultValue( "gridColor", "255 255 255 20" );
EditorSettings.setDefaultValue( "gridSize", "10 10 10" );
EditorSettings.setDefaultValue( "snapToGrid", "0" ); //<-- Not currently used
EditorSettings.setDefaultValue( "renderPlane", "0" );
EditorSettings.setDefaultValue( "renderPlaneHashes", "0" );
EditorSettings.setDefaultValue( "planeDim", "500" );
EditorSettings.endGroup();
EditorSettings.endGroup();
//-------------------------------------
EditorSettings.beginGroup( "TerrainEditor", true );
EditorSettings.setDefaultValue( "currentAction", "raiseHeight" );
EditorSettings.beginGroup( "Brush" );
EditorSettings.setDefaultValue( "maxBrushSize", "40 40" );
EditorSettings.setDefaultValue( "brushSize", "1 1" );
EditorSettings.setDefaultValue( "brushType", "box" );
EditorSettings.setDefaultValue( "brushPressure", "1" );
EditorSettings.setDefaultValue( "brushSoftness", "1" );
EditorSettings.endGroup();
EditorSettings.beginGroup( "ActionValues" );
EditorSettings.setDefaultValue( "adjustHeightVal", "10" );
EditorSettings.setDefaultValue( "setHeightVal", "100" );
EditorSettings.setDefaultValue( "scaleVal", "1" ); //<-- Tool not currently implemented
EditorSettings.setDefaultValue( "smoothFactor", "0.1" );
EditorSettings.setDefaultValue( "noiseFactor", "1.0" );
EditorSettings.setDefaultValue( "softSelectRadius", "50" );
EditorSettings.setDefaultValue( "softSelectFilter", "1.000000 0.833333 0.666667 0.500000 0.333333 0.166667 0.000000" );
EditorSettings.setDefaultValue( "softSelectDefaultFilter", "1.000000 0.833333 0.666667 0.500000 0.333333 0.166667 0.000000" );
EditorSettings.setDefaultValue( "slopeMinAngle", "0" );
EditorSettings.setDefaultValue( "slopeMaxAngle", "90" );
EditorSettings.endGroup();
EditorSettings.endGroup();
//-------------------------------------
EditorSettings.beginGroup( "TerrainPainter", true );
EditorSettings.endGroup();
//-------------------------------------
//TODO: this doesn't belong here
function setDefault( %name, %value )
{
if( !isDefined( %name ) )
eval( %name SPC "=" SPC "\"" @ %value @ "\";" );
}
setDefault( "$pref::WorldEditor::visibleDistanceScale", "1" ); // DAW: Keep this around for now as is used by EditTSCtrl
// JCF: Couldn't some or all of these be exposed
// from WorldEditor::ConsoleInit via Con::AddVariable()
// and do away with this file?
function EditorGui::readWorldEditorSettings(%this)
{
EditorSettings.beginGroup( "WorldEditor", true );
EWorldEditor.dropType = EditorSettings.value( "dropType" ); //$pref::WorldEditor::dropType;
EWorldEditor.undoLimit = EditorSettings.value( "undoLimit" ); //$pref::WorldEditor::undoLimit;
EWorldEditor.forceLoadDAE = EditorSettings.value( "forceLoadDAE" ); //$pref::WorldEditor::forceLoadDAE;
%this.currentDisplayType = EditorSettings.value( "displayType" );
%this.currentOrthoFOV = EditorSettings.value( "orthoFOV" );
EWorldEditor.renderOrthoGrid = EditorSettings.value( "orthoShowGrid" );
%this.currentEditor = EditorSettings.value( "currentEditor" );
%this.torsionPath = EditorSettings.value( "torsionPath" );
EditorSettings.beginGroup( "ObjectIcons" );
EWorldEditor.fadeIcons = EditorSettings.value( "fadeIcons" );
EWorldEditor.fadeIconsStartDist = EditorSettings.value( "fadeIconsStartDist" );
EWorldEditor.fadeIconsEndDist = EditorSettings.value( "fadeIconsEndDist" );
EWorldEditor.fadeIconsStartAlpha = EditorSettings.value( "fadeIconsStartAlpha" );
EWorldEditor.fadeIconsEndAlpha = EditorSettings.value( "fadeIconsEndAlpha" );
EditorSettings.endGroup();
EditorSettings.beginGroup( "Grid" );
EWorldEditor.gridSize = EditorSettings.value( "gridSize" );
EWorldEditor.gridSnap = EditorSettings.value( "gridSnap" );
EWorldEditor.gridColor = EditorSettings.value( "gridColor" );
EWorldEditor.gridOriginColor = EditorSettings.value( "gridOriginColor" );
EWorldEditor.gridMinorColor = EditorSettings.value( "gridMinorColor" );
EditorSettings.endGroup();
EditorSettings.beginGroup( "Tools" );
EWorldEditor.stickToGround = EditorSettings.value("snapGround"); //$pref::WorldEditor::snapGround;
EWorldEditor.setSoftSnap( EditorSettings.value("snapSoft") ); //$pref::WorldEditor::snapSoft
EWorldEditor.setSoftSnapSize( EditorSettings.value("snapSoftSize") ); //$pref::WorldEditor::snapSoftSize
EWorldEditor.boundingBoxCollision = EditorSettings.value("boundingBoxCollision"); //$pref::WorldEditor::boundingBoxCollision;
EWorldEditor.objectsUseBoxCenter = EditorSettings.value("objectsUseBoxCenter"); //$pref::WorldEditor::objectsUseBoxCenter;
EWorldEditor.dropAtScreenCenterScalar = EditorSettings.value("dropAtScreenCenterScalar");
EWorldEditor.dropAtScreenCenterMax = EditorSettings.value("dropAtScreenCenterMax");
EditorSettings.endGroup();
EditorSettings.beginGroup( "Render" );
EWorldEditor.renderObjHandle = EditorSettings.value("renderObjHandle"); //$pref::WorldEditor::renderObjHandle;
EWorldEditor.renderObjText = EditorSettings.value("renderObjText"); //$pref::WorldEditor::renderObjText;
EWorldEditor.renderPopupBackground = EditorSettings.value("renderPopupBackground"); //$pref::WorldEditor::renderPopupBackground;
EWorldEditor.renderSelectionBox = EditorSettings.value("renderSelectionBox"); //$pref::WorldEditor::renderSelectionBox;
EWorldEditor.showMousePopupInfo = EditorSettings.value("showMousePopupInfo"); //$pref::WorldEditor::showMousePopupInfo;
EditorSettings.endGroup();
EditorSettings.beginGroup( "Color" );
EWorldEditor.dragRectColor = EditorSettings.value("dragRectColor"); //$pref::WorldEditor::dragRectColor;
EWorldEditor.objectTextColor = EditorSettings.value("objectTextColor"); //$pref::WorldEditor::objectTextColor;
EWorldEditor.objMouseOverColor = EditorSettings.value("objMouseOverColor"); //$pref::WorldEditor::objMouseOverColor;
EWorldEditor.objMouseOverSelectColor = EditorSettings.value("objMouseOverSelectColor"); //$pref::WorldEditor::objMouseOverSelectColor;
EWorldEditor.objSelectColor = EditorSettings.value("objSelectColor"); //$pref::WorldEditor::objSelectColor;
EWorldEditor.popupBackgroundColor = EditorSettings.value("popupBackgroundColor"); //$pref::WorldEditor::popupBackgroundColor;
EWorldEditor.popupTextColor = EditorSettings.value("popupTextColor"); //$pref::WorldEditor::popupTextColor;
EWorldEditor.selectionBoxColor = EditorSettings.value("selectionBoxColor"); //$pref::WorldEditor::selectionBoxColor;
EditorSettings.endGroup();
EditorSettings.beginGroup( "Images" );
EWorldEditor.defaultHandle = EditorSettings.value("defaultHandle"); //$pref::WorldEditor::defaultHandle;
EWorldEditor.lockedHandle = EditorSettings.value("lockedHandle"); //$pref::WorldEditor::lockedHandle;
EWorldEditor.selectHandle = EditorSettings.value("selectHandle"); //$pref::WorldEditor::selectHandle;
EditorSettings.endGroup();
EditorSettings.beginGroup( "Docs" );
EWorldEditor.documentationLocal = EditorSettings.value( "documentationLocal" );
EWorldEditor.documentationURL = EditorSettings.value( "documentationURL" );
EWorldEditor.documentationReference = EditorSettings.value( "documentationReference" );
EWorldEditor.forumURL = EditorSettings.value( "forumURL" );
EditorSettings.endGroup();
//EWorldEditor.planarMovement = $pref::WorldEditor::planarMovement; //<-- What is this used for?
EditorSettings.endGroup(); // WorldEditor
EditorSettings.beginGroup( "AxisGizmo", true );
GlobalGizmoProfile.screenLength = EditorSettings.value("axisGizmoMaxScreenLen"); //$pref::WorldEditor::axisGizmoMaxScreenLen;
GlobalGizmoProfile.rotationSnap = EditorSettings.value("rotationSnap"); //$pref::WorldEditor::rotationSnap;
GlobalGizmoProfile.snapRotations = EditorSettings.value("snapRotations"); //$pref::WorldEditor::snapRotations;
GlobalGizmoProfile.rotateScalar = EditorSettings.value("mouseRotateScalar"); //$pref::WorldEditor::mouseRotateScalar;
GlobalGizmoProfile.scaleScalar = EditorSettings.value("mouseScaleScalar"); //$pref::WorldEditor::mouseScaleScalar;
GlobalGizmoProfile.renderWhenUsed = EditorSettings.value("renderWhenUsed");
GlobalGizmoProfile.renderInfoText = EditorSettings.value("renderInfoText");
EditorSettings.beginGroup( "Grid" );
GlobalGizmoProfile.gridColor = EditorSettings.value("gridColor"); //$pref::WorldEditor::gridColor;
GlobalGizmoProfile.gridSize = EditorSettings.value("gridSize"); //$pref::WorldEditor::gridSize;
GlobalGizmoProfile.snapToGrid = EditorSettings.value("snapToGrid"); //$pref::WorldEditor::snapToGrid;
GlobalGizmoProfile.renderPlane = EditorSettings.value("renderPlane"); //$pref::WorldEditor::renderPlane;
GlobalGizmoProfile.renderPlaneHashes = EditorSettings.value("renderPlaneHashes"); //$pref::WorldEditor::renderPlaneHashes;
GlobalGizmoProfile.planeDim = EditorSettings.value("planeDim"); //$pref::WorldEditor::planeDim;
EditorSettings.endGroup();
EditorSettings.endGroup(); // AxisGizmo
}
function EditorGui::writeWorldEditorSettings(%this)
{
EditorSettings.beginGroup( "WorldEditor", true );
EditorSettings.setValue( "dropType", EWorldEditor.dropType ); //$pref::WorldEditor::dropType
EditorSettings.setValue( "undoLimit", EWorldEditor.undoLimit ); //$pref::WorldEditor::undoLimit
EditorSettings.setValue( "forceLoadDAE", EWorldEditor.forceLoadDAE ); //$pref::WorldEditor::forceLoadDAE
EditorSettings.setValue( "displayType", %this.currentDisplayType );
EditorSettings.setValue( "orthoFOV", %this.currentOrthoFOV );
EditorSettings.setValue( "orthoShowGrid", EWorldEditor.renderOrthoGrid );
EditorSettings.setValue( "currentEditor", %this.currentEditor );
EditorSettings.setvalue( "torsionPath", %this.torsionPath );
EditorSettings.beginGroup( "ObjectIcons" );
EditorSettings.setValue( "fadeIcons", EWorldEditor.fadeIcons );
EditorSettings.setValue( "fadeIconsStartDist", EWorldEditor.fadeIconsStartDist );
EditorSettings.setValue( "fadeIconsEndDist", EWorldEditor.fadeIconsEndDist );
EditorSettings.setValue( "fadeIconsStartAlpha", EWorldEditor.fadeIconsStartAlpha );
EditorSettings.setValue( "fadeIconsEndAlpha", EWorldEditor.fadeIconsEndAlpha );
EditorSettings.endGroup();
EditorSettings.beginGroup( "Grid" );
EditorSettings.setValue( "gridSize", EWorldEditor.gridSize );
EditorSettings.setValue( "gridSnap", EWorldEditor.gridSnap );
EditorSettings.setValue( "gridColor", EWorldEditor.gridColor );
EditorSettings.setValue( "gridOriginColor", EWorldEditor.gridOriginColor );
EditorSettings.setValue( "gridMinorColor", EWorldEditor.gridMinorColor );
EditorSettings.endGroup();
EditorSettings.beginGroup( "Tools" );
EditorSettings.setValue( "snapGround", EWorldEditor.stickToGround ); //$Pref::WorldEditor::snapGround
EditorSettings.setValue( "snapSoft", EWorldEditor.getSoftSnap() ); //$Pref::WorldEditor::snapSoft
EditorSettings.setValue( "snapSoftSize", EWorldEditor.getSoftSnapSize() ); //$Pref::WorldEditor::snapSoftSize
EditorSettings.setValue( "boundingBoxCollision", EWorldEditor.boundingBoxCollision ); //$Pref::WorldEditor::boundingBoxCollision
EditorSettings.setValue( "objectsUseBoxCenter", EWorldEditor.objectsUseBoxCenter ); //$Pref::WorldEditor::objectsUseBoxCenter
EditorSettings.setValue( "dropAtScreenCenterScalar", EWorldEditor.dropAtScreenCenterScalar );
EditorSettings.setValue( "dropAtScreenCenterMax", EWorldEditor.dropAtScreenCenterMax );
EditorSettings.endGroup();
EditorSettings.beginGroup( "Render" );
EditorSettings.setValue( "renderObjHandle", EWorldEditor.renderObjHandle ); //$Pref::WorldEditor::renderObjHandle
EditorSettings.setValue( "renderObjText", EWorldEditor.renderObjText ); //$Pref::WorldEditor::renderObjText
EditorSettings.setValue( "renderPopupBackground", EWorldEditor.renderPopupBackground ); //$Pref::WorldEditor::renderPopupBackground
EditorSettings.setValue( "renderSelectionBox", EWorldEditor.renderSelectionBox ); //$Pref::WorldEditor::renderSelectionBox
EditorSettings.setValue( "showMousePopupInfo", EWorldEditor.showMousePopupInfo ); //$Pref::WorldEditor::showMousePopupInfo
EditorSettings.endGroup();
EditorSettings.beginGroup( "Color" );
EditorSettings.setValue( "dragRectColor", EWorldEditor.dragRectColor ); //$Pref::WorldEditor::dragRectColor
EditorSettings.setValue( "objectTextColor", EWorldEditor.objectTextColor ); //$Pref::WorldEditor::objectTextColor
EditorSettings.setValue( "objMouseOverColor", EWorldEditor.objMouseOverColor ); //$Pref::WorldEditor::objMouseOverColor
EditorSettings.setValue( "objMouseOverSelectColor",EWorldEditor.objMouseOverSelectColor );//$Pref::WorldEditor::objMouseOverSelectColor
EditorSettings.setValue( "objSelectColor", EWorldEditor.objSelectColor ); //$Pref::WorldEditor::objSelectColor
EditorSettings.setValue( "popupBackgroundColor", EWorldEditor.popupBackgroundColor ); //$Pref::WorldEditor::popupBackgroundColor
EditorSettings.setValue( "selectionBoxColor", EWorldEditor.selectionBoxColor ); //$Pref::WorldEditor::selectionBoxColor
EditorSettings.endGroup();
EditorSettings.beginGroup( "Images" );
EditorSettings.setValue( "defaultHandle", EWorldEditor.defaultHandle ); //$Pref::WorldEditor::defaultHandle
EditorSettings.setValue( "selectHandle", EWorldEditor.selectHandle ); //$Pref::WorldEditor::selectHandle
EditorSettings.setValue( "lockedHandle", EWorldEditor.lockedHandle ); //$Pref::WorldEditor::lockedHandle
EditorSettings.endGroup();
EditorSettings.beginGroup( "Docs" );
EditorSettings.setValue( "documentationLocal", EWorldEditor.documentationLocal );
EditorSettings.setValue( "documentationReference", EWorldEditor.documentationReference );
EditorSettings.setValue( "documentationURL", EWorldEditor.documentationURL );
EditorSettings.setValue( "forumURL", EWorldEditor.forumURL );
EditorSettings.endGroup();
EditorSettings.endGroup(); // WorldEditor
EditorSettings.beginGroup( "AxisGizmo", true );
EditorSettings.setValue( "axisGizmoMaxScreenLen", GlobalGizmoProfile.screenLength ); //$Pref::WorldEditor::axisGizmoMaxScreenLen
EditorSettings.setValue( "rotationSnap", GlobalGizmoProfile.rotationSnap ); //$Pref::WorldEditor::rotationSnap
EditorSettings.setValue( "snapRotations", GlobalGizmoProfile.snapRotations ); //$Pref::WorldEditor::snapRotations
EditorSettings.setValue( "mouseRotateScalar", GlobalGizmoProfile.rotateScalar ); //$Pref::WorldEditor::mouseRotateScalar
EditorSettings.setValue( "mouseScaleScalar", GlobalGizmoProfile.scaleScalar ); //$Pref::WorldEditor::mouseScaleScalar
EditorSettings.setValue( "renderWhenUsed", GlobalGizmoProfile.renderWhenUsed );
EditorSettings.setValue( "renderInfoText", GlobalGizmoProfile.renderInfoText );
EditorSettings.beginGroup( "Grid" );
EditorSettings.setValue( "gridColor", GlobalGizmoProfile.gridColor ); //$Pref::WorldEditor::gridColor
EditorSettings.setValue( "gridSize", GlobalGizmoProfile.gridSize ); //$Pref::WorldEditor::gridSize
EditorSettings.setValue( "snapToGrid", GlobalGizmoProfile.snapToGrid ); //$Pref::WorldEditor::snapToGrid
EditorSettings.setValue( "renderPlane", GlobalGizmoProfile.renderPlane ); //$Pref::WorldEditor::renderPlane
EditorSettings.setValue( "renderPlaneHashes", GlobalGizmoProfile.renderPlaneHashes );//$Pref::WorldEditor::renderPlaneHashes
EditorSettings.setValue( "planeDim", GlobalGizmoProfile.planeDim ); //$Pref::WorldEditor::planeDim
EditorSettings.endGroup();
EditorSettings.endGroup(); // AxisGizmo
}
function EditorGui::readTerrainEditorSettings(%this)
{
EditorSettings.beginGroup( "TerrainEditor", true );
ETerrainEditor.savedAction = EditorSettings.value("currentAction");
EditorSettings.beginGroup( "Brush" );
ETerrainEditor.maxBrushSize = EditorSettings.value("maxBrushSize");
ETerrainEditor.setBrushSize( EditorSettings.value("brushSize") );
ETerrainEditor.setBrushType( EditorSettings.value("brushType") );
ETerrainEditor.setBrushPressure( EditorSettings.value("brushPressure") );
ETerrainEditor.setBrushSoftness( EditorSettings.value("brushSoftness") );
EditorSettings.endGroup();
EditorSettings.beginGroup( "ActionValues" );
ETerrainEditor.adjustHeightVal = EditorSettings.value("adjustHeightVal");
ETerrainEditor.setHeightVal = EditorSettings.value("setHeightVal");
ETerrainEditor.scaleVal = EditorSettings.value("scaleVal");
ETerrainEditor.smoothFactor = EditorSettings.value("smoothFactor");
ETerrainEditor.noiseFactor = EditorSettings.value("noiseFactor");
ETerrainEditor.softSelectRadius = EditorSettings.value("softSelectRadius");
ETerrainEditor.softSelectFilter = EditorSettings.value("softSelectFilter");
ETerrainEditor.softSelectDefaultFilter = EditorSettings.value("softSelectDefaultFilter");
ETerrainEditor.setSlopeLimitMinAngle( EditorSettings.value("slopeMinAngle") );
ETerrainEditor.setSlopeLimitMaxAngle( EditorSettings.value("slopeMaxAngle") );
EditorSettings.endGroup();
EditorSettings.endGroup();
}
function EditorGui::writeTerrainEditorSettings(%this)
{
EditorSettings.beginGroup( "TerrainEditor", true );
EditorSettings.setValue( "currentAction", ETerrainEditor.savedAction );
EditorSettings.beginGroup( "Brush" );
EditorSettings.setValue( "maxBrushSize", ETerrainEditor.maxBrushSize );
EditorSettings.setValue( "brushSize", ETerrainEditor.getBrushSize() );
EditorSettings.setValue( "brushType", ETerrainEditor.getBrushType() );
EditorSettings.setValue( "brushPressure", ETerrainEditor.getBrushPressure() );
EditorSettings.setValue( "brushSoftness", ETerrainEditor.getBrushSoftness() );
EditorSettings.endGroup();
EditorSettings.beginGroup( "ActionValues" );
EditorSettings.setValue( "adjustHeightVal", ETerrainEditor.adjustHeightVal );
EditorSettings.setValue( "setHeightVal", ETerrainEditor.setHeightVal );
EditorSettings.setValue( "scaleVal", ETerrainEditor.scaleVal );
EditorSettings.setValue( "smoothFactor", ETerrainEditor.smoothFactor );
EditorSettings.setValue( "noiseFactor", ETerrainEditor.noiseFactor );
EditorSettings.setValue( "softSelectRadius", ETerrainEditor.softSelectRadius );
EditorSettings.setValue( "softSelectFilter", ETerrainEditor.softSelectFilter );
EditorSettings.setValue( "softSelectDefaultFilter",ETerrainEditor.softSelectDefaultFilter );
EditorSettings.setValue( "slopeMinAngle", ETerrainEditor.getSlopeLimitMinAngle() );
EditorSettings.setValue( "slopeMaxAngle", ETerrainEditor.getSlopeLimitMaxAngle() );
EditorSettings.endGroup();
EditorSettings.endGroup();
}
| |
// Graph Engine
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE.md file in the project root for full license information.
//
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Runtime.InteropServices;
using System.Reflection;
using Trinity.Utilities;
using System.Runtime.CompilerServices;
using System.IO;
using Trinity.Diagnostics;
using Trinity.Mathematics;
using Trinity.Core.Lib;
using Trinity.Storage;
using Trinity.Daemon;
using Trinity.Properties;
using Trinity.TSL.Lib;
using Trinity.Network;
using System.Globalization;
namespace Trinity
{
partial class InternalCalls
{
/*************************************************************
*
* One to one mapped to Trinity.C/header/InternalCalls.h
* Each entry is first looked up with reflection. When a matched
* method handle is found, the full name of the entry is then
* synthesized with the following rules:
*
* 1. basic form:
* name_space.class_name::method_name[(optional signature)]
* 2. when parameter type list is provided in the C# entry,
* [optional signature] is synthesized and complies with
* mono naming convension. See GetTypeSignature(Type) for
* detailed rules.
*
*************************************************************/
static private List<InternalCallEntry> iCallEntries = new List<InternalCallEntry>
{
#region TrinityConfig
new InternalCallEntry("SetStorageRoot" , typeof(CTrinityConfig)),
new InternalCallEntry("CReadOnly" , typeof(CTrinityConfig)),
new InternalCallEntry("CSetReadOnly" , typeof(CTrinityConfig)),
new InternalCallEntry("CTrunkCount" , typeof(CTrinityConfig)),
new InternalCallEntry("CSetTrunkCount" , typeof(CTrinityConfig)),
new InternalCallEntry("GetStorageCapacityProfile" , typeof(CTrinityConfig)),
new InternalCallEntry("SetStorageCapacityProfile" , typeof(CTrinityConfig)),
new InternalCallEntry("CLargeObjectThreshold" , typeof(CTrinityConfig)),
new InternalCallEntry("CSetLargeObjectThreshold" , typeof(CTrinityConfig)),
new InternalCallEntry("CSetGCDefragInterval" , typeof(CTrinityConfig)),
#endregion
#region File I/O
new InternalCallEntry("C_wfopen_s" , typeof(CStdio)),
new InternalCallEntry("fread" , typeof(CStdio)),
new InternalCallEntry("fwrite" , typeof(CStdio)),
new InternalCallEntry("fflush" , typeof(CStdio)),
new InternalCallEntry("fclose" , typeof(CStdio)),
new InternalCallEntry("feof" , typeof(CStdio)),
#endregion
#region Memory
new InternalCallEntry("Copy" , typeof(CMemory), new List<Type>(){ typeof(void*), typeof(void*),typeof(int) }),
new InternalCallEntry("malloc" , typeof(CMemory)),
new InternalCallEntry("free" , typeof(CMemory)),
new InternalCallEntry("realloc" , typeof(CMemory)),
new InternalCallEntry("memcpy" , typeof(CMemory)),
new InternalCallEntry("memmove" , typeof(CMemory)),
new InternalCallEntry("memset" , typeof(CMemory)),
new InternalCallEntry("memcmp" , typeof(CMemory)),
new InternalCallEntry("_aligned_malloc" , typeof(CMemory)),
new InternalCallEntry("_aligned_free" , typeof(CMemory)),
new InternalCallEntry("AlignedAlloc" , typeof(CMemory)),
new InternalCallEntry("SetWorkingSetProfile" , typeof(CMemory)),
new InternalCallEntry("SetMaxWorkingSet" , typeof(CMemory)),
#endregion
#region Mathematics
new InternalCallEntry("multiply_double_vector" , typeof(CMathUtility)),
new InternalCallEntry("multiply_sparse_double_vector" , typeof(CMathUtility)),
#endregion
#region GetLastError
new InternalCallEntry("GetLastError" , typeof(CTrinityC)),
#endregion
#region Storage
new InternalCallEntry("CInitialize" , typeof(CLocalMemoryStorage)),
new InternalCallEntry("CCellCount" , typeof(CLocalMemoryStorage)),
new InternalCallEntry("CDispose" , typeof(CLocalMemoryStorage)),
new InternalCallEntry("CSaveStorage" , typeof(CLocalMemoryStorage)),
new InternalCallEntry("CLoadStorage" , typeof(CLocalMemoryStorage)),
new InternalCallEntry("CResetStorage" , typeof(CLocalMemoryStorage)),
new InternalCallEntry("CGetTrinityImageSignature" , typeof(CLocalMemoryStorage)),
/* Non-logging interfaces */
new InternalCallEntry("CSaveCell" , typeof(CLocalMemoryStorage), new List<Type>{typeof(long), typeof(byte*), typeof(int), typeof(ushort)}),
new InternalCallEntry("CAddCell" , typeof(CLocalMemoryStorage), new List<Type>{typeof(long), typeof(byte*), typeof(int), typeof(ushort)}),
new InternalCallEntry("CUpdateCell" , typeof(CLocalMemoryStorage), new List<Type>{typeof(long), typeof(byte*), typeof(int)}),
new InternalCallEntry("CRemoveCell" , typeof(CLocalMemoryStorage), new List<Type>{typeof(long)}),
/* Logging interfaces */
new InternalCallEntry("CSaveCell" , typeof(CLocalMemoryStorage), new List<Type>{typeof(long), typeof(byte*), typeof(int), typeof(ushort), typeof(CellAccessOptions)}),
new InternalCallEntry("CAddCell" , typeof(CLocalMemoryStorage), new List<Type>{typeof(long), typeof(byte*), typeof(int), typeof(ushort), typeof(CellAccessOptions)}),
new InternalCallEntry("CUpdateCell" , typeof(CLocalMemoryStorage), new List<Type>{typeof(long), typeof(byte*), typeof(int), typeof(CellAccessOptions)}),
new InternalCallEntry("CRemoveCell" , typeof(CLocalMemoryStorage), new List<Type>{typeof(long), typeof(CellAccessOptions)}),
new InternalCallEntry("CWriteAheadLog" , typeof(CLocalMemoryStorage)),
new InternalCallEntry("CSetWriteAheadLogFile" , typeof(CLocalMemoryStorage)),
new InternalCallEntry("CWriteAheadLogComputeChecksum" , typeof(LOG_RECORD_HEADER)),
new InternalCallEntry("CWriteAheadLogValidateChecksum" , typeof(LOG_RECORD_HEADER)),
///////////////////////
new InternalCallEntry("CResizeCell" , typeof(CLocalMemoryStorage)),
new InternalCallEntry("CGetCellType" , typeof(CLocalMemoryStorage)),
new InternalCallEntry("CReleaseCellLock" , typeof(CLocalMemoryStorage)),
new InternalCallEntry("CContains" , typeof(CLocalMemoryStorage)),
new InternalCallEntry("CLocalMemoryStorageEnumeratorAllocate" , typeof(CLocalMemoryStorage)),
new InternalCallEntry("CLocalMemoryStorageEnumeratorDeallocate" , typeof(CLocalMemoryStorage)),
new InternalCallEntry("CLocalMemoryStorageEnumeratorMoveNext" , typeof(CLocalMemoryStorage)),
new InternalCallEntry("CLocalMemoryStorageEnumeratorReset" , typeof(CLocalMemoryStorage)),
new InternalCallEntry("CThreadContextAllocate" , typeof(CLocalMemoryStorage)),
new InternalCallEntry("CThreadContextSet" , typeof(CLocalMemoryStorage)),
new InternalCallEntry("CThreadContextDeallocate" , typeof(CLocalMemoryStorage)),
new InternalCallEntry("SetDefragmentationPaused" , typeof(CLocalMemoryStorage)),
new InternalCallEntry("StopDefragAndAwaitCeased" , typeof(CLocalMemoryStorage)),
new InternalCallEntry("RestartDefragmentation" , typeof(CLocalMemoryStorage)),
new InternalCallEntry("CTrunkCommittedMemorySize" , typeof(CLocalMemoryStorage)),
new InternalCallEntry("CMTHashCommittedMemorySize" , typeof(CLocalMemoryStorage)),
new InternalCallEntry("CTotalCommittedMemorySize" , typeof(CLocalMemoryStorage)),
new InternalCallEntry("CTotalCellSize" , typeof(CLocalMemoryStorage)),
new InternalCallEntry("CGetLockedCellInfo4CellAccessor" , typeof(CLocalMemoryStorage)),
new InternalCallEntry("CGetLockedCellInfo4SaveCell" , typeof(CLocalMemoryStorage)),
new InternalCallEntry("CGetLockedCellInfo4AddCell" , typeof(CLocalMemoryStorage)),
new InternalCallEntry("CGetLockedCellInfo4UpdateCell" , typeof(CLocalMemoryStorage)),
new InternalCallEntry("CGetLockedCellInfo4LoadCell" , typeof(CLocalMemoryStorage)),
new InternalCallEntry("CGetLockedCellInfo4AddOrUseCell" , typeof(CLocalMemoryStorage)),
new InternalCallEntry("CLockedGetCellSize" , typeof(CLocalMemoryStorage)),
new InternalCallEntry("CStartDebugger" , typeof(CLocalMemoryStorage)),
#endregion
#region Network
//TODO remove network InternalCall entries
new InternalCallEntry("StartSocketServer" , typeof(CNativeNetwork)),
new InternalCallEntry("ShutdownSocketServer" , typeof(CNativeNetwork)),
new InternalCallEntry("AwaitRequest" , typeof(CNativeNetwork)),
new InternalCallEntry("SendResponse" , typeof(CNativeNetwork)),
new InternalCallEntry("CreateClientSocket" , typeof(CNativeNetwork)),
new InternalCallEntry("ClientSocketConnect" , typeof(CNativeNetwork)),
new InternalCallEntry("ClientSend" , typeof(CNativeNetwork)),
new InternalCallEntry("ClientReceive" , typeof(CNativeNetwork)),
new InternalCallEntry("WaitForAckPackage" , typeof(CNativeNetwork)),
new InternalCallEntry("WaitForStatusPackage" , typeof(CNativeNetwork)),
new InternalCallEntry("CloseClientSocket" , typeof(CNativeNetwork)),
#endregion
};
}
struct InternalCallEntry
{
public InternalCallEntry(string name, Type ctype) : this(name, ctype, null) { }
public InternalCallEntry(string name, Type ctype, List<Type> parameterTypes)
{
MethodName = name;
ClassType = ctype;
ParameterTypes = parameterTypes;
}
public string MethodName;
public Type ClassType;
public List<Type> ParameterTypes;
}
partial class InternalCalls
{
static unsafe InternalCalls()
{
if (Environment.OSVersion.Platform == PlatformID.Win32NT)
{
TrinityC.Ping();
// ---------------- Methods are JITted in Register(), RuntimeHelpers.PrepareMethod
Win32.NativeAPI.timeBeginPeriod(1);
__INIT_TRINITY_C__();
Register();
}
}
/// <summary>
/// Hotswap a C# method with a C function in internal call table
/// </summary>
internal static unsafe void HotSwap(MethodInfo method, string CMethodName)
{
//Prepare the method
RuntimeHelpers.PrepareMethod(method.MethodHandle);
if (!RegisterInternalCall(method.MethodHandle.Value.ToPointer(), CMethodName))
{
throw new InvalidOperationException(String.Format(CultureInfo.InvariantCulture, "{0} cannot be hot hot swapped!", method.Name));
}
}
/// <summary>
/// Hotswap a C# method with another one
/// !!Caution: Make sure that ptr1 and source have same prototype
/// !!Caution: Make sure both methods are marked as "NoInlining"
/// </summary>
internal static unsafe void HotSwap(MethodInfo target, MethodInfo source)
{
RuntimeHelpers.PrepareMethod(target.MethodHandle);
RuntimeHelpers.PrepareMethod(source.MethodHandle);
void* target_ptr = target.MethodHandle.Value.ToPointer();
void* src_ptr = source.MethodHandle.Value.ToPointer();
HotSwapCSharpMethod(target_ptr, src_ptr);
}
/// <summary>
/// Hotswap a C# method with another one
/// !!Caution: Make sure that ptr1 and source have same prototype
/// !!Caution: Make sure both methods are marked as "NoInlining"
/// </summary>
internal static unsafe void HotSwap(Type targetType, string targetMethod, Type sourceType, string sourceMethod)
{
var source = sourceType.GetMethod(sourceMethod, (BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance));
var target = targetType.GetMethod(targetMethod, (BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance));
if (source != null && target != null)
{
//Console.WriteLine("Swapping {0} from {1}", target.Name, source.Name);
HotSwap(target, source);
}
else
{
throw new InvalidOperationException("HotSwap: Failed to find method!");
}
}
private static unsafe void Register()
{
foreach (var entry in iCallEntries)
{
foreach (MethodInfo m in entry.ClassType.GetMethods(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static))
{
//Only static functions are supported
if (!m.IsStatic)
continue;
if (entry.MethodName != m.Name)
continue;
if (m.GetCustomAttribute<DllImportAttribute>() != null)
continue;
if (entry.ParameterTypes != null)
{
var param = m.GetParameters();
if (entry.ParameterTypes.Count != param.Length)
continue;
bool sameTypes = true;
for (int i = 0; i < param.Length; ++i)
{
if (entry.ParameterTypes[i] != param[i].ParameterType)
{
sameTypes = false;
continue;
}
}
if (!sameTypes)
continue;
}
//Method matched. Register it now.
string entry_namespace = entry.ClassType.Namespace;
string entry_classname = entry.ClassType.Name;
string entry_methodname = m.Name;
string entry_methodparams = String.Join(",", from p in m.GetParameters()
select GetTypeSignature(p));
string completeName;
if (entry.ParameterTypes != null)
{
completeName = entry_namespace + "." + entry_classname + "::" + entry_methodname + "(" + entry_methodparams + ")";
}
else
{
completeName = entry_namespace + "." + entry_classname + "::" + entry_methodname;
}
if (!RegisterInternalCall(m.MethodHandle.Value.ToPointer(), completeName))
{
throw new InvalidOperationException(String.Format(CultureInfo.InvariantCulture, "InternalCall {0} cannot be registered!", completeName));
}
break;
}
}
}
/// <summary>
/// See mono source code mono/metadata/debug-helpers.c: mono_type_get_desc
/// </summary>
private static Dictionary<Type, string> s_built_in_types = new Dictionary<Type, string>
{
{typeof(void) ,"void"},
{typeof(char) ,"char"},
{typeof(bool) ,"bool"},
{typeof(byte) ,"byte"},
{typeof(sbyte) ,"sbyte"},
{typeof(ushort) ,"uint16"},
{typeof(short) ,"int16"},
{typeof(uint) ,"uint"},
{typeof(int) ,"int"},
{typeof(ulong) ,"ulong"},
{typeof(long) ,"long"},
//{typeof(uintptr) ,"uintptr"},
//{typeof(intptr) ,"intptr"},
{typeof(float) ,"single"},
{typeof(double) ,"double"},
{typeof(string) ,"string"},
{typeof(object) ,"object"},
};
private static string GetTypeSignature(ParameterInfo p)
{
Type ptype = p.ParameterType;
Type etype = ptype;
bool is_byref = false;
bool is_pointer = false;
do
{
// XXX: no support for array, generics, function pointers etc.
// but these types are not used in InternalCalls.
if (etype.IsByRef) { is_byref = true; }
if (etype.IsPointer) { is_pointer = true; }
if (etype.GetElementType() != null) { etype = etype.GetElementType(); }
} while (etype.GetElementType() != null);
string built_in_type_name;
if (s_built_in_types.TryGetValue(etype, out built_in_type_name))
{
if (is_pointer) { built_in_type_name += "*"; }
if (is_byref) { built_in_type_name += "&"; }
return built_in_type_name;
}
return ptype.FullName;
}
internal static void __init()
{
//Nothing, just trigger the static constructor
}
[DllImport("Trinity.C.dll")]
private static extern unsafe void __INIT_TRINITY_C__();
[DllImport("Trinity.C.dll")]
static private unsafe extern bool RegisterInternalCall(void* MethodTablePtr, string name);
[DllImport("Trinity.C.dll")]
static private unsafe extern void HotSwapCSharpMethod(void* TargetMethodDesc, void* SourceMethodDesc);
}
}
| |
using System;
using System.Collections;
using UnityEngine;
#if UNITY_EDITOR
using UnityEditor;
#endif
namespace UnitySampleAssets.Utility
{
public class WaypointCircuit : MonoBehaviour
{
public WaypointList waypointList = new WaypointList();
[SerializeField] private bool smoothRoute = true;
private int numPoints;
private Vector3[] points;
private float[] distances;
public float editorVisualisationSubsteps = 100;
public float Length { get; private set; }
public Transform[] Waypoints
{
get { return waypointList.items; }
}
//this being here will save GC allocs
private int p0n;
private int p1n;
private int p2n;
private int p3n;
private float i;
private Vector3 P0;
private Vector3 P1;
private Vector3 P2;
private Vector3 P3;
// Use this for initialization
private void Awake()
{
if (Waypoints.Length > 1)
{
CachePositionsAndDistances();
}
numPoints = Waypoints.Length;
}
public RoutePoint GetRoutePoint(float dist)
{
// position and direction
Vector3 p1 = GetRoutePosition(dist);
Vector3 p2 = GetRoutePosition(dist + 0.1f);
Vector3 delta = p2 - p1;
return new RoutePoint(p1, delta.normalized);
}
public Vector3 GetRoutePosition(float dist)
{
int point = 0;
if (Length == 0)
{
Length = distances[distances.Length - 1];
}
dist = Mathf.Repeat(dist, Length);
while (distances[point] < dist)
{
++point;
}
// get nearest two points, ensuring points wrap-around start & end of circuit
p1n = ((point - 1) + numPoints)%numPoints;
p2n = point;
// found point numbers, now find interpolation value between the two middle points
i = Mathf.InverseLerp(distances[p1n], distances[p2n], dist);
if (smoothRoute)
{
// smooth catmull-rom calculation between the two relevant points
// get indices for the surrounding 2 points, because
// four points are required by the catmull-rom function
p0n = ((point - 2) + numPoints)%numPoints;
p3n = (point + 1)%numPoints;
// 2nd point may have been the 'last' point - a dupe of the first,
// (to give a value of max track distance instead of zero)
// but now it must be wrapped back to zero if that was the case.
p2n = p2n%numPoints;
P0 = points[p0n];
P1 = points[p1n];
P2 = points[p2n];
P3 = points[p3n];
return CatmullRom(P0, P1, P2, P3, i);
}
else
{
// simple linear lerp between the two points:
p1n = ((point - 1) + numPoints)%numPoints;
p2n = point;
return Vector3.Lerp(points[p1n], points[p2n], i);
}
}
private Vector3 CatmullRom(Vector3 _P0, Vector3 _P1, Vector3 _P2, Vector3 _P3, float _i)
{
// comments are no use here... it's the catmull-rom equation.
// Un-magic this, lord vector!
return 0.5f*
((2*_P1) + (-_P0 + _P2)*_i + (2*_P0 - 5*_P1 + 4*_P2 - _P3)*_i*_i +
(-_P0 + 3*_P1 - 3*_P2 + _P3)*_i*_i*_i);
}
private void CachePositionsAndDistances()
{
// transfer the position of each point and distances between points to arrays for
// speed of lookup at runtime
points = new Vector3[Waypoints.Length + 1];
distances = new float[Waypoints.Length + 1];
float accumulateDistance = 0;
for (int i = 0; i < points.Length; ++i)
{
var t1 = Waypoints[(i)%Waypoints.Length];
var t2 = Waypoints[(i + 1)%Waypoints.Length];
if (t1 != null && t2 != null)
{
Vector3 p1 = t1.position;
Vector3 p2 = t2.position;
points[i] = Waypoints[i%Waypoints.Length].position;
distances[i] = accumulateDistance;
accumulateDistance += (p1 - p2).magnitude;
}
}
}
private void OnDrawGizmos()
{
DrawGizmos(false);
}
private void OnDrawGizmosSelected()
{
DrawGizmos(true);
}
private void DrawGizmos(bool selected)
{
waypointList.circuit = this;
if (Waypoints.Length > 1)
{
numPoints = Waypoints.Length;
CachePositionsAndDistances();
Length = distances[distances.Length - 1];
Gizmos.color = selected ? Color.yellow : new Color(1, 1, 0, 0.5f);
Vector3 prev = Waypoints[0].position;
if (smoothRoute)
{
for (float dist = 0; dist < Length; dist += Length/editorVisualisationSubsteps)
{
Vector3 next = GetRoutePosition(dist + 1);
Gizmos.DrawLine(prev, next);
prev = next;
}
Gizmos.DrawLine(prev, Waypoints[0].position);
}
else
{
for (int n = 0; n < Waypoints.Length; ++n)
{
Vector3 next = Waypoints[(n + 1)%Waypoints.Length].position;
Gizmos.DrawLine(prev, next);
prev = next;
}
}
}
}
[Serializable]
public class WaypointList
{
public WaypointCircuit circuit;
public Transform[] items = new Transform[0];
}
public struct RoutePoint
{
public Vector3 position;
public Vector3 direction;
public RoutePoint(Vector3 position, Vector3 direction)
{
this.position = position;
this.direction = direction;
}
}
}
}
namespace UnitySampleAssets.Utility.Inspector
{
#if UNITY_EDITOR
[CustomPropertyDrawer(typeof (WaypointCircuit.WaypointList))]
public class WaypointListDrawer : PropertyDrawer
{
private float lineHeight = 18;
private float spacing = 4;
public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
{
EditorGUI.BeginProperty(position, label, property);
float x = position.x;
float y = position.y;
float inspectorWidth = position.width;
// Draw label
// Don't make child fields be indented
var indent = EditorGUI.indentLevel;
EditorGUI.indentLevel = 0;
var items = property.FindPropertyRelative("items");
var titles = new string[] {"Transform", "", "", ""};
var props = new string[] {"transform", "^", "v", "-"};
var widths = new float[] {.7f, .1f, .1f, .1f};
float lineHeight = 18;
bool changedLength = false;
if (items.arraySize > 0)
{
for (int i = -1; i < items.arraySize; ++i)
{
var item = items.GetArrayElementAtIndex(i);
float rowX = x;
for (int n = 0; n < props.Length; ++n)
{
float w = widths[n]*inspectorWidth;
// Calculate rects
Rect rect = new Rect(rowX, y, w, lineHeight);
rowX += w;
if (i == -1)
{
EditorGUI.LabelField(rect, titles[n]);
}
else
{
if (n == 0)
{
EditorGUI.ObjectField(rect, item.objectReferenceValue, typeof (Transform), true);
}
else
{
if (GUI.Button(rect, props[n]))
{
switch (props[n])
{
case "-":
items.DeleteArrayElementAtIndex(i);
items.DeleteArrayElementAtIndex(i);
changedLength = true;
break;
case "v":
if (i > 0)
{
items.MoveArrayElement(i, i + 1);
}
break;
case "^":
if (i < items.arraySize - 1)
{
items.MoveArrayElement(i, i - 1);
}
break;
}
}
}
}
}
y += lineHeight + spacing;
if (changedLength)
{
break;
}
}
}
else
{
// add button
var addButtonRect = new Rect((x + position.width) - widths[widths.Length - 1]*inspectorWidth, y,
widths[widths.Length - 1]*inspectorWidth, lineHeight);
if (GUI.Button(addButtonRect, "+"))
{
items.InsertArrayElementAtIndex(items.arraySize);
}
y += lineHeight + spacing;
}
// add all button
var addAllButtonRect = new Rect(x, y, inspectorWidth, lineHeight);
if (GUI.Button(addAllButtonRect, "Assign using all child objects"))
{
var circuit = property.FindPropertyRelative("circuit").objectReferenceValue as WaypointCircuit;
var children = new Transform[circuit.transform.childCount];
int n = 0;
foreach (Transform child in circuit.transform)
{
children[n++] = child;
}
Array.Sort(children, new TransformNameComparer());
circuit.waypointList.items = new Transform[children.Length];
for (n = 0; n < children.Length; ++n)
{
circuit.waypointList.items[n] = children[n];
}
}
y += lineHeight + spacing;
// rename all button
var renameButtonRect = new Rect(x, y, inspectorWidth, lineHeight);
if (GUI.Button(renameButtonRect, "Auto Rename numerically from this order"))
{
var circuit = property.FindPropertyRelative("circuit").objectReferenceValue as WaypointCircuit;
int n = 0;
foreach (Transform child in circuit.waypointList.items)
{
child.name = "Waypoint " + (n++).ToString("000");
}
}
y += lineHeight + spacing;
// Set indent back to what it was
EditorGUI.indentLevel = indent;
EditorGUI.EndProperty();
}
public override float GetPropertyHeight(SerializedProperty property, GUIContent label)
{
SerializedProperty items = property.FindPropertyRelative("items");
float lineAndSpace = lineHeight + spacing;
return 40 + (items.arraySize*lineAndSpace) + lineAndSpace;
}
// comparer for check distances in ray cast hits
public class TransformNameComparer : IComparer
{
public int Compare(object x, object y)
{
return ((Transform) x).name.CompareTo(((Transform) y).name);
}
}
}
#endif
}
| |
using System.IO.Ports;
using Microsoft.SPOT.Hardware;
namespace Ktos.MicroFramework.Stm32
{
/// <summary>
/// Based on: https://kodfilemon.googlecode.com/svn/trunk/STM32F4Discovery_Demo/Common/Stm32F4Discovery.cs
/// </summary>
public class Stm32F4Discovery
{
/// <summary>
/// Static constructor is run on every boot on .NET Micro Framework, registers HardwareProvider
/// </summary>
static Stm32F4Discovery()
{
HardwareProvider.Register(new Stm32F4DiscoveryHardwareProvider());
}
/// <summary>
/// A hardware provider for STM32F4-DISCOVERY
/// </summary>
private sealed class Stm32F4DiscoveryHardwareProvider : HardwareProvider
{
}
/// <summary>
/// Defines numeric values for CPU pins with human-readable name
/// </summary>
public class Pins
{
public const Cpu.Pin GPIO_NONE = Cpu.Pin.GPIO_NONE;
public const Cpu.Pin PA0 = 0 * 16 + 0; //0
public const Cpu.Pin PA1 = (Cpu.Pin)(0 * 16 + 1); //1 ADC0 COM2(rts)
public const Cpu.Pin PA2 = (Cpu.Pin)(0 * 16 + 2); //2 ADC1 COM2(tx)
public const Cpu.Pin PA3 = (Cpu.Pin)(0 * 16 + 3); //3 ADC2 COM2(rx)
public const Cpu.Pin PA4 = (Cpu.Pin)(0 * 16 + 4); //4
public const Cpu.Pin PA5 = (Cpu.Pin)(0 * 16 + 5); //5 SPI0(msk)
public const Cpu.Pin PA6 = (Cpu.Pin)(0 * 16 + 6); //6 SPI0(miso)
public const Cpu.Pin PA7 = (Cpu.Pin)(0 * 16 + 7); //7 SPI0(mosi)
public const Cpu.Pin PA8 = (Cpu.Pin)(0 * 16 + 8); //8
public const Cpu.Pin PA9 = (Cpu.Pin)(0 * 16 + 9); //9 COM1(tx)
public const Cpu.Pin PA10 = (Cpu.Pin)(0 * 16 + 10); //10 COM1(rx)
public const Cpu.Pin PA11 = (Cpu.Pin)(0 * 16 + 11); //11 COM1(cts)
public const Cpu.Pin PA12 = (Cpu.Pin)(0 * 16 + 12); //12 COM1(rts)
public const Cpu.Pin PA13 = (Cpu.Pin)(0 * 16 + 13); //13
public const Cpu.Pin PA14 = (Cpu.Pin)(0 * 16 + 14); //14
public const Cpu.Pin PA15 = (Cpu.Pin)(0 * 16 + 15); //15
public const Cpu.Pin PB0 = (Cpu.Pin)(1 * 16 + 0); //16 ADC3
public const Cpu.Pin PB1 = (Cpu.Pin)(1 * 16 + 1); //17 ADC4
public const Cpu.Pin PB2 = (Cpu.Pin)(1 * 16 + 2); //18
public const Cpu.Pin PB3 = (Cpu.Pin)(1 * 16 + 3); //19
public const Cpu.Pin PB4 = (Cpu.Pin)(1 * 16 + 4); //20
public const Cpu.Pin PB5 = (Cpu.Pin)(1 * 16 + 5); //21
public const Cpu.Pin PB6 = (Cpu.Pin)(1 * 16 + 6); //22 I2C(scl)
public const Cpu.Pin PB7 = (Cpu.Pin)(1 * 16 + 7); //23
public const Cpu.Pin PB8 = (Cpu.Pin)(1 * 16 + 8); //24
public const Cpu.Pin PB9 = (Cpu.Pin)(1 * 16 + 9); //25 I2C(sda)
public const Cpu.Pin PB10 = (Cpu.Pin)(1 * 16 + 10); //26
public const Cpu.Pin PB11 = (Cpu.Pin)(1 * 16 + 11); //27
public const Cpu.Pin PB12 = (Cpu.Pin)(1 * 16 + 12); //28
public const Cpu.Pin PB13 = (Cpu.Pin)(1 * 16 + 13); //29 SPI1(msk)
public const Cpu.Pin PB14 = (Cpu.Pin)(1 * 16 + 14); //30 SPI1(miso)
public const Cpu.Pin PB15 = (Cpu.Pin)(1 * 16 + 15); //31 SPI1(mosi)
public const Cpu.Pin PC0 = (Cpu.Pin)(2 * 16 + 0); //32
public const Cpu.Pin PC1 = (Cpu.Pin)(2 * 16 + 1); //33
public const Cpu.Pin PC2 = (Cpu.Pin)(2 * 16 + 2); //34
public const Cpu.Pin PC3 = (Cpu.Pin)(2 * 16 + 3); //35
public const Cpu.Pin PC4 = (Cpu.Pin)(2 * 16 + 4); //36 ADC5
public const Cpu.Pin PC5 = (Cpu.Pin)(2 * 16 + 5); //37 ADC6
public const Cpu.Pin PC6 = (Cpu.Pin)(2 * 16 + 6); //38 COM6(tx)
public const Cpu.Pin PC7 = (Cpu.Pin)(2 * 16 + 7); //39 COM6(rx)
public const Cpu.Pin PC8 = (Cpu.Pin)(2 * 16 + 8); //40
public const Cpu.Pin PC9 = (Cpu.Pin)(2 * 16 + 9); //41
public const Cpu.Pin PC10 = (Cpu.Pin)(2 * 16 + 10); //42 SPI2(msk) COM4(tx)
public const Cpu.Pin PC11 = (Cpu.Pin)(2 * 16 + 11); //43 SPI2(miso) COM4(rx)
public const Cpu.Pin PC12 = (Cpu.Pin)(2 * 16 + 12); //44 SPI2(mosi) COM5(tx)
public const Cpu.Pin PC13 = (Cpu.Pin)(2 * 16 + 13); //45
public const Cpu.Pin PC14 = (Cpu.Pin)(2 * 16 + 14); //46
public const Cpu.Pin PC15 = (Cpu.Pin)(2 * 16 + 15); //47
public const Cpu.Pin PD0 = (Cpu.Pin)(3 * 16 + 0); //48
public const Cpu.Pin PD1 = (Cpu.Pin)(3 * 16 + 1); //49
public const Cpu.Pin PD2 = (Cpu.Pin)(3 * 16 + 2); //50 COM5: (rx)
public const Cpu.Pin PD3 = (Cpu.Pin)(3 * 16 + 3); //51 COM2(cts)
public const Cpu.Pin PD4 = (Cpu.Pin)(3 * 16 + 4); //52
public const Cpu.Pin PD5 = (Cpu.Pin)(3 * 16 + 5); //53
public const Cpu.Pin PD6 = (Cpu.Pin)(3 * 16 + 6); //54
public const Cpu.Pin PD7 = (Cpu.Pin)(3 * 16 + 7); //55
public const Cpu.Pin PD8 = (Cpu.Pin)(3 * 16 + 8); //56 COM3(tx)
public const Cpu.Pin PD9 = (Cpu.Pin)(3 * 16 + 9); //57 COM3(rx)
public const Cpu.Pin PD10 = (Cpu.Pin)(3 * 16 + 10); //58
public const Cpu.Pin PD11 = (Cpu.Pin)(3 * 16 + 11); //59 COM3(cts)
public const Cpu.Pin PD12 = (Cpu.Pin)(3 * 16 + 12); //60 PWM0 COM3(rts)
public const Cpu.Pin PD13 = (Cpu.Pin)(3 * 16 + 13); //61 PWM1
public const Cpu.Pin PD14 = (Cpu.Pin)(3 * 16 + 14); //62 PWM2
public const Cpu.Pin PD15 = (Cpu.Pin)(3 * 16 + 15); //63 PWM3
public const Cpu.Pin PE0 = (Cpu.Pin)(4 * 16 + 0); //64
public const Cpu.Pin PE1 = (Cpu.Pin)(4 * 16 + 1); //65
public const Cpu.Pin PE2 = (Cpu.Pin)(4 * 16 + 2); //66
public const Cpu.Pin PE3 = (Cpu.Pin)(4 * 16 + 3); //67
public const Cpu.Pin PE4 = (Cpu.Pin)(4 * 16 + 4); //68
public const Cpu.Pin PE5 = (Cpu.Pin)(4 * 16 + 5); //69
public const Cpu.Pin PE6 = (Cpu.Pin)(4 * 16 + 6); //70
public const Cpu.Pin PE7 = (Cpu.Pin)(4 * 16 + 7); //71
public const Cpu.Pin PE8 = (Cpu.Pin)(4 * 16 + 8); //72
public const Cpu.Pin PE9 = (Cpu.Pin)(4 * 16 + 9); //73 PWM4
public const Cpu.Pin PE10 = (Cpu.Pin)(4 * 16 + 10); //74
public const Cpu.Pin PE11 = (Cpu.Pin)(4 * 16 + 11); //75 PWM5
public const Cpu.Pin PE12 = (Cpu.Pin)(4 * 16 + 12); //76
public const Cpu.Pin PE13 = (Cpu.Pin)(4 * 16 + 13); //77 PWM6
public const Cpu.Pin PE14 = (Cpu.Pin)(4 * 16 + 14); //78 PWM7
public const Cpu.Pin PE15 = (Cpu.Pin)(4 * 16 + 15); //79
/// <summary>
/// Returns a pin name as a string from pin numeric value
/// </summary>
/// <param name="pin">CPU pin numeric value</param>
/// <returns>A pin name</returns>
public static string GetPinName(Cpu.Pin pin)
{
if (pin == Cpu.Pin.GPIO_NONE)
return "GPIO_NONE";
var pinNumber = (int)pin;
int port = pinNumber / 16;
int num = pinNumber - 16 * port;
string result = "P" + (char)('A' + port) + num;
return result;
}
}
/// <summary>
/// Defines numeric values for pins associated with buttons
/// </summary>
public class ButtonPins
{
public const Cpu.Pin User = Pins.PA0;
}
/// <summary>
/// Defines numeric values for pins associated with built-in LEDs
/// </summary>
public class LedPins
{
public const Cpu.Pin Green = Pins.PD12; //60
public const Cpu.Pin Orange = Pins.PD13; //61
public const Cpu.Pin Red = Pins.PD14; //62
public const Cpu.Pin Blue = Pins.PD15; //63
}
/// <summary>
/// Lists every free to use pin
/// </summary>
public class FreePins
{
public const Cpu.Pin PA1 = Pins.PA1;
public const Cpu.Pin PA2 = Pins.PA2;
public const Cpu.Pin PA3 = Pins.PA3;
public const Cpu.Pin PA8 = Pins.PA8;
public const Cpu.Pin PA15 = Pins.PA15;
public const Cpu.Pin PB0 = Pins.PB0;
public const Cpu.Pin PB1 = Pins.PB1;
public const Cpu.Pin PB2 = Pins.PB2;
public const Cpu.Pin PB4 = Pins.PB4;
public const Cpu.Pin PB5 = Pins.PB5;
public const Cpu.Pin PB7 = Pins.PB7;
public const Cpu.Pin PB8 = Pins.PB8;
public const Cpu.Pin PB11 = Pins.PB11;
public const Cpu.Pin PB12 = Pins.PB12;
public const Cpu.Pin PB13 = Pins.PB13;
public const Cpu.Pin PB14 = Pins.PB14;
public const Cpu.Pin PB15 = Pins.PB15;
public const Cpu.Pin PC1 = Pins.PC1;
public const Cpu.Pin PC2 = Pins.PC2;
public const Cpu.Pin PC4 = Pins.PC4;
public const Cpu.Pin PC5 = Pins.PC5;
public const Cpu.Pin PC6 = Pins.PC6;
public const Cpu.Pin PC8 = Pins.PC8;
public const Cpu.Pin PC9 = Pins.PC9;
public const Cpu.Pin PC11 = Pins.PC11;
public const Cpu.Pin PC13 = Pins.PC13;
public const Cpu.Pin PC14 = Pins.PC14;
public const Cpu.Pin PC15 = Pins.PC15;
public const Cpu.Pin PD1 = Pins.PD1;
public const Cpu.Pin PD2 = Pins.PD2;
public const Cpu.Pin PD3 = Pins.PD3;
public const Cpu.Pin PD6 = Pins.PD6;
public const Cpu.Pin PD7 = Pins.PD7;
public const Cpu.Pin PD8 = Pins.PD8;
public const Cpu.Pin PD9 = Pins.PD9;
public const Cpu.Pin PD10 = Pins.PD10;
public const Cpu.Pin PD11 = Pins.PD11;
public const Cpu.Pin PE3 = Pins.PE3;
public const Cpu.Pin PE4 = Pins.PE4;
public const Cpu.Pin PE5 = Pins.PE5;
public const Cpu.Pin PE6 = Pins.PE6;
public const Cpu.Pin PE7 = Pins.PE7;
public const Cpu.Pin PE8 = Pins.PE8;
public const Cpu.Pin PE9 = Pins.PE9;
public const Cpu.Pin PE10 = Pins.PE10;
public const Cpu.Pin PE11 = Pins.PE11;
public const Cpu.Pin PE12 = Pins.PE12;
public const Cpu.Pin PE13 = Pins.PE13;
public const Cpu.Pin PE14 = Pins.PE14;
public const Cpu.Pin PE15 = Pins.PE15;
}
/// <summary>
/// Defines serial ports on device
/// </summary>
public static class SerialPorts
{
public const string COM1 = Serial.COM1;
public const string COM2 = Serial.COM2;
public const string COM3 = Serial.COM3;
public const string COM4 = "COM4";
public const string COM5 = "COM5";
public const string COM6 = "COM6";
}
/// <summary>
/// Defines SPI devices on device
/// </summary>
public static class SpiDevices
{
public const SPI.SPI_module SPI1 = SPI.SPI_module.SPI1;
public const SPI.SPI_module SPI2 = SPI.SPI_module.SPI2;
public const SPI.SPI_module SPI3 = SPI.SPI_module.SPI3;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Windows.Forms;
using Bloom.MiscUI;
using Bloom.web.controllers;
using DesktopAnalytics;
using Sentry;
using SIL.Reporting;
using SIL.Windows.Forms.Progress;
namespace Bloom
{
// NB: these must have the exactly the same symbols
public enum ModalIf { None, Alpha, Beta, All }
public enum PassiveIf { None, Alpha, Beta, All }
/// <summary>
/// Provides a way to note a problem in the log and, depending on channel, notify the user.
/// </summary>
public class NonFatalProblem
{
/// <summary>
/// Always log, possibly inform the user, possibly throw the exception
/// </summary>
/// <param name="modalThreshold">Will show a modal dialog if the channel is this or lower</param>
/// <param name="passiveThreshold">Will toast if channel is this or lower (and didn't modal) and shortUserLevelMessage is defined.</param>
/// <param name="shortUserLevelMessage">Simple message that fits in small toast notification</param>
/// <param name="moreDetails">Info adds information about the problem, which we get if they report the problem</param>
/// <param name="exception"></param>
/// <param name="showSendReport">Set to 'false' to eliminate yellow screens and "Report" links on toasts</param>
public static void Report(ModalIf modalThreshold, PassiveIf passiveThreshold, string shortUserLevelMessage = null,
string moreDetails = null,
Exception exception = null, bool showSendReport = true, bool isShortMessagePreEncoded = false, bool skipSentryReport = false, bool showRequestDetails = false,
string[] additionalFilesToInclude = null)
{
var originalException = exception;
s_expectedByUnitTest?.ProblemWasReported();
var channel = ApplicationUpdateSupport.ChannelName.ToLowerInvariant();
try
{
shortUserLevelMessage = shortUserLevelMessage ?? "";
var fullDetailedMessage = shortUserLevelMessage;
if(!string.IsNullOrEmpty(moreDetails))
fullDetailedMessage = fullDetailedMessage + System.Environment.NewLine + moreDetails;
if(exception == null)
{
//the code below is simpler if we always have an exception, even this thing that gives
//us the stacktrace we would otherwise be missing. Note, you might be tempted to throw
//and then catch an exception instead, but for some reason the resulting stack trace
//would contain only this method.
exception = new ApplicationException(new StackTrace().ToString());
}
if(Program.RunningUnitTests)
{
//It's not clear to me what we can do that works for all unit test scenarios...
//We can imagine those for which throwing an exception at this point would be helpful,
//but there are others in which say, not finding a file is expected. Either way,
//the rest of the test should fail if the problem is real, so doing anything here
//would just be a help, not really necessary for getting the test to fail.
//So, for now I'm going to just go with doing nothing in general.
// We'll save a little information so we can write specific "this does not report a problem"
// tests.
LastNonFatalProblemReported = fullDetailedMessage;
return;
}
if (!skipSentryReport)
{
if (originalException != null)
ReportSentryOnly(originalException, fullDetailedMessage);
else
ReportSentryOnly(shortUserLevelMessage, fullDetailedMessage);
}
//if this isn't going modal even for devs, it's just background noise and we don't want the
//thousands of exceptions we were getting as with BL-3280
if (modalThreshold != ModalIf.None)
{
Analytics.ReportException(exception);
}
Logger.WriteError("NonFatalProblem: " + fullDetailedMessage, exception);
if (Program.RunningInConsoleMode)
{
// This is "nonfatal", so report as best we can (standard error) and keep going...
Console.Error.WriteLine($"Nonfatal problem: {fullDetailedMessage}");
return;
}
//just convert from PassiveIf to ModalIf so that we don't have to duplicate code
var passive = (ModalIf)ModalIf.Parse(typeof(ModalIf), passiveThreshold.ToString());
var formForSynchronizing = Application.OpenForms.Cast<Form>().LastOrDefault();
if (formForSynchronizing is ProgressDialog)
{
// Targetting ProgressDialog doesn't work so well for toasts, since the dialog tends
// to disappear immediately and the user never sees the toast.
modalThreshold = passive;
}
if (Matches(modalThreshold).Any(s => channel.Contains(s)))
{
try
{
if (showSendReport)
{
// N.B.: We should be more careful than ever about when we want 'showSendReport' to be 'true',
// since this new "nonfatal" UI doesn't have a "Cancel" button.
ProblemReportApi.ShowProblemDialog(Form.ActiveForm, exception, fullDetailedMessage, "nonfatal", shortUserLevelMessage, isShortMessagePreEncoded,additionalFilesToInclude);
}
else
{
// We don't want any notification (MessageBox or toast) targetting a ProgressDialog,
// since the dialog seems to disappear quickly and leave us hanging... and not able to show.
// We'll keep the form if it's not a ProgressDialog in order to center our message properly.
if (formForSynchronizing is ProgressDialog)
{
MessageBox.Show(fullDetailedMessage, string.Empty, MessageBoxButtons.OK);
} else {
MessageBox.Show(formForSynchronizing, fullDetailedMessage, string.Empty, MessageBoxButtons.OK);
}
}
}
catch (Exception ex)
{
Bloom.Utils.MiscUtils.SuppressUnusedExceptionVarWarning(ex);
//if we're running when the UI is already shut down, the above is going to throw.
//At least if we're running in a debugger, we'll stop here:
throw new ApplicationException(fullDetailedMessage + "Error trying to report normally.");
}
return;
}
if(!string.IsNullOrEmpty(shortUserLevelMessage) && Matches(passive).Any(s => channel.Contains(s)))
{
ShowToast(shortUserLevelMessage, exception, fullDetailedMessage, showSendReport, showRequestDetails);
}
}
catch(Exception errorWhileReporting)
{
// Don't annoy developers for expected error if the internet is not available.
if (errorWhileReporting.Message.StartsWith("Bloom could not retrieve the URL") && Bloom.web.UrlLookup.FastInternetAvailable)
{
Debug.Fail("error in nonfatalError reporting");
}
if (channel.Contains("developer") || channel.Contains("alpha"))
ErrorReport.NotifyUserOfProblem(errorWhileReporting,"Error while reporting non fatal error");
}
}
/// <summary>
/// Sends a report to Sentry only (no log, no toast, etc.).
/// Does not send to Sentry if ApplicationUpdateSupport.IsDev is true.
/// Fails silently (unless throwOnException is true).
/// </summary>
/// <param name="exception">The exception to report to Sentry</param>
/// <param name="message">An optional message to send with the exception to provide more context</param>
/// <param name="throwOnException">If true, will rethrow any exception which occurs while reporting to Sentry.</param>
/// <remarks>Note, some previous Sentry reports were adding the message as a fullDetailedMessage tag, but when we refactored
/// to create this method, we decided to standardize on the more versatile breadcrumbs approach.</remarks>
public static void ReportSentryOnly(Exception exception, string message = null, bool throwOnException = false)
{
if (ApplicationUpdateSupport.IsDev)
{
Debug.WriteLine("Developer, we though you might want to know that ReportSentryOnly() was called. Ignore if you like.");
Debug.Indent();
Debug.WriteLine(exception);
Debug.Unindent();
return;
}
try
{
if (!string.IsNullOrWhiteSpace(message))
SentrySdk.AddBreadcrumb(message);
SentrySdk.CaptureException(exception);
}
catch (Exception err)
{
// will only "do something" if we're testing reporting and have thus turned off checking for dev
Debug.Fail(err.Message);
if (throwOnException)
throw;
}
}
/// <summary>
/// Sends a report to Sentry only (no log, no toast, etc.).
/// Does not send to Sentry if ApplicationUpdateSupport.IsDev is true.
/// Fails silently.
/// </summary>
/// <param name="message">The message to send with the report</param>
/// <param name="fullDetailedMessage">An optional message which can be added to the Sentry report</param>
public static void ReportSentryOnly(string message, string fullDetailedMessage = null)
{
if (ApplicationUpdateSupport.IsDev)
{
Debug.WriteLine("Developer, we though you might want to know that ReportSentryOnly() was called. Ignore if you like.");
Debug.Indent();
Debug.WriteLine(message);
Debug.WriteLine(fullDetailedMessage);
Debug.Unindent();
return;
}
try
{
var evt = new SentryEvent { Message = message };
if (!string.IsNullOrWhiteSpace(fullDetailedMessage))
evt.SetExtra("fullDetailedMessage", fullDetailedMessage);
evt.SetExtra("stackTrace", new StackTrace().ToString());
SentrySdk.CaptureEvent(evt);
}
catch (Exception err)
{
// will only "do something" if we're testing reporting and have thus turned off checking for dev
Debug.Fail(err.Message);
}
}
private static void ShowToast(string shortUserLevelMessage, Exception exception, string fullDetailedMessage, bool showSendReport = true, bool showDetailsOnRequest = false)
{
// The form is used for the screen shot as well as for synchronizing, so get the shell if possible.
// See https://issues.bloomlibrary.org/youtrack/issue/BL-8348.
var formForSynchronizing = Application.OpenForms.Cast<Form>().Where(x => x is Bloom.Shell).FirstOrDefault();
if (formForSynchronizing == null)
formForSynchronizing = Application.OpenForms.Cast<Form>().LastOrDefault();
if (formForSynchronizing == null)
return; // can't safely show a toast, may be on wrong thread.
if (formForSynchronizing.InvokeRequired)
{
formForSynchronizing.BeginInvoke(new Action(() =>
{
ShowToast(shortUserLevelMessage, exception, fullDetailedMessage, showSendReport);
}));
return;
}
var toast = new ToastNotifier();
var callToAction = string.Empty;
if (showSendReport)
{
toast.ToastClicked +=
(s, e) =>
{
ProblemReportApi.ShowProblemDialog(formForSynchronizing, exception, fullDetailedMessage, "nonfatal", shortUserLevelMessage);
};
callToAction = "Report";
}
else if (showDetailsOnRequest)
{
toast.ToastClicked +=
(s, e) =>
{
ErrorReport.NotifyUserOfProblem(new ShowAlwaysPolicy(), null, default(ErrorResult), "{0}",
string.Join(Environment.NewLine, // handle Linux newlines on Windows (and vice-versa)
fullDetailedMessage.Split(new[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries)));
};
callToAction = "Details";
}
toast.Image.Image = ToastNotifier.WarningBitmap;
toast.Show(shortUserLevelMessage, callToAction, 5);
}
private static IEnumerable<string> Matches(ModalIf threshold)
{
switch (threshold)
{
case ModalIf.All:
return new string[] { "" /*will match anything*/};
case ModalIf.Beta:
return new string[] { "developer", "alpha", "beta" };
case ModalIf.Alpha:
return new string[] { "developer", "alpha" };
default:
return new string[] { };
}
}
private static ExpectedByUnitTest s_expectedByUnitTest = null;
public static string LastNonFatalProblemReported = null; // just for unit tests
/// <summary>
/// use this in unit tests to cleanly check that a message would have been shown.
/// E.g. using (new NonFatalProblem.ExpectedByUnitTest()) {...}
/// </summary>
public class ExpectedByUnitTest : IDisposable
{
private bool _reported;
public ExpectedByUnitTest()
{
s_expectedByUnitTest?.Dispose();
s_expectedByUnitTest = this;
}
internal void ProblemWasReported()
{
_reported = true;
}
public void Dispose()
{
s_expectedByUnitTest = null;
if (!_reported)
throw new Exception("NonFatalProblem was expected but wasn't generated.");
}
}
}
}
| |
//
// Copyright (c) 2004-2011 Jaroslaw Kowalski <[email protected]>
//
// 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.LayoutRenderers
{
using System;
using System.Collections.Generic;
using NLog.LayoutRenderers;
using NLog.Layouts;
using NLog.Targets;
using NLog.Internal;
using Xunit;
public class ExceptionTests : NLogTestBase
{
private ILogger logger = LogManager.GetLogger("NLog.UnitTests.LayoutRenderer.ExceptionTests");
private const string ExceptionDataFormat = "{0}: {1}";
[Fact]
public void ExceptionWithStackTrace_ObsoleteMethodTest()
{
LogManager.Configuration = CreateConfigurationFromString(@"
<nlog>
<targets>
<target name='debug1' type='Debug' layout='${exception}' />
<target name='debug2' type='Debug' layout='${exception:format=stacktrace}' />
<target name='debug3' type='Debug' layout='${exception:format=type}' />
<target name='debug4' type='Debug' layout='${exception:format=shorttype}' />
<target name='debug5' type='Debug' layout='${exception:format=tostring}' />
<target name='debug6' type='Debug' layout='${exception:format=message}' />
<target name='debug7' type='Debug' layout='${exception:format=method}' />
<target name='debug8' type='Debug' layout='${exception:format=message,shorttype:separator=*}' />
<target name='debug9' type='Debug' layout='${exception:format=data}' />
</targets>
<rules>
<logger minlevel='Info' writeTo='debug1,debug2,debug3,debug4,debug5,debug6,debug7,debug8,debug9' />
</rules>
</nlog>");
const string exceptionMessage = "Test exception";
const string exceptionDataKey = "testkey";
const string exceptionDataValue = "testvalue";
Exception ex = GetExceptionWithStackTrace(exceptionMessage);
ex.Data.Add(exceptionDataKey, exceptionDataValue);
#pragma warning disable 0618
// Obsolete method requires testing until completely removed.
logger.ErrorException("msg", ex);
#pragma warning restore 0618
AssertDebugLastMessage("debug1", exceptionMessage);
AssertDebugLastMessage("debug2", ex.StackTrace);
AssertDebugLastMessage("debug3", typeof(InvalidOperationException).FullName);
AssertDebugLastMessage("debug4", typeof(InvalidOperationException).Name);
AssertDebugLastMessage("debug5", ex.ToString());
AssertDebugLastMessage("debug6", exceptionMessage);
AssertDebugLastMessage("debug9", string.Format(ExceptionDataFormat, exceptionDataKey, exceptionDataValue));
// each version of the framework produces slightly different information for MethodInfo, so we just
// make sure it's not empty
var debug7Target = (NLog.Targets.DebugTarget)LogManager.Configuration.FindTargetByName("debug7");
Assert.False(string.IsNullOrEmpty(debug7Target.LastMessage));
AssertDebugLastMessage("debug8", "Test exception*" + typeof(InvalidOperationException).Name);
}
[Fact]
public void ExceptionWithStackTraceTest()
{
LogManager.Configuration = CreateConfigurationFromString(@"
<nlog>
<targets>
<target name='debug1' type='Debug' layout='${exception}' />
<target name='debug2' type='Debug' layout='${exception:format=stacktrace}' />
<target name='debug3' type='Debug' layout='${exception:format=type}' />
<target name='debug4' type='Debug' layout='${exception:format=shorttype}' />
<target name='debug5' type='Debug' layout='${exception:format=tostring}' />
<target name='debug6' type='Debug' layout='${exception:format=message}' />
<target name='debug7' type='Debug' layout='${exception:format=method}' />
<target name='debug8' type='Debug' layout='${exception:format=message,shorttype:separator=*}' />
<target name='debug9' type='Debug' layout='${exception:format=data}' />
</targets>
<rules>
<logger minlevel='Info' writeTo='debug1,debug2,debug3,debug4,debug5,debug6,debug7,debug8,debug9' />
</rules>
</nlog>");
const string exceptionMessage = "Test exception";
const string exceptionDataKey = "testkey";
const string exceptionDataValue = "testvalue";
Exception ex = GetExceptionWithStackTrace(exceptionMessage);
ex.Data.Add(exceptionDataKey, exceptionDataValue);
logger.Error(ex, "msg");
AssertDebugLastMessage("debug1", exceptionMessage);
AssertDebugLastMessage("debug2", ex.StackTrace);
AssertDebugLastMessage("debug3", typeof(InvalidOperationException).FullName);
AssertDebugLastMessage("debug4", typeof(InvalidOperationException).Name);
AssertDebugLastMessage("debug5", ex.ToString());
AssertDebugLastMessage("debug6", exceptionMessage);
AssertDebugLastMessage("debug9", string.Format(ExceptionDataFormat, exceptionDataKey, exceptionDataValue));
// each version of the framework produces slightly different information for MethodInfo, so we just
// make sure it's not empty
var debug7Target = (NLog.Targets.DebugTarget)LogManager.Configuration.FindTargetByName("debug7");
Assert.False(string.IsNullOrEmpty(debug7Target.LastMessage));
AssertDebugLastMessage("debug8", "Test exception*" + typeof(InvalidOperationException).Name);
}
[Fact]
public void ExceptionWithoutStackTrace_ObsoleteMethodTest()
{
LogManager.Configuration = CreateConfigurationFromString(@"
<nlog>
<targets>
<target name='debug1' type='Debug' layout='${exception}' />
<target name='debug2' type='Debug' layout='${exception:format=stacktrace}' />
<target name='debug3' type='Debug' layout='${exception:format=type}' />
<target name='debug4' type='Debug' layout='${exception:format=shorttype}' />
<target name='debug5' type='Debug' layout='${exception:format=tostring}' />
<target name='debug6' type='Debug' layout='${exception:format=message}' />
<target name='debug7' type='Debug' layout='${exception:format=method}' />
<target name='debug8' type='Debug' layout='${exception:format=message,shorttype:separator=*}' />
<target name='debug9' type='Debug' layout='${exception:format=data}' />
</targets>
<rules>
<logger minlevel='Info' writeTo='debug1,debug2,debug3,debug4,debug5,debug6,debug7,debug8,debug9' />
</rules>
</nlog>");
const string exceptionMessage = "Test exception";
const string exceptionDataKey = "testkey";
const string exceptionDataValue = "testvalue";
Exception ex = GetExceptionWithoutStackTrace(exceptionMessage);
ex.Data.Add(exceptionDataKey, exceptionDataValue);
#pragma warning disable 0618
// Obsolete method requires testing until completely removed.
logger.ErrorException("msg", ex);
#pragma warning restore 0618
AssertDebugLastMessage("debug1", exceptionMessage);
AssertDebugLastMessage("debug2", "");
AssertDebugLastMessage("debug3", typeof(InvalidOperationException).FullName);
AssertDebugLastMessage("debug4", typeof(InvalidOperationException).Name);
AssertDebugLastMessage("debug5", ex.ToString());
AssertDebugLastMessage("debug6", exceptionMessage);
AssertDebugLastMessage("debug7", "");
AssertDebugLastMessage("debug8", "Test exception*" + typeof(InvalidOperationException).Name);
AssertDebugLastMessage("debug9", string.Format(ExceptionDataFormat, exceptionDataKey, exceptionDataValue));
}
[Fact]
public void ExceptionWithoutStackTraceTest()
{
LogManager.Configuration = CreateConfigurationFromString(@"
<nlog>
<targets>
<target name='debug1' type='Debug' layout='${exception}' />
<target name='debug2' type='Debug' layout='${exception:format=stacktrace}' />
<target name='debug3' type='Debug' layout='${exception:format=type}' />
<target name='debug4' type='Debug' layout='${exception:format=shorttype}' />
<target name='debug5' type='Debug' layout='${exception:format=tostring}' />
<target name='debug6' type='Debug' layout='${exception:format=message}' />
<target name='debug7' type='Debug' layout='${exception:format=method}' />
<target name='debug8' type='Debug' layout='${exception:format=message,shorttype:separator=*}' />
<target name='debug9' type='Debug' layout='${exception:format=data}' />
</targets>
<rules>
<logger minlevel='Info' writeTo='debug1,debug2,debug3,debug4,debug5,debug6,debug7,debug8,debug9' />
</rules>
</nlog>");
const string exceptionMessage = "Test exception";
const string exceptionDataKey = "testkey";
const string exceptionDataValue = "testvalue";
Exception ex = GetExceptionWithoutStackTrace(exceptionMessage);
ex.Data.Add(exceptionDataKey, exceptionDataValue);
logger.Error(ex, "msg");
AssertDebugLastMessage("debug1", exceptionMessage);
AssertDebugLastMessage("debug2", "");
AssertDebugLastMessage("debug3", typeof(InvalidOperationException).FullName);
AssertDebugLastMessage("debug4", typeof(InvalidOperationException).Name);
AssertDebugLastMessage("debug5", ex.ToString());
AssertDebugLastMessage("debug6", exceptionMessage);
AssertDebugLastMessage("debug7", "");
AssertDebugLastMessage("debug8", "Test exception*" + typeof(InvalidOperationException).Name);
AssertDebugLastMessage("debug9", string.Format(ExceptionDataFormat, exceptionDataKey, exceptionDataValue));
}
[Fact]
public void ExceptionNewLineSeparatorTest()
{
LogManager.Configuration = CreateConfigurationFromString(@"
<nlog>
<targets>
<target name='debug1' type='Debug' layout='${exception:format=message,shorttype:separator= }' />
</targets>
<rules>
<logger minlevel='Info' writeTo='debug1' />
</rules>
</nlog>");
string exceptionMessage = "Test exception";
Exception ex = GetExceptionWithStackTrace(exceptionMessage);
#pragma warning disable 0618
// Obsolete method requires testing until completely removed.
logger.ErrorException("msg", ex);
AssertDebugLastMessage("debug1", "Test exception\r\n" + typeof(InvalidOperationException).Name);
#pragma warning restore 0618
logger.Error(ex, "msg");
AssertDebugLastMessage("debug1", "Test exception\r\n" + typeof(InvalidOperationException).Name);
}
[Fact]
public void ExceptionUsingLogMethodTest()
{
SetConfigurationForExceptionUsingRootMethodTests();
string exceptionMessage = "Test exception";
Exception ex = GetExceptionWithStackTrace(exceptionMessage);
logger.Log(LogLevel.Error, ex, "msg");
AssertDebugLastMessage("debug1", "ERROR*Test exception*" + typeof(InvalidOperationException).Name);
}
[Fact]
public void ExceptionUsingTraceMethodTest()
{
SetConfigurationForExceptionUsingRootMethodTests();
string exceptionMessage = "Test exception";
Exception ex = GetExceptionWithStackTrace(exceptionMessage);
logger.Trace(ex, "msg");
AssertDebugLastMessage("debug1", "TRACE*Test exception*" + typeof(InvalidOperationException).Name);
}
[Fact]
public void ExceptionUsingDebugMethodTest()
{
SetConfigurationForExceptionUsingRootMethodTests();
string exceptionMessage = "Test exception";
Exception ex = GetExceptionWithStackTrace(exceptionMessage);
logger.Debug(ex, "msg");
AssertDebugLastMessage("debug1", "DEBUG*Test exception*" + typeof(InvalidOperationException).Name);
}
[Fact]
public void ExceptionUsingInfoMethodTest()
{
SetConfigurationForExceptionUsingRootMethodTests();
string exceptionMessage = "Test exception";
Exception ex = GetExceptionWithStackTrace(exceptionMessage);
logger.Info(ex, "msg");
AssertDebugLastMessage("debug1", "INFO*Test exception*" + typeof(InvalidOperationException).Name);
}
[Fact]
public void ExceptionUsingWarnMethodTest()
{
SetConfigurationForExceptionUsingRootMethodTests();
string exceptionMessage = "Test exception";
Exception ex = GetExceptionWithStackTrace(exceptionMessage);
logger.Warn(ex, "msg");
AssertDebugLastMessage("debug1", "WARN*Test exception*" + typeof(InvalidOperationException).Name);
}
[Fact]
public void ExceptionUsingErrorMethodTest()
{
SetConfigurationForExceptionUsingRootMethodTests();
string exceptionMessage = "Test exception";
Exception ex = GetExceptionWithStackTrace(exceptionMessage);
logger.Error(ex, "msg");
AssertDebugLastMessage("debug1", "ERROR*Test exception*" + typeof(InvalidOperationException).Name);
}
[Fact]
public void ExceptionUsingFatalMethodTest()
{
SetConfigurationForExceptionUsingRootMethodTests();
string exceptionMessage = "Test exception";
Exception ex = GetExceptionWithStackTrace(exceptionMessage);
logger.Fatal(ex, "msg");
AssertDebugLastMessage("debug1", "FATAL*Test exception*" + typeof(InvalidOperationException).Name);
}
[Fact]
public void InnerExceptionTest()
{
LogManager.Configuration = CreateConfigurationFromString(@"
<nlog>
<targets>
<target name='debug1' type='Debug' layout='${exception:format=shorttype,message:maxInnerExceptionLevel=3}' />
</targets>
<rules>
<logger minlevel='Info' writeTo='debug1' />
</rules>
</nlog>");
string exceptionMessage = "Test exception";
Exception ex = GetNestedExceptionWithStackTrace(exceptionMessage);
#pragma warning disable 0618
// Obsolete method requires testing until completely removed.
logger.ErrorException("msg", ex);
AssertDebugLastMessage("debug1", "InvalidOperationException Wrapper2" + EnvironmentHelper.NewLine +
"InvalidOperationException Wrapper1" + EnvironmentHelper.NewLine +
"InvalidOperationException Test exception");
#pragma warning restore 0618
logger.Error(ex, "msg");
AssertDebugLastMessage("debug1", "InvalidOperationException Wrapper2" + EnvironmentHelper.NewLine +
"InvalidOperationException Wrapper1" + EnvironmentHelper.NewLine +
"InvalidOperationException Test exception");
}
[Fact]
public void CustomInnerException_ObsoleteMethodTest()
{
LogManager.Configuration = CreateConfigurationFromString(@"
<nlog>
<targets>
<target name='debug1' type='Debug' layout='${exception:format=shorttype,message:maxInnerExceptionLevel=1:innerExceptionSeparator= ----INNER---- :innerFormat=type,message}' />
<target name='debug2' type='Debug' layout='${exception:format=shorttype,message:maxInnerExceptionLevel=1:innerExceptionSeparator= ----INNER---- :innerFormat=type,message,data}' />
</targets>
<rules>
<logger minlevel='Info' writeTo='debug1' />
<logger minlevel='Info' writeTo='debug2' />
</rules>
</nlog>");
var t = (DebugTarget)LogManager.Configuration.AllTargets[0];
var elr = ((SimpleLayout)t.Layout).Renderers[0] as ExceptionLayoutRenderer;
Assert.Equal("\r\n----INNER----\r\n", elr.InnerExceptionSeparator);
string exceptionMessage = "Test exception";
const string exceptionDataKey = "testkey";
const string exceptionDataValue = "testvalue";
Exception ex = GetNestedExceptionWithStackTrace(exceptionMessage);
ex.InnerException.Data.Add(exceptionDataKey, exceptionDataValue);
#pragma warning disable 0618
// Obsolete method requires testing until completely removed.
logger.ErrorException("msg", ex);
#pragma warning restore 0618
AssertDebugLastMessage("debug1", "InvalidOperationException Wrapper2" +
"\r\n----INNER----\r\n" +
"System.InvalidOperationException Wrapper1");
AssertDebugLastMessage("debug2", string.Format("InvalidOperationException Wrapper2" +
"\r\n----INNER----\r\n" +
"System.InvalidOperationException Wrapper1 " + ExceptionDataFormat, exceptionDataKey, exceptionDataValue));
}
[Fact]
public void CustomInnerExceptionTest()
{
LogManager.Configuration = CreateConfigurationFromString(@"
<nlog>
<targets>
<target name='debug1' type='Debug' layout='${exception:format=shorttype,message:maxInnerExceptionLevel=1:innerExceptionSeparator= ----INNER---- :innerFormat=type,message}' />
<target name='debug2' type='Debug' layout='${exception:format=shorttype,message:maxInnerExceptionLevel=1:innerExceptionSeparator= ----INNER---- :innerFormat=type,message,data}' />
</targets>
<rules>
<logger minlevel='Info' writeTo='debug1' />
<logger minlevel='Info' writeTo='debug2' />
</rules>
</nlog>");
var t = (DebugTarget)LogManager.Configuration.AllTargets[0];
var elr = ((SimpleLayout) t.Layout).Renderers[0] as ExceptionLayoutRenderer;
Assert.Equal("\r\n----INNER----\r\n", elr.InnerExceptionSeparator);
string exceptionMessage = "Test exception";
const string exceptionDataKey = "testkey";
const string exceptionDataValue = "testvalue";
Exception ex = GetNestedExceptionWithStackTrace(exceptionMessage);
ex.InnerException.Data.Add(exceptionDataKey, exceptionDataValue);
logger.Error(ex, "msg");
AssertDebugLastMessage("debug1", "InvalidOperationException Wrapper2" +
"\r\n----INNER----\r\n" +
"System.InvalidOperationException Wrapper1");
AssertDebugLastMessage("debug2", string.Format("InvalidOperationException Wrapper2" +
"\r\n----INNER----\r\n" +
"System.InvalidOperationException Wrapper1 " + ExceptionDataFormat, exceptionDataKey, exceptionDataValue));
}
[Fact]
public void ErrorException_should_not_throw_exception_when_exception_message_property_throw_exception()
{
LogManager.Configuration = CreateConfigurationFromString(@"
<nlog>
<targets>
<target name='debug1' type='Debug' layout='${exception}' />
</targets>
<rules>
<logger minlevel='Info' writeTo='debug1' />
</rules>
</nlog>");
var ex = new ExceptionWithBrokenMessagePropertyException();
#pragma warning disable 0618
// Obsolete method requires testing until completely removed.
Assert.ThrowsDelegate action = () => logger.ErrorException("msg", ex);
#pragma warning restore 0618
Assert.DoesNotThrow(action);
}
private class ExceptionWithBrokenMessagePropertyException : NLogConfigurationException
{
public override string Message
{
get { throw new Exception("Exception from Message property"); }
}
}
private void SetConfigurationForExceptionUsingRootMethodTests()
{
LogManager.Configuration = CreateConfigurationFromString(@"
<nlog>
<targets>
<target name='debug1' type='Debug' layout='${level:uppercase=true}*${exception:format=message,shorttype:separator=*}' />
</targets>
<rules>
<logger minlevel='Trace' writeTo='debug1' />
</rules>
</nlog>");
}
private Exception GetExceptionWithStackTrace(string exceptionMessage)
{
try
{
GenericClass<int, string, bool>.Method1("aaa", true, null, 42, DateTime.Now);
return null;
}
catch (Exception exception)
{
return exception;
}
}
private Exception GetNestedExceptionWithStackTrace(string exceptionMessage)
{
try
{
try
{
try
{
GenericClass<int, string, bool>.Method1("aaa", true, null, 42, DateTime.Now);
}
catch (Exception exception)
{
throw new InvalidOperationException("Wrapper1", exception);
}
}
catch (Exception exception)
{
throw new InvalidOperationException("Wrapper2", exception);
}
return null;
}
catch (Exception ex)
{
return ex;
}
}
private Exception GetExceptionWithoutStackTrace(string exceptionMessage)
{
return new InvalidOperationException(exceptionMessage);
}
private class GenericClass<TA, TB, TC>
{
internal static List<GenericClass<TA, TB, TC>> Method1(string aaa, bool b, object o, int i, DateTime now)
{
Method2(aaa, b, o, i, now, null, null);
return null;
}
internal static int Method2<T1, T2, T3>(T1 aaa, T2 b, T3 o, int i, DateTime now, Nullable<int> gfff, List<int>[] something)
{
throw new InvalidOperationException("Test exception");
}
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.