context stringlengths 2.52k 185k | gt stringclasses 1 value |
|---|---|
/*
* Exchange Web Services Managed API
*
* Copyright (c) Microsoft Corporation
* All rights reserved.
*
* MIT License
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this
* software and associated documentation files (the "Software"), to deal in the Software
* without restriction, including without limitation the rights to use, copy, modify, merge,
* publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
* to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or
* substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
* PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
* FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
* OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
namespace Microsoft.Exchange.WebServices.Data
{
using System;
using System.Collections.Generic;
using System.Text;
/// <summary>
/// Represents a SearchMailboxesRequest request.
/// </summary>
internal sealed class SearchMailboxesRequest : MultiResponseServiceRequest<SearchMailboxesResponse>, IDiscoveryVersionable
{
private List<MailboxQuery> searchQueries = new List<MailboxQuery>();
private SearchResultType searchResultType = SearchResultType.PreviewOnly;
private SortDirection sortOrder = SortDirection.Ascending;
private string sortByProperty;
private bool performDeduplication;
private int pageSize;
private string pageItemReference;
private SearchPageDirection pageDirection = SearchPageDirection.Next;
private PreviewItemResponseShape previewItemResponseShape;
/// <summary>
/// Initializes a new instance of the <see cref="SearchMailboxesRequest"/> class.
/// </summary>
/// <param name="service">The service.</param>
/// <param name="errorHandlingMode"> Indicates how errors should be handled.</param>
internal SearchMailboxesRequest(ExchangeService service, ServiceErrorHandling errorHandlingMode)
: base(service, errorHandlingMode)
{
}
/// <summary>
/// Creates the service response.
/// </summary>
/// <param name="service">The service.</param>
/// <param name="responseIndex">Index of the response.</param>
/// <returns>Service response.</returns>
internal override SearchMailboxesResponse CreateServiceResponse(ExchangeService service, int responseIndex)
{
return new SearchMailboxesResponse();
}
/// <summary>
/// Gets the name of the response XML element.
/// </summary>
/// <returns>XML element name.</returns>
internal override string GetResponseXmlElementName()
{
return XmlElementNames.SearchMailboxesResponse;
}
/// <summary>
/// Gets the name of the response message XML element.
/// </summary>
/// <returns>XML element name.</returns>
internal override string GetResponseMessageXmlElementName()
{
return XmlElementNames.SearchMailboxesResponseMessage;
}
/// <summary>
/// Gets the expected response message count.
/// </summary>
/// <returns>Number of expected response messages.</returns>
internal override int GetExpectedResponseMessageCount()
{
return 1;
}
/// <summary>
/// Gets the name of the XML element.
/// </summary>
/// <returns>XML element name.</returns>
internal override string GetXmlElementName()
{
return XmlElementNames.SearchMailboxes;
}
/// <summary>
/// Validate request.
/// </summary>
internal override void Validate()
{
base.Validate();
if (this.SearchQueries == null || this.SearchQueries.Count == 0)
{
throw new ServiceValidationException(Strings.MailboxQueriesParameterIsNotSpecified);
}
foreach (MailboxQuery searchQuery in this.SearchQueries)
{
if (searchQuery.MailboxSearchScopes == null || searchQuery.MailboxSearchScopes.Length == 0)
{
throw new ServiceValidationException(Strings.MailboxQueriesParameterIsNotSpecified);
}
}
if (!string.IsNullOrEmpty(this.SortByProperty))
{
PropertyDefinitionBase prop = null;
try
{
prop = ServiceObjectSchema.FindPropertyDefinition(this.SortByProperty);
}
catch (KeyNotFoundException)
{
}
if (prop == null)
{
throw new ServiceValidationException(string.Format(Strings.InvalidSortByPropertyForMailboxSearch, this.SortByProperty));
}
}
}
/// <summary>
/// Parses the response.
/// See O15:324151 on why we need to override ParseResponse here instead of calling the one in MultiResponseServiceRequest.cs
/// </summary>
/// <param name="reader">The reader.</param>
/// <returns>Service response collection.</returns>
internal override object ParseResponse(EwsServiceXmlReader reader)
{
ServiceResponseCollection<SearchMailboxesResponse> serviceResponses = new ServiceResponseCollection<SearchMailboxesResponse>();
reader.ReadStartElement(XmlNamespace.Messages, XmlElementNames.ResponseMessages);
while (true)
{
// Read ahead to see if we've reached the end of the response messages early.
reader.Read();
if (reader.IsEndElement(XmlNamespace.Messages, XmlElementNames.ResponseMessages))
{
break;
}
SearchMailboxesResponse response = new SearchMailboxesResponse();
response.LoadFromXml(reader, this.GetResponseMessageXmlElementName());
serviceResponses.Add(response);
}
reader.ReadEndElementIfNecessary(XmlNamespace.Messages, XmlElementNames.ResponseMessages);
return serviceResponses;
}
/// <summary>
/// Writes XML elements.
/// </summary>
/// <param name="writer">The writer.</param>
internal override void WriteElementsToXml(EwsServiceXmlWriter writer)
{
writer.WriteStartElement(XmlNamespace.Messages, XmlElementNames.SearchQueries);
foreach (MailboxQuery mailboxQuery in this.SearchQueries)
{
writer.WriteStartElement(XmlNamespace.Types, XmlElementNames.MailboxQuery);
writer.WriteElementValue(XmlNamespace.Types, XmlElementNames.Query, mailboxQuery.Query);
writer.WriteStartElement(XmlNamespace.Types, XmlElementNames.MailboxSearchScopes);
foreach (MailboxSearchScope mailboxSearchScope in mailboxQuery.MailboxSearchScopes)
{
// The checks here silently downgrade the schema based on compatibility checks, to receive errors use the validate method
if (mailboxSearchScope.SearchScopeType == MailboxSearchScopeType.LegacyExchangeDN || DiscoverySchemaChanges.SearchMailboxesAdditionalSearchScopes.IsCompatible(this))
{
writer.WriteStartElement(XmlNamespace.Types, XmlElementNames.MailboxSearchScope);
writer.WriteElementValue(XmlNamespace.Types, XmlElementNames.Mailbox, mailboxSearchScope.Mailbox);
writer.WriteElementValue(XmlNamespace.Types, XmlElementNames.SearchScope, mailboxSearchScope.SearchScope);
if (DiscoverySchemaChanges.SearchMailboxesExtendedData.IsCompatible(this))
{
writer.WriteStartElement(XmlNamespace.Types, XmlElementNames.ExtendedAttributes);
if (mailboxSearchScope.SearchScopeType != MailboxSearchScopeType.LegacyExchangeDN)
{
writer.WriteStartElement(XmlNamespace.Types, XmlElementNames.ExtendedAttribute);
writer.WriteElementValue(XmlNamespace.Types, XmlElementNames.ExtendedAttributeName, XmlElementNames.SearchScopeType);
writer.WriteElementValue(XmlNamespace.Types, XmlElementNames.ExtendedAttributeValue, mailboxSearchScope.SearchScopeType);
writer.WriteEndElement();
}
if (mailboxSearchScope.ExtendedAttributes != null && mailboxSearchScope.ExtendedAttributes.Count > 0)
{
foreach (ExtendedAttribute attribute in mailboxSearchScope.ExtendedAttributes)
{
writer.WriteStartElement(XmlNamespace.Types, XmlElementNames.ExtendedAttribute);
writer.WriteElementValue(XmlNamespace.Types, XmlElementNames.ExtendedAttributeName, attribute.Name);
writer.WriteElementValue(XmlNamespace.Types, XmlElementNames.ExtendedAttributeValue, attribute.Value);
writer.WriteEndElement();
}
}
writer.WriteEndElement(); // ExtendedData
}
writer.WriteEndElement(); // MailboxSearchScope
}
}
writer.WriteEndElement(); // MailboxSearchScopes
writer.WriteEndElement(); // MailboxQuery
}
writer.WriteEndElement(); // SearchQueries
writer.WriteElementValue(XmlNamespace.Messages, XmlElementNames.ResultType, this.ResultType);
if (this.PreviewItemResponseShape != null)
{
writer.WriteStartElement(XmlNamespace.Messages, XmlElementNames.PreviewItemResponseShape);
writer.WriteElementValue(XmlNamespace.Types, XmlElementNames.BaseShape, this.PreviewItemResponseShape.BaseShape);
if (this.PreviewItemResponseShape.AdditionalProperties != null && this.PreviewItemResponseShape.AdditionalProperties.Length > 0)
{
writer.WriteStartElement(XmlNamespace.Types, XmlElementNames.AdditionalProperties);
foreach (ExtendedPropertyDefinition additionalProperty in this.PreviewItemResponseShape.AdditionalProperties)
{
additionalProperty.WriteToXml(writer);
}
writer.WriteEndElement(); // AdditionalProperties
}
writer.WriteEndElement(); // PreviewItemResponseShape
}
if (!string.IsNullOrEmpty(this.SortByProperty))
{
writer.WriteStartElement(XmlNamespace.Messages, XmlElementNames.SortBy);
writer.WriteAttributeValue(XmlElementNames.Order, this.SortOrder.ToString());
writer.WriteStartElement(XmlNamespace.Types, XmlElementNames.FieldURI);
writer.WriteAttributeValue(XmlElementNames.FieldURI, this.sortByProperty);
writer.WriteEndElement(); // FieldURI
writer.WriteEndElement(); // SortBy
}
// Language
if (!string.IsNullOrEmpty(this.Language))
{
writer.WriteElementValue(XmlNamespace.Messages, XmlElementNames.Language, this.Language);
}
// Dedupe
writer.WriteElementValue(XmlNamespace.Messages, XmlElementNames.Deduplication, this.performDeduplication);
if (this.PageSize > 0)
{
writer.WriteElementValue(XmlNamespace.Messages, XmlElementNames.PageSize, this.PageSize.ToString());
}
if (!string.IsNullOrEmpty(this.PageItemReference))
{
writer.WriteElementValue(XmlNamespace.Messages, XmlElementNames.PageItemReference, this.PageItemReference);
}
writer.WriteElementValue(XmlNamespace.Messages, XmlElementNames.PageDirection, this.PageDirection.ToString());
}
/// <summary>
/// Gets the request version.
/// </summary>
/// <returns>Earliest Exchange version in which this request is supported.</returns>
internal override ExchangeVersion GetMinimumRequiredServerVersion()
{
return ExchangeVersion.Exchange2013;
}
/// <summary>
/// Collection of query + mailboxes
/// </summary>
public List<MailboxQuery> SearchQueries
{
get { return this.searchQueries; }
set { this.searchQueries = value; }
}
/// <summary>
/// Search result type
/// </summary>
public SearchResultType ResultType
{
get { return this.searchResultType; }
set { this.searchResultType = value; }
}
/// <summary>
/// Preview item response shape
/// </summary>
public PreviewItemResponseShape PreviewItemResponseShape
{
get { return this.previewItemResponseShape; }
set { this.previewItemResponseShape = value; }
}
/// <summary>
/// Sort order
/// </summary>
public SortDirection SortOrder
{
get { return this.sortOrder; }
set { this.sortOrder = value; }
}
/// <summary>
/// Sort by property name
/// </summary>
public string SortByProperty
{
get { return this.sortByProperty; }
set { this.sortByProperty = value; }
}
/// <summary>
/// Query language
/// </summary>
public string Language
{
get;
set;
}
/// <summary>
/// Perform deduplication or not
/// </summary>
public bool PerformDeduplication
{
get { return this.performDeduplication; }
set { this.performDeduplication = value; }
}
/// <summary>
/// Page size
/// </summary>
public int PageSize
{
get { return this.pageSize; }
set { this.pageSize = value; }
}
/// <summary>
/// Page item reference
/// </summary>
public string PageItemReference
{
get { return this.pageItemReference; }
set { this.pageItemReference = value; }
}
/// <summary>
/// Page direction
/// </summary>
public SearchPageDirection PageDirection
{
get { return this.pageDirection; }
set { this.pageDirection = value; }
}
/// <summary>
/// Gets or sets the server version.
/// </summary>
/// <value>
/// The server version.
/// </value>
long IDiscoveryVersionable.ServerVersion
{
get;
set;
}
}
}
| |
// Part of fCraft | Copyright (c) 2009-2013 Matvei Stefarov <me@matvei.org> | BSD-3 | See LICENSE.txt
using System;
using System.IO;
using System.IO.Compression;
using System.Net;
namespace fCraft.MapConversion {
/// <summary> .Dat map conversion implementation, for converting .Dat map format into fCraft's default map format. </summary>
public sealed class MapDat : IMapImporter {
public string ServerName {
get { return "Classic/Vanilla"; }
}
public bool SupportsImport {
get { return true; }
}
public bool SupportsExport {
get { return false; }
}
public string FileExtension {
get { return "dat"; }
}
public MapStorageType StorageType {
get { return MapStorageType.SingleFile; }
}
public MapFormat Format {
get { return MapFormat.Classic; }
}
public bool ClaimsName( string fileName ) {
if( fileName == null ) throw new ArgumentNullException( "fileName" );
return fileName.EndsWith( ".dat", StringComparison.OrdinalIgnoreCase ) ||
fileName.EndsWith( ".mine", StringComparison.OrdinalIgnoreCase );
}
public bool Claims( string fileName ) {
if( fileName == null ) throw new ArgumentNullException( "fileName" );
try {
using( FileStream mapStream = File.OpenRead( fileName ) ) {
byte[] temp = new byte[8];
mapStream.Seek( -4, SeekOrigin.End );
mapStream.Read( temp, 0, 4 );
mapStream.Seek( 0, SeekOrigin.Begin );
int length = BitConverter.ToInt32( temp, 0 );
byte[] data = new byte[length];
using( GZipStream reader = new GZipStream( mapStream, CompressionMode.Decompress, true ) ) {
reader.Read( data, 0, length );
}
for( int i = 0; i < length - 1; i++ ) {
if( data[i] == 0xAC && data[i + 1] == 0xED ) {
return true;
}
}
return false;
}
} catch( Exception ) {
return false;
}
}
public Map LoadHeader( string fileName ) {
if( fileName == null ) throw new ArgumentNullException( "fileName" );
Map map = Load( fileName );
map.Blocks = null;
return map;
}
public static byte MapBlock(byte block)
{
return Mapping[block];
}
public static Block MapBlock(Block block)
{
return (Block)Mapping[(byte)block];
}
public Map Load( string fileName ) {
if( fileName == null ) throw new ArgumentNullException( "fileName" );
using( FileStream mapStream = File.OpenRead( fileName ) ) {
byte[] temp = new byte[8];
Map map = null;
mapStream.Seek( -4, SeekOrigin.End );
mapStream.Read( temp, 0, 4 );
mapStream.Seek( 0, SeekOrigin.Begin );
int uncompressedLength = BitConverter.ToInt32( temp, 0 );
byte[] data = new byte[uncompressedLength];
using( GZipStream reader = new GZipStream( mapStream, CompressionMode.Decompress, true ) ) {
reader.Read( data, 0, uncompressedLength );
}
for( int i = 0; i < uncompressedLength - 1; i++ ) {
if( data[i] != 0xAC || data[i + 1] != 0xED ) continue;
// bypassing the header crap
int pointer = i + 6;
Array.Copy( data, pointer, temp, 0, 2 );
pointer += IPAddress.HostToNetworkOrder( BitConverter.ToInt16( temp, 0 ) );
pointer += 13;
int headerEnd;
// find the end of serialization listing
for( headerEnd = pointer; headerEnd < data.Length - 1; headerEnd++ ) {
if( data[headerEnd] == 0x78 && data[headerEnd + 1] == 0x70 ) {
headerEnd += 2;
break;
}
}
// start parsing serialization listing
int offset = 0;
int width = 0, length = 0, height = 0;
short x=0,
y=0,
z=0;
while( pointer < headerEnd ) {
switch( (char)data[pointer] ) {
case 'Z':
offset++;
break;
case 'F':
case 'I':
offset += 4;
break;
case 'J':
offset += 8;
break;
}
pointer += 1;
Array.Copy( data, pointer, temp, 0, 2 );
short skip = IPAddress.HostToNetworkOrder( BitConverter.ToInt16( temp, 0 ) );
pointer += 2;
// look for relevant variables
Array.Copy( data, headerEnd + offset - 4, temp, 0, 4 );
if( BufferUtil.MemCmp( data, pointer, "width" ) ) {
width = (ushort)IPAddress.HostToNetworkOrder( BitConverter.ToInt32( temp, 0 ) );
} else if( BufferUtil.MemCmp( data, pointer, "depth" ) ) {
height = (ushort)IPAddress.HostToNetworkOrder( BitConverter.ToInt32( temp, 0 ) );
} else if( BufferUtil.MemCmp( data, pointer, "height" ) ) {
length = (ushort)IPAddress.HostToNetworkOrder( BitConverter.ToInt32( temp, 0 ) );
} else if( BufferUtil.MemCmp( data, pointer, "xSpawn" ) ) {
x = (short)( IPAddress.HostToNetworkOrder( BitConverter.ToInt32( temp, 0 ) ) * 32 + 16 );
} else if( BufferUtil.MemCmp( data, pointer, "ySpawn" ) ) {
y = (short)( IPAddress.HostToNetworkOrder( BitConverter.ToInt32( temp, 0 ) ) * 32 + 16 );
} else if( BufferUtil.MemCmp( data, pointer, "zSpawn" ) ) {
z = (short)( IPAddress.HostToNetworkOrder( BitConverter.ToInt32( temp, 0 ) ) * 32 + 16 );
}
pointer += skip;
}
map = new Map( null, width, length, height, false ) {
Spawn = new Position( x, y, z )
};
// find the start of the block array
bool foundBlockArray = false;
offset = Array.IndexOf<byte>( data, 0x00, headerEnd );
while( offset != -1 && offset < data.Length - 2 ) {
if( data[offset] == 0x00 && data[offset + 1] == 0x78 && data[offset + 2] == 0x70 ) {
foundBlockArray = true;
pointer = offset + 7;
}
offset = Array.IndexOf<byte>( data, 0x00, offset + 1 );
}
// copy the block array... or fail
if( foundBlockArray ) {
map.Blocks = new byte[map.Volume];
Array.Copy( data, pointer, map.Blocks, 0, map.Blocks.Length );
map.ConvertBlockTypes( Mapping );
} else {
throw new MapFormatException( "MapDAT: Could not locate block array." );
}
break;
}
if( map == null ) {
throw new MapFormatException( "MapDAT: No data." );
}
return map;
}
}
static readonly byte[] Mapping = new byte[256];
static MapDat() {
Mapping[50] = (byte)Block.Air; // torch
Mapping[51] = (byte)Block.Lava; // fire
Mapping[52] = (byte)Block.Glass; // spawner
Mapping[53] = (byte)Block.Slab; // wood stairs
Mapping[54] = (byte)Block.Wood; // chest
Mapping[55] = (byte)Block.Air; // redstone wire
Mapping[56] = (byte)Block.IronOre; // diamond ore
Mapping[57] = (byte)Block.Aqua; // diamond block
Mapping[58] = (byte)Block.Log; // workbench
Mapping[59] = (byte)Block.Leaves; // crops
Mapping[60] = (byte)Block.Dirt; // soil
Mapping[61] = (byte)Block.Stone; // furnace
Mapping[62] = (byte)Block.Stone; // burning furnace
Mapping[63] = (byte)Block.Air; // sign post
Mapping[64] = (byte)Block.Air; // wooden door
Mapping[65] = (byte)Block.Air; // ladder
Mapping[66] = (byte)Block.Air; // rails
Mapping[67] = (byte)Block.Slab; // cobblestone stairs
Mapping[68] = (byte)Block.Air; // wall sign
Mapping[69] = (byte)Block.Air; // lever
Mapping[70] = (byte)Block.Air; // pressure plate
Mapping[71] = (byte)Block.Air; // iron door
Mapping[72] = (byte)Block.Air; // wooden pressure plate
Mapping[73] = (byte)Block.IronOre; // redstone ore
Mapping[74] = (byte)Block.IronOre; // glowing redstone ore
Mapping[75] = (byte)Block.Air; // redstone torch (off)
Mapping[76] = (byte)Block.Air; // redstone torch (on)
Mapping[77] = (byte)Block.Air; // stone button
Mapping[78] = (byte)Block.Air; // snow
Mapping[79] = (byte)Block.Glass; // ice
Mapping[80] = (byte)Block.White; // snow block
Mapping[81] = (byte)Block.Leaves; // cactus
Mapping[82] = (byte)Block.Gray; // clay
Mapping[83] = (byte)Block.Leaves; // reed
Mapping[84] = (byte)Block.Log; // jukebox
Mapping[85] = (byte)Block.Wood; // fence
Mapping[86] = (byte)Block.Orange; // pumpkin
Mapping[87] = (byte)Block.Dirt; // netherstone
Mapping[88] = (byte)Block.Gravel; // slow sand
Mapping[89] = (byte)Block.Sand; // lightstone
Mapping[90] = (byte)Block.Violet; // portal
Mapping[91] = (byte)Block.Orange; // jack-o-lantern
// all others default to 0/air
}
}
}
| |
// Copyright 2016 Tom Deseyn <tom.deseyn@gmail.com>
// This software is made available under the MIT License
// See COPYING for details
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Reflection.Emit;
using System.Threading;
using System.Threading.Tasks;
using Tmds.DBus.Protocol;
namespace Tmds.DBus.CodeGen
{
internal class DBusAdapterTypeBuilder
{
private static readonly ConstructorInfo s_messageWriterConstructor = typeof(MessageWriter).GetConstructor(Type.EmptyTypes);
private static readonly Type[] s_dbusAdaptorConstructorParameterTypes = new Type[] { typeof(DBusConnection), typeof(ObjectPath), typeof(object), typeof(IProxyFactory), typeof(SynchronizationContext) };
private static readonly ConstructorInfo s_baseConstructor = typeof(DBusAdapter).GetConstructor(BindingFlags.Instance | BindingFlags.NonPublic, s_dbusAdaptorConstructorParameterTypes);
private static readonly ConstructorInfo s_methodHandlerConstructor = typeof(DBusAdapter.MethodCallHandler).GetConstructors()[0];
private static readonly ConstructorInfo s_signatureConstructor = typeof(Signature).GetConstructor(new Type[] { typeof(string) });
private static readonly ConstructorInfo s_nullableSignatureConstructor = typeof(Signature?).GetConstructor(new Type[] { typeof(Signature) });
private static readonly ConstructorInfo s_messageReaderConstructor = typeof(MessageReader).GetConstructor(new Type[] { typeof(Message), typeof(IProxyFactory) });
private static readonly FieldInfo s_methodDictionaryField = typeof(DBusAdapter).GetField(nameof(DBusAdapter._methodHandlers), BindingFlags.Instance | BindingFlags.NonPublic);
private static readonly FieldInfo s_objectField = typeof(DBusAdapter).GetField(nameof(DBusAdapter._object), BindingFlags.Instance | BindingFlags.NonPublic);
private static readonly MethodInfo s_methodDictionaryAdd = typeof(Dictionary<string, DBusAdapter.MethodCallHandler>).GetMethod("Add", new Type[] { typeof(string), typeof(DBusAdapter.MethodCallHandler) });
private static readonly MethodInfo s_startWatchingSignals = typeof(DBusAdapter).GetMethod(nameof(DBusAdapter.StartWatchingSignals), BindingFlags.Instance | BindingFlags.NonPublic);
private static readonly MethodInfo s_emitVoidSignal = typeof(DBusAdapter).GetMethod(nameof(DBusAdapter.EmitVoidSignal), BindingFlags.Instance | BindingFlags.NonPublic);
private static readonly MethodInfo s_emitNonVoidSignal = typeof(DBusAdapter).GetMethod(nameof(DBusAdapter.EmitNonVoidSignal), BindingFlags.Instance | BindingFlags.NonPublic);
private static readonly MethodInfo s_createNonVoidReply = typeof(DBusAdapter).GetMethod(nameof(DBusAdapter.CreateNonVoidReply), BindingFlags.Instance | BindingFlags.NonPublic);
private static readonly MethodInfo s_createVoidReply = typeof(DBusAdapter).GetMethod(nameof(DBusAdapter.CreateVoidReply), BindingFlags.Instance | BindingFlags.NonPublic);
private static readonly MethodInfo s_readerSkipString = typeof(MessageReader).GetMethod(nameof(MessageReader.SkipString), BindingFlags.Instance | BindingFlags.Public);
private static readonly MethodInfo s_writerWriteString = typeof(MessageWriter).GetMethod(nameof(MessageWriter.WriteString), BindingFlags.Instance | BindingFlags.Public);
private static readonly MethodInfo s_writerSetSkipNextStructPadding = typeof(MessageWriter).GetMethod(nameof(MessageWriter.SetSkipNextStructPadding), BindingFlags.Instance | BindingFlags.Public);
private static readonly FieldInfo s_setTypeIntrospectionField = typeof(DBusAdapter).GetField(nameof(DBusAdapter._typeIntrospection), BindingFlags.Instance | BindingFlags.NonPublic);
private static readonly Type s_taskOfMessageType = typeof(Task<Message>);
private static readonly Type s_nullableSignatureType = typeof(Signature?);
private static readonly Type s_action2GenericType = typeof(Action<,>);
private static readonly Type s_messageWriterType = typeof(MessageWriter);
private static readonly Type s_messageReaderType = typeof(MessageReader);
private static readonly Type s_stringType = typeof(string);
private static readonly Type[] s_methodHandlerParameterTypes = new[] { typeof(object), typeof(Message), typeof(IProxyFactory) };
private readonly ModuleBuilder _moduleBuilder;
private TypeBuilder _typeBuilder;
public DBusAdapterTypeBuilder(ModuleBuilder moduleBuilder)
{
_moduleBuilder = moduleBuilder;
}
public TypeInfo Build(Type objectType)
{
if (_typeBuilder != null)
{
throw new InvalidOperationException("Type has already been built.");
}
var parentType = typeof(DBusAdapter);
var adapterName = objectType.FullName + "Adapter";
_typeBuilder = _moduleBuilder.DefineType(adapterName, TypeAttributes.Class | TypeAttributes.Public, parentType);
var description = TypeDescription.DescribeObject(objectType);
ImplementConstructor(description);
ImplementStartWatchingSignals(description.Interfaces);
return _typeBuilder.CreateTypeInfo();
}
private void ImplementStartWatchingSignals(IList<InterfaceDescription> interfaces)
{
var signalCount = interfaces.Aggregate(0, (count, iface) => count +
(iface.Signals?.Count ?? 0) +
((iface.PropertiesChangedSignal != null) ? 1 : 0));
if (signalCount == 0)
{
return;
}
var method = _typeBuilder.OverrideAbstractMethod(s_startWatchingSignals);
var ilg = method.GetILGenerator();
// signals = new Task<IDisposable>[signalCount];
ilg.Emit(OpCodes.Ldc_I4, signalCount);
ilg.Emit(OpCodes.Newarr, typeof(Task<IDisposable>));
var idx = 0;
foreach (var dbusInterface in interfaces)
{
IEnumerable<SignalDescription> signals = dbusInterface.Signals ?? Array.Empty<SignalDescription>();
if (dbusInterface.PropertiesChangedSignal != null)
{
signals = signals.Concat(new[] { dbusInterface.PropertiesChangedSignal });
}
foreach (var signal in signals)
{
// signals[i] = Watch((IDbusInterface)this, SendSignalAction)
ilg.Emit(OpCodes.Dup); // signals
ilg.Emit(OpCodes.Ldc_I4, idx); // i
{
// Watch(...)
{
// (IDbusInterface)this
ilg.Emit(OpCodes.Ldarg_0);
ilg.Emit(OpCodes.Ldfld, s_objectField);
ilg.Emit(OpCodes.Castclass, dbusInterface.Type);
}
{
//SendSignalAction
ilg.Emit(OpCodes.Ldarg_0);
ilg.Emit(OpCodes.Ldftn, GenSendSignal(signal, signal == dbusInterface.PropertiesChangedSignal));
ilg.Emit(OpCodes.Newobj, signal.ActionType.GetConstructors()[0]);
}
if (signal.HasOnError)
{
// Action<Exception> = null
ilg.Emit(OpCodes.Ldnull);
}
ilg.Emit(OpCodes.Callvirt, signal.MethodInfo);
}
ilg.Emit(OpCodes.Stelem_Ref);
idx++;
}
}
ilg.Emit(OpCodes.Ret);
}
private void ImplementConstructor(TypeDescription typeDescription)
{
var dbusInterfaces = typeDescription.Interfaces;
// DBusConnection connection, ObjectPath objectPath, object o, IProxyFactory factory
var constructor = _typeBuilder.DefineConstructor(MethodAttributes.Public, CallingConventions.Standard, s_dbusAdaptorConstructorParameterTypes);
var ilg = constructor.GetILGenerator();
{
// base constructor
ilg.Emit(OpCodes.Ldarg_0); // this
ilg.Emit(OpCodes.Ldarg_1); // DBusConnection
ilg.Emit(OpCodes.Ldarg_2); // ObjectPath
ilg.Emit(OpCodes.Ldarg_3); // object
ilg.Emit(OpCodes.Ldarg, 4); // IProxyFactory
ilg.Emit(OpCodes.Ldarg, 5); // SynchronizationContext
ilg.Emit(OpCodes.Call, s_baseConstructor);
}
var introspectionXml = GenerateIntrospectionXml(typeDescription);
ilg.Emit(OpCodes.Ldarg_0);
ilg.Emit(OpCodes.Ldstr, introspectionXml);
ilg.Emit(OpCodes.Stfld, s_setTypeIntrospectionField);
foreach (var dbusInterface in dbusInterfaces)
{
IEnumerable<MethodDescription> methods = dbusInterface.Methods ?? Array.Empty<MethodDescription>();
var propertyMethods = new[] { dbusInterface.GetPropertyMethod,
dbusInterface.GetAllPropertiesMethod,
dbusInterface.SetPropertyMethod };
methods = methods.Concat(propertyMethods);
foreach (var method in methods)
{
if (method == null)
{
continue;
}
if (method.IsGenericOut)
{
throw new NotImplementedException($"Cannot adaptor class for generic method {method.MethodInfo.ToString()}. Refactor the method to return Task<object>.");
}
var signature = method.InSignature;
var memberName = method.Name;
bool isPropertyMethod = propertyMethods.Contains(method);
string key = isPropertyMethod ? DBusAdapter.GetPropertyAddKey(dbusInterface.Name, memberName, signature) :
DBusAdapter.GetMethodLookupKey(dbusInterface.Name, memberName, signature);
// _methodHandlers.Add(key, GenMethodHandler)
{
// _methodHandlers
ilg.Emit(OpCodes.Ldarg_0);
ilg.Emit(OpCodes.Ldfld, s_methodDictionaryField);
// key
ilg.Emit(OpCodes.Ldstr, key);
// value
ilg.Emit(OpCodes.Ldarg_0);
ilg.Emit(OpCodes.Ldftn, GenMethodHandler(key, method, isPropertyMethod));
ilg.Emit(OpCodes.Newobj, s_methodHandlerConstructor);
// Add
ilg.Emit(OpCodes.Call, s_methodDictionaryAdd);
}
}
}
ilg.Emit(OpCodes.Ret);
}
private MethodInfo GenSendSignal(SignalDescription signalDescription, bool isPropertiesChangedSignal)
{
var key = $"{signalDescription.Interface.Name}.{signalDescription.Name}";
var method = _typeBuilder.DefineMethod($"Emit{key}".Replace('.', '_'), MethodAttributes.Private, null,
signalDescription.SignalType == null ? Type.EmptyTypes : new[] { signalDescription.SignalType });
var ilg = method.GetILGenerator();
ilg.Emit(OpCodes.Ldarg_0);
if (isPropertiesChangedSignal)
{
ilg.Emit(OpCodes.Ldstr, "org.freedesktop.DBus.Properties");
ilg.Emit(OpCodes.Ldstr, "PropertiesChanged");
}
else
{
ilg.Emit(OpCodes.Ldstr, signalDescription.Interface.Name);
ilg.Emit(OpCodes.Ldstr, signalDescription.Name);
}
if (signalDescription.SignalType == null)
{
ilg.Emit(OpCodes.Call, s_emitVoidSignal);
}
else
{
// Signature
if (isPropertiesChangedSignal)
{
ilg.Emit(OpCodes.Ldstr, "sa{sv}as");
ilg.Emit(OpCodes.Newobj, s_signatureConstructor);
ilg.Emit(OpCodes.Newobj, s_nullableSignatureConstructor);
}
else if (signalDescription.SignalSignature.HasValue)
{
ilg.Emit(OpCodes.Ldstr, signalDescription.SignalSignature.Value.Value);
ilg.Emit(OpCodes.Newobj, s_signatureConstructor);
ilg.Emit(OpCodes.Newobj, s_nullableSignatureConstructor);
}
else
{
LocalBuilder signature = ilg.DeclareLocal(s_nullableSignatureType);
ilg.Emit(OpCodes.Ldloca_S, signature);
ilg.Emit(OpCodes.Initobj, s_nullableSignatureType);
ilg.Emit(OpCodes.Ldloc, signature);
}
// Writer
ilg.Emit(OpCodes.Newobj, s_messageWriterConstructor);
if (isPropertiesChangedSignal)
{
ilg.Emit(OpCodes.Dup);
ilg.Emit(OpCodes.Ldstr, signalDescription.Interface.Name);
ilg.Emit(OpCodes.Call, s_writerWriteString);
ilg.Emit(OpCodes.Dup);
ilg.Emit(OpCodes.Call, s_writerSetSkipNextStructPadding);
}
ilg.Emit(OpCodes.Dup);
ilg.Emit(OpCodes.Ldarg_1);
ilg.Emit(OpCodes.Call, WriteMethodFactory.CreateWriteMethodForType(signalDescription.SignalType, isCompileTimeType: true));
ilg.Emit(OpCodes.Call, s_emitNonVoidSignal);
}
ilg.Emit(OpCodes.Ret);
return method;
}
private MethodInfo GenMethodHandler(string key, MethodDescription dbusMethod, bool propertyMethod)
{
// Task<Message> MethodCall(object o(Ldarg_1), Message methodCall(Ldarg_2), IProxyFactory(Ldarg_3));
string methodName = $"Handle{key}".Replace('.', '_');
var method = _typeBuilder.DefineMethod(methodName, MethodAttributes.Private, s_taskOfMessageType, s_methodHandlerParameterTypes);
var ilg = method.GetILGenerator();
// call CreateReply
// this
ilg.Emit(OpCodes.Ldarg_0);
// Message
ilg.Emit(OpCodes.Ldarg_2);
// Task = (IDbusInterface)object.CallMethod(arguments)
{
// (IIinterface)object
ilg.Emit(OpCodes.Ldarg_1);
ilg.Emit(OpCodes.Castclass, dbusMethod.Interface.Type);
// Arguments
if (dbusMethod.InArguments.Count != 0)
{
// create reader for reading the arguments
ilg.Emit(OpCodes.Ldarg_2); // message
ilg.Emit(OpCodes.Ldarg_3); // IProxyFactory
LocalBuilder reader = ilg.DeclareLocal(s_messageReaderType);
ilg.Emit(OpCodes.Newobj, s_messageReaderConstructor); // new MessageReader(message, proxyFactory)
ilg.Emit(OpCodes.Stloc, reader);
if (propertyMethod)
{
ilg.Emit(OpCodes.Ldloc, reader);
ilg.Emit(OpCodes.Call, s_readerSkipString);
}
foreach (var argument in dbusMethod.InArguments)
{
Type parameterType = argument.Type;
ilg.Emit(OpCodes.Ldloc, reader);
ilg.Emit(OpCodes.Call, ReadMethodFactory.CreateReadMethodForType(parameterType));
}
}
// Call method
ilg.Emit(OpCodes.Callvirt, dbusMethod.MethodInfo);
}
if (dbusMethod.OutType != null)
{
// Action<MessageWriter, T>
ilg.Emit(OpCodes.Ldnull);
ilg.Emit(OpCodes.Ldftn, WriteMethodFactory.CreateWriteMethodForType(dbusMethod.OutType, isCompileTimeType: true));
var actionConstructor = s_action2GenericType.MakeGenericType(new[] { s_messageWriterType, dbusMethod.OutType }).GetConstructors()[0];
ilg.Emit(OpCodes.Newobj, actionConstructor);
// signature
if (dbusMethod.OutSignature.HasValue)
{
ilg.Emit(OpCodes.Ldstr, dbusMethod.OutSignature.Value.Value);
ilg.Emit(OpCodes.Newobj, s_signatureConstructor);
ilg.Emit(OpCodes.Newobj, s_nullableSignatureConstructor);
}
else
{
LocalBuilder signature = ilg.DeclareLocal(s_nullableSignatureType);
ilg.Emit(OpCodes.Ldloca_S, signature);
ilg.Emit(OpCodes.Initobj, s_nullableSignatureType);
ilg.Emit(OpCodes.Ldloc, signature);
}
// CreateReply
ilg.Emit(OpCodes.Call, s_createNonVoidReply.MakeGenericMethod(new[] { dbusMethod.OutType }));
}
else
{
// CreateReply
ilg.Emit(OpCodes.Call, s_createVoidReply);
}
ilg.Emit(OpCodes.Ret);
return method;
}
private string GenerateIntrospectionXml(TypeDescription description)
{
var writer = new IntrospectionWriter();
bool hasProperties = false;
foreach (var interf in description.Interfaces)
{
writer.WriteInterfaceStart(interf.Name);
foreach (var method in interf.Methods)
{
writer.WriteMethodStart(method.Name);
foreach (var arg in method.InArguments)
{
writer.WriteInArg(arg.Name, arg.Signature);
}
foreach (var arg in method.OutArguments)
{
writer.WriteOutArg(arg.Name, arg.Signature);
}
writer.WriteMethodEnd();
}
foreach (var signal in interf.Signals)
{
writer.WriteSignalStart(signal.Name);
foreach (var arg in signal.SignalArguments)
{
writer.WriteArg(arg.Name, arg.Signature);
}
writer.WriteSignalEnd();
}
foreach (var prop in interf.Properties)
{
hasProperties = true;
writer.WriteProperty(prop.Name, prop.Signature, prop.Access);
}
writer.WriteInterfaceEnd();
}
if (hasProperties)
{
writer.WritePropertiesInterface();
}
writer.WriteIntrospectableInterface();
writer.WritePeerInterface();
return writer.ToString();
}
}
}
| |
// Copyright (c) .NET Foundation. 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.Data.Common;
using System.Data.SqlClient;
using System.Text.Encodings.Web;
using System.Text.Unicode;
using Benchmarks.Configuration;
using Benchmarks.Data;
using Benchmarks.Middleware;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using MySql.Data.MySqlClient;
using Npgsql;
namespace Benchmarks
{
public class Startup
{
public Startup(IHostingEnvironment hostingEnv, Scenarios scenarios)
{
// Set up configuration sources.
var builder = new ConfigurationBuilder()
.SetBasePath(hostingEnv.ContentRootPath)
.AddJsonFile("appsettings.json")
.AddJsonFile($"appsettings.{hostingEnv.EnvironmentName}.json", optional: true)
.AddEnvironmentVariables()
.AddCommandLine(Program.Args)
;
Configuration = builder.Build();
Scenarios = scenarios;
}
public IConfigurationRoot Configuration { get; set; }
public Scenarios Scenarios { get; }
public void ConfigureServices(IServiceCollection services)
{
services.Configure<AppSettings>(Configuration);
// We re-register the Scenarios as an instance singleton here to avoid it being created again due to the
// registration done in Program.Main
services.AddSingleton(Scenarios);
// Common DB services
services.AddSingleton<IRandom, DefaultRandom>();
services.AddEntityFrameworkSqlServer();
var appSettings = Configuration.Get<AppSettings>();
Console.WriteLine($"Database: {appSettings.Database}");
if (appSettings.Database == DatabaseServer.PostgreSql)
{
if (Scenarios.Any("Ef"))
{
services.AddDbContextPool<ApplicationDbContext>(options => options.UseNpgsql(appSettings.ConnectionString));
}
if (Scenarios.Any("Raw") || Scenarios.Any("Dapper"))
{
services.AddSingleton<DbProviderFactory>(NpgsqlFactory.Instance);
}
}
else if (appSettings.Database == DatabaseServer.MySql)
{
if (Scenarios.Any("Raw") || Scenarios.Any("Dapper"))
{
services.AddSingleton<DbProviderFactory>(MySqlClientFactory.Instance);
}
}
if (Scenarios.Any("Ef"))
{
services.AddScoped<EfDb>();
}
if (Scenarios.Any("Raw"))
{
services.AddScoped<RawDb>();
}
if (Scenarios.Any("Dapper"))
{
services.AddScoped<DapperDb>();
}
if (Scenarios.Any("Update"))
{
BatchUpdateString.Initialize(appSettings.Database);
}
if (Scenarios.Any("Fortunes"))
{
var settings = new TextEncoderSettings(UnicodeRanges.BasicLatin, UnicodeRanges.Katakana, UnicodeRanges.Hiragana);
settings.AllowCharacter('\u2014'); // allow EM DASH through
services.AddWebEncoders((options) =>
{
options.TextEncoderSettings = settings;
});
}
if (Scenarios.Any("Mvc"))
{
var mvcBuilder = services
.AddMvcCore()
.SetCompatibilityVersion(CompatibilityVersion.Latest)
;
if (Scenarios.MvcJson || Scenarios.Any("MvcDbSingle") || Scenarios.Any("MvcDbMulti"))
{
mvcBuilder.AddJsonFormatters();
}
if (Scenarios.MvcViews || Scenarios.Any("MvcDbFortunes"))
{
mvcBuilder
.AddViews()
.AddRazorViewEngine();
}
}
}
public void Configure(IApplicationBuilder app)
{
if (Scenarios.Plaintext)
{
app.UsePlainText();
}
if (Scenarios.Json)
{
app.UseJson();
}
if (Scenarios.Utf8Json)
{
app.UseUtf8Json();
}
if (Scenarios.SpanJson)
{
app.UseSpanJson();
}
// Fortunes endpoints
if (Scenarios.DbFortunesRaw)
{
app.UseFortunesRaw();
}
if (Scenarios.DbFortunesDapper)
{
app.UseFortunesDapper();
}
if (Scenarios.DbFortunesEf)
{
app.UseFortunesEf();
}
// Single query endpoints
if (Scenarios.DbSingleQueryRaw)
{
app.UseSingleQueryRaw();
}
if (Scenarios.DbSingleQueryDapper)
{
app.UseSingleQueryDapper();
}
if (Scenarios.DbSingleQueryEf)
{
app.UseSingleQueryEf();
}
// Multiple query endpoints
if (Scenarios.DbMultiQueryRaw)
{
app.UseMultipleQueriesRaw();
}
if (Scenarios.DbMultiQueryDapper)
{
app.UseMultipleQueriesDapper();
}
if (Scenarios.DbMultiQueryEf)
{
app.UseMultipleQueriesEf();
}
// Multiple update endpoints
if (Scenarios.DbMultiUpdateRaw)
{
app.UseMultipleUpdatesRaw();
}
if (Scenarios.DbMultiUpdateDapper)
{
app.UseMultipleUpdatesDapper();
}
if (Scenarios.DbMultiUpdateEf)
{
app.UseMultipleUpdatesEf();
}
if (Scenarios.Any("Mvc"))
{
app.UseMvc();
}
if (Scenarios.StaticFiles)
{
app.UseStaticFiles();
}
}
}
}
| |
using Duende.IdentityServer.Events;
using Duende.IdentityServer.Extensions;
using Duende.IdentityServer.Models;
using Duende.IdentityServer.Services;
using Duende.IdentityServer.Validation;
using IdentityModel;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
namespace DuendeIdP.Pages.Consent;
[Authorize]
[SecurityHeadersAttribute]
public class Index : PageModel
{
private readonly IIdentityServerInteractionService _interaction;
private readonly IEventService _events;
private readonly ILogger<Index> _logger;
public Index(
IIdentityServerInteractionService interaction,
IEventService events,
ILogger<Index> logger)
{
_interaction = interaction;
_events = events;
_logger = logger;
}
public ViewModel View { get; set; }
[BindProperty]
public InputModel Input { get; set; }
public async Task<IActionResult> OnGet(string returnUrl)
{
View = await BuildViewModelAsync(returnUrl);
if (View == null)
{
return RedirectToPage("/Error/Index");
}
Input = new InputModel
{
ReturnUrl = returnUrl,
};
return Page();
}
public async Task<IActionResult> OnPost()
{
// validate return url is still valid
var request = await _interaction.GetAuthorizationContextAsync(Input.ReturnUrl);
if (request == null) return RedirectToPage("/Error/Index");
ConsentResponse grantedConsent = null;
// user clicked 'no' - send back the standard 'access_denied' response
if (Input?.Button == "no")
{
grantedConsent = new ConsentResponse { Error = AuthorizationError.AccessDenied };
// emit event
await _events.RaiseAsync(new ConsentDeniedEvent(User.GetSubjectId(), request.Client.ClientId, request.ValidatedResources.RawScopeValues));
}
// user clicked 'yes' - validate the data
else if (Input?.Button == "yes")
{
// if the user consented to some scope, build the response model
if (Input.ScopesConsented != null && Input.ScopesConsented.Any())
{
var scopes = Input.ScopesConsented;
if (ConsentOptions.EnableOfflineAccess == false)
{
scopes = scopes.Where(x => x != Duende.IdentityServer.IdentityServerConstants.StandardScopes.OfflineAccess);
}
grantedConsent = new ConsentResponse
{
RememberConsent = Input.RememberConsent,
ScopesValuesConsented = scopes.ToArray(),
Description = Input.Description
};
// emit event
await _events.RaiseAsync(new ConsentGrantedEvent(User.GetSubjectId(), request.Client.ClientId, request.ValidatedResources.RawScopeValues, grantedConsent.ScopesValuesConsented, grantedConsent.RememberConsent));
}
else
{
ModelState.AddModelError("", ConsentOptions.MustChooseOneErrorMessage);
}
}
else
{
ModelState.AddModelError("", ConsentOptions.InvalidSelectionErrorMessage);
}
if (grantedConsent != null)
{
// communicate outcome of consent back to identityserver
await _interaction.GrantConsentAsync(request, grantedConsent);
// redirect back to authorization endpoint
if (request.IsNativeClient() == true)
{
// The client is native, so this change in how to
// return the response is for better UX for the end user.
return this.LoadingPage(Input.ReturnUrl);
}
return Redirect(Input.ReturnUrl);
}
// we need to redisplay the consent UI
View = await BuildViewModelAsync(Input.ReturnUrl, Input);
return Page();
}
private async Task<ViewModel> BuildViewModelAsync(string returnUrl, InputModel model = null)
{
var request = await _interaction.GetAuthorizationContextAsync(returnUrl);
if (request != null)
{
return CreateConsentViewModel(model, returnUrl, request);
}
else
{
_logger.LogError("No consent request matching request: {0}", returnUrl);
}
return null;
}
private ViewModel CreateConsentViewModel(
InputModel model, string returnUrl,
AuthorizationRequest request)
{
var vm = new ViewModel
{
ClientName = request.Client.ClientName ?? request.Client.ClientId,
ClientUrl = request.Client.ClientUri,
ClientLogoUrl = request.Client.LogoUri,
AllowRememberConsent = request.Client.AllowRememberConsent
};
vm.IdentityScopes = request.ValidatedResources.Resources.IdentityResources
.Select(x => CreateScopeViewModel(x, model?.ScopesConsented == null || model.ScopesConsented?.Contains(x.Name) == true))
.ToArray();
var resourceIndicators = request.Parameters.GetValues(OidcConstants.AuthorizeRequest.Resource) ?? Enumerable.Empty<string>();
var apiResources = request.ValidatedResources.Resources.ApiResources.Where(x => resourceIndicators.Contains(x.Name));
var apiScopes = new List<ScopeViewModel>();
foreach (var parsedScope in request.ValidatedResources.ParsedScopes)
{
var apiScope = request.ValidatedResources.Resources.FindApiScope(parsedScope.ParsedName);
if (apiScope != null)
{
var scopeVm = CreateScopeViewModel(parsedScope, apiScope, model == null || model.ScopesConsented?.Contains(parsedScope.RawValue) == true);
scopeVm.Resources = apiResources.Where(x => x.Scopes.Contains(parsedScope.ParsedName))
.Select(x => new ResourceViewModel
{
Name = x.Name,
DisplayName = x.DisplayName ?? x.Name,
}).ToArray();
apiScopes.Add(scopeVm);
}
}
if (ConsentOptions.EnableOfflineAccess && request.ValidatedResources.Resources.OfflineAccess)
{
apiScopes.Add(GetOfflineAccessScope(model == null || model.ScopesConsented?.Contains(Duende.IdentityServer.IdentityServerConstants.StandardScopes.OfflineAccess) == true));
}
vm.ApiScopes = apiScopes;
return vm;
}
private ScopeViewModel CreateScopeViewModel(IdentityResource identity, bool check)
{
return new ScopeViewModel
{
Name = identity.Name,
Value = identity.Name,
DisplayName = identity.DisplayName ?? identity.Name,
Description = identity.Description,
Emphasize = identity.Emphasize,
Required = identity.Required,
Checked = check || identity.Required
};
}
public ScopeViewModel CreateScopeViewModel(ParsedScopeValue parsedScopeValue, ApiScope apiScope, bool check)
{
var displayName = apiScope.DisplayName ?? apiScope.Name;
if (!String.IsNullOrWhiteSpace(parsedScopeValue.ParsedParameter))
{
displayName += ":" + parsedScopeValue.ParsedParameter;
}
return new ScopeViewModel
{
Name = parsedScopeValue.ParsedName,
Value = parsedScopeValue.RawValue,
DisplayName = displayName,
Description = apiScope.Description,
Emphasize = apiScope.Emphasize,
Required = apiScope.Required,
Checked = check || apiScope.Required
};
}
private ScopeViewModel GetOfflineAccessScope(bool check)
{
return new ScopeViewModel
{
Value = Duende.IdentityServer.IdentityServerConstants.StandardScopes.OfflineAccess,
DisplayName = ConsentOptions.OfflineAccessDisplayName,
Description = ConsentOptions.OfflineAccessDescription,
Emphasize = true,
Checked = check
};
}
}
| |
// 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;
namespace System.Collections.Generic
{
/*============================================================
**
** Class: LowLevelDictionary<TKey, TValue>
**
** Private version of Dictionary<> for internal System.Private.CoreLib use. This
** permits sharing more source between BCL and System.Private.CoreLib (as well as the
** fact that Dictionary<> is just a useful class in general.)
**
** This does not strive to implement the full api surface area
** (but any portion it does implement should match the real Dictionary<>'s
** behavior.)
**
===========================================================*/
internal partial class LowLevelDictionary<TKey, TValue>
{
private const int DefaultSize = 17;
public LowLevelDictionary()
: this(DefaultSize, new DefaultComparer<TKey>())
{
}
public LowLevelDictionary(int capacity)
: this(capacity, new DefaultComparer<TKey>())
{
}
public LowLevelDictionary(IEqualityComparer<TKey> comparer) : this(DefaultSize, comparer)
{
}
public LowLevelDictionary(int capacity, IEqualityComparer<TKey> comparer)
{
_comparer = comparer;
Clear(capacity);
}
public int Count
{
get
{
return _numEntries;
}
}
public TValue this[TKey key]
{
get
{
if (key == null)
throw new ArgumentNullException(nameof(key));
Entry entry = Find(key);
if (entry == null)
throw new KeyNotFoundException();
return entry._value;
}
set
{
if (key == null)
throw new ArgumentNullException(nameof(key));
_version++;
Entry entry = Find(key);
if (entry != null)
entry._value = value;
else
UncheckedAdd(key, value);
}
}
public bool TryGetValue(TKey key, out TValue value)
{
value = default(TValue);
if (key == null)
throw new ArgumentNullException(nameof(key));
Entry entry = Find(key);
if (entry != null)
{
value = entry._value;
return true;
}
return false;
}
public void Add(TKey key, TValue value)
{
if (key == null)
throw new ArgumentNullException(nameof(key));
Entry entry = Find(key);
if (entry != null)
throw new ArgumentException(SR.Format(SR.Argument_AddingDuplicate, key));
_version++;
UncheckedAdd(key, value);
}
public void Clear(int capacity = DefaultSize)
{
_version++;
_buckets = new Entry[capacity];
_numEntries = 0;
}
public bool Remove(TKey key)
{
if (key == null)
throw new ArgumentNullException(nameof(key));
int bucket = GetBucket(key);
Entry prev = null;
Entry entry = _buckets[bucket];
while (entry != null)
{
if (_comparer.Equals(key, entry._key))
{
if (prev == null)
{
_buckets[bucket] = entry._next;
}
else
{
prev._next = entry._next;
}
_version++;
_numEntries--;
return true;
}
prev = entry;
entry = entry._next;
}
return false;
}
internal TValue LookupOrAdd(TKey key, TValue value)
{
Entry entry = Find(key);
if (entry != null)
return entry._value;
UncheckedAdd(key, value);
return value;
}
private Entry Find(TKey key)
{
int bucket = GetBucket(key);
Entry entry = _buckets[bucket];
while (entry != null)
{
if (_comparer.Equals(key, entry._key))
return entry;
entry = entry._next;
}
return null;
}
private Entry UncheckedAdd(TKey key, TValue value)
{
Entry entry = new Entry();
entry._key = key;
entry._value = value;
int bucket = GetBucket(key);
entry._next = _buckets[bucket];
_buckets[bucket] = entry;
_numEntries++;
if (_numEntries > (_buckets.Length * 2))
ExpandBuckets();
return entry;
}
private void ExpandBuckets()
{
try
{
int newNumBuckets = _buckets.Length * 2 + 1;
Entry[] newBuckets = new Entry[newNumBuckets];
for (int i = 0; i < _buckets.Length; i++)
{
Entry entry = _buckets[i];
while (entry != null)
{
Entry nextEntry = entry._next;
int bucket = GetBucket(entry._key, newNumBuckets);
entry._next = newBuckets[bucket];
newBuckets[bucket] = entry;
entry = nextEntry;
}
}
_buckets = newBuckets;
}
catch (OutOfMemoryException)
{
}
}
private int GetBucket(TKey key, int numBuckets = 0)
{
int h = _comparer.GetHashCode(key);
h &= 0x7fffffff;
return (h % (numBuckets == 0 ? _buckets.Length : numBuckets));
}
private sealed class Entry
{
public TKey _key;
public TValue _value;
public Entry _next;
}
private Entry[] _buckets;
private int _numEntries;
private int _version;
private IEqualityComparer<TKey> _comparer;
// This comparator is used if no comparator is supplied. It emulates the behavior of EqualityComparer<T>.Default.
private sealed class DefaultComparer<T> : IEqualityComparer<T>
{
public bool Equals(T x, T y)
{
if (x == null)
return y == null;
IEquatable<T> iequatable = x as IEquatable<T>;
if (iequatable != null)
return iequatable.Equals(y);
return ((object)x).Equals(y);
}
public int GetHashCode(T obj)
{
return ((object)obj).GetHashCode();
}
}
protected sealed class LowLevelDictEnumerator : IEnumerator<KeyValuePair<TKey, TValue>>
{
public LowLevelDictEnumerator(LowLevelDictionary<TKey, TValue> dict)
{
_dict = dict;
_version = _dict._version;
Entry[] entries = new Entry[_dict._numEntries];
int dst = 0;
for (int bucket = 0; bucket < _dict._buckets.Length; bucket++)
{
Entry entry = _dict._buckets[bucket];
while (entry != null)
{
entries[dst++] = entry;
entry = entry._next;
}
}
_entries = entries;
Reset();
}
public KeyValuePair<TKey, TValue> Current
{
get
{
if (_version != _dict._version)
throw new InvalidOperationException("InvalidOperation_EnumFailedVersion");
if (_curPosition == -1 || _curPosition == _entries.Length)
throw new InvalidOperationException("InvalidOperation_EnumOpCantHappen");
Entry entry = _entries[_curPosition];
return new KeyValuePair<TKey, TValue>(entry._key, entry._value);
}
}
public void Dispose()
{
}
public bool MoveNext()
{
if (_version != _dict._version)
throw new InvalidOperationException("InvalidOperation_EnumFailedVersion");
if (_curPosition != _entries.Length)
_curPosition++;
bool anyMore = (_curPosition != _entries.Length);
return anyMore;
}
object IEnumerator.Current
{
get
{
KeyValuePair<TKey, TValue> kv = Current;
return kv;
}
}
public void Reset()
{
if (_version != _dict._version)
throw new InvalidOperationException("InvalidOperation_EnumFailedVersion");
_curPosition = -1;
}
private LowLevelDictionary<TKey, TValue> _dict;
private Entry[] _entries;
private int _curPosition;
private int _version;
}
}
}
| |
// 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.Data;
using System.Net;
using System.Net.Sockets;
using System.Web;
using System.Collections;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.ComponentModel;
using Microsoft.Web.Services3;
using WebsitePanel.Providers;
using WebsitePanel.Providers.OS;
using WebsitePanel.Providers.RemoteDesktopServices;
using WebsitePanel.Server.Utils;
using WebsitePanel.Providers.HostedSolution;
using WebsitePanel.EnterpriseServer.Base.RDS;
namespace WebsitePanel.Server
{
/// <summary>
/// Summary description for RemoteDesktopServices
/// </summary>
[WebService(Namespace = "http://smbsaas/websitepanel/server/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[Policy("ServerPolicy")]
[ToolboxItem(false)]
public class RemoteDesktopServices : HostingServiceProviderWebService, IRemoteDesktopServices
{
private IRemoteDesktopServices RDSProvider
{
get { return (IRemoteDesktopServices)Provider; }
}
[WebMethod, SoapHeader("settings")]
public bool CreateCollection(string organizationId, RdsCollection collection)
{
try
{
Log.WriteStart("'{0}' CreateCollection", ProviderSettings.ProviderName);
var result = RDSProvider.CreateCollection(organizationId, collection);
Log.WriteEnd("'{0}' CreateCollection", ProviderSettings.ProviderName);
return result;
}
catch (Exception ex)
{
Log.WriteError(String.Format("'{0}' CreateCollection", ProviderSettings.ProviderName), ex);
throw;
}
}
[WebMethod, SoapHeader("settings")]
public void EditRdsCollectionSettings(RdsCollection collection)
{
try
{
Log.WriteStart("'{0}' EditRdsCollectionSettings", ProviderSettings.ProviderName);
RDSProvider.EditRdsCollectionSettings(collection);
Log.WriteEnd("'{0}' EditRdsCollectionSettings", ProviderSettings.ProviderName);
}
catch (Exception ex)
{
Log.WriteError(String.Format("'{0}' EditRdsCollectionSettings", ProviderSettings.ProviderName), ex);
throw;
}
}
[WebMethod, SoapHeader("settings")]
public List<RdsUserSession> GetRdsUserSessions(string collectionName)
{
try
{
Log.WriteStart("'{0}' GetRdsUserSessions", ProviderSettings.ProviderName);
var result = RDSProvider.GetRdsUserSessions(collectionName);
Log.WriteEnd("'{0}' GetRdsUserSessions", ProviderSettings.ProviderName);
return result;
}
catch (Exception ex)
{
Log.WriteError(String.Format("'{0}' GetRdsUserSessions", ProviderSettings.ProviderName), ex);
throw;
}
}
[WebMethod, SoapHeader("settings")]
public bool AddRdsServersToDeployment(RdsServer[] servers)
{
try
{
Log.WriteStart("'{0}' AddRdsServersToDeployment", ProviderSettings.ProviderName);
var result = RDSProvider.AddRdsServersToDeployment(servers);
Log.WriteEnd("'{0}' AddRdsServersToDeployment", ProviderSettings.ProviderName);
return result;
}
catch (Exception ex)
{
Log.WriteError(String.Format("'{0}' AddRdsServersToDeployment", ProviderSettings.ProviderName), ex);
throw;
}
}
[WebMethod, SoapHeader("settings")]
public RdsCollection GetCollection(string collectionName)
{
try
{
Log.WriteStart("'{0}' GetCollection", ProviderSettings.ProviderName);
var result = RDSProvider.GetCollection(collectionName);
Log.WriteEnd("'{0}' GetCollection", ProviderSettings.ProviderName);
return result;
}
catch (Exception ex)
{
Log.WriteError(String.Format("'{0}' GetCollection", ProviderSettings.ProviderName), ex);
throw;
}
}
[WebMethod, SoapHeader("settings")]
public bool RemoveCollection(string organizationId, string collectionName, List<RdsServer> servers)
{
try
{
Log.WriteStart("'{0}' RemoveCollection", ProviderSettings.ProviderName);
var result = RDSProvider.RemoveCollection(organizationId, collectionName, servers);
Log.WriteEnd("'{0}' RemoveCollection", ProviderSettings.ProviderName);
return result;
}
catch (Exception ex)
{
Log.WriteError(String.Format("'{0}' RemoveCollection", ProviderSettings.ProviderName), ex);
throw;
}
}
[WebMethod, SoapHeader("settings")]
public bool SetUsersInCollection(string organizationId, string collectionName, List<string> users)
{
try
{
Log.WriteStart("'{0}' UpdateUsersInCollection", ProviderSettings.ProviderName);
var result = RDSProvider.SetUsersInCollection(organizationId, collectionName, users);
Log.WriteEnd("'{0}' UpdateUsersInCollection", ProviderSettings.ProviderName);
return result;
}
catch (Exception ex)
{
Log.WriteError(String.Format("'{0}' UpdateUsersInCollection", ProviderSettings.ProviderName), ex);
throw;
}
}
[WebMethod, SoapHeader("settings")]
public void AddSessionHostServerToCollection(string organizationId, string collectionName, RdsServer server)
{
try
{
Log.WriteStart("'{0}' AddSessionHostServersToCollection", ProviderSettings.ProviderName);
RDSProvider.AddSessionHostServerToCollection(organizationId, collectionName, server);
Log.WriteEnd("'{0}' AddSessionHostServersToCollection", ProviderSettings.ProviderName);
}
catch (Exception ex)
{
Log.WriteError(String.Format("'{0}' AddSessionHostServersToCollection", ProviderSettings.ProviderName), ex);
throw;
}
}
[WebMethod, SoapHeader("settings")]
public void AddSessionHostServersToCollection(string organizationId, string collectionName, List<RdsServer> servers)
{
try
{
Log.WriteStart("'{0}' AddSessionHostServersToCollection", ProviderSettings.ProviderName);
RDSProvider.AddSessionHostServersToCollection(organizationId, collectionName, servers);
Log.WriteEnd("'{0}' AddSessionHostServersToCollection", ProviderSettings.ProviderName);
}
catch (Exception ex)
{
Log.WriteError(String.Format("'{0}' AddSessionHostServersToCollection", ProviderSettings.ProviderName), ex);
throw;
}
}
[WebMethod, SoapHeader("settings")]
public void RemoveSessionHostServerFromCollection(string organizationId, string collectionName, RdsServer server)
{
try
{
Log.WriteStart("'{0}' RemoveSessionHostServerFromCollection", ProviderSettings.ProviderName);
RDSProvider.RemoveSessionHostServerFromCollection(organizationId, collectionName, server);
Log.WriteEnd("'{0}' RemoveSessionHostServerFromCollection", ProviderSettings.ProviderName);
}
catch (Exception ex)
{
Log.WriteError(String.Format("'{0}' RemoveSessionHostServerFromCollection", ProviderSettings.ProviderName), ex);
throw;
}
}
[WebMethod, SoapHeader("settings")]
public void RemoveSessionHostServersFromCollection(string organizationId, string collectionName, List<RdsServer> servers)
{
try
{
Log.WriteStart("'{0}' RemoveSessionHostServersFromCollection", ProviderSettings.ProviderName);
RDSProvider.RemoveSessionHostServersFromCollection(organizationId, collectionName, servers);
Log.WriteEnd("'{0}' RemoveSessionHostServersFromCollection", ProviderSettings.ProviderName);
}
catch (Exception ex)
{
Log.WriteError(String.Format("'{0}' RemoveSessionHostServersFromCollection", ProviderSettings.ProviderName), ex);
throw;
}
}
[WebMethod, SoapHeader("settings")]
public void SetRDServerNewConnectionAllowed(bool newConnectionAllowed, RdsServer server)
{
try
{
Log.WriteStart("'{0}' SetRDServerNewConnectionAllowed", ProviderSettings.ProviderName);
RDSProvider.SetRDServerNewConnectionAllowed(newConnectionAllowed, server);
Log.WriteEnd("'{0}' SetRDServerNewConnectionAllowed", ProviderSettings.ProviderName);
}
catch (Exception ex)
{
Log.WriteError(String.Format("'{0}' SetRDServerNewConnectionAllowed", ProviderSettings.ProviderName), ex);
throw;
}
}
[WebMethod, SoapHeader("settings")]
public List<StartMenuApp> GetAvailableRemoteApplications(string collectionName)
{
try
{
Log.WriteStart("'{0}' GetAvailableRemoteApplications", ProviderSettings.ProviderName);
var result = RDSProvider.GetAvailableRemoteApplications(collectionName);
Log.WriteEnd("'{0}' GetAvailableRemoteApplications", ProviderSettings.ProviderName);
return result;
}
catch (Exception ex)
{
Log.WriteError(String.Format("'{0}' UpdateUsersInCollection", ProviderSettings.ProviderName), ex);
throw;
}
}
[WebMethod, SoapHeader("settings")]
public List<RemoteApplication> GetCollectionRemoteApplications(string collectionName)
{
try
{
Log.WriteStart("'{0}' GetCollectionRemoteApplications", ProviderSettings.ProviderName);
var result = RDSProvider.GetCollectionRemoteApplications(collectionName);
Log.WriteEnd("'{0}' GetCollectionRemoteApplications", ProviderSettings.ProviderName);
return result;
}
catch (Exception ex)
{
Log.WriteError(String.Format("'{0}' GetCollectionRemoteApplications", ProviderSettings.ProviderName), ex);
throw;
}
}
[WebMethod, SoapHeader("settings")]
public bool AddRemoteApplication(string collectionName, RemoteApplication remoteApp)
{
try
{
Log.WriteStart("'{0}' AddRemoteApplication", ProviderSettings.ProviderName);
var result = RDSProvider.AddRemoteApplication(collectionName, remoteApp);
Log.WriteEnd("'{0}' AddRemoteApplication", ProviderSettings.ProviderName);
return result;
}
catch (Exception ex)
{
Log.WriteError(String.Format("'{0}' AddRemoteApplication", ProviderSettings.ProviderName), ex);
throw;
}
}
[WebMethod, SoapHeader("settings")]
public bool AddRemoteApplications(string collectionName, List<RemoteApplication> remoteApps)
{
try
{
Log.WriteStart("'{0}' AddRemoteApplications", ProviderSettings.ProviderName);
var result = RDSProvider.AddRemoteApplications(collectionName, remoteApps);
Log.WriteEnd("'{0}' AddRemoteApplications", ProviderSettings.ProviderName);
return result;
}
catch (Exception ex)
{
Log.WriteError(String.Format("'{0}' AddRemoteApplications", ProviderSettings.ProviderName), ex);
throw;
}
}
[WebMethod, SoapHeader("settings")]
public bool RemoveRemoteApplication(string collectionName, RemoteApplication remoteApp)
{
try
{
Log.WriteStart("'{0}' RemoveRemoteApplication", ProviderSettings.ProviderName);
var result = RDSProvider.RemoveRemoteApplication(collectionName, remoteApp);
Log.WriteEnd("'{0}' RemoveRemoteApplication", ProviderSettings.ProviderName);
return result;
}
catch (Exception ex)
{
Log.WriteError(String.Format("'{0}' RemoveRemoteApplication", ProviderSettings.ProviderName), ex);
throw;
}
}
[WebMethod, SoapHeader("settings")]
public bool AddSessionHostFeatureToServer(string hostName)
{
try
{
Log.WriteStart("'{0}' AddSessionHostFeatureToServer", ProviderSettings.ProviderName);
var result = RDSProvider.AddSessionHostFeatureToServer(hostName);
Log.WriteEnd("'{0}' AddSessionHostFeatureToServer", ProviderSettings.ProviderName);
return result;
}
catch (Exception ex)
{
Log.WriteError(String.Format("'{0}' AddSessionHostServersToCollection", ProviderSettings.ProviderName), ex);
throw;
}
}
[WebMethod, SoapHeader("settings")]
public bool CheckSessionHostFeatureInstallation(string hostName)
{
try
{
Log.WriteStart("'{0}' CheckSessionHostFeatureInstallation", ProviderSettings.ProviderName);
var result = RDSProvider.CheckSessionHostFeatureInstallation(hostName);
Log.WriteEnd("'{0}' CheckSessionHostFeatureInstallation", ProviderSettings.ProviderName);
return result;
}
catch (Exception ex)
{
Log.WriteError(String.Format("'{0}' CheckSessionHostFeatureInstallation", ProviderSettings.ProviderName), ex);
throw;
}
}
[WebMethod, SoapHeader("settings")]
public bool CheckServerAvailability(string hostName)
{
try
{
Log.WriteStart("'{0}' CheckServerAvailability", ProviderSettings.ProviderName);
var result = RDSProvider.CheckServerAvailability(hostName);
Log.WriteEnd("'{0}' CheckServerAvailability", ProviderSettings.ProviderName);
return result;
}
catch (Exception ex)
{
Log.WriteError(String.Format("'{0}' CheckServerAvailability", ProviderSettings.ProviderName), ex);
throw;
}
}
[WebMethod, SoapHeader("settings")]
public string[] GetApplicationUsers(string collectionName, string applicationName)
{
try
{
Log.WriteStart("'{0}' GetApplicationUsers", ProviderSettings.ProviderName);
var result = RDSProvider.GetApplicationUsers(collectionName, applicationName);
Log.WriteEnd("'{0}' GetApplicationUsers", ProviderSettings.ProviderName);
return result;
}
catch (Exception ex)
{
Log.WriteError(String.Format("'{0}' GetApplicationUsers", ProviderSettings.ProviderName), ex);
throw;
}
}
[WebMethod, SoapHeader("settings")]
public bool SetApplicationUsers(string collectionName, RemoteApplication remoteApp, string[] users)
{
try
{
Log.WriteStart("'{0}' SetApplicationUsers", ProviderSettings.ProviderName);
var result = RDSProvider.SetApplicationUsers(collectionName, remoteApp, users);
Log.WriteEnd("'{0}' SetApplicationUsers", ProviderSettings.ProviderName);
return result;
}
catch (Exception ex)
{
Log.WriteError(String.Format("'{0}' SetApplicationUsers", ProviderSettings.ProviderName), ex);
throw;
}
}
[WebMethod, SoapHeader("settings")]
public bool CheckRDSServerAvaliable(string hostname)
{
try
{
Log.WriteStart("'{0}' CheckRDSServerAvaliable", ProviderSettings.ProviderName);
var result = RDSProvider.CheckRDSServerAvaliable(hostname);
Log.WriteEnd("'{0}' CheckRDSServerAvaliable", ProviderSettings.ProviderName);
return result;
}
catch (Exception ex)
{
Log.WriteError(String.Format("'{0}' CheckRDSServerAvaliable", ProviderSettings.ProviderName), ex);
throw;
}
}
[WebMethod, SoapHeader("settings")]
public List<string> GetServersExistingInCollections()
{
try
{
Log.WriteStart("'{0}' GetServersExistingInCollections", ProviderSettings.ProviderName);
var result = RDSProvider.GetServersExistingInCollections();
Log.WriteEnd("'{0}' GetServersExistingInCollections", ProviderSettings.ProviderName);
return result;
}
catch (Exception ex)
{
Log.WriteError(String.Format("'{0}' GetServersExistingInCollections", ProviderSettings.ProviderName), ex);
throw;
}
}
[WebMethod, SoapHeader("settings")]
public void LogOffRdsUser(string unifiedSessionId, string hostServer)
{
try
{
Log.WriteStart("'{0}' LogOffRdsUser", ProviderSettings.ProviderName);
RDSProvider.LogOffRdsUser(unifiedSessionId, hostServer);
Log.WriteEnd("'{0}' LogOffRdsUser", ProviderSettings.ProviderName);
}
catch (Exception ex)
{
Log.WriteError(String.Format("'{0}' LogOffRdsUser", ProviderSettings.ProviderName), ex);
throw;
}
}
[WebMethod, SoapHeader("settings")]
public List<string> GetRdsCollectionSessionHosts(string collectionName)
{
try
{
Log.WriteStart("'{0}' GetRdsCollectionSessionHosts", ProviderSettings.ProviderName);
var result = RDSProvider.GetRdsCollectionSessionHosts(collectionName);
Log.WriteEnd("'{0}' GetRdsCollectionSessionHosts", ProviderSettings.ProviderName);
return result;
}
catch(Exception ex)
{
Log.WriteError(String.Format("'{0}' GetRdsCollectionSessionHosts", ProviderSettings.ProviderName), ex);
throw;
}
}
[WebMethod, SoapHeader("settings")]
public RdsServerInfo GetRdsServerInfo(string serverName)
{
try
{
Log.WriteStart("'{0}' GetRdsServerInfo", ProviderSettings.ProviderName);
var result = RDSProvider.GetRdsServerInfo(serverName);
Log.WriteEnd("'{0}' GetRdsServerInfo", ProviderSettings.ProviderName);
return result;
}
catch (Exception ex)
{
Log.WriteError(String.Format("'{0}' GetRdsServerInfo", ProviderSettings.ProviderName), ex);
throw;
}
}
[WebMethod, SoapHeader("settings")]
public string GetRdsServerStatus(string serverName)
{
try
{
Log.WriteStart("'{0}' GetRdsServerStatus", ProviderSettings.ProviderName);
var result = RDSProvider.GetRdsServerStatus(serverName);
Log.WriteEnd("'{0}' GetRdsServerStatus", ProviderSettings.ProviderName);
return result;
}
catch (Exception ex)
{
Log.WriteError(String.Format("'{0}' GetRdsServerStatus", ProviderSettings.ProviderName), ex);
throw;
}
}
[WebMethod, SoapHeader("settings")]
public void ShutDownRdsServer(string serverName)
{
try
{
Log.WriteStart("'{0}' ShutDownRdsServer", ProviderSettings.ProviderName);
RDSProvider.ShutDownRdsServer(serverName);
Log.WriteEnd("'{0}' ShutDownRdsServer", ProviderSettings.ProviderName);
}
catch (Exception ex)
{
Log.WriteError(String.Format("'{0}' ShutDownRdsServer", ProviderSettings.ProviderName), ex);
throw;
}
}
[WebMethod, SoapHeader("settings")]
public void RestartRdsServer(string serverName)
{
try
{
Log.WriteStart("'{0}' RestartRdsServer", ProviderSettings.ProviderName);
RDSProvider.RestartRdsServer(serverName);
Log.WriteEnd("'{0}' RestartRdsServer", ProviderSettings.ProviderName);
}
catch (Exception ex)
{
Log.WriteError(String.Format("'{0}' RestartRdsServer", ProviderSettings.ProviderName), ex);
throw;
}
}
[WebMethod, SoapHeader("settings")]
public void SaveRdsCollectionLocalAdmins(List<string> users, List<string> hosts, string organizationId, string collectionName)
{
try
{
Log.WriteStart("'{0}' SaveRdsCollectionLocalAdmins", ProviderSettings.ProviderName);
RDSProvider.SaveRdsCollectionLocalAdmins(users, hosts, collectionName, organizationId);
Log.WriteEnd("'{0}' SaveRdsCollectionLocalAdmins", ProviderSettings.ProviderName);
}
catch (Exception ex)
{
Log.WriteError(String.Format("'{0}' SaveRdsCollectionLocalAdmins", ProviderSettings.ProviderName), ex);
throw;
}
}
[WebMethod, SoapHeader("settings")]
public List<string> GetRdsCollectionLocalAdmins(string organizationId, string collectionName)
{
try
{
Log.WriteStart("'{0}' GetRdsCollectionLocalAdmins", ProviderSettings.ProviderName);
var result = RDSProvider.GetRdsCollectionLocalAdmins(organizationId, collectionName);
Log.WriteEnd("'{0}' GetRdsCollectionLocalAdmins", ProviderSettings.ProviderName);
return result;
}
catch (Exception ex)
{
Log.WriteError(String.Format("'{0}' GetRdsCollectionLocalAdmins", ProviderSettings.ProviderName), ex);
throw;
}
}
[WebMethod, SoapHeader("settings")]
public void MoveRdsServerToTenantOU(string hostName, string organizationId)
{
try
{
Log.WriteStart("'{0}' MoveRdsServerToTenantOU", ProviderSettings.ProviderName);
RDSProvider.MoveRdsServerToTenantOU(hostName, organizationId);
Log.WriteEnd("'{0}' MoveRdsServerToTenantOU", ProviderSettings.ProviderName);
}
catch (Exception ex)
{
Log.WriteError(String.Format("'{0}' MoveRdsServerToTenantOU", ProviderSettings.ProviderName), ex);
throw;
}
}
[WebMethod, SoapHeader("settings")]
public void RemoveRdsServerFromTenantOU(string hostName, string organizationId)
{
try
{
Log.WriteStart("'{0}' RemoveRdsServerFromTenantOU", ProviderSettings.ProviderName);
RDSProvider.RemoveRdsServerFromTenantOU(hostName, organizationId);
Log.WriteEnd("'{0}' RemoveRdsServerFromTenantOU", ProviderSettings.ProviderName);
}
catch (Exception ex)
{
Log.WriteError(String.Format("'{0}' RemoveRdsServerFromTenantOU", ProviderSettings.ProviderName), ex);
throw;
}
}
[WebMethod, SoapHeader("settings")]
public void InstallCertificate(byte[] certificate, string password, List<string> hostNames)
{
try
{
Log.WriteStart("'{0}' InstallCertificate", ProviderSettings.ProviderName);
RDSProvider.InstallCertificate(certificate, password, hostNames);
Log.WriteEnd("'{0}' InstallCertificate", ProviderSettings.ProviderName);
}
catch (Exception ex)
{
Log.WriteError(String.Format("'{0}' InstallCertificate", ProviderSettings.ProviderName), ex);
throw;
}
}
[WebMethod, SoapHeader("settings")]
public void MoveSessionHostToRdsOU(string hostName)
{
try
{
Log.WriteStart("'{0}' MoveSessionHostToRdsOU", ProviderSettings.ProviderName);
RDSProvider.MoveSessionHostToRdsOU(hostName);
Log.WriteEnd("'{0}' MoveSessionHostToRdsOU", ProviderSettings.ProviderName);
}
catch (Exception ex)
{
Log.WriteError(String.Format("'{0}' MoveSessionHostToRdsOU", ProviderSettings.ProviderName), ex);
throw;
}
}
[WebMethod, SoapHeader("settings")]
public void ApplyGPO(string organizationId, string collectionName, RdsServerSettings serverSettings)
{
try
{
Log.WriteStart("'{0}' ApplyGPO", ProviderSettings.ProviderName);
RDSProvider.ApplyGPO(organizationId, collectionName, serverSettings);
Log.WriteEnd("'{0}' ApplyGPO", ProviderSettings.ProviderName);
}
catch (Exception ex)
{
Log.WriteError(String.Format("'{0}' ApplyGPO", ProviderSettings.ProviderName), ex);
throw;
}
}
[WebMethod, SoapHeader("settings")]
public void ShadowSession(string sessionId, string fqdName, bool control)
{
try
{
Log.WriteStart("'{0}' ShadowSession", ProviderSettings.ProviderName);
RDSProvider.ShadowSession(sessionId, fqdName, control);
Log.WriteEnd("'{0}' ShadowSession", ProviderSettings.ProviderName);
}
catch (Exception ex)
{
Log.WriteError(String.Format("'{0}' ShadowSession", ProviderSettings.ProviderName), ex);
throw;
}
}
[WebMethod, SoapHeader("settings")]
public void MoveSessionHostsToCollectionOU(List<RdsServer> servers, string collectionName, string organizationId)
{
try
{
Log.WriteStart("'{0}' MoveSessionHostsToCollectionOU", ProviderSettings.ProviderName);
RDSProvider.MoveSessionHostsToCollectionOU(servers, collectionName, organizationId);
Log.WriteEnd("'{0}' MoveSessionHostsToCollectionOU", ProviderSettings.ProviderName);
}
catch (Exception ex)
{
Log.WriteError(String.Format("'{0}' MoveSessionHostsToCollectionOU", ProviderSettings.ProviderName), ex);
throw;
}
}
[WebMethod, SoapHeader("settings")]
public ImportedRdsCollection GetExistingCollection(string collectionName)
{
try
{
Log.WriteStart("'{0}' GetExistingCollection", ProviderSettings.ProviderName);
return RDSProvider.GetExistingCollection(collectionName);
Log.WriteEnd("'{0}' GetExistingCollection", ProviderSettings.ProviderName);
}
catch (Exception ex)
{
Log.WriteError(String.Format("'{0}' GetExistingCollection", ProviderSettings.ProviderName), ex);
throw;
}
}
[WebMethod, SoapHeader("settings")]
public void ImportCollection(string organizationId, RdsCollection collection, List<string> users)
{
try
{
Log.WriteStart("'{0}' ImportCollection", ProviderSettings.ProviderName);
RDSProvider.ImportCollection(organizationId, collection, users);
Log.WriteEnd("'{0}' ImportCollection", ProviderSettings.ProviderName);
}
catch (Exception ex)
{
Log.WriteError(String.Format("'{0}' ImportCollection", ProviderSettings.ProviderName), ex);
throw;
}
}
[WebMethod, SoapHeader("settings")]
public void SendMessage(List<RdsMessageRecipient> recipients, string text)
{
try
{
Log.WriteStart("'{0}' SendMessage", ProviderSettings.ProviderName);
RDSProvider.SendMessage(recipients, text);
Log.WriteEnd("'{0}' SendMessage", ProviderSettings.ProviderName);
}
catch (Exception ex)
{
Log.WriteError(String.Format("'{0}' SendMessage", ProviderSettings.ProviderName), ex);
throw;
}
}
}
}
| |
// Generated by UblXml2CSharp
using System.Xml;
using UblLarsen.Ubl2;
using UblLarsen.Ubl2.Cac;
using UblLarsen.Ubl2.Ext;
using UblLarsen.Ubl2.Udt;
namespace UblLarsen.Test.UblClass
{
internal class UBLForecast21Example
{
public static ForecastType Create()
{
var doc = new ForecastType
{
UBLVersionID = "2.1",
ProfileID = "bpid:urn:oasis:names:draft:bpss:ubl-2-1-cpfr-forecast-draft",
ID = "OF758494",
CopyIndicator = false,
UUID = "349ABBAE-DF9D-40B4-849F-94C5FF9D1AF4",
IssueDate = "2010-01-01",
IssueTime = "12:00:01.000",
Note = new TextType[]
{
new TextType
{
Value = "sample"
}
},
BasedOnConsensusIndicator = true,
ForecastPurposeCode = "ORDER_FORECAST",
ForecastPeriod = new PeriodType
{
StartDate = "2010-02-01",
EndDate = "2010-05-26"
},
SenderParty = new PartyType
{
PartyIdentification = new PartyIdentificationType[]
{
new PartyIdentificationType
{
ID = "6903148000007"
}
},
PartyName = new PartyNameType[]
{
new PartyNameType
{
Name = "Consortial"
}
},
PostalAddress = new AddressType
{
StreetName = "Busy Street",
BuildingName = "Thereabouts",
BuildingNumber = "56A",
CityName = "Farthing",
PostalZone = "AA99 1BB",
CountrySubentity = "Heremouthshire",
AddressLine = new AddressLineType[]
{
new AddressLineType
{
Line = "The Roundabout"
}
},
Country = new CountryType
{
IdentificationCode = "GB"
}
},
PartyTaxScheme = new PartyTaxSchemeType[]
{
new PartyTaxSchemeType
{
RegistrationName = "Farthing Purchasing Consortium",
CompanyID = "175 269 2355",
ExemptionReason = new TextType[]
{
new TextType
{
Value = "N/A"
}
},
TaxScheme = new TaxSchemeType
{
ID = "VAT",
TaxTypeCode = "VAT"
}
}
},
Contact = new ContactType
{
Name = "Mrs Bouquet",
Telephone = "0158 1233714",
Telefax = "0158 1233856",
ElectronicMail = "bouquet@fpconsortial.co.uk"
}
},
ReceiverParty = new PartyType
{
PartyIdentification = new PartyIdentificationType[]
{
new PartyIdentificationType
{
ID = "2203148000007"
}
},
PartyName = new PartyNameType[]
{
new PartyNameType
{
Name = "IYT Corporation"
}
},
PostalAddress = new AddressType
{
StreetName = "Avon Way",
BuildingName = "Thereabouts",
BuildingNumber = "56A",
CityName = "Bridgtow",
PostalZone = "ZZ99 1ZZ",
CountrySubentity = "Avon",
AddressLine = new AddressLineType[]
{
new AddressLineType
{
Line = "3rd Floor, Room 5"
}
},
Country = new CountryType
{
IdentificationCode = "GB"
}
},
PartyTaxScheme = new PartyTaxSchemeType[]
{
new PartyTaxSchemeType
{
RegistrationName = "Bridgtow District Council",
CompanyID = "12356478",
ExemptionReason = new TextType[]
{
new TextType
{
Value = "Local Authority"
}
},
TaxScheme = new TaxSchemeType
{
ID = "UK VAT",
TaxTypeCode = "VAT"
}
}
},
Contact = new ContactType
{
Name = "Mr Fred Churchill",
Telephone = "0127 2653214",
Telefax = "0127 2653215",
ElectronicMail = "fred@iytcorporation.gov.uk"
}
},
BuyerCustomerParty = new CustomerPartyType
{
Party = new PartyType
{
PartyIdentification = new PartyIdentificationType[]
{
new PartyIdentificationType
{
ID = "0012345000359"
}
}
}
},
SellerSupplierParty = new SupplierPartyType
{
Party = new PartyType
{
PartyIdentification = new PartyIdentificationType[]
{
new PartyIdentificationType
{
ID = "0012345000058"
}
}
}
},
ForecastLine = new ForecastLineType[]
{
new ForecastLineType
{
ID = "forecastLineID",
ForecastTypeCode = "TOTAL",
ForecastPeriod = new PeriodType
{
StartDate = "2010-02-01",
EndDate = "2010-05-26"
},
SalesItem = new SalesItemType
{
Quantity = new QuantityType
{
unitCode = "KGM",
Value = 20M
},
Item = new ItemType
{
Description = new TextType[]
{
new TextType
{
Value = "Acme beeswax"
}
},
Name = "beeswax",
BuyersItemIdentification = new ItemIdentificationType
{
ID = "6578489"
},
SellersItemIdentification = new ItemIdentificationType
{
ID = "17589683"
},
StandardItemIdentification = new ItemIdentificationType
{
ID = "00123450000584"
}
}
}
}
}
};
doc.Xmlns = new System.Xml.Serialization.XmlSerializerNamespaces(new[]
{
new XmlQualifiedName("cac","urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2"),
new XmlQualifiedName("cbc","urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2"),
});
return doc;
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using FluentAssertions.Execution;
namespace FluentAssertions.Equivalency.Steps
{
public class GenericDictionaryEquivalencyStep : IEquivalencyStep
{
#pragma warning disable SA1110 // Allow opening parenthesis on new line to reduce line length
private static readonly MethodInfo AssertSameLengthMethod =
new Func<IDictionary<object, object>, IDictionary<object, object>, bool>(AssertSameLength).GetMethodInfo()
.GetGenericMethodDefinition();
private static readonly MethodInfo AssertDictionaryEquivalenceMethod =
new Action<EquivalencyValidationContext, IEquivalencyValidator, IEquivalencyAssertionOptions,
IDictionary<object, object>, IDictionary<object, object>>
(AssertDictionaryEquivalence).GetMethodInfo().GetGenericMethodDefinition();
#pragma warning restore SA1110
public EquivalencyResult Handle(Comparands comparands, IEquivalencyValidationContext context,
IEquivalencyValidator nestedValidator)
{
if (comparands.Expectation != null)
{
Type expectationType = comparands.GetExpectedType(context.Options);
bool isDictionary = DictionaryInterfaceInfo.TryGetFrom(expectationType, "expectation", out var expectedDictionary);
if (isDictionary)
{
Handle(comparands, expectedDictionary, context, nestedValidator);
return EquivalencyResult.AssertionCompleted;
}
}
return EquivalencyResult.ContinueWithNext;
}
private static void Handle(Comparands comparands, DictionaryInterfaceInfo expectedDictionary,
IEquivalencyValidationContext context,
IEquivalencyValidator nestedValidator)
{
if (AssertSubjectIsNotNull(comparands.Subject)
&& AssertExpectationIsNotNull(comparands.Subject, comparands.Expectation))
{
var (isDictionary, actualDictionary) = EnsureSubjectIsDictionary(comparands, expectedDictionary);
if (isDictionary)
{
if (AssertSameLength(comparands, actualDictionary, expectedDictionary))
{
AssertDictionaryEquivalence(comparands, context, nestedValidator, actualDictionary, expectedDictionary);
}
}
}
}
private static bool AssertSubjectIsNotNull(object subject)
{
return AssertionScope.Current
.ForCondition(subject is not null)
.FailWith("Expected {context:Subject} not to be {0}{reason}.", new object[] { null });
}
private static bool AssertExpectationIsNotNull(object subject, object expectation)
{
return AssertionScope.Current
.ForCondition(expectation is not null)
.FailWith("Expected {context:Subject} to be {0}{reason}, but found {1}.", null, subject);
}
private static (bool isDictionary, DictionaryInterfaceInfo info) EnsureSubjectIsDictionary(Comparands comparands,
DictionaryInterfaceInfo expectedDictionary)
{
bool isDictionary = DictionaryInterfaceInfo.TryGetFromWithKey(comparands.Subject.GetType(), "subject",
expectedDictionary.Key, out var actualDictionary);
if (!isDictionary)
{
if (expectedDictionary.TryConvertFrom(comparands.Subject, out var convertedSubject))
{
comparands.Subject = convertedSubject;
isDictionary = DictionaryInterfaceInfo.TryGetFrom(comparands.Subject.GetType(), "subject", out actualDictionary);
}
}
if (!isDictionary)
{
AssertionScope.Current.FailWith(
$"Expected {{context:subject}} to be a dictionary or collection of key-value pairs that is keyed to type {expectedDictionary.Key}. " +
$"It implements {actualDictionary}.");
}
return (isDictionary, actualDictionary);
}
private static bool AssertSameLength(Comparands comparands, DictionaryInterfaceInfo actualDictionary,
DictionaryInterfaceInfo expectedDictionary)
{
if (comparands.Subject is ICollection subjectCollection
&& comparands.Expectation is ICollection expectationCollection
&& subjectCollection.Count == expectationCollection.Count)
{
return true;
}
return (bool)AssertSameLengthMethod
.MakeGenericMethod(actualDictionary.Key, actualDictionary.Value, expectedDictionary.Key, expectedDictionary.Value)
.Invoke(null, new[] { comparands.Subject, comparands.Expectation });
}
private static bool AssertSameLength<TSubjectKey, TSubjectValue, TExpectedKey, TExpectedValue>(
IDictionary<TSubjectKey, TSubjectValue> subject, IDictionary<TExpectedKey, TExpectedValue> expectation)
// Type constraint of TExpectedKey is asymmetric in regards to TSubjectKey
// but it is valid. This constraint is implicitly enforced by the dictionary interface info which is called before
// the AssertSameLength method.
where TExpectedKey : TSubjectKey
{
if (expectation.Count == subject.Count)
{
return true;
}
KeyDifference<TSubjectKey, TExpectedKey> keyDifference = CalculateKeyDifference(subject, expectation);
bool hasMissingKeys = keyDifference.MissingKeys.Count > 0;
bool hasAdditionalKeys = keyDifference.AdditionalKeys.Any();
return Execute.Assertion
.WithExpectation("Expected {context:subject} to be a dictionary with {0} item(s){reason}, ", expectation.Count)
.ForCondition(!hasMissingKeys || hasAdditionalKeys)
.FailWith("but it misses key(s) {0}", keyDifference.MissingKeys)
.Then
.ForCondition(hasMissingKeys || !hasAdditionalKeys)
.FailWith("but has additional key(s) {0}", keyDifference.AdditionalKeys)
.Then
.ForCondition(!hasMissingKeys || !hasAdditionalKeys)
.FailWith("but it misses key(s) {0} and has additional key(s) {1}", keyDifference.MissingKeys,
keyDifference.AdditionalKeys)
.Then
.ClearExpectation();
}
private static KeyDifference<TSubjectKey, TExpectedKey> CalculateKeyDifference<TSubjectKey, TSubjectValue, TExpectedKey,
TExpectedValue>(IDictionary<TSubjectKey, TSubjectValue> subject,
IDictionary<TExpectedKey, TExpectedValue> expectation)
where TExpectedKey : TSubjectKey
{
var missingKeys = new List<TExpectedKey>();
var presentKeys = new HashSet<TSubjectKey>();
foreach (TExpectedKey expectationKey in expectation.Keys)
{
if (subject.ContainsKey(expectationKey))
{
presentKeys.Add(expectationKey);
}
else
{
missingKeys.Add(expectationKey);
}
}
var additionalKeys = new List<TSubjectKey>();
foreach (TSubjectKey subjectKey in subject.Keys)
{
if (!presentKeys.Contains(subjectKey))
{
additionalKeys.Add(subjectKey);
}
}
return new KeyDifference<TSubjectKey, TExpectedKey>(missingKeys, additionalKeys);
}
private static void AssertDictionaryEquivalence(Comparands comparands, IEquivalencyValidationContext context,
IEquivalencyValidator parent, DictionaryInterfaceInfo actualDictionary, DictionaryInterfaceInfo expectedDictionary)
{
AssertDictionaryEquivalenceMethod
.MakeGenericMethod(actualDictionary.Key, actualDictionary.Value, expectedDictionary.Key, expectedDictionary.Value)
.Invoke(null, new[] { context, parent, context.Options, comparands.Subject, comparands.Expectation });
}
private static void AssertDictionaryEquivalence<TSubjectKey, TSubjectValue, TExpectedKey, TExpectedValue>(
EquivalencyValidationContext context,
IEquivalencyValidator parent,
IEquivalencyAssertionOptions options,
IDictionary<TSubjectKey, TSubjectValue> subject,
IDictionary<TExpectedKey, TExpectedValue> expectation)
where TExpectedKey : TSubjectKey
{
foreach (TExpectedKey key in expectation.Keys)
{
if (subject.TryGetValue(key, out TSubjectValue subjectValue))
{
if (options.IsRecursive)
{
// Run the child assertion without affecting the current context
using (new AssertionScope())
{
var nestedComparands = new Comparands(subject[key], expectation[key], typeof(TExpectedValue));
parent.RecursivelyAssertEquality(nestedComparands,
context.AsDictionaryItem<TExpectedKey, TExpectedValue>(key));
}
}
else
{
subjectValue.Should().Be(expectation[key], context.Reason.FormattedMessage, context.Reason.Arguments);
}
}
else
{
AssertionScope.Current
.BecauseOf(context.Reason)
.FailWith("Expected {context:subject} to contain key {0}{reason}.", key);
}
}
}
private class KeyDifference<TSubjectKey, TExpectedKey>
{
public KeyDifference(List<TExpectedKey> missingKeys, List<TSubjectKey> additionalKeys)
{
MissingKeys = missingKeys;
AdditionalKeys = additionalKeys;
}
public List<TExpectedKey> MissingKeys { get; }
public List<TSubjectKey> AdditionalKeys { get; }
}
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
namespace Apache.Ignite.Core.Impl.Cache
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Threading.Tasks;
using Apache.Ignite.Core.Binary;
using Apache.Ignite.Core.Cache;
using Apache.Ignite.Core.Cache.Configuration;
using Apache.Ignite.Core.Cache.Expiry;
using Apache.Ignite.Core.Cache.Query;
using Apache.Ignite.Core.Cache.Query.Continuous;
using Apache.Ignite.Core.Cluster;
using Apache.Ignite.Core.Impl.Binary;
using Apache.Ignite.Core.Impl.Binary.IO;
using Apache.Ignite.Core.Impl.Cache.Expiry;
using Apache.Ignite.Core.Impl.Cache.Query;
using Apache.Ignite.Core.Impl.Cache.Query.Continuous;
using Apache.Ignite.Core.Impl.Cluster;
using Apache.Ignite.Core.Impl.Common;
using Apache.Ignite.Core.Impl.Transactions;
/// <summary>
/// Native cache wrapper.
/// </summary>
[SuppressMessage("Microsoft.Design", "CA1001:TypesThatOwnDisposableFieldsShouldBeDisposable")]
internal class CacheImpl<TK, TV> : PlatformTargetAdapter, ICache<TK, TV>, ICacheInternal, ICacheLockInternal
{
/** Ignite instance. */
private readonly IIgniteInternal _ignite;
/** Flag: skip store. */
private readonly bool _flagSkipStore;
/** Flag: keep binary. */
private readonly bool _flagKeepBinary;
/** Flag: no-retries.*/
private readonly bool _flagNoRetries;
/** Flag: partition recover.*/
private readonly bool _flagPartitionRecover;
/** Transaction manager. */
private readonly CacheTransactionManager _txManager;
/** Pre-allocated delegate. */
private readonly Func<IBinaryStream, Exception> _readException;
/// <summary>
/// Constructor.
/// </summary>
/// <param name="target">Target.</param>
/// <param name="flagSkipStore">Skip store flag.</param>
/// <param name="flagKeepBinary">Keep binary flag.</param>
/// <param name="flagNoRetries">No-retries mode flag.</param>
/// <param name="flagPartitionRecover">Partition recover mode flag.</param>
public CacheImpl(IPlatformTargetInternal target,
bool flagSkipStore, bool flagKeepBinary, bool flagNoRetries, bool flagPartitionRecover)
: base(target)
{
_ignite = target.Marshaller.Ignite;
_flagSkipStore = flagSkipStore;
_flagKeepBinary = flagKeepBinary;
_flagNoRetries = flagNoRetries;
_flagPartitionRecover = flagPartitionRecover;
_txManager = GetConfiguration().AtomicityMode == CacheAtomicityMode.Transactional
? new CacheTransactionManager(_ignite.GetTransactions())
: null;
_readException = stream => ReadException(Marshaller.StartUnmarshal(stream));
}
/** <inheritDoc /> */
public IIgnite Ignite
{
get { return _ignite; }
}
/// <summary>
/// Performs async operation.
/// </summary>
private Task DoOutOpAsync<T1>(CacheOp op, T1 val1)
{
return DoOutOpAsync<object, T1>((int) op, val1);
}
/// <summary>
/// Performs async operation.
/// </summary>
private Task<TR> DoOutOpAsync<T1, TR>(CacheOp op, T1 val1)
{
return DoOutOpAsync<T1, TR>((int) op, val1);
}
/// <summary>
/// Performs async operation.
/// </summary>
private Task DoOutOpAsync<T1, T2>(CacheOp op, T1 val1, T2 val2)
{
return DoOutOpAsync<T1, T2, object>((int) op, val1, val2);
}
/// <summary>
/// Performs async operation.
/// </summary>
private Task<TR> DoOutOpAsync<T1, T2, TR>(CacheOp op, T1 val1, T2 val2)
{
return DoOutOpAsync<T1, T2, TR>((int) op, val1, val2);
}
/// <summary>
/// Performs async operation.
/// </summary>
private Task DoOutOpAsync(CacheOp op, Action<BinaryWriter> writeAction = null)
{
return DoOutOpAsync<object>(op, writeAction);
}
/// <summary>
/// Performs async operation.
/// </summary>
private Task<T> DoOutOpAsync<T>(CacheOp op, Action<BinaryWriter> writeAction = null,
Func<BinaryReader, T> convertFunc = null)
{
return DoOutOpAsync((int)op, writeAction, IsKeepBinary, convertFunc);
}
/** <inheritDoc /> */
public string Name
{
get { return DoInOp<string>((int)CacheOp.GetName); }
}
/** <inheritDoc /> */
public CacheConfiguration GetConfiguration()
{
return DoInOp((int) CacheOp.GetConfig, stream => new CacheConfiguration(
BinaryUtils.Marshaller.StartUnmarshal(stream)));
}
/** <inheritDoc /> */
public bool IsEmpty()
{
return GetSize() == 0;
}
/** <inheritDoc /> */
public ICache<TK, TV> WithSkipStore()
{
if (_flagSkipStore)
return this;
return new CacheImpl<TK, TV>(DoOutOpObject((int) CacheOp.WithSkipStore),
true, _flagKeepBinary, true, _flagPartitionRecover);
}
/// <summary>
/// Skip store flag getter.
/// </summary>
internal bool IsSkipStore { get { return _flagSkipStore; } }
/** <inheritDoc /> */
public ICache<TK1, TV1> WithKeepBinary<TK1, TV1>()
{
if (_flagKeepBinary)
{
var result = this as ICache<TK1, TV1>;
if (result == null)
throw new InvalidOperationException(
"Can't change type of binary cache. WithKeepBinary has been called on an instance of " +
"binary cache with incompatible generic arguments.");
return result;
}
return new CacheImpl<TK1, TV1>(DoOutOpObject((int) CacheOp.WithKeepBinary),
_flagSkipStore, true, _flagNoRetries, _flagPartitionRecover);
}
/** <inheritDoc /> */
public ICache<TK, TV> WithExpiryPolicy(IExpiryPolicy plc)
{
IgniteArgumentCheck.NotNull(plc, "plc");
var cache0 = DoOutOpObject((int)CacheOp.WithExpiryPolicy, w => ExpiryPolicySerializer.WritePolicy(w, plc));
return new CacheImpl<TK, TV>(cache0, _flagSkipStore, _flagKeepBinary,
_flagNoRetries, _flagPartitionRecover);
}
/** <inheritDoc /> */
public bool IsKeepBinary
{
get { return _flagKeepBinary; }
}
/** <inheritDoc /> */
public void LoadCache(ICacheEntryFilter<TK, TV> p, params object[] args)
{
DoOutInOpX((int) CacheOp.LoadCache, writer => WriteLoadCacheData(writer, p, args), _readException);
}
/** <inheritDoc /> */
public Task LoadCacheAsync(ICacheEntryFilter<TK, TV> p, params object[] args)
{
return DoOutOpAsync(CacheOp.LoadCacheAsync, writer => WriteLoadCacheData(writer, p, args));
}
/** <inheritDoc /> */
public void LocalLoadCache(ICacheEntryFilter<TK, TV> p, params object[] args)
{
DoOutInOpX((int) CacheOp.LocLoadCache, writer => WriteLoadCacheData(writer, p, args), _readException);
}
/** <inheritDoc /> */
public Task LocalLoadCacheAsync(ICacheEntryFilter<TK, TV> p, params object[] args)
{
return DoOutOpAsync(CacheOp.LocLoadCacheAsync, writer => WriteLoadCacheData(writer, p, args));
}
/// <summary>
/// Writes the load cache data to the writer.
/// </summary>
private void WriteLoadCacheData(BinaryWriter writer, ICacheEntryFilter<TK, TV> p, object[] args)
{
if (p != null)
{
var p0 = new CacheEntryFilterHolder(p, (k, v) => p.Invoke(new CacheEntry<TK, TV>((TK) k, (TV) v)),
Marshaller, IsKeepBinary);
writer.WriteObject(p0);
}
else
writer.WriteObject<CacheEntryFilterHolder>(null);
if (args != null && args.Length > 0)
{
writer.WriteInt(args.Length);
foreach (var o in args)
writer.WriteObject(o);
}
else
{
writer.WriteInt(0);
}
}
/** <inheritDoc /> */
public void LoadAll(IEnumerable<TK> keys, bool replaceExistingValues)
{
LoadAllAsync(keys, replaceExistingValues).Wait();
}
/** <inheritDoc /> */
public Task LoadAllAsync(IEnumerable<TK> keys, bool replaceExistingValues)
{
return DoOutOpAsync(CacheOp.LoadAll, writer =>
{
writer.WriteBoolean(replaceExistingValues);
writer.WriteEnumerable(keys);
});
}
/** <inheritDoc /> */
public bool ContainsKey(TK key)
{
IgniteArgumentCheck.NotNull(key, "key");
return DoOutOp(CacheOp.ContainsKey, key);
}
/** <inheritDoc /> */
public Task<bool> ContainsKeyAsync(TK key)
{
IgniteArgumentCheck.NotNull(key, "key");
return DoOutOpAsync<TK, bool>(CacheOp.ContainsKeyAsync, key);
}
/** <inheritDoc /> */
public bool ContainsKeys(IEnumerable<TK> keys)
{
IgniteArgumentCheck.NotNull(keys, "keys");
return DoOutOp(CacheOp.ContainsKeys, writer => writer.WriteEnumerable(keys));
}
/** <inheritDoc /> */
public Task<bool> ContainsKeysAsync(IEnumerable<TK> keys)
{
IgniteArgumentCheck.NotNull(keys, "keys");
return DoOutOpAsync<bool>(CacheOp.ContainsKeysAsync, writer => writer.WriteEnumerable(keys));
}
/** <inheritDoc /> */
public TV LocalPeek(TK key, params CachePeekMode[] modes)
{
IgniteArgumentCheck.NotNull(key, "key");
TV res;
if (TryLocalPeek(key, out res))
return res;
throw GetKeyNotFoundException();
}
/** <inheritDoc /> */
public bool TryLocalPeek(TK key, out TV value, params CachePeekMode[] modes)
{
IgniteArgumentCheck.NotNull(key, "key");
var res = DoOutInOpX((int)CacheOp.Peek,
w =>
{
w.Write(key);
w.WriteInt(EncodePeekModes(modes));
},
(s, r) => r == True ? new CacheResult<TV>(Unmarshal<TV>(s)) : new CacheResult<TV>(),
_readException);
value = res.Success ? res.Value : default(TV);
return res.Success;
}
/** <inheritDoc /> */
public TV this[TK key]
{
get
{
return Get(key);
}
set
{
Put(key, value);
}
}
/** <inheritDoc /> */
public TV Get(TK key)
{
IgniteArgumentCheck.NotNull(key, "key");
return DoOutInOpX((int) CacheOp.Get,
w => w.Write(key),
(stream, res) =>
{
if (res != True)
throw GetKeyNotFoundException();
return Unmarshal<TV>(stream);
}, _readException);
}
/** <inheritDoc /> */
public Task<TV> GetAsync(TK key)
{
IgniteArgumentCheck.NotNull(key, "key");
return DoOutOpAsync(CacheOp.GetAsync, w => w.WriteObject(key), reader =>
{
if (reader != null)
return reader.ReadObject<TV>();
throw GetKeyNotFoundException();
});
}
/** <inheritDoc /> */
public bool TryGet(TK key, out TV value)
{
IgniteArgumentCheck.NotNull(key, "key");
var res = DoOutInOpNullable(CacheOp.Get, key);
value = res.Value;
return res.Success;
}
/** <inheritDoc /> */
public Task<CacheResult<TV>> TryGetAsync(TK key)
{
IgniteArgumentCheck.NotNull(key, "key");
return DoOutOpAsync(CacheOp.GetAsync, w => w.WriteObject(key), reader => GetCacheResult(reader));
}
/** <inheritDoc /> */
public ICollection<ICacheEntry<TK, TV>> GetAll(IEnumerable<TK> keys)
{
IgniteArgumentCheck.NotNull(keys, "keys");
return DoOutInOpX((int) CacheOp.GetAll,
writer => writer.WriteEnumerable(keys),
(s, r) => r == True ? ReadGetAllDictionary(Marshaller.StartUnmarshal(s, _flagKeepBinary)) : null,
_readException);
}
/** <inheritDoc /> */
public Task<ICollection<ICacheEntry<TK, TV>>> GetAllAsync(IEnumerable<TK> keys)
{
IgniteArgumentCheck.NotNull(keys, "keys");
return DoOutOpAsync(CacheOp.GetAllAsync, w => w.WriteEnumerable(keys), r => ReadGetAllDictionary(r));
}
/** <inheritdoc /> */
public void Put(TK key, TV val)
{
IgniteArgumentCheck.NotNull(key, "key");
IgniteArgumentCheck.NotNull(val, "val");
StartTx();
DoOutOp(CacheOp.Put, key, val);
}
/** <inheritDoc /> */
public Task PutAsync(TK key, TV val)
{
IgniteArgumentCheck.NotNull(key, "key");
IgniteArgumentCheck.NotNull(val, "val");
StartTx();
return DoOutOpAsync(CacheOp.PutAsync, key, val);
}
/** <inheritDoc /> */
public CacheResult<TV> GetAndPut(TK key, TV val)
{
IgniteArgumentCheck.NotNull(key, "key");
IgniteArgumentCheck.NotNull(val, "val");
StartTx();
return DoOutInOpNullable(CacheOp.GetAndPut, key, val);
}
/** <inheritDoc /> */
public Task<CacheResult<TV>> GetAndPutAsync(TK key, TV val)
{
IgniteArgumentCheck.NotNull(key, "key");
IgniteArgumentCheck.NotNull(val, "val");
StartTx();
return DoOutOpAsync(CacheOp.GetAndPutAsync, w =>
{
w.WriteObject(key);
w.WriteObject(val);
}, r => GetCacheResult(r));
}
/** <inheritDoc /> */
public CacheResult<TV> GetAndReplace(TK key, TV val)
{
IgniteArgumentCheck.NotNull(key, "key");
IgniteArgumentCheck.NotNull(val, "val");
StartTx();
return DoOutInOpNullable(CacheOp.GetAndReplace, key, val);
}
/** <inheritDoc /> */
public Task<CacheResult<TV>> GetAndReplaceAsync(TK key, TV val)
{
IgniteArgumentCheck.NotNull(key, "key");
IgniteArgumentCheck.NotNull(val, "val");
StartTx();
return DoOutOpAsync(CacheOp.GetAndReplaceAsync, w =>
{
w.WriteObject(key);
w.WriteObject(val);
}, r => GetCacheResult(r));
}
/** <inheritDoc /> */
public CacheResult<TV> GetAndRemove(TK key)
{
IgniteArgumentCheck.NotNull(key, "key");
StartTx();
return DoOutInOpNullable(CacheOp.GetAndRemove, key);
}
/** <inheritDoc /> */
public Task<CacheResult<TV>> GetAndRemoveAsync(TK key)
{
IgniteArgumentCheck.NotNull(key, "key");
StartTx();
return DoOutOpAsync(CacheOp.GetAndRemoveAsync, w => w.WriteObject(key), r => GetCacheResult(r));
}
/** <inheritdoc /> */
public bool PutIfAbsent(TK key, TV val)
{
IgniteArgumentCheck.NotNull(key, "key");
IgniteArgumentCheck.NotNull(val, "val");
StartTx();
return DoOutOp(CacheOp.PutIfAbsent, key, val);
}
/** <inheritDoc /> */
public Task<bool> PutIfAbsentAsync(TK key, TV val)
{
IgniteArgumentCheck.NotNull(key, "key");
IgniteArgumentCheck.NotNull(val, "val");
StartTx();
return DoOutOpAsync<TK, TV, bool>(CacheOp.PutIfAbsentAsync, key, val);
}
/** <inheritdoc /> */
public CacheResult<TV> GetAndPutIfAbsent(TK key, TV val)
{
IgniteArgumentCheck.NotNull(key, "key");
IgniteArgumentCheck.NotNull(val, "val");
StartTx();
return DoOutInOpNullable(CacheOp.GetAndPutIfAbsent, key, val);
}
/** <inheritDoc /> */
public Task<CacheResult<TV>> GetAndPutIfAbsentAsync(TK key, TV val)
{
IgniteArgumentCheck.NotNull(key, "key");
IgniteArgumentCheck.NotNull(val, "val");
StartTx();
return DoOutOpAsync(CacheOp.GetAndPutIfAbsentAsync, w =>
{
w.WriteObject(key);
w.WriteObject(val);
}, r => GetCacheResult(r));
}
/** <inheritdoc /> */
public bool Replace(TK key, TV val)
{
IgniteArgumentCheck.NotNull(key, "key");
IgniteArgumentCheck.NotNull(val, "val");
StartTx();
return DoOutOp(CacheOp.Replace2, key, val);
}
/** <inheritDoc /> */
public Task<bool> ReplaceAsync(TK key, TV val)
{
IgniteArgumentCheck.NotNull(key, "key");
IgniteArgumentCheck.NotNull(val, "val");
StartTx();
return DoOutOpAsync<TK, TV, bool>(CacheOp.Replace2Async, key, val);
}
/** <inheritdoc /> */
public bool Replace(TK key, TV oldVal, TV newVal)
{
IgniteArgumentCheck.NotNull(key, "key");
IgniteArgumentCheck.NotNull(oldVal, "oldVal");
IgniteArgumentCheck.NotNull(newVal, "newVal");
StartTx();
return DoOutOp(CacheOp.Replace3, key, oldVal, newVal);
}
/** <inheritDoc /> */
public Task<bool> ReplaceAsync(TK key, TV oldVal, TV newVal)
{
IgniteArgumentCheck.NotNull(key, "key");
IgniteArgumentCheck.NotNull(oldVal, "oldVal");
IgniteArgumentCheck.NotNull(newVal, "newVal");
StartTx();
return DoOutOpAsync<bool>(CacheOp.Replace3Async, w =>
{
w.WriteObject(key);
w.WriteObject(oldVal);
w.WriteObject(newVal);
});
}
/** <inheritdoc /> */
public void PutAll(IEnumerable<KeyValuePair<TK, TV>> vals)
{
IgniteArgumentCheck.NotNull(vals, "vals");
StartTx();
DoOutOp(CacheOp.PutAll, writer => writer.WriteDictionary(vals));
}
/** <inheritDoc /> */
public Task PutAllAsync(IEnumerable<KeyValuePair<TK, TV>> vals)
{
IgniteArgumentCheck.NotNull(vals, "vals");
StartTx();
return DoOutOpAsync(CacheOp.PutAllAsync, writer => writer.WriteDictionary(vals));
}
/** <inheritdoc /> */
public void LocalEvict(IEnumerable<TK> keys)
{
IgniteArgumentCheck.NotNull(keys, "keys");
DoOutOp(CacheOp.LocEvict, writer => writer.WriteEnumerable(keys));
}
/** <inheritdoc /> */
public void Clear()
{
DoOutInOp((int) CacheOp.ClearCache);
}
/** <inheritDoc /> */
public Task ClearAsync()
{
return DoOutOpAsync(CacheOp.ClearCacheAsync);
}
/** <inheritdoc /> */
public void Clear(TK key)
{
IgniteArgumentCheck.NotNull(key, "key");
DoOutOp(CacheOp.Clear, key);
}
/** <inheritDoc /> */
public Task ClearAsync(TK key)
{
IgniteArgumentCheck.NotNull(key, "key");
return DoOutOpAsync(CacheOp.ClearAsync, key);
}
/** <inheritdoc /> */
public void ClearAll(IEnumerable<TK> keys)
{
IgniteArgumentCheck.NotNull(keys, "keys");
DoOutOp(CacheOp.ClearAll, writer => writer.WriteEnumerable(keys));
}
/** <inheritDoc /> */
public Task ClearAllAsync(IEnumerable<TK> keys)
{
IgniteArgumentCheck.NotNull(keys, "keys");
return DoOutOpAsync(CacheOp.ClearAllAsync, writer => writer.WriteEnumerable(keys));
}
/** <inheritdoc /> */
public void LocalClear(TK key)
{
IgniteArgumentCheck.NotNull(key, "key");
DoOutOp(CacheOp.LocalClear, key);
}
/** <inheritdoc /> */
public void LocalClearAll(IEnumerable<TK> keys)
{
IgniteArgumentCheck.NotNull(keys, "keys");
DoOutOp(CacheOp.LocalClearAll, writer => writer.WriteEnumerable(keys));
}
/** <inheritdoc /> */
public bool Remove(TK key)
{
IgniteArgumentCheck.NotNull(key, "key");
StartTx();
return DoOutOp(CacheOp.RemoveObj, key);
}
/** <inheritDoc /> */
public Task<bool> RemoveAsync(TK key)
{
IgniteArgumentCheck.NotNull(key, "key");
StartTx();
return DoOutOpAsync<TK, bool>(CacheOp.RemoveObjAsync, key);
}
/** <inheritDoc /> */
public bool Remove(TK key, TV val)
{
IgniteArgumentCheck.NotNull(key, "key");
IgniteArgumentCheck.NotNull(val, "val");
StartTx();
return DoOutOp(CacheOp.RemoveBool, key, val);
}
/** <inheritDoc /> */
public Task<bool> RemoveAsync(TK key, TV val)
{
IgniteArgumentCheck.NotNull(key, "key");
IgniteArgumentCheck.NotNull(val, "val");
StartTx();
return DoOutOpAsync<TK, TV, bool>(CacheOp.RemoveBoolAsync, key, val);
}
/** <inheritDoc /> */
public void RemoveAll(IEnumerable<TK> keys)
{
IgniteArgumentCheck.NotNull(keys, "keys");
StartTx();
DoOutOp(CacheOp.RemoveAll, writer => writer.WriteEnumerable(keys));
}
/** <inheritDoc /> */
public Task RemoveAllAsync(IEnumerable<TK> keys)
{
IgniteArgumentCheck.NotNull(keys, "keys");
StartTx();
return DoOutOpAsync(CacheOp.RemoveAllAsync, writer => writer.WriteEnumerable(keys));
}
/** <inheritDoc /> */
public void RemoveAll()
{
StartTx();
DoOutInOp((int) CacheOp.RemoveAll2);
}
/** <inheritDoc /> */
public Task RemoveAllAsync()
{
StartTx();
return DoOutOpAsync(CacheOp.RemoveAll2Async);
}
/** <inheritDoc /> */
public int GetLocalSize(params CachePeekMode[] modes)
{
return Size0(true, modes);
}
/** <inheritDoc /> */
public int GetSize(params CachePeekMode[] modes)
{
return Size0(false, modes);
}
/** <inheritDoc /> */
public Task<int> GetSizeAsync(params CachePeekMode[] modes)
{
var modes0 = EncodePeekModes(modes);
return DoOutOpAsync<int>(CacheOp.SizeAsync, w => w.WriteInt(modes0));
}
/// <summary>
/// Internal size routine.
/// </summary>
/// <param name="loc">Local flag.</param>
/// <param name="modes">peek modes</param>
/// <returns>Size.</returns>
private int Size0(bool loc, params CachePeekMode[] modes)
{
var modes0 = EncodePeekModes(modes);
var op = loc ? CacheOp.SizeLoc : CacheOp.Size;
return (int) DoOutInOp((int) op, modes0);
}
/** <inheritdoc /> */
public TRes Invoke<TArg, TRes>(TK key, ICacheEntryProcessor<TK, TV, TArg, TRes> processor, TArg arg)
{
IgniteArgumentCheck.NotNull(key, "key");
IgniteArgumentCheck.NotNull(processor, "processor");
StartTx();
var holder = new CacheEntryProcessorHolder(processor, arg,
(e, a) => processor.Process((IMutableCacheEntry<TK, TV>)e, (TArg)a), typeof(TK), typeof(TV));
return DoOutInOpX((int) CacheOp.Invoke,
writer =>
{
writer.Write(key);
writer.Write(holder);
},
(input, res) => res == True ? Unmarshal<TRes>(input) : default(TRes),
_readException);
}
/** <inheritDoc /> */
public Task<TRes> InvokeAsync<TArg, TRes>(TK key, ICacheEntryProcessor<TK, TV, TArg, TRes> processor, TArg arg)
{
IgniteArgumentCheck.NotNull(key, "key");
IgniteArgumentCheck.NotNull(processor, "processor");
StartTx();
var holder = new CacheEntryProcessorHolder(processor, arg,
(e, a) => processor.Process((IMutableCacheEntry<TK, TV>)e, (TArg)a), typeof(TK), typeof(TV));
return DoOutOpAsync(CacheOp.InvokeAsync, writer =>
{
writer.Write(key);
writer.Write(holder);
},
r =>
{
if (r == null)
return default(TRes);
var hasError = r.ReadBoolean();
if (hasError)
throw ReadException(r);
return r.ReadObject<TRes>();
});
}
/** <inheritdoc /> */
public ICollection<ICacheEntryProcessorResult<TK, TRes>> InvokeAll<TArg, TRes>(IEnumerable<TK> keys,
ICacheEntryProcessor<TK, TV, TArg, TRes> processor, TArg arg)
{
IgniteArgumentCheck.NotNull(keys, "keys");
IgniteArgumentCheck.NotNull(processor, "processor");
StartTx();
var holder = new CacheEntryProcessorHolder(processor, arg,
(e, a) => processor.Process((IMutableCacheEntry<TK, TV>)e, (TArg)a), typeof(TK), typeof(TV));
return DoOutInOpX((int) CacheOp.InvokeAll,
writer =>
{
writer.WriteEnumerable(keys);
writer.Write(holder);
},
(input, res) => res == True
? ReadInvokeAllResults<TRes>(Marshaller.StartUnmarshal(input, IsKeepBinary))
: null, _readException);
}
/** <inheritDoc /> */
public Task<ICollection<ICacheEntryProcessorResult<TK, TRes>>> InvokeAllAsync<TArg, TRes>(IEnumerable<TK> keys,
ICacheEntryProcessor<TK, TV, TArg, TRes> processor, TArg arg)
{
IgniteArgumentCheck.NotNull(keys, "keys");
IgniteArgumentCheck.NotNull(processor, "processor");
StartTx();
var holder = new CacheEntryProcessorHolder(processor, arg,
(e, a) => processor.Process((IMutableCacheEntry<TK, TV>)e, (TArg)a), typeof(TK), typeof(TV));
return DoOutOpAsync(CacheOp.InvokeAllAsync,
writer =>
{
writer.WriteEnumerable(keys);
writer.Write(holder);
},
input => ReadInvokeAllResults<TRes>(input));
}
/** <inheritDoc /> */
public T DoOutInOpExtension<T>(int extensionId, int opCode, Action<IBinaryRawWriter> writeAction,
Func<IBinaryRawReader, T> readFunc)
{
return DoOutInOpX((int) CacheOp.Extension, writer =>
{
writer.WriteInt(extensionId);
writer.WriteInt(opCode);
writeAction(writer);
},
(input, res) => res == True
? readFunc(Marshaller.StartUnmarshal(input))
: default(T), _readException);
}
/** <inheritdoc /> */
public ICacheLock Lock(TK key)
{
IgniteArgumentCheck.NotNull(key, "key");
return DoOutInOpX((int) CacheOp.Lock, w => w.Write(key),
(stream, res) => new CacheLock(stream.ReadInt(), this), _readException);
}
/** <inheritdoc /> */
public ICacheLock LockAll(IEnumerable<TK> keys)
{
IgniteArgumentCheck.NotNull(keys, "keys");
return DoOutInOpX((int) CacheOp.LockAll, w => w.WriteEnumerable(keys),
(stream, res) => new CacheLock(stream.ReadInt(), this), _readException);
}
/** <inheritdoc /> */
public bool IsLocalLocked(TK key, bool byCurrentThread)
{
IgniteArgumentCheck.NotNull(key, "key");
return DoOutOp(CacheOp.IsLocalLocked, writer =>
{
writer.Write(key);
writer.WriteBoolean(byCurrentThread);
});
}
/** <inheritDoc /> */
public ICacheMetrics GetMetrics()
{
return DoInOp((int) CacheOp.GlobalMetrics, stream =>
{
IBinaryRawReader reader = Marshaller.StartUnmarshal(stream, false);
return new CacheMetricsImpl(reader);
});
}
/** <inheritDoc /> */
public ICacheMetrics GetMetrics(IClusterGroup clusterGroup)
{
IgniteArgumentCheck.NotNull(clusterGroup, "clusterGroup");
var prj = clusterGroup as ClusterGroupImpl;
if (prj == null)
throw new ArgumentException("Unexpected IClusterGroup implementation: " + clusterGroup.GetType());
return prj.GetCacheMetrics(Name);
}
/** <inheritDoc /> */
public ICacheMetrics GetLocalMetrics()
{
return DoInOp((int) CacheOp.LocalMetrics, stream =>
{
IBinaryRawReader reader = Marshaller.StartUnmarshal(stream, false);
return new CacheMetricsImpl(reader);
});
}
/** <inheritDoc /> */
public Task Rebalance()
{
return DoOutOpAsync(CacheOp.Rebalance);
}
/** <inheritDoc /> */
public ICache<TK, TV> WithNoRetries()
{
if (_flagNoRetries)
return this;
return new CacheImpl<TK, TV>(DoOutOpObject((int) CacheOp.WithNoRetries),
_flagSkipStore, _flagKeepBinary, true, _flagPartitionRecover);
}
/** <inheritDoc /> */
public ICache<TK, TV> WithPartitionRecover()
{
if (_flagPartitionRecover)
return this;
return new CacheImpl<TK, TV>(DoOutOpObject((int) CacheOp.WithPartitionRecover),
_flagSkipStore, _flagKeepBinary, _flagNoRetries, true);
}
/** <inheritDoc /> */
public ICollection<int> GetLostPartitions()
{
return DoInOp((int) CacheOp.GetLostPartitions, s =>
{
var cnt = s.ReadInt();
var res = new List<int>(cnt);
if (cnt > 0)
{
for (var i = 0; i < cnt; i++)
{
res.Add(s.ReadInt());
}
}
return res;
});
}
#region Queries
/** <inheritDoc /> */
public IQueryCursor<IList> QueryFields(SqlFieldsQuery qry)
{
return QueryFields(qry, ReadFieldsArrayList);
}
/// <summary>
/// Reads the fields array list.
/// </summary>
private static IList ReadFieldsArrayList(IBinaryRawReader reader, int count)
{
IList res = new ArrayList(count);
for (var i = 0; i < count; i++)
res.Add(reader.ReadObject<object>());
return res;
}
/** <inheritDoc /> */
public IQueryCursor<T> QueryFields<T>(SqlFieldsQuery qry, Func<IBinaryRawReader, int, T> readerFunc)
{
IgniteArgumentCheck.NotNull(qry, "qry");
IgniteArgumentCheck.NotNull(readerFunc, "readerFunc");
if (string.IsNullOrEmpty(qry.Sql))
throw new ArgumentException("Sql cannot be null or empty");
var cursor = DoOutOpObject((int) CacheOp.QrySqlFields, writer =>
{
writer.WriteBoolean(qry.Local);
writer.WriteString(qry.Sql);
writer.WriteInt(qry.PageSize);
QueryBase.WriteQueryArgs(writer, qry.Arguments);
writer.WriteBoolean(qry.EnableDistributedJoins);
writer.WriteBoolean(qry.EnforceJoinOrder);
writer.WriteBoolean(false); // Lazy flag.
writer.WriteInt((int) qry.Timeout.TotalMilliseconds);
writer.WriteBoolean(qry.ReplicatedOnly);
writer.WriteBoolean(qry.Colocated);
writer.WriteString(qry.Schema); // Schema
});
return new FieldsQueryCursor<T>(cursor, _flagKeepBinary, readerFunc);
}
/** <inheritDoc /> */
public IQueryCursor<ICacheEntry<TK, TV>> Query(QueryBase qry)
{
IgniteArgumentCheck.NotNull(qry, "qry");
var cursor = DoOutOpObject((int) qry.OpId, writer => qry.Write(writer, IsKeepBinary));
return new QueryCursor<TK, TV>(cursor, _flagKeepBinary);
}
/** <inheritdoc /> */
public IContinuousQueryHandle QueryContinuous(ContinuousQuery<TK, TV> qry)
{
IgniteArgumentCheck.NotNull(qry, "qry");
return QueryContinuousImpl(qry, null);
}
/** <inheritdoc /> */
public IContinuousQueryHandle<ICacheEntry<TK, TV>> QueryContinuous(ContinuousQuery<TK, TV> qry, QueryBase initialQry)
{
IgniteArgumentCheck.NotNull(qry, "qry");
IgniteArgumentCheck.NotNull(initialQry, "initialQry");
return QueryContinuousImpl(qry, initialQry);
}
/// <summary>
/// QueryContinuous implementation.
/// </summary>
private IContinuousQueryHandle<ICacheEntry<TK, TV>> QueryContinuousImpl(ContinuousQuery<TK, TV> qry,
QueryBase initialQry)
{
qry.Validate();
return new ContinuousQueryHandleImpl<TK, TV>(qry, Marshaller, _flagKeepBinary,
writeAction => DoOutOpObject((int) CacheOp.QryContinuous, writeAction), initialQry);
}
#endregion
#region Enumerable support
/** <inheritdoc /> */
public IEnumerable<ICacheEntry<TK, TV>> GetLocalEntries(CachePeekMode[] peekModes)
{
return new CacheEnumerable<TK, TV>(this, EncodePeekModes(peekModes));
}
/** <inheritdoc /> */
public IEnumerator<ICacheEntry<TK, TV>> GetEnumerator()
{
return new CacheEnumeratorProxy<TK, TV>(this, false, 0);
}
/** <inheritdoc /> */
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
/// <summary>
/// Create real cache enumerator.
/// </summary>
/// <param name="loc">Local flag.</param>
/// <param name="peekModes">Peek modes for local enumerator.</param>
/// <returns>Cache enumerator.</returns>
internal CacheEnumerator<TK, TV> CreateEnumerator(bool loc, int peekModes)
{
if (loc)
{
var target = DoOutOpObject((int) CacheOp.LocIterator, (IBinaryStream s) => s.WriteInt(peekModes));
return new CacheEnumerator<TK, TV>(target, _flagKeepBinary);
}
return new CacheEnumerator<TK, TV>(DoOutOpObject((int) CacheOp.Iterator), _flagKeepBinary);
}
#endregion
/** <inheritDoc /> */
protected override T Unmarshal<T>(IBinaryStream stream)
{
return Marshaller.Unmarshal<T>(stream, _flagKeepBinary);
}
/// <summary>
/// Encodes the peek modes into a single int value.
/// </summary>
private static int EncodePeekModes(CachePeekMode[] modes)
{
int modesEncoded = 0;
if (modes != null)
{
foreach (var mode in modes)
modesEncoded |= (int) mode;
}
return modesEncoded;
}
/// <summary>
/// Reads results of InvokeAll operation.
/// </summary>
/// <typeparam name="T">The type of the result.</typeparam>
/// <param name="reader">Stream.</param>
/// <returns>Results of InvokeAll operation.</returns>
private ICollection<ICacheEntryProcessorResult<TK, T>> ReadInvokeAllResults<T>(BinaryReader reader)
{
var count = reader.ReadInt();
if (count == -1)
return null;
var results = new List<ICacheEntryProcessorResult<TK, T>>(count);
for (var i = 0; i < count; i++)
{
var key = reader.ReadObject<TK>();
var hasError = reader.ReadBoolean();
results.Add(hasError
? new CacheEntryProcessorResult<TK, T>(key, ReadException(reader))
: new CacheEntryProcessorResult<TK, T>(key, reader.ReadObject<T>()));
}
return results;
}
/// <summary>
/// Reads the exception, either in binary wrapper form, or as a pair of strings.
/// </summary>
/// <param name="reader">The stream.</param>
/// <returns>Exception.</returns>
private Exception ReadException(BinaryReader reader)
{
var item = reader.ReadObject<object>();
var clsName = item as string;
if (clsName == null)
return new CacheEntryProcessorException((Exception) item);
var msg = reader.ReadObject<string>();
var trace = reader.ReadObject<string>();
var inner = reader.ReadBoolean() ? reader.ReadObject<Exception>() : null;
return ExceptionUtils.GetException(_ignite, clsName, msg, trace, reader, inner);
}
/// <summary>
/// Read dictionary returned by GET_ALL operation.
/// </summary>
/// <param name="reader">Reader.</param>
/// <returns>Dictionary.</returns>
private static ICollection<ICacheEntry<TK, TV>> ReadGetAllDictionary(BinaryReader reader)
{
if (reader == null)
return null;
IBinaryStream stream = reader.Stream;
if (stream.ReadBool())
{
int size = stream.ReadInt();
var res = new List<ICacheEntry<TK, TV>>(size);
for (int i = 0; i < size; i++)
{
TK key = reader.ReadObject<TK>();
TV val = reader.ReadObject<TV>();
res.Add(new CacheEntry<TK, TV>(key, val));
}
return res;
}
return null;
}
/// <summary>
/// Gets the cache result.
/// </summary>
private static CacheResult<TV> GetCacheResult(BinaryReader reader)
{
var res = reader == null
? new CacheResult<TV>()
: new CacheResult<TV>(reader.ReadObject<TV>());
return res;
}
/// <summary>
/// Throws the key not found exception.
/// </summary>
private static KeyNotFoundException GetKeyNotFoundException()
{
return new KeyNotFoundException("The given key was not present in the cache.");
}
/// <summary>
/// Does the out op.
/// </summary>
private bool DoOutOp<T1>(CacheOp op, T1 x)
{
return DoOutInOpX((int) op, w =>
{
w.Write(x);
}, _readException);
}
/// <summary>
/// Does the out op.
/// </summary>
private bool DoOutOp<T1, T2>(CacheOp op, T1 x, T2 y)
{
return DoOutInOpX((int) op, w =>
{
w.Write(x);
w.Write(y);
}, _readException);
}
/// <summary>
/// Does the out op.
/// </summary>
private bool DoOutOp<T1, T2, T3>(CacheOp op, T1 x, T2 y, T3 z)
{
return DoOutInOpX((int) op, w =>
{
w.Write(x);
w.Write(y);
w.Write(z);
}, _readException);
}
/// <summary>
/// Does the out op.
/// </summary>
private bool DoOutOp(CacheOp op, Action<BinaryWriter> write)
{
return DoOutInOpX((int) op, write, _readException);
}
/// <summary>
/// Does the out-in op.
/// </summary>
private CacheResult<TV> DoOutInOpNullable(CacheOp cacheOp, TK x)
{
return DoOutInOpX((int)cacheOp,
w => w.Write(x),
(stream, res) => res == True ? new CacheResult<TV>(Unmarshal<TV>(stream)) : new CacheResult<TV>(),
_readException);
}
/// <summary>
/// Does the out-in op.
/// </summary>
private CacheResult<TV> DoOutInOpNullable<T1, T2>(CacheOp cacheOp, T1 x, T2 y)
{
return DoOutInOpX((int)cacheOp,
w =>
{
w.Write(x);
w.Write(y);
},
(stream, res) => res == True ? new CacheResult<TV>(Unmarshal<TV>(stream)) : new CacheResult<TV>(),
_readException);
}
/** <inheritdoc /> */
public void Enter(long id)
{
DoOutInOp((int) CacheOp.EnterLock, id);
}
/** <inheritdoc /> */
public bool TryEnter(long id, TimeSpan timeout)
{
return DoOutOp((int) CacheOp.TryEnterLock, (IBinaryStream s) =>
{
s.WriteLong(id);
s.WriteLong((long) timeout.TotalMilliseconds);
}) == True;
}
/** <inheritdoc /> */
public void Exit(long id)
{
DoOutInOp((int) CacheOp.ExitLock, id);
}
/** <inheritdoc /> */
public void Close(long id)
{
DoOutInOp((int) CacheOp.CloseLock, id);
}
/// <summary>
/// Starts a transaction when applicable.
/// </summary>
private void StartTx()
{
if (_txManager != null)
_txManager.StartTx();
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.IO;
using System.Runtime.Serialization;
using System.Text;
using System.Reflection;
using Xunit;
using System.Linq;
using System.Diagnostics;
using Validation;
namespace System.Collections.Immutable.Test
{
public abstract class ImmutablesTestBase
{
/// <summary>
/// Gets the number of operations to perform in randomized tests.
/// </summary>
protected int RandomOperationsCount
{
get { return 100; }
}
internal static void AssertAreSame<T>(T expected, T actual, string message = null, params object[] formattingArgs)
{
if (typeof(T).GetTypeInfo().IsValueType)
{
Assert.Equal(expected, actual); //, message, formattingArgs);
}
else
{
Assert.Same(expected, actual); //, message, formattingArgs);
}
}
internal static void CollectionAssertAreEquivalent<T>(ICollection<T> expected, ICollection<T> actual)
{
Assert.Equal(expected.Count, actual.Count);
foreach (var value in expected)
{
Assert.Contains(value, actual);
}
}
protected static string ToString(System.Collections.IEnumerable sequence)
{
var sb = new StringBuilder();
sb.Append('{');
int count = 0;
foreach (object item in sequence)
{
if (count > 0)
{
sb.Append(',');
}
if (count == 10)
{
sb.Append("...");
break;
}
sb.Append(item);
count++;
}
sb.Append('}');
return sb.ToString();
}
protected static object ToStringDeferred(System.Collections.IEnumerable sequence)
{
return new DeferredToString(() => ToString(sequence));
}
protected static void ManuallyEnumerateTest<T>(IList<T> expectedResults, IEnumerator<T> enumerator)
{
T[] manualArray = new T[expectedResults.Count];
int i = 0;
Assert.Throws<InvalidOperationException>(() => enumerator.Current);
while (enumerator.MoveNext())
{
manualArray[i++] = enumerator.Current;
}
enumerator.MoveNext();
Assert.Throws<InvalidOperationException>(() => enumerator.Current);
enumerator.MoveNext();
Assert.Throws<InvalidOperationException>(() => enumerator.Current);
Assert.Equal(expectedResults.Count, i); //, "Enumeration did not produce enough elements.");
Assert.Equal<T>(expectedResults, manualArray);
}
/// <summary>
/// Generates an array of unique values.
/// </summary>
/// <param name="length">The desired length of the array.</param>
/// <returns>An array of doubles.</returns>
protected double[] GenerateDummyFillData(int length = 1000)
{
Contract.Requires(length >= 0);
Contract.Ensures(Contract.Result<double[]>() != null);
Contract.Ensures(Contract.Result<double[]>().Length == length);
int seed = unchecked((int)DateTime.Now.Ticks);
Console.WriteLine("Random seed {0}", seed);
var random = new Random(seed);
var inputs = new double[length];
var ensureUniqueness = new HashSet<double>();
for (int i = 0; i < inputs.Length; i++)
{
double input;
do
{
input = random.NextDouble();
}
while (!ensureUniqueness.Add(input));
inputs[i] = input;
}
return inputs;
}
/// <summary>
/// Tests the EqualsStructurally public method and the IStructrualEquatable.Equals method.
/// </summary>
/// <typeparam name="TCollection">The type of tested collection.</typeparam>
/// <typeparam name="TElement">The type of element stored in the collection.</typeparam>
/// <param name="objectUnderTest">An instance of the collection to test, which must have at least two elements.</param>
/// <param name="additionalItem">A unique item that does not already exist in <paramref name="objectUnderTest" />.</param>
/// <param name="equalsStructurally">A delegate that invokes the EqualsStructurally method.</param>
protected static void StructuralEqualityHelper<TCollection, TElement>(TCollection objectUnderTest, TElement additionalItem, Func<TCollection, IEnumerable<TElement>, bool> equalsStructurally)
where TCollection : class, IEnumerable<TElement>
{
Requires.NotNull(objectUnderTest, "objectUnderTest");
Requires.Argument(objectUnderTest.Count() >= 2, "objectUnderTest", "Collection must contain at least two elements.");
Requires.NotNull(equalsStructurally, "equalsStructurally");
var structuralEquatableUnderTest = objectUnderTest as IStructuralEquatable;
var enumerableUnderTest = (IEnumerable<TElement>)objectUnderTest;
var equivalentSequence = objectUnderTest.ToList();
var shorterSequence = equivalentSequence.Take(equivalentSequence.Count() - 1);
var longerSequence = equivalentSequence.Concat(new[] { additionalItem });
var differentSequence = shorterSequence.Concat(new[] { additionalItem });
var nonUniqueSubsetSequenceOfSameLength = shorterSequence.Concat(shorterSequence.Take(1));
var testValues = new IEnumerable<TElement>[] {
objectUnderTest,
null,
Enumerable.Empty<TElement>(),
equivalentSequence,
longerSequence,
shorterSequence,
nonUniqueSubsetSequenceOfSameLength,
};
foreach (var value in testValues)
{
bool expectedResult = value != null && Enumerable.SequenceEqual(objectUnderTest, value);
if (structuralEquatableUnderTest != null)
{
Assert.Equal(expectedResult, structuralEquatableUnderTest.Equals(value, null));
if (value != null)
{
Assert.Equal(
expectedResult,
structuralEquatableUnderTest.Equals(new NonGenericEnumerableWrapper(value), null));
}
}
Assert.Equal(expectedResult, equalsStructurally(objectUnderTest, value));
}
}
private class DeferredToString
{
private readonly Func<string> generator;
internal DeferredToString(Func<string> generator)
{
Contract.Requires(generator != null);
this.generator = generator;
}
public override string ToString()
{
return this.generator();
}
}
private class NonGenericEnumerableWrapper : IEnumerable
{
private readonly IEnumerable enumerable;
internal NonGenericEnumerableWrapper(IEnumerable enumerable)
{
Requires.NotNull(enumerable, "enumerable");
this.enumerable = enumerable;
}
public IEnumerator GetEnumerator()
{
return this.enumerable.GetEnumerator();
}
}
}
}
| |
using System;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Data.Common;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Xml;
using System.Xml.Serialization;
using SubSonic;
using SubSonic.Utilities;
namespace DalSic
{
/// <summary>
/// Strongly-typed collection for the ConMotivosDeBloqueo class.
/// </summary>
[Serializable]
public partial class ConMotivosDeBloqueoCollection : ActiveList<ConMotivosDeBloqueo, ConMotivosDeBloqueoCollection>
{
public ConMotivosDeBloqueoCollection() {}
/// <summary>
/// Filters an existing collection based on the set criteria. This is an in-memory filter
/// Thanks to developingchris for this!
/// </summary>
/// <returns>ConMotivosDeBloqueoCollection</returns>
public ConMotivosDeBloqueoCollection Filter()
{
for (int i = this.Count - 1; i > -1; i--)
{
ConMotivosDeBloqueo o = this[i];
foreach (SubSonic.Where w in this.wheres)
{
bool remove = false;
System.Reflection.PropertyInfo pi = o.GetType().GetProperty(w.ColumnName);
if (pi.CanRead)
{
object val = pi.GetValue(o, null);
switch (w.Comparison)
{
case SubSonic.Comparison.Equals:
if (!val.Equals(w.ParameterValue))
{
remove = true;
}
break;
}
}
if (remove)
{
this.Remove(o);
break;
}
}
}
return this;
}
}
/// <summary>
/// This is an ActiveRecord class which wraps the CON_MotivosDeBloqueo table.
/// </summary>
[Serializable]
public partial class ConMotivosDeBloqueo : ActiveRecord<ConMotivosDeBloqueo>, IActiveRecord
{
#region .ctors and Default Settings
public ConMotivosDeBloqueo()
{
SetSQLProps();
InitSetDefaults();
MarkNew();
}
private void InitSetDefaults() { SetDefaults(); }
public ConMotivosDeBloqueo(bool useDatabaseDefaults)
{
SetSQLProps();
if(useDatabaseDefaults)
ForceDefaults();
MarkNew();
}
public ConMotivosDeBloqueo(object keyID)
{
SetSQLProps();
InitSetDefaults();
LoadByKey(keyID);
}
public ConMotivosDeBloqueo(string columnName, object columnValue)
{
SetSQLProps();
InitSetDefaults();
LoadByParam(columnName,columnValue);
}
protected static void SetSQLProps() { GetTableSchema(); }
#endregion
#region Schema and Query Accessor
public static Query CreateQuery() { return new Query(Schema); }
public static TableSchema.Table Schema
{
get
{
if (BaseSchema == null)
SetSQLProps();
return BaseSchema;
}
}
private static void GetTableSchema()
{
if(!IsSchemaInitialized)
{
//Schema declaration
TableSchema.Table schema = new TableSchema.Table("CON_MotivosDeBloqueo", TableType.Table, DataService.GetInstance("sicProvider"));
schema.Columns = new TableSchema.TableColumnCollection();
schema.SchemaName = @"dbo";
//columns
TableSchema.TableColumn colvarIdMotivoBloqueo = new TableSchema.TableColumn(schema);
colvarIdMotivoBloqueo.ColumnName = "idMotivoBloqueo";
colvarIdMotivoBloqueo.DataType = DbType.Int32;
colvarIdMotivoBloqueo.MaxLength = 0;
colvarIdMotivoBloqueo.AutoIncrement = true;
colvarIdMotivoBloqueo.IsNullable = false;
colvarIdMotivoBloqueo.IsPrimaryKey = true;
colvarIdMotivoBloqueo.IsForeignKey = false;
colvarIdMotivoBloqueo.IsReadOnly = false;
colvarIdMotivoBloqueo.DefaultSetting = @"";
colvarIdMotivoBloqueo.ForeignKeyTableName = "";
schema.Columns.Add(colvarIdMotivoBloqueo);
TableSchema.TableColumn colvarDescripcion = new TableSchema.TableColumn(schema);
colvarDescripcion.ColumnName = "descripcion";
colvarDescripcion.DataType = DbType.String;
colvarDescripcion.MaxLength = 40;
colvarDescripcion.AutoIncrement = false;
colvarDescripcion.IsNullable = true;
colvarDescripcion.IsPrimaryKey = false;
colvarDescripcion.IsForeignKey = false;
colvarDescripcion.IsReadOnly = false;
colvarDescripcion.DefaultSetting = @"";
colvarDescripcion.ForeignKeyTableName = "";
schema.Columns.Add(colvarDescripcion);
BaseSchema = schema;
//add this schema to the provider
//so we can query it later
DataService.Providers["sicProvider"].AddSchema("CON_MotivosDeBloqueo",schema);
}
}
#endregion
#region Props
[XmlAttribute("IdMotivoBloqueo")]
[Bindable(true)]
public int IdMotivoBloqueo
{
get { return GetColumnValue<int>(Columns.IdMotivoBloqueo); }
set { SetColumnValue(Columns.IdMotivoBloqueo, value); }
}
[XmlAttribute("Descripcion")]
[Bindable(true)]
public string Descripcion
{
get { return GetColumnValue<string>(Columns.Descripcion); }
set { SetColumnValue(Columns.Descripcion, value); }
}
#endregion
#region PrimaryKey Methods
protected override void SetPrimaryKey(object oValue)
{
base.SetPrimaryKey(oValue);
SetPKValues();
}
private DalSic.ConTurnoBloqueoCollection colConTurnoBloqueoRecords;
public DalSic.ConTurnoBloqueoCollection ConTurnoBloqueoRecords
{
get
{
if(colConTurnoBloqueoRecords == null)
{
colConTurnoBloqueoRecords = new DalSic.ConTurnoBloqueoCollection().Where(ConTurnoBloqueo.Columns.IdMotivoBloqueo, IdMotivoBloqueo).Load();
colConTurnoBloqueoRecords.ListChanged += new ListChangedEventHandler(colConTurnoBloqueoRecords_ListChanged);
}
return colConTurnoBloqueoRecords;
}
set
{
colConTurnoBloqueoRecords = value;
colConTurnoBloqueoRecords.ListChanged += new ListChangedEventHandler(colConTurnoBloqueoRecords_ListChanged);
}
}
void colConTurnoBloqueoRecords_ListChanged(object sender, ListChangedEventArgs e)
{
if (e.ListChangedType == ListChangedType.ItemAdded)
{
// Set foreign key value
colConTurnoBloqueoRecords[e.NewIndex].IdMotivoBloqueo = IdMotivoBloqueo;
}
}
#endregion
//no foreign key tables defined (0)
//no ManyToMany tables defined (0)
#region ObjectDataSource support
/// <summary>
/// Inserts a record, can be used with the Object Data Source
/// </summary>
public static void Insert(string varDescripcion)
{
ConMotivosDeBloqueo item = new ConMotivosDeBloqueo();
item.Descripcion = varDescripcion;
if (System.Web.HttpContext.Current != null)
item.Save(System.Web.HttpContext.Current.User.Identity.Name);
else
item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name);
}
/// <summary>
/// Updates a record, can be used with the Object Data Source
/// </summary>
public static void Update(int varIdMotivoBloqueo,string varDescripcion)
{
ConMotivosDeBloqueo item = new ConMotivosDeBloqueo();
item.IdMotivoBloqueo = varIdMotivoBloqueo;
item.Descripcion = varDescripcion;
item.IsNew = false;
if (System.Web.HttpContext.Current != null)
item.Save(System.Web.HttpContext.Current.User.Identity.Name);
else
item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name);
}
#endregion
#region Typed Columns
public static TableSchema.TableColumn IdMotivoBloqueoColumn
{
get { return Schema.Columns[0]; }
}
public static TableSchema.TableColumn DescripcionColumn
{
get { return Schema.Columns[1]; }
}
#endregion
#region Columns Struct
public struct Columns
{
public static string IdMotivoBloqueo = @"idMotivoBloqueo";
public static string Descripcion = @"descripcion";
}
#endregion
#region Update PK Collections
public void SetPKValues()
{
if (colConTurnoBloqueoRecords != null)
{
foreach (DalSic.ConTurnoBloqueo item in colConTurnoBloqueoRecords)
{
if (item.IdMotivoBloqueo != IdMotivoBloqueo)
{
item.IdMotivoBloqueo = IdMotivoBloqueo;
}
}
}
}
#endregion
#region Deep Save
public void DeepSave()
{
Save();
if (colConTurnoBloqueoRecords != null)
{
colConTurnoBloqueoRecords.SaveAll();
}
}
#endregion
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Globalization;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Testing;
using Xunit;
using VerifyCS = Test.Utilities.CSharpSecurityCodeFixVerifier<
Microsoft.NetFramework.CSharp.Analyzers.CSharpDoNotUseInsecureDtdProcessingInApiDesignAnalyzer,
Microsoft.CodeAnalysis.Testing.EmptyCodeFixProvider>;
using VerifyVB = Test.Utilities.VisualBasicSecurityCodeFixVerifier<
Microsoft.NetFramework.VisualBasic.Analyzers.BasicDoNotUseInsecureDtdProcessingInApiDesignAnalyzer,
Microsoft.CodeAnalysis.Testing.EmptyCodeFixProvider>;
namespace Microsoft.NetFramework.Analyzers.UnitTests
{
public partial class DoNotUseInsecureDtdProcessingInApiDesignAnalyzerTests
{
private static DiagnosticResult GetCA3077ConstructorCSharpResultAt(int line, int column, string name)
=> VerifyCS.Diagnostic().WithLocation(line, column).WithArguments(string.Format(CultureInfo.CurrentCulture, MicrosoftNetFrameworkAnalyzersResources.XmlDocumentDerivedClassConstructorNoSecureXmlResolverMessage, name));
private static DiagnosticResult GetCA3077ConstructorBasicResultAt(int line, int column, string name)
=> VerifyVB.Diagnostic().WithLocation(line, column).WithArguments(string.Format(CultureInfo.CurrentCulture, MicrosoftNetFrameworkAnalyzersResources.XmlDocumentDerivedClassConstructorNoSecureXmlResolverMessage, name));
[Fact]
public async Task XmlDocumentDerivedTypeWithEmptyConstructorShouldGenerateDiagnostic()
{
await VerifyCSharpAnalyzerAsync(@"
using System;
using System.Xml;
namespace TestNamespace
{
class TestClass : XmlDocument
{
public TestClass () {}
}
}",
GetCA3077ConstructorCSharpResultAt(9, 16, "TestClass")
);
await VerifyVisualBasicAnalyzerAsync(@"
Imports System.Xml
Namespace TestNamespace
Class TestClass
Inherits XmlDocument
Public Sub New()
End Sub
End Class
End Namespace",
GetCA3077ConstructorBasicResultAt(7, 20, "TestClass")
);
}
[Fact]
public async Task XmlDocumentDerivedTypeSetResolverToNullInOnlyCtorShouldNotGenerateDiagnostic()
{
await VerifyCSharpAnalyzerAsync(@"
using System;
using System.Xml;
namespace TestNamespace
{
class TestClass : XmlDocument
{
public TestClass()
{
this.XmlResolver = null;
}
}
}"
);
await VerifyVisualBasicAnalyzerAsync(@"
Imports System.Xml
Namespace TestNamespace
Class TestClass
Inherits XmlDocument
Public Sub New()
Me.XmlResolver = Nothing
End Sub
End Class
End Namespace");
}
[Fact]
public async Task XmlDocumentDerivedTypeSetInsecureResolverInOnlyCtorShouldGenerateDiagnostic()
{
await VerifyCSharpAnalyzerAsync(@"
using System;
using System.Xml;
namespace TestNamespace
{
class TestClass : XmlDocument
{
public TestClass(XmlResolver resolver)
{
this.XmlResolver = resolver;
}
}
}",
GetCA3077ConstructorCSharpResultAt(9, 16, "TestClass")
);
await VerifyVisualBasicAnalyzerAsync(@"
Imports System.Xml
Namespace TestNamespace
Class TestClass
Inherits XmlDocument
Public Sub New(resolver As XmlResolver)
Me.XmlResolver = resolver
End Sub
End Class
End Namespace",
GetCA3077ConstructorBasicResultAt(7, 20, "TestClass")
);
}
[Fact]
public async Task XmlDocumentDerivedTypeSetInsecureResolverInCtorShouldGenerateDiagnostic()
{
await VerifyCSharpAnalyzerAsync(@"
using System;
using System.Xml;
namespace TestNamespace
{
class TestClass : XmlDocument
{
public TestClass()
{
this.XmlResolver = null;
}
public TestClass(XmlResolver resolver)
{
this.XmlResolver = resolver;
}
}
}",
GetCA3077ConstructorCSharpResultAt(14, 16, "TestClass")
);
await VerifyVisualBasicAnalyzerAsync(@"
Imports System.Xml
Namespace TestNamespace
Class TestClass
Inherits XmlDocument
Public Sub New()
Me.XmlResolver = Nothing
End Sub
Public Sub New(resolver As XmlResolver)
Me.XmlResolver = resolver
End Sub
End Class
End Namespace",
GetCA3077ConstructorBasicResultAt(11, 20, "TestClass")
);
}
[Fact]
public async Task XmlDocumentDerivedTypeSetSecureResolverForVariableInCtorShouldGenerateDiagnostic()
{
await VerifyCSharpAnalyzerAsync(@"
using System;
using System.Xml;
namespace TestNamespace
{
class TestClass : XmlDocument
{
public TestClass(XmlDocument doc)
{
doc.XmlResolver = null;
}
}
}",
GetCA3077ConstructorCSharpResultAt(9, 16, "TestClass")
);
await VerifyVisualBasicAnalyzerAsync(@"
Imports System.Xml
Namespace TestNamespace
Class TestClass
Inherits XmlDocument
Public Sub New(doc As XmlDocument)
doc.XmlResolver = Nothing
End Sub
End Class
End Namespace",
GetCA3077ConstructorBasicResultAt(7, 20, "TestClass")
);
}
[Fact]
public async Task XmlDocumentDerivedTypeSetSecureResolverWithOutThisInCtorShouldNotGenerateDiagnostic()
{
await VerifyCSharpAnalyzerAsync(@"
using System;
using System.Xml;
namespace TestNamespace
{
class TestClass : XmlDocument
{
public TestClass(XmlDocument doc)
{
doc.XmlResolver = null;
XmlResolver = null;
}
}
}"
);
await VerifyVisualBasicAnalyzerAsync(@"
Imports System.Xml
Namespace TestNamespace
Class TestClass
Inherits XmlDocument
Public Sub New(doc As XmlDocument)
doc.XmlResolver = Nothing
XmlResolver = Nothing
End Sub
End Class
End Namespace");
}
[Fact]
public async Task XmlDocumentDerivedTypeSetSecureResolverToAXmlDocumentFieldInCtorShouldGenerateDiagnostic()
{
await VerifyCSharpAnalyzerAsync(@"
using System;
using System.Xml;
namespace TestNamespace
{
class TestClass : XmlDocument
{
private XmlDocument doc = new XmlDocument();
public TestClass(XmlDocument doc)
{
this.doc.XmlResolver = null;
}
}
}",
GetCA3077ConstructorCSharpResultAt(10, 16, "TestClass")
);
await VerifyVisualBasicAnalyzerAsync(@"
Imports System.Xml
Namespace TestNamespace
Class TestClass
Inherits XmlDocument
Private doc As New XmlDocument()
Public Sub New(doc As XmlDocument)
Me.doc.XmlResolver = Nothing
End Sub
End Class
End Namespace",
GetCA3077ConstructorBasicResultAt(8, 20, "TestClass")
);
}
[Fact]
public async Task XmlDocumentDerivedTypeSetSecureResolverAtLeastOnceInCtorShouldNotGenerateDiagnostic()
{
await VerifyCSharpAnalyzerAsync(@"
using System;
using System.Xml;
namespace TestNamespace
{
class TestClass : XmlDocument
{
public TestClass(bool flag)
{
if (flag)
{
XmlResolver = null;
}
else
{
XmlResolver = new XmlUrlResolver();
}
}
}
}"
);
await VerifyVisualBasicAnalyzerAsync(@"
Imports System.Xml
Namespace TestNamespace
Class TestClass
Inherits XmlDocument
Public Sub New(flag As Boolean)
If flag Then
XmlResolver = Nothing
Else
XmlResolver = New XmlUrlResolver()
End If
End Sub
End Class
End Namespace");
}
[Fact]
public async Task XmlDocumentDerivedTypeSetNullToHidingFieldInCtorShouldGenerateDiagnostic()
{
await VerifyCSharpAnalyzerAsync(@"
using System;
using System.Xml;
namespace TestNamespace
{
class TestClass : XmlDocument
{
XmlResolver XmlResolver;
public TestClass()
{
this.XmlResolver = null;
}
}
}",
GetCA3077ConstructorCSharpResultAt(10, 16, "TestClass")
);
await VerifyVisualBasicAnalyzerAsync(@"
Imports System.Xml
Namespace TestNamespace
Class TestClass
Inherits XmlDocument
Private XmlResolver As XmlResolver
Public Sub New()
Me.XmlResolver = Nothing
End Sub
End Class
End Namespace",
GetCA3077ConstructorBasicResultAt(8, 20, "TestClass")
);
}
[Fact]
public async Task XmlDocumentDerivedTypeSetNullToBaseXmlResolverInCtorShouldNotGenerateDiagnostic()
{
await VerifyCSharpAnalyzerAsync(@"
using System;
using System.Xml;
namespace TestNamespace
{
class TestClass : XmlDocument
{
XmlResolver XmlResolver;
public TestClass()
{
base.XmlResolver = null;
}
}
}"
);
await VerifyVisualBasicAnalyzerAsync(@"
Imports System.Xml
Namespace TestNamespace
Class TestClass
Inherits XmlDocument
Private XmlResolver As XmlResolver
Public Sub New()
MyBase.XmlResolver = Nothing
End Sub
End Class
End Namespace");
}
[Fact]
public async Task XmlDocumentDerivedTypeSetUrlResolverToBaseXmlResolverInCtorShouldGenerateDiagnostic()
{
await VerifyCSharpAnalyzerAsync(@"
using System;
using System.Xml;
namespace TestNamespace
{
class TestClass : XmlDocument
{
private XmlResolver XmlResolver;
public TestClass()
{
base.XmlResolver = new XmlUrlResolver();
}
}
}",
GetCA3077ConstructorCSharpResultAt(10, 16, "TestClass")
);
await VerifyVisualBasicAnalyzerAsync(@"
Imports System.Xml
Namespace TestNamespace
Class TestClass
Inherits XmlDocument
Private XmlResolver As XmlResolver
Public Sub New()
MyBase.XmlResolver = New XmlUrlResolver()
End Sub
End Class
End Namespace",
GetCA3077ConstructorBasicResultAt(8, 20, "TestClass")
);
}
[Fact]
public async Task XmlDocumentDerivedTypeSetNullToHidingPropertyInCtorShouldGenerateDiagnostic()
{
await VerifyCSharpAnalyzerAsync(@"
using System;
using System.Xml;
namespace TestNamespace
{
class TestClass : XmlDocument
{
XmlResolver XmlResolver { set; get; }
public TestClass()
{
this.XmlResolver = null;
}
}
}",
GetCA3077ConstructorCSharpResultAt(11, 16, "TestClass")
);
await VerifyVisualBasicAnalyzerAsync(@"
Imports System.Xml
Namespace TestNamespace
Class TestClass
Inherits XmlDocument
Private Property XmlResolver() As XmlResolver
Get
Return m_XmlResolver
End Get
Set
m_XmlResolver = Value
End Set
End Property
Private m_XmlResolver As XmlResolver
Public Sub New()
Me.XmlResolver = Nothing
End Sub
End Class
End Namespace",
GetCA3077ConstructorBasicResultAt(17, 20, "TestClass")
);
}
[Fact]
public async Task XmlDocumentDerivedTypeSetNullToBaseWithHidingPropertyInCtorShouldNotGenerateDiagnostic()
{
await VerifyCSharpAnalyzerAsync(@"
using System;
using System.Xml;
namespace TestNamespace
{
class TestClass : XmlDocument
{
XmlResolver XmlResolver { set; get; }
public TestClass()
{
base.XmlResolver = null;
}
}
}"
);
await VerifyVisualBasicAnalyzerAsync(@"
Imports System.Xml
Namespace TestNamespace
Class TestClass
Inherits XmlDocument
Private Property XmlResolver() As XmlResolver
Get
Return m_XmlResolver
End Get
Set
m_XmlResolver = Value
End Set
End Property
Private m_XmlResolver As XmlResolver
Public Sub New()
MyBase.XmlResolver = Nothing
End Sub
End Class
End Namespace");
}
[Fact]
public async Task XmlDocumentDerivedTypeSetUrlResolverToBaseWithHidingPropertyInCtorShouldGenerateDiagnostic()
{
await VerifyCSharpAnalyzerAsync(@"
using System;
using System.Xml;
namespace TestNamespace
{
class TestClass : XmlDocument
{
XmlResolver XmlResolver { set; get; }
public TestClass()
{
base.XmlResolver = new XmlUrlResolver();
}
}
}",
GetCA3077ConstructorCSharpResultAt(11, 16, "TestClass")
);
await VerifyVisualBasicAnalyzerAsync(@"
Imports System.Xml
Namespace TestNamespace
Class TestClass
Inherits XmlDocument
Private Property XmlResolver() As XmlResolver
Get
Return m_XmlResolver
End Get
Set
m_XmlResolver = Value
End Set
End Property
Private m_XmlResolver As XmlResolver
Public Sub New()
MyBase.XmlResolver = New XmlUrlResolver()
End Sub
End Class
End Namespace",
GetCA3077ConstructorBasicResultAt(17, 20, "TestClass")
);
}
private async Task VerifyCSharpAnalyzerAsync(string source, params DiagnosticResult[] expected)
{
var test = new VerifyCS.Test
{
ReferenceAssemblies = ReferenceAssemblies.NetFramework.Net472.Default,
TestCode = source,
};
test.ExpectedDiagnostics.AddRange(expected);
await test.RunAsync();
}
private async Task VerifyVisualBasicAnalyzerAsync(string source, params DiagnosticResult[] expected)
{
var test = new VerifyVB.Test
{
ReferenceAssemblies = ReferenceAssemblies.NetFramework.Net472.Default,
TestCode = source,
};
test.ExpectedDiagnostics.AddRange(expected);
await test.RunAsync();
}
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.Reflection;
using log4net;
using Nini.Config;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
using Mono.Addins;
namespace OpenSim.Region.CoreModules.Agent.AssetTransaction
{
[Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "AssetTransactionModule")]
public class AssetTransactionModule : INonSharedRegionModule,
IAgentAssetTransactions
{
// private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
protected Scene m_Scene;
private bool m_dumpAssetsToFile = false;
private int m_levelUpload = 0;
/// <summary>
/// Each agent has its own singleton collection of transactions
/// </summary>
private Dictionary<UUID, AgentAssetTransactions> AgentTransactions =
new Dictionary<UUID, AgentAssetTransactions>();
#region Region Module interface
public void Initialise(IConfigSource source)
{
IConfig sconfig = source.Configs["Startup"];
if (sconfig != null)
{
m_levelUpload = sconfig.GetInt("LevelUpload", 0);
}
}
public void AddRegion(Scene scene)
{
m_Scene = scene;
scene.RegisterModuleInterface<IAgentAssetTransactions>(this);
scene.EventManager.OnNewClient += NewClient;
}
public void RegionLoaded(Scene scene)
{
}
public void RemoveRegion(Scene scene)
{
}
public void Close()
{
}
public string Name
{
get { return "AgentTransactionModule"; }
}
public Type ReplaceableInterface
{
get { return typeof(IAgentAssetTransactions); }
}
#endregion
public void NewClient(IClientAPI client)
{
client.OnAssetUploadRequest += HandleUDPUploadRequest;
client.OnXferReceive += HandleXfer;
}
#region AgentAssetTransactions
/// <summary>
/// Get the collection of asset transactions for the given user.
/// If one does not already exist, it is created.
/// </summary>
/// <param name="userID"></param>
/// <returns></returns>
private AgentAssetTransactions GetUserTransactions(UUID userID)
{
lock (AgentTransactions)
{
if (!AgentTransactions.ContainsKey(userID))
{
AgentAssetTransactions transactions =
new AgentAssetTransactions(userID, m_Scene,
m_dumpAssetsToFile);
AgentTransactions.Add(userID, transactions);
}
return AgentTransactions[userID];
}
}
/// <summary>
/// Remove the given agent asset transactions. This should be called
/// when a client is departing from a scene (and hence won't be making
/// any more transactions here).
/// </summary>
/// <param name="userID"></param>
public void RemoveAgentAssetTransactions(UUID userID)
{
// m_log.DebugFormat("Removing agent asset transactions structure for agent {0}", userID);
lock (AgentTransactions)
{
AgentTransactions.Remove(userID);
}
}
/// <summary>
/// Create an inventory item from data that has been received through
/// a transaction.
/// This is called when new clothing or body parts are created.
/// It may also be called in other situations.
/// </summary>
/// <param name="remoteClient"></param>
/// <param name="transactionID"></param>
/// <param name="folderID"></param>
/// <param name="callbackID"></param>
/// <param name="description"></param>
/// <param name="name"></param>
/// <param name="invType"></param>
/// <param name="type"></param>
/// <param name="wearableType"></param>
/// <param name="nextOwnerMask"></param>
public bool HandleItemCreationFromTransaction(IClientAPI remoteClient,
UUID transactionID, UUID folderID, uint callbackID,
string description, string name, sbyte invType,
sbyte type, byte wearableType, uint nextOwnerMask)
{
// m_log.DebugFormat(
// "[TRANSACTIONS MANAGER] Called HandleItemCreationFromTransaction with item {0}", name);
AgentAssetTransactions transactions =
GetUserTransactions(remoteClient.AgentId);
return transactions.RequestCreateInventoryItem(remoteClient, transactionID,
folderID, callbackID, description, name, invType, type,
wearableType, nextOwnerMask);
}
/// <summary>
/// Update an inventory item with data that has been received through a
/// transaction.
/// </summary>
/// <remarks>
/// This is called when clothing or body parts are updated (for
/// instance, with new textures or colours). It may also be called in
/// other situations.
/// </remarks>
/// <param name="remoteClient"></param>
/// <param name="transactionID"></param>
/// <param name="item"></param>
public void HandleItemUpdateFromTransaction(IClientAPI remoteClient,
UUID transactionID, InventoryItemBase item)
{
// m_log.DebugFormat(
// "[ASSET TRANSACTION MODULE]: Called HandleItemUpdateFromTransaction with item {0}",
// item.Name);
AgentAssetTransactions transactions = GetUserTransactions(remoteClient.AgentId);
transactions.RequestUpdateInventoryItem(remoteClient, transactionID, item);
}
/// <summary>
/// Update a task inventory item with data that has been received
/// through a transaction.
///
/// This is currently called when, for instance, a notecard in a prim
/// is saved. The data is sent up through a single AssetUploadRequest.
/// A subsequent UpdateTaskInventory then references the transaction
/// and comes through this method.
/// </summary>
/// <param name="remoteClient"></param>
/// <param name="part"></param>
/// <param name="transactionID"></param>
/// <param name="item"></param>
public void HandleTaskItemUpdateFromTransaction(
IClientAPI remoteClient, SceneObjectPart part, UUID transactionID, TaskInventoryItem item)
{
// m_log.DebugFormat(
// "[ASSET TRANSACTION MODULE]: Called HandleTaskItemUpdateFromTransaction with item {0} in {1} for {2} in {3}",
// item.Name, part.Name, remoteClient.Name, m_Scene.RegionInfo.RegionName);
AgentAssetTransactions transactions =
GetUserTransactions(remoteClient.AgentId);
transactions.RequestUpdateTaskInventoryItem(remoteClient, part,
transactionID, item);
}
/// <summary>
/// Request that a client (agent) begin an asset transfer.
/// </summary>
/// <param name="remoteClient"></param>
/// <param name="assetID"></param>
/// <param name="transactionID"></param>
/// <param name="type"></param>
/// <param name="data"></param></param>
/// <param name="tempFile"></param>
public void HandleUDPUploadRequest(IClientAPI remoteClient,
UUID assetID, UUID transactionID, sbyte type, byte[] data,
bool storeLocal, bool tempFile)
{
// m_log.DebugFormat(
// "[ASSET TRANSACTION MODULE]: HandleUDPUploadRequest - assetID: {0}, transaction {1}, type {2}, storeLocal {3}, tempFile {4}, data.Length {5}",
// assetID, transactionID, type, storeLocal, tempFile, data.Length);
if (((AssetType)type == AssetType.Texture ||
(AssetType)type == AssetType.Sound ||
(AssetType)type == AssetType.TextureTGA ||
(AssetType)type == AssetType.Animation) &&
tempFile == false)
{
ScenePresence avatar = null;
Scene scene = (Scene)remoteClient.Scene;
scene.TryGetScenePresence(remoteClient.AgentId, out avatar);
// check user level
if (avatar != null)
{
if (avatar.GodController.UserLevel < m_levelUpload)
{
remoteClient.SendAgentAlertMessage("Unable to upload asset. Insufficient permissions.", false);
return;
}
}
// check funds
IMoneyModule mm = scene.RequestModuleInterface<IMoneyModule>();
if (mm != null)
{
if (!mm.UploadCovered(remoteClient.AgentId, mm.UploadCharge))
{
remoteClient.SendAgentAlertMessage("Unable to upload asset. Insufficient funds.", false);
return;
}
}
}
AgentAssetTransactions transactions = GetUserTransactions(remoteClient.AgentId);
AssetXferUploader uploader = transactions.RequestXferUploader(transactionID);
uploader.StartUpload(remoteClient, assetID, transactionID, type, data, storeLocal, tempFile);
}
/// <summary>
/// Handle asset transfer data packets received in response to the
/// asset upload request in HandleUDPUploadRequest()
/// </summary>
/// <param name="remoteClient"></param>
/// <param name="xferID"></param>
/// <param name="packetID"></param>
/// <param name="data"></param>
public void HandleXfer(IClientAPI remoteClient, ulong xferID,
uint packetID, byte[] data)
{
// m_log.Debug("xferID: " + xferID + " packetID: " + packetID + " data length " + data.Length);
AgentAssetTransactions transactions = GetUserTransactions(remoteClient.AgentId);
transactions.HandleXfer(xferID, packetID, data);
}
#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 contains functional tests for Parallel.Invoke
//
// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=--=-=-=-=-=-=-=-=-=-=-=-
using Xunit;
namespace System.Threading.Tasks.Tests
{
public sealed class ParallelInvokeTest
{
#region Member Variables
private const int SEED = 1000; // minimum seed to be passed into ZetaSequence workload
private int _count; // no of actions
private ActionType _actionType; // type of actions
private Action[] _actions;
private double[] _results; // global place to store the workload results for verification
#endregion
public ParallelInvokeTest(ParallelInvokeTestParameters parameters)
{
_count = parameters.Count;
_actionType = parameters.ActionType;
_actions = new Action[_count];
_results = new double[_count];
// initialize actions
for (int i = 0; i < _count; i++)
{
int iCopy = i;
if (_actionType == ActionType.Empty)
{
_actions[i] = new Action(delegate { });
}
else if (_actionType == ActionType.EqualWorkload)
{
_actions[i] = new Action(delegate
{
_results[iCopy] = ZetaSequence(SEED);
});
}
else
{
_actions[i] = new Action(delegate
{
_results[iCopy] = ZetaSequence((iCopy + 1) * SEED);
});
}
}
}
/// <summary>
/// Actual Test.
/// Call Parallel.Invoke with actions using different workloads
///
/// Expected: Each action was invoked and returned the expected result
/// </summary>
/// <returns></returns>
public void RealRun()
{
Parallel.Invoke(_actions);
// verify result
//Function point comparison cant be done by rounding off to nearest decimal points since
//1.64 could be represented as 1.63999999 or as 1.6499999999. To perform floating point comparisons,
//a range has to be defined and check to ensure that the result obtained is within the specified range
double minLimit = 1.63;
double maxLimit = 1.65;
foreach (double r in _results)
{
//If action is empty we are expected zero as result
Assert.False(_actionType == ActionType.Empty && r != 0, string.Format("Differ in results. Expected result to be Zero but got {0}", r));
Assert.False(_actionType != ActionType.Empty && (r < minLimit || r > maxLimit), string.Format("Differ in results. Expected result to lie between {0} and {1} but got {2}", minLimit, maxLimit, r));
}
}
#region Helper Methods
// calculate 1 + 1/(2*2) + 1/(3*3) + ... + 1/(n*n) = Math.Pow (Math.PI, 2) / 6
private static double ZetaSequence(int n)
{
double result = 0;
for (int i = 1; i < n; i++)
{
result += 1.0 / ((double)i * (double)i);
}
return result;
}
#endregion
}
public enum ActionType
{
Empty,
EqualWorkload,
DifferentWorkload,
}
public class ParallelInvokeTestParameters
{
public ParallelInvokeTestParameters()
{
Count = 0;
ActionType = ActionType.Empty;
}
public int Count;
public ActionType ActionType;
}
#region Test Methods
public static class TestMethods
{
[Fact]
public static void ParallelInvoke0()
{
ParallelInvokeTestParameters parameters = new ParallelInvokeTestParameters
{
Count = 0,
ActionType = ActionType.DifferentWorkload,
};
ParallelInvokeTest test = new ParallelInvokeTest(parameters);
test.RealRun();
}
[Fact]
public static void ParallelInvoke1()
{
ParallelInvokeTestParameters parameters = new ParallelInvokeTestParameters
{
Count = 1,
ActionType = ActionType.DifferentWorkload,
};
ParallelInvokeTest test = new ParallelInvokeTest(parameters);
test.RealRun();
}
[Fact]
public static void ParallelInvoke2()
{
ParallelInvokeTestParameters parameters = new ParallelInvokeTestParameters
{
Count = 10,
ActionType = ActionType.DifferentWorkload,
};
ParallelInvokeTest test = new ParallelInvokeTest(parameters);
test.RealRun();
}
[Fact]
public static void ParallelInvoke3()
{
ParallelInvokeTestParameters parameters = new ParallelInvokeTestParameters
{
Count = 97,
ActionType = ActionType.DifferentWorkload,
};
ParallelInvokeTest test = new ParallelInvokeTest(parameters);
test.RealRun();
}
[Fact]
public static void ParallelInvoke4()
{
ParallelInvokeTestParameters parameters = new ParallelInvokeTestParameters
{
Count = 0,
ActionType = ActionType.Empty,
};
ParallelInvokeTest test = new ParallelInvokeTest(parameters);
test.RealRun();
}
[Fact]
public static void ParallelInvoke5()
{
ParallelInvokeTestParameters parameters = new ParallelInvokeTestParameters
{
Count = 1,
ActionType = ActionType.Empty,
};
ParallelInvokeTest test = new ParallelInvokeTest(parameters);
test.RealRun();
}
[Fact]
public static void ParallelInvoke6()
{
ParallelInvokeTestParameters parameters = new ParallelInvokeTestParameters
{
Count = 10,
ActionType = ActionType.Empty,
};
ParallelInvokeTest test = new ParallelInvokeTest(parameters);
test.RealRun();
}
[Fact]
public static void ParallelInvoke7()
{
ParallelInvokeTestParameters parameters = new ParallelInvokeTestParameters
{
Count = 97,
ActionType = ActionType.Empty,
};
ParallelInvokeTest test = new ParallelInvokeTest(parameters);
test.RealRun();
}
[Fact]
public static void ParallelInvoke8()
{
ParallelInvokeTestParameters parameters = new ParallelInvokeTestParameters
{
Count = 0,
ActionType = ActionType.EqualWorkload,
};
ParallelInvokeTest test = new ParallelInvokeTest(parameters);
test.RealRun();
}
[Fact]
public static void ParallelInvoke9()
{
ParallelInvokeTestParameters parameters = new ParallelInvokeTestParameters
{
Count = 1,
ActionType = ActionType.EqualWorkload,
};
ParallelInvokeTest test = new ParallelInvokeTest(parameters);
test.RealRun();
}
[Fact]
public static void ParallelInvoke10()
{
ParallelInvokeTestParameters parameters = new ParallelInvokeTestParameters
{
Count = 10,
ActionType = ActionType.EqualWorkload,
};
ParallelInvokeTest test = new ParallelInvokeTest(parameters);
test.RealRun();
}
[Fact]
public static void ParallelInvoke11()
{
ParallelInvokeTestParameters parameters = new ParallelInvokeTestParameters
{
Count = 97,
ActionType = ActionType.EqualWorkload,
};
ParallelInvokeTest test = new ParallelInvokeTest(parameters);
test.RealRun();
}
}
#endregion
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Collections.Generic;
using Microsoft.AspNetCore.Mvc.ModelBinding.Validation;
using Xunit;
namespace Microsoft.AspNetCore.Mvc.ModelBinding.Metadata
{
public class DefaultValidationMetadataProviderTest
{
[Fact]
public void PropertyValidationFilter_ShouldValidateEntry_False_IfPropertyHasValidateNever()
{
// Arrange
var provider = new DefaultValidationMetadataProvider();
var attributes = new Attribute[] { new ValidateNeverAttribute() };
var key = ModelMetadataIdentity.ForProperty(typeof(string).GetProperty(nameof(string.Length)), typeof(int), typeof(string));
var context = new ValidationMetadataProviderContext(key, new ModelAttributes(new object[0], attributes, null));
// Act
provider.CreateValidationMetadata(context);
// Assert
Assert.NotNull(context.ValidationMetadata.PropertyValidationFilter);
Assert.False(context.ValidationMetadata.PropertyValidationFilter.ShouldValidateEntry(
new ValidationEntry(),
new ValidationEntry()));
}
[Fact]
public void PropertyValidationFilter_Null_IfPropertyHasValidateNeverOnItsType()
{
// Arrange
var provider = new DefaultValidationMetadataProvider();
var attributes = new Attribute[] { new ValidateNeverAttribute() };
var key = ModelMetadataIdentity.ForProperty(typeof(string).GetProperty(nameof(string.Length)), typeof(int), typeof(string));
var context = new ValidationMetadataProviderContext(key, new ModelAttributes(attributes, new object[0], null));
// Act
provider.CreateValidationMetadata(context);
// Assert
Assert.Null(context.ValidationMetadata.PropertyValidationFilter);
}
[Fact]
public void PropertyValidationFilter_Null_ForType()
{
// Arrange
var provider = new DefaultValidationMetadataProvider();
var attributes = new Attribute[] { new ValidateNeverAttribute() };
var key = ModelMetadataIdentity.ForType(typeof(ValidateNeverClass));
var context = new ValidationMetadataProviderContext(key, new ModelAttributes(attributes, null, null));
// Act
provider.CreateValidationMetadata(context);
// Assert
Assert.Null(context.ValidationMetadata.PropertyValidationFilter);
}
[Fact]
public void PropertyValidationFilter_ShouldValidateEntry_False_IfContainingTypeHasValidateNever()
{
// Arrange
var provider = new DefaultValidationMetadataProvider();
var key = ModelMetadataIdentity.ForProperty(
typeof(ValidateNeverClass).GetProperty(nameof(ValidateNeverClass.ClassName)),
typeof(string),
typeof(ValidateNeverClass));
var context = new ValidationMetadataProviderContext(key, new ModelAttributes(new object[0], new object[0], null));
// Act
provider.CreateValidationMetadata(context);
// Assert
Assert.NotNull(context.ValidationMetadata.PropertyValidationFilter);
Assert.False(context.ValidationMetadata.PropertyValidationFilter.ShouldValidateEntry(
new ValidationEntry(),
new ValidationEntry()));
}
[Fact]
public void PropertyValidationFilter_ShouldValidateEntry_False_IfContainingTypeInheritsValidateNever()
{
// Arrange
var provider = new DefaultValidationMetadataProvider();
var key = ModelMetadataIdentity.ForProperty(
typeof(ValidateNeverSubclass).GetProperty(nameof(ValidateNeverSubclass.SubclassName)),
typeof(string),
typeof(ValidateNeverSubclass));
var context = new ValidationMetadataProviderContext(key, new ModelAttributes(new object[0], new object[0], null));
// Act
provider.CreateValidationMetadata(context);
// Assert
Assert.NotNull(context.ValidationMetadata.PropertyValidationFilter);
Assert.False(context.ValidationMetadata.PropertyValidationFilter.ShouldValidateEntry(
new ValidationEntry(),
new ValidationEntry()));
}
[Fact]
public void GetValidationDetails_MarkedWithClientValidator_ReturnsValidator()
{
// Arrange
var provider = new DefaultValidationMetadataProvider();
var attribute = new TestClientModelValidationAttribute();
var attributes = new Attribute[] { attribute };
var key = ModelMetadataIdentity.ForProperty(typeof(string).GetProperty(nameof(string.Length)), typeof(int), typeof(string));
var context = new ValidationMetadataProviderContext(key, new ModelAttributes(new object[0], attributes, null));
// Act
provider.CreateValidationMetadata(context);
// Assert
var validatorMetadata = Assert.Single(context.ValidationMetadata.ValidatorMetadata);
Assert.Same(attribute, validatorMetadata);
}
[Fact]
public void GetValidationDetails_MarkedWithModelValidator_ReturnsValidator()
{
// Arrange
var provider = new DefaultValidationMetadataProvider();
var attribute = new TestModelValidationAttribute();
var attributes = new Attribute[] { attribute };
var key = ModelMetadataIdentity.ForProperty(typeof(string).GetProperty(nameof(string.Length)), typeof(int), typeof(string));
var context = new ValidationMetadataProviderContext(key, new ModelAttributes(new object[0], attributes, null));
// Act
provider.CreateValidationMetadata(context);
// Assert
var validatorMetadata = Assert.Single(context.ValidationMetadata.ValidatorMetadata);
Assert.Same(attribute, validatorMetadata);
}
[Fact]
public void GetValidationDetails_Validator_AlreadyInContext_Ignores()
{
// Arrange
var provider = new DefaultValidationMetadataProvider();
var attribute = new TestValidationAttribute();
var attributes = new Attribute[] { attribute };
var key = ModelMetadataIdentity.ForProperty(typeof(string).GetProperty(nameof(string.Length)), typeof(int), typeof(string));
var context = new ValidationMetadataProviderContext(key, new ModelAttributes(new object[0], attributes, null));
context.ValidationMetadata.ValidatorMetadata.Add(attribute);
// Act
provider.CreateValidationMetadata(context);
// Assert
var validatorMetadata = Assert.Single(context.ValidationMetadata.ValidatorMetadata);
Assert.Same(attribute, validatorMetadata);
}
[ValidateNever]
private class ValidateNeverClass
{
public string ClassName { get; set; }
}
private class ValidateNeverSubclass : ValidateNeverClass
{
public string SubclassName { get; set; }
}
private class TestModelValidationAttribute : Attribute, IModelValidator
{
public IEnumerable<ModelValidationResult> Validate(ModelValidationContext context)
{
throw new NotImplementedException();
}
}
private class TestClientModelValidationAttribute : Attribute, IClientModelValidator
{
public void AddValidation(ClientModelValidationContext context)
{
throw new NotImplementedException();
}
}
private class TestValidationAttribute : Attribute, IModelValidator, IClientModelValidator
{
public void AddValidation(ClientModelValidationContext context)
{
throw new NotImplementedException();
}
public IEnumerable<ModelValidationResult> Validate(ModelValidationContext context)
{
throw new NotImplementedException();
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Text.RegularExpressions;
using Mercurial.Attributes;
using Mercurial.Versions;
namespace Mercurial
{
/// <summary>
/// This class implements the "hg resolve" command (<see href="http://www.selenic.com/mercurial/hg.1.html#resolve"/>):
/// Redo merges or set/view the merge status of files.
/// </summary>
public sealed class ResolveCommand : IncludeExcludeCommandBase<ResolveCommand>, IMercurialCommand<IEnumerable<MergeConflict>>
{
/// <summary>
/// This is the backing field for the <see cref="Files"/> property.
/// </summary>
private readonly ListFile _Files = new ListFile();
/// <summary>
/// This is the backing field for the <see cref="MergeTool"/> property.
/// </summary>
private string _MergeTool = string.Empty;
/// <summary>
/// Initializes a new instance of the <see cref="ResolveCommand"/> class.
/// </summary>
public ResolveCommand()
: base("resolve")
{
// Do nothing here
}
/// <summary>
/// Gets or sets a value indicating whether to select all unresolved files.
/// Default value is <c>false</c>.
/// </summary>
/// <remarks>
/// Note that if the <see cref="Action"/> property is set to <see cref="ResolveAction.List"/>, then
/// this property is not used.
/// </remarks>
[BooleanArgument(TrueOption = "--all")]
[DefaultValue(false)]
public bool SelectAll
{
get;
set;
}
/// <summary>
/// Sets the <see cref="SelectAll"/> property to the specified value and
/// returns this <see cref="ResolveCommand"/> instance.
/// </summary>
/// <param name="value">
/// The new value for the <see cref="SelectAll"/> property.
/// </param>
/// <returns>
/// This <see cref="ResolveCommand"/> instance.
/// </returns>
/// <remarks>
/// This method is part of the fluent interface.
/// </remarks>
public ResolveCommand WithSelectAll(bool value = true)
{
SelectAll = value;
return this;
}
/// <summary>
/// Gets the collection of files to process.
/// </summary>
public Collection<string> Files
{
get
{
return _Files.Collection;
}
}
/// <summary>
/// Adds the value to the <see cref="Files"/> collection property and
/// returns this <see cref="ResolveCommand"/> instance.
/// </summary>
/// <param name="value">
/// The value to add to the <see cref="Files"/> collection property.
/// </param>
/// <returns>
/// This <see cref="ResolveCommand"/> instance.
/// </returns>
/// <remarks>
/// This method is part of the fluent interface.
/// </remarks>
/// <exception cref="ArgumentNullException">
/// <para><paramref name="value"/> is <c>null</c> or empty.</para>
/// </exception>
public ResolveCommand WithFile(string value)
{
if (StringEx.IsNullOrWhiteSpace(value))
throw new ArgumentNullException("value");
Files.Add(value);
return this;
}
/// <summary>
/// Gets or sets the merge tool to use.
/// Default value is <see cref="string.Empty"/> in which case the default merge tool(s) are used.
/// </summary>
[DefaultValue("")]
public string MergeTool
{
get
{
return _MergeTool;
}
set
{
RequiresVersion(new Version(1, 7), "MergeTool property of the ResolveCommand class");
_MergeTool = (value ?? string.Empty).Trim();
}
}
/// <summary>
/// Sets the <see cref="MergeTool"/> property to the specified value and
/// returns this <see cref="ResolveCommand"/> instance.
/// </summary>
/// <param name="value">
/// The new value for the <see cref="MergeTool"/> property.
/// </param>
/// <returns>
/// This <see cref="ResolveCommand"/> instance.
/// </returns>
/// <remarks>
/// This method is part of the fluent interface.
/// </remarks>
public ResolveCommand WithMergeTool(string value)
{
MergeTool = value;
return this;
}
/// <summary>
/// Gets or sets the <see cref="ResolveAction"/> to take.
/// Default value is <see cref="ResolveAction.MarkResolved"/>.
/// </summary>
[EnumArgument(ResolveAction.MarkResolved, "--mark")]
[EnumArgument(ResolveAction.MarkUnresolved, "--unmark")]
[EnumArgument(ResolveAction.List, "--list")]
[DefaultValue(ResolveAction.MarkResolved)]
public ResolveAction Action
{
get;
set;
}
/// <summary>
/// Sets the <see cref="Action"/> property to the specified value and
/// returns this <see cref="ResolveCommand"/> instance.
/// </summary>
/// <param name="value">
/// The new value for the <see cref="Action"/> property.
/// </param>
/// <returns>
/// This <see cref="ResolveCommand"/> instance.
/// </returns>
/// <remarks>
/// This method is part of the fluent interface.
/// </remarks>
public ResolveCommand WithAction(ResolveAction value)
{
Action = value;
return this;
}
/// <summary>
/// This method should parse and store the appropriate execution result output
/// according to the type of data the command line client would return for
/// the command.
/// </summary>
/// <param name="exitCode">
/// The exit code from executing the command line client.
/// </param>
/// <param name="standardOutput">
/// The standard output from executing the command line client.
/// </param>
/// <exception cref="MercurialResultParsingException">
/// Unable to parse one or more of the lines of output from the 'hg resolve --list' command
/// </exception>
protected override void ParseStandardOutputForResults(int exitCode, string standardOutput)
{
if (exitCode != 0 || Action != ResolveAction.List)
return;
var resolutionRegex = new Regex(@"^(?<state>[UR])\s(?<file>.*)$", RegexOptions.IgnoreCase);
string[] lines = OutputParsingUtilities.SplitIntoLines(standardOutput);
var result = new List<MergeConflict>();
foreach (Match resolutionMatch in lines.Select(line => resolutionRegex.Match(line)))
{
if (!resolutionMatch.Success)
throw new MercurialResultParsingException(exitCode, "Unable to parse one or more of the lines of output from the 'hg resolve --list' command", standardOutput);
result.Add(new MergeConflict(
resolutionMatch.Groups["file"].Value,
resolutionMatch.Groups["state"].Value == "R" ? MergeConflictState.Resolved : MergeConflictState.Unresolved));
}
Result = result;
}
/// <summary>
/// Gets the result from the command line execution, as an appropriately typed value.
/// </summary>
public IEnumerable<MergeConflict> Result
{
get;
private set;
}
/// <summary>
/// Gets all the arguments to the <see cref="CommandBase{T}.Command"/>, or an
/// empty array if there are none.
/// </summary>
public override IEnumerable<string> Arguments
{
get
{
foreach (string argument in GetBaseArguments())
yield return argument;
foreach (string argument in MercurialVersionBase.Current.MergeToolOption(MergeTool))
yield return argument;
foreach (string argument in _Files.GetArguments())
yield return argument;
}
}
/// <summary>
/// Gets the base arguments.
/// </summary>
/// <returns>
/// The contents of the base arguments property, to avoide unverifiable code in <see cref="Arguments"/>.
/// </returns>
private IEnumerable<string> GetBaseArguments()
{
return base.Arguments;
}
/// <summary>
/// Override this method to implement code that will execute after command
/// line execution.
/// </summary>
protected override void Cleanup()
{
base.Cleanup();
_Files.Cleanup();
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Security.Principal;
using System.Threading.Tasks;
using IdentityModel;
using IdentityServer4.Events;
using IdentityServer4.Services;
using IdentityServer4.Stores;
using IdentityServerAspNetIdentity.Models;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
namespace IdentityServer4.Quickstart.UI
{
[SecurityHeaders]
[AllowAnonymous]
public class ExternalController : Controller
{
private readonly UserManager<ApplicationUser> _userManager;
private readonly SignInManager<ApplicationUser> _signInManager;
private readonly IIdentityServerInteractionService _interaction;
private readonly IClientStore _clientStore;
private readonly IEventService _events;
private readonly ILogger<ExternalController> _logger;
public ExternalController(
UserManager<ApplicationUser> userManager,
SignInManager<ApplicationUser> signInManager,
IIdentityServerInteractionService interaction,
IClientStore clientStore,
IEventService events,
ILogger<ExternalController> logger)
{
_userManager = userManager;
_signInManager = signInManager;
_interaction = interaction;
_clientStore = clientStore;
_events = events;
_logger = logger;
}
/// <summary>
/// initiate roundtrip to external authentication provider
/// </summary>
[HttpGet]
public async Task<IActionResult> Challenge(string provider, string returnUrl)
{
if (string.IsNullOrEmpty(returnUrl)) returnUrl = "~/";
// validate returnUrl - either it is a valid OIDC URL or back to a local page
if (Url.IsLocalUrl(returnUrl) == false && _interaction.IsValidReturnUrl(returnUrl) == false)
{
// user might have clicked on a malicious link - should be logged
throw new Exception("invalid return URL");
}
if (AccountOptions.WindowsAuthenticationSchemeName == provider)
{
// windows authentication needs special handling
return await ProcessWindowsLoginAsync(returnUrl);
}
else
{
// start challenge and roundtrip the return URL and scheme
var props = new AuthenticationProperties
{
RedirectUri = Url.Action(nameof(Callback)),
Items =
{
{ "returnUrl", returnUrl },
{ "scheme", provider },
}
};
return Challenge(props, provider);
}
}
/// <summary>
/// Post processing of external authentication
/// </summary>
[HttpGet]
public async Task<IActionResult> Callback()
{
// read external identity from the temporary cookie
var result = await HttpContext.AuthenticateAsync(IdentityConstants.ExternalScheme);
if (result?.Succeeded != true)
{
throw new Exception("External authentication error");
}
if (_logger.IsEnabled(LogLevel.Debug))
{
var externalClaims = result.Principal.Claims.Select(c => $"{c.Type}: {c.Value}");
_logger.LogDebug("External claims: {@claims}", externalClaims);
}
// lookup our user and external provider info
var (user, provider, providerUserId, claims) = await FindUserFromExternalProviderAsync(result);
if (user == null)
{
// this might be where you might initiate a custom workflow for user registration
// in this sample we don't show how that would be done, as our sample implementation
// simply auto-provisions new external user
user = await AutoProvisionUserAsync(provider, providerUserId, claims);
}
// this allows us to collect any additonal claims or properties
// for the specific prtotocols used and store them in the local auth cookie.
// this is typically used to store data needed for signout from those protocols.
var additionalLocalClaims = new List<Claim>();
var localSignInProps = new AuthenticationProperties();
ProcessLoginCallbackForOidc(result, additionalLocalClaims, localSignInProps);
ProcessLoginCallbackForWsFed(result, additionalLocalClaims, localSignInProps);
ProcessLoginCallbackForSaml2p(result, additionalLocalClaims, localSignInProps);
// issue authentication cookie for user
// we must issue the cookie maually, and can't use the SignInManager because
// it doesn't expose an API to issue additional claims from the login workflow
var principal = await _signInManager.CreateUserPrincipalAsync(user);
additionalLocalClaims.AddRange(principal.Claims);
var name = principal.FindFirst(JwtClaimTypes.Name)?.Value ?? user.Id;
await HttpContext.SignInAsync(user.Id, name, provider, localSignInProps, additionalLocalClaims.ToArray());
// delete temporary cookie used during external authentication
await HttpContext.SignOutAsync(IdentityConstants.ExternalScheme);
// retrieve return URL
var returnUrl = result.Properties.Items["returnUrl"] ?? "~/";
// check if external login is in the context of an OIDC request
var context = await _interaction.GetAuthorizationContextAsync(returnUrl);
await _events.RaiseAsync(new UserLoginSuccessEvent(provider, providerUserId, user.Id, name, true, context?.ClientId));
if (context != null)
{
if (await _clientStore.IsPkceClientAsync(context.ClientId))
{
// if the client is PKCE then we assume it's native, so this change in how to
// return the response is for better UX for the end user.
return View("Redirect", new RedirectViewModel { RedirectUrl = returnUrl });
}
}
return Redirect(returnUrl);
}
private async Task<IActionResult> ProcessWindowsLoginAsync(string returnUrl)
{
// see if windows auth has already been requested and succeeded
var result = await HttpContext.AuthenticateAsync(AccountOptions.WindowsAuthenticationSchemeName);
if (result?.Principal is WindowsPrincipal wp)
{
// we will issue the external cookie and then redirect the
// user back to the external callback, in essence, treating windows
// auth the same as any other external authentication mechanism
var props = new AuthenticationProperties()
{
RedirectUri = Url.Action("Callback"),
Items =
{
{ "returnUrl", returnUrl },
{ "scheme", AccountOptions.WindowsAuthenticationSchemeName },
}
};
var id = new ClaimsIdentity(AccountOptions.WindowsAuthenticationSchemeName);
id.AddClaim(new Claim(JwtClaimTypes.Subject, wp.FindFirst(ClaimTypes.PrimarySid).Value));
id.AddClaim(new Claim(JwtClaimTypes.Name, wp.Identity.Name));
// add the groups as claims -- be careful if the number of groups is too large
if (AccountOptions.IncludeWindowsGroups)
{
var wi = wp.Identity as WindowsIdentity;
var groups = wi.Groups.Translate(typeof(NTAccount));
var roles = groups.Select(x => new Claim(JwtClaimTypes.Role, x.Value));
id.AddClaims(roles);
}
await HttpContext.SignInAsync(
IdentityServer4.IdentityServerConstants.ExternalCookieAuthenticationScheme,
new ClaimsPrincipal(id),
props);
return Redirect(props.RedirectUri);
}
else
{
// trigger windows auth
// since windows auth don't support the redirect uri,
// this URL is re-triggered when we call challenge
return Challenge(AccountOptions.WindowsAuthenticationSchemeName);
}
}
private async Task<(ApplicationUser user, string provider, string providerUserId, IEnumerable<Claim> claims)>
FindUserFromExternalProviderAsync(AuthenticateResult result)
{
var externalUser = result.Principal;
// try to determine the unique id of the external user (issued by the provider)
// the most common claim type for that are the sub claim and the NameIdentifier
// depending on the external provider, some other claim type might be used
var userIdClaim = externalUser.FindFirst(JwtClaimTypes.Subject) ??
externalUser.FindFirst(ClaimTypes.NameIdentifier) ??
throw new Exception("Unknown userid");
// remove the user id claim so we don't include it as an extra claim if/when we provision the user
var claims = externalUser.Claims.ToList();
claims.Remove(userIdClaim);
var provider = result.Properties.Items["scheme"];
var providerUserId = userIdClaim.Value;
// find external user
var user = await _userManager.FindByLoginAsync(provider, providerUserId);
return (user, provider, providerUserId, claims);
}
private async Task<ApplicationUser> AutoProvisionUserAsync(string provider, string providerUserId, IEnumerable<Claim> claims)
{
// create a list of claims that we want to transfer into our store
var filtered = new List<Claim>();
// user's display name
var name = claims.FirstOrDefault(x => x.Type == JwtClaimTypes.Name)?.Value ??
claims.FirstOrDefault(x => x.Type == ClaimTypes.Name)?.Value;
if (name != null)
{
filtered.Add(new Claim(JwtClaimTypes.Name, name));
}
else
{
var first = claims.FirstOrDefault(x => x.Type == JwtClaimTypes.GivenName)?.Value ??
claims.FirstOrDefault(x => x.Type == ClaimTypes.GivenName)?.Value;
var last = claims.FirstOrDefault(x => x.Type == JwtClaimTypes.FamilyName)?.Value ??
claims.FirstOrDefault(x => x.Type == ClaimTypes.Surname)?.Value;
if (first != null && last != null)
{
filtered.Add(new Claim(JwtClaimTypes.Name, first + " " + last));
}
else if (first != null)
{
filtered.Add(new Claim(JwtClaimTypes.Name, first));
}
else if (last != null)
{
filtered.Add(new Claim(JwtClaimTypes.Name, last));
}
}
// email
var email = claims.FirstOrDefault(x => x.Type == JwtClaimTypes.Email)?.Value ??
claims.FirstOrDefault(x => x.Type == ClaimTypes.Email)?.Value;
if (email != null)
{
filtered.Add(new Claim(JwtClaimTypes.Email, email));
}
var user = new ApplicationUser
{
UserName = Guid.NewGuid().ToString(),
};
var identityResult = await _userManager.CreateAsync(user);
if (!identityResult.Succeeded) throw new Exception(identityResult.Errors.First().Description);
if (filtered.Any())
{
identityResult = await _userManager.AddClaimsAsync(user, filtered);
if (!identityResult.Succeeded) throw new Exception(identityResult.Errors.First().Description);
}
identityResult = await _userManager.AddLoginAsync(user, new UserLoginInfo(provider, providerUserId, provider));
if (!identityResult.Succeeded) throw new Exception(identityResult.Errors.First().Description);
return user;
}
private void ProcessLoginCallbackForOidc(AuthenticateResult externalResult, List<Claim> localClaims, AuthenticationProperties localSignInProps)
{
// if the external system sent a session id claim, copy it over
// so we can use it for single sign-out
var sid = externalResult.Principal.Claims.FirstOrDefault(x => x.Type == JwtClaimTypes.SessionId);
if (sid != null)
{
localClaims.Add(new Claim(JwtClaimTypes.SessionId, sid.Value));
}
// if the external provider issued an id_token, we'll keep it for signout
var id_token = externalResult.Properties.GetTokenValue("id_token");
if (id_token != null)
{
localSignInProps.StoreTokens(new[] { new AuthenticationToken { Name = "id_token", Value = id_token } });
}
}
private void ProcessLoginCallbackForWsFed(AuthenticateResult externalResult, List<Claim> localClaims, AuthenticationProperties localSignInProps)
{
}
private void ProcessLoginCallbackForSaml2p(AuthenticateResult externalResult, List<Claim> localClaims, AuthenticationProperties localSignInProps)
{
}
}
}
| |
/*
* 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.Reflection;
using BulletDotNET;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Region.Physics.Manager;
using log4net;
namespace OpenSim.Region.Physics.BulletDotNETPlugin
{
public class BulletDotNETCharacter : PhysicsActor
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
public btRigidBody Body;
public btCollisionShape Shell;
public btVector3 tempVector1;
public btVector3 tempVector2;
public btVector3 tempVector3;
public btVector3 tempVector4;
public btVector3 tempVector5RayCast;
public btVector3 tempVector6RayCast;
public btVector3 tempVector7RayCast;
public btQuaternion tempQuat1;
public btTransform tempTrans1;
public ClosestNotMeRayResultCallback ClosestCastResult;
private btTransform m_bodyTransform;
private btVector3 m_bodyPosition;
private btVector3 m_CapsuleOrientationAxis;
private btQuaternion m_bodyOrientation;
private btDefaultMotionState m_bodyMotionState;
private btGeneric6DofConstraint m_aMotor;
// private Vector3 m_movementComparision;
private Vector3 m_position;
private Vector3 m_zeroPosition;
private bool m_zeroFlag = false;
private bool m_lastUpdateSent = false;
private Vector3 m_velocity;
private Vector3 m_target_velocity;
private Vector3 m_acceleration;
private Vector3 m_rotationalVelocity;
private bool m_pidControllerActive = true;
public float PID_D = 80.0f;
public float PID_P = 90.0f;
public float CAPSULE_RADIUS = 0.37f;
public float CAPSULE_LENGTH = 2.140599f;
public float heightFudgeFactor = 0.52f;
public float walkDivisor = 1.3f;
public float runDivisor = 0.8f;
private float m_mass = 80f;
public float m_density = 60f;
private bool m_flying = false;
private bool m_iscolliding = false;
private bool m_iscollidingGround = false;
private bool m_wascolliding = false;
private bool m_wascollidingGround = false;
private bool m_iscollidingObj = false;
private bool m_alwaysRun = false;
private bool m_hackSentFall = false;
private bool m_hackSentFly = false;
public uint m_localID = 0;
public bool m_returnCollisions = false;
// taints and their non-tainted counterparts
public bool m_isPhysical = false; // the current physical status
public bool m_tainted_isPhysical = false; // set when the physical status is tainted (false=not existing in physics engine, true=existing)
private float m_tainted_CAPSULE_LENGTH; // set when the capsule length changes.
private bool m_taintRemove = false;
// private bool m_taintedPosition = false;
// private Vector3 m_taintedPosition_value;
private Vector3 m_taintedForce;
private float m_buoyancy = 0f;
// private CollisionLocker ode;
// private string m_name = String.Empty;
private bool[] m_colliderarr = new bool[11];
private bool[] m_colliderGroundarr = new bool[11];
private BulletDotNETScene m_parent_scene;
public int m_eventsubscription = 0;
private CollisionEventUpdate CollisionEventsThisFrame = null;
private int m_requestedUpdateFrequency = 0;
public BulletDotNETCharacter(string avName, BulletDotNETScene parent_scene, Vector3 pos, Vector3 size, float pid_d, float pid_p, float capsule_radius, float tensor, float density, float height_fudge_factor, float walk_divisor, float rundivisor)
{
m_position = pos;
m_zeroPosition = pos;
m_parent_scene = parent_scene;
PID_D = pid_d;
PID_P = pid_p;
CAPSULE_RADIUS = capsule_radius;
m_density = density;
heightFudgeFactor = height_fudge_factor;
walkDivisor = walk_divisor;
runDivisor = rundivisor;
for (int i = 0; i < 11; i++)
{
m_colliderarr[i] = false;
}
for (int i = 0; i < 11; i++)
{
m_colliderGroundarr[i] = false;
}
CAPSULE_LENGTH = (size.Z * 1.15f) - CAPSULE_RADIUS * 2.0f;
m_tainted_CAPSULE_LENGTH = CAPSULE_LENGTH;
m_isPhysical = false; // current status: no ODE information exists
m_tainted_isPhysical = true; // new tainted status: need to create ODE information
m_parent_scene.AddPhysicsActorTaint(this);
// m_name = avName;
tempVector1 = new btVector3(0, 0, 0);
tempVector2 = new btVector3(0, 0, 0);
tempVector3 = new btVector3(0, 0, 0);
tempVector4 = new btVector3(0, 0, 0);
tempVector5RayCast = new btVector3(0, 0, 0);
tempVector6RayCast = new btVector3(0, 0, 0);
tempVector7RayCast = new btVector3(0, 0, 0);
tempQuat1 = new btQuaternion(0, 0, 0, 1);
tempTrans1 = new btTransform(tempQuat1, tempVector1);
// m_movementComparision = new PhysicsVector(0, 0, 0);
m_CapsuleOrientationAxis = new btVector3(1, 0, 1);
}
/// <summary>
/// This creates the Avatar's physical Surrogate at the position supplied
/// </summary>
/// <param name="npositionX"></param>
/// <param name="npositionY"></param>
/// <param name="npositionZ"></param>
// WARNING: This MUST NOT be called outside of ProcessTaints, else we can have unsynchronized access
// to ODE internals. ProcessTaints is called from within thread-locked Simulate(), so it is the only
// place that is safe to call this routine AvatarGeomAndBodyCreation.
private void AvatarGeomAndBodyCreation(float npositionX, float npositionY, float npositionZ)
{
if (CAPSULE_LENGTH <= 0)
{
m_log.Warn("[PHYSICS]: The capsule size you specified in opensim.ini is invalid! Setting it to the smallest possible size!");
CAPSULE_LENGTH = 0.01f;
}
if (CAPSULE_RADIUS <= 0)
{
m_log.Warn("[PHYSICS]: The capsule size you specified in opensim.ini is invalid! Setting it to the smallest possible size!");
CAPSULE_RADIUS = 0.01f;
}
Shell = new btCapsuleShape(CAPSULE_RADIUS, CAPSULE_LENGTH);
if (m_bodyPosition == null)
m_bodyPosition = new btVector3(npositionX, npositionY, npositionZ);
m_bodyPosition.setValue(npositionX, npositionY, npositionZ);
if (m_bodyOrientation == null)
m_bodyOrientation = new btQuaternion(m_CapsuleOrientationAxis, (Utils.DEG_TO_RAD * 90));
if (m_bodyTransform == null)
m_bodyTransform = new btTransform(m_bodyOrientation, m_bodyPosition);
else
{
m_bodyTransform.Dispose();
m_bodyTransform = new btTransform(m_bodyOrientation, m_bodyPosition);
}
if (m_bodyMotionState == null)
m_bodyMotionState = new btDefaultMotionState(m_bodyTransform);
else
m_bodyMotionState.setWorldTransform(m_bodyTransform);
m_mass = Mass;
Body = new btRigidBody(m_mass, m_bodyMotionState, Shell);
// this is used for self identification. User localID instead of body handle
Body.setUserPointer(new IntPtr((int)m_localID));
if (ClosestCastResult != null)
ClosestCastResult.Dispose();
ClosestCastResult = new ClosestNotMeRayResultCallback(Body);
m_parent_scene.AddRigidBody(Body);
Body.setActivationState(4);
if (m_aMotor != null)
{
if (m_aMotor.Handle != IntPtr.Zero)
{
m_parent_scene.getBulletWorld().removeConstraint(m_aMotor);
m_aMotor.Dispose();
}
m_aMotor = null;
}
m_aMotor = new btGeneric6DofConstraint(Body, m_parent_scene.TerrainBody,
m_parent_scene.TransZero,
m_parent_scene.TransZero, false);
m_aMotor.setAngularLowerLimit(m_parent_scene.VectorZero);
m_aMotor.setAngularUpperLimit(m_parent_scene.VectorZero);
}
public void Remove()
{
m_taintRemove = true;
}
public override bool Stopped
{
get { return m_zeroFlag; }
}
public override Vector3 Size
{
get { return new Vector3(CAPSULE_RADIUS * 2, CAPSULE_RADIUS * 2, CAPSULE_LENGTH); }
set
{
m_pidControllerActive = true;
Vector3 SetSize = value;
m_tainted_CAPSULE_LENGTH = (SetSize.Z * 1.15f) - CAPSULE_RADIUS * 2.0f;
//m_log.Info("[SIZE]: " + CAPSULE_LENGTH.ToString());
Velocity = Vector3.Zero;
m_parent_scene.AddPhysicsActorTaint(this);
}
}
/// <summary>
/// turn the PID controller on or off.
/// The PID Controller will turn on all by itself in many situations
/// </summary>
/// <param name="status"></param>
public void SetPidStatus(bool status)
{
m_pidControllerActive = status;
}
public override PrimitiveBaseShape Shape
{
set { return; }
}
public override uint LocalID
{
set { m_localID = value; }
}
public override bool Grabbed
{
set { return; }
}
public override bool Selected
{
set { return; }
}
public override void CrossingFailure()
{
}
public override void link(PhysicsActor obj)
{
}
public override void delink()
{
}
public override void LockAngularMotion(Vector3 axis)
{
}
public override Vector3 Position
{
get { return m_position; }
set
{
// m_taintedPosition_value = value;
m_position = value;
// m_taintedPosition = true;
}
}
public override float Mass
{
get
{
float AVvolume = (float)(Math.PI * Math.Pow(CAPSULE_RADIUS, 2) * CAPSULE_LENGTH);
return m_density * AVvolume;
}
}
public override Vector3 Force
{
get { return m_target_velocity; }
set { return; }
}
public override int VehicleType
{
get { return 0; }
set { return; }
}
public override void VehicleFloatParam(int param, float value)
{
}
public override void VehicleVectorParam(int param, Vector3 value)
{
}
public override void VehicleRotationParam(int param, Quaternion rotation)
{
}
public override void VehicleFlags(int param, bool remove)
{
}
public override void SetVolumeDetect(int param)
{
}
public override Vector3 GeometricCenter
{
get { return Vector3.Zero; }
}
public override Vector3 CenterOfMass
{
get { return Vector3.Zero; }
}
public override Vector3 Velocity
{
get
{
if (m_zeroFlag)
return Vector3.Zero;
m_lastUpdateSent = false;
return m_velocity;
}
set
{
m_pidControllerActive = true;
m_target_velocity = value;
}
}
public override Vector3 Torque
{
get { return Vector3.Zero; }
set { return; }
}
public override float CollisionScore
{
get { return 0f; }
set { }
}
public override Vector3 Acceleration
{
get { return m_acceleration; }
}
public override Quaternion Orientation
{
get { return Quaternion.Identity; }
set
{
}
}
public override int PhysicsActorType
{
get { return (int)ActorTypes.Agent; }
set { return; }
}
public override bool IsPhysical
{
get { return false; }
set { return; }
}
public override bool Flying
{
get { return m_flying; }
set { m_flying = value; }
}
public override bool SetAlwaysRun
{
get { return m_alwaysRun; }
set { m_alwaysRun = value; }
}
public override bool ThrottleUpdates
{
get { return false; }
set { return; }
}
/// <summary>
/// Returns if the avatar is colliding in general.
/// This includes the ground and objects and avatar.
/// </summary>
public override bool IsColliding
{
get { return m_iscolliding; }
set
{
int i;
int truecount = 0;
int falsecount = 0;
if (m_colliderarr.Length >= 10)
{
for (i = 0; i < 10; i++)
{
m_colliderarr[i] = m_colliderarr[i + 1];
}
}
m_colliderarr[10] = value;
for (i = 0; i < 11; i++)
{
if (m_colliderarr[i])
{
truecount++;
}
else
{
falsecount++;
}
}
// Equal truecounts and false counts means we're colliding with something.
m_log.DebugFormat("[PHYSICS]: TrueCount:{0}, FalseCount:{1}",truecount,falsecount);
if (falsecount > 1.2 * truecount)
{
m_iscolliding = false;
}
else
{
m_iscolliding = true;
}
if (m_wascolliding != m_iscolliding)
{
//base.SendCollisionUpdate(new CollisionEventUpdate());
}
m_wascolliding = m_iscolliding;
}
}
/// <summary>
/// Returns if an avatar is colliding with the ground
/// </summary>
public override bool CollidingGround
{
get { return m_iscollidingGround; }
set
{
// Collisions against the ground are not really reliable
// So, to get a consistant value we have to average the current result over time
// Currently we use 1 second = 10 calls to this.
int i;
int truecount = 0;
int falsecount = 0;
if (m_colliderGroundarr.Length >= 10)
{
for (i = 0; i < 10; i++)
{
m_colliderGroundarr[i] = m_colliderGroundarr[i + 1];
}
}
m_colliderGroundarr[10] = value;
for (i = 0; i < 11; i++)
{
if (m_colliderGroundarr[i])
{
truecount++;
}
else
{
falsecount++;
}
}
// Equal truecounts and false counts means we're colliding with something.
if (falsecount > 1.2 * truecount)
{
m_iscollidingGround = false;
}
else
{
m_iscollidingGround = true;
}
if (m_wascollidingGround != m_iscollidingGround)
{
//base.SendCollisionUpdate(new CollisionEventUpdate());
}
m_wascollidingGround = m_iscollidingGround;
}
}
/// <summary>
/// Returns if the avatar is colliding with an object
/// </summary>
public override bool CollidingObj
{
get { return m_iscollidingObj; }
set
{
m_iscollidingObj = value;
if (value)
m_pidControllerActive = false;
else
m_pidControllerActive = true;
}
}
public override bool FloatOnWater
{
set { return; }
}
public override Vector3 RotationalVelocity
{
get { return m_rotationalVelocity; }
set { m_rotationalVelocity = value; }
}
public override bool Kinematic
{
get { return false; }
set { }
}
public override float Buoyancy
{
get { return m_buoyancy; }
set { m_buoyancy = value; }
}
public override Vector3 PIDTarget { set { return; } }
public override bool PIDActive { set { return; } }
public override float PIDTau { set { return; } }
public override bool PIDHoverActive
{
set { return; }
}
public override float PIDHoverHeight
{
set { return; }
}
public override PIDHoverType PIDHoverType
{
set { return; }
}
public override float PIDHoverTau
{
set { return; }
}
public override Quaternion APIDTarget
{
set { return; }
}
public override bool APIDActive
{
set { return; }
}
public override float APIDStrength
{
set { return; }
}
public override float APIDDamping
{
set { return; }
}
/// <summary>
/// Adds the force supplied to the Target Velocity
/// The PID controller takes this target velocity and tries to make it a reality
/// </summary>
/// <param name="force"></param>
/// <param name="pushforce">Is this a push by a script?</param>
public override void AddForce(Vector3 force, bool pushforce)
{
if (pushforce)
{
m_pidControllerActive = false;
force *= 100f;
doForce(force, false);
//System.Console.WriteLine("Push!");
//_target_velocity.X += force.X;
// _target_velocity.Y += force.Y;
//_target_velocity.Z += force.Z;
}
else
{
m_pidControllerActive = true;
m_target_velocity.X += force.X;
m_target_velocity.Y += force.Y;
m_target_velocity.Z += force.Z;
}
//m_lastUpdateSent = false;
}
public void doForce(Vector3 force, bool now)
{
tempVector3.setValue(force.X, force.Y, force.Z);
if (now)
{
Body.applyCentralForce(tempVector3);
}
else
{
m_taintedForce += force;
m_parent_scene.AddPhysicsActorTaint(this);
}
}
public void doImpulse(Vector3 force, bool now)
{
tempVector3.setValue(force.X, force.Y, force.Z);
if (now)
{
Body.applyCentralImpulse(tempVector3);
}
else
{
m_taintedForce += force;
m_parent_scene.AddPhysicsActorTaint(this);
}
}
public override void AddAngularForce(Vector3 force, bool pushforce)
{
}
public override void SetMomentum(Vector3 momentum)
{
}
public override void SubscribeEvents(int ms)
{
m_eventsubscription = ms;
m_requestedUpdateFrequency = ms;
m_parent_scene.addCollisionEventReporting(this);
}
public override void UnSubscribeEvents()
{
m_parent_scene.remCollisionEventReporting(this);
m_eventsubscription = 0;
m_requestedUpdateFrequency = 0;
}
public override bool SubscribedEvents()
{
if (m_eventsubscription > 0)
return true;
return false;
}
public void AddCollision(uint collideWith, ContactPoint contact)
{
if (CollisionEventsThisFrame == null)
{
CollisionEventsThisFrame = new CollisionEventUpdate();
}
CollisionEventsThisFrame.addCollider(collideWith, contact);
}
public void SendCollisions()
{
if (m_eventsubscription >= m_requestedUpdateFrequency)
{
if (CollisionEventsThisFrame != null)
{
base.SendCollisionUpdate(CollisionEventsThisFrame);
}
CollisionEventsThisFrame = new CollisionEventUpdate();
m_eventsubscription = 0;
}
return;
}
internal void Dispose()
{
if (Body.isInWorld())
m_parent_scene.removeFromWorld(Body);
if (m_aMotor.Handle != IntPtr.Zero)
m_parent_scene.getBulletWorld().removeConstraint(m_aMotor);
m_aMotor.Dispose(); m_aMotor = null;
ClosestCastResult.Dispose(); ClosestCastResult = null;
Body.Dispose(); Body = null;
Shell.Dispose(); Shell = null;
tempQuat1.Dispose();
tempTrans1.Dispose();
tempVector1.Dispose();
tempVector2.Dispose();
tempVector3.Dispose();
tempVector4.Dispose();
tempVector5RayCast.Dispose();
tempVector6RayCast.Dispose();
}
public void ProcessTaints(float timestep)
{
if (m_tainted_isPhysical != m_isPhysical)
{
if (m_tainted_isPhysical)
{
// Create avatar capsule and related ODE data
if (!(Shell == null && Body == null))
{
m_log.Warn("[PHYSICS]: re-creating the following avatar ODE data, even though it already exists - "
+ (Shell != null ? "Shell " : "")
+ (Body != null ? "Body " : ""));
}
AvatarGeomAndBodyCreation(m_position.X, m_position.Y, m_position.Z);
}
else
{
// destroy avatar capsule and related ODE data
Dispose();
tempVector1 = new btVector3(0, 0, 0);
tempVector2 = new btVector3(0, 0, 0);
tempVector3 = new btVector3(0, 0, 0);
tempVector4 = new btVector3(0, 0, 0);
tempVector5RayCast = new btVector3(0, 0, 0);
tempVector6RayCast = new btVector3(0, 0, 0);
tempVector7RayCast = new btVector3(0, 0, 0);
tempQuat1 = new btQuaternion(0, 0, 0, 1);
tempTrans1 = new btTransform(tempQuat1, tempVector1);
// m_movementComparision = new PhysicsVector(0, 0, 0);
m_CapsuleOrientationAxis = new btVector3(1, 0, 1);
}
m_isPhysical = m_tainted_isPhysical;
}
if (m_tainted_CAPSULE_LENGTH != CAPSULE_LENGTH)
{
if (Body != null)
{
m_pidControllerActive = true;
// no lock needed on _parent_scene.OdeLock because we are called from within the thread lock in OdePlugin's simulate()
//d.JointDestroy(Amotor);
float prevCapsule = CAPSULE_LENGTH;
CAPSULE_LENGTH = m_tainted_CAPSULE_LENGTH;
//m_log.Info("[SIZE]: " + CAPSULE_LENGTH.ToString());
Dispose();
tempVector1 = new btVector3(0, 0, 0);
tempVector2 = new btVector3(0, 0, 0);
tempVector3 = new btVector3(0, 0, 0);
tempVector4 = new btVector3(0, 0, 0);
tempVector5RayCast = new btVector3(0, 0, 0);
tempVector6RayCast = new btVector3(0, 0, 0);
tempVector7RayCast = new btVector3(0, 0, 0);
tempQuat1 = new btQuaternion(0, 0, 0, 1);
tempTrans1 = new btTransform(tempQuat1, tempVector1);
// m_movementComparision = new PhysicsVector(0, 0, 0);
m_CapsuleOrientationAxis = new btVector3(1, 0, 1);
AvatarGeomAndBodyCreation(m_position.X, m_position.Y,
m_position.Z + (Math.Abs(CAPSULE_LENGTH - prevCapsule) * 2));
Velocity = Vector3.Zero;
}
else
{
m_log.Warn("[PHYSICS]: trying to change capsule size, but the following ODE data is missing - "
+ (Shell == null ? "Shell " : "")
+ (Body == null ? "Body " : ""));
}
}
if (m_taintRemove)
{
Dispose();
}
}
/// <summary>
/// Called from Simulate
/// This is the avatar's movement control + PID Controller
/// </summary>
/// <param name="timeStep"></param>
public void Move(float timeStep)
{
// no lock; for now it's only called from within Simulate()
// If the PID Controller isn't active then we set our force
// calculating base velocity to the current position
if (Body == null)
return;
tempTrans1.Dispose();
tempTrans1 = Body.getInterpolationWorldTransform();
tempVector1.Dispose();
tempVector1 = tempTrans1.getOrigin();
tempVector2.Dispose();
tempVector2 = Body.getInterpolationLinearVelocity();
if (m_pidControllerActive == false)
{
m_zeroPosition.X = tempVector1.getX();
m_zeroPosition.Y = tempVector1.getY();
m_zeroPosition.Z = tempVector1.getZ();
}
//PidStatus = true;
Vector3 vec = Vector3.Zero;
Vector3 vel = new Vector3(tempVector2.getX(), tempVector2.getY(), tempVector2.getZ());
float movementdivisor = 1f;
if (!m_alwaysRun)
{
movementdivisor = walkDivisor;
}
else
{
movementdivisor = runDivisor;
}
// if velocity is zero, use position control; otherwise, velocity control
if (m_target_velocity.X == 0.0f && m_target_velocity.Y == 0.0f && m_target_velocity.Z == 0.0f && m_iscolliding)
{
// keep track of where we stopped. No more slippin' & slidin'
if (!m_zeroFlag)
{
m_zeroFlag = true;
m_zeroPosition.X = tempVector1.getX();
m_zeroPosition.Y = tempVector1.getY();
m_zeroPosition.Z = tempVector1.getZ();
}
if (m_pidControllerActive)
{
// We only want to deactivate the PID Controller if we think we want to have our surrogate
// react to the physics scene by moving it's position.
// Avatar to Avatar collisions
// Prim to avatar collisions
Vector3 pos = new Vector3(tempVector1.getX(), tempVector1.getY(), tempVector1.getZ());
vec.X = (m_target_velocity.X - vel.X) * (PID_D) + (m_zeroPosition.X - pos.X) * (PID_P * 2);
vec.Y = (m_target_velocity.Y - vel.Y) * (PID_D) + (m_zeroPosition.Y - pos.Y) * (PID_P * 2);
if (m_flying)
{
vec.Z = (m_target_velocity.Z - vel.Z) * (PID_D) + (m_zeroPosition.Z - pos.Z) * PID_P;
}
}
//PidStatus = true;
}
else
{
m_pidControllerActive = true;
m_zeroFlag = false;
if (m_iscolliding && !m_flying)
{
// We're standing on something
vec.X = ((m_target_velocity.X / movementdivisor) - vel.X) * (PID_D);
vec.Y = ((m_target_velocity.Y / movementdivisor) - vel.Y) * (PID_D);
}
else if (m_iscolliding && m_flying)
{
// We're flying and colliding with something
vec.X = ((m_target_velocity.X / movementdivisor) - vel.X) * (PID_D / 16);
vec.Y = ((m_target_velocity.Y / movementdivisor) - vel.Y) * (PID_D / 16);
}
else if (!m_iscolliding && m_flying)
{
// we're in mid air suspended
vec.X = ((m_target_velocity.X / movementdivisor) - vel.X) * (PID_D / 6);
vec.Y = ((m_target_velocity.Y / movementdivisor) - vel.Y) * (PID_D / 6);
// We don't want linear velocity to cause our avatar to bounce, so we check target Z and actual velocity X, Y
// rebound preventing
if (m_target_velocity.Z < 0.025f && m_velocity.X < 0.25f && m_velocity.Y < 0.25f)
m_zeroFlag = true;
}
if (m_iscolliding && !m_flying && m_target_velocity.Z > 0.0f)
{
// We're colliding with something and we're not flying but we're moving
// This means we're walking or running.
Vector3 pos = new Vector3(tempVector1.getX(), tempVector1.getY(), tempVector1.getZ());
vec.Z = (m_target_velocity.Z - vel.Z) * PID_D + (m_zeroPosition.Z - pos.Z) * PID_P;
if (m_target_velocity.X > 0)
{
vec.X = ((m_target_velocity.X - vel.X) / 1.2f) * PID_D;
}
if (m_target_velocity.Y > 0)
{
vec.Y = ((m_target_velocity.Y - vel.Y) / 1.2f) * PID_D;
}
}
else if (!m_iscolliding && !m_flying)
{
// we're not colliding and we're not flying so that means we're falling!
// m_iscolliding includes collisions with the ground.
// d.Vector3 pos = d.BodyGetPosition(Body);
if (m_target_velocity.X > 0)
{
vec.X = ((m_target_velocity.X - vel.X) / 1.2f) * PID_D;
}
if (m_target_velocity.Y > 0)
{
vec.Y = ((m_target_velocity.Y - vel.Y) / 1.2f) * PID_D;
}
}
if (m_flying)
{
vec.Z = (m_target_velocity.Z - vel.Z) * (PID_D);
}
}
if (m_flying)
{
// Slight PID correction
vec.Z += (((-1 * m_parent_scene.gravityz) * m_mass) * 0.06f);
//auto fly height. Kitto Flora
//d.Vector3 pos = d.BodyGetPosition(Body);
float target_altitude = m_parent_scene.GetTerrainHeightAtXY(m_position.X, m_position.Y) + 5.0f;
if (m_position.Z < target_altitude)
{
vec.Z += (target_altitude - m_position.Z) * PID_P * 5.0f;
}
}
if (Body != null && (((m_target_velocity.X > 0.2f || m_target_velocity.X < -0.2f) || (m_target_velocity.Y > 0.2f || m_target_velocity.Y < -0.2f))))
{
Body.setFriction(0.001f);
//m_log.DebugFormat("[PHYSICS]: Avatar force applied: {0}, Target:{1}", vec.ToString(), m_target_velocity.ToString());
}
if (Body != null)
{
int activationstate = Body.getActivationState();
if (activationstate == 0)
{
Body.forceActivationState(1);
}
}
doImpulse(vec, true);
}
/// <summary>
/// Updates the reported position and velocity. This essentially sends the data up to ScenePresence.
/// </summary>
public void UpdatePositionAndVelocity()
{
if (Body == null)
return;
//int val = Environment.TickCount;
CheckIfStandingOnObject();
//m_log.DebugFormat("time:{0}", Environment.TickCount - val);
//IsColliding = Body.checkCollideWith(m_parent_scene.TerrainBody);
tempTrans1.Dispose();
tempTrans1 = Body.getInterpolationWorldTransform();
tempVector1.Dispose();
tempVector1 = tempTrans1.getOrigin();
tempVector2.Dispose();
tempVector2 = Body.getInterpolationLinearVelocity();
// no lock; called from Simulate() -- if you call this from elsewhere, gotta lock or do Monitor.Enter/Exit!
Vector3 vec = new Vector3(tempVector1.getX(), tempVector1.getY(), tempVector1.getZ());
// kluge to keep things in bounds. ODE lets dead avatars drift away (they should be removed!)
if (vec.X < -10.0f) vec.X = 0.0f;
if (vec.Y < -10.0f) vec.Y = 0.0f;
if (vec.X > (int)Constants.RegionSize + 10.2f) vec.X = (int)Constants.RegionSize + 10.2f;
if (vec.Y > (int)Constants.RegionSize + 10.2f) vec.Y = (int)Constants.RegionSize + 10.2f;
m_position.X = vec.X;
m_position.Y = vec.Y;
m_position.Z = vec.Z;
// Did we move last? = zeroflag
// This helps keep us from sliding all over
if (m_zeroFlag)
{
m_velocity.X = 0.0f;
m_velocity.Y = 0.0f;
m_velocity.Z = 0.0f;
// Did we send out the 'stopped' message?
if (!m_lastUpdateSent)
{
m_lastUpdateSent = true;
//base.RequestPhysicsterseUpdate();
}
}
else
{
m_lastUpdateSent = false;
vec = new Vector3(tempVector2.getX(), tempVector2.getY(), tempVector2.getZ());
m_velocity.X = (vec.X);
m_velocity.Y = (vec.Y);
m_velocity.Z = (vec.Z);
//m_log.Debug(m_target_velocity);
if (m_velocity.Z < -6 && !m_hackSentFall)
{
m_hackSentFall = true;
m_pidControllerActive = false;
}
else if (m_flying && !m_hackSentFly)
{
//m_hackSentFly = true;
//base.SendCollisionUpdate(new CollisionEventUpdate());
}
else
{
m_hackSentFly = false;
m_hackSentFall = false;
}
}
if (Body != null)
{
if (Body.getFriction() < 0.9f)
Body.setFriction(0.9f);
}
//if (Body != null)
// Body.clearForces();
}
public void CheckIfStandingOnObject()
{
float capsuleHalfHeight = ((CAPSULE_LENGTH + 2*CAPSULE_RADIUS)*0.5f);
tempVector5RayCast.setValue(m_position.X, m_position.Y, m_position.Z);
tempVector6RayCast.setValue(m_position.X, m_position.Y, m_position.Z - 1 * capsuleHalfHeight * 1.1f);
ClosestCastResult.Dispose();
ClosestCastResult = new ClosestNotMeRayResultCallback(Body);
try
{
m_parent_scene.getBulletWorld().rayTest(tempVector5RayCast, tempVector6RayCast, ClosestCastResult);
}
catch (AccessViolationException)
{
m_log.Debug("BAD!");
}
if (ClosestCastResult.hasHit())
{
if (tempVector7RayCast != null)
tempVector7RayCast.Dispose();
//tempVector7RayCast = ClosestCastResult.getHitPointWorld();
/*if (tempVector7RayCast == null) // null == no result also
{
CollidingObj = false;
IsColliding = false;
CollidingGround = false;
return;
}
float zVal = tempVector7RayCast.getZ();
if (zVal != 0)
m_log.Debug("[PHYSICS]: HAAAA");
if (zVal < m_position.Z && zVal > ((CAPSULE_LENGTH + 2 * CAPSULE_RADIUS) *0.5f))
{
CollidingObj = true;
IsColliding = true;
}
else
{
CollidingObj = false;
IsColliding = false;
CollidingGround = false;
}*/
//height+2*radius = capsule full length
//CollidingObj = true;
//IsColliding = true;
m_iscolliding = true;
}
else
{
//CollidingObj = false;
//IsColliding = false;
//CollidingGround = false;
m_iscolliding = 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.
// ------------------------------------------------------------------------------
// Changes to this file must follow the http://aka.ms/api-review process.
// ------------------------------------------------------------------------------
namespace System
{
[global::System.CLSCompliantAttribute(false)]
public static partial class WindowsRuntimeSystemExtensions
{
public static global::Windows.Foundation.IAsyncAction AsAsyncAction(this global::System.Threading.Tasks.Task source) { throw null; }
public static global::Windows.Foundation.IAsyncOperation<TResult> AsAsyncOperation<TResult>(this global::System.Threading.Tasks.Task<TResult> source) { throw null; }
public static global::System.Threading.Tasks.Task AsTask(this global::Windows.Foundation.IAsyncAction source) { throw null; }
public static global::System.Threading.Tasks.Task AsTask(this global::Windows.Foundation.IAsyncAction source, global::System.Threading.CancellationToken cancellationToken) { throw null; }
public static global::System.Threading.Tasks.Task AsTask<TProgress>(this global::Windows.Foundation.IAsyncActionWithProgress<TProgress> source) { throw null; }
public static global::System.Threading.Tasks.Task AsTask<TProgress>(this global::Windows.Foundation.IAsyncActionWithProgress<TProgress> source, global::System.IProgress<TProgress> progress) { throw null; }
public static global::System.Threading.Tasks.Task AsTask<TProgress>(this global::Windows.Foundation.IAsyncActionWithProgress<TProgress> source, global::System.Threading.CancellationToken cancellationToken) { throw null; }
public static global::System.Threading.Tasks.Task AsTask<TProgress>(this global::Windows.Foundation.IAsyncActionWithProgress<TProgress> source, global::System.Threading.CancellationToken cancellationToken, global::System.IProgress<TProgress> progress) { throw null; }
public static global::System.Threading.Tasks.Task<TResult> AsTask<TResult>(this global::Windows.Foundation.IAsyncOperation<TResult> source) { throw null; }
public static global::System.Threading.Tasks.Task<TResult> AsTask<TResult>(this global::Windows.Foundation.IAsyncOperation<TResult> source, global::System.Threading.CancellationToken cancellationToken) { throw null; }
public static global::System.Threading.Tasks.Task<TResult> AsTask<TResult, TProgress>(this global::Windows.Foundation.IAsyncOperationWithProgress<TResult, TProgress> source) { throw null; }
public static global::System.Threading.Tasks.Task<TResult> AsTask<TResult, TProgress>(this global::Windows.Foundation.IAsyncOperationWithProgress<TResult, TProgress> source, global::System.IProgress<TProgress> progress) { throw null; }
public static global::System.Threading.Tasks.Task<TResult> AsTask<TResult, TProgress>(this global::Windows.Foundation.IAsyncOperationWithProgress<TResult, TProgress> source, global::System.Threading.CancellationToken cancellationToken) { throw null; }
public static global::System.Threading.Tasks.Task<TResult> AsTask<TResult, TProgress>(this global::Windows.Foundation.IAsyncOperationWithProgress<TResult, TProgress> source, global::System.Threading.CancellationToken cancellationToken, global::System.IProgress<TProgress> progress) { throw null; }
[global::System.ComponentModel.EditorBrowsableAttribute((global::System.ComponentModel.EditorBrowsableState)(1))]
public static global::System.Runtime.CompilerServices.TaskAwaiter GetAwaiter(this global::Windows.Foundation.IAsyncAction source) { throw null; }
[global::System.ComponentModel.EditorBrowsableAttribute((global::System.ComponentModel.EditorBrowsableState)(1))]
public static global::System.Runtime.CompilerServices.TaskAwaiter GetAwaiter<TProgress>(this global::Windows.Foundation.IAsyncActionWithProgress<TProgress> source) { throw null; }
[global::System.ComponentModel.EditorBrowsableAttribute((global::System.ComponentModel.EditorBrowsableState)(1))]
public static global::System.Runtime.CompilerServices.TaskAwaiter<TResult> GetAwaiter<TResult>(this global::Windows.Foundation.IAsyncOperation<TResult> source) { throw null; }
[global::System.ComponentModel.EditorBrowsableAttribute((global::System.ComponentModel.EditorBrowsableState)(1))]
public static global::System.Runtime.CompilerServices.TaskAwaiter<TResult> GetAwaiter<TResult, TProgress>(this global::Windows.Foundation.IAsyncOperationWithProgress<TResult, TProgress> source) { throw null; }
}
}
namespace System.IO
{
public static partial class WindowsRuntimeStorageExtensions
{
[global::System.CLSCompliantAttribute(false)]
public static global::System.Threading.Tasks.Task<global::System.IO.Stream> OpenStreamForReadAsync(this global::Windows.Storage.IStorageFile windowsRuntimeFile) { throw null; }
[global::System.CLSCompliantAttribute(false)]
public static global::System.Threading.Tasks.Task<global::System.IO.Stream> OpenStreamForReadAsync(this global::Windows.Storage.IStorageFolder rootDirectory, string relativePath) { throw null; }
[global::System.CLSCompliantAttribute(false)]
public static global::System.Threading.Tasks.Task<global::System.IO.Stream> OpenStreamForWriteAsync(this global::Windows.Storage.IStorageFile windowsRuntimeFile) { throw null; }
[global::System.CLSCompliantAttribute(false)]
public static global::System.Threading.Tasks.Task<global::System.IO.Stream> OpenStreamForWriteAsync(this global::Windows.Storage.IStorageFolder rootDirectory, string relativePath, global::Windows.Storage.CreationCollisionOption creationCollisionOption) { throw null; }
[global::System.CLSCompliantAttribute(false)]
public static global::Microsoft.Win32.SafeHandles.SafeFileHandle CreateSafeFileHandle(
this global::Windows.Storage.IStorageFile windowsRuntimeFile,
global::System.IO.FileAccess access = global::System.IO.FileAccess.ReadWrite,
global::System.IO.FileShare share = global::System.IO.FileShare.Read,
global::System.IO.FileOptions options = global::System.IO.FileOptions.None) { throw null; }
[global::System.CLSCompliantAttribute(false)]
public static global::Microsoft.Win32.SafeHandles.SafeFileHandle CreateSafeFileHandle(
this global::Windows.Storage.IStorageFolder rootDirectory,
string relativePath,
global::System.IO.FileMode mode) { throw null; }
[global::System.CLSCompliantAttribute(false)]
public static global::Microsoft.Win32.SafeHandles.SafeFileHandle CreateSafeFileHandle(
this global::Windows.Storage.IStorageFolder rootDirectory,
string relativePath,
global::System.IO.FileMode mode,
global::System.IO.FileAccess access,
global::System.IO.FileShare share = global::System.IO.FileShare.Read,
global::System.IO.FileOptions options = global::System.IO.FileOptions.None) { throw null; }
}
public static partial class WindowsRuntimeStreamExtensions
{
[global::System.CLSCompliantAttribute(false)]
public static global::Windows.Storage.Streams.IInputStream AsInputStream(this global::System.IO.Stream stream) { throw null; }
[global::System.CLSCompliantAttribute(false)]
public static global::Windows.Storage.Streams.IOutputStream AsOutputStream(this global::System.IO.Stream stream) { throw null; }
[global::System.CLSCompliantAttribute(false)]
public static global::Windows.Storage.Streams.IRandomAccessStream AsRandomAccessStream(this global::System.IO.Stream stream) { throw null; }
[global::System.CLSCompliantAttribute(false)]
public static global::System.IO.Stream AsStream(this global::Windows.Storage.Streams.IRandomAccessStream windowsRuntimeStream) { throw null; }
[global::System.CLSCompliantAttribute(false)]
public static global::System.IO.Stream AsStream(this global::Windows.Storage.Streams.IRandomAccessStream windowsRuntimeStream, int bufferSize) { throw null; }
[global::System.CLSCompliantAttribute(false)]
public static global::System.IO.Stream AsStreamForRead(this global::Windows.Storage.Streams.IInputStream windowsRuntimeStream) { throw null; }
[global::System.CLSCompliantAttribute(false)]
public static global::System.IO.Stream AsStreamForRead(this global::Windows.Storage.Streams.IInputStream windowsRuntimeStream, int bufferSize) { throw null; }
[global::System.CLSCompliantAttribute(false)]
public static global::System.IO.Stream AsStreamForWrite(this global::Windows.Storage.Streams.IOutputStream windowsRuntimeStream) { throw null; }
[global::System.CLSCompliantAttribute(false)]
public static global::System.IO.Stream AsStreamForWrite(this global::Windows.Storage.Streams.IOutputStream windowsRuntimeStream, int bufferSize) { throw null; }
}
}
namespace System.Runtime.InteropServices.WindowsRuntime
{
[global::System.CLSCompliantAttribute(false)]
public static partial class AsyncInfo
{
public static global::Windows.Foundation.IAsyncAction Run(global::System.Func<global::System.Threading.CancellationToken, global::System.Threading.Tasks.Task> taskProvider) { throw null; }
public static global::Windows.Foundation.IAsyncActionWithProgress<TProgress> Run<TProgress>(global::System.Func<global::System.Threading.CancellationToken, global::System.IProgress<TProgress>, global::System.Threading.Tasks.Task> taskProvider) { throw null; }
public static global::Windows.Foundation.IAsyncOperation<TResult> Run<TResult>(global::System.Func<global::System.Threading.CancellationToken, global::System.Threading.Tasks.Task<TResult>> taskProvider) { throw null; }
public static global::Windows.Foundation.IAsyncOperationWithProgress<TResult, TProgress> Run<TResult, TProgress>(global::System.Func<global::System.Threading.CancellationToken, global::System.IProgress<TProgress>, global::System.Threading.Tasks.Task<TResult>> taskProvider) { throw null; }
}
public sealed partial class WindowsRuntimeBuffer
{
internal WindowsRuntimeBuffer() { }
[global::System.CLSCompliantAttribute(false)]
public static global::Windows.Storage.Streams.IBuffer Create(byte[] data, int offset, int length, int capacity) { throw null; }
[global::System.CLSCompliantAttribute(false)]
public static global::Windows.Storage.Streams.IBuffer Create(int capacity) { throw null; }
}
public static partial class WindowsRuntimeBufferExtensions
{
[global::System.CLSCompliantAttribute(false)]
public static global::Windows.Storage.Streams.IBuffer AsBuffer(this byte[] source) { throw null; }
[global::System.CLSCompliantAttribute(false)]
public static global::Windows.Storage.Streams.IBuffer AsBuffer(this byte[] source, int offset, int length) { throw null; }
[global::System.CLSCompliantAttribute(false)]
public static global::Windows.Storage.Streams.IBuffer AsBuffer(this byte[] source, int offset, int length, int capacity) { throw null; }
[global::System.CLSCompliantAttribute(false)]
public static global::System.IO.Stream AsStream(this global::Windows.Storage.Streams.IBuffer source) { throw null; }
[global::System.CLSCompliantAttribute(false)]
public static void CopyTo(this byte[] source, int sourceIndex, global::Windows.Storage.Streams.IBuffer destination, uint destinationIndex, int count) { }
[global::System.CLSCompliantAttribute(false)]
public static void CopyTo(this byte[] source, global::Windows.Storage.Streams.IBuffer destination) { }
[global::System.CLSCompliantAttribute(false)]
public static void CopyTo(this global::Windows.Storage.Streams.IBuffer source, byte[] destination) { }
[global::System.CLSCompliantAttribute(false)]
public static void CopyTo(this global::Windows.Storage.Streams.IBuffer source, uint sourceIndex, byte[] destination, int destinationIndex, int count) { }
[global::System.CLSCompliantAttribute(false)]
public static void CopyTo(this global::Windows.Storage.Streams.IBuffer source, uint sourceIndex, global::Windows.Storage.Streams.IBuffer destination, uint destinationIndex, uint count) { }
[global::System.CLSCompliantAttribute(false)]
public static void CopyTo(this global::Windows.Storage.Streams.IBuffer source, global::Windows.Storage.Streams.IBuffer destination) { }
[global::System.CLSCompliantAttribute(false)]
public static byte GetByte(this global::Windows.Storage.Streams.IBuffer source, uint byteOffset) { throw null; }
[global::System.CLSCompliantAttribute(false)]
public static global::Windows.Storage.Streams.IBuffer GetWindowsRuntimeBuffer(this global::System.IO.MemoryStream underlyingStream) { throw null; }
[global::System.CLSCompliantAttribute(false)]
public static global::Windows.Storage.Streams.IBuffer GetWindowsRuntimeBuffer(this global::System.IO.MemoryStream underlyingStream, int positionInStream, int length) { throw null; }
[global::System.CLSCompliantAttribute(false)]
public static bool IsSameData(this global::Windows.Storage.Streams.IBuffer buffer, global::Windows.Storage.Streams.IBuffer otherBuffer) { throw null; }
[global::System.CLSCompliantAttribute(false)]
public static byte[] ToArray(this global::Windows.Storage.Streams.IBuffer source) { throw null; }
[global::System.CLSCompliantAttribute(false)]
public static byte[] ToArray(this global::Windows.Storage.Streams.IBuffer source, uint sourceIndex, int count) { throw null; }
}
}
namespace Windows.Foundation
{
public partial struct Point
{
private int _dummy;
public Point(double x, double y) { throw null; }
public double X { get { throw null; } set { } }
public double Y { get { throw null; } set { } }
public override bool Equals(object o) { throw null; }
public bool Equals(global::Windows.Foundation.Point value) { throw null; }
public override int GetHashCode() { throw null; }
public static bool operator ==(global::Windows.Foundation.Point point1, global::Windows.Foundation.Point point2) { throw null; }
public static bool operator !=(global::Windows.Foundation.Point point1, global::Windows.Foundation.Point point2) { throw null; }
public override string ToString() { throw null; }
public string ToString(global::System.IFormatProvider provider) { throw null; }
}
public partial struct Rect
{
private int _dummy;
public Rect(double x, double y, double width, double height) { throw null; }
public Rect(global::Windows.Foundation.Point point1, global::Windows.Foundation.Point point2) { throw null; }
public Rect(global::Windows.Foundation.Point location, global::Windows.Foundation.Size size) { throw null; }
public double Bottom { get { throw null; } }
public static global::Windows.Foundation.Rect Empty { get { throw null; } }
public double Height { get { throw null; } set { } }
public bool IsEmpty { get { throw null; } }
public double Left { get { throw null; } }
public double Right { get { throw null; } }
public double Top { get { throw null; } }
public double Width { get { throw null; } set { } }
public double X { get { throw null; } set { } }
public double Y { get { throw null; } set { } }
public bool Contains(global::Windows.Foundation.Point point) { throw null; }
public override bool Equals(object o) { throw null; }
public bool Equals(global::Windows.Foundation.Rect value) { throw null; }
public override int GetHashCode() { throw null; }
public void Intersect(global::Windows.Foundation.Rect rect) { }
public static bool operator ==(global::Windows.Foundation.Rect rect1, global::Windows.Foundation.Rect rect2) { throw null; }
public static bool operator !=(global::Windows.Foundation.Rect rect1, global::Windows.Foundation.Rect rect2) { throw null; }
public override string ToString() { throw null; }
public string ToString(global::System.IFormatProvider provider) { throw null; }
public void Union(global::Windows.Foundation.Point point) { }
public void Union(global::Windows.Foundation.Rect rect) { }
}
public partial struct Size
{
private int _dummy;
public Size(double width, double height) { throw null; }
public static global::Windows.Foundation.Size Empty { get { throw null; } }
public double Height { get { throw null; } set { } }
public bool IsEmpty { get { throw null; } }
public double Width { get { throw null; } set { } }
public override bool Equals(object o) { throw null; }
public bool Equals(global::Windows.Foundation.Size value) { throw null; }
public override int GetHashCode() { throw null; }
public static bool operator ==(global::Windows.Foundation.Size size1, global::Windows.Foundation.Size size2) { throw null; }
public static bool operator !=(global::Windows.Foundation.Size size1, global::Windows.Foundation.Size size2) { throw null; }
public override string ToString() { throw null; }
}
}
namespace Windows.UI
{
public partial struct Color
{
private int _dummy;
public byte A { get { throw null; } set { } }
public byte B { get { throw null; } set { } }
public byte G { get { throw null; } set { } }
public byte R { get { throw null; } set { } }
public override bool Equals(object o) { throw null; }
public bool Equals(global::Windows.UI.Color color) { throw null; }
public static global::Windows.UI.Color FromArgb(byte a, byte r, byte g, byte b) { throw null; }
public override int GetHashCode() { throw null; }
public static bool operator ==(global::Windows.UI.Color color1, global::Windows.UI.Color color2) { throw null; }
public static bool operator !=(global::Windows.UI.Color color1, global::Windows.UI.Color color2) { throw null; }
public override string ToString() { throw null; }
public string ToString(global::System.IFormatProvider provider) { throw null; }
}
}
| |
/* ====================================================================
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.
==================================================================== */
/*
* TestCellStyle.java
*
* Created on December 11, 2001, 5:51 PM
*/
namespace TestCases.HSSF.UserModel
{
using System;
using System.IO;
using NPOI.Util;
using NPOI.HSSF.UserModel;
using NUnit.Framework;
using TestCases.HSSF;
using NPOI.SS.UserModel;
using NPOI.HSSF.Util;
/**
* Class to Test cell styling functionality
*
* @author Andrew C. Oliver
*/
[TestFixture]
public class TestCellStyle
{
private static HSSFWorkbook OpenSample(String sampleFileName)
{
return HSSFTestDataSamples.OpenSampleWorkbook(sampleFileName);
}
/** Creates a new instance of TestCellStyle */
public TestCellStyle()
{
}
/**
* TEST NAME: Test Write Sheet Font <P>
* OBJECTIVE: Test that HSSF can Create a simple spreadsheet with numeric and string values and styled with fonts.<P>
* SUCCESS: HSSF Creates a sheet. Filesize Matches a known good. NPOI.SS.UserModel.Sheet objects
* Last row, first row is Tested against the correct values (99,0).<P>
* FAILURE: HSSF does not Create a sheet or excepts. Filesize does not Match the known good.
* NPOI.SS.UserModel.Sheet last row or first row is incorrect. <P>
*
*/
[Test]
public void TestWriteSheetFont()
{
string filepath = TempFile.GetTempFilePath("TestWriteSheetFont",
".xls");
FileStream out1 = new FileStream(filepath,FileMode.OpenOrCreate);
HSSFWorkbook wb = new HSSFWorkbook();
NPOI.SS.UserModel.ISheet s = wb.CreateSheet();
IRow r = null;
ICell c = null;
IFont fnt = wb.CreateFont();
NPOI.SS.UserModel.ICellStyle cs = wb.CreateCellStyle();
fnt.Color=(HSSFColor.Red.Index);
fnt.Boldweight= (short)FontBoldWeight.Bold;
cs.SetFont(fnt);
for (short rownum = ( short ) 0; rownum < 100; rownum++)
{
r = s.CreateRow(rownum);
// r.SetRowNum(( short ) rownum);
for (short cellnum = ( short ) 0; cellnum < 50; cellnum += 2)
{
c = r.CreateCell(cellnum);
c.SetCellValue(rownum * 10000 + cellnum
+ ((( double ) rownum / 1000)
+ (( double ) cellnum / 10000)));
c = r.CreateCell(cellnum + 1);
c.SetCellValue("TEST");
c.CellStyle = (cs);
}
}
wb.Write(out1);
out1.Close();
SanityChecker sanityChecker = new SanityChecker();
sanityChecker.CheckHSSFWorkbook(wb);
Assert.AreEqual(99, s.LastRowNum, "LAST ROW == 99");
Assert.AreEqual(0, s.FirstRowNum, "FIRST ROW == 0");
// assert((s.LastRowNum == 99));
}
/**
* Tests that is creating a file with a date or an calendar works correctly.
*/
[Test]
public void TestDataStyle()
{
string filepath = TempFile.GetTempFilePath("TestWriteSheetStyleDate",
".xls");
FileStream out1 = new FileStream(filepath,FileMode.OpenOrCreate);
HSSFWorkbook wb = new HSSFWorkbook();
NPOI.SS.UserModel.ISheet s = wb.CreateSheet();
NPOI.SS.UserModel.ICellStyle cs = wb.CreateCellStyle();
IRow row = s.CreateRow(0);
// with Date:
ICell cell = row.CreateCell(1);
cs.DataFormat=(HSSFDataFormat.GetBuiltinFormat("m/d/yy"));
cell.CellStyle = (cs);
cell.SetCellValue(DateTime.Now);
// with Calendar:
cell = row.CreateCell(2);
cs.DataFormat=(HSSFDataFormat.GetBuiltinFormat("m/d/yy"));
cell.CellStyle = (cs);
cell.SetCellValue(DateTime.Now);
wb.Write(out1);
out1.Close();
SanityChecker sanityChecker = new SanityChecker();
sanityChecker.CheckHSSFWorkbook(wb);
Assert.AreEqual(0, s.LastRowNum, "LAST ROW ");
Assert.AreEqual(0, s.FirstRowNum,"FIRST ROW ");
}
[Test]
public void TestHashEquals()
{
HSSFWorkbook wb = new HSSFWorkbook();
NPOI.SS.UserModel.ISheet s = wb.CreateSheet();
NPOI.SS.UserModel.ICellStyle cs1 = wb.CreateCellStyle();
NPOI.SS.UserModel.ICellStyle cs2 = wb.CreateCellStyle();
IRow row = s.CreateRow(0);
ICell cell1 = row.CreateCell(1);
ICell cell2 = row.CreateCell(2);
cs1.DataFormat = (HSSFDataFormat.GetBuiltinFormat("m/d/yy"));
cs2.DataFormat = (HSSFDataFormat.GetBuiltinFormat("m/dd/yy"));
cell1.CellStyle = (cs1);
cell1.SetCellValue(DateTime.Now);
cell2.CellStyle = (cs2);
cell2.SetCellValue(DateTime.Now);
Assert.AreEqual(cs1.GetHashCode(), cs1.GetHashCode());
Assert.AreEqual(cs2.GetHashCode(), cs2.GetHashCode());
Assert.IsTrue(cs1.Equals(cs1));
Assert.IsTrue(cs2.Equals(cs2));
// Change cs1, hash will alter
int hash1 = cs1.GetHashCode();
cs1.DataFormat = (HSSFDataFormat.GetBuiltinFormat("m/dd/yy"));
Assert.IsFalse(hash1 == cs1.GetHashCode());
wb.Close();
}
/**
* TEST NAME: Test Write Sheet Style <P>
* OBJECTIVE: Test that HSSF can Create a simple spreadsheet with numeric and string values and styled with colors
* and borders.<P>
* SUCCESS: HSSF Creates a sheet. Filesize Matches a known good. NPOI.SS.UserModel.Sheet objects
* Last row, first row is Tested against the correct values (99,0).<P>
* FAILURE: HSSF does not Create a sheet or excepts. Filesize does not Match the known good.
* NPOI.SS.UserModel.Sheet last row or first row is incorrect. <P>
*
*/
[Test]
public void TestWriteSheetStyle()
{
string filepath = TempFile.GetTempFilePath("TestWriteSheetStyle",
".xls");
FileStream out1 = new FileStream(filepath,FileMode.OpenOrCreate);
HSSFWorkbook wb = new HSSFWorkbook();
NPOI.SS.UserModel.ISheet s = wb.CreateSheet();
IRow r = null;
ICell c = null;
IFont fnt = wb.CreateFont();
NPOI.SS.UserModel.ICellStyle cs = wb.CreateCellStyle();
NPOI.SS.UserModel.ICellStyle cs2 = wb.CreateCellStyle();
cs.BorderBottom= (BorderStyle.Thin);
cs.BorderLeft= (BorderStyle.Thin);
cs.BorderRight= (BorderStyle.Thin);
cs.BorderTop= (BorderStyle.Thin);
cs.FillForegroundColor= ( short ) 0xA;
cs.FillPattern = FillPattern.SolidForeground;
fnt.Color= ( short ) 0xf;
fnt.IsItalic= (true);
cs2.FillForegroundColor= ( short ) 0x0;
cs2.FillPattern= FillPattern.SolidForeground;
cs2.SetFont(fnt);
for (short rownum = ( short ) 0; rownum < 100; rownum++)
{
r = s.CreateRow(rownum);
// r.SetRowNum(( short ) rownum);
for (short cellnum = ( short ) 0; cellnum < 50; cellnum += 2)
{
c = r.CreateCell(cellnum);
c.SetCellValue(rownum * 10000 + cellnum
+ ((( double ) rownum / 1000)
+ (( double ) cellnum / 10000)));
c.CellStyle = (cs);
c = r.CreateCell(cellnum + 1);
c.SetCellValue("TEST");
c.CellStyle = (cs2);
}
}
wb.Write(out1);
out1.Close();
SanityChecker sanityChecker = new SanityChecker();
sanityChecker.CheckHSSFWorkbook(wb);
Assert.AreEqual(99, s.LastRowNum, "LAST ROW == 99");
Assert.AreEqual(0, s.FirstRowNum, "FIRST ROW == 0");
// assert((s.LastRowNum == 99));
}
/**
* Cloning one NPOI.SS.UserModel.CellType onto Another, same
* HSSFWorkbook
*/
[Test]
public void TestCloneStyleSameWB()
{
HSSFWorkbook wb = new HSSFWorkbook();
IFont fnt = wb.CreateFont();
fnt.FontName=("TestingFont");
Assert.AreEqual(5, wb.NumberOfFonts);
NPOI.SS.UserModel.ICellStyle orig = wb.CreateCellStyle();
orig.Alignment=(HorizontalAlignment.Right);
orig.SetFont(fnt);
orig.DataFormat=((short)18);
Assert.AreEqual(HorizontalAlignment.Right,orig.Alignment);
Assert.AreEqual(fnt,orig.GetFont(wb));
Assert.AreEqual(18,orig.DataFormat);
NPOI.SS.UserModel.ICellStyle clone = wb.CreateCellStyle();
Assert.AreNotEqual(HorizontalAlignment.Right , clone.Alignment);
Assert.AreNotEqual(fnt, clone.GetFont(wb));
Assert.AreNotEqual(18, clone.DataFormat);
clone.CloneStyleFrom(orig);
Assert.AreEqual(HorizontalAlignment.Right, orig.Alignment);
Assert.AreEqual(fnt, clone.GetFont(wb));
Assert.AreEqual(18, clone.DataFormat);
Assert.AreEqual(5, wb.NumberOfFonts);
orig.Alignment = HorizontalAlignment.Left;
Assert.AreEqual(HorizontalAlignment.Right, clone.Alignment);
}
/**
* Cloning one NPOI.SS.UserModel.CellType onto Another, across
* two different HSSFWorkbooks
*/
[Test]
public void TestCloneStyleDiffWB()
{
HSSFWorkbook wbOrig = new HSSFWorkbook();
IFont fnt = wbOrig.CreateFont();
fnt.FontName=("TestingFont");
Assert.AreEqual(5, wbOrig.NumberOfFonts);
IDataFormat fmt = wbOrig.CreateDataFormat();
fmt.GetFormat("MadeUpOne");
fmt.GetFormat("MadeUpTwo");
NPOI.SS.UserModel.ICellStyle orig = wbOrig.CreateCellStyle();
orig.Alignment = (HorizontalAlignment.Right);
orig.SetFont(fnt);
orig.DataFormat=(fmt.GetFormat("Test##"));
Assert.AreEqual(HorizontalAlignment.Right, orig.Alignment);
Assert.AreEqual(fnt,orig.GetFont(wbOrig));
Assert.AreEqual(fmt.GetFormat("Test##") , orig.DataFormat);
// Now a style on another workbook
HSSFWorkbook wbClone = new HSSFWorkbook();
Assert.AreEqual(4, wbClone.NumberOfFonts);
IDataFormat fmtClone = wbClone.CreateDataFormat();
NPOI.SS.UserModel.ICellStyle clone = wbClone.CreateCellStyle();
Assert.AreEqual(4, wbClone.NumberOfFonts);
Assert.AreNotEqual(HorizontalAlignment.Right,clone.Alignment);
Assert.AreNotEqual("TestingFont", clone.GetFont(wbClone).FontName);
clone.CloneStyleFrom(orig);
Assert.AreEqual(HorizontalAlignment.Right, clone.Alignment);
Assert.AreEqual("TestingFont" ,clone.GetFont(wbClone).FontName);
Assert.AreEqual(fmtClone.GetFormat("Test##"),clone.DataFormat);
Assert.AreNotEqual(fmtClone.GetFormat("Test##") , fmt.GetFormat("Test##"));
Assert.AreEqual(5, wbClone.NumberOfFonts);
}
[Test]
public void TestStyleNames()
{
HSSFWorkbook wb = OpenSample("WithExtendedStyles.xls");
NPOI.SS.UserModel.ISheet s = wb.GetSheetAt(0);
ICell c1 = s.GetRow(0).GetCell(0);
ICell c2 = s.GetRow(1).GetCell(0);
ICell c3 = s.GetRow(2).GetCell(0);
HSSFCellStyle cs1 = (HSSFCellStyle)c1.CellStyle;
HSSFCellStyle cs2 = (HSSFCellStyle)c2.CellStyle;
HSSFCellStyle cs3 = (HSSFCellStyle)c3.CellStyle;
Assert.IsNotNull(cs1);
Assert.IsNotNull(cs2);
Assert.IsNotNull(cs3);
// Check we got the styles we'd expect
Assert.AreEqual(10, cs1.GetFont(wb).FontHeightInPoints);
Assert.AreEqual(9, cs2.GetFont(wb).FontHeightInPoints);
Assert.AreEqual(12, cs3.GetFont(wb).FontHeightInPoints);
Assert.AreEqual(15, cs1.Index);
Assert.AreEqual(23, cs2.Index);
Assert.AreEqual(24, cs3.Index);
Assert.IsNull(cs1.ParentStyle);
Assert.IsNotNull(cs2.ParentStyle);
Assert.IsNotNull(cs3.ParentStyle);
Assert.AreEqual(21, cs2.ParentStyle.Index);
Assert.AreEqual(22, cs3.ParentStyle.Index);
// Now Check we can get style records for
// the parent ones
Assert.IsNull(wb.Workbook.GetStyleRecord(15));
Assert.IsNull(wb.Workbook.GetStyleRecord(23));
Assert.IsNull(wb.Workbook.GetStyleRecord(24));
Assert.IsNotNull(wb.Workbook.GetStyleRecord(21));
Assert.IsNotNull(wb.Workbook.GetStyleRecord(22));
// Now Check the style names
Assert.AreEqual(null, cs1.UserStyleName);
Assert.AreEqual(null, cs2.UserStyleName);
Assert.AreEqual(null, cs3.UserStyleName);
Assert.AreEqual("style1", cs2.ParentStyle.UserStyleName);
Assert.AreEqual("style2", cs3.ParentStyle.UserStyleName);
// now apply a named style to a new cell
ICell c4 = s.GetRow(0).CreateCell(1);
c4.CellStyle = (cs2);
Assert.AreEqual("style1", ((HSSFCellStyle)c4.CellStyle).ParentStyle.UserStyleName);
}
[Test]
public void TestGetSetBorderHair()
{
HSSFWorkbook wb = OpenSample("55341_CellStyleBorder.xls");
ISheet s = wb.GetSheetAt(0);
ICellStyle cs;
cs = s.GetRow(0).GetCell(0).CellStyle;
Assert.AreEqual(BorderStyle.Hair, cs.BorderRight);
cs = s.GetRow(1).GetCell(1).CellStyle;
Assert.AreEqual(BorderStyle.Dotted, cs.BorderRight);
cs = s.GetRow(2).GetCell(2).CellStyle;
Assert.AreEqual(BorderStyle.DashDotDot, cs.BorderRight);
cs = s.GetRow(3).GetCell(3).CellStyle;
Assert.AreEqual(BorderStyle.Dashed, cs.BorderRight);
cs = s.GetRow(4).GetCell(4).CellStyle;
Assert.AreEqual(BorderStyle.Thin, cs.BorderRight);
cs = s.GetRow(5).GetCell(5).CellStyle;
Assert.AreEqual(BorderStyle.MediumDashDotDot, cs.BorderRight);
cs = s.GetRow(6).GetCell(6).CellStyle;
Assert.AreEqual(BorderStyle.SlantedDashDot, cs.BorderRight);
cs = s.GetRow(7).GetCell(7).CellStyle;
Assert.AreEqual(BorderStyle.MediumDashDot, cs.BorderRight);
cs = s.GetRow(8).GetCell(8).CellStyle;
Assert.AreEqual(BorderStyle.MediumDashed, cs.BorderRight);
cs = s.GetRow(9).GetCell(9).CellStyle;
Assert.AreEqual(BorderStyle.Medium, cs.BorderRight);
cs = s.GetRow(10).GetCell(10).CellStyle;
Assert.AreEqual(BorderStyle.Thick, cs.BorderRight);
cs = s.GetRow(11).GetCell(11).CellStyle;
Assert.AreEqual(BorderStyle.Double, cs.BorderRight);
}
[Test]
public void TestShrinkToFit()
{
// Existing file
IWorkbook wb = OpenSample("ShrinkToFit.xls");
ISheet s = wb.GetSheetAt(0);
IRow r = s.GetRow(0);
ICellStyle cs = r.GetCell(0).CellStyle;
Assert.AreEqual(true, cs.ShrinkToFit);
// New file
IWorkbook wbOrig = new HSSFWorkbook();
s = wbOrig.CreateSheet();
r = s.CreateRow(0);
cs = wbOrig.CreateCellStyle();
cs.ShrinkToFit = (/*setter*/false);
r.CreateCell(0).CellStyle = (/*setter*/cs);
cs = wbOrig.CreateCellStyle();
cs.ShrinkToFit = (/*setter*/true);
r.CreateCell(1).CellStyle = (/*setter*/cs);
// Write out1, Read, and check
wb = HSSFTestDataSamples.WriteOutAndReadBack(wbOrig as HSSFWorkbook);
s = wb.GetSheetAt(0);
r = s.GetRow(0);
Assert.AreEqual(false, r.GetCell(0).CellStyle.ShrinkToFit);
Assert.AreEqual(true, r.GetCell(1).CellStyle.ShrinkToFit);
}
[Test]
public void Test56959()
{
IWorkbook wb = new HSSFWorkbook();
ISheet sheet = wb.CreateSheet("somesheet");
IRow row = sheet.CreateRow(0);
// Create a new font and alter it.
IFont font = wb.CreateFont();
font.FontHeightInPoints = ((short)24);
font.FontName = ("Courier New");
font.IsItalic = (true);
font.IsStrikeout = (true);
font.Color = (HSSFColor.Red.Index);
ICellStyle style = wb.CreateCellStyle();
style.BorderBottom = BorderStyle.Dotted;
style.SetFont(font);
ICell cell = row.CreateCell(0);
cell.CellStyle = (style);
cell.SetCellValue("testtext");
ICell newCell = row.CreateCell(1);
newCell.CellStyle = (style);
newCell.SetCellValue("2testtext2");
ICellStyle newStyle = newCell.CellStyle;
Assert.AreEqual(BorderStyle.Dotted, newStyle.BorderBottom);
Assert.AreEqual(HSSFColor.Red.Index, ((HSSFCellStyle)newStyle).GetFont(wb).Color);
// OutputStream out = new FileOutputStream("/tmp/56959.xls");
// try {
// wb.write(out);
// } finally {
// out.close();
// }
}
[Test]
public void Test58043()
{
HSSFWorkbook wb = new HSSFWorkbook();
HSSFCellStyle cellStyle = wb.CreateCellStyle() as HSSFCellStyle;
Assert.AreEqual(0, cellStyle.Rotation);
cellStyle.Rotation = ((short)89);
Assert.AreEqual(89, cellStyle.Rotation);
cellStyle.Rotation = ((short)90);
Assert.AreEqual(90, cellStyle.Rotation);
cellStyle.Rotation = ((short)-1);
Assert.AreEqual(-1, cellStyle.Rotation);
cellStyle.Rotation = ((short)-89);
Assert.AreEqual(-89, cellStyle.Rotation);
cellStyle.Rotation = ((short)-90);
Assert.AreEqual(-90, cellStyle.Rotation);
cellStyle.Rotation = ((short)-89);
Assert.AreEqual(-89, cellStyle.Rotation);
// values above 90 are mapped to the correct values for compatibility between HSSF and XSSF
cellStyle.Rotation = ((short)179);
Assert.AreEqual(-89, cellStyle.Rotation);
cellStyle.Rotation = ((short)180);
Assert.AreEqual(-90, cellStyle.Rotation);
wb.Close();
}
}
}
| |
// Copyright (c) 2010-2013 SharpDX - Alexandre Mutel
//
// 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 SharpDX.IO;
using SharpDX.Win32;
namespace SharpDX.WIC
{
public partial class BitmapDecoder
{
private WICStream internalWICStream;
/// <summary>
/// Initializes a new instance of the <see cref="BitmapDecoder"/> class from a <see cref="BitmapDecoderInfo"/>.
/// </summary>
/// <param name="bitmapDecoderInfo">The bitmap decoder info.</param>
/// <unmanaged>HRESULT IWICBitmapDecoderInfo::CreateInstance([Out, Fast] IWICBitmapDecoder** ppIBitmapDecoder)</unmanaged>
public BitmapDecoder(BitmapDecoderInfo bitmapDecoderInfo)
{
bitmapDecoderInfo.CreateInstance(this);
}
/// <summary>
/// Initializes a new instance of the <see cref="BitmapDecoder"/> class from a guid. <see cref="BitmapDecoderGuids"/> for a list of default supported decoder.
/// </summary>
/// <param name="factory">The factory.</param>
/// <param name="containerFormatGuid">The container format GUID.</param>
/// <unmanaged>HRESULT IWICImagingFactory::CreateDecoder([In] const GUID& guidContainerFormat,[In, Optional] const GUID* pguidVendor,[Out, Fast] IWICBitmapDecoder** ppIDecoder)</unmanaged>
public BitmapDecoder(ImagingFactory factory, Guid containerFormatGuid)
{
factory.CreateDecoder(containerFormatGuid, null, this);
}
/// <summary>
/// Initializes a new instance of the <see cref="BitmapDecoder"/> class.
/// </summary>
/// <param name="factory">The factory.</param>
/// <param name="containerFormatGuid">The container format GUID.</param>
/// <param name="guidVendorRef">The GUID vendor ref.</param>
/// <unmanaged>HRESULT IWICImagingFactory::CreateDecoder([In] const GUID& guidContainerFormat,[In, Optional] const GUID* pguidVendor,[Out, Fast] IWICBitmapDecoder** ppIDecoder)</unmanaged>
public BitmapDecoder(ImagingFactory factory, Guid containerFormatGuid, System.Guid guidVendorRef)
{
factory.CreateDecoder(containerFormatGuid, guidVendorRef, this);
}
/// <summary>
/// Initializes a new instance of the <see cref="BitmapDecoder"/> class from a <see cref="IStream"/>.
/// </summary>
/// <param name="factory">The factory.</param>
/// <param name="streamRef">The stream ref.</param>
/// <param name="metadataOptions">The metadata options.</param>
/// <unmanaged>HRESULT IWICImagingFactory::CreateDecoderFromStream([In, Optional] IStream* pIStream,[In, Optional] const GUID* pguidVendor,[In] WICDecodeOptions metadataOptions,[Out, Fast] IWICBitmapDecoder** ppIDecoder)</unmanaged>
public BitmapDecoder(ImagingFactory factory, IStream streamRef, SharpDX.WIC.DecodeOptions metadataOptions)
{
factory.CreateDecoderFromStream_(ComStream.ToIntPtr(streamRef), null, metadataOptions, this);
}
/// <summary>
/// Initializes a new instance of the <see cref="BitmapDecoder"/> class from a <see cref="IStream"/>.
/// </summary>
/// <param name="factory">The factory.</param>
/// <param name="streamRef">The stream ref.</param>
/// <param name="metadataOptions">The metadata options.</param>
/// <unmanaged>HRESULT IWICImagingFactory::CreateDecoderFromStream([In, Optional] IStream* pIStream,[In, Optional] const GUID* pguidVendor,[In] WICDecodeOptions metadataOptions,[Out, Fast] IWICBitmapDecoder** ppIDecoder)</unmanaged>
public BitmapDecoder(ImagingFactory factory, Stream streamRef, SharpDX.WIC.DecodeOptions metadataOptions)
{
internalWICStream = new WICStream(factory, streamRef);
factory.CreateDecoderFromStream_(ComStream.ToIntPtr(internalWICStream), null, metadataOptions, this);
}
/// <summary>
/// Initializes a new instance of the <see cref="BitmapDecoder"/> class from a <see cref="IStream"/>.
/// </summary>
/// <param name="factory">The factory.</param>
/// <param name="streamRef">The stream ref.</param>
/// <param name="guidVendorRef">The GUID vendor ref.</param>
/// <param name="metadataOptions">The metadata options.</param>
/// <unmanaged>HRESULT IWICImagingFactory::CreateDecoderFromStream([In, Optional] IStream* pIStream,[In, Optional] const GUID* pguidVendor,[In] WICDecodeOptions metadataOptions,[Out, Fast] IWICBitmapDecoder** ppIDecoder)</unmanaged>
public BitmapDecoder(ImagingFactory factory, IStream streamRef, System.Guid guidVendorRef, SharpDX.WIC.DecodeOptions metadataOptions)
{
factory.CreateDecoderFromStream_(ComStream.ToIntPtr(streamRef), guidVendorRef, metadataOptions, this);
}
/// <summary>
/// Initializes a new instance of the <see cref="BitmapDecoder"/> class from a <see cref="IStream"/>.
/// </summary>
/// <param name="factory">The factory.</param>
/// <param name="streamRef">The stream ref.</param>
/// <param name="guidVendorRef">The GUID vendor ref.</param>
/// <param name="metadataOptions">The metadata options.</param>
/// <unmanaged>HRESULT IWICImagingFactory::CreateDecoderFromStream([In, Optional] IStream* pIStream,[In, Optional] const GUID* pguidVendor,[In] WICDecodeOptions metadataOptions,[Out, Fast] IWICBitmapDecoder** ppIDecoder)</unmanaged>
public BitmapDecoder(ImagingFactory factory, Stream streamRef, System.Guid guidVendorRef, SharpDX.WIC.DecodeOptions metadataOptions)
{
internalWICStream = new WICStream(factory, streamRef);
factory.CreateDecoderFromStream_(ComStream.ToIntPtr(internalWICStream), guidVendorRef, metadataOptions, this);
}
/// <summary>
/// Initializes a new instance of the <see cref="BitmapDecoder"/> class from a file in read mode.
/// </summary>
/// <param name="factory">The factory.</param>
/// <param name="filename">The filename.</param>
/// <param name="metadataOptions">The metadata options.</param>
/// <unmanaged>HRESULT IWICImagingFactory::CreateDecoderFromFilename([In] const wchar_t* wzFilename,[In, Optional] const GUID* pguidVendor,[In] unsigned int dwDesiredAccess,[In] WICDecodeOptions metadataOptions,[Out, Fast] IWICBitmapDecoder** ppIDecoder)</unmanaged>
public BitmapDecoder(ImagingFactory factory, string filename, SharpDX.WIC.DecodeOptions metadataOptions)
: this(factory, filename, null, NativeFileAccess.Read, metadataOptions)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="BitmapDecoder"/> class from a file.
/// </summary>
/// <param name="factory">The factory.</param>
/// <param name="filename">The filename.</param>
/// <param name="desiredAccess">The desired access.</param>
/// <param name="metadataOptions">The metadata options.</param>
/// <unmanaged>HRESULT IWICImagingFactory::CreateDecoderFromFilename([In] const wchar_t* wzFilename,[In, Optional] const GUID* pguidVendor,[In] unsigned int dwDesiredAccess,[In] WICDecodeOptions metadataOptions,[Out, Fast] IWICBitmapDecoder** ppIDecoder)</unmanaged>
public BitmapDecoder(ImagingFactory factory, string filename, NativeFileAccess desiredAccess, SharpDX.WIC.DecodeOptions metadataOptions) : this(factory, filename, null, desiredAccess, metadataOptions)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="BitmapDecoder"/> class from a file.
/// </summary>
/// <param name="factory">The factory.</param>
/// <param name="filename">The filename.</param>
/// <param name="guidVendorRef">The GUID vendor ref.</param>
/// <param name="desiredAccess">The desired access.</param>
/// <param name="metadataOptions">The metadata options.</param>
/// <unmanaged>HRESULT IWICImagingFactory::CreateDecoderFromFilename([In] const wchar_t* wzFilename,[In, Optional] const GUID* pguidVendor,[In] unsigned int dwDesiredAccess,[In] WICDecodeOptions metadataOptions,[Out, Fast] IWICBitmapDecoder** ppIDecoder)</unmanaged>
public BitmapDecoder(ImagingFactory factory, string filename, System.Guid? guidVendorRef, NativeFileAccess desiredAccess, SharpDX.WIC.DecodeOptions metadataOptions)
{
factory.CreateDecoderFromFilename(filename, guidVendorRef, (int)desiredAccess, metadataOptions, this);
}
#if !WIN8METRO
/// <summary>
/// Initializes a new instance of the <see cref="BitmapDecoder"/> class from a file stream.
/// </summary>
/// <param name="factory">The factory.</param>
/// <param name="fileStream">The filename.</param>
/// <param name="metadataOptions">The metadata options.</param>
/// <unmanaged>HRESULT IWICImagingFactory::CreateDecoderFromFileHandle([In] unsigned int hFile,[In, Optional] const GUID* pguidVendor,[In] WICDecodeOptions metadataOptions,[Out, Fast] IWICBitmapDecoder** ppIDecoder)</unmanaged>
public BitmapDecoder(ImagingFactory factory, FileStream fileStream, SharpDX.WIC.DecodeOptions metadataOptions)
{
factory.CreateDecoderFromFileHandle(fileStream.SafeFileHandle.DangerousGetHandle(), null, metadataOptions, this);
}
/// <summary>
/// Initializes a new instance of the <see cref="BitmapDecoder"/> class from a file stream.
/// </summary>
/// <param name="factory">The factory.</param>
/// <param name="fileStream">The filename.</param>
/// <param name="guidVendorRef">The GUID vendor ref.</param>
/// <param name="metadataOptions">The metadata options.</param>
/// <unmanaged>HRESULT IWICImagingFactory::CreateDecoderFromFileHandle([In] unsigned int hFile,[In, Optional] const GUID* pguidVendor,[In] WICDecodeOptions metadataOptions,[Out, Fast] IWICBitmapDecoder** ppIDecoder)</unmanaged>
public BitmapDecoder(ImagingFactory factory, FileStream fileStream, System.Guid guidVendorRef, SharpDX.WIC.DecodeOptions metadataOptions)
{
factory.CreateDecoderFromFileHandle(fileStream.SafeFileHandle.DangerousGetHandle(), guidVendorRef, metadataOptions, this);
}
#endif
/// <summary>
/// Queries the capabilities of the decoder based on the specified stream.
/// </summary>
/// <param name="stream">The stream to retrieve the decoder capabilities from..</param>
/// <returns>Capabilities of the decoder</returns>
/// <unmanaged>HRESULT IWICBitmapDecoder::QueryCapability([In, Optional] IStream* pIStream,[Out] WICBitmapDecoderCapabilities* pdwCapability)</unmanaged>
public SharpDX.WIC.BitmapDecoderCapabilities QueryCapability(IStream stream)
{
return QueryCapability_(ComStream.ToIntPtr(stream));
}
/// <summary>
/// Initializes the decoder with the provided stream.
/// </summary>
/// <param name="stream">The stream to use for initialization.</param>
/// <param name="cacheOptions">The cache options.</param>
/// <returns>If the method succeeds, it returns <see cref="Result.Ok"/>. Otherwise, it throws an exception.</returns>
/// <unmanaged>HRESULT IWICBitmapDecoder::Initialize([In, Optional] IStream* pIStream,[In] WICDecodeOptions cacheOptions)</unmanaged>
public void Initialize(IStream stream, SharpDX.WIC.DecodeOptions cacheOptions)
{
if (this.internalWICStream != null)
throw new InvalidOperationException("This instance is already initialized with an existing stream");
Initialize_(ComStream.ToIntPtr(stream), cacheOptions);
}
protected override unsafe void Dispose(bool disposing)
{
base.Dispose(disposing);
if (disposing)
{
if (this.internalWICStream != null)
internalWICStream.Dispose();
internalWICStream = null;
}
}
/// <summary>
/// Get the <see cref="ColorContext"/> of the image (if any)
/// </summary>
/// <param name="imagingFactory">The factory for creating new color contexts</param>
/// <param name="colorContexts">The color context array, or null</param>
/// <remarks>
/// When the image format does not support color contexts,
/// <see cref="ResultCode.UnsupportedOperation"/> is returned.
/// </remarks>
/// <unmanaged>HRESULT IWICBitmapDecoder::GetColorContexts([In] unsigned int cCount,[Out, Buffer, Optional] IWICColorContext** ppIColorContexts,[Out] unsigned int* pcActualCount)</unmanaged>
public Result TryGetColorContexts(ImagingFactory imagingFactory, out ColorContext[] colorContexts)
{
return ColorContextsHelper.TryGetColorContexts(GetColorContexts, imagingFactory, out colorContexts);
}
/// <summary>
/// Get the <see cref="ColorContext"/> of the image (if any)
/// </summary>
/// <returns>
/// null if the decoder does not support color contexts;
/// otherwise an array of zero or more ColorContext objects
/// </returns>
/// <unmanaged>HRESULT IWICBitmapDecoder::GetColorContexts([In] unsigned int cCount,[Out, Buffer, Optional] IWICColorContext** ppIColorContexts,[Out] </unmanaged>
public ColorContext[] TryGetColorContexts(ImagingFactory imagingFactory)
{
return ColorContextsHelper.TryGetColorContexts(GetColorContexts, imagingFactory);
}
[Obsolete("Use TryGetColorContexts instead")]
public ColorContext[] ColorContexts
{
get { return new ColorContext[0]; }
}
}
}
| |
// Inflater.cs
//
// Copyright (C) 2001 Mike Krueger
// Copyright (C) 2004 John Reilly
//
// This file was translated from java, it was part of the GNU Classpath
// Copyright (C) 2001 Free Software Foundation, Inc.
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation; either version 2
// of the License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
//
// Linking this library statically or dynamically with other modules is
// making a combined work based on this library. Thus, the terms and
// conditions of the GNU General Public License cover the whole
// combination.
//
// As a special exception, the copyright holders of this library give you
// permission to link this library with independent modules to produce an
// executable, regardless of the license terms of these independent
// modules, and to copy and distribute the resulting executable under
// terms of your choice, provided that you also meet, for each linked
// independent module, the terms and conditions of the license of that
// module. An independent module is a module which is not derived from
// or based on this library. If you modify this library, you may extend
// this exception to your version of the library, but you are not
// obligated to do so. If you do not wish to do so, delete this
// exception statement from your version.
using System;
using ICSharpCode.SharpZipLib.Checksums;
using ICSharpCode.SharpZipLib.Zip.Compression.Streams;
namespace ICSharpCode.SharpZipLib.Zip.Compression
{
/// <summary>
/// Inflater is used to decompress data that has been compressed according
/// to the "deflate" standard described in rfc1951.
///
/// By default Zlib (rfc1950) headers and footers are expected in the input.
/// You can use constructor <code> public Inflater(bool noHeader)</code> passing true
/// if there is no Zlib header information
///
/// The usage is as following. First you have to set some input with
/// <code>setInput()</code>, then inflate() it. If inflate doesn't
/// inflate any bytes there may be three reasons:
/// <ul>
/// <li>needsInput() returns true because the input buffer is empty.
/// You have to provide more input with <code>setInput()</code>.
/// NOTE: needsInput() also returns true when, the stream is finished.
/// </li>
/// <li>needsDictionary() returns true, you have to provide a preset
/// dictionary with <code>setDictionary()</code>.</li>
/// <li>finished() returns true, the inflater has finished.</li>
/// </ul>
/// Once the first output byte is produced, a dictionary will not be
/// needed at a later stage.
///
/// author of the original java version : John Leuner, Jochen Hoenicke
/// </summary>
public class Inflater
{
/// <summary>
/// Copy lengths for literal codes 257..285
/// </summary>
static int[] CPLENS = {
3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258
};
/// <summary>
/// Extra bits for literal codes 257..285
/// </summary>
static int[] CPLEXT = {
0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2,
3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0
};
/// <summary>
/// Copy offsets for distance codes 0..29
/// </summary>
static int[] CPDIST = {
1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
8193, 12289, 16385, 24577
};
/// <summary>
/// Extra bits for distance codes
/// </summary>
static int[] CPDEXT = {
0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6,
7, 7, 8, 8, 9, 9, 10, 10, 11, 11,
12, 12, 13, 13
};
/// <summary>
/// These are the possible states for an inflater
/// </summary>
const int DECODE_HEADER = 0;
const int DECODE_DICT = 1;
const int DECODE_BLOCKS = 2;
const int DECODE_STORED_LEN1 = 3;
const int DECODE_STORED_LEN2 = 4;
const int DECODE_STORED = 5;
const int DECODE_DYN_HEADER = 6;
const int DECODE_HUFFMAN = 7;
const int DECODE_HUFFMAN_LENBITS = 8;
const int DECODE_HUFFMAN_DIST = 9;
const int DECODE_HUFFMAN_DISTBITS = 10;
const int DECODE_CHKSUM = 11;
const int FINISHED = 12;
/// <summary>
/// This variable contains the current state.
/// </summary>
int mode;
/// <summary>
/// The adler checksum of the dictionary or of the decompressed
/// stream, as it is written in the header resp. footer of the
/// compressed stream.
/// Only valid if mode is DECODE_DICT or DECODE_CHKSUM.
/// </summary>
int readAdler;
/// <summary>
/// The number of bits needed to complete the current state. This
/// is valid, if mode is DECODE_DICT, DECODE_CHKSUM,
/// DECODE_HUFFMAN_LENBITS or DECODE_HUFFMAN_DISTBITS.
/// </summary>
int neededBits;
int repLength;
int repDist;
int uncomprLen;
/// <summary>
/// True, if the last block flag was set in the last block of the
/// inflated stream. This means that the stream ends after the
/// current block.
/// </summary>
bool isLastBlock;
/// <summary>
/// The total number of inflated bytes.
/// </summary>
int totalOut;
/// <summary>
/// The total number of bytes set with setInput(). This is not the
/// value returned by the TotalIn property, since this also includes the
/// unprocessed input.
/// </summary>
int totalIn;
/// <summary>
/// This variable stores the noHeader flag that was given to the constructor.
/// True means, that the inflated stream doesn't contain a Zlib header or
/// footer.
/// </summary>
bool noHeader;
StreamManipulator input;
OutputWindow outputWindow;
InflaterDynHeader dynHeader;
InflaterHuffmanTree litlenTree, distTree;
Adler32 adler;
/// <summary>
/// Creates a new inflater or RFC1951 decompressor
/// RFC1950/Zlib headers and footers will be expected in the input data
/// </summary>
public Inflater() : this(false)
{
}
/// <summary>
/// Creates a new inflater.
/// </summary>
/// <param name="noHeader">
/// True if no RFC1950/Zlib header and footer fields are expected in the input data
///
/// This is used for GZIPed/Zipped input.
///
/// For compatibility with
/// Sun JDK you should provide one byte of input more than needed in
/// this case.
/// </param>
public Inflater(bool noHeader)
{
this.noHeader = noHeader;
this.adler = new Adler32();
input = new StreamManipulator();
outputWindow = new OutputWindow();
mode = noHeader ? DECODE_BLOCKS : DECODE_HEADER;
}
/// <summary>
/// Resets the inflater so that a new stream can be decompressed. All
/// pending input and output will be discarded.
/// </summary>
public void Reset()
{
mode = noHeader ? DECODE_BLOCKS : DECODE_HEADER;
totalIn = totalOut = 0;
input.Reset();
outputWindow.Reset();
dynHeader = null;
litlenTree = null;
distTree = null;
isLastBlock = false;
adler.Reset();
}
/// <summary>
/// Decodes a zlib/RFC1950 header.
/// </summary>
/// <returns>
/// False if more input is needed.
/// </returns>
/// <exception cref="System.ApplicationException">
/// The header is invalid.
/// </exception>
private bool DecodeHeader()
{
int header = input.PeekBits(16);
if (header < 0) {
return false;
}
input.DropBits(16);
/* The header is written in "wrong" byte order */
header = ((header << 8) | (header >> 8)) & 0xffff;
if (header % 31 != 0) {
throw new ApplicationException("Header checksum illegal");
}
if ((header & 0x0f00) != (Deflater.DEFLATED << 8)) {
throw new ApplicationException("Compression Method unknown");
}
/* Maximum size of the backwards window in bits.
* We currently ignore this, but we could use it to make the
* inflater window more space efficient. On the other hand the
* full window (15 bits) is needed most times, anyway.
int max_wbits = ((header & 0x7000) >> 12) + 8;
*/
if ((header & 0x0020) == 0) { // Dictionary flag?
mode = DECODE_BLOCKS;
} else {
mode = DECODE_DICT;
neededBits = 32;
}
return true;
}
/// <summary>
/// Decodes the dictionary checksum after the deflate header.
/// </summary>
/// <returns>
/// False if more input is needed.
/// </returns>
private bool DecodeDict()
{
while (neededBits > 0) {
int dictByte = input.PeekBits(8);
if (dictByte < 0) {
return false;
}
input.DropBits(8);
readAdler = (readAdler << 8) | dictByte;
neededBits -= 8;
}
return false;
}
/// <summary>
/// Decodes the huffman encoded symbols in the input stream.
/// </summary>
/// <returns>
/// false if more input is needed, true if output window is
/// full or the current block ends.
/// </returns>
/// <exception cref="System.ApplicationException">
/// if deflated stream is invalid.
/// </exception>
private bool DecodeHuffman()
{
int free = outputWindow.GetFreeSpace();
while (free >= 258) {
int symbol;
switch (mode) {
case DECODE_HUFFMAN:
/* This is the inner loop so it is optimized a bit */
while (((symbol = litlenTree.GetSymbol(input)) & ~0xff) == 0) {
outputWindow.Write(symbol);
if (--free < 258) {
return true;
}
}
if (symbol < 257) {
if (symbol < 0) {
return false;
} else {
/* symbol == 256: end of block */
distTree = null;
litlenTree = null;
mode = DECODE_BLOCKS;
return true;
}
}
try {
repLength = CPLENS[symbol - 257];
neededBits = CPLEXT[symbol - 257];
} catch (Exception) {
throw new ApplicationException("Illegal rep length code");
}
goto case DECODE_HUFFMAN_LENBITS; /* fall through */
case DECODE_HUFFMAN_LENBITS:
if (neededBits > 0) {
mode = DECODE_HUFFMAN_LENBITS;
int i = input.PeekBits(neededBits);
if (i < 0) {
return false;
}
input.DropBits(neededBits);
repLength += i;
}
mode = DECODE_HUFFMAN_DIST;
goto case DECODE_HUFFMAN_DIST;/* fall through */
case DECODE_HUFFMAN_DIST:
symbol = distTree.GetSymbol(input);
if (symbol < 0) {
return false;
}
try {
repDist = CPDIST[symbol];
neededBits = CPDEXT[symbol];
} catch (Exception) {
throw new ApplicationException("Illegal rep dist code");
}
goto case DECODE_HUFFMAN_DISTBITS;/* fall through */
case DECODE_HUFFMAN_DISTBITS:
if (neededBits > 0) {
mode = DECODE_HUFFMAN_DISTBITS;
int i = input.PeekBits(neededBits);
if (i < 0) {
return false;
}
input.DropBits(neededBits);
repDist += i;
}
outputWindow.Repeat(repLength, repDist);
free -= repLength;
mode = DECODE_HUFFMAN;
break;
default:
throw new ApplicationException("Inflater unknown mode");
}
}
return true;
}
/// <summary>
/// Decodes the adler checksum after the deflate stream.
/// </summary>
/// <returns>
/// false if more input is needed.
/// </returns>
/// <exception cref="ApplicationException">
/// If checksum doesn't match.
/// </exception>
private bool DecodeChksum()
{
while (neededBits > 0) {
int chkByte = input.PeekBits(8);
if (chkByte < 0) {
return false;
}
input.DropBits(8);
readAdler = (readAdler << 8) | chkByte;
neededBits -= 8;
}
if ((int) adler.Value != readAdler) {
throw new ApplicationException("Adler chksum doesn't match: " + (int)adler.Value + " vs. " + readAdler);
}
mode = FINISHED;
return false;
}
/// <summary>
/// Decodes the deflated stream.
/// </summary>
/// <returns>
/// false if more input is needed, or if finished.
/// </returns>
/// <exception cref="ApplicationException">
/// ApplicationException, if deflated stream is invalid.
/// </exception>
private bool Decode()
{
switch (mode) {
case DECODE_HEADER:
return DecodeHeader();
case DECODE_DICT:
return DecodeDict();
case DECODE_CHKSUM:
return DecodeChksum();
case DECODE_BLOCKS:
if (isLastBlock) {
if (noHeader) {
mode = FINISHED;
return false;
} else {
input.SkipToByteBoundary();
neededBits = 32;
mode = DECODE_CHKSUM;
return true;
}
}
int type = input.PeekBits(3);
if (type < 0) {
return false;
}
input.DropBits(3);
if ((type & 1) != 0) {
isLastBlock = true;
}
switch (type >> 1){
case DeflaterConstants.STORED_BLOCK:
input.SkipToByteBoundary();
mode = DECODE_STORED_LEN1;
break;
case DeflaterConstants.STATIC_TREES:
litlenTree = InflaterHuffmanTree.defLitLenTree;
distTree = InflaterHuffmanTree.defDistTree;
mode = DECODE_HUFFMAN;
break;
case DeflaterConstants.DYN_TREES:
dynHeader = new InflaterDynHeader();
mode = DECODE_DYN_HEADER;
break;
default:
throw new ApplicationException("Unknown block type " + type);
}
return true;
case DECODE_STORED_LEN1:
{
if ((uncomprLen = input.PeekBits(16)) < 0) {
return false;
}
input.DropBits(16);
mode = DECODE_STORED_LEN2;
}
goto case DECODE_STORED_LEN2; /* fall through */
case DECODE_STORED_LEN2:
{
int nlen = input.PeekBits(16);
if (nlen < 0) {
return false;
}
input.DropBits(16);
if (nlen != (uncomprLen ^ 0xffff)) {
throw new ApplicationException("broken uncompressed block");
}
mode = DECODE_STORED;
}
goto case DECODE_STORED;/* fall through */
case DECODE_STORED:
{
int more = outputWindow.CopyStored(input, uncomprLen);
uncomprLen -= more;
if (uncomprLen == 0) {
mode = DECODE_BLOCKS;
return true;
}
return !input.IsNeedingInput;
}
case DECODE_DYN_HEADER:
if (!dynHeader.Decode(input)) {
return false;
}
litlenTree = dynHeader.BuildLitLenTree();
distTree = dynHeader.BuildDistTree();
mode = DECODE_HUFFMAN;
goto case DECODE_HUFFMAN; /* fall through */
case DECODE_HUFFMAN:
case DECODE_HUFFMAN_LENBITS:
case DECODE_HUFFMAN_DIST:
case DECODE_HUFFMAN_DISTBITS:
return DecodeHuffman();
case FINISHED:
return false;
default:
throw new ApplicationException("Inflater.Decode unknown mode");
}
}
/// <summary>
/// Sets the preset dictionary. This should only be called, if
/// needsDictionary() returns true and it should set the same
/// dictionary, that was used for deflating. The getAdler()
/// function returns the checksum of the dictionary needed.
/// </summary>
/// <param name="buffer">
/// The dictionary.
/// </param>
/// <exception cref="System.InvalidOperationException">
/// No dictionary is needed.
/// </exception>
/// <exception cref="System.ArgumentException">
/// if the dictionary checksum is wrong.
/// </exception>
public void SetDictionary(byte[] buffer)
{
SetDictionary(buffer, 0, buffer.Length);
}
/// <summary>
/// Sets the preset dictionary. This should only be called, if
/// needsDictionary() returns true and it should set the same
/// dictionary, that was used for deflating. The getAdler()
/// function returns the checksum of the dictionary needed.
/// </summary>
/// <param name="buffer">
/// The dictionary.
/// </param>
/// <param name="offset">
/// The offset into buffer where the dictionary starts.
/// </param>
/// <param name="len">
/// The length of the dictionary.
/// </param>
/// <exception cref="System.InvalidOperationException">
/// No dictionary is needed.
/// </exception>
/// <exception cref="ApplicationException">
/// The adler checksum for the buffer is invalid
/// </exception>
public void SetDictionary(byte[] buffer, int offset, int len)
{
if (!IsNeedingDictionary) {
throw new InvalidOperationException();
}
adler.Update(buffer, offset, len);
if ((int)adler.Value != readAdler) {
throw new ApplicationException("Wrong adler checksum");
}
adler.Reset();
outputWindow.CopyDict(buffer, offset, len);
mode = DECODE_BLOCKS;
}
/// <summary>
/// Sets the input. This should only be called, if needsInput()
/// returns true.
/// </summary>
/// <param name="buf">
/// the input.
/// </param>
/// <exception cref="System.InvalidOperationException">
/// if no input is needed.
/// </exception>
public void SetInput(byte[] buf)
{
SetInput(buf, 0, buf.Length);
}
/// <summary>
/// Sets the input. This should only be called, if needsInput()
/// returns true.
/// </summary>
/// <param name="buffer">
/// The source of input data
/// </param>
/// <param name="offset">
/// The offset into buffer where the input starts.
/// </param>
/// <param name="length">
/// The number of bytes of input to use.
/// </param>
/// <exception cref="System.InvalidOperationException">
/// No input is needed.
/// </exception>
/// <exception cref="System.ArgumentOutOfRangeException">
/// The off and/or len are wrong.
/// </exception>
public void SetInput(byte[] buffer, int offset, int length)
{
input.SetInput(buffer, offset, length);
totalIn += length;
}
/// <summary>
/// Inflates the compressed stream to the output buffer. If this
/// returns 0, you should check, whether needsDictionary(),
/// needsInput() or finished() returns true, to determine why no
/// further output is produced.
/// </summary>
/// <param name = "buf">
/// the output buffer.
/// </param>
/// <returns>
/// the number of bytes written to the buffer, 0 if no further
/// output can be produced.
/// </returns>
/// <exception cref="System.ArgumentOutOfRangeException">
/// if buf has length 0.
/// </exception>
/// <exception cref="System.FormatException">
/// if deflated stream is invalid.
/// </exception>
public int Inflate(byte[] buf)
{
return Inflate(buf, 0, buf.Length);
}
/// <summary>
/// Inflates the compressed stream to the output buffer. If this
/// returns 0, you should check, whether needsDictionary(),
/// needsInput() or finished() returns true, to determine why no
/// further output is produced.
/// </summary>
/// <param name = "buf">
/// the output buffer.
/// </param>
/// <param name = "offset">
/// the offset into buffer where the output should start.
/// </param>
/// <param name = "len">
/// the maximum length of the output.
/// </param>
/// <returns>
/// the number of bytes written to the buffer, 0 if no further output can be produced.
/// </returns>
/// <exception cref="System.ArgumentOutOfRangeException">
/// if len is <= 0.
/// </exception>
/// <exception cref="System.ArgumentOutOfRangeException">
/// if the offset and/or len are wrong.
/// </exception>
/// <exception cref="System.FormatException">
/// if deflated stream is invalid.
/// </exception>
public int Inflate(byte[] buf, int offset, int len)
{
if (len < 0) {
throw new ArgumentOutOfRangeException("len < 0");
}
// Special case: len may be zero
if (len == 0) {
if (IsFinished == false) {// -jr- 08-Nov-2003 INFLATE_BUG fix..
Decode();
}
return 0;
}
/*
// Check for correct buff, off, len triple
if (off < 0 || off + len >= buf.Length) {
throw new ArgumentException("off/len outside buf bounds");
}
*/
int count = 0;
int more;
do {
if (mode != DECODE_CHKSUM) {
/* Don't give away any output, if we are waiting for the
* checksum in the input stream.
*
* With this trick we have always:
* needsInput() and not finished()
* implies more output can be produced.
*/
more = outputWindow.CopyOutput(buf, offset, len);
adler.Update(buf, offset, more);
offset += more;
count += more;
totalOut += more;
len -= more;
if (len == 0) {
return count;
}
}
} while (Decode() || (outputWindow.GetAvailable() > 0 && mode != DECODE_CHKSUM));
return count;
}
/// <summary>
/// Returns true, if the input buffer is empty.
/// You should then call setInput().
/// NOTE: This method also returns true when the stream is finished.
/// </summary>
public bool IsNeedingInput {
get {
return input.IsNeedingInput;
}
}
/// <summary>
/// Returns true, if a preset dictionary is needed to inflate the input.
/// </summary>
public bool IsNeedingDictionary {
get {
return mode == DECODE_DICT && neededBits == 0;
}
}
/// <summary>
/// Returns true, if the inflater has finished. This means, that no
/// input is needed and no output can be produced.
/// </summary>
public bool IsFinished {
get {
return mode == FINISHED && outputWindow.GetAvailable() == 0;
}
}
/// <summary>
/// Gets the adler checksum. This is either the checksum of all
/// uncompressed bytes returned by inflate(), or if needsDictionary()
/// returns true (and thus no output was yet produced) this is the
/// adler checksum of the expected dictionary.
/// </summary>
/// <returns>
/// the adler checksum.
/// </returns>
public int Adler {
get {
return IsNeedingDictionary ? readAdler : (int) adler.Value;
}
}
/// <summary>
/// Gets the total number of output bytes returned by inflate().
/// </summary>
/// <returns>
/// the total number of output bytes.
/// </returns>
public int TotalOut {
get {
return totalOut;
}
}
/// <summary>
/// Gets the total number of processed compressed input bytes.
/// </summary>
/// <returns>
/// The total number of bytes of processed input bytes.
/// </returns>
public int TotalIn {
get {
return totalIn - RemainingInput;
}
}
#if TEST_HAK
/// <summary>
/// -jr test hak trying to figure out a bug
///</summary>
public int UnseenInput {
get {
return totalIn - ((input.AvailableBits + 7) >> 3);
}
}
/// <summary>
/// -jr test hak trying to figure out a bug
///</summary>
public int PlainTotalIn {
get {
return totalIn;
}
}
#endif
/// <summary>
/// Gets the number of unprocessed input bytes. Useful, if the end of the
/// stream is reached and you want to further process the bytes after
/// the deflate stream.
/// </summary>
/// <returns>
/// The number of bytes of the input which have not been processed.
/// </returns>
public int RemainingInput {
get {
return input.AvailableBytes;
}
}
}
}
| |
/*
Copyright (c) 2014, Lars Brubaker
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 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.
The views and conclusions contained in the software and documentation are those
of the authors and should not be interpreted as representing official policies,
either expressed or implied, of the FreeBSD Project.
*/
using MatterHackers.Agg.Font;
using MatterHackers.Agg.VertexSource;
using MatterHackers.VectorMath;
using System;
namespace MatterHackers.Agg.UI
{
public class TextEditWidget : ScrollableWidget
{
public InternalTextEditWidget InternalTextEditWidget { get; protected set; }
public event KeyEventHandler EnterPressed;
public event EventHandler EditComplete;
private int borderWidth = 0;
public static event EventHandler ShowSoftwareKeyboard;
public static event EventHandler HideSoftwareKeyboard;
public static event EventHandler KeyboardCollapsed;
public Color TextColor
{
get
{
return InternalTextEditWidget.TextColor;
}
set
{
InternalTextEditWidget.TextColor = value;
}
}
public override int TabIndex
{
get
{
return InternalTextEditWidget.TabIndex;
}
set
{
InternalTextEditWidget.TabIndex = value;
}
}
public Color CursorColor
{
get
{
return InternalTextEditWidget.cursorColor;
}
set
{
InternalTextEditWidget.cursorColor = value;
}
}
public new bool DoubleBuffer
{
get
{
return InternalTextEditWidget.DoubleBuffer;
}
set
{
InternalTextEditWidget.DoubleBuffer = value;
}
}
public void ClearUndoHistory()
{
InternalTextEditWidget.ClearUndoHistory();
}
public Color HighlightColor
{
get
{
return InternalTextEditWidget.highlightColor;
}
set
{
InternalTextEditWidget.highlightColor = value;
}
}
public override Color BorderColor
{
get
{
return InternalTextEditWidget.borderColor;
}
set
{
InternalTextEditWidget.borderColor = value;
}
}
public int BorderWidth
{
get
{
return borderWidth;
}
set
{
this.borderWidth = value;
InternalTextEditWidget.BorderWidth = this.borderWidth;
}
}
public bool Selecting
{
get { return InternalTextEditWidget.Selecting; }
set { InternalTextEditWidget.Selecting = value; }
}
public bool Multiline
{
get { return InternalTextEditWidget.Multiline; }
set
{
InternalTextEditWidget.Multiline = value;
if (Multiline == true)
{
AutoScroll = true;
VerticalScrollBar.Show = ScrollBar.ShowState.WhenRequired;
}
else
{
AutoScroll = false;
VerticalScrollBar.Show = ScrollBar.ShowState.Never;
}
}
}
public int SelectionIndexToStartBefore
{
get { return InternalTextEditWidget.SelectionIndexToStartBefore; }
set { InternalTextEditWidget.SelectionIndexToStartBefore = value; }
}
public int CharIndexToInsertBefore
{
get { return InternalTextEditWidget.CharIndexToInsertBefore; }
set { InternalTextEditWidget.CharIndexToInsertBefore = value; }
}
public override string Text
{
get
{
return InternalTextEditWidget.Text;
}
set
{
InternalTextEditWidget.Text = value;
}
}
public string Selection
{
get
{
return InternalTextEditWidget.Selection;
}
}
internal TextEditWidget()
{
}
public TextEditWidget(string text = "", double x = 0, double y = 0, double pointSize = 12, double pixelWidth = 0, double pixelHeight = 0, bool multiLine = false, int tabIndex = 0, TypeFace typeFace = null)
{
InternalTextEditWidget = new InternalTextEditWidget(text, pointSize, multiLine, tabIndex, typeFace: typeFace);
HookUpToInternalWidget(pixelWidth, pixelHeight);
OriginRelativeParent = new Vector2(x, y);
BackgroundColor = Color.White;
Multiline = multiLine;
}
public override void AddChild(GuiWidget child, int indexInChildrenList = -1)
{
throw new Exception("You cannot add children to a TextEdit widget.");
}
protected void HookUpToInternalWidget(double pixelWidth, double pixelHeight)
{
Cursor = Cursors.IBeam;
InternalTextEditWidget.EditComplete += new EventHandler(internalTextEditWidget_EditComplete);
InternalTextEditWidget.EnterPressed += new KeyEventHandler(internalTextEditWidget_EnterPressed);
if (pixelWidth == 0)
{
pixelWidth = InternalTextEditWidget.Width;
}
if (pixelHeight == 0)
{
pixelHeight = InternalTextEditWidget.Height;
}
this.LocalBounds = new RectangleDouble(0, 0, pixelWidth, pixelHeight);
InternalTextEditWidget.InsertBarPositionChanged += new EventHandler(internalTextEditWidget_InsertBarPositionChanged);
InternalTextEditWidget.FocusChanged += new EventHandler(internalTextEditWidget_FocusChanged);
InternalTextEditWidget.TextChanged += new EventHandler(internalTextEditWidget_TextChanged);
base.AddChild(InternalTextEditWidget);
}
private void internalTextEditWidget_TextChanged(object sender, EventArgs e)
{
OnTextChanged(e);
}
/// <summary>
/// Make this widget the focus of keyboard input.
/// </summary>
/// <returns></returns>
public override void Focus()
{
#if DEBUG
if (Parent == null)
{
throw new Exception("Don't call Focus() until you have a Parent.\nCalling focus without a parent will not result in the focus chain pointing to the widget, so it will not work.");
}
#endif
InternalTextEditWidget.Focus();
}
private void internalTextEditWidget_FocusChanged(object sender, EventArgs e)
{
if (ContainsFocus)
{
if (ShowSoftwareKeyboard != null)
{
UiThread.RunOnIdle(() =>
{
ShowSoftwareKeyboard(this, null);
});
}
}
else
{
OnHideSoftwareKeyboard();
}
OnFocusChanged(e);
}
public override void OnClosed(EventArgs e)
{
if (Focused)
{
OnHideSoftwareKeyboard();
}
base.OnClosed(e);
}
private void OnHideSoftwareKeyboard()
{
UiThread.RunOnIdle(() =>
{
HideSoftwareKeyboard?.Invoke(this, null);
KeyboardCollapsed?.Invoke(this, null);
});
}
public static void OnKeyboardCollapsed()
{
KeyboardCollapsed?.Invoke(null, null);
}
private void internalTextEditWidget_EnterPressed(object sender, KeyEventArgs keyEvent)
{
EnterPressed?.Invoke(this, keyEvent);
}
public override void OnMouseDown(MouseEventArgs mouseEvent)
{
ScrollBar scrollBar = this.VerticalScrollBar;
double scrollBarX = mouseEvent.X;
double scrollBarY = mouseEvent.Y;
scrollBar.ParentToChildTransform.inverse_transform(ref scrollBarX, ref scrollBarY);
bool clickIsOnScrollBar = scrollBar.Visible && scrollBar.PositionWithinLocalBounds(scrollBarX, scrollBarY);
if (!clickIsOnScrollBar)
{
double scrollingAreaX = mouseEvent.X;
double scrollingAreaY = mouseEvent.Y;
ScrollArea.ParentToChildTransform.inverse_transform(ref scrollingAreaX, ref scrollingAreaY);
if (scrollingAreaX > InternalTextEditWidget.LocalBounds.Right)
{
scrollingAreaX = InternalTextEditWidget.LocalBounds.Right - 1;
}
else if (scrollingAreaX < InternalTextEditWidget.LocalBounds.Left)
{
scrollingAreaX = InternalTextEditWidget.LocalBounds.Left;
}
if (scrollingAreaY > InternalTextEditWidget.LocalBounds.Top)
{
scrollingAreaY = InternalTextEditWidget.LocalBounds.Top - 1;
}
else if (scrollingAreaY < InternalTextEditWidget.LocalBounds.Bottom)
{
scrollingAreaY = InternalTextEditWidget.LocalBounds.Bottom;
}
ScrollArea.ParentToChildTransform.transform(ref scrollingAreaX, ref scrollingAreaY);
mouseEvent.X = scrollingAreaX;
mouseEvent.Y = scrollingAreaY;
}
base.OnMouseDown(mouseEvent);
if (Focused)
{
throw new Exception("We should have moved the mouse so that it gave selection to the internal text edit widget.");
}
}
private void internalTextEditWidget_EditComplete(object sender, EventArgs e)
{
EditComplete?.Invoke(this, null);
}
public TypeFacePrinter Printer
{
get
{
return InternalTextEditWidget.Printer;
}
}
private void internalTextEditWidget_InsertBarPositionChanged(object sender, EventArgs e)
{
double fontHeight = Printer.TypeFaceStyle.EmSizeInPixels;
Vector2 barPosition = InternalTextEditWidget.InsertBarPosition;
// move the minimum amount required to keep the bar in view
Vector2 currentOffsetInView = barPosition + TopLeftOffset;
Vector2 requiredOffet = Vector2.Zero;
if (currentOffsetInView.X > Width - 2)
{
requiredOffet.X = currentOffsetInView.X - Width + 2;
}
else if (currentOffsetInView.X < 0)
{
requiredOffet.X = currentOffsetInView.X;
}
if (currentOffsetInView.Y <= -(Height - fontHeight))
{
requiredOffet.Y = -(currentOffsetInView.Y + Height) + fontHeight;
}
else if (currentOffsetInView.Y > 0)
{
requiredOffet.Y = -currentOffsetInView.Y;
}
TopLeftOffset = new VectorMath.Vector2(TopLeftOffset.X - requiredOffet.X, TopLeftOffset.Y + requiredOffet.Y);
}
public bool SelectAllOnFocus
{
get { return InternalTextEditWidget.SelectAllOnFocus; }
set { InternalTextEditWidget.SelectAllOnFocus = value; }
}
public bool ReadOnly { get => InternalTextEditWidget.ReadOnly; set => InternalTextEditWidget.ReadOnly = value; }
}
}
| |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.Threading; // DLL support
using System.IO;
using System.Text.RegularExpressions;
using System.Windows.Forms.RibbonHelpers;
using System.Net;
using System.Diagnostics;
using usbGenericHidCommunications;
namespace PNPControllerKFlop
{
public partial class Form1 : RibbonForm
{
// bed settings
public double NeedleZHeight = 35;
public double Xoffset = -0.116;
public double Yoffset = 0.0;
public double NeedleXSpacing = -32.2;
public double dblPCBThickness = 1.6;
public int FeedRate = 20000;
public int chipfeederms = 250;
public double ClearHeight = 15;
public double LowClearHeight = 15;
public DataSet dsMain;
public DataTable dtFeeders;
// Add these two lines
// remote control
HttpListener listener = new HttpListener();
string listeningURL = "http://10.0.0.8:8080/";
// Create an instance of the USB reference device
private usbDevice usbController;
byte BaseCameraPWM = 150;
byte HeadCameraPWM = 150;
byte VibrationMotorSpeed = 150;
// manual picker selector
public int currentfeeder = 0;
private delegate void SetTextCallback(System.Windows.Forms.Control control, string text);
private delegate void SetDROTextCallback(System.Windows.Forms.RibbonTextBox control, string text);
private ComponentFeeders cf = new ComponentFeeders();
private Components comp = new Components();
private PCBLoader csvload = new PCBLoader();
private DataToMach3 dtom3 = new DataToMach3();
private kflop kf = new kflop();
public Form1()
{
InitializeComponent();
usbController = new usbDevice(0x04D8, 0x0042);
usbController.usbEvent += new usbDevice.usbEventsHandler(usbEvent_receiver);
usbController.findTargetDevice();
InitializeBackgroundWorker();
this.FormClosing += new FormClosingEventHandler(Form_FormClosing);
dtFeeders = cf.POPFeedersTable();
kf.initdevice();
LoadSettings();
RunBoardInit();
Thread thrdRemote = new Thread(new ThreadStart(initRemote));
thrdRemote.Start();
thrdRemote.IsBackground = true;
csvload.SetupGridView(dataGridView1);
// setup manual feeder single picker list
}
void Form_FormClosing(object sender, FormClosingEventArgs e)
{
SaveSettings();
timer1.Stop();
backgroundWorkerDoCommand.CancelAsync();
backgroundWorkerUpdateDRO.CancelAsync();
}
private void usbEvent_receiver(object o, EventArgs e)
{
// Check the status of the USB device and update the form accordingly
if (usbController.isDeviceAttached)
{
// Device is currently attached
SetResultsLabelText("USB Device is attached");
}
else
{
// Device is currently unattached
// Update the status label
SetResultsLabelText("USB Device is detached");
}
}
/// <summary>
/// RunBoardInit() run self test on control board and initalise all settings
/// </summary>
private void RunBoardInit()
{
usbController.setBaseCameraPWM(byte.Parse(ribbonTextBoxBaseLedBrightness.TextBoxText));
usbController.setHeadCameraPWM(byte.Parse(ribbonTextBoxHeadLedBrightness.TextBoxText));
// usbController.setVibrationMotorSpeed(byte.Parse(ribbonTextBoxMotorPWM.TextBoxText));
usbController.setVibrationMotorSpeed(250);
usbController.setVAC1(false);
usbController.setVAC2(false);
// usbController.setResetFeeder();
// SetFeederOutputs(15);
/*
Thread.Sleep(200);
usbController.setVibrationMotor(true);
Thread.Sleep(500);
usbController.setVibrationMotor(false);
usbController.setVibrationMotorSpeed(250);
Thread.Sleep(500);
usbController.setHeadCameraLED(true);
Thread.Sleep(500);
usbController.setHeadCameraLED(false);
Thread.Sleep(500);
usbController.setBaseCameraLED(true);
Thread.Sleep(500);
usbController.setBaseCameraLED(false);
Thread.Sleep(500);
usbController.setVAC1(true);
Thread.Sleep(500);
usbController.setVAC1(false);
Thread.Sleep(500);
usbController.setVAC2(true);
Thread.Sleep(500);
* */
}
public double CalcAZHeight(double targetheight)
{
return NeedleZHeight - targetheight;
// return targetheight;
}
public double CalcAZPlaceHeight(double targetheight)
{
return (NeedleZHeight - targetheight) - dblPCBThickness;
}
public double CalcXwithNeedleSpacing(double target)
{
return (NeedleXSpacing + target);
}
// Thread safe updating of control's text property
public void SetText(System.Windows.Forms.Control control, string text)
{
try
{
if (control.InvokeRequired)
{
SetTextCallback d = new SetTextCallback(SetText);
Invoke(d, new object[] { control, text });
}
else
{
control.Text = text;
}
}
catch { }
}
public void SetDROText(System.Windows.Forms.RibbonTextBox control, string text)
{
try
{
if (this.ribbon1.InvokeRequired)
{
SetDROTextCallback d = new SetDROTextCallback(SetDROText);
Invoke(d, new object[] { control, text });
}
else
{
control.TextBoxText = text;
}
}
catch { }
}
private void StetActiveComponentText(string text)
{
text = "Current Component: " + text;
if (this.statusStrip1.InvokeRequired)
this.statusStrip1.Invoke(
new MethodInvoker(() => this.toolStripStatusLabelCurrentCommand.Text = text));
else this.toolStripStatusLabelCurrentCommand.Text = text;
}
private void SetCurrentCommandText(string text)
{
text = "Active Command: " + text;
if (this.statusStrip1.InvokeRequired)
this.statusStrip1.Invoke(
new MethodInvoker(() => this.toolStripStatusLabelActiveComponent.Text = text));
else this.toolStripStatusLabelActiveComponent.Text = text;
}
private void SetRemoteIPText(string text)
{
text = "Remote IP: " + text;
if (this.statusStrip1.InvokeRequired)
this.statusStrip1.Invoke(
new MethodInvoker(() => this.toolStripStatusLabelIP.Text = text));
else this.toolStripStatusLabelIP.Text = text;
}
private void SetResultsLabelText(string text)
{
if (this.statusStrip1.InvokeRequired)
this.statusStrip1.Invoke(
new MethodInvoker(() => this.toolStripStatusLabelresultLabel.Text = text));
else this.toolStripStatusLabelresultLabel.Text = text;
}
private void InitializeBackgroundWorker()
{
backgroundWorkerUpdateDRO.DoWork +=
new DoWorkEventHandler(backgroundWorkerUpdateDRO_DoWork_1);
backgroundWorkerUpdateDRO.RunWorkerCompleted +=
new RunWorkerCompletedEventHandler(
backgroundWorkerUpdateDRO_RunWorkerCompleted);
backgroundWorkerUpdateDRO.ProgressChanged +=
new ProgressChangedEventHandler(
backgroundWorkerUpdateDRO_ProgressChanged);
backgroundWorkerDoCommand.DoWork +=
new DoWorkEventHandler(backgroundWorkerDoCommand_DoWork);
backgroundWorkerDoCommand.RunWorkerCompleted +=
new RunWorkerCompletedEventHandler(
backgroundWorkerDoCommand_RunWorkerCompleted);
backgroundWorkerDoCommand.ProgressChanged +=
new ProgressChangedEventHandler(
backgroundWorkerDoCommand_ProgressChanged);
backgroundWorkerGetFeeder.RunWorkerCompleted +=
new RunWorkerCompletedEventHandler(
backgroundWorkerGetFeeder_RunWorkerCompleted);
backgroundWorkerGetFeeder.ProgressChanged +=
new ProgressChangedEventHandler(
backgroundWorkerGetFeeder_ProgressChanged);
backgroundWorkerChipFeeder.DoWork +=
new DoWorkEventHandler(backgroundWorkerChipFeeder_DoWork);
}
private void backgroundWorkerUpdateDRO_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
toolStripStatusLabelresultLabel.Text = "Running!";
}
private void backgroundWorkerDoCommand_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
toolStripProgressBar1.Value = e.ProgressPercentage;
toolStripStatusLabelresultLabel.Text = "Running!";
}
private void backgroundWorkerGetFeeder_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
toolStripStatusLabelresultLabel.Text = "Running!";
}
// This event handler deals with the results of the background operation.
private void backgroundWorkerUpdateDRO_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
if (e.Cancelled == true)
{
toolStripStatusLabelresultLabel.Text = "Cancelled!";
}
else if (e.Error != null)
{
toolStripStatusLabelresultLabel.Text = "Error: " + e.Error.Message;
}
else
{
toolStripStatusLabelresultLabel.Text = "Done!";
}
}
private void backgroundWorkerDoCommand_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
if (e.Cancelled == true)
{
toolStripStatusLabelresultLabel.Text = "Canceled!";
}
else if (e.Error != null)
{
toolStripStatusLabelresultLabel.Text = "Error: " + e.Error.Message;
}
else
{
toolStripStatusLabelresultLabel.Text = "Done!";
}
}
private void backgroundWorkerGetFeeder_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
if (e.Cancelled == true)
{
toolStripStatusLabelresultLabel.Text = "Canceled!";
}
else if (e.Error != null)
{
toolStripStatusLabelresultLabel.Text = "Error: " + e.Error.Message;
}
else
{
toolStripStatusLabelresultLabel.Text = "Done!";
}
}
private void CheckFeederReady()
{
while (!usbController.getFeederReadyStatus())
{
Thread.Sleep(50);
}
}
private void backgroundWorkerUpdateDRO_DoWork_1(object sender, DoWorkEventArgs e)
{
BackgroundWorker worker = sender as BackgroundWorker;
if (backgroundWorkerUpdateDRO.CancellationPending)
{
e.Cancel = true;
}
double x, y, z, a, b, c = 0;
kf.GetDRO(out x, out y, out z, out a, out b, out c);
SetDROText(ribbonTextBoxDROX, x.ToString());
SetDROText(ribbonTextBoxDROY, y.ToString());
SetDROText(ribbonTextBoxDROZ, z.ToString());
SetDROText(ribbonTextBoxDROA, a.ToString());
SetDROText(ribbonTextBoxDROB, b.ToString());
SetDROText(ribbonTextBoxDROC, c.ToString());
worker.ReportProgress(100);
}
private void backgroundWorkerDoCommand_DoWork(object sender, DoWorkEventArgs e)
{
BackgroundWorker worker = sender as BackgroundWorker;
DataView rundata = new DataView();
rundata = dtom3.ConvertToGCode(dataGridView1, Double.Parse(ribbonTextBoxBoardOffsetX.TextBoxText), Double.Parse(ribbonTextBoxBoardOffsetY.TextBoxText));
double feedrate = double.Parse(ribbonTextBoxFeedRate.TextBoxText);
int currentrow = 0;
int totalrows = rundata.Count;
if (totalrows > 0)
{
// MessageBox.Show(totalrows.ToString());
// RunMach3Command(Script, "G01 B0 C0");
/* table columns
RefDes
Type
PosX
PosY
ComponentRotation
ComponentValue
feederNumber
Code
ComponentHeight
DefaultRotation
VerifywithCamera
TapeFeeder
feederPosX
feederPosY
feederPosZ
PickPlusChipHeight
* */
double progresspert = 0;
double progresspertcalc = 100 / totalrows;
double feederPosX = 0;
double feederPosY = 0;
double feederPosZ = 0;
double placePosX = 0;
double placePosY = 0;
double ComponentRotation = 0;
double DefaultRotation = 0;
double componentHeight = 0;
double newrotation = 0;
while (currentrow < totalrows)
{
if (backgroundWorkerDoCommand.CancellationPending)
{
e.Cancel = true;
SetCurrentCommandText("Stopped");
rundata.Dispose();
break;
}
feederPosX = double.Parse(rundata[currentrow]["feederPosX"].ToString()) + Xoffset;
feederPosY = double.Parse(rundata[currentrow]["feederPosY"].ToString()) + Yoffset;
feederPosZ = double.Parse(rundata[currentrow]["feederPosZ"].ToString());
placePosX = double.Parse(rundata[currentrow]["PosX"].ToString()) + Xoffset;
placePosY = double.Parse(rundata[currentrow]["PosY"].ToString()) + Yoffset;
ComponentRotation = double.Parse(rundata[currentrow]["ComponentRotation"].ToString());
DefaultRotation = double.Parse(rundata[currentrow]["DefaultRotation"].ToString());
componentHeight = double.Parse(rundata[currentrow]["ComponentHeight"].ToString());
if (currentrow == 0)
{
SetFeederOutputs(Int32.Parse(rundata[currentrow]["FeederNumber"].ToString())); // send feeder to position
}
SetCurrentCommandText("Feeder Activate");
SetCurrentCommandText(rundata[currentrow]["RefDes"].ToString());
StetActiveComponentText(rundata[currentrow]["RefDes"].ToString());
kf.MoveSingleFeed(feedrate, feederPosX, feederPosY, ClearHeight, ClearHeight, 0, 0);
SetCurrentCommandText("Picking Component");
if (rundata[currentrow]["TapeFeeder"].ToString().Equals("True"))
{
while (!usbController.getFeederReadyStatus())
{
Thread.Sleep(10);
}
Thread.Sleep(150);
// use picker 1
kf.MoveSingleFeed(feedrate, feederPosX, feederPosY, CalcAZHeight(feederPosZ), ClearHeight, 0, 0);
// go down and turn on suction
ChangeVacOutput(1, true);
Thread.Sleep(200);
kf.MoveSingleFeed(feedrate, feederPosX, feederPosY, ClearHeight, ClearHeight, 0, 0);
}
else
{
// use picker 2
kf.MoveSingleFeed(feedrate, feederPosX, feederPosY, ClearHeight, CalcAZHeight(feederPosZ), 0, 0);
ChangeVacOutput(2, true);
//Thread.Sleep(500);
Thread.Sleep(200);
kf.MoveSingleFeed(feedrate, feederPosX, feederPosY, ClearHeight, ClearHeight, 0, 0);
}
// send picker to pick next item
if (currentrow >= 0 && (currentrow + 1) < totalrows)
{
Thread.Sleep(100);
SetFeederOutputs(Int32.Parse(rundata[currentrow + 1]["FeederNumber"].ToString())); // send feeder to position
}
// rotate head
SetResultsLabelText("Placing Component");
if (rundata[currentrow]["TapeFeeder"].ToString().Equals("True"))
{
// use picker 1
if (DefaultRotation != ComponentRotation)
{
newrotation = DefaultRotation + ComponentRotation;
if (ComponentRotation == 0)
{
newrotation = DefaultRotation;
}
kf.MoveSingleFeed(feedrate, placePosX, placePosY, ClearHeight, ClearHeight, 0, newrotation);
}
else
{
kf.MoveSingleFeed(feedrate, placePosX, placePosY, ClearHeight, ClearHeight, 0, 0);
}
SetResultsLabelText("ComponentHeight: " + CalcAZPlaceHeight(componentHeight).ToString());
kf.MoveSingleFeed(feedrate, placePosX, placePosY, CalcAZPlaceHeight(componentHeight), ClearHeight, 0, newrotation);
Thread.Sleep(100);
ChangeVacOutput(1, false);
Thread.Sleep(200);
kf.MoveSingleFeed(feedrate, placePosX, placePosY, ClearHeight, ClearHeight, 0, newrotation);
}
else
{
// use picker 2 CalcXwithNeedleSpacing
if (DefaultRotation != ComponentRotation)
{
newrotation = DefaultRotation + ComponentRotation;
if (ComponentRotation == 0)
{
newrotation = DefaultRotation;
}
kf.MoveSingleFeed(feedrate, CalcXwithNeedleSpacing(placePosX), placePosY, ClearHeight, ClearHeight, newrotation, 0);
kf.MoveSingleFeed(feedrate, CalcXwithNeedleSpacing(placePosX), placePosY, ClearHeight, CalcAZPlaceHeight(componentHeight), newrotation, 0);
// go down and turn off suction
ChangeVacOutput(2, false);
Thread.Sleep(200);
kf.MoveSingleFeed(feedrate, CalcXwithNeedleSpacing(placePosX), placePosY, ClearHeight, ClearHeight, newrotation, 0);
}
else
{
kf.MoveSingleFeed(feedrate, CalcXwithNeedleSpacing(placePosX), placePosY, ClearHeight, ClearHeight, 0, 0);
kf.MoveSingleFeed(feedrate, CalcXwithNeedleSpacing(placePosX), placePosY, ClearHeight, CalcAZPlaceHeight(componentHeight), 0, 0);
ChangeVacOutput(2, false);
Thread.Sleep(200);
kf.MoveSingleFeed(feedrate, CalcXwithNeedleSpacing(placePosX), placePosY, ClearHeight, ClearHeight, 0, 0);
}
}
currentrow++;
progresspert = currentrow * progresspertcalc;
worker.ReportProgress(Int32.Parse(progresspert.ToString()));
}
rundata.Dispose();
}
else
{
MessageBox.Show("Board file not loaded");
}
backgroundWorkerDoCommand.CancelAsync();
worker.ReportProgress(100);
// home all axis and zero
SetResultsLabelText("Home and Reset");
//kf.HomeAll();
//Thread thrd = new Thread(new ThreadStart(DoHomeAll));
//thrd.Start();
// thrd.IsBackground = true;
}
public void ChangeVacOutput(int vac, bool turnon)
{
if (vac == 1)
{
if (turnon)
{
usbController.setVAC1(true);
Thread.Sleep(100);
}
else
{
usbController.setVAC1(false);
}
}
else
{
if (turnon)
{
usbController.setVAC2(true);
Thread.Sleep(200);
}
else
{
usbController.setVAC2(false);
Thread.Sleep(100);
}
}
// Thread.Sleep(50);
}
public void SetFeederOutputs(int feedercommand)
{
usbController.setGotoFeeder(Byte.Parse(feedercommand.ToString()));
// check if on main feeder rack
if (feedercommand == 98)
{
// command set, now toggle interupt pin
usbController.setResetFeeder();
}
if (feedercommand > 20 && feedercommand < 30)
{
chipfeederms = Int32.Parse(ribbonTextBoxChipMS.TextBoxText);
if (backgroundWorkerChipFeeder.IsBusy != true)
{
backgroundWorkerChipFeeder.RunWorkerAsync();
}
}
}
private void exitToolStripMenuItem_Click(object sender, EventArgs e)
{
Application.Exit();
}
// update the DRO screen with current position
private void timer1_Tick(object sender, EventArgs e)
{
if (backgroundWorkerUpdateDRO.IsBusy != true)
{
// Start the asynchronous operation.
backgroundWorkerUpdateDRO.RunWorkerAsync();
}
}
private void Form1_Load(object sender, EventArgs e)
{
// LoadCamera(pictureBox1, "Video Camera", 4, cam, true);
// LoadCamera(pictureBox2, "USB Camera", 4, cam2, false);
}
private void buttonStopGCode_Click(object sender, EventArgs e)
{
backgroundWorkerDoCommand.CancelAsync();
}
private void buttonChipFeederGo_Click(object sender, EventArgs e)
{
toolStripProgressBar1.Value = 0;
// currentfeeder = Int32.Parse(comboBoxManualReelFeeder.SelectedValue.ToString());
if (backgroundWorkerGetFeeder.IsBusy != true)
{
backgroundWorkerGetFeeder.RunWorkerAsync();
}
}
private void buttonChipFeeder_Click(object sender, EventArgs e)
{
chipfeederms = Int32.Parse(ribbonTextBoxChipMS.TextBoxText);
if (backgroundWorkerChipFeeder.IsBusy != true)
{
backgroundWorkerChipFeeder.RunWorkerAsync();
}
}
private void backgroundWorkerChipFeeder_DoWork(object sender, DoWorkEventArgs e)
{
usbController.setVibrationMotorSpeed(250);
usbController.setVibrationMotor(true);
int i = 0;
while (i < chipfeederms)
{
Thread.Sleep(10);
i = i + 10;
}
usbController.setVibrationMotor(false);
usbController.setVibrationMotorSpeed(250);
}
private void ribbonButtonSmallOpen_Click(object sender, EventArgs e)
{
openFileDialog1.Filter = "XML files|*.xml";
DialogResult result = openFileDialog1.ShowDialog();
if (result == DialogResult.OK) // Test result.
{
string file = openFileDialog1.FileName;
try
{
// string imagefile = file.Replace(".xml", ".jpg");
// if (System.IO.File.Exists(imagefile))
// {
// pictureBoxPCB.Image = new Bitmap(imagefile);
// }
try
{
dsMain.Clear();
}
catch { }
dsMain = csvload.LoadPCB(file, dataGridView1);
// data loaded, now set board defaults
ribbonTextBoxBoardOffsetX.TextBoxText = dsMain.Tables["Settings"].Rows[0]["BoardOffsetX"].ToString(); //double
ribbonTextBoxBoardOffsetY.TextBoxText = dsMain.Tables["Settings"].Rows[0]["BoardOffsetY"].ToString(); //double
ribbonTextBoxPCBThickness.TextBoxText = dsMain.Tables["Settings"].Rows[0]["PCBThickness"].ToString(); //double //double dblPCBThickness
ribbonTextBoxFeedRate.TextBoxText = dsMain.Tables["Settings"].Rows[0]["FeedRate"].ToString(); //int FeedRate
ribbonTextBoxChipMS.TextBoxText = dsMain.Tables["Settings"].Rows[0]["chipfeederms"].ToString(); //int chipfeederms
dblPCBThickness = Double.Parse(dsMain.Tables["Settings"].Rows[0]["PCBThickness"].ToString());
FeedRate = Int32.Parse(dsMain.Tables["Settings"].Rows[0]["FeedRate"].ToString());
chipfeederms = Int32.Parse(dsMain.Tables["Settings"].Rows[0]["chipfeederms"].ToString());
DrawComponents();
}
catch (Exception exc)
{
MessageBox.Show(exc.ToString());
}
}
}
private void DrawComponents()
{
if (pictureBoxPCB.Image == null)
{
pictureBoxPCB.Image = new Bitmap(pictureBoxPCB.Width,
pictureBoxPCB.Height);
}
else
{
pictureBoxPCB.InitialImage = null;
pictureBoxPCB.Image = new Bitmap(pictureBoxPCB.Width,
pictureBoxPCB.Height);
}
using (Graphics g = Graphics.FromImage(pictureBoxPCB.Image))
{
// draw black background
g.Clear(Color.White);
DataTable dt = dsMain.Tables["Component"];
foreach (DataRow row in dt.Rows)
{
try
{
int newx = Convert.ToInt32(Double.Parse(row["PosX"].ToString()) * 2.5);
int newy = Convert.ToInt32(Double.Parse(row["PosY"].ToString()) * 2.5);
//MessageBox.Show(newx.ToString() + " - " + newy.ToString());
switch (row["RefDes"].ToString().Substring(0, 1).ToLower())
{
case "r":
Rectangle rectres = new Rectangle(newx, newy, 2, 2);
g.DrawRectangle(Pens.Black, rectres);
break;
case "c":
Rectangle rectcap = new Rectangle(newx, newy, 2, 2);
g.DrawRectangle(Pens.Orange, rectcap);
break;
case "U":
Rectangle rectic = new Rectangle(newx, newy, 2, 2);
g.DrawRectangle(Pens.Gray, rectic);
break;
default:
Rectangle rect = new Rectangle(newx, newy, 2, 2);
g.DrawRectangle(Pens.Red, rect);
break;
}
}
catch (Exception ex) {
MessageBox.Show(ex.ToString());
}
}
}
pictureBoxPCB.Image.RotateFlip(RotateFlipType.Rotate180FlipX);
pictureBoxPCB.Invalidate();
}
private void ribbonButtonStart_Click(object sender, EventArgs e)
{
kf.setAlltoZero();
SaveSettings();
FeedRate = Int32.Parse(ribbonTextBoxFeedRate.TextBoxText);
DataView rundata = new DataView();
rundata = dtom3.ConvertToGCode(dataGridView1, Double.Parse(ribbonTextBoxBoardOffsetX.TextBoxText), Double.Parse(ribbonTextBoxBoardOffsetY.TextBoxText));
if (backgroundWorkerDoCommand.IsBusy != true)
{
backgroundWorkerDoCommand.RunWorkerAsync();
}
}
private void ribbonButtonEStop_Click_1(object sender, EventArgs e)
{
backgroundWorkerDoCommand.CancelAsync();
Thread thrd = new Thread(new ThreadStart(DoEStop));
thrd.Start();
thrd.IsBackground = true;
kf.initdevicesettings();
}
private void DoEStop()
{
kf.EStop();
}
private void buttonHomeAll_Click(object sender, EventArgs e)
{
Thread thrd = new Thread(new ThreadStart(DoHomeAll));
thrd.Start();
thrd.IsBackground = true;
}
private void DoHomeAll()
{
SetFeederOutputs(98);
kf.HomeAll();
}
private void ribbonButtonCheckAll_Click(object sender, EventArgs e)
{
for (int i = 0; i < dataGridView1.Rows.Count; i++)
{
dataGridView1.Rows[i].Cells["Pick"].Value = true;
}
}
private void ribbonButtonUnCheckAll_Click(object sender, EventArgs e)
{
for (int i = 0; i < dataGridView1.Rows.Count; i++)
{
dataGridView1.Rows[i].Cells["Pick"].Value = false;
}
}
private void ribbonButtonChipFeederShake_Click(object sender, EventArgs e)
{
chipfeederms = Int32.Parse(ribbonTextBoxChipMS.TextBoxText);
if (backgroundWorkerChipFeeder.IsBusy != true)
{
backgroundWorkerChipFeeder.RunWorkerAsync();
}
}
private void ribbonCheckBoxLEDPicker_CheckBoxCheckChanged(object sender, EventArgs e)
{
if (ribbonCheckBoxLEDPicker.Checked)
{
usbController.setHeadCameraLED(true);
}
else
{
usbController.setHeadCameraLED(false);
}
}
private void ribbonCheckBoxLEDCamera_CheckBoxCheckChanged(object sender, EventArgs e)
{
if (ribbonCheckBoxLEDCamera.Checked)
{
usbController.setBaseCameraLED(true);
} else {
usbController.setBaseCameraLED(false);
}
}
private void ribbonButtonComponentEditorOpen_Click(object sender, EventArgs e)
{
ComponentEditor cm = new ComponentEditor();
cm.Show(this);
}
private void ribbonButtonBaseCameraOpen_Click(object sender, EventArgs e)
{
CameraVision camvis = new CameraVision();
camvis.Show(this);
}
private void ribbonButtonVisionPickerCamera_Click(object sender, EventArgs e)
{
CameraHead camhead = new CameraHead();
camhead.Show(this);
}
private void ribbonButtonDROStart_Click(object sender, EventArgs e)
{
timer1.Start();
}
private void ribbonButtonDROStop_Click(object sender, EventArgs e)
{
timer1.Stop();
}
private void ribbonButtonManualJOGLeft_Click(object sender, EventArgs e)
{
kf.JogAxis("Y", false);
}
private void ribbonButtonManualJOGRight_Click(object sender, EventArgs e)
{
kf.JogAxis("Y", true);
}
private void ribbonButtonManualJOGUp_Click(object sender, EventArgs e)
{
kf.JogAxis("X", true);
}
private void ribbonButtonManualJOGDown_Click(object sender, EventArgs e)
{
kf.JogAxis("X", false);
}
private void LoadSettings() {
ribbonTextBoxBoardOffsetX.TextBoxText = Properties.Settings.Default.Properties["SettingBoardOffsetX"].DefaultValue.ToString(); // double
ribbonTextBoxBoardOffsetY.TextBoxText = Properties.Settings.Default.Properties["SettingBoardOffsetY"].DefaultValue.ToString(); //double
ribbonTextBoxPCBThickness.TextBoxText = Properties.Settings.Default.Properties["SettingPCBThickness"].DefaultValue.ToString(); //double //double dblPCBThickness
ribbonTextBoxFeedRate.TextBoxText = Properties.Settings.Default.Properties["SettingFeedRate"].DefaultValue.ToString(); //int FeedRate
ribbonTextBoxChipMS.TextBoxText = Properties.Settings.Default.Properties["SettingTimeMS"].DefaultValue.ToString(); //int chipfeederms
ribbonTextBoxHeadLedBrightness.TextBoxText = Properties.Settings.Default.Properties["HeadLedBrightness"].DefaultValue.ToString(); //byte chipfeederms
ribbonTextBoxBaseLedBrightness.TextBoxText = Properties.Settings.Default.Properties["BaseLedBrightness"].DefaultValue.ToString(); //byte chipfeederms
ribbonTextBoxMotorPWM.TextBoxText = Properties.Settings.Default.Properties["MotorPWM"].DefaultValue.ToString(); //byte chipfeederms
dblPCBThickness = Double.Parse(Properties.Settings.Default.Properties["SettingPCBThickness"].DefaultValue.ToString());
FeedRate = Int32.Parse(Properties.Settings.Default.Properties["SettingFeedRate"].DefaultValue.ToString());
chipfeederms = Int32.Parse(Properties.Settings.Default.Properties["SettingTimeMS"].DefaultValue.ToString());
}
private void SaveSettings()
{
Properties.Settings.Default.SettingBoardOffsetX = Double.Parse(ribbonTextBoxBoardOffsetX.TextBoxText);
Properties.Settings.Default.SettingBoardOffsetY = Double.Parse(ribbonTextBoxBoardOffsetY.TextBoxText);
Properties.Settings.Default.SettingPCBThickness = Double.Parse(ribbonTextBoxPCBThickness.TextBoxText);
Properties.Settings.Default.SettingFeedRate = Int32.Parse(ribbonTextBoxFeedRate.TextBoxText);
Properties.Settings.Default.SettingTimeMS = Int32.Parse(ribbonTextBoxChipMS.TextBoxText);
Properties.Settings.Default.HeadLedBrightness = byte.Parse(ribbonTextBoxHeadLedBrightness.TextBoxText);
Properties.Settings.Default.BaseLedBrightness = byte.Parse(ribbonTextBoxBaseLedBrightness.TextBoxText);
Properties.Settings.Default.MotorPWM = byte.Parse(ribbonTextBoxMotorPWM.TextBoxText);
// Save settings
Properties.Settings.Default.Save();
}
private void ribbonButtonCSVtoXML_Click(object sender, EventArgs e)
{
FormCSVtoXML csvcml = new FormCSVtoXML();
csvcml.Show(this);
}
private void ribbonButtonBoardMultiplier_Click(object sender, EventArgs e)
{
FormBoardMultiplier boardmult = new FormBoardMultiplier();
boardmult.Show(this);
}
private void ribbonButtonManualControlPicker1Left_Click(object sender, EventArgs e)
{
kf.JogAxis("B", false);
}
private void ribbonButtonManualControlPicker1Right_Click(object sender, EventArgs e)
{
kf.JogAxis("B", true);
}
private void ribbonButtonManualControlPicker1Up_Click(object sender, EventArgs e)
{
kf.JogAxis("A", false);
}
private void ribbonButtonManualControlPicker1Down_Click(object sender, EventArgs e)
{
kf.JogAxis("A", true);
}
private void ribbonButtonManualControlPicker2Left_Click(object sender, EventArgs e)
{
kf.JogAxis("C", false);
}
private void ribbonButtonManualControlPicker2Right_Click(object sender, EventArgs e)
{
kf.JogAxis("C", true);
}
private void ribbonButtonManualControlPicker2Up_Click(object sender, EventArgs e)
{
kf.JogAxis("Z", false);
}
private void ribbonButtonManualControlPicker2Down_Click(object sender, EventArgs e)
{
kf.JogAxis("Z", true);
}
private void ribbonButton7_Click(object sender, EventArgs e)
{
ManualPicker mp = new ManualPicker();
mp.Show();
}
// remote control for http remote access
public void stopRemote()
{
if (listener.IsListening)
{
listener.Stop();
}
}
protected string GetIP() //get IP address
{
// IPHostEntry ipHost = Dns.GetHostEntry(Dns.GetHostName());
//IPAddress ipAddr = ipHost.AddressList[0];
//return ipAddr.ToString();
string strHostName = System.Net.Dns.GetHostName();
IPHostEntry ipEntry = System.Net.Dns.GetHostEntry(strHostName);
foreach (IPAddress ipAddress in ipEntry.AddressList)
{
if (ipAddress.AddressFamily.ToString() == "InterNetwork")
{
return ipAddress.ToString();
}
}
return "-";
}
public void initRemote()
{
SetRemoteIPText(GetIP() + ":8080");
listeningURL = "http://" + GetIP() + ":8080/";
listener.Prefixes.Add(listeningURL);
listener.Start();
while (listener.IsListening)
{
HttpListenerContext context = listener.GetContext();
try
{
Thread t = new Thread(() =>
{
var request = context.Request;
switch (request.QueryString["command"].ToString())
{
case "start":
SaveSettings();
FeedRate = Int32.Parse(ribbonTextBoxFeedRate.TextBoxText);
DataView rundata = new DataView();
rundata = dtom3.ConvertToGCode(dataGridView1, Double.Parse(ribbonTextBoxBoardOffsetX.TextBoxText), Double.Parse(ribbonTextBoxBoardOffsetY.TextBoxText));
if (backgroundWorkerDoCommand.IsBusy != true)
{
backgroundWorkerDoCommand.RunWorkerAsync();
}
break;
case "stop":
backgroundWorkerDoCommand.CancelAsync();
break;
case "homeall":
Thread thrd2 = new Thread(new ThreadStart(DoHomeAll));
thrd2.Start();
thrd2.IsBackground = true;
break;
case "estop":
Thread thrdestop = new Thread(new ThreadStart(DoEStop));
thrdestop.Start();
thrdestop.IsBackground = true;
break;
}
byte[] Buffer = System.Text.Encoding.UTF8.GetBytes("OK" + Environment.NewLine);
context.Response.ContentType = "text/html; charset=utf-8";
context.Response.OutputStream.Write(Buffer, 0, Buffer.Length);
context.Response.Close();
//writing the sent message into the console
});
t.Start();
}
catch (Exception e)
{
Debug.WriteLine(e.Message);
}
}
}
private void ribbonButtonInit_Click(object sender, EventArgs e)
{
RunBoardInit();
}
private void ribbonCheckBoxVACPicker1_CheckBoxCheckChanged(object sender, EventArgs e)
{
if (ribbonCheckBoxVACPicker1.Checked)
{
usbController.setVAC1(true);
}
else
{
usbController.setVAC1(false);
}
}
private void ribbonCheckBoxVACPicker2_CheckBoxCheckChanged(object sender, EventArgs e)
{
if (ribbonCheckBoxVACPicker2.Checked)
{
usbController.setVAC2(true);
}
else
{
usbController.setVAC2(false);
}
}
private void JogStop(object sender, MouseEventArgs e)
{
kf.JogAxisStop();
}
private void ribbonButtonCameraComponentVision_Click(object sender, EventArgs e)
{
ComponentVision cmv = new ComponentVision();
cmv.Show(this);
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using Microsoft.Build.Shared;
using Microsoft.Build.Tasks;
using Microsoft.Build.Utilities;
using Xunit;
namespace Microsoft.Build.UnitTests.AxTlbImp_Tests
{
sealed public class AxImp_Tests
{
/// <summary>
/// Tests that the assembly being imported is passed to the command line
/// </summary>
[Fact]
public void ActiveXControlName()
{
var t = new ResolveComReference.AxImp();
string testParameterValue = "AxInterop.Foo.dll";
Assert.Null(t.ActiveXControlName); // "ActiveXControlName should be null by default"
t.ActiveXControlName = testParameterValue;
Assert.Equal(testParameterValue, t.ActiveXControlName); // "New ActiveXControlName value should be set"
CommandLine.ValidateHasParameter(t, testParameterValue, false /* no response file */);
}
/// <summary>
/// Tests that the assembly being imported is passed to the command line
/// </summary>
[Fact]
[Trait("Category", "mono-osx-failing")]
public void ActiveXControlNameWithSpaces()
{
var t = new ResolveComReference.AxImp();
string testParameterValue = @"c:\Program Files\AxInterop.Foo.dll";
Assert.Null(t.ActiveXControlName); // "ActiveXControlName should be null by default"
t.ActiveXControlName = testParameterValue;
Assert.Equal(testParameterValue, t.ActiveXControlName); // "New ActiveXControlName value should be set"
CommandLine.ValidateHasParameter(t, testParameterValue, false /* no response file */);
}
/// <summary>
/// Tests the /source switch
/// </summary>
[Fact]
public void GenerateSource()
{
var t = new ResolveComReference.AxImp();
Assert.False(t.GenerateSource); // "GenerateSource should be false by default"
CommandLine.ValidateNoParameterStartsWith(
t,
@"/source",
false /* no response file */);
t.GenerateSource = true;
Assert.True(t.GenerateSource); // "GenerateSource should be true"
CommandLine.ValidateHasParameter(
t,
@"/source",
false /* no response file */);
}
/// <summary>
/// Tests the /nologo switch
/// </summary>
[Fact]
public void NoLogo()
{
if (!NativeMethodsShared.IsWindows)
{
return; // "The /nologo switch is not available on Mono"
}
var t = new ResolveComReference.AxImp();
Assert.False(t.NoLogo); // "NoLogo should be false by default"
CommandLine.ValidateNoParameterStartsWith(t, @"/nologo", false /* no response file */);
t.NoLogo = true;
Assert.True(t.NoLogo); // "NoLogo should be true"
CommandLine.ValidateHasParameter(t, @"/nologo", false /* no response file */);
}
/// <summary>
/// Tests the /out: switch
/// </summary>
[Fact]
public void OutputAssembly()
{
var t = new ResolveComReference.AxImp();
string testParameterValue = "AxInterop.Foo.dll";
Assert.Null(t.OutputAssembly); // "OutputAssembly should be null by default"
CommandLine.ValidateNoParameterStartsWith(
t,
@"/out:",
false /* no response file */);
t.OutputAssembly = testParameterValue;
Assert.Equal(testParameterValue, t.OutputAssembly); // "New OutputAssembly value should be set"
CommandLine.ValidateHasParameter(
t,
@"/out:" + testParameterValue,
false /* no response file */);
}
/// <summary>
/// Tests the /out: switch, with a space in the output file
/// </summary>
[Fact]
public void OutputAssemblyWithSpaces()
{
var t = new ResolveComReference.AxImp();
string testParameterValue = @"c:\Program Files\AxInterop.Foo.dll";
Assert.Null(t.OutputAssembly); // "OutputAssembly should be null by default"
CommandLine.ValidateNoParameterStartsWith(
t,
@"/out:",
false /* no response file */);
t.OutputAssembly = testParameterValue;
Assert.Equal(testParameterValue, t.OutputAssembly); // "New OutputAssembly value should be set"
CommandLine.ValidateHasParameter(
t,
@"/out:" + testParameterValue,
false /* no response file */);
}
/// <summary>
/// Tests the /rcw: switch
/// </summary>
[Fact]
public void RuntimeCallableWrapper()
{
var t = new ResolveComReference.AxImp();
string testParameterValue = "Interop.Foo.dll";
Assert.Null(t.RuntimeCallableWrapperAssembly); // "RuntimeCallableWrapper should be null by default"
CommandLine.ValidateNoParameterStartsWith(
t,
@"/rcw:",
false /* no response file */);
t.RuntimeCallableWrapperAssembly = testParameterValue;
Assert.Equal(testParameterValue, t.RuntimeCallableWrapperAssembly); // "New RuntimeCallableWrapper value should be set"
CommandLine.ValidateHasParameter(
t,
@"/rcw:" + testParameterValue,
false /* no response file */);
}
/// <summary>
/// Tests the /rcw: switch with a space in the filename
/// </summary>
[Fact]
public void RuntimeCallableWrapperWithSpaces()
{
var t = new ResolveComReference.AxImp();
string testParameterValue = @"C:\Program Files\Microsoft Visual Studio 10.0\Interop.Foo.dll";
Assert.Null(t.RuntimeCallableWrapperAssembly); // "RuntimeCallableWrapper should be null by default"
CommandLine.ValidateNoParameterStartsWith(
t,
@"/rcw:",
false /* no response file */);
t.RuntimeCallableWrapperAssembly = testParameterValue;
Assert.Equal(testParameterValue, t.RuntimeCallableWrapperAssembly); // "New RuntimeCallableWrapper value should be set"
CommandLine.ValidateHasParameter(
t,
@"/rcw:" + testParameterValue,
false /* no response file */);
}
/// <summary>
/// Tests the /silent switch
/// </summary>
[Fact]
public void Silent()
{
var t = new ResolveComReference.AxImp();
Assert.False(t.Silent); // "Silent should be false by default"
CommandLine.ValidateNoParameterStartsWith(
t,
@"/silent",
false /* no response file */);
t.Silent = true;
Assert.True(t.Silent); // "Silent should be true"
CommandLine.ValidateHasParameter(
t,
@"/silent",
false /* no response file */);
}
/// <summary>
/// Tests the /verbose switch
/// </summary>
[Fact]
public void Verbose()
{
var t = new ResolveComReference.AxImp();
Assert.False(t.Verbose); // "Verbose should be false by default"
CommandLine.ValidateNoParameterStartsWith(
t,
@"/verbose",
false /* no response file */);
t.Verbose = true;
Assert.True(t.Verbose); // "Verbose should be true"
CommandLine.ValidateHasParameter(
t,
@"/verbose",
false /* no response file */);
}
/// <summary>
/// Tests that task does the right thing (fails) when no .ocx file is passed to it
/// </summary>
[Fact]
public void TaskFailsWithNoInputs()
{
var t = new ResolveComReference.AxImp();
Utilities.ExecuteTaskAndVerifyLogContainsErrorFromResource(t, "AxImp.NoInputFileSpecified");
}
}
}
| |
// 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.ObjectModel;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Runtime.ExceptionServices;
using Microsoft.VisualStudio.Debugger.Clr;
using Microsoft.VisualStudio.Debugger.ComponentInterfaces;
using Microsoft.VisualStudio.Debugger.Evaluation;
using Microsoft.VisualStudio.Debugger.Evaluation.ClrCompilation;
using Xunit;
namespace Microsoft.CodeAnalysis.ExpressionEvaluator
{
public abstract class ResultProviderTestBase
{
private readonly IDkmClrFormatter _formatter;
private readonly IDkmClrResultProvider _resultProvider;
internal readonly DkmInspectionContext DefaultInspectionContext;
internal ResultProviderTestBase(ResultProvider resultProvider, DkmInspectionContext defaultInspectionContext)
{
_formatter = resultProvider.Formatter;
_resultProvider = resultProvider;
this.DefaultInspectionContext = defaultInspectionContext;
}
internal DkmClrValue CreateDkmClrValue(
object value,
Type type = null,
string alias = null,
DkmEvaluationResultFlags evalFlags = DkmEvaluationResultFlags.None,
DkmClrValueFlags valueFlags = DkmClrValueFlags.None,
DkmInspectionContext inspectionContext = null)
{
if (type == null)
{
type = value.GetType();
}
return new DkmClrValue(
value,
DkmClrValue.GetHostObjectValue((TypeImpl)type, value),
new DkmClrType((TypeImpl)type),
alias,
_formatter,
evalFlags,
valueFlags,
inspectionContext);
}
internal DkmClrValue CreateDkmClrValue(
object value,
DkmClrType type,
string alias = null,
DkmEvaluationResultFlags evalFlags = DkmEvaluationResultFlags.None,
DkmClrValueFlags valueFlags = DkmClrValueFlags.None,
DkmInspectionContext inspectionContext = null)
{
return new DkmClrValue(
value,
DkmClrValue.GetHostObjectValue(type.GetLmrType(), value),
type,
alias,
_formatter,
evalFlags,
valueFlags,
inspectionContext);
}
internal DkmClrValue CreateErrorValue(
DkmClrType type,
string message,
DkmInspectionContext inspectionContext = null)
{
return new DkmClrValue(
value: null,
hostObjectValue: message,
type: type,
alias: null,
formatter: _formatter,
evalFlags: DkmEvaluationResultFlags.None,
valueFlags: DkmClrValueFlags.Error,
inspectionContext: inspectionContext);
}
#region Formatter Tests
internal string FormatNull<T>(bool useHexadecimal = false)
{
return FormatValue(null, typeof(T), useHexadecimal);
}
internal string FormatValue(object value, bool useHexadecimal = false)
{
return FormatValue(value, value.GetType(), useHexadecimal);
}
internal string FormatValue(object value, Type type, bool useHexadecimal = false)
{
var clrValue = CreateDkmClrValue(
value,
type,
inspectionContext: CreateDkmInspectionContext(_formatter, DkmEvaluationFlags.None, radix: useHexadecimal ? 16u : 10u));
return clrValue.GetValueString();
}
internal bool HasUnderlyingString(object value)
{
return HasUnderlyingString(value, value.GetType());
}
internal bool HasUnderlyingString(object value, Type type)
{
var clrValue = GetValueForUnderlyingString(value, type);
return clrValue.HasUnderlyingString();
}
internal string GetUnderlyingString(object value)
{
var clrValue = GetValueForUnderlyingString(value, value.GetType());
return clrValue.GetUnderlyingString();
}
internal DkmClrValue GetValueForUnderlyingString(object value, Type type)
{
return CreateDkmClrValue(
value,
type,
evalFlags: DkmEvaluationResultFlags.RawString,
inspectionContext: CreateDkmInspectionContext(_formatter, DkmEvaluationFlags.None, radix: 10));
}
#endregion
#region ResultProvider Tests
internal DkmInspectionContext CreateDkmInspectionContext(DkmEvaluationFlags flags = DkmEvaluationFlags.None, uint radix = 10)
{
return CreateDkmInspectionContext(_formatter, flags, radix);
}
internal static DkmInspectionContext CreateDkmInspectionContext(IDkmClrFormatter formatter, DkmEvaluationFlags flags, uint radix)
{
return new DkmInspectionContext(formatter, flags, radix);
}
internal DkmEvaluationResult FormatResult(string name, DkmClrValue value, DkmClrType declaredType = null)
{
return FormatResult(name, name, value, declaredType);
}
internal DkmEvaluationResult FormatResult(string name, string fullName, DkmClrValue value, DkmClrType declaredType = null)
{
// TODO: IDkmClrResultProvider.GetResult should have
// an explicit declaredType parameter. See #1099981
return ((ResultProvider)_resultProvider).GetResult(value, declaredType ?? value.Type, formatSpecifiers: null, resultName: name, resultFullName: fullName);
}
internal DkmEvaluationResult[] GetChildren(DkmEvaluationResult evalResult, DkmInspectionContext inspectionContext = null)
{
DkmEvaluationResultEnumContext enumContext;
const int size = 1;
var builder = ArrayBuilder<DkmEvaluationResult>.GetInstance();
// Request 0 children.
var items = GetChildren(evalResult, 0, inspectionContext, out enumContext);
Assert.Equal(items.Length, 0);
// Request >0 children.
items = GetChildren(evalResult, size, inspectionContext, out enumContext);
while (items.Length > 0)
{
builder.AddRange(items);
Assert.True(builder.Count <= enumContext.Count);
int offset = builder.Count;
// Request 0 items.
items = GetItems(enumContext, offset, 0);
Assert.Equal(items.Length, 0);
// Request >0 items.
items = GetItems(enumContext, offset, size);
}
Assert.Equal(builder.Count, enumContext.Count);
return builder.ToArrayAndFree();
}
internal DkmEvaluationResult[] GetChildren(DkmEvaluationResult evalResult, int initialRequestSize, DkmInspectionContext inspectionContext, out DkmEvaluationResultEnumContext enumContext)
{
DkmGetChildrenAsyncResult getChildrenResult = default(DkmGetChildrenAsyncResult);
_resultProvider.GetChildren(evalResult, null, initialRequestSize, inspectionContext ?? DefaultInspectionContext, r => { getChildrenResult = r; });
var exception = getChildrenResult.Exception;
if (exception != null)
{
ExceptionDispatchInfo.Capture(exception).Throw();
}
enumContext = getChildrenResult.EnumContext;
return getChildrenResult.InitialChildren;
}
internal DkmEvaluationResult[] GetItems(DkmEvaluationResultEnumContext enumContext, int startIndex, int count)
{
DkmEvaluationEnumAsyncResult getItemsResult = default(DkmEvaluationEnumAsyncResult);
_resultProvider.GetItems(enumContext, null, startIndex, count, r => { getItemsResult = r; });
var exception = getItemsResult.Exception;
if (exception != null)
{
ExceptionDispatchInfo.Capture(exception).Throw();
}
return getItemsResult.Items;
}
internal static DkmEvaluationResult EvalResult(
string name,
string value,
string type,
string fullName,
DkmEvaluationResultFlags flags = DkmEvaluationResultFlags.None,
DkmEvaluationResultCategory category = DkmEvaluationResultCategory.Other,
string editableValue = null,
DkmCustomUIVisualizerInfo[] customUIVisualizerInfo = null)
{
return DkmSuccessEvaluationResult.Create(
null,
null,
name,
fullName,
flags,
value,
editableValue,
type,
category,
default(DkmEvaluationResultAccessType),
default(DkmEvaluationResultStorageType),
default(DkmEvaluationResultTypeModifierFlags),
null,
(customUIVisualizerInfo != null) ? new ReadOnlyCollection<DkmCustomUIVisualizerInfo>(customUIVisualizerInfo) : null,
null,
null);
}
internal static DkmEvaluationResult EvalFailedResult(
string name,
string message,
string type = null,
string fullName = null,
DkmEvaluationResultFlags flags = DkmEvaluationResultFlags.None)
{
return DkmFailedEvaluationResult.Create(
null,
null,
name,
fullName,
message,
flags,
type,
null);
}
internal static void Verify(IReadOnlyList<DkmEvaluationResult> actual, params DkmEvaluationResult[] expected)
{
try
{
int n = actual.Count;
Assert.Equal(expected.Length, n);
for (int i = 0; i < n; i++)
{
Verify(actual[i], expected[i]);
}
}
catch
{
foreach (DkmSuccessEvaluationResult result in actual)
{
var optionalArgumentsTemplate = string.Empty;
if (result.Flags != DkmEvaluationResultFlags.None)
{
optionalArgumentsTemplate += ", {4}";
}
if (result.Category != DkmEvaluationResultCategory.Other)
{
optionalArgumentsTemplate += ", {5}";
}
if (result.EditableValue != null)
{
optionalArgumentsTemplate += ", editableValue: {6}";
}
var evalResultTemplate = "EvalResult({0}, {1}, {2}, {3}" + optionalArgumentsTemplate + "),";
var resultValue = (result.Value == null) ? "null" : Quote(Escape(result.Value));
Console.WriteLine(evalResultTemplate,
Quote(result.Name),
resultValue, Quote(result.Type),
(result.FullName != null) ? Quote(Escape(result.FullName)) : "null",
FormatEnumValue(result.Flags),
FormatEnumValue(result.Category),
Quote(result.EditableValue));
}
throw;
}
}
private static string Escape(string str)
{
return str.Replace("\"", "\\\"");
}
private static string Quote(string str)
{
return '"' + str + '"';
}
private static string FormatEnumValue(Enum e)
{
var parts = e.ToString().Split(new[] { ", " }, StringSplitOptions.RemoveEmptyEntries);
var enumTypeName = e.GetType().Name;
return string.Join(" | ", parts.Select(p => enumTypeName + "." + p));
}
internal static void Verify(DkmEvaluationResult actual, DkmEvaluationResult expected)
{
Assert.Equal(expected.Name, actual.Name);
Assert.Equal(expected.FullName, actual.FullName);
var expectedSuccess = expected as DkmSuccessEvaluationResult;
if (expectedSuccess != null)
{
var actualSuccess = (DkmSuccessEvaluationResult)actual;
Assert.Equal(expectedSuccess.Value, actualSuccess.Value);
Assert.Equal(expectedSuccess.Type, actualSuccess.Type);
Assert.Equal(expectedSuccess.Flags, actualSuccess.Flags);
Assert.Equal(expectedSuccess.Category, actualSuccess.Category);
Assert.Equal(expectedSuccess.EditableValue, actualSuccess.EditableValue);
// Verify the DebuggerVisualizerAttribute
Assert.True(
(expectedSuccess.CustomUIVisualizers == actualSuccess.CustomUIVisualizers) ||
(expectedSuccess.CustomUIVisualizers != null && actualSuccess.CustomUIVisualizers != null &&
expectedSuccess.CustomUIVisualizers.SequenceEqual(actualSuccess.CustomUIVisualizers, CustomUIVisualizerInfoComparer.Instance)));
}
else
{
var actualFailed = (DkmFailedEvaluationResult)actual;
var expectedFailed = (DkmFailedEvaluationResult)expected;
Assert.Equal(expectedFailed.ErrorMessage, actualFailed.ErrorMessage);
Assert.Equal(expectedFailed.Type, actualFailed.Type);
Assert.Equal(expectedFailed.Flags, actualFailed.Flags);
}
}
#endregion
private sealed class CustomUIVisualizerInfoComparer : IEqualityComparer<DkmCustomUIVisualizerInfo>
{
internal static readonly CustomUIVisualizerInfoComparer Instance = new CustomUIVisualizerInfoComparer();
bool IEqualityComparer<DkmCustomUIVisualizerInfo>.Equals(DkmCustomUIVisualizerInfo x, DkmCustomUIVisualizerInfo y)
{
return x == y ||
(x != null && y != null &&
x.Id == y.Id &&
x.MenuName == y.MenuName &&
x.Description == y.Description &&
x.Metric == y.Metric &&
x.UISideVisualizerTypeName == y.UISideVisualizerTypeName &&
x.UISideVisualizerAssemblyName == y.UISideVisualizerAssemblyName &&
x.UISideVisualizerAssemblyLocation == y.UISideVisualizerAssemblyLocation &&
x.DebuggeeSideVisualizerTypeName == y.DebuggeeSideVisualizerTypeName &&
x.DebuggeeSideVisualizerAssemblyName == y.DebuggeeSideVisualizerAssemblyName);
}
int IEqualityComparer<DkmCustomUIVisualizerInfo>.GetHashCode(DkmCustomUIVisualizerInfo obj)
{
throw new NotImplementedException();
}
}
}
}
| |
// Copyright 2019 Esri
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using ArcGIS.Core.Data;
using ArcGIS.Desktop.Framework;
using ArcGIS.Desktop.Framework.Contracts;
using ArcGIS.Desktop.Framework.Threading.Tasks;
using ArcGIS.Desktop.Mapping;
using System.Windows.Input;
using ArcGIS.Desktop.Catalog;
using ArcGIS.Desktop.Core;
using System.Windows.Data;
using ReplaceAttachments.Util;
using System.Threading.Tasks;
namespace ReplaceAttachments
{
internal class AttachmentsDockpaneViewModel : DockPane
{
private const string _dockPaneID = "ReplaceAttachments_AttachmentsDockpane";
private ObservableCollection<string> _layers = new ObservableCollection<string>();
private ObservableCollection<string> _relationshipClasses = new ObservableCollection<string>();
private ObservableCollection<string> _attachmentNames = new ObservableCollection<string>();
private object _lockCollections = new object();
private bool _isGoEnabled = false;
protected AttachmentsDockpaneViewModel() {
// when a new mapview is coming in we need to update the list of layers
ArcGIS.Desktop.Mapping.Events.ActiveMapViewChangedEvent.Subscribe(OnMapViewChanged);
BindingOperations.EnableCollectionSynchronization(_layers, _lockCollections);
BindingOperations.EnableCollectionSynchronization(_relationshipClasses, _lockCollections);
BindingOperations.EnableCollectionSynchronization(_attachmentNames, _lockCollections);
}
protected override Task InitializeAsync()
{
if (MapView.Active != null) UpdateLayers(MapView.Active.Map);
return Task.FromResult(0);
}
private void OnMapViewChanged (ArcGIS.Desktop.Mapping.Events.ActiveMapViewChangedEventArgs args)
{
if (args.IncomingView == null) return;
UpdateLayers(args.IncomingView.Map);
}
/// <summary>
/// Show the DockPane.
/// </summary>
internal static void Show()
{
DockPane pane = FrameworkApplication.DockPaneManager.Find(_dockPaneID);
if (pane == null)
return;
pane.Activate();
}
/// <summary>
/// Text shown near the top of the DockPane.
/// </summary>
private string _heading = "Replace Attachments for Related Feature Classes";
public string Heading
{
get { return _heading; }
set
{
SetProperty(ref _heading, value, () => Heading);
}
}
private string _selectedLayer;
private string _selectedRelationship;
private string _relatedFeatureClass;
private string oldAttachmentName;
private string newAttachment;
private Definition relatedFeatureClassDefinition;
public ObservableCollection<string> Layers
{
get { return _layers; }
}
public ObservableCollection<string> RelationshipClasses
{
get { return _relationshipClasses; }
}
public ObservableCollection<string> AttachmentNames
{
get { return _attachmentNames; }
}
public string SelectedRelationship
{
get { return _selectedRelationship; }
set
{
SetProperty(ref _selectedRelationship, value, () => SelectedRelationship);
UpdateRelatedFeatureClass();
UpdateIsGoEnabled();
}
}
public string SelectedLayer
{
get { return _selectedLayer; }
set
{
SetProperty(ref _selectedLayer, value, () => SelectedLayer);
UpdateRelationshipClasses();
UpdateIsGoEnabled();
}
}
public bool IsGoEnabled
{
get { return _isGoEnabled; }
set
{
SetProperty(ref _isGoEnabled, value, () => IsGoEnabled);
}
}
public string RelatedFeatureClass
{
get { return _relatedFeatureClass; }
set
{
SetProperty(ref _relatedFeatureClass, value, () => RelatedFeatureClass);
QueuedTask.Run(() =>
{
lock (_lockCollections) _attachmentNames.Clear();
using (Table table = (MapView.Active.Map.Layers.First(layer => layer.Name.Equals(SelectedLayer)) as FeatureLayer).GetTable())
{
if (!table.IsAttachmentEnabled()) return;
Geodatabase geodatabase = null;
if (table != null && table.GetDatastore() is Geodatabase)
geodatabase = table.GetDatastore() as Geodatabase;
if (geodatabase == null) return;
if (_relatedFeatureClass == null) return;
Table relatedTable = geodatabase.OpenDataset<Table>(_relatedFeatureClass);
if (relatedTable == null) return;
using (RowCursor rowCursor = table.Search(null, false))
{
while (rowCursor.MoveNext())
{
using (Row row = rowCursor.Current)
{
IEnumerable<Attachment> attachments = row.GetAttachments(null, true);
foreach (Attachment attachment in attachments)
{
lock (_lockCollections)
{
_attachmentNames.Add(attachment.GetName());
}
}
}
}
}
}
});
}
}
public string OldAttachmentName
{
get { return oldAttachmentName; }
set
{
SetProperty(ref oldAttachmentName, value, () => OldAttachmentName);
UpdateIsGoEnabled();
}
}
public string NewAttachment
{
get { return newAttachment; }
set
{
SetProperty(ref newAttachment, value, () => NewAttachment);
UpdateIsGoEnabled();
}
}
private ICommand _goReplaceAttachment = null;
public ICommand GoReplaceAttachment
{
get
{
if (_goReplaceAttachment == null) _goReplaceAttachment = new RelayCommand(Work, () => true);
return _goReplaceAttachment;
}
}
private ICommand _selectPath = null;
public ICommand SelectPath
{
get
{
if (_selectPath == null) _selectPath = new RelayCommand(GetPath, () => true);
return _selectPath;
}
}
private void GetPath(object param)
{
OpenItemDialog pathDialog = new OpenItemDialog();
pathDialog.Title = "Select Path to attachment";
pathDialog.InitialLocation = @"C:\Data\";
pathDialog.MultiSelect = false;
pathDialog.Filter = ItemFilters.rasters;
bool? ok = pathDialog.ShowDialog();
if (ok == true)
{
IEnumerable<Item> selectedItems = pathDialog.Items;
foreach (Item selectedItem in selectedItems)
NewAttachment = selectedItem.Path;
}
}
/// <summary>
/// Given that
/// 1. A layer has been selected
/// 2. A RelationshipClass has been selected
/// 3. The Table/FeatureClass related to the Table/FeatureClass corresponding to the layer selected has Attachments enabled
///
/// Then, this method will
/// 1. Get all the rows of the Related Table/FeatureClass
/// 2. Find if any row has Attachments which have the same name as the value of "OldAttachmentName"
/// 3. Replace the Attachment Data for the matching Attachments with the Data corresponding to "NewAttachment"
/// </summary>
private void Work(object param)
{
QueuedTask.Run(() =>
{
using (Table table = (MapView.Active.Map.Layers.First(layer => layer.Name.Equals(SelectedLayer)) as FeatureLayer).GetTable())
{
if (!table.IsAttachmentEnabled()) return;
Geodatabase geodatabase = null;
if (table != null && table.GetDatastore() is Geodatabase)
geodatabase = table.GetDatastore() as Geodatabase;
if (geodatabase == null) return;
if (_relatedFeatureClass == null) return;
Table relatedTable = geodatabase.OpenDataset<Table>(_relatedFeatureClass);
if (relatedTable == null) return;
if (String.IsNullOrEmpty(OldAttachmentName)) return;
if (String.IsNullOrEmpty(NewAttachment) || !File.Exists(NewAttachment)) return;
using (MemoryStream newAttachmentMemoryStream = CreateMemoryStreamFromContentsOf(NewAttachment))
{
using (RowCursor rowCursor = table.Search(null, false))
{
while (rowCursor.MoveNext())
{
using (Row row = rowCursor.Current)
{
IEnumerable<Attachment> attachments = row.GetAttachments(null, true).Where(attachment => attachment.GetName().Equals(oldAttachmentName));
foreach (Attachment attachment in attachments)
{
attachment.SetData(newAttachmentMemoryStream);
row.UpdateAttachment(attachment);
}
}
}
}
}
}
});
}
private async void UpdateIsGoEnabled()
{
IsGoEnabled = await QueuedTask.Run(() =>
{
bool isGoEnabled = false;
using (Table table = (MapView.Active.Map.Layers.First(layer => layer.Name.Equals(SelectedLayer)) as FeatureLayer).GetTable())
{
if (!table.IsAttachmentEnabled()) return isGoEnabled;
Geodatabase geodatabase = null;
if (table != null && table.GetDatastore() is Geodatabase)
geodatabase = table.GetDatastore() as Geodatabase;
if (geodatabase == null) return isGoEnabled;
if (_relatedFeatureClass == null) return isGoEnabled;
Table relatedTable = geodatabase.OpenDataset<Table>(_relatedFeatureClass);
if (relatedTable == null) return isGoEnabled;
if (String.IsNullOrEmpty(OldAttachmentName)) return isGoEnabled;
if (String.IsNullOrEmpty(NewAttachment) || !File.Exists(NewAttachment)) return isGoEnabled;
isGoEnabled = true;
}
return isGoEnabled;
});
}
/// <summary>
/// This method will populate the Layers (bound to the LayersComboBox) with all the Feature Layers present in the Active Map View
/// </summary>
public void UpdateLayers(Map map)
{
lock (_lockCollections)
{
_layers.Clear();
_layers.AddRange(new ObservableCollection<string>(map.Layers.Where(layer => layer is FeatureLayer).Select(layer => layer.Name)));
}
}
/// <summary>
/// Given that a Layer has been selected, this method will populate the RelationshipClasses (bound to RelationshipClasses Combobox) with the names of the RelationshipClasses
/// in which the FeatureClass/Table corresponding to the selected layer participates (as Origin or Destination)
/// </summary>
public void UpdateRelationshipClasses()
{
QueuedTask.Run(() =>
{
lock (_lockCollections) _relationshipClasses.Clear();
using (Table table = (MapView.Active.Map.Layers.First(layer => layer.Name.Equals(SelectedLayer)) as FeatureLayer).GetTable())
{
Geodatabase geodatabase = null;
if (table != null && table.GetDatastore() is Geodatabase)
geodatabase = table.GetDatastore() as Geodatabase;
if (geodatabase == null) return;
IReadOnlyList<RelationshipClassDefinition> relationshipClassDefinitions = geodatabase.GetDefinitions<RelationshipClassDefinition>();
IEnumerable<RelationshipClassDefinition> relavantRelationshipClassDefns = relationshipClassDefinitions.Where(definition =>
definition.GetOriginClass().Contains(table.GetName()) ||
definition.GetDestinationClass().Contains(table.GetName()));
IEnumerable<string> relationshipClassNames = relavantRelationshipClassDefns.Select(definition => definition.GetName());
lock (_lockCollections) _relationshipClasses.AddRange(new ObservableCollection<string>(relationshipClassNames));
}
});
}
/// <summary>
/// Given that the RelationshipClass is selected, this method will
/// 1. Get the Definitions of Datasets related by the selected relationship class
/// 2. Set the RelatedFeatureClass property to the Table/FeatureClass which is related to the FeatureClass corresponding to the selected layer
/// </summary>
public void UpdateRelatedFeatureClass()
{
QueuedTask.Run(() =>
{
using (Table table = (MapView.Active.Map.Layers.First(layer => layer.Name.Equals(SelectedLayer)) as FeatureLayer).GetTable())
{
Geodatabase geodatabase = null;
if (table != null && table.GetDatastore() is Geodatabase)
geodatabase = table.GetDatastore() as Geodatabase;
if (geodatabase == null) return;
if(SelectedRelationship == null) return;
IReadOnlyList<Definition> relatedDefinitions = geodatabase.GetRelatedDefinitions(geodatabase.GetDefinition<RelationshipClassDefinition>(SelectedRelationship),
DefinitionRelationshipType.DatasetsRelatedThrough);
relatedFeatureClassDefinition = relatedDefinitions.First(definition => definition.GetName() != table.GetDefinition().GetName());
RelatedFeatureClass = relatedFeatureClassDefinition.GetName();
}
});
}
/// <summary>
/// This is a helper method to generate a memory stream from a a file
/// </summary>
/// <param name="fileNameWithPath"></param>
/// <returns>Memory Stream representing the File</returns>
private static MemoryStream CreateMemoryStreamFromContentsOf(String fileNameWithPath)
{
MemoryStream memoryStream;
using (memoryStream = new MemoryStream())
using (FileStream file = new FileStream(fileNameWithPath, FileMode.Open, FileAccess.Read))
{
byte[] bytes = new byte[file.Length];
file.Read(bytes, 0, (int)file.Length);
memoryStream.Write(bytes, 0, (int)file.Length);
}
return memoryStream;
}
}
/// <summary>
/// Button implementation to show the DockPane.
/// </summary>
internal class AttachmentsDockpane_ShowButton : Button
{
protected override void OnClick()
{
AttachmentsDockpaneViewModel.Show();
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections;
using System.ComponentModel;
using System.Xml.Serialization;
namespace System.Xml.Schema
{
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public class XmlSchemaType : XmlSchemaAnnotated
{
private string _name;
private XmlSchemaDerivationMethod _final = XmlSchemaDerivationMethod.None;
private XmlSchemaDerivationMethod _derivedBy;
private XmlSchemaType _baseSchemaType;
private XmlSchemaDatatype _datatype;
private XmlSchemaDerivationMethod _finalResolved;
private volatile SchemaElementDecl _elementDecl;
private volatile XmlQualifiedName _qname = XmlQualifiedName.Empty;
private XmlSchemaType _redefined;
//compiled information
private XmlSchemaContentType _contentType;
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public static XmlSchemaSimpleType GetBuiltInSimpleType(XmlQualifiedName qualifiedName)
{
if (qualifiedName == null)
{
throw new ArgumentNullException(nameof(qualifiedName));
}
return DatatypeImplementation.GetSimpleTypeFromXsdType(qualifiedName);
}
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public static XmlSchemaSimpleType GetBuiltInSimpleType(XmlTypeCode typeCode)
{
return DatatypeImplementation.GetSimpleTypeFromTypeCode(typeCode);
}
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public static XmlSchemaComplexType GetBuiltInComplexType(XmlTypeCode typeCode)
{
if (typeCode == XmlTypeCode.Item)
{
return XmlSchemaComplexType.AnyType;
}
return null;
}
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public static XmlSchemaComplexType GetBuiltInComplexType(XmlQualifiedName qualifiedName)
{
if (qualifiedName == null)
{
throw new ArgumentNullException(nameof(qualifiedName));
}
if (qualifiedName.Equals(XmlSchemaComplexType.AnyType.QualifiedName))
{
return XmlSchemaComplexType.AnyType;
}
if (qualifiedName.Equals(XmlSchemaComplexType.UntypedAnyType.QualifiedName))
{
return XmlSchemaComplexType.UntypedAnyType;
}
return null;
}
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
[XmlAttribute("name")]
public string Name
{
get { return _name; }
set { _name = value; }
}
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
[XmlAttribute("final"), DefaultValue(XmlSchemaDerivationMethod.None)]
public XmlSchemaDerivationMethod Final
{
get { return _final; }
set { _final = value; }
}
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
[XmlIgnore]
public XmlQualifiedName QualifiedName
{
get { return _qname; }
}
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
[XmlIgnore]
public XmlSchemaDerivationMethod FinalResolved
{
get { return _finalResolved; }
}
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
[XmlIgnore]
[Obsolete("This property has been deprecated. Please use BaseXmlSchemaType property that returns a strongly typed base schema type. http://go.microsoft.com/fwlink/?linkid=14202")]
public object BaseSchemaType
{
get
{
if (_baseSchemaType == null)
return null;
if (_baseSchemaType.QualifiedName.Namespace == XmlReservedNs.NsXs)
{
return _baseSchemaType.Datatype;
}
return _baseSchemaType;
}
}
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
[XmlIgnore]
public XmlSchemaType BaseXmlSchemaType
{
get { return _baseSchemaType; }
}
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
[XmlIgnore]
public XmlSchemaDerivationMethod DerivedBy
{
get { return _derivedBy; }
}
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
[XmlIgnore]
public XmlSchemaDatatype Datatype
{
get { return _datatype; }
}
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
[XmlIgnore]
public virtual bool IsMixed
{
get { return false; }
set {; }
}
[XmlIgnore]
public XmlTypeCode TypeCode
{
get
{
if (this == XmlSchemaComplexType.AnyType)
{
return XmlTypeCode.Item;
}
if (_datatype == null)
{
return XmlTypeCode.None;
}
return _datatype.TypeCode;
}
}
[XmlIgnore]
internal XmlValueConverter ValueConverter
{
get
{
if (_datatype == null)
{ //Default converter
return XmlUntypedConverter.Untyped;
}
return _datatype.ValueConverter;
}
}
internal XmlReader Validate(XmlReader reader, XmlResolver resolver, XmlSchemaSet schemaSet, ValidationEventHandler valEventHandler)
{
if (schemaSet != null)
{
XmlReaderSettings readerSettings = new XmlReaderSettings();
readerSettings.ValidationType = ValidationType.Schema;
readerSettings.Schemas = schemaSet;
readerSettings.ValidationEventHandler += valEventHandler;
return new XsdValidatingReader(reader, resolver, readerSettings, this);
}
return null;
}
internal XmlSchemaContentType SchemaContentType
{
get
{
return _contentType;
}
}
internal void SetQualifiedName(XmlQualifiedName value)
{
_qname = value;
}
internal void SetFinalResolved(XmlSchemaDerivationMethod value)
{
_finalResolved = value;
}
internal void SetBaseSchemaType(XmlSchemaType value)
{
_baseSchemaType = value;
}
internal void SetDerivedBy(XmlSchemaDerivationMethod value)
{
_derivedBy = value;
}
internal void SetDatatype(XmlSchemaDatatype value)
{
_datatype = value;
}
internal SchemaElementDecl ElementDecl
{
get { return _elementDecl; }
set { _elementDecl = value; }
}
[XmlIgnore]
internal XmlSchemaType Redefined
{
get { return _redefined; }
set { _redefined = value; }
}
internal virtual XmlQualifiedName DerivedFrom
{
get { return XmlQualifiedName.Empty; }
}
internal void SetContentType(XmlSchemaContentType value)
{
_contentType = value;
}
public static bool IsDerivedFrom(XmlSchemaType derivedType, XmlSchemaType baseType, XmlSchemaDerivationMethod except)
{
if (derivedType == null || baseType == null)
{
return false;
}
if (derivedType == baseType)
{
return true;
}
if (baseType == XmlSchemaComplexType.AnyType)
{ //Not checking for restriction blocked since all types are implicitly derived by restriction from xs:anyType
return true;
}
do
{
XmlSchemaSimpleType dt = derivedType as XmlSchemaSimpleType;
XmlSchemaSimpleType bt = baseType as XmlSchemaSimpleType;
if (bt != null && dt != null)
{ //SimpleTypes
if (bt == DatatypeImplementation.AnySimpleType)
{ //Not checking block=restriction
return true;
}
if ((except & derivedType.DerivedBy) != 0 || !dt.Datatype.IsDerivedFrom(bt.Datatype))
{
return false;
}
return true;
}
else
{ //Complex types
if ((except & derivedType.DerivedBy) != 0)
{
return false;
}
derivedType = derivedType.BaseXmlSchemaType;
if (derivedType == baseType)
{
return true;
}
}
} while (derivedType != null);
return false;
}
internal static bool IsDerivedFromDatatype(XmlSchemaDatatype derivedDataType, XmlSchemaDatatype baseDataType, XmlSchemaDerivationMethod except)
{
if (DatatypeImplementation.AnySimpleType.Datatype == baseDataType)
{
return true;
}
return derivedDataType.IsDerivedFrom(baseDataType);
}
[XmlIgnore]
internal override string NameAttribute
{
get { return Name; }
set { Name = value; }
}
}
}
| |
// <copyright file="Complex32Test.cs" company="Math.NET">
// Math.NET Numerics, part of the Math.NET Project
// http://numerics.mathdotnet.com
// http://github.com/mathnet/mathnet-numerics
// http://mathnetnumerics.codeplex.com
// Copyright (c) 2009-2010 Math.NET
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
// </copyright>
using System;
using NUnit.Framework;
namespace MathNet.Numerics.UnitTests.ComplexTests
{
#if NOSYSNUMERICS
using Complex = Numerics.Complex;
#else
using Complex = System.Numerics.Complex;
#endif
/// <summary>
/// Complex32 tests.
/// </summary>
[TestFixture]
public class Complex32Test
{
/// <summary>
/// Can add a complex number and a double using operator.
/// </summary>
[Test]
public void CanAddComplexNumberAndDoubleUsingOperator()
{
Assert.That((Complex32.NaN + float.NaN).IsNaN());
Assert.That((float.NaN + Complex32.NaN).IsNaN());
Assert.That((float.PositiveInfinity + Complex32.One).IsInfinity());
Assert.That((Complex32.PositiveInfinity + 1.0f).IsInfinity());
Assert.That((Complex32.One + 0.0f) == Complex32.One);
Assert.That((0.0f + Complex32.One) == Complex32.One);
Assert.That(new Complex32(1.1f, -2.2f) + 1.1f == new Complex32(2.2f, -2.2f));
Assert.That(-2.2f + new Complex32(-1.1f, 2.2f) == new Complex32(-3.3f, 2.2f));
}
/// <summary>
/// Can add/subtract complex numbers using operator.
/// </summary>
[Test]
public void CanAddSubtractComplexNumbersUsingOperator()
{
Assert.That((Complex32.NaN - Complex32.NaN).IsNaN());
Assert.That((Complex32.PositiveInfinity - Complex32.One).IsInfinity());
Assert.That((Complex32.One - Complex32.Zero) == Complex32.One);
Assert.That((new Complex32(1.1f, -2.2f) - new Complex32(1.1f, -2.2f)) == Complex32.Zero);
}
/// <summary>
/// Can add two complex numbers.
/// </summary>
[Test]
public void CanAddTwoComplexNumbers()
{
Assert.That(Complex32.Add(Complex32.NaN, (Complex32.NaN)).IsNaN());
Assert.That(Complex32.Add(Complex32.PositiveInfinity, Complex32.One).IsInfinity());
Assert.That(Complex32.Add(Complex32.One, Complex32.Zero) == Complex32.One);
Assert.That(Complex32.Add(new Complex32(1.1f, -2.2f), new Complex32(-1.1f, 2.2f)) == Complex32.Zero);
}
/// <summary>
/// Can add two complex numbers using operator.
/// </summary>
[Test]
public void CanAddTwoComplexNumbersUsingOperator()
{
Assert.That((Complex32.NaN + Complex32.NaN).IsNaN());
Assert.That((Complex32.PositiveInfinity + Complex32.One).IsInfinity());
Assert.That((Complex32.One + Complex32.Zero) == Complex32.One);
Assert.That((new Complex32(1.1f, -2.2f) + new Complex32(-1.1f, 2.2f)) == Complex32.Zero);
}
/// <summary>
/// Can get hash code.
/// </summary>
[Test]
public void CanCalculateHashCode()
{
Assert.AreEqual(new Complex32(1, 2).GetHashCode(), new Complex32(1, 2).GetHashCode());
Assert.AreNotEqual(new Complex32(1, 0).GetHashCode(), new Complex32(0, 1).GetHashCode());
Assert.AreNotEqual(new Complex32(1, 1).GetHashCode(), new Complex32(2, 2).GetHashCode());
Assert.AreNotEqual(new Complex32(1, 0).GetHashCode(), new Complex32(-1, 0).GetHashCode());
Assert.AreNotEqual(new Complex32(0, 1).GetHashCode(), new Complex32(0, -1).GetHashCode());
}
/// <summary>
/// Can compute exponential.
/// </summary>
/// <param name="real">Real part.</param>
/// <param name="imag">Imaginary part.</param>
/// <param name="expectedReal">Expected real part.</param>
/// <param name="expectedImag">Expected imaginary part.</param>
[TestCase(0.0f, 0.0f, 1.0f, 0.0f)]
[TestCase(0.0f, 1.0f, 0.54030230586813977f, 0.8414709848078965f)]
[TestCase(-1.0f, 1.0f, 0.19876611034641295f, 0.30955987565311222f)]
[TestCase(-111.0f, 111.0f, -2.3259065941590448e-49f, -5.1181940185795617e-49f)]
public void CanComputeExponential(float real, float imag, float expectedReal, float expectedImag)
{
var value = new Complex32(real, imag);
var expected = new Complex32(expectedReal, expectedImag);
AssertHelpers.AlmostEqualRelative(expected, value.Exponential(), 6);
}
/// <summary>
/// Can compute natural logarithm.
/// </summary>
/// <param name="real">Real part.</param>
/// <param name="imag">Imaginary part.</param>
/// <param name="expectedReal">Expected real part.</param>
/// <param name="expectedImag">Expected imaginary part.</param>
[TestCase(0.0f, 0.0f, float.NegativeInfinity, 0.0f)]
[TestCase(0.0f, 1.0f, 0.0f, 1.5707963267948966f)]
[TestCase(-1.0f, 1.0f, 0.34657359027997264f, 2.3561944901923448f)]
[TestCase(-111.1f, 111.1f, 5.0570042869255571f, 2.3561944901923448f)]
[TestCase(111.1f, -111.1f, 5.0570042869255571f, -0.78539816339744828f)]
public void CanComputeNaturalLogarithm(float real, float imag, float expectedReal, float expectedImag)
{
var value = new Complex32(real, imag);
var expected = new Complex32(expectedReal, expectedImag);
AssertHelpers.AlmostEqualRelative(expected, value.NaturalLogarithm(), 7);
}
/// <summary>
/// Can compute power.
/// </summary>
[Test]
public void CanComputePower()
{
var a = new Complex32(1.19209289550780998537e-7f, 1.19209289550780998537e-7f);
var b = new Complex32(1.19209289550780998537e-7f, 1.19209289550780998537e-7f);
AssertHelpers.AlmostEqualRelative(
new Complex32(9.99998047207974718744e-1f, -1.76553541154378695012e-6f), a.Power(b), 6);
a = new Complex32(0.0f, 1.19209289550780998537e-7f);
b = new Complex32(0.0f, -1.19209289550780998537e-7f);
AssertHelpers.AlmostEqualRelative(new Complex32(1.00000018725172576491f, 1.90048076369011843105e-6f), a.Power(b), 6);
a = new Complex32(0.0f, -1.19209289550780998537e-7f);
b = new Complex32(0.0f, 0.5f);
AssertHelpers.AlmostEqualRelative(new Complex32(-2.56488189382693049636e-1f, -2.17823120666116144959f), a.Power(b), 4);
a = new Complex32(0.0f, 0.5f);
b = new Complex32(0.0f, -0.5f);
AssertHelpers.AlmostEqualRelative(new Complex32(2.06287223508090495171f, 7.45007062179724087859e-1f), a.Power(b), 6);
a = new Complex32(0.0f, -0.5f);
b = new Complex32(0.0f, 1.0f);
AssertHelpers.AlmostEqualRelative(new Complex32(3.70040633557002510874f, -3.07370876701949232239f), a.Power(b), 6);
a = new Complex32(0.0f, 2.0f);
b = new Complex32(0.0f, -2.0f);
AssertHelpers.AlmostEqualRelative(new Complex32(4.24532146387429353891f, -2.27479427903521192648e1f), a.Power(b), 5);
a = new Complex32(0.0f, -8.388608e6f);
b = new Complex32(1.19209289550780998537e-7f, 0.0f);
AssertHelpers.AlmostEqualRelative(new Complex32(1.00000190048219620166f, -1.87253870018168043834e-7f), a.Power(b), 6);
a = new Complex32(0.0f, 0.0f);
b = new Complex32(0.0f, 0.0f);
AssertHelpers.AlmostEqualRelative(new Complex32(1.0f, 0.0f), a.Power(b), 6);
a = new Complex32(0.0f, 0.0f);
b = new Complex32(1.0f, 0.0f);
AssertHelpers.AlmostEqualRelative(new Complex32(0.0f, 0.0f), a.Power(b), 6);
a = new Complex32(0.0f, 0.0f);
b = new Complex32(-1.0f, 0.0f);
AssertHelpers.AlmostEqualRelative(new Complex32(float.PositiveInfinity, 0.0f), a.Power(b), 6);
a = new Complex32(0.0f, 0.0f);
b = new Complex32(-1.0f, 1.0f);
AssertHelpers.AlmostEqualRelative(new Complex32(float.PositiveInfinity, float.PositiveInfinity), a.Power(b), 6);
a = new Complex32(0.0f, 0.0f);
b = new Complex32(0.0f, 1.0f);
Assert.That(a.Power(b).IsNaN());
}
/// <summary>
/// Can compute root.
/// </summary>
[Test]
public void CanComputeRoot()
{
var a = new Complex32(1.19209289550780998537e-7f, 1.19209289550780998537e-7f);
var b = new Complex32(1.19209289550780998537e-7f, 1.19209289550780998537e-7f);
AssertHelpers.AlmostEqualRelative(new Complex32(0.0f, 0.0f), a.Root(b), 6);
a = new Complex32(0.0f, -1.19209289550780998537e-7f);
b = new Complex32(0.0f, 0.5f);
AssertHelpers.AlmostEqualRelative(new Complex32(0.038550761943650161f, 0.019526430428319544f), a.Root(b), 5);
a = new Complex32(0.0f, 0.5f);
b = new Complex32(0.0f, -0.5f);
AssertHelpers.AlmostEqualRelative(new Complex32(0.007927894711475968f, -0.042480480425152213f), a.Root(b), 5);
a = new Complex32(0.0f, -0.5f);
b = new Complex32(0.0f, 1.0f);
AssertHelpers.AlmostEqualRelative(new Complex32(0.15990905692806806f, 0.13282699942462053f), a.Root(b), 6);
a = new Complex32(0.0f, 2.0f);
b = new Complex32(0.0f, -2.0f);
AssertHelpers.AlmostEqualRelative(new Complex32(0.42882900629436788f, 0.15487175246424678f), a.Root(b), 6);
a = new Complex32(0.0f, -8.388608e6f);
b = new Complex32(1.19209289550780998537e-7f, 0.0f);
AssertHelpers.AlmostEqualRelative(new Complex32(float.PositiveInfinity, float.NegativeInfinity), a.Root(b), 6);
}
/// <summary>
/// Can compute square.
/// </summary>
[Test]
public void CanComputeSquare()
{
var complex = new Complex32(1.19209289550780998537e-7f, 1.19209289550780998537e-7f);
AssertHelpers.AlmostEqualRelative(new Complex32(0, 2.8421709430403888e-14f), complex.Square(), 7);
complex = new Complex32(0.0f, 1.19209289550780998537e-7f);
AssertHelpers.AlmostEqualRelative(new Complex32(-1.4210854715201944e-14f, 0.0f), complex.Square(), 7);
complex = new Complex32(0.0f, -1.19209289550780998537e-7f);
AssertHelpers.AlmostEqualRelative(new Complex32(-1.4210854715201944e-14f, 0.0f), complex.Square(), 7);
complex = new Complex32(0.0f, 0.5f);
AssertHelpers.AlmostEqualRelative(new Complex32(-0.25f, 0.0f), complex.Square(), 7);
complex = new Complex32(0.0f, -0.5f);
AssertHelpers.AlmostEqualRelative(new Complex32(-0.25f, 0.0f), complex.Square(), 7);
complex = new Complex32(0.0f, -8.388608e6f);
AssertHelpers.AlmostEqualRelative(new Complex32(-70368744177664.0f, 0.0f), complex.Square(), 7);
}
/// <summary>
/// Can compute square root.
/// </summary>
[Test]
public void CanComputeSquareRoot()
{
var complex = new Complex32(1.19209289550780998537e-7f, 1.19209289550780998537e-7f);
AssertHelpers.AlmostEqualRelative(
new Complex32(0.00037933934912842666f, 0.00015712750315077684f), complex.SquareRoot(), 7);
complex = new Complex32(0.0f, 1.19209289550780998537e-7f);
AssertHelpers.AlmostEqualRelative(
new Complex32(0.00024414062499999973f, 0.00024414062499999976f), complex.SquareRoot(), 7);
complex = new Complex32(0.0f, -1.19209289550780998537e-7f);
AssertHelpers.AlmostEqualRelative(
new Complex32(0.00024414062499999973f, -0.00024414062499999976f), complex.SquareRoot(), 7);
complex = new Complex32(0.0f, 0.5f);
AssertHelpers.AlmostEqualRelative(new Complex32(0.5f, 0.5f), complex.SquareRoot(), 7);
complex = new Complex32(0.0f, -0.5f);
AssertHelpers.AlmostEqualRelative(new Complex32(0.5f, -0.5f), complex.SquareRoot(), 7);
complex = new Complex32(0.0f, -8.388608e6f);
AssertHelpers.AlmostEqualRelative(new Complex32(2048.0f, -2048.0f), complex.SquareRoot(), 7);
complex = new Complex32(8.388608e6f, 1.19209289550780998537e-7f);
AssertHelpers.AlmostEqualRelative(new Complex32(2896.3093757400989f, 2.0579515874459933e-11f), complex.SquareRoot(), 7);
complex = new Complex32(0.0f, 0.0f);
AssertHelpers.AlmostEqualRelative(Complex32.Zero, complex.SquareRoot(), 7);
}
/// <summary>
/// Can convert a double to a complex.
/// </summary>
[Test]
public void CanConvertDoubleToComplex()
{
Assert.That(((Complex32)float.NaN).IsNaN());
Assert.That(((Complex32)float.NegativeInfinity).IsInfinity());
Assert.AreEqual((Complex32)1.1f, new Complex32(1.1f, 0));
}
/// <summary>
/// Can create a complex number using constructor.
/// </summary>
[Test]
public void CanCreateComplexNumberUsingConstructor()
{
var complex = new Complex32(1.1f, -2.2f);
Assert.AreEqual(1.1f, complex.Real, "Real part is 1.1f.");
Assert.AreEqual(-2.2f, complex.Imaginary, "Imaginary part is -2.2f.");
}
/// <summary>
/// Can create a complex number with modulus argument.
/// </summary>
[Test]
public void CanCreateComplexNumberWithModulusArgument()
{
var complex = Complex32.FromPolarCoordinates(2, (float)-Math.PI / 6);
Assert.AreEqual((float)Constants.Sqrt3, complex.Real, 1e-7f, "Real part is Sqrt(3).");
Assert.AreEqual(-1.0f, complex.Imaginary, 1e-7f, "Imaginary part is -1.");
}
/// <summary>
/// Can create a complex number with real imaginary initializer.
/// </summary>
[Test]
public void CanCreateComplexNumberWithRealImaginaryInitializer()
{
var complex = new Complex32(1.1f, -2.2f);
Assert.AreEqual(1.1f, complex.Real, "Real part is 1.1f.");
Assert.AreEqual(-2.2f, complex.Imaginary, "Imaginary part is -2.2f.");
}
/// <summary>
/// Can determine if imaginary is unit.
/// </summary>
[Test]
public void CanDetermineIfImaginaryUnit()
{
var complex = new Complex32(0, 1);
Assert.IsTrue(complex.IsImaginaryOne(), "Imaginary unit");
}
/// <summary>
/// Can determine if a complex is infinity.
/// </summary>
[Test]
public void CanDetermineIfInfinity()
{
var complex = new Complex32(float.PositiveInfinity, 1);
Assert.IsTrue(complex.IsInfinity(), "Real part is infinity.");
complex = new Complex32(1, float.NegativeInfinity);
Assert.IsTrue(complex.IsInfinity(), "Imaginary part is infinity.");
complex = new Complex32(float.NegativeInfinity, float.PositiveInfinity);
Assert.IsTrue(complex.IsInfinity(), "Both parts are infinity.");
}
/// <summary>
/// Can determine if a complex is not a number.
/// </summary>
[Test]
public void CanDetermineIfNaN()
{
var complex = new Complex32(float.NaN, 1);
Assert.IsTrue(complex.IsNaN(), "Real part is NaN.");
complex = new Complex32(1, float.NaN);
Assert.IsTrue(complex.IsNaN(), "Imaginary part is NaN.");
complex = new Complex32(float.NaN, float.NaN);
Assert.IsTrue(complex.IsNaN(), "Both parts are NaN.");
}
/// <summary>
/// Can determine Complex32 number with a value of one.
/// </summary>
[Test]
public void CanDetermineIfOneValueComplexNumber()
{
var complex = new Complex32(1, 0);
Assert.IsTrue(complex.IsOne(), "Complex32 number with a value of one.");
}
/// <summary>
/// Can determine if a complex is a real non-negative number.
/// </summary>
[Test]
public void CanDetermineIfRealNonNegativeNumber()
{
var complex = new Complex32(1, 0);
Assert.IsTrue(complex.IsReal(), "Is a real non-negative number.");
}
/// <summary>
/// Can determine if a complex is a real number.
/// </summary>
[Test]
public void CanDetermineIfRealNumber()
{
var complex = new Complex32(-1, 0);
Assert.IsTrue(complex.IsReal(), "Is a real number.");
}
/// <summary>
/// Can determine if a complex is a zero number.
/// </summary>
[Test]
public void CanDetermineIfZeroValueComplexNumber()
{
var complex = new Complex32(0, 0);
Assert.IsTrue(complex.IsZero(), "Zero complex number.");
}
/// <summary>
/// Can divide a complex number and a double using operators.
/// </summary>
[Test]
public void CanDivideComplexNumberAndDoubleUsingOperators()
{
Assert.That((Complex32.NaN * 1.0f).IsNaN());
Assert.AreEqual(new Complex32(-2, 2), new Complex32(4, -4) / -2);
Assert.AreEqual(new Complex32(0.25f, 0.25f), 2 / new Complex32(4, -4));
Assert.AreEqual(Complex32.PositiveInfinity, 2.0f / Complex32.Zero);
Assert.AreEqual(Complex32.PositiveInfinity, Complex32.One / 0);
}
/// <summary>
/// Can divide two complex numbers.
/// </summary>
[Test]
public void CanDivideTwoComplexNumbers()
{
Assert.That(Complex32.Divide(Complex32.NaN, Complex32.One).IsNaN());
Assert.AreEqual(new Complex32(-2, 0), Complex32.Divide(new Complex32(4, -4), new Complex32(-2, 2)));
Assert.AreEqual(Complex32.PositiveInfinity, Complex32.Divide(Complex32.One, Complex32.Zero));
}
/// <summary>
/// Can divide two complex numbers using operators.
/// </summary>
[Test]
public void CanDivideTwoComplexNumbersUsingOperators()
{
Assert.That((Complex32.NaN / Complex32.One).IsNaN());
Assert.AreEqual(new Complex32(-2, 0), new Complex32(4, -4) / new Complex32(-2, 2));
Assert.AreEqual(Complex32.PositiveInfinity, Complex32.One / Complex32.Zero);
}
/// <summary>
/// Can multiple a complex number and a double using operators.
/// </summary>
[Test]
public void CanMultipleComplexNumberAndDoubleUsingOperators()
{
Assert.That((Complex32.NaN * 1.0f).IsNaN());
Assert.AreEqual(new Complex32(8, -8), new Complex32(4, -4) * 2);
Assert.AreEqual(new Complex32(8, -8), 2 * new Complex32(4, -4));
}
/// <summary>
/// Can multiple two complex numbers.
/// </summary>
[Test]
public void CanMultipleTwoComplexNumbers()
{
Assert.That(Complex32.Multiply(Complex32.NaN, Complex32.One).IsNaN());
Assert.AreEqual(new Complex32(0, 16), Complex32.Multiply(new Complex32(4, -4), new Complex32(-2, 2)));
}
/// <summary>
/// Can multiple two complex numbers using operators.
/// </summary>
[Test]
public void CanMultipleTwoComplexNumbersUsingOperators()
{
Assert.That((Complex32.NaN * Complex32.One).IsNaN());
Assert.AreEqual(new Complex32(0, 16), new Complex32(4, -4) * new Complex32(-2, 2));
}
/// <summary>
/// Can negate.
/// </summary>
[Test]
public void CanNegateValue()
{
var complex = new Complex32(1.1f, -2.2f);
Assert.AreEqual(new Complex32(-1.1f, 2.2f), Complex32.Negate(complex));
}
/// <summary>
/// Can negate using operator.
/// </summary>
[Test]
public void CanNegateValueUsingOperator()
{
var complex = new Complex32(1.1f, -2.2f);
Assert.AreEqual(new Complex32(-1.1f, 2.2f), -complex);
}
/// <summary>
/// Can subtract a complex number and a double using operator.
/// </summary>
[Test]
public void CanSubtractComplexNumberAndDoubleUsingOperator()
{
Assert.That((Complex32.NaN - float.NaN).IsNaN());
Assert.That((float.NaN - Complex32.NaN).IsNaN());
Assert.That((float.PositiveInfinity - Complex32.One).IsInfinity());
Assert.That((Complex32.PositiveInfinity - 1.0f).IsInfinity());
Assert.That((Complex32.One - 0.0f) == Complex32.One);
Assert.That((0.0f - Complex32.One) == -Complex32.One);
Assert.That(new Complex32(1.1f, -2.2f) - 1.1f == new Complex32(0.0f, -2.2f));
Assert.That(-2.2f - new Complex32(-1.1f, 2.2f) == new Complex32(-1.1f, -2.2f));
}
/// <summary>
/// Can subtract two complex numbers.
/// </summary>
[Test]
public void CanSubtractTwoComplexNumbers()
{
Assert.That(Complex32.Subtract(Complex32.NaN, Complex32.NaN).IsNaN());
Assert.That(Complex32.Subtract(Complex32.PositiveInfinity, Complex32.One).IsInfinity());
Assert.That(Complex32.Subtract(Complex32.One, Complex32.Zero) == Complex32.One);
Assert.That(Complex32.Subtract(new Complex32(1.1f, -2.2f), new Complex32(1.1f, -2.2f)) == Complex32.Zero);
}
/// <summary>
/// Can test for equality.
/// </summary>
[Test]
public void CanTestForEquality()
{
Assert.AreNotEqual(Complex32.NaN, Complex32.NaN);
Assert.AreEqual(Complex32.PositiveInfinity, Complex32.PositiveInfinity);
Assert.AreEqual(new Complex32(1.1f, -2.2f), new Complex32(1.1f, -2.2f));
Assert.AreNotEqual(new Complex32(-1.1f, 2.2f), new Complex32(1.1f, -2.2f));
}
/// <summary>
/// Can test for equality using operators.
/// </summary>
[Test]
public void CanTestForEqualityUsingOperators()
{
#pragma warning disable 1718
Assert.That(Complex32.NaN != Complex32.NaN);
Assert.That(Complex32.PositiveInfinity == Complex32.PositiveInfinity);
#pragma warning restore 1718
Assert.That(new Complex32(1.1f, -2.2f) == new Complex32(1.1f, -2.2f));
Assert.That(new Complex32(-1.1f, 2.2f) != new Complex32(1.1f, -2.2f));
}
/// <summary>
/// Can use unary "+" operator.
/// </summary>
[Test]
public void CanUsePlusOperator()
{
var complex = new Complex32(1.1f, -2.2f);
Assert.AreEqual(complex, +complex);
}
/// <summary>
/// Can compute magnitude.
/// </summary>
/// <param name="real">Real part.</param>
/// <param name="imag">Imaginary part.</param>
/// <param name="expected">Expected value.</param>
[TestCase(0.0f, 0.0f, 0.0f)]
[TestCase(0.0f, 1.0f, 1.0f)]
[TestCase(-1.0f, 1.0f, 1.4142135623730951f)]
[TestCase(-111.1f, 111.1f, 157.11912677965086f)]
public void CanComputeMagnitude(float real, float imag, float expected)
{
Assert.AreEqual(expected, new Complex32(real, imag).Magnitude);
}
/// <summary>
/// Can compute sign.
/// </summary>
/// <param name="real">Real part.</param>
/// <param name="imag">Imaginary part.</param>
/// <param name="expectedReal">Expected real value.</param>
/// <param name="expectedImag">Expected imaginary value.</param>
[TestCase(float.PositiveInfinity, float.PositiveInfinity, (float)Constants.Sqrt1Over2, (float)Constants.Sqrt1Over2)]
[TestCase(float.PositiveInfinity, float.NegativeInfinity, (float)Constants.Sqrt1Over2, (float)-Constants.Sqrt1Over2)]
[TestCase(float.NegativeInfinity, float.PositiveInfinity, (float)-Constants.Sqrt1Over2, (float)-Constants.Sqrt1Over2)]
[TestCase(float.NegativeInfinity, float.NegativeInfinity, (float)-Constants.Sqrt1Over2, (float)Constants.Sqrt1Over2)]
[TestCase(0.0f, 0.0f, 0.0f, 0.0f)]
[TestCase(-1.0f, 1.0f, -0.70710678118654746f, 0.70710678118654746f)]
[TestCase(-111.1f, 111.1f, -0.70710678118654746f, 0.70710678118654746f)]
public void CanComputeSign(float real, float imag, float expectedReal, float expectedImag)
{
Assert.AreEqual(new Complex32(expectedReal, expectedImag), new Complex32(real, imag).Sign);
}
/// <summary>
/// Can convert a decimal to a complex.
/// </summary>
[Test]
public void CanConvertDecimalToComplex()
{
var orginal = new decimal(1.234567890);
var complex = (Complex32)orginal;
Assert.AreEqual((float)1.234567890, complex.Real);
Assert.AreEqual(0.0f, complex.Imaginary);
}
/// <summary>
/// Can convert a byte to a complex.
/// </summary>
[Test]
public void CanConvertByteToComplex()
{
const byte Orginal = 123;
var complex = (Complex32)Orginal;
Assert.AreEqual(123, complex.Real);
Assert.AreEqual(0.0f, complex.Imaginary);
}
/// <summary>
/// Can convert a short to a complex.
/// </summary>
[Test]
public void CanConvertShortToComplex()
{
const short Orginal = 123;
var complex = (Complex32)Orginal;
Assert.AreEqual(123, complex.Real);
Assert.AreEqual(0.0f, complex.Imaginary);
}
/// <summary>
/// Can convert an int to a complex.
/// </summary>
[Test]
public void CanConvertIntToComplex()
{
const int Orginal = 123;
var complex = (Complex32)Orginal;
Assert.AreEqual(123, complex.Real);
Assert.AreEqual(0.0f, complex.Imaginary);
}
/// <summary>
/// Can convert a long to a complex.
/// </summary>
[Test]
public void CanConvertLongToComplex()
{
const long Orginal = 123;
var complex = (Complex32)Orginal;
Assert.AreEqual(123, complex.Real);
Assert.AreEqual(0.0f, complex.Imaginary);
}
/// <summary>
/// Can convert an uint to a complex.
/// </summary>
[Test]
public void CanConvertUIntToComplex()
{
const uint Orginal = 123;
var complex = (Complex32)Orginal;
Assert.AreEqual(123, complex.Real);
Assert.AreEqual(0.0f, complex.Imaginary);
}
/// <summary>
/// Can convert an ulong to complex.
/// </summary>
[Test]
public void CanConvertULongToComplex()
{
const ulong Orginal = 123;
var complex = (Complex32)Orginal;
Assert.AreEqual(123, complex.Real);
Assert.AreEqual(0.0f, complex.Imaginary);
}
/// <summary>
/// Can convert a float to a complex.
/// </summary>
[Test]
public void CanConvertFloatToComplex()
{
const float Orginal = 123.456789f;
var complex = (Complex32)Orginal;
Assert.AreEqual(123.456789f, complex.Real);
Assert.AreEqual(0.0f, complex.Imaginary);
}
/// <summary>
/// Can convert a complex to a complex32.
/// </summary>
[Test]
public void CanConvertComplexToComplex32()
{
var complex32 = new Complex(123.456, -78.9);
var complex = (Complex32)complex32;
Assert.AreEqual(123.456f, complex.Real);
Assert.AreEqual(-78.9f, complex.Imaginary);
}
/// <summary>
/// Can conjugate.
/// </summary>
[Test]
public void CanGetConjugate()
{
var complex = new Complex32(123.456f, -78.9f);
var conjugate = complex.Conjugate();
Assert.AreEqual(complex.Real, conjugate.Real);
Assert.AreEqual(-complex.Imaginary, conjugate.Imaginary);
}
}
}
| |
/* Copyright (c) 2006 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/* Change history
* Oct 13 2008 Joe Feser joseph.feser@gmail.com
* Converted ArrayLists and other .NET 1.1 collections to use Generics
* Combined IExtensionElement and IExtensionElementFactory interfaces
*
*/
#define USE_TRACING
using System;
using Google.GData.Client;
using Google.GData.Extensions;
namespace Google.GData.Contacts {
/// <summary>
/// short table to hold the namespace and the prefix
/// </summary>
public class ContactsNameTable
{
/// <summary>static string to specify the Contacts namespace supported</summary>
public const string NSContacts = "http://schemas.google.com/contact/2008";
/// <summary>static string to specify the Google Contacts prefix used</summary>
public const string contactsPrefix = "gContact";
/// <summary>
/// Group Member ship info element string
/// </summary>
public const string GroupMembershipInfo = "groupMembershipInfo";
/// <summary>
/// SystemGroup element, indicating that this entry is a system group
/// </summary>
public const string SystemGroupElement = "systemGroup";
/// <summary>
/// Specifies billing information of the entity represented by the contact. The element cannot be repeated
/// </summary>
public const string BillingInformationElement = "billingInformation";
/// <summary>
/// Stores birthday date of the person represented by the contact. The element cannot be repeated
/// </summary>
public const string BirthdayElement = "birthday";
/// <summary>
/// Storage for URL of the contact's calendar. The element can be repeated
/// </summary>
public const string CalendarLinkElement = "calendarLink";
/// <summary>
/// A directory server associated with this contact. May not be repeated
/// </summary>
public const string DirectoryServerElement = "directoryServer";
/// <summary>
/// An event associated with a contact. May be repeated.
/// </summary>
public const string EventElement = "event";
/// <summary>
/// Describes an ID of the contact in an external system of some kind. This element may be repeated.
/// </summary>
public const string ExternalIdElement = "externalId";
/// <summary>
/// Specifies the gender of the person represented by the contact. The element cannot be repeated.
/// </summary>
public const string GenderElement = "gender";
/// <summary>
/// Specifies hobbies or interests of the person specified by the contact. The element can be repeated
/// </summary>
public const string HobbyElement = "hobby";
/// <summary>
/// Specifies the initials of the person represented by the contact. The element cannot be repeated.
/// </summary>
public const string InitialsElement = "initials";
/// <summary>
/// Storage for arbitrary pieces of information about the contact. Each jot has a type specified by the rel attribute and a text value. The element can be repeated.
/// </summary>
public const string JotElement = "jot";
/// <summary>
/// Specifies the preferred languages of the contact. The element can be repeated
/// </summary>
public const string LanguageElement = "language";
/// <summary>
/// Specifies maiden name of the person represented by the contact. The element cannot be repeated.
/// </summary>
public const string MaidenNameElement = "maidenName";
/// <summary>
/// Specifies the mileage for the entity represented by the contact. Can be used for example to document distance needed for reimbursement purposes.
/// The value is not interpreted. The element cannot be repeated
/// </summary>
public const string MileageElement = "mileage";
/// <summary>
/// Specifies the nickname of the person represented by the contact. The element cannot be repeated
/// </summary>
public const string NicknameElement = "nickname";
/// <summary>
/// Specifies the occupation/profession of the person specified by the contact. The element cannot be repeated.
/// </summary>
public const string OccupationElement = "occupation";
/// <summary>
/// Classifies importance into 3 categories. can not be repeated
/// </summary>
public const string PriorityElement = "priority";
/// <summary>
/// Describes the relation to another entity. maybe repeated
/// </summary>
public const string RelationElement = "relation";
/// <summary>
/// Classifies sensitifity of the contact
/// </summary>
public const string SensitivityElement = "sensitivity";
/// <summary>
/// Specifies short name of the person represented by the contact. The element cannot be repeated.
/// </summary>
public const string ShortNameElement = "shortName";
/// <summary>
/// Specifies the subject of the contact. The element cannot be repeated.
/// </summary>
public const string SubjectElement = "subject";
/// <summary>
/// Represents an arbitrary key-value pair attached to the contact.
/// </summary>
public const string UserDefinedFieldElement = "userDefinedField";
/// <summary>
/// Websites associated with the contact. Maybe repeated
/// </summary>
public const string WebsiteElement = "website";
/// <summary>
/// rel Attribute
/// </summary>
/// <returns></returns>
public static string AttributeRel = "rel";
/// <summary>
/// label Attribute
/// </summary>
/// <returns></returns>
public static string AttributeLabel = "label";
}
/// <summary>
/// an element is defined that represents a group to which the contact belongs
/// </summary>
public class GroupMembership: SimpleElement
{
/// <summary>the href attribute </summary>
public const string XmlAttributeHRef = "href";
/// <summary>the deleted attribute </summary>
public const string XmlAttributeDeleted = "deleted";
/// <summary>
/// default constructor
/// </summary>
public GroupMembership()
: base(ContactsNameTable.GroupMembershipInfo, ContactsNameTable.contactsPrefix, ContactsNameTable.NSContacts)
{
this.Attributes.Add(XmlAttributeHRef, null);
this.Attributes.Add(XmlAttributeDeleted, null);
}
/////////////////////////////////////////////////////////////////////
/// <summary>Identifies the group to which the contact belongs or belonged.
/// The group is referenced by its id.</summary>
//////////////////////////////////////////////////////////////////////
public string HRef
{
get
{
return this.Attributes[XmlAttributeHRef] as string;
}
set
{
this.Attributes[XmlAttributeHRef] = value;
}
}
/////////////////////////////////////////////////////////////////////
/// <summary>Means, that the group membership was removed for the contact.
/// This attribute will only be included if showdeleted is specified
/// as query parameter, otherwise groupMembershipInfo for groups a contact
/// does not belong to anymore is simply not returned.</summary>
//////////////////////////////////////////////////////////////////////
public string Deleted
{
get
{
return this.Attributes[XmlAttributeDeleted] as string;
}
}
}
/// <summary>
/// extension element to represent a system group
/// </summary>
public class SystemGroup : SimpleElement
{
/// <summary>
/// id attribute for the system group element
/// </summary>
/// <returns></returns>
public const string XmlAttributeId = "id";
/// <summary>
/// default constructor
/// </summary>
public SystemGroup()
: base(ContactsNameTable.SystemGroupElement, ContactsNameTable.contactsPrefix, ContactsNameTable.NSContacts)
{
this.Attributes.Add(XmlAttributeId, null);
}
/////////////////////////////////////////////////////////////////////
/// <summary>Identifies the system group. Note that you still need
/// to use the group entries href membership to retrieve the group
/// </summary>
//////////////////////////////////////////////////////////////////////
public string Id
{
get
{
return this.Attributes[XmlAttributeId] as string;
}
}
}
/// <summary>
/// abstract class for a basecontactentry, used for contacts and groups
/// </summary>
public abstract class BaseContactEntry : AbstractEntry, IContainsDeleted
{
private ExtensionCollection<ExtendedProperty> xproperties;
/// <summary>
/// Constructs a new BaseContactEntry instance
/// to indicate that it is an event.
/// </summary>
public BaseContactEntry()
: base()
{
Tracing.TraceMsg("Created BaseContactEntry Entry");
this.AddExtension(new ExtendedProperty());
this.AddExtension(new Deleted());
}
/// <summary>
/// returns the extended properties on this object
/// </summary>
/// <returns></returns>
public ExtensionCollection<ExtendedProperty> ExtendedProperties
{
get
{
if (this.xproperties == null)
{
this.xproperties = new ExtensionCollection<ExtendedProperty>(this);
}
return this.xproperties;
}
}
/// <summary>
/// if this is a previously deleted contact, returns true
/// to delete a contact, use the delete method
/// </summary>
public bool Deleted
{
get
{
if (FindExtension(GDataParserNameTable.XmlDeletedElement,
BaseNameTable.gNamespace) != null)
{
return true;
}
return false;
}
}
}
/// <summary>
/// Specifies billing information of the entity represented by the contact. The element cannot be repeated
/// </summary>
public class BillingInformation : SimpleElement
{
/// <summary>
/// default constructor for BillingInformation
/// </summary>
public BillingInformation()
: base(ContactsNameTable.BillingInformationElement,
ContactsNameTable.contactsPrefix,
ContactsNameTable.NSContacts)
{
}
/// <summary>
/// default constructor for BillingInformation with an initial value
/// </summary>
/// <param name="initValue"/>
public BillingInformation(string initValue)
: base(ContactsNameTable.BillingInformationElement,
ContactsNameTable.contactsPrefix,
ContactsNameTable.NSContacts, initValue)
{
}
}
/// <summary>
/// Stores birthday date of the person represented by the contact. The element cannot be repeated.
/// </summary>
public class Birthday : SimpleElement
{
/// <summary>
/// When Attribute
/// </summary>
/// <returns></returns>
public static string AttributeWhen = "when";
/// <summary>
/// default constructor for Birthday
/// </summary>
public Birthday()
: base(ContactsNameTable.BirthdayElement,
ContactsNameTable.contactsPrefix,
ContactsNameTable.NSContacts)
{
this.Attributes.Add(AttributeWhen, null);
}
/// <summary>
/// default constructor for Birthday with an initial value
/// </summary>
/// <param name="initValue"/>
public Birthday(string initValue)
: base(ContactsNameTable.BirthdayElement,
ContactsNameTable.contactsPrefix,
ContactsNameTable.NSContacts)
{
this.Attributes.Add(AttributeWhen, initValue);
}
//////////////////////////////////////////////////////////////////////
/// <summary>Birthday date, given in format YYYY-MM-DD (with the year), or --MM-DD (without the year)</summary>
/// <returns> </returns>
//////////////////////////////////////////////////////////////////////
public string When
{
get
{
return this.Attributes[AttributeWhen] as string;
}
set
{
this.Attributes[AttributeWhen] = value;
}
}
}
/// <summary>
/// Storage for URL of the contact's information. The element can be repeated.
/// </summary>
public class ContactsLink : LinkAttributesElement
{
/// <summary>
/// href Attribute
/// </summary>
/// <returns></returns>
public static string AttributeHref = "href";
/// <summary>
/// default constructor for CalendarLink
/// </summary>
public ContactsLink(string elementName, string elementPrefix, string elementNamespace)
: base(elementName, elementPrefix, elementNamespace)
{
this.Attributes.Add(AttributeHref, null);
}
//////////////////////////////////////////////////////////////////////
/// <summary>The URL of the the related link.</summary>
/// <returns> </returns>
//////////////////////////////////////////////////////////////////////
public string Href
{
get
{
return this.Attributes[AttributeHref] as string;
}
set
{
this.Attributes[AttributeHref] = value;
}
}
}
/// <summary>
/// Storage for URL of the contact's calendar. The element can be repeated.
/// </summary>
public class CalendarLink : ContactsLink
{
public CalendarLink()
: base(ContactsNameTable.CalendarLinkElement,
ContactsNameTable.contactsPrefix,
ContactsNameTable.NSContacts)
{
}
}
/// <summary>
/// DirectoryServer schema extension
/// </summary>
public class DirectoryServer : SimpleElement
{
/// <summary>
/// default constructor for DirectoryServer
/// </summary>
public DirectoryServer()
: base(ContactsNameTable.DirectoryServerElement,
ContactsNameTable.contactsPrefix,
ContactsNameTable.NSContacts)
{
}
/// <summary>
/// default constructor for DirectoryServer with an initial value
/// </summary>
/// <param name="initValue"/>
public DirectoryServer(string initValue)
: base(ContactsNameTable.DirectoryServerElement,
ContactsNameTable.contactsPrefix,
ContactsNameTable.NSContacts, initValue)
{
}
}
/// <summary>
/// Event schema extension
/// </summary>
public class Event : SimpleContainer
{
/// <summary>
/// default constructor for Event
/// </summary>
public Event()
: base(ContactsNameTable.EventElement,
ContactsNameTable.contactsPrefix,
ContactsNameTable.NSContacts)
{
this.Attributes.Add(ContactsNameTable.AttributeRel, null);
this.Attributes.Add(ContactsNameTable.AttributeLabel, null);
this.ExtensionFactories.Add(new When());
}
//////////////////////////////////////////////////////////////////////
/// <summary>Predefined calendar link type. Can be one of work, home or free-busy</summary>
/// <returns> </returns>
//////////////////////////////////////////////////////////////////////
public string Relation
{
get
{
return this.Attributes[ContactsNameTable.AttributeRel] as string;
}
set
{
this.Attributes[ContactsNameTable.AttributeRel] = value;
}
}
//////////////////////////////////////////////////////////////////////
/// <summary>User-defined calendar link type.</summary>
/// <returns> </returns>
//////////////////////////////////////////////////////////////////////
public string Label
{
get
{
return this.Attributes[ContactsNameTable.AttributeLabel] as string;
}
set
{
this.Attributes[ContactsNameTable.AttributeLabel] = value;
}
}
/// <summary>
/// exposes the When element for this event
/// </summary>
/// <returns></returns>
public When When
{
get
{
return FindExtension(GDataParserNameTable.XmlWhenElement,
BaseNameTable.gNamespace) as When;
}
set
{
ReplaceExtension(GDataParserNameTable.XmlWhenElement,
BaseNameTable.gNamespace,
value);
}
}
}
/// <summary>
/// ExternalId schema extension
/// </summary>
public class ExternalId : SimpleAttribute
{
/// <summary>
/// default constructor for ExternalId
/// </summary>
public ExternalId()
: base(ContactsNameTable.ExternalIdElement,
ContactsNameTable.contactsPrefix,
ContactsNameTable.NSContacts)
{
this.Attributes.Add(ContactsNameTable.AttributeRel, null);
this.Attributes.Add(ContactsNameTable.AttributeLabel, null);
}
/// <summary>
/// default constructor for ExternalId with an initial value
/// </summary>
/// <param name="initValue"/>
public ExternalId(string initValue)
: base(ContactsNameTable.ExternalIdElement,
ContactsNameTable.contactsPrefix,
ContactsNameTable.NSContacts, initValue)
{
this.Attributes.Add(ContactsNameTable.AttributeRel, null);
this.Attributes.Add(ContactsNameTable.AttributeLabel, null);
}
//////////////////////////////////////////////////////////////////////
/// <summary>Predefined calendar link type. Can be one of work, home or free-busy</summary>
/// <returns> </returns>
//////////////////////////////////////////////////////////////////////
public string Relation
{
get
{
return this.Attributes[ContactsNameTable.AttributeRel] as string;
}
set
{
this.Attributes[ContactsNameTable.AttributeRel] = value;
}
}
//////////////////////////////////////////////////////////////////////
/// <summary>User-defined calendar link type.</summary>
/// <returns> </returns>
//////////////////////////////////////////////////////////////////////
public string Label
{
get
{
return this.Attributes[ContactsNameTable.AttributeLabel] as string;
}
set
{
this.Attributes[ContactsNameTable.AttributeLabel] = value;
}
}
}
/// <summary>
/// Gender schema extension
/// </summary>
public class Gender : SimpleAttribute
{
/// <summary>
/// default constructor for Gender
/// </summary>
public Gender()
: base(ContactsNameTable.GenderElement,
ContactsNameTable.contactsPrefix,
ContactsNameTable.NSContacts)
{
}
/// <summary>
/// default constructor for Gender with an initial value
/// </summary>
/// <param name="initValue"/>
public Gender(string initValue)
: base(ContactsNameTable.GenderElement,
ContactsNameTable.contactsPrefix,
ContactsNameTable.NSContacts, initValue)
{
}
}
/// <summary>
/// Hobby schema extension
/// </summary>
public class Hobby : SimpleElement
{
/// <summary>
/// default constructor for Hobby
/// </summary>
public Hobby()
: base(ContactsNameTable.HobbyElement,
ContactsNameTable.contactsPrefix,
ContactsNameTable.NSContacts)
{
}
/// <summary>
/// default constructor for Hobby with an initial value
/// </summary>
/// <param name="initValue"/>
public Hobby(string initValue)
: base(ContactsNameTable.HobbyElement,
ContactsNameTable.contactsPrefix,
ContactsNameTable.NSContacts, initValue)
{
}
}
/// <summary>
/// Initials schema extension
/// </summary>
public class Initials : SimpleElement
{
/// <summary>
/// default constructor for Initials
/// </summary>
public Initials()
: base(ContactsNameTable.InitialsElement,
ContactsNameTable.contactsPrefix,
ContactsNameTable.NSContacts)
{
}
/// <summary>
/// default constructor for Initials with an initial value
/// </summary>
/// <param name="initValue"/>
public Initials(string initValue)
: base(ContactsNameTable.InitialsElement,
ContactsNameTable.contactsPrefix,
ContactsNameTable.NSContacts, initValue)
{
}
}
/// <summary>
/// Jot schema extension
/// </summary>
public class Jot : SimpleElement
{
/// <summary>
/// default constructor for Jot
/// </summary>
public Jot()
: base(ContactsNameTable.JotElement,
ContactsNameTable.contactsPrefix,
ContactsNameTable.NSContacts)
{
this.Attributes.Add(ContactsNameTable.AttributeRel, null);
}
//////////////////////////////////////////////////////////////////////
/// <summary>Predefined calendar link type. Can be one of work, home or free-busy</summary>
/// <returns> </returns>
//////////////////////////////////////////////////////////////////////
public string Relation
{
get
{
return this.Attributes[ContactsNameTable.AttributeRel] as string;
}
set
{
this.Attributes[ContactsNameTable.AttributeRel] = value;
}
}
}
/// <summary>
/// Language schema extension
/// </summary>
public class Language : SimpleElement
{
/// <summary>
/// the code attribute
/// </summary>
/// <returns></returns>
public static string AttributeCode = "code";
/// <summary>
/// default constructor for Language
/// </summary>
public Language()
: base(ContactsNameTable.LanguageElement,
ContactsNameTable.contactsPrefix,
ContactsNameTable.NSContacts)
{
this.Attributes.Add(ContactsNameTable.AttributeLabel, null);
this.Attributes.Add(AttributeCode, null);
}
/// <summary>
/// default constructor for Language with an initial value
/// </summary>
/// <param name="initValue"/>
public Language(string initValue)
: base(ContactsNameTable.LanguageElement,
ContactsNameTable.contactsPrefix,
ContactsNameTable.NSContacts, initValue)
{
this.Attributes.Add(ContactsNameTable.AttributeLabel, null);
this.Attributes.Add(AttributeCode, null);
}
//////////////////////////////////////////////////////////////////////
/// <summary>A freeform name of a language. Must not be empty or all whitespace..</summary>
/// <returns> </returns>
//////////////////////////////////////////////////////////////////////
public string Label
{
get
{
return this.Attributes[ContactsNameTable.AttributeLabel] as string;
}
set
{
this.Attributes[ContactsNameTable.AttributeLabel] = value;
}
}
//////////////////////////////////////////////////////////////////////
/// <summary>A language code conforming to the IETF BCP 47 specification. .</summary>
/// <returns> </returns>
//////////////////////////////////////////////////////////////////////
public string Code
{
get
{
return this.Attributes[AttributeCode] as string;
}
set
{
this.Attributes[AttributeCode] = value;
}
}
}
/// <summary>
/// Specifies maiden name of the person represented by the contact. The element cannot be repeated.
/// </summary>
public class MaidenName : SimpleElement
{
/// <summary>
/// default constructor for MaidenName
/// </summary>
public MaidenName()
: base(ContactsNameTable.MaidenNameElement,
ContactsNameTable.contactsPrefix,
ContactsNameTable.NSContacts)
{
}
/// <summary>
/// default constructor for MaidenName with an initial value
/// </summary>
/// <param name="initValue"/>
public MaidenName(string initValue)
: base(ContactsNameTable.MaidenNameElement,
ContactsNameTable.contactsPrefix,
ContactsNameTable.NSContacts, initValue)
{
}
}
/// <summary>
/// Specifies the mileage for the entity represented by the contact. Can be used for example to
/// document distance needed for reimbursement purposes. The value is not interpreted. The element cannot be repeated.
/// </summary>
public class Mileage : SimpleElement
{
/// <summary>
/// default constructor for Mileage
/// </summary>
public Mileage()
: base(ContactsNameTable.MileageElement,
ContactsNameTable.contactsPrefix,
ContactsNameTable.NSContacts)
{
}
/// <summary>
/// default constructor for Mileage with an initial value
/// </summary>
/// <param name="initValue"/>
public Mileage(string initValue)
: base(ContactsNameTable.MileageElement,
ContactsNameTable.contactsPrefix,
ContactsNameTable.NSContacts, initValue)
{
}
}
/// <summary>
/// Specifies the nickname of the person represented by the contact. The element cannot be repeated
/// </summary>
public class Nickname : SimpleElement
{
/// <summary>
/// default constructor for Nickname
/// </summary>
public Nickname()
: base(ContactsNameTable.NicknameElement,
ContactsNameTable.contactsPrefix,
ContactsNameTable.NSContacts)
{
}
/// <summary>
/// default constructor for Nickname with an initial value
/// </summary>
/// <param name="initValue"/>
public Nickname(string initValue)
: base(ContactsNameTable.NicknameElement,
ContactsNameTable.contactsPrefix,
ContactsNameTable.NSContacts, initValue)
{
}
}
/// <summary>
/// Specifies the occupation/profession of the person specified by the contact. The element cannot be repeated.
/// </summary>
public class Occupation : SimpleElement
{
/// <summary>
/// default constructor for Occupation
/// </summary>
public Occupation()
: base(ContactsNameTable.OccupationElement,
ContactsNameTable.contactsPrefix,
ContactsNameTable.NSContacts)
{
}
/// <summary>
/// default constructor for Occupation with an initial value
/// </summary>
/// <param name="initValue"/>
public Occupation(string initValue)
: base(ContactsNameTable.OccupationElement,
ContactsNameTable.contactsPrefix,
ContactsNameTable.NSContacts, initValue)
{
}
}
/// <summary>
/// Classifies importance of the contact into 3 categories, low, normal and high
/// </summary>
public class Priority : SimpleElement
{
/// <summary>
/// default constructor for Priority
/// </summary>
public Priority()
: base(ContactsNameTable.PriorityElement,
ContactsNameTable.contactsPrefix,
ContactsNameTable.NSContacts)
{
this.Attributes.Add(ContactsNameTable.AttributeRel, null);
}
/// <summary>
/// default constructor for Priority with an initial value
/// </summary>
/// <param name="initValue"/>
public Priority(string initValue)
: base(ContactsNameTable.OccupationElement,
ContactsNameTable.contactsPrefix,
ContactsNameTable.NSContacts)
{
this.Attributes.Add(ContactsNameTable.AttributeRel, initValue);
}
//////////////////////////////////////////////////////////////////////
/// <summary>Predefined calendar link type. Can be one of work, home or free-busy</summary>
/// <returns> </returns>
//////////////////////////////////////////////////////////////////////
public string Relation
{
get
{
return this.Attributes[ContactsNameTable.AttributeRel] as string;
}
set
{
this.Attributes[ContactsNameTable.AttributeRel] = value;
}
}
}
/// <summary>
/// Relation schema extension
/// </summary>
public class Relation : SimpleElement
{
/// <summary>
/// default constructor for Relation
/// </summary>
public Relation()
: base(ContactsNameTable.RelationElement,
ContactsNameTable.contactsPrefix,
ContactsNameTable.NSContacts)
{
this.Attributes.Add(ContactsNameTable.AttributeLabel, null);
this.Attributes.Add(ContactsNameTable.AttributeRel, null);
}
//////////////////////////////////////////////////////////////////////
/// <summary>A freeform name of a language. Must not be empty or all whitespace..</summary>
/// <returns> </returns>
//////////////////////////////////////////////////////////////////////
public string Label
{
get
{
return this.Attributes[ContactsNameTable.AttributeLabel] as string;
}
set
{
this.Attributes[ContactsNameTable.AttributeLabel] = value;
}
}
//////////////////////////////////////////////////////////////////////
/// <summary>defines the link type.</summary>
/// <returns> </returns>
//////////////////////////////////////////////////////////////////////
public string Rel
{
get
{
return this.Attributes[ContactsNameTable.AttributeRel] as string;
}
set
{
this.Attributes[ContactsNameTable.AttributeRel] = value;
}
}
}
/// <summary>
/// Classifies sensitivity of the contact into the following categories:
/// confidential, normal, personal or private
/// </summary>
public class Sensitivity : SimpleElement
{
/// <summary>
/// default constructor for Sensitivity
/// </summary>
public Sensitivity()
: base(ContactsNameTable.SensitivityElement,
ContactsNameTable.contactsPrefix,
ContactsNameTable.NSContacts)
{
this.Attributes.Add(ContactsNameTable.AttributeRel, null);
}
/// <summary>
/// default constructor for Sensitivity with an initial value
/// </summary>
/// <param name="initValue"/>
public Sensitivity(string initValue)
: base(ContactsNameTable.OccupationElement,
ContactsNameTable.contactsPrefix,
ContactsNameTable.NSContacts)
{
this.Attributes.Add(ContactsNameTable.AttributeRel, initValue);
}
//////////////////////////////////////////////////////////////////////
/// <summary>returns the relationship value</summary>
/// <returns> </returns>
//////////////////////////////////////////////////////////////////////
public string Relation
{
get
{
return this.Attributes[ContactsNameTable.AttributeRel] as string;
}
set
{
this.Attributes[ContactsNameTable.AttributeRel] = value;
}
}
}
/// <summary>
/// Specifies short name of the person represented by the contact. The element cannot be repeated.
/// </summary>
public class ShortName : SimpleElement
{
/// <summary>
/// default constructor for ShortName
/// </summary>
public ShortName()
: base(ContactsNameTable.ShortNameElement,
ContactsNameTable.contactsPrefix,
ContactsNameTable.NSContacts)
{
}
/// <summary>
/// default constructor for ShortName with an initial value
/// </summary>
/// <param name="initValue"/>
public ShortName(string initValue)
: base(ContactsNameTable.ShortNameElement,
ContactsNameTable.contactsPrefix,
ContactsNameTable.NSContacts, initValue)
{
}
}
/// <summary>
/// Specifies the subject of the contact. The element cannot be repeated.
/// </summary>
public class Subject : SimpleElement
{
/// <summary>
/// default constructor for Subject
/// </summary>
public Subject()
: base(ContactsNameTable.SubjectElement,
ContactsNameTable.contactsPrefix,
ContactsNameTable.NSContacts)
{
}
/// <summary>
/// default constructor for Subject with an initial value
/// </summary>
/// <param name="initValue"/>
public Subject(string initValue)
: base(ContactsNameTable.SubjectElement,
ContactsNameTable.contactsPrefix,
ContactsNameTable.NSContacts, initValue)
{
}
}
/// <summary>
/// Represents an arbitrary key-value pair attached to the contact.
/// </summary>
public class UserDefinedField : SimpleAttribute
{
/// <summary>
/// key attribute
/// </summary>
/// <returns></returns>
public static string AttributeKey = "key";
/// <summary>
/// default constructor for UserDefinedField
/// </summary>
public UserDefinedField()
: base(ContactsNameTable.UserDefinedFieldElement,
ContactsNameTable.contactsPrefix,
ContactsNameTable.NSContacts)
{
this.Attributes.Add(AttributeKey, null);
}
/// <summary>
/// default constructor for UserDefinedField with an initial value
/// </summary>
/// <param name="initValue"/>
/// <param name="initKey"/>
public UserDefinedField(string initValue, string initKey)
: base(ContactsNameTable.UserDefinedFieldElement,
ContactsNameTable.contactsPrefix,
ContactsNameTable.NSContacts, initValue)
{
this.Attributes.Add(AttributeKey, initKey);
}
//////////////////////////////////////////////////////////////////////
/// <summary>A simple string value used to name this field. Case-sensitive</summary>
/// <returns> </returns>
//////////////////////////////////////////////////////////////////////
public string Key
{
get
{
return this.Attributes[AttributeKey] as string;
}
set
{
this.Attributes[AttributeKey] = value;
}
}
}
/// <summary>
/// WebSite schema extension
/// </summary>
public class Website : ContactsLink
{
/// <summary>
/// default constructor for WebSite
/// </summary>
public Website()
: base(ContactsNameTable.WebsiteElement,
ContactsNameTable.contactsPrefix,
ContactsNameTable.NSContacts)
{
}
}
}
| |
// 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.Collections;
using System.ComponentModel;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Net;
using System.Runtime.InteropServices;
using System.Threading.Tasks;
using System.Threading;
namespace System.Net.Sockets
{
public partial class SocketAsyncEventArgs : EventArgs, IDisposable
{
// Struct sizes needed for some custom marshaling.
internal static readonly int s_controlDataSize = Marshal.SizeOf<Interop.Winsock.ControlData>();
internal static readonly int s_controlDataIPv6Size = Marshal.SizeOf<Interop.Winsock.ControlDataIPv6>();
internal static readonly int s_wsaMsgSize = Marshal.SizeOf<Interop.Winsock.WSAMsg>();
// Buffer,Offset,Count property variables.
private WSABuffer _wsaBuffer;
private IntPtr _ptrSingleBuffer;
// BufferList property variables.
private WSABuffer[] _wsaBufferArray;
private bool _bufferListChanged;
// Internal buffers for WSARecvMsg
private byte[] _wsaMessageBuffer;
private GCHandle _wsaMessageBufferGCHandle;
private IntPtr _ptrWSAMessageBuffer;
private byte[] _controlBuffer;
private GCHandle _controlBufferGCHandle;
private IntPtr _ptrControlBuffer;
private WSABuffer[] _wsaRecvMsgWSABufferArray;
private GCHandle _wsaRecvMsgWSABufferArrayGCHandle;
private IntPtr _ptrWSARecvMsgWSABufferArray;
// Internal buffer for AcceptEx when Buffer not supplied.
private IntPtr _ptrAcceptBuffer;
// Internal SocketAddress buffer
private GCHandle _socketAddressGCHandle;
private Internals.SocketAddress _pinnedSocketAddress;
private IntPtr _ptrSocketAddressBuffer;
private IntPtr _ptrSocketAddressBufferSize;
// SendPacketsElements property variables.
private SendPacketsElement[] _sendPacketsElementsInternal;
private Interop.Winsock.TransmitPacketsElement[] _sendPacketsDescriptor;
private int _sendPacketsElementsFileCount;
private int _sendPacketsElementsBufferCount;
// Internal variables for SendPackets
private FileStream[] _sendPacketsFileStreams;
private SafeHandle[] _sendPacketsFileHandles;
private IntPtr _ptrSendPacketsDescriptor;
// Overlapped object related variables.
private SafeNativeOverlapped _ptrNativeOverlapped;
private PreAllocatedOverlapped _preAllocatedOverlapped;
private object[] _objectsToPin;
private enum PinState
{
None = 0,
NoBuffer,
SingleAcceptBuffer,
SingleBuffer,
MultipleBuffer,
SendPackets
}
private PinState _pinState;
private byte[] _pinnedAcceptBuffer;
private byte[] _pinnedSingleBuffer;
private int _pinnedSingleBufferOffset;
private int _pinnedSingleBufferCount;
internal int? SendPacketsDescriptorCount
{
get
{
return _sendPacketsDescriptor == null ? null : (int?)_sendPacketsDescriptor.Length;
}
}
private void InitializeInternals()
{
// Zero tells TransmitPackets to select a default send size.
_sendPacketsSendSize = 0;
}
private void FreeInternals(bool calledFromFinalizer)
{
// Free native overlapped data.
FreeOverlapped(calledFromFinalizer);
}
private void SetupSingleBuffer()
{
CheckPinSingleBuffer(true);
}
private void SetupMultipleBuffers()
{
_bufferListChanged = true;
CheckPinMultipleBuffers();
}
private void SetupSendPacketsElements()
{
_sendPacketsElementsInternal = null;
}
private void InnerComplete()
{
CompleteIOCPOperation();
}
private unsafe void PrepareIOCPOperation()
{
Debug.Assert(_currentSocket != null, "_currentSocket is null");
Debug.Assert(_currentSocket.SafeHandle != null, "_currentSocket.SafeHandle is null");
Debug.Assert(!_currentSocket.SafeHandle.IsInvalid, "_currentSocket.SafeHandle is invalid");
ThreadPoolBoundHandle boundHandle = _currentSocket.SafeHandle.GetOrAllocateThreadPoolBoundHandle();
NativeOverlapped* overlapped = null;
if (_preAllocatedOverlapped != null)
{
overlapped = boundHandle.AllocateNativeOverlapped(_preAllocatedOverlapped);
if (GlobalLog.IsEnabled)
{
GlobalLog.Print(
"SocketAsyncEventArgs#" + LoggingHash.HashString(this) +
"::boundHandle#" + LoggingHash.HashString(boundHandle) +
"::AllocateNativeOverlapped(m_PreAllocatedOverlapped=" +
LoggingHash.HashString(_preAllocatedOverlapped) +
"). Returned = " + ((IntPtr)overlapped).ToString("x"));
}
}
else
{
overlapped = boundHandle.AllocateNativeOverlapped(CompletionPortCallback, this, null);
if (GlobalLog.IsEnabled)
{
GlobalLog.Print(
"SocketAsyncEventArgs#" + LoggingHash.HashString(this) +
"::boundHandle#" + LoggingHash.HashString(boundHandle) +
"::AllocateNativeOverlapped(pinData=null)" +
"). Returned = " + ((IntPtr)overlapped).ToString("x"));
}
}
Debug.Assert(overlapped != null, "NativeOverlapped is null.");
_ptrNativeOverlapped = new SafeNativeOverlapped(_currentSocket.SafeHandle, overlapped);
}
private void CompleteIOCPOperation()
{
// TODO #4900: Optimization to remove callbacks if the operations are completed synchronously:
// Use SetFileCompletionNotificationModes(FILE_SKIP_COMPLETION_PORT_ON_SUCCESS).
// If SetFileCompletionNotificationModes(FILE_SKIP_COMPLETION_PORT_ON_SUCCESS) is not set on this handle
// it is guaranteed that the IOCP operation will be completed in the callback even if Socket.Success was
// returned by the Win32 API.
// Required to allow another IOCP operation for the same handle.
if (_ptrNativeOverlapped != null)
{
_ptrNativeOverlapped.Dispose();
_ptrNativeOverlapped = null;
}
}
private void InnerStartOperationAccept(bool userSuppliedBuffer)
{
if (!userSuppliedBuffer)
{
CheckPinSingleBuffer(false);
}
}
internal unsafe SocketError DoOperationAccept(Socket socket, SafeCloseSocket handle, SafeCloseSocket acceptHandle, out int bytesTransferred)
{
PrepareIOCPOperation();
SocketError socketError = SocketError.Success;
if (!socket.AcceptEx(
handle,
acceptHandle,
(_ptrSingleBuffer != IntPtr.Zero) ? _ptrSingleBuffer : _ptrAcceptBuffer,
(_ptrSingleBuffer != IntPtr.Zero) ? Count - _acceptAddressBufferCount : 0,
_acceptAddressBufferCount / 2,
_acceptAddressBufferCount / 2,
out bytesTransferred,
_ptrNativeOverlapped))
{
socketError = SocketPal.GetLastSocketError();
}
return socketError;
}
private void InnerStartOperationConnect()
{
// ConnectEx uses a sockaddr buffer containing he remote address to which to connect.
// It can also optionally take a single buffer of data to send after the connection is complete.
//
// The sockaddr is pinned with a GCHandle to avoid having to use the object array form of UnsafePack.
// The optional buffer is pinned using the Overlapped.UnsafePack method that takes a single object to pin.
PinSocketAddressBuffer();
CheckPinNoBuffer();
}
internal unsafe SocketError DoOperationConnect(Socket socket, SafeCloseSocket handle, out int bytesTransferred)
{
PrepareIOCPOperation();
SocketError socketError = SocketError.Success;
if (!socket.ConnectEx(
handle,
_ptrSocketAddressBuffer,
_socketAddress.Size,
_ptrSingleBuffer,
Count,
out bytesTransferred,
_ptrNativeOverlapped))
{
socketError = SocketPal.GetLastSocketError();
}
return socketError;
}
private void InnerStartOperationDisconnect()
{
CheckPinNoBuffer();
}
private void InnerStartOperationReceive()
{
// WWSARecv uses a WSABuffer array describing buffers of data to send.
//
// Single and multiple buffers are handled differently so as to optimize
// performance for the more common single buffer case.
//
// For a single buffer:
// The Overlapped.UnsafePack method is used that takes a single object to pin.
// A single WSABuffer that pre-exists in SocketAsyncEventArgs is used.
//
// For multiple buffers:
// The Overlapped.UnsafePack method is used that takes an array of objects to pin.
// An array to reference the multiple buffer is allocated.
// An array of WSABuffer descriptors is allocated.
}
internal unsafe SocketError DoOperationReceive(SafeCloseSocket handle, out SocketFlags flags, out int bytesTransferred)
{
PrepareIOCPOperation();
flags = _socketFlags;
SocketError socketError;
if (_buffer != null)
{
// Single buffer case.
socketError = Interop.Winsock.WSARecv(
handle,
ref _wsaBuffer,
1,
out bytesTransferred,
ref flags,
_ptrNativeOverlapped,
IntPtr.Zero);
}
else
{
// Multi buffer case.
socketError = Interop.Winsock.WSARecv(
handle,
_wsaBufferArray,
_wsaBufferArray.Length,
out bytesTransferred,
ref flags,
_ptrNativeOverlapped,
IntPtr.Zero);
}
if (socketError == SocketError.SocketError)
{
socketError = SocketPal.GetLastSocketError();
}
return socketError;
}
private void InnerStartOperationReceiveFrom()
{
// WSARecvFrom uses e a WSABuffer array describing buffers in which to
// receive data and from which to send data respectively. Single and multiple buffers
// are handled differently so as to optimize performance for the more common single buffer case.
//
// For a single buffer:
// The Overlapped.UnsafePack method is used that takes a single object to pin.
// A single WSABuffer that pre-exists in SocketAsyncEventArgs is used.
//
// For multiple buffers:
// The Overlapped.UnsafePack method is used that takes an array of objects to pin.
// An array to reference the multiple buffer is allocated.
// An array of WSABuffer descriptors is allocated.
//
// WSARecvFrom and WSASendTo also uses a sockaddr buffer in which to store the address from which the data was received.
// The sockaddr is pinned with a GCHandle to avoid having to use the object array form of UnsafePack.
PinSocketAddressBuffer();
}
internal unsafe SocketError DoOperationReceiveFrom(SafeCloseSocket handle, out SocketFlags flags, out int bytesTransferred)
{
PrepareIOCPOperation();
flags = _socketFlags;
SocketError socketError;
if (_buffer != null)
{
socketError = Interop.Winsock.WSARecvFrom(
handle,
ref _wsaBuffer,
1,
out bytesTransferred,
ref flags,
_ptrSocketAddressBuffer,
_ptrSocketAddressBufferSize,
_ptrNativeOverlapped,
IntPtr.Zero);
}
else
{
socketError = Interop.Winsock.WSARecvFrom(
handle,
_wsaBufferArray,
_wsaBufferArray.Length,
out bytesTransferred,
ref flags,
_ptrSocketAddressBuffer,
_ptrSocketAddressBufferSize,
_ptrNativeOverlapped,
IntPtr.Zero);
}
if (socketError == SocketError.SocketError)
{
socketError = SocketPal.GetLastSocketError();
}
return socketError;
}
private void InnerStartOperationReceiveMessageFrom()
{
// WSARecvMsg uses a WSAMsg descriptor.
// The WSAMsg buffer is pinned with a GCHandle to avoid complicating the use of Overlapped.
// WSAMsg contains a pointer to a sockaddr.
// The sockaddr is pinned with a GCHandle to avoid complicating the use of Overlapped.
// WSAMsg contains a pointer to a WSABuffer array describing data buffers.
// WSAMsg also contains a single WSABuffer describing a control buffer.
PinSocketAddressBuffer();
// Create and pin a WSAMessageBuffer if none already.
if (_wsaMessageBuffer == null)
{
_wsaMessageBuffer = new byte[s_wsaMsgSize];
_wsaMessageBufferGCHandle = GCHandle.Alloc(_wsaMessageBuffer, GCHandleType.Pinned);
_ptrWSAMessageBuffer = Marshal.UnsafeAddrOfPinnedArrayElement(_wsaMessageBuffer, 0);
}
// Create and pin an appropriately sized control buffer if none already
IPAddress ipAddress = (_socketAddress.Family == AddressFamily.InterNetworkV6 ? _socketAddress.GetIPAddress() : null);
bool ipv4 = (_currentSocket.AddressFamily == AddressFamily.InterNetwork || (ipAddress != null && ipAddress.IsIPv4MappedToIPv6)); // DualMode
bool ipv6 = _currentSocket.AddressFamily == AddressFamily.InterNetworkV6;
if (ipv4 && (_controlBuffer == null || _controlBuffer.Length != s_controlDataSize))
{
if (_controlBufferGCHandle.IsAllocated)
{
_controlBufferGCHandle.Free();
}
_controlBuffer = new byte[s_controlDataSize];
}
else if (ipv6 && (_controlBuffer == null || _controlBuffer.Length != s_controlDataIPv6Size))
{
if (_controlBufferGCHandle.IsAllocated)
{
_controlBufferGCHandle.Free();
}
_controlBuffer = new byte[s_controlDataIPv6Size];
}
if (!_controlBufferGCHandle.IsAllocated)
{
_controlBufferGCHandle = GCHandle.Alloc(_controlBuffer, GCHandleType.Pinned);
_ptrControlBuffer = Marshal.UnsafeAddrOfPinnedArrayElement(_controlBuffer, 0);
}
// If single buffer we need a pinned 1 element WSABuffer.
if (_buffer != null)
{
if (_wsaRecvMsgWSABufferArray == null)
{
_wsaRecvMsgWSABufferArray = new WSABuffer[1];
}
_wsaRecvMsgWSABufferArray[0].Pointer = _ptrSingleBuffer;
_wsaRecvMsgWSABufferArray[0].Length = _count;
_wsaRecvMsgWSABufferArrayGCHandle = GCHandle.Alloc(_wsaRecvMsgWSABufferArray, GCHandleType.Pinned);
_ptrWSARecvMsgWSABufferArray = Marshal.UnsafeAddrOfPinnedArrayElement(_wsaRecvMsgWSABufferArray, 0);
}
else
{
// Just pin the multi-buffer WSABuffer.
_wsaRecvMsgWSABufferArrayGCHandle = GCHandle.Alloc(_wsaBufferArray, GCHandleType.Pinned);
_ptrWSARecvMsgWSABufferArray = Marshal.UnsafeAddrOfPinnedArrayElement(_wsaBufferArray, 0);
}
// Fill in WSAMessageBuffer.
unsafe
{
Interop.Winsock.WSAMsg* pMessage = (Interop.Winsock.WSAMsg*)_ptrWSAMessageBuffer; ;
pMessage->socketAddress = _ptrSocketAddressBuffer;
pMessage->addressLength = (uint)_socketAddress.Size;
pMessage->buffers = _ptrWSARecvMsgWSABufferArray;
if (_buffer != null)
{
pMessage->count = (uint)1;
}
else
{
pMessage->count = (uint)_wsaBufferArray.Length;
}
if (_controlBuffer != null)
{
pMessage->controlBuffer.Pointer = _ptrControlBuffer;
pMessage->controlBuffer.Length = _controlBuffer.Length;
}
pMessage->flags = _socketFlags;
}
}
internal unsafe SocketError DoOperationReceiveMessageFrom(Socket socket, SafeCloseSocket handle, out int bytesTransferred)
{
PrepareIOCPOperation();
SocketError socketError = socket.WSARecvMsg(
handle,
_ptrWSAMessageBuffer,
out bytesTransferred,
_ptrNativeOverlapped,
IntPtr.Zero);
if (socketError == SocketError.SocketError)
{
socketError = SocketPal.GetLastSocketError();
}
return socketError;
}
private void InnerStartOperationSend()
{
// WSASend uses a WSABuffer array describing buffers of data to send.
//
// Single and multiple buffers are handled differently so as to optimize
// performance for the more common single buffer case.
//
// For a single buffer:
// The Overlapped.UnsafePack method is used that takes a single object to pin.
// A single WSABuffer that pre-exists in SocketAsyncEventArgs is used.
//
// For multiple buffers:
// The Overlapped.UnsafePack method is used that takes an array of objects to pin.
// An array to reference the multiple buffer is allocated.
// An array of WSABuffer descriptors is allocated.
}
internal unsafe SocketError DoOperationSend(SafeCloseSocket handle, out int bytesTransferred)
{
PrepareIOCPOperation();
SocketError socketError;
if (_buffer != null)
{
// Single buffer case.
socketError = Interop.Winsock.WSASend(
handle,
ref _wsaBuffer,
1,
out bytesTransferred,
_socketFlags,
_ptrNativeOverlapped,
IntPtr.Zero);
}
else
{
// Multi buffer case.
socketError = Interop.Winsock.WSASend(
handle,
_wsaBufferArray,
_wsaBufferArray.Length,
out bytesTransferred,
_socketFlags,
_ptrNativeOverlapped,
IntPtr.Zero);
}
if (socketError == SocketError.SocketError)
{
socketError = SocketPal.GetLastSocketError();
}
return socketError;
}
private void InnerStartOperationSendPackets()
{
// Prevent mutithreaded manipulation of the list.
if (_sendPacketsElements != null)
{
_sendPacketsElementsInternal = (SendPacketsElement[])_sendPacketsElements.Clone();
}
// TransmitPackets uses an array of TRANSMIT_PACKET_ELEMENT structs as
// descriptors for buffers and files to be sent. It also takes a send size
// and some flags. The TRANSMIT_PACKET_ELEMENT for a file contains a native file handle.
// This function basically opens the files to get the file handles, pins down any buffers
// specified and builds the native TRANSMIT_PACKET_ELEMENT array that will be passed
// to TransmitPackets.
// Scan the elements to count files and buffers.
_sendPacketsElementsFileCount = 0;
_sendPacketsElementsBufferCount = 0;
Debug.Assert(_sendPacketsElementsInternal != null);
foreach (SendPacketsElement spe in _sendPacketsElementsInternal)
{
if (spe != null)
{
if (spe._filePath != null)
{
_sendPacketsElementsFileCount++;
}
if (spe._buffer != null && spe._count > 0)
{
_sendPacketsElementsBufferCount++;
}
}
}
// Attempt to open the files if any were given.
if (_sendPacketsElementsFileCount > 0)
{
// Create arrays for streams and handles.
_sendPacketsFileStreams = new FileStream[_sendPacketsElementsFileCount];
_sendPacketsFileHandles = new SafeHandle[_sendPacketsElementsFileCount];
// Loop through the elements attempting to open each files and get its handle.
int index = 0;
foreach (SendPacketsElement spe in _sendPacketsElementsInternal)
{
if (spe != null && spe._filePath != null)
{
Exception fileStreamException = null;
try
{
// Create a FileStream to open the file.
_sendPacketsFileStreams[index] =
new FileStream(spe._filePath, FileMode.Open, FileAccess.Read, FileShare.Read);
}
catch (Exception ex)
{
// Save the exception to throw after closing any previous successful file opens.
fileStreamException = ex;
}
if (fileStreamException != null)
{
// Got an exception opening a file - do some cleanup then throw.
for (int i = 0; i < _sendPacketsElementsFileCount; i++)
{
// Drop handles.
_sendPacketsFileHandles[i] = null;
// Close any open streams.
if (_sendPacketsFileStreams[i] != null)
{
_sendPacketsFileStreams[i].Dispose();
_sendPacketsFileStreams[i] = null;
}
}
throw fileStreamException;
}
// Get the file handle from the stream.
_sendPacketsFileHandles[index] = _sendPacketsFileStreams[index].SafeFileHandle;
index++;
}
}
}
CheckPinSendPackets();
}
internal SocketError DoOperationSendPackets(Socket socket, SafeCloseSocket handle)
{
PrepareIOCPOperation();
bool result = socket.TransmitPackets(
handle,
_ptrSendPacketsDescriptor,
_sendPacketsDescriptor.Length,
_sendPacketsSendSize,
_ptrNativeOverlapped);
return result ? SocketError.Success : SocketPal.GetLastSocketError();
}
private void InnerStartOperationSendTo()
{
// WSASendTo uses a WSABuffer array describing buffers in which to
// receive data and from which to send data respectively. Single and multiple buffers
// are handled differently so as to optimize performance for the more common single buffer case.
//
// For a single buffer:
// The Overlapped.UnsafePack method is used that takes a single object to pin.
// A single WSABuffer that pre-exists in SocketAsyncEventArgs is used.
//
// For multiple buffers:
// The Overlapped.UnsafePack method is used that takes an array of objects to pin.
// An array to reference the multiple buffer is allocated.
// An array of WSABuffer descriptors is allocated.
//
// WSARecvFrom and WSASendTo also uses a sockaddr buffer in which to store the address from which the data was received.
// The sockaddr is pinned with a GCHandle to avoid having to use the object array form of UnsafePack.
PinSocketAddressBuffer();
}
internal SocketError DoOperationSendTo(SafeCloseSocket handle, out int bytesTransferred)
{
PrepareIOCPOperation();
SocketError socketError;
if (_buffer != null)
{
// Single buffer case.
socketError = Interop.Winsock.WSASendTo(
handle,
ref _wsaBuffer,
1,
out bytesTransferred,
_socketFlags,
_ptrSocketAddressBuffer,
_socketAddress.Size,
_ptrNativeOverlapped,
IntPtr.Zero);
}
else
{
socketError = Interop.Winsock.WSASendTo(
handle,
_wsaBufferArray,
_wsaBufferArray.Length,
out bytesTransferred,
_socketFlags,
_ptrSocketAddressBuffer,
_socketAddress.Size,
_ptrNativeOverlapped,
IntPtr.Zero);
}
if (socketError == SocketError.SocketError)
{
socketError = SocketPal.GetLastSocketError();
}
return socketError;
}
// Ensures Overlapped object exists for operations that need no data buffer.
private void CheckPinNoBuffer()
{
// PreAllocatedOverlapped will be reused.
if (_pinState == PinState.None)
{
SetupOverlappedSingle(true);
}
}
// Maintains pinned state of single buffer.
private void CheckPinSingleBuffer(bool pinUsersBuffer)
{
if (pinUsersBuffer)
{
// Using app supplied buffer.
if (_buffer == null)
{
// No user buffer is set so unpin any existing single buffer pinning.
if (_pinState == PinState.SingleBuffer)
{
FreeOverlapped(false);
}
}
else
{
if (_pinState == PinState.SingleBuffer && _pinnedSingleBuffer == _buffer)
{
// This buffer is already pinned - update if offset or count has changed.
if (_offset != _pinnedSingleBufferOffset)
{
_pinnedSingleBufferOffset = _offset;
_ptrSingleBuffer = Marshal.UnsafeAddrOfPinnedArrayElement(_buffer, _offset);
_wsaBuffer.Pointer = _ptrSingleBuffer;
}
if (_count != _pinnedSingleBufferCount)
{
_pinnedSingleBufferCount = _count;
_wsaBuffer.Length = _count;
}
}
else
{
FreeOverlapped(false);
SetupOverlappedSingle(true);
}
}
}
else
{
// Using internal accept buffer.
if (!(_pinState == PinState.SingleAcceptBuffer) || !(_pinnedSingleBuffer == _acceptBuffer))
{
// Not already pinned - so pin it.
FreeOverlapped(false);
SetupOverlappedSingle(false);
}
}
}
// Ensures Overlapped object exists with appropriate multiple buffers pinned.
private void CheckPinMultipleBuffers()
{
if (_bufferList == null)
{
// No buffer list is set so unpin any existing multiple buffer pinning.
if (_pinState == PinState.MultipleBuffer)
{
FreeOverlapped(false);
}
}
else
{
if (!(_pinState == PinState.MultipleBuffer) || _bufferListChanged)
{
// Need to setup a new Overlapped.
_bufferListChanged = false;
FreeOverlapped(false);
try
{
SetupOverlappedMultiple();
}
catch (Exception)
{
FreeOverlapped(false);
throw;
}
}
}
}
// Ensures Overlapped object exists with appropriate buffers pinned.
private void CheckPinSendPackets()
{
if (_pinState != PinState.None)
{
FreeOverlapped(false);
}
SetupOverlappedSendPackets();
}
// Ensures appropriate SocketAddress buffer is pinned.
private void PinSocketAddressBuffer()
{
// Check if already pinned.
if (_pinnedSocketAddress == _socketAddress)
{
return;
}
// Unpin any existing.
if (_socketAddressGCHandle.IsAllocated)
{
_socketAddressGCHandle.Free();
}
// Pin down the new one.
_socketAddressGCHandle = GCHandle.Alloc(_socketAddress.Buffer, GCHandleType.Pinned);
_socketAddress.CopyAddressSizeIntoBuffer();
_ptrSocketAddressBuffer = Marshal.UnsafeAddrOfPinnedArrayElement(_socketAddress.Buffer, 0);
_ptrSocketAddressBufferSize = Marshal.UnsafeAddrOfPinnedArrayElement(_socketAddress.Buffer, _socketAddress.GetAddressSizeOffset());
_pinnedSocketAddress = _socketAddress;
}
// Cleans up any existing Overlapped object and related state variables.
private void FreeOverlapped(bool checkForShutdown)
{
if (!checkForShutdown || !Environment.HasShutdownStarted)
{
// Free the overlapped object.
if (_ptrNativeOverlapped != null && !_ptrNativeOverlapped.IsInvalid)
{
_ptrNativeOverlapped.Dispose();
_ptrNativeOverlapped = null;
}
// Free the preallocated overlapped object. This in turn will unpin
// any pinned buffers.
if (_preAllocatedOverlapped != null)
{
_preAllocatedOverlapped.Dispose();
_preAllocatedOverlapped = null;
_pinState = PinState.None;
_pinnedAcceptBuffer = null;
_pinnedSingleBuffer = null;
_pinnedSingleBufferOffset = 0;
_pinnedSingleBufferCount = 0;
}
// Free any allocated GCHandles.
if (_socketAddressGCHandle.IsAllocated)
{
_socketAddressGCHandle.Free();
_pinnedSocketAddress = null;
}
if (_wsaMessageBufferGCHandle.IsAllocated)
{
_wsaMessageBufferGCHandle.Free();
_ptrWSAMessageBuffer = IntPtr.Zero;
}
if (_wsaRecvMsgWSABufferArrayGCHandle.IsAllocated)
{
_wsaRecvMsgWSABufferArrayGCHandle.Free();
_ptrWSARecvMsgWSABufferArray = IntPtr.Zero;
}
if (_controlBufferGCHandle.IsAllocated)
{
_controlBufferGCHandle.Free();
_ptrControlBuffer = IntPtr.Zero;
}
}
}
// Sets up an Overlapped object with either _buffer or _acceptBuffer pinned.
unsafe private void SetupOverlappedSingle(bool pinSingleBuffer)
{
// Pin buffer, get native pointers, and fill in WSABuffer descriptor.
if (pinSingleBuffer)
{
if (_buffer != null)
{
_preAllocatedOverlapped = new PreAllocatedOverlapped(CompletionPortCallback, this, _buffer);
if (GlobalLog.IsEnabled)
{
GlobalLog.Print(
"SocketAsyncEventArgs#" + LoggingHash.HashString(this) +
"::SetupOverlappedSingle: new PreAllocatedOverlapped pinSingleBuffer=true, non-null buffer: " +
LoggingHash.HashString(_preAllocatedOverlapped));
}
_pinnedSingleBuffer = _buffer;
_pinnedSingleBufferOffset = _offset;
_pinnedSingleBufferCount = _count;
_ptrSingleBuffer = Marshal.UnsafeAddrOfPinnedArrayElement(_buffer, _offset);
_ptrAcceptBuffer = IntPtr.Zero;
_wsaBuffer.Pointer = _ptrSingleBuffer;
_wsaBuffer.Length = _count;
_pinState = PinState.SingleBuffer;
}
else
{
_preAllocatedOverlapped = new PreAllocatedOverlapped(CompletionPortCallback, this, null);
if (GlobalLog.IsEnabled)
{
GlobalLog.Print(
"SocketAsyncEventArgs#" + LoggingHash.HashString(this) +
"::SetupOverlappedSingle: new PreAllocatedOverlapped pinSingleBuffer=true, null buffer: " +
LoggingHash.HashString(_preAllocatedOverlapped));
}
_pinnedSingleBuffer = null;
_pinnedSingleBufferOffset = 0;
_pinnedSingleBufferCount = 0;
_ptrSingleBuffer = IntPtr.Zero;
_ptrAcceptBuffer = IntPtr.Zero;
_wsaBuffer.Pointer = _ptrSingleBuffer;
_wsaBuffer.Length = _count;
_pinState = PinState.NoBuffer;
}
}
else
{
_preAllocatedOverlapped = new PreAllocatedOverlapped(CompletionPortCallback, this, _acceptBuffer);
if (GlobalLog.IsEnabled)
{
GlobalLog.Print(
"SocketAsyncEventArgs#" + LoggingHash.HashString(this) +
"::SetupOverlappedSingle: new PreAllocatedOverlapped pinSingleBuffer=false: " +
LoggingHash.HashString(_preAllocatedOverlapped));
}
_pinnedAcceptBuffer = _acceptBuffer;
_ptrAcceptBuffer = Marshal.UnsafeAddrOfPinnedArrayElement(_acceptBuffer, 0);
_ptrSingleBuffer = IntPtr.Zero;
_pinState = PinState.SingleAcceptBuffer;
}
}
// Sets up an Overlapped object with with multiple buffers pinned.
unsafe private void SetupOverlappedMultiple()
{
ArraySegment<byte>[] tempList = new ArraySegment<byte>[_bufferList.Count];
_bufferList.CopyTo(tempList, 0);
// Number of things to pin is number of buffers.
// Ensure we have properly sized object array.
if (_objectsToPin == null || (_objectsToPin.Length != tempList.Length))
{
_objectsToPin = new object[tempList.Length];
}
// Fill in object array.
for (int i = 0; i < (tempList.Length); i++)
{
_objectsToPin[i] = tempList[i].Array;
}
if (_wsaBufferArray == null || _wsaBufferArray.Length != tempList.Length)
{
_wsaBufferArray = new WSABuffer[tempList.Length];
}
// Pin buffers and fill in WSABuffer descriptor pointers and lengths.
_preAllocatedOverlapped = new PreAllocatedOverlapped(CompletionPortCallback, this, _objectsToPin);
if (GlobalLog.IsEnabled)
{
GlobalLog.Print(
"SocketAsyncEventArgs#" + LoggingHash.HashString(this) + "::SetupOverlappedMultiple: new PreAllocatedOverlapped." +
LoggingHash.HashString(_preAllocatedOverlapped));
}
for (int i = 0; i < tempList.Length; i++)
{
ArraySegment<byte> localCopy = tempList[i];
RangeValidationHelpers.ValidateSegment(localCopy);
_wsaBufferArray[i].Pointer = Marshal.UnsafeAddrOfPinnedArrayElement(localCopy.Array, localCopy.Offset);
_wsaBufferArray[i].Length = localCopy.Count;
}
_pinState = PinState.MultipleBuffer;
}
// Sets up an Overlapped object for SendPacketsAsync.
unsafe private void SetupOverlappedSendPackets()
{
int index;
// Alloc native descriptor.
_sendPacketsDescriptor =
new Interop.Winsock.TransmitPacketsElement[_sendPacketsElementsFileCount + _sendPacketsElementsBufferCount];
// Number of things to pin is number of buffers + 1 (native descriptor).
// Ensure we have properly sized object array.
if (_objectsToPin == null || (_objectsToPin.Length != _sendPacketsElementsBufferCount + 1))
{
_objectsToPin = new object[_sendPacketsElementsBufferCount + 1];
}
// Fill in objects to pin array. Native descriptor buffer first and then user specified buffers.
_objectsToPin[0] = _sendPacketsDescriptor;
index = 1;
foreach (SendPacketsElement spe in _sendPacketsElementsInternal)
{
if (spe != null && spe._buffer != null && spe._count > 0)
{
_objectsToPin[index] = spe._buffer;
index++;
}
}
// Pin buffers.
_preAllocatedOverlapped = new PreAllocatedOverlapped(CompletionPortCallback, this, _objectsToPin);
if (GlobalLog.IsEnabled)
{
GlobalLog.Print(
"SocketAsyncEventArgs#" + LoggingHash.HashString(this) + "::SetupOverlappedSendPackets: new PreAllocatedOverlapped: " +
LoggingHash.HashString(_preAllocatedOverlapped));
}
// Get pointer to native descriptor.
_ptrSendPacketsDescriptor = Marshal.UnsafeAddrOfPinnedArrayElement(_sendPacketsDescriptor, 0);
// Fill in native descriptor.
int descriptorIndex = 0;
int fileIndex = 0;
foreach (SendPacketsElement spe in _sendPacketsElementsInternal)
{
if (spe != null)
{
if (spe._buffer != null && spe._count > 0)
{
// This element is a buffer.
_sendPacketsDescriptor[descriptorIndex].buffer = Marshal.UnsafeAddrOfPinnedArrayElement(spe._buffer, spe._offset);
_sendPacketsDescriptor[descriptorIndex].length = (uint)spe._count;
_sendPacketsDescriptor[descriptorIndex].flags = (Interop.Winsock.TransmitPacketsElementFlags)spe._flags;
descriptorIndex++;
}
else if (spe._filePath != null)
{
// This element is a file.
_sendPacketsDescriptor[descriptorIndex].fileHandle = _sendPacketsFileHandles[fileIndex].DangerousGetHandle();
_sendPacketsDescriptor[descriptorIndex].fileOffset = spe._offset;
_sendPacketsDescriptor[descriptorIndex].length = (uint)spe._count;
_sendPacketsDescriptor[descriptorIndex].flags = (Interop.Winsock.TransmitPacketsElementFlags)spe._flags;
fileIndex++;
descriptorIndex++;
}
}
}
_pinState = PinState.SendPackets;
}
internal void LogBuffer(int size)
{
switch (_pinState)
{
case PinState.SingleAcceptBuffer:
SocketsEventSource.Dump(_acceptBuffer, 0, size);
break;
case PinState.SingleBuffer:
SocketsEventSource.Dump(_buffer, _offset, size);
break;
case PinState.MultipleBuffer:
foreach (WSABuffer wsaBuffer in _wsaBufferArray)
{
SocketsEventSource.Dump(wsaBuffer.Pointer, Math.Min(wsaBuffer.Length, size));
if ((size -= wsaBuffer.Length) <= 0)
{
break;
}
}
break;
default:
break;
}
}
internal void LogSendPacketsBuffers(int size)
{
foreach (SendPacketsElement spe in _sendPacketsElementsInternal)
{
if (spe != null)
{
if (spe._buffer != null && spe._count > 0)
{
// This element is a buffer.
SocketsEventSource.Dump(spe._buffer, spe._offset, Math.Min(spe._count, size));
}
else if (spe._filePath != null)
{
// This element is a file.
SocketsEventSource.Log.NotLoggedFile(spe._filePath, LoggingHash.HashInt(_currentSocket), _completedOperation);
}
}
}
}
private SocketError FinishOperationAccept(Internals.SocketAddress remoteSocketAddress)
{
SocketError socketError;
IntPtr localAddr;
int localAddrLength;
IntPtr remoteAddr;
try
{
_currentSocket.GetAcceptExSockaddrs(
_ptrSingleBuffer != IntPtr.Zero ? _ptrSingleBuffer : _ptrAcceptBuffer,
_count != 0 ? _count - _acceptAddressBufferCount : 0,
_acceptAddressBufferCount / 2,
_acceptAddressBufferCount / 2,
out localAddr,
out localAddrLength,
out remoteAddr,
out remoteSocketAddress.InternalSize
);
Marshal.Copy(remoteAddr, remoteSocketAddress.Buffer, 0, remoteSocketAddress.Size);
// Set the socket context.
IntPtr handle = _currentSocket.SafeHandle.DangerousGetHandle();
socketError = Interop.Winsock.setsockopt(
_acceptSocket.SafeHandle,
SocketOptionLevel.Socket,
SocketOptionName.UpdateAcceptContext,
ref handle,
Marshal.SizeOf(handle));
if (socketError == SocketError.SocketError)
{
socketError = SocketPal.GetLastSocketError();
}
}
catch (ObjectDisposedException)
{
socketError = SocketError.OperationAborted;
}
return socketError;
}
private SocketError FinishOperationConnect()
{
SocketError socketError;
// Update the socket context.
try
{
socketError = Interop.Winsock.setsockopt(
_currentSocket.SafeHandle,
SocketOptionLevel.Socket,
SocketOptionName.UpdateConnectContext,
null,
0);
if (socketError == SocketError.SocketError)
{
socketError = SocketPal.GetLastSocketError();
}
}
catch (ObjectDisposedException)
{
socketError = SocketError.OperationAborted;
}
return socketError;
}
private unsafe int GetSocketAddressSize()
{
return *(int*)_ptrSocketAddressBufferSize;
}
private unsafe void FinishOperationReceiveMessageFrom()
{
IPAddress address = null;
Interop.Winsock.WSAMsg* PtrMessage = (Interop.Winsock.WSAMsg*)Marshal.UnsafeAddrOfPinnedArrayElement(_wsaMessageBuffer, 0);
if (_controlBuffer.Length == s_controlDataSize)
{
// IPv4.
Interop.Winsock.ControlData controlData = Marshal.PtrToStructure<Interop.Winsock.ControlData>(PtrMessage->controlBuffer.Pointer);
if (controlData.length != UIntPtr.Zero)
{
address = new IPAddress((long)controlData.address);
}
_receiveMessageFromPacketInfo = new IPPacketInformation(((address != null) ? address : IPAddress.None), (int)controlData.index);
}
else if (_controlBuffer.Length == s_controlDataIPv6Size)
{
// IPv6.
Interop.Winsock.ControlDataIPv6 controlData = Marshal.PtrToStructure<Interop.Winsock.ControlDataIPv6>(PtrMessage->controlBuffer.Pointer);
if (controlData.length != UIntPtr.Zero)
{
address = new IPAddress(controlData.address);
}
_receiveMessageFromPacketInfo = new IPPacketInformation(((address != null) ? address : IPAddress.IPv6None), (int)controlData.index);
}
else
{
// Other.
_receiveMessageFromPacketInfo = new IPPacketInformation();
}
}
private void FinishOperationSendPackets()
{
// Close the files if open.
if (_sendPacketsFileStreams != null)
{
for (int i = 0; i < _sendPacketsElementsFileCount; i++)
{
// Drop handles.
_sendPacketsFileHandles[i] = null;
// Close any open streams.
if (_sendPacketsFileStreams[i] != null)
{
_sendPacketsFileStreams[i].Dispose();
_sendPacketsFileStreams[i] = null;
}
}
}
_sendPacketsFileStreams = null;
_sendPacketsFileHandles = null;
}
private unsafe void CompletionPortCallback(uint errorCode, uint numBytes, NativeOverlapped* nativeOverlapped)
{
#if DEBUG
GlobalLog.SetThreadSource(ThreadKinds.CompletionPort);
using (GlobalLog.SetThreadKind(ThreadKinds.System))
{
if (GlobalLog.IsEnabled)
{
GlobalLog.Enter(
"CompletionPortCallback",
"errorCode: " + errorCode + ", numBytes: " + numBytes +
", overlapped#" + ((IntPtr)nativeOverlapped).ToString("x"));
}
#endif
SocketFlags socketFlags = SocketFlags.None;
SocketError socketError = (SocketError)errorCode;
// This is the same NativeOverlapped* as we already have a SafeHandle for, re-use the original.
Debug.Assert((IntPtr)nativeOverlapped == _ptrNativeOverlapped.DangerousGetHandle(), "Handle mismatch");
if (socketError == SocketError.Success)
{
FinishOperationSuccess(socketError, (int)numBytes, socketFlags);
}
else
{
if (socketError != SocketError.OperationAborted)
{
if (_currentSocket.CleanedUp)
{
socketError = SocketError.OperationAborted;
}
else
{
try
{
// The Async IO completed with a failure.
// here we need to call WSAGetOverlappedResult() just so Marshal.GetLastWin32Error() will return the correct error.
bool success = Interop.Winsock.WSAGetOverlappedResult(
_currentSocket.SafeHandle,
_ptrNativeOverlapped,
out numBytes,
false,
out socketFlags);
socketError = SocketPal.GetLastSocketError();
}
catch
{
// _currentSocket.CleanedUp check above does not always work since this code is subject to race conditions.
socketError = SocketError.OperationAborted;
}
}
}
FinishOperationAsyncFailure(socketError, (int)numBytes, socketFlags);
}
#if DEBUG
if (GlobalLog.IsEnabled)
{
GlobalLog.Leave("CompletionPortCallback");
}
}
#endif
}
}
}
| |
#region License
/*
The MIT License
Copyright (c) 2008 Sky Morey
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#endregion
using System.Text;
using System.Patterns.Form;
namespace System.Web.UI.WebControls
{
/// <summary>
/// DropDownListEx
/// </summary>
public class DropDownListEx : DropDownList, IFormControl
{
private string _staticTextSeparator = ", ";
private FormFieldViewMode _renderViewMode;
/// <summary>
/// SingleItemRenderMode
/// </summary>
public enum SingleItemRenderMode
{
/// <summary>
/// UseFieldMode
/// </summary>
UseFieldMode = 0,
/// <summary>
/// RenderHidden
/// </summary>
RenderHidden,
/// <summary>
/// RenderStaticWithHidden
/// </summary>
RenderStaticWithHidden
}
public DropDownListEx()
: base()
{
HasHeaderItem = true;
}
public bool AutoSelectFirstItem { get; set; }
public bool AutoSelectIfSingleItem { get; set; }
public bool HasHeaderItem { get; set; }
public FormFieldViewMode ViewMode { get; set; }
#region Option-Groups
public static ListItem CreateBeginGroupListItem(string text)
{
var listItem = new ListItem(text);
listItem.Attributes["group"] = "begin";
return listItem;
}
public static ListItem CreateEndGroupListItem()
{
var listItem = new ListItem();
listItem.Attributes["group"] = "end";
return listItem;
}
//[Match("match with ListBox RenderContents")]
protected override void RenderContents(HtmlTextWriter w)
{
ListItemCollection itemHash = Items;
int itemCount = itemHash.Count;
if (itemCount > 0)
{
bool isA = false;
for (int itemKey = 0; itemKey < itemCount; itemKey++)
{
ListItem listItem = itemHash[itemKey];
if (listItem.Enabled)
switch (listItem.Attributes["group"])
{
case "begin":
w.WriteBeginTag("optgroup");
w.WriteAttribute("label", listItem.Text);
w.Write('>');
break;
case "end":
w.WriteEndTag("optgroup");
break;
default:
w.WriteBeginTag("option");
if (listItem.Selected)
{
if (isA)
VerifyMultiSelect();
isA = true;
w.WriteAttribute("selected", "selected");
}
w.WriteAttribute("value", listItem.Value, true);
if (listItem.Attributes.Count > 0)
listItem.Attributes.Render(w);
if (Page != null)
Page.ClientScript.RegisterForEventValidation(UniqueID, listItem.Value);
w.Write('>');
HttpUtility.HtmlEncode(listItem.Text, w);
w.WriteEndTag("option");
w.WriteLine();
break;
}
}
}
}
#endregion
protected override void OnPreRender(EventArgs e)
{
base.OnPreRender(e);
_renderViewMode = ViewMode;
int itemCountIfListHasSingleItem = (HasHeaderItem ? 2 : 1);
int firstItemIndex = itemCountIfListHasSingleItem - 1;
bool setSelectedIndex = ((SelectedIndex == 0) && ((AutoSelectFirstItem) || ((AutoSelectIfSingleItem) && (Items.Count == itemCountIfListHasSingleItem))));
if (setSelectedIndex)
SelectedIndex = firstItemIndex;
SingleItemRenderMode singleItemRenderMode = SingleItemRenderOption;
if ((singleItemRenderMode != SingleItemRenderMode.UseFieldMode) && (_renderViewMode == FormFieldViewMode.Input) && (Items.Count == itemCountIfListHasSingleItem))
switch (singleItemRenderMode)
{
case SingleItemRenderMode.RenderHidden:
_renderViewMode = FormFieldViewMode.Hidden;
break;
case SingleItemRenderMode.RenderStaticWithHidden:
_renderViewMode = FormFieldViewMode.StaticWithHidden;
break;
}
}
protected override void Render(HtmlTextWriter w)
{
switch (_renderViewMode)
{
case FormFieldViewMode.Static:
RenderStaticText(w);
break;
case FormFieldViewMode.StaticWithHidden:
RenderStaticText(w);
RenderHidden(w);
break;
case FormFieldViewMode.Hidden:
RenderHidden(w);
break;
default:
base.Render(w);
break;
}
}
protected void RenderHidden(HtmlTextWriter w)
{
var b = new StringBuilder();
foreach (ListItem item in Items)
if (item.Selected)
b.Append(item.Value + ",");
if (b.Length > 0)
b.Length--;
w.AddAttribute(HtmlTextWriterAttribute.Type, "hidden");
w.AddAttribute(HtmlTextWriterAttribute.Id, ClientID);
w.AddAttribute(HtmlTextWriterAttribute.Name, UniqueID);
w.AddAttribute(HtmlTextWriterAttribute.Value, b.ToString());
w.RenderBeginTag(HtmlTextWriterTag.Input);
w.RenderEndTag();
}
protected virtual void RenderStaticText(HtmlTextWriter w)
{
string staticTextSeparator = StaticTextSeparator;
var b = new StringBuilder();
foreach (ListItem item in Items)
if (item.Selected)
b.Append(HttpUtility.HtmlEncode(item.Text) + staticTextSeparator);
int staticTextSeparatorLength = staticTextSeparator.Length;
if (b.Length > staticTextSeparatorLength)
b.Length -= staticTextSeparatorLength;
w.AddAttribute(HtmlTextWriterAttribute.Class, "static");
w.RenderBeginTag(HtmlTextWriterTag.Span);
w.Write(b.ToString());
w.RenderEndTag();
}
public SingleItemRenderMode SingleItemRenderOption { get; set; }
public string StaticTextSeparator
{
get { return _staticTextSeparator; }
set
{
if (value == null)
throw new ArgumentNullException("value");
_staticTextSeparator = value;
}
}
}
}
| |
#region License
// Copyright (c) Jeremy Skinner (http://www.jeremyskinner.co.uk)
//
// 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.
//
// The latest version of this file can be found at https://github.com/jeremyskinner/FluentValidation
#endregion
using System.Linq;
namespace FluentValidation.Tests
{
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Xunit;
public class CollectionValidatorWithParentTests
{
Person person;
public CollectionValidatorWithParentTests()
{
person = new Person()
{
AnotherInt = 99,
Children = new List<Person>()
{
new Person() { Email = "person@email.com"}
},
Orders = new List<Order>()
{
new Order { ProductName = "email_that_does_not_belong_to_a_person", Amount = 99},
new Order { ProductName = "person@email.com", Amount = 1},
new Order { ProductName = "another_email_that_does_not_belong_to_a_person", Amount = 1},
}
};
}
[Fact]
public void Validates_collection()
{
var validator = new TestValidator {
v => v.RuleFor(x => x.Surname).NotNull(),
v => v.RuleFor(x => x.Orders).SetCollectionValidator(y => new OrderValidator(y))
};
var results = validator.Validate(person);
results.Errors.Count.ShouldEqual(3);
results.Errors[1].PropertyName.ShouldEqual("Orders[0].ProductName");
results.Errors[2].PropertyName.ShouldEqual("Orders[2].ProductName");
}
[Fact]
public void Validates_collection_asynchronously()
{
var validator = new TestValidator {
v => v.RuleFor(x => x.Surname).NotNull(),
v => v.RuleFor(x => x.Orders).SetCollectionValidator(y => new AsyncOrderValidator(y))
};
var results = validator.ValidateAsync(person).Result;
results.Errors.Count.ShouldEqual(3);
results.Errors[1].PropertyName.ShouldEqual("Orders[0].ProductName");
results.Errors[2].PropertyName.ShouldEqual("Orders[2].ProductName");
}
[Fact]
public void Collection_should_be_explicitly_included_with_expression()
{
var validator = new TestValidator {
v => v.RuleFor(x => x.Surname).NotNull(),
v => v.RuleFor(x => x.Orders).SetCollectionValidator(y => new OrderValidator(y))
};
var results = validator.Validate(person, x => x.Orders);
results.Errors.Count.ShouldEqual(2);
}
[Fact]
public void Collection_should_be_explicitly_included_with_string()
{
var validator = new TestValidator {
v => v.RuleFor(x => x.Surname).NotNull(),
v => v.RuleFor(x => x.Orders).SetCollectionValidator(y => new OrderValidator(y))
};
var results = validator.Validate(person, "Orders");
results.Errors.Count.ShouldEqual(2);
}
[Fact]
public void Collection_should_be_excluded()
{
var validator = new TestValidator {
v => v.RuleFor(x => x.Surname).NotNull(),
v => v.RuleFor(x => x.Orders).SetCollectionValidator(y => new OrderValidator(y))
};
var results = validator.Validate(person, x => x.Forename);
results.Errors.Count.ShouldEqual(0);
}
[Fact]
public void Condition_should_work_with_child_collection()
{
var validator = new TestValidator() {
v => v.RuleFor(x => x.Orders).SetCollectionValidator(y => new OrderValidator(y)).When(x => x.Orders.Count == 4 /*there are only 3*/)
};
var result = validator.Validate(person);
result.IsValid.ShouldBeTrue();
}
[Fact]
public void Async_condition_should_work_with_child_collection() {
var validator = new TestValidator() {
v => v.RuleFor(x => x.Orders).SetCollectionValidator(y => new OrderValidator(y)).WhenAsync(x => TaskHelpers.FromResult(x.Orders.Count == 4 /*there are only 3*/))
};
var result = validator.ValidateAsync(person).Result;
result.IsValid.ShouldBeTrue();
}
[Fact]
public void Skips_null_items()
{
var validator = new TestValidator {
v => v.RuleFor(x => x.Surname).NotNull(),
v => v.RuleFor(x => x.Orders).SetCollectionValidator(y => new OrderValidator(y))
};
person.Orders[0] = null;
var results = validator.Validate(person);
results.Errors.Count.ShouldEqual(2); //2 errors - 1 for person, 1 for 3rd Order.
}
[Fact]
public void Can_validate_collection_using_validator_for_base_type()
{
var validator = new TestValidator() {
v => v.RuleFor(x => x.Orders).SetCollectionValidator(y => new OrderInterfaceValidator(y))
};
var result = validator.Validate(person);
result.IsValid.ShouldBeFalse();
}
[Fact]
public void Can_specifiy_condition_for_individual_collection_elements()
{
var validator = new TestValidator {
v => v.RuleFor(x => x.Orders)
.SetCollectionValidator(y => new OrderValidator(y))
.Where(x => x.Amount != 1)
};
var results = validator.Validate(person);
results.Errors.Count.ShouldEqual(1);
}
[Fact]
public void Should_override_property_name()
{
var validator = new TestValidator {
v => v.RuleFor(x => x.Orders).SetCollectionValidator(y => new OrderValidator(y))
.OverridePropertyName("Orders2")
};
var results = validator.Validate(person);
results.Errors[0].PropertyName.ShouldEqual("Orders2[0].ProductName");
}
public class OrderValidator : AbstractValidator<Order>
{
public OrderValidator(Person person)
{
RuleFor(x => x.ProductName).Must(BeOneOfTheChildrensEmailAddress(person));
}
private Func<string, bool> BeOneOfTheChildrensEmailAddress(Person person)
{
return productName => person.Children.Any(child => child.Email == productName);
}
}
public class OrderInterfaceValidator : AbstractValidator<IOrder>
{
public OrderInterfaceValidator(Person person)
{
RuleFor(x => x.Amount).NotEqual(person.AnotherInt);
}
}
public class AsyncOrderValidator : AbstractValidator<Order>
{
public AsyncOrderValidator(Person person)
{
RuleFor(x => x.ProductName).MustAsync(BeOneOfTheChildrensEmailAddress(person));
}
private Func<string, CancellationToken, Task<bool>> BeOneOfTheChildrensEmailAddress(Person person)
{
return (productName, cancel) => TaskHelpers.FromResult(person.Children.Any(child => child.Email == productName));
}
}
}
}
| |
using System.Collections.Generic;
using System.Diagnostics;
namespace Lucene.Net.Index
{
using Bits = Lucene.Net.Util.Bits;
/*
* 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 Directory = Lucene.Net.Store.Directory;
using InfoStream = Lucene.Net.Util.InfoStream;
using MonotonicAppendingLongBuffer = Lucene.Net.Util.Packed.MonotonicAppendingLongBuffer;
/// <summary>
/// Holds common state used during segment merging.
///
/// @lucene.experimental
/// </summary>
public class MergeState
{
/// <summary>
/// Remaps docids around deletes during merge
/// </summary>
public abstract class DocMap
{
internal DocMap()
{
}
/// <summary>
/// Returns the mapped docID corresponding to the provided one. </summary>
public abstract int Get(int docID);
/// <summary>
/// Returns the total number of documents, ignoring
/// deletions.
/// </summary>
public abstract int MaxDoc { get; }
/// <summary>
/// Returns the number of not-deleted documents. </summary>
public int NumDocs
{
get { return MaxDoc - NumDeletedDocs; }
}
/// <summary>
/// Returns the number of deleted documents. </summary>
public abstract int NumDeletedDocs { get; }
/// <summary>
/// Returns true if there are any deletions. </summary>
public virtual bool HasDeletions()
{
return NumDeletedDocs > 0;
}
/// <summary>
/// Creates a <seealso cref="DocMap"/> instance appropriate for
/// this reader.
/// </summary>
public static DocMap Build(AtomicReader reader)
{
int maxDoc = reader.MaxDoc;
if (!reader.HasDeletions)
{
return new NoDelDocMap(maxDoc);
}
Bits liveDocs = reader.LiveDocs;
return Build(maxDoc, liveDocs);
}
public static DocMap Build(int maxDoc, Bits liveDocs)
{
Debug.Assert(liveDocs != null);
MonotonicAppendingLongBuffer docMap = new MonotonicAppendingLongBuffer();
int del = 0;
for (int i = 0; i < maxDoc; ++i)
{
docMap.Add(i - del);
if (!liveDocs.Get(i))
{
++del;
}
}
docMap.Freeze();
int numDeletedDocs = del;
Debug.Assert(docMap.Size() == maxDoc);
return new DocMapAnonymousInnerClassHelper(maxDoc, liveDocs, docMap, numDeletedDocs);
}
private class DocMapAnonymousInnerClassHelper : DocMap
{
private int maxDoc;
private Bits LiveDocs;
private MonotonicAppendingLongBuffer DocMap;
private int numDeletedDocs;
public DocMapAnonymousInnerClassHelper(int maxDoc, Bits liveDocs, MonotonicAppendingLongBuffer docMap, int numDeletedDocs)
{
this.maxDoc = maxDoc;
this.LiveDocs = liveDocs;
this.DocMap = docMap;
this.numDeletedDocs = numDeletedDocs;
}
public override int Get(int docID)
{
if (!LiveDocs.Get(docID))
{
return -1;
}
return (int)DocMap.Get(docID);
}
public override int MaxDoc
{
get { return maxDoc; }
}
public override int NumDeletedDocs
{
get { return numDeletedDocs; }
}
}
}
private sealed class NoDelDocMap : DocMap
{
internal readonly int maxDoc;
internal NoDelDocMap(int maxDoc)
{
this.maxDoc = maxDoc;
}
public override int Get(int docID)
{
return docID;
}
public override int MaxDoc
{
get { return maxDoc; }
}
public override int NumDeletedDocs
{
get { return 0; }
}
}
/// <summary>
/// <seealso cref="SegmentInfo"/> of the newly merged segment. </summary>
public readonly SegmentInfo SegmentInfo;
/// <summary>
/// <seealso cref="FieldInfos"/> of the newly merged segment. </summary>
public FieldInfos FieldInfos;
/// <summary>
/// Readers being merged. </summary>
public readonly IList<AtomicReader> Readers;
/// <summary>
/// Maps docIDs around deletions. </summary>
public DocMap[] DocMaps;
/// <summary>
/// New docID base per reader. </summary>
public int[] DocBase;
/// <summary>
/// Holds the CheckAbort instance, which is invoked
/// periodically to see if the merge has been aborted.
/// </summary>
public readonly CheckAbort checkAbort;
/// <summary>
/// InfoStream for debugging messages. </summary>
public readonly InfoStream InfoStream;
// TODO: get rid of this? it tells you which segments are 'aligned' (e.g. for bulk merging)
// but is this really so expensive to compute again in different components, versus once in SM?
/// <summary>
/// <seealso cref="SegmentReader"/>s that have identical field
/// name/number mapping, so their stored fields and term
/// vectors may be bulk merged.
/// </summary>
public SegmentReader[] MatchingSegmentReaders;
/// <summary>
/// How many <seealso cref="#matchingSegmentReaders"/> are set. </summary>
public int MatchedCount;
/// <summary>
/// Sole constructor. </summary>
internal MergeState(IList<AtomicReader> readers, SegmentInfo segmentInfo, InfoStream infoStream, CheckAbort checkAbort_)
{
this.Readers = readers;
this.SegmentInfo = segmentInfo;
this.InfoStream = infoStream;
this.checkAbort = checkAbort_;
}
/// <summary>
/// Class for recording units of work when merging segments.
/// </summary>
public class CheckAbort
{
internal double WorkCount;
internal readonly MergePolicy.OneMerge Merge;
internal readonly Directory Dir;
/// <summary>
/// Creates a #CheckAbort instance. </summary>
public CheckAbort(MergePolicy.OneMerge merge, Directory dir)
{
this.Merge = merge;
this.Dir = dir;
}
/// <summary>
/// Records the fact that roughly units amount of work
/// have been done since this method was last called.
/// When adding time-consuming code into SegmentMerger,
/// you should test different values for units to ensure
/// that the time in between calls to merge.checkAborted
/// is up to ~ 1 second.
/// </summary>
public virtual void Work(double units)
{
WorkCount += units;
if (WorkCount >= 10000.0)
{
Merge.CheckAborted(Dir);
WorkCount = 0;
}
}
/// <summary>
/// If you use this: IW.close(false) cannot abort your merge!
/// @lucene.internal
/// </summary>
public static readonly MergeState.CheckAbort NONE = new CheckAbortAnonymousInnerClassHelper();
private class CheckAbortAnonymousInnerClassHelper : MergeState.CheckAbort
{
public CheckAbortAnonymousInnerClassHelper()
: base(null, null)
{
}
public override void Work(double units)
{
// do nothing
}
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.X86;
namespace JIT.HardwareIntrinsics.X86
{
public static partial class Program
{
private static void BlendVariableSByte()
{
var test = new SimpleTernaryOpTest__BlendVariableSByte();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
// Validates basic functionality works, using LoadAligned
test.RunBasicScenario_LoadAligned();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
// Validates calling via reflection works, using LoadAligned
test.RunReflectionScenario_LoadAligned();
}
// Validates passing a static member works
test.RunClsVarScenario();
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
// Validates passing a local works, using LoadAligned
test.RunLclVarScenario_LoadAligned();
}
// Validates passing the field of a local works
test.RunLclFldScenario();
// Validates passing an instance member works
test.RunFldScenario();
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class SimpleTernaryOpTest__BlendVariableSByte
{
private const int VectorSize = 32;
private const int Op1ElementCount = VectorSize / sizeof(SByte);
private const int Op2ElementCount = VectorSize / sizeof(SByte);
private const int Op3ElementCount = VectorSize / sizeof(SByte);
private const int RetElementCount = VectorSize / sizeof(SByte);
private static SByte[] _data1 = new SByte[Op1ElementCount];
private static SByte[] _data2 = new SByte[Op2ElementCount];
private static SByte[] _data3 = new SByte[Op3ElementCount];
private static Vector256<SByte> _clsVar1;
private static Vector256<SByte> _clsVar2;
private static Vector256<SByte> _clsVar3;
private Vector256<SByte> _fld1;
private Vector256<SByte> _fld2;
private Vector256<SByte> _fld3;
private SimpleTernaryOpTest__DataTable<SByte, SByte, SByte, SByte> _dataTable;
static SimpleTernaryOpTest__BlendVariableSByte()
{
var random = new Random();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (sbyte)(random.Next(sbyte.MinValue, sbyte.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<SByte>, byte>(ref _clsVar1), ref Unsafe.As<SByte, byte>(ref _data1[0]), VectorSize);
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (sbyte)(random.Next(sbyte.MinValue, sbyte.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<SByte>, byte>(ref _clsVar2), ref Unsafe.As<SByte, byte>(ref _data2[0]), VectorSize);
for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = (sbyte)(((i % 2) == 0) ? -128 : 1); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<SByte>, byte>(ref _clsVar3), ref Unsafe.As<SByte, byte>(ref _data3[0]), VectorSize);
}
public SimpleTernaryOpTest__BlendVariableSByte()
{
Succeeded = true;
var random = new Random();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (sbyte)(random.Next(sbyte.MinValue, sbyte.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<SByte>, byte>(ref _fld1), ref Unsafe.As<SByte, byte>(ref _data1[0]), VectorSize);
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (sbyte)(random.Next(sbyte.MinValue, sbyte.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<SByte>, byte>(ref _fld2), ref Unsafe.As<SByte, byte>(ref _data2[0]), VectorSize);
for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = (sbyte)(((i % 2) == 0) ? -128 : 1); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<SByte>, byte>(ref _fld3), ref Unsafe.As<SByte, byte>(ref _data3[0]), VectorSize);
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (sbyte)(random.Next(sbyte.MinValue, sbyte.MaxValue)); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (sbyte)(random.Next(sbyte.MinValue, sbyte.MaxValue)); }
for (var i = 0; i < Op3ElementCount; i++) { _data3[i] = (sbyte)(((i % 2) == 0) ? -128 : 1); }
_dataTable = new SimpleTernaryOpTest__DataTable<SByte, SByte, SByte, SByte>(_data1, _data2, _data3, new SByte[RetElementCount], VectorSize);
}
public bool IsSupported => Avx2.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
var result = Avx2.BlendVariable(
Unsafe.Read<Vector256<SByte>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector256<SByte>>(_dataTable.inArray2Ptr),
Unsafe.Read<Vector256<SByte>>(_dataTable.inArray3Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
var result = Avx2.BlendVariable(
Avx.LoadVector256((SByte*)(_dataTable.inArray1Ptr)),
Avx.LoadVector256((SByte*)(_dataTable.inArray2Ptr)),
Avx.LoadVector256((SByte*)(_dataTable.inArray3Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
var result = Avx2.BlendVariable(
Avx.LoadAlignedVector256((SByte*)(_dataTable.inArray1Ptr)),
Avx.LoadAlignedVector256((SByte*)(_dataTable.inArray2Ptr)),
Avx.LoadAlignedVector256((SByte*)(_dataTable.inArray3Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
var result = typeof(Avx2).GetMethod(nameof(Avx2.BlendVariable), new Type[] { typeof(Vector256<SByte>), typeof(Vector256<SByte>), typeof(Vector256<SByte>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector256<SByte>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector256<SByte>>(_dataTable.inArray2Ptr),
Unsafe.Read<Vector256<SByte>>(_dataTable.inArray3Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<SByte>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
var result = typeof(Avx2).GetMethod(nameof(Avx2.BlendVariable), new Type[] { typeof(Vector256<SByte>), typeof(Vector256<SByte>), typeof(Vector256<SByte>) })
.Invoke(null, new object[] {
Avx.LoadVector256((SByte*)(_dataTable.inArray1Ptr)),
Avx.LoadVector256((SByte*)(_dataTable.inArray2Ptr)),
Avx.LoadVector256((SByte*)(_dataTable.inArray3Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<SByte>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
var result = typeof(Avx2).GetMethod(nameof(Avx2.BlendVariable), new Type[] { typeof(Vector256<SByte>), typeof(Vector256<SByte>), typeof(Vector256<SByte>) })
.Invoke(null, new object[] {
Avx.LoadAlignedVector256((SByte*)(_dataTable.inArray1Ptr)),
Avx.LoadAlignedVector256((SByte*)(_dataTable.inArray2Ptr)),
Avx.LoadAlignedVector256((SByte*)(_dataTable.inArray3Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<SByte>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.inArray3Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
var result = Avx2.BlendVariable(
_clsVar1,
_clsVar2,
_clsVar3
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _clsVar3, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_UnsafeRead()
{
var firstOp = Unsafe.Read<Vector256<SByte>>(_dataTable.inArray1Ptr);
var secondOp = Unsafe.Read<Vector256<SByte>>(_dataTable.inArray2Ptr);
var thirdOp = Unsafe.Read<Vector256<SByte>>(_dataTable.inArray3Ptr);
var result = Avx2.BlendVariable(firstOp, secondOp, thirdOp);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, secondOp, thirdOp, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
var firstOp = Avx.LoadVector256((SByte*)(_dataTable.inArray1Ptr));
var secondOp = Avx.LoadVector256((SByte*)(_dataTable.inArray2Ptr));
var thirdOp = Avx.LoadVector256((SByte*)(_dataTable.inArray3Ptr));
var result = Avx2.BlendVariable(firstOp, secondOp, thirdOp);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, secondOp, thirdOp, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
var firstOp = Avx.LoadAlignedVector256((SByte*)(_dataTable.inArray1Ptr));
var secondOp = Avx.LoadAlignedVector256((SByte*)(_dataTable.inArray2Ptr));
var thirdOp = Avx.LoadAlignedVector256((SByte*)(_dataTable.inArray3Ptr));
var result = Avx2.BlendVariable(firstOp, secondOp, thirdOp);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, secondOp, thirdOp, _dataTable.outArrayPtr);
}
public void RunLclFldScenario()
{
var test = new SimpleTernaryOpTest__BlendVariableSByte();
var result = Avx2.BlendVariable(test._fld1, test._fld2, test._fld3);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, test._fld3, _dataTable.outArrayPtr);
}
public void RunFldScenario()
{
var result = Avx2.BlendVariable(_fld1, _fld2, _fld3);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _fld3, _dataTable.outArrayPtr);
}
public void RunUnsupportedScenario()
{
Succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
Succeeded = true;
}
}
private void ValidateResult(Vector256<SByte> firstOp, Vector256<SByte> secondOp, Vector256<SByte> thirdOp, void* result, [CallerMemberName] string method = "")
{
SByte[] inArray1 = new SByte[Op1ElementCount];
SByte[] inArray2 = new SByte[Op2ElementCount];
SByte[] inArray3 = new SByte[Op3ElementCount];
SByte[] outArray = new SByte[RetElementCount];
Unsafe.Write(Unsafe.AsPointer(ref inArray1[0]), firstOp);
Unsafe.Write(Unsafe.AsPointer(ref inArray2[0]), secondOp);
Unsafe.Write(Unsafe.AsPointer(ref inArray3[0]), thirdOp);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize);
ValidateResult(inArray1, inArray2, inArray3, outArray, method);
}
private void ValidateResult(void* firstOp, void* secondOp, void* thirdOp, void* result, [CallerMemberName] string method = "")
{
SByte[] inArray1 = new SByte[Op1ElementCount];
SByte[] inArray2 = new SByte[Op2ElementCount];
SByte[] inArray3 = new SByte[Op3ElementCount];
SByte[] outArray = new SByte[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(firstOp), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(secondOp), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref inArray3[0]), ref Unsafe.AsRef<byte>(thirdOp), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize);
ValidateResult(inArray1, inArray2, inArray3, outArray, method);
}
private void ValidateResult(SByte[] firstOp, SByte[] secondOp, SByte[] thirdOp, SByte[] result, [CallerMemberName] string method = "")
{
if (((thirdOp[0] >> 7) & 1) == 1 ? secondOp[0] != result[0] : firstOp[0] != result[0])
{
Succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if (((thirdOp[i] >> 7) & 1) == 1 ? secondOp[i] != result[i] : firstOp[i] != result[i])
{
Succeeded = false;
break;
}
}
}
if (!Succeeded)
{
Console.WriteLine($"{nameof(Avx2)}.{nameof(Avx2.BlendVariable)}<SByte>(Vector256<SByte>, Vector256<SByte>, Vector256<SByte>): {method} failed:");
Console.WriteLine($" firstOp: ({string.Join(", ", firstOp)})");
Console.WriteLine($" secondOp: ({string.Join(", ", secondOp)})");
Console.WriteLine($" thirdOp: ({string.Join(", ", thirdOp)})");
Console.WriteLine($" result: ({string.Join(", ", result)})");
Console.WriteLine();
}
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.Editor.UnitTests.BraceHighlighting;
using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.BraceHighlighting
{
public class BraceHighlightingTests : AbstractBraceHighlightingTests
{
protected override Task<TestWorkspace> CreateWorkspaceAsync(string markup, ParseOptions options)
{
return TestWorkspace.CreateCSharpAsync(markup, parseOptions: options);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.BraceHighlighting)]
public async Task TestCurlies()
{
await TestBraceHighlightingAsync("public class C$$ {\r\n} ");
await TestBraceHighlightingAsync("public class C $$[|{|]\r\n[|}|] ");
await TestBraceHighlightingAsync("public class C {$$\r\n} ");
await TestBraceHighlightingAsync("public class C {\r\n$$} ");
await TestBraceHighlightingAsync("public class C [|{|]\r\n[|}|]$$ ");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.BraceHighlighting)]
public async Task TestTouchingItems()
{
await TestBraceHighlightingAsync("public class C $$[|{|]\r\n public void Foo(){}\r\n[|}|] ");
await TestBraceHighlightingAsync("public class C {$$\r\n public void Foo(){}\r\n} ");
await TestBraceHighlightingAsync("public class C {\r\n public void Foo$$[|(|][|)|]{}\r\n} ");
await TestBraceHighlightingAsync("public class C {\r\n public void Foo($$){}\r\n} ");
await TestBraceHighlightingAsync("public class C {\r\n public void Foo[|(|][|)|]$$[|{|][|}|]\r\n} ");
await TestBraceHighlightingAsync("public class C {\r\n public void Foo(){$$}\r\n} ");
await TestBraceHighlightingAsync("public class C {\r\n public void Foo()[|{|][|}|]$$\r\n} ");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.BraceHighlighting)]
public async Task TestAngles()
{
await TestBraceHighlightingAsync("/// $$<summary>Foo</summary>");
await TestBraceHighlightingAsync("/// <$$summary>Foo</summary>");
await TestBraceHighlightingAsync("/// <summary$$>Foo</summary>");
await TestBraceHighlightingAsync("/// <summary>$$Foo</summary>");
await TestBraceHighlightingAsync("/// <summary>Foo$$</summary>");
await TestBraceHighlightingAsync("/// <summary>Foo<$$/summary>");
await TestBraceHighlightingAsync("/// <summary>Foo</$$summary>");
await TestBraceHighlightingAsync("/// <summary>Foo</summary$$>");
await TestBraceHighlightingAsync("/// <summary>Foo</summary>$$");
await TestBraceHighlightingAsync(
@"public class C$$[|<|]T[|>|]
{
}");
await TestBraceHighlightingAsync(
@"public class C<$$T>
{
}");
await TestBraceHighlightingAsync(
@"public class C<T$$>
{
}");
await TestBraceHighlightingAsync(
@"public class C[|<|]T[|>$$|]
{
}");
await TestBraceHighlightingAsync(
@"class C
{
void Foo()
{
bool a = b $$< c;
bool d = e > f;
}
}");
await TestBraceHighlightingAsync(
@"class C
{
void Foo()
{
bool a = b <$$ c;
bool d = e > f;
}
}");
await TestBraceHighlightingAsync(
@"class C
{
void Foo()
{
bool a = b < c;
bool d = e $$> f;
}
}");
await TestBraceHighlightingAsync(
@"class C
{
void Foo()
{
bool a = b < c;
bool d = e >$$ f;
}
}");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.BraceHighlighting)]
public async Task TestSwitch()
{
await TestBraceHighlightingAsync(
@"class C
{
void M(int variable)
{
switch $$[|(|]variable[|)|]
{
case 0:
break;
}
}
}");
await TestBraceHighlightingAsync(
@"class C
{
void M(int variable)
{
switch ($$variable)
{
case 0:
break;
}
}
}");
await TestBraceHighlightingAsync(
@"class C
{
void M(int variable)
{
switch (variable$$)
{
case 0:
break;
}
}
}");
await TestBraceHighlightingAsync(
@"class C
{
void M(int variable)
{
switch [|(|]variable[|)$$|]
{
case 0:
break;
}
}
}");
await TestBraceHighlightingAsync(
@"class C
{
void M(int variable)
{
switch (variable)
$$[|{|]
case 0:
break;
[|}|]
}
}");
await TestBraceHighlightingAsync(
@"class C
{
void M(int variable)
{
switch (variable)
{$$
case 0:
break;
}
}
}");
await TestBraceHighlightingAsync(
@"class C
{
void M(int variable)
{
switch (variable)
{
case 0:
break;
$$}
}
}");
await TestBraceHighlightingAsync(
@"class C
{
void M(int variable)
{
switch (variable)
[|{|]
case 0:
break;
[|}$$|]
}
}");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.BraceHighlighting)]
public async Task TestEOF()
{
await TestBraceHighlightingAsync("public class C [|{|]\r\n[|}|]$$");
await TestBraceHighlightingAsync("public class C [|{|]\r\n void Foo(){}[|}|]$$");
}
[WpfFact, Trait(Traits.Feature, Traits.Features.BraceHighlighting)]
public async Task TestTuples()
{
await TestBraceHighlightingAsync(
@"class C
{
[|(|]int, int[|)$$|] x = (1, 2);
}", TestOptions.Regular);
await TestBraceHighlightingAsync(
@"class C
{
(int, int) x = [|(|]1, 2[|)$$|];
}", TestOptions.Regular);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.BraceHighlighting)]
public async Task TestNestedTuples()
{
await TestBraceHighlightingAsync(
@"class C
{
([|(|]int, int[|)$$|], string) x = ((1, 2), ""hello"";
}", TestOptions.Regular);
await TestBraceHighlightingAsync(
@"class C
{
((int, int), string) x = ([|(|]1, 2[|)$$|], ""hello"";
}", TestOptions.Regular);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.BraceHighlighting)]
public async Task TestTuplesWithGenerics()
{
await TestBraceHighlightingAsync(
@"class C
{
[|(|]Dictionary<int, string>, List<int>[|)$$|] x = (null, null);
}", TestOptions.Regular);
await TestBraceHighlightingAsync(
@"class C
{
var x = [|(|]new Dictionary<int, string>(), new List<int>()[|)$$|];
}", TestOptions.Regular);
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Web;
using System.Xml;
using Umbraco.Core;
using Umbraco.Core.Cache;
using Umbraco.Core.Models.Rdbms;
using umbraco.cms.businesslogic.cache;
using umbraco.BusinessLogic;
using umbraco.DataLayer;
using System.Web.Security;
using System.Text;
using System.Security.Cryptography;
using System.Linq;
namespace umbraco.cms.businesslogic.member
{
/// <summary>
/// The Member class represents a member of the public website (not to be confused with umbraco users)
///
/// Members are used when creating communities and collaborative applications using umbraco, or if there are a
/// need for identifying or authentifying the visitor. (extranets, protected/private areas of the public website)
///
/// Inherits generic datafields from it's baseclass content.
/// </summary>
public class Member : Content
{
#region Constants and static members
public static readonly string UmbracoMemberProviderName = "UmbracoMembershipProvider";
public static readonly string UmbracoRoleProviderName = "UmbracoRoleProvider";
public static readonly Guid _objectType = new Guid(Constants.ObjectTypes.Member);
private static readonly object m_Locker = new object();
// zb-00004 #29956 : refactor cookies names & handling
private const string m_SQLOptimizedMany = @"
select
umbracoNode.id, umbracoNode.uniqueId, umbracoNode.level,
umbracoNode.parentId, umbracoNode.path, umbracoNode.sortOrder, umbracoNode.createDate,
umbracoNode.nodeUser, umbracoNode.text,
cmsMember.Email, cmsMember.LoginName, cmsMember.Password
from umbracoNode
inner join cmsContent on cmsContent.nodeId = umbracoNode.id
inner join cmsMember on cmsMember.nodeId = cmsContent.nodeId
where umbracoNode.nodeObjectType = @nodeObjectType AND {0}
order by {1}";
#endregion
#region Private members
private string m_Text;
private string m_Email;
private string m_Password;
private string m_LoginName;
private Hashtable m_Groups = null;
#endregion
#region Constructors
/// <summary>
/// Initializes a new instance of the Member class.
/// </summary>
/// <param name="id">Identifier</param>
public Member(int id) : base(id) { }
/// <summary>
/// Initializes a new instance of the Member class.
/// </summary>
/// <param name="id">Identifier</param>
public Member(Guid id) : base(id) { }
/// <summary>
/// Initializes a new instance of the Member class, with an option to only initialize
/// the data used by the tree in the umbraco console.
/// </summary>
/// <param name="id">Identifier</param>
/// <param name="noSetup"></param>
public Member(int id, bool noSetup) : base(id, noSetup) { }
public Member(Guid id, bool noSetup) : base(id, noSetup) { }
#endregion
#region Static methods
/// <summary>
/// A list of all members in the current umbraco install
///
/// Note: is ressource intensive, use with care.
/// </summary>
public static Member[] GetAll
{
get
{
return GetAllAsList().ToArray();
}
}
public static IEnumerable<Member> GetAllAsList()
{
var tmp = new List<Member>();
using (IRecordsReader dr = SqlHelper.ExecuteReader(
string.Format(m_SQLOptimizedMany.Trim(), "1=1", "umbracoNode.text"),
SqlHelper.CreateParameter("@nodeObjectType", Member._objectType)))
{
while (dr.Read())
{
Member m = new Member(dr.GetInt("id"), true);
m.PopulateMemberFromReader(dr);
tmp.Add(m);
}
}
return tmp.ToArray();
}
/// <summary>
/// Retrieves a list of members thats not start with a-z
/// </summary>
/// <returns>array of members</returns>
public static Member[] getAllOtherMembers()
{
var tmp = new List<Member>();
using (IRecordsReader dr = SqlHelper.ExecuteReader(
string.Format(m_SQLOptimizedMany.Trim(), "LOWER(SUBSTRING(text, 1, 1)) NOT IN ('a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z')", "umbracoNode.text"),
SqlHelper.CreateParameter("@nodeObjectType", Member._objectType)))
{
while (dr.Read())
{
Member m = new Member(dr.GetInt("id"), true);
m.PopulateMemberFromReader(dr);
tmp.Add(m);
}
}
return tmp.ToArray();
}
/// <summary>
/// Retrieves a list of members by the first letter in their name.
/// </summary>
/// <param name="letter">The first letter</param>
/// <returns></returns>
public static Member[] getMemberFromFirstLetter(char letter)
{
return GetMemberByName(letter.ToString(), true);
}
public static Member[] GetMemberByName(string usernameToMatch, bool matchByNameInsteadOfLogin)
{
string field = matchByNameInsteadOfLogin ? "umbracoNode.text" : "cmsMember.loginName";
var tmp = new List<Member>();
using (IRecordsReader dr = SqlHelper.ExecuteReader(
string.Format(m_SQLOptimizedMany.Trim(),
string.Format("{0} like @letter", field),
"umbracoNode.text"),
SqlHelper.CreateParameter("@nodeObjectType", Member._objectType),
SqlHelper.CreateParameter("@letter", usernameToMatch + "%")))
{
while (dr.Read())
{
Member m = new Member(dr.GetInt("id"), true);
m.PopulateMemberFromReader(dr);
tmp.Add(m);
}
}
return tmp.ToArray();
}
/// <summary>
/// Creates a new member
/// </summary>
/// <param name="Name">Membername</param>
/// <param name="mbt">Member type</param>
/// <param name="u">The umbraco usercontext</param>
/// <returns>The new member</returns>
public static Member MakeNew(string Name, MemberType mbt, User u)
{
return MakeNew(Name, "", "", mbt, u);
}
/// <summary>
/// Creates a new member
/// </summary>
/// <param name="Name">Membername</param>
/// <param name="mbt">Member type</param>
/// <param name="u">The umbraco usercontext</param>
/// <param name="Email">The email of the user</param>
/// <returns>The new member</returns>
public static Member MakeNew(string Name, string Email, MemberType mbt, User u)
{
return MakeNew(Name, "", Email, mbt, u);
}
/// <summary>
/// Creates a new member
/// </summary>
/// <param name="Name">Membername</param>
/// <param name="mbt">Member type</param>
/// <param name="u">The umbraco usercontext</param>
/// <param name="Email">The email of the user</param>
/// <returns>The new member</returns>
public static Member MakeNew(string Name, string LoginName, string Email, MemberType mbt, User u)
{
var loginName = (!String.IsNullOrEmpty(LoginName)) ? LoginName : Name;
if (String.IsNullOrEmpty(loginName))
throw new ArgumentException("The loginname must be different from an empty string", "loginName");
// Test for e-mail
if (Email != "" && Member.GetMemberFromEmail(Email) != null && Membership.Providers[UmbracoMemberProviderName].RequiresUniqueEmail)
throw new Exception(String.Format("Duplicate Email! A member with the e-mail {0} already exists", Email));
else if (Member.GetMemberFromLoginName(loginName) != null)
throw new Exception(String.Format("Duplicate User name! A member with the user name {0} already exists", loginName));
// Lowercased to prevent duplicates
Email = Email.ToLower();
Guid newId = Guid.NewGuid();
//create the cms node first
CMSNode newNode = MakeNew(-1, _objectType, u.Id, 1, Name, newId);
//we need to create an empty member and set the underlying text property
Member tmp = new Member(newId, true);
tmp.SetText(Name);
//create the content data for the new member
tmp.CreateContent(mbt);
// Create member specific data ..
SqlHelper.ExecuteNonQuery(
"insert into cmsMember (nodeId,Email,LoginName,Password) values (@id,@email,@loginName,'')",
SqlHelper.CreateParameter("@id", tmp.Id),
SqlHelper.CreateParameter("@loginName", loginName),
SqlHelper.CreateParameter("@email", Email));
//read the whole object from the db
Member m = new Member(newId);
NewEventArgs e = new NewEventArgs();
m.OnNew(e);
m.Save();
return m;
}
/// <summary>
/// Retrieve a member given the loginname
///
/// Used when authentifying the Member
/// </summary>
/// <param name="loginName">The unique Loginname</param>
/// <returns>The member with the specified loginname - null if no Member with the login exists</returns>
public static Member GetMemberFromLoginName(string loginName)
{
if (String.IsNullOrEmpty(loginName))
throw new ArgumentException("The username of a Member must be different from an emptry string", "loginName");
if (IsMember(loginName))
{
object o = SqlHelper.ExecuteScalar<object>(
"select nodeID from cmsMember where LoginName = @loginName",
SqlHelper.CreateParameter("@loginName", loginName));
if (o == null)
return null;
int tmpId;
if (!int.TryParse(o.ToString(), out tmpId))
return null;
return new Member(tmpId);
}
else
HttpContext.Current.Trace.Warn("No member with loginname: " + loginName + " Exists");
return null;
}
/// <summary>
/// Retrieve a Member given an email, the first if there multiple members with same email
///
/// Used when authentifying the Member
/// </summary>
/// <param name="email">The email of the member</param>
/// <returns>The member with the specified email - null if no Member with the email exists</returns>
public static Member GetMemberFromEmail(string email)
{
if (string.IsNullOrEmpty(email))
return null;
object o = SqlHelper.ExecuteScalar<object>(
"select nodeID from cmsMember where Email = @email",
SqlHelper.CreateParameter("@email", email.ToLower()));
if (o == null)
return null;
int tmpId;
if (!int.TryParse(o.ToString(), out tmpId))
return null;
return new Member(tmpId);
}
/// <summary>
/// Retrieve Members given an email
///
/// Used when authentifying a Member
/// </summary>
/// <param name="email">The email of the member(s)</param>
/// <returns>The members with the specified email</returns>
public static Member[] GetMembersFromEmail(string email)
{
if (string.IsNullOrEmpty(email))
return null;
var tmp = new List<Member>();
using (IRecordsReader dr = SqlHelper.ExecuteReader(string.Format(m_SQLOptimizedMany.Trim(),
"Email = @email",
"umbracoNode.text"),
SqlHelper.CreateParameter("@nodeObjectType", Member._objectType),
SqlHelper.CreateParameter("@email", email.ToLower())))
{
while (dr.Read())
{
Member m = new Member(dr.GetInt("id"), true);
m.PopulateMemberFromReader(dr);
tmp.Add(m);
}
}
return tmp.ToArray();
}
/// <summary>
/// Retrieve a Member given the credentials
///
/// Used when authentifying the member
/// </summary>
/// <param name="loginName">Member login</param>
/// <param name="password">Member password</param>
/// <returns>The member with the credentials - null if none exists</returns>
public static Member GetMemberFromLoginNameAndPassword(string loginName, string password)
{
if (IsMember(loginName))
{
// validate user via provider
if (Membership.ValidateUser(loginName, password))
{
return GetMemberFromLoginName(loginName);
}
else
{
HttpContext.Current.Trace.Warn("Incorrect login/password");
return null;
}
}
else
{
HttpContext.Current.Trace.Warn("No member with loginname: " + loginName + " Exists");
// throw new ArgumentException("No member with Loginname: " + LoginName + " exists");
return null;
}
}
public static Member GetMemberFromLoginAndEncodedPassword(string loginName, string password)
{
object o = SqlHelper.ExecuteScalar<object>(
"select nodeID from cmsMember where LoginName = @loginName and Password = @password",
SqlHelper.CreateParameter("loginName", loginName),
SqlHelper.CreateParameter("password", password));
if (o == null)
return null;
int tmpId;
if (!int.TryParse(o.ToString(), out tmpId))
return null;
return new Member(tmpId);
}
public static bool InUmbracoMemberMode()
{
return Membership.Provider.Name == UmbracoMemberProviderName;
}
public static bool IsUsingUmbracoRoles()
{
return Roles.Provider.Name == UmbracoRoleProviderName;
}
/// <summary>
/// Helper method - checks if a Member with the LoginName exists
/// </summary>
/// <param name="loginName">Member login</param>
/// <returns>True if the member exists</returns>
public static bool IsMember(string loginName)
{
Debug.Assert(loginName != null, "loginName cannot be null");
object o = SqlHelper.ExecuteScalar<object>(
"select count(nodeID) as tmp from cmsMember where LoginName = @loginName",
SqlHelper.CreateParameter("@loginName", loginName));
if (o == null)
return false;
int count;
if (!int.TryParse(o.ToString(), out count))
return false;
return count > 0;
}
/// <summary>
/// Deletes all members of the membertype specified
///
/// Used when a membertype is deleted
///
/// Use with care
/// </summary>
/// <param name="dt">The membertype which are being deleted</param>
public static void DeleteFromType(MemberType dt)
{
var objs = getContentOfContentType(dt);
foreach (Content c in objs)
{
// due to recursive structure document might already been deleted..
if (IsNode(c.UniqueId))
{
Member tmp = new Member(c.UniqueId);
tmp.delete();
}
}
}
#endregion
#region Public Properties
/// <summary>
/// The name of the member
/// </summary>
public override string Text
{
get
{
if (string.IsNullOrEmpty(m_Text))
{
m_Text = SqlHelper.ExecuteScalar<string>(
"select text from umbracoNode where id = @id",
SqlHelper.CreateParameter("@id", Id));
}
return m_Text;
}
set
{
m_Text = value;
base.Text = value;
}
}
/// <summary>
/// The members password, used when logging in on the public website
/// </summary>
public string Password
{
get
{
if (string.IsNullOrEmpty(m_Password))
{
m_Password = SqlHelper.ExecuteScalar<string>(
"select Password from cmsMember where nodeId = @id",
SqlHelper.CreateParameter("@id", Id));
}
return m_Password;
}
set
{
// We need to use the provider for this in order for hashing, etc. support
// To write directly to the db use the ChangePassword method
// this is not pretty but nessecary due to a design flaw (the membership provider should have been a part of the cms project)
MemberShipHelper helper = new MemberShipHelper();
ChangePassword(helper.EncodePassword(value, Membership.Provider.PasswordFormat));
}
}
/// <summary>
/// The loginname of the member, used when logging in
/// </summary>
public string LoginName
{
get
{
if (string.IsNullOrEmpty(m_LoginName))
{
m_LoginName = SqlHelper.ExecuteScalar<string>(
"select LoginName from cmsMember where nodeId = @id",
SqlHelper.CreateParameter("@id", Id));
}
return m_LoginName;
}
set
{
if (String.IsNullOrEmpty(value))
throw new ArgumentException("The loginname must be different from an empty string", "LoginName");
if (value.Contains(","))
throw new ArgumentException("The parameter 'LoginName' must not contain commas.");
SqlHelper.ExecuteNonQuery(
"update cmsMember set LoginName = @loginName where nodeId = @id",
SqlHelper.CreateParameter("@loginName", value),
SqlHelper.CreateParameter("@id", Id));
m_LoginName = value;
}
}
/// <summary>
/// A list of groups the member are member of
/// </summary>
public Hashtable Groups
{
get
{
if (m_Groups == null)
PopulateGroups();
return m_Groups;
}
}
/// <summary>
/// The members email
/// </summary>
public string Email
{
get
{
if (String.IsNullOrEmpty(m_Email))
{
m_Email = SqlHelper.ExecuteScalar<string>(
"select Email from cmsMember where nodeId = @id",
SqlHelper.CreateParameter("@id", Id));
}
return m_Email.ToLower();
}
set
{
var oldEmail = Email;
var newEmail = value.ToLower();
var requireUniqueEmail = Membership.Providers[UmbracoMemberProviderName].RequiresUniqueEmail;
var howManyMembersWithEmail = Member.GetMembersFromEmail(newEmail).Length;
if (((oldEmail == newEmail && howManyMembersWithEmail > 1) ||
(oldEmail != newEmail && howManyMembersWithEmail > 0))
&& requireUniqueEmail)
{
// If the value hasn't changed and there are more than 1 member with that email, then throw
// If the value has changed and there are any member with that new email, then throw
throw new Exception(String.Format("Duplicate Email! A member with the e-mail {0} already exists", newEmail));
}
SqlHelper.ExecuteNonQuery(
"update cmsMember set Email = @email where nodeId = @id",
SqlHelper.CreateParameter("@id", Id), SqlHelper.CreateParameter("@email", newEmail));
// Set the backing field to new value
m_Email = newEmail;
}
}
#endregion
#region Public Methods
protected override void setupNode()
{
base.setupNode();
using (IRecordsReader dr = SqlHelper.ExecuteReader(
@"SELECT Email, LoginName, Password FROM cmsMember WHERE nodeId=@nodeId",
SqlHelper.CreateParameter("@nodeId", this.Id)))
{
if (dr.Read())
{
if (!dr.IsNull("Email"))
m_Email = dr.GetString("Email");
m_LoginName = dr.GetString("LoginName");
m_Password = dr.GetString("Password");
}
else
{
throw new ArgumentException(string.Format("No Member exists with Id '{0}'", this.Id));
}
}
}
/// <summary>
/// Used to persist object changes to the database. In Version3.0 it's just a stub for future compatibility
/// </summary>
public override void Save()
{
SaveEventArgs e = new SaveEventArgs();
FireBeforeSave(e);
if (!e.Cancel)
{
var db = ApplicationContext.Current.DatabaseContext.Database;
using (var transaction = db.GetTransaction())
{
foreach (var property in GenericProperties)
{
var poco = new PropertyDataDto
{
Id = property.Id,
PropertyTypeId = property.PropertyType.Id,
NodeId = Id,
VersionId = property.VersionId
};
if (property.Value != null)
{
string dbType = property.PropertyType.DataTypeDefinition.DbType;
if (dbType.Equals("Integer"))
{
if (property.Value is bool || property.PropertyType.DataTypeDefinition.DataType.Id == new Guid("38b352c1-e9f8-4fd8-9324-9a2eab06d97a"))
{
poco.Integer = property.Value != null && string.IsNullOrEmpty(property.Value.ToString())
? 0
: Convert.ToInt32(property.Value);
}
else
{
int value = 0;
if (int.TryParse(property.Value.ToString(), out value))
{
poco.Integer = value;
}
}
}
else if (dbType.Equals("Date"))
{
DateTime date;
if(DateTime.TryParse(property.Value.ToString(), out date))
poco.Date = date;
}
else if (dbType.Equals("Nvarchar"))
{
poco.VarChar = property.Value.ToString();
}
else
{
poco.Text = property.Value.ToString();
}
}
bool isNew = db.IsNew(poco);
if (isNew)
{
db.Insert(poco);
}
else
{
db.Update(poco);
}
}
transaction.Complete();
}
// re-generate xml
XmlDocument xd = new XmlDocument();
XmlGenerate(xd);
// generate preview for blame history?
if (UmbracoSettings.EnableGlobalPreviewStorage)
{
// Version as new guid to ensure different versions are generated as members are not versioned currently!
SavePreviewXml(generateXmlWithoutSaving(xd), Guid.NewGuid());
}
FireAfterSave(e);
}
}
/// <summary>
/// Xmlrepresentation of a member
/// </summary>
/// <param name="xd">The xmldocument context</param>
/// <param name="Deep">Recursive - should always be set to false</param>
/// <returns>A the xmlrepresentation of the current member</returns>
public override XmlNode ToXml(XmlDocument xd, bool Deep)
{
XmlNode x = base.ToXml(xd, Deep);
if (x.Attributes["loginName"] == null)
{
x.Attributes.Append(xmlHelper.addAttribute(xd, "loginName", LoginName));
x.Attributes.Append(xmlHelper.addAttribute(xd, "email", Email));
}
return x;
}
/// <summary>
/// Deltes the current member
/// </summary>
public override void delete()
{
DeleteEventArgs e = new DeleteEventArgs();
FireBeforeDelete(e);
if (!e.Cancel)
{
// delete all relations to groups
foreach (int groupId in this.Groups.Keys)
{
RemoveGroup(groupId);
}
// delete memeberspecific data!
SqlHelper.ExecuteNonQuery("Delete from cmsMember where nodeId = @id",
SqlHelper.CreateParameter("@id", Id));
// Delete all content and cmsnode specific data!
base.delete();
FireAfterDelete(e);
}
}
public void ChangePassword(string newPassword)
{
SqlHelper.ExecuteNonQuery(
"update cmsMember set Password = @password where nodeId = @id",
SqlHelper.CreateParameter("@password", newPassword),
SqlHelper.CreateParameter("@id", Id));
//update this object's password
m_Password = newPassword;
}
/// <summary>
/// Adds the member to group with the specified id
/// </summary>
/// <param name="GroupId">The id of the group which the member is being added to</param>
[MethodImpl(MethodImplOptions.Synchronized)]
public void AddGroup(int GroupId)
{
AddGroupEventArgs e = new AddGroupEventArgs();
e.GroupId = GroupId;
FireBeforeAddGroup(e);
if (!e.Cancel)
{
IParameter[] parameters = new IParameter[] { SqlHelper.CreateParameter("@id", Id),
SqlHelper.CreateParameter("@groupId", GroupId) };
bool exists = SqlHelper.ExecuteScalar<int>("SELECT COUNT(member) FROM cmsMember2MemberGroup WHERE member = @id AND memberGroup = @groupId",
parameters) > 0;
if (!exists)
SqlHelper.ExecuteNonQuery("INSERT INTO cmsMember2MemberGroup (member, memberGroup) values (@id, @groupId)",
parameters);
PopulateGroups();
FireAfterAddGroup(e);
}
}
/// <summary>
/// Removes the member from the MemberGroup specified
/// </summary>
/// <param name="GroupId">The MemberGroup from which the Member is removed</param>
public void RemoveGroup(int GroupId)
{
RemoveGroupEventArgs e = new RemoveGroupEventArgs();
e.GroupId = GroupId;
FireBeforeRemoveGroup(e);
if (!e.Cancel)
{
SqlHelper.ExecuteNonQuery(
"delete from cmsMember2MemberGroup where member = @id and Membergroup = @groupId",
SqlHelper.CreateParameter("@id", Id), SqlHelper.CreateParameter("@groupId", GroupId));
PopulateGroups();
FireAfterRemoveGroup(e);
}
}
#endregion
#region Protected methods
protected override XmlNode generateXmlWithoutSaving(XmlDocument xd)
{
XmlNode node = xd.CreateNode(XmlNodeType.Element, "node", "");
XmlPopulate(xd, ref node, false);
node.Attributes.Append(xmlHelper.addAttribute(xd, "loginName", LoginName));
node.Attributes.Append(xmlHelper.addAttribute(xd, "email", Email));
return node;
}
protected void PopulateMemberFromReader(IRecordsReader dr)
{
SetupNodeForTree(dr.GetGuid("uniqueId"),
_objectType, dr.GetShort("level"),
dr.GetInt("parentId"),
dr.GetInt("nodeUser"),
dr.GetString("path"),
dr.GetString("text"),
dr.GetDateTime("createDate"), false);
if (!dr.IsNull("Email"))
m_Email = dr.GetString("Email");
m_LoginName = dr.GetString("LoginName");
m_Password = dr.GetString("Password");
}
#endregion
#region Private methods
private void PopulateGroups()
{
var temp = new Hashtable();
using (var dr = SqlHelper.ExecuteReader(
"select memberGroup from cmsMember2MemberGroup where member = @id",
SqlHelper.CreateParameter("@id", Id)))
{
while (dr.Read())
temp.Add(dr.GetInt("memberGroup"),
new MemberGroup(dr.GetInt("memberGroup")));
}
m_Groups = temp;
}
private static string GetCacheKey(int id)
{
return string.Format("{0}{1}", CacheKeys.MemberBusinessLogicCacheKey, id);
}
// zb-00035 #29931 : helper class to handle member state
class MemberState
{
public int MemberId { get; set; }
public Guid MemberGuid { get; set; }
public string MemberLogin { get; set; }
public MemberState(int memberId, Guid memberGuid, string memberLogin)
{
MemberId = memberId;
MemberGuid = memberGuid;
MemberLogin = memberLogin;
}
}
// zb-00035 #29931 : helper methods to handle member state
[Obsolete("Only use .NET Membership APIs to handle state now", true)]
static void SetMemberState(Member member)
{
SetMemberState(member.Id, member.UniqueId, member.LoginName);
}
[Obsolete("Only use .NET Membership APIs to handle state now", true)]
static void SetMemberState(int memberId, Guid memberGuid, string memberLogin)
{
string value = string.Format("{0}+{1}+{2}", memberId, memberGuid, memberLogin);
// zb-00004 #29956 : refactor cookies names & handling
StateHelper.Cookies.Member.SetValue(value);
}
[Obsolete("Only use .NET Membership APIs to handle state now", true)]
static void SetMemberState(Member member, bool useSession, double cookieDays)
{
SetMemberState(member.Id, member.UniqueId, member.LoginName, useSession, cookieDays);
}
[Obsolete("Only use .NET Membership APIs to handle state now", true)]
static void SetMemberState(int memberId, Guid memberGuid, string memberLogin, bool useSession, double cookieDays)
{
string value = string.Format("{0}+{1}+{2}", memberId, memberGuid, memberLogin);
// zb-00004 #29956 : refactor cookies names & handling
if (useSession)
HttpContext.Current.Session[StateHelper.Cookies.Member.Key] = value;
else
StateHelper.Cookies.Member.SetValue(value, cookieDays);
}
[Obsolete("Only use .NET Membership APIs to handle state now", true)]
static void ClearMemberState()
{
// zb-00004 #29956 : refactor cookies names & handling
StateHelper.Cookies.Member.Clear();
FormsAuthentication.SignOut();
}
[Obsolete("Only use .NET Membership APIs to handle state now", true)]
static MemberState GetMemberState()
{
// NH: Refactor to fix issue 30171, where auth using pure .NET Members doesn't clear old Umbraco cookie, thus this method gets the previous
// umbraco user instead of the new one
// zb-00004 #29956 : refactor cookies names & handling + bring session-related stuff here
string value = null;
if (StateHelper.Cookies.Member.HasValue)
{
value = StateHelper.Cookies.Member.GetValue();
if (!String.IsNullOrEmpty(value))
{
string validateMemberId = value.Substring(0, value.IndexOf("+"));
if (Membership.GetUser() == null || validateMemberId != Membership.GetUser().ProviderUserKey.ToString())
{
Member.RemoveMemberFromCache(int.Parse(validateMemberId));
value = String.Empty;
}
}
}
// compatibility with .NET Memberships
if (String.IsNullOrEmpty(value) && HttpContext.Current.User.Identity.IsAuthenticated)
{
int _currentMemberId = 0;
if (int.TryParse(Membership.GetUser().ProviderUserKey.ToString(), out _currentMemberId))
{
if (memberExists(_currentMemberId))
{
// current member is always in the cache, else add it!
Member m = GetMemberFromCache(_currentMemberId);
if (m == null)
{
m = new Member(_currentMemberId);
AddMemberToCache(m);
}
return new MemberState(m.Id, m.UniqueId, m.LoginName);
}
}
}
else
{
var context = HttpContext.Current;
if (context != null && context.Session != null && context.Session[StateHelper.Cookies.Member.Key] != null)
{
string v = context.Session[StateHelper.Cookies.Member.Key].ToString();
if (v != "0")
value = v;
}
}
if (value == null)
return null;
// #30350 - do not use Split as memberLogin could contain '+'
int pos1 = value.IndexOf('+');
if (pos1 < 0)
return null;
int pos2 = value.IndexOf('+', pos1 + 1);
if (pos2 < 0)
return null;
int memberId;
if (!Int32.TryParse(value.Substring(0, pos1), out memberId))
return null;
Guid memberGuid;
try
{
// Guid.TryParse is in .NET 4 only
// using try...catch for .NET 3.5 compatibility
memberGuid = new Guid(value.Substring(pos1 + 1, pos2 - pos1 - 1));
}
catch
{
return null;
}
MemberState ms = new MemberState(memberId, memberGuid, value.Substring(pos2 + 1));
return ms;
}
#endregion
#region MemberHandle functions
/// <summary>
/// Method is used when logging a member in.
///
/// Adds the member to the cache of logged in members
///
/// Uses cookiebased recognition
///
/// Can be used in the runtime
/// </summary>
/// <param name="m">The member to log in</param>
public static void AddMemberToCache(Member m)
{
if (m != null)
{
AddToCacheEventArgs e = new AddToCacheEventArgs();
m.FireBeforeAddToCache(e);
if (!e.Cancel)
{
// Add cookie with member-id, guid and loginname
// zb-00035 #29931 : cleanup member state management
// NH 4.7.1: We'll no longer use legacy cookies to handle Umbraco Members
//SetMemberState(m);
FormsAuthentication.SetAuthCookie(m.LoginName, true);
//cache the member
var cachedMember = ApplicationContext.Current.ApplicationCache.GetCacheItem(
GetCacheKey(m.Id),
TimeSpan.FromMinutes(30),
() =>
{
// Debug information
HttpContext.Current.Trace.Write("member",
string.Format("Member added to cache: {0}/{1} ({2})",
m.Text, m.LoginName, m.Id));
return m;
});
m.FireAfterAddToCache(e);
}
}
}
// zb-00035 #29931 : remove old cookie code
/// <summary>
/// Method is used when logging a member in.
///
/// Adds the member to the cache of logged in members
///
/// Uses cookie or session based recognition
///
/// Can be used in the runtime
/// </summary>
/// <param name="m">The member to log in</param>
/// <param name="UseSession">create a persistent cookie</param>
/// <param name="TimespanForCookie">Has no effect</param>
[Obsolete("Use the membership api and FormsAuthentication to log users in, this method is no longer used anymore")]
public static void AddMemberToCache(Member m, bool UseSession, TimeSpan TimespanForCookie)
{
if (m != null)
{
var e = new AddToCacheEventArgs();
m.FireBeforeAddToCache(e);
if (!e.Cancel)
{
// zb-00035 #29931 : cleanup member state management
// NH 4.7.1: We'll no longer use Umbraco legacy cookies to handle members
//SetMemberState(m, UseSession, TimespanForCookie.TotalDays);
FormsAuthentication.SetAuthCookie(m.LoginName, !UseSession);
//cache the member
var cachedMember = ApplicationContext.Current.ApplicationCache.GetCacheItem(
GetCacheKey(m.Id),
TimeSpan.FromMinutes(30),
() =>
{
// Debug information
HttpContext.Current.Trace.Write("member",
string.Format("Member added to cache: {0}/{1} ({2})",
m.Text, m.LoginName, m.Id));
return m;
});
m.FireAfterAddToCache(e);
}
}
}
/// <summary>
/// Removes the member from the cache
///
/// Can be used in the public website
/// </summary>
/// <param name="m">Member to remove</param>
[Obsolete("Obsolete, use the RemoveMemberFromCache(int NodeId) instead", false)]
public static void RemoveMemberFromCache(Member m)
{
RemoveMemberFromCache(m.Id);
}
/// <summary>
/// Removes the member from the cache
///
/// Can be used in the public website
/// </summary>
/// <param name="NodeId">Node Id of the member to remove</param>
[Obsolete("Member cache is automatically cleared when members are updated")]
public static void RemoveMemberFromCache(int NodeId)
{
ApplicationContext.Current.ApplicationCache.ClearCacheItem(GetCacheKey(NodeId));
}
/// <summary>
/// Deletes the member cookie from the browser
///
/// Can be used in the public website
/// </summary>
/// <param name="m">Member</param>
[Obsolete("Obsolete, use the ClearMemberFromClient(int NodeId) instead", false)]
public static void ClearMemberFromClient(Member m)
{
if (m != null)
ClearMemberFromClient(m.Id);
else
{
// If the member doesn't exists as an object, we'll just make sure that cookies are cleared
// zb-00035 #29931 : cleanup member state management
ClearMemberState();
}
FormsAuthentication.SignOut();
}
/// <summary>
/// Deletes the member cookie from the browser
///
/// Can be used in the public website
/// </summary>
/// <param name="NodeId">The Node id of the member to clear</param>
[Obsolete("Use FormsAuthentication.SignOut instead")]
public static void ClearMemberFromClient(int NodeId)
{
// zb-00035 #29931 : cleanup member state management
// NH 4.7.1: We'll no longer use legacy Umbraco cookies to handle members
// ClearMemberState();
FormsAuthentication.SignOut();
RemoveMemberFromCache(NodeId);
}
/// <summary>
/// Retrieve a collection of members in the cache
///
/// Can be used from the public website
/// </summary>
/// <returns>A collection of cached members</returns>
public static Hashtable CachedMembers()
{
var h = new Hashtable();
var items = ApplicationContext.Current.ApplicationCache.GetCacheItemsByKeySearch<Member>(
CacheKeys.MemberBusinessLogicCacheKey);
foreach (var i in items)
{
h.Add(i.Id, i);
}
return h;
}
/// <summary>
/// Retrieve a member from the cache
///
/// Can be used from the public website
/// </summary>
/// <param name="id">Id of the member</param>
/// <returns>If the member is cached it returns the member - else null</returns>
public static Member GetMemberFromCache(int id)
{
Hashtable members = CachedMembers();
if (members.ContainsKey(id))
return (Member)members[id];
else
return null;
}
/// <summary>
/// An indication if the current visitor is logged in
///
/// Can be used from the public website
/// </summary>
/// <returns>True if the the current visitor is logged in</returns>
public static bool IsLoggedOn()
{
if (HttpContext.Current.User == null)
return false;
//if member is not auth'd , but still might have a umb cookie saying otherwise...
if (!HttpContext.Current.User.Identity.IsAuthenticated)
{
int _currentMemberId = CurrentMemberId();
//if we have a cookie...
if (_currentMemberId > 0)
{
//log in the member so .net knows about the member..
FormsAuthentication.SetAuthCookie(new Member(_currentMemberId).LoginName, true);
//making sure that the correct status is returned first time around...
return true;
}
}
return HttpContext.Current.User.Identity.IsAuthenticated;
}
/// <summary>
/// Make a lookup in the database to verify if a member truely exists
/// </summary>
/// <param name="NodeId">The node id of the member</param>
/// <returns>True is a record exists in db</returns>
private static bool memberExists(int NodeId)
{
return SqlHelper.ExecuteScalar<int>("select count(nodeId) from cmsMember where nodeId = @nodeId", SqlHelper.CreateParameter("@nodeId", NodeId)) == 1;
}
/// <summary>
/// Gets the current visitors memberid
/// </summary>
/// <returns>The current visitors members id, if the visitor is not logged in it returns 0</returns>
public static int CurrentMemberId()
{
int _currentMemberId = 0;
// For backwards compatibility between umbraco members and .net membership
if (HttpContext.Current.User.Identity.IsAuthenticated)
{
int.TryParse(Membership.GetUser().ProviderUserKey.ToString(), out _currentMemberId);
}
// NH 4.7.1: We'll no longer use legacy Umbraco cookies to handle members
/*
else
{
// zb-00035 #29931 : cleanup member state management
MemberState ms = GetMemberState();
if (ms != null)
_currentMemberId = ms.MemberId;
}
if (_currentMemberId > 0 && !memberExists(_currentMemberId))
{
_currentMemberId = 0;
// zb-00035 #29931 : cleanup member state management
ClearMemberState();
}
*/
return _currentMemberId;
}
/// <summary>
/// Get the current member
/// </summary>
/// <returns>Returns the member, if visitor is not logged in: null</returns>
public static Member GetCurrentMember()
{
try
{
if (HttpContext.Current.User.Identity.IsAuthenticated)
{
// zb-00035 #29931 : cleanup member state management
/*MemberState ms = GetMemberState();
if (ms == null || ms.MemberId == 0)
return null;
// return member from cache
Member member = GetMemberFromCache(ms.MemberId);
if (member == null)
member = new Member(ms.MemberId);
*/
int _currentMemberId = 0;
if (int.TryParse(Membership.GetUser().ProviderUserKey.ToString(), out _currentMemberId))
{
Member m = new Member(_currentMemberId);
return m;
}
}
}
catch
{
}
return null;
}
#endregion
#region Events
/// <summary>
/// The save event handler
/// </summary>
public delegate void SaveEventHandler(Member sender, SaveEventArgs e);
/// <summary>
/// The new event handler
/// </summary>
public delegate void NewEventHandler(Member sender, NewEventArgs e);
/// <summary>
/// The delete event handler
/// </summary>
public delegate void DeleteEventHandler(Member sender, DeleteEventArgs e);
/// <summary>
/// The add to cache event handler
/// </summary>
public delegate void AddingToCacheEventHandler(Member sender, AddToCacheEventArgs e);
/// <summary>
/// The add group event handler
/// </summary>
public delegate void AddingGroupEventHandler(Member sender, AddGroupEventArgs e);
/// <summary>
/// The remove group event handler
/// </summary>
public delegate void RemovingGroupEventHandler(Member sender, RemoveGroupEventArgs e);
/// <summary>
/// Occurs when [before save].
/// </summary>
new public static event SaveEventHandler BeforeSave;
/// <summary>
/// Raises the <see cref="E:BeforeSave"/> event.
/// </summary>
/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
new protected virtual void FireBeforeSave(SaveEventArgs e)
{
if (BeforeSave != null)
{
BeforeSave(this, e);
}
}
new public static event SaveEventHandler AfterSave;
new protected virtual void FireAfterSave(SaveEventArgs e)
{
if (AfterSave != null)
{
AfterSave(this, e);
}
}
public static event NewEventHandler New;
protected virtual void OnNew(NewEventArgs e)
{
if (New != null)
{
New(this, e);
}
}
public static event AddingGroupEventHandler BeforeAddGroup;
protected virtual void FireBeforeAddGroup(AddGroupEventArgs e)
{
if (BeforeAddGroup != null)
{
BeforeAddGroup(this, e);
}
}
public static event AddingGroupEventHandler AfterAddGroup;
protected virtual void FireAfterAddGroup(AddGroupEventArgs e)
{
if (AfterAddGroup != null)
{
AfterAddGroup(this, e);
}
}
public static event RemovingGroupEventHandler BeforeRemoveGroup;
protected virtual void FireBeforeRemoveGroup(RemoveGroupEventArgs e)
{
if (BeforeRemoveGroup != null)
{
BeforeRemoveGroup(this, e);
}
}
public static event RemovingGroupEventHandler AfterRemoveGroup;
protected virtual void FireAfterRemoveGroup(RemoveGroupEventArgs e)
{
if (AfterRemoveGroup != null)
{
AfterRemoveGroup(this, e);
}
}
public static event AddingToCacheEventHandler BeforeAddToCache;
protected virtual void FireBeforeAddToCache(AddToCacheEventArgs e)
{
if (BeforeAddToCache != null)
{
BeforeAddToCache(this, e);
}
}
public static event AddingToCacheEventHandler AfterAddToCache;
protected virtual void FireAfterAddToCache(AddToCacheEventArgs e)
{
if (AfterAddToCache != null)
{
AfterAddToCache(this, e);
}
}
new public static event DeleteEventHandler BeforeDelete;
new protected virtual void FireBeforeDelete(DeleteEventArgs e)
{
if (BeforeDelete != null)
{
BeforeDelete(this, e);
}
}
new public static event DeleteEventHandler AfterDelete;
new protected virtual void FireAfterDelete(DeleteEventArgs e)
{
if (AfterDelete != null)
{
AfterDelete(this, e);
}
}
#endregion
#region Membership helper class used for encryption methods
/// <summary>
/// ONLY FOR INTERNAL USE.
/// This is needed due to a design flaw where the Umbraco membership provider is located
/// in a separate project referencing this project, which means we can't call special methods
/// directly on the UmbracoMemberShipMember class.
/// This is a helper implementation only to be able to use the encryption functionality
/// of the membership provides (which are protected).
///
/// ... which means this class should have been marked internal with a Friend reference to the other assembly right??
/// </summary>
internal class MemberShipHelper : MembershipProvider
{
public override string ApplicationName
{
get
{
throw new NotImplementedException();
}
set
{
throw new NotImplementedException();
}
}
public override bool ChangePassword(string username, string oldPassword, string newPassword)
{
throw new NotImplementedException();
}
public override bool ChangePasswordQuestionAndAnswer(string username, string password, string newPasswordQuestion, string newPasswordAnswer)
{
throw new NotImplementedException();
}
public override MembershipUser CreateUser(string username, string password, string email, string passwordQuestion, string passwordAnswer, bool isApproved, object providerUserKey, out MembershipCreateStatus status)
{
throw new NotImplementedException();
}
public override bool DeleteUser(string username, bool deleteAllRelatedData)
{
throw new NotImplementedException();
}
public string EncodePassword(string password, MembershipPasswordFormat pwFormat)
{
string encodedPassword = password;
switch (pwFormat)
{
case MembershipPasswordFormat.Clear:
break;
case MembershipPasswordFormat.Encrypted:
encodedPassword =
Convert.ToBase64String(EncryptPassword(Encoding.Unicode.GetBytes(password)));
break;
case MembershipPasswordFormat.Hashed:
HMACSHA1 hash = new HMACSHA1();
hash.Key = Encoding.Unicode.GetBytes(password);
encodedPassword =
Convert.ToBase64String(hash.ComputeHash(Encoding.Unicode.GetBytes(password)));
break;
}
return encodedPassword;
}
public override bool EnablePasswordReset
{
get { throw new NotImplementedException(); }
}
public override bool EnablePasswordRetrieval
{
get { throw new NotImplementedException(); }
}
public override MembershipUserCollection FindUsersByEmail(string emailToMatch, int pageIndex, int pageSize, out int totalRecords)
{
throw new NotImplementedException();
}
public override MembershipUserCollection FindUsersByName(string usernameToMatch, int pageIndex, int pageSize, out int totalRecords)
{
throw new NotImplementedException();
}
public override MembershipUserCollection GetAllUsers(int pageIndex, int pageSize, out int totalRecords)
{
throw new NotImplementedException();
}
public override int GetNumberOfUsersOnline()
{
throw new NotImplementedException();
}
public override string GetPassword(string username, string answer)
{
throw new NotImplementedException();
}
public override MembershipUser GetUser(string username, bool userIsOnline)
{
throw new NotImplementedException();
}
public override MembershipUser GetUser(object providerUserKey, bool userIsOnline)
{
throw new NotImplementedException();
}
public override string GetUserNameByEmail(string email)
{
throw new NotImplementedException();
}
public override int MaxInvalidPasswordAttempts
{
get { throw new NotImplementedException(); }
}
public override int MinRequiredNonAlphanumericCharacters
{
get { throw new NotImplementedException(); }
}
public override int MinRequiredPasswordLength
{
get { throw new NotImplementedException(); }
}
public override int PasswordAttemptWindow
{
get { throw new NotImplementedException(); }
}
public override MembershipPasswordFormat PasswordFormat
{
get { throw new NotImplementedException(); }
}
public override string PasswordStrengthRegularExpression
{
get { throw new NotImplementedException(); }
}
public override bool RequiresQuestionAndAnswer
{
get { throw new NotImplementedException(); }
}
public override bool RequiresUniqueEmail
{
get { throw new NotImplementedException(); }
}
public override string ResetPassword(string username, string answer)
{
throw new NotImplementedException();
}
public override bool UnlockUser(string userName)
{
throw new NotImplementedException();
}
public override void UpdateUser(MembershipUser user)
{
throw new NotImplementedException();
}
public override bool ValidateUser(string username, string password)
{
throw new NotImplementedException();
}
}
#endregion
}
}
| |
// Copyright (c) 1995-2009 held by the author(s). All rights reserved.
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the names of the Naval Postgraduate School (NPS)
// Modeling Virtual Environments and Simulation (MOVES) Institute
// (http://www.nps.edu and http://www.MovesInstitute.org)
// nor the names of its contributors may be used to endorse or
// promote products derived from this software without specific
// prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// AS IS AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
// COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
// ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008, MOVES Institute, Naval Postgraduate School. All
// rights reserved. This work is licensed under the BSD open source license,
// available at https://www.movesinstitute.org/licenses/bsd.html
//
// Author: DMcG
// Modified for use with C#:
// - Peter Smith (Naval Air Warfare Center - Training Systems Division)
// - Zvonko Bostjancic (Blubit d.o.o. - zvonko.bostjancic@blubit.si)
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Text;
using System.Xml.Serialization;
using OpenDis.Core;
namespace OpenDis.Dis1995
{
/// <summary>
/// Section 5.3.6.5. Acknowledge the receiptof a start/resume, stop/freeze, or RemoveEntityPDU
/// </summary>
[Serializable]
[XmlRoot]
public partial class AcknowledgePdu : SimulationManagementPdu, IEquatable<AcknowledgePdu>
{
/// <summary>
/// type of message being acknowledged
/// </summary>
private ushort _acknowledgeFlag;
/// <summary>
/// Whether or not the receiving entity was able to comply with the request
/// </summary>
private ushort _responseFlag;
/// <summary>
/// Request ID that is unique
/// </summary>
private uint _requestID;
/// <summary>
/// Initializes a new instance of the <see cref="AcknowledgePdu"/> class.
/// </summary>
public AcknowledgePdu()
{
PduType = (byte)15;
}
/// <summary>
/// Implements the operator !=.
/// </summary>
/// <param name="left">The left operand.</param>
/// <param name="right">The right operand.</param>
/// <returns>
/// <c>true</c> if operands are not equal; otherwise, <c>false</c>.
/// </returns>
public static bool operator !=(AcknowledgePdu left, AcknowledgePdu right)
{
return !(left == right);
}
/// <summary>
/// Implements the operator ==.
/// </summary>
/// <param name="left">The left operand.</param>
/// <param name="right">The right operand.</param>
/// <returns>
/// <c>true</c> if both operands are equal; otherwise, <c>false</c>.
/// </returns>
public static bool operator ==(AcknowledgePdu left, AcknowledgePdu right)
{
if (object.ReferenceEquals(left, right))
{
return true;
}
if (((object)left == null) || ((object)right == null))
{
return false;
}
return left.Equals(right);
}
public override int GetMarshalledSize()
{
int marshalSize = 0;
marshalSize = base.GetMarshalledSize();
marshalSize += 2; // this._acknowledgeFlag
marshalSize += 2; // this._responseFlag
marshalSize += 4; // this._requestID
return marshalSize;
}
/// <summary>
/// Gets or sets the type of message being acknowledged
/// </summary>
[XmlElement(Type = typeof(ushort), ElementName = "acknowledgeFlag")]
public ushort AcknowledgeFlag
{
get
{
return this._acknowledgeFlag;
}
set
{
this._acknowledgeFlag = value;
}
}
/// <summary>
/// Gets or sets the Whether or not the receiving entity was able to comply with the request
/// </summary>
[XmlElement(Type = typeof(ushort), ElementName = "responseFlag")]
public ushort ResponseFlag
{
get
{
return this._responseFlag;
}
set
{
this._responseFlag = value;
}
}
/// <summary>
/// Gets or sets the Request ID that is unique
/// </summary>
[XmlElement(Type = typeof(uint), ElementName = "requestID")]
public uint RequestID
{
get
{
return this._requestID;
}
set
{
this._requestID = value;
}
}
/// <summary>
/// Automatically sets the length of the marshalled data, then calls the marshal method.
/// </summary>
/// <param name="dos">The DataOutputStream instance to which the PDU is marshaled.</param>
public override void MarshalAutoLengthSet(DataOutputStream dos)
{
// Set the length prior to marshalling data
this.Length = (ushort)this.GetMarshalledSize();
this.Marshal(dos);
}
/// <summary>
/// Marshal the data to the DataOutputStream. Note: Length needs to be set before calling this method
/// </summary>
/// <param name="dos">The DataOutputStream instance to which the PDU is marshaled.</param>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Due to ignoring errors.")]
public override void Marshal(DataOutputStream dos)
{
base.Marshal(dos);
if (dos != null)
{
try
{
dos.WriteUnsignedShort((ushort)this._acknowledgeFlag);
dos.WriteUnsignedShort((ushort)this._responseFlag);
dos.WriteUnsignedInt((uint)this._requestID);
}
catch (Exception e)
{
if (PduBase.TraceExceptions)
{
Trace.WriteLine(e);
Trace.Flush();
}
this.RaiseExceptionOccured(e);
if (PduBase.ThrowExceptions)
{
throw e;
}
}
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Due to ignoring errors.")]
public override void Unmarshal(DataInputStream dis)
{
base.Unmarshal(dis);
if (dis != null)
{
try
{
this._acknowledgeFlag = dis.ReadUnsignedShort();
this._responseFlag = dis.ReadUnsignedShort();
this._requestID = dis.ReadUnsignedInt();
}
catch (Exception e)
{
if (PduBase.TraceExceptions)
{
Trace.WriteLine(e);
Trace.Flush();
}
this.RaiseExceptionOccured(e);
if (PduBase.ThrowExceptions)
{
throw e;
}
}
}
}
/// <summary>
/// This allows for a quick display of PDU data. The current format is unacceptable and only used for debugging.
/// This will be modified in the future to provide a better display. Usage:
/// pdu.GetType().InvokeMember("Reflection", System.Reflection.BindingFlags.InvokeMethod, null, pdu, new object[] { sb });
/// where pdu is an object representing a single pdu and sb is a StringBuilder.
/// Note: The supplied Utilities folder contains a method called 'DecodePDU' in the PDUProcessor Class that provides this functionality
/// </summary>
/// <param name="sb">The StringBuilder instance to which the PDU is written to.</param>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Due to ignoring errors.")]
public override void Reflection(StringBuilder sb)
{
sb.AppendLine("<AcknowledgePdu>");
base.Reflection(sb);
try
{
sb.AppendLine("<acknowledgeFlag type=\"ushort\">" + this._acknowledgeFlag.ToString(CultureInfo.InvariantCulture) + "</acknowledgeFlag>");
sb.AppendLine("<responseFlag type=\"ushort\">" + this._responseFlag.ToString(CultureInfo.InvariantCulture) + "</responseFlag>");
sb.AppendLine("<requestID type=\"uint\">" + this._requestID.ToString(CultureInfo.InvariantCulture) + "</requestID>");
sb.AppendLine("</AcknowledgePdu>");
}
catch (Exception e)
{
if (PduBase.TraceExceptions)
{
Trace.WriteLine(e);
Trace.Flush();
}
this.RaiseExceptionOccured(e);
if (PduBase.ThrowExceptions)
{
throw e;
}
}
}
/// <summary>
/// Determines whether the specified <see cref="System.Object"/> is equal to this instance.
/// </summary>
/// <param name="obj">The <see cref="System.Object"/> to compare with this instance.</param>
/// <returns>
/// <c>true</c> if the specified <see cref="System.Object"/> is equal to this instance; otherwise, <c>false</c>.
/// </returns>
public override bool Equals(object obj)
{
return this == obj as AcknowledgePdu;
}
/// <summary>
/// Compares for reference AND value equality.
/// </summary>
/// <param name="obj">The object to compare with this instance.</param>
/// <returns>
/// <c>true</c> if both operands are equal; otherwise, <c>false</c>.
/// </returns>
public bool Equals(AcknowledgePdu obj)
{
bool ivarsEqual = true;
if (obj.GetType() != this.GetType())
{
return false;
}
ivarsEqual = base.Equals(obj);
if (this._acknowledgeFlag != obj._acknowledgeFlag)
{
ivarsEqual = false;
}
if (this._responseFlag != obj._responseFlag)
{
ivarsEqual = false;
}
if (this._requestID != obj._requestID)
{
ivarsEqual = false;
}
return ivarsEqual;
}
/// <summary>
/// HashCode Helper
/// </summary>
/// <param name="hash">The hash value.</param>
/// <returns>The new hash value.</returns>
private static int GenerateHash(int hash)
{
hash = hash << (5 + hash);
return hash;
}
/// <summary>
/// Gets the hash code.
/// </summary>
/// <returns>The hash code.</returns>
public override int GetHashCode()
{
int result = 0;
result = GenerateHash(result) ^ base.GetHashCode();
result = GenerateHash(result) ^ this._acknowledgeFlag.GetHashCode();
result = GenerateHash(result) ^ this._responseFlag.GetHashCode();
result = GenerateHash(result) ^ this._requestID.GetHashCode();
return result;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
//------------------------------------------------------------------------------
using System.Collections.Generic;
using System.Data.Common;
using System.Data.SqlTypes;
using System.Diagnostics;
using System.IO;
using System.Globalization;
using System.Reflection;
using System.Xml;
using MSS = Microsoft.SqlServer.Server;
using Microsoft.SqlServer.Server;
namespace System.Data.SqlClient
{
using Res = System.SR;
internal abstract class DataFeed
{
}
internal class StreamDataFeed : DataFeed
{
internal Stream _source;
internal StreamDataFeed(Stream source)
{
_source = source;
}
}
internal class TextDataFeed : DataFeed
{
internal TextReader _source;
internal TextDataFeed(TextReader source)
{
_source = source;
}
}
internal class XmlDataFeed : DataFeed
{
internal XmlReader _source;
internal XmlDataFeed(XmlReader source)
{
_source = source;
}
}
public sealed partial class SqlParameter : DbParameter
{
private MetaType _metaType;
private SqlCollation _collation;
private string _xmlSchemaCollectionDatabase;
private string _xmlSchemaCollectionOwningSchema;
private string _xmlSchemaCollectionName;
private string _typeName;
private string _parameterName;
private byte _precision;
private byte _scale;
private bool _hasScale; // V1.0 compat, ignore _hasScale
private MetaType _internalMetaType;
private SqlBuffer _sqlBufferReturnValue;
private INullable _valueAsINullable;
private bool _isSqlParameterSqlType;
private bool _isNull = true;
private bool _coercedValueIsSqlType;
private bool _coercedValueIsDataFeed;
private int _actualSize = -1;
public SqlParameter() : base()
{
}
public SqlParameter(string parameterName, SqlDbType dbType) : this()
{
this.ParameterName = parameterName;
this.SqlDbType = dbType;
}
public SqlParameter(string parameterName, object value) : this()
{
Debug.Assert(!(value is SqlDbType), "use SqlParameter(string, SqlDbType)");
this.ParameterName = parameterName;
this.Value = value;
}
public SqlParameter(string parameterName, SqlDbType dbType, int size) : this()
{
this.ParameterName = parameterName;
this.SqlDbType = dbType;
this.Size = size;
}
public SqlParameter(string parameterName, SqlDbType dbType, int size, string sourceColumn) : this()
{
this.ParameterName = parameterName;
this.SqlDbType = dbType;
this.Size = size;
this.SourceColumn = sourceColumn;
}
//
// currently the user can't set this value. it gets set by the return value from tds
//
internal SqlCollation Collation
{
get
{
return _collation;
}
set
{
_collation = value;
}
}
public SqlCompareOptions CompareInfo
{
// Bits 21 through 25 represent the CompareInfo
get
{
SqlCollation collation = _collation;
if (null != collation)
{
return collation.SqlCompareOptions;
}
return SqlCompareOptions.None;
}
set
{
SqlCollation collation = _collation;
if (null == collation)
{
_collation = collation = new SqlCollation();
}
if ((value & SqlString.x_iValidSqlCompareOptionMask) != value)
{
throw ADP.ArgumentOutOfRange("CompareInfo");
}
collation.SqlCompareOptions = value;
}
}
public string XmlSchemaCollectionDatabase
{
get
{
string xmlSchemaCollectionDatabase = _xmlSchemaCollectionDatabase;
return ((xmlSchemaCollectionDatabase != null) ? xmlSchemaCollectionDatabase : ADP.StrEmpty);
}
set
{
_xmlSchemaCollectionDatabase = value;
}
}
public string XmlSchemaCollectionOwningSchema
{
get
{
string xmlSchemaCollectionOwningSchema = _xmlSchemaCollectionOwningSchema;
return ((xmlSchemaCollectionOwningSchema != null) ? xmlSchemaCollectionOwningSchema : ADP.StrEmpty);
}
set
{
_xmlSchemaCollectionOwningSchema = value;
}
}
public string XmlSchemaCollectionName
{
get
{
string xmlSchemaCollectionName = _xmlSchemaCollectionName;
return ((xmlSchemaCollectionName != null) ? xmlSchemaCollectionName : ADP.StrEmpty);
}
set
{
_xmlSchemaCollectionName = value;
}
}
override public DbType DbType
{
get
{
return GetMetaTypeOnly().DbType;
}
set
{
MetaType metatype = _metaType;
if ((null == metatype) || (metatype.DbType != value) ||
// Two special datetime cases for backward compat
// DbType.Date and DbType.Time should always be treated as setting DbType.DateTime instead
value == DbType.Date ||
value == DbType.Time)
{
PropertyTypeChanging();
_metaType = MetaType.GetMetaTypeFromDbType(value);
}
}
}
public override void ResetDbType()
{
ResetSqlDbType();
}
internal MetaType InternalMetaType
{
get
{
Debug.Assert(null != _internalMetaType, "null InternalMetaType");
return _internalMetaType;
}
set { _internalMetaType = value; }
}
public int LocaleId
{
// Lowest 20 bits represent LocaleId
get
{
SqlCollation collation = _collation;
if (null != collation)
{
return collation.LCID;
}
return 0;
}
set
{
SqlCollation collation = _collation;
if (null == collation)
{
_collation = collation = new SqlCollation();
}
if (value != (SqlCollation.MaskLcid & value))
{
throw ADP.ArgumentOutOfRange("LocaleId");
}
collation.LCID = value;
}
}
internal bool SizeInferred
{
get
{
return 0 == _size;
}
}
internal MSS.SmiParameterMetaData MetaDataForSmi(out ParameterPeekAheadValue peekAhead)
{
peekAhead = null;
MetaType mt = ValidateTypeLengths();
long actualLen = GetActualSize();
long maxLen = this.Size;
// GetActualSize returns bytes length, but smi expects char length for
// character types, so adjust
if (!mt.IsLong)
{
if (SqlDbType.NChar == mt.SqlDbType || SqlDbType.NVarChar == mt.SqlDbType)
{
actualLen = actualLen / sizeof(char);
}
if (actualLen > maxLen)
{
maxLen = actualLen;
}
}
// Determine maxLength for types that ValidateTypeLengths won't figure out
if (0 == maxLen)
{
if (SqlDbType.Binary == mt.SqlDbType || SqlDbType.VarBinary == mt.SqlDbType)
{
maxLen = MSS.SmiMetaData.MaxBinaryLength;
}
else if (SqlDbType.Char == mt.SqlDbType || SqlDbType.VarChar == mt.SqlDbType)
{
maxLen = MSS.SmiMetaData.MaxANSICharacters;
}
else if (SqlDbType.NChar == mt.SqlDbType || SqlDbType.NVarChar == mt.SqlDbType)
{
maxLen = MSS.SmiMetaData.MaxUnicodeCharacters;
}
}
else if ((maxLen > MSS.SmiMetaData.MaxBinaryLength && (SqlDbType.Binary == mt.SqlDbType || SqlDbType.VarBinary == mt.SqlDbType))
|| (maxLen > MSS.SmiMetaData.MaxANSICharacters && (SqlDbType.Char == mt.SqlDbType || SqlDbType.VarChar == mt.SqlDbType))
|| (maxLen > MSS.SmiMetaData.MaxUnicodeCharacters && (SqlDbType.NChar == mt.SqlDbType || SqlDbType.NVarChar == mt.SqlDbType)))
{
maxLen = -1;
}
int localeId = LocaleId;
if (0 == localeId && mt.IsCharType)
{
object value = GetCoercedValue();
if (value is SqlString && !((SqlString)value).IsNull)
{
localeId = ((SqlString)value).LCID;
}
else
{
localeId = Locale.GetCurrentCultureLcid();
}
}
SqlCompareOptions compareOpts = CompareInfo;
if (0 == compareOpts && mt.IsCharType)
{
object value = GetCoercedValue();
if (value is SqlString && !((SqlString)value).IsNull)
{
compareOpts = ((SqlString)value).SqlCompareOptions;
}
else
{
compareOpts = MSS.SmiMetaData.GetDefaultForType(mt.SqlDbType).CompareOptions;
}
}
string typeSpecificNamePart1 = null;
string typeSpecificNamePart2 = null;
string typeSpecificNamePart3 = null;
if (SqlDbType.Xml == mt.SqlDbType)
{
typeSpecificNamePart1 = this.XmlSchemaCollectionDatabase;
typeSpecificNamePart2 = this.XmlSchemaCollectionOwningSchema;
typeSpecificNamePart3 = this.XmlSchemaCollectionName;
}
else if (SqlDbType.Udt == mt.SqlDbType || (SqlDbType.Structured == mt.SqlDbType && !ADP.IsEmpty(this.TypeName)))
{
// Split the input name. The type name is specified as single 3 part name.
// NOTE: ParseTypeName throws if format is incorrect
String[] names;
if (SqlDbType.Udt == mt.SqlDbType)
{
throw ADP.DbTypeNotSupported(SqlDbType.Udt.ToString());
}
else
{
names = ParseTypeName(this.TypeName);
}
if (1 == names.Length)
{
typeSpecificNamePart3 = names[0];
}
else if (2 == names.Length)
{
typeSpecificNamePart2 = names[0];
typeSpecificNamePart3 = names[1];
}
else if (3 == names.Length)
{
typeSpecificNamePart1 = names[0];
typeSpecificNamePart2 = names[1];
typeSpecificNamePart3 = names[2];
}
else
{
throw ADP.ArgumentOutOfRange("names");
}
if ((!ADP.IsEmpty(typeSpecificNamePart1) && TdsEnums.MAX_SERVERNAME < typeSpecificNamePart1.Length)
|| (!ADP.IsEmpty(typeSpecificNamePart2) && TdsEnums.MAX_SERVERNAME < typeSpecificNamePart2.Length)
|| (!ADP.IsEmpty(typeSpecificNamePart3) && TdsEnums.MAX_SERVERNAME < typeSpecificNamePart3.Length))
{
throw ADP.ArgumentOutOfRange("names");
}
}
byte precision = GetActualPrecision();
byte scale = GetActualScale();
// precision for decimal types may still need adjustment.
if (SqlDbType.Decimal == mt.SqlDbType)
{
if (0 == precision)
{
precision = TdsEnums.DEFAULT_NUMERIC_PRECISION;
}
}
// Sub-field determination
List<SmiExtendedMetaData> fields = null;
MSS.SmiMetaDataPropertyCollection extendedProperties = null;
if (SqlDbType.Structured == mt.SqlDbType)
{
GetActualFieldsAndProperties(out fields, out extendedProperties, out peekAhead);
}
return new MSS.SmiParameterMetaData(mt.SqlDbType,
maxLen,
precision,
scale,
localeId,
compareOpts,
SqlDbType.Structured == mt.SqlDbType,
fields,
extendedProperties,
this.ParameterNameFixed,
typeSpecificNamePart1,
typeSpecificNamePart2,
typeSpecificNamePart3,
this.Direction);
}
internal bool ParameterIsSqlType
{
get
{
return _isSqlParameterSqlType;
}
set
{
_isSqlParameterSqlType = value;
}
}
override public string ParameterName
{
get
{
string parameterName = _parameterName;
return ((null != parameterName) ? parameterName : ADP.StrEmpty);
}
set
{
if (ADP.IsEmpty(value) || (value.Length < TdsEnums.MAX_PARAMETER_NAME_LENGTH)
|| (('@' == value[0]) && (value.Length <= TdsEnums.MAX_PARAMETER_NAME_LENGTH)))
{
if (_parameterName != value)
{
PropertyChanging();
_parameterName = value;
}
}
else
{
throw SQL.InvalidParameterNameLength(value);
}
}
}
internal string ParameterNameFixed
{
get
{
string parameterName = ParameterName;
if ((0 < parameterName.Length) && ('@' != parameterName[0]))
{
parameterName = "@" + parameterName;
}
Debug.Assert(parameterName.Length <= TdsEnums.MAX_PARAMETER_NAME_LENGTH, "parameter name too long");
return parameterName;
}
}
public override Byte Precision
{
get
{
return PrecisionInternal;
}
set
{
PrecisionInternal = value;
}
}
internal byte PrecisionInternal
{
get
{
byte precision = _precision;
SqlDbType dbtype = GetMetaSqlDbTypeOnly();
if ((0 == precision) && (SqlDbType.Decimal == dbtype))
{
precision = ValuePrecision(SqlValue);
}
return precision;
}
set
{
SqlDbType sqlDbType = SqlDbType;
if (sqlDbType == SqlDbType.Decimal && value > TdsEnums.MAX_NUMERIC_PRECISION)
{
throw SQL.PrecisionValueOutOfRange(value);
}
if (_precision != value)
{
PropertyChanging();
_precision = value;
}
}
}
private bool ShouldSerializePrecision()
{
return (0 != _precision);
}
public override Byte Scale
{
get
{
return ScaleInternal;
}
set
{
ScaleInternal = value;
}
}
internal byte ScaleInternal
{
get
{
byte scale = _scale;
SqlDbType dbtype = GetMetaSqlDbTypeOnly();
if ((0 == scale) && (SqlDbType.Decimal == dbtype))
{
scale = ValueScale(SqlValue);
}
return scale;
}
set
{
if (_scale != value || !_hasScale)
{
PropertyChanging();
_scale = value;
_hasScale = true;
_actualSize = -1; // Invalidate actual size such that it is re-calculated
}
}
}
private bool ShouldSerializeScale()
{
return (0 != _scale); // V1.0 compat, ignore _hasScale
}
public SqlDbType SqlDbType
{
get
{
return GetMetaTypeOnly().SqlDbType;
}
set
{
MetaType metatype = _metaType;
// HACK!!!
// We didn't want to expose SmallVarBinary on SqlDbType so we
// stuck it at the end of SqlDbType in v1.0, except that now
// we have new data types after that and it's smack dab in the
// middle of the valid range. To prevent folks from setting
// this invalid value we have to have this code here until we
// can take the time to fix it later.
if ((SqlDbType)TdsEnums.SmallVarBinary == value)
{
throw SQL.InvalidSqlDbType(value);
}
if ((null == metatype) || (metatype.SqlDbType != value))
{
PropertyTypeChanging();
_metaType = MetaType.GetMetaTypeFromSqlDbType(value, value == SqlDbType.Structured);
}
}
}
private bool ShouldSerializeSqlDbType()
{
return (null != _metaType);
}
public void ResetSqlDbType()
{
if (null != _metaType)
{
PropertyTypeChanging();
_metaType = null;
}
}
public object SqlValue
{
get
{
if (_value != null)
{
if (_value == DBNull.Value)
{
return MetaType.GetNullSqlValue(GetMetaTypeOnly().SqlType);
}
if (_value is INullable)
{
return _value;
}
// For Date and DateTime2, return the CLR object directly without converting it to a SqlValue
// GetMetaTypeOnly() will convert _value to a string in the case of char or char[], so only check
// the SqlDbType for DateTime.
if (_value is DateTime)
{
SqlDbType sqlDbType = GetMetaTypeOnly().SqlDbType;
if (sqlDbType == SqlDbType.Date || sqlDbType == SqlDbType.DateTime2)
{
return _value;
}
}
return (MetaType.GetSqlValueFromComVariant(_value));
}
else if (_sqlBufferReturnValue != null)
{
return _sqlBufferReturnValue.SqlValue;
}
return null;
}
set
{
Value = value;
}
}
public String TypeName
{
get
{
string typeName = _typeName;
return ((null != typeName) ? typeName : ADP.StrEmpty);
}
set
{
_typeName = value;
}
}
override public object Value
{ // V1.2.3300, XXXParameter V1.0.3300
get
{
if (_value != null)
{
return _value;
}
else if (_sqlBufferReturnValue != null)
{
if (ParameterIsSqlType)
{
return _sqlBufferReturnValue.SqlValue;
}
return _sqlBufferReturnValue.Value;
}
return null;
}
set
{
_value = value;
_sqlBufferReturnValue = null;
_coercedValue = null;
_valueAsINullable = _value as INullable;
_isSqlParameterSqlType = (_valueAsINullable != null);
_isNull = ((_value == null) || (_value == DBNull.Value) || ((_isSqlParameterSqlType) && (_valueAsINullable.IsNull)));
_actualSize = -1;
}
}
internal INullable ValueAsINullable
{
get
{
return _valueAsINullable;
}
}
internal bool IsNull
{
get
{
// NOTE: Udts can change their value any time
if (_internalMetaType.SqlDbType == Data.SqlDbType.Udt)
{
_isNull = ((_value == null) || (_value == DBNull.Value) || ((_isSqlParameterSqlType) && (_valueAsINullable.IsNull)));
}
return _isNull;
}
}
//
// always returns data in bytes - except for non-unicode chars, which will be in number of chars
//
internal int GetActualSize()
{
MetaType mt = InternalMetaType;
SqlDbType actualType = mt.SqlDbType;
// NOTE: Users can change the Udt at any time, so we may need to recalculate
if ((_actualSize == -1) || (actualType == Data.SqlDbType.Udt))
{
_actualSize = 0;
object val = GetCoercedValue();
bool isSqlVariant = false;
if (IsNull && !mt.IsVarTime)
{
return 0;
}
// if this is a backend SQLVariant type, then infer the TDS type from the SQLVariant type
if (actualType == SqlDbType.Variant)
{
mt = MetaType.GetMetaTypeFromValue(val, streamAllowed: false);
actualType = MetaType.GetSqlDataType(mt.TDSType, 0 /*no user type*/, 0 /*non-nullable type*/).SqlDbType;
isSqlVariant = true;
}
if (mt.IsFixed)
{
_actualSize = mt.FixedLength;
}
else
{
// @hack: until we have ForceOffset behavior we have the following semantics:
// @hack: if the user supplies a Size through the Size property or constructor,
// @hack: we only send a MAX of Size bytes over. If the actualSize is < Size, then
// @hack: we send over actualSize
int coercedSize = 0;
// get the actual length of the data, in bytes
switch (actualType)
{
case SqlDbType.NChar:
case SqlDbType.NVarChar:
case SqlDbType.NText:
case SqlDbType.Xml:
{
coercedSize = ((!_isNull) && (!_coercedValueIsDataFeed)) ? (StringSize(val, _coercedValueIsSqlType)) : 0;
_actualSize = (ShouldSerializeSize() ? Size : 0);
_actualSize = ((ShouldSerializeSize() && (_actualSize <= coercedSize)) ? _actualSize : coercedSize);
if (_actualSize == -1)
_actualSize = coercedSize;
_actualSize <<= 1;
}
break;
case SqlDbType.Char:
case SqlDbType.VarChar:
case SqlDbType.Text:
{
// for these types, ActualSize is the num of chars, not actual bytes - since non-unicode chars are not always uniform size
coercedSize = ((!_isNull) && (!_coercedValueIsDataFeed)) ? (StringSize(val, _coercedValueIsSqlType)) : 0;
_actualSize = (ShouldSerializeSize() ? Size : 0);
_actualSize = ((ShouldSerializeSize() && (_actualSize <= coercedSize)) ? _actualSize : coercedSize);
if (_actualSize == -1)
_actualSize = coercedSize;
}
break;
case SqlDbType.Binary:
case SqlDbType.VarBinary:
case SqlDbType.Image:
case SqlDbType.Timestamp:
coercedSize = ((!_isNull) && (!_coercedValueIsDataFeed)) ? (BinarySize(val, _coercedValueIsSqlType)) : 0;
_actualSize = (ShouldSerializeSize() ? Size : 0);
_actualSize = ((ShouldSerializeSize() && (_actualSize <= coercedSize)) ? _actualSize : coercedSize);
if (_actualSize == -1)
_actualSize = coercedSize;
break;
case SqlDbType.Udt:
throw ADP.DbTypeNotSupported(SqlDbType.Udt.ToString());
case SqlDbType.Structured:
coercedSize = -1;
break;
case SqlDbType.Time:
_actualSize = (isSqlVariant ? 5 : MetaType.GetTimeSizeFromScale(GetActualScale()));
break;
case SqlDbType.DateTime2:
// Date in number of days (3 bytes) + time
_actualSize = 3 + (isSqlVariant ? 5 : MetaType.GetTimeSizeFromScale(GetActualScale()));
break;
case SqlDbType.DateTimeOffset:
// Date in days (3 bytes) + offset in minutes (2 bytes) + time
_actualSize = 5 + (isSqlVariant ? 5 : MetaType.GetTimeSizeFromScale(GetActualScale()));
break;
default:
Debug.Assert(false, "Unknown variable length type!");
break;
} // switch
// don't even send big values over to the variant
if (isSqlVariant && (coercedSize > TdsEnums.TYPE_SIZE_LIMIT))
throw SQL.ParameterInvalidVariant(this.ParameterName);
}
}
return _actualSize;
}
// Coerced Value is also used in SqlBulkCopy.ConvertValue(object value, _SqlMetaData metadata)
internal static object CoerceValue(object value, MetaType destinationType, out bool coercedToDataFeed, out bool typeChanged, bool allowStreaming = true)
{
Debug.Assert(!(value is DataFeed), "Value provided should not already be a data feed");
Debug.Assert(!ADP.IsNull(value), "Value provided should not be null");
Debug.Assert(null != destinationType, "null destinationType");
coercedToDataFeed = false;
typeChanged = false;
Type currentType = value.GetType();
if ((typeof(object) != destinationType.ClassType) &&
(currentType != destinationType.ClassType) &&
((currentType != destinationType.SqlType) || (SqlDbType.Xml == destinationType.SqlDbType)))
{ // Special case for Xml types (since we need to convert SqlXml into a string)
try
{
// Assume that the type changed
typeChanged = true;
if ((typeof(string) == destinationType.ClassType))
{
// For Xml data, destination Type is always string
if (typeof(SqlXml) == currentType)
{
value = MetaType.GetStringFromXml((XmlReader)(((SqlXml)value).CreateReader()));
}
else if (typeof(SqlString) == currentType)
{
typeChanged = false; // Do nothing
}
else if (typeof(XmlReader).IsAssignableFrom(currentType))
{
if (allowStreaming)
{
coercedToDataFeed = true;
value = new XmlDataFeed((XmlReader)value);
}
else
{
value = MetaType.GetStringFromXml((XmlReader)value);
}
}
else if (typeof(char[]) == currentType)
{
value = new string((char[])value);
}
else if (typeof(SqlChars) == currentType)
{
value = new string(((SqlChars)value).Value);
}
else if (value is TextReader && allowStreaming)
{
coercedToDataFeed = true;
value = new TextDataFeed((TextReader)value);
}
else
{
value = Convert.ChangeType(value, destinationType.ClassType, (IFormatProvider)null);
}
}
else if ((DbType.Currency == destinationType.DbType) && (typeof(string) == currentType))
{
value = Decimal.Parse((string)value, NumberStyles.Currency, (IFormatProvider)null); // WebData 99376
}
else if ((typeof(SqlBytes) == currentType) && (typeof(byte[]) == destinationType.ClassType))
{
typeChanged = false; // Do nothing
}
else if ((typeof(string) == currentType) && (SqlDbType.Time == destinationType.SqlDbType))
{
value = TimeSpan.Parse((string)value);
}
else if ((typeof(string) == currentType) && (SqlDbType.DateTimeOffset == destinationType.SqlDbType))
{
value = DateTimeOffset.Parse((string)value, (IFormatProvider)null);
}
else if ((typeof(DateTime) == currentType) && (SqlDbType.DateTimeOffset == destinationType.SqlDbType))
{
value = new DateTimeOffset((DateTime)value);
}
else if (TdsEnums.SQLTABLE == destinationType.TDSType && (
value is DbDataReader ||
value is System.Collections.Generic.IEnumerable<SqlDataRecord>))
{
// no conversion for TVPs.
typeChanged = false;
}
else if (destinationType.ClassType == typeof(byte[]) && value is Stream && allowStreaming)
{
coercedToDataFeed = true;
value = new StreamDataFeed((Stream)value);
}
else
{
value = Convert.ChangeType(value, destinationType.ClassType, (IFormatProvider)null);
}
}
catch (Exception e)
{
if (!ADP.IsCatchableExceptionType(e))
{
throw;
}
throw ADP.ParameterConversionFailed(value, destinationType.ClassType, e); // WebData 75433
}
}
Debug.Assert(allowStreaming || !coercedToDataFeed, "Streaming is not allowed, but type was coerced into a data feed");
Debug.Assert(value.GetType() == currentType ^ typeChanged, "Incorrect value for typeChanged");
return value;
}
internal void FixStreamDataForNonPLP()
{
object value = GetCoercedValue();
AssertCachedPropertiesAreValid();
if (!_coercedValueIsDataFeed)
{
return;
}
_coercedValueIsDataFeed = false;
if (value is TextDataFeed)
{
if (Size > 0)
{
char[] buffer = new char[Size];
int nRead = ((TextDataFeed)value)._source.ReadBlock(buffer, 0, Size);
CoercedValue = new string(buffer, 0, nRead);
}
else
{
CoercedValue = ((TextDataFeed)value)._source.ReadToEnd();
}
return;
}
if (value is StreamDataFeed)
{
if (Size > 0)
{
byte[] buffer = new byte[Size];
int totalRead = 0;
Stream sourceStream = ((StreamDataFeed)value)._source;
while (totalRead < Size)
{
int nRead = sourceStream.Read(buffer, totalRead, Size - totalRead);
if (nRead == 0)
{
break;
}
totalRead += nRead;
}
if (totalRead < Size)
{
Array.Resize(ref buffer, totalRead);
}
CoercedValue = buffer;
}
else
{
MemoryStream ms = new MemoryStream();
((StreamDataFeed)value)._source.CopyTo(ms);
CoercedValue = ms.ToArray();
}
return;
}
if (value is XmlDataFeed)
{
CoercedValue = MetaType.GetStringFromXml(((XmlDataFeed)value)._source);
return;
}
// We should have returned before reaching here
Debug.Assert(false, "_coercedValueIsDataFeed was true, but the value was not a known DataFeed type");
}
internal byte GetActualPrecision()
{
return ShouldSerializePrecision() ? PrecisionInternal : ValuePrecision(CoercedValue);
}
internal byte GetActualScale()
{
if (ShouldSerializeScale())
{
return ScaleInternal;
}
// issue: how could a user specify 0 as the actual scale?
if (GetMetaTypeOnly().IsVarTime)
{
return TdsEnums.DEFAULT_VARTIME_SCALE;
}
return ValueScale(CoercedValue);
}
internal int GetParameterSize()
{
return ShouldSerializeSize() ? Size : ValueSize(CoercedValue);
}
private void GetActualFieldsAndProperties(out List<MSS.SmiExtendedMetaData> fields, out SmiMetaDataPropertyCollection props, out ParameterPeekAheadValue peekAhead)
{
fields = null;
props = null;
peekAhead = null;
object value = GetCoercedValue();
if (value is SqlDataReader)
{
fields = new List<MSS.SmiExtendedMetaData>(((SqlDataReader)value).GetInternalSmiMetaData());
if (fields.Count <= 0)
{
throw SQL.NotEnoughColumnsInStructuredType();
}
bool[] keyCols = new bool[fields.Count];
bool hasKey = false;
for (int i = 0; i < fields.Count; i++)
{
MSS.SmiQueryMetaData qmd = fields[i] as MSS.SmiQueryMetaData;
if (null != qmd && !qmd.IsKey.IsNull && qmd.IsKey.Value)
{
keyCols[i] = true;
hasKey = true;
}
}
// Add unique key property, if any found.
if (hasKey)
{
props = new SmiMetaDataPropertyCollection();
props[MSS.SmiPropertySelector.UniqueKey] = new MSS.SmiUniqueKeyProperty(new List<bool>(keyCols));
}
}
else if (value is IEnumerable<SqlDataRecord>)
{
// must grab the first record of the enumerator to get the metadata
IEnumerator<MSS.SqlDataRecord> enumerator = ((IEnumerable<MSS.SqlDataRecord>)value).GetEnumerator();
MSS.SqlDataRecord firstRecord = null;
try
{
// no need for fields if there's no rows or no columns -- we'll be sending a null instance anyway.
if (enumerator.MoveNext())
{
firstRecord = enumerator.Current;
int fieldCount = firstRecord.FieldCount;
if (0 < fieldCount)
{
// It's valid! Grab those fields.
bool[] keyCols = new bool[fieldCount];
bool[] defaultFields = new bool[fieldCount];
bool[] sortOrdinalSpecified = new bool[fieldCount];
int maxSortOrdinal = -1; // largest sort ordinal seen, used to optimize locating holes in the list
bool hasKey = false;
bool hasDefault = false;
int sortCount = 0;
SmiOrderProperty.SmiColumnOrder[] sort = new SmiOrderProperty.SmiColumnOrder[fieldCount];
fields = new List<MSS.SmiExtendedMetaData>(fieldCount);
for (int i = 0; i < fieldCount; i++)
{
SqlMetaData colMeta = firstRecord.GetSqlMetaData(i);
fields.Add(MSS.MetaDataUtilsSmi.SqlMetaDataToSmiExtendedMetaData(colMeta));
if (colMeta.IsUniqueKey)
{
keyCols[i] = true;
hasKey = true;
}
if (colMeta.UseServerDefault)
{
defaultFields[i] = true;
hasDefault = true;
}
sort[i].Order = colMeta.SortOrder;
if (SortOrder.Unspecified != colMeta.SortOrder)
{
// SqlMetaData takes care of checking for negative sort ordinals with specified sort order
// bail early if there's no way sort order could be monotonically increasing
if (fieldCount <= colMeta.SortOrdinal)
{
throw SQL.SortOrdinalGreaterThanFieldCount(i, colMeta.SortOrdinal);
}
// Check to make sure we haven't seen this ordinal before
if (sortOrdinalSpecified[colMeta.SortOrdinal])
{
throw SQL.DuplicateSortOrdinal(colMeta.SortOrdinal);
}
sort[i].SortOrdinal = colMeta.SortOrdinal;
sortOrdinalSpecified[colMeta.SortOrdinal] = true;
if (colMeta.SortOrdinal > maxSortOrdinal)
{
maxSortOrdinal = colMeta.SortOrdinal;
}
sortCount++;
}
}
if (hasKey)
{
props = new SmiMetaDataPropertyCollection();
props[MSS.SmiPropertySelector.UniqueKey] = new MSS.SmiUniqueKeyProperty(new List<bool>(keyCols));
}
if (hasDefault)
{
// May have already created props list in unique key handling
if (null == props)
{
props = new SmiMetaDataPropertyCollection();
}
props[MSS.SmiPropertySelector.DefaultFields] = new MSS.SmiDefaultFieldsProperty(new List<bool>(defaultFields));
}
if (0 < sortCount)
{
// validate monotonically increasing sort order.
// Since we already checked for duplicates, we just need
// to watch for values outside of the sortCount range.
if (maxSortOrdinal >= sortCount)
{
// there is at least one hole, find the first one
int i;
for (i = 0; i < sortCount; i++)
{
if (!sortOrdinalSpecified[i])
{
break;
}
}
Debug.Assert(i < sortCount, "SqlParameter.GetActualFieldsAndProperties: SortOrdinal hole-finding algorithm failed!");
throw SQL.MissingSortOrdinal(i);
}
// May have already created props list
if (null == props)
{
props = new SmiMetaDataPropertyCollection();
}
props[MSS.SmiPropertySelector.SortOrder] = new MSS.SmiOrderProperty(
new List<SmiOrderProperty.SmiColumnOrder>(sort));
}
// pack it up so we don't have to rewind to send the first value
peekAhead = new ParameterPeekAheadValue();
peekAhead.Enumerator = enumerator;
peekAhead.FirstRecord = firstRecord;
// now that it's all packaged, make sure we don't dispose it.
enumerator = null;
}
else
{
throw SQL.NotEnoughColumnsInStructuredType();
}
}
else
{
throw SQL.IEnumerableOfSqlDataRecordHasNoRows();
}
}
finally
{
if (enumerator != null)
{
enumerator.Dispose();
}
}
}
else if (value is DbDataReader)
{
// For ProjectK\CoreCLR, DbDataReader no longer supports GetSchema
// So instead we will attempt to generate the metadata from the Field Type alone
var reader = (DbDataReader)value;
if (reader.FieldCount <= 0)
{
throw SQL.NotEnoughColumnsInStructuredType();
}
fields = new List<MSS.SmiExtendedMetaData>(reader.FieldCount);
for (int i = 0; i < reader.FieldCount; i++)
{
fields.Add(MSS.MetaDataUtilsSmi.SmiMetaDataFromType(reader.GetName(i), reader.GetFieldType(i)));
}
}
}
internal object GetCoercedValue()
{
// NOTE: User can change the Udt at any time
if ((null == _coercedValue) || (_internalMetaType.SqlDbType == Data.SqlDbType.Udt))
{ // will also be set during parameter Validation
bool isDataFeed = Value is DataFeed;
if ((IsNull) || (isDataFeed))
{
// No coercion is done for DataFeeds and Nulls
_coercedValue = Value;
_coercedValueIsSqlType = (_coercedValue == null) ? false : _isSqlParameterSqlType; // set to null for output parameters that keeps _isSqlParameterSqlType
_coercedValueIsDataFeed = isDataFeed;
_actualSize = IsNull ? 0 : -1;
}
else
{
bool typeChanged;
_coercedValue = CoerceValue(Value, _internalMetaType, out _coercedValueIsDataFeed, out typeChanged);
_coercedValueIsSqlType = ((_isSqlParameterSqlType) && (!typeChanged)); // Type changed always results in a CLR type
_actualSize = -1;
}
}
AssertCachedPropertiesAreValid();
return _coercedValue;
}
internal bool CoercedValueIsSqlType
{
get
{
if (null == _coercedValue)
{
GetCoercedValue();
}
AssertCachedPropertiesAreValid();
return _coercedValueIsSqlType;
}
}
internal bool CoercedValueIsDataFeed
{
get
{
if (null == _coercedValue)
{
GetCoercedValue();
}
AssertCachedPropertiesAreValid();
return _coercedValueIsDataFeed;
}
}
[Conditional("DEBUG")]
internal void AssertCachedPropertiesAreValid()
{
AssertPropertiesAreValid(_coercedValue, _coercedValueIsSqlType, _coercedValueIsDataFeed, IsNull);
}
[Conditional("DEBUG")]
internal void AssertPropertiesAreValid(object value, bool? isSqlType = null, bool? isDataFeed = null, bool? isNull = null)
{
Debug.Assert(!isSqlType.HasValue || (isSqlType.Value == (value is INullable)), "isSqlType is incorrect");
Debug.Assert(!isDataFeed.HasValue || (isDataFeed.Value == (value is DataFeed)), "isDataFeed is incorrect");
Debug.Assert(!isNull.HasValue || (isNull.Value == ADP.IsNull(value)), "isNull is incorrect");
}
private SqlDbType GetMetaSqlDbTypeOnly()
{
MetaType metaType = _metaType;
if (null == metaType)
{ // infer the type from the value
metaType = MetaType.GetDefaultMetaType();
}
return metaType.SqlDbType;
}
// This may not be a good thing to do in case someone overloads the parameter type but I
// don't want to go from SqlDbType -> metaType -> TDSType
private MetaType GetMetaTypeOnly()
{
if (null != _metaType)
{
return _metaType;
}
if (null != _value && DBNull.Value != _value)
{
// We have a value set by the user then just use that value
// char and char[] are not directly supported so we convert those values to string
if (_value is char)
{
_value = _value.ToString();
}
else if (Value is char[])
{
_value = new string((char[])_value);
}
return MetaType.GetMetaTypeFromValue(_value, inferLen: false);
}
else if (null != _sqlBufferReturnValue)
{ // value came back from the server
Type valueType = _sqlBufferReturnValue.GetTypeFromStorageType(_isSqlParameterSqlType);
if (null != valueType)
{
return MetaType.GetMetaTypeFromType(valueType);
}
}
return MetaType.GetDefaultMetaType();
}
internal void Prepare(SqlCommand cmd)
{
if (null == _metaType)
{
throw ADP.PrepareParameterType(cmd);
}
else if (!ShouldSerializeSize() && !_metaType.IsFixed)
{
throw ADP.PrepareParameterSize(cmd);
}
else if ((!ShouldSerializePrecision() && !ShouldSerializeScale()) && (_metaType.SqlDbType == SqlDbType.Decimal))
{
throw ADP.PrepareParameterScale(cmd, SqlDbType.ToString());
}
}
private void PropertyChanging()
{
_internalMetaType = null;
}
private void PropertyTypeChanging()
{
PropertyChanging();
CoercedValue = null;
}
internal void SetSqlBuffer(SqlBuffer buff)
{
_sqlBufferReturnValue = buff;
_value = null;
_coercedValue = null;
_isNull = _sqlBufferReturnValue.IsNull;
_coercedValueIsDataFeed = false;
_coercedValueIsSqlType = false;
_actualSize = -1;
}
internal void Validate(int index, bool isCommandProc)
{
MetaType metaType = GetMetaTypeOnly();
_internalMetaType = metaType;
// NOTE: (General Criteria): SqlParameter does a Size Validation check and would fail if the size is 0.
// This condition filters all scenarios where we view a valid size 0.
if (ADP.IsDirection(this, ParameterDirection.Output) &&
!ADP.IsDirection(this, ParameterDirection.ReturnValue) &&
(!metaType.IsFixed) &&
!ShouldSerializeSize() &&
((null == _value) || (_value == DBNull.Value)) &&
(SqlDbType != SqlDbType.Timestamp) &&
(SqlDbType != SqlDbType.Udt) &&
// Output parameter with size 0 throws for XML, TEXT, NTEXT, IMAGE.
(SqlDbType != SqlDbType.Xml) &&
!metaType.IsVarTime)
{
throw ADP.UninitializedParameterSize(index, metaType.ClassType);
}
if (metaType.SqlDbType != SqlDbType.Udt && Direction != ParameterDirection.Output)
{
GetCoercedValue();
}
// Validate structured-type-specific details.
if (metaType.SqlDbType == SqlDbType.Structured)
{
if (!isCommandProc && ADP.IsEmpty(TypeName))
throw SQL.MustSetTypeNameForParam(metaType.TypeName, this.ParameterName);
if (ParameterDirection.Input != this.Direction)
{
throw SQL.UnsupportedTVPOutputParameter(this.Direction, this.ParameterName);
}
if (DBNull.Value == GetCoercedValue())
{
throw SQL.DBNullNotSupportedForTVPValues(this.ParameterName);
}
}
else if (!ADP.IsEmpty(TypeName))
{
throw SQL.UnexpectedTypeNameForNonStructParams(this.ParameterName);
}
}
// func will change type to that with a 4 byte length if the type has a two
// byte length and a parameter length > than that expressible in 2 bytes
internal MetaType ValidateTypeLengths()
{
MetaType mt = InternalMetaType;
// Since the server will automatically reject any
// char, varchar, binary, varbinary, nchar, or nvarchar parameter that has a
// byte sizeInCharacters > 8000 bytes, we promote the parameter to image, text, or ntext. This
// allows the user to specify a parameter type using a COM+ datatype and be able to
// use that parameter against a BLOB column.
if ((SqlDbType.Udt != mt.SqlDbType) && (false == mt.IsFixed) && (false == mt.IsLong))
{ // if type has 2 byte length
long actualSizeInBytes = this.GetActualSize();
long sizeInCharacters = this.Size;
// 'actualSizeInBytes' is the size of value passed;
// 'sizeInCharacters' is the parameter size;
// 'actualSizeInBytes' is in bytes;
// 'this.Size' is in characters;
// 'sizeInCharacters' is in characters;
// 'TdsEnums.TYPE_SIZE_LIMIT' is in bytes;
// For Non-NCharType and for non-Yukon or greater variables, size should be maintained;
// Modified variable names from 'size' to 'sizeInCharacters', 'actualSize' to 'actualSizeInBytes', and
// 'maxSize' to 'maxSizeInBytes'
// The idea is to
// Keeping these goals in mind - the following are the changes we are making
long maxSizeInBytes = 0;
if (mt.IsNCharType)
maxSizeInBytes = ((sizeInCharacters * sizeof(char)) > actualSizeInBytes) ? sizeInCharacters * sizeof(char) : actualSizeInBytes;
else
{
// Notes:
// Elevation from (n)(var)char (4001+) to (n)text succeeds without failure only with Yukon and greater.
// it fails in sql server 2000
maxSizeInBytes = (sizeInCharacters > actualSizeInBytes) ? sizeInCharacters : actualSizeInBytes;
}
if ((maxSizeInBytes > TdsEnums.TYPE_SIZE_LIMIT) || (_coercedValueIsDataFeed) ||
(sizeInCharacters == -1) || (actualSizeInBytes == -1))
{ // is size > size able to be described by 2 bytes
// Convert the parameter to its max type
mt = MetaType.GetMaxMetaTypeFromMetaType(mt);
_metaType = mt;
InternalMetaType = mt;
if (!mt.IsPlp)
{
if (mt.SqlDbType == SqlDbType.Xml)
{
throw ADP.InvalidMetaDataValue(); //Xml should always have IsPartialLength = true
}
if (mt.SqlDbType == SqlDbType.NVarChar
|| mt.SqlDbType == SqlDbType.VarChar
|| mt.SqlDbType == SqlDbType.VarBinary)
{
Size = (int)(SmiMetaData.UnlimitedMaxLengthIndicator);
}
}
}
}
return mt;
}
private byte ValuePrecision(object value)
{
if (value is SqlDecimal)
{
if (((SqlDecimal)value).IsNull)
return 0;
return ((SqlDecimal)value).Precision;
}
return ValuePrecisionCore(value);
}
private byte ValueScale(object value)
{
if (value is SqlDecimal)
{
if (((SqlDecimal)value).IsNull)
return 0;
return ((SqlDecimal)value).Scale;
}
return ValueScaleCore(value);
}
private static int StringSize(object value, bool isSqlType)
{
if (isSqlType)
{
Debug.Assert(!((INullable)value).IsNull, "Should not call StringSize on null values");
if (value is SqlString)
{
return ((SqlString)value).Value.Length;
}
if (value is SqlChars)
{
return ((SqlChars)value).Value.Length;
}
}
else
{
string svalue = (value as string);
if (null != svalue)
{
return svalue.Length;
}
char[] cvalue = (value as char[]);
if (null != cvalue)
{
return cvalue.Length;
}
if (value is char)
{
return 1;
}
}
// Didn't match, unknown size
return 0;
}
private static int BinarySize(object value, bool isSqlType)
{
if (isSqlType)
{
Debug.Assert(!((INullable)value).IsNull, "Should not call StringSize on null values");
if (value is SqlBinary)
{
return ((SqlBinary)value).Length;
}
if (value is SqlBytes)
{
return ((SqlBytes)value).Value.Length;
}
}
else
{
byte[] bvalue = (value as byte[]);
if (null != bvalue)
{
return bvalue.Length;
}
if (value is byte)
{
return 1;
}
}
// Didn't match, unknown size
return 0;
}
private int ValueSize(object value)
{
if (value is SqlString)
{
if (((SqlString)value).IsNull)
return 0;
return ((SqlString)value).Value.Length;
}
if (value is SqlChars)
{
if (((SqlChars)value).IsNull)
return 0;
return ((SqlChars)value).Value.Length;
}
if (value is SqlBinary)
{
if (((SqlBinary)value).IsNull)
return 0;
return ((SqlBinary)value).Length;
}
if (value is SqlBytes)
{
if (((SqlBytes)value).IsNull)
return 0;
return (int)(((SqlBytes)value).Length);
}
if (value is DataFeed)
{
// Unknown length
return 0;
}
return ValueSizeCore(value);
}
// parse an string of the form db.schema.name where any of the three components
// might have "[" "]" and dots within it.
// returns:
// [0] dbname (or null)
// [1] schema (or null)
// [2] name
// NOTE: if perf/space implications of Regex is not a problem, we can get rid
// of this and use a simple regex to do the parsing
internal static string[] ParseTypeName(string typeName)
{
Debug.Assert(null != typeName, "null typename passed to ParseTypeName");
try
{
string errorMsg;
{
errorMsg = Res.SQL_TypeName;
}
return MultipartIdentifier.ParseMultipartIdentifier(typeName, "[\"", "]\"", '.', 3, true, errorMsg, true);
}
catch (ArgumentException)
{
{
throw SQL.InvalidParameterTypeNameFormat();
}
}
}
}
}
| |
// Copyright 2018 The Noda Time Authors. All rights reserved.
// Use of this source code is governed by the Apache License 2.0,
// as found in the LICENSE.txt file.
using NodaTime.Annotations;
using NodaTime.Globalization;
using NodaTime.Text.Patterns;
using NodaTime.Utility;
using System.Globalization;
using System.Text;
namespace NodaTime.Text
{
/// <summary>
/// Represents a pattern for parsing and formatting <see cref="AnnualDate"/> values.
/// </summary>
/// <threadsafety>
/// When used with a read-only <see cref="CultureInfo" />, this type is immutable and instances
/// may be shared freely between threads. We recommend only using read-only cultures for patterns, although this is
/// not currently enforced.
/// </threadsafety>
[Immutable] // Well, assuming an immutable culture...
public sealed class AnnualDatePattern : IPattern<AnnualDate>
{
internal static readonly AnnualDate DefaultTemplateValue = new AnnualDate(1, 1);
private const string DefaultFormatPattern = "G"; // General, ISO-like
internal static readonly PatternBclSupport<AnnualDate> BclSupport =
new PatternBclSupport<AnnualDate>(DefaultFormatPattern, fi => fi.AnnualDatePatternParser);
/// <summary>
/// Gets an invariant annual date pattern which is compatible with the month/day part of ISO-8601.
/// This corresponds to the text pattern "MM'-'dd".
/// </summary>
/// <value>An invariant annual date pattern which is compatible with the month/day part of ISO-8601.</value>
public static AnnualDatePattern Iso => Patterns.IsoPatternImpl;
/// <summary>
/// Class whose existence is solely to avoid type initialization order issues, most of which stem
/// from needing NodaFormatInfo.InvariantInfo...
/// </summary>
private static class Patterns
{
internal static readonly AnnualDatePattern IsoPatternImpl = CreateWithInvariantCulture("MM'-'dd");
}
/// <summary>
/// Returns the pattern that this object delegates to. Mostly useful to avoid this public class
/// implementing an internal interface.
/// </summary>
internal IPartialPattern<AnnualDate> UnderlyingPattern { get; }
/// <summary>
/// Gets the pattern text for this pattern, as supplied on creation.
/// </summary>
/// <value>The pattern text for this pattern, as supplied on creation.</value>
public string PatternText { get; }
/// <summary>
/// Returns the localization information used in this pattern.
/// </summary>
private NodaFormatInfo FormatInfo { get; }
/// <summary>
/// Gets the value used as a template for parsing: any field values unspecified
/// in the pattern are taken from the template.
/// </summary>
/// <value>The value used as a template for parsing.</value>
public AnnualDate TemplateValue { get; }
private AnnualDatePattern(string patternText, NodaFormatInfo formatInfo, AnnualDate templateValue,
IPartialPattern<AnnualDate> pattern)
{
PatternText = patternText;
FormatInfo = formatInfo;
TemplateValue = templateValue;
UnderlyingPattern = pattern;
}
/// <summary>
/// Parses the given text value according to the rules of this pattern.
/// </summary>
/// <remarks>
/// This method never throws an exception (barring a bug in Noda Time itself). Even errors such as
/// the argument being null are wrapped in a parse result.
/// </remarks>
/// <param name="text">The text value to parse.</param>
/// <returns>The result of parsing, which may be successful or unsuccessful.</returns>
public ParseResult<AnnualDate> Parse([SpecialNullHandling] string text) => UnderlyingPattern.Parse(text);
/// <summary>
/// Formats the given annual date as text according to the rules of this pattern.
/// </summary>
/// <param name="value">The annual date to format.</param>
/// <returns>The annual date formatted according to this pattern.</returns>
public string Format(AnnualDate value) => UnderlyingPattern.Format(value);
/// <summary>
/// Formats the given value as text according to the rules of this pattern,
/// appending to the given <see cref="StringBuilder"/>.
/// </summary>
/// <param name="value">The value to format.</param>
/// <param name="builder">The <c>StringBuilder</c> to append to.</param>
/// <returns>The builder passed in as <paramref name="builder"/>.</returns>
public StringBuilder AppendFormat(AnnualDate value, StringBuilder builder) => UnderlyingPattern.AppendFormat(value, builder);
/// <summary>
/// Creates a pattern for the given pattern text, format info, and template value.
/// </summary>
/// <param name="patternText">Pattern text to create the pattern for</param>
/// <param name="formatInfo">The format info to use in the pattern</param>
/// <param name="templateValue">Template value to use for unspecified fields</param>
/// <returns>A pattern for parsing and formatting annual dates.</returns>
/// <exception cref="InvalidPatternException">The pattern text was invalid.</exception>
internal static AnnualDatePattern Create(string patternText, NodaFormatInfo formatInfo,
AnnualDate templateValue)
{
Preconditions.CheckNotNull(patternText, nameof(patternText));
Preconditions.CheckNotNull(formatInfo, nameof(formatInfo));
// Use the "fixed" parser for the common case of the default template value.
var pattern = templateValue == DefaultTemplateValue
? formatInfo.AnnualDatePatternParser.ParsePattern(patternText)
: new AnnualDatePatternParser(templateValue).ParsePattern(patternText, formatInfo);
// If ParsePattern returns a standard pattern instance, we need to get the underlying partial pattern.
pattern = (pattern as AnnualDatePattern)?.UnderlyingPattern ?? pattern;
var partialPattern = (IPartialPattern<AnnualDate>) pattern;
return new AnnualDatePattern(patternText, formatInfo, templateValue, partialPattern);
}
/// <summary>
/// Creates a pattern for the given pattern text, culture, and template value.
/// </summary>
/// <remarks>
/// See the user guide for the available pattern text options.
/// </remarks>
/// <param name="patternText">Pattern text to create the pattern for</param>
/// <param name="cultureInfo">The culture to use in the pattern</param>
/// <param name="templateValue">Template value to use for unspecified fields</param>
/// <returns>A pattern for parsing and formatting annual dates.</returns>
/// <exception cref="InvalidPatternException">The pattern text was invalid.</exception>
public static AnnualDatePattern Create(string patternText, [ValidatedNotNull] CultureInfo cultureInfo, AnnualDate templateValue) =>
Create(patternText, NodaFormatInfo.GetFormatInfo(cultureInfo), templateValue);
/// <summary>
/// Creates a pattern for the given pattern text and culture, with a template value of 2000-01-01.
/// </summary>
/// <remarks>
/// See the user guide for the available pattern text options.
/// </remarks>
/// <param name="patternText">Pattern text to create the pattern for</param>
/// <param name="cultureInfo">The culture to use in the pattern</param>
/// <returns>A pattern for parsing and formatting annual dates.</returns>
/// <exception cref="InvalidPatternException">The pattern text was invalid.</exception>
public static AnnualDatePattern Create(string patternText, CultureInfo cultureInfo) =>
Create(patternText, cultureInfo, DefaultTemplateValue);
/// <summary>
/// Creates a pattern for the given pattern text in the current thread's current culture.
/// </summary>
/// <remarks>
/// See the user guide for the available pattern text options. Note that the current culture
/// is captured at the time this method is called - it is not captured at the point of parsing
/// or formatting values.
/// </remarks>
/// <param name="patternText">Pattern text to create the pattern for</param>
/// <returns>A pattern for parsing and formatting annual dates.</returns>
/// <exception cref="InvalidPatternException">The pattern text was invalid.</exception>
public static AnnualDatePattern CreateWithCurrentCulture(string patternText) =>
Create(patternText, NodaFormatInfo.CurrentInfo, DefaultTemplateValue);
/// <summary>
/// Creates a pattern for the given pattern text in the invariant culture.
/// </summary>
/// <remarks>
/// See the user guide for the available pattern text options. Note that the current culture
/// is captured at the time this method is called - it is not captured at the point of parsing
/// or formatting values.
/// </remarks>
/// <param name="patternText">Pattern text to create the pattern for</param>
/// <returns>A pattern for parsing and formatting annual dates.</returns>
/// <exception cref="InvalidPatternException">The pattern text was invalid.</exception>
public static AnnualDatePattern CreateWithInvariantCulture(string patternText) =>
Create(patternText, NodaFormatInfo.InvariantInfo, DefaultTemplateValue);
/// <summary>
/// Creates a pattern for the same original pattern text as this pattern, but with the specified
/// localization information.
/// </summary>
/// <param name="formatInfo">The localization information to use in the new pattern.</param>
/// <returns>A new pattern with the given localization information.</returns>
private AnnualDatePattern WithFormatInfo(NodaFormatInfo formatInfo) =>
Create(PatternText, formatInfo, TemplateValue);
/// <summary>
/// Creates a pattern for the same original pattern text as this pattern, but with the specified
/// culture.
/// </summary>
/// <param name="cultureInfo">The culture to use in the new pattern.</param>
/// <returns>A new pattern with the given culture.</returns>
public AnnualDatePattern WithCulture([ValidatedNotNull] CultureInfo cultureInfo) =>
WithFormatInfo(NodaFormatInfo.GetFormatInfo(cultureInfo));
/// <summary>
/// Creates a pattern like this one, but with the specified template value.
/// </summary>
/// <param name="newTemplateValue">The template value for the new pattern, used to fill in unspecified fields.</param>
/// <returns>A new pattern with the given template value.</returns>
public AnnualDatePattern WithTemplateValue(AnnualDate newTemplateValue) =>
Create(PatternText, FormatInfo, newTemplateValue);
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.IO;
using System.Reflection;
using OpenMetaverse;
using log4net;
using OpenSim.Framework;
using OpenSim.Region.Framework.Interfaces;
using System.Collections.Generic;
using System.Xml;
using PermissionMask = OpenSim.Framework.PermissionMask;
namespace OpenSim.Region.Framework.Scenes
{
public partial class SceneObjectGroup : EntityBase
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
/// <summary>
/// Force all task inventories of prims in the scene object to persist
/// </summary>
public void ForceInventoryPersistence()
{
SceneObjectPart[] parts = m_parts.GetArray();
for (int i = 0; i < parts.Length; i++)
parts[i].Inventory.ForceInventoryPersistence();
}
/// <summary>
/// Start the scripts contained in all the prims in this group.
/// </summary>
/// <param name="startParam"></param>
/// <param name="postOnRez"></param>
/// <param name="engine"></param>
/// <param name="stateSource"></param>
/// <returns>
/// Number of scripts that were valid for starting. This does not guarantee that all these scripts
/// were actually started, but just that the start could be attempt (e.g. the asset data for the script could be found)
/// </returns>
public int CreateScriptInstances(int startParam, bool postOnRez, string engine, int stateSource)
{
int scriptsStarted = 0;
if (m_scene == null)
{
m_log.DebugFormat("[PRIM INVENTORY]: m_scene is null. Unable to create script instances");
return 0;
}
// Don't start scripts if they're turned off in the region!
if (!m_scene.RegionInfo.RegionSettings.DisableScripts)
{
SceneObjectPart[] parts = m_parts.GetArray();
for (int i = 0; i < parts.Length; i++)
scriptsStarted
+= parts[i].Inventory.CreateScriptInstances(startParam, postOnRez, engine, stateSource);
}
return scriptsStarted;
}
/// <summary>
/// Stop and remove the scripts contained in all the prims in this group
/// </summary>
/// <param name="sceneObjectBeingDeleted">
/// Should be true if these scripts are being removed because the scene
/// object is being deleted. This will prevent spurious updates to the client.
/// </param>
public void RemoveScriptInstances(bool sceneObjectBeingDeleted)
{
SceneObjectPart[] parts = m_parts.GetArray();
for (int i = 0; i < parts.Length; i++)
parts[i].Inventory.RemoveScriptInstances(sceneObjectBeingDeleted);
}
/// <summary>
/// Stop the scripts contained in all the prims in this group
/// </summary>
public void StopScriptInstances()
{
Array.ForEach<SceneObjectPart>(m_parts.GetArray(), p => p.Inventory.StopScriptInstances());
}
/// <summary>
/// Add an inventory item from a user's inventory to a prim in this scene object.
/// </summary>
/// <param name="agentID">The agent adding the item.</param>
/// <param name="localID">The local ID of the part receiving the add.</param>
/// <param name="item">The user inventory item being added.</param>
/// <param name="copyItemID">The item UUID that should be used by the new item.</param>
/// <returns></returns>
public bool AddInventoryItem(UUID agentID, uint localID, InventoryItemBase item, UUID copyItemID)
{
// m_log.DebugFormat(
// "[PRIM INVENTORY]: Adding inventory item {0} from {1} to part with local ID {2}",
// item.Name, remoteClient.Name, localID);
UUID newItemId = (copyItemID != UUID.Zero) ? copyItemID : item.ID;
SceneObjectPart part = GetPart(localID);
if (part != null)
{
TaskInventoryItem taskItem = new TaskInventoryItem();
taskItem.ItemID = newItemId;
taskItem.AssetID = item.AssetID;
taskItem.Name = item.Name;
taskItem.Description = item.Description;
taskItem.OwnerID = part.OwnerID; // Transfer ownership
taskItem.CreatorID = item.CreatorIdAsUuid;
taskItem.Type = item.AssetType;
taskItem.InvType = item.InvType;
if (agentID != part.OwnerID && m_scene.Permissions.PropagatePermissions())
{
taskItem.BasePermissions = item.BasePermissions &
item.NextPermissions;
taskItem.CurrentPermissions = item.CurrentPermissions &
item.NextPermissions;
taskItem.EveryonePermissions = item.EveryOnePermissions &
item.NextPermissions;
taskItem.GroupPermissions = item.GroupPermissions &
item.NextPermissions;
taskItem.NextPermissions = item.NextPermissions;
// We're adding this to a prim we don't own. Force
// owner change
taskItem.Flags |= (uint)InventoryItemFlags.ObjectSlamPerm;
}
else
{
taskItem.BasePermissions = item.BasePermissions;
taskItem.CurrentPermissions = item.CurrentPermissions;
taskItem.EveryonePermissions = item.EveryOnePermissions;
taskItem.GroupPermissions = item.GroupPermissions;
taskItem.NextPermissions = item.NextPermissions;
}
taskItem.Flags = item.Flags;
// m_log.DebugFormat(
// "[PRIM INVENTORY]: Flags are 0x{0:X} for item {1} added to part {2} by {3}",
// taskItem.Flags, taskItem.Name, localID, remoteClient.Name);
// TODO: These are pending addition of those fields to TaskInventoryItem
// taskItem.SalePrice = item.SalePrice;
// taskItem.SaleType = item.SaleType;
taskItem.CreationDate = (uint)item.CreationDate;
bool addFromAllowedDrop = agentID != part.OwnerID;
part.Inventory.AddInventoryItem(taskItem, addFromAllowedDrop);
return true;
}
else
{
m_log.ErrorFormat(
"[PRIM INVENTORY]: " +
"Couldn't find prim local ID {0} in group {1}, {2} to add inventory item ID {3}",
localID, Name, UUID, newItemId);
}
return false;
}
/// <summary>
/// Returns an existing inventory item. Returns the original, so any changes will be live.
/// </summary>
/// <param name="primID"></param>
/// <param name="itemID"></param>
/// <returns>null if the item does not exist</returns>
public TaskInventoryItem GetInventoryItem(uint primID, UUID itemID)
{
SceneObjectPart part = GetPart(primID);
if (part != null)
{
return part.Inventory.GetInventoryItem(itemID);
}
else
{
m_log.ErrorFormat(
"[PRIM INVENTORY]: " +
"Couldn't find prim local ID {0} in prim {1}, {2} to get inventory item ID {3}",
primID, part.Name, part.UUID, itemID);
}
return null;
}
/// <summary>
/// Update an existing inventory item.
/// </summary>
/// <param name="item">The updated item. An item with the same id must already exist
/// in this prim's inventory</param>
/// <returns>false if the item did not exist, true if the update occurred succesfully</returns>
public bool UpdateInventoryItem(TaskInventoryItem item)
{
SceneObjectPart part = GetPart(item.ParentPartID);
if (part != null)
{
part.Inventory.UpdateInventoryItem(item);
return true;
}
else
{
m_log.ErrorFormat(
"[PRIM INVENTORY]: " +
"Couldn't find prim ID {0} to update item {1}, {2}",
item.ParentPartID, item.Name, item.ItemID);
}
return false;
}
public int RemoveInventoryItem(uint localID, UUID itemID)
{
SceneObjectPart part = GetPart(localID);
if (part != null)
{
int type = part.Inventory.RemoveInventoryItem(itemID);
return type;
}
return -1;
}
public uint GetEffectivePermissions()
{
uint perms=(uint)(PermissionMask.Modify |
PermissionMask.Copy |
PermissionMask.Move |
PermissionMask.Transfer) | 7;
uint ownerMask = 0x7fffffff;
SceneObjectPart[] parts = m_parts.GetArray();
for (int i = 0; i < parts.Length; i++)
{
SceneObjectPart part = parts[i];
ownerMask &= part.OwnerMask;
perms &= part.Inventory.MaskEffectivePermissions();
}
if ((ownerMask & (uint)PermissionMask.Modify) == 0)
perms &= ~(uint)PermissionMask.Modify;
if ((ownerMask & (uint)PermissionMask.Copy) == 0)
perms &= ~(uint)PermissionMask.Copy;
if ((ownerMask & (uint)PermissionMask.Transfer) == 0)
perms &= ~(uint)PermissionMask.Transfer;
// If root prim permissions are applied here, this would screw
// with in-inventory manipulation of the next owner perms
// in a major way. So, let's move this to the give itself.
// Yes. I know. Evil.
// if ((ownerMask & RootPart.NextOwnerMask & (uint)PermissionMask.Modify) == 0)
// perms &= ~((uint)PermissionMask.Modify >> 13);
// if ((ownerMask & RootPart.NextOwnerMask & (uint)PermissionMask.Copy) == 0)
// perms &= ~((uint)PermissionMask.Copy >> 13);
// if ((ownerMask & RootPart.NextOwnerMask & (uint)PermissionMask.Transfer) == 0)
// perms &= ~((uint)PermissionMask.Transfer >> 13);
return perms;
}
public void ApplyNextOwnerPermissions()
{
// m_log.DebugFormat("[PRIM INVENTORY]: Applying next owner permissions to {0} {1}", Name, UUID);
SceneObjectPart[] parts = m_parts.GetArray();
for (int i = 0; i < parts.Length; i++)
parts[i].ApplyNextOwnerPermissions();
}
public string GetStateSnapshot()
{
Dictionary<UUID, string> states = new Dictionary<UUID, string>();
SceneObjectPart[] parts = m_parts.GetArray();
for (int i = 0; i < parts.Length; i++)
{
SceneObjectPart part = parts[i];
foreach (KeyValuePair<UUID, string> s in part.Inventory.GetScriptStates())
states[s.Key] = s.Value;
}
if (states.Count < 1)
return String.Empty;
XmlDocument xmldoc = new XmlDocument();
XmlNode xmlnode = xmldoc.CreateNode(XmlNodeType.XmlDeclaration,
String.Empty, String.Empty);
xmldoc.AppendChild(xmlnode);
XmlElement rootElement = xmldoc.CreateElement("", "ScriptData",
String.Empty);
xmldoc.AppendChild(rootElement);
XmlElement wrapper = xmldoc.CreateElement("", "ScriptStates",
String.Empty);
rootElement.AppendChild(wrapper);
foreach (KeyValuePair<UUID, string> state in states)
{
XmlDocument sdoc = new XmlDocument();
sdoc.LoadXml(state.Value);
XmlNodeList rootL = sdoc.GetElementsByTagName("State");
XmlNode rootNode = rootL[0];
XmlNode newNode = xmldoc.ImportNode(rootNode, true);
wrapper.AppendChild(newNode);
}
return xmldoc.InnerXml;
}
public void SetState(string objXMLData, IScene ins)
{
if (!(ins is Scene))
return;
Scene s = (Scene)ins;
if (objXMLData == String.Empty)
return;
IScriptModule scriptModule = null;
foreach (IScriptModule sm in s.RequestModuleInterfaces<IScriptModule>())
{
if (sm.ScriptEngineName == s.DefaultScriptEngine)
scriptModule = sm;
else if (scriptModule == null)
scriptModule = sm;
}
if (scriptModule == null)
return;
XmlDocument doc = new XmlDocument();
try
{
doc.LoadXml(objXMLData);
}
catch (Exception) // (System.Xml.XmlException)
{
// We will get here if the XML is invalid or in unit
// tests. Really should determine which it is and either
// fail silently or log it
// Fail silently, for now.
// TODO: Fix this
//
return;
}
XmlNodeList rootL = doc.GetElementsByTagName("ScriptData");
if (rootL.Count != 1)
return;
XmlElement rootE = (XmlElement)rootL[0];
XmlNodeList dataL = rootE.GetElementsByTagName("ScriptStates");
if (dataL.Count != 1)
return;
XmlElement dataE = (XmlElement)dataL[0];
foreach (XmlNode n in dataE.ChildNodes)
{
XmlElement stateE = (XmlElement)n;
UUID itemID = new UUID(stateE.GetAttribute("UUID"));
scriptModule.SetXMLState(itemID, n.OuterXml);
}
}
public void ResumeScripts()
{
SceneObjectPart[] parts = m_parts.GetArray();
for (int i = 0; i < parts.Length; i++)
parts[i].Inventory.ResumeScripts();
}
/// <summary>
/// Returns true if any part in the scene object contains scripts, false otherwise.
/// </summary>
/// <returns></returns>
public bool ContainsScripts()
{
foreach (SceneObjectPart part in Parts)
if (part.Inventory.ContainsScripts())
return true;
return false;
}
}
}
| |
using System;
using System.ComponentModel;
using System.Drawing;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.Diagnostics.CodeAnalysis;
namespace WeifenLuo.WinFormsUI.Docking
{
public class DockContent : Form, IDockContent
{
public DockContent()
{
m_dockHandler = new DockContentHandler(this, new GetPersistStringCallback(GetPersistString));
m_dockHandler.DockStateChanged += new EventHandler(DockHandler_DockStateChanged);
//Suggested as a fix by bensty regarding form resize
this.ParentChanged += new EventHandler(DockContent_ParentChanged);
this.VisibleChanged += new EventHandler(DockContent_VisibleChanged);
}
//DockContent doc;
void DockContent_VisibleChanged(object sender, EventArgs e)
{
CallUpdateContent();
//if (this.Visible)
// this.UpdateContent(this.DockPanel.ActiveDocument);
}
public virtual void UpdateContent(IDockContent doc)
{
}
public virtual void CallUpdateContent()
{
}
//Suggested as a fix by bensty regarding form resize
private void DockContent_ParentChanged(object Sender, EventArgs e)
{
if (this.Parent != null)
this.Font = this.Parent.Font;
}
private DockContentHandler m_dockHandler = null;
[Browsable(false)]
public DockContentHandler DockHandler
{
get { return m_dockHandler; }
}
[LocalizedCategory("Category_Docking")]
[LocalizedDescription("DockContent_AllowEndUserDocking_Description")]
[DefaultValue(true)]
public bool AllowEndUserDocking
{
get { return DockHandler.AllowEndUserDocking; }
set { DockHandler.AllowEndUserDocking = value; }
}
[LocalizedCategory("Category_Docking")]
[LocalizedDescription("DockContent_DockAreas_Description")]
[DefaultValue(DockAreas.DockLeft|DockAreas.DockRight|DockAreas.DockTop|DockAreas.DockBottom|DockAreas.Document|DockAreas.Float)]
public DockAreas DockAreas
{
get { return DockHandler.DockAreas; }
set { DockHandler.DockAreas = value; }
}
[LocalizedCategory("Category_Docking")]
[LocalizedDescription("DockContent_AutoHidePortion_Description")]
[DefaultValue(0.25)]
public double AutoHidePortion
{
get { return DockHandler.AutoHidePortion; }
set { DockHandler.AutoHidePortion = value; }
}
private string m_tabText = null;
[Localizable(true)]
[LocalizedCategory("Category_Docking")]
[LocalizedDescription("DockContent_TabText_Description")]
[DefaultValue(null)]
public string TabText
{
get { return m_tabText; }
set { DockHandler.TabText = m_tabText = value; }
}
private bool ShouldSerializeTabText()
{
return (m_tabText != null);
}
[LocalizedCategory("Category_Docking")]
[LocalizedDescription("DockContent_CloseButton_Description")]
[DefaultValue(true)]
public bool CloseButton
{
get { return DockHandler.CloseButton; }
set { DockHandler.CloseButton = value; }
}
[LocalizedCategory("Category_Docking")]
[LocalizedDescription("DockContent_CloseButtonVisible_Description")]
[DefaultValue(true)]
public bool CloseButtonVisible
{
get { return DockHandler.CloseButtonVisible; }
set { DockHandler.CloseButtonVisible = value; }
}
[Browsable(false)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public DockPanel DockPanel
{
get { return DockHandler.DockPanel; }
set { DockHandler.DockPanel = value; }
}
[Browsable(false)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public DockState DockState
{
get { return DockHandler.DockState; }
set { DockHandler.DockState = value; }
}
[Browsable(false)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public DockPane Pane
{
get { return DockHandler.Pane; }
set { DockHandler.Pane = value; }
}
[Browsable(false)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public bool IsHidden
{
get { return DockHandler.IsHidden; }
set { DockHandler.IsHidden = value; }
}
[Browsable(false)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public DockState VisibleState
{
get { return DockHandler.VisibleState; }
set { DockHandler.VisibleState = value; }
}
[Browsable(false)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public bool IsFloat
{
get { return DockHandler.IsFloat; }
set { DockHandler.IsFloat = value; }
}
[Browsable(false)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public DockPane PanelPane
{
get { return DockHandler.PanelPane; }
set { DockHandler.PanelPane = value; }
}
[Browsable(false)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public DockPane FloatPane
{
get { return DockHandler.FloatPane; }
set { DockHandler.FloatPane = value; }
}
[SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate")]
protected virtual string GetPersistString()
{
return GetType().ToString();
}
[LocalizedCategory("Category_Docking")]
[LocalizedDescription("DockContent_HideOnClose_Description")]
[DefaultValue(false)]
public bool HideOnClose
{
get { return DockHandler.HideOnClose; }
set { DockHandler.HideOnClose = value; }
}
[LocalizedCategory("Category_Docking")]
[LocalizedDescription("DockContent_ShowHint_Description")]
[DefaultValue(DockState.Unknown)]
public DockState ShowHint
{
get { return DockHandler.ShowHint; }
set { DockHandler.ShowHint = value; }
}
[Browsable(false)]
public bool IsActivated
{
get { return DockHandler.IsActivated; }
}
public bool IsDockStateValid(DockState dockState)
{
return DockHandler.IsDockStateValid(dockState);
}
[LocalizedCategory("Category_Docking")]
[LocalizedDescription("DockContent_TabPageContextMenu_Description")]
[DefaultValue(null)]
public ContextMenu TabPageContextMenu
{
get { return DockHandler.TabPageContextMenu; }
set { DockHandler.TabPageContextMenu = value; }
}
[LocalizedCategory("Category_Docking")]
[LocalizedDescription("DockContent_TabPageContextMenuStrip_Description")]
[DefaultValue(null)]
public ContextMenuStrip TabPageContextMenuStrip
{
get { return DockHandler.TabPageContextMenuStrip; }
set { DockHandler.TabPageContextMenuStrip = value; }
}
[Localizable(true)]
[Category("Appearance")]
[LocalizedDescription("DockContent_ToolTipText_Description")]
[DefaultValue(null)]
public string ToolTipText
{
get { return DockHandler.ToolTipText; }
set { DockHandler.ToolTipText = value; }
}
public new void Activate()
{
DockHandler.Activate();
}
public new void Hide()
{
DockHandler.Hide();
}
public new void Show()
{
DockHandler.Show();
}
public void Show(DockPanel dockPanel)
{
DockHandler.Show(dockPanel);
}
public void Show(DockPanel dockPanel, DockState dockState)
{
DockHandler.Show(dockPanel, dockState);
}
[SuppressMessage("Microsoft.Naming", "CA1720:AvoidTypeNamesInParameters")]
public void Show(DockPanel dockPanel, Rectangle floatWindowBounds)
{
DockHandler.Show(dockPanel, floatWindowBounds);
}
public void Show(DockPane pane, IDockContent beforeContent)
{
DockHandler.Show(pane, beforeContent);
}
public void Show(DockPane previousPane, DockAlignment alignment, double proportion)
{
DockHandler.Show(previousPane, alignment, proportion);
}
[SuppressMessage("Microsoft.Naming", "CA1720:AvoidTypeNamesInParameters")]
public void FloatAt(Rectangle floatWindowBounds)
{
DockHandler.FloatAt(floatWindowBounds);
}
public void DockTo(DockPane paneTo, DockStyle dockStyle, int contentIndex)
{
DockHandler.DockTo(paneTo, dockStyle, contentIndex);
}
public void DockTo(DockPanel panel, DockStyle dockStyle)
{
DockHandler.DockTo(panel, dockStyle);
}
#region IDockContent Members
void IDockContent.OnActivated(EventArgs e)
{
this.OnActivated(e);
}
void IDockContent.OnDeactivate(EventArgs e)
{
this.OnDeactivate(e);
}
#endregion
#region Events
private void DockHandler_DockStateChanged(object sender, EventArgs e)
{
OnDockStateChanged(e);
}
private static readonly object DockStateChangedEvent = new object();
[LocalizedCategory("Category_PropertyChanged")]
[LocalizedDescription("Pane_DockStateChanged_Description")]
public event EventHandler DockStateChanged
{
add { Events.AddHandler(DockStateChangedEvent, value); }
remove { Events.RemoveHandler(DockStateChangedEvent, value); }
}
protected virtual void OnDockStateChanged(EventArgs e)
{
EventHandler handler = (EventHandler)Events[DockStateChangedEvent];
if (handler != null)
handler(this, e);
}
#endregion
/// <summary>
/// Overridden to avoid resize issues with nested controls
/// </summary>
/// <remarks>
/// http://blogs.msdn.com/b/alejacma/archive/2008/11/20/controls-won-t-get-resized-once-the-nesting-hierarchy-of-windows-exceeds-a-certain-depth-x64.aspx
/// http://support.microsoft.com/kb/953934
/// </remarks>
protected override void OnSizeChanged(EventArgs e)
{
if (DockPanel != null && DockPanel.SupportDeeplyNestedContent && IsHandleCreated)
{
BeginInvoke((MethodInvoker)delegate
{
base.OnSizeChanged(e);
});
}
else
{
base.OnSizeChanged(e);
}
}
}
}
| |
// 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.Runtime.CompilerServices;
using System.Runtime.Serialization;
using System.Threading;
using System.Transactions.Distributed;
namespace System.Transactions
{
public class TransactionEventArgs : EventArgs
{
internal Transaction _transaction;
public Transaction Transaction => _transaction;
}
public delegate void TransactionCompletedEventHandler(object sender, TransactionEventArgs e);
public enum IsolationLevel
{
Serializable = 0,
RepeatableRead = 1,
ReadCommitted = 2,
ReadUncommitted = 3,
Snapshot = 4,
Chaos = 5,
Unspecified = 6,
}
public enum TransactionStatus
{
Active = 0,
Committed = 1,
Aborted = 2,
InDoubt = 3
}
public enum DependentCloneOption
{
BlockCommitUntilComplete = 0,
RollbackIfNotComplete = 1,
}
[Flags]
public enum EnlistmentOptions
{
None = 0x0,
EnlistDuringPrepareRequired = 0x1,
}
// When we serialize a Transaction, we specify the type DistributedTransaction, so a Transaction never
// actually gets deserialized.
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2229", Justification = "Serialization not yet supported and will be done using DistributedTransaction")]
public class Transaction : IDisposable, ISerializable
{
// UseServiceDomain
//
// Property tells parts of system.transactions if it should use a
// service domain for current.
[System.Runtime.CompilerServices.MethodImplAttribute(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
internal static bool UseServiceDomainForCurrent() => false;
// InteropMode
//
// This property figures out the current interop mode based on the
// top of the transaction scope stack as well as the default mode
// from config.
internal static EnterpriseServicesInteropOption InteropMode(TransactionScope currentScope)
{
if (currentScope != null)
{
return currentScope.InteropMode;
}
return EnterpriseServicesInteropOption.None;
}
internal static Transaction FastGetTransaction(TransactionScope currentScope, ContextData contextData, out Transaction contextTransaction)
{
Transaction current = null;
contextTransaction = null;
contextTransaction = contextData.CurrentTransaction;
switch (InteropMode(currentScope))
{
case EnterpriseServicesInteropOption.None:
current = contextTransaction;
// If there is a transaction in the execution context or if there is a current transaction scope
// then honer the transaction context.
if (current == null && currentScope == null)
{
// Otherwise check for an external current.
if (TransactionManager.s_currentDelegateSet)
{
current = TransactionManager.s_currentDelegate();
}
else
{
current = EnterpriseServices.GetContextTransaction(contextData);
}
}
break;
case EnterpriseServicesInteropOption.Full:
current = EnterpriseServices.GetContextTransaction(contextData);
break;
case EnterpriseServicesInteropOption.Automatic:
if (EnterpriseServices.UseServiceDomainForCurrent())
{
current = EnterpriseServices.GetContextTransaction(contextData);
}
else
{
current = contextData.CurrentTransaction;
}
break;
}
return current;
}
// GetCurrentTransactionAndScope
//
// Returns both the current transaction and scope. This is implemented for optimizations
// in TransactionScope because it is required to get both of them in several cases.
internal static void GetCurrentTransactionAndScope(
TxLookup defaultLookup,
out Transaction current,
out TransactionScope currentScope,
out Transaction contextTransaction)
{
current = null;
currentScope = null;
contextTransaction = null;
ContextData contextData = ContextData.LookupContextData(defaultLookup);
if (contextData != null)
{
currentScope = contextData.CurrentScope;
current = FastGetTransaction(currentScope, contextData, out contextTransaction);
}
}
public static Transaction Current
{
get
{
TransactionsEtwProvider etwLog = TransactionsEtwProvider.Log;
if (etwLog.IsEnabled())
{
etwLog.MethodEnter(TraceSourceType.TraceSourceBase, "Transaction.get_Current");
}
Transaction current = null;
TransactionScope currentScope = null;
Transaction contextValue = null;
GetCurrentTransactionAndScope(TxLookup.Default, out current, out currentScope, out contextValue);
if (currentScope != null)
{
if (currentScope.ScopeComplete)
{
throw new InvalidOperationException(SR.TransactionScopeComplete);
}
}
if (etwLog.IsEnabled())
{
etwLog.MethodExit(TraceSourceType.TraceSourceBase, "Transaction.get_Current");
}
return current;
}
set
{
TransactionsEtwProvider etwLog = TransactionsEtwProvider.Log;
if (etwLog.IsEnabled())
{
etwLog.MethodEnter(TraceSourceType.TraceSourceBase, "Transaction.set_Current");
}
// Bring your own Transaction(BYOT) is supported only for legacy scenarios.
// This transaction won't be flown across thread continuations.
if (InteropMode(ContextData.TLSCurrentData.CurrentScope) != EnterpriseServicesInteropOption.None)
{
if (etwLog.IsEnabled())
{
etwLog.InvalidOperation("Transaction", "Transaction.set_Current");
}
throw new InvalidOperationException(SR.CannotSetCurrent);
}
// Support only legacy scenarios using TLS.
ContextData.TLSCurrentData.CurrentTransaction = value;
// Clear CallContext data.
CallContextCurrentData.ClearCurrentData(null, false);
if (etwLog.IsEnabled())
{
etwLog.MethodExit(TraceSourceType.TraceSourceBase, "Transaction.set_Current");
}
}
}
// Storage for the transaction isolation level
internal IsolationLevel _isoLevel;
// Storage for the consistent flag
internal bool _complete = false;
// Record an identifier for this clone
internal int _cloneId;
// Storage for a disposed flag
internal const int _disposedTrueValue = 1;
internal int _disposed = 0;
internal bool Disposed { get { return _disposed == Transaction._disposedTrueValue; } }
internal Guid DistributedTxId
{
get
{
Guid returnValue = Guid.Empty;
if (_internalTransaction != null)
{
returnValue = _internalTransaction.DistributedTxId;
}
return returnValue;
}
}
// Internal synchronization object for transactions. It is not safe to lock on the
// transaction object because it is public and users of the object may lock it for
// other purposes.
internal InternalTransaction _internalTransaction;
// The TransactionTraceIdentifier for the transaction instance.
internal TransactionTraceIdentifier _traceIdentifier;
// Not used by anyone
private Transaction() { }
// Create a transaction with the given settings
//
internal Transaction(IsolationLevel isoLevel, InternalTransaction internalTransaction)
{
TransactionManager.ValidateIsolationLevel(isoLevel);
_isoLevel = isoLevel;
// Never create a transaction with an IsolationLevel of Unspecified.
if (IsolationLevel.Unspecified == _isoLevel)
{
_isoLevel = TransactionManager.DefaultIsolationLevel;
}
if (internalTransaction != null)
{
_internalTransaction = internalTransaction;
_cloneId = Interlocked.Increment(ref _internalTransaction._cloneCount);
}
else
{
// Null is passed from the constructor of a CommittableTransaction. That
// constructor will fill in the traceIdentifier because it has allocated the
// internal transaction.
}
}
internal Transaction(DistributedTransaction distributedTransaction)
{
_isoLevel = distributedTransaction.IsolationLevel;
_internalTransaction = new InternalTransaction(this, distributedTransaction);
_cloneId = Interlocked.Increment(ref _internalTransaction._cloneCount);
}
internal Transaction(IsolationLevel isoLevel, ISimpleTransactionSuperior superior)
{
TransactionManager.ValidateIsolationLevel(isoLevel);
if (superior == null)
{
throw new ArgumentNullException(nameof(superior));
}
_isoLevel = isoLevel;
// Never create a transaction with an IsolationLevel of Unspecified.
if (IsolationLevel.Unspecified == _isoLevel)
{
_isoLevel = TransactionManager.DefaultIsolationLevel;
}
_internalTransaction = new InternalTransaction(this, superior);
// ISimpleTransactionSuperior is defined to also promote to MSDTC.
_internalTransaction.SetPromoterTypeToMSDTC();
_cloneId = 1;
}
#region System.Object Overrides
// Don't use the identifier for the hash code.
//
public override int GetHashCode()
{
return _internalTransaction.TransactionHash;
}
// Don't allow equals to get the identifier
//
public override bool Equals(object obj)
{
Transaction transaction = obj as Transaction;
// If we can't cast the object as a Transaction, it must not be equal
// to this, which is a Transaction.
if (null == transaction)
{
return false;
}
// Check the internal transaction object for equality.
return _internalTransaction.TransactionHash == transaction._internalTransaction.TransactionHash;
}
public static bool operator ==(Transaction x, Transaction y)
{
if (((object)x) != null)
{
return x.Equals(y);
}
return ((object)y) == null;
}
public static bool operator !=(Transaction x, Transaction y)
{
if (((object)x) != null)
{
return !x.Equals(y);
}
return ((object)y) != null;
}
#endregion
public TransactionInformation TransactionInformation
{
get
{
TransactionsEtwProvider etwLog = TransactionsEtwProvider.Log;
if (etwLog.IsEnabled())
{
etwLog.MethodEnter(TraceSourceType.TraceSourceLtm, this);
}
if (Disposed)
{
throw new ObjectDisposedException(nameof(Transaction));
}
TransactionInformation txInfo = _internalTransaction._transactionInformation;
if (txInfo == null)
{
// A race would only result in an extra allocation
txInfo = new TransactionInformation(_internalTransaction);
_internalTransaction._transactionInformation = txInfo;
}
if (etwLog.IsEnabled())
{
etwLog.MethodExit(TraceSourceType.TraceSourceLtm, this);
}
return txInfo;
}
}
// Return the Isolation Level for the given transaction
//
public IsolationLevel IsolationLevel
{
get
{
TransactionsEtwProvider etwLog = TransactionsEtwProvider.Log;
if (etwLog.IsEnabled())
{
etwLog.MethodEnter(TraceSourceType.TraceSourceLtm, this);
}
if (Disposed)
{
throw new ObjectDisposedException(nameof(Transaction));
}
if (etwLog.IsEnabled())
{
etwLog.MethodExit(TraceSourceType.TraceSourceLtm, this);
}
return _isoLevel;
}
}
/// <summary>
/// Gets the PromoterType value for the transaction.
/// </summary>
/// <value>
/// If the transaction has not yet been promoted and does not yet have a promotable single phase enlistment,
/// this property value will be Guid.Empty.
///
/// If the transaction has been promoted or has a promotable single phase enlistment, this will return the
/// promoter type specified by the transaction promoter.
///
/// If the transaction is, or will be, promoted to MSDTC, the value will be TransactionInterop.PromoterTypeDtc.
/// </value>
public Guid PromoterType
{
get
{
TransactionsEtwProvider etwLog = TransactionsEtwProvider.Log;
if (etwLog.IsEnabled())
{
etwLog.MethodEnter(TraceSourceType.TraceSourceLtm, this);
}
if (Disposed)
{
throw new ObjectDisposedException(nameof(Transaction));
}
lock (_internalTransaction)
{
return _internalTransaction._promoterType;
}
}
}
/// <summary>
/// Gets the PromotedToken for the transaction.
///
/// If the transaction has not already been promoted, retrieving this value will cause promotion. Before retrieving the
/// PromotedToken, the Transaction.PromoterType value should be checked to see if it is a promoter type (Guid) that the
/// caller understands. If the caller does not recognize the PromoterType value, retreiving the PromotedToken doesn't
/// have much value because the caller doesn't know how to utilize it. But if the PromoterType is recognized, the
/// caller should know how to utilize the PromotedToken to communicate with the promoting distributed transaction
/// coordinator to enlist on the distributed transaction.
///
/// If the value of a transaction's PromoterType is TransactionInterop.PromoterTypeDtc, then that transaction's
/// PromotedToken will be an MSDTC-based TransmitterPropagationToken.
/// </summary>
/// <returns>
/// The byte[] that can be used to enlist with the distributed transaction coordinator used to promote the transaction.
/// The format of the byte[] depends upon the value of Transaction.PromoterType.
/// </returns>
public byte[] GetPromotedToken()
{
// We need to ask the current transaction state for the PromotedToken because depending on the state
// we may need to induce a promotion.
TransactionsEtwProvider etwLog = TransactionsEtwProvider.Log;
if (etwLog.IsEnabled())
{
etwLog.MethodEnter(TraceSourceType.TraceSourceLtm, this);
}
if (Disposed)
{
throw new ObjectDisposedException(nameof(Transaction));
}
// We always make a copy of the promotedToken stored in the internal transaction.
byte[] internalPromotedToken;
lock (_internalTransaction)
{
internalPromotedToken = _internalTransaction.State.PromotedToken(_internalTransaction);
}
byte[] toReturn = new byte[internalPromotedToken.Length];
Array.Copy(internalPromotedToken, toReturn, toReturn.Length);
return toReturn;
}
public Enlistment EnlistDurable(
Guid resourceManagerIdentifier,
IEnlistmentNotification enlistmentNotification,
EnlistmentOptions enlistmentOptions)
{
TransactionsEtwProvider etwLog = TransactionsEtwProvider.Log;
if (etwLog.IsEnabled())
{
etwLog.MethodEnter(TraceSourceType.TraceSourceLtm, this);
}
if (Disposed)
{
throw new ObjectDisposedException(nameof(Transaction));
}
if (resourceManagerIdentifier == Guid.Empty)
{
throw new ArgumentException(SR.BadResourceManagerId, nameof(resourceManagerIdentifier));
}
if (enlistmentNotification == null)
{
throw new ArgumentNullException(nameof(enlistmentNotification));
}
if (enlistmentOptions != EnlistmentOptions.None && enlistmentOptions != EnlistmentOptions.EnlistDuringPrepareRequired)
{
throw new ArgumentOutOfRangeException(nameof(enlistmentOptions));
}
if (_complete)
{
throw TransactionException.CreateTransactionCompletedException(DistributedTxId);
}
lock (_internalTransaction)
{
Enlistment enlistment = _internalTransaction.State.EnlistDurable(_internalTransaction,
resourceManagerIdentifier, enlistmentNotification, enlistmentOptions, this);
if (etwLog.IsEnabled())
{
etwLog.MethodExit(TraceSourceType.TraceSourceLtm, this);
}
return enlistment;
}
}
// Forward request to the state machine to take the appropriate action.
//
public Enlistment EnlistDurable(
Guid resourceManagerIdentifier,
ISinglePhaseNotification singlePhaseNotification,
EnlistmentOptions enlistmentOptions)
{
TransactionsEtwProvider etwLog = TransactionsEtwProvider.Log;
if (etwLog.IsEnabled())
{
etwLog.MethodEnter(TraceSourceType.TraceSourceLtm, this);
}
if (Disposed)
{
throw new ObjectDisposedException(nameof(Transaction));
}
if (resourceManagerIdentifier == Guid.Empty)
{
throw new ArgumentException(SR.BadResourceManagerId, nameof(resourceManagerIdentifier));
}
if (singlePhaseNotification == null)
{
throw new ArgumentNullException(nameof(singlePhaseNotification));
}
if (enlistmentOptions != EnlistmentOptions.None && enlistmentOptions != EnlistmentOptions.EnlistDuringPrepareRequired)
{
throw new ArgumentOutOfRangeException(nameof(enlistmentOptions));
}
if (_complete)
{
throw TransactionException.CreateTransactionCompletedException(DistributedTxId);
}
lock (_internalTransaction)
{
Enlistment enlistment = _internalTransaction.State.EnlistDurable(_internalTransaction,
resourceManagerIdentifier, singlePhaseNotification, enlistmentOptions, this);
if (etwLog.IsEnabled())
{
etwLog.MethodExit(TraceSourceType.TraceSourceLtm, this);
}
return enlistment;
}
}
public void Rollback()
{
TransactionsEtwProvider etwLog = TransactionsEtwProvider.Log;
if (etwLog.IsEnabled())
{
etwLog.MethodEnter(TraceSourceType.TraceSourceLtm, this);
etwLog.TransactionRollback(this, "Transaction");
}
if (Disposed)
{
throw new ObjectDisposedException(nameof(Transaction));
}
lock (_internalTransaction)
{
Debug.Assert(_internalTransaction.State != null);
_internalTransaction.State.Rollback(_internalTransaction, null);
}
if (etwLog.IsEnabled())
{
etwLog.MethodExit(TraceSourceType.TraceSourceLtm, this);
}
}
public void Rollback(Exception e)
{
TransactionsEtwProvider etwLog = TransactionsEtwProvider.Log;
if (etwLog.IsEnabled())
{
etwLog.MethodEnter(TraceSourceType.TraceSourceLtm, this);
etwLog.TransactionRollback(this, "Transaction");
}
if (Disposed)
{
throw new ObjectDisposedException(nameof(Transaction));
}
lock (_internalTransaction)
{
Debug.Assert(_internalTransaction.State != null);
_internalTransaction.State.Rollback(_internalTransaction, e);
}
if (etwLog.IsEnabled())
{
etwLog.MethodExit(TraceSourceType.TraceSourceLtm, this);
}
}
// Forward request to the state machine to take the appropriate action.
//
public Enlistment EnlistVolatile(IEnlistmentNotification enlistmentNotification, EnlistmentOptions enlistmentOptions)
{
TransactionsEtwProvider etwLog = TransactionsEtwProvider.Log;
if (etwLog.IsEnabled())
{
etwLog.MethodEnter(TraceSourceType.TraceSourceLtm, this);
}
if (Disposed)
{
throw new ObjectDisposedException(nameof(Transaction));
}
if (enlistmentNotification == null)
{
throw new ArgumentNullException(nameof(enlistmentNotification));
}
if (enlistmentOptions != EnlistmentOptions.None && enlistmentOptions != EnlistmentOptions.EnlistDuringPrepareRequired)
{
throw new ArgumentOutOfRangeException(nameof(enlistmentOptions));
}
if (_complete)
{
throw TransactionException.CreateTransactionCompletedException(DistributedTxId);
}
lock (_internalTransaction)
{
Enlistment enlistment = _internalTransaction.State.EnlistVolatile(_internalTransaction,
enlistmentNotification, enlistmentOptions, this);
if (etwLog.IsEnabled())
{
etwLog.MethodExit(TraceSourceType.TraceSourceLtm, this);
}
return enlistment;
}
}
// Forward request to the state machine to take the appropriate action.
//
public Enlistment EnlistVolatile(ISinglePhaseNotification singlePhaseNotification, EnlistmentOptions enlistmentOptions)
{
TransactionsEtwProvider etwLog = TransactionsEtwProvider.Log;
if (etwLog.IsEnabled())
{
etwLog.MethodEnter(TraceSourceType.TraceSourceLtm, this);
}
if (Disposed)
{
throw new ObjectDisposedException(nameof(Transaction));
}
if (singlePhaseNotification == null)
{
throw new ArgumentNullException(nameof(singlePhaseNotification));
}
if (enlistmentOptions != EnlistmentOptions.None && enlistmentOptions != EnlistmentOptions.EnlistDuringPrepareRequired)
{
throw new ArgumentOutOfRangeException(nameof(enlistmentOptions));
}
if (_complete)
{
throw TransactionException.CreateTransactionCompletedException(DistributedTxId);
}
lock (_internalTransaction)
{
Enlistment enlistment = _internalTransaction.State.EnlistVolatile(_internalTransaction,
singlePhaseNotification, enlistmentOptions, this);
if (etwLog.IsEnabled())
{
etwLog.MethodExit(TraceSourceType.TraceSourceLtm, this);
}
return enlistment;
}
}
// Create a clone of the transaction that forwards requests to this object.
//
public Transaction Clone()
{
TransactionsEtwProvider etwLog = TransactionsEtwProvider.Log;
if (etwLog.IsEnabled())
{
etwLog.MethodEnter(TraceSourceType.TraceSourceLtm, this);
}
if (Disposed)
{
throw new ObjectDisposedException(nameof(Transaction));
}
if (_complete)
{
throw TransactionException.CreateTransactionCompletedException(DistributedTxId);
}
Transaction clone = InternalClone();
if (etwLog.IsEnabled())
{
etwLog.MethodExit(TraceSourceType.TraceSourceLtm, this);
}
return clone;
}
internal Transaction InternalClone()
{
Transaction clone = new Transaction(_isoLevel, _internalTransaction);
TransactionsEtwProvider etwLog = TransactionsEtwProvider.Log;
if (etwLog.IsEnabled())
{
etwLog.TransactionCloneCreate(clone, "Transaction");
}
return clone;
}
// Create a dependent clone of the transaction that forwards requests to this object.
//
public DependentTransaction DependentClone(
DependentCloneOption cloneOption
)
{
TransactionsEtwProvider etwLog = TransactionsEtwProvider.Log;
if (etwLog.IsEnabled())
{
etwLog.MethodEnter(TraceSourceType.TraceSourceLtm, this);
}
if (cloneOption != DependentCloneOption.BlockCommitUntilComplete
&& cloneOption != DependentCloneOption.RollbackIfNotComplete)
{
throw new ArgumentOutOfRangeException(nameof(cloneOption));
}
if (Disposed)
{
throw new ObjectDisposedException(nameof(Transaction));
}
if (_complete)
{
throw TransactionException.CreateTransactionCompletedException(DistributedTxId);
}
DependentTransaction clone = new DependentTransaction(
_isoLevel, _internalTransaction, cloneOption == DependentCloneOption.BlockCommitUntilComplete);
if (etwLog.IsEnabled())
{
etwLog.TransactionCloneCreate(clone, "DependentTransaction");
etwLog.MethodExit(TraceSourceType.TraceSourceLtm, this);
}
return clone;
}
internal TransactionTraceIdentifier TransactionTraceId
{
get
{
if (_traceIdentifier == TransactionTraceIdentifier.Empty)
{
lock (_internalTransaction)
{
if (_traceIdentifier == TransactionTraceIdentifier.Empty)
{
TransactionTraceIdentifier temp = new TransactionTraceIdentifier(
_internalTransaction.TransactionTraceId.TransactionIdentifier,
_cloneId);
Interlocked.MemoryBarrier();
_traceIdentifier = temp;
}
}
}
return _traceIdentifier;
}
}
// Forward request to the state machine to take the appropriate action.
//
public event TransactionCompletedEventHandler TransactionCompleted
{
add
{
if (Disposed)
{
throw new ObjectDisposedException(nameof(Transaction));
}
lock (_internalTransaction)
{
// Register for completion with the inner transaction
_internalTransaction.State.AddOutcomeRegistrant(_internalTransaction, value);
}
}
remove
{
lock (_internalTransaction)
{
_internalTransaction._transactionCompletedDelegate = (TransactionCompletedEventHandler)
System.Delegate.Remove(_internalTransaction._transactionCompletedDelegate, value);
}
}
}
public void Dispose()
{
InternalDispose();
}
// Handle Transaction Disposal.
//
internal virtual void InternalDispose()
{
TransactionsEtwProvider etwLog = TransactionsEtwProvider.Log;
if (etwLog.IsEnabled())
{
etwLog.MethodEnter(TraceSourceType.TraceSourceLtm, this);
}
if (Interlocked.Exchange(ref _disposed, Transaction._disposedTrueValue) == Transaction._disposedTrueValue)
{
return;
}
// Attempt to clean up the internal transaction
long remainingITx = Interlocked.Decrement(ref _internalTransaction._cloneCount);
if (remainingITx == 0)
{
_internalTransaction.Dispose();
}
if (etwLog.IsEnabled())
{
etwLog.MethodExit(TraceSourceType.TraceSourceLtm, this);
}
}
// Ask the state machine for serialization info.
//
void ISerializable.GetObjectData(
SerializationInfo serializationInfo,
StreamingContext context)
{
TransactionsEtwProvider etwLog = TransactionsEtwProvider.Log;
if (etwLog.IsEnabled())
{
etwLog.MethodEnter(TraceSourceType.TraceSourceLtm, this);
}
if (Disposed)
{
throw new ObjectDisposedException(nameof(Transaction));
}
if (serializationInfo == null)
{
throw new ArgumentNullException(nameof(serializationInfo));
}
if (_complete)
{
throw TransactionException.CreateTransactionCompletedException(DistributedTxId);
}
lock (_internalTransaction)
{
_internalTransaction.State.GetObjectData(_internalTransaction, serializationInfo, context);
}
if (etwLog.IsEnabled())
{
etwLog.TransactionSerialized(this, "Transaction");
etwLog.MethodExit(TraceSourceType.TraceSourceLtm, this);
}
}
/// <summary>
/// Create a promotable single phase enlistment that promotes to MSDTC.
/// </summary>
/// <param name="promotableSinglePhaseNotification">The object that implements the IPromotableSinglePhaseNotification interface.</param>
/// <returns>
/// True if the enlistment is successful.
///
/// False if the transaction already has a durable enlistment or promotable single phase enlistment or
/// if the transaction has already promoted. In this case, the caller will need to enlist in the transaction through other
/// means, such as Transaction.EnlistDurable or retreive the MSDTC export cookie or propagation token to enlist with MSDTC.
/// </returns>
// We apparently didn't spell Promotable like FXCop thinks it should be spelled.
public bool EnlistPromotableSinglePhase(IPromotableSinglePhaseNotification promotableSinglePhaseNotification)
{
return EnlistPromotableSinglePhase(promotableSinglePhaseNotification, TransactionInterop.PromoterTypeDtc);
}
/// <summary>
/// Create a promotable single phase enlistment that promotes to a distributed transaction manager other than MSDTC.
/// </summary>
/// <param name="promotableSinglePhaseNotification">The object that implements the IPromotableSinglePhaseNotification interface.</param>
/// <param name="promoterType">
/// The promoter type Guid that identifies the format of the byte[] that is returned by the ITransactionPromoter.Promote
/// call that is implemented by the IPromotableSinglePhaseNotificationObject, and thus the promoter of the transaction.
/// </param>
/// <returns>
/// True if the enlistment is successful.
///
/// False if the transaction already has a durable enlistment or promotable single phase enlistment or
/// if the transaction has already promoted. In this case, the caller will need to enlist in the transaction through other
/// means.
///
/// If the Transaction.PromoterType matches the promoter type supported by the caller, then the
/// Transaction.PromotedToken can be retrieved and used to enlist directly with the identified distributed transaction manager.
///
/// How the enlistment is created with the distributed transaction manager identified by the Transaction.PromoterType
/// is defined by that distributed transaction manager.
/// </returns>
public bool EnlistPromotableSinglePhase(IPromotableSinglePhaseNotification promotableSinglePhaseNotification, Guid promoterType)
{
TransactionsEtwProvider etwLog = TransactionsEtwProvider.Log;
if (etwLog.IsEnabled())
{
etwLog.MethodEnter(TraceSourceType.TraceSourceLtm, this);
}
if (Disposed)
{
throw new ObjectDisposedException(nameof(Transaction));
}
if (promotableSinglePhaseNotification == null)
{
throw new ArgumentNullException(nameof(promotableSinglePhaseNotification));
}
if (promoterType == Guid.Empty)
{
throw new ArgumentException(SR.PromoterTypeInvalid, nameof(promoterType));
}
if (_complete)
{
throw TransactionException.CreateTransactionCompletedException(DistributedTxId);
}
bool succeeded = false;
lock (_internalTransaction)
{
succeeded = _internalTransaction.State.EnlistPromotableSinglePhase(_internalTransaction, promotableSinglePhaseNotification, this, promoterType);
}
if (etwLog.IsEnabled())
{
etwLog.MethodExit(TraceSourceType.TraceSourceLtm, this);
}
return succeeded;
}
public Enlistment PromoteAndEnlistDurable(Guid resourceManagerIdentifier,
IPromotableSinglePhaseNotification promotableNotification,
ISinglePhaseNotification enlistmentNotification,
EnlistmentOptions enlistmentOptions)
{
TransactionsEtwProvider etwLog = TransactionsEtwProvider.Log;
if (etwLog.IsEnabled())
{
etwLog.MethodEnter(TraceSourceType.TraceSourceDistributed, this);
}
if (Disposed)
{
throw new ObjectDisposedException(nameof(Transaction));
}
if (resourceManagerIdentifier == Guid.Empty)
{
throw new ArgumentException(SR.BadResourceManagerId, nameof(resourceManagerIdentifier));
}
if (promotableNotification == null)
{
throw new ArgumentNullException(nameof(promotableNotification));
}
if (enlistmentNotification == null)
{
throw new ArgumentNullException(nameof(enlistmentNotification));
}
if (enlistmentOptions != EnlistmentOptions.None && enlistmentOptions != EnlistmentOptions.EnlistDuringPrepareRequired)
{
throw new ArgumentOutOfRangeException(nameof(enlistmentOptions));
}
if (_complete)
{
throw TransactionException.CreateTransactionCompletedException(DistributedTxId);
}
lock (_internalTransaction)
{
Enlistment enlistment = _internalTransaction.State.PromoteAndEnlistDurable(_internalTransaction,
resourceManagerIdentifier, promotableNotification, enlistmentNotification, enlistmentOptions, this);
if (etwLog.IsEnabled())
{
etwLog.MethodExit(TraceSourceType.TraceSourceDistributed, this);
}
return enlistment;
}
}
public void SetDistributedTransactionIdentifier(IPromotableSinglePhaseNotification promotableNotification,
Guid distributedTransactionIdentifier)
{
TransactionsEtwProvider etwLog = TransactionsEtwProvider.Log;
if (etwLog.IsEnabled())
{
etwLog.MethodEnter(TraceSourceType.TraceSourceLtm, this);
}
if (Disposed)
{
throw new ObjectDisposedException(nameof(Transaction));
}
if (promotableNotification == null)
{
throw new ArgumentNullException(nameof(promotableNotification));
}
if (distributedTransactionIdentifier == Guid.Empty)
{
throw new ArgumentException(null, nameof(distributedTransactionIdentifier));
}
if (_complete)
{
throw TransactionException.CreateTransactionCompletedException(DistributedTxId);
}
lock (_internalTransaction)
{
_internalTransaction.State.SetDistributedTransactionId(_internalTransaction,
promotableNotification,
distributedTransactionIdentifier);
if (etwLog.IsEnabled())
{
etwLog.MethodExit(TraceSourceType.TraceSourceLtm, this);
}
return;
}
}
internal DistributedTransaction Promote()
{
lock (_internalTransaction)
{
// This method is only called when we expect to be promoting to MSDTC.
_internalTransaction.ThrowIfPromoterTypeIsNotMSDTC();
_internalTransaction.State.Promote(_internalTransaction);
return _internalTransaction.PromotedTransaction;
}
}
}
//
// The following code & data is related to management of Transaction.Current
//
internal enum DefaultComContextState
{
Unknown = 0,
Unavailable = -1,
Available = 1
}
//
// The TxLookup enum is used internally to detect where the ambient context needs to be stored or looked up.
// Default - Used internally when looking up Transaction.Current.
// DefaultCallContext - Used when TransactionScope with async flow option is enabled. Internally we will use CallContext to store the ambient transaction.
// Default TLS - Used for legacy/syncronous TransactionScope. Internally we will use TLS to store the ambient transaction.
//
internal enum TxLookup
{
Default,
DefaultCallContext,
DefaultTLS,
}
//
// CallContextCurrentData holds the ambient transaction and uses CallContext and ConditionalWeakTable to track the ambient transaction.
// For async flow scenarios, we should not allow flowing of transaction across app domains. To prevent transaction from flowing across
// AppDomain/Remoting boundaries, we are using ConditionalWeakTable to hold the actual ambient transaction and store only a object reference
// in CallContext. When TransactionScope is used to invoke a call across AppDomain/Remoting boundaries, only the object reference will be sent
// across and not the actaul ambient transaction which is stashed away in the ConditionalWeakTable.
//
internal static class CallContextCurrentData
{
private static AsyncLocal<ContextKey> s_currentTransaction = new AsyncLocal<ContextKey>();
// ConditionalWeakTable is used to automatically remove the entries that are no longer referenced. This will help prevent leaks in async nested TransactionScope
// usage and when child nested scopes are not syncronized properly.
private static readonly ConditionalWeakTable<ContextKey, ContextData> s_contextDataTable = new ConditionalWeakTable<ContextKey, ContextData>();
//
// Set CallContext data with the given contextKey.
// return the ContextData if already present in contextDataTable, otherwise return the default value.
//
public static ContextData CreateOrGetCurrentData(ContextKey contextKey)
{
s_currentTransaction.Value = contextKey;
return s_contextDataTable.GetValue(contextKey, (env) => new ContextData(true));
}
public static void ClearCurrentData(ContextKey contextKey, bool removeContextData)
{
// Get the current ambient CallContext.
ContextKey key = s_currentTransaction.Value;
if (contextKey != null || key != null)
{
// removeContextData flag is used for perf optimization to avoid removing from the table in certain nested TransactionScope usage.
if (removeContextData)
{
// if context key is passed in remove that from the contextDataTable, otherwise remove the default context key.
s_contextDataTable.Remove(contextKey ?? key);
}
if (key != null)
{
s_currentTransaction.Value = null;
}
}
}
public static bool TryGetCurrentData(out ContextData currentData)
{
currentData = null;
ContextKey contextKey = s_currentTransaction.Value;
if (contextKey == null)
{
return false;
}
else
{
return s_contextDataTable.TryGetValue(contextKey, out currentData);
}
}
}
//
// MarshalByRefObject is needed for cross AppDomain scenarios where just using object will end up with a different reference when call is made across serialization boundary.
//
internal class ContextKey // : MarshalByRefObject
{
}
internal class ContextData
{
internal TransactionScope CurrentScope;
internal Transaction CurrentTransaction;
internal DefaultComContextState DefaultComContextState;
internal WeakReference WeakDefaultComContext;
internal bool _asyncFlow;
[ThreadStatic]
private static ContextData s_staticData;
internal ContextData(bool asyncFlow)
{
_asyncFlow = asyncFlow;
}
internal static ContextData TLSCurrentData
{
get
{
ContextData data = s_staticData;
if (data == null)
{
data = new ContextData(false);
s_staticData = data;
}
return data;
}
set
{
if (value == null && s_staticData != null)
{
// set each property to null to retain one TLS ContextData copy.
s_staticData.CurrentScope = null;
s_staticData.CurrentTransaction = null;
s_staticData.DefaultComContextState = DefaultComContextState.Unknown;
s_staticData.WeakDefaultComContext = null;
}
else
{
s_staticData = value;
}
}
}
internal static ContextData LookupContextData(TxLookup defaultLookup)
{
ContextData currentData = null;
if (CallContextCurrentData.TryGetCurrentData(out currentData))
{
if (currentData.CurrentScope == null && currentData.CurrentTransaction == null && defaultLookup != TxLookup.DefaultCallContext)
{
// Clear Call Context Data
CallContextCurrentData.ClearCurrentData(null, true);
return TLSCurrentData;
}
return currentData;
}
else
{
return TLSCurrentData;
}
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.IO;
using NUnit.Framework;
using Microsoft.Build.BuildEngine;
using System.Threading;
using System.Collections;
namespace Microsoft.Build.UnitTests
{
/*
* Class: OnErrorHandling
* Owner: jomof
*
* Tests that exercise the <OnError> tag.
*/
[TestFixture]
sealed public class OnErrorHandling
{
/*
* Method: Basic
* Owner: jomof
*
* Construct a simple OnError tag.
*/
[Test]
public void Basic()
{
MockLogger l = new MockLogger();
Project p = ObjectModelHelpers.CreateInMemoryProject(@"
<Project DefaultTargets=`Build` ToolsVersion=`msbuilddefaulttoolsversion` xmlns=`msbuildnamespace`>
<Target Name='CleanUp'>
<Message Text='CleanUp-was-called.'/>
</Target>
<Target Name='Build'>
<Error Text='This is an error.'/>
<OnError ExecuteTargets='CleanUp'/>
</Target>
</Project>",
l
);
p.Build(new string [] {"Build"}, null);
Assertion.Assert("Expected one error because 'Build' failed.", l.ErrorCount==1);
Assertion.Assert("The CleanUp target should have been called.", (l.FullLog.IndexOf("CleanUp-was-called") != -1));
}
/// <summary>
/// Target items and properties should be published to the project level even when a task that
/// outputs them fails. (Of course the task must have populated its property before it errors.)
/// Then these items and properties should be visible to the onerror targets.
/// </summary>
[Test]
public void FailingTaskStillPublishesOutputs()
{
MockLogger l = new MockLogger();
string resx = Path.Combine(Path.GetTempPath(), "FailingTaskStillPublishesOutputs.resx");
try
{
File.WriteAllText(resx, @"
<root>
<resheader name=""resmimetype"">
<value>text/microsoft-resx</value>
</resheader>
<resheader name=""version"">
<value>2.0</value>
</resheader>
<resheader name=""reader"">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name=""writer"">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<data name=""a"">
<value>aa</value>
</data>
<data name=""b"">
<value>bb</value>
</data>
</root>");
Project p = ObjectModelHelpers.CreateInMemoryProject(@"
<Project DefaultTargets=`Build` ToolsVersion=`msbuilddefaulttoolsversion` xmlns=`msbuildnamespace`>
<Target Name='Build'>
<GenerateResource
Sources='" + resx + @"'
ExecuteAsTool='false'
StronglyTypedLanguage='!@:|'>
<Output TaskParameter='FilesWritten' ItemName='FilesWrittenItem'/>
<Output TaskParameter='FilesWritten' PropertyName='FilesWrittenProperty'/>
</GenerateResource>
<OnError ExecuteTargets='ErrorTarget'/>
</Target>
<Target Name='ErrorTarget'>
<Message Text='[@(fileswrittenitem)]'/>
<Message Text='[$(fileswrittenproperty)]'/>
</Target>
</Project>",
l
);
p.Build(new string[] { "Build" }, null);
string resource = Path.ChangeExtension(resx, ".resources");
Assertion.Assert("Expected one error because 'Build' failed.", l.ErrorCount >= 1);
l.AssertLogContains("[" + resource + "]", "[" + resource + "]");
// And outputs are visible at the project level
Assertion.AssertEquals(resource, p.GetEvaluatedItemsByName("FilesWrittenItem")[0].FinalItemSpec);
Assertion.AssertEquals(resource, p.GetEvaluatedProperty("FilesWrittenProperty"));
p.ResetBuildStatus();
// But are gone after resetting of course
Assertion.AssertEquals(0, p.GetEvaluatedItemsByName("FilesWrittenItem").Count);
Assertion.AssertEquals(null, p.GetEvaluatedProperty("FilesWrittenProperty"));
}
finally
{
File.Delete(resx);
}
}
/// <summary>
/// Target items and properties should be published to the project level when an OnError
/// target runs, and those items and properties should be visible to the OnError targets.
/// </summary>
[Test]
public void OnErrorSeesPropertiesAndItemsFromFirstTarget()
{
MockLogger l = new MockLogger();
Project p = ObjectModelHelpers.CreateInMemoryProject(@"
<Project DefaultTargets=`Build` ToolsVersion=`msbuilddefaulttoolsversion` xmlns=`msbuildnamespace`>
<Target Name='Build'>
<!-- Create a bunch of items and properties -->
<CreateItem Include='a1'>
<Output ItemName='i1' TaskParameter='Include'/>
</CreateItem>
<ItemGroup>
<i1 Include='a2'/>
</ItemGroup>
<CreateProperty Value='v1'>
<Output PropertyName='p1' TaskParameter='Value'/>
</CreateProperty>
<PropertyGroup>
<p2>v2</p2>
</PropertyGroup>
<Error Text='This is an error.'/>
<OnError ExecuteTargets='ErrorTarget'/>
</Target>
<Target Name='ErrorTarget'>
<Message Text='[@(i1)][$(p1)][$(p2)]'/>
</Target>
</Project>",
l
);
p.Build(new string[] { "Build" }, null);
Assertion.Assert("Expected one error because 'Build' failed.", l.ErrorCount == 1);
l.AssertLogContains("[a1;a2][v1][v2]");
}
/*
* Method: TwoExecuteTargets
* Owner: jomof
*
* Make sure two execute targets can be called.
*/
[Test]
public void TwoExecuteTargets()
{
MockLogger l = new MockLogger();
Project p = ObjectModelHelpers.CreateInMemoryProject(@"
<Project DefaultTargets=`Build` ToolsVersion=`msbuilddefaulttoolsversion` xmlns=`msbuildnamespace`>
<Target Name='CleanUp'>
<Message Text='CleanUp-was-called.'/>
</Target>
<Target Name='CleanUp2'>
<Message Text='CleanUp2-was-called.'/>
</Target>
<Target Name='Build'>
<Error Text='This is an error.'/>
<OnError ExecuteTargets='CleanUp;CleanUp2'/>
</Target>
</Project>",
l
);
p.Build(new string [] {"Build"}, null);
Assertion.Assert("Expected one error because 'Build' failed.", l.ErrorCount==1);
Assertion.Assert("The CleanUp target should have been called.", (l.FullLog.IndexOf("CleanUp-was-called") != -1));
Assertion.Assert("The CleanUp2 target should have been called.", (l.FullLog.IndexOf("CleanUp2-was-called") != -1));
}
/*
* Method: TwoOnErrorClauses
* Owner: jomof
*
* Make sure two OnError clauses can be used.
*/
[Test]
public void TwoOnErrorClauses()
{
MockLogger l = new MockLogger();
Project p = ObjectModelHelpers.CreateInMemoryProject(@"
<Project DefaultTargets=`Build` ToolsVersion=`msbuilddefaulttoolsversion` xmlns=`msbuildnamespace`>
<Target Name='CleanUp'>
<Message Text='CleanUp-was-called.'/>
</Target>
<Target Name='CleanUp2'>
<Message Text='CleanUp2-was-called.'/>
</Target>
<Target Name='Build'>
<Error Text='This is an error.'/>
<OnError ExecuteTargets='CleanUp'/>
<OnError ExecuteTargets='CleanUp2'/>
</Target>
</Project>",
l
);
p.Build(new string [] {"Build"}, null);
Assertion.Assert("Expected one error because 'Build' failed.", l.ErrorCount==1);
Assertion.Assert("The CleanUp target should have been called.", (l.FullLog.IndexOf("CleanUp-was-called") != -1));
Assertion.Assert("The CleanUp2 target should have been called.", (l.FullLog.IndexOf("CleanUp2-was-called") != -1));
}
/*
* Method: DependentTarget
* Owner: jomof
*
* Make sure that a target that is a dependent of a target called because of an
* OnError clause is called
*/
[Test]
public void DependentTarget()
{
MockLogger l = new MockLogger();
Project p = ObjectModelHelpers.CreateInMemoryProject(@"
<Project DefaultTargets=`Build` ToolsVersion=`msbuilddefaulttoolsversion` xmlns=`msbuildnamespace`>
<Target Name='CleanUp' DependsOnTargets='CleanUp2'>
<Message Text='CleanUp-was-called.'/>
</Target>
<Target Name='CleanUp2'>
<Message Text='CleanUp2-was-called.'/>
</Target>
<Target Name='Build'>
<Error Text='This is an error.'/>
<OnError ExecuteTargets='CleanUp'/>
</Target>
</Project>",
l
);
p.Build(new string [] {"Build"}, null);
Assertion.Assert("Expected one error because 'Build' failed.", l.ErrorCount==1);
Assertion.Assert("The CleanUp target should have been called.", (l.FullLog.IndexOf("CleanUp-was-called") != -1));
Assertion.Assert("The CleanUp2 target should have been called.", (l.FullLog.IndexOf("CleanUp2-was-called") != -1));
}
/*
* Method: ErrorInChildIsHandledInParent
* Owner: jomof
*
* If a target is dependent on a child target and that child target errors,
* then the parent's OnError clauses should fire.
*/
[Test]
public void ErrorInChildIsHandledInParent()
{
MockLogger l = new MockLogger();
Project p = ObjectModelHelpers.CreateInMemoryProject(@"
<Project DefaultTargets=`Build` ToolsVersion=`msbuilddefaulttoolsversion` xmlns=`msbuildnamespace`>
<Target Name='CleanUp'>
<Message Text='CleanUp-was-called.'/>
</Target>
<Target Name='BuildStep1'>
<Error Text='Error-in-build-step-1.'/>
</Target>
<Target Name='Build' DependsOnTargets='BuildStep1'>
<OnError ExecuteTargets='CleanUp'/>
</Target>
</Project>",
l
);
p.Build(new string [] {"Build"}, null);
Assertion.Assert("Expected one error because 'BuildStep1' failed.", l.ErrorCount==1);
Assertion.Assert("The CleanUp target should have been called.", (l.FullLog.IndexOf("CleanUp-was-called") != -1));
Assertion.Assert("The BuildStep1 target should have been called.", (l.FullLog.IndexOf("Error-in-build-step-1") != -1));
}
/*
* Method: NonExistentExecuteTarget
* Owner: jomof
*
* Construct a simple OnError tag.
*/
[Test]
public void NonExistentExecuteTarget()
{
MockLogger l = new MockLogger();
Project p = ObjectModelHelpers.CreateInMemoryProject(@"
<Project DefaultTargets=`Build` ToolsVersion=`msbuilddefaulttoolsversion` xmlns=`msbuildnamespace`>
<Target Name='Build'>
<Error Text='This is an error.'/>
<OnError ExecuteTargets='CleanUp'/>
</Target>
</Project>",
l
);
p.Build(new string [] {"Build"}, null);
Assertion.Assert("Expected at least one error because 'Build' failed and one error because 'CleanUp' didn't exist.", l.ErrorCount==2);
Assertion.Assert("The CleanUp target should not have been called.", (l.FullLog.IndexOf("CleanUp-was-called") == -1));
}
/*
* Method: TrueCondition
* Owner: jomof
*
* Test the case when the result of the condition is 'true'
*/
[Test]
public void TrueCondition()
{
MockLogger l = new MockLogger();
Project p = ObjectModelHelpers.CreateInMemoryProject(@"
<Project DefaultTargets=`Build` ToolsVersion=`msbuilddefaulttoolsversion` xmlns=`msbuildnamespace`>
<Target Name='CleanUp'>
<Message Text='CleanUp-was-called.'/>
</Target>
<Target Name='Build'>
<Error Text='This is an error.'/>
<OnError Condition=`'A'!='B'` ExecuteTargets='CleanUp'/>
</Target>
</Project>",
l
);
p.Build(new string [] {"Build"}, null);
Assertion.Assert("Expected one error because 'Build' failed.", l.ErrorCount == 1);
Assertion.Assert("The CleanUp target should have been called.", (l.FullLog.IndexOf("CleanUp-was-called") != -1));
}
/*
* Method: FalseCondition
* Owner: jomof
*
* Test the case when the result of the condition is 'false'
*/
[Test]
public void FalseCondition()
{
MockLogger l = new MockLogger();
Project p = ObjectModelHelpers.CreateInMemoryProject(@"
<Project DefaultTargets=`Build` ToolsVersion=`msbuilddefaulttoolsversion` xmlns=`msbuildnamespace`>
<Target Name='CleanUp'>
<Message Text='CleanUp-was-called.'/>
</Target>
<Target Name='Build'>
<Error Text='This is an error.'/>
<OnError Condition=`'A'=='B'` ExecuteTargets='CleanUp'/>
</Target>
</Project>",
l
);
p.Build(new string [] {"Build"}, null);
Assertion.Assert("Expected one error because 'Build' failed.", l.ErrorCount == 1);
Assertion.Assert("The CleanUp target should not have been called.", (l.FullLog.IndexOf("CleanUp-was-called") == -1));
}
/*
* Method: PropertiesInExecuteTargets
* Owner: jomof
*
* Make sure that properties in ExecuteTargets are properly expanded.
*/
[Test]
public void PropertiesInExecuteTargets()
{
MockLogger l = new MockLogger();
Project p = ObjectModelHelpers.CreateInMemoryProject(@"
<Project DefaultTargets=`Build` ToolsVersion=`msbuilddefaulttoolsversion` xmlns=`msbuildnamespace`>
<PropertyGroup>
<Part1>Clean</Part1>
<Part2>Up</Part2>
</PropertyGroup>
<Target Name='CleanUp'>
<Message Text='CleanUp-was-called.'/>
</Target>
<Target Name='Build'>
<Error Text='This is an error.'/>
<OnError Condition=`'A'!='B'` ExecuteTargets='$(Part1)$(Part2)'/>
</Target>
</Project>",
l
);
p.Build(new string [] {"Build"}, null);
Assertion.Assert("Expected one error because 'Build' failed.", l.ErrorCount == 1);
Assertion.Assert("The CleanUp target should have been called.", (l.FullLog.IndexOf("CleanUp-was-called") != -1));
}
/*
* Method: ErrorTargetsContinueAfterErrorsInErrorHandler
* Owner: jomof
*
* If an error occurs in an error handling target, then continue processing
* remaining error targets
*/
[Test]
public void ErrorTargetsContinueAfterErrorsInErrorHandler()
{
MockLogger l = new MockLogger();
Project p = ObjectModelHelpers.CreateInMemoryProject(@"
<Project DefaultTargets=`Build` ToolsVersion=`msbuilddefaulttoolsversion` xmlns=`msbuildnamespace`>
<Target Name='CleanUp1'>
<Message Text='CleanUp1-was-called.'/>
<Error Text='Error in CleanUp1.'/>
</Target>
<Target Name='CleanUp2'>
<Message Text='CleanUp2-was-called.'/>
<Error Text='Error in CleanUp2.'/>
</Target>
<Target Name='CleanUp3'>
<Message Text='CleanUp3-was-called.'/>
<Error Text='Error in CleanUp3.'/>
</Target>
<Target Name='CoreBuild'>
<Error Text='This is an error.'/>
<OnError ExecuteTargets='CleanUp1;CleanUp2'/>
</Target>
<Target Name='Build' DependsOnTargets='CoreBuild'>
<OnError ExecuteTargets='CleanUp3'/>
</Target>
</Project>",
l
);
p.Build(new string [] {"Build"}, null);
Assertion.Assert("Four build errors expect: One from CoreBuild and on each from the error handlers.", l.ErrorCount == 4);
Assertion.Assert("The CleanUp1 target should have been called.", (l.FullLog.IndexOf("CleanUp1-was-called") != -1));
Assertion.Assert("The CleanUp2 target should have been called.", (l.FullLog.IndexOf("CleanUp2-was-called") != -1));
Assertion.Assert("The CleanUp3 target should have been called.", (l.FullLog.IndexOf("CleanUp3-was-called") != -1));
}
/*
* Method: ExecuteTargetIsMissing
* Owner: jomof
*
* If an OnError specifies an ExecuteTarget that is missing, that's an error
*/
[Test]
public void ExecuteTargetIsMissing()
{
MockLogger l = new MockLogger();
Project p = ObjectModelHelpers.CreateInMemoryProject(@"
<Project DefaultTargets=`Build` ToolsVersion=`msbuilddefaulttoolsversion` xmlns=`msbuildnamespace`>
<Target Name='Build'>
<Error Text='This is an error.'/>
<OnError Condition=`'A'!='B'` ExecuteTargets='CleanUp'/>
</Target>
</Project>",
l
);
p.Build(new string [] {"Build"}, null);
Assertion.Assert("Expected one error because 'Build' failed and one because 'CleanUp' doesn't exist.", l.ErrorCount == 2);
}
/*
* Method: CommentsAroundOnError
* Owner: jomof
*
* Since there is special-case code to ignore comments around OnError blocks,
* let's test this case.
*/
[Test]
public void CommentsAroundOnError()
{
MockLogger l = new MockLogger();
Project p = ObjectModelHelpers.CreateInMemoryProject(@"
<Project DefaultTargets=`Build` ToolsVersion=`msbuilddefaulttoolsversion` xmlns=`msbuildnamespace`>
<Target Name='CleanUp'>
<Message Text='CleanUp-was-called.'/>
</Target>
<Target Name='Build'>
<Error Text='This is an error.'/>
<!-- Comment before OnError -->
<OnError Condition=`'A'!='B'` ExecuteTargets='CleanUp'/>
<!-- Comment after OnError -->
</Target>
</Project>",
l
);
p.Build(new string [] {"Build"}, null);
Assertion.Assert("Expected one error because 'Build' failed.", l.ErrorCount == 1);
Assertion.Assert("The CleanUp target should have been called.", (l.FullLog.IndexOf("CleanUp-was-called") != -1));
}
/*
* Method: CircularDependency
* Owner: jomof
*
* Detect circular dependencies and break out.
*/
[Test]
public void CircularDependency()
{
MockLogger l = new MockLogger();
Project p = ObjectModelHelpers.CreateInMemoryProject(@"
<Project DefaultTargets=`Build` ToolsVersion=`msbuilddefaulttoolsversion` xmlns=`msbuildnamespace`>
<Target Name='Build'>
<Error Text='Error in Build-Target'/>
<OnError ExecuteTargets='Build'/>
</Target>
</Project>",
l
);
p.Build(new string [] {"Build"}, null);
Assertion.Assert("Expected one error because 'Build' failed and one error because of the circular dependency.", l.ErrorCount == 2);
}
/*
* Method: OutOfOrderOnError
* Owner: jomof
*
* OnError clauses must come at the end of a Target, it can't be sprinkled in-between tasks. Catch this case.
*/
[Test]
[ExpectedException(typeof(InvalidProjectFileException))]
public void OutOfOrderOnError()
{
MockLogger l = new MockLogger();
Project p = ObjectModelHelpers.CreateInMemoryProject(@"
<Project DefaultTargets=`Build` ToolsVersion=`msbuilddefaulttoolsversion` xmlns=`msbuildnamespace`>
<Target Name='CleanUp'>
<Message Text='CleanUp-was-called.'/>
</Target>
<Target Name='Build'>
<OnError ExecuteTargets='CleanUp'/>
<Delete Files='__non__existent_file__'/>
</Target>
</Project>",
l
);
/* No build required */
}
#region Postbuild
/*
* Method: PostBuildBasic
* Owner: jomof
*
* Handle the basic post-build case where the user has asked for 'On_Success' and
* none of the build steps fail.
*/
[Test]
public void PostBuildBasic()
{
MockLogger l = new MockLogger();
Project p = ObjectModelHelpers.CreateInMemoryProject
(
PostBuildBuilder("On_Success", FailAt.Nowhere),
l
);
p.Build(new string [] {"Build"}, null);
Assertion.Assert("Expected no error because 'Build' succeeded.", l.ErrorCount == 0);
Assertion.Assert("The ResGen target should have been called.", (l.FullLog.IndexOf("ResGen-was-called") != -1));
Assertion.Assert("The Compile target should have been called.", (l.FullLog.IndexOf("Compile-was-called") != -1));
Assertion.Assert("The GenerateSatellites target should have been called.", (l.FullLog.IndexOf("GenerateSatellites-was-called") != -1));
Assertion.Assert("The PostBuild target should have been called.", (l.FullLog.IndexOf("PostBuild-was-called") != -1));
}
/*
* Method: PostBuildOnSuccessWhereCompileFailed
* Owner: jomof
*
* User asked for 'On_Success' but the compile step failed. We don't expect post-build
* to be called.
*/
[Test]
public void PostBuildOnSuccessWhereCompileFailed()
{
MockLogger l = new MockLogger();
Project p = ObjectModelHelpers.CreateInMemoryProject
(
PostBuildBuilder("On_Success", FailAt.Compile),
l
);
p.Build(new string [] {"Build"}, null);
Assertion.Assert("Expected one error because 'Build' failed.", l.ErrorCount == 1);
Assertion.Assert("The ResGen target should have been called.", (l.FullLog.IndexOf("ResGen-was-called") != -1));
Assertion.Assert("The Compile target should have been called.", (l.FullLog.IndexOf("Compile-was-called") != -1));
Assertion.Assert("The Compile target should have failed.", (l.FullLog.IndexOf("Compile-step-failed") != -1));
Assertion.Assert("The GenerateSatellites target should not have been called.", (l.FullLog.IndexOf("GenerateSatellites-was-called") == -1));
Assertion.Assert("The PostBuild target should not have been called.", (l.FullLog.IndexOf("PostBuild-was-called") == -1));
}
/*
* Method: PostBuildOnSuccessWhereGenerateSatellitesFailed
* Owner: jomof
*
* User asked for 'On_Success' but the PostBuildOnSuccessWhereGenerateSatellitesFailed step
* failed. We don't expect post-build to be called.
*/
[Test]
public void PostBuildOnSuccessWhereGenerateSatellitesFailed()
{
MockLogger l = new MockLogger();
Project p = ObjectModelHelpers.CreateInMemoryProject
(
PostBuildBuilder("On_Success", FailAt.GenerateSatellites),
l
);
p.Build(new string [] {"Build"}, null);
Assertion.Assert("Expected one error because 'Build' failed.", l.ErrorCount == 1);
Assertion.Assert("The ResGen target should have been called.", (l.FullLog.IndexOf("ResGen-was-called") != -1));
Assertion.Assert("The Compile target should have been called.", (l.FullLog.IndexOf("Compile-was-called") != -1));
Assertion.Assert("The GenerateSatellites target should have been called.", (l.FullLog.IndexOf("GenerateSatellites-was-called") != -1));
Assertion.Assert("The GenerateSatellites target should have failed.", (l.FullLog.IndexOf("GenerateSatellites-step-failed") != -1));
Assertion.Assert("The PostBuild target should not have been called.", (l.FullLog.IndexOf("PostBuild-was-called") == -1));
}
/*
* Method: PostBuildAlwaysWhereCompileFailed
* Owner: jomof
*
* User asked for 'Always' but the compile step failed. We expect the post-build
* to be called.
*/
[Test]
public void PostBuildAlwaysWhereCompileFailed()
{
MockLogger l = new MockLogger();
Project p = ObjectModelHelpers.CreateInMemoryProject
(
PostBuildBuilder("Always", FailAt.Compile),
l
);
p.Build(new string [] {"Build"}, null);
Assertion.Assert("Expected one error because 'Build' failed.", l.ErrorCount == 1);
Assertion.Assert("The ResGen target should have been called.", (l.FullLog.IndexOf("ResGen-was-called") != -1));
Assertion.Assert("The Compile target should have been called.", (l.FullLog.IndexOf("Compile-was-called") != -1));
Assertion.Assert("The Compile target should have failed.", (l.FullLog.IndexOf("Compile-step-failed") != -1));
Assertion.Assert("The GenerateSatellites target should not have been called.", (l.FullLog.IndexOf("GenerateSatellites-was-called") == -1));
Assertion.Assert("The PostBuild target should have been called.", (l.FullLog.IndexOf("PostBuild-was-called") != -1));
}
/*
* Method: PostBuildFinalOutputChangedWhereCompileFailed
* Owner: jomof
*
* User asked for 'Final_Output_Changed' but the Compile step failed.
* We expect post-build to be called.
*/
[Test]
public void PostBuildFinalOutputChangedWhereCompileFailed()
{
MockLogger l = new MockLogger();
Project p = ObjectModelHelpers.CreateInMemoryProject
(
PostBuildBuilder("Final_Output_Changed", FailAt.Compile),
l
);
p.Build(new string [] {"Build"}, null);
Assertion.Assert("Expected one error because 'Build' failed.", l.ErrorCount == 1);
Assertion.Assert("The ResGen target should have been called.", (l.FullLog.IndexOf("ResGen-was-called") != -1));
Assertion.Assert("The Compile target should have been called.", (l.FullLog.IndexOf("Compile-was-called") != -1));
Assertion.Assert("The Compile target should have failed.", (l.FullLog.IndexOf("Compile-step-failed") != -1));
Assertion.Assert("The GenerateSatellites target should not have been called.", (l.FullLog.IndexOf("GenerateSatellites-was-called") == -1));
Assertion.Assert("The PostBuild target should not have been called.", (l.FullLog.IndexOf("PostBuild-was-called") == -1));
}
/*
* Method: PostBuildFinalOutputChangedWhereGenerateSatellitesFailed
* Owner: jomof
*
* User asked for 'Final_Output_Changed' but the GenerateSatellites step failed.
* We expect post-build to be called because Compile succeeded (and wrote to the output).
*/
[Test]
public void PostBuildFinalOutputChangedWhereGenerateSatellitesFailed()
{
MockLogger l = new MockLogger();
Project p = ObjectModelHelpers.CreateInMemoryProject
(
PostBuildBuilder("Final_Output_Changed", FailAt.GenerateSatellites),
l
);
p.Build(new string [] {"Build"}, null);
Assertion.Assert("Expected one error because 'Build' failed.", l.ErrorCount == 1);
Assertion.Assert("The ResGen target should have been called.", (l.FullLog.IndexOf("ResGen-was-called") != -1));
Assertion.Assert("The Compile target should have been called.", (l.FullLog.IndexOf("Compile-was-called") != -1));
Assertion.Assert("The GenerateSatellites target should have been called.", (l.FullLog.IndexOf("GenerateSatellites-was-called") != -1));
Assertion.Assert("The GenerateSatellites target should have failed.", (l.FullLog.IndexOf("GenerateSatellites-step-failed") != -1));
Assertion.Assert("The PostBuild target should have been called.", (l.FullLog.IndexOf("PostBuild-was-called") != -1));
}
/*
* The different places that PostBuildBuilder might be instructed to fail at
*/
private enum FailAt
{
Compile,
GenerateSatellites,
Nowhere
}
/*
* Method: PostBuildBuilder
* Owner: jomof
*
* Build a project file that mimics the fairly complex way we plan to use OnError
* to handle all the different combinations of project failures and post-build
* conditions.
*
*/
private static string PostBuildBuilder
(
string controlFlag, // On_Success, Always, Final_Output_Changed
FailAt failAt
)
{
string compileStep = "";
if (FailAt.Compile == failAt)
{
compileStep = "<Error Text='Compile-step-failed'/>";
}
string generateSatellites = "";
if (FailAt.GenerateSatellites == failAt)
{
generateSatellites = "<Error Text='GenerateSatellites-step-failed'/>";
}
return String.Format(@"
<Project DefaultTargets=`Build` ToolsVersion=`msbuilddefaulttoolsversion` xmlns=`msbuildnamespace`>
<PropertyGroup>
<Flag>{0}</Flag>
</PropertyGroup>
<Target Name='ResGen'>
<Message Text='ResGen-was-called.'/>
</Target>
<Target Name='Compile'>
<Message Text='Compile-was-called.'/>
<RemoveDir Directories='c:\__Hopefully_Nonexistent_Directory__'/>
{1}
<CreateItem Include='Yes'>
<Output TaskParameter='Include' ItemName='FinalOutputChanged'/>
</CreateItem>
</Target>
<Target Name='GenerateSatellites'>
<Message Text='GenerateSatellites-was-called.'/>
{2}
</Target>
<Target Name='PostBuild'>
<Message Text='PostBuild-was-called.'/>
</Target>
<Target Name='PostBuildOnSuccess' Condition=`'$(Flag)'!='Final_Output_Changed'` DependsOnTargets='PostBuild'>
<Message Text='PostBuildOnSuccess-was-called.'/>
</Target>
<Target Name='PostBuildOnOutputChange' Condition=`'$(Flag)_@(FinalOutputChanged)'=='Final_Output_Changed_Yes'` DependsOnTargets='PostBuild'>
<Message Text='PostBuildOnOutputChange-was-called.'/>
</Target>
<Target Name='CoreBuildSucceeded' DependsOnTargets='PostBuildOnSuccess;PostBuildOnOutputChange'>
<Message Text='CoreBuildSucceeded-was-called.'/>
</Target>
<Target Name='CoreBuild' DependsOnTargets='ResGen;Compile;GenerateSatellites'>
<Message Text='CoreBuild-was-called.'/>
<OnError Condition=`'$(Flag)'=='Always'` ExecuteTargets=`PostBuild`/>
<OnError ExecuteTargets=`PostBuildOnOutputChange`/>
</Target>
<Target Name='Build' DependsOnTargets='CoreBuild;CoreBuildSucceeded'>
<Message Text='Build-target-was-called.'/>
</Target>
</Project>
", controlFlag, compileStep, generateSatellites);
}
#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\X86\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.X86;
namespace JIT.HardwareIntrinsics.X86
{
public static partial class Program
{
private static void XorUInt32()
{
var test = new SimpleBinaryOpTest__XorUInt32();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
// Validates basic functionality works, using LoadAligned
test.RunBasicScenario_LoadAligned();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
// Validates calling via reflection works, using LoadAligned
test.RunReflectionScenario_LoadAligned();
}
// Validates passing a static member works
test.RunClsVarScenario();
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
// Validates passing a local works, using LoadAligned
test.RunLclVarScenario_LoadAligned();
}
// Validates passing the field of a local works
test.RunLclFldScenario();
// Validates passing an instance member works
test.RunFldScenario();
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class SimpleBinaryOpTest__XorUInt32
{
private const int VectorSize = 16;
private const int Op1ElementCount = VectorSize / sizeof(UInt32);
private const int Op2ElementCount = VectorSize / sizeof(UInt32);
private const int RetElementCount = VectorSize / sizeof(UInt32);
private static UInt32[] _data1 = new UInt32[Op1ElementCount];
private static UInt32[] _data2 = new UInt32[Op2ElementCount];
private static Vector128<UInt32> _clsVar1;
private static Vector128<UInt32> _clsVar2;
private Vector128<UInt32> _fld1;
private Vector128<UInt32> _fld2;
private SimpleBinaryOpTest__DataTable<UInt32, UInt32, UInt32> _dataTable;
static SimpleBinaryOpTest__XorUInt32()
{
var random = new Random();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (uint)(random.Next(0, int.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt32>, byte>(ref _clsVar1), ref Unsafe.As<UInt32, byte>(ref _data1[0]), VectorSize);
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (uint)(random.Next(0, int.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt32>, byte>(ref _clsVar2), ref Unsafe.As<UInt32, byte>(ref _data2[0]), VectorSize);
}
public SimpleBinaryOpTest__XorUInt32()
{
Succeeded = true;
var random = new Random();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (uint)(random.Next(0, int.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt32>, byte>(ref _fld1), ref Unsafe.As<UInt32, byte>(ref _data1[0]), VectorSize);
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (uint)(random.Next(0, int.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt32>, byte>(ref _fld2), ref Unsafe.As<UInt32, byte>(ref _data2[0]), VectorSize);
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (uint)(random.Next(0, int.MaxValue)); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (uint)(random.Next(0, int.MaxValue)); }
_dataTable = new SimpleBinaryOpTest__DataTable<UInt32, UInt32, UInt32>(_data1, _data2, new UInt32[RetElementCount], VectorSize);
}
public bool IsSupported => Sse2.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
var result = Sse2.Xor(
Unsafe.Read<Vector128<UInt32>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<UInt32>>(_dataTable.inArray2Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
var result = Sse2.Xor(
Sse2.LoadVector128((UInt32*)(_dataTable.inArray1Ptr)),
Sse2.LoadVector128((UInt32*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
var result = Sse2.Xor(
Sse2.LoadAlignedVector128((UInt32*)(_dataTable.inArray1Ptr)),
Sse2.LoadAlignedVector128((UInt32*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
var result = typeof(Sse2).GetMethod(nameof(Sse2.Xor), new Type[] { typeof(Vector128<UInt32>), typeof(Vector128<UInt32>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector128<UInt32>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<UInt32>>(_dataTable.inArray2Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt32>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
var result = typeof(Sse2).GetMethod(nameof(Sse2.Xor), new Type[] { typeof(Vector128<UInt32>), typeof(Vector128<UInt32>) })
.Invoke(null, new object[] {
Sse2.LoadVector128((UInt32*)(_dataTable.inArray1Ptr)),
Sse2.LoadVector128((UInt32*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt32>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
var result = typeof(Sse2).GetMethod(nameof(Sse2.Xor), new Type[] { typeof(Vector128<UInt32>), typeof(Vector128<UInt32>) })
.Invoke(null, new object[] {
Sse2.LoadAlignedVector128((UInt32*)(_dataTable.inArray1Ptr)),
Sse2.LoadAlignedVector128((UInt32*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt32>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
var result = Sse2.Xor(
_clsVar1,
_clsVar2
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_UnsafeRead()
{
var left = Unsafe.Read<Vector128<UInt32>>(_dataTable.inArray1Ptr);
var right = Unsafe.Read<Vector128<UInt32>>(_dataTable.inArray2Ptr);
var result = Sse2.Xor(left, right);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
var left = Sse2.LoadVector128((UInt32*)(_dataTable.inArray1Ptr));
var right = Sse2.LoadVector128((UInt32*)(_dataTable.inArray2Ptr));
var result = Sse2.Xor(left, right);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
var left = Sse2.LoadAlignedVector128((UInt32*)(_dataTable.inArray1Ptr));
var right = Sse2.LoadAlignedVector128((UInt32*)(_dataTable.inArray2Ptr));
var result = Sse2.Xor(left, right);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclFldScenario()
{
var test = new SimpleBinaryOpTest__XorUInt32();
var result = Sse2.Xor(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunFldScenario()
{
var result = Sse2.Xor(_fld1, _fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
public void RunUnsupportedScenario()
{
Succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
Succeeded = true;
}
}
private void ValidateResult(Vector128<UInt32> left, Vector128<UInt32> right, void* result, [CallerMemberName] string method = "")
{
UInt32[] inArray1 = new UInt32[Op1ElementCount];
UInt32[] inArray2 = new UInt32[Op2ElementCount];
UInt32[] outArray = new UInt32[RetElementCount];
Unsafe.Write(Unsafe.AsPointer(ref inArray1[0]), left);
Unsafe.Write(Unsafe.AsPointer(ref inArray2[0]), right);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize);
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(void* left, void* right, void* result, [CallerMemberName] string method = "")
{
UInt32[] inArray1 = new UInt32[Op1ElementCount];
UInt32[] inArray2 = new UInt32[Op2ElementCount];
UInt32[] outArray = new UInt32[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(left), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(right), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize);
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(UInt32[] left, UInt32[] right, UInt32[] result, [CallerMemberName] string method = "")
{
if ((uint)(left[0] ^ right[0]) != result[0])
{
Succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if ((uint)(left[i] ^ right[i]) != result[i])
{
Succeeded = false;
break;
}
}
}
if (!Succeeded)
{
Console.WriteLine($"{nameof(Sse2)}.{nameof(Sse2.Xor)}<UInt32>(Vector128<UInt32>, Vector128<UInt32>): {method} failed:");
Console.WriteLine($" left: ({string.Join(", ", left)})");
Console.WriteLine($" right: ({string.Join(", ", right)})");
Console.WriteLine($" result: ({string.Join(", ", result)})");
Console.WriteLine();
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Security.Cryptography.Xml;
using System.Security.Cryptography.X509Certificates;
using Xunit;
using Test.Cryptography;
using System.Security.Cryptography.Pkcs.Tests;
using System.Linq;
namespace System.Security.Cryptography.Pkcs.EnvelopedCmsTests.Tests
{
public abstract partial class DecryptTests
{
private bool _useExplicitPrivateKey;
public static bool SupportsCngCertificates { get; } = (!PlatformDetection.IsFullFramework || PlatformDetection.IsNetfx462OrNewer);
public static bool SupportsIndefiniteLengthEncoding { get; } = !PlatformDetection.IsFullFramework;
public DecryptTests(bool useExplicitPrivateKey)
{
_useExplicitPrivateKey = useExplicitPrivateKey;
}
[ConditionalFact(nameof(SupportsCngCertificates))]
[OuterLoop(/* Leaks key on disk if interrupted */)]
public void Decrypt_IssuerAndSerial()
{
byte[] content = { 5, 112, 233, 43 };
ContentInfo contentInfo = new ContentInfo(content);
TestSimpleDecrypt_RoundTrip(Certificates.RSAKeyTransfer1, contentInfo, Oids.Aes256, SubjectIdentifierType.IssuerAndSerialNumber);
}
[ConditionalFact(nameof(SupportsCngCertificates))]
[OuterLoop(/* Leaks key on disk if interrupted */)]
public void Decrypt_Ski()
{
byte[] content = { 6, 3, 128, 33, 44 };
ContentInfo contentInfo = new ContentInfo(content);
TestSimpleDecrypt_RoundTrip(Certificates.RSAKeyTransfer1, contentInfo, Oids.Aes256, SubjectIdentifierType.SubjectKeyIdentifier);
}
[Fact]
[OuterLoop(/* Leaks key on disk if interrupted */)]
public void Decrypt_Capi()
{
byte[] content = { 5, 77, 32, 33, 2, 34 };
ContentInfo contentInfo = new ContentInfo(content);
TestSimpleDecrypt_RoundTrip(Certificates.RSAKeyTransferCapi1, contentInfo, Oids.Aes256, SubjectIdentifierType.IssuerAndSerialNumber);
}
[ConditionalFact(nameof(SupportsCngCertificates))]
[OuterLoop(/* Leaks key on disk if interrupted */)]
public void Decrypt_256()
{
byte[] content = { 5, 77, 32, 33, 2, 34 };
ContentInfo contentInfo = new ContentInfo(content);
TestSimpleDecrypt_RoundTrip(Certificates.RSASha256KeyTransfer1, contentInfo, Oids.Aes256, SubjectIdentifierType.IssuerAndSerialNumber);
}
[ConditionalFact(nameof(SupportsCngCertificates))]
[OuterLoop(/* Leaks key on disk if interrupted */)]
public void Decrypt_384()
{
byte[] content = { 5, 77, 32, 33, 2, 34 };
ContentInfo contentInfo = new ContentInfo(content);
TestSimpleDecrypt_RoundTrip(Certificates.RSASha384KeyTransfer1, contentInfo, Oids.Aes256, SubjectIdentifierType.IssuerAndSerialNumber);
}
[ConditionalFact(nameof(SupportsCngCertificates))]
[OuterLoop(/* Leaks key on disk if interrupted */)]
public void Decrypt_512()
{
byte[] content = { 5, 77, 32, 33, 2, 34 };
ContentInfo contentInfo = new ContentInfo(content);
TestSimpleDecrypt_RoundTrip(Certificates.RSASha512KeyTransfer1, contentInfo, Oids.Aes256, SubjectIdentifierType.IssuerAndSerialNumber);
}
[ConditionalFact(nameof(SupportsCngCertificates))]
[OuterLoop("Leaks key on disk if interrupted")]
public void Decrypt_512_FixedValue()
{
byte[] content = { 5, 77, 32, 33, 2, 34 };
byte[] message = (
"3082012506092A864886F70D010703A0820116308201120201003181CE3081CB" +
"02010030343020311E301C060355040313155253415368613531324B65795472" +
"616E736665723102102F5D9D58A5F41B844650AA233E68F105300D06092A8648" +
"86F70D01010105000481803163AA33F8F5E033DC03AE98CCEE158199589FC420" +
"19200DCC1D202309CCCAF79CC0278B9502B5709F1311E522DA325338136D3F1E" +
"A271FAEA978CC656A3CB94B1C6A8D7AFC836C3193DB693E8B8767472C2C23125" +
"BA11E7D0623E4C8B848826BBF99EB411CB88B4731740D1AD834F0E4076BAD0D4" +
"BA695CFE8CDB2DE3E77196303C06092A864886F70D010701301D060960864801" +
"650304012A0410280AC7A629BFC9FD6FB24F8A42F094B48010B78CDFECFF32A8" +
"E86D448989382A93E7"
).HexToByteArray();
VerifySimpleDecrypt(message, Certificates.RSASha512KeyTransfer1, new ContentInfo(content));
}
[ConditionalFact(nameof(SupportsCngCertificates))]
[OuterLoop("Leaks key on disk if interrupted")]
public void Decrypt_512_NoData_FixedValue()
{
// This is the Decrypt_512_FixedData test re-encoded to remove the
// encryptedContentInfo.encryptedContent optional value.
byte[] content = Array.Empty<byte>();
byte[] message = (
"3082011306092A864886F70D010703A0820104308201000201003181CE3081CB" +
"02010030343020311E301C060355040313155253415368613531324B65795472" +
"616E736665723102102F5D9D58A5F41B844650AA233E68F105300D06092A8648" +
"86F70D01010105000481803163AA33F8F5E033DC03AE98CCEE158199589FC420" +
"19200DCC1D202309CCCAF79CC0278B9502B5709F1311E522DA325338136D3F1E" +
"A271FAEA978CC656A3CB94B1C6A8D7AFC836C3193DB693E8B8767472C2C23125" +
"BA11E7D0623E4C8B848826BBF99EB411CB88B4731740D1AD834F0E4076BAD0D4" +
"BA695CFE8CDB2DE3E77196302A06092A864886F70D010701301D060960864801" +
"650304012A0410280AC7A629BFC9FD6FB24F8A42F094B4"
).HexToByteArray();
if (PlatformDetection.IsFullFramework)
{
// On NetFx when Array.Empty should be returned an array of 6 zeros is
// returned instead.
content = new byte[6];
}
VerifySimpleDecrypt(message, Certificates.RSASha512KeyTransfer1, new ContentInfo(content));
}
[ConditionalFact(nameof(SupportsCngCertificates))]
[OuterLoop("Leaks key on disk if interrupted")]
public void Decrypt_512_CekDoesNotDecrypt_FixedValue()
{
// This is the Decrypt_512_NoData_FixedValue test except that the last
// byte of the recipient encrypted key has been changed from 0x96 to 0x95
// (the sequence 7195 identifies the changed byte)
byte[] content = Array.Empty<byte>();
byte[] message = (
"3082011306092A864886F70D010703A0820104308201000201003181CE3081CB" +
"02010030343020311E301C060355040313155253415368613531324B65795472" +
"616E736665723102102F5D9D58A5F41B844650AA233E68F105300D06092A8648" +
"86F70D01010105000481803163AA33F8F5E033DC03AE98CCEE158199589FC420" +
"19200DCC1D202309CCCAF79CC0278B9502B5709F1311E522DA325338136D3F1E" +
"A271FAEA978CC656A3CB94B1C6A8D7AFC836C3193DB693E8B8767472C2C23125" +
"BA11E7D0623E4C8B848826BBF99EB411CB88B4731740D1AD834F0E4076BAD0D4" +
"BA695CFE8CDB2DE3E77195302A06092A864886F70D010701301D060960864801" +
"650304012A0410280AC7A629BFC9FD6FB24F8A42F094B4"
).HexToByteArray();
Assert.ThrowsAny<CryptographicException>(
() => VerifySimpleDecrypt(message, Certificates.RSASha512KeyTransfer1, new ContentInfo(content)));
}
[Fact]
[OuterLoop(/* Leaks key on disk if interrupted */)]
public void Decrypt_SignedWithinEnveloped()
{
byte[] content =
("3082032506092a864886f70d010702a082031630820312020101310b300906052b0e03021a0500301206092a864886f70d01"
+ "0701a0050403010203a08202103082020c30820179a00302010202105d2ffff863babc9b4d3c80ab178a4cca300906052b0e"
+ "03021d0500301e311c301a060355040313135253414b65795472616e736665724361706931301e170d313530343135303730"
+ "3030305a170d3235303431353037303030305a301e311c301a060355040313135253414b65795472616e7366657243617069"
+ "3130819f300d06092a864886f70d010101050003818d0030818902818100aa272700586c0cc41b05c65c7d846f5a2bc27b03"
+ "e301c37d9bff6d75b6eb6671ba9596c5c63ba2b1af5c318d9ca39e7400d10c238ac72630579211b86570d1a1d44ec86aa8f6"
+ "c9d2b4e283ea3535923f398a312a23eaeacd8d34faaca965cd910b37da4093ef76c13b337c1afab7d1d07e317b41a336baa4"
+ "111299f99424408d0203010001a3533051304f0603551d0104483046801015432db116b35d07e4ba89edb2469d7aa120301e"
+ "311c301a060355040313135253414b65795472616e73666572436170693182105d2ffff863babc9b4d3c80ab178a4cca3009"
+ "06052b0e03021d05000381810081e5535d8eceef265acbc82f6c5f8bc9d84319265f3ccf23369fa533c8dc1938952c593166"
+ "2d9ecd8b1e7b81749e48468167e2fce3d019fa70d54646975b6dc2a3ba72d5a5274c1866da6d7a5df47938e034a075d11957"
+ "d653b5c78e5291e4401045576f6d4eda81bef3c369af56121e49a083c8d1adb09f291822e99a4296463181d73081d4020101"
+ "3032301e311c301a060355040313135253414b65795472616e73666572436170693102105d2ffff863babc9b4d3c80ab178a"
+ "4cca300906052b0e03021a0500300d06092a864886f70d010101050004818031a718ea1483c88494661e1d3dedfea0a3d97e"
+ "eb64c3e093a628b257c0cfc183ecf11697ac84f2af882b8de0c793572af38dc15d1b6f3d8f2392ba1cc71210e177c146fd16"
+ "b77a583b6411e801d7a2640d612f2fe99d87e9718e0e505a7ab9536d71dbde329da21816ce7da1416a74a3e0a112b86b33af"
+ "336a2ba6ae2443d0ab").HexToByteArray();
ContentInfo contentInfo = new ContentInfo(new Oid(Oids.Pkcs7Signed), content);
TestSimpleDecrypt_RoundTrip(Certificates.RSAKeyTransferCapi1, contentInfo, Oids.Aes256, SubjectIdentifierType.IssuerAndSerialNumber);
}
[Fact]
[OuterLoop(/* Leaks key on disk if interrupted */)]
public void Decrypt_EnvelopedWithinEnveloped()
{
byte[] content =
("3082010c06092a864886f70d010703a081fe3081fb0201003181c83081c5020100302e301a311830160603550403130f5253"
+ "414b65795472616e7366657231021031d935fb63e8cfab48a0bf7b397b67c0300d06092a864886f70d010101050004818013"
+ "dc0eb2984a445d04a1f6246b8fe41f1d24507548d449d454d5bb5e0638d75ed101bf78c0155a5d208eb746755fbccbc86923"
+ "8443760a9ae94770d6373e0197be23a6a891f0c522ca96b3e8008bf23547474b7e24e7f32e8134df3862d84f4dea2470548e"
+ "c774dd74f149a56cdd966e141122900d00ad9d10ea1848541294a1302b06092a864886f70d010701301406082a864886f70d"
+ "030704089c8119f6cf6b174c8008bcea3a10d0737eb9").HexToByteArray();
ContentInfo contentInfo = new ContentInfo(new Oid(Oids.Pkcs7SignedEnveloped), content);
TestSimpleDecrypt_RoundTrip(Certificates.RSAKeyTransferCapi1, contentInfo, Oids.Aes256, SubjectIdentifierType.IssuerAndSerialNumber);
}
[Fact]
public void EncryptToNegativeSerialNumber()
{
CertLoader negativeSerial = Certificates.NegativeSerialNumber;
const string expectedSerial = "FD319CB1514B06AF49E00522277E43C8";
byte[] content = { 1, 2, 3 };
ContentInfo contentInfo = new ContentInfo(content);
EnvelopedCms cms = new EnvelopedCms(contentInfo);
using (X509Certificate2 cert = negativeSerial.GetCertificate())
{
Assert.Equal(expectedSerial, cert.SerialNumber);
CmsRecipient recipient = new CmsRecipient(SubjectIdentifierType.IssuerAndSerialNumber, cert);
cms.Encrypt(recipient);
}
EnvelopedCms cms2 = new EnvelopedCms();
cms2.Decode(cms.Encode());
RecipientInfoCollection recipients = cms2.RecipientInfos;
Assert.Equal(1, recipients.Count);
RecipientInfo recipientInfo = recipients[0];
Assert.Equal(SubjectIdentifierType.IssuerAndSerialNumber, recipientInfo.RecipientIdentifier.Type);
X509IssuerSerial issuerSerial = (X509IssuerSerial)recipientInfo.RecipientIdentifier.Value;
Assert.Equal(expectedSerial, issuerSerial.SerialNumber);
using (X509Certificate2 cert = negativeSerial.TryGetCertificateWithPrivateKey())
{
Assert.Equal(expectedSerial, cert.SerialNumber);
cms2.Decrypt(new X509Certificate2Collection(cert));
}
Assert.Equal(content, cms2.ContentInfo.Content);
}
[Fact]
[OuterLoop(/* Leaks key on disk if interrupted */)]
public void TestDecryptSimpleAes128_IssuerAndSerial()
{
// Message encrypted on framework for a recipient using the certificate returned by Certificates.RSAKeyTransfer1.GetCertificate()
// and of type IssuerAndSerialNumber. The symmetric algorithm is Aes128
byte[] encryptedMessage =
("3082011F06092A864886F70D010703A08201103082010C0201003181C83081C5020100302E301A311830160"
+ "603550403130F5253414B65795472616E7366657231021031D935FB63E8CFAB48A0BF7B397B67C0300D0609"
+ "2A864886F70D0101073000048180862175CD3B2932235A67C6A025F75CDA1A43B53E785370895BA9AC8D0DD"
+ "318EB36DFAE275B16ABD497FEBBFCF2D4B3F38C75B91DC40941A2CC1F7F47E701EEA2D5A770C485565F8726"
+ "DC0D59DDE17AA6DB0F9384C919FC8BC6CB561A980A9AE6095486FDF9F52249FB466B3676E4AEFE4035C15DC"
+ "EE769F25E4660D4BE664E7F303C06092A864886F70D010701301D060960864801650304010204100A068EE9"
+ "03E085EA5A03D1D8B4B73DD88010740E5DE9B798AA062B449F104D0F5D35").HexToByteArray();
byte[] expectedContent = { 1, 2, 3, 4 };
ContentInfo expectedContentInfo = new ContentInfo(expectedContent);
CertLoader certLoader = Certificates.RSAKeyTransfer1;
VerifySimpleDecrypt(encryptedMessage, certLoader, expectedContentInfo);
}
[Fact]
[OuterLoop(/* Leaks key on disk if interrupted */)]
public void TestDecryptSimpleAes192_IssuerAndSerial()
{
// Message encrypted on framework for a recipient using the certificate returned by Certificates.RSAKeyTransfer1.GetCertificate()
// and of type IssuerAndSerialNumber. The symmetric algorithm used is Aes192
byte[] encryptedMessage =
("3082011F06092A864886F70D010703A08201103082010C0201003181C83081C5020100302E301A311830160"
+ "603550403130F5253414B65795472616E7366657231021031D935FB63E8CFAB48A0BF7B397B67C0300D0609"
+ "2A864886F70D010107300004818029B82454B4C301F277D7872A14695A41ED24FD37AC4C9942F9EE96774E0"
+ "C6ACC18E756993A38AB215E5702CD34F244E52402DA432E8B79DF748405135E8A6D8CB78D88D9E4C142565C"
+ "06F9FAFB32F5A9A4074E10FCCB0758A708CA758C12A17A4961969FCB3B2A6E6C9EB49F5E688D107E1B1DF3D"
+ "531BC684B944FCE6BD4550C303C06092A864886F70D010701301D06096086480165030401160410FD7CBBF5"
+ "6101854387E584C1B6EF3B08801034BD11C68228CB683E0A43AB5D27A8A4").HexToByteArray();
byte[] expectedContent = { 1, 2, 3, 4 };
ContentInfo expectedContentInfo = new ContentInfo(expectedContent);
CertLoader certLoader = Certificates.RSAKeyTransfer1;
VerifySimpleDecrypt(encryptedMessage, certLoader, expectedContentInfo);
}
[Fact]
[OuterLoop(/* Leaks key on disk if interrupted */)]
public void TestDecryptSimpleAes256_IssuerAndSerial()
{
// Message encrypted on framework for a recipient using the certificate returned by Certificates.RSAKeyTransfer1.GetCertificate()
// and of type IssuerAndSerialNumber. The symmetric algorithm used is Aes256
byte[] encryptedMessage =
("3082011F06092A864886F70D010703A08201103082010C0201003181C83081C5020100302E301A311830160"
+ "603550403130F5253414B65795472616E7366657231021031D935FB63E8CFAB48A0BF7B397B67C0300D0609"
+ "2A864886F70D01010730000481800215BF7505BCD5D083F8EFDA01A4F91D61DE3967779B2F5E4360593D4CB"
+ "96474E36198531A5E20E417B04C5C7E3263C3301DF8FA888FFBECC796500D382858379059C986285AFD605C"
+ "B5DE125487CCA658DF261C836720E2E14440DA60E2F12D6D5E3992A0DB59973929DF6FC23D8E891F97CA956"
+ "2A7AD160B502FA3C10477AA303C06092A864886F70D010701301D060960864801650304012A04101287FE80"
+ "93F3C517AE86AFB95E599D7E80101823D88F47191857BE0743C4C730E39E").HexToByteArray();
byte[] expectedContent = { 1, 2, 3, 4 };
ContentInfo expectedContentInfo = new ContentInfo(expectedContent);
CertLoader certLoader = Certificates.RSAKeyTransfer1;
VerifySimpleDecrypt(encryptedMessage, certLoader, expectedContentInfo);
}
[Fact]
[OuterLoop(/* Leaks key on disk if interrupted */)]
public void TestDecryptSimpleTripleDes_IssuerAndSerial()
{
// Message encrypted on framework for a recipient using the certificate returned by Certificates.RSAKeyTransfer1.GetCertificate()
// and of type IssuerAndSerialNumber. The symmetric algorithm used is 3DES-CBC
byte[] encryptedMessage =
("3082010C06092A864886F70D010703A081FE3081FB0201003181C83081C5020100302E301A3118301606035"
+ "50403130F5253414B65795472616E7366657231021031D935FB63E8CFAB48A0BF7B397B67C0300D06092A86"
+ "4886F70D0101010500048180062F6F16637C8F35B73924AD85BA47D99DBB4800CB8F0C4094F6896050B7C1F"
+ "11CE79BEE55A638EAAE70F2C32C01FC24B8D09D9D574CB7373788C8BC3A4748124154338C74B644A2A11750"
+ "9E97D1B3535FAE70E4E7C8F2F866232CBFC6448E89CF9D72B948EDCF9C9FC9C153BCC7104680282A4BBBC1E"
+ "E367F094F627EE45FCD302B06092A864886F70D010701301406082A864886F70D030704081E3F12D42E4041"
+ "58800877A4A100165DD0F2").HexToByteArray();
byte[] expectedContent = { 1, 2, 3, 4 };
ContentInfo expectedContentInfo = new ContentInfo(expectedContent);
CertLoader certLoader = Certificates.RSAKeyTransfer1;
VerifySimpleDecrypt(encryptedMessage, certLoader, expectedContentInfo);
}
[Fact]
[OuterLoop(/* Leaks key on disk if interrupted */)]
public void TestDecryptSimpleAes256_Ski()
{
// Message encrypted on framework for a recipient using the certificate returned by Certificates.RSAKeyTransfer1.GetCertificate()
// and of type SubjectKeyIdentifier. The symmetric algorithm used is Aes256
byte[] encryptedMessage =
("3082010306092A864886F70D010703A081F53081F20201023181AE3081AB0201028014F2008AA9FA3742E83"
+ "70CB1674CE1D1582921DCC3300D06092A864886F70D010101050004818055F258073615B95426A7021E1B30"
+ "9CFE8DD135B58D29F174B9FE19AE80CFC84621BCE3DBD63A5422AF30A6FAA3E2DFC05CB1AB5AB4FBA6C84EB"
+ "1C2E17D5BE5C4959DBE8F96BF1A9701F55B697843032EEC7AFEC58A36815168F017DCFD70C74AD05C48B5E4"
+ "D9DDEE409FDC9DC3326B6C5BA9F433A9E031FF9B09473176637F50303C06092A864886F70D010701301D060"
+ "960864801650304012A0410314DA87435ED110DFE4F52FA70CEF7B080104DDA6C617338DEBDD10913A9141B"
+ "EE52").HexToByteArray();
byte[] expectedContent = { 1, 2, 3, 4 };
ContentInfo expectedContentInfo = new ContentInfo(expectedContent);
CertLoader certLoader = Certificates.RSAKeyTransfer1;
VerifySimpleDecrypt(encryptedMessage, certLoader, expectedContentInfo);
}
[Fact]
[OuterLoop(/* Leaks key on disk if interrupted */)]
public void TestDecryptSimpleAes256_RsaTransferCapi()
{
// Message encrypted on framework for a recipient using the certificate returned by Certificates.RSAKeyTransferCapi1.GetCertificate()
// and of type IssuerAndSerialNumber. The symmetric algorithm used is Aes256
byte[] encryptedMessage =
("3082012306092A864886F70D010703A0820114308201100201003181CC3081C90201003032301E311C301A0"
+ "60355040313135253414B65795472616E73666572436170693102105D2FFFF863BABC9B4D3C80AB178A4CCA"
+ "300D06092A864886F70D01010730000481804F3F4A6707B329AB9A7343C62F20D5C1EAF4E74ECBB2DC66D1C"
+ "642FC4AA3E40FC4C13547C6C9F73D525EE2FE4147B2043B8FEBF8604C0E4091C657B48DFD83A322F0879580"
+ "FA002C9B27AD1FCF9B8AF24EDDA927BB6728D11530B3F96EBFC859ED6B9F7B009F992171FACB587A7D05E8B"
+ "467B3A1DACC08B2F3341413A7E96576303C06092A864886F70D010701301D060960864801650304012A0410"
+ "6F911E14D9D991DAB93C0B7738D1EC208010044264D201501735F73052FFCA4B2A95").HexToByteArray();
byte[] expectedContent = { 1, 2, 3, 4 };
ContentInfo expectedContentInfo = new ContentInfo(expectedContent);
CertLoader certLoader = Certificates.RSAKeyTransferCapi1;
VerifySimpleDecrypt(encryptedMessage, certLoader, expectedContentInfo);
}
[Fact]
[OuterLoop(/* Leaks key on disk if interrupted */)]
public void TestDecryptSimpleAes256_RsaSha256()
{
// Message encrypted on framework for a recipient using the certificate returned by
// Certificates.RSASha256KeyTransfer1.GetCertificate() and of type IssuerAndSerialNumber. The symmetric algorithm used is Aes256
byte[] encryptedMessage =
("3082012506092A864886F70D010703A0820116308201120201003181CE3081CB02010030343020311E301C0"
+ "60355040313155253415368613235364B65795472616E7366657231021072C6C7734916468C4D608253DA01"
+ "7676300D06092A864886F70D01010730000481805C32FA32EBDCFFC3595166EEDACFC9E9D60842105B581E1"
+ "8B85DE1409F4C999995637153480438530955EE4481A3B27B866FF4E106A525CDFFC6941BDD01EFECCC6CCC"
+ "82A3D7F743F7543AB20A61A7831FE4DFB24A1652B072B3758FE4B2588D3B94A29575B6422DC5EF52E432565"
+ "36CA25A11BB92817D61FEAFBDDDEC6EE331303C06092A864886F70D010701301D060960864801650304012A"
+ "041021D59FDB89C13A3EC3766EF32FB333D080105AE8DEB71DF50DD85F66FEA63C8113F4").HexToByteArray();
byte[] expectedContent = { 1, 2, 3, 4 };
ContentInfo expectedContentInfo = new ContentInfo(expectedContent);
CertLoader certLoader = Certificates.RSASha256KeyTransfer1;
VerifySimpleDecrypt(encryptedMessage, certLoader, expectedContentInfo);
}
[Fact]
[OuterLoop(/* Leaks key on disk if interrupted */)]
public void TestDecryptSimpleAes256_RsaSha384()
{
// Message encrypted on framework for a recipient using the certificate returned by Certificates.RSASha384KeyTransfer1.GetCertificate()
// and of type IssuerAndSerialNumber. The symmetric algorithm used is Aes256
byte[] encryptedMessage =
("3082012506092A864886F70D010703A0820116308201120201003181CE3081CB02010030343020311E301C0"
+ "60355040313155253415368613338344B65795472616E736665723102103C724FB7A0159A9345CAAC9E3DF5"
+ "F136300D06092A864886F70D010107300004818011C1B85914331C005EA89E30D00364821B29BC0C459A22D"
+ "917494A1092CDBDA2022792E46C5E88BAD0EE3FD4927B856722311F9B17934FB29CAB8FE595C2AB2B20096B"
+ "9E2FC6F9D7B92125F571CBFC945C892EE4764D9B63369350FD2DAEFE455B367F48E100CB461F112808E792A"
+ "8AA49B66C79E511508A877530BBAA896696303C06092A864886F70D010701301D060960864801650304012A"
+ "0410D653E25E06BFF2EEB0BED4A90D00FE2680106B7EF143912ABA5C24F5E2C151E59D7D").HexToByteArray();
byte[] expectedContent = { 1, 2, 3, 4 };
ContentInfo expectedContentInfo = new ContentInfo(expectedContent);
CertLoader certLoader = Certificates.RSASha384KeyTransfer1;
VerifySimpleDecrypt(encryptedMessage, certLoader, expectedContentInfo);
}
[Fact]
[OuterLoop(/* Leaks key on disk if interrupted */)]
public void TestDecryptSimpleAes256_RsaSha512()
{
// Message encrypted on framework for a recipient using the certificate returned by Certificates.RSASha512KeyTransfer1.GetCertificate()
// and of type IssuerAndSerialNumber. The symmetric algorithm used is Aes256
byte[] encryptedMessage =
("3082012506092A864886F70D010703A0820116308201120201003181CE3081CB02010030343020311E301C0"
+ "60355040313155253415368613531324B65795472616E736665723102102F5D9D58A5F41B844650AA233E68"
+ "F105300D06092A864886F70D01010730000481802156D42FF5ED2F0338302E7298EF79BA1D04E20E68B079D"
+ "B3239120E1FC03FEDA8B544F59142AACAFBC5E58205E8A0D124AAD17B5DCAA39BFC6BA634E820DE623BFDB6"
+ "582BC48AF1B3DEF6849A57D2033586AF01079D67C9AB3AA9F6B51754BCC479A19581D4045EBE23145370219"
+ "98ECB6F5E1BCF8D6BED6A75FE957A40077D303C06092A864886F70D010701301D060960864801650304012A"
+ "04100B696608E489E7C35914D0A3DB9EB27F80103D362181B54721FB2CB7CE461CB31030").HexToByteArray();
byte[] expectedContent = { 1, 2, 3, 4 };
ContentInfo expectedContentInfo = new ContentInfo(expectedContent);
CertLoader certLoader = Certificates.RSASha512KeyTransfer1;
VerifySimpleDecrypt(encryptedMessage, certLoader, expectedContentInfo);
}
[Fact]
[OuterLoop(/* Leaks key on disk if interrupted */)]
public void TestDecryptSimple_ExplicitSki()
{
// Message encrypted on framework for a recipient using the certificate returned by Certificates.RSAKeyTransfer_ExplicitSki.GetCertificate()
// and of type SubjectKeyIdentifier. The symmetric algorithm used is Aes256
byte[] encryptedMessage =
("3082018806092A864886F70D010703A082017930820175020102318201303082012C020102801401952851C"
+ "55DB594B0C6167F5863C5B6B67AEFE6300D06092A864886F70D010101050004820100269EAF029262C87125"
+ "314DD3FB02302FA212EB3CC06F73DF1474382BBA2A92845F39FF5A7F5020482849C36B4BC6BC82F7AF0E2E3"
+ "9143548CC32B93B72EF0659C6895F77E6B5839962678532392185C9431658B34D1ABD31F64F4C4A9B348A77"
+ "56783D60244519ADDD33560405E9377A91617127C2EECF2BAE53AB930FC13AFD25723FB60DB763286EDF6F1"
+ "187D8124B6A569AA2BD19294A7D551A0D90F8436274690231520A2254C19EA9BF877FC99566059A29CDF503"
+ "6BEA1D517916BA2F20AC9F1D8F164B6E8ACDD52BA8B2650EBBCC2ED9103561E11AF422D10DF7405404195FA"
+ "EF79A1FDC680F3A3DC395E3E9C0B10394DF35AE134E6CB719E35152F8E5303C06092A864886F70D01070130"
+ "1D060960864801650304012A041085072D8771A2A2BB403E3236A7C60C2A80105C71A04E73C57FE75C1DEDD"
+ "94B57FD01").HexToByteArray();
byte[] expectedContent = { 1, 2, 3, 4 };
ContentInfo expectedContentInfo = new ContentInfo(expectedContent);
CertLoader certLoader = Certificates.RSAKeyTransfer_ExplicitSki;
VerifySimpleDecrypt(encryptedMessage, certLoader, expectedContentInfo);
}
[Fact]
[OuterLoop(/* Leaks key on disk if interrupted */)]
public void TestDecryptSimple_Pkcs7Signed_GeneratedOnWindows()
{
byte[] expectedContent =
("3082032506092a864886f70d010702a082031630820312020101310b300906052b0e03021a0500301206092a864886f70d01"
+ "0701a0050403010203a08202103082020c30820179a00302010202105d2ffff863babc9b4d3c80ab178a4cca300906052b0e"
+ "03021d0500301e311c301a060355040313135253414b65795472616e736665724361706931301e170d313530343135303730"
+ "3030305a170d3235303431353037303030305a301e311c301a060355040313135253414b65795472616e7366657243617069"
+ "3130819f300d06092a864886f70d010101050003818d0030818902818100aa272700586c0cc41b05c65c7d846f5a2bc27b03"
+ "e301c37d9bff6d75b6eb6671ba9596c5c63ba2b1af5c318d9ca39e7400d10c238ac72630579211b86570d1a1d44ec86aa8f6"
+ "c9d2b4e283ea3535923f398a312a23eaeacd8d34faaca965cd910b37da4093ef76c13b337c1afab7d1d07e317b41a336baa4"
+ "111299f99424408d0203010001a3533051304f0603551d0104483046801015432db116b35d07e4ba89edb2469d7aa120301e"
+ "311c301a060355040313135253414b65795472616e73666572436170693182105d2ffff863babc9b4d3c80ab178a4cca3009"
+ "06052b0e03021d05000381810081e5535d8eceef265acbc82f6c5f8bc9d84319265f3ccf23369fa533c8dc1938952c593166"
+ "2d9ecd8b1e7b81749e48468167e2fce3d019fa70d54646975b6dc2a3ba72d5a5274c1866da6d7a5df47938e034a075d11957"
+ "d653b5c78e5291e4401045576f6d4eda81bef3c369af56121e49a083c8d1adb09f291822e99a4296463181d73081d4020101"
+ "3032301e311c301a060355040313135253414b65795472616e73666572436170693102105d2ffff863babc9b4d3c80ab178a"
+ "4cca300906052b0e03021a0500300d06092a864886f70d010101050004818031a718ea1483c88494661e1d3dedfea0a3d97e"
+ "eb64c3e093a628b257c0cfc183ecf11697ac84f2af882b8de0c793572af38dc15d1b6f3d8f2392ba1cc71210e177c146fd16"
+ "b77a583b6411e801d7a2640d612f2fe99d87e9718e0e505a7ab9536d71dbde329da21816ce7da1416a74a3e0a112b86b33af"
+ "336a2ba6ae2443d0ab").HexToByteArray();
ContentInfo expectedContentInfo = new ContentInfo(new Oid(Oids.Pkcs7Signed), expectedContent);
byte[] encodedMessage = Convert.FromBase64String(
"MIIERwYJKoZIhvcNAQcDoIIEODCCBDQCAQAxgcwwgckCAQAwMjAeMRwwGgYDVQQDExNSU0FLZXlU" +
"cmFuc2ZlckNhcGkxAhBdL//4Y7q8m008gKsXikzKMA0GCSqGSIb3DQEBAQUABIGAngdmU69zGsgJ" +
"mx+hXmTjlefr1oazKRK8VGOeqNMm++J3yHxwz68CLoN4FIEyS/HE3NQE6qb3M80HOpk5fmVVMw7Z" +
"3mrsZlPLOEjJIxEFqAC/JFEzvyE/BL+1OvwRoHpxHsAvZNlz5f9g18wQVE7X5TkkbOJV/6F2disK" +
"H0jik68wggNeBgkqhkiG9w0BBwIwHQYJYIZIAWUDBAEqBBDr3I8NYAnetX+2h9D/nVAggIIDMOlW" +
"7mDuuScuXhCXgZaPy0/zEWy/sYDzxhj1G1X2qBwhB7m6Ez6giibAEYwfRNYaOiVIitIJAUU9LSKg" +
"n0FL1o0eCcgvo04w+zoaBH8pFFk78kuR+T73kflz+O3Eno1pIFpy+2cz2B0QvQSC7lYikbZ4J+/C" +
"7F/uqRoK7sdafNdyUnKhDL+vvP6ToGf9C4g0TjoFEC2ycyJxIBh1F57pqjht6HMQcYm+/fQoBtkt" +
"NrvZxJPlBhbQad/9pSCd0G6NDoPnDuFAicaxGVa7yI2BbvGTCc6NSnbdCzv2EgvsI10Yko+XO4/i" +
"oPnk9pquZBzC3p61XRKbBDrd5RsbkvPDXUHJKD5NQ3W3z9Bnc3bjNyilgDSIB01dE4AcWzdg+RGb" +
"TA7iAbAQKp2zjxb/prmxw1mhO9g6OkDovSTqmQQt7MlHFYFcX9wH8yEe+huIechmiy7famofluJX" +
"vBIz4m3JozlodyNX0nu9QwW58WWcFu6OyoPjFhlB+tLIHUElq9/AAEgwwgfsAj6jEQaHiFG+CYSJ" +
"RjX9+DHFJXMDyzW+eJw8Z/mvbZzzKF553xlAGpfUHHq4CywTyVTHn4nu9HPOeFzoirj1lzFvqmQd" +
"Dgp3T8NOPrns9ZIUBmdNNs/vUxNZqEeN4d0nD5lBG4aZnjsxr4i25rR3Jpe3kKrFtJQ74efkRM37" +
"1ntz9HGiA95G41fuaMw7lgOOfTL+AENNvwRGRCAhinajvQLDkFEuX5ErTtmBxJWU3ZET46u/vRiK" +
"NiRteFiN0hLv1jy+RJK+d+B/QEH3FeVMm3Tz5ll2LfO2nn/QR51hth7qFsvtFpwQqkkhMac6dMf/" +
"bb62pZY15U3y2x5jSn+MZVrNbL4ZK/JO5JFomqKVRjLH1/IZ+kuFNaaTrKFWB4U2gxrMdcjMCZvx" +
"ylbuf01Ajxo74KhPY9sIRztG4BU8ZaE69Ke50wJTE3ulm+g6hzNECdQS/yjuA8AUReGRj2NH/U4M" +
"lEUiR/rMHB/Mq/Vj6lsRFEVxHJSzek6jvrQ4UzVgWGrH4KnP3Rca8CfBTQX79RcZPu+0kI3KI+4H" +
"0Q+UBbb72FHnWsw3uqPEyA==");
CertLoader certLoader = Certificates.RSAKeyTransferCapi1;
VerifySimpleDecrypt(encodedMessage, certLoader, expectedContentInfo);
}
[Fact]
[OuterLoop(/* Leaks key on disk if interrupted */)]
public void TestDecryptSimple_Pkcs7Signed_GeneratedOnLinux()
{
byte[] expectedContent =
("3082032506092a864886f70d010702a082031630820312020101310b300906052b0e03021a0500301206092a864886f70d01"
+ "0701a0050403010203a08202103082020c30820179a00302010202105d2ffff863babc9b4d3c80ab178a4cca300906052b0e"
+ "03021d0500301e311c301a060355040313135253414b65795472616e736665724361706931301e170d313530343135303730"
+ "3030305a170d3235303431353037303030305a301e311c301a060355040313135253414b65795472616e7366657243617069"
+ "3130819f300d06092a864886f70d010101050003818d0030818902818100aa272700586c0cc41b05c65c7d846f5a2bc27b03"
+ "e301c37d9bff6d75b6eb6671ba9596c5c63ba2b1af5c318d9ca39e7400d10c238ac72630579211b86570d1a1d44ec86aa8f6"
+ "c9d2b4e283ea3535923f398a312a23eaeacd8d34faaca965cd910b37da4093ef76c13b337c1afab7d1d07e317b41a336baa4"
+ "111299f99424408d0203010001a3533051304f0603551d0104483046801015432db116b35d07e4ba89edb2469d7aa120301e"
+ "311c301a060355040313135253414b65795472616e73666572436170693182105d2ffff863babc9b4d3c80ab178a4cca3009"
+ "06052b0e03021d05000381810081e5535d8eceef265acbc82f6c5f8bc9d84319265f3ccf23369fa533c8dc1938952c593166"
+ "2d9ecd8b1e7b81749e48468167e2fce3d019fa70d54646975b6dc2a3ba72d5a5274c1866da6d7a5df47938e034a075d11957"
+ "d653b5c78e5291e4401045576f6d4eda81bef3c369af56121e49a083c8d1adb09f291822e99a4296463181d73081d4020101"
+ "3032301e311c301a060355040313135253414b65795472616e73666572436170693102105d2ffff863babc9b4d3c80ab178a"
+ "4cca300906052b0e03021a0500300d06092a864886f70d010101050004818031a718ea1483c88494661e1d3dedfea0a3d97e"
+ "eb64c3e093a628b257c0cfc183ecf11697ac84f2af882b8de0c793572af38dc15d1b6f3d8f2392ba1cc71210e177c146fd16"
+ "b77a583b6411e801d7a2640d612f2fe99d87e9718e0e505a7ab9536d71dbde329da21816ce7da1416a74a3e0a112b86b33af"
+ "336a2ba6ae2443d0ab").HexToByteArray();
ContentInfo expectedContentInfo = new ContentInfo(new Oid(Oids.Pkcs7Signed), expectedContent);
byte[] encodedMessage = Convert.FromBase64String(
"MIIERwYJKoZIhvcNAQcDoIIEODCCBDQCAQAxgcwwgckCAQAwMjAeMRwwGgYDVQQDExNSU0FLZXlU" +
"cmFuc2ZlckNhcGkxAhBdL//4Y7q8m008gKsXikzKMA0GCSqGSIb3DQEBAQUABIGAfsH5F4ZlwIcH" +
"nzqn8sOn+ZwK884en7HZrQbgEfedy5ti0ituKn70yTDz4iuNJtpguukCfCAsOT/n3eQn+T6etIa9" +
"byRGQst3F6QtgjAzdb5P1N6c5Mpz1o6k0mbNP/f0FqAaNtuAOnYwlEMwWOz9x4eEYpOhhlc6agRG" +
"qWItNVgwggNeBgkqhkiG9w0BBwIwHQYJYIZIAWUDBAEqBBCA8qaTiT+6IkrO8Ks9WOBggIIDMIkr" +
"7OGlPd3CfzO2CfJA3Sis/1ulDm1ioMCS9V5kLHVx4GWDETORG/YTPA54luxJkvIdU5VwO86+QuXf" +
"rgaly38XHTLZv+RBxUwCaWI0pgvaykEki5CnDu4j9uRQxqz6iU5bY6SKxG3bwcnUzGhWFdQVcNJn" +
"xzuMEcbrix5zfqmoeqemaYyqVqgMPNOnc5kmMOqHrha76qMdbYOSpwx81zYwstBlg+S9+AgOMR+W" +
"qrV9aXJTovjiJEVHPEPJFx0v/wCthhXso51mSU091Cs8qVfvokzlzXcK2dPF5d8EdmZCcmHsoq35" +
"/DfAL4DkfKucwiP9W7rT1a2BmVMquFTMI+KXyDvNhMVasjhKq5eM2G+oUDc3kGa3akaPZ+hNEHA+" +
"BNAS7iIpRft2GMNfTqpkBqnS6pB0+SSf02/JVkcFuHXZ9oZJsvZRm8M1i4WdVauBJ34rInQBdhaO" +
"yaFDx69tBvolclYnMzvdHLiP2TZbiR6kM0vqD1DGjEHNDE+m/jxL7HXcNotW84J9CWlDnm9zaNhL" +
"sB4PJNiNjKhkAsO+2HaNWlEPrmgmWKvNi/Qyrz1qUryqz2/2HGrFDqmjTeEf1+yy35N3Pqv5uvAj" +
"f/ySihknnAh77nI0yOPy0Uto+hbO+xraeujrEifaII8izcz6UG6LHNPxOyscne7HNcqPSAFLsNFJ" +
"1oOlKO0SwhPkGQsk4W5tjVfvLvJiPNcL7SY/eof4vVsRRwX6Op5WUjhJIagY1Vij+4hOcn5TqdmU" +
"OZDh/FC3x4DI556BeMfbWxHNlGvptROQwQ6BasfdiVWCWzMHwLpz27Y47vKbMQ+8TL9668ilT83f" +
"6eo6mHZ590pzuDB+gFrjEK44ov0rvHBK5jHwnSObQvChN0ElizWBdMSUbx9SkcnReH6Fd29SSXdu" +
"RaVspnhmFNXWg7qGYHpEChnIGSr/WIKETZ84f7FRCxCNSYoQtrHs0SskiEGJYEbB6KDMFimEZ4YN" +
"b4cV8VLC9Pxa1Qe1Oa05FBzG2DAP2PfObeKR34afF5wo6vIZfQE0WWoPo9YS326vz1iA5rE0F6qw" +
"zCNmZl8+rW6x73MTEcWhvg==");
CertLoader certLoader = Certificates.RSAKeyTransferCapi1;
VerifySimpleDecrypt(encodedMessage, certLoader, expectedContentInfo);
}
[Fact]
public void DecryptEnvelopedOctetStringWithDefiniteLength()
{
// enveloped content consists of 5 bytes: <id: 1 byte><length: 1 byte><content: 3 bytes>
// <id>:
// 04 - Octet string
// 30 - Sequence
// <length>: 03 => length is 3 (encoded with definite length)
// <content>: 010203
// Note: we expect invalid ASN.1 sequence
byte[] content = "0403010203".HexToByteArray();
byte[] expectedContent = "3003010203".HexToByteArray();
ContentInfo contentInfo = new ContentInfo(new Oid(Oids.Pkcs7Enveloped), content);
ContentInfo expectedContentInfo = new ContentInfo(new Oid(Oids.Pkcs7Enveloped), expectedContent);
TestSimpleDecrypt_RoundTrip(Certificates.RSAKeyTransferCapi1, contentInfo, Oids.Aes256, SubjectIdentifierType.IssuerAndSerialNumber, expectedContentInfo);
}
[Fact]
public void DecryptEnvelopedOctetStringWithInefficientlyEncodedLength()
{
// enveloped content consists of 5 or 6 bytes: <id: 1 byte><length: 1 or 2 bytes><content: 3 bytes>
// <id>:
// 04 - Octet string
// 30 - Sequence
// <length>: 03 => length is 3 (encoded with definite length)
// 81 03 => length is 3 (encoded with inefficiently encoded length)
// <content>: 010203
// Note: we expect invalid ASN.1 sequence
byte[] content = "048103010203".HexToByteArray();
byte[] expectedContent = "3003010203".HexToByteArray();
ContentInfo contentInfo = new ContentInfo(new Oid(Oids.Pkcs7Enveloped), content);
ContentInfo expectedContentInfo = new ContentInfo(new Oid(Oids.Pkcs7Enveloped), expectedContent);
TestSimpleDecrypt_RoundTrip(Certificates.RSAKeyTransferCapi1, contentInfo, Oids.Aes256, SubjectIdentifierType.IssuerAndSerialNumber, expectedContentInfo);
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "netfx does not allow it")]
public void DecryptEnvelopedEmptyArray()
{
byte[] content = Array.Empty<byte>();
byte[] expectedContent = "3000".HexToByteArray();
ContentInfo contentInfo = new ContentInfo(new Oid(Oids.Pkcs7Enveloped), content);
ContentInfo expectedContentInfo = new ContentInfo(new Oid(Oids.Pkcs7Enveloped), expectedContent);
TestSimpleDecrypt_RoundTrip(Certificates.RSAKeyTransferCapi1, contentInfo, Oids.Aes256, SubjectIdentifierType.IssuerAndSerialNumber, expectedContentInfo);
}
[Fact]
public void DecryptEnvelopedEmptyOctetString()
{
byte[] content = "0400".HexToByteArray();
byte[] expectedContent = "3000".HexToByteArray();
ContentInfo contentInfo = new ContentInfo(new Oid(Oids.Pkcs7Enveloped), content);
ContentInfo expectedContentInfo = new ContentInfo(new Oid(Oids.Pkcs7Enveloped), expectedContent);
TestSimpleDecrypt_RoundTrip(Certificates.RSAKeyTransferCapi1, contentInfo, Oids.Aes256, SubjectIdentifierType.IssuerAndSerialNumber, expectedContentInfo);
}
[Fact]
public void DecryptEnvelopedOctetStringWithExtraData()
{
byte[] content = "04010203".HexToByteArray();
byte[] expectedContent = "300102".HexToByteArray();
ContentInfo contentInfo = new ContentInfo(new Oid(Oids.Pkcs7Enveloped), content);
ContentInfo expectedContentInfo = new ContentInfo(new Oid(Oids.Pkcs7Enveloped), expectedContent);
TestSimpleDecrypt_RoundTrip(Certificates.RSAKeyTransferCapi1, contentInfo, Oids.Aes256, SubjectIdentifierType.IssuerAndSerialNumber, expectedContentInfo);
}
[Fact]
public void DecryptEnvelopedDataWithNonPkcs7Oid()
{
byte[] content = "3003010203".HexToByteArray();
string nonPkcs7Oid = "0.0";
ContentInfo contentInfo = new ContentInfo(new Oid(nonPkcs7Oid), content);
TestSimpleDecrypt_RoundTrip(Certificates.RSAKeyTransferCapi1, contentInfo, Oids.Aes256, SubjectIdentifierType.IssuerAndSerialNumber);
}
[ConditionalFact(nameof(SupportsIndefiniteLengthEncoding))]
public void DecryptEnvelopedEmptyOctetStringWithIndefiniteLength()
{
byte[] content = "30800000".HexToByteArray();
byte[] expectedContent = "3000".HexToByteArray();
ContentInfo contentInfo = new ContentInfo(new Oid(Oids.Pkcs7Enveloped), content);
ContentInfo expectedContentInfo = new ContentInfo(new Oid(Oids.Pkcs7Enveloped), expectedContent);
TestSimpleDecrypt_RoundTrip(Certificates.RSAKeyTransferCapi1, contentInfo, Oids.Aes256, SubjectIdentifierType.IssuerAndSerialNumber, expectedContentInfo);
}
[ConditionalFact(nameof(SupportsIndefiniteLengthEncoding))]
public void DecryptEnvelopedOctetStringWithIndefiniteLength()
{
byte[] content = "308004000000".HexToByteArray();
byte[] expectedContent = "30020400".HexToByteArray();
ContentInfo contentInfo = new ContentInfo(new Oid(Oids.Pkcs7Enveloped), content);
ContentInfo expectedContentInfo = new ContentInfo(new Oid(Oids.Pkcs7Enveloped), expectedContent);
TestSimpleDecrypt_RoundTrip(Certificates.RSAKeyTransferCapi1, contentInfo, Oids.Aes256, SubjectIdentifierType.IssuerAndSerialNumber, expectedContentInfo);
}
private void TestSimpleDecrypt_RoundTrip(CertLoader certLoader, ContentInfo contentInfo, string algorithmOidValue, SubjectIdentifierType type, ContentInfo expectedContentInfo = null)
{
// Deep-copy the contentInfo since the real ContentInfo doesn't do this. This defends against a bad implementation changing
// our "expectedContentInfo" to match what it produces.
expectedContentInfo = expectedContentInfo ?? new ContentInfo(new Oid(contentInfo.ContentType), (byte[])(contentInfo.Content.Clone()));
string certSubjectName;
byte[] encodedMessage;
byte[] originalCopy = (byte[])(contentInfo.Content.Clone());
using (X509Certificate2 certificate = certLoader.GetCertificate())
{
certSubjectName = certificate.Subject;
AlgorithmIdentifier alg = new AlgorithmIdentifier(new Oid(algorithmOidValue));
EnvelopedCms ecms = new EnvelopedCms(contentInfo, alg);
CmsRecipient cmsRecipient = new CmsRecipient(type, certificate);
ecms.Encrypt(cmsRecipient);
Assert.Equal(originalCopy.ByteArrayToHex(), ecms.ContentInfo.Content.ByteArrayToHex());
encodedMessage = ecms.Encode();
}
// We don't pass "certificate" down because it's expected that the certificate used for encrypting doesn't have a private key (part of the purpose of this test is
// to ensure that you don't need the recipient's private key to encrypt.) The decrypt phase will have to locate the matching cert with the private key.
VerifySimpleDecrypt(encodedMessage, certLoader, expectedContentInfo);
}
private void VerifySimpleDecrypt(byte[] encodedMessage, CertLoader certLoader, ContentInfo expectedContent)
{
EnvelopedCms ecms = new EnvelopedCms();
ecms.Decode(encodedMessage);
using (X509Certificate2 cert = certLoader.TryGetCertificateWithPrivateKey())
{
if (cert == null)
return; // Sorry - CertLoader is not configured to load certs with private keys - we've tested as much as we can.
#if netcoreapp // API not present on netfx
if (_useExplicitPrivateKey)
{
using (X509Certificate2 pubCert = certLoader.GetCertificate())
{
RecipientInfo recipient = ecms.RecipientInfos.Cast<RecipientInfo>().Where((r) => r.RecipientIdentifier.MatchesCertificate(cert)).Single();
ecms.Decrypt(recipient, cert.PrivateKey);
}
}
else
#endif
{
X509Certificate2Collection extraStore = new X509Certificate2Collection(cert);
ecms.Decrypt(extraStore);
}
ContentInfo contentInfo = ecms.ContentInfo;
Assert.Equal(expectedContent.ContentType.Value, contentInfo.ContentType.Value);
Assert.Equal(expectedContent.Content.ByteArrayToHex(), contentInfo.Content.ByteArrayToHex());
}
}
}
}
| |
// 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 exists to contain miscellaneous module-level attributes
** and other miscellaneous stuff.
**
**
**
===========================================================*/
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
using System.Collections.Generic;
using System.Reflection;
using System.Security;
using System.StubHelpers;
using System.Threading.Tasks;
#if FEATURE_COMINTEROP
using System.Runtime.InteropServices.WindowsRuntime;
[assembly:Guid("BED7F4EA-1A96-11d2-8F08-00A0C9A6186D")]
// The following attribute are required to ensure COM compatibility.
[assembly:System.Runtime.InteropServices.ComCompatibleVersion(1, 0, 3300, 0)]
[assembly:System.Runtime.InteropServices.TypeLibVersion(2, 4)]
#endif // FEATURE_COMINTEROP
[assembly:DefaultDependencyAttribute(LoadHint.Always)]
// mscorlib would like to have its literal strings frozen if possible
[assembly: System.Runtime.CompilerServices.StringFreezingAttribute()]
namespace System
{
static class Internal
{
// This method is purely an aid for NGen to statically deduce which
// instantiations to save in the ngen image.
// Otherwise, the JIT-compiler gets used, which is bad for working-set.
// Note that IBC can provide this information too.
// However, this helps in keeping the JIT-compiler out even for
// test scenarios which do not use IBC.
// This can be removed after V2, when we implement other schemes
// of keeping the JIT-compiler out for generic instantiations.
// Method marked as NoOptimization as we don't want the JIT to
// inline any methods or take any short-circuit paths since the
// instantiation closure process is driven by "fixup" references
// left in the final code stream.
[MethodImplAttribute(MethodImplOptions.NoOptimization)]
static void CommonlyUsedGenericInstantiations()
{
// Make absolutely sure we include some of the most common
// instantiations here in mscorlib's ngen image.
// Note that reference type instantiations are already included
// automatically for us.
// Need to sort non null, len > 1 array or paths will short-circuit
Array.Sort<double>(new double[1]);
Array.Sort<int>(new int[1]);
Array.Sort<IntPtr>(new IntPtr[1]);
new ArraySegment<byte>(new byte[1], 0, 0);
new Dictionary<Char, Object>();
new Dictionary<Guid, Byte>();
new Dictionary<Guid, Object>();
new Dictionary<Guid, Guid>(); // Added for Visual Studio 2010
new Dictionary<Int16, IntPtr>();
new Dictionary<Int32, Byte>();
new Dictionary<Int32, Int32>();
new Dictionary<Int32, Object>();
new Dictionary<IntPtr, Boolean>();
new Dictionary<IntPtr, Int16>();
new Dictionary<Object, Boolean>();
new Dictionary<Object, Char>();
new Dictionary<Object, Guid>();
new Dictionary<Object, Int32>();
new Dictionary<Object, Int64>(); // Added for Visual Studio 2010
new Dictionary<uint, WeakReference>(); // NCL team needs this
new Dictionary<Object, UInt32>();
new Dictionary<UInt32, Object>();
new Dictionary<Int64, Object>();
#if FEATURE_CORECLR
// to genereate mdil for Dictionary instantiation when key is user defined value type
new Dictionary<Guid, Int32>();
#endif
// Microsoft.Windows.Design
new Dictionary<System.Reflection.MemberTypes, Object>();
new EnumEqualityComparer<System.Reflection.MemberTypes>();
// Microsoft.Expression.DesignModel
new Dictionary<Object, KeyValuePair<Object,Object>>();
new Dictionary<KeyValuePair<Object,Object>, Object>();
NullableHelper<Boolean>();
NullableHelper<Byte>();
NullableHelper<Char>();
NullableHelper<DateTime>();
NullableHelper<Decimal>();
NullableHelper<Double>();
NullableHelper<Guid>();
NullableHelper<Int16>();
NullableHelper<Int32>();
NullableHelper<Int64>();
NullableHelper<Single>();
NullableHelper<TimeSpan>();
NullableHelper<DateTimeOffset>(); // For SQL
new List<Boolean>();
new List<Byte>();
new List<Char>();
new List<DateTime>();
new List<Decimal>();
new List<Double>();
new List<Guid>();
new List<Int16>();
new List<Int32>();
new List<Int64>();
new List<TimeSpan>();
new List<SByte>();
new List<Single>();
new List<UInt16>();
new List<UInt32>();
new List<UInt64>();
new List<IntPtr>();
new List<KeyValuePair<Object, Object>>();
new List<GCHandle>(); // NCL team needs this
new List<DateTimeOffset>();
new KeyValuePair<Char, UInt16>('\0', UInt16.MinValue);
new KeyValuePair<UInt16, Double>(UInt16.MinValue, Double.MinValue);
new KeyValuePair<Object, Int32>(String.Empty, Int32.MinValue);
new KeyValuePair<Int32, Int32>(Int32.MinValue, Int32.MinValue);
SZArrayHelper<Boolean>(null);
SZArrayHelper<Byte>(null);
SZArrayHelper<DateTime>(null);
SZArrayHelper<Decimal>(null);
SZArrayHelper<Double>(null);
SZArrayHelper<Guid>(null);
SZArrayHelper<Int16>(null);
SZArrayHelper<Int32>(null);
SZArrayHelper<Int64>(null);
SZArrayHelper<TimeSpan>(null);
SZArrayHelper<SByte>(null);
SZArrayHelper<Single>(null);
SZArrayHelper<UInt16>(null);
SZArrayHelper<UInt32>(null);
SZArrayHelper<UInt64>(null);
SZArrayHelper<DateTimeOffset>(null);
SZArrayHelper<CustomAttributeTypedArgument>(null);
SZArrayHelper<CustomAttributeNamedArgument>(null);
#if FEATURE_CORECLR
#pragma warning disable 4014
// This is necessary to generate MDIL for AsyncVoidMethodBuilder
AsyncHelper<int>();
AsyncHelper2<int>();
AsyncHelper3();
#pragma warning restore 4014
#endif
}
static T NullableHelper<T>() where T : struct
{
Nullable.Compare<T>(null, null);
Nullable.Equals<T>(null, null);
Nullable<T> nullable = new Nullable<T>();
return nullable.GetValueOrDefault();
}
static void SZArrayHelper<T>(SZArrayHelper oSZArrayHelper)
{
// Instantiate common methods for IList implementation on Array
oSZArrayHelper.get_Count<T>();
oSZArrayHelper.get_Item<T>(0);
oSZArrayHelper.GetEnumerator<T>();
}
#if FEATURE_CORECLR
// System.Runtime.CompilerServices.AsyncVoidMethodBuilder
// System.Runtime.CompilerServices.TaskAwaiter
static async void AsyncHelper<T>()
{
await Task.Delay(1);
}
// System.Runtime.CompilerServices.AsyncTaskMethodBuilder`1[System.__Canon]
// System.Runtime.CompilerServices.TaskAwaiter'[System.__Canon]
static async Task<String> AsyncHelper2<T>()
{
return await Task.FromResult<string>("");
}
// System.Runtime.CompilerServices.AsyncTaskMethodBuilder
// System.Runtime.CompilerServices.AsyncTaskMethodBuilder'1[VoidTaskResult]
static async Task AsyncHelper3()
{
await Task.FromResult<string>("");
}
#endif
#if FEATURE_COMINTEROP
// Similar to CommonlyUsedGenericInstantiations but for instantiations of marshaling stubs used
// for WinRT redirected interfaces. Note that we do care about reference types here as well because,
// say, IList<string> and IList<object> cannot share marshaling stubs.
// The methods below "call" most commonly used stub methods on redirected interfaces and take arguments
// typed as matching instantiations of mscorlib copies of WinRT interfaces (IIterable<T>, IVector<T>,
// IMap<K, V>, ...) which is necessary to generate all required IL stubs.
[SecurityCritical]
static void CommonlyUsedWinRTRedirectedInterfaceStubs()
{
WinRT_IEnumerable<byte>(null, null, null);
WinRT_IEnumerable<char>(null, null, null);
WinRT_IEnumerable<short>(null, null, null);
WinRT_IEnumerable<ushort>(null, null, null);
WinRT_IEnumerable<int>(null, null, null);
WinRT_IEnumerable<uint>(null, null, null);
WinRT_IEnumerable<long>(null, null, null);
WinRT_IEnumerable<ulong>(null, null, null);
WinRT_IEnumerable<float>(null, null, null);
WinRT_IEnumerable<double>(null, null, null);
// The underlying WinRT types for shared instantiations have to be referenced explicitly.
// They are not guaranteeed to be created indirectly because of generic code sharing.
WinRT_IEnumerable<string>(null, null, null); typeof(IIterable<string>).ToString(); typeof(IIterator<string>).ToString();
WinRT_IEnumerable<object>(null, null, null); typeof(IIterable<object>).ToString(); typeof(IIterator<object>).ToString();
WinRT_IList<int>(null, null, null, null);
WinRT_IList<string>(null, null, null, null); typeof(IVector<string>).ToString();
WinRT_IList<object>(null, null, null, null); typeof(IVector<object>).ToString();
WinRT_IReadOnlyList<int>(null, null, null);
WinRT_IReadOnlyList<string>(null, null, null); typeof(IVectorView<string>).ToString();
WinRT_IReadOnlyList<object>(null, null, null); typeof(IVectorView<object>).ToString();
WinRT_IDictionary<string, int>(null, null, null, null); typeof(IMap<string, int>).ToString();
WinRT_IDictionary<string, string>(null, null, null, null); typeof(IMap<string, string>).ToString();
WinRT_IDictionary<string, object>(null, null, null, null); typeof(IMap<string, object>).ToString();
WinRT_IDictionary<object, object>(null, null, null, null); typeof(IMap<object, object>).ToString();
WinRT_IReadOnlyDictionary<string, int>(null, null, null, null); typeof(IMapView<string, int>).ToString();
WinRT_IReadOnlyDictionary<string, string>(null, null, null, null); typeof(IMapView<string, string>).ToString();
WinRT_IReadOnlyDictionary<string, object>(null, null, null, null); typeof(IMapView<string, object>).ToString();
WinRT_IReadOnlyDictionary<object, object>(null, null, null, null); typeof(IMapView<object, object>).ToString();
WinRT_Nullable<bool>();
WinRT_Nullable<byte>();
WinRT_Nullable<int>();
WinRT_Nullable<uint>();
WinRT_Nullable<long>();
WinRT_Nullable<ulong>();
WinRT_Nullable<float>();
WinRT_Nullable<double>();
}
[SecurityCritical]
static void WinRT_IEnumerable<T>(IterableToEnumerableAdapter iterableToEnumerableAdapter, EnumerableToIterableAdapter enumerableToIterableAdapter, IIterable<T> iterable)
{
// instantiate stubs for the one method on IEnumerable<T> and the one method on IIterable<T>
iterableToEnumerableAdapter.GetEnumerator_Stub<T>();
enumerableToIterableAdapter.First_Stub<T>();
}
[SecurityCritical]
static void WinRT_IList<T>(VectorToListAdapter vectorToListAdapter, VectorToCollectionAdapter vectorToCollectionAdapter, ListToVectorAdapter listToVectorAdapter, IVector<T> vector)
{
WinRT_IEnumerable<T>(null, null, null);
// instantiate stubs for commonly used methods on IList<T> and ICollection<T>
vectorToListAdapter.Indexer_Get<T>(0);
vectorToListAdapter.Indexer_Set<T>(0, default(T));
vectorToListAdapter.Insert<T>(0, default(T));
vectorToListAdapter.RemoveAt<T>(0);
vectorToCollectionAdapter.Count<T>();
vectorToCollectionAdapter.Add<T>(default(T));
vectorToCollectionAdapter.Clear<T>();
// instantiate stubs for commonly used methods on IVector<T>
listToVectorAdapter.GetAt<T>(0);
listToVectorAdapter.Size<T>();
listToVectorAdapter.SetAt<T>(0, default(T));
listToVectorAdapter.InsertAt<T>(0, default(T));
listToVectorAdapter.RemoveAt<T>(0);
listToVectorAdapter.Append<T>(default(T));
listToVectorAdapter.RemoveAtEnd<T>();
listToVectorAdapter.Clear<T>();
}
[SecurityCritical]
static void WinRT_IReadOnlyCollection<T>(VectorViewToReadOnlyCollectionAdapter vectorViewToReadOnlyCollectionAdapter)
{
WinRT_IEnumerable<T>(null, null, null);
// instantiate stubs for commonly used methods on IReadOnlyCollection<T>
vectorViewToReadOnlyCollectionAdapter.Count<T>();
}
[SecurityCritical]
static void WinRT_IReadOnlyList<T>(IVectorViewToIReadOnlyListAdapter vectorToListAdapter, IReadOnlyListToIVectorViewAdapter listToVectorAdapter, IVectorView<T> vectorView)
{
WinRT_IEnumerable<T>(null, null, null);
WinRT_IReadOnlyCollection<T>(null);
// instantiate stubs for commonly used methods on IReadOnlyList<T>
vectorToListAdapter.Indexer_Get<T>(0);
// instantiate stubs for commonly used methods on IVectorView<T>
listToVectorAdapter.GetAt<T>(0);
listToVectorAdapter.Size<T>();
}
[SecurityCritical]
static void WinRT_IDictionary<K, V>(MapToDictionaryAdapter mapToDictionaryAdapter, MapToCollectionAdapter mapToCollectionAdapter, DictionaryToMapAdapter dictionaryToMapAdapter, IMap<K, V> map)
{
WinRT_IEnumerable<KeyValuePair<K, V>>(null, null, null);
// instantiate stubs for commonly used methods on IDictionary<K, V> and ICollection<KeyValuePair<K, V>>
V dummy;
mapToDictionaryAdapter.Indexer_Get<K, V>(default(K));
mapToDictionaryAdapter.Indexer_Set<K, V>(default(K), default(V));
mapToDictionaryAdapter.ContainsKey<K, V>(default(K));
mapToDictionaryAdapter.Add<K, V>(default(K), default(V));
mapToDictionaryAdapter.Remove<K, V>(default(K));
mapToDictionaryAdapter.TryGetValue<K, V>(default(K), out dummy);
mapToCollectionAdapter.Count<K, V>();
mapToCollectionAdapter.Add<K, V>(new KeyValuePair<K, V>(default(K), default(V)));
mapToCollectionAdapter.Clear<K, V>();
// instantiate stubs for commonly used methods on IMap<K, V>
dictionaryToMapAdapter.Lookup<K, V>(default(K));
dictionaryToMapAdapter.Size<K, V>();
dictionaryToMapAdapter.HasKey<K, V>(default(K));
dictionaryToMapAdapter.Insert<K, V>(default(K), default(V));
dictionaryToMapAdapter.Remove<K, V>(default(K));
dictionaryToMapAdapter.Clear<K, V>();
}
[SecurityCritical]
static void WinRT_IReadOnlyDictionary<K, V>(IMapViewToIReadOnlyDictionaryAdapter mapToDictionaryAdapter, IReadOnlyDictionaryToIMapViewAdapter dictionaryToMapAdapter, IMapView<K, V> mapView, MapViewToReadOnlyCollectionAdapter mapViewToReadOnlyCollectionAdapter)
{
WinRT_IEnumerable<KeyValuePair<K, V>>(null, null, null);
WinRT_IReadOnlyCollection<KeyValuePair<K, V>>(null);
// instantiate stubs for commonly used methods on IReadOnlyDictionary<K, V>
V dummy;
mapToDictionaryAdapter.Indexer_Get<K, V>(default(K));
mapToDictionaryAdapter.ContainsKey<K, V>(default(K));
mapToDictionaryAdapter.TryGetValue<K, V>(default(K), out dummy);
// instantiate stubs for commonly used methods in IReadOnlyCollection<T>
mapViewToReadOnlyCollectionAdapter.Count<K, V>();
// instantiate stubs for commonly used methods on IMapView<K, V>
dictionaryToMapAdapter.Lookup<K, V>(default(K));
dictionaryToMapAdapter.Size<K, V>();
dictionaryToMapAdapter.HasKey<K, V>(default(K));
}
[SecurityCritical]
static void WinRT_Nullable<T>() where T : struct
{
Nullable<T> nullable = new Nullable<T>();
NullableMarshaler.ConvertToNative(ref nullable);
NullableMarshaler.ConvertToManagedRetVoid(IntPtr.Zero, ref nullable);
}
#endif // FEATURE_COMINTEROP
}
}
| |
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using DotVVM.Framework.Binding;
using DotVVM.Framework.Binding.Expressions;
using DotVVM.Framework.Compilation.Javascript;
using DotVVM.Framework.Utils;
namespace DotVVM.Framework.Controls
{
[ContainsDotvvmProperties]
[ControlMarkupOptions(AllowContent = true)]
[Newtonsoft.Json.JsonConverter(typeof(DotvvmControlDebugJsonConverter))]
public abstract class DotvvmBindableObject: IDotvvmObjectLike
{
private static readonly ConcurrentDictionary<Type, DotvvmProperty[]> declaredProperties = new ConcurrentDictionary<Type, DotvvmProperty[]>();
internal DotvvmControlProperties properties;
/// <summary>
/// Gets the collection of control property values.
/// </summary>
public DotvvmPropertyDictionary Properties =>
new DotvvmPropertyDictionary(this);
/// <summary>
/// Gets or sets whether this control should be rendered on the server.
/// </summary>
public virtual bool RenderOnServer
{
get { return (RenderMode)GetValue(RenderSettings.ModeProperty)! == RenderMode.Server; }
}
/// <summary>
/// Gets the parent control.
/// </summary>
[MarkupOptions(MappingMode = MappingMode.Exclude)]
public DotvvmBindableObject? Parent { get; set; }
// WORKAROUND: Roslyn is unable to cache the delegate itself
private static Func<Type, DotvvmProperty[]> _dotvvmProperty_ResolveProperties = DotvvmProperty.ResolveProperties;
/// <summary>
/// Gets all properties declared on this class or on any of its base classes.
/// </summary>
protected DotvvmProperty[] GetDeclaredProperties()
{
return declaredProperties.GetOrAdd(GetType(), _dotvvmProperty_ResolveProperties);
}
/// <summary>
/// Determines whether the specified property is set.
/// </summary>
public bool IsPropertySet(DotvvmProperty property, bool inherit = true)
{
return property.IsSet(this, inherit);
}
/// <summary>
/// Gets or sets a data context for the control and its children. All value and command bindings are evaluated in context of this value.
/// The DataContext is null in client-side templates.
/// </summary>
[BindingCompilationRequirements(
optional: new[] { typeof(Binding.Properties.SimplePathExpressionBindingProperty) })]
[MarkupOptions(AllowHardCodedValue = false)]
public object? DataContext
{
get { return GetValue(DataContextProperty); }
set { SetValue(DataContextProperty, value); }
}
DotvvmBindableObject IDotvvmObjectLike.Self => this;
public static readonly DotvvmProperty DataContextProperty =
DotvvmProperty.Register<object, DotvvmBindableObject>(c => c.DataContext, isValueInherited: true);
/// <summary> Returns the value of the specified property. If the property contains a binding, it is evaluted. </summary>
[return: MaybeNull]
public T GetValue<T>(DotvvmProperty property, bool inherit = true)
{
return (T)GetValue(property, inherit)!;
}
/// <summary> If the object is IBinding and the property is not of type IBinding, it is evaluated. </summary>
internal object? EvalPropertyValue(DotvvmProperty property, object? value)
{
if (property.IsBindingProperty) return value;
if (value is IBinding)
{
DotvvmBindableObject control = this;
// DataContext is always bound to it's parent, setting it right here is a bit faster
if (property == DataContextProperty)
control = control.Parent ?? throw new DotvvmControlException(this, "Cannot set DataContext binding on the root control");
// handle binding
if (value is IStaticValueBinding binding)
{
value = binding.Evaluate(control);
}
else if (value is ICommandBinding command)
{
value = command.GetCommandDelegate(control);
}
else
{
throw new NotSupportedException($"Cannot evaluate binding {value} of type {value.GetType().Name}.");
}
}
return value;
}
/// <summary>
/// Gets the value of a specified property. If the property contains a binding, it is evaluted.
/// </summary>
public virtual object? GetValue(DotvvmProperty property, bool inherit = true) =>
EvalPropertyValue(property, GetValueRaw(property, inherit));
/// <summary>
/// Gets the value or a binding object for a specified property.
/// </summary>
public virtual object? GetValueRaw(DotvvmProperty property, bool inherit = true)
{
return property.GetValue(this, inherit);
}
/// <summary> For internal use, public because it's used from our generated code. If want to use it, create the arguments using <see cref="PropertyImmutableHashtable.CreateTableWithValues{T}(DotvvmProperty[], T[])" /> </summary>
public void MagicSetValue(DotvvmProperty[] keys, object[] values, int hashSeed)
{
this.properties.AssignBulk(keys, values, hashSeed);
}
/// <summary> Sets the value of a specified property. </summary>
public void SetValue<T>(DotvvmProperty property, ValueOrBinding<T> valueOrBinding)
{
if (valueOrBinding.BindingOrDefault == null)
this.SetValue(property, valueOrBinding.BoxedValue);
else
this.SetBinding(property, valueOrBinding.BindingOrDefault);
}
/// <summary> Gets the value of a specified property. Bindings are always returned, not evaluated. </summary>
public ValueOrBinding<T> GetValueOrBinding<T>(DotvvmProperty property, bool inherit = true)
{
var value = this.GetValueRaw(property, inherit);
if (value is IBinding binding)
return new ValueOrBinding<T>(binding);
else return new ValueOrBinding<T>((T)value!);
}
/// <summary>
/// Sets the value of a specified property.
/// </summary>
public virtual void SetValue(DotvvmProperty property, object? value)
{
// "unbox" ValueOrBinding instances
value = ValueOrBindingExtensions.UnwrapToObject(value);
SetValueRaw(property, value);
}
/// <summary>
/// Sets the value of a specified property.
/// </summary>
public void SetValue<T>(DotvvmProperty property, T value)
where T: struct
{
SetValue(property, BoxingUtils.BoxGeneric(value));
}
/// <summary> Sets the value of specified property by updating the view model this property is bound to. Throws if the property does not contain binding </summary>
public void SetValueToSource(DotvvmProperty property, object? value)
{
if (value is IBinding newBinding)
throw new DotvvmControlException(this, $"Cannot set binding {value} to source.") { RelatedBinding = newBinding, RelatedProperty = property };
var binding = GetBinding(property);
if (binding is null)
throw new DotvvmControlException(this, $"Property {property} does not contain binding, so it's source cannot be updated.") { RelatedProperty = property };
if (binding is not IUpdatableValueBinding updatableValueBinding)
throw new DotvvmControlException(this, $"Cannot set source of binding {value}, it does not implement IUpdatableValueBinding.") { RelatedBinding = binding, RelatedProperty = property };
updatableValueBinding.UpdateSource(value, this);
}
/// <summary>
/// Sets the value or a binding to the specified property.
/// </summary>
public void SetValueRaw(DotvvmProperty property, object? value)
{
property.SetValue(this, value);
}
/// <summary>
/// Gets the binding set to a specified property. Returns null if the property is not set or if the value is not a binding.
/// </summary>
public IBinding? GetBinding(DotvvmProperty property, bool inherit = true)
=> GetValueRaw(property, inherit) as IBinding;
/// <summary>
/// Gets the value binding set to a specified property. Returns null if the property is not a binding, throws if the binding some kind of command.
/// </summary>
public IValueBinding? GetValueBinding(DotvvmProperty property, bool inherit = true)
{
var binding = GetBinding(property, inherit);
if (binding != null && !(binding is IStaticValueBinding)) // throw exception on incompatible binding types
{
throw new BindingHelper.BindingNotSupportedException(binding) { RelatedControl = this };
}
return binding as IValueBinding;
}
/// <summary> Returns a Javascript (knockout) expression representing value or binding of this property. </summary>
public ParametrizedCode GetJavascriptValue(DotvvmProperty property, bool inherit = true) =>
GetValueOrBinding<object>(property, inherit).GetParametrizedJsExpression(this);
/// <summary>
/// Gets the command binding set to a specified property. Returns null if the property is not a binding, throws if the binding is not command, controlCommand or staticCommand.
/// </summary>
public ICommandBinding? GetCommandBinding(DotvvmProperty property, bool inherit = true)
{
var binding = GetBinding(property, inherit);
if (binding != null && !(binding is ICommandBinding))
{
throw new BindingHelper.BindingNotSupportedException(binding) { RelatedControl = this };
}
return binding as ICommandBinding;
}
/// <summary>
/// Sets the binding to a specified property.
/// </summary>
public void SetBinding(DotvvmProperty property, IBinding? binding)
{
SetValueRaw(property, binding);
}
/// <summary>
/// Gets the hierarchy of all DataContext bindings from the root to current control.
/// </summary>
[Obsolete]
internal IEnumerable<IValueBinding> GetDataContextHierarchy()
{
var bindings = new List<IValueBinding>();
DotvvmBindableObject? current = this;
while (current != null)
{
var binding = current.GetValueBinding(DataContextProperty, false);
if (binding != null)
{
bindings.Add(binding);
}
current = current.Parent;
}
bindings.Reverse();
return bindings;
}
/// <summary>
/// Gets the closest control binding target. Returns null if the control is not found.
/// </summary>
public DotvvmBindableObject? GetClosestControlBindingTarget() =>
GetClosestControlBindingTarget(out int numberOfDataContextChanges);
/// <summary>
/// Gets the closest control binding target and returns number of DataContext changes since the target. Returns null if the control is not found.
/// </summary>
public DotvvmBindableObject? GetClosestControlBindingTarget(out int numberOfDataContextChanges) =>
(Parent ?? this).GetClosestWithPropertyValue(out numberOfDataContextChanges, (control, _) => (bool)control.GetValue(Internal.IsControlBindingTargetProperty)!);
/// <summary>
/// Gets the closest control binding target and returns number of DataContext changes since the target. Returns null if the control is not found.
/// </summary>
public DotvvmBindableObject? GetClosestControlValidationTarget(out int numberOfDataContextChanges) =>
GetClosestWithPropertyValue(out numberOfDataContextChanges, (c, _) => c.IsPropertySet(Validation.TargetProperty, false), includeDataContextChangeOnMatchedControl: false);
/// <summary>
/// Gets the closest control with specified property value and returns number of DataContext changes since the target. Returns null if the control is not found.
/// </summary>
public DotvvmBindableObject? GetClosestWithPropertyValue(out int numberOfDataContextChanges, Func<DotvvmBindableObject, DotvvmProperty?, bool> filterFunction, bool includeDataContextChangeOnMatchedControl = true, DotvvmProperty? delegateValue = null)
{
DotvvmBindableObject? current = this;
numberOfDataContextChanges = 0;
while (current != null)
{
var isMatched = false;
if (current.GetValueBinding(DataContextProperty, false) != null)
{
if (current.HasBinding(DataContextProperty) || current.HasBinding(Internal.PathFragmentProperty))
{
numberOfDataContextChanges++;
isMatched = true;
}
}
if (filterFunction(current, delegateValue))
{
if (isMatched && !includeDataContextChangeOnMatchedControl)
{
numberOfDataContextChanges--;
}
break;
}
current = current.Parent;
}
return current;
}
/// <summary> if this property contains any kind of binding. Note that the property value is not inherited. </summary>
public bool HasBinding(DotvvmProperty property)
{
return properties.TryGet(property, out var value) && value is IBinding;
}
/// <summary> if this property contains value binding. Note that the property value is not inherited. </summary>
public bool HasValueBinding(DotvvmProperty property)
{
return properties.TryGet(property, out var value) && value is IValueBinding;
}
/// <summary> if this property contains binding of the specified type. Note that the property value is not inherited. </summary>
public bool HasBinding<TBinding>(DotvvmProperty property)
where TBinding : IBinding
{
return properties.TryGet(property, out var value) && value is TBinding;
}
/// <summary>
/// Gets all bindings set on the control (excluding BindingProperties).
/// </summary>
public IEnumerable<KeyValuePair<DotvvmProperty, IBinding>> GetAllBindings()
{
return Properties.Where(p => p.Value is IBinding)
.Select(p => new KeyValuePair<DotvvmProperty, IBinding>(p.Key, (IBinding)p.Value!));
}
/// <summary>
/// Gets all ancestors of this control starting with the parent.
/// </summary>
/// <param name="includingThis">Returns also the caller control</param>
/// <param name="onlyWhenInChildren">Only enumerate until the parent has this control in <see cref="DotvvmControl.Children" />. Note that it may have a non-trivial performance penalty</param>
public IEnumerable<DotvvmBindableObject> GetAllAncestors(bool includingThis = false, bool onlyWhenInChildren = false)
{
var ancestor = includingThis ? this : Parent;
while (ancestor != null)
{
yield return ancestor;
if (onlyWhenInChildren)
{
if (!(ancestor.Parent is DotvvmControl parentControl && parentControl.Children.Contains(ancestor)))
yield break;
}
ancestor = ancestor.Parent;
}
}
/// <summary>
/// Gets the root of the control tree. The the control is properly rooted, the result value will be of type <see cref="Infrastructure.DotvvmView" />
/// </summary>
public DotvvmBindableObject GetRoot()
{
if (Parent == null) return this;
return GetAllAncestors().Last();
}
/// <summary> Does a deep clone of the control. </summary>
protected internal virtual DotvvmBindableObject CloneControl()
{
var newThis = (DotvvmBindableObject)this.MemberwiseClone();
this.properties.CloneInto(ref newThis.properties);
return newThis;
}
/// <summary>
/// Gets the logical children of this control (including controls that are not in the visual tree but which can contain command bindings).
/// </summary>
public virtual IEnumerable<DotvvmBindableObject> GetLogicalChildren()
{
return Enumerable.Empty<DotvvmBindableObject>();
}
/// <summary>
/// Copies the value of a property from this <see cref="DotvvmBindableObject"/> (source) to a property of another <see cref="DotvvmBindableObject"/> (target).
/// </summary>
/// <exception cref="DotvvmControlException">Gets thrown if copying fails and <paramref name="throwOnFailure"/> is set to true</exception>
/// <param name="sourceProperty">The <see cref="DotvvmProperty"/> whose value will be copied</param>
/// <param name="target">The <see cref="DotvvmBindableObject"/> that holds the value of the <paramref name="targetProperty"/></param>
/// <param name="targetProperty">The <see cref="DotvvmProperty"/> to which <paramref name="sourceProperty"/> will be copied</param>
/// <param name="throwOnFailure">Determines whether to throw an exception if copying fails</param>
protected void CopyProperty(DotvvmProperty sourceProperty, DotvvmBindableObject target, DotvvmProperty targetProperty, bool throwOnFailure = false)
{
if (throwOnFailure && !targetProperty.MarkupOptions.AllowBinding && !targetProperty.MarkupOptions.AllowHardCodedValue)
{
throw new DotvvmControlException(this, $"TargetProperty: {targetProperty.FullName} doesn't allow bindings nor hard coded values");
}
if (targetProperty.MarkupOptions.AllowBinding && HasBinding(sourceProperty))
{
target.SetBinding(targetProperty, GetBinding(sourceProperty));
}
else if (targetProperty.MarkupOptions.AllowHardCodedValue && IsPropertySet(sourceProperty))
{
target.SetValue(targetProperty, GetValue(sourceProperty));
}
else if (throwOnFailure)
{
throw new DotvvmControlException(this, $"Value of {sourceProperty.FullName} couldn't be copied to targetProperty: {targetProperty.FullName}, because {targetProperty.FullName} is not set.");
}
}
}
}
| |
using System;
using System.IO;
using System.Linq;
using System.Diagnostics;
using System.Collections.Generic;
using System.Text.RegularExpressions;
namespace NotFounds
{
public class Program
{
private static void Main(string[] Argv)
{
switch (Argv.Length)
{
case 1:
if (Argv[0].StartsWith("-"))
{
if (Argv[0] == "-v") ShowVersion();
else if (Argv[0] == "-h") ShowHelp();
else { ShowHelp(); Environment.Exit(1); }
}
else
{
var pl0 = new pl0();
pl0.Run(Argv[0]);
}
break;
case 2:
if (Argv[0] == "-t")
{
var pl0 = new pl0();
pl0.Run(Argv[1], true);
}
else { ShowHelp(); Environment.Exit(1); }
break;
case 3:
int time;
if (Argv[0] == "-t" && int.TryParse(Argv[1], out time) && time > 0)
{
var pl0 = new pl0(time);
pl0.Run(Argv[2], true);
}
else { ShowHelp(); Environment.Exit(1); }
break;
default:
ShowHelp();
Environment.Exit(1);
break;
}
}
private static void ShowHelp()
{
Console.WriteLine("[Usage]");
Console.WriteLine("mono pl0-run [options] filename");
Console.WriteLine("[Options]");
Console.WriteLine("-h\t\tShow Help.");
Console.WriteLine("-v\t\tShow Version.");
Console.WriteLine("-t time\t\tSet TimeOut time with millisecond.");
}
private static void ShowVersion()
{
Console.WriteLine(FileVersionInfo.GetVersionInfo(System.Reflection.Assembly.GetExecutingAssembly().Location));
}
}
public class pl0
{
private int regA;
private int regB;
private int regC;
private int PC;
private int FP;
private int SP;
private const int MaxSize = 1000;
private const int offset = 800;
private const int MemSize = MaxSize - offset;
private int[] memory = new int[MemSize];
private int TimeOut;
public pl0(int timeout = 5000)
{
TimeOut = timeout;
Init();
}
private void Init()
{
regA = 0;
regB = 0;
regC = 0;
PC = 1;
FP = MaxSize;
SP = MaxSize;
memory = new int[MemSize];
}
public void Run(string filePath, bool isCount = false)
{
if (!File.Exists(filePath)) WriteErrorAndExit("File Not Exits Exception");
string[] instructions = File.ReadAllLines(filePath);
var sw = new Stopwatch();
if (isCount)
{
Console.WriteLine(" --- Program Start! --- ");
sw.Start();
}
while (1 <= PC && instructions.Length >= PC)
{
if (isCount && sw.ElapsedMilliseconds > TimeOut) WriteErrorAndExit($"Time Out : {TimeOut} ms");
string[] args = instructions[PC - 1].Replace('\t', ' ').Replace(" ", " ").Trim(' ').Split(' ', ',');
if (args[0].StartsWith("@")) { DEBUG(); args[0] = args[0].Substring(1); }
switch (args[0].ToUpper())
{
case "LOAD":
LOAD(args[1], args[2]);
break;
case "STORE":
STORE(args[1], args[2]);
break;
case "PUSH":
PUSH(args[1]);
break;
case "POP":
POP(args[1]);
break;
case "PLUS":
PLUS();
break;
case "MINUS":
MINUS();
break;
case "MULTI":
MULTI();
break;
case "DIV":
DIV();
break;
case "CMPODD":
CMPODD();
break;
case "CMPEQ":
CMPEQ();
break;
case "CMPLT":
CMPLT();
break;
case "CMPGT":
CMPGT();
break;
case "CMPNOTEQ":
CMPNOTEQ();
break;
case "CMPLE":
CMPLE();
break;
case "CMPGE":
CMPGE();
break;
case "JMP":
JMP(args[1]);
break;
case "JPC":
JPC(args[1]);
break;
case "CALL":
CALL(args[1]);
break;
case "RET":
RET(args[1]);
break;
case "PUSHUP":
PUSHUP();
break;
case "PRINT":
PRINT(args[1]);
break;
case "PRINTLN":
PRINTLN();
break;
case "END":
if (isCount)
{
sw.Stop();
Console.WriteLine(" --- Program End! --- ");
Console.WriteLine($" Time : {sw.ElapsedMilliseconds} ms");
}
return;
case "DEBUG":
DEBUG();
break;
default:
WriteErrorAndExit("Syntax Error");
break;
}
PC++;
}
}
private int AnalyzeParam(string param)
{
int ret;
param = param.Replace(" ", "").Replace("#(", "").Replace(")", "");
if (int.TryParse(param, out ret)) return ret;
if (GetRegFromString(param, out ret)) return ret;
string[] tokens = param.Split('+', '-');
Stack<char> operands = new Stack<char>();
param.Where(c => (c == '+' || c == '-')).ToList().ForEach(c => operands.Push(c));
if (tokens.Length != operands.Count + 1)
WriteErrorAndExit($"Syntax Error");
ret = AnalyzeParam(tokens[0]);
for (int i = 1; 0 < operands.Count; i++)
{
char ope = operands.Pop();
switch (ope)
{
case '+':
ret += AnalyzeParam(tokens[i]);
break;
case '-':
ret -= AnalyzeParam(tokens[i]);
break;
}
}
return ret;
}
private bool GetRegFromString(string reg, out int value)
{
switch (reg.ToUpper())
{
case "A":
value = regA;
return true;
case "B":
value = regB;
return true;
case "C":
value = regC;
return true;
case "FP":
value = FP;
return true;
case "SP":
value = SP;
return true;
default:
value = -1;
return false;
}
}
private void LOAD(string reg, string adr)
{
int val;
if (int.TryParse(adr, out val)) {}
else if (GetRegFromString(adr, out val)) {}
else
{
int address = AnalyzeParam(adr);
if (offset <= address && address <= MaxSize)
{
address -= offset;
}
else WriteErrorAndExit($"Null Pointer Exception : Wrong Address {address}");
val = memory[address];
}
switch (reg.ToUpper())
{
case "A":
regA = val;
break;
case "B":
regB = val;
break;
case "C":
regC = val;
break;
case "FP":
FP = val;
break;
case "SP":
SP = val;
break;
default:
WriteErrorAndExit($"Syntax Error : Not Exists \"{reg}\"");
break;
}
}
private void STORE(string reg, string adr)
{
int address = AnalyzeParam(adr);
if (offset <= address && address < MaxSize)
{
address -= offset;
}
else WriteErrorAndExit($"Null Pointer Exception : Wrong Address {address}");
memory[address] = AnalyzeParam(reg);
}
private void PUSH(string reg)
{
Action<int> Push = (int value) =>
{
if (offset < SP)
{
memory[--SP - offset] = value;
}
else WriteErrorAndExit($"Out Of Memory Exception");
};
int val;
if (!GetRegFromString(reg, out val)) WriteErrorAndExit($"Syntax Error : Not Exists {reg}");
Push(val);
}
private void POP(string reg)
{
Func<int> Pop = () =>
{
if (SP < MaxSize)
{
return memory[SP++ - offset];
}
else WriteErrorAndExit($"Stack Empry Exception");
return 0;
};
switch (reg.ToUpper())
{
case "A":
regA = Pop();
break;
case "B":
regB = Pop();
break;
case "C":
regC = Pop();
break;
case "FP":
FP = Pop();
break;
case "SP":
SP = Pop();
break;
default:
WriteErrorAndExit($"Systax Error : Not Exists \"{reg}\"");
break;
}
}
private void PLUS()
{
regC = regA + regB;
}
private void MINUS()
{
regC = regA - regB;
}
private void MULTI()
{
regC = regA * regB;
}
private void DIV()
{
if (regB == 0) WriteErrorAndExit($"Zero Division Exception");
regC = regA / regB;
}
private void CMPODD()
{
if (regA % 2 == 1) regC = 1;
else regC = 0;
}
private void CMPEQ()
{
if (regA == regB) regC = 1;
else regC = 0;
}
private void CMPLT()
{
if (regA < regB) regC = 1;
else regC = 0;
}
private void CMPGT()
{
if (regA > regB) regC = 1;
else regC = 0;
}
private void CMPNOTEQ()
{
if (regA != regB) regC = 1;
else regC = 0;
}
private void CMPLE()
{
if (regA <= regB) regC = 1;
else regC = 0;
}
private void CMPGE()
{
if (regA >= regB) regC = 1;
else regC = 0;
}
private void JMP(string address)
{
PC = AnalyzeParam(address) - 1;
}
private void JPC(string address)
{
if (regC == 0) JMP(address);
}
private void CALL(string address)
{
Action<int> Push = (int value) =>
{
if (offset < SP)
{
memory[--SP - offset] = value;
}
else WriteErrorAndExit($"Out Of Memory Exception");
};
Push(PC + 1);
JMP(address);
}
private void RET(string address)
{
Func<int> Pop = () =>
{
if (SP < MaxSize)
{
return memory[SP++ - offset];
}
else WriteErrorAndExit($"Out Of Memory Exception");
return 0;
};
PC = Pop() - 1;
SP += AnalyzeParam(address);
}
private void PUSHUP()
{
SP--;
}
private void PRINT(string reg)
{
Console.Write(AnalyzeParam(reg));
}
private void PRINTLN()
{
Console.WriteLine("");
}
private void DEBUG()
{
Console.Error.Write($"regA:{regA} regB:{regB} regC:{regC} PC:{PC} FP:{FP} SP:{SP}");
Console.Error.Write(" Stack:{");
for (int i = SP; i < MaxSize; i++)
Console.Error.Write($"{memory[i - offset]} ");
Console.Error.WriteLine("}");
}
private void WriteErrorAndExit(string message)
{
Console.Error.WriteLine($"{message}.(PC:{PC})");
DEBUG();
Environment.Exit(1);
}
}
}
| |
// ***********************************************************************
// Copyright (c) 2015 Charlie Poole, Rob Prouse
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// ***********************************************************************
using System;
using System.Collections.Generic;
#if PARALLEL
using System.Collections.Concurrent;
#endif
using NUnit.Framework.Interfaces;
using System.Threading;
#if NET20
using NUnit.Compatibility;
#endif
namespace NUnit.Framework.Internal
{
/// <summary>
/// Represents the result of running a test suite
/// </summary>
public class TestSuiteResult : TestResult
{
private int _passCount = 0;
private int _failCount = 0;
private int _warningCount = 0;
private int _skipCount = 0;
private int _inconclusiveCount = 0;
#if PARALLEL
private readonly ConcurrentQueue<ITestResult> _children = new ConcurrentQueue<ITestResult>();
#else
private readonly List<ITestResult> _children = new List<ITestResult>();
#endif
/// <summary>
/// Construct a TestSuiteResult base on a TestSuite
/// </summary>
/// <param name="suite">The TestSuite to which the result applies</param>
public TestSuiteResult(TestSuite suite) : base(suite)
{
}
#region Overrides
/// <summary>
/// Gets the number of test cases that failed
/// when running the test and all its children.
/// </summary>
public override int FailCount
{
get
{
#if PARALLEL
RwLock.EnterReadLock();
#endif
try
{
return _failCount;
}
finally
{
#if PARALLEL
RwLock.ExitReadLock();
#endif
}
}
}
/// <summary>
/// Gets the number of test cases that passed
/// when running the test and all its children.
/// </summary>
public override int PassCount
{
get
{
#if PARALLEL
RwLock.EnterReadLock();
#endif
try
{
return _passCount;
}
finally
{
#if PARALLEL
RwLock.ExitReadLock();
#endif
}
}
}
/// <summary>
/// Gets the number of test cases that passed
/// when running the test and all its children.
/// </summary>
public override int WarningCount
{
get
{
#if PARALLEL
RwLock.EnterReadLock();
#endif
try
{
return _warningCount;
}
finally
{
#if PARALLEL
RwLock.ExitReadLock();
#endif
}
}
}
/// <summary>
/// Gets the number of test cases that were skipped
/// when running the test and all its children.
/// </summary>
public override int SkipCount
{
get
{
#if PARALLEL
RwLock.EnterReadLock();
#endif
try
{
return _skipCount;
}
finally
{
#if PARALLEL
RwLock.ExitReadLock();
#endif
}
}
}
/// <summary>
/// Gets the number of test cases that were inconclusive
/// when running the test and all its children.
/// </summary>
public override int InconclusiveCount
{
get
{
#if PARALLEL
RwLock.EnterReadLock();
#endif
try
{
return _inconclusiveCount;
}
finally
{
#if PARALLEL
RwLock.ExitReadLock();
#endif
}
}
}
/// <summary>
/// Indicates whether this result has any child results.
/// </summary>
public override bool HasChildren
{
get
{
#if PARALLEL
return !_children.IsEmpty;
#else
return _children.Count != 0;
#endif
}
}
/// <summary>
/// Gets the collection of child results.
/// </summary>
public override IEnumerable<ITestResult> Children
{
get { return _children; }
}
#endregion
#region AddResult Method
/// <summary>
/// Adds a child result to this result, setting this result's
/// ResultState to Failure if the child result failed.
/// </summary>
/// <param name="result">The result to be added</param>
public virtual void AddResult(ITestResult result)
{
#if PARALLEL
_children.Enqueue(result);
RwLock.EnterWriteLock();
try
{
MergeChildResult(result);
}
finally
{
RwLock.ExitWriteLock();
}
#else
_children.Add(result);
MergeChildResult(result);
#endif
}
private void MergeChildResult(ITestResult childResult)
{
// If this result is marked cancelled, don't change it
if (ResultState != ResultState.Cancelled)
UpdateResultState(childResult.ResultState);
InternalAssertCount += childResult.AssertCount;
_passCount += childResult.PassCount;
_failCount += childResult.FailCount;
_warningCount += childResult.WarningCount;
_skipCount += childResult.SkipCount;
_inconclusiveCount += childResult.InconclusiveCount;
}
private void UpdateResultState(ResultState childResultState)
{
switch (childResultState.Status)
{
case TestStatus.Passed:
if (ResultState.Status == TestStatus.Inconclusive)
SetResult(ResultState.Success);
break;
case TestStatus.Warning:
if (ResultState.Status == TestStatus.Inconclusive || ResultState.Status == TestStatus.Passed)
SetResult(ResultState.ChildWarning, CHILD_WARNINGS_MESSAGE);
break;
case TestStatus.Failed:
if (ResultState.Status != TestStatus.Failed)
SetResult(ResultState.ChildFailure, CHILD_ERRORS_MESSAGE);
break;
case TestStatus.Skipped:
if (childResultState.Label == "Ignored")
if (ResultState.Status == TestStatus.Inconclusive || ResultState.Status == TestStatus.Passed)
SetResult(ResultState.ChildIgnored, CHILD_IGNORE_MESSAGE);
break;
}
}
#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.Diagnostics;
using System.Runtime.InteropServices;
namespace System.Globalization
{
public partial class CompareInfo
{
internal static unsafe int InvariantIndexOf(string source, string value, int startIndex, int count, bool ignoreCase)
{
Debug.Assert(source != null);
Debug.Assert(value != null);
Debug.Assert(startIndex >= 0 && startIndex < source.Length);
fixed (char* pSource = source) fixed (char* pValue = value)
{
char* pSrc = &pSource[startIndex];
int index = InvariantFindString(pSrc, count, pValue, value.Length, ignoreCase, start : true);
if (index >= 0)
{
return index + startIndex;
}
return -1;
}
}
internal static unsafe int InvariantIndexOf(ReadOnlySpan<char> source, ReadOnlySpan<char> value, bool ignoreCase)
{
Debug.Assert(source.Length != 0);
Debug.Assert(value.Length != 0);
fixed (char* pSource = &MemoryMarshal.GetReference(source))
fixed (char* pValue = &MemoryMarshal.GetReference(value))
{
return InvariantFindString(pSource, source.Length, pValue, value.Length, ignoreCase, start: true);
}
}
internal static unsafe int InvariantLastIndexOf(string source, string value, int startIndex, int count, bool ignoreCase)
{
Debug.Assert(source != null);
Debug.Assert(value != null);
Debug.Assert(startIndex >= 0 && startIndex < source.Length);
fixed (char* pSource = source) fixed (char* pValue = value)
{
char* pSrc = &pSource[startIndex - count + 1];
int index = InvariantFindString(pSrc, count, pValue, value.Length, ignoreCase, start : false);
if (index >= 0)
{
return index + startIndex - count + 1;
}
return -1;
}
}
private static unsafe int InvariantFindString(char* source, int sourceCount, char* value, int valueCount, bool ignoreCase, bool start)
{
int ctrSource = 0; // index value into source
int ctrValue = 0; // index value into value
char sourceChar; // Character for case lookup in source
char valueChar; // Character for case lookup in value
int lastSourceStart;
Debug.Assert(source != null);
Debug.Assert(value != null);
Debug.Assert(sourceCount >= 0);
Debug.Assert(valueCount >= 0);
if (valueCount == 0)
{
return start ? 0 : sourceCount - 1;
}
if (sourceCount < valueCount)
{
return -1;
}
if (start)
{
lastSourceStart = sourceCount - valueCount;
if (ignoreCase)
{
char firstValueChar = InvariantToUpper(value[0]);
for (ctrSource = 0; ctrSource <= lastSourceStart; ctrSource++)
{
sourceChar = InvariantToUpper(source[ctrSource]);
if (sourceChar != firstValueChar)
{
continue;
}
for (ctrValue = 1; ctrValue < valueCount; ctrValue++)
{
sourceChar = InvariantToUpper(source[ctrSource + ctrValue]);
valueChar = InvariantToUpper(value[ctrValue]);
if (sourceChar != valueChar)
{
break;
}
}
if (ctrValue == valueCount)
{
return ctrSource;
}
}
}
else
{
char firstValueChar = value[0];
for (ctrSource = 0; ctrSource <= lastSourceStart; ctrSource++)
{
sourceChar = source[ctrSource];
if (sourceChar != firstValueChar)
{
continue;
}
for (ctrValue = 1; ctrValue < valueCount; ctrValue++)
{
sourceChar = source[ctrSource + ctrValue];
valueChar = value[ctrValue];
if (sourceChar != valueChar)
{
break;
}
}
if (ctrValue == valueCount)
{
return ctrSource;
}
}
}
}
else
{
lastSourceStart = sourceCount - valueCount;
if (ignoreCase)
{
char firstValueChar = InvariantToUpper(value[0]);
for (ctrSource = lastSourceStart; ctrSource >= 0; ctrSource--)
{
sourceChar = InvariantToUpper(source[ctrSource]);
if (sourceChar != firstValueChar)
{
continue;
}
for (ctrValue = 1; ctrValue < valueCount; ctrValue++)
{
sourceChar = InvariantToUpper(source[ctrSource + ctrValue]);
valueChar = InvariantToUpper(value[ctrValue]);
if (sourceChar != valueChar)
{
break;
}
}
if (ctrValue == valueCount)
{
return ctrSource;
}
}
}
else
{
char firstValueChar = value[0];
for (ctrSource = lastSourceStart; ctrSource >= 0; ctrSource--)
{
sourceChar = source[ctrSource];
if (sourceChar != firstValueChar)
{
continue;
}
for (ctrValue = 1; ctrValue < valueCount; ctrValue++)
{
sourceChar = source[ctrSource + ctrValue];
valueChar = value[ctrValue];
if (sourceChar != valueChar)
{
break;
}
}
if (ctrValue == valueCount)
{
return ctrSource;
}
}
}
}
return -1;
}
private static char InvariantToUpper(char c)
{
return (uint)(c - 'a') <= (uint)('z' - 'a') ? (char)(c - 0x20) : c;
}
private unsafe SortKey InvariantCreateSortKey(string source, CompareOptions options)
{
if (source == null) { throw new ArgumentNullException(nameof(source)); }
if ((options & ValidSortkeyCtorMaskOffFlags) != 0)
{
throw new ArgumentException(SR.Argument_InvalidFlag, nameof(options));
}
byte [] keyData;
if (source.Length == 0)
{
keyData = Array.Empty<byte>();
}
else
{
// In the invariant mode, all string comparisons are done as ordinal so when generating the sort keys we generate it according to this fact
keyData = new byte[source.Length * sizeof(char)];
fixed (char* pChar = source) fixed (byte* pByte = keyData)
{
if ((options & (CompareOptions.IgnoreCase | CompareOptions.OrdinalIgnoreCase)) != 0)
{
short *pShort = (short *) pByte;
for (int i=0; i<source.Length; i++)
{
pShort[i] = (short) InvariantToUpper(source[i]);
}
}
else
{
Buffer.MemoryCopy(pChar, pByte, keyData.Length, keyData.Length);
}
}
}
return new SortKey(Name, source, options, keyData);
}
}
}
| |
using System.Net;
using System.Text.RegularExpressions;
namespace Facility.Definition.Http;
/// <summary>
/// The HTTP mapping for a service method.
/// </summary>
public sealed class HttpMethodInfo : HttpElementInfo
{
/// <summary>
/// The service method.
/// </summary>
public ServiceMethodInfo ServiceMethod { get; }
/// <summary>
/// The HTTP method (e.g. GET or POST).
/// </summary>
public string Method { get; }
/// <summary>
/// The path of the method, always starting with a slash.
/// </summary>
public string Path { get; }
/// <summary>
/// The fields of the request DTO that correspond to path parameters.
/// </summary>
public IReadOnlyList<HttpPathFieldInfo> PathFields { get; }
/// <summary>
/// The fields of the request DTO that correspond to query parameters.
/// </summary>
public IReadOnlyList<HttpQueryFieldInfo> QueryFields { get; }
/// <summary>
/// The fields of the request DTO that correspond to normal fields in the request body.
/// </summary>
public IReadOnlyList<HttpNormalFieldInfo> RequestNormalFields { get; }
/// <summary>
/// The field of the request DTO that corresponds to the entire request body.
/// </summary>
public HttpBodyFieldInfo? RequestBodyField { get; }
/// <summary>
/// The fields of the request DTO that correspond to HTTP headers.
/// </summary>
public IReadOnlyList<HttpHeaderFieldInfo> RequestHeaderFields { get; }
/// <summary>
/// The fields of the response DTO that correspond to HTTP headers.
/// </summary>
public IReadOnlyList<HttpHeaderFieldInfo> ResponseHeaderFields { get; }
/// <summary>
/// The valid responses.
/// </summary>
public IReadOnlyList<HttpResponseInfo> ValidResponses { get; }
/// <summary>
/// Compares service methods by HTTP route.
/// </summary>
/// <remarks>Orders methods by path, then by HTTP method. Critically, it orders potentially ambiguous routes
/// in the order that they should be considered, e.g. `/widgets/query` before `/widgets/{id}`.</remarks>
public static readonly IComparer<HttpMethodInfo> ByRouteComparer = new NestedByRouteComparer();
internal HttpMethodInfo(ServiceMethodInfo methodInfo, ServiceInfo serviceInfo)
{
ServiceMethod = methodInfo;
Method = "POST";
Path = $"/{methodInfo.Name}";
HttpStatusCode? statusCode = null;
foreach (var methodParameter in GetHttpParameters(methodInfo))
{
if (methodParameter.Name == "method")
{
Method = GetHttpMethodFromParameter(methodParameter);
}
else if (methodParameter.Name == "path")
{
if (methodParameter.Value.Length == 0 || methodParameter.Value[0] != '/')
AddValidationError(new ServiceDefinitionError("'path' value must start with a slash.", methodParameter.GetPart(ServicePartKind.Value)?.Position));
Path = methodParameter.Value;
}
else if (methodParameter.Name == "code")
{
statusCode = TryParseStatusCodeInteger(methodParameter);
}
else
{
AddInvalidHttpParameterError(methodParameter);
}
}
var pathParameterNames = new HashSet<string>(GetPathParameterNames(Path));
var requestPathFields = new List<HttpPathFieldInfo>();
var requestQueryFields = new List<HttpQueryFieldInfo>();
var requestNormalFields = new List<HttpNormalFieldInfo>();
HttpBodyFieldInfo? requestBodyField = null;
var requestHeaderFields = new List<HttpHeaderFieldInfo>();
foreach (var requestField in methodInfo.RequestFields)
{
var from = requestField.TryGetHttpAttribute()?.TryGetParameterValue("from");
if (from == "path")
{
if (!IsValidSimpleField(requestField, serviceInfo))
AddValidationError(new ServiceDefinitionError("Type not supported by path field.", requestField.Position));
var pathInfo = new HttpPathFieldInfo(requestField);
if (!pathParameterNames.Remove(pathInfo.Name))
AddValidationError(new ServiceDefinitionError("Path request field has no placeholder in the method path.", requestField.Position));
requestPathFields.Add(pathInfo);
}
else if (from == "query")
{
if (!IsValidSimpleField(requestField, serviceInfo))
AddValidationError(new ServiceDefinitionError("Type not supported by query field.", requestField.Position));
requestQueryFields.Add(new HttpQueryFieldInfo(requestField));
}
else if (from == "normal")
{
if (IsNoContentMethod(Method))
AddValidationError(new ServiceDefinitionError($"HTTP {Method} does not support normal fields.", requestField.Position));
requestNormalFields.Add(new HttpNormalFieldInfo(requestField));
}
else if (from == "body")
{
if (!IsValidRequestBodyField(requestField, serviceInfo))
AddValidationError(new ServiceDefinitionError("Type not supported by body request field.", requestField.Position));
if (requestBodyField != null)
AddValidationError(new ServiceDefinitionError("Requests do not support multiple body fields.", requestField.Position));
var bodyInfo = new HttpBodyFieldInfo(requestField);
if (bodyInfo.StatusCode != null)
AddValidationError(new ServiceDefinitionError("Request fields do not support status codes.", requestField.Position));
requestBodyField = bodyInfo;
}
else if (from == "header")
{
if (!IsValidSimpleField(requestField, serviceInfo))
AddValidationError(new ServiceDefinitionError("Type not supported by header request field.", requestField.Position));
requestHeaderFields.Add(new HttpHeaderFieldInfo(requestField));
}
else if (from != null)
{
AddValidationError(new ServiceDefinitionError($"Unsupported 'from' parameter of 'http' attribute: '{from}'", requestField.Position));
}
else if (pathParameterNames.Remove(requestField.Name))
{
if (!IsValidSimpleField(requestField, serviceInfo))
AddValidationError(new ServiceDefinitionError("Type not supported by path field.", requestField.Position));
requestPathFields.Add(new HttpPathFieldInfo(requestField));
}
else if (Method == "GET" || Method == "DELETE")
{
if (!IsValidSimpleField(requestField, serviceInfo))
AddValidationError(new ServiceDefinitionError("Type not supported by query field.", requestField.Position));
requestQueryFields.Add(new HttpQueryFieldInfo(requestField));
}
else
{
requestNormalFields.Add(new HttpNormalFieldInfo(requestField));
}
}
if (pathParameterNames.Count != 0)
AddValidationError(new ServiceDefinitionError($"Unused path parameter '{pathParameterNames.First()}'.", methodInfo.Position));
if (requestBodyField != null && requestNormalFields.Count != 0)
AddValidationError(new ServiceDefinitionError("A request cannot have a normal field and a body field.", requestBodyField.ServiceField.Position));
PathFields = requestPathFields;
QueryFields = requestQueryFields;
RequestNormalFields = requestNormalFields;
RequestBodyField = requestBodyField;
RequestHeaderFields = requestHeaderFields;
var responseNormalFields = new List<HttpNormalFieldInfo>();
var responseBodyFields = new List<HttpBodyFieldInfo>();
var responseHeaderFields = new List<HttpHeaderFieldInfo>();
foreach (var responseField in methodInfo.ResponseFields)
{
var from = responseField.TryGetHttpAttribute()?.TryGetParameterValue("from");
if (from == "path" || from == "query")
{
AddValidationError(new ServiceDefinitionError("Response fields must not be path or query fields.", responseField.Position));
}
else if (from == "body")
{
if (!IsValidResponseBodyField(responseField, serviceInfo))
AddValidationError(new ServiceDefinitionError("Type not supported by body response field.", responseField.Position));
responseBodyFields.Add(new HttpBodyFieldInfo(responseField));
}
else if (from == "header")
{
if (!IsValidSimpleField(responseField, serviceInfo))
AddValidationError(new ServiceDefinitionError("Type not supported by header response field.", responseField.Position));
responseHeaderFields.Add(new HttpHeaderFieldInfo(responseField));
}
else if (from == "normal" || from == null)
{
responseNormalFields.Add(new HttpNormalFieldInfo(responseField));
}
else
{
AddValidationError(new ServiceDefinitionError($"Unsupported 'from' parameter of 'http' attribute: '{from}'", responseField.Position));
}
}
ResponseHeaderFields = responseHeaderFields;
ValidResponses = GetValidResponses(serviceInfo, statusCode, responseNormalFields, responseBodyFields).OrderBy(x => x.StatusCode).ToList();
var duplicateStatusCode = ValidResponses.GroupBy(x => x.StatusCode).FirstOrDefault(x => x.Count() > 1);
if (duplicateStatusCode != null)
AddValidationError(new ServiceDefinitionError($"Multiple handlers for status code {(int) duplicateStatusCode.Key}.", methodInfo.Position));
}
/// <summary>
/// The children of the element, if any.
/// </summary>
public override IEnumerable<HttpElementInfo> GetChildren() => PathFields.AsEnumerable<HttpElementInfo>()
.Concat(QueryFields).Concat(RequestNormalFields).Concat(new[] { RequestBodyField }.Where(x => x != null))
.Concat(RequestHeaderFields).Concat(ResponseHeaderFields).Concat(ValidResponses)!;
private string GetHttpMethodFromParameter(ServiceAttributeParameterInfo parameter)
{
var httpMethod = parameter.Value.ToUpperInvariant();
if (!s_httpMethods.Contains(httpMethod))
{
AddValidationError(new ServiceDefinitionError($"Unsupported HTTP method '{httpMethod}'.", parameter.GetPart(ServicePartKind.Value)?.Position));
return "POST";
}
return httpMethod;
}
private static bool IsValidSimpleField(ServiceFieldInfo fieldInfo, ServiceInfo serviceInfo)
{
var fieldType = serviceInfo.GetFieldType(fieldInfo);
var fieldTypeKind = fieldType?.Kind;
if (fieldTypeKind == null)
return false;
if (fieldTypeKind == ServiceTypeKind.Array)
fieldTypeKind = fieldType!.ValueType!.Kind;
return fieldTypeKind == ServiceTypeKind.String ||
fieldTypeKind == ServiceTypeKind.Boolean ||
fieldTypeKind == ServiceTypeKind.Double ||
fieldTypeKind == ServiceTypeKind.Int32 ||
fieldTypeKind == ServiceTypeKind.Int64 ||
fieldTypeKind == ServiceTypeKind.Decimal ||
fieldTypeKind == ServiceTypeKind.Enum;
}
private static bool IsValidRequestBodyField(ServiceFieldInfo fieldInfo, ServiceInfo serviceInfo)
{
var fieldTypeKind = serviceInfo.GetFieldType(fieldInfo)?.Kind;
return fieldTypeKind == ServiceTypeKind.Object ||
fieldTypeKind == ServiceTypeKind.Error ||
fieldTypeKind == ServiceTypeKind.Dto ||
fieldTypeKind == ServiceTypeKind.Result ||
fieldTypeKind == ServiceTypeKind.Array ||
fieldTypeKind == ServiceTypeKind.Map ||
fieldTypeKind == ServiceTypeKind.Bytes ||
fieldTypeKind == ServiceTypeKind.String;
}
private static bool IsValidResponseBodyField(ServiceFieldInfo fieldInfo, ServiceInfo serviceInfo)
{
return IsValidRequestBodyField(fieldInfo, serviceInfo) ||
serviceInfo.GetFieldType(fieldInfo)?.Kind == ServiceTypeKind.Boolean;
}
private IEnumerable<HttpResponseInfo> GetValidResponses(ServiceInfo serviceInfo, HttpStatusCode? statusCode, IReadOnlyList<HttpNormalFieldInfo> responseNormalFields, IReadOnlyList<HttpBodyFieldInfo> responseBodyFields)
{
foreach (var responseBodyField in responseBodyFields)
{
// use the status code on the field or the default: OK or NoContent
HttpStatusCode bodyStatusCode;
var isBoolean = serviceInfo.GetFieldType(responseBodyField.ServiceField)?.Kind == ServiceTypeKind.Boolean;
if (responseBodyField.StatusCode != null)
bodyStatusCode = responseBodyField.StatusCode.Value;
else
bodyStatusCode = isBoolean ? HttpStatusCode.NoContent : HttpStatusCode.OK;
// 204 and 304 don't support content
if (IsNoContentStatusCode(bodyStatusCode) && !isBoolean)
AddValidationError(new ServiceDefinitionError($"A body field with HTTP status code {(int) bodyStatusCode} must be Boolean.", responseBodyField.ServiceField.Position));
yield return new HttpResponseInfo(bodyStatusCode, responseBodyField);
}
// if the DTO has a status code, or there are any normal fields, or there are no body fields, the DTO must represent a status code
HttpStatusCode? responseStatusCode = null;
if (statusCode != null)
responseStatusCode = statusCode;
else if (responseNormalFields.Count != 0 || responseBodyFields.Count == 0)
responseStatusCode = HttpStatusCode.OK;
if (responseStatusCode != null)
{
// 204 and 304 don't support content
if (IsNoContentStatusCode(responseStatusCode) && responseNormalFields.Count != 0)
AddValidationError(new ServiceDefinitionError($"HTTP status code {(int) responseStatusCode} does not support normal fields.", responseNormalFields[0].ServiceField.Position));
yield return new HttpResponseInfo(responseStatusCode.Value, responseNormalFields);
}
}
private static bool IsNoContentMethod(string method) => method == "GET" || method == "DELETE";
private static bool IsNoContentStatusCode(HttpStatusCode? statusCode) => statusCode == HttpStatusCode.NoContent || statusCode == HttpStatusCode.NotModified;
private static IReadOnlyList<string> GetPathParameterNames(string routePath) =>
s_regexPathParameterRegex.Matches(routePath).Cast<Match>().Select(x => x.Groups[1].ToString()).ToList();
private class NestedByRouteComparer : IComparer<HttpMethodInfo>
{
public int Compare(HttpMethodInfo? left, HttpMethodInfo? right)
{
if (left == null)
return right == null ? 0 : -1;
if (right == null)
return 1;
var leftParts = left.Path.Split(new[] { '/' }, StringSplitOptions.RemoveEmptyEntries);
var rightParts = right.Path.Split(new[] { '/' }, StringSplitOptions.RemoveEmptyEntries);
var partIndex = 0;
while (true)
{
var leftPart = partIndex < leftParts.Length ? leftParts[partIndex] : null;
var rightPart = partIndex < rightParts.Length ? rightParts[partIndex] : null;
if (leftPart == null && rightPart == null)
break;
if (leftPart == null)
return -1;
if (rightPart == null)
return 1;
var leftPlaceholder = leftPart[0] == '{';
var rightPlaceholder = rightPart[0] == '{';
if (!leftPlaceholder || !rightPlaceholder)
{
if (leftPlaceholder || rightPlaceholder)
return leftPlaceholder ? 1 : -1;
var partCompare = string.CompareOrdinal(leftPart, rightPart);
if (partCompare != 0)
return partCompare;
}
partIndex++;
}
var leftRank = s_httpMethods.IndexOf(left.Method);
var rightRank = s_httpMethods.IndexOf(right.Method);
if (leftRank >= 0 && rightRank >= 0)
return leftRank.CompareTo(rightRank);
if (leftRank >= 0)
return -1;
if (rightRank >= 0)
return 1;
return string.CompareOrdinal(left.Method, right.Method);
}
}
private static readonly List<string> s_httpMethods = new() { "GET", "POST", "PUT", "PATCH", "DELETE" };
private static readonly Regex s_regexPathParameterRegex = new(@"\{([^\}]+)\}", RegexOptions.CultureInvariant);
}
| |
/*
* 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.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Reflection;
using System.Xml;
using System.Xml.Schema;
using System.Xml.Serialization;
using log4net;
using OpenMetaverse;
using OpenMetaverse.StructuredData;
namespace OpenSim.Framework
{
public enum ProfileShape : byte
{
Circle = 0,
Square = 1,
IsometricTriangle = 2,
EquilateralTriangle = 3,
RightTriangle = 4,
HalfCircle = 5
}
public enum HollowShape : byte
{
Same = 0,
Circle = 16,
Square = 32,
Triangle = 48
}
public enum PCodeEnum : byte
{
Primitive = 9,
Avatar = 47,
Grass = 95,
NewTree = 111,
ParticleSystem = 143,
Tree = 255
}
public enum Extrusion : byte
{
Straight = 16,
Curve1 = 32,
Curve2 = 48,
Flexible = 128
}
[Serializable]
public class PrimitiveBaseShape
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
public static readonly UUID DEFAULT_TEXTURE_ID = new UUID("89556747-24cb-43ed-920b-47caed15465f");
#region Properties
// TextureEntries
Primitive.TextureEntry m_textures;
[XmlIgnore]
public Primitive.TextureEntry Textures
{
get { return m_textures; }
set
{
m_textures = value;
m_textureEntryBytes = null; // parallel data no longer in sync
}
}
// Provided for better documentation/readability to document places where byte array accessors are used
byte[] m_textureEntryBytes; // persisted byte version of m_textures
[XmlIgnore]
public byte[] TextureEntryBytes
{
get
{
// Already calculated the bytes
if (m_textureEntryBytes != null)
return m_textureEntryBytes;
// need to recalc the bytes
return m_textures.GetBytes();
}
set
{
m_textureEntryBytes = value;
// Now initialize m_textures to match the byte[] m_textureEntry
if (value == null)
m_textures = new Primitive.TextureEntry(UUID.Zero);
else
m_textures = BytesToTextureEntry(value);
}
}
// Called only during during serialization/deserialization/viewer packets
// Provided for serialization compatibility, use Textures/TextureEntryBytes instead.
public byte[] TextureEntry
{
get { return TextureEntryBytes; }
set { TextureEntryBytes = value; }
}
public ushort PathBegin { set; get; }
public byte PathCurve { get; set; }
public ushort PathEnd { get; set; }
public sbyte PathRadiusOffset { get; set; }
public byte PathRevolutions { get; set; }
public byte PathScaleX { get; set; }
public byte PathScaleY { get; set; }
public byte PathShearX { get; set; }
public byte PathShearY { get; set; }
public sbyte PathSkew { get; set; }
public sbyte PathTaperX { get; set; }
public sbyte PathTaperY { get; set; }
public sbyte PathTwist { get; set; }
public sbyte PathTwistBegin { get; set; }
public byte PCode { get; set; }
public ushort ProfileBegin { get; set; }
public ushort ProfileEnd { get; set; }
public byte ProfileCurve
{
get { return (byte)((byte)HollowShape | (byte)ProfileShape); }
set
{
// Handle hollow shape component
byte hollowShapeByte = (byte)(value & 0xf0);
if (!Enum.IsDefined(typeof(HollowShape), hollowShapeByte))
{
m_log.WarnFormat(
"[SHAPE]: Attempt to set a ProfileCurve with a hollow shape value of {0}, which isn't a valid enum. Replacing with default shape.",
hollowShapeByte);
this.HollowShape = HollowShape.Same;
}
else
{
this.HollowShape = (HollowShape)hollowShapeByte;
}
// Handle profile shape component
byte profileShapeByte = (byte)(value & 0xf);
if (!Enum.IsDefined(typeof(ProfileShape), profileShapeByte))
{
m_log.WarnFormat(
"[SHAPE]: Attempt to set a ProfileCurve with a profile shape value of {0}, which isn't a valid enum. Replacing with square.",
profileShapeByte);
this.ProfileShape = ProfileShape.Square;
}
else
{
this.ProfileShape = (ProfileShape)profileShapeByte;
}
}
}
public ushort ProfileHollow { get; set; }
public ProfileShape ProfileShape { get; set; }
public HollowShape HollowShape { get; set; }
public Vector3 Scale { get; set; }
public byte State { get; set; }
// Physics
public PhysicsShapeType PreferredPhysicsShape { get; set; }
// Materials
[XmlIgnore]
public RenderMaterials RenderMaterials { get; set; }
// Used for XML Serialization
public byte[] RenderMaterialsBytes
{
get { return RenderMaterials.ToBytes(); }
set { RenderMaterials = RenderMaterials.FromBytes(value, 0); }
}
// Sculpted
public bool SculptEntry { get; set; }
public UUID SculptTexture { get; set; }
public byte SculptType { get; set; }
[XmlIgnore]
public byte[] SculptData { get; set; }
// Mesh
public int VertexCount { get; set; }
public int HighLODBytes { get; set; }
public int MidLODBytes { get; set; }
public int LowLODBytes { get; set; }
public int LowestLODBytes { get; set; }
// Flexi
public bool FlexiEntry { get; set; }
public int FlexiSoftness { get; set; }
public float FlexiTension { get; set; }
public float FlexiDrag { get; set; }
public float FlexiGravity { get; set; }
public float FlexiWind { get; set; }
public float FlexiForceX { get; set; }
public float FlexiForceY { get; set; }
public float FlexiForceZ { get; set; }
//Bright n sparkly
public bool LightEntry { get; set; }
public float LightColorR { get; set; }
public float LightColorG { get; set; }
public float LightColorB { get; set; }
float _lightColorA = 1f;
public float LightColorA
{
get { return _lightColorA; }
set { _lightColorA = value; }
}
public float LightRadius { get; set; }
public float LightCutoff { get; set; }
public float LightFalloff { get; set; }
float _lightIntensity = 1f;
public float LightIntensity
{
get { return _lightIntensity; }
set { _lightIntensity = Math.Min(value, 1.0f); }
}
// Light Projection Filter
public bool ProjectionEntry { get; set; }
/// <summary>
/// Gets or sets the UUID of the texture the projector emits.
/// </summary>
/// <value>The projection texture UUID.</value>
public UUID ProjectionTextureUUID { get; set; }
/// <summary>
/// Gets or sets the projection Field of View in radians.
/// Valid range is from 0.0 to 3.0. Invalid values are clamped to the valid range.
/// </summary>
/// <value>The projection FOV.</value>
float _projectionFOV;
public float ProjectionFOV
{
get { return _projectionFOV; }
set { _projectionFOV = Util.Clip(value, 0.0f, 3.0f); }
}
/// <summary>
/// Gets or sets the projection focus - aka how far away from the source prim the texture will be sharp. Beyond this value the texture and its border will gradually get blurry out to the limit of the effective range.
/// </summary>
/// <value>The projection focus distance in meters.</value>
public float ProjectionFocus { get; set; }
/// <summary>
/// Gets or sets the projection ambiance - the brightness of a very blurred edition of the projected texture that is placed on all faces of all objects within the projector's FOV and effective range.
/// Valid range is from 0.0 on up. Invalid values are clamped to the valid range.
/// </summary>
/// <value>The projection ambiance brightness.</value>
float _projectionAmb;
public float ProjectionAmbiance
{
get { return _projectionAmb; }
set { _projectionAmb = Math.Max(0.0f, value); }
}
/// <summary>
/// Entries to store media textures on each face
/// </summary>
/// Do not change this value directly - always do it through an IMoapModule.
/// Lock before manipulating.
public PrimMedia Media { get; set; }
#endregion
#region Constructors
public PrimitiveBaseShape()
{
SculptTexture = UUID.Zero;
SculptData = new byte[0];
PCode = (byte)PCodeEnum.Primitive;
ExtraParams = new byte[1];
Textures = new Primitive.TextureEntry(DEFAULT_TEXTURE_ID);
RenderMaterials = new RenderMaterials();
}
/// <summary>
/// Construct a PrimitiveBaseShape object from a OpenMetaverse.Primitive object
/// </summary>
/// <param name="prim"></param>
public PrimitiveBaseShape(Primitive prim)
{
// m_log.DebugFormat("[PRIMITIVE BASE SHAPE]: Creating from {0}", prim.ID);
PCode = (byte)prim.PrimData.PCode;
ExtraParams = new byte[1];
State = prim.PrimData.State;
PathBegin = Primitive.PackBeginCut(prim.PrimData.PathBegin);
PathEnd = Primitive.PackEndCut(prim.PrimData.PathEnd);
PathScaleX = Primitive.PackPathScale(prim.PrimData.PathScaleX);
PathScaleY = Primitive.PackPathScale(prim.PrimData.PathScaleY);
PathShearX = (byte)Primitive.PackPathShear(prim.PrimData.PathShearX);
PathShearY = (byte)Primitive.PackPathShear(prim.PrimData.PathShearY);
PathSkew = Primitive.PackPathTwist(prim.PrimData.PathSkew);
ProfileBegin = Primitive.PackBeginCut(prim.PrimData.ProfileBegin);
ProfileEnd = Primitive.PackEndCut(prim.PrimData.ProfileEnd);
Scale = prim.Scale;
PathCurve = (byte)prim.PrimData.PathCurve;
ProfileCurve = (byte)prim.PrimData.ProfileCurve;
ProfileHollow = Primitive.PackProfileHollow(prim.PrimData.ProfileHollow);
PathRadiusOffset = Primitive.PackPathTwist(prim.PrimData.PathRadiusOffset);
PathRevolutions = Primitive.PackPathRevolutions(prim.PrimData.PathRevolutions);
PathTaperX = Primitive.PackPathTaper(prim.PrimData.PathTaperX);
PathTaperY = Primitive.PackPathTaper(prim.PrimData.PathTaperY);
PathTwist = Primitive.PackPathTwist(prim.PrimData.PathTwist);
PathTwistBegin = Primitive.PackPathTwist(prim.PrimData.PathTwistBegin);
Textures = prim.Textures; // also updates TextureEntry (and TextureEntryBytes)
if (prim.Sculpt != null)
{
SculptEntry = (prim.Sculpt.Type != OpenMetaverse.SculptType.None);
SculptData = prim.Sculpt.GetBytes();
SculptTexture = prim.Sculpt.SculptTexture;
SculptType = (byte)prim.Sculpt.Type;
}
else
{
SculptType = (byte)OpenMetaverse.SculptType.None;
SculptTexture = UUID.Zero;
SculptData = new byte[0];
}
RenderMaterials = new RenderMaterials();
}
#endregion
private Primitive.TextureEntry BytesToTextureEntry(byte[] data)
{
try
{
return new Primitive.TextureEntry(data, 0, data.Length);
}
catch
{
m_log.WarnFormat("[SHAPE]: Failed to decode texture entries, length={0}", (data == null) ? 0 : data.Length);
return new Primitive.TextureEntry(UUID.Zero);
}
}
public static PrimitiveBaseShape Default
{
get
{
PrimitiveBaseShape boxShape = CreateBox();
boxShape.SetScale(0.5f);
return boxShape;
}
}
public static PrimitiveBaseShape Create()
{
PrimitiveBaseShape shape = new PrimitiveBaseShape();
return shape;
}
public static PrimitiveBaseShape CreateBox()
{
PrimitiveBaseShape shape = Create();
shape.PathCurve = (byte) Extrusion.Straight;
shape.ProfileShape = ProfileShape.Square;
shape.PathScaleX = 100;
shape.PathScaleY = 100;
return shape;
}
public static PrimitiveBaseShape CreateSphere()
{
PrimitiveBaseShape shape = Create();
shape.PathCurve = (byte) Extrusion.Curve1;
shape.ProfileShape = ProfileShape.HalfCircle;
shape.PathScaleX = 100;
shape.PathScaleY = 100;
return shape;
}
public static PrimitiveBaseShape CreateCylinder()
{
PrimitiveBaseShape shape = Create();
shape.PathCurve = (byte) Extrusion.Curve1;
shape.ProfileShape = ProfileShape.Square;
shape.PathScaleX = 100;
shape.PathScaleY = 100;
return shape;
}
public void SetScale(float side)
{
Scale = new Vector3(side, side, side);
}
public void SetHeight(float height)
{
Scale = new Vector3(Scale.X, Scale.Y, height);
}
public void SetRadius(float radius)
{
float diameter = radius * 2f;
Scale = new Vector3(diameter, diameter, Scale.Z);
}
public PrimitiveBaseShape Copy()
{
PrimitiveBaseShape shape = (PrimitiveBaseShape)MemberwiseClone();
shape.TextureEntryBytes = (byte[])TextureEntryBytes.Clone();
shape.Media = new PrimMedia(Media);
shape.RenderMaterials = RenderMaterials.Copy();
return shape;
}
public static PrimitiveBaseShape CreateCylinder(float radius, float height)
{
PrimitiveBaseShape shape = CreateCylinder();
shape.SetHeight(height);
shape.SetRadius(radius);
return shape;
}
public void SetPathRange(Vector3 pathRange)
{
PathBegin = Primitive.PackBeginCut(pathRange.X);
PathEnd = Primitive.PackEndCut(pathRange.Y);
}
public void SetPathRange(float begin, float end)
{
PathBegin = Primitive.PackBeginCut(begin);
PathEnd = Primitive.PackEndCut(end);
}
public void SetSculptProperties(byte sculptType, UUID SculptTextureUUID)
{
SculptType = sculptType;
SculptTexture = SculptTextureUUID;
}
public void SetProfileRange(Vector3 profileRange)
{
ProfileBegin = Primitive.PackBeginCut(profileRange.X);
ProfileEnd = Primitive.PackEndCut(profileRange.Y);
}
public void SetProfileRange(float begin, float end)
{
ProfileBegin = Primitive.PackBeginCut(begin);
ProfileEnd = Primitive.PackEndCut(end);
}
[XmlIgnore]
public byte[] ExtraParams
{
get
{
return ExtraParamsToBytes();
}
set
{
ReadInExtraParamsBytes(value);
}
}
/// <summary>
/// Calculate a hash value over fields that can affect the underlying physics shape.
/// Things like RenderMaterials and TextureEntry data are not included.
/// </summary>
/// <param name="size"></param>
/// <param name="lod"></param>
/// <returns>ulong - a calculated hash value</returns>
public ulong GetMeshKey(Vector3 size, float lod)
{
ulong hash = 5381;
hash = djb2(hash, this.PathCurve);
hash = djb2(hash, (byte)((byte)this.HollowShape | (byte)this.ProfileShape));
hash = djb2(hash, this.PathBegin);
hash = djb2(hash, this.PathEnd);
hash = djb2(hash, this.PathScaleX);
hash = djb2(hash, this.PathScaleY);
hash = djb2(hash, this.PathShearX);
hash = djb2(hash, this.PathShearY);
hash = djb2(hash, (byte)this.PathTwist);
hash = djb2(hash, (byte)this.PathTwistBegin);
hash = djb2(hash, (byte)this.PathRadiusOffset);
hash = djb2(hash, (byte)this.PathTaperX);
hash = djb2(hash, (byte)this.PathTaperY);
hash = djb2(hash, this.PathRevolutions);
hash = djb2(hash, (byte)this.PathSkew);
hash = djb2(hash, this.ProfileBegin);
hash = djb2(hash, this.ProfileEnd);
hash = djb2(hash, this.ProfileHollow);
// TODO: Separate scale out from the primitive shape data (after
// scaling is supported at the physics engine level)
byte[] scaleBytes = size.GetBytes();
for (int i = 0; i < scaleBytes.Length; i++)
hash = djb2(hash, scaleBytes[i]);
// Include LOD in hash, accounting for endianness
byte[] lodBytes = new byte[4];
Buffer.BlockCopy(BitConverter.GetBytes(lod), 0, lodBytes, 0, 4);
if (!BitConverter.IsLittleEndian)
{
Array.Reverse(lodBytes, 0, 4);
}
for (int i = 0; i < lodBytes.Length; i++)
hash = djb2(hash, lodBytes[i]);
// include sculpt UUID
if (this.SculptEntry)
{
scaleBytes = this.SculptTexture.GetBytes();
for (int i = 0; i < scaleBytes.Length; i++)
hash = djb2(hash, scaleBytes[i]);
hash = djb2(hash, this.SculptType);
}
return hash;
}
private ulong djb2(ulong hash, byte c)
{
return ((hash << 5) + hash) + (ulong)c;
}
private ulong djb2(ulong hash, ushort c)
{
hash = ((hash << 5) + hash) + (ulong)((byte)c);
return ((hash << 5) + hash) + (ulong)(c >> 8);
}
public byte[] ExtraParamsToBytes()
{
// m_log.DebugFormat("[EXTRAPARAMS]: Called ExtraParamsToBytes()");
bool hasSculptEntry = false;
ushort FlexiEP = 0x10;
ushort LightEP = 0x20;
ushort SculptEP = 0x30;
ushort ProjectionEP = 0x40;
int i = 0;
uint TotalBytesLength = 1; // ExtraParamsNum
uint ExtraParamsNum = 0;
if (FlexiEntry)
{
ExtraParamsNum++;
TotalBytesLength += 16;// data
TotalBytesLength += 2 + 4; // type
}
if (LightEntry)
{
ExtraParamsNum++;
TotalBytesLength += 16;// data
TotalBytesLength += 2 + 4; // type
}
if (SculptEntry)
{
hasSculptEntry = true;
ExtraParamsNum++;
TotalBytesLength += 17;// data
TotalBytesLength += 2 + 4; // type
}
if (ProjectionEntry)
{
ExtraParamsNum++;
TotalBytesLength += 28;// data
TotalBytesLength += 2 + 4;// type
}
byte[] returnbytes = new byte[TotalBytesLength];
// uint paramlength = ExtraParamsNum;
// Stick in the number of parameters
returnbytes[i++] = (byte)ExtraParamsNum;
if (FlexiEntry)
{
byte[] FlexiData = GetFlexiBytes();
returnbytes[i++] = (byte)(FlexiEP % 256);
returnbytes[i++] = (byte)((FlexiEP >> 8) % 256);
returnbytes[i++] = (byte)(FlexiData.Length % 256);
returnbytes[i++] = (byte)((FlexiData.Length >> 8) % 256);
returnbytes[i++] = (byte)((FlexiData.Length >> 16) % 256);
returnbytes[i++] = (byte)((FlexiData.Length >> 24) % 256);
Array.Copy(FlexiData, 0, returnbytes, i, FlexiData.Length);
i += FlexiData.Length;
}
if (LightEntry)
{
byte[] LightData = GetLightBytes();
returnbytes[i++] = (byte)(LightEP % 256);
returnbytes[i++] = (byte)((LightEP >> 8) % 256);
returnbytes[i++] = (byte)(LightData.Length % 256);
returnbytes[i++] = (byte)((LightData.Length >> 8) % 256);
returnbytes[i++] = (byte)((LightData.Length >> 16) % 256);
returnbytes[i++] = (byte)((LightData.Length >> 24) % 256);
Array.Copy(LightData, 0, returnbytes, i, LightData.Length);
i += LightData.Length;
}
if (hasSculptEntry)
{
byte[] SculptData = GetSculptBytes();
returnbytes[i++] = (byte)(SculptEP % 256);
returnbytes[i++] = (byte)((SculptEP >> 8) % 256);
returnbytes[i++] = (byte)(SculptData.Length % 256);
returnbytes[i++] = (byte)((SculptData.Length >> 8) % 256);
returnbytes[i++] = (byte)((SculptData.Length >> 16) % 256);
returnbytes[i++] = (byte)((SculptData.Length >> 24) % 256);
Array.Copy(SculptData, 0, returnbytes, i, SculptData.Length);
i += SculptData.Length;
}
if (ProjectionEntry)
{
byte[] ProjectionData = GetProjectionBytes();
returnbytes[i++] = (byte)(ProjectionEP % 256);
returnbytes[i++] = (byte)((ProjectionEP >> 8) % 256);
returnbytes[i++] = (byte)((ProjectionData.Length) % 256);
returnbytes[i++] = (byte)((ProjectionData.Length >> 16) % 256);
returnbytes[i++] = (byte)((ProjectionData.Length >> 20) % 256);
returnbytes[i++] = (byte)((ProjectionData.Length >> 24) % 256);
Array.Copy(ProjectionData, 0, returnbytes, i, ProjectionData.Length);
i += ProjectionData.Length;
}
if (!FlexiEntry && !LightEntry && !SculptEntry && !ProjectionEntry)
{
byte[] returnbyte = new byte[1];
returnbyte[0] = 0;
return returnbyte;
}
return returnbytes;
}
public void ReadInUpdateExtraParam(ushort type, bool inUse, byte[] data)
{
const ushort FlexiEP = 0x10;
const ushort LightEP = 0x20;
const ushort SculptEP = 0x30;
const ushort ProjectionEP = 0x40;
switch (type)
{
case FlexiEP:
if (!inUse)
{
FlexiEntry = false;
return;
}
ReadFlexiData(data, 0);
break;
case LightEP:
if (!inUse)
{
LightEntry = false;
return;
}
ReadLightData(data, 0);
break;
case SculptEP:
if (!inUse)
{
SculptEntry = false;
return;
}
ReadSculptData(data, 0);
break;
case ProjectionEP:
if (!inUse)
{
ProjectionEntry = false;
return;
}
ReadProjectionData(data, 0);
break;
}
}
public void ReadInExtraParamsBytes(byte[] data)
{
if (data == null || data.Length == 1)
return;
const ushort FlexiEP = 0x10;
const ushort LightEP = 0x20;
const ushort SculptEP = 0x30;
const ushort ProjectionEP = 0x40;
bool lGotFlexi = false;
bool lGotLight = false;
bool lGotSculpt = false;
bool lGotFilter = false;
int i = 0;
byte extraParamCount = 0;
if (data.Length > 0)
{
extraParamCount = data[i++];
}
for (int k = 0; k < extraParamCount; k++)
{
ushort epType = Utils.BytesToUInt16(data, i);
i += 2;
// uint paramLength = Helpers.BytesToUIntBig(data, i);
i += 4;
switch (epType)
{
case FlexiEP:
ReadFlexiData(data, i);
i += 16;
lGotFlexi = true;
break;
case LightEP:
ReadLightData(data, i);
i += 16;
lGotLight = true;
break;
case SculptEP:
ReadSculptData(data, i);
i += 17;
lGotSculpt = true;
break;
case ProjectionEP:
ReadProjectionData(data, i);
i += 28;
lGotFilter = true;
break;
}
}
if (!lGotFlexi)
FlexiEntry = false;
if (!lGotLight)
LightEntry = false;
if (!lGotSculpt)
SculptEntry = false;
if (!lGotFilter)
ProjectionEntry = false;
}
public void ReadSculptData(byte[] data, int pos)
{
byte[] SculptTextureUUID = new byte[16];
UUID SculptUUID = UUID.Zero;
byte SculptTypel = data[16+pos];
if (data.Length+pos >= 17)
{
SculptEntry = true;
SculptTextureUUID = new byte[16];
SculptTypel = data[16 + pos];
Array.Copy(data, pos, SculptTextureUUID,0, 16);
SculptUUID = new UUID(SculptTextureUUID, 0);
}
else
{
SculptEntry = false;
SculptUUID = UUID.Zero;
SculptTypel = 0x00;
}
if (SculptEntry)
{
if (SculptType != (byte)1 && SculptType != (byte)2 && SculptType != (byte)3 && SculptType != (byte)4)
SculptType = 4;
}
SculptTexture = SculptUUID;
SculptType = SculptTypel;
//m_log.Info("[SCULPT]:" + SculptUUID.ToString());
}
public byte[] GetSculptBytes()
{
byte[] data = new byte[17];
SculptTexture.GetBytes().CopyTo(data, 0);
data[16] = (byte)SculptType;
return data;
}
/// <summary>
/// Simple routine that clamps a float value to a min/max
/// </summary>
/// <param name="b"></param>
/// <param name="bmin"></param>
/// <param name="bmax"></param>
/// <returns>The calculated value in min/max range.</returns>
private static float llclamp(float b, float bmin, float bmax)
{
if (b < bmin) b = bmin;
if (b > bmax) b = bmax;
return b;
}
/// <summary>
/// Get Server Weight for a Mesh based on the vertex count against an average # of vertices.
/// </summary>
/// <returns>A floating point server weight cost "score" </returns>
public float GetServerWeight()
{
return (GetServerWeight(VertexCount));
}
/// <summary>
/// Get Server Weight for a Mesh based on the vertex count against an average # of vertices.
/// </summary>
/// <returns>A floating point server weight cost "score" </returns>
public static float GetServerWeight(int vertexCount)
{
const int AverageVerticesPerPrim = 422;
return ((float)vertexCount / (float)AverageVerticesPerPrim);
}
/// <summary>
/// Get Streaming Cost for a Mesh based on the byte count (which corresponds to tri-count) for each of the LOD
/// levels we stored when the mesh was uploaded.
/// </summary>
/// <returns>A floating point streaming cost "score" </returns>
public float GetStreamingCost()
{
return (GetStreamingCost(Scale, HighLODBytes, MidLODBytes, LowestLODBytes, LowestLODBytes));
}
/// <summary>
/// Get Streaming Cost for a Mesh based on the byte count (which corresponds to tri-count) for each of the LOD
/// levels we stored when the mesh was uploaded.
/// </summary>
/// <returns>A floating point streaming cost "score" </returns>
public static float GetStreamingCost(Vector3 scale, int hibytes, int midbytes, int lowbytes, int lowestbytes)
{
float streaming_cost = 0.0f;
const float MAX_AREA = 102932.0f; // The area of a circle that encompasses a region.
const float MIN_AREA = 1.0f; // Minimum area we will consider.
const float MAX_DISTANCE = 512.0f; // Distance in meters
const float METADATA_DISCOUNT = 128.0f; // Number of bytes to deduct for metadata when determining streaming cost.
const float MINIMUM_SIZE = 16.0f; // Minimum number of bytes per LoD block when determining streaming cost
const float BYTES_PER_TRIANGLE = 16.0f; // Approximation of bytes per triangle to use for determining mesh streaming cost.
const float TRIANGLE_BUDGET = 250000.0f; // Target visible triangle budget to use when estimating streaming cost.
const float MESH_COST_SCALAR = 15000.0f; // Prim budget. Prims per region max
try
{
float radius = (Vector3.Mag(scale) / (float)2.0);
// LOD Distances
float dlowest = Math.Min(radius / 0.03f, MAX_DISTANCE);
float dlow = Math.Min(radius / 0.06f, MAX_DISTANCE);
float dmid = Math.Min(radius / 0.24f, MAX_DISTANCE);
int bytes_high = hibytes;
int bytes_mid = midbytes;
int bytes_low = lowbytes;
int bytes_lowest = lowestbytes;
if (bytes_high <= 0)
return 0.0f;
if (bytes_mid <= 0)
bytes_mid = bytes_high;
if (bytes_low <= 0)
bytes_low = bytes_mid;
if (bytes_lowest <= 0)
bytes_lowest = bytes_low;
float triangles_lowest = Math.Max((float)bytes_lowest - METADATA_DISCOUNT, MINIMUM_SIZE) / BYTES_PER_TRIANGLE;
float triangles_low = Math.Max((float)bytes_low - METADATA_DISCOUNT, MINIMUM_SIZE) / BYTES_PER_TRIANGLE;
float triangles_mid = Math.Max((float)bytes_mid - METADATA_DISCOUNT, MINIMUM_SIZE) / BYTES_PER_TRIANGLE;
float triangles_high = Math.Max((float)bytes_high - METADATA_DISCOUNT, MINIMUM_SIZE) / BYTES_PER_TRIANGLE;
float high_area = Math.Min((float)Math.PI * dmid * dmid, MAX_AREA);
float mid_area = Math.Min((float)Math.PI * dlow * dlow, MAX_AREA);
float low_area = Math.Min((float)Math.PI * dlowest * dlowest, MAX_AREA);
float lowest_area = MAX_AREA;
lowest_area -= low_area;
low_area -= mid_area;
mid_area -= high_area;
high_area = llclamp(high_area, MIN_AREA, MAX_AREA);
mid_area = llclamp(mid_area, MIN_AREA, MAX_AREA);
low_area = llclamp(low_area, MIN_AREA, MAX_AREA);
lowest_area = llclamp(lowest_area, MIN_AREA, MAX_AREA);
float total_area = high_area + mid_area + low_area + lowest_area;
high_area /= total_area;
mid_area /= total_area;
low_area /= total_area;
lowest_area /= total_area;
float weighted_average = (triangles_high * high_area) + (triangles_mid * mid_area) +
(triangles_low * low_area) + (triangles_lowest * lowest_area);
streaming_cost = weighted_average / TRIANGLE_BUDGET * MESH_COST_SCALAR;
}
catch (Exception e)
{
m_log.ErrorFormat("[MESH]: exception calculating streaming cost: {0}", e);
streaming_cost = 0.0f;
}
return streaming_cost;
}
public void ReadFlexiData(byte[] data, int pos)
{
if (data.Length-pos >= 16)
{
FlexiEntry = true;
FlexiSoftness = ((data[pos] & 0x80) >> 6) | ((data[pos + 1] & 0x80) >> 7);
FlexiTension = (float)(data[pos++] & 0x7F) / 10.0f;
FlexiDrag = (float)(data[pos++] & 0x7F) / 10.0f;
FlexiGravity = (float)(data[pos++] / 10.0f) - 10.0f;
FlexiWind = (float)data[pos++] / 10.0f;
Vector3 lForce = new Vector3(data, pos);
FlexiForceX = lForce.X;
FlexiForceY = lForce.Y;
FlexiForceZ = lForce.Z;
}
else
{
FlexiEntry = false;
FlexiSoftness = 0;
FlexiTension = 0.0f;
FlexiDrag = 0.0f;
FlexiGravity = 0.0f;
FlexiWind = 0.0f;
FlexiForceX = 0f;
FlexiForceY = 0f;
FlexiForceZ = 0f;
}
}
public byte[] GetFlexiBytes()
{
byte[] data = new byte[16];
int i = 0;
// Softness is packed in the upper bits of tension and drag
data[i] = (byte)((FlexiSoftness & 2) << 6);
data[i + 1] = (byte)((FlexiSoftness & 1) << 7);
data[i++] |= (byte)((byte)(FlexiTension * 10.01f) & 0x7F);
data[i++] |= (byte)((byte)(FlexiDrag * 10.01f) & 0x7F);
data[i++] = (byte)((FlexiGravity + 10.0f) * 10.01f);
data[i++] = (byte)(FlexiWind * 10.01f);
Vector3 lForce = new Vector3(FlexiForceX, FlexiForceY, FlexiForceZ);
lForce.GetBytes().CopyTo(data, i);
return data;
}
public void ReadLightData(byte[] data, int pos)
{
if (data.Length - pos >= 16)
{
LightEntry = true;
Color4 lColor = new Color4(data, pos, false);
LightIntensity = Math.Min(lColor.A, 1.0f);
LightColorA = 1f;
LightColorR = lColor.R;
LightColorG = lColor.G;
LightColorB = lColor.B;
LightRadius = Utils.BytesToFloat(data, pos + 4);
LightCutoff = Utils.BytesToFloat(data, pos + 8);
LightFalloff = Utils.BytesToFloat(data, pos + 12);
}
else
{
LightEntry = false;
LightColorA = 1f;
LightColorR = 0f;
LightColorG = 0f;
LightColorB = 0f;
LightRadius = 0f;
LightCutoff = 0f;
LightFalloff = 0f;
LightIntensity = 0f;
}
}
public byte[] GetLightBytes()
{
byte[] data = new byte[16];
// Alpha channel in color is intensity
Color4 tmpColor = new Color4(LightColorR,LightColorG,LightColorB, Math.Min(LightIntensity, 1.0f));
tmpColor.GetBytes().CopyTo(data, 0);
Utils.FloatToBytes(LightRadius).CopyTo(data, 4);
Utils.FloatToBytes(LightCutoff).CopyTo(data, 8);
Utils.FloatToBytes(LightFalloff).CopyTo(data, 12);
return data;
}
public void ReadProjectionData(byte[] data, int pos)
{
byte[] projectionTextureUUID = new byte[16];
if (data.Length - pos >= 28)
{
ProjectionEntry = true;
Array.Copy(data, pos, projectionTextureUUID,0, 16);
ProjectionTextureUUID = new UUID(projectionTextureUUID, 0);
ProjectionFOV = Utils.BytesToFloat(data, pos + 16);
ProjectionFocus = Utils.BytesToFloat(data, pos + 20);
ProjectionAmbiance = Utils.BytesToFloat(data, pos + 24);
}
else
{
ProjectionEntry = false;
ProjectionTextureUUID = UUID.Zero;
ProjectionFOV = 0f;
ProjectionFocus = 0f;
ProjectionAmbiance = 0f;
}
}
public byte[] GetProjectionBytes()
{
byte[] data = new byte[28];
ProjectionTextureUUID.GetBytes().CopyTo(data, 0);
Utils.FloatToBytes(ProjectionFOV).CopyTo(data, 16);
Utils.FloatToBytes(ProjectionFocus).CopyTo(data, 20);
Utils.FloatToBytes(ProjectionAmbiance).CopyTo(data, 24);
return data;
}
/// <summary>
/// Return a single MaterialID for a given Face
/// </summary>
/// <returns>The UUID of the Material or UUID.Zero if none is set</returns>
public UUID GetMaterialID(int face)
{
UUID id;
if (face < 0)
{
return Textures.DefaultTexture.MaterialID;
}
else
{
var faceEntry = Textures.CreateFace((uint)face);
return faceEntry.MaterialID;
}
}
/// <summary>
/// Return a list of deduplicated materials ids from the texture entry.
/// We remove duplicates because a materialid may be used across faces and we only
/// need to represent it here once.
/// </summary>
/// <returns>The List of UUIDs found, possibly empty if no materials are in use.</returns>
public List<UUID> GetMaterialIDs()
{
List<UUID> matIds = new List<UUID>();
if (Textures != null)
{
if ((Textures.DefaultTexture != null) &&
(Textures.DefaultTexture.MaterialID != UUID.Zero))
{
matIds.Add(Textures.DefaultTexture.MaterialID);
}
foreach (var face in Textures.FaceTextures)
{
if ((face != null) && (face.MaterialID != UUID.Zero))
{
if (matIds.Contains(face.MaterialID) == false)
matIds.Add(face.MaterialID);
}
}
}
return matIds;
}
/// <summary>
/// Creates a OpenMetaverse.Primitive and populates it with converted PrimitiveBaseShape values
/// </summary>
/// <returns></returns>
public Primitive ToOmvPrimitive()
{
// position and rotation defaults here since they are not available in PrimitiveBaseShape
return ToOmvPrimitive(new Vector3(0.0f, 0.0f, 0.0f),
new Quaternion(0.0f, 0.0f, 0.0f, 1.0f));
}
/// <summary>
/// Creates a OpenMetaverse.Primitive and populates it with converted PrimitiveBaseShape values
/// </summary>
/// <param name="position"></param>
/// <param name="rotation"></param>
/// <returns></returns>
public Primitive ToOmvPrimitive(Vector3 position, Quaternion rotation)
{
OpenMetaverse.Primitive prim = new OpenMetaverse.Primitive();
prim.Scale = this.Scale;
prim.Position = position;
prim.Rotation = rotation;
if (this.SculptEntry)
{
prim.Sculpt = new Primitive.SculptData();
prim.Sculpt.Type = (OpenMetaverse.SculptType)this.SculptType;
prim.Sculpt.SculptTexture = this.SculptTexture;
}
prim.PrimData.PathShearX = Primitive.UnpackPathShear((sbyte)this.PathShearX);
prim.PrimData.PathShearY = Primitive.UnpackPathShear((sbyte)this.PathShearY);
prim.PrimData.PathBegin = (float)this.PathBegin * 2.0e-5f;
prim.PrimData.PathEnd = 1.0f - (float)this.PathEnd * 2.0e-5f;
prim.PrimData.PathScaleX = (200 - this.PathScaleX) * 0.01f;
prim.PrimData.PathScaleY = (200 - this.PathScaleY) * 0.01f;
prim.PrimData.PathTaperX = this.PathTaperX * 0.01f;
prim.PrimData.PathTaperY = this.PathTaperY * 0.01f;
prim.PrimData.PathTwistBegin = this.PathTwistBegin * 0.01f;
prim.PrimData.PathTwist = this.PathTwist * 0.01f;
prim.PrimData.ProfileBegin = (float)this.ProfileBegin * 2.0e-5f;
prim.PrimData.ProfileEnd = 1.0f - (float)this.ProfileEnd * 2.0e-5f;
prim.PrimData.ProfileHollow = (float)this.ProfileHollow * 2.0e-5f;
prim.PrimData.profileCurve = this.ProfileCurve;
prim.PrimData.ProfileHole = (HoleType)this.HollowShape;
prim.PrimData.PathCurve = (PathCurve)this.PathCurve;
prim.PrimData.PathRadiusOffset = 0.01f * this.PathRadiusOffset;
prim.PrimData.PathRevolutions = 1.0f + 0.015f * this.PathRevolutions;
prim.PrimData.PathSkew = 0.01f * this.PathSkew;
prim.PrimData.PCode = OpenMetaverse.PCode.Prim;
prim.PrimData.State = 0;
if (this.FlexiEntry)
{
prim.Flexible = new Primitive.FlexibleData();
prim.Flexible.Drag = this.FlexiDrag;
prim.Flexible.Force = new Vector3(this.FlexiForceX, this.FlexiForceY, this.FlexiForceZ);
prim.Flexible.Gravity = this.FlexiGravity;
prim.Flexible.Softness = this.FlexiSoftness;
prim.Flexible.Tension = this.FlexiTension;
prim.Flexible.Wind = this.FlexiWind;
}
if (this.LightEntry)
{
prim.Light = new Primitive.LightData();
prim.Light.Color = new Color4(this.LightColorR, this.LightColorG, this.LightColorB, this.LightColorA);
prim.Light.Cutoff = this.LightCutoff;
prim.Light.Falloff = this.LightFalloff;
prim.Light.Intensity = this.LightIntensity;
prim.Light.Radius = this.LightRadius;
}
prim.Textures = this.Textures;
prim.Properties = new Primitive.ObjectProperties();
prim.Properties.Name = "Primitive";
prim.Properties.Description = String.Empty;
prim.Properties.CreatorID = UUID.Zero;
prim.Properties.GroupID = UUID.Zero;
prim.Properties.OwnerID = UUID.Zero;
prim.Properties.Permissions = new Permissions();
prim.Properties.SalePrice = 10;
prim.Properties.SaleType = new SaleType();
return prim;
}
/// <summary>
/// Encapsulates a list of media entries.
/// </summary>
/// This class is necessary because we want to replace auto-serialization of PrimMedia with something more
/// OSD like and less vulnerable to change.
public class PrimMedia : IXmlSerializable
{
public const string MEDIA_TEXTURE_TYPE = "sl";
// keys are 0-based (face number - 1)
// protected Dictionary<int,MediaEntry> m_MediaList = new Dictionary<int,MediaEntry>();
[NonSerialized]
protected MediaEntry[] m_MediaFaces = null;
public PrimMedia() : base()
{
New(0);
}
public PrimMedia(int capacity) : base()
{
New(capacity);
}
public PrimMedia(MediaEntry[] entries) : base()
{
m_MediaFaces = entries.Clone() as MediaEntry[];
}
public PrimMedia(PrimMedia other) : base()
{
if ((other == null) || (other.m_MediaFaces == null))
{
New(0);
}
else
{
lock (this)
{
m_MediaFaces = other.CopyArray();
}
}
}
public int Count
{
get { return (m_MediaFaces == null) ? 0 : m_MediaFaces.Length; }
}
public MediaEntry this[int face]
{
get { lock (this) return m_MediaFaces[face]; }
set { lock (this) m_MediaFaces[face] = value; }
}
public void Resize(int newSize)
{
lock (this)
{
if (m_MediaFaces == null)
{
New(newSize);
return;
}
Array.Resize<MediaEntry>(ref m_MediaFaces, newSize);
}
}
// This should be implemented in OpenMetaverse.MediaEntry but isn't.
private MediaEntry MediaEntryCopy(MediaEntry entry)
{
if (entry == null) return null;
MediaEntry newEntry = new MediaEntry();
newEntry.AutoLoop = entry.AutoLoop;
newEntry.AutoPlay = entry.AutoPlay;
newEntry.AutoScale = entry.AutoScale;
newEntry.AutoZoom = entry.AutoZoom;
newEntry.ControlPermissions = entry.ControlPermissions;
newEntry.Controls = entry.Controls;
newEntry.CurrentURL = entry.CurrentURL;
newEntry.EnableAlterntiveImage = entry.EnableAlterntiveImage;
newEntry.EnableWhiteList = entry.EnableWhiteList;
newEntry.Height = entry.Height;
newEntry.HomeURL = entry.HomeURL;
newEntry.InteractOnFirstClick = entry.InteractOnFirstClick;
newEntry.InteractPermissions = entry.InteractPermissions;
newEntry.Width = entry.Width;
if (entry.WhiteList != null)
newEntry.WhiteList = (string[])entry.WhiteList.Clone();
else
entry.WhiteList = null;
newEntry.Width = entry.Width;
return newEntry;
}
public MediaEntry[] CopyArray()
{
lock (this)
{
if (m_MediaFaces == null)
return null;
int len = m_MediaFaces.Length;
MediaEntry[] copyFaces = new MediaEntry[len];
for (int x=0; x<len; x++)
{
copyFaces[x] = MediaEntryCopy(m_MediaFaces[x]);
}
return copyFaces;
}
}
/// <summary>
/// This method frees the media array if capacity is less than 1 (media list with no entries), otherwise allocates a new array of the specified size.
/// </summary>
/// <param name="capacity"></param>
public void New(int capacity)
{
lock (this)
{
// m_MediaList = new Dictionary<int, MediaEntry>();
if (capacity <= 0)
m_MediaFaces = null;
else
m_MediaFaces = new MediaEntry[capacity];
}
}
public XmlSchema GetSchema()
{
return null;
}
public string ToXml()
{
lock (this)
{
using (StringWriter sw = new StringWriter())
{
using (XmlTextWriter xtw = new XmlTextWriter(sw))
{
xtw.WriteStartElement("OSMedia");
xtw.WriteAttributeString("type", MEDIA_TEXTURE_TYPE);
xtw.WriteAttributeString("version", "0.1");
OSDArray meArray = new OSDArray();
lock (this)
{
if (m_MediaFaces != null)
{
foreach (MediaEntry me in m_MediaFaces)
{
OSD osd = (null == me ? new OSD() : me.GetOSD());
meArray.Add(osd);
}
}
}
xtw.WriteStartElement("OSData");
xtw.WriteRaw(OSDParser.SerializeLLSDXmlString(meArray));
xtw.WriteEndElement();
xtw.WriteEndElement();
xtw.Flush();
return sw.ToString();
}
}
}
}
public void WriteXml(XmlWriter writer)
{
writer.WriteRaw(ToXml());
}
public static PrimMedia FromXml(string rawXml)
{
PrimMedia ml = new PrimMedia();
ml.ReadXml(rawXml);
return ml;
}
public void ReadXml(string rawXml)
{
if (rawXml.StartsWith("<"))
{
rawXml = rawXml.Replace("<", "<").Replace(">", ">");
}
using (StringReader sr = new StringReader(rawXml))
{
using (XmlTextReader xtr = new XmlTextReader(sr))
{
xtr.MoveToContent();
string type = xtr.GetAttribute("type");
//m_log.DebugFormat("[MOAP]: Loaded media texture entry with type {0}", type);
if (type != MEDIA_TEXTURE_TYPE)
return;
xtr.ReadStartElement("OSMedia");
OSDArray osdMeArray = (OSDArray)OSDParser.DeserializeLLSDXml(xtr.ReadInnerXml());
lock (this)
{
this.New(osdMeArray.Count);
int index = 0;
foreach (OSD osdMe in osdMeArray)
{
m_MediaFaces[index++] = (osdMe is OSDMap ? MediaEntry.FromOSD(osdMe) : new MediaEntry());
}
}
xtr.ReadEndElement();
}
}
}
public void ReadXml(XmlReader reader)
{
if (reader.IsEmptyElement)
return;
ReadXml(reader.ReadInnerXml());
}
}
}
}
| |
// 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: This class implements a set of methods for retrieving
// sort key information.
//
//
////////////////////////////////////////////////////////////////////////////
namespace System.Globalization {
using System;
using System.Runtime.CompilerServices;
using System.Runtime.Serialization;
using System.Diagnostics.Contracts;
[System.Runtime.InteropServices.ComVisible(true)]
#if FEATURE_SERIALIZATION
[Serializable]
#endif
public class SortKey
{
//--------------------------------------------------------------------//
// Internal Information //
//--------------------------------------------------------------------//
//
// Variables.
//
[OptionalField(VersionAdded = 3)]
internal String localeName; // locale identifier
[OptionalField(VersionAdded = 1)] // LCID field so serialization is Whidbey compatible though we don't officially support it
internal int win32LCID;
// Whidbey serialization
internal CompareOptions options; // options
internal String m_String; // original string
internal byte[] m_KeyData; // sortkey data
//
// The following constructor is designed to be called from CompareInfo to get the
// the sort key of specific string for synthetic culture
//
internal SortKey(String localeName, String str, CompareOptions options, byte[] keyData)
{
this.m_KeyData = keyData;
this.localeName = localeName;
this.options = options;
this.m_String = str;
}
#if FEATURE_USE_LCID
[OnSerializing]
private void OnSerializing(StreamingContext context)
{
//set LCID to proper value for Whidbey serialization (no other use)
if (win32LCID == 0)
{
win32LCID = CultureInfo.GetCultureInfo(localeName).LCID;
}
}
[OnDeserialized]
private void OnDeserialized(StreamingContext context)
{
//set locale name to proper value after Whidbey deserialization
if (String.IsNullOrEmpty(localeName) && win32LCID != 0)
{
localeName = CultureInfo.GetCultureInfo(win32LCID).Name;
}
}
#endif //FEATURE_USE_LCID
////////////////////////////////////////////////////////////////////////
//
// GetOriginalString
//
// Returns the original string used to create the current instance
// of SortKey.
//
////////////////////////////////////////////////////////////////////////
public virtual String OriginalString
{
get {
return (m_String);
}
}
////////////////////////////////////////////////////////////////////////
//
// GetKeyData
//
// Returns a byte array representing the current instance of the
// sort key.
//
////////////////////////////////////////////////////////////////////////
public virtual byte[] KeyData
{
get {
return (byte[])(m_KeyData.Clone());
}
}
////////////////////////////////////////////////////////////////////////
//
// Compare
//
// Compares the two sort keys. Returns 0 if the two sort keys are
// equal, a number less than 0 if sortkey1 is less than sortkey2,
// and a number greater than 0 if sortkey1 is greater than sortkey2.
//
////////////////////////////////////////////////////////////////////////
public static int Compare(SortKey sortkey1, SortKey sortkey2) {
if (sortkey1==null || sortkey2==null) {
throw new ArgumentNullException((sortkey1==null ? "sortkey1": "sortkey2"));
}
Contract.EndContractBlock();
byte[] key1Data = sortkey1.m_KeyData;
byte[] key2Data = sortkey2.m_KeyData;
Contract.Assert(key1Data!=null, "key1Data!=null");
Contract.Assert(key2Data!=null, "key2Data!=null");
if (key1Data.Length == 0) {
if (key2Data.Length == 0) {
return (0);
}
return (-1);
}
if (key2Data.Length == 0) {
return (1);
}
int compLen = (key1Data.Length<key2Data.Length)?key1Data.Length:key2Data.Length;
for (int i=0; i<compLen; i++) {
if (key1Data[i]>key2Data[i]) {
return (1);
}
if (key1Data[i]<key2Data[i]) {
return (-1);
}
}
return 0;
}
////////////////////////////////////////////////////////////////////////
//
// Equals
//
// Implements Object.Equals(). Returns a boolean indicating whether
// or not object refers to the same SortKey as the current instance.
//
////////////////////////////////////////////////////////////////////////
public override bool Equals(Object value)
{
SortKey that = value as SortKey;
if (that != null)
{
return Compare(this, that) == 0;
}
return (false);
}
////////////////////////////////////////////////////////////////////////
//
// GetHashCode
//
// Implements Object.GetHashCode(). Returns the hash code for the
// SortKey. The hash code is guaranteed to be the same for
// SortKey A and B where A.Equals(B) is true.
//
////////////////////////////////////////////////////////////////////////
public override int GetHashCode()
{
return (CompareInfo.GetCompareInfo(
this.localeName).GetHashCodeOfString(this.m_String, this.options));
}
////////////////////////////////////////////////////////////////////////
//
// ToString
//
// Implements Object.ToString(). Returns a string describing the
// SortKey.
//
////////////////////////////////////////////////////////////////////////
public override String ToString()
{
return ("SortKey - " + localeName + ", " + options + ", " + m_String);
}
}
}
| |
// Copyright (C) by Housemarque, Inc.
namespace Hopac {
using Microsoft.FSharp.Core;
using Hopac.Core;
using System;
using System.Threading;
using System.Runtime.CompilerServices;
internal static class MVar {
internal const int Demand = -1;
internal const int Empty = 0;
internal const int Full = 1;
internal const int Locked = 2;
}
/// <summary>Represents a serialized variable.</summary>
public class MVar<T> : Alt<T> {
internal T Value;
internal volatile int State;
internal Cont<T> Takers;
/// <summary>Creates a new serialized variable.</summary>
[MethodImpl(AggressiveInlining.Flag)]
public MVar() { }
/// <summary>Creates a new serialized variable that is initially filled with the given value.</summary>
[MethodImpl(AggressiveInlining.Flag)]
public MVar(T t) {
this.Value = t;
this.State = MVar.Full;
}
internal override void DoJob(ref Worker wr, Cont<T> tK) {
Spin:
var state = this.State;
if (state == MVar.Locked) goto Spin;
if (state != Interlocked.CompareExchange(ref this.State, MVar.Locked, state))
goto Spin;
if (state <= MVar.Empty)
goto EmptyOrDemand;
T value = this.Value;
this.Value = default(T); // Avoid memory leaks.
this.State = MVar.Empty;
Cont.Do(tK, ref wr, value);
return;
EmptyOrDemand:
WaitQueue.AddTaker(ref this.Takers, tK);
this.State = MVar.Demand;
}
internal override void TryAlt(ref Worker wr, int i, Cont<T> tK, Else tE) {
var pkSelf = tE.pk;
Spin:
var state = this.State;
if (state == MVar.Locked) goto Spin;
if (state != Interlocked.CompareExchange(ref this.State, MVar.Locked, state))
goto Spin;
if (state <= MVar.Empty)
goto EmptyOrDemand;
TryPick:
var stSelf = Pick.TryPick(pkSelf);
if (stSelf > 0) goto AlreadyPicked;
if (stSelf < 0) goto TryPick;
Pick.SetNacks(ref wr, i, pkSelf);
T t = this.Value;
this.Value = default(T);
this.State = MVar.Empty;
Cont.Do(tK, ref wr, t);
return;
AlreadyPicked:
this.State = MVar.Full;
return;
EmptyOrDemand:
WaitQueue.AddTaker(ref this.Takers, i, pkSelf, tK);
this.State = MVar.Demand;
tE.TryElse(ref wr, i + 1);
return;
}
internal void Fill(ref Worker wr, T t) {
TryNextTaker:
var state = this.State;
if (state == MVar.Locked)
goto TryNextTaker;
if (state != Interlocked.CompareExchange(ref this.State, MVar.Locked, state))
goto TryNextTaker;
if (state == MVar.Empty)
goto WasEmpty;
var tail = this.Takers;
if (null == tail)
goto MVarFull;
var cursor = tail.Next;
if (tail == cursor) {
this.Takers = null;
this.State = MVar.Empty;
} else {
tail.Next = cursor.Next;
this.State = MVar.Demand;
tail = cursor as Cont<T>;
}
var taker = tail as Taker<T>;
if (null == taker)
goto GotTaker;
var pk = taker.Pick;
TryPick:
int st = Pick.TryPick(pk);
if (st > 0)
goto TryNextTaker;
if (st < 0)
goto TryPick;
Pick.SetNacks(ref wr, taker.Me, pk);
tail = taker.Cont;
GotTaker:
tail.Value = t;
Worker.Push(ref wr, tail);
return;
WasEmpty:
this.Value = t;
this.State = MVar.Full;
return;
MVarFull:
this.State = MVar.Full;
throw new Exception("MVar full");
}
}
namespace Core {
internal sealed class MVarReadCont<T> : Cont<T> {
private MVar<T> tM;
private Cont<T> tK;
internal MVarReadCont(MVar<T> tM, Cont<T> tK) {
this.tM = tM;
this.tK = tK;
}
internal override Proc GetProc(ref Worker wr) {
return Handler.GetProc(ref wr, ref tK);
}
internal override void DoHandle(ref Worker wr, Exception e) {
Handler.DoHandle(tK, ref wr, e);
}
internal override void DoWork(ref Worker wr) {
DoCont(ref wr, this.Value);
}
internal override void DoCont(ref Worker wr, T t) {
tM.Fill(ref wr, t);
Cont.Do(tK, ref wr, t);
}
}
///
public sealed class MVarRead<T> : Alt<T> {
private MVar<T> tM;
///
[MethodImpl(AggressiveInlining.Flag)]
public MVarRead(MVar<T> tM) { this.tM = tM; }
internal override void DoJob(ref Worker wr, Cont<T> tK) {
var tM = this.tM;
Spin:
var state = tM.State;
if (state == MVar.Locked) goto Spin;
if (state != Interlocked.CompareExchange(ref tM.State, MVar.Locked, state))
goto Spin;
if (state <= MVar.Empty)
goto EmptyOrDemand;
var t = tM.Value;
tM.State = MVar.Full;
Cont.Do(tK, ref wr, t);
return;
EmptyOrDemand:
WaitQueue.AddTaker(ref tM.Takers, new MVarReadCont<T>(tM, tK));
tM.State = MVar.Demand;
}
internal override void TryAlt(ref Worker wr, int i, Cont<T> tK, Else tE) {
var tM = this.tM;
var pkSelf = tE.pk;
Spin:
var state = tM.State;
if (state == MVar.Locked) goto Spin;
if (state != Interlocked.CompareExchange(ref tM.State, MVar.Locked, state))
goto Spin;
if (state <= MVar.Empty)
goto EmptyOrDemand;
TryPick:
var stSelf = Pick.TryPick(pkSelf);
if (stSelf > 0) goto AlreadyPicked;
if (stSelf < 0) goto TryPick;
Pick.SetNacks(ref wr, i, pkSelf);
var t = tM.Value;
tM.State = MVar.Full;
Cont.Do(tK, ref wr, t);
return;
AlreadyPicked:
tM.State = MVar.Full;
return;
EmptyOrDemand:
WaitQueue.AddTaker(ref tM.Takers, i, pkSelf, new MVarReadCont<T>(tM, tK));
tM.State = MVar.Demand;
tE.TryElse(ref wr, i + 1);
return;
}
}
internal sealed class MVarModifyFunCont<T, Y> : Cont<T> {
private MVarModifyFun<T, Y> tm;
private Cont<Y> yK;
internal MVarModifyFunCont(MVarModifyFun<T, Y> tm, Cont<Y> yK) {
this.tm = tm;
this.yK = yK;
}
internal override Proc GetProc(ref Worker wr) {
return Handler.GetProc(ref wr, ref yK);
}
internal override void DoHandle(ref Worker wr, Exception e) {
Handler.DoHandle(yK, ref wr, e);
}
internal override void DoWork(ref Worker wr) {
DoCont(ref wr, this.Value);
}
internal override void DoCont(ref Worker wr, T t) {
var tm = this.tm;
var yK = this.yK;
tm.tM.Fill(ref wr, tm.Do(t, ref yK.Value));
Work.Do(yK, ref wr);
}
}
///
public abstract class MVarModifyFun<T, Y> : Alt<Y> {
internal MVar<T> tM;
///
[MethodImpl(AggressiveInlining.Flag)]
public Alt<Y> InternalInit(MVar<T> tM) { this.tM = tM; return this; }
///
public abstract T Do(T t, ref Y y);
internal override void DoJob(ref Worker wr, Cont<Y> yK) {
var tM = this.tM;
Spin:
var state = tM.State;
if (state == MVar.Locked) goto Spin;
if (state != Interlocked.CompareExchange(ref tM.State, MVar.Locked, state))
goto Spin;
if (state <= MVar.Empty)
goto EmptyOrDemand;
var t = tM.Value;
tM.State = MVar.Empty;
tM.Fill(ref wr, Do(t, ref yK.Value));
Work.Do(yK, ref wr);
return;
EmptyOrDemand:
WaitQueue.AddTaker(ref tM.Takers, new MVarModifyFunCont<T, Y>(this, yK));
tM.State = MVar.Demand;
}
internal override void TryAlt(ref Worker wr, int i, Cont<Y> yK, Else tE) {
var tM = this.tM;
var pkSelf = tE.pk;
Spin:
var state = tM.State;
if (state == MVar.Locked) goto Spin;
if (state != Interlocked.CompareExchange(ref tM.State, MVar.Locked, state))
goto Spin;
if (state <= MVar.Empty)
goto EmptyOrDemand;
TryPick:
var stSelf = Pick.TryPick(pkSelf);
if (stSelf > 0) goto AlreadyPicked;
if (stSelf < 0) goto TryPick;
Pick.SetNacks(ref wr, i, pkSelf);
var t = tM.Value;
tM.State = MVar.Empty;
tM.Fill(ref wr, Do(t, ref yK.Value));
Work.Do(yK, ref wr);
return;
AlreadyPicked:
tM.State = MVar.Full;
return;
EmptyOrDemand:
WaitQueue.AddTaker(ref tM.Takers, i, pkSelf, new MVarModifyFunCont<T, Y>(this, yK));
tM.State = MVar.Demand;
tE.TryElse(ref wr, i + 1);
return;
}
}
internal sealed class MVarTryModifyFunCont<T, Y> : Cont<T> {
private MVarTryModifyFun<T, Y> tm;
private Cont<Y> yK;
[MethodImpl(AggressiveInlining.Flag)]
internal MVarTryModifyFunCont(MVarTryModifyFun<T, Y> tm, Cont<Y> yK) {
this.tm = tm;
this.yK = yK;
}
internal override Proc GetProc(ref Worker wr) {
return Handler.GetProc(ref wr, ref yK);
}
internal override void DoHandle(ref Worker wr, Exception e) {
Handler.DoHandle(yK, ref wr, e);
}
[MethodImpl(AggressiveInlining.Flag)]
internal static void Do(MVarTryModifyFun<T, Y> tm, Cont<Y> yK, ref Worker wr, T t) {
Exception raised = null;
try {
t = tm.Do(t, ref yK.Value);
} catch (Exception e) {
raised = e;
}
tm.tM.Fill(ref wr, t);
if (null != raised)
Handler.DoHandle(yK, ref wr, raised);
else
Work.Do(yK, ref wr);
}
internal override void DoWork(ref Worker wr) { Do(tm, yK, ref wr, this.Value); }
internal override void DoCont(ref Worker wr, T t) { Do(tm, yK, ref wr, t); }
}
///
public abstract class MVarTryModifyFun<T, Y> : Alt<Y> {
internal MVar<T> tM;
///
[MethodImpl(AggressiveInlining.Flag)]
public Alt<Y> InternalInit(MVar<T> tM) { this.tM = tM; return this; }
///
public abstract T Do(T t, ref Y y);
internal override void DoJob(ref Worker wr, Cont<Y> yK) {
var tM = this.tM;
Spin:
var state = tM.State;
if (state == MVar.Locked) goto Spin;
if (state != Interlocked.CompareExchange(ref tM.State, MVar.Locked, state))
goto Spin;
if (state <= MVar.Empty)
goto EmptyOrDemand;
var t = tM.Value;
tM.State = MVar.Empty;
MVarTryModifyFunCont<T, Y>.Do(this, yK, ref wr, t);
return;
EmptyOrDemand:
WaitQueue.AddTaker(ref tM.Takers, new MVarTryModifyFunCont<T, Y>(this, yK));
tM.State = MVar.Demand;
}
internal override void TryAlt(ref Worker wr, int i, Cont<Y> yK, Else tE) {
var tM = this.tM;
var pkSelf = tE.pk;
Spin:
var state = tM.State;
if (state == MVar.Locked) goto Spin;
if (state != Interlocked.CompareExchange(ref tM.State, MVar.Locked, state))
goto Spin;
if (state <= MVar.Empty)
goto EmptyOrDemand;
TryPick:
var stSelf = Pick.TryPick(pkSelf);
if (stSelf > 0) goto AlreadyPicked;
if (stSelf < 0) goto TryPick;
Pick.SetNacks(ref wr, i, pkSelf);
var t = tM.Value;
tM.State = MVar.Empty;
MVarTryModifyFunCont<T, Y>.Do(this, yK, ref wr, t);
return;
AlreadyPicked:
tM.State = MVar.Full;
return;
EmptyOrDemand:
WaitQueue.AddTaker(ref tM.Takers, i, pkSelf, new MVarTryModifyFunCont<T, Y>(this, yK));
tM.State = MVar.Demand;
tE.TryElse(ref wr, i + 1);
return;
}
}
///
public sealed class MVarFill<T> : Job<Unit> {
private MVar<T> tM;
private T t;
///
[MethodImpl(AggressiveInlining.Flag)]
public MVarFill(MVar<T> tM, T t) {
this.tM = tM;
this.t = t;
}
internal override void DoJob(ref Worker wr, Cont<Unit> uK) {
tM.Fill(ref wr, t);
Work.Do(uK, ref wr);
}
}
}
}
| |
// 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 Roslyn.Utilities;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using EmitContext = Microsoft.CodeAnalysis.Emit.EmitContext;
using System.Collections.Immutable;
using Microsoft.CodeAnalysis;
using System.Reflection.PortableExecutable;
using Microsoft.CodeAnalysis.Emit;
namespace Microsoft.Cci
{
/// <summary>
/// Represents a .NET assembly.
/// </summary>
internal interface IAssembly : IModule, IAssemblyReference
{
/// <summary>
/// A list of the files that constitute the assembly. These are not the source language files that may have been
/// used to compile the assembly, but the files that contain constituent modules of a multi-module assembly as well
/// as any external resources. It corresponds to the File table of the .NET assembly file format.
/// </summary>
IEnumerable<IFileReference> GetFiles(EmitContext context);
/// <summary>
/// A set of bits and bit ranges representing properties of the assembly. The value of <see cref="Flags"/> can be set
/// from source code via the AssemblyFlags assembly custom attribute. The interpretation of the property depends on the target platform.
/// </summary>
uint Flags { get; }
/// <summary>
/// The public part of the key used to encrypt the SHA1 hash over the persisted form of this assembly. Empty or null if not specified.
/// This value is used by the loader to decrypt an encrypted hash value stored in the assembly, which it then compares with a freshly computed hash value
/// in order to verify the integrity of the assembly.
/// </summary>
ImmutableArray<byte> PublicKey { get; }
/// <summary>
/// The contents of the AssemblySignatureKeyAttribute
/// </summary>
string SignatureKey { get; }
AssemblyHashAlgorithm HashAlgorithm { get; }
}
/// <summary>
/// A reference to a .NET assembly.
/// </summary>
internal interface IAssemblyReference : IModuleReference
{
AssemblyIdentity Identity { get; }
}
/// <summary>
/// An object that represents a .NET module.
/// </summary>
internal interface IModule : IUnit, IModuleReference
{
ModulePropertiesForSerialization Properties { get; }
/// <summary>
/// Used to distinguish which style to pick while writing native PDB information.
/// </summary>
/// <remarks>
/// The PDB content for custom debug information is different between Visual Basic and CSharp.
/// E.g. C# always includes a CustomMetadata Header (MD2) that contains the namespace scope counts, where
/// as VB only outputs namespace imports into the namespace scopes.
/// C# defines forwards in that header, VB includes them into the scopes list.
///
/// Currently the compiler doesn't allow mixing C# and VB method bodies. Thus this flag can be per module.
/// It is possible to move this flag to per-method basis but native PDB CDI forwarding would need to be adjusted accordingly.
/// </remarks>
bool GenerateVisualBasicStylePdb { get; }
/// <summary>
/// Public types defined in other modules making up this assembly and to which other assemblies may refer to via this assembly.
/// </summary>
IEnumerable<ITypeReference> GetExportedTypes(EmitContext context);
/// <summary>
/// A list of objects representing persisted instances of types that extend System.Attribute. Provides an extensible way to associate metadata
/// with this assembly.
/// </summary>
IEnumerable<ICustomAttribute> AssemblyAttributes { get; }
/// <summary>
/// A list of objects representing persisted instances of pairs of security actions and sets of security permissions.
/// These apply by default to every method reachable from the module.
/// </summary>
IEnumerable<SecurityAttribute> AssemblySecurityAttributes { get; }
/// <summary>
/// A list of the assemblies that are referenced by this module.
/// </summary>
IEnumerable<IAssemblyReference> GetAssemblyReferences(EmitContext context);
/// <summary>
/// A list of named byte sequences persisted with the assembly and used during execution, typically via .NET Framework helper classes.
/// </summary>
IEnumerable<ManagedResource> GetResources(EmitContext context);
/// <summary>
/// CorLibrary assembly referenced by this module.
/// </summary>
IAssemblyReference GetCorLibrary(EmitContext context);
/// <summary>
/// The Assembly that contains this module. If this module is main module then this returns this.
/// </summary>
new IAssembly GetContainingAssembly(EmitContext context);
/// <summary>
/// The method that will be called to start execution of this executable module.
/// </summary>
IMethodReference PEEntryPoint { get; }
IMethodReference DebugEntryPoint { get; }
/// <summary>
/// Returns zero or more strings used in the module. If the module is produced by reading in a CLR PE file, then this will be the contents
/// of the user string heap. If the module is produced some other way, the method may return an empty enumeration or an enumeration that is a
/// subset of the strings actually used in the module. The main purpose of this method is to provide a way to control the order of strings in a
/// prefix of the user string heap when writing out a module as a PE file.
/// </summary>
IEnumerable<string> GetStrings();
/// <summary>
/// Returns all top-level (not nested) types defined in the current module.
/// </summary>
IEnumerable<INamespaceTypeDefinition> GetTopLevelTypes(EmitContext context);
/// <summary>
/// The kind of metadata stored in this module. For example whether this module is an executable or a manifest resource file.
/// </summary>
OutputKind Kind { get; }
/// <summary>
/// A list of objects representing persisted instances of types that extend System.Attribute. Provides an extensible way to associate metadata
/// with this module.
/// </summary>
IEnumerable<ICustomAttribute> ModuleAttributes { get; }
/// <summary>
/// The name of the module.
/// </summary>
string ModuleName { get; }
/// <summary>
/// A list of the modules that are referenced by this module.
/// </summary>
IEnumerable<IModuleReference> ModuleReferences { get; }
/// <summary>
/// A list of named byte sequences persisted with the module and used during execution, typically via the Win32 API.
/// A module will define Win32 resources rather than "managed" resources mainly to present metadata to legacy tools
/// and not typically use the data in its own code.
/// </summary>
IEnumerable<IWin32Resource> Win32Resources { get; }
/// <summary>
/// An alternate form the Win32 resources may take. These represent the rsrc$01 and rsrc$02 section data and relocs
/// from a COFF object file.
/// </summary>
ResourceSection Win32ResourceSection { get; }
IAssembly AsAssembly { get; }
ITypeReference GetPlatformType(PlatformType t, EmitContext context);
bool IsPlatformType(ITypeReference typeRef, PlatformType t);
IEnumerable<IReference> ReferencesInIL(out int count);
/// <summary>
/// Builds symbol definition to location map used for emitting token -> location info
/// into PDB to be consumed by WinMdExp.exe tool (only applicable for /t:winmdobj)
/// </summary>
MultiDictionary<DebugSourceDocument, DefinitionWithLocation> GetSymbolToLocationMap();
/// <summary>
/// Assembly reference aliases (C# only).
/// </summary>
ImmutableArray<AssemblyReferenceAlias> GetAssemblyReferenceAliases(EmitContext context);
/// <summary>
/// Linked assembly names to be stored to native PDB (VB only).
/// </summary>
IEnumerable<string> LinkedAssembliesDebugInfo { get; }
/// <summary>
/// Project level imports (VB only, TODO: C# scripts).
/// </summary>
ImmutableArray<UsedNamespaceOrType> GetImports();
/// <summary>
/// Default namespace (VB only).
/// </summary>
string DefaultNamespace { get; }
// An approximate number of method definitions that can
// provide a basis for approximating the capacities of
// various databases used during Emit.
int HintNumberOfMethodDefinitions { get; }
}
internal struct DefinitionWithLocation
{
public readonly IDefinition Definition;
public readonly uint StartLine;
public readonly uint StartColumn;
public readonly uint EndLine;
public readonly uint EndColumn;
public DefinitionWithLocation(IDefinition definition,
int startLine, int startColumn, int endLine, int endColumn)
{
Debug.Assert(startLine >= 0);
Debug.Assert(startColumn >= 0);
Debug.Assert(endLine >= 0);
Debug.Assert(endColumn >= 0);
this.Definition = definition;
this.StartLine = (uint)startLine;
this.StartColumn = (uint)startColumn;
this.EndLine = (uint)endLine;
this.EndColumn = (uint)endColumn;
}
public override string ToString()
{
return string.Format(
"{0} => start:{1}/{2}, end:{3}/{4}",
this.Definition.ToString(),
this.StartLine.ToString(), this.StartColumn.ToString(),
this.EndLine.ToString(), this.EndColumn.ToString());
}
}
/// <summary>
/// A reference to a .NET module.
/// </summary>
internal interface IModuleReference : IUnitReference
{
/// <summary>
/// The Assembly that contains this module. May be null if the module is not part of an assembly.
/// </summary>
IAssemblyReference GetContainingAssembly(EmitContext context);
}
/// <summary>
/// A unit of metadata stored as a single artifact and potentially produced and revised independently from other units.
/// Examples of units include .NET assemblies and modules, as well C++ object files and compiled headers.
/// </summary>
internal interface IUnit : IUnitReference, IDefinition
{
}
/// <summary>
/// A reference to a instance of <see cref="IUnit"/>.
/// </summary>
internal interface IUnitReference : IReference, INamedEntity
{
}
}
| |
using Lucene.Net.Diagnostics;
using Lucene.Net.Support;
using System;
using System.Collections.Generic;
#if FEATURE_SERIALIZABLE_EXCEPTIONS
using System.Runtime.Serialization;
#endif
namespace Lucene.Net.Util
{
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using DirectAllocator = Lucene.Net.Util.ByteBlockPool.DirectAllocator;
/// <summary>
/// <see cref="BytesRefHash"/> is a special purpose hash-map like data-structure
/// optimized for <see cref="BytesRef"/> instances. <see cref="BytesRefHash"/> maintains mappings of
/// byte arrays to ids (Map<BytesRef,int>) storing the hashed bytes
/// efficiently in continuous storage. The mapping to the id is
/// encapsulated inside <see cref="BytesRefHash"/> and is guaranteed to be increased
/// for each added <see cref="BytesRef"/>.
///
/// <para>
/// Note: The maximum capacity <see cref="BytesRef"/> instance passed to
/// <see cref="Add(BytesRef)"/> must not be longer than <see cref="ByteBlockPool.BYTE_BLOCK_SIZE"/>-2.
/// The internal storage is limited to 2GB total byte storage.
/// </para>
///
/// @lucene.internal
/// </summary>
public sealed class BytesRefHash : IDisposable // LUCENENET specific: Implemented IDisposable to enable usage of the using statement
{
public const int DEFAULT_CAPACITY = 16;
// the following fields are needed by comparer,
// so package private to prevent access$-methods:
internal readonly ByteBlockPool pool;
internal int[] bytesStart;
private readonly BytesRef scratch1 = new BytesRef();
private int hashSize;
private int hashHalfSize;
private int hashMask;
private int count;
private int lastCount = -1;
private int[] ids;
private readonly BytesStartArray bytesStartArray;
private Counter bytesUsed;
/// <summary>
/// Creates a new <see cref="BytesRefHash"/> with a <see cref="ByteBlockPool"/> using a
/// <see cref="DirectAllocator"/>.
/// </summary>
public BytesRefHash()
: this(new ByteBlockPool(new DirectAllocator()))
{
}
/// <summary>
/// Creates a new <see cref="BytesRefHash"/>
/// </summary>
public BytesRefHash(ByteBlockPool pool)
: this(pool, DEFAULT_CAPACITY, new DirectBytesStartArray(DEFAULT_CAPACITY))
{
}
/// <summary>
/// Creates a new <see cref="BytesRefHash"/>
/// </summary>
public BytesRefHash(ByteBlockPool pool, int capacity, BytesStartArray bytesStartArray)
{
hashSize = capacity;
hashHalfSize = hashSize >> 1;
hashMask = hashSize - 1;
this.pool = pool;
ids = new int[hashSize];
Arrays.Fill(ids, -1);
this.bytesStartArray = bytesStartArray;
bytesStart = bytesStartArray.Init();
bytesUsed = bytesStartArray.BytesUsed() == null ? Counter.NewCounter() : bytesStartArray.BytesUsed();
bytesUsed.AddAndGet(hashSize * RamUsageEstimator.NUM_BYTES_INT32);
}
/// <summary>
/// Returns the number of <see cref="BytesRef"/> values in this <see cref="BytesRefHash"/>.
/// <para/>
/// NOTE: This was size() in Lucene.
/// </summary>
/// <returns> The number of <see cref="BytesRef"/> values in this <see cref="BytesRefHash"/>. </returns>
public int Count => count;
/// <summary>
/// Populates and returns a <see cref="BytesRef"/> with the bytes for the given
/// bytesID.
/// <para/>
/// Note: the given bytesID must be a positive integer less than the current
/// size (<see cref="Count"/>)
/// </summary>
/// <param name="bytesID">
/// The id </param>
/// <param name="ref">
/// The <see cref="BytesRef"/> to populate
/// </param>
/// <returns> The given <see cref="BytesRef"/> instance populated with the bytes for the given
/// bytesID </returns>
public BytesRef Get(int bytesID, BytesRef @ref)
{
if (Debugging.AssertsEnabled)
{
Debugging.Assert(bytesStart != null, "bytesStart is null - not initialized");
Debugging.Assert(bytesID < bytesStart.Length, () => "bytesID exceeds byteStart len: " + bytesStart.Length);
}
pool.SetBytesRef(@ref, bytesStart[bytesID]);
return @ref;
}
/// <summary>
/// Returns the ids array in arbitrary order. Valid ids start at offset of 0
/// and end at a limit of <see cref="Count"/> - 1
/// <para>
/// Note: this is a destructive operation. <see cref="Clear()"/> must be called in
/// order to reuse this <see cref="BytesRefHash"/> instance.
/// </para>
/// </summary>
public int[] Compact()
{
if (Debugging.AssertsEnabled) Debugging.Assert(bytesStart != null, "bytesStart is null - not initialized");
int upto = 0;
for (int i = 0; i < hashSize; i++)
{
if (ids[i] != -1)
{
if (upto < i)
{
ids[upto] = ids[i];
ids[i] = -1;
}
upto++;
}
}
if (Debugging.AssertsEnabled) Debugging.Assert(upto == count);
lastCount = count;
return ids;
}
/// <summary>
/// Returns the values array sorted by the referenced byte values.
/// <para>
/// Note: this is a destructive operation. <see cref="Clear()"/> must be called in
/// order to reuse this <see cref="BytesRefHash"/> instance.
/// </para>
/// </summary>
/// <param name="comp">
/// The <see cref="T:IComparer{BytesRef}"/> used for sorting </param>
public int[] Sort(IComparer<BytesRef> comp)
{
int[] compact = Compact();
new IntroSorterAnonymousInnerClassHelper(this, comp, compact).Sort(0, count);
return compact;
}
private class IntroSorterAnonymousInnerClassHelper : IntroSorter
{
private BytesRefHash outerInstance;
private IComparer<BytesRef> comp;
private int[] compact;
private readonly BytesRef pivot = new BytesRef(), scratch1 = new BytesRef(), scratch2 = new BytesRef();
public IntroSorterAnonymousInnerClassHelper(BytesRefHash outerInstance, IComparer<BytesRef> comp, int[] compact)
{
this.outerInstance = outerInstance;
this.comp = comp;
this.compact = compact;
}
protected override void Swap(int i, int j)
{
int o = compact[i];
compact[i] = compact[j];
compact[j] = o;
}
protected override int Compare(int i, int j)
{
int id1 = compact[i], id2 = compact[j];
if (Debugging.AssertsEnabled) Debugging.Assert(outerInstance.bytesStart.Length > id1 && outerInstance.bytesStart.Length > id2);
outerInstance.pool.SetBytesRef(outerInstance.scratch1, outerInstance.bytesStart[id1]);
outerInstance.pool.SetBytesRef(scratch2, outerInstance.bytesStart[id2]);
return comp.Compare(outerInstance.scratch1, scratch2);
}
protected override void SetPivot(int i)
{
int id = compact[i];
if (Debugging.AssertsEnabled) Debugging.Assert(outerInstance.bytesStart.Length > id);
outerInstance.pool.SetBytesRef(pivot, outerInstance.bytesStart[id]);
}
protected override int ComparePivot(int j)
{
int id = compact[j];
if (Debugging.AssertsEnabled) Debugging.Assert(outerInstance.bytesStart.Length > id);
outerInstance.pool.SetBytesRef(scratch2, outerInstance.bytesStart[id]);
return comp.Compare(pivot, scratch2);
}
}
private bool Equals(int id, BytesRef b)
{
pool.SetBytesRef(scratch1, bytesStart[id]);
return scratch1.BytesEquals(b);
}
private bool Shrink(int targetSize)
{
// Cannot use ArrayUtil.shrink because we require power
// of 2:
int newSize = hashSize;
while (newSize >= 8 && newSize / 4 > targetSize)
{
newSize /= 2;
}
if (newSize != hashSize)
{
bytesUsed.AddAndGet(RamUsageEstimator.NUM_BYTES_INT32 * -(hashSize - newSize));
hashSize = newSize;
ids = new int[hashSize];
Arrays.Fill(ids, -1);
hashHalfSize = newSize / 2;
hashMask = newSize - 1;
return true;
}
else
{
return false;
}
}
/// <summary>
/// Clears the <see cref="BytesRef"/> which maps to the given <see cref="BytesRef"/>
/// </summary>
public void Clear(bool resetPool)
{
lastCount = count;
count = 0;
if (resetPool)
{
pool.Reset(false, false); // we don't need to 0-fill the buffers
}
bytesStart = bytesStartArray.Clear();
if (lastCount != -1 && Shrink(lastCount))
{
// shrink clears the hash entries
return;
}
Arrays.Fill(ids, -1);
}
public void Clear()
{
Clear(true);
}
/// <summary>
/// Closes the <see cref="BytesRefHash"/> and releases all internally used memory
/// </summary>
public void Dispose()
{
Clear(true);
ids = null;
bytesUsed.AddAndGet(RamUsageEstimator.NUM_BYTES_INT32 * -hashSize);
}
/// <summary>
/// Adds a new <see cref="BytesRef"/>
/// </summary>
/// <param name="bytes">
/// The bytes to hash </param>
/// <returns> The id the given bytes are hashed if there was no mapping for the
/// given bytes, otherwise <c>(-(id)-1)</c>. this guarantees
/// that the return value will always be >= 0 if the given bytes
/// haven't been hashed before.
/// </returns>
/// <exception cref="MaxBytesLengthExceededException">
/// if the given bytes are > 2 +
/// <see cref="ByteBlockPool.BYTE_BLOCK_SIZE"/> </exception>
public int Add(BytesRef bytes)
{
if (Debugging.AssertsEnabled) Debugging.Assert(bytesStart != null, "bytesStart is null - not initialized");
int length = bytes.Length;
// final position
int hashPos = FindHash(bytes);
int e = ids[hashPos];
if (e == -1)
{
// new entry
int len2 = 2 + bytes.Length;
if (len2 + pool.ByteUpto > ByteBlockPool.BYTE_BLOCK_SIZE)
{
if (len2 > ByteBlockPool.BYTE_BLOCK_SIZE)
{
throw new MaxBytesLengthExceededException("bytes can be at most " + (ByteBlockPool.BYTE_BLOCK_SIZE - 2) + " in length; got " + bytes.Length);
}
pool.NextBuffer();
}
var buffer = pool.Buffer;
int bufferUpto = pool.ByteUpto;
if (count >= bytesStart.Length)
{
bytesStart = bytesStartArray.Grow();
if (Debugging.AssertsEnabled) Debugging.Assert(count < bytesStart.Length + 1, () => "count: " + count + " len: " + bytesStart.Length);
}
e = count++;
bytesStart[e] = bufferUpto + pool.ByteOffset;
// We first encode the length, followed by the
// bytes. Length is encoded as vInt, but will consume
// 1 or 2 bytes at most (we reject too-long terms,
// above).
if (length < 128)
{
// 1 byte to store length
buffer[bufferUpto] = (byte)length;
pool.ByteUpto += length + 1;
if (Debugging.AssertsEnabled) Debugging.Assert(length >= 0, () => "Length must be positive: " + length);
System.Buffer.BlockCopy(bytes.Bytes, bytes.Offset, buffer, bufferUpto + 1, length);
}
else
{
// 2 byte to store length
buffer[bufferUpto] = (byte)(0x80 | (length & 0x7f));
buffer[bufferUpto + 1] = (byte)((length >> 7) & 0xff);
pool.ByteUpto += length + 2;
System.Buffer.BlockCopy(bytes.Bytes, bytes.Offset, buffer, bufferUpto + 2, length);
}
if (Debugging.AssertsEnabled) Debugging.Assert(ids[hashPos] == -1);
ids[hashPos] = e;
if (count == hashHalfSize)
{
Rehash(2 * hashSize, true);
}
return e;
}
return -(e + 1);
}
/// <summary>
/// Returns the id of the given <see cref="BytesRef"/>.
/// </summary>
/// <param name="bytes">
/// The bytes to look for
/// </param>
/// <returns> The id of the given bytes, or <c>-1</c> if there is no mapping for the
/// given bytes. </returns>
public int Find(BytesRef bytes)
{
return ids[FindHash(bytes)];
}
private int FindHash(BytesRef bytes)
{
if (Debugging.AssertsEnabled) Debugging.Assert(bytesStart != null, "bytesStart is null - not initialized");
int code = DoHash(bytes.Bytes, bytes.Offset, bytes.Length);
// final position
int hashPos = code & hashMask;
int e = ids[hashPos];
if (e != -1 && !Equals(e, bytes))
{
// Conflict; use linear probe to find an open slot
// (see LUCENE-5604):
do
{
code++;
hashPos = code & hashMask;
e = ids[hashPos];
} while (e != -1 && !Equals(e, bytes));
}
return hashPos;
}
/// <summary>
/// Adds a "arbitrary" int offset instead of a <see cref="BytesRef"/>
/// term. This is used in the indexer to hold the hash for term
/// vectors, because they do not redundantly store the <see cref="T:byte[]"/> term
/// directly and instead reference the <see cref="T:byte[]"/> term
/// already stored by the postings <see cref="BytesRefHash"/>. See
/// <see cref="Index.TermsHashPerField.Add(int)"/>.
/// </summary>
public int AddByPoolOffset(int offset)
{
if (Debugging.AssertsEnabled) Debugging.Assert(bytesStart != null, "bytesStart is null - not initialized");
// final position
int code = offset;
int hashPos = offset & hashMask;
int e = ids[hashPos];
if (e != -1 && bytesStart[e] != offset)
{
// Conflict; use linear probe to find an open slot
// (see LUCENE-5604):
do
{
code++;
hashPos = code & hashMask;
e = ids[hashPos];
} while (e != -1 && bytesStart[e] != offset);
}
if (e == -1)
{
// new entry
if (count >= bytesStart.Length)
{
bytesStart = bytesStartArray.Grow();
if (Debugging.AssertsEnabled) Debugging.Assert(count < bytesStart.Length + 1, () => "count: " + count + " len: " + bytesStart.Length);
}
e = count++;
bytesStart[e] = offset;
if (Debugging.AssertsEnabled) Debugging.Assert(ids[hashPos] == -1);
ids[hashPos] = e;
if (count == hashHalfSize)
{
Rehash(2 * hashSize, false);
}
return e;
}
return -(e + 1);
}
/// <summary>
/// Called when hash is too small (> 50% occupied) or too large (< 20%
/// occupied).
/// </summary>
private void Rehash(int newSize, bool hashOnData)
{
int newMask = newSize - 1;
bytesUsed.AddAndGet(RamUsageEstimator.NUM_BYTES_INT32 * (newSize));
int[] newHash = new int[newSize];
Arrays.Fill(newHash, -1);
for (int i = 0; i < hashSize; i++)
{
int e0 = ids[i];
if (e0 != -1)
{
int code;
if (hashOnData)
{
int off = bytesStart[e0];
int start = off & ByteBlockPool.BYTE_BLOCK_MASK;
var bytes = pool.Buffers[off >> ByteBlockPool.BYTE_BLOCK_SHIFT];
int len;
int pos;
if ((bytes[start] & 0x80) == 0)
{
// length is 1 byte
len = bytes[start];
pos = start + 1;
}
else
{
len = (bytes[start] & 0x7f) + ((bytes[start + 1] & 0xff) << 7);
pos = start + 2;
}
code = DoHash(bytes, pos, len);
}
else
{
code = bytesStart[e0];
}
int hashPos = code & newMask;
if (Debugging.AssertsEnabled) Debugging.Assert(hashPos >= 0);
if (newHash[hashPos] != -1)
{
// Conflict; use linear probe to find an open slot
// (see LUCENE-5604):
do
{
code++;
hashPos = code & newMask;
} while (newHash[hashPos] != -1);
}
newHash[hashPos] = e0;
}
}
hashMask = newMask;
bytesUsed.AddAndGet(RamUsageEstimator.NUM_BYTES_INT32 * (-ids.Length));
ids = newHash;
hashSize = newSize;
hashHalfSize = newSize / 2;
}
// TODO: maybe use long? But our keys are typically short...
private static int DoHash(byte[] bytes, int offset, int length)
{
return StringHelper.Murmurhash3_x86_32(bytes, offset, length, StringHelper.GOOD_FAST_HASH_SEED);
}
/// <summary>
/// Reinitializes the <see cref="BytesRefHash"/> after a previous <see cref="Clear()"/>
/// call. If <see cref="Clear()"/> has not been called previously this method has no
/// effect.
/// </summary>
public void Reinit()
{
if (bytesStart == null)
{
bytesStart = bytesStartArray.Init();
}
if (ids == null)
{
ids = new int[hashSize];
bytesUsed.AddAndGet(RamUsageEstimator.NUM_BYTES_INT32 * hashSize);
}
}
/// <summary>
/// Returns the bytesStart offset into the internally used
/// <see cref="ByteBlockPool"/> for the given <paramref name="bytesID"/>
/// </summary>
/// <param name="bytesID">
/// The id to look up </param>
/// <returns> The bytesStart offset into the internally used
/// <see cref="ByteBlockPool"/> for the given id </returns>
public int ByteStart(int bytesID)
{
if (Debugging.AssertsEnabled)
{
Debugging.Assert(bytesStart != null, "bytesStart is null - not initialized");
Debugging.Assert(bytesID >= 0 && bytesID < count, () => bytesID.ToString());
}
return bytesStart[bytesID];
}
/// <summary>
/// Thrown if a <see cref="BytesRef"/> exceeds the <see cref="BytesRefHash"/> limit of
/// <see cref="ByteBlockPool.BYTE_BLOCK_SIZE"/>-2.
/// </summary>
// LUCENENET: It is no longer good practice to use binary serialization.
// See: https://github.com/dotnet/corefx/issues/23584#issuecomment-325724568
#if FEATURE_SERIALIZABLE_EXCEPTIONS
[Serializable]
#endif
public class MaxBytesLengthExceededException : Exception
{
internal MaxBytesLengthExceededException(string message)
: base(message)
{
}
#if FEATURE_SERIALIZABLE_EXCEPTIONS
/// <summary>
/// Initializes a new instance of this class with serialized data.
/// </summary>
/// <param name="info">The <see cref="SerializationInfo"/> that holds the serialized object data about the exception being thrown.</param>
/// <param name="context">The <see cref="StreamingContext"/> that contains contextual information about the source or destination.</param>
protected MaxBytesLengthExceededException(SerializationInfo info, StreamingContext context)
: base(info, context)
{
}
#endif
}
/// <summary>
/// Manages allocation of the per-term addresses. </summary>
public abstract class BytesStartArray
{
/// <summary>
/// Initializes the <see cref="BytesStartArray"/>. This call will allocate memory.
/// </summary>
/// <returns> The initialized bytes start array. </returns>
public abstract int[] Init();
/// <summary>
/// Grows the <see cref="BytesStartArray"/>.
/// </summary>
/// <returns> The grown array. </returns>
public abstract int[] Grow();
/// <summary>
/// Clears the <see cref="BytesStartArray"/> and returns the cleared instance.
/// </summary>
/// <returns> The cleared instance, this might be <c>null</c>. </returns>
public abstract int[] Clear();
/// <summary>
/// A <see cref="Counter"/> reference holding the number of bytes used by this
/// <see cref="BytesStartArray"/>. The <see cref="BytesRefHash"/> uses this reference to
/// track it memory usage.
/// </summary>
/// <returns> a <see cref="J2N.Threading.Atomic.AtomicInt64"/> reference holding the number of bytes used
/// by this <see cref="BytesStartArray"/>. </returns>
public abstract Counter BytesUsed();
}
/// <summary>
/// A simple <see cref="BytesStartArray"/> that tracks
/// memory allocation using a private <see cref="Counter"/>
/// instance.
/// </summary>
public class DirectBytesStartArray : BytesStartArray
{
// TODO: can't we just merge this w/
// TrackingDirectBytesStartArray...? Just add a ctor
// that makes a private bytesUsed?
protected readonly int m_initSize;
internal int[] bytesStart;
internal readonly Counter bytesUsed;
public DirectBytesStartArray(int initSize, Counter counter)
{
this.bytesUsed = counter;
this.m_initSize = initSize;
}
public DirectBytesStartArray(int initSize)
: this(initSize, Counter.NewCounter())
{
}
public override int[] Clear()
{
return bytesStart = null;
}
public override int[] Grow()
{
if (Debugging.AssertsEnabled) Debugging.Assert(bytesStart != null);
return bytesStart = ArrayUtil.Grow(bytesStart, bytesStart.Length + 1);
}
public override int[] Init()
{
return bytesStart = new int[ArrayUtil.Oversize(m_initSize, RamUsageEstimator.NUM_BYTES_INT32)];
}
public override Counter BytesUsed()
{
return bytesUsed;
}
}
}
}
| |
/*
* Copyright 2010 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License. You may obtain
* a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.IO;
using System.Web;
using System.Web.Script.Serialization;
namespace Facebook
{
enum HttpVerb
{
GET,
POST,
DELETE
}
/// <summary>
/// Wrapper around the Facebook Graph API.
/// </summary>
public class FacebookAPI
{
/// <summary>
/// The access token used to authenticate API calls.
/// </summary>
public string AccessToken { get; set; }
/// <summary>
/// Create a new instance of the API, with public access only.
/// </summary>
public FacebookAPI()
: this(null) { }
/// <summary>
/// Create a new instance of the API, using the given token to
/// authenticate.
/// </summary>
/// <param name="token">The access token used for
/// authentication</param>
public FacebookAPI(string token)
{
AccessToken = token;
}
/// <summary>
/// Makes a Facebook Graph API GET request.
/// </summary>
/// <param name="relativePath">The path for the call,
/// e.g. /username</param>
public JSONObject Get(string relativePath)
{
return Call(relativePath, HttpVerb.GET, null);
}
/// <summary>
/// Makes a Facebook Graph API GET request.
/// </summary>
/// <param name="relativePath">The path for the call,
/// e.g. /username</param>
public dynamic GetDynamic(string relativePath)
{
return new DynamicJSONObject(Get(relativePath));
}
/// <summary>
/// Makes a Facebook Graph API GET request.
/// </summary>
/// <param name="relativePath">The path for the call,
/// e.g. /username</param>
/// <param name="args">A dictionary of key/value pairs that
/// will get passed as query arguments.</param>
public JSONObject Get(string relativePath,
Dictionary<string, string> args)
{
return Call(relativePath, HttpVerb.GET, args);
}
/// <summary>
/// Makes a Facebook Graph API DELETE request.
/// </summary>
/// <param name="relativePath">The path for the call,
/// e.g. /username</param>
public JSONObject Delete(string relativePath)
{
return Call(relativePath, HttpVerb.DELETE, null);
}
/// <summary>
/// Makes a Facebook Graph API POST request.
/// </summary>
/// <param name="relativePath">The path for the call,
/// e.g. /username</param>
/// <param name="args">A dictionary of key/value pairs that
/// will get passed as query arguments. These determine
/// what will get set in the graph API.</param>
public JSONObject Post(string relativePath,
Dictionary<string, string> args)
{
return Call(relativePath, HttpVerb.POST, args);
}
/// <summary>
/// Makes a Facebook Graph API Call.
/// </summary>
/// <param name="relativePath">The path for the call,
/// e.g. /username</param>
/// <param name="httpVerb">The HTTP verb to use, e.g.
/// GET, POST, DELETE</param>
/// <param name="args">A dictionary of key/value pairs that
/// will get passed as query arguments.</param>
private JSONObject Call(string relativePath,
HttpVerb httpVerb,
Dictionary<string, string> args)
{
Uri baseURL = new Uri("https://graph.facebook.com");
Uri url = new Uri(baseURL, relativePath);
if (args == null)
{
args = new Dictionary<string, string>();
}
if (!string.IsNullOrEmpty(AccessToken))
{
args["access_token"] = AccessToken;
}
JSONObject obj = JSONObject.CreateFromString(MakeRequest(url,
httpVerb,
args));
if (obj.IsDictionary && obj.Dictionary.ContainsKey("error"))
{
throw new FacebookAPIException(obj.Dictionary["error"]
.Dictionary["type"]
.String,
obj.Dictionary["error"]
.Dictionary["message"]
.String);
}
return obj;
}
/// <summary>
/// Make an HTTP request, with the given query args
/// </summary>
/// <param name="url">The URL of the request</param>
/// <param name="verb">The HTTP verb to use</param>
/// <param name="args">Dictionary of key/value pairs that represents
/// the key/value pairs for the request</param>
private string MakeRequest(Uri url, HttpVerb httpVerb,
Dictionary<string, string> args)
{
if (args != null && args.Keys.Count > 0 && httpVerb == HttpVerb.GET)
{
url = new Uri(url.ToString() + EncodeDictionary(args, true));
}
HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
request.Method = httpVerb.ToString();
if (httpVerb == HttpVerb.POST)
{
string postData = EncodeDictionary(args, false);
ASCIIEncoding encoding = new ASCIIEncoding();
byte[] postDataBytes = encoding.GetBytes(postData);
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = postDataBytes.Length;
Stream requestStream = request.GetRequestStream();
requestStream.Write(postDataBytes, 0, postDataBytes.Length);
requestStream.Close();
}
try
{
using (HttpWebResponse response
= request.GetResponse() as HttpWebResponse)
{
StreamReader reader
= new StreamReader(response.GetResponseStream());
return reader.ReadToEnd();
}
}
catch (WebException e)
{
throw new FacebookAPIException("Server Error", e.Message);
}
}
/// <summary>
/// Encode a dictionary of key/value pairs as an HTTP query string.
/// </summary>
/// <param name="dict">The dictionary to encode</param>
/// <param name="questionMark">Whether or not to start it
/// with a question mark (for GET requests)</param>
private string EncodeDictionary(Dictionary<string, string> dict,
bool questionMark)
{
StringBuilder sb = new StringBuilder();
if (questionMark)
{
sb.Append("?");
}
foreach (KeyValuePair<string, string> kvp in dict)
{
sb.Append(HttpUtility.UrlEncode(kvp.Key));
sb.Append("=");
sb.Append(HttpUtility.UrlEncode(kvp.Value));
sb.Append("&");
}
sb.Remove(sb.Length - 1, 1); // Remove trailing &
return sb.ToString();
}
}
}
| |
#region Copyright notice and license
// Copyright 2015 gRPC 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.Diagnostics;
using System.IO;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Threading;
using System.Threading.Tasks;
using Grpc.Core.Internal;
using Grpc.Core.Utils;
namespace Grpc.Core.Internal
{
/// <summary>
/// Manages server side native call lifecycle.
/// </summary>
internal class AsyncCallServer<TRequest, TResponse> : AsyncCallBase<TResponse, TRequest>, IReceivedCloseOnServerCallback, ISendStatusFromServerCompletionCallback
{
readonly TaskCompletionSource<object> finishedServersideTcs = new TaskCompletionSource<object>();
readonly CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();
readonly Server server;
public AsyncCallServer(Func<TResponse, byte[]> serializer, Func<byte[], TRequest> deserializer, Server server) : base(serializer, deserializer)
{
this.server = GrpcPreconditions.CheckNotNull(server);
}
public void Initialize(CallSafeHandle call, CompletionQueueSafeHandle completionQueue)
{
call.Initialize(completionQueue);
server.AddCallReference(this);
InitializeInternal(call);
}
/// <summary>
/// Only for testing purposes.
/// </summary>
public void InitializeForTesting(INativeCall call)
{
server.AddCallReference(this);
InitializeInternal(call);
}
/// <summary>
/// Starts a server side call.
/// </summary>
public Task ServerSideCallAsync()
{
lock (myLock)
{
GrpcPreconditions.CheckNotNull(call);
started = true;
call.StartServerSide(ReceiveCloseOnServerCallback);
return finishedServersideTcs.Task;
}
}
/// <summary>
/// Sends a streaming response. Only one pending send action is allowed at any given time.
/// </summary>
public Task SendMessageAsync(TResponse msg, WriteFlags writeFlags)
{
return SendMessageInternalAsync(msg, writeFlags);
}
/// <summary>
/// Receives a streaming request. Only one pending read action is allowed at any given time.
/// </summary>
public Task<TRequest> ReadMessageAsync()
{
return ReadMessageInternalAsync();
}
/// <summary>
/// Initiates sending a initial metadata.
/// Even though C-core allows sending metadata in parallel to sending messages, we will treat sending metadata as a send message operation
/// to make things simpler.
/// </summary>
public Task SendInitialMetadataAsync(Metadata headers)
{
lock (myLock)
{
GrpcPreconditions.CheckNotNull(headers, "metadata");
GrpcPreconditions.CheckState(started);
GrpcPreconditions.CheckState(!initialMetadataSent, "Response headers can only be sent once per call.");
GrpcPreconditions.CheckState(streamingWritesCounter == 0, "Response headers can only be sent before the first write starts.");
var earlyResult = CheckSendAllowedOrEarlyResult();
if (earlyResult != null)
{
return earlyResult;
}
using (var metadataArray = MetadataArraySafeHandle.Create(headers))
{
call.StartSendInitialMetadata(SendCompletionCallback, metadataArray);
}
this.initialMetadataSent = true;
streamingWriteTcs = new TaskCompletionSource<object>();
return streamingWriteTcs.Task;
}
}
/// <summary>
/// Sends call result status, indicating we are done with writes.
/// Sending a status different from StatusCode.OK will also implicitly cancel the call.
/// </summary>
public Task SendStatusFromServerAsync(Status status, Metadata trailers, ResponseWithFlags? optionalWrite)
{
byte[] payload = optionalWrite.HasValue ? UnsafeSerialize(optionalWrite.Value.Response) : null;
var writeFlags = optionalWrite.HasValue ? optionalWrite.Value.WriteFlags : default(WriteFlags);
lock (myLock)
{
GrpcPreconditions.CheckState(started);
GrpcPreconditions.CheckState(!disposed);
GrpcPreconditions.CheckState(!halfcloseRequested, "Can only send status from server once.");
using (var metadataArray = MetadataArraySafeHandle.Create(trailers))
{
call.StartSendStatusFromServer(SendStatusFromServerCompletionCallback, status, metadataArray, !initialMetadataSent,
payload, writeFlags);
}
halfcloseRequested = true;
initialMetadataSent = true;
sendStatusFromServerTcs = new TaskCompletionSource<object>();
if (optionalWrite.HasValue)
{
streamingWritesCounter++;
}
return sendStatusFromServerTcs.Task;
}
}
/// <summary>
/// Gets cancellation token that gets cancelled once close completion
/// is received and the cancelled flag is set.
/// </summary>
public CancellationToken CancellationToken
{
get
{
return cancellationTokenSource.Token;
}
}
public string Peer
{
get
{
return call.GetPeer();
}
}
protected override bool IsClient
{
get { return false; }
}
protected override Exception GetRpcExceptionClientOnly()
{
throw new InvalidOperationException("Call be only called for client calls");
}
protected override void OnAfterReleaseResources()
{
server.RemoveCallReference(this);
}
protected override Task CheckSendAllowedOrEarlyResult()
{
GrpcPreconditions.CheckState(!halfcloseRequested, "Response stream has already been completed.");
GrpcPreconditions.CheckState(!finished, "Already finished.");
GrpcPreconditions.CheckState(streamingWriteTcs == null, "Only one write can be pending at a time");
GrpcPreconditions.CheckState(!disposed);
return null;
}
/// <summary>
/// Handles the server side close completion.
/// </summary>
private void HandleFinishedServerside(bool success, bool cancelled)
{
// NOTE: because this event is a result of batch containing GRPC_OP_RECV_CLOSE_ON_SERVER,
// success will be always set to true.
lock (myLock)
{
finished = true;
if (streamingReadTcs == null)
{
// if there's no pending read, readingDone=true will dispose now.
// if there is a pending read, we will dispose once that read finishes.
readingDone = true;
streamingReadTcs = new TaskCompletionSource<TRequest>();
streamingReadTcs.SetResult(default(TRequest));
}
ReleaseResourcesIfPossible();
}
if (cancelled)
{
cancellationTokenSource.Cancel();
}
finishedServersideTcs.SetResult(null);
}
IReceivedCloseOnServerCallback ReceiveCloseOnServerCallback => this;
void IReceivedCloseOnServerCallback.OnReceivedCloseOnServer(bool success, bool cancelled)
{
HandleFinishedServerside(success, cancelled);
}
ISendStatusFromServerCompletionCallback SendStatusFromServerCompletionCallback => this;
void ISendStatusFromServerCompletionCallback.OnSendStatusFromServerCompletion(bool success)
{
HandleSendStatusFromServerFinished(success);
}
public struct ResponseWithFlags
{
public ResponseWithFlags(TResponse response, WriteFlags writeFlags)
{
this.Response = response;
this.WriteFlags = writeFlags;
}
public TResponse Response { get; }
public WriteFlags WriteFlags { get; }
}
}
}
| |
using System;
using System.Text;
/// <summary>
/// Convert(System.Text.Encoding,System.Text.Encoding,System.Byte[],System.Int32,System.Int32)
/// </summary>
public class EncodingConvert2
{
#region Public Methods
public bool RunTests()
{
bool retVal = true;
TestLibrary.TestFramework.LogInformation("[Positive]");
retVal = PosTest1() && retVal;
retVal = PosTest2() && retVal;
retVal = PosTest3() && retVal;
retVal = NegTest1() && retVal;
retVal = NegTest2() && retVal;
retVal = NegTest3() && retVal;
retVal = NegTest4() && retVal;
retVal = NegTest5() && retVal;
retVal = NegTest6() && retVal;
return retVal;
}
#region Positive Test Cases
public bool PosTest1()
{
bool retVal = true;
// Add your scenario description here
TestLibrary.TestFramework.BeginScenario("PosTest1: Verify method Convert when count == bytes.Length .");
try
{
string unicodeStr = "test string .";
Encoding ascii = Encoding.UTF8;
Encoding unicode = Encoding.Unicode;
byte[] unicodeBytes = unicode.GetBytes(unicodeStr);
byte[] asciiBytes = Encoding.Convert(unicode, ascii, unicodeBytes,0,unicodeBytes.Length);
char[] asciiChars = new char[ascii.GetCharCount(asciiBytes, 0, asciiBytes.Length)];
ascii.GetChars(asciiBytes, 0, asciiBytes.Length, asciiChars, 0);
string asciiStr = new string(asciiChars);
if (unicodeStr != asciiStr)
{
TestLibrary.TestFramework.LogError("001.1", "Method Convert Err !");
retVal = false;
return retVal;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("001", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
public bool PosTest2()
{
bool retVal = true;
// Add your scenario description here
TestLibrary.TestFramework.BeginScenario("PosTest2: Verify method Convert when count == 0 .");
try
{
string unicodeStr = "test string .";
Encoding ascii = Encoding.UTF8;
Encoding unicode = Encoding.Unicode;
byte[] unicodeBytes = unicode.GetBytes(unicodeStr);
byte[] asciiBytes = Encoding.Convert(unicode, ascii, unicodeBytes, 0, 0);
char[] asciiChars = new char[ascii.GetCharCount(asciiBytes, 0, asciiBytes.Length)];
ascii.GetChars(asciiBytes, 0, asciiBytes.Length, asciiChars, 0);
string asciiStr = new string(asciiChars);
if (asciiStr != "")
{
TestLibrary.TestFramework.LogError("002.1", "Method Convert Err !");
retVal = false;
return retVal;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("002.2", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
public bool PosTest3()
{
bool retVal = true;
// Add your scenario description here
TestLibrary.TestFramework.BeginScenario("PosTest3: Verify method Convert when bytes == null.");
try
{
Encoding ascii = Encoding.UTF8;
Encoding unicode = Encoding.Unicode;
byte[] unicodeBytes = new byte[0];
byte[] asciiBytes = Encoding.Convert(unicode, ascii, unicodeBytes, 0, 0);
char[] asciiChars = new char[ascii.GetCharCount(asciiBytes, 0, asciiBytes.Length)];
ascii.GetChars(asciiBytes, 0, asciiBytes.Length, asciiChars, 0);
string asciiStr = new string(asciiChars);
if (asciiStr != "")
{
TestLibrary.TestFramework.LogError("003.1", "Method Convert Err !");
retVal = false;
return retVal;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("003.2", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
#endregion
#region Nagetive Test Cases
public bool NegTest1()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("NegTest1: ArgumentNullException is not thrown.");
try
{
string unicodeStr = "test string .";
Encoding ascii = null;
Encoding unicode = Encoding.Unicode;
byte[] unicodeBytes = unicode.GetBytes(unicodeStr);
byte[] asciiBytes = Encoding.Convert(unicode, ascii, unicodeBytes, 0, unicodeBytes.Length);
TestLibrary.TestFramework.LogError("101.1", "ArgumentNullException is not thrown.");
retVal = false;
}
catch (ArgumentNullException)
{ }
catch (Exception e)
{
TestLibrary.TestFramework.LogError("101.2", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
public bool NegTest2()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("NegTest2: ArgumentNullException is not thrown.");
try
{
Encoding ascii = Encoding.UTF8;
Encoding unicode = null;
byte[] unicodeBytes = new byte[] { 1, 2, 3 };
byte[] asciiBytes = Encoding.Convert(unicode, ascii, unicodeBytes, 0, unicodeBytes.Length);
TestLibrary.TestFramework.LogError("102.1", "ArgumentNullException is not thrown.");
retVal = false;
}
catch (ArgumentNullException)
{ }
catch (Exception e)
{
TestLibrary.TestFramework.LogError("102.2", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
public bool NegTest3()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("NegTest3: ArgumentNullException is not thrown.");
try
{
Encoding ascii = Encoding.UTF8;
Encoding unicode = Encoding.Unicode;
byte[] unicodeBytes = null;
byte[] asciiBytes = Encoding.Convert(unicode, ascii, unicodeBytes, 0, 2);
TestLibrary.TestFramework.LogError("103.1", "ArgumentNullException is not thrown.");
retVal = false;
}
catch (ArgumentNullException)
{ }
catch (Exception e)
{
TestLibrary.TestFramework.LogError("103.2", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
public bool NegTest4()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("NegTest4: ArgumentOutOfRangeException is not thrown.");
try
{
string unicodeStr = "test string .";
Encoding ascii = Encoding.UTF8;
Encoding unicode = Encoding.Unicode;
byte[] unicodeBytes = unicode.GetBytes(unicodeStr);
byte[] asciiBytes = Encoding.Convert(unicode, ascii, unicodeBytes, -1, unicodeBytes.Length);
TestLibrary.TestFramework.LogError("104.1", "ArgumentNullException is not thrown.");
retVal = false;
}
catch (ArgumentOutOfRangeException)
{ }
catch (Exception e)
{
TestLibrary.TestFramework.LogError("104.2", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
public bool NegTest5()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("NegTest5: ArgumentOutOfRangeException is not thrown.");
try
{
string unicodeStr = "test string .";
Encoding ascii = Encoding.UTF8;
Encoding unicode = Encoding.Unicode;
byte[] unicodeBytes = unicode.GetBytes(unicodeStr);
byte[] asciiBytes = Encoding.Convert(unicode, ascii, unicodeBytes, 0, unicodeBytes.Length + 1);
TestLibrary.TestFramework.LogError("105.1", "ArgumentNullException is not thrown.");
retVal = false;
}
catch (ArgumentOutOfRangeException)
{ }
catch (Exception e)
{
TestLibrary.TestFramework.LogError("105.2", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
public bool NegTest6()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("NegTest6: ArgumentOutOfRangeException is not thrown.");
try
{
string unicodeStr = "test string .";
Encoding ascii = Encoding.UTF8;
Encoding unicode = Encoding.Unicode;
byte[] unicodeBytes = unicode.GetBytes(unicodeStr);
byte[] asciiBytes = Encoding.Convert(unicode, ascii, unicodeBytes, 0, -1);
TestLibrary.TestFramework.LogError("106.1", "ArgumentNullException is not thrown.");
retVal = false;
}
catch (ArgumentOutOfRangeException)
{ }
catch (Exception e)
{
TestLibrary.TestFramework.LogError("106.2", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
#endregion
#endregion
public static int Main()
{
EncodingConvert2 test = new EncodingConvert2();
TestLibrary.TestFramework.BeginTestCase("EncodingConvert2");
if (test.RunTests())
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("PASS");
return 100;
}
else
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("FAIL");
return 0;
}
}
}
| |
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
namespace SAFish.PhotoTool
{
/// <summary>
/// Summary description for ProgressDialog.
/// </summary>
public class ProgressDialog : System.Windows.Forms.Form, IProgressCallback
{
#region Private Attributes
private System.Windows.Forms.Button cancelButton;
private System.Windows.Forms.Label label;
private System.Windows.Forms.ProgressBar progressBar;
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.Container components = null;
public delegate void SetTextInvoker(String text);
public delegate void ShowProgressInvoker(bool show);
public delegate void IncrementInvoker( int val );
public delegate void StepToInvoker( int val );
public delegate void RangeInvoker( int minimum, int maximum );
private String titleRoot = "";
private System.Threading.ManualResetEvent initEvent = new System.Threading.ManualResetEvent(false);
private System.Threading.ManualResetEvent abortEvent = new System.Threading.ManualResetEvent(false);
private bool requiresClose = true;
#endregion
#region Constructors
public ProgressDialog()
{
//
// Required for Windows Form Designer support
//
InitializeComponent();
}
#endregion
#region Implementation of IProgressCallback
/// <summary>
/// Call this method from the worker thread to initialize
/// the progress meter.
/// </summary>
/// <param name="minimum">The minimum value in the progress range (e.g. 0)</param>
/// <param name="maximum">The maximum value in the progress range (e.g. 100)</param>
public void Begin( int minimum, int maximum )
{
initEvent.WaitOne();
Invoke( new RangeInvoker( DoBegin ), new object[] { minimum, maximum } );
}
/// <summary>
/// Call this method from the worker thread to initialize
/// the progress callback, without setting the range
/// </summary>
public void Begin()
{
initEvent.WaitOne();
Invoke( new MethodInvoker( DoBegin ) );
}
/// <summary>
/// Call this method from the worker thread to reset the range in the progress callback
/// </summary>
/// <param name="minimum">The minimum value in the progress range (e.g. 0)</param>
/// <param name="maximum">The maximum value in the progress range (e.g. 100)</param>
/// <remarks>You must have called one of the Begin() methods prior to this call.</remarks>
public void SetRange( int minimum, int maximum )
{
initEvent.WaitOne();
Invoke( new RangeInvoker( DoSetRange ), new object[] { minimum, maximum } );
}
/// <summary>
/// Call this method from the worker thread to update the progress text.
/// </summary>
/// <param name="text">The progress text to display</param>
public void SetText( String text )
{
initEvent.WaitOne();
Invoke( new SetTextInvoker(DoSetText), new object[] { text } );
}
public void ShowProgress(bool show)
{
initEvent.WaitOne();
Invoke(new ShowProgressInvoker(DoShowProgress), new object[] { show } );
}
/// <summary>
/// Call this method from the worker thread to increase the progress counter by a specified value.
/// </summary>
/// <param name="val">The amount by which to increment the progress indicator</param>
public void Increment( int val )
{
initEvent.WaitOne();
Invoke( new IncrementInvoker( DoIncrement ), new object[] { val } );
}
/// <summary>
/// Call this method from the worker thread to step the progress meter to a particular value.
/// </summary>
/// <param name="val"></param>
public void StepTo( int val )
{
initEvent.WaitOne();
Invoke( new StepToInvoker( DoStepTo ), new object[] { val } );
}
/// <summary>
/// If this property is true, then you should abort work
/// </summary>
public bool IsAborting
{
get
{
return abortEvent.WaitOne( 0, false );
}
}
/// <summary>
/// Call this method from the worker thread to finalize the progress meter
/// </summary>
public void End()
{
if( requiresClose )
{
Invoke( new MethodInvoker( DoEnd ) );
}
}
#endregion
#region Implementation members invoked on the owner thread
private void DoSetText( String text )
{
string txt = text;
// make sure the text fits onto the label
Graphics g = Graphics.FromHwnd(this.Handle);
SizeF s = g.MeasureString(txt, label.Font);
while (s.Width > label.Width)
{
txt = txt.Substring(1);
s = g.MeasureString("..." + txt, label.Font);
}
if (txt != text) txt = "..." + txt;
label.Text = txt;
g.Dispose();
}
private void DoIncrement( int val )
{
progressBar.Increment( val );
UpdateStatusText();
}
private void DoShowProgress(bool show)
{
progressBar.Visible = show;
}
private void DoStepTo( int val )
{
progressBar.Value = val;
UpdateStatusText();
}
private void DoBegin( int minimum, int maximum )
{
DoBegin();
DoSetRange( minimum, maximum );
}
private void DoBegin()
{
cancelButton.Enabled = true;
ControlBox = true;
}
private void DoSetRange( int minimum, int maximum )
{
progressBar.Minimum = minimum;
progressBar.Maximum = maximum;
progressBar.Value = minimum;
titleRoot = Text;
}
private void DoEnd()
{
Close();
}
#endregion
#region Overrides
/// <summary>
/// Handles the form load, and sets an event to ensure that
/// intialization is synchronized with the appearance of the form.
/// </summary>
/// <param name="e"></param>
protected override void OnLoad(System.EventArgs e)
{
base.OnLoad( e );
ControlBox = false;
initEvent.Set();
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if(components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
/// <summary>
/// Handler for 'Close' clicking
/// </summary>
/// <param name="e"></param>
protected override void OnClosing(System.ComponentModel.CancelEventArgs e)
{
requiresClose = false;
AbortWork();
base.OnClosing( e );
}
#endregion
#region Private implementation methods
/// <summary>
/// Utility function that formats and updates the title bar text
/// </summary>
private void UpdateStatusText()
{
Text = titleRoot + String.Format( " - {0}% complete", (progressBar.Value * 100 ) / (progressBar.Maximum - progressBar.Minimum) );
}
/// <summary>
/// Utility function to terminate the thread
/// </summary>
private void AbortWork()
{
abortEvent.Set();
}
#endregion
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.progressBar = new System.Windows.Forms.ProgressBar();
this.label = new System.Windows.Forms.Label();
this.cancelButton = new System.Windows.Forms.Button();
this.SuspendLayout();
//
// progressBar
//
this.progressBar.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.progressBar.Location = new System.Drawing.Point(8, 48);
this.progressBar.Name = "progressBar";
this.progressBar.Size = new System.Drawing.Size(192, 23);
this.progressBar.Step = 1;
this.progressBar.TabIndex = 1;
//
// label
//
this.label.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.label.Location = new System.Drawing.Point(8, 8);
this.label.Name = "label";
this.label.Size = new System.Drawing.Size(272, 32);
this.label.TabIndex = 0;
this.label.Text = "Initialising...";
//
// cancelButton
//
this.cancelButton.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.cancelButton.DialogResult = System.Windows.Forms.DialogResult.Cancel;
this.cancelButton.Enabled = false;
this.cancelButton.Location = new System.Drawing.Point(208, 48);
this.cancelButton.Name = "cancelButton";
this.cancelButton.TabIndex = 2;
this.cancelButton.Text = "Cancel";
//
// ProgressDialog
//
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.ClientSize = new System.Drawing.Size(290, 79);
this.ControlBox = false;
this.Controls.Add(this.cancelButton);
this.Controls.Add(this.progressBar);
this.Controls.Add(this.label);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
this.MaximizeBox = false;
this.MinimizeBox = false;
this.Name = "ProgressDialog";
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent;
this.Text = " Progress";
this.ResumeLayout(false);
}
#endregion
}
}
| |
// Copyright 2020 The Tilt Brush Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System;
using System.Collections.Generic;
using UnityEngine;
namespace TiltBrush {
/*
Design questions raised:
- How should strokes be saved?
1. Save one stroke, with the control points of the parent-most stroke.
At load time, reconstruct the entire tree of strokes.
2. "Bake" out all strokes with geometry; ignore parent strokes.
At load time this looks like a normal sketch.
Tradeoffs:
#1 makes sketches more fragile; more logic is run at load time, and if that
logic changes, the sketch changes. Also, #1 requires a hacked Tilt Brush to
load. #2 can be loaded by a regular build.
- How should #1 be implemented? We currently assume one stroke <-> one batch.
Generalize it to one stroke <-> many batches?
When line is ended, currently Pointer is in charge of finalization, then
it passes the line (and maybe subset) to SketchMemory.
Instead, pass the line only to SketchMemory, and have it do the finalization
(if necessary) and saving of the strokes.
- How should #2 be implemented?
We'd have to remove control-point storage out of PointerScript (a good idea anyway).
Then we could call MemorizeBrushStroke on each of the strokes in the tree.
*/
/// ParentBrush is an experimental brush which does not have any geometry itself;
/// instead, it has child brushes which may either create geometry, or be ParentBrushes
/// themselves(!).
public abstract class ParentBrush : BaseBrushScript {
/// Enumerates the coordinate frames associated with knots that are useful for attachments.
[Serializable]
public enum AttachFrame {
/// The pose of the input device (or Pointer) when the knot was placed.
Pointer,
/// Assumes the Knots describe a line. Forward is aligned to the tangent; right and up are
/// normal and binormal. Parallel transport is used to determine how right and up change
/// from knot to knot, so this framing is all bend, no twist.
LineTangent,
// Assumes Knots describe a ribbon. Forward is the main tangent (the one that's also the
// line tangent); ??? is the bitangent (ie the other surface tangent); and ??? is the
// surface normal. Currently unused.
RibbonTangent,
}
/// Analagous to GeometryBrush's knots, but less info is needed.
protected class PbKnot {
// Pose of the pointer, in Canvas space.
public TrTransform m_pointer;
// Just a quat because T and S are assumed to be the same as m_pointer.
public Quaternion? m_tangentFrame;
// Total distance from knot 0.
public float m_distance;
// Stroke BaseSize, modulated by pressure.
public float m_pressuredSize;
public TrTransform CanvasFromTool {
get {
return TrTransform.TR(m_pointer.translation, m_pointer.rotation);
}
}
public TrTransform CanvasFromTangent {
get {
if (m_tangentFrame == null) {
throw new InvalidOperationException("Frame not defined on this knot");
}
return TrTransform.TR(m_pointer.translation, m_tangentFrame.Value);
}
}
public TrTransform GetFrame(AttachFrame frame) {
switch (frame) {
case AttachFrame.Pointer: return CanvasFromTool;
case AttachFrame.LineTangent: return CanvasFromTangent;
default: throw new NotImplementedException();
}
}
public PbKnot Clone() {
return new PbKnot {
m_pointer = m_pointer,
m_tangentFrame = m_tangentFrame,
m_distance = m_distance,
m_pressuredSize = m_pressuredSize
};
}
}
//
// PbChild classes
//
/// This is the main abstraction that determines the movement/behavior of child brushes.
protected abstract class PbChild {
public BaseBrushScript m_brush;
/// Returns a pointer position for the child brush.
public TrTransform CalculateChildXfFixedScale(List<PbKnot> parentKnots) {
// Brushes interpret .scale to mean "size of the person/pointer drawing me".
// They also assume that .scale is identical for all knots in the stroke, since
// users can't draw and scale themselves at the same time.
// Thus, for now, keep enforcing that assumption.
// TODO: revisit this when we understand more.
var ret = CalculateChildXf(parentKnots);
return TrTransform.TRS(ret.translation, ret.rotation, parentKnots[0].m_pointer.scale);
}
// Subclasses should return a canvas-space position and orientation for the child pointer.
// The parent pointer's position can be inferred from the transform of the most-recent knot.
// At the moment, .scale on the return value is ignored.
protected abstract TrTransform CalculateChildXf(List<PbKnot> parentKnots);
}
/// The simplest possible implementation -- doesn't modify pointer transform at all.
protected class PbChildIdentityXf : PbChild {
protected override TrTransform CalculateChildXf(List<PbKnot> parentKnots) {
var cur = parentKnots[parentKnots.Count-1];
return cur.m_pointer;
}
}
/// A PbChild that need some sort of knot-based reference frame.
protected abstract class PbChildWithKnotBasedFrame : PbChild {
public readonly int m_frameKnot;
public readonly AttachFrame m_frame;
/// If frameKnot is < 0, it is relative to a knot at the current end of the stroke.
public PbChildWithKnotBasedFrame(int frameKnot, AttachFrame frame) {
m_frameKnot = frameKnot;
m_frame = frame;
}
/// Returns the attach point for this child, as a knot.
/// See also GetAttachTransform().
public PbKnot GetAttachKnot(List<PbKnot> parentKnots) {
int knotIndex = (m_frameKnot >= 0) ? m_frameKnot : parentKnots.Count + m_frameKnot;
return parentKnots[knotIndex];
}
/// Returns the attach point for this child, as a TrTransform.
public TrTransform GetAttachTransform(List<PbKnot> parentKnots) {
return GetAttachKnot(parentKnots).GetFrame(m_frame);
}
}
/// Applies a transform, specified relative to a knot's tangent or pointer frame.
///
/// The knot may be specified relative to the start of the stroke for things like tree
/// branches, or relative to the current end of the stroke for things like spirals.
///
/// There is an optional distance-based twist about frame-forward.
protected class PbChildWithOffset : PbChildWithKnotBasedFrame {
public TrTransform m_offset;
public float m_twist;
public bool m_pressureAffectsOffset;
/// Pass:
/// frameKnot - the index of a knot; negative to index from the end.
/// offset - specified relative to the knot+frame, as a %age of brush size.
/// twist - in degrees-per-meter; rotates based on distance from initial knot
/// pressureAffectsOffset - true if the offset should be modulated by pressure, too.
/// For example, the rungs of a double-helix should be closer to the parent
/// when pressure makes the brush smaller; but maybe a tickertape should remain
/// constant-size and pressure only affects the stuff written on the tape.
public PbChildWithOffset(int frameKnot, AttachFrame frame, TrTransform offset, float twist,
bool pressureAffectsOffset = true)
: base(frameKnot, frame) {
m_offset = offset;
m_twist = twist;
m_pressureAffectsOffset = pressureAffectsOffset;
}
protected override TrTransform CalculateChildXf(List<PbKnot> parentKnots) {
TrTransform actionInCanvasSpace; {
PbKnot knot = GetAttachKnot(parentKnots);
float rotationDegrees = knot.m_distance * App.UNITS_TO_METERS * m_twist;
TrTransform offset = m_offset;
// It's cleaner to tack a TrTransform.S(size) onto the action, but that
// would modify .scale, which is currently interpreted as "pointer size"
// (affecting control point density) and which is also assumed by most
// brushes to be constant.
if (m_pressureAffectsOffset) {
offset.translation *= knot.m_pressuredSize;
} else {
offset.translation *= m_brush.BaseSize_LS;
}
TrTransform action =
TrTransform.R(Quaternion.AngleAxis(rotationDegrees, Vector3.forward))
* offset;
actionInCanvasSpace = action.TransformBy(knot.GetFrame(m_frame));
}
var cur = parentKnots[parentKnots.Count-1];
return actionInCanvasSpace * cur.m_pointer;
}
}
//
// Instance api
//
const float kSolidAspectRatio = 0.2f;
protected List<PbKnot> m_knots = new List<PbKnot>();
protected List<PbChild> m_children = new List<PbChild>();
protected int m_recursionLevel = 0;
//
// ParentBrush stuff
//
public ParentBrush() : base(bCanBatch : false) { }
// Finishes initializing the passed PbChild, and adds to children array
protected void InitializeAndAddChild(
PbChild child,
BrushDescriptor desc, Color color, float relativeSize = 1) {
Debug.Assert(child.m_brush == null);
TrTransform childXf = child.CalculateChildXfFixedScale(m_knots);
BaseBrushScript brush = Create(
transform.parent, childXf, desc, color, m_BaseSize_PS * relativeSize);
ParentBrush pb = brush as ParentBrush;
string originalName = brush.gameObject.name;
string newName;
if (pb != null) {
newName = string.Format("{0}.{1}", gameObject.name, m_children.Count);
} else {
newName = string.Format(
"{0}.{1} (Leaf {2})", gameObject.name, m_children.Count, originalName);
}
brush.gameObject.name = newName;
if (pb != null) {
pb.m_recursionLevel = m_recursionLevel + 1;
}
child.m_brush = brush;
m_children.Add(child);
}
private void MaybeCreateChildren() {
// Wait until we have a tangent frame
if (m_knots[1].m_tangentFrame == null) { return; }
// Wait until we have non-zero size, because creating children with size 0 is terrible.
// The preview line is evil and changes our size between control points.
if (m_BaseSize_PS == 0) { return; }
MaybeCreateChildrenImpl();
}
// Looks through children to find ones that are attached to a knot.
// Returns the distance to the most recent knot with a child.
// If there are no such children, returns distance to the start of stroke.
protected float DistanceSinceLastKnotBasedChild() {
PbKnot cur = m_knots[m_knots.Count-1];
float minDistance = cur.m_distance;
foreach (var child_ in m_children) {
var child = child_ as PbChildWithOffset;
if (child != null) {
float distanceFromChildToTip = cur.m_distance - child.GetAttachKnot(m_knots).m_distance;
minDistance = Mathf.Min(minDistance, distanceFromChildToTip);
}
}
return minDistance;
}
void OnDestroy() {
foreach (var child in m_children) {
BaseBrushScript bbs = child.m_brush;
bbs.DestroyMesh();
Destroy(bbs.gameObject);
}
}
/// Subclasses should fill this in.
/// Callee can assume the size is valid and at least one tangent frame exists.
protected abstract void MaybeCreateChildrenImpl();
//
// BaseBrushScript api
//
protected override bool UpdatePositionImpl(
Vector3 translation, Quaternion rotation, float pressure) {
TrTransform parentXf = TrTransform.TR(translation, rotation);
// Update m_knots
{
Debug.Assert(m_knots.Count > 1, "There should always be at least 2 knots");
PbKnot cur = m_knots[m_knots.Count-1];
PbKnot prev = m_knots[m_knots.Count-2];
Vector3 move = parentXf.translation - prev.m_pointer.translation;
cur.m_pointer = parentXf;
float moveLen = move.magnitude;
cur.m_tangentFrame = (moveLen > 1e-5f)
? MathUtils.ComputeMinimalRotationFrame(
move / moveLen, prev.m_tangentFrame, cur.m_pointer.rotation)
: prev.m_tangentFrame;
cur.m_distance = prev.m_distance + moveLen;
cur.m_pressuredSize = PressuredSize(pressure);
}
MaybeCreateChildren();
bool createdControlPoint = false;
for (int i = 0; i < m_children.Count; ++i) {
PbChild child = m_children[i];
var childXf = child.CalculateChildXfFixedScale(m_knots);
if (child.m_brush.UpdatePosition_LS(childXf, pressure)) {
// Need to save off any control point which is applicable to any of our children.
// This does mean that if we have a giant tree of children, we might be saving
// off every control point.
// TODO: maybe there's a way for the parent to impose some order on this;
// like it doesn't always send positions to its children? But that would make
// interactive drawing less pretty.
createdControlPoint = true;
}
}
if (createdControlPoint) {
m_knots.Add(m_knots[m_knots.Count - 1].Clone());
}
return createdControlPoint;
}
void CommonInit(TrTransform localPointerXf) {
for (int i = 0; i < 2; ++i) {
m_knots.Add(new PbKnot {
m_pointer = localPointerXf,
m_pressuredSize = PressuredSize(1)
});
}
}
protected override void InitBrush(BrushDescriptor desc, TrTransform localPointerXf) {
base.InitBrush(desc, localPointerXf);
CommonInit(localPointerXf);
}
public override void ResetBrushForPreview(TrTransform localPointerXf) {
base.ResetBrushForPreview(localPointerXf);
m_knots.Clear();
foreach (var child in m_children) {
if (child != null) {
Destroy(child.m_brush.gameObject);
}
}
m_children.Clear();
CommonInit(localPointerXf);
}
public override bool AlwaysRebuildPreviewBrush() {
return true;
}
public override GeometryPool.VertexLayout GetVertexLayout(BrushDescriptor desc) {
return new GeometryPool.VertexLayout {
bUseColors = false,
bUseNormals = false,
bUseTangents = false,
uv0Size = 2,
uv0Semantic = GeometryPool.Semantic.XyIsUv,
uv1Size = 0,
uv1Semantic = GeometryPool.Semantic.Unspecified
};
}
public override void ApplyChangesToVisuals() {
foreach (var child in m_children) {
child.m_brush.ApplyChangesToVisuals();
}
}
public override int GetNumUsedVerts() {
// TODO: can this be zero? I seem to remember bad things happening
// with brushes that return 0, should check.
int count = 1;
foreach (var child in m_children) {
count += child.m_brush.GetNumUsedVerts();
}
return count;
}
public override float GetSpawnInterval(float pressure01) {
return PressuredSize(pressure01) * kSolidAspectRatio;
}
protected override void InitUndoClone(GameObject clone) {
// TODO: CloneAsUndoObject() won't clone any of our children (because they're
// not in transform.children). And even if it could, we'd have difficulties mapping
// m_children to transform.children. I guess we could assume they're parallel arrays.
//
// I think the correct thing to do here is to move CloneAsUndoObject() into BaseBrushScript.
}
public override void FinalizeSolitaryBrush() {
foreach (var child in m_children) {
child.m_brush.FinalizeSolitaryBrush();
}
}
public override BatchSubset FinalizeBatchedBrush() {
throw new NotImplementedException();
}
}
} // namespace TiltBrush
| |
using System;
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Orleans.Configuration;
namespace Orleans.Runtime
{
/// <summary>
/// Identifies activations that have been idle long enough to be deactivated.
/// </summary>
internal class ActivationCollector : IActivationCollector
{
internal Action<GrainId> Debug_OnDecideToCollectActivation;
private readonly TimeSpan quantum;
private readonly TimeSpan shortestAgeLimit;
private readonly ConcurrentDictionary<DateTime, Bucket> buckets;
private readonly object nextTicketLock;
private DateTime nextTicket;
private static readonly List<ActivationData> nothing = new List<ActivationData> { Capacity = 0 };
private readonly ILogger logger;
public ActivationCollector(IOptions<GrainCollectionOptions> options, ILogger<ActivationCollector> logger)
{
if (TimeSpan.Zero == options.Value.CollectionQuantum)
{
throw new ArgumentException("Globals.CollectionQuantum cannot be zero.", "config");
}
quantum = options.Value.CollectionQuantum;
shortestAgeLimit = TimeSpan.FromTicks(options.Value.ClassSpecificCollectionAge.Values
.Aggregate(options.Value.CollectionAge.Ticks, (a,v) => Math.Min(a,v.Ticks)));
buckets = new ConcurrentDictionary<DateTime, Bucket>();
nextTicket = MakeTicketFromDateTime(DateTime.UtcNow);
nextTicketLock = new object();
this.logger = logger;
}
public TimeSpan Quantum { get { return quantum; } }
private int ApproximateCount
{
get
{
int sum = 0;
foreach (var bucket in buckets.Values)
{
sum += bucket.ApproximateCount;
}
return sum;
}
}
// Return the number of activations that were used (touched) in the last recencyPeriod.
public int GetNumRecentlyUsed(TimeSpan recencyPeriod)
{
if (TimeSpan.Zero == shortestAgeLimit)
{
// Collection has been disabled for some types.
return ApproximateCount;
}
var now = DateTime.UtcNow;
int sum = 0;
foreach (var bucket in buckets)
{
// Ticket is the date time when this bucket should be collected (last touched time plus age limit)
// For now we take the shortest age limit as an approximation of the per-type age limit.
DateTime ticket = bucket.Key;
var timeTillCollection = ticket - now;
var timeSinceLastUsed = shortestAgeLimit - timeTillCollection;
if (timeSinceLastUsed <= recencyPeriod)
{
sum += bucket.Value.ApproximateCount;
}
}
return sum;
}
public void ScheduleCollection(ActivationData item)
{
lock (item)
{
if (item.IsExemptFromCollection)
{
return;
}
TimeSpan timeout = item.CollectionAgeLimit;
if (TimeSpan.Zero == timeout)
{
// either the CollectionAgeLimit hasn't been initialized (will be rectified later) or it's been disabled.
return;
}
DateTime ticket = MakeTicketFromTimeSpan(timeout);
if (default(DateTime) != item.CollectionTicket)
{
throw new InvalidOperationException("Call CancelCollection before calling ScheduleCollection.");
}
Add(item, ticket);
}
}
public bool TryCancelCollection(ActivationData item)
{
if (item.IsExemptFromCollection) return false;
lock (item)
{
DateTime ticket = item.CollectionTicket;
if (default(DateTime) == ticket) return false;
if (IsExpired(ticket)) return false;
// first, we attempt to remove the ticket.
Bucket bucket;
if (!buckets.TryGetValue(ticket, out bucket) || !bucket.TryRemove(item)) return false;
}
return true;
}
public bool TryRescheduleCollection(ActivationData item)
{
if (item.IsExemptFromCollection) return false;
lock (item)
{
if (TryRescheduleCollection_Impl(item, item.CollectionAgeLimit)) return true;
item.ResetCollectionTicket();
return false;
}
}
private bool TryRescheduleCollection_Impl(ActivationData item, TimeSpan timeout)
{
// note: we expect the activation lock to be held.
if (default(DateTime) == item.CollectionTicket) return false;
ThrowIfTicketIsInvalid(item.CollectionTicket);
if (IsExpired(item.CollectionTicket)) return false;
DateTime oldTicket = item.CollectionTicket;
DateTime newTicket = MakeTicketFromTimeSpan(timeout);
// if the ticket value doesn't change, then the source and destination bucket are the same and there's nothing to do.
if (newTicket.Equals(oldTicket)) return true;
Bucket bucket;
if (!buckets.TryGetValue(oldTicket, out bucket) || !bucket.TryRemove(item))
{
// fail: item is not associated with currentKey.
return false;
}
// it shouldn't be possible for Add to throw an exception here, as only one concurrent competitor should be able to reach to this point in the method.
item.ResetCollectionTicket();
Add(item, newTicket);
return true;
}
private bool DequeueQuantum(out IEnumerable<ActivationData> items, DateTime now)
{
DateTime key;
lock (nextTicketLock)
{
if (nextTicket > now)
{
items = null;
return false;
}
key = nextTicket;
nextTicket += quantum;
}
Bucket bucket;
if (!buckets.TryRemove(key, out bucket))
{
items = nothing;
return true;
}
items = bucket.CancelAll();
return true;
}
public override string ToString()
{
var now = DateTime.UtcNow;
return string.Format("<#Activations={0}, #Buckets={1}, buckets={2}>",
ApproximateCount,
buckets.Count,
Utils.EnumerableToString(
buckets.Values.OrderBy(bucket => bucket.Key), bucket => Utils.TimeSpanToString(bucket.Key - now) + "->" + bucket.ApproximateCount + " items"));
}
/// <summary>
/// Scans for activations that are due for collection.
/// </summary>
/// <returns>A list of activations that are due for collection.</returns>
public List<ActivationData> ScanStale()
{
var now = DateTime.UtcNow;
List<ActivationData> result = null;
IEnumerable<ActivationData> activations;
while (DequeueQuantum(out activations, now))
{
// at this point, all tickets associated with activations are cancelled and any attempts to reschedule will fail silently. if the activation is to be reactivated, it's our job to clear the activation's copy of the ticket.
foreach (var activation in activations)
{
lock (activation)
{
activation.ResetCollectionTicket();
if (activation.State != ActivationState.Valid)
{
// Do nothing: don't collect, don't reschedule.
// The activation can't be in Created or Activating, since we only ScheduleCollection after successfull activation.
// If the activation is already in Deactivating or Invalid state, its already being collected or was collected
// (both mean a bug, this activation should not be in the collector)
// So in any state except for Valid we should just not collect and not reschedule.
logger.Warn(ErrorCode.Catalog_ActivationCollector_BadState_1,
"ActivationCollector found an activation in a non Valid state. All activation inside the ActivationCollector should be in Valid state. Activation: {0}",
activation.ToDetailedString());
}
else if (activation.ShouldBeKeptAlive)
{
// Consider: need to reschedule to what is the remaining time for ShouldBeKeptAlive, not the full CollectionAgeLimit.
ScheduleCollection(activation);
}
else if (!activation.IsInactive)
{
// This is essentialy a bug, an active activation should not be in the last bucket.
logger.Warn(ErrorCode.Catalog_ActivationCollector_BadState_2,
"ActivationCollector found an active activation in it's last bucket. This is violation of ActivationCollector invariants. " +
"For now going to defer it's collection. Activation: {0}",
activation.ToDetailedString());
ScheduleCollection(activation);
}
else if (!activation.IsStale(now))
{
// This is essentialy a bug, a non stale activation should not be in the last bucket.
logger.Warn(ErrorCode.Catalog_ActivationCollector_BadState_3,
"ActivationCollector found a non stale activation in it's last bucket. This is violation of ActivationCollector invariants. Now: {0}" +
"For now going to defer it's collection. Activation: {1}",
LogFormatter.PrintDate(now),
activation.ToDetailedString());
ScheduleCollection(activation);
}
else
{
// Atomically set Deactivating state, to disallow any new requests or new timer ticks to be dispatched on this activation.
activation.PrepareForDeactivation();
DecideToCollectActivation(activation, ref result);
}
}
}
}
return result ?? nothing;
}
/// <summary>
/// Scans for activations that have been idle for the specified age limit.
/// </summary>
/// <param name="ageLimit">The age limit.</param>
/// <returns></returns>
public List<ActivationData> ScanAll(TimeSpan ageLimit)
{
List<ActivationData> result = null;
var now = DateTime.UtcNow;
int bucketCount = buckets.Count;
int i = 0;
foreach (var bucket in buckets.Values)
{
if (i >= bucketCount) break;
int notToExceed = bucket.ApproximateCount;
int j = 0;
foreach (var activation in bucket)
{
// theoretically, we could iterate forever on the ConcurrentDictionary. we limit ourselves to an approximation of the bucket's Count property to limit the number of iterations we perform.
if (j >= notToExceed) break;
lock (activation)
{
if (activation.State != ActivationState.Valid)
{
// Do nothing: don't collect, don't reschedule.
}
else if (activation.ShouldBeKeptAlive)
{
// do nothing
}
else if (!activation.IsInactive)
{
// do nothing
}
else
{
if (activation.GetIdleness(now) >= ageLimit)
{
if (bucket.TryRemove(activation))
{
// we removed the activation from the collector. it's our responsibility to deactivate it.
activation.PrepareForDeactivation();
DecideToCollectActivation(activation, ref result);
}
// someone else has already deactivated the activation, so there's nothing to do.
}
else
{
// activation is not idle long enough for collection. do nothing.
}
}
}
++j;
}
++i;
}
return result ?? nothing;
}
private void DecideToCollectActivation(ActivationData activation, ref List<ActivationData> condemned)
{
if (null == condemned)
{
condemned = new List<ActivationData> { activation };
}
else
{
condemned.Add(activation);
}
this.Debug_OnDecideToCollectActivation?.Invoke(activation.Grain);
}
private static void ThrowIfTicketIsInvalid(DateTime ticket, TimeSpan quantum)
{
ThrowIfDefault(ticket, "ticket");
if (0 != ticket.Ticks % quantum.Ticks)
{
throw new ArgumentException(string.Format("invalid ticket ({0})", ticket));
}
}
private void ThrowIfTicketIsInvalid(DateTime ticket)
{
ThrowIfTicketIsInvalid(ticket, quantum);
}
private void ThrowIfExemptFromCollection(ActivationData activation, string name)
{
if (activation.IsExemptFromCollection)
{
throw new ArgumentException(string.Format("{0} should not refer to a system target or system grain.", name), name);
}
}
private bool IsExpired(DateTime ticket)
{
return ticket < nextTicket;
}
private DateTime MakeTicketFromDateTime(DateTime timestamp)
{
// round the timestamp to the next quantum. e.g. if the quantum is 1 minute and the timestamp is 3:45:22, then the ticket will be 3:46. note that TimeStamp.Ticks and DateTime.Ticks both return a long.
DateTime ticket = new DateTime(((timestamp.Ticks - 1) / quantum.Ticks + 1) * quantum.Ticks);
if (ticket < nextTicket)
{
throw new ArgumentException(string.Format("The earliest collection that can be scheduled from now is for {0}", new DateTime(nextTicket.Ticks - quantum.Ticks + 1)));
}
return ticket;
}
private DateTime MakeTicketFromTimeSpan(TimeSpan timeout)
{
if (timeout < quantum)
{
throw new ArgumentException(String.Format("timeout must be at least {0}, but it is {1}", quantum, timeout), "timeout");
}
return MakeTicketFromDateTime(DateTime.UtcNow + timeout);
}
private void Add(ActivationData item, DateTime ticket)
{
// note: we expect the activation lock to be held.
item.ResetCollectionCancelledFlag();
Bucket bucket =
buckets.GetOrAdd(
ticket,
key =>
new Bucket(key, quantum));
bucket.Add(item);
item.SetCollectionTicket(ticket);
}
static private void ThrowIfDefault<T>(T value, string name) where T : IEquatable<T>
{
if (value.Equals(default(T)))
{
throw new ArgumentException(string.Format("default({0}) is not allowed in this context.", typeof(T).Name), name);
}
}
private class Bucket : IEnumerable<ActivationData>
{
private readonly DateTime key;
private readonly ConcurrentDictionary<ActivationId, ActivationData> items;
public DateTime Key { get { return key; } }
public int ApproximateCount { get { return items.Count; } }
public Bucket(DateTime key, TimeSpan quantum)
{
ThrowIfTicketIsInvalid(key, quantum);
this.key = key;
items = new ConcurrentDictionary<ActivationId, ActivationData>();
}
public void Add(ActivationData item)
{
if (!items.TryAdd(item.ActivationId, item))
{
throw new InvalidOperationException("item is already associated with this bucket");
}
}
public bool TryRemove(ActivationData item)
{
if (!item.TrySetCollectionCancelledFlag()) return false;
return items.TryRemove(item.ActivationId, out ActivationData unused);
}
public IEnumerable<ActivationData> CancelAll()
{
List<ActivationData> result = null;
foreach (var pair in items)
{
// attempt to cancel the item. if we succeed, it wasn't already cancelled and we can return it. otherwise, we silently ignore it.
if (pair.Value.TrySetCollectionCancelledFlag())
{
if (result == null)
{
// we only need to ensure there's enough space left for this element and any potential entries.
result = new List<ActivationData>();
}
result.Add(pair.Value);
}
}
return result ?? nothing;
}
public IEnumerator<ActivationData> GetEnumerator()
{
return items.Values.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}
}
}
| |
// Copyright (c) 2012, Event Store LLP
// 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 Event Store LLP 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.Threading;
using EventStore.ClientAPI.Common.Concurrent;
using EventStore.ClientAPI.Common.Utils;
using EventStore.ClientAPI.Exceptions;
using EventStore.ClientAPI.SystemData;
namespace EventStore.ClientAPI
{
/// <summary>
/// Base class representing catch-up subscriptions.
/// </summary>
public abstract class EventStoreCatchUpSubscription
{
private const int DefaultReadBatchSize = 500;
private const int DefaultMaxPushQueueSize = 10000;
private static readonly ResolvedEvent DropSubscriptionEvent = new ResolvedEvent();
/// <summary>
/// Indicates whether the subscription is to all events or to
/// a specific stream.
/// </summary>
public bool IsSubscribedToAll { get { return _streamId == string.Empty; } }
/// <summary>
/// The name of the stream to which the subscription is subscribed
/// (empty if subscribed to all).
/// </summary>
public string StreamId { get { return _streamId; } }
/// <summary>
/// The <see cref="ILogger"/> to use for the subscription.
/// </summary>
protected readonly ILogger Log;
private readonly IEventStoreConnection _connection;
private readonly bool _resolveLinkTos;
private readonly UserCredentials _userCredentials;
private readonly string _streamId;
/// <summary>
/// The batch size to use during the read phase of the subscription.
/// </summary>
protected readonly int ReadBatchSize;
/// <summary>
/// The maximum number of events to buffer before the subscription drops.
/// </summary>
protected readonly int MaxPushQueueSize;
/// <summary>
/// Action invoked when a new event appears on the subscription.
/// </summary>
protected readonly Action<EventStoreCatchUpSubscription, ResolvedEvent> EventAppeared;
private readonly Action<EventStoreCatchUpSubscription> _liveProcessingStarted;
private readonly Action<EventStoreCatchUpSubscription, SubscriptionDropReason, Exception> _subscriptionDropped;
/// <summary>
/// Whether or not to use verbose logging (useful during debugging).
/// </summary>
protected readonly bool Verbose;
private readonly ConcurrentQueue<ResolvedEvent> _liveQueue = new ConcurrentQueue<ResolvedEvent>();
private EventStoreSubscription _subscription;
private DropData _dropData;
private volatile bool _allowProcessing;
private int _isProcessing;
private volatile bool _stop;
private int _isDropped;
private readonly ManualResetEventSlim _stopped = new ManualResetEventSlim(true);
/// <summary>
/// Read events until the given position or event number.
/// </summary>
/// <param name="connection">The connection.</param>
/// <param name="resolveLinkTos">Whether to resolve Link events.</param>
/// <param name="userCredentials">User credentials for the operation.</param>
/// <param name="lastCommitPosition">The commit position to read until.</param>
/// <param name="lastEventNumber">The event number to read until.</param>
protected abstract void ReadEventsTill(IEventStoreConnection connection,
bool resolveLinkTos,
UserCredentials userCredentials,
long? lastCommitPosition,
int? lastEventNumber);
/// <summary>
/// Try to process a single <see cref="ResolvedEvent"/>.
/// </summary>
/// <param name="e">The <see cref="ResolvedEvent"/> to process.</param>
protected abstract void TryProcess(ResolvedEvent e);
/// <summary>
/// Constructs state for EventStoreCatchUpSubscription.
/// </summary>
/// <param name="connection">The connection.</param>
/// <param name="log">The <see cref="ILogger"/> to use.</param>
/// <param name="streamId">The stream name.</param>
/// <param name="resolveLinkTos">Whether to resolve Link events.</param>
/// <param name="userCredentials">User credentials for the operations.</param>
/// <param name="eventAppeared">Action invoked when events are received.</param>
/// <param name="liveProcessingStarted">Action invoked when the read phase finishes.</param>
/// <param name="subscriptionDropped">Action invoked if the subscription drops.</param>
/// <param name="verboseLogging">Whether to use verbose logging.</param>
/// <param name="readBatchSize">Batch size for use in the reading phase.</param>
/// <param name="maxPushQueueSize">The maximum number of events to buffer before dropping the subscription.</param>
protected EventStoreCatchUpSubscription(IEventStoreConnection connection,
ILogger log,
string streamId,
bool resolveLinkTos,
UserCredentials userCredentials,
Action<EventStoreCatchUpSubscription, ResolvedEvent> eventAppeared,
Action<EventStoreCatchUpSubscription> liveProcessingStarted,
Action<EventStoreCatchUpSubscription, SubscriptionDropReason, Exception> subscriptionDropped,
bool verboseLogging,
int readBatchSize = DefaultReadBatchSize,
int maxPushQueueSize = DefaultMaxPushQueueSize)
{
Ensure.NotNull(connection, "connection");
Ensure.NotNull(log, "log");
Ensure.NotNull(eventAppeared, "eventAppeared");
Ensure.Positive(readBatchSize, "readBatchSize");
Ensure.Positive(maxPushQueueSize, "maxPushQueueSize");
_connection = connection;
Log = log;
_streamId = string.IsNullOrEmpty(streamId) ? string.Empty : streamId;
_resolveLinkTos = resolveLinkTos;
_userCredentials = userCredentials;
ReadBatchSize = readBatchSize;
MaxPushQueueSize = maxPushQueueSize;
EventAppeared = eventAppeared;
_liveProcessingStarted = liveProcessingStarted;
_subscriptionDropped = subscriptionDropped;
Verbose = verboseLogging;
}
internal void Start()
{
if (Verbose) Log.Debug("Catch-up Subscription to {0}: starting...", IsSubscribedToAll ? "<all>" : StreamId);
RunSubscription();
}
/// <summary>
/// Attempts to stop the subscription.
/// </summary>
/// <param name="timeout">The amount of time within which the subscription should stop.</param>
/// <exception cref="TimeoutException">Thrown if the subscription fails to stop within it's timeout period.</exception>
public void Stop(TimeSpan timeout)
{
if (Verbose) Log.Debug("Catch-up Subscription to {0}: requesting stop...", IsSubscribedToAll ? "<all>" : StreamId);
if (Verbose) Log.Debug("Catch-up Subscription to {0}: unhooking from connection.Connected.");
_connection.Connected -= OnReconnect;
_stop = true;
EnqueueSubscriptionDropNotification(SubscriptionDropReason.UserInitiated, null);
if (!_stopped.Wait(timeout))
throw new TimeoutException(string.Format("Couldn't stop {0} in time.", GetType().Name));
}
private void OnReconnect(object sender, ClientConnectionEventArgs clientConnectionEventArgs)
{
if (Verbose) Log.Debug("Catch-up Subscription to {0}: recovering after reconnection.");
if (Verbose) Log.Debug("Catch-up Subscription to {0}: unhooking from connection.Connected.");
_connection.Connected -= OnReconnect;
RunSubscription();
}
private void RunSubscription()
{
ThreadPool.QueueUserWorkItem(_ =>
{
if (Verbose) Log.Debug("Catch-up Subscription to {0}: running...", IsSubscribedToAll ? "<all>" : StreamId);
_stopped.Reset();
try
{
if (!_stop)
{
if (Verbose) Log.Debug("Catch-up Subscription to {0}: pulling events...", IsSubscribedToAll ? "<all>" : StreamId);
ReadEventsTill(_connection, _resolveLinkTos, _userCredentials, null, null);
}
if (!_stop)
{
if (Verbose) Log.Debug("Catch-up Subscription to {0}: subscribing...", IsSubscribedToAll ? "<all>" : StreamId);
_subscription = _streamId == string.Empty
? _connection.SubscribeToAll(_resolveLinkTos, EnqueuePushedEvent, ServerSubscriptionDropped, _userCredentials)
: _connection.SubscribeToStream(_streamId, _resolveLinkTos, EnqueuePushedEvent, ServerSubscriptionDropped, _userCredentials);
if (Verbose) Log.Debug("Catch-up Subscription to {0}: pulling events (if left)...", IsSubscribedToAll ? "<all>" : StreamId);
ReadEventsTill(_connection, _resolveLinkTos, _userCredentials, _subscription.LastCommitPosition, _subscription.LastEventNumber);
}
}
catch (Exception exc)
{
DropSubscription(SubscriptionDropReason.CatchUpError, exc);
return;
}
if (_stop)
{
DropSubscription(SubscriptionDropReason.UserInitiated, null);
return;
}
if (Verbose) Log.Debug("Catch-up Subscription to {0}: processing live events...", IsSubscribedToAll ? "<all>" : StreamId);
if (_liveProcessingStarted != null)
_liveProcessingStarted(this);
if (Verbose) Log.Debug("Catch-up Subscription to {0}: hooking to connection.Connected");
_connection.Connected += OnReconnect;
_allowProcessing = true;
EnsureProcessingPushQueue();
});
}
private void EnqueuePushedEvent(EventStoreSubscription subscription, ResolvedEvent e)
{
if (Verbose)
Log.Debug("Catch-up Subscription to {0}: event appeared ({1}, {2}, {3} @ {4}).",
IsSubscribedToAll ? "<all>" : StreamId,
e.OriginalStreamId, e.OriginalEventNumber, e.OriginalEvent.EventType, e.OriginalPosition);
if (_liveQueue.Count >= MaxPushQueueSize)
{
EnqueueSubscriptionDropNotification(SubscriptionDropReason.ProcessingQueueOverflow, null);
subscription.Unsubscribe();
return;
}
_liveQueue.Enqueue(e);
if (_allowProcessing)
EnsureProcessingPushQueue();
}
private void ServerSubscriptionDropped(EventStoreSubscription subscription, SubscriptionDropReason reason, Exception exc)
{
EnqueueSubscriptionDropNotification(reason, exc);
}
private void EnqueueSubscriptionDropNotification(SubscriptionDropReason reason, Exception error)
{
// if drop data was already set -- no need to enqueue drop again, somebody did that already
var dropData = new DropData(reason, error);
if (Interlocked.CompareExchange(ref _dropData, dropData, null) == null)
{
_liveQueue.Enqueue(DropSubscriptionEvent);
if (_allowProcessing)
EnsureProcessingPushQueue();
}
}
private void EnsureProcessingPushQueue()
{
if (Interlocked.CompareExchange(ref _isProcessing, 1, 0) == 0)
ThreadPool.QueueUserWorkItem(_ => ProcessLiveQueue());
}
private void ProcessLiveQueue()
{
do
{
ResolvedEvent e;
while (_liveQueue.TryDequeue(out e))
{
if (e.Event == null) // drop subscription artificial ResolvedEvent
{
if (_dropData == null) throw new Exception("Drop reason not specified.");
DropSubscription(_dropData.Reason, _dropData.Error);
Interlocked.CompareExchange(ref _isProcessing, 0, 1);
return;
}
try
{
TryProcess(e);
}
catch (Exception exc)
{
DropSubscription(SubscriptionDropReason.EventHandlerException, exc);
return;
}
}
Interlocked.CompareExchange(ref _isProcessing, 0, 1);
} while (_liveQueue.Count > 0 && Interlocked.CompareExchange(ref _isProcessing, 1, 0) == 0);
}
private void DropSubscription(SubscriptionDropReason reason, Exception error)
{
if (Interlocked.CompareExchange(ref _isDropped, 1, 0) == 0)
{
if (Verbose)
Log.Debug("Catch-up Subscription to {0}: dropping subscription, reason: {1} {2}.",
IsSubscribedToAll ? "<all>" : StreamId, reason, error == null ? string.Empty : error.ToString());
if (_subscription != null)
_subscription.Unsubscribe();
if (_subscriptionDropped != null)
_subscriptionDropped(this, reason, error);
_stopped.Set();
}
}
private class DropData
{
public readonly SubscriptionDropReason Reason;
public readonly Exception Error;
public DropData(SubscriptionDropReason reason, Exception error)
{
Reason = reason;
Error = error;
}
}
}
/// <summary>
/// A catch-up subscription to all events in the Event Store.
/// </summary>
public class EventStoreAllCatchUpSubscription: EventStoreCatchUpSubscription
{
/// <summary>
/// The last position processed on the subscription.
/// </summary>
public Position LastProcessedPosition
{
get
{
Position oldPos = _lastProcessedPosition;
Position curPos;
while (oldPos != (curPos = _lastProcessedPosition))
{
oldPos = curPos;
}
return curPos;
}
}
private Position _nextReadPosition;
private Position _lastProcessedPosition;
internal EventStoreAllCatchUpSubscription(IEventStoreConnection connection,
ILogger log,
Position? fromPositionExclusive, /* if null -- from the very beginning */
bool resolveLinkTos,
UserCredentials userCredentials,
Action<EventStoreCatchUpSubscription, ResolvedEvent> eventAppeared,
Action<EventStoreCatchUpSubscription> liveProcessingStarted,
Action<EventStoreCatchUpSubscription, SubscriptionDropReason, Exception> subscriptionDropped,
bool verboseLogging,
int readBatchSize = 500)
: base(connection, log, string.Empty, resolveLinkTos, userCredentials,
eventAppeared, liveProcessingStarted, subscriptionDropped, verboseLogging, readBatchSize)
{
_lastProcessedPosition = fromPositionExclusive ?? new Position(-1, -1);
_nextReadPosition = fromPositionExclusive ?? Position.Start;
}
/// <summary>
/// Read events until the given position.
/// </summary>
/// <param name="connection">The connection.</param>
/// <param name="resolveLinkTos">Whether to resolve Link events.</param>
/// <param name="userCredentials">User credentials for the operation.</param>
/// <param name="lastCommitPosition">The commit position to read until.</param>
/// <param name="lastEventNumber">The event number to read until.</param>
protected override void ReadEventsTill(IEventStoreConnection connection, bool resolveLinkTos,
UserCredentials userCredentials, long? lastCommitPosition, int? lastEventNumber)
{
bool done;
do
{
AllEventsSlice slice = connection.ReadAllEventsForward(_nextReadPosition, ReadBatchSize, resolveLinkTos, userCredentials);
foreach (var e in slice.Events)
{
if (e.OriginalPosition == null) throw new Exception("Subscription event came up with no OriginalPosition.");
TryProcess(e);
}
_nextReadPosition = slice.NextPosition;
done = lastCommitPosition == null
? slice.IsEndOfStream
: slice.NextPosition >= new Position(lastCommitPosition.Value, lastCommitPosition.Value);
if (!done && slice.IsEndOfStream)
Thread.Sleep(1); // we are waiting for server to flush its data
} while (!done);
if (Verbose)
Log.Debug("Catch-up Subscription to {0}: finished reading events, nextReadPosition = {1}.",
IsSubscribedToAll ? "<all>" : StreamId, _nextReadPosition);
}
/// <summary>
/// Try to process a single <see cref="ResolvedEvent"/>.
/// </summary>
/// <param name="e">The <see cref="ResolvedEvent"/> to process.</param>
protected override void TryProcess(ResolvedEvent e)
{
bool processed = false;
if (e.OriginalPosition > _lastProcessedPosition)
{
EventAppeared(this, e);
_lastProcessedPosition = e.OriginalPosition.Value;
processed = true;
}
if (Verbose)
Log.Debug("Catch-up Subscription to {0}: {1} event ({2}, {3}, {4} @ {5}).",
IsSubscribedToAll ? "<all>" : StreamId, processed ? "processed" : "skipping",
e.OriginalEvent.EventStreamId, e.OriginalEvent.EventNumber, e.OriginalEvent.EventType, e.OriginalPosition);
}
}
/// <summary>
/// A catch-up subscription to a single stream in the Event Store.
/// </summary>
public class EventStoreStreamCatchUpSubscription : EventStoreCatchUpSubscription
{
/// <summary>
/// The last event number processed on the subscription.
/// </summary>
public int LastProcessedEventNumber { get { return _lastProcessedEventNumber; } }
private int _nextReadEventNumber;
private int _lastProcessedEventNumber;
internal EventStoreStreamCatchUpSubscription(IEventStoreConnection connection,
ILogger log,
string streamId,
int? fromEventNumberExclusive, /* if null -- from the very beginning */
bool resolveLinkTos,
UserCredentials userCredentials,
Action<EventStoreCatchUpSubscription, ResolvedEvent> eventAppeared,
Action<EventStoreCatchUpSubscription> liveProcessingStarted,
Action<EventStoreCatchUpSubscription, SubscriptionDropReason, Exception> subscriptionDropped,
bool verboseLogging,
int readBatchSize = 500)
: base(connection, log, streamId, resolveLinkTos, userCredentials,
eventAppeared, liveProcessingStarted, subscriptionDropped, verboseLogging, readBatchSize)
{
Ensure.NotNullOrEmpty(streamId, "streamId");
_lastProcessedEventNumber = fromEventNumberExclusive ?? -1;
_nextReadEventNumber = fromEventNumberExclusive ?? 0;
}
/// <summary>
/// Read events until the given event number.
/// </summary>
/// <param name="connection">The connection.</param>
/// <param name="resolveLinkTos">Whether to resolve Link events.</param>
/// <param name="userCredentials">User credentials for the operation.</param>
/// <param name="lastCommitPosition">The commit position to read until.</param>
/// <param name="lastEventNumber">The event number to read until.</param>
protected override void ReadEventsTill(IEventStoreConnection connection, bool resolveLinkTos,
UserCredentials userCredentials, long? lastCommitPosition, int? lastEventNumber)
{
bool done;
do
{
var slice = connection.ReadStreamEventsForward(StreamId, _nextReadEventNumber, ReadBatchSize, resolveLinkTos, userCredentials);
switch (slice.Status)
{
case SliceReadStatus.Success:
{
foreach (var e in slice.Events)
{
TryProcess(e);
}
_nextReadEventNumber = slice.NextEventNumber;
done = lastEventNumber == null ? slice.IsEndOfStream : slice.NextEventNumber > lastEventNumber;
break;
}
case SliceReadStatus.StreamNotFound:
{
if (lastEventNumber.HasValue && lastEventNumber != -1)
throw new Exception(string.Format("Impossible: stream {0} disappeared in the middle of catching up subscription.", StreamId));
done = true;
break;
}
case SliceReadStatus.StreamDeleted:
throw new StreamDeletedException(StreamId);
default:
throw new ArgumentOutOfRangeException(string.Format("Unexpected StreamEventsSlice.Status: {0}.", slice.Status));
}
if (!done && slice.IsEndOfStream)
Thread.Sleep(1); // we are waiting for server to flush its data
} while (!done);
if (Verbose)
Log.Debug("Catch-up Subscription to {0}: finished reading events, nextReadEventNumber = {1}.",
IsSubscribedToAll ? "<all>" : StreamId, _nextReadEventNumber);
}
/// <summary>
/// Try to process a single <see cref="ResolvedEvent"/>.
/// </summary>
/// <param name="e">The <see cref="ResolvedEvent"/> to process.</param>
protected override void TryProcess(ResolvedEvent e)
{
bool processed = false;
if (e.OriginalEventNumber > _lastProcessedEventNumber)
{
EventAppeared(this, e);
_lastProcessedEventNumber = e.OriginalEventNumber;
processed = true;
}
if (Verbose)
Log.Debug("Catch-up Subscription to {0}: {1} event ({2}, {3}, {4} @ {5}).",
IsSubscribedToAll ? "<all>" : StreamId, processed ? "processed" : "skipping",
e.OriginalEvent.EventStreamId, e.OriginalEvent.EventNumber, e.OriginalEvent.EventType, e.OriginalEventNumber);
}
}
}
| |
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Allocation;
using osu.Framework.Bindables;
using osu.Framework.Extensions.Color4Extensions;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Colour;
using osu.Framework.Graphics.Containers;
using osu.Framework.Graphics.Effects;
using osu.Framework.Graphics.Shapes;
using osu.Framework.Graphics.Sprites;
using osu.Game.Beatmaps;
using osu.Game.Graphics;
using osu.Game.Graphics.Containers;
using osu.Game.Graphics.Sprites;
using osu.Game.Online.Chat;
using osu.Game.Online.Rooms;
using osu.Game.Overlays;
using osu.Game.Screens.OnlinePlay.Components;
using osuTK;
using osuTK.Graphics;
namespace osu.Game.Screens.OnlinePlay.Lounge.Components
{
public class DrawableRoom : CompositeDrawable
{
protected const float CORNER_RADIUS = 10;
private const float height = 100;
public readonly Room Room;
[Resolved]
private BeatmapManager beatmaps { get; set; }
protected Container ButtonsContainer { get; private set; }
private readonly Bindable<MatchType> roomType = new Bindable<MatchType>();
private readonly Bindable<RoomCategory> roomCategory = new Bindable<RoomCategory>();
private readonly Bindable<bool> hasPassword = new Bindable<bool>();
private DrawableRoomParticipantsList drawableRoomParticipantsList;
private RoomSpecialCategoryPill specialCategoryPill;
private PasswordProtectedIcon passwordIcon;
private EndDateInfo endDateInfo;
private DelayedLoadWrapper wrapper;
public DrawableRoom(Room room)
{
Room = room;
RelativeSizeAxes = Axes.X;
Height = height;
Masking = true;
CornerRadius = CORNER_RADIUS;
EdgeEffect = new EdgeEffectParameters
{
Type = EdgeEffectType.Shadow,
Colour = Color4.Black.Opacity(40),
Radius = 5,
};
}
[BackgroundDependencyLoader]
private void load(OverlayColourProvider colours)
{
ButtonsContainer = new Container
{
Anchor = Anchor.CentreRight,
Origin = Anchor.CentreRight,
RelativeSizeAxes = Axes.Y,
AutoSizeAxes = Axes.X
};
InternalChildren = new[]
{
// This resolves internal 1px gaps due to applying the (parenting) corner radius and masking across multiple filling background sprites.
new Box
{
RelativeSizeAxes = Axes.Both,
Colour = colours.Background5,
},
CreateBackground().With(d =>
{
d.RelativeSizeAxes = Axes.Both;
}),
wrapper = new DelayedLoadWrapper(() =>
new Container
{
Name = @"Room content",
RelativeSizeAxes = Axes.Both,
// This negative padding resolves 1px gaps between this background and the background above.
Padding = new MarginPadding { Left = 20, Vertical = -0.5f },
Child = new Container
{
RelativeSizeAxes = Axes.Both,
Masking = true,
CornerRadius = CORNER_RADIUS,
Children = new Drawable[]
{
new GridContainer
{
RelativeSizeAxes = Axes.Both,
ColumnDimensions = new[]
{
new Dimension(GridSizeMode.Relative, 0.2f)
},
Content = new[]
{
new Drawable[]
{
new Box
{
RelativeSizeAxes = Axes.Both,
Colour = colours.Background5,
},
new Box
{
RelativeSizeAxes = Axes.Both,
Colour = ColourInfo.GradientHorizontal(colours.Background5, colours.Background5.Opacity(0.3f))
},
}
}
},
new Container
{
Name = @"Left details",
RelativeSizeAxes = Axes.Both,
Padding = new MarginPadding
{
Left = 20,
Vertical = 5
},
Children = new Drawable[]
{
new FillFlowContainer
{
RelativeSizeAxes = Axes.X,
AutoSizeAxes = Axes.Y,
Direction = FillDirection.Vertical,
Children = new Drawable[]
{
new FillFlowContainer
{
AutoSizeAxes = Axes.Both,
Direction = FillDirection.Horizontal,
Spacing = new Vector2(5),
Children = new Drawable[]
{
new RoomStatusPill
{
Anchor = Anchor.CentreLeft,
Origin = Anchor.CentreLeft
},
specialCategoryPill = new RoomSpecialCategoryPill
{
Anchor = Anchor.CentreLeft,
Origin = Anchor.CentreLeft
},
endDateInfo = new EndDateInfo
{
Anchor = Anchor.CentreLeft,
Origin = Anchor.CentreLeft,
},
}
},
new FillFlowContainer
{
RelativeSizeAxes = Axes.X,
AutoSizeAxes = Axes.Y,
Padding = new MarginPadding { Top = 3 },
Direction = FillDirection.Vertical,
Children = new Drawable[]
{
new RoomNameText(),
new RoomStatusText()
}
}
},
},
new FillFlowContainer
{
Anchor = Anchor.BottomLeft,
Origin = Anchor.BottomLeft,
AutoSizeAxes = Axes.Both,
Direction = FillDirection.Horizontal,
Spacing = new Vector2(5),
Children = new Drawable[]
{
new PlaylistCountPill
{
Anchor = Anchor.CentreLeft,
Origin = Anchor.CentreLeft,
},
new StarRatingRangeDisplay
{
Anchor = Anchor.CentreLeft,
Origin = Anchor.CentreLeft,
Scale = new Vector2(0.8f)
}
}
}
}
},
new FillFlowContainer
{
Name = "Right content",
Anchor = Anchor.CentreRight,
Origin = Anchor.CentreRight,
AutoSizeAxes = Axes.X,
RelativeSizeAxes = Axes.Y,
Spacing = new Vector2(5),
Padding = new MarginPadding
{
Right = 10,
Vertical = 20,
},
Children = new Drawable[]
{
ButtonsContainer,
drawableRoomParticipantsList = new DrawableRoomParticipantsList
{
Anchor = Anchor.CentreRight,
Origin = Anchor.CentreRight,
NumberOfCircles = NumberOfAvatars
}
}
},
passwordIcon = new PasswordProtectedIcon { Alpha = 0 }
},
},
}, 0)
{
RelativeSizeAxes = Axes.Both,
}
};
}
protected override void LoadComplete()
{
base.LoadComplete();
wrapper.DelayedLoadComplete += _ =>
{
wrapper.FadeInFromZero(200);
roomCategory.BindTo(Room.Category);
roomCategory.BindValueChanged(c =>
{
if (c.NewValue == RoomCategory.Spotlight)
specialCategoryPill.Show();
else
specialCategoryPill.Hide();
}, true);
roomType.BindTo(Room.Type);
roomType.BindValueChanged(t =>
{
endDateInfo.Alpha = t.NewValue == MatchType.Playlists ? 1 : 0;
}, true);
hasPassword.BindTo(Room.HasPassword);
hasPassword.BindValueChanged(v => passwordIcon.Alpha = v.NewValue ? 1 : 0, true);
};
}
protected override IReadOnlyDependencyContainer CreateChildDependencies(IReadOnlyDependencyContainer parent)
{
return new CachedModelDependencyContainer<Room>(base.CreateChildDependencies(parent))
{
Model = { Value = Room }
};
}
private int numberOfAvatars = 7;
public int NumberOfAvatars
{
get => numberOfAvatars;
set
{
numberOfAvatars = value;
if (drawableRoomParticipantsList != null)
drawableRoomParticipantsList.NumberOfCircles = value;
}
}
protected virtual Drawable CreateBackground() => new OnlinePlayBackgroundSprite();
private class RoomNameText : OsuSpriteText
{
[Resolved(typeof(Room), nameof(Online.Rooms.Room.Name))]
private Bindable<string> name { get; set; }
public RoomNameText()
{
Font = OsuFont.GetFont(size: 28);
}
[BackgroundDependencyLoader]
private void load()
{
Current = name;
}
}
private class RoomStatusText : OnlinePlayComposite
{
[Resolved]
private OsuColour colours { get; set; }
private SpriteText statusText;
private LinkFlowContainer beatmapText;
public RoomStatusText()
{
RelativeSizeAxes = Axes.X;
AutoSizeAxes = Axes.Y;
Width = 0.5f;
}
[BackgroundDependencyLoader]
private void load()
{
InternalChild = new GridContainer
{
RelativeSizeAxes = Axes.X,
AutoSizeAxes = Axes.Y,
ColumnDimensions = new[]
{
new Dimension(GridSizeMode.AutoSize),
},
RowDimensions = new[]
{
new Dimension(GridSizeMode.AutoSize)
},
Content = new[]
{
new Drawable[]
{
statusText = new OsuSpriteText
{
Font = OsuFont.Default.With(size: 16),
Colour = colours.Lime1
},
beatmapText = new LinkFlowContainer(s =>
{
s.Font = OsuFont.Default.With(size: 16);
s.Colour = colours.Lime1;
})
{
RelativeSizeAxes = Axes.X,
AutoSizeAxes = Axes.Y
}
}
}
};
}
protected override void LoadComplete()
{
base.LoadComplete();
SelectedItem.BindValueChanged(onSelectedItemChanged, true);
}
private void onSelectedItemChanged(ValueChangedEvent<PlaylistItem> item)
{
beatmapText.Clear();
if (Type.Value == MatchType.Playlists)
{
statusText.Text = "Ready to play";
return;
}
if (item.NewValue?.Beatmap.Value != null)
{
statusText.Text = "Currently playing ";
beatmapText.AddLink(item.NewValue.Beatmap.Value.GetDisplayTitleRomanisable(),
LinkAction.OpenBeatmap,
item.NewValue.Beatmap.Value.OnlineBeatmapID.ToString(),
creationParameters: s =>
{
s.Truncate = true;
s.RelativeSizeAxes = Axes.X;
});
}
}
}
public class PasswordProtectedIcon : CompositeDrawable
{
[BackgroundDependencyLoader]
private void load(OsuColour colours)
{
Anchor = Anchor.TopRight;
Origin = Anchor.TopRight;
Size = new Vector2(32);
InternalChildren = new Drawable[]
{
new Box
{
Anchor = Anchor.TopRight,
Origin = Anchor.TopCentre,
Colour = colours.Gray5,
Rotation = 45,
RelativeSizeAxes = Axes.Both,
Width = 2,
},
new SpriteIcon
{
Icon = FontAwesome.Solid.Lock,
Anchor = Anchor.TopRight,
Origin = Anchor.TopRight,
Margin = new MarginPadding(6),
Size = new Vector2(14),
}
};
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Decorator.Models;
using Decorator.Models.ManageViewModels;
using Decorator.Services;
namespace Decorator.Controllers
{
[Authorize]
public class ManageController : Controller
{
private readonly UserManager<ApplicationUser> _userManager;
private readonly SignInManager<ApplicationUser> _signInManager;
private readonly IEmailSender _emailSender;
private readonly ISmsSender _smsSender;
private readonly ILogger _logger;
public ManageController(
UserManager<ApplicationUser> userManager,
SignInManager<ApplicationUser> signInManager,
IEmailSender emailSender,
ISmsSender smsSender,
ILoggerFactory loggerFactory)
{
_userManager = userManager;
_signInManager = signInManager;
_emailSender = emailSender;
_smsSender = smsSender;
_logger = loggerFactory.CreateLogger<ManageController>();
}
//
// GET: /Manage/Index
[HttpGet]
public async Task<IActionResult> Index(ManageMessageId? message = null)
{
ViewData["StatusMessage"] =
message == ManageMessageId.ChangePasswordSuccess ? "Your password has been changed."
: message == ManageMessageId.SetPasswordSuccess ? "Your password has been set."
: message == ManageMessageId.SetTwoFactorSuccess ? "Your two-factor authentication provider has been set."
: message == ManageMessageId.Error ? "An error has occurred."
: message == ManageMessageId.AddPhoneSuccess ? "Your phone number was added."
: message == ManageMessageId.RemovePhoneSuccess ? "Your phone number was removed."
: "";
var user = await GetCurrentUserAsync();
var model = new IndexViewModel
{
HasPassword = await _userManager.HasPasswordAsync(user),
PhoneNumber = await _userManager.GetPhoneNumberAsync(user),
TwoFactor = await _userManager.GetTwoFactorEnabledAsync(user),
Logins = await _userManager.GetLoginsAsync(user),
BrowserRemembered = await _signInManager.IsTwoFactorClientRememberedAsync(user)
};
return View(model);
}
//
// POST: /Manage/RemoveLogin
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> RemoveLogin(RemoveLoginViewModel account)
{
ManageMessageId? message = ManageMessageId.Error;
var user = await GetCurrentUserAsync();
if (user != null)
{
var result = await _userManager.RemoveLoginAsync(user, account.LoginProvider, account.ProviderKey);
if (result.Succeeded)
{
await _signInManager.SignInAsync(user, isPersistent: false);
message = ManageMessageId.RemoveLoginSuccess;
}
}
return RedirectToAction(nameof(ManageLogins), new { Message = message });
}
//
// GET: /Manage/AddPhoneNumber
public IActionResult AddPhoneNumber()
{
return View();
}
//
// POST: /Manage/AddPhoneNumber
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> AddPhoneNumber(AddPhoneNumberViewModel model)
{
if (!ModelState.IsValid)
{
return View(model);
}
// Generate the token and send it
var user = await GetCurrentUserAsync();
var code = await _userManager.GenerateChangePhoneNumberTokenAsync(user, model.PhoneNumber);
await _smsSender.SendSmsAsync(model.PhoneNumber, "Your security code is: " + code);
return RedirectToAction(nameof(VerifyPhoneNumber), new { PhoneNumber = model.PhoneNumber });
}
//
// POST: /Manage/EnableTwoFactorAuthentication
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> EnableTwoFactorAuthentication()
{
var user = await GetCurrentUserAsync();
if (user != null)
{
await _userManager.SetTwoFactorEnabledAsync(user, true);
await _signInManager.SignInAsync(user, isPersistent: false);
_logger.LogInformation(1, "User enabled two-factor authentication.");
}
return RedirectToAction(nameof(Index), "Manage");
}
//
// POST: /Manage/DisableTwoFactorAuthentication
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> DisableTwoFactorAuthentication()
{
var user = await GetCurrentUserAsync();
if (user != null)
{
await _userManager.SetTwoFactorEnabledAsync(user, false);
await _signInManager.SignInAsync(user, isPersistent: false);
_logger.LogInformation(2, "User disabled two-factor authentication.");
}
return RedirectToAction(nameof(Index), "Manage");
}
//
// GET: /Manage/VerifyPhoneNumber
[HttpGet]
public async Task<IActionResult> VerifyPhoneNumber(string phoneNumber)
{
var code = await _userManager.GenerateChangePhoneNumberTokenAsync(await GetCurrentUserAsync(), phoneNumber);
// Send an SMS to verify the phone number
return phoneNumber == null ? View("Error") : View(new VerifyPhoneNumberViewModel { PhoneNumber = phoneNumber });
}
//
// POST: /Manage/VerifyPhoneNumber
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> VerifyPhoneNumber(VerifyPhoneNumberViewModel model)
{
if (!ModelState.IsValid)
{
return View(model);
}
var user = await GetCurrentUserAsync();
if (user != null)
{
var result = await _userManager.ChangePhoneNumberAsync(user, model.PhoneNumber, model.Code);
if (result.Succeeded)
{
await _signInManager.SignInAsync(user, isPersistent: false);
return RedirectToAction(nameof(Index), new { Message = ManageMessageId.AddPhoneSuccess });
}
}
// If we got this far, something failed, redisplay the form
ModelState.AddModelError(string.Empty, "Failed to verify phone number");
return View(model);
}
//
// POST: /Manage/RemovePhoneNumber
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> RemovePhoneNumber()
{
var user = await GetCurrentUserAsync();
if (user != null)
{
var result = await _userManager.SetPhoneNumberAsync(user, null);
if (result.Succeeded)
{
await _signInManager.SignInAsync(user, isPersistent: false);
return RedirectToAction(nameof(Index), new { Message = ManageMessageId.RemovePhoneSuccess });
}
}
return RedirectToAction(nameof(Index), new { Message = ManageMessageId.Error });
}
//
// GET: /Manage/ChangePassword
[HttpGet]
public IActionResult ChangePassword()
{
return View();
}
//
// POST: /Manage/ChangePassword
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> ChangePassword(ChangePasswordViewModel model)
{
if (!ModelState.IsValid)
{
return View(model);
}
var user = await GetCurrentUserAsync();
if (user != null)
{
var result = await _userManager.ChangePasswordAsync(user, model.OldPassword, model.NewPassword);
if (result.Succeeded)
{
await _signInManager.SignInAsync(user, isPersistent: false);
_logger.LogInformation(3, "User changed their password successfully.");
return RedirectToAction(nameof(Index), new { Message = ManageMessageId.ChangePasswordSuccess });
}
AddErrors(result);
return View(model);
}
return RedirectToAction(nameof(Index), new { Message = ManageMessageId.Error });
}
//
// GET: /Manage/SetPassword
[HttpGet]
public IActionResult SetPassword()
{
return View();
}
//
// POST: /Manage/SetPassword
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> SetPassword(SetPasswordViewModel model)
{
if (!ModelState.IsValid)
{
return View(model);
}
var user = await GetCurrentUserAsync();
if (user != null)
{
var result = await _userManager.AddPasswordAsync(user, model.NewPassword);
if (result.Succeeded)
{
await _signInManager.SignInAsync(user, isPersistent: false);
return RedirectToAction(nameof(Index), new { Message = ManageMessageId.SetPasswordSuccess });
}
AddErrors(result);
return View(model);
}
return RedirectToAction(nameof(Index), new { Message = ManageMessageId.Error });
}
//GET: /Manage/ManageLogins
[HttpGet]
public async Task<IActionResult> ManageLogins(ManageMessageId? message = null)
{
ViewData["StatusMessage"] =
message == ManageMessageId.RemoveLoginSuccess ? "The external login was removed."
: message == ManageMessageId.AddLoginSuccess ? "The external login was added."
: message == ManageMessageId.Error ? "An error has occurred."
: "";
var user = await GetCurrentUserAsync();
if (user == null)
{
return View("Error");
}
var userLogins = await _userManager.GetLoginsAsync(user);
var otherLogins = _signInManager.GetExternalAuthenticationSchemes().Where(auth => userLogins.All(ul => auth.AuthenticationScheme != ul.LoginProvider)).ToList();
ViewData["ShowRemoveButton"] = user.PasswordHash != null || userLogins.Count > 1;
return View(new ManageLoginsViewModel
{
CurrentLogins = userLogins,
OtherLogins = otherLogins
});
}
//
// POST: /Manage/LinkLogin
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult LinkLogin(string provider)
{
// Request a redirect to the external login provider to link a login for the current user
var redirectUrl = Url.Action("LinkLoginCallback", "Manage");
var properties = _signInManager.ConfigureExternalAuthenticationProperties(provider, redirectUrl, _userManager.GetUserId(User));
return Challenge(properties, provider);
}
//
// GET: /Manage/LinkLoginCallback
[HttpGet]
public async Task<ActionResult> LinkLoginCallback()
{
var user = await GetCurrentUserAsync();
if (user == null)
{
return View("Error");
}
var info = await _signInManager.GetExternalLoginInfoAsync(await _userManager.GetUserIdAsync(user));
if (info == null)
{
return RedirectToAction(nameof(ManageLogins), new { Message = ManageMessageId.Error });
}
var result = await _userManager.AddLoginAsync(user, info);
var message = result.Succeeded ? ManageMessageId.AddLoginSuccess : ManageMessageId.Error;
return RedirectToAction(nameof(ManageLogins), new { Message = message });
}
#region Helpers
private void AddErrors(IdentityResult result)
{
foreach (var error in result.Errors)
{
ModelState.AddModelError(string.Empty, error.Description);
}
}
public enum ManageMessageId
{
AddPhoneSuccess,
AddLoginSuccess,
ChangePasswordSuccess,
SetTwoFactorSuccess,
SetPasswordSuccess,
RemoveLoginSuccess,
RemovePhoneSuccess,
Error
}
private Task<ApplicationUser> GetCurrentUserAsync()
{
return _userManager.GetUserAsync(HttpContext.User);
}
#endregion
}
}
| |
using Newtonsoft.Json;
using OCM.API.Common.Model;
using OCM.Core.Data;
using System;
using System.Collections;
using System.Configuration;
using System.Linq;
using System.Threading.Tasks;
namespace OCM.API.Common
{
/// <summary>
/// Used to perform a data submission.
/// </summary>
public class SubmissionManager
{
public bool AllowUpdates = false;
public bool RequireSubmissionReview = true;
public SubmissionManager()
{
AllowUpdates = false;
}
//convert a simple POI to data and back again to fully populate all related properties, as submission may only have simple IDs for ref data etc
private Model.ChargePoint PopulateFullPOI(Model.ChargePoint poi, Model.CoreReferenceData refData)
{
OCMEntities tempDataModel = new OCMEntities();
//convert simple poi to fully populated db version
var poiData = new POIManager().PopulateChargePoint_SimpleToData(poi, tempDataModel);
//convert back to simple POI
var modelPOI = Model.Extensions.ChargePoint.FromDataModel(poiData, false, false, true, true, refData);
//clear temp changes from the poi
//dataModel.Entry(poiData).Reload();
tempDataModel.Dispose();
return modelPOI;
}
private string PerformSerialisationToString(object graph, JsonSerializerSettings serializerSettings)
{
if (serializerSettings != null)
{
return JsonConvert.SerializeObject(graph, serializerSettings);
}
else
{
return JsonConvert.SerializeObject(graph);
}
}
public bool SubmitDataAgreement(Model.DataSharingAgreement agreement, int userId)
{
var dataModel = new Core.Data.OCMEntities();
var item = new Core.Data.DataSharingAgreement
{
CompanyName = agreement.CompanyName,
ContactEmail = agreement.ContactEmail,
CountryId = agreement.CountryID,
DataFeedType = agreement.DataFeedType,
DataFeedUrl = agreement.DataFeedURL,
DataLicense = agreement.DataLicense,
DistributionLimitations = agreement.DistributionLimitations,
RepresentativeName = agreement.RepresentativeName,
UserId = userId,
WebsiteUrl = agreement.WebsiteURL,
DateAgreed = DateTime.UtcNow,
DateCreated = DateTime.UtcNow,
Comments = agreement.Comments
};
dataModel.DataSharingAgreements.Add(item);
dataModel.SaveChanges();
try
{
SendContactUsMessage(item.RepresentativeName, item.ContactEmail, $"A new data sharing agreement has been submitted for {item.CompanyName}");
}
catch { }
return true;
}
/// <summary>
/// Consumers should prepare a new/updated ChargePoint with as much info populated as possible
/// </summary>
/// <param name="submission">ChargePoint info for submission, if ID and UUID set will be treated as an update</param>
/// <returns>false on error or not enough data supplied</returns>
public async Task<ValidationResult> PerformPOISubmission(Model.ChargePoint updatedPOI, Model.User user, bool performCacheRefresh = true, bool disablePOISuperseding = false)
{
try
{
var poiManager = new POIManager();
bool enableEditQueueLogging = bool.Parse(ConfigurationManager.AppSettings["EnableEditQueue"]);
bool isUpdate = false;
bool userCanEditWithoutApproval = false;
bool isSystemUser = false;
int? supersedesID = null;//POI from another data provider which has been superseded by an edit
//if user signed in, check if they have required permission to perform an edit/approve (if required)
if (user != null)
{
if (user.ID == (int)StandardUsers.System) isSystemUser = true;
//if user is system user, edits/updates are not recorded in edit queue
if (isSystemUser)
{
enableEditQueueLogging = false;
}
userCanEditWithoutApproval = POIManager.CanUserEditPOI(updatedPOI, user);
}
var dataModel = new Core.Data.OCMEntities();
//if poi is an update, validate if update can be performed
if (updatedPOI.ID > 0 && !String.IsNullOrEmpty(updatedPOI.UUID))
{
if (dataModel.ChargePoints.Any(c => c.Id == updatedPOI.ID && c.Uuid == updatedPOI.UUID))
{
//update is valid poi, check if user has permission to perform an update
isUpdate = true;
if (userCanEditWithoutApproval) AllowUpdates = true;
if (!AllowUpdates && !enableEditQueueLogging)
{
//valid update requested but updates not allowed
return new ValidationResult { IsValid = false, Message = "Updates are disabled" };
}
}
else
{
//update does not correctly identify an existing poi
return new ValidationResult { IsValid = false, Message = "Update does not correctly match an existing POI" };
}
}
//validate if minimal required data is present
if (updatedPOI.AddressInfo.Title == null || (updatedPOI.AddressInfo.Country == null && updatedPOI.AddressInfo.CountryID == null))
{
return new ValidationResult { IsValid = false, Message = "Update failed basic validation" };
}
//convert to DB version of POI and back so that properties are fully populated
using (var refDataManager = new ReferenceDataManager())
{
var refData = await refDataManager.GetCoreReferenceDataAsync();
updatedPOI = PopulateFullPOI(updatedPOI, refData);
}
Model.ChargePoint oldPOI = null;
if (updatedPOI.ID > 0)
{
//get json snapshot of current cp data to store as 'previous'
oldPOI = await poiManager.Get(updatedPOI.ID);
}
//if user cannot edit directly, add to edit queue for approval
var editQueueItem = new Core.Data.EditQueueItem { DateSubmitted = DateTime.UtcNow };
if (enableEditQueueLogging)
{
editQueueItem.EntityId = updatedPOI.ID;
editQueueItem.EntityType = dataModel.EntityTypes.FirstOrDefault(t => t.Id == 1);
//charging point location entity type id
//serialize cp as json
//null extra data we don't want to serialize/compare
updatedPOI.UserComments = null;
updatedPOI.MediaItems = null;
string editData = PerformSerialisationToString(updatedPOI, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore });
editQueueItem.EditData = editData;
if (updatedPOI.ID > 0)
{
//check if poi will change with this edit, if not we discard it completely
if (!poiManager.HasDifferences(oldPOI, updatedPOI))
{
System.Diagnostics.Debug.WriteLine("POI Update has no changes, discarding change.");
return new ValidationResult { IsValid = true, ItemId = updatedPOI.ID, Message = "No POI changes detected" };
}
else
{
editQueueItem.PreviousData = PerformSerialisationToString(oldPOI, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore });
}
}
if (user != null)
{
editQueueItem.User = dataModel.Users.FirstOrDefault(u => u.Id == user.ID);
}
var processedByUser = editQueueItem.User ?? dataModel.Users.FirstOrDefault(u => u.Id == (int)StandardUsers.System);
editQueueItem.IsProcessed = false;
dataModel.EditQueueItems.Add(editQueueItem);
//TODO: send notification of new item for approval
//save edit queue item
dataModel.SaveChanges();
//if previous edit queue item exists by same user for same POI, mark as processed
var previousEdits = dataModel.EditQueueItems.Where(e => e.UserId == editQueueItem.UserId && e.EntityId == editQueueItem.EntityId && e.EntityTypeId == editQueueItem.EntityTypeId && e.Id != editQueueItem.Id && e.IsProcessed != true);
foreach (var previousEdit in previousEdits)
{
previousEdit.IsProcessed = true;
previousEdit.ProcessedByUser = processedByUser;
previousEdit.DateProcessed = DateTime.UtcNow;
}
//save updated edit queue items
dataModel.SaveChanges();
}
//prepare and save changes POI changes/addition
if (isUpdate && !AllowUpdates)
{
//user has submitted an edit but is not an approved editor
//SendEditSubmissionNotification(updatedPOI, user);
//user is not an editor, item is now pending in edit queue for approval.
return new ValidationResult { IsValid = true, ItemId = updatedPOI.ID, Message = "Update submitted for review" };
}
if (isUpdate && updatedPOI.SubmissionStatusTypeID >= 1000)
{
//update is a delisting, skip superseding poi
System.Diagnostics.Debug.WriteLine("skipping superseding of imported POI due to delisting");
}
else
{
//if poi being updated exists from an imported source we supersede the old POI with the new version, unless we're doing a fresh import from same data provider
if (!disablePOISuperseding)
{
//if update by non-system user will change an imported/externally provided data, supersede old POI with new one (retain ID against new POI)
if (isUpdate && !isSystemUser && oldPOI.DataProviderID != (int)StandardDataProviders.OpenChargeMapContrib)
{
//move old poi to new id, set status of new item to superseded
supersedesID = poiManager.SupersedePOI(dataModel, oldPOI, updatedPOI);
}
}
}
//user is an editor, go ahead and store the addition/update
//set/update cp properties
var cpData = poiManager.PopulateChargePoint_SimpleToData(updatedPOI, dataModel);
//if item has no submission status and user permitted to edit, set to published
if (userCanEditWithoutApproval && cpData.SubmissionStatusTypeId == null)
{
cpData.SubmissionStatusTypeId = (int)StandardSubmissionStatusTypes.Submitted_Published; //hack due to conflicting state change for SubmissionStatusType
}
else
{
//no submission status, set to 'under review'
if (cpData.SubmissionStatusTypeId == null) cpData.SubmissionStatusTypeId = (int)StandardSubmissionStatusTypes.Submitted_UnderReview;
}
cpData.DateLastStatusUpdate = DateTime.UtcNow;
if (!isUpdate)
{
//new data objects need added to data model before save
if (cpData.AddressInfo != null) dataModel.AddressInfos.Add(cpData.AddressInfo);
dataModel.ChargePoints.Add(cpData);
}
//finally - save poi update
dataModel.SaveChanges();
//get id of update/new poi
int newPoiID = cpData.Id;
//this is an authorised update, reflect change in edit queue item
if (enableEditQueueLogging && user != null && user.ID > 0)
{
var editUser = dataModel.Users.FirstOrDefault(u => u.Id == user.ID);
editQueueItem.User = editUser;
if (newPoiID > 0) editQueueItem.EntityId = newPoiID;
//if user is authorised to edit, process item automatically without review
if (userCanEditWithoutApproval)
{
editQueueItem.ProcessedByUser = editUser;
editQueueItem.DateProcessed = DateTime.UtcNow;
editQueueItem.IsProcessed = true;
}
//save edit queue item changes
dataModel.SaveChanges();
}
else
{
//anonymous submission, update edit queue item
if (enableEditQueueLogging && user == null)
{
if (newPoiID > 0) editQueueItem.EntityId = newPoiID;
dataModel.SaveChanges();
}
}
System.Diagnostics.Debug.WriteLine("Added/Updated CP:" + cpData.Id);
//if user is not anonymous, log their submission and update their reputation points
if (user != null)
{
AuditLogManager.Log(user, isUpdate ? AuditEventType.UpdatedItem : AuditEventType.CreatedItem, "Modified OCM-" + cpData.Id, null);
//add reputation points
new UserManager().AddReputationPoints(user, 1);
}
//preserve new POI Id for caller
updatedPOI.ID = cpData.Id;
if (performCacheRefresh)
{
if (supersedesID != null)
{
await CacheManager.RefreshCachedPOI((int)supersedesID);
}
await CacheManager.RefreshCachedPOI(updatedPOI.ID);
}
return new ValidationResult { IsValid = true, ItemId = updatedPOI.ID, Message = "Update submitted." };
}
catch (Exception exp)
{
System.Diagnostics.Debug.WriteLine(exp.ToString());
AuditLogManager.ReportWebException(true, null, AuditEventType.SystemErrorWeb, "POI Submission Failed", exp);
//error performing submission
return new ValidationResult { IsValid = false, Message = "Submission Failed with an Exception: " + exp.Message };
}
}
private static void SendNewPOISubmissionNotification(Model.ChargePoint poi, Model.User user, Core.Data.ChargePoint cpData)
{
try
{
string approvalStatus = cpData.SubmissionStatusType.Title;
//send notification
NotificationManager notification = new NotificationManager();
Hashtable msgParams = new Hashtable();
msgParams.Add("Description", "OCM-" + cpData.Id + " : " + poi.AddressInfo.Title);
msgParams.Add("SubmissionStatusType", approvalStatus);
msgParams.Add("ItemURL", "https://openchargemap.org/site/poi/details/" + cpData.Id);
msgParams.Add("ChargePointID", cpData.Id);
msgParams.Add("UserName", user != null ? user.Username : "Anonymous");
msgParams.Add("MessageBody",
"New Location " + approvalStatus + " OCM-" + cpData.Id + " Submitted: " +
poi.AddressInfo.Title);
notification.PrepareNotification(NotificationType.LocationSubmitted, msgParams);
//notify default system recipients
notification.SendNotification(NotificationType.LocationSubmitted);
}
catch (Exception)
{
;
; //failed to send notification
}
}
private static void SendEditSubmissionNotification(Model.ChargePoint poi, Model.User user)
{
try
{
string approvalStatus = "Edit Submitted for approval";
//send notification
var notification = new NotificationManager();
var msgParams = new Hashtable();
msgParams.Add("Description", "OCM-" + poi.ID + " : " + poi.AddressInfo.Title);
msgParams.Add("SubmissionStatusType", approvalStatus);
msgParams.Add("ItemURL", "https://openchargemap.org/site/poi/details/" + poi.ID);
msgParams.Add("ChargePointID", poi.ID);
msgParams.Add("UserName", user != null ? user.Username : "Anonymous");
msgParams.Add("MessageBody",
"Edit item for Approval: Location " + approvalStatus + " OCM-" + poi.ID + " Submitted: " +
poi.AddressInfo.Title);
notification.PrepareNotification(NotificationType.LocationSubmitted, msgParams);
//notify default system recipients
notification.SendNotification(NotificationType.LocationSubmitted);
}
catch (Exception)
{
;
; //failed to send notification
}
}
/// <summary>
/// Submit a new comment against a given charge equipment id
/// </summary>
/// <param name="comment"></param>
/// <returns>ID of new comment, -1 for invalid cp, -2 for general error saving comment</returns>
public async Task<int> PerformSubmission(Common.Model.UserComment comment, Model.User user)
{
//TODO: move all to UserCommentManager
//populate data model comment from simple comment object
var dataModel = new Core.Data.OCMEntities();
int cpID = comment.ChargePointID;
var dataComment = new Core.Data.UserComment();
var dataChargePoint = dataModel.ChargePoints.FirstOrDefault(c => c.Id == cpID);
if (dataChargePoint == null) return -1; //invalid charge point specified
dataComment.ChargePointId = dataChargePoint.Id;
dataComment.Comment = comment.Comment;
int commentTypeID = comment.CommentTypeID ?? 10; //default to General Comment
// some clients may post a CommentType object instead of just an ID
if (comment.CommentType != null)
{
commentTypeID = comment.CommentType.ID;
}
dataComment.UserCommentTypeId = commentTypeID;
int? checkinStatusType = comment.CheckinStatusTypeID;
dataComment.CheckinStatusTypeId = (byte?)comment.CheckinStatusTypeID;
// some clients may post a CheckinStatusType object instead of just an ID
if (dataComment.CheckinStatusTypeId == null && comment.CheckinStatusType != null)
{
dataComment.CheckinStatusTypeId = (byte?)comment.CheckinStatusType.ID;
}
dataComment.UserName = comment.UserName;
dataComment.Rating = comment.Rating;
dataComment.RelatedUrl = comment.RelatedURL;
dataComment.DateCreated = DateTime.UtcNow;
if (user != null && user.ID > 0)
{
var ocmUser = dataModel.Users.FirstOrDefault(u => u.Id == user.ID);
if (ocmUser != null)
{
dataComment.UserId = ocmUser.Id;
dataComment.UserName = ocmUser.Username;
}
}
try
{
dataChargePoint.DateLastStatusUpdate = DateTime.UtcNow;
dataModel.UserComments.Add(dataComment);
dataModel.SaveChanges();
if (user != null)
{
AuditLogManager.Log(user, AuditEventType.CreatedItem, "Added Comment " + dataComment.Id + " to OCM-" + cpID, null);
//add reputation points
new UserManager().AddReputationPoints(user, 1);
}
//SendPOICommentSubmissionNotifications(comment, user, dataComment);
//TODO: only refresh cache for specific POI
await CacheManager.RefreshCachedPOI(dataComment.ChargePoint.Id);
return dataComment.Id;
}
catch (Exception exp)
{
return -2; //error saving
}
}
private static void SendPOICommentSubmissionNotifications(Common.Model.UserComment comment, Model.User user, Core.Data.UserComment dataComment)
{
try
{
//prepare notification
NotificationManager notification = new NotificationManager();
Hashtable msgParams = new Hashtable();
msgParams.Add("Description", "");
msgParams.Add("ChargePointID", comment.ChargePointID);
msgParams.Add("ItemURL", "https://openchargemap.org/site/poi/details/" + comment.ChargePointID);
msgParams.Add("UserName", user != null ? user.Username : comment.UserName);
msgParams.Add("MessageBody", "Comment (" + dataComment.UserCommentType.Title + ") added to OCM-" + comment.ChargePointID + ": " + dataComment.Comment);
//if fault report, attempt to notify operator
if (dataComment.UserCommentType.Id == (int)StandardCommentTypes.FaultReport)
{
//decide if we can send a fault notification to the operator
notification.PrepareNotification(NotificationType.FaultReport, msgParams);
//notify default system recipients
bool operatorNotified = false;
if (dataComment.ChargePoint.Operator != null)
{
if (!String.IsNullOrEmpty(dataComment.ChargePoint.Operator.FaultReportEmail))
{
try
{
notification.SendNotification(dataComment.ChargePoint.Operator.FaultReportEmail, ConfigurationManager.AppSettings["DefaultRecipientEmailAddresses"].ToString());
operatorNotified = true;
}
catch (Exception)
{
System.Diagnostics.Debug.WriteLine("Fault report: failed to notify operator");
}
}
}
if (!operatorNotified)
{
notification.Subject += " (OCM: Could not notify Operator)";
notification.SendNotification(NotificationType.LocationCommentReceived);
}
}
else
{
//normal comment, notification to OCM only
notification.PrepareNotification(NotificationType.LocationCommentReceived, msgParams);
//notify default system recipients
notification.SendNotification(NotificationType.LocationCommentReceived);
}
}
catch (Exception)
{
; ; // failed to send notification
}
}
public int PerformSubmission(Common.Model.MediaItem mediaItem, Model.User user)
{
return -1;
}
public bool SubmitContactSubmission(ContactSubmission contactSubmission)
{
return SendContactUsMessage(contactSubmission.Name, contactSubmission.Email, contactSubmission.Comment);
}
public bool SendContactUsMessage(string senderName, string senderEmail, string comment)
{
try
{
//send notification
NotificationManager notification = new NotificationManager();
Hashtable msgParams = new Hashtable();
msgParams.Add("Description", (comment.Length > 64 ? comment.Substring(0, 64) + ".." : comment));
msgParams.Add("Name", senderName);
msgParams.Add("Email", senderEmail);
msgParams.Add("Comment", comment);
notification.PrepareNotification(NotificationType.ContactUsMessage, msgParams);
//notify default system recipients
return notification.SendNotification(NotificationType.ContactUsMessage);
}
catch (Exception exp)
{
System.Diagnostics.Debug.WriteLine(exp.ToString());
return false; //failed
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net.Http.HPack;
using System.Reflection;
using System.Text;
using Xunit;
namespace System.Net.Http.Unit.Tests.HPack
{
public class DynamicTableTest
{
private readonly HeaderField _header1 = new HeaderField(Encoding.ASCII.GetBytes("header-1"), Encoding.ASCII.GetBytes("value1"));
private readonly HeaderField _header2 = new HeaderField(Encoding.ASCII.GetBytes("header-02"), Encoding.ASCII.GetBytes("value_2"));
[Fact]
public void DynamicTable_IsInitiallyEmpty()
{
DynamicTable dynamicTable = new DynamicTable(4096);
Assert.Equal(0, dynamicTable.Count);
Assert.Equal(0, dynamicTable.Size);
Assert.Equal(4096, dynamicTable.MaxSize);
}
[Fact]
public void DynamicTable_Count_IsNumberOfEntriesInDynamicTable()
{
DynamicTable dynamicTable = new DynamicTable(4096);
dynamicTable.Insert(_header1.Name, _header1.Value);
Assert.Equal(1, dynamicTable.Count);
dynamicTable.Insert(_header2.Name, _header2.Value);
Assert.Equal(2, dynamicTable.Count);
}
[Fact]
public void DynamicTable_Size_IsCurrentDynamicTableSize()
{
DynamicTable dynamicTable = new DynamicTable(4096);
Assert.Equal(0, dynamicTable.Size);
dynamicTable.Insert(_header1.Name, _header1.Value);
Assert.Equal(_header1.Length, dynamicTable.Size);
dynamicTable.Insert(_header2.Name, _header2.Value);
Assert.Equal(_header1.Length + _header2.Length, dynamicTable.Size);
}
[Fact]
public void DynamicTable_FirstEntry_IsMostRecentEntry()
{
DynamicTable dynamicTable = new DynamicTable(4096);
dynamicTable.Insert(_header1.Name, _header1.Value);
dynamicTable.Insert(_header2.Name, _header2.Value);
VerifyTableEntries(dynamicTable, _header2, _header1);
}
[Fact]
public void BoundsCheck_ThrowsIndexOutOfRangeException()
{
DynamicTable dynamicTable = new DynamicTable(4096);
Assert.Throws<IndexOutOfRangeException>(() => dynamicTable[0]);
dynamicTable.Insert(_header1.Name, _header1.Value);
Assert.Throws<IndexOutOfRangeException>(() => dynamicTable[1]);
}
[Fact]
public void DynamicTable_InsertEntryLargerThanMaxSize_NoOp()
{
DynamicTable dynamicTable = new DynamicTable(_header1.Length - 1);
dynamicTable.Insert(_header1.Name, _header1.Value);
Assert.Equal(0, dynamicTable.Count);
Assert.Equal(0, dynamicTable.Size);
}
[Fact]
public void DynamicTable_InsertEntryLargerThanRemainingSpace_NoOp()
{
DynamicTable dynamicTable = new DynamicTable(_header1.Length);
dynamicTable.Insert(_header1.Name, _header1.Value);
VerifyTableEntries(dynamicTable, _header1);
dynamicTable.Insert(_header2.Name, _header2.Value);
Assert.Equal(0, dynamicTable.Count);
Assert.Equal(0, dynamicTable.Size);
}
[Theory]
[InlineData(0)]
[InlineData(1)]
[InlineData(2)]
[InlineData(3)]
public void DynamicTable_WrapsRingBuffer_Success(int targetInsertIndex)
{
FieldInfo insertIndexField = typeof(DynamicTable).GetField("_insertIndex", BindingFlags.NonPublic | BindingFlags.Instance);
DynamicTable table = new DynamicTable(maxSize: 256);
Stack<byte[]> insertedHeaders = new Stack<byte[]>();
// Insert into dynamic table until its insert index into its ring buffer loops back to 0.
do
{
InsertOne();
}
while ((int)insertIndexField.GetValue(table) != 0);
// Finally loop until the insert index reaches the target.
while ((int)insertIndexField.GetValue(table) != targetInsertIndex)
{
InsertOne();
}
void InsertOne()
{
byte[] data = Encoding.ASCII.GetBytes($"header-{insertedHeaders.Count}");
insertedHeaders.Push(data);
table.Insert(data, data);
}
// Now check to see that we can retrieve the remaining headers.
// Some headers will have been evacuated from the table during this process, so we don't exhaust the entire insertedHeaders stack.
Assert.True(table.Count > 0);
Assert.True(table.Count < insertedHeaders.Count);
for (int i = 0; i < table.Count; ++i)
{
HeaderField dynamicField = table[i];
byte[] expectedData = insertedHeaders.Pop();
Assert.True(expectedData.AsSpan().SequenceEqual(dynamicField.Name));
Assert.True(expectedData.AsSpan().SequenceEqual(dynamicField.Value));
}
}
[Theory]
[MemberData(nameof(CreateResizeData))]
public void DynamicTable_Resize_Success(int initialMaxSize, int finalMaxSize, int insertSize)
{
// This is purely to make it simple to perfectly reach our initial max size to test growing a full but non-wrapping buffer.
Debug.Assert((insertSize % 64) == 0, $"{nameof(insertSize)} must be a multiple of 64 ({nameof(HeaderField)}.{nameof(HeaderField.RfcOverhead)} * 2)");
DynamicTable dynamicTable = new DynamicTable(maxSize: initialMaxSize);
int insertedSize = 0;
while (insertedSize != insertSize)
{
byte[] data = Encoding.ASCII.GetBytes($"header-{dynamicTable.Size}".PadRight(16, ' '));
Debug.Assert(data.Length == 16);
dynamicTable.Insert(data, data);
insertedSize += data.Length * 2 + HeaderField.RfcOverhead;
}
List<HeaderField> headers = new List<HeaderField>();
for (int i = 0; i < dynamicTable.Count; ++i)
{
headers.Add(dynamicTable[i]);
}
dynamicTable.Resize(finalMaxSize);
int expectedCount = Math.Min(finalMaxSize / 64, headers.Count);
Assert.Equal(expectedCount, dynamicTable.Count);
for (int i = 0; i < dynamicTable.Count; ++i)
{
Assert.True(headers[i].Name.AsSpan().SequenceEqual(dynamicTable[i].Name));
Assert.True(headers[i].Value.AsSpan().SequenceEqual(dynamicTable[i].Value));
}
}
[Fact]
public void DynamicTable_ResizingEvictsOldestEntries()
{
DynamicTable dynamicTable = new DynamicTable(4096);
dynamicTable.Insert(_header1.Name, _header1.Value);
dynamicTable.Insert(_header2.Name, _header2.Value);
VerifyTableEntries(dynamicTable, _header2, _header1);
dynamicTable.Resize(_header2.Length);
VerifyTableEntries(dynamicTable, _header2);
}
[Fact]
public void DynamicTable_ResizingToZeroEvictsAllEntries()
{
DynamicTable dynamicTable = new DynamicTable(4096);
dynamicTable.Insert(_header1.Name, _header1.Value);
dynamicTable.Insert(_header2.Name, _header2.Value);
dynamicTable.Resize(0);
Assert.Equal(0, dynamicTable.Count);
Assert.Equal(0, dynamicTable.Size);
}
[Fact]
public void DynamicTable_CanBeResizedToLargerMaxSize()
{
DynamicTable dynamicTable = new DynamicTable(_header1.Length);
dynamicTable.Insert(_header1.Name, _header1.Value);
dynamicTable.Insert(_header2.Name, _header2.Value);
// _header2 is larger than _header1, so an attempt at inserting it
// would first clear the table then return without actually inserting it,
// given it is larger than the current max size.
Assert.Equal(0, dynamicTable.Count);
Assert.Equal(0, dynamicTable.Size);
dynamicTable.Resize(dynamicTable.MaxSize + _header2.Length);
dynamicTable.Insert(_header2.Name, _header2.Value);
VerifyTableEntries(dynamicTable, _header2);
}
public static IEnumerable<object[]> CreateResizeData()
{
int[] values = new[] { 128, 256, 384, 512 };
return from initialMaxSize in values
from finalMaxSize in values
from insertSize in values
select new object[] { initialMaxSize, finalMaxSize, insertSize };
}
private void VerifyTableEntries(DynamicTable dynamicTable, params HeaderField[] entries)
{
Assert.Equal(entries.Length, dynamicTable.Count);
Assert.Equal(entries.Sum(e => e.Length), dynamicTable.Size);
for (int i = 0; i < entries.Length; i++)
{
HeaderField headerField = dynamicTable[i];
Assert.NotSame(entries[i].Name, headerField.Name);
Assert.Equal(entries[i].Name, headerField.Name);
Assert.NotSame(entries[i].Value, headerField.Value);
Assert.Equal(entries[i].Value, headerField.Value);
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Diagnostics.RazorViews;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Features;
using Microsoft.AspNetCore.Routing;
using Microsoft.Extensions.FileProviders;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Microsoft.Extensions.StackTrace.Sources;
using Microsoft.Net.Http.Headers;
namespace Microsoft.AspNetCore.Diagnostics
{
/// <summary>
/// Captures synchronous and asynchronous exceptions from the pipeline and generates error responses.
/// </summary>
public class DeveloperExceptionPageMiddleware
{
private readonly RequestDelegate _next;
private readonly DeveloperExceptionPageOptions _options;
private readonly ILogger _logger;
private readonly IFileProvider _fileProvider;
private readonly DiagnosticSource _diagnosticSource;
private readonly ExceptionDetailsProvider _exceptionDetailsProvider;
private readonly Func<ErrorContext, Task> _exceptionHandler;
private static readonly MediaTypeHeaderValue _textHtmlMediaType = new MediaTypeHeaderValue("text/html");
/// <summary>
/// Initializes a new instance of the <see cref="DeveloperExceptionPageMiddleware"/> class
/// </summary>
/// <param name="next"></param>
/// <param name="options"></param>
/// <param name="loggerFactory"></param>
/// <param name="hostingEnvironment"></param>
/// <param name="diagnosticSource"></param>
/// <param name="filters"></param>
public DeveloperExceptionPageMiddleware(
RequestDelegate next,
IOptions<DeveloperExceptionPageOptions> options,
ILoggerFactory loggerFactory,
IWebHostEnvironment hostingEnvironment,
DiagnosticSource diagnosticSource,
IEnumerable<IDeveloperPageExceptionFilter> filters)
{
if (next == null)
{
throw new ArgumentNullException(nameof(next));
}
if (options == null)
{
throw new ArgumentNullException(nameof(options));
}
if (filters == null)
{
throw new ArgumentNullException(nameof(filters));
}
_next = next;
_options = options.Value;
_logger = loggerFactory.CreateLogger<DeveloperExceptionPageMiddleware>();
_fileProvider = _options.FileProvider ?? hostingEnvironment.ContentRootFileProvider;
_diagnosticSource = diagnosticSource;
_exceptionDetailsProvider = new ExceptionDetailsProvider(_fileProvider, _logger, _options.SourceCodeLineCount);
_exceptionHandler = DisplayException;
foreach (var filter in filters.Reverse())
{
var nextFilter = _exceptionHandler;
_exceptionHandler = errorContext => filter.HandleExceptionAsync(errorContext, nextFilter);
}
}
/// <summary>
/// Process an individual request.
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
public async Task Invoke(HttpContext context)
{
try
{
await _next(context);
}
catch (Exception ex)
{
_logger.UnhandledException(ex);
if (context.Response.HasStarted)
{
_logger.ResponseStartedErrorPageMiddleware();
throw;
}
try
{
context.Response.Clear();
// Preserve the status code that would have been written by the server automatically when a BadHttpRequestException is thrown.
if (ex is BadHttpRequestException badHttpRequestException)
{
context.Response.StatusCode = badHttpRequestException.StatusCode;
}
else
{
context.Response.StatusCode = 500;
}
await _exceptionHandler(new ErrorContext(context, ex));
if (_diagnosticSource.IsEnabled("Microsoft.AspNetCore.Diagnostics.UnhandledException"))
{
_diagnosticSource.Write("Microsoft.AspNetCore.Diagnostics.UnhandledException", new { httpContext = context, exception = ex });
}
return;
}
catch (Exception ex2)
{
// If there's a Exception while generating the error page, re-throw the original exception.
_logger.DisplayErrorPageException(ex2);
}
throw;
}
}
// Assumes the response headers have not been sent. If they have, still attempt to write to the body.
private Task DisplayException(ErrorContext errorContext)
{
var httpContext = errorContext.HttpContext;
var headers = httpContext.Request.GetTypedHeaders();
var acceptHeader = headers.Accept;
// If the client does not ask for HTML just format the exception as plain text
if (acceptHeader == null || !acceptHeader.Any(h => h.IsSubsetOf(_textHtmlMediaType)))
{
httpContext.Response.ContentType = "text/plain; charset=utf-8";
var sb = new StringBuilder();
sb.AppendLine(errorContext.Exception.ToString());
sb.AppendLine();
sb.AppendLine("HEADERS");
sb.AppendLine("=======");
foreach (var pair in httpContext.Request.Headers)
{
sb.AppendLine(FormattableString.Invariant($"{pair.Key}: {pair.Value}"));
}
return httpContext.Response.WriteAsync(sb.ToString());
}
if (errorContext.Exception is ICompilationException compilationException)
{
return DisplayCompilationException(httpContext, compilationException);
}
return DisplayRuntimeException(httpContext, errorContext.Exception);
}
private Task DisplayCompilationException(
HttpContext context,
ICompilationException compilationException)
{
var model = new CompilationErrorPageModel(_options);
var errorPage = new CompilationErrorPage(model);
if (compilationException.CompilationFailures == null)
{
return errorPage.ExecuteAsync(context);
}
foreach (var compilationFailure in compilationException.CompilationFailures)
{
if (compilationFailure == null)
{
continue;
}
var stackFrames = new List<StackFrameSourceCodeInfo>();
var exceptionDetails = new ExceptionDetails(compilationFailure.FailureSummary!, stackFrames);
model.ErrorDetails.Add(exceptionDetails);
model.CompiledContent.Add(compilationFailure.CompiledContent);
if (compilationFailure.Messages == null)
{
continue;
}
var sourceLines = compilationFailure
.SourceFileContent?
.Split(new[] { Environment.NewLine }, StringSplitOptions.None);
foreach (var item in compilationFailure.Messages)
{
if (item == null)
{
continue;
}
var frame = new StackFrameSourceCodeInfo
{
File = compilationFailure.SourceFilePath,
Line = item.StartLine,
Function = string.Empty
};
if (sourceLines != null)
{
_exceptionDetailsProvider.ReadFrameContent(frame, sourceLines, item.StartLine, item.EndLine);
}
frame.ErrorDetails = item.Message;
stackFrames.Add(frame);
}
}
return errorPage.ExecuteAsync(context);
}
private Task DisplayRuntimeException(HttpContext context, Exception ex)
{
var endpoint = context.GetEndpoint();
EndpointModel? endpointModel = null;
if (endpoint != null)
{
endpointModel = new EndpointModel();
endpointModel.DisplayName = endpoint.DisplayName;
if (endpoint is RouteEndpoint routeEndpoint)
{
endpointModel.RoutePattern = routeEndpoint.RoutePattern.RawText;
endpointModel.Order = routeEndpoint.Order;
var httpMethods = endpoint.Metadata.GetMetadata<IHttpMethodMetadata>()?.HttpMethods;
if (httpMethods != null)
{
endpointModel.HttpMethods = string.Join(", ", httpMethods);
}
}
}
var request = context.Request;
var title = Resources.ErrorPageHtml_Title;
if (ex is BadHttpRequestException badHttpRequestException)
{
var badRequestReasonPhrase = WebUtilities.ReasonPhrases.GetReasonPhrase(badHttpRequestException.StatusCode);
if (!string.IsNullOrEmpty(badRequestReasonPhrase))
{
title = badRequestReasonPhrase;
}
}
var model = new ErrorPageModel
{
Options = _options,
ErrorDetails = _exceptionDetailsProvider.GetDetails(ex),
Query = request.Query,
Cookies = request.Cookies,
Headers = request.Headers,
RouteValues = request.RouteValues,
Endpoint = endpointModel,
Title = title,
};
var errorPage = new ErrorPage(model);
return errorPage.ExecuteAsync(context);
}
}
}
| |
namespace Cinotam.AbpModuleZero.Migrations
{
using System;
using System.Collections.Generic;
using System.Data.Entity.Infrastructure.Annotations;
using System.Data.Entity.Migrations;
public partial class AbpZero_Initial : DbMigration
{
public override void Up()
{
CreateTable(
"dbo.AbpAuditLogs",
c => new
{
Id = c.Long(nullable: false, identity: true),
TenantId = c.Int(),
UserId = c.Long(),
ServiceName = c.String(maxLength: 256),
MethodName = c.String(maxLength: 256),
Parameters = c.String(maxLength: 1024),
ExecutionTime = c.DateTime(nullable: false),
ExecutionDuration = c.Int(nullable: false),
ClientIpAddress = c.String(maxLength: 64),
ClientName = c.String(maxLength: 128),
BrowserInfo = c.String(maxLength: 256),
Exception = c.String(maxLength: 2000),
},
annotations: new Dictionary<string, object>
{
{ "DynamicFilter_AuditLog_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
})
.PrimaryKey(t => t.Id);
CreateTable(
"dbo.AbpPermissions",
c => new
{
Id = c.Long(nullable: false, identity: true),
Name = c.String(nullable: false, maxLength: 128),
IsGranted = c.Boolean(nullable: false),
CreationTime = c.DateTime(nullable: false),
CreatorUserId = c.Long(),
RoleId = c.Int(),
UserId = c.Long(),
Discriminator = c.String(nullable: false, maxLength: 128),
})
.PrimaryKey(t => t.Id)
.ForeignKey("dbo.AbpUsers", t => t.UserId, cascadeDelete: true)
.ForeignKey("dbo.AbpRoles", t => t.RoleId, cascadeDelete: true)
.Index(t => t.RoleId)
.Index(t => t.UserId);
CreateTable(
"dbo.AbpRoles",
c => new
{
Id = c.Int(nullable: false, identity: true),
TenantId = c.Int(),
Name = c.String(nullable: false, maxLength: 32),
DisplayName = c.String(nullable: false, maxLength: 64),
IsStatic = c.Boolean(nullable: false),
IsDefault = c.Boolean(nullable: false),
IsDeleted = c.Boolean(nullable: false),
DeleterUserId = c.Long(),
DeletionTime = c.DateTime(),
LastModificationTime = c.DateTime(),
LastModifierUserId = c.Long(),
CreationTime = c.DateTime(nullable: false),
CreatorUserId = c.Long(),
},
annotations: new Dictionary<string, object>
{
{ "DynamicFilter_Role_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
{ "DynamicFilter_Role_SoftDelete", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
})
.PrimaryKey(t => t.Id)
.ForeignKey("dbo.AbpUsers", t => t.CreatorUserId)
.ForeignKey("dbo.AbpUsers", t => t.DeleterUserId)
.ForeignKey("dbo.AbpUsers", t => t.LastModifierUserId)
.ForeignKey("dbo.AbpTenants", t => t.TenantId)
.Index(t => t.TenantId)
.Index(t => t.DeleterUserId)
.Index(t => t.LastModifierUserId)
.Index(t => t.CreatorUserId);
CreateTable(
"dbo.AbpUsers",
c => new
{
Id = c.Long(nullable: false, identity: true),
TenantId = c.Int(),
AuthenticationSource = c.String(maxLength: 64),
Name = c.String(nullable: false, maxLength: 32),
Surname = c.String(nullable: false, maxLength: 32),
UserName = c.String(nullable: false, maxLength: 32),
Password = c.String(nullable: false, maxLength: 128),
EmailAddress = c.String(nullable: false, maxLength: 256),
IsEmailConfirmed = c.Boolean(nullable: false),
EmailConfirmationCode = c.String(maxLength: 128),
PasswordResetCode = c.String(maxLength: 128),
LastLoginTime = c.DateTime(),
IsActive = c.Boolean(nullable: false),
IsDeleted = c.Boolean(nullable: false),
DeleterUserId = c.Long(),
DeletionTime = c.DateTime(),
LastModificationTime = c.DateTime(),
LastModifierUserId = c.Long(),
CreationTime = c.DateTime(nullable: false),
CreatorUserId = c.Long(),
},
annotations: new Dictionary<string, object>
{
{ "DynamicFilter_User_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
{ "DynamicFilter_User_SoftDelete", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
})
.PrimaryKey(t => t.Id)
.ForeignKey("dbo.AbpUsers", t => t.CreatorUserId)
.ForeignKey("dbo.AbpUsers", t => t.DeleterUserId)
.ForeignKey("dbo.AbpUsers", t => t.LastModifierUserId)
.ForeignKey("dbo.AbpTenants", t => t.TenantId)
.Index(t => t.TenantId)
.Index(t => t.DeleterUserId)
.Index(t => t.LastModifierUserId)
.Index(t => t.CreatorUserId);
CreateTable(
"dbo.AbpUserLogins",
c => new
{
Id = c.Long(nullable: false, identity: true),
UserId = c.Long(nullable: false),
LoginProvider = c.String(nullable: false, maxLength: 128),
ProviderKey = c.String(nullable: false, maxLength: 256),
})
.PrimaryKey(t => t.Id)
.ForeignKey("dbo.AbpUsers", t => t.UserId, cascadeDelete: true)
.Index(t => t.UserId);
CreateTable(
"dbo.AbpUserRoles",
c => new
{
Id = c.Long(nullable: false, identity: true),
UserId = c.Long(nullable: false),
RoleId = c.Int(nullable: false),
CreationTime = c.DateTime(nullable: false),
CreatorUserId = c.Long(),
})
.PrimaryKey(t => t.Id)
.ForeignKey("dbo.AbpUsers", t => t.UserId, cascadeDelete: true)
.Index(t => t.UserId);
CreateTable(
"dbo.AbpSettings",
c => new
{
Id = c.Long(nullable: false, identity: true),
TenantId = c.Int(),
UserId = c.Long(),
Name = c.String(nullable: false, maxLength: 256),
Value = c.String(maxLength: 2000),
LastModificationTime = c.DateTime(),
LastModifierUserId = c.Long(),
CreationTime = c.DateTime(nullable: false),
CreatorUserId = c.Long(),
})
.PrimaryKey(t => t.Id)
.ForeignKey("dbo.AbpUsers", t => t.UserId)
.ForeignKey("dbo.AbpTenants", t => t.TenantId)
.Index(t => t.TenantId)
.Index(t => t.UserId);
CreateTable(
"dbo.AbpTenants",
c => new
{
Id = c.Int(nullable: false, identity: true),
TenancyName = c.String(nullable: false, maxLength: 64),
Name = c.String(nullable: false, maxLength: 128),
IsActive = c.Boolean(nullable: false),
IsDeleted = c.Boolean(nullable: false),
DeleterUserId = c.Long(),
DeletionTime = c.DateTime(),
LastModificationTime = c.DateTime(),
LastModifierUserId = c.Long(),
CreationTime = c.DateTime(nullable: false),
CreatorUserId = c.Long(),
},
annotations: new Dictionary<string, object>
{
{ "DynamicFilter_Tenant_SoftDelete", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
})
.PrimaryKey(t => t.Id)
.ForeignKey("dbo.AbpUsers", t => t.CreatorUserId)
.ForeignKey("dbo.AbpUsers", t => t.DeleterUserId)
.ForeignKey("dbo.AbpUsers", t => t.LastModifierUserId)
.Index(t => t.DeleterUserId)
.Index(t => t.LastModifierUserId)
.Index(t => t.CreatorUserId);
}
public override void Down()
{
DropForeignKey("dbo.AbpRoles", "TenantId", "dbo.AbpTenants");
DropForeignKey("dbo.AbpPermissions", "RoleId", "dbo.AbpRoles");
DropForeignKey("dbo.AbpRoles", "LastModifierUserId", "dbo.AbpUsers");
DropForeignKey("dbo.AbpRoles", "DeleterUserId", "dbo.AbpUsers");
DropForeignKey("dbo.AbpRoles", "CreatorUserId", "dbo.AbpUsers");
DropForeignKey("dbo.AbpUsers", "TenantId", "dbo.AbpTenants");
DropForeignKey("dbo.AbpSettings", "TenantId", "dbo.AbpTenants");
DropForeignKey("dbo.AbpTenants", "LastModifierUserId", "dbo.AbpUsers");
DropForeignKey("dbo.AbpTenants", "DeleterUserId", "dbo.AbpUsers");
DropForeignKey("dbo.AbpTenants", "CreatorUserId", "dbo.AbpUsers");
DropForeignKey("dbo.AbpSettings", "UserId", "dbo.AbpUsers");
DropForeignKey("dbo.AbpUserRoles", "UserId", "dbo.AbpUsers");
DropForeignKey("dbo.AbpPermissions", "UserId", "dbo.AbpUsers");
DropForeignKey("dbo.AbpUserLogins", "UserId", "dbo.AbpUsers");
DropForeignKey("dbo.AbpUsers", "LastModifierUserId", "dbo.AbpUsers");
DropForeignKey("dbo.AbpUsers", "DeleterUserId", "dbo.AbpUsers");
DropForeignKey("dbo.AbpUsers", "CreatorUserId", "dbo.AbpUsers");
DropIndex("dbo.AbpTenants", new[] { "CreatorUserId" });
DropIndex("dbo.AbpTenants", new[] { "LastModifierUserId" });
DropIndex("dbo.AbpTenants", new[] { "DeleterUserId" });
DropIndex("dbo.AbpSettings", new[] { "UserId" });
DropIndex("dbo.AbpSettings", new[] { "TenantId" });
DropIndex("dbo.AbpUserRoles", new[] { "UserId" });
DropIndex("dbo.AbpUserLogins", new[] { "UserId" });
DropIndex("dbo.AbpUsers", new[] { "CreatorUserId" });
DropIndex("dbo.AbpUsers", new[] { "LastModifierUserId" });
DropIndex("dbo.AbpUsers", new[] { "DeleterUserId" });
DropIndex("dbo.AbpUsers", new[] { "TenantId" });
DropIndex("dbo.AbpRoles", new[] { "CreatorUserId" });
DropIndex("dbo.AbpRoles", new[] { "LastModifierUserId" });
DropIndex("dbo.AbpRoles", new[] { "DeleterUserId" });
DropIndex("dbo.AbpRoles", new[] { "TenantId" });
DropIndex("dbo.AbpPermissions", new[] { "UserId" });
DropIndex("dbo.AbpPermissions", new[] { "RoleId" });
DropTable("dbo.AbpTenants",
removedAnnotations: new Dictionary<string, object>
{
{ "DynamicFilter_Tenant_SoftDelete", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
});
DropTable("dbo.AbpSettings");
DropTable("dbo.AbpUserRoles");
DropTable("dbo.AbpUserLogins");
DropTable("dbo.AbpUsers",
removedAnnotations: new Dictionary<string, object>
{
{ "DynamicFilter_User_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
{ "DynamicFilter_User_SoftDelete", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
});
DropTable("dbo.AbpRoles",
removedAnnotations: new Dictionary<string, object>
{
{ "DynamicFilter_Role_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
{ "DynamicFilter_Role_SoftDelete", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
});
DropTable("dbo.AbpPermissions");
DropTable("dbo.AbpAuditLogs",
removedAnnotations: new Dictionary<string, object>
{
{ "DynamicFilter_AuditLog_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" },
});
}
}
}
| |
//
// ReflectionWriter.cs
//
// Author:
// Jb Evain (jbevain@gmail.com)
//
// (C) 2005 - 2007 Jb Evain
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
namespace Mono.Cecil {
using System;
using System.Collections;
using System.Globalization;
using System.Text;
using Mono.Cecil.Binary;
using Mono.Cecil.Cil;
using Mono.Cecil.Metadata;
using Mono.Cecil.Signatures;
internal sealed class ReflectionWriter : BaseReflectionVisitor {
StructureWriter m_structureWriter;
ModuleDefinition m_mod;
SignatureWriter m_sigWriter;
CodeWriter m_codeWriter;
MetadataWriter m_mdWriter;
MetadataTableWriter m_tableWriter;
MetadataRowWriter m_rowWriter;
bool m_saveSymbols;
string m_asmOutput;
ISymbolWriter m_symbolWriter;
ArrayList m_typeDefStack;
ArrayList m_methodStack;
ArrayList m_fieldStack;
ArrayList m_genericParamStack;
IDictionary m_typeSpecTokenCache;
IDictionary m_memberRefTokenCache;
uint m_methodIndex;
uint m_fieldIndex;
uint m_paramIndex;
uint m_eventIndex;
uint m_propertyIndex;
MemoryBinaryWriter m_constWriter;
public StructureWriter StructureWriter {
get { return m_structureWriter; }
set {
m_structureWriter = value;
Initialize ();
}
}
public CodeWriter CodeWriter {
get { return m_codeWriter; }
}
public bool SaveSymbols {
get { return m_saveSymbols; }
set { m_saveSymbols = value; }
}
public string OutputFile
{
get { return m_asmOutput; }
set { m_asmOutput = value; }
}
public ISymbolWriter SymbolWriter {
get { return m_symbolWriter; }
set { m_symbolWriter = value; }
}
public SignatureWriter SignatureWriter {
get { return m_sigWriter; }
}
public MetadataWriter MetadataWriter {
get { return m_mdWriter; }
}
public MetadataTableWriter MetadataTableWriter {
get { return m_tableWriter; }
}
public MetadataRowWriter MetadataRowWriter {
get { return m_rowWriter; }
}
public ReflectionWriter (ModuleDefinition mod)
{
m_mod = mod;
}
void Initialize ()
{
m_mdWriter = new MetadataWriter (
m_mod.Assembly,
m_mod.Image.MetadataRoot,
m_structureWriter.Assembly.Kind,
m_mod.Assembly.Runtime,
m_structureWriter.GetWriter ());
m_tableWriter = m_mdWriter.GetTableVisitor ();
m_rowWriter = m_tableWriter.GetRowVisitor () as MetadataRowWriter;
m_sigWriter = new SignatureWriter (m_mdWriter);
m_codeWriter = new CodeWriter (this, m_mdWriter.CilWriter);
m_typeDefStack = new ArrayList ();
m_methodStack = new ArrayList ();
m_fieldStack = new ArrayList ();
m_genericParamStack = new ArrayList ();
m_typeSpecTokenCache = new Hashtable ();
m_memberRefTokenCache = new Hashtable ();
m_methodIndex = 1;
m_fieldIndex = 1;
m_paramIndex = 1;
m_eventIndex = 1;
m_propertyIndex = 1;
m_constWriter = new MemoryBinaryWriter ();
}
public TypeReference GetCoreType (string name)
{
return m_mod.Controller.Reader.SearchCoreType (name);
}
public static uint GetRidFor (IMetadataTokenProvider tp)
{
return tp.MetadataToken.RID;
}
public uint GetRidFor (AssemblyNameReference asmName)
{
return (uint) m_mod.AssemblyReferences.IndexOf (asmName) + 1;
}
public uint GetRidFor (ModuleDefinition mod)
{
return (uint) m_mod.Assembly.Modules.IndexOf (mod) + 1;
}
public uint GetRidFor (ModuleReference modRef)
{
return (uint) m_mod.ModuleReferences.IndexOf (modRef) + 1;
}
static bool IsTypeSpec (TypeReference type)
{
return type is TypeSpecification || type is GenericParameter;
}
public MetadataToken GetTypeDefOrRefToken (TypeReference type)
{
if (IsTypeSpec (type)) {
uint sig = m_sigWriter.AddTypeSpec (GetTypeSpecSig (type));
if (m_typeSpecTokenCache.Contains (sig))
return (MetadataToken) m_typeSpecTokenCache [sig];
TypeSpecTable tsTable = m_tableWriter.GetTypeSpecTable ();
TypeSpecRow tsRow = m_rowWriter.CreateTypeSpecRow (sig);
tsTable.Rows.Add (tsRow);
MetadataToken token = new MetadataToken (TokenType.TypeSpec, (uint) tsTable.Rows.Count);
if (! (type is GenericParameter))
type.MetadataToken = token;
m_typeSpecTokenCache [sig] = token;
return token;
} else if (type != null)
return type.MetadataToken;
else // <Module> and interfaces
return new MetadataToken (TokenType.TypeRef, 0);
}
public MetadataToken GetMemberRefToken (MemberReference member)
{
if (member is MethodSpecification)
return GetMemberRefToken (((MethodSpecification) member).ElementMethod);
if (member is IMemberDefinition)
return member.MetadataToken;
if (m_memberRefTokenCache.Contains (member))
return (MetadataToken) m_memberRefTokenCache [member];
MemberRefTable mrTable = m_tableWriter.GetMemberRefTable ();
uint sig = 0;
if (member is FieldReference)
sig = m_sigWriter.AddFieldSig (GetFieldSig ((FieldReference) member));
else if (member is MethodReference)
sig = m_sigWriter.AddMethodRefSig (GetMethodRefSig ((MethodReference) member));
MetadataToken declaringType = GetTypeDefOrRefToken (member.DeclaringType);
uint name = m_mdWriter.AddString (member.Name);
for (int i = 0; i < mrTable.Rows.Count; i++) {
MemberRefRow row = mrTable [i];
if (row.Class == declaringType && row.Name == name && row.Signature == sig)
return MetadataToken.FromMetadataRow (TokenType.MemberRef, i);
}
MemberRefRow mrRow = m_rowWriter.CreateMemberRefRow (
declaringType,
name,
sig);
mrTable.Rows.Add (mrRow);
member.MetadataToken = new MetadataToken (
TokenType.MemberRef, (uint) mrTable.Rows.Count);
m_memberRefTokenCache [member] = member.MetadataToken;
return member.MetadataToken;
}
public MetadataToken GetMethodSpecToken (GenericInstanceMethod gim)
{
uint sig = m_sigWriter.AddMethodSpec (GetMethodSpecSig (gim));
MethodSpecTable msTable = m_tableWriter.GetMethodSpecTable ();
MetadataToken meth = GetMemberRefToken (gim.ElementMethod);
for (int i = 0; i < msTable.Rows.Count; i++) {
MethodSpecRow row = msTable [i];
if (row.Method == meth && row.Instantiation == sig)
return MetadataToken.FromMetadataRow (TokenType.MethodSpec, i);
}
MethodSpecRow msRow = m_rowWriter.CreateMethodSpecRow (
meth,
sig);
msTable.Rows.Add (msRow);
gim.MetadataToken = new MetadataToken (TokenType.MethodSpec, (uint) msTable.Rows.Count);
return gim.MetadataToken;
}
public override void VisitModuleDefinition (ModuleDefinition mod)
{
mod.FullLoad ();
}
public override void VisitTypeDefinitionCollection (TypeDefinitionCollection types)
{
TypeDefTable tdTable = m_tableWriter.GetTypeDefTable ();
if (types [Constants.ModuleType] == null)
types.Add (new TypeDefinition (
Constants.ModuleType, string.Empty, TypeAttributes.NotPublic));
foreach (TypeDefinition t in types)
m_typeDefStack.Add (t);
m_typeDefStack.Sort (TableComparers.TypeDef.Instance);
for (int i = 0; i < m_typeDefStack.Count; i++) {
TypeDefinition t = (TypeDefinition) m_typeDefStack [i];
if (t.Module.Assembly != m_mod.Assembly)
throw new ReflectionException ("A type as not been correctly imported");
t.MetadataToken = new MetadataToken (TokenType.TypeDef, (uint) (i + 1));
}
foreach (TypeDefinition t in m_typeDefStack) {
TypeDefRow tdRow = m_rowWriter.CreateTypeDefRow (
t.Attributes,
m_mdWriter.AddString (t.Name),
m_mdWriter.AddString (t.Namespace),
GetTypeDefOrRefToken (t.BaseType),
0,
0);
tdTable.Rows.Add (tdRow);
}
}
public void CompleteTypeDefinitions ()
{
TypeDefTable tdTable = m_tableWriter.GetTypeDefTable ();
for (int i = 0; i < m_typeDefStack.Count; i++) {
TypeDefRow tdRow = tdTable [i];
TypeDefinition t = (TypeDefinition) m_typeDefStack [i];
tdRow.FieldList = m_fieldIndex;
tdRow.MethodList = m_methodIndex;
foreach (FieldDefinition field in t.Fields)
VisitFieldDefinition (field);
foreach (MethodDefinition ctor in t.Constructors)
VisitMethodDefinition (ctor);
foreach (MethodDefinition meth in t.Methods)
VisitMethodDefinition (meth);
if (t.HasLayoutInfo)
WriteLayout (t);
}
foreach (FieldDefinition field in m_fieldStack) {
VisitCustomAttributeCollection (field.CustomAttributes);
if (field.MarshalSpec != null)
VisitMarshalSpec (field.MarshalSpec);
}
foreach (MethodDefinition meth in m_methodStack) {
VisitCustomAttributeCollection (meth.ReturnType.CustomAttributes);
foreach (ParameterDefinition param in meth.Parameters)
VisitCustomAttributeCollection (param.CustomAttributes);
VisitGenericParameterCollection (meth.GenericParameters);
VisitOverrideCollection (meth.Overrides);
VisitCustomAttributeCollection (meth.CustomAttributes);
VisitSecurityDeclarationCollection (meth.SecurityDeclarations);
if (meth.PInvokeInfo != null) {
meth.Attributes |= MethodAttributes.PInvokeImpl;
VisitPInvokeInfo (meth.PInvokeInfo);
}
}
foreach (TypeDefinition t in m_typeDefStack)
t.Accept (this);
}
public override void VisitTypeReferenceCollection (TypeReferenceCollection refs)
{
ArrayList orderedTypeRefs = new ArrayList (refs.Count);
foreach (TypeReference tr in refs)
orderedTypeRefs.Add (tr);
orderedTypeRefs.Sort (TableComparers.TypeRef.Instance);
TypeRefTable trTable = m_tableWriter.GetTypeRefTable ();
foreach (TypeReference t in orderedTypeRefs) {
MetadataToken scope;
if (t.Module.Assembly != m_mod.Assembly)
throw new ReflectionException ("A type as not been correctly imported");
if (t.Scope == null)
continue;
if (t.DeclaringType != null)
scope = new MetadataToken (TokenType.TypeRef, GetRidFor (t.DeclaringType));
else if (t.Scope is AssemblyNameReference)
scope = new MetadataToken (TokenType.AssemblyRef,
GetRidFor ((AssemblyNameReference) t.Scope));
else if (t.Scope is ModuleDefinition)
scope = new MetadataToken (TokenType.Module,
GetRidFor ((ModuleDefinition) t.Scope));
else if (t.Scope is ModuleReference)
scope = new MetadataToken (TokenType.ModuleRef,
GetRidFor ((ModuleReference) t.Scope));
else
scope = new MetadataToken (TokenType.ExportedType, 0);
TypeRefRow trRow = m_rowWriter.CreateTypeRefRow (
scope,
m_mdWriter.AddString (t.Name),
m_mdWriter.AddString (t.Namespace));
trTable.Rows.Add (trRow);
t.MetadataToken = new MetadataToken (TokenType.TypeRef, (uint) trTable.Rows.Count);
}
}
public override void VisitGenericParameterCollection (GenericParameterCollection parameters)
{
if (parameters.Count == 0)
return;
foreach (GenericParameter gp in parameters)
m_genericParamStack.Add (gp);
}
public override void VisitInterfaceCollection (InterfaceCollection interfaces)
{
if (interfaces.Count == 0)
return;
InterfaceImplTable iiTable = m_tableWriter.GetInterfaceImplTable ();
foreach (TypeReference interf in interfaces) {
InterfaceImplRow iiRow = m_rowWriter.CreateInterfaceImplRow (
GetRidFor (interfaces.Container),
GetTypeDefOrRefToken (interf));
iiTable.Rows.Add (iiRow);
}
}
public override void VisitExternTypeCollection (ExternTypeCollection externs)
{
VisitCollection (externs);
}
public override void VisitExternType (TypeReference externType)
{
// TODO
}
public override void VisitOverrideCollection (OverrideCollection meths)
{
if (meths.Count == 0)
return;
MethodImplTable miTable = m_tableWriter.GetMethodImplTable ();
foreach (MethodReference ov in meths) {
MethodImplRow miRow = m_rowWriter.CreateMethodImplRow (
GetRidFor (meths.Container.DeclaringType as TypeDefinition),
new MetadataToken (TokenType.Method, GetRidFor (meths.Container)),
GetMemberRefToken (ov));
miTable.Rows.Add (miRow);
}
}
public override void VisitNestedTypeCollection (NestedTypeCollection nestedTypes)
{
if (nestedTypes.Count == 0)
return;
NestedClassTable ncTable = m_tableWriter.GetNestedClassTable ();
foreach (TypeDefinition nested in nestedTypes) {
NestedClassRow ncRow = m_rowWriter.CreateNestedClassRow (
nested.MetadataToken.RID,
GetRidFor (nestedTypes.Container));
ncTable.Rows.Add (ncRow);
}
}
public override void VisitParameterDefinitionCollection (ParameterDefinitionCollection parameters)
{
if (parameters.Count == 0)
return;
ushort seq = 1;
ParamTable pTable = m_tableWriter.GetParamTable ();
foreach (ParameterDefinition param in parameters)
InsertParameter (pTable, param, seq++);
}
void InsertParameter (ParamTable pTable, ParameterDefinition param, ushort seq)
{
ParamRow pRow = m_rowWriter.CreateParamRow (
param.Attributes,
seq,
m_mdWriter.AddString (param.Name));
pTable.Rows.Add (pRow);
param.MetadataToken = new MetadataToken (TokenType.Param, (uint) pTable.Rows.Count);
if (param.MarshalSpec != null)
param.MarshalSpec.Accept (this);
if (param.HasConstant)
WriteConstant (param, param.ParameterType);
m_paramIndex++;
}
static bool RequiresParameterRow (MethodReturnType mrt)
{
return mrt.HasConstant || mrt.MarshalSpec != null ||
mrt.CustomAttributes.Count > 0 || mrt.Parameter.Attributes != (ParameterAttributes) 0;
}
public override void VisitMethodDefinition (MethodDefinition method)
{
MethodTable mTable = m_tableWriter.GetMethodTable ();
MethodRow mRow = m_rowWriter.CreateMethodRow (
RVA.Zero,
method.ImplAttributes,
method.Attributes,
m_mdWriter.AddString (method.Name),
m_sigWriter.AddMethodDefSig (GetMethodDefSig (method)),
m_paramIndex);
mTable.Rows.Add (mRow);
m_methodStack.Add (method);
method.MetadataToken = new MetadataToken (TokenType.Method, (uint) mTable.Rows.Count);
m_methodIndex++;
if (RequiresParameterRow (method.ReturnType))
InsertParameter (m_tableWriter.GetParamTable (), method.ReturnType.Parameter, 0);
VisitParameterDefinitionCollection (method.Parameters);
}
public override void VisitPInvokeInfo (PInvokeInfo pinvk)
{
ImplMapTable imTable = m_tableWriter.GetImplMapTable ();
ImplMapRow imRow = m_rowWriter.CreateImplMapRow (
pinvk.Attributes,
new MetadataToken (TokenType.Method, GetRidFor (pinvk.Method)),
m_mdWriter.AddString (pinvk.EntryPoint),
GetRidFor (pinvk.Module));
imTable.Rows.Add (imRow);
}
public override void VisitEventDefinitionCollection (EventDefinitionCollection events)
{
if (events.Count == 0)
return;
EventMapTable emTable = m_tableWriter.GetEventMapTable ();
EventMapRow emRow = m_rowWriter.CreateEventMapRow (
GetRidFor (events.Container),
m_eventIndex);
emTable.Rows.Add (emRow);
VisitCollection (events);
}
public override void VisitEventDefinition (EventDefinition evt)
{
EventTable eTable = m_tableWriter.GetEventTable ();
EventRow eRow = m_rowWriter.CreateEventRow (
evt.Attributes,
m_mdWriter.AddString (evt.Name),
GetTypeDefOrRefToken (evt.EventType));
eTable.Rows.Add (eRow);
evt.MetadataToken = new MetadataToken (TokenType.Event, (uint) eTable.Rows.Count);
if (evt.AddMethod != null)
WriteSemantic (MethodSemanticsAttributes.AddOn, evt, evt.AddMethod);
if (evt.InvokeMethod != null)
WriteSemantic (MethodSemanticsAttributes.Fire, evt, evt.InvokeMethod);
if (evt.RemoveMethod != null)
WriteSemantic (MethodSemanticsAttributes.RemoveOn, evt, evt.RemoveMethod);
m_eventIndex++;
}
public override void VisitFieldDefinition (FieldDefinition field)
{
FieldTable fTable = m_tableWriter.GetFieldTable ();
FieldRow fRow = m_rowWriter.CreateFieldRow (
field.Attributes,
m_mdWriter.AddString (field.Name),
m_sigWriter.AddFieldSig (GetFieldSig (field)));
fTable.Rows.Add (fRow);
field.MetadataToken = new MetadataToken (TokenType.Field, (uint) fTable.Rows.Count);
m_fieldIndex++;
if (field.HasConstant)
WriteConstant (field, field.FieldType);
if (field.HasLayoutInfo)
WriteLayout (field);
m_fieldStack.Add (field);
}
public override void VisitPropertyDefinitionCollection (PropertyDefinitionCollection properties)
{
if (properties.Count == 0)
return;
PropertyMapTable pmTable = m_tableWriter.GetPropertyMapTable ();
PropertyMapRow pmRow = m_rowWriter.CreatePropertyMapRow (
GetRidFor (properties.Container),
m_propertyIndex);
pmTable.Rows.Add (pmRow);
VisitCollection (properties);
}
public override void VisitPropertyDefinition (PropertyDefinition property)
{
PropertyTable pTable = m_tableWriter.GetPropertyTable ();
PropertyRow pRow = m_rowWriter.CreatePropertyRow (
property.Attributes,
m_mdWriter.AddString (property.Name),
m_sigWriter.AddPropertySig (GetPropertySig (property)));
pTable.Rows.Add (pRow);
property.MetadataToken = new MetadataToken (TokenType.Property, (uint) pTable.Rows.Count);
if (property.GetMethod != null)
WriteSemantic (MethodSemanticsAttributes.Getter, property, property.GetMethod);
if (property.SetMethod != null)
WriteSemantic (MethodSemanticsAttributes.Setter, property, property.SetMethod);
if (property.HasConstant)
WriteConstant (property, property.PropertyType);
m_propertyIndex++;
}
public override void VisitSecurityDeclarationCollection (SecurityDeclarationCollection secDecls)
{
if (secDecls.Count == 0)
return;
DeclSecurityTable dsTable = m_tableWriter.GetDeclSecurityTable ();
foreach (SecurityDeclaration secDec in secDecls) {
DeclSecurityRow dsRow = m_rowWriter.CreateDeclSecurityRow (
secDec.Action,
secDecls.Container.MetadataToken,
m_mdWriter.AddBlob (secDec.Resolved ?
m_mod.GetAsByteArray (secDec) : secDec.Blob));
dsTable.Rows.Add (dsRow);
}
}
public override void VisitCustomAttributeCollection (CustomAttributeCollection customAttrs)
{
if (customAttrs.Count == 0)
return;
CustomAttributeTable caTable = m_tableWriter.GetCustomAttributeTable ();
foreach (CustomAttribute ca in customAttrs) {
MetadataToken parent;
if (customAttrs.Container is AssemblyDefinition)
parent = new MetadataToken (TokenType.Assembly, 1);
else if (customAttrs.Container is ModuleDefinition)
parent = new MetadataToken (TokenType.Module, 1);
else if (customAttrs.Container is IMetadataTokenProvider)
parent = ((IMetadataTokenProvider) customAttrs.Container).MetadataToken;
else
throw new ReflectionException ("Unknown Custom Attribute parent");
uint value = ca.Resolved ?
m_sigWriter.AddCustomAttribute (GetCustomAttributeSig (ca), ca.Constructor) :
m_mdWriter.AddBlob (m_mod.GetAsByteArray (ca));
CustomAttributeRow caRow = m_rowWriter.CreateCustomAttributeRow (
parent,
GetMemberRefToken (ca.Constructor),
value);
caTable.Rows.Add (caRow);
}
}
public override void VisitMarshalSpec (MarshalSpec marshalSpec)
{
FieldMarshalTable fmTable = m_tableWriter.GetFieldMarshalTable ();
FieldMarshalRow fmRow = m_rowWriter.CreateFieldMarshalRow (
marshalSpec.Container.MetadataToken,
m_sigWriter.AddMarshalSig (GetMarshalSig (marshalSpec)));
fmTable.Rows.Add (fmRow);
}
void WriteConstant (IHasConstant hc, TypeReference type)
{
ConstantTable cTable = m_tableWriter.GetConstantTable ();
ElementType et;
if (type is TypeDefinition && (type as TypeDefinition).IsEnum) {
Type t = hc.Constant.GetType ();
if (t.IsEnum)
t = Enum.GetUnderlyingType (t);
et = GetCorrespondingType (string.Concat (t.Namespace, '.', t.Name));
} else
et = GetCorrespondingType (type.FullName);
if (et == ElementType.Object || et == ElementType.Type)
et = hc.Constant == null ?
ElementType.Class :
GetCorrespondingType (hc.Constant.GetType ().FullName);
ConstantRow cRow = m_rowWriter.CreateConstantRow (
et,
hc.MetadataToken,
m_mdWriter.AddBlob (EncodeConstant (et, hc.Constant)));
cTable.Rows.Add (cRow);
}
void WriteLayout (FieldDefinition field)
{
FieldLayoutTable flTable = m_tableWriter.GetFieldLayoutTable ();
FieldLayoutRow flRow = m_rowWriter.CreateFieldLayoutRow (
field.Offset,
GetRidFor (field));
flTable.Rows.Add (flRow);
}
void WriteLayout (TypeDefinition type)
{
ClassLayoutTable clTable = m_tableWriter.GetClassLayoutTable ();
ClassLayoutRow clRow = m_rowWriter.CreateClassLayoutRow (
type.PackingSize,
type.ClassSize,
GetRidFor (type));
clTable.Rows.Add (clRow);
}
void WriteSemantic (MethodSemanticsAttributes attrs,
IMetadataTokenProvider member, MethodDefinition meth)
{
MethodSemanticsTable msTable = m_tableWriter.GetMethodSemanticsTable ();
MethodSemanticsRow msRow = m_rowWriter.CreateMethodSemanticsRow (
attrs,
GetRidFor (meth),
member.MetadataToken);
msTable.Rows.Add (msRow);
}
void SortTables ()
{
TablesHeap th = m_mdWriter.GetMetadataRoot ().Streams.TablesHeap;
th.Sorted = 0;
if (th.HasTable (NestedClassTable.RId))
m_tableWriter.GetNestedClassTable ().Rows.Sort (
TableComparers.NestedClass.Instance);
th.Sorted |= ((long) 1 << NestedClassTable.RId);
if (th.HasTable (InterfaceImplTable.RId))
m_tableWriter.GetInterfaceImplTable ().Rows.Sort (
TableComparers.InterfaceImpl.Instance);
th.Sorted |= ((long) 1 << InterfaceImplTable.RId);
if (th.HasTable (ConstantTable.RId))
m_tableWriter.GetConstantTable ().Rows.Sort (
TableComparers.Constant.Instance);
th.Sorted |= ((long) 1 << ConstantTable.RId);
if (th.HasTable (MethodSemanticsTable.RId))
m_tableWriter.GetMethodSemanticsTable ().Rows.Sort (
TableComparers.MethodSem.Instance);
th.Sorted |= ((long) 1 << MethodSemanticsTable.RId);
if (th.HasTable (FieldMarshalTable.RId))
m_tableWriter.GetFieldMarshalTable ().Rows.Sort (
TableComparers.FieldMarshal.Instance);
th.Sorted |= ((long) 1 << FieldMarshalTable.RId);
if (th.HasTable (ClassLayoutTable.RId))
m_tableWriter.GetClassLayoutTable ().Rows.Sort (
TableComparers.TypeLayout.Instance);
th.Sorted |= ((long) 1 << ClassLayoutTable.RId);
if (th.HasTable (FieldLayoutTable.RId))
m_tableWriter.GetFieldLayoutTable ().Rows.Sort (
TableComparers.FieldLayout.Instance);
th.Sorted |= ((long) 1 << FieldLayoutTable.RId);
if (th.HasTable (ImplMapTable.RId))
m_tableWriter.GetImplMapTable ().Rows.Sort (
TableComparers.PInvoke.Instance);
th.Sorted |= ((long) 1 << ImplMapTable.RId);
if (th.HasTable (FieldRVATable.RId))
m_tableWriter.GetFieldRVATable ().Rows.Sort (
TableComparers.FieldRVA.Instance);
th.Sorted |= ((long) 1 << FieldRVATable.RId);
if (th.HasTable (MethodImplTable.RId))
m_tableWriter.GetMethodImplTable ().Rows.Sort (
TableComparers.Override.Instance);
th.Sorted |= ((long) 1 << MethodImplTable.RId);
if (th.HasTable (CustomAttributeTable.RId))
m_tableWriter.GetCustomAttributeTable ().Rows.Sort (
TableComparers.CustomAttribute.Instance);
th.Sorted |= ((long) 1 << CustomAttributeTable.RId);
if (th.HasTable (DeclSecurityTable.RId))
m_tableWriter.GetDeclSecurityTable ().Rows.Sort (
TableComparers.SecurityDeclaration.Instance);
th.Sorted |= ((long) 1 << DeclSecurityTable.RId);
}
void CompleteGenericTables ()
{
if (m_genericParamStack.Count == 0)
return;
TablesHeap th = m_mdWriter.GetMetadataRoot ().Streams.TablesHeap;
GenericParamTable gpTable = m_tableWriter.GetGenericParamTable ();
GenericParamConstraintTable gpcTable = m_tableWriter.GetGenericParamConstraintTable ();
m_genericParamStack.Sort (TableComparers.GenericParam.Instance);
foreach (GenericParameter gp in m_genericParamStack) {
GenericParamRow gpRow = m_rowWriter.CreateGenericParamRow (
(ushort) gp.Owner.GenericParameters.IndexOf (gp),
gp.Attributes,
gp.Owner.MetadataToken,
m_mdWriter.AddString (gp.Name));
gpTable.Rows.Add (gpRow);
gp.MetadataToken = new MetadataToken (TokenType.GenericParam, (uint) gpTable.Rows.Count);
VisitCustomAttributeCollection (gp.CustomAttributes);
if (gp.Constraints.Count == 0)
continue;
foreach (TypeReference constraint in gp.Constraints) {
GenericParamConstraintRow gpcRow = m_rowWriter.CreateGenericParamConstraintRow (
(uint) gpTable.Rows.Count,
GetTypeDefOrRefToken (constraint));
gpcTable.Rows.Add (gpcRow);
}
}
th.Sorted |= ((long) 1 << GenericParamTable.RId);
th.Sorted |= ((long) 1 << GenericParamConstraintTable.RId);
}
public override void TerminateModuleDefinition (ModuleDefinition module)
{
VisitCustomAttributeCollection (module.Assembly.CustomAttributes);
VisitSecurityDeclarationCollection (module.Assembly.SecurityDeclarations);
VisitCustomAttributeCollection (module.CustomAttributes);
CompleteGenericTables ();
SortTables ();
MethodTable mTable = m_tableWriter.GetMethodTable ();
for (int i = 0; i < m_methodStack.Count; i++) {
MethodDefinition meth = (MethodDefinition) m_methodStack [i];
if (meth.HasBody)
mTable [i].RVA = m_codeWriter.WriteMethodBody (meth);
}
if (m_fieldStack.Count > 0) {
FieldRVATable frTable = null;
foreach (FieldDefinition field in m_fieldStack) {
if (field.InitialValue != null && field.InitialValue.Length > 0) {
if (frTable == null)
frTable = m_tableWriter.GetFieldRVATable ();
FieldRVARow frRow = m_rowWriter.CreateFieldRVARow (
m_mdWriter.GetDataCursor (),
field.MetadataToken.RID);
m_mdWriter.AddData (field.InitialValue.Length + 3 & (~3));
m_mdWriter.AddFieldInitData (field.InitialValue);
frTable.Rows.Add (frRow);
}
}
}
if (m_symbolWriter != null)
m_symbolWriter.Dispose ();
if (m_mod.Assembly.EntryPoint != null)
m_mdWriter.EntryPointToken =
((uint) TokenType.Method) | GetRidFor (m_mod.Assembly.EntryPoint);
m_mod.Image.MetadataRoot.Accept (m_mdWriter);
}
public static ElementType GetCorrespondingType (string fullName)
{
switch (fullName) {
case Constants.Boolean :
return ElementType.Boolean;
case Constants.Char :
return ElementType.Char;
case Constants.SByte :
return ElementType.I1;
case Constants.Int16 :
return ElementType.I2;
case Constants.Int32 :
return ElementType.I4;
case Constants.Int64 :
return ElementType.I8;
case Constants.Byte :
return ElementType.U1;
case Constants.UInt16 :
return ElementType.U2;
case Constants.UInt32 :
return ElementType.U4;
case Constants.UInt64 :
return ElementType.U8;
case Constants.Single :
return ElementType.R4;
case Constants.Double :
return ElementType.R8;
case Constants.String :
return ElementType.String;
case Constants.Type :
return ElementType.Type;
case Constants.Object :
return ElementType.Object;
default:
return ElementType.Class;
}
}
byte [] EncodeConstant (ElementType et, object value)
{
m_constWriter.Empty ();
if (value == null)
et = ElementType.Class;
IConvertible ic = value as IConvertible;
IFormatProvider fp = CultureInfo.CurrentCulture.NumberFormat;
switch (et) {
case ElementType.Boolean :
m_constWriter.Write ((byte) (ic.ToBoolean (fp) ? 1 : 0));
break;
case ElementType.Char :
m_constWriter.Write ((ushort) ic.ToChar (fp));
break;
case ElementType.I1 :
m_constWriter.Write (ic.ToSByte (fp));
break;
case ElementType.I2 :
m_constWriter.Write (ic.ToInt16 (fp));
break;
case ElementType.I4 :
m_constWriter.Write (ic.ToInt32 (fp));
break;
case ElementType.I8 :
m_constWriter.Write (ic.ToInt64 (fp));
break;
case ElementType.U1 :
m_constWriter.Write (ic.ToByte (fp));
break;
case ElementType.U2 :
m_constWriter.Write (ic.ToUInt16 (fp));
break;
case ElementType.U4 :
m_constWriter.Write (ic.ToUInt32 (fp));
break;
case ElementType.U8 :
m_constWriter.Write (ic.ToUInt64 (fp));
break;
case ElementType.R4 :
m_constWriter.Write (ic.ToSingle (fp));
break;
case ElementType.R8 :
m_constWriter.Write (ic.ToDouble (fp));
break;
case ElementType.String :
m_constWriter.Write (Encoding.Unicode.GetBytes ((string) value));
break;
case ElementType.Class :
m_constWriter.Write (new byte [4]);
break;
default :
throw new ArgumentException ("Non valid element for a constant");
}
return m_constWriter.ToArray ();
}
public SigType GetSigType (TypeReference type)
{
string name = type.FullName;
switch (name) {
case Constants.Void :
return new SigType (ElementType.Void);
case Constants.Object :
return new SigType (ElementType.Object);
case Constants.Boolean :
return new SigType (ElementType.Boolean);
case Constants.String :
return new SigType (ElementType.String);
case Constants.Char :
return new SigType (ElementType.Char);
case Constants.SByte :
return new SigType (ElementType.I1);
case Constants.Byte :
return new SigType (ElementType.U1);
case Constants.Int16 :
return new SigType (ElementType.I2);
case Constants.UInt16 :
return new SigType (ElementType.U2);
case Constants.Int32 :
return new SigType (ElementType.I4);
case Constants.UInt32 :
return new SigType (ElementType.U4);
case Constants.Int64 :
return new SigType (ElementType.I8);
case Constants.UInt64 :
return new SigType (ElementType.U8);
case Constants.Single :
return new SigType (ElementType.R4);
case Constants.Double :
return new SigType (ElementType.R8);
case Constants.IntPtr :
return new SigType (ElementType.I);
case Constants.UIntPtr :
return new SigType (ElementType.U);
case Constants.TypedReference :
return new SigType (ElementType.TypedByRef);
}
if (type is GenericParameter) {
GenericParameter gp = type as GenericParameter;
int pos = gp.Owner.GenericParameters.IndexOf (gp);
if (gp.Owner is TypeReference)
return new VAR (pos);
else if (gp.Owner is MethodReference)
return new MVAR (pos);
else
throw new ReflectionException ("Unkown generic parameter type");
} else if (type is GenericInstanceType) {
GenericInstanceType git = type as GenericInstanceType;
GENERICINST gi = new GENERICINST ();
gi.ValueType = git.IsValueType;
gi.Type = GetTypeDefOrRefToken (git.ElementType);
gi.Signature = new GenericInstSignature ();
gi.Signature.Arity = git.GenericArguments.Count;
gi.Signature.Types = new GenericArg [gi.Signature.Arity];
for (int i = 0; i < git.GenericArguments.Count; i++)
gi.Signature.Types [i] = GetGenericArgSig (git.GenericArguments [i]);
return gi;
} else if (type is ArrayType) {
ArrayType aryType = type as ArrayType;
if (aryType.IsSizedArray) {
SZARRAY szary = new SZARRAY ();
szary.CustomMods = GetCustomMods (aryType.ElementType);
szary.Type = GetSigType (aryType.ElementType);
return szary;
}
// not optimized
ArrayShape shape = new ArrayShape ();
shape.Rank = aryType.Dimensions.Count;
shape.NumSizes = 0;
for (int i = 0; i < shape.Rank; i++) {
ArrayDimension dim = aryType.Dimensions [i];
if (dim.UpperBound > 0)
shape.NumSizes++;
}
shape.Sizes = new int [shape.NumSizes];
shape.NumLoBounds = shape.Rank;
shape.LoBounds = new int [shape.NumLoBounds];
for (int i = 0; i < shape.Rank; i++) {
ArrayDimension dim = aryType.Dimensions [i];
shape.LoBounds [i] = dim.LowerBound;
if (dim.UpperBound > 0)
shape.Sizes [i] = dim.UpperBound - dim.LowerBound + 1;
}
ARRAY ary = new ARRAY ();
ary.Shape = shape;
ary.CustomMods = GetCustomMods (aryType.ElementType);
ary.Type = GetSigType (aryType.ElementType);
return ary;
} else if (type is PointerType) {
PTR p = new PTR ();
TypeReference elementType = (type as PointerType).ElementType;
p.Void = elementType.FullName == Constants.Void;
if (!p.Void) {
p.CustomMods = GetCustomMods (elementType);
p.PtrType = GetSigType (elementType);
}
return p;
} else if (type is FunctionPointerType) {
FNPTR fp = new FNPTR ();
FunctionPointerType fptr = type as FunctionPointerType;
int sentinel = fptr.GetSentinel ();
if (sentinel < 0)
fp.Method = GetMethodDefSig (fptr);
else
fp.Method = GetMethodRefSig (fptr);
return fp;
} else if (type is TypeSpecification) {
return GetSigType ((type as TypeSpecification).ElementType);
} else if (type.IsValueType) {
VALUETYPE vt = new VALUETYPE ();
vt.Type = GetTypeDefOrRefToken (type);
return vt;
} else {
CLASS c = new CLASS ();
c.Type = GetTypeDefOrRefToken (type);
return c;
}
}
public GenericArg GetGenericArgSig (TypeReference type)
{
GenericArg arg = new GenericArg (GetSigType (type));
arg.CustomMods = GetCustomMods (type);
return arg;
}
public CustomMod [] GetCustomMods (TypeReference type)
{
ModType modifier = type as ModType;
if (modifier == null)
return new CustomMod [0];
ArrayList cmods = new ArrayList ();
do {
CustomMod cmod = new CustomMod ();
cmod.TypeDefOrRef = GetTypeDefOrRefToken (modifier.ModifierType);
if (modifier is ModifierOptional)
cmod.CMOD = CustomMod.CMODType.OPT;
else if (modifier is ModifierRequired)
cmod.CMOD = CustomMod.CMODType.REQD;
cmods.Add (cmod);
modifier = modifier.ElementType as ModType;
} while (modifier != null);
return cmods.ToArray (typeof (CustomMod)) as CustomMod [];
}
public Signature GetMemberRefSig (MemberReference member)
{
if (member is FieldReference)
return GetFieldSig (member as FieldReference);
else
return GetMemberRefSig (member as MethodReference);
}
public FieldSig GetFieldSig (FieldReference field)
{
FieldSig sig = new FieldSig ();
sig.CallingConvention |= 0x6;
sig.Field = true;
sig.CustomMods = GetCustomMods (field.FieldType);
sig.Type = GetSigType (field.FieldType);
return sig;
}
Param [] GetParametersSig (ParameterDefinitionCollection parameters)
{
Param [] ret = new Param [parameters.Count];
for (int i = 0; i < ret.Length; i++) {
ParameterDefinition pDef = parameters [i];
Param p = new Param ();
p.CustomMods = GetCustomMods (pDef.ParameterType);
if (pDef.ParameterType.FullName == Constants.TypedReference)
p.TypedByRef = true;
else if (IsByReferenceType (pDef.ParameterType)) {
p.ByRef = true;
p.Type = GetSigType (pDef.ParameterType);
} else
p.Type = GetSigType (pDef.ParameterType);
ret [i] = p;
}
return ret;
}
void CompleteMethodSig (IMethodSignature meth, MethodSig sig)
{
sig.HasThis = meth.HasThis;
sig.ExplicitThis = meth.ExplicitThis;
if (sig.HasThis)
sig.CallingConvention |= 0x20;
if (sig.ExplicitThis)
sig.CallingConvention |= 0x40;
if ((meth.CallingConvention & MethodCallingConvention.VarArg) != 0)
sig.CallingConvention |= 0x5;
sig.ParamCount = meth.Parameters.Count;
sig.Parameters = GetParametersSig (meth.Parameters);
RetType rtSig = new RetType ();
rtSig.CustomMods = GetCustomMods (meth.ReturnType.ReturnType);
if (meth.ReturnType.ReturnType.FullName == Constants.Void)
rtSig.Void = true;
else if (meth.ReturnType.ReturnType.FullName == Constants.TypedReference)
rtSig.TypedByRef = true;
else if (IsByReferenceType (meth.ReturnType.ReturnType)) {
rtSig.ByRef = true;
rtSig.Type = GetSigType (meth.ReturnType.ReturnType);
} else
rtSig.Type = GetSigType (meth.ReturnType.ReturnType);
sig.RetType = rtSig;
}
static bool IsByReferenceType (TypeReference type)
{
TypeSpecification ts = type as TypeSpecification;
while (ts != null) {
if (ts is ReferenceType)
return true;
ts = ts.ElementType as TypeSpecification;
}
return false;
}
public MethodRefSig GetMethodRefSig (IMethodSignature meth)
{
MethodReference methodRef = meth as MethodReference;
if (methodRef != null && methodRef.GenericParameters.Count > 0)
return GetMethodDefSig (meth);
MethodRefSig methSig = new MethodRefSig ();
CompleteMethodSig (meth, methSig);
int sentinel = meth.GetSentinel ();
if (sentinel >= 0)
methSig.Sentinel = sentinel;
if ((meth.CallingConvention & MethodCallingConvention.C) != 0)
methSig.CallingConvention |= 0x1;
else if ((meth.CallingConvention & MethodCallingConvention.StdCall) != 0)
methSig.CallingConvention |= 0x2;
else if ((meth.CallingConvention & MethodCallingConvention.ThisCall) != 0)
methSig.CallingConvention |= 0x3;
else if ((meth.CallingConvention & MethodCallingConvention.FastCall) != 0)
methSig.CallingConvention |= 0x4;
return methSig;
}
public MethodDefSig GetMethodDefSig (IMethodSignature meth)
{
MethodDefSig sig = new MethodDefSig ();
CompleteMethodSig (meth, sig);
MethodReference methodRef = meth as MethodReference;
if (methodRef != null && methodRef.GenericParameters.Count > 0) {
sig.CallingConvention |= 0x10;
sig.GenericParameterCount = methodRef.GenericParameters.Count;
}
return sig;
}
public PropertySig GetPropertySig (PropertyDefinition prop)
{
PropertySig ps = new PropertySig ();
ps.CallingConvention |= 0x8;
bool hasThis;
bool explicitThis;
MethodCallingConvention mcc;
ParameterDefinitionCollection parameters = prop.Parameters;
MethodDefinition meth;
if (prop.GetMethod != null)
meth = prop.GetMethod;
else if (prop.SetMethod != null)
meth = prop.SetMethod;
else
meth = null;
if (meth != null) {
hasThis = meth.HasThis;
explicitThis = meth.ExplicitThis;
mcc = meth.CallingConvention;
} else {
hasThis = explicitThis = false;
mcc = MethodCallingConvention.Default;
}
if (hasThis)
ps.CallingConvention |= 0x20;
if (explicitThis)
ps.CallingConvention |= 0x40;
if ((mcc & MethodCallingConvention.VarArg) != 0)
ps.CallingConvention |= 0x5;
int paramCount = parameters != null ? parameters.Count : 0;
ps.ParamCount = paramCount;
ps.Parameters = GetParametersSig (parameters);
ps.CustomMods = GetCustomMods (prop.PropertyType);
ps.Type = GetSigType (prop.PropertyType);
return ps;
}
public TypeSpec GetTypeSpecSig (TypeReference type)
{
TypeSpec ts = new TypeSpec ();
ts.CustomMods = GetCustomMods (type);
ts.Type = GetSigType (type);
return ts;
}
public MethodSpec GetMethodSpecSig (GenericInstanceMethod gim)
{
GenericInstSignature gis = new GenericInstSignature ();
gis.Arity = gim.GenericArguments.Count;
gis.Types = new GenericArg [gis.Arity];
for (int i = 0; i < gis.Arity; i++)
gis.Types [i] = GetGenericArgSig (gim.GenericArguments [i]);
return new MethodSpec (gis);
}
static string GetObjectTypeName (object o)
{
Type t = o.GetType ();
return string.Concat (t.Namespace, ".", t.Name);
}
static CustomAttrib.Elem CreateElem (TypeReference type, object value)
{
CustomAttrib.Elem elem = new CustomAttrib.Elem ();
elem.Value = value;
elem.ElemType = type;
elem.FieldOrPropType = GetCorrespondingType (type.FullName);
switch (elem.FieldOrPropType) {
case ElementType.Boolean :
case ElementType.Char :
case ElementType.R4 :
case ElementType.R8 :
case ElementType.I1 :
case ElementType.I2 :
case ElementType.I4 :
case ElementType.I8 :
case ElementType.U1 :
case ElementType.U2 :
case ElementType.U4 :
case ElementType.U8 :
elem.Simple = true;
break;
case ElementType.String:
elem.String = true;
break;
case ElementType.Type:
elem.Type = true;
break;
case ElementType.Object:
elem.BoxedValueType = true;
if (value == null)
elem.FieldOrPropType = ElementType.String;
else
elem.FieldOrPropType = GetCorrespondingType (
GetObjectTypeName (value));
break;
}
return elem;
}
static CustomAttrib.FixedArg CreateFixedArg (TypeReference type, object value)
{
CustomAttrib.FixedArg fa = new CustomAttrib.FixedArg ();
if (value is object []) {
fa.SzArray = true;
object [] values = value as object [];
TypeReference obj = ((ArrayType) type).ElementType;
fa.NumElem = (uint) values.Length;
fa.Elems = new CustomAttrib.Elem [values.Length];
for (int i = 0; i < values.Length; i++)
fa.Elems [i] = CreateElem (obj, values [i]);
} else {
fa.Elems = new CustomAttrib.Elem [1];
fa.Elems [0] = CreateElem (type, value);
}
return fa;
}
static CustomAttrib.NamedArg CreateNamedArg (TypeReference type, string name,
object value, bool field)
{
CustomAttrib.NamedArg na = new CustomAttrib.NamedArg ();
na.Field = field;
na.Property = !field;
na.FieldOrPropName = name;
na.FieldOrPropType = GetCorrespondingType (type.FullName);
na.FixedArg = CreateFixedArg (type, value);
return na;
}
public static CustomAttrib GetCustomAttributeSig (CustomAttribute ca)
{
CustomAttrib cas = new CustomAttrib (ca.Constructor);
cas.Prolog = CustomAttrib.StdProlog;
cas.FixedArgs = new CustomAttrib.FixedArg [ca.Constructor.Parameters.Count];
for (int i = 0; i < cas.FixedArgs.Length; i++)
cas.FixedArgs [i] = CreateFixedArg (
ca.Constructor.Parameters [i].ParameterType, ca.ConstructorParameters [i]);
int nn = ca.Fields.Count + ca.Properties.Count;
cas.NumNamed = (ushort) nn;
cas.NamedArgs = new CustomAttrib.NamedArg [nn];
if (cas.NamedArgs.Length > 0) {
int curs = 0;
foreach (DictionaryEntry entry in ca.Fields) {
string field = (string) entry.Key;
cas.NamedArgs [curs++] = CreateNamedArg (
ca.GetFieldType (field), field, entry.Value, true);
}
foreach (DictionaryEntry entry in ca.Properties) {
string property = (string) entry.Key;
cas.NamedArgs [curs++] = CreateNamedArg (
ca.GetPropertyType (property), property, entry.Value, false);
}
}
return cas;
}
static MarshalSig GetMarshalSig (MarshalSpec mSpec)
{
MarshalSig ms = new MarshalSig (mSpec.NativeIntrinsic);
if (mSpec is ArrayMarshalSpec) {
ArrayMarshalSpec amd = mSpec as ArrayMarshalSpec;
MarshalSig.Array ar = new MarshalSig.Array ();
ar.ArrayElemType = amd.ElemType;
ar.NumElem = amd.NumElem;
ar.ParamNum = amd.ParamNum;
ar.ElemMult = amd.ElemMult;
ms.Spec = ar;
} else if (mSpec is CustomMarshalerSpec) {
CustomMarshalerSpec cmd = mSpec as CustomMarshalerSpec;
MarshalSig.CustomMarshaler cm = new MarshalSig.CustomMarshaler ();
cm.Guid = cmd.Guid.ToString ();
cm.UnmanagedType = cmd.UnmanagedType;
cm.ManagedType = cmd.ManagedType;
cm.Cookie = cmd.Cookie;
ms.Spec = cm;
} else if (mSpec is FixedArraySpec) {
FixedArraySpec fad = mSpec as FixedArraySpec;
MarshalSig.FixedArray fa = new MarshalSig.FixedArray ();
fa.ArrayElemType = fad.ElemType;
fa.NumElem = fad.NumElem;
ms.Spec = fa;
} else if (mSpec is FixedSysStringSpec) {
MarshalSig.FixedSysString fss = new MarshalSig.FixedSysString ();
fss.Size = (mSpec as FixedSysStringSpec).Size;
ms.Spec = fss;
} else if (mSpec is SafeArraySpec) {
MarshalSig.SafeArray sa = new MarshalSig.SafeArray ();
sa.ArrayElemType = (mSpec as SafeArraySpec).ElemType;
ms.Spec = sa;
}
return ms;
}
public void WriteSymbols (ModuleDefinition module)
{
if (!m_saveSymbols)
return;
if (m_asmOutput == null)
m_asmOutput = module.Assembly.Name.Name + "." + (module.Assembly.Kind == AssemblyKind.Dll ? "dll" : "exe");
if (m_symbolWriter == null)
m_symbolWriter = SymbolStoreHelper.GetWriter (module, m_asmOutput);
foreach (TypeDefinition type in module.Types) {
foreach (MethodDefinition method in type.Methods)
WriteSymbols (method);
foreach (MethodDefinition ctor in type.Constructors)
WriteSymbols (ctor);
}
m_symbolWriter.Dispose ();
}
void WriteSymbols (MethodDefinition meth)
{
if (!meth.HasBody)
return;
m_symbolWriter.Write (meth.Body, GetVariablesSig (meth));
}
byte [][] GetVariablesSig (MethodDefinition meth)
{
VariableDefinitionCollection variables = meth.Body.Variables;
byte [][] signatures = new byte [variables.Count][];
for (int i = 0; i < variables.Count; i++) {
signatures [i] = GetVariableSig (variables [i]);
}
return signatures;
}
byte [] GetVariableSig (VariableDefinition var)
{
return m_sigWriter.CompressLocalVar (m_codeWriter.GetLocalVariableSig (var));
}
}
}
| |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;
using BasecampAPI;
namespace Scout
{
public partial class ToDoListControl : Panel
{
public ToDoListControl()
{
InitializeComponent();
AutoScroll = true;
BackColor = Color.White;
ControlRemoved += new ControlEventHandler(ToDoListControl_ControlRemoved);
Margin = new Padding(0);
}
public event EventHandler<ToDoListEventArgs> ItemEdit;
void ToDoListControl_ControlRemoved(object sender, ControlEventArgs e)
{
ToDoItemControl todo = sender as ToDoItemControl;
if (todo != null && !todo.IsDisposed && todo.ToDoItem != null)
{
ListenToItem(todo.ToDoItem, false);
}
}
ToDoList list;
ComboBox comboList;
List<Person> people;
public void SetPeople(List<Person> people)
{
this.people = people;
}
string personToFindID;
bool FindPerson(Person p)
{
return p.ID == personToFindID;
}
Dictionary<ToDoItem, ToDoItemControl> controlsByItem = new Dictionary<ToDoItem, ToDoItemControl>();
public void SetList(ToDoList list)
{
ListenToList(false);
this.list = list;
ListenToList(true);
Fill();
}
public void SetListCombo(ComboBox comboList)
{
ListenToCombo(false);
this.comboList = comboList;
ListenToCombo(true);
if (comboList != null)
{
ToDoList list = comboList.SelectedItem as ToDoList;
SetList(list);
}
}
private void ListenToCombo(bool listen)
{
if (comboList == null) return;
if (listen)
comboList.SelectedIndexChanged += new EventHandler(comboList_SelectedIndexChanged);
else
comboList.SelectedIndexChanged -= new EventHandler(comboList_SelectedIndexChanged);
}
void comboList_SelectedIndexChanged(object sender, EventArgs e)
{
ToDoList list = comboList.SelectedItem as ToDoList;
SetList(list);
}
private void Add(ToDoItem item)
{
ToDoItemControl c = new ToDoItemControl();
c.Size = new Size(1, 30);
c.ToDoItem = item;
c.Font = Font;
c.Location = new Point(0, Controls.Count * 30);
c.Width = (int)((double)ClientSize.Width * 0.9);
c.Margin = new Padding(0);
c.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
if (people != null)
{
personToFindID = item.PersonID;
c.Person = people.Find(FindPerson);
}
c.Editing += new EventHandler(c_Editing);
ListenToItem(item, true);
Controls.Add(c);
controlsByItem[item] = c;
}
void c_Editing(object sender, EventArgs e)
{
if (ItemEdit != null)
ItemEdit(this, new ToDoListEventArgs((sender as ToDoItemControl).ToDoItem));
}
private void Fill()
{
try
{
Cursor = Cursors.WaitCursor;
DisposeInternals();
Controls.Clear();
controlsByItem.Clear();
if (list != null)
list.GetItems().ForEach(Add);
}
finally
{
Cursor = Cursors.Default;
Refresh();
}
}
private void DisposeInternals()
{
foreach (Control c in Controls)
{
ToDoItemControl todo = c as ToDoItemControl;
if (todo != null)
{
todo.Editing -= new EventHandler(c_Editing);
ListenToItem(todo.ToDoItem, false);
}
//c.Dispose();
}
}
private void ListenToList(bool listen)
{
if (list == null) return;
if (listen)
list.Changed += new EventHandler(list_Changed);
else
list.Changed -= new EventHandler(list_Changed);
}
void list_Changed(object sender, EventArgs e)
{
Fill();
}
private void ListenToItem(ToDoItem item, bool listen)
{
if (item == null) return;
if (listen)
{
item.PositionChanged += new EventHandler(item_PositionChanged);
item.PersonChanged += new EventHandler(item_PersonChanged);
item.CompletedChanged += new EventHandler(item_CompletedChanged);
}
else
{
item.PositionChanged -= new EventHandler(item_PositionChanged);
item.PersonChanged += new EventHandler(item_PositionChanged);
item.CompletedChanged -= new EventHandler(item_CompletedChanged);
}
}
void item_CompletedChanged(object sender, EventArgs e)
{
Fill();
}
void item_PersonChanged(object sender, EventArgs e)
{
if (people != null)
{
ToDoItem item = sender as ToDoItem;
personToFindID = item.PersonID;
if (controlsByItem.ContainsKey(item))
controlsByItem[item].Person= people.Find(FindPerson);
}
}
void item_PositionChanged(object sender, EventArgs e)
{
Fill();
}
}
public class ToDoListEventArgs : EventArgs
{
public ToDoListEventArgs(ToDoItem item)
{
Item = item;
}
public readonly ToDoItem Item;
}
}
| |
#region -- License Terms --
//
// MessagePack for CLI
//
// Copyright (C) 2010-2015 FUJIWARA, Yusuke
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#endregion -- License Terms --
#if UNITY_STANDALONE || UNITY_WEBPLAYER || UNITY_WII || UNITY_IPHONE || UNITY_ANDROID || UNITY_PS3 || UNITY_XBOX360 || UNITY_FLASH || UNITY_BKACKBERRY || UNITY_WINRT
#define UNITY
#endif
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
#if !UNITY
#if XAMIOS || XAMDROID
using Contract = MsgPack.MPContract;
#else
using System.Diagnostics.Contracts;
#endif // XAMIOS || XAMDROID
#endif // !UNITY
using System.Globalization;
using System.Linq;
namespace MsgPack
{
/// <summary>
/// Implements <see cref="IDictionary{TKey,TValue}"/> for <see cref="MessagePackObject"/>.
/// </summary>
/// <remarks>
/// This dictionary handles <see cref="MessagePackObject"/> type semantics for the key.
/// Additionally, this dictionary implements 'freezing' feature.
/// For details, see <see cref="IsFrozen"/>, <see cref="Freeze"/>, and <see cref="AsFrozen"/>.
/// </remarks>
#if !SILVERLIGHT && !NETFX_CORE
[Serializable]
#endif
[DebuggerTypeProxy( typeof( DictionaryDebuggerProxy<,> ) )]
public partial class MessagePackObjectDictionary :
IDictionary<MessagePackObject, MessagePackObject>, IDictionary
{
private const int Threashold = 10;
private const int ListInitialCapacity = Threashold;
private const int DictionaryInitialCapacity = Threashold * 2;
private List<MessagePackObject> _keys;
private List<MessagePackObject> _values;
private Dictionary<MessagePackObject, MessagePackObject> _dictionary;
private int _version;
private bool _isFrozen;
/// <summary>
/// Gets a value indicating whether this instance is frozen.
/// </summary>
/// <value>
/// <c>true</c> if this instance is frozen; otherwise, <c>false</c>.
/// </value>
/// <remarks>
/// This operation is an O(1) operation.
/// </remarks>
public bool IsFrozen
{
get { return this._isFrozen; }
}
/// <summary>
/// Gets the number of elements contained in the <see cref="MessagePackObjectDictionary"/>.
/// </summary>
/// <returns>
/// The number of elements contained in the <see cref="MessagePackObjectDictionary"/>.
/// </returns>
/// <remarks>
/// This operation is an O(1) operation.
/// </remarks>
public int Count
{
get
{
#if !UNITY
this.AssertInvariant();
#endif // !UNITY
return this._dictionary == null ? this._keys.Count : this._dictionary.Count;
}
}
/// <summary>
/// Gets or sets the element with the specified key.
/// </summary>
/// <value>
/// The element with the specified key.
/// </value>
/// <param name="key">Key for geting or seting value.</param>
/// <exception cref="ArgumentNullException">
/// <paramref name="key"/> is <see cref="MessagePackObject.Nil"/>.
/// </exception>
/// <exception cref="T:System.Collections.Generic.KeyNotFoundException">
/// The property is retrieved and <paramref name="key"/> is not found.
/// </exception>
/// <exception cref="InvalidOperationException">
/// The property is set and this instance is frozen.
/// </exception>
/// <remarks>
/// <para>
/// Note that tiny integers are considered equal regardless of its CLI <see cref="Type"/>,
/// and UTF-8 encoded bytes are considered equals to <see cref="String"/>.
/// </para>
/// <para>
/// This method approaches an O(1) operation.
/// </para>
/// </remarks>
public MessagePackObject this[ MessagePackObject key ]
{
get
{
if ( key.IsNil )
{
ThrowKeyNotNilException( "key" );
}
#if !UNITY
Contract.EndContractBlock();
#endif // !UNITY
MessagePackObject result;
if ( !this.TryGetValue( key, out result ) )
{
throw new KeyNotFoundException( String.Format( CultureInfo.CurrentCulture, "Key '{0}'({1} type) does not exist in this dictionary.", key, key.UnderlyingType ) );
}
return result;
}
set
{
if ( key.IsNil )
{
ThrowKeyNotNilException( "key" );
}
this.VerifyIsNotFrozen();
#if !UNITY
Contract.EndContractBlock();
this.AssertInvariant();
#endif // !UNITY
this.AddCore( key, value, true );
}
}
#if !UNITY
/// <summary>
/// Gets an <see cref="KeySet"/> containing the keys of the <see cref="MessagePackObjectDictionary"/>.
/// </summary>
/// <returns>
/// An <see cref="KeySet"/> containing the keys of the object.
/// This value will not be <c>null</c>.
/// </returns>
/// <remarks>
/// This operation is an O(1) operation.
/// </remarks>
public KeySet Keys
{
get
{
this.AssertInvariant();
return new KeySet( this );
}
}
#else
/// <summary>
/// Gets an <see cref="KeyCollection"/> containing the keys of the <see cref="MessagePackObjectDictionary"/>.
/// </summary>
/// <returns>
/// An <see cref="KeyCollection"/> containing the keys of the object.
/// This value will not be <c>null</c>.
/// </returns>
/// <remarks>
/// This operation is an O(1) operation.
/// </remarks>
public KeyCollection Keys
{
get
{
#if !UNITY
this.AssertInvariant();
#endif // !UNITY
return new KeyCollection( this );
}
}
#endif // !UNITY
/// <summary>
/// Gets an <see cref="ValueCollection"/> containing the values of the <see cref="MessagePackObjectDictionary"/>.
/// </summary>
/// <returns>
/// An <see cref="ValueCollection"/> containing the values of the object.
/// This value will not be <c>null</c>.
/// </returns>
/// <remarks>
/// This operation is an O(1) operation.
/// </remarks>
public ValueCollection Values
{
get
{
#if !UNITY
this.AssertInvariant();
#endif // !UNITY
return new ValueCollection( this );
}
}
ICollection<MessagePackObject> IDictionary<MessagePackObject, MessagePackObject>.Keys
{
get { return this.Keys; }
}
ICollection<MessagePackObject> IDictionary<MessagePackObject, MessagePackObject>.Values
{
get { return this.Values; }
}
[SuppressMessage( "Microsoft.Design", "CA1033:InterfaceMethodsShouldBeCallableByChildTypes", Justification = "Child types should never call this property." )]
bool ICollection<KeyValuePair<MessagePackObject, MessagePackObject>>.IsReadOnly
{
get { return this.IsFrozen; }
}
[SuppressMessage( "Microsoft.Design", "CA1033:InterfaceMethodsShouldBeCallableByChildTypes", Justification = "Child types should never call this property." )]
bool IDictionary.IsFixedSize
{
get { return this.IsFrozen; }
}
[SuppressMessage( "Microsoft.Design", "CA1033:InterfaceMethodsShouldBeCallableByChildTypes", Justification = "Child types should never call this property." )]
bool IDictionary.IsReadOnly
{
get { return this.IsFrozen; }
}
ICollection IDictionary.Keys
{
get { return this._keys; }
}
ICollection IDictionary.Values
{
get { return this.Values; }
}
[SuppressMessage( "Microsoft.Design", "CA1033:InterfaceMethodsShouldBeCallableByChildTypes", Justification = "Child types should never call this property." )]
object IDictionary.this[ object key ]
{
get
{
if ( key == null )
{
throw new ArgumentNullException( "key" );
}
#if !UNITY
Contract.EndContractBlock();
#endif // !UNITY
var typedKey = ValidateObjectArgument( key, "key" );
if ( typedKey.IsNil )
{
ThrowKeyNotNilException( "key" );
}
MessagePackObject value;
if ( !this.TryGetValue( typedKey, out value ) )
{
return null;
}
return value;
}
set
{
if ( key == null )
{
throw new ArgumentNullException( "key" );
}
this.VerifyIsNotFrozen();
#if !UNITY
Contract.EndContractBlock();
#endif // !UNITY
var typedKey = ValidateObjectArgument( key, "key" );
if ( typedKey.IsNil )
{
ThrowKeyNotNilException( "key" );
}
this[ typedKey ] = ValidateObjectArgument( value, "value" );
}
}
[SuppressMessage( "Microsoft.Design", "CA1033:InterfaceMethodsShouldBeCallableByChildTypes", Justification = "Child types should never call this property." )]
bool ICollection.IsSynchronized
{
get { return false; }
}
[SuppressMessage( "Microsoft.Design", "CA1033:InterfaceMethodsShouldBeCallableByChildTypes", Justification = "Child types should never call this property." )]
object ICollection.SyncRoot
{
get { return this; }
}
/// <summary>
/// Initializes an empty new instance of the <see cref="MessagePackObjectDictionary"/> class with default capacity.
/// </summary>
/// <remarks>
/// This operation is an O(1) operation.
/// </remarks>
public MessagePackObjectDictionary()
{
this._keys = new List<MessagePackObject>( ListInitialCapacity );
this._values = new List<MessagePackObject>( ListInitialCapacity );
}
/// <summary>
/// Initializes an empty new instance of the <see cref="MessagePackObjectDictionary"/> class with specified initial capacity.
/// </summary>
/// <param name="initialCapacity">The initial capacity.</param>
/// <exception cref="ArgumentOutOfRangeException">
/// <paramref name="initialCapacity"/> is negative.
/// </exception>
/// <remarks>
/// This operation is an O(1) operation.
/// </remarks>
public MessagePackObjectDictionary( int initialCapacity )
{
if ( initialCapacity < 0 )
{
throw new ArgumentOutOfRangeException( "initialCapacity" );
}
#if !UNITY
Contract.EndContractBlock();
#endif // !UNITY
if ( initialCapacity <= Threashold )
{
this._keys = new List<MessagePackObject>( initialCapacity );
this._values = new List<MessagePackObject>( initialCapacity );
}
else
{
this._dictionary = new Dictionary<MessagePackObject, MessagePackObject>( initialCapacity, MessagePackObjectEqualityComparer.Instance );
}
}
/// <summary>
/// Initializes a new instance of the <see cref="MessagePackObjectDictionary"/> class.
/// </summary>
/// <param name="dictionary">The dictionary to be copied from.</param>
/// <exception cref="ArgumentNullException">
/// <paramref name="dictionary"/> is <c>null</c>.
/// </exception>
/// <exception cref="ArgumentException">
/// Failed to copy from <paramref name="dictionary"/>.
/// </exception>
/// <remarks>
/// This constructor takes <em>O(N)</em> time, <em>N</em> is <see cref="P:ICollection{T}.Count"/> of <paramref name="dictionary"/>.
/// Initial capacity will be <see cref="P:ICollection{T}.Count"/> of <paramref name="dictionary"/>.
/// </remarks>
public MessagePackObjectDictionary( IDictionary<MessagePackObject, MessagePackObject> dictionary )
{
if ( dictionary == null )
{
throw new ArgumentNullException( "dictionary" );
}
#if !UNITY
Contract.EndContractBlock();
#endif // !UNITY
if ( dictionary.Count <= Threashold )
{
this._keys = new List<MessagePackObject>( dictionary.Count );
this._values = new List<MessagePackObject>( dictionary.Count );
}
else
{
this._dictionary = new Dictionary<MessagePackObject, MessagePackObject>( dictionary.Count, MessagePackObjectEqualityComparer.Instance );
}
try
{
foreach ( var kv in dictionary )
{
this.AddCore( kv.Key, kv.Value, false );
}
}
catch ( ArgumentException ex )
{
#if SILVERLIGHT
throw new ArgumentException( "Failed to copy specified dictionary.", ex );
#else
throw new ArgumentException( "Failed to copy specified dictionary.", "dictionary", ex );
#endif
}
}
private static void ThrowKeyNotNilException( string parameterName )
{
throw new ArgumentNullException( parameterName, "Key cannot be nil." );
}
private static void ThrowDuplicatedKeyException( MessagePackObject key, string parameterName )
{
throw new ArgumentException( String.Format( CultureInfo.CurrentCulture, "Key '{0}'({1} type) already exists in this dictionary.", key, key.UnderlyingType ), parameterName );
}
private void VerifyIsNotFrozen()
{
if ( this._isFrozen )
{
throw new InvalidOperationException( "This dictionary is frozen." );
}
}
#if !UNITY
[Conditional( "DEBUG" )]
private void AssertInvariant()
{
if ( this._dictionary == null )
{
Contract.Assert( this._keys != null, "this._keys != null" );
Contract.Assert( this._values != null, "this._values != null" );
Contract.Assert( this._keys.Count == this._values.Count, "this._keys.Count == this._values.Count" );
Contract.Assert(
this._keys.Distinct( MessagePackObjectEqualityComparer.Instance ).Count() == this._keys.Count,
"this._keys.Distinct( MessagePackObjectEqualityComparer.Instance ).Count() == this._keys.Count"
);
}
else
{
Contract.Assert( this._keys == null, "this._keys == null" );
Contract.Assert( this._values == null, "this._values == null" );
}
}
#endif // !UNITY
private static MessagePackObject ValidateObjectArgument( object obj, string parameterName )
{
var result = TryValidateObjectArgument( obj );
if ( result == null )
{
throw new ArgumentException( String.Format( CultureInfo.CurrentCulture, "Cannot convert '{1}' to {0}.", typeof( MessagePackObject ).Name, obj.GetType() ), parameterName );
}
return result.Value;
}
private static MessagePackObject? TryValidateObjectArgument( object value )
{
if ( value == null )
{
return MessagePackObject.Nil;
}
if ( value is MessagePackObject )
{
return ( MessagePackObject )value;
}
byte[] asBytes;
if ( ( asBytes = value as byte[] ) != null )
{
return asBytes;
}
string asString;
if ( ( asString = value as string ) != null )
{
return asString;
}
MessagePackString asMessagePackString;
if ( ( asMessagePackString = value as MessagePackString ) != null )
{
return new MessagePackObject( asMessagePackString );
}
#if NETFX_CORE
switch ( WinRTCompatibility.GetTypeCode( value.GetType() ) )
#else
switch ( Type.GetTypeCode( value.GetType() ) )
#endif // NETFX_CORE
{
case TypeCode.Boolean:
{
return ( bool )value;
}
case TypeCode.Byte:
{
return ( byte )value;
}
case TypeCode.DateTime:
{
return MessagePackConvert.FromDateTime( ( DateTime )value );
}
case TypeCode.DBNull:
case TypeCode.Empty:
{
return MessagePackObject.Nil;
}
case TypeCode.Double:
{
return ( double )value;
}
case TypeCode.Int16:
{
return ( short )value;
}
case TypeCode.Int32:
{
return ( int )value;
}
case TypeCode.Int64:
{
return ( long )value;
}
case TypeCode.SByte:
{
return ( sbyte )value;
}
case TypeCode.Single:
{
return ( float )value;
}
case TypeCode.String:
{
return value.ToString();
}
case TypeCode.UInt16:
{
return ( ushort )value;
}
case TypeCode.UInt32:
{
return ( uint )value;
}
case TypeCode.UInt64:
{
return ( ulong )value;
}
// ReSharper disable RedundantCaseLabel
case TypeCode.Char:
case TypeCode.Decimal:
case TypeCode.Object:
// ReSharper restore RedundantCaseLabel
default:
{
return null;
}
}
}
/// <summary>
/// Determines whether the <see cref="MessagePackObjectDictionary"/> contains an element with the specified key.
/// </summary>
/// <param name="key">The key to locate in the <see cref="MessagePackObjectDictionary"/>.</param>
/// <exception cref="ArgumentNullException">
/// <paramref name="key"/> is <see cref="MessagePackObject.Nil"/>.
/// </exception>
/// <returns>
/// <c>true</c> if the <see cref="MessagePackObjectDictionary"/> contains an element with the key; otherwise, <c>false</c>.
/// </returns>
/// <remarks>
/// This method approaches an O(1) operation.
/// </remarks>
public bool ContainsKey( MessagePackObject key )
{
if ( key.IsNil )
{
ThrowKeyNotNilException( "key" );
}
#if !UNITY
Contract.EndContractBlock();
#endif // !UNITY
#if !UNITY
this.AssertInvariant();
#endif // !UNITY
return
this._dictionary == null
? this._keys.Contains( key, MessagePackObjectEqualityComparer.Instance )
: this._dictionary.ContainsKey( key );
}
/// <summary>
/// Determines whether the <see cref="MessagePackObjectDictionary"/> contains an element with the specified value.
/// </summary>
/// <param name="value">The value to locate in the <see cref="MessagePackObjectDictionary"/>.</param>
/// <returns>
/// <c>true</c> if the <see cref="MessagePackObjectDictionary"/> contains an element with the value; otherwise, <c>false</c>.
/// </returns>
/// <remarks>
/// This method approaches an O(<em>N</em>) operation where <em>N</em> is <see cref="Count"/>.
/// </remarks>
public bool ContainsValue( MessagePackObject value )
{
#if !UNITY
this.AssertInvariant();
#endif // !UNITY
return
this._dictionary == null
? this._values.Contains( value, MessagePackObjectEqualityComparer.Instance )
#if !UNITY
: this._dictionary.ContainsValue( value );
#else
: this._dictionary.Values.Contains( value, MessagePackObjectEqualityComparer.Instance );
#endif // !UNITY
}
[SuppressMessage( "Microsoft.Design", "CA1033:InterfaceMethodsShouldBeCallableByChildTypes", Justification = "Child types should never call this property." )]
bool ICollection<KeyValuePair<MessagePackObject, MessagePackObject>>.Contains( KeyValuePair<MessagePackObject, MessagePackObject> item )
{
MessagePackObject value;
if ( !this.TryGetValue( item.Key, out value ) )
{
return false;
}
return item.Value == value;
}
[SuppressMessage( "Microsoft.Design", "CA1033:InterfaceMethodsShouldBeCallableByChildTypes", Justification = "Child types should never call this property." )]
bool IDictionary.Contains( object key )
{
// ReSharper disable HeuristicUnreachableCode
// ReSharper disable once ConditionIsAlwaysTrueOrFalse
if ( key == null )
{
return false;
}
// ReSharper restore HeuristicUnreachableCode
var typedKey = TryValidateObjectArgument( key );
if ( typedKey.GetValueOrDefault().IsNil )
{
return false;
}
{
return this.ContainsKey( typedKey.GetValueOrDefault() );
}
}
/// <summary>
/// Gets the value associated with the specified key.
/// </summary>
/// <param name="key">
/// The key whose value to get.
/// </param>
/// <param name="value">
/// When this method returns, the value associated with the specified key, if the key is found;
/// otherwise, the default value for the type of the <paramref name="value"/> parameter.
/// This parameter is passed uninitialized.
/// </param>
/// <returns>
/// <c>true</c> if this dictionary contains an element with the specified key; otherwise, <c>false</c>.
/// </returns>
/// <exception cref="ArgumentNullException">
/// <paramref name="key"/> is <see cref="MessagePackObject.Nil"/>.
/// </exception>
/// <remarks>
/// <para>
/// Note that tiny integers are considered equal regardless of its CLI <see cref="Type"/>,
/// and UTF-8 encoded bytes are considered equals to <see cref="String"/>.
/// </para>
/// <para>
/// This method approaches an O(1) operation.
/// </para>
/// </remarks>
public bool TryGetValue( MessagePackObject key, out MessagePackObject value )
{
if ( key.IsNil )
{
ThrowKeyNotNilException( "key" );
}
#if !UNITY
Contract.EndContractBlock();
this.AssertInvariant();
#endif // !UNITY
if ( this._dictionary == null )
{
int index = this._keys.FindIndex( item => item == key );
if ( index < 0 )
{
value = MessagePackObject.Nil;
return false;
}
else
{
value = this._values[ index ];
return true;
}
}
else
{
return this._dictionary.TryGetValue( key, out value );
}
}
/// <summary>
/// Adds the specified key and value to the dictionary.
/// </summary>
/// <param name="key">
/// The key of the element to add.
/// </param>
/// <param name="value">
/// The value of the element to add. The value can be <c>null</c> for reference types.
/// </param>
/// <returns>
/// An element with the same key already does not exist in the dictionary and sucess to add then newly added node;
/// otherwise <c>null</c>.
/// </returns>
/// <exception cref="ArgumentException">
/// <paramref name="key"/> already exists in this dictionary.
/// Note that tiny integers are considered equal regardless of its CLI <see cref="Type"/>,
/// and UTF-8 encoded bytes are considered equals to <see cref="String"/>.
/// </exception>
/// <exception cref="ArgumentNullException">
/// <paramref name="key"/> is <see cref="MessagePackObject.Nil"/>.
/// </exception>
/// <remarks>
/// If <see cref="Count"/> is less than the capacity, this method approaches an O(1) operation.
/// If the capacity must be increased to accommodate the new element,
/// this method becomes an O(<em>N</em>) operation, where <em>N</em> is <see cref="Count"/>.
/// </remarks>
public void Add( MessagePackObject key, MessagePackObject value )
{
if ( key.IsNil )
{
ThrowKeyNotNilException( "key" );
}
this.VerifyIsNotFrozen();
#if !UNITY
Contract.EndContractBlock();
#endif // !UNITY
this.AddCore( key, value, false );
}
private void AddCore( MessagePackObject key, MessagePackObject value, bool allowOverwrite )
{
#if !UNITY
Contract.Assert( !key.IsNil, "!key.IsNil" );
#endif // !UNITY
if ( this._dictionary == null )
{
if ( this._keys.Count < Threashold )
{
int index = this._keys.FindIndex( item => item == key );
if ( index < 0 )
{
this._keys.Add( key );
this._values.Add( value );
}
else
{
if ( !allowOverwrite )
{
ThrowDuplicatedKeyException( key, "key" );
}
this._values[ index ] = value;
}
unchecked
{
this._version++;
}
return;
}
if ( this._keys.Count == Threashold && allowOverwrite )
{
int index = this._keys.FindIndex( item => item == key );
if ( 0 <= index )
{
this._values[ index ] = value;
unchecked
{
this._version++;
}
return;
}
}
// Swith to hashtable base
this._dictionary = new Dictionary<MessagePackObject, MessagePackObject>( DictionaryInitialCapacity, MessagePackObjectEqualityComparer.Instance );
for ( int i = 0; i < this._keys.Count; i++ )
{
this._dictionary.Add( this._keys[ i ], this._values[ i ] );
}
this._keys = null;
this._values = null;
}
if ( allowOverwrite )
{
this._dictionary[ key ] = value;
}
else
{
try
{
this._dictionary.Add( key, value );
}
catch ( ArgumentException )
{
ThrowDuplicatedKeyException( key, "key" );
}
}
unchecked
{
this._version++;
}
}
void ICollection<KeyValuePair<MessagePackObject, MessagePackObject>>.Add( KeyValuePair<MessagePackObject, MessagePackObject> item )
{
if ( item.Key.IsNil )
{
ThrowKeyNotNilException( "key" );
}
this.VerifyIsNotFrozen();
#if !UNITY
Contract.EndContractBlock();
#endif // !UNITY
this.AddCore( item.Key, item.Value, false );
}
void IDictionary.Add( object key, object value )
{
if ( key == null )
{
throw new ArgumentNullException( "key" );
}
this.VerifyIsNotFrozen();
#if !UNITY
Contract.EndContractBlock();
#endif // !UNITY
var typedKey = ValidateObjectArgument( key, "key" );
if ( typedKey.IsNil )
{
ThrowKeyNotNilException( "key" );
}
this.AddCore( typedKey, ValidateObjectArgument( value, "value" ), false );
}
/// <summary>
/// Removes the element with the specified key from the <see cref="MessagePackObjectDictionary"/>.
/// </summary>
/// <param name="key">The key of the element to remove.</param>
/// <returns>
/// <c>true</c> if the element is successfully removed; otherwise, <c>false</c>.
/// This method also returns false if <paramref name="key"/> was not found in the original <see cref="MessagePackObjectDictionary"/>.
/// </returns>
/// <exception cref="ArgumentNullException">
/// <paramref name="key"/> is <see cref="MessagePackObject.Nil"/>.
/// </exception>
/// <remarks>
/// This method approaches an O(1) operation.
/// </remarks>
public bool Remove( MessagePackObject key )
{
if ( key.IsNil )
{
ThrowKeyNotNilException( "key" );
}
this.VerifyIsNotFrozen();
#if !UNITY
Contract.EndContractBlock();
#endif // !UNITY
return this.RemoveCore( key, default( MessagePackObject ), false );
}
private bool RemoveCore( MessagePackObject key, MessagePackObject value, bool checkValue )
{
#if !UNITY
Contract.Assert( !key.IsNil, "!key.IsNil" );
this.AssertInvariant();
#endif // !UNITY
if ( this._dictionary == null )
{
int index = this._keys.FindIndex( item => item == key );
if ( index < 0 )
{
return false;
}
if ( checkValue && this._values[ index ] != value )
{
return false;
}
this._keys.RemoveAt( index );
this._values.RemoveAt( index );
}
else
{
if ( checkValue )
{
if ( !( this._dictionary as ICollection<KeyValuePair<MessagePackObject, MessagePackObject>> ).Remove(
new KeyValuePair<MessagePackObject, MessagePackObject>( key, value ) ) )
{
return false;
}
}
else
{
if ( !this._dictionary.Remove( key ) )
{
return false;
}
}
}
unchecked
{
this._version++;
}
return true;
}
bool ICollection<KeyValuePair<MessagePackObject, MessagePackObject>>.Remove( KeyValuePair<MessagePackObject, MessagePackObject> item )
{
if ( item.Key.IsNil )
{
ThrowKeyNotNilException( "key" );
}
this.VerifyIsNotFrozen();
#if !UNITY
Contract.EndContractBlock();
#endif // !UNITY
return this.RemoveCore( item.Key, item.Value, true );
}
void IDictionary.Remove( object key )
{
if ( key == null )
{
throw new ArgumentNullException( "key" );
}
this.VerifyIsNotFrozen();
#if !UNITY
Contract.EndContractBlock();
#endif // !UNITY
var typedKey = ValidateObjectArgument( key, "key" );
if ( typedKey.IsNil )
{
ThrowKeyNotNilException( "key" );
}
this.RemoveCore( typedKey, default( MessagePackObject ), false );
}
/// <summary>
/// Removes all items from the <see cref="MessagePackObjectDictionary"/>.
/// </summary>
/// <remarks>
/// This method approaches an O(<em>N</em>) operation, where <em>N</em> is <see cref="Count"/>.
/// </remarks>
public void Clear()
{
this.VerifyIsNotFrozen();
#if !UNITY
this.AssertInvariant();
#endif // !UNITY
if ( this._dictionary == null )
{
this._keys.Clear();
this._values.Clear();
}
else
{
this._dictionary.Clear();
}
unchecked
{
this._version++;
}
}
[SuppressMessage( "Microsoft.Design", "CA1033:InterfaceMethodsShouldBeCallableByChildTypes", Justification = "Child types should never call this property." )]
void ICollection<KeyValuePair<MessagePackObject, MessagePackObject>>.CopyTo( KeyValuePair<MessagePackObject, MessagePackObject>[] array, int arrayIndex )
{
CollectionOperation.CopyTo( this, this.Count, 0, array, arrayIndex, this.Count );
}
[SuppressMessage( "Microsoft.Design", "CA1033:InterfaceMethodsShouldBeCallableByChildTypes", Justification = "Child types should never call this property." )]
void ICollection.CopyTo( Array array, int index )
{
DictionaryEntry[] asDictionaryEntries;
if ( ( asDictionaryEntries = array as DictionaryEntry[] ) != null )
{
CollectionOperation.CopyTo( this, this.Count, 0, asDictionaryEntries, index, array.Length, kv => new DictionaryEntry( kv.Key, kv.Value ) );
return;
}
CollectionOperation.CopyTo( this, this.Count, array, index );
}
/// <summary>
/// Returns an enumerator that iterates through the <see cref="MessagePackObjectDictionary"/>.
/// </summary>
/// <returns>
/// Returns an enumerator that iterates through the <see cref="MessagePackObjectDictionary"/>.
/// </returns>
/// <remarks>
/// This method is an O(1) operation.
/// </remarks>
public Enumerator GetEnumerator()
{
return new Enumerator( this );
}
IEnumerator<KeyValuePair<MessagePackObject, MessagePackObject>> IEnumerable<KeyValuePair<MessagePackObject, MessagePackObject>>.GetEnumerator()
{
return this.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return this.GetEnumerator();
}
IDictionaryEnumerator IDictionary.GetEnumerator()
{
// Avoid tricky casting error.
return new DictionaryEnumerator( this );
}
/// <summary>
/// Freezes this instance.
/// </summary>
/// <returns>
/// This instance itself.
/// This value will not be <c>null</c> and its <see cref="IsFrozen"/> is <c>true</c>.
/// </returns>
/// <remarks>
/// This method freezes this instance itself.
/// This operation is an O(1) operation.
/// </remarks>
public MessagePackObjectDictionary Freeze()
{
this._isFrozen = true;
return this;
}
/// <summary>
/// Gets a copy of this instance as frozen instance.
/// </summary>
/// <returns>
/// New <see cref="MessagePackObjectDictionary"/> instance which contains same items as this instance.
/// This value will not be <c>null</c> and its <see cref="IsFrozen"/> is <c>true</c>.
/// </returns>
/// <remarks>
/// This method does not freeze this instance itself.
/// This operation is an O(<em>N</em>) operation where <em>O(N)</em> <see cref="Count"/> of items.
/// </remarks>
public MessagePackObjectDictionary AsFrozen()
{
return new MessagePackObjectDictionary( this ).Freeze();
}
}
}
| |
#region MigraDoc - Creating Documents on the Fly
//
// Authors:
// Klaus Potzesny (mailto:Klaus.Potzesny@pdfsharp.com)
//
// Copyright (c) 2001-2009 empira Software GmbH, Cologne (Germany)
//
// http://www.pdfsharp.com
// http://www.migradoc.com
// http://sourceforge.net/projects/pdfsharp
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
#endregion
using System;
using System.IO;
using System.Diagnostics;
using MigraDoc.DocumentObjectModel;
using PdfSharp.Drawing;
using MigraDoc.DocumentObjectModel.Shapes;
using MigraDoc.Rendering.Resources;
namespace MigraDoc.Rendering
{
/// <summary>
/// Renders images.
/// </summary>
internal class ImageRenderer : ShapeRenderer
{
internal ImageRenderer(XGraphics gfx, Image image, FieldInfos fieldInfos)
: base(gfx, image, fieldInfos)
{
this.image = image;
ImageRenderInfo renderInfo = new ImageRenderInfo();
renderInfo.shape = this.shape;
this.renderInfo = renderInfo;
}
internal ImageRenderer(XGraphics gfx, RenderInfo renderInfo, FieldInfos fieldInfos)
: base(gfx, renderInfo, fieldInfos)
{
this.image = (Image)renderInfo.DocumentObject;
}
internal override void Format(Area area, FormatInfo previousFormatInfo)
{
if (!this.image.IsStreamBased)
{
this.imageFilePath = image.GetFilePath(this.documentRenderer.WorkingDirectory);
//if (!File.Exists(this.imageFilePath))
if (!XImage.ExistsFile(this.imageFilePath))
{
this.failure = ImageFailure.FileNotFound;
Trace.WriteLine(Messages.ImageNotFound(this.image.Name), "warning");
}
}
ImageFormatInfo formatInfo = (ImageFormatInfo)this.renderInfo.FormatInfo;
formatInfo.failure = this.failure;
formatInfo.ImagePath = this.imageFilePath;
CalculateImageDimensions();
base.Format(area, previousFormatInfo);
}
protected override XUnit ShapeHeight
{
get
{
ImageFormatInfo formatInfo = (ImageFormatInfo)this.renderInfo.FormatInfo;
return formatInfo.Height + this.lineFormatRenderer.GetWidth();
}
}
protected override XUnit ShapeWidth
{
get
{
ImageFormatInfo formatInfo = (ImageFormatInfo)this.renderInfo.FormatInfo;
return formatInfo.Width + this.lineFormatRenderer.GetWidth();
}
}
internal override void Render()
{
RenderFilling();
ImageFormatInfo formatInfo = (ImageFormatInfo)this.renderInfo.FormatInfo;
Area contentArea = this.renderInfo.LayoutInfo.ContentArea;
XRect destRect = new XRect(contentArea.X, contentArea.Y, formatInfo.Width, formatInfo.Height);
if (formatInfo.failure == ImageFailure.None)
{
XImage xImage = null;
try
{
XRect srcRect = new XRect(formatInfo.CropX, formatInfo.CropY, formatInfo.CropWidth, formatInfo.CropHeight);
xImage = image.IsStreamBased ? XImage.FromStream(image.ImageStream) : XImage.FromFile(formatInfo.ImagePath);
this.gfx.DrawImage(xImage, destRect, srcRect, XGraphicsUnit.Point); //Pixel.
}
catch (Exception)
{
RenderFailureImage(destRect);
}
finally
{
if (xImage != null)
xImage.Dispose();
}
}
else
RenderFailureImage(destRect);
RenderLine();
}
void RenderFailureImage(XRect destRect)
{
this.gfx.DrawRectangle(XBrushes.LightGray, destRect);
string failureString;
ImageFormatInfo formatInfo = (ImageFormatInfo)this.RenderInfo.FormatInfo;
switch (formatInfo.failure)
{
case ImageFailure.EmptySize:
failureString = Messages.DisplayEmptyImageSize;
break;
case ImageFailure.FileNotFound:
failureString = Messages.DisplayImageFileNotFound;
break;
case ImageFailure.InvalidType:
failureString = Messages.DisplayInvalidImageType;
break;
case ImageFailure.NotRead:
default:
failureString = Messages.DisplayImageNotRead;
break;
}
// Create stub font
XFont font = new XFont("Courier New", 8);
this.gfx.DrawString(failureString, font, XBrushes.Red, destRect, XStringFormats.Center);
}
private void CalculateImageDimensions()
{
ImageFormatInfo formatInfo = (ImageFormatInfo)this.renderInfo.FormatInfo;
if (formatInfo.failure == ImageFailure.None)
{
XImage xImage = null;
try
{
xImage = image.IsStreamBased ? XImage.FromStream(image.ImageStream) : XImage.FromFile(formatInfo.ImagePath);
}
catch (InvalidOperationException ex)
{
Trace.WriteLine(Messages.InvalidImageType(ex.Message));
formatInfo.failure = ImageFailure.InvalidType;
}
try
{
XUnit usrWidth = image.Width.Point;
XUnit usrHeight = image.Height.Point;
bool usrWidthSet = !this.image.IsNull("Width");
bool usrHeightSet = !this.image.IsNull("Height");
XUnit resultWidth = usrWidth;
XUnit resultHeight = usrHeight;
double xPixels = xImage.PixelWidth;
bool usrResolutionSet = !image.IsNull("Resolution");
double horzRes = usrResolutionSet ? (double)image.Resolution : xImage.HorizontalResolution;
XUnit inherentWidth = XUnit.FromInch(xPixels / horzRes);
double yPixels = xImage.PixelHeight;
double vertRes = usrResolutionSet ? (double)image.Resolution : xImage.VerticalResolution;
XUnit inherentHeight = XUnit.FromInch(yPixels / vertRes);
bool lockRatio = this.image.IsNull("LockAspectRatio") ? true : image.LockAspectRatio;
double scaleHeight = this.image.ScaleHeight;
double scaleWidth = this.image.ScaleWidth;
bool scaleHeightSet = !this.image.IsNull("ScaleHeight");
bool scaleWidthSet = !this.image.IsNull("ScaleWidth");
if (lockRatio && !(scaleHeightSet && scaleWidthSet))
{
if (usrWidthSet && !usrHeightSet)
{
resultHeight = inherentHeight / inherentWidth * usrWidth;
}
else if (usrHeightSet && !usrWidthSet)
{
resultWidth = inherentWidth / inherentHeight * usrHeight;
}
else if (!usrHeightSet && !usrWidthSet)
{
resultHeight = inherentHeight;
resultWidth = inherentWidth;
}
if (scaleHeightSet)
{
resultHeight = resultHeight * scaleHeight;
resultWidth = resultWidth * scaleHeight;
}
if (scaleWidthSet)
{
resultHeight = resultHeight * scaleWidth;
resultWidth = resultWidth * scaleWidth;
}
}
else
{
if (!usrHeightSet)
resultHeight = inherentHeight;
if (!usrWidthSet)
resultWidth = inherentWidth;
if (scaleHeightSet)
resultHeight = resultHeight * scaleHeight;
if (scaleWidthSet)
resultWidth = resultWidth * scaleWidth;
}
formatInfo.CropWidth = (int)xPixels;
formatInfo.CropHeight = (int)yPixels;
if (!this.image.IsNull("PictureFormat"))
{
PictureFormat picFormat = this.image.PictureFormat;
//Cropping in pixels.
XUnit cropLeft = picFormat.CropLeft.Point;
XUnit cropRight = picFormat.CropRight.Point;
XUnit cropTop = picFormat.CropTop.Point;
XUnit cropBottom = picFormat.CropBottom.Point;
formatInfo.CropX = (int)(horzRes * cropLeft.Inch);
formatInfo.CropY = (int)(vertRes * cropTop.Inch);
formatInfo.CropWidth -= (int)(horzRes * ((XUnit)(cropLeft + cropRight)).Inch);
formatInfo.CropHeight -= (int)(vertRes * ((XUnit)(cropTop + cropBottom)).Inch);
//Scaled cropping of the height and width.
double xScale = resultWidth / inherentWidth;
double yScale = resultHeight / inherentHeight;
cropLeft = xScale * cropLeft;
cropRight = xScale * cropRight;
cropTop = yScale * cropTop;
cropBottom = yScale * cropBottom;
resultHeight = resultHeight - cropTop - cropBottom;
resultWidth = resultWidth - cropLeft - cropRight;
}
if (resultHeight <= 0 || resultWidth <= 0)
{
formatInfo.Width = XUnit.FromCentimeter(2.5);
formatInfo.Height = XUnit.FromCentimeter(2.5);
Trace.WriteLine(Messages.EmptyImageSize);
this.failure = ImageFailure.EmptySize;
}
else
{
formatInfo.Width = resultWidth;
formatInfo.Height = resultHeight;
}
}
catch (Exception ex)
{
Trace.WriteLine(Messages.ImageNotReadable(this.image.Name, ex.Message));
formatInfo.failure = ImageFailure.NotRead;
}
finally
{
if (xImage != null)
xImage.Dispose();
}
}
if (formatInfo.failure != ImageFailure.None)
{
if (!this.image.IsNull("Width"))
formatInfo.Width = this.image.Width.Point;
else
formatInfo.Width = XUnit.FromCentimeter(2.5);
if (!this.image.IsNull("Height"))
formatInfo.Height = this.image.Height.Point;
else
formatInfo.Height = XUnit.FromCentimeter(2.5);
return;
}
}
Image image;
string imageFilePath;
ImageFailure failure;
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
namespace Apache.Ignite.Core.Impl.Binary
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using Apache.Ignite.Core.Binary;
using Apache.Ignite.Core.Impl.Binary.IO;
using Apache.Ignite.Core.Impl.Binary.Metadata;
using Apache.Ignite.Core.Impl.Binary.Structure;
using Apache.Ignite.Core.Impl.Common;
/// <summary>
/// Binary writer implementation.
/// </summary>
internal class BinaryWriter : IBinaryWriter, IBinaryRawWriter
{
/** Marshaller. */
private readonly Marshaller _marsh;
/** Stream. */
private readonly IBinaryStream _stream;
/** Builder (used only during build). */
private BinaryObjectBuilder _builder;
/** Handles. */
private BinaryHandleDictionary<object, long> _hnds;
/** Metadatas collected during this write session. */
private IDictionary<int, BinaryType> _metas;
/** Current stack frame. */
private Frame _frame;
/** Whether we are currently detaching an object. */
private bool _detaching;
/** Whether we are directly within peer loading object holder. */
private bool _isInWrapper;
/** Schema holder. */
private readonly BinaryObjectSchemaHolder _schema = BinaryObjectSchemaHolder.Current;
/// <summary>
/// Gets the marshaller.
/// </summary>
internal Marshaller Marshaller
{
get { return _marsh; }
}
/// <summary>
/// Write named boolean value.
/// </summary>
/// <param name="fieldName">Field name.</param>
/// <param name="val">Boolean value.</param>
public void WriteBoolean(string fieldName, bool val)
{
WriteFieldId(fieldName, BinaryTypeId.Bool);
WriteBooleanField(val);
}
/// <summary>
/// Writes the boolean field.
/// </summary>
/// <param name="val">if set to <c>true</c> [value].</param>
internal void WriteBooleanField(bool val)
{
_stream.WriteByte(BinaryTypeId.Bool);
_stream.WriteBool(val);
}
/// <summary>
/// Write boolean value.
/// </summary>
/// <param name="val">Boolean value.</param>
public void WriteBoolean(bool val)
{
_stream.WriteBool(val);
}
/// <summary>
/// Write named boolean array.
/// </summary>
/// <param name="fieldName">Field name.</param>
/// <param name="val">Boolean array.</param>
public void WriteBooleanArray(string fieldName, bool[] val)
{
WriteFieldId(fieldName, BinaryTypeId.ArrayBool);
if (val == null)
WriteNullField();
else
{
_stream.WriteByte(BinaryTypeId.ArrayBool);
BinaryUtils.WriteBooleanArray(val, _stream);
}
}
/// <summary>
/// Write boolean array.
/// </summary>
/// <param name="val">Boolean array.</param>
public void WriteBooleanArray(bool[] val)
{
if (val == null)
WriteNullRawField();
else
{
_stream.WriteByte(BinaryTypeId.ArrayBool);
BinaryUtils.WriteBooleanArray(val, _stream);
}
}
/// <summary>
/// Write named byte value.
/// </summary>
/// <param name="fieldName">Field name.</param>
/// <param name="val">Byte value.</param>
public void WriteByte(string fieldName, byte val)
{
WriteFieldId(fieldName, BinaryTypeId.Byte);
WriteByteField(val);
}
/// <summary>
/// Write byte field value.
/// </summary>
/// <param name="val">Byte value.</param>
internal void WriteByteField(byte val)
{
_stream.WriteByte(BinaryTypeId.Byte);
_stream.WriteByte(val);
}
/// <summary>
/// Write byte value.
/// </summary>
/// <param name="val">Byte value.</param>
public void WriteByte(byte val)
{
_stream.WriteByte(val);
}
/// <summary>
/// Write named byte array.
/// </summary>
/// <param name="fieldName">Field name.</param>
/// <param name="val">Byte array.</param>
public void WriteByteArray(string fieldName, byte[] val)
{
WriteFieldId(fieldName, BinaryTypeId.ArrayByte);
if (val == null)
WriteNullField();
else
{
_stream.WriteByte(BinaryTypeId.ArrayByte);
BinaryUtils.WriteByteArray(val, _stream);
}
}
/// <summary>
/// Write byte array.
/// </summary>
/// <param name="val">Byte array.</param>
public void WriteByteArray(byte[] val)
{
if (val == null)
WriteNullRawField();
else
{
_stream.WriteByte(BinaryTypeId.ArrayByte);
BinaryUtils.WriteByteArray(val, _stream);
}
}
/// <summary>
/// Write named short value.
/// </summary>
/// <param name="fieldName">Field name.</param>
/// <param name="val">Short value.</param>
public void WriteShort(string fieldName, short val)
{
WriteFieldId(fieldName, BinaryTypeId.Short);
WriteShortField(val);
}
/// <summary>
/// Write short field value.
/// </summary>
/// <param name="val">Short value.</param>
internal void WriteShortField(short val)
{
_stream.WriteByte(BinaryTypeId.Short);
_stream.WriteShort(val);
}
/// <summary>
/// Write short value.
/// </summary>
/// <param name="val">Short value.</param>
public void WriteShort(short val)
{
_stream.WriteShort(val);
}
/// <summary>
/// Write named short array.
/// </summary>
/// <param name="fieldName">Field name.</param>
/// <param name="val">Short array.</param>
public void WriteShortArray(string fieldName, short[] val)
{
WriteFieldId(fieldName, BinaryTypeId.ArrayShort);
if (val == null)
WriteNullField();
else
{
_stream.WriteByte(BinaryTypeId.ArrayShort);
BinaryUtils.WriteShortArray(val, _stream);
}
}
/// <summary>
/// Write short array.
/// </summary>
/// <param name="val">Short array.</param>
public void WriteShortArray(short[] val)
{
if (val == null)
WriteNullRawField();
else
{
_stream.WriteByte(BinaryTypeId.ArrayShort);
BinaryUtils.WriteShortArray(val, _stream);
}
}
/// <summary>
/// Write named char value.
/// </summary>
/// <param name="fieldName">Field name.</param>
/// <param name="val">Char value.</param>
public void WriteChar(string fieldName, char val)
{
WriteFieldId(fieldName, BinaryTypeId.Char);
WriteCharField(val);
}
/// <summary>
/// Write char field value.
/// </summary>
/// <param name="val">Char value.</param>
internal void WriteCharField(char val)
{
_stream.WriteByte(BinaryTypeId.Char);
_stream.WriteChar(val);
}
/// <summary>
/// Write char value.
/// </summary>
/// <param name="val">Char value.</param>
public void WriteChar(char val)
{
_stream.WriteChar(val);
}
/// <summary>
/// Write named char array.
/// </summary>
/// <param name="fieldName">Field name.</param>
/// <param name="val">Char array.</param>
public void WriteCharArray(string fieldName, char[] val)
{
WriteFieldId(fieldName, BinaryTypeId.ArrayChar);
if (val == null)
WriteNullField();
else
{
_stream.WriteByte(BinaryTypeId.ArrayChar);
BinaryUtils.WriteCharArray(val, _stream);
}
}
/// <summary>
/// Write char array.
/// </summary>
/// <param name="val">Char array.</param>
public void WriteCharArray(char[] val)
{
if (val == null)
WriteNullRawField();
else
{
_stream.WriteByte(BinaryTypeId.ArrayChar);
BinaryUtils.WriteCharArray(val, _stream);
}
}
/// <summary>
/// Write named int value.
/// </summary>
/// <param name="fieldName">Field name.</param>
/// <param name="val">Int value.</param>
public void WriteInt(string fieldName, int val)
{
WriteFieldId(fieldName, BinaryTypeId.Int);
WriteIntField(val);
}
/// <summary>
/// Writes the int field.
/// </summary>
/// <param name="val">The value.</param>
internal void WriteIntField(int val)
{
_stream.WriteByte(BinaryTypeId.Int);
_stream.WriteInt(val);
}
/// <summary>
/// Write int value.
/// </summary>
/// <param name="val">Int value.</param>
public void WriteInt(int val)
{
_stream.WriteInt(val);
}
/// <summary>
/// Write named int array.
/// </summary>
/// <param name="fieldName">Field name.</param>
/// <param name="val">Int array.</param>
public void WriteIntArray(string fieldName, int[] val)
{
WriteFieldId(fieldName, BinaryTypeId.ArrayInt);
if (val == null)
WriteNullField();
else
{
_stream.WriteByte(BinaryTypeId.ArrayInt);
BinaryUtils.WriteIntArray(val, _stream);
}
}
/// <summary>
/// Write int array.
/// </summary>
/// <param name="val">Int array.</param>
public void WriteIntArray(int[] val)
{
if (val == null)
WriteNullRawField();
else
{
_stream.WriteByte(BinaryTypeId.ArrayInt);
BinaryUtils.WriteIntArray(val, _stream);
}
}
/// <summary>
/// Write named long value.
/// </summary>
/// <param name="fieldName">Field name.</param>
/// <param name="val">Long value.</param>
public void WriteLong(string fieldName, long val)
{
WriteFieldId(fieldName, BinaryTypeId.Long);
WriteLongField(val);
}
/// <summary>
/// Writes the long field.
/// </summary>
/// <param name="val">The value.</param>
internal void WriteLongField(long val)
{
_stream.WriteByte(BinaryTypeId.Long);
_stream.WriteLong(val);
}
/// <summary>
/// Write long value.
/// </summary>
/// <param name="val">Long value.</param>
public void WriteLong(long val)
{
_stream.WriteLong(val);
}
/// <summary>
/// Write named long array.
/// </summary>
/// <param name="fieldName">Field name.</param>
/// <param name="val">Long array.</param>
public void WriteLongArray(string fieldName, long[] val)
{
WriteFieldId(fieldName, BinaryTypeId.ArrayLong);
if (val == null)
WriteNullField();
else
{
_stream.WriteByte(BinaryTypeId.ArrayLong);
BinaryUtils.WriteLongArray(val, _stream);
}
}
/// <summary>
/// Write long array.
/// </summary>
/// <param name="val">Long array.</param>
public void WriteLongArray(long[] val)
{
if (val == null)
WriteNullRawField();
else
{
_stream.WriteByte(BinaryTypeId.ArrayLong);
BinaryUtils.WriteLongArray(val, _stream);
}
}
/// <summary>
/// Write named float value.
/// </summary>
/// <param name="fieldName">Field name.</param>
/// <param name="val">Float value.</param>
public void WriteFloat(string fieldName, float val)
{
WriteFieldId(fieldName, BinaryTypeId.Float);
WriteFloatField(val);
}
/// <summary>
/// Writes the float field.
/// </summary>
/// <param name="val">The value.</param>
internal void WriteFloatField(float val)
{
_stream.WriteByte(BinaryTypeId.Float);
_stream.WriteFloat(val);
}
/// <summary>
/// Write float value.
/// </summary>
/// <param name="val">Float value.</param>
public void WriteFloat(float val)
{
_stream.WriteFloat(val);
}
/// <summary>
/// Write named float array.
/// </summary>
/// <param name="fieldName">Field name.</param>
/// <param name="val">Float array.</param>
public void WriteFloatArray(string fieldName, float[] val)
{
WriteFieldId(fieldName, BinaryTypeId.ArrayFloat);
if (val == null)
WriteNullField();
else
{
_stream.WriteByte(BinaryTypeId.ArrayFloat);
BinaryUtils.WriteFloatArray(val, _stream);
}
}
/// <summary>
/// Write float array.
/// </summary>
/// <param name="val">Float array.</param>
public void WriteFloatArray(float[] val)
{
if (val == null)
WriteNullRawField();
else
{
_stream.WriteByte(BinaryTypeId.ArrayFloat);
BinaryUtils.WriteFloatArray(val, _stream);
}
}
/// <summary>
/// Write named double value.
/// </summary>
/// <param name="fieldName">Field name.</param>
/// <param name="val">Double value.</param>
public void WriteDouble(string fieldName, double val)
{
WriteFieldId(fieldName, BinaryTypeId.Double);
WriteDoubleField(val);
}
/// <summary>
/// Writes the double field.
/// </summary>
/// <param name="val">The value.</param>
internal void WriteDoubleField(double val)
{
_stream.WriteByte(BinaryTypeId.Double);
_stream.WriteDouble(val);
}
/// <summary>
/// Write double value.
/// </summary>
/// <param name="val">Double value.</param>
public void WriteDouble(double val)
{
_stream.WriteDouble(val);
}
/// <summary>
/// Write named double array.
/// </summary>
/// <param name="fieldName">Field name.</param>
/// <param name="val">Double array.</param>
public void WriteDoubleArray(string fieldName, double[] val)
{
WriteFieldId(fieldName, BinaryTypeId.ArrayDouble);
if (val == null)
WriteNullField();
else
{
_stream.WriteByte(BinaryTypeId.ArrayDouble);
BinaryUtils.WriteDoubleArray(val, _stream);
}
}
/// <summary>
/// Write double array.
/// </summary>
/// <param name="val">Double array.</param>
public void WriteDoubleArray(double[] val)
{
if (val == null)
WriteNullRawField();
else
{
_stream.WriteByte(BinaryTypeId.ArrayDouble);
BinaryUtils.WriteDoubleArray(val, _stream);
}
}
/// <summary>
/// Write named decimal value.
/// </summary>
/// <param name="fieldName">Field name.</param>
/// <param name="val">Decimal value.</param>
public void WriteDecimal(string fieldName, decimal? val)
{
WriteFieldId(fieldName, BinaryTypeId.Decimal);
if (val == null)
WriteNullField();
else
{
_stream.WriteByte(BinaryTypeId.Decimal);
BinaryUtils.WriteDecimal(val.Value, _stream);
}
}
/// <summary>
/// Write decimal value.
/// </summary>
/// <param name="val">Decimal value.</param>
public void WriteDecimal(decimal? val)
{
if (val == null)
WriteNullRawField();
else
{
_stream.WriteByte(BinaryTypeId.Decimal);
BinaryUtils.WriteDecimal(val.Value, _stream);
}
}
/// <summary>
/// Write named decimal array.
/// </summary>
/// <param name="fieldName">Field name.</param>
/// <param name="val">Decimal array.</param>
public void WriteDecimalArray(string fieldName, decimal?[] val)
{
WriteFieldId(fieldName, BinaryTypeId.ArrayDecimal);
if (val == null)
WriteNullField();
else
{
_stream.WriteByte(BinaryTypeId.ArrayDecimal);
BinaryUtils.WriteDecimalArray(val, _stream);
}
}
/// <summary>
/// Write decimal array.
/// </summary>
/// <param name="val">Decimal array.</param>
public void WriteDecimalArray(decimal?[] val)
{
if (val == null)
WriteNullRawField();
else
{
_stream.WriteByte(BinaryTypeId.ArrayDecimal);
BinaryUtils.WriteDecimalArray(val, _stream);
}
}
/// <summary>
/// Write named date value.
/// </summary>
/// <param name="fieldName">Field name.</param>
/// <param name="val">Date value.</param>
public void WriteTimestamp(string fieldName, DateTime? val)
{
WriteFieldId(fieldName, BinaryTypeId.Timestamp);
if (val == null)
WriteNullField();
else
{
_stream.WriteByte(BinaryTypeId.Timestamp);
BinaryUtils.WriteTimestamp(val.Value, _stream);
}
}
/// <summary>
/// Write date value.
/// </summary>
/// <param name="val">Date value.</param>
public void WriteTimestamp(DateTime? val)
{
if (val == null)
WriteNullRawField();
else
{
_stream.WriteByte(BinaryTypeId.Timestamp);
BinaryUtils.WriteTimestamp(val.Value, _stream);
}
}
/// <summary>
/// Write named date array.
/// </summary>
/// <param name="fieldName">Field name.</param>
/// <param name="val">Date array.</param>
public void WriteTimestampArray(string fieldName, DateTime?[] val)
{
WriteFieldId(fieldName, BinaryTypeId.Timestamp);
if (val == null)
WriteNullField();
else
{
_stream.WriteByte(BinaryTypeId.ArrayTimestamp);
BinaryUtils.WriteTimestampArray(val, _stream);
}
}
/// <summary>
/// Write date array.
/// </summary>
/// <param name="val">Date array.</param>
public void WriteTimestampArray(DateTime?[] val)
{
if (val == null)
WriteNullRawField();
else
{
_stream.WriteByte(BinaryTypeId.ArrayTimestamp);
BinaryUtils.WriteTimestampArray(val, _stream);
}
}
/// <summary>
/// Write named string value.
/// </summary>
/// <param name="fieldName">Field name.</param>
/// <param name="val">String value.</param>
public void WriteString(string fieldName, string val)
{
WriteFieldId(fieldName, BinaryTypeId.String);
if (val == null)
WriteNullField();
else
{
_stream.WriteByte(BinaryTypeId.String);
BinaryUtils.WriteString(val, _stream);
}
}
/// <summary>
/// Write string value.
/// </summary>
/// <param name="val">String value.</param>
public void WriteString(string val)
{
if (val == null)
WriteNullRawField();
else
{
_stream.WriteByte(BinaryTypeId.String);
BinaryUtils.WriteString(val, _stream);
}
}
/// <summary>
/// Write named string array.
/// </summary>
/// <param name="fieldName">Field name.</param>
/// <param name="val">String array.</param>
public void WriteStringArray(string fieldName, string[] val)
{
WriteFieldId(fieldName, BinaryTypeId.ArrayString);
if (val == null)
WriteNullField();
else
{
_stream.WriteByte(BinaryTypeId.ArrayString);
BinaryUtils.WriteStringArray(val, _stream);
}
}
/// <summary>
/// Write string array.
/// </summary>
/// <param name="val">String array.</param>
public void WriteStringArray(string[] val)
{
if (val == null)
WriteNullRawField();
else
{
_stream.WriteByte(BinaryTypeId.ArrayString);
BinaryUtils.WriteStringArray(val, _stream);
}
}
/// <summary>
/// Write named GUID value.
/// </summary>
/// <param name="fieldName">Field name.</param>
/// <param name="val">GUID value.</param>
public void WriteGuid(string fieldName, Guid? val)
{
WriteFieldId(fieldName, BinaryTypeId.Guid);
if (val == null)
WriteNullField();
else
{
_stream.WriteByte(BinaryTypeId.Guid);
BinaryUtils.WriteGuid(val.Value, _stream);
}
}
/// <summary>
/// Write GUID value.
/// </summary>
/// <param name="val">GUID value.</param>
public void WriteGuid(Guid? val)
{
if (val == null)
WriteNullRawField();
else
{
_stream.WriteByte(BinaryTypeId.Guid);
BinaryUtils.WriteGuid(val.Value, _stream);
}
}
/// <summary>
/// Write named GUID array.
/// </summary>
/// <param name="fieldName">Field name.</param>
/// <param name="val">GUID array.</param>
public void WriteGuidArray(string fieldName, Guid?[] val)
{
WriteFieldId(fieldName, BinaryTypeId.ArrayGuid);
if (val == null)
WriteNullField();
else
{
_stream.WriteByte(BinaryTypeId.ArrayGuid);
BinaryUtils.WriteGuidArray(val, _stream);
}
}
/// <summary>
/// Write GUID array.
/// </summary>
/// <param name="val">GUID array.</param>
public void WriteGuidArray(Guid?[] val)
{
if (val == null)
WriteNullRawField();
else
{
_stream.WriteByte(BinaryTypeId.ArrayGuid);
BinaryUtils.WriteGuidArray(val, _stream);
}
}
/// <summary>
/// Write named enum value.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="fieldName">Field name.</param>
/// <param name="val">Enum value.</param>
public void WriteEnum<T>(string fieldName, T val)
{
WriteFieldId(fieldName, BinaryTypeId.Enum);
WriteEnum(val);
}
/// <summary>
/// Write enum value.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="val">Enum value.</param>
public void WriteEnum<T>(T val)
{
// ReSharper disable once CompareNonConstrainedGenericWithNull
if (val == null)
WriteNullField();
else
{
// Unwrap nullable.
var valType = val.GetType();
var type = Nullable.GetUnderlyingType(valType) ?? valType;
if (!type.IsEnum)
{
throw new BinaryObjectException("Type is not an enum: " + type);
}
var handler = BinarySystemHandlers.GetWriteHandler(type);
if (handler != null)
{
// All enums except long/ulong.
handler.Write(this, val);
}
else
{
throw new BinaryObjectException(string.Format("Enum '{0}' has unsupported underlying type '{1}'. " +
"Use WriteObject instead of WriteEnum.",
type, Enum.GetUnderlyingType(type)));
}
}
}
/// <summary>
/// Write enum value.
/// </summary>
/// <param name="val">Enum value.</param>
/// <param name="type">Enum type.</param>
internal void WriteEnum(int val, Type type)
{
var desc = _marsh.GetDescriptor(type);
_stream.WriteByte(BinaryTypeId.Enum);
_stream.WriteInt(desc.TypeId);
_stream.WriteInt(val);
var metaHnd = _marsh.GetBinaryTypeHandler(desc);
SaveMetadata(desc, metaHnd.OnObjectWriteFinished());
}
/// <summary>
/// Write named enum array.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="fieldName">Field name.</param>
/// <param name="val">Enum array.</param>
public void WriteEnumArray<T>(string fieldName, T[] val)
{
WriteFieldId(fieldName, BinaryTypeId.ArrayEnum);
WriteEnumArray(val);
}
/// <summary>
/// Write enum array.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="val">Enum array.</param>
public void WriteEnumArray<T>(T[] val)
{
WriteEnumArrayInternal(val, null);
}
/// <summary>
/// Writes the enum array.
/// </summary>
/// <param name="val">The value.</param>
/// <param name="elementTypeId">The element type id.</param>
public void WriteEnumArrayInternal(Array val, int? elementTypeId)
{
if (val == null)
WriteNullField();
else
{
_stream.WriteByte(BinaryTypeId.ArrayEnum);
BinaryUtils.WriteArray(val, this, elementTypeId);
}
}
/// <summary>
/// Write named object value.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="fieldName">Field name.</param>
/// <param name="val">Object value.</param>
public void WriteObject<T>(string fieldName, T val)
{
WriteFieldId(fieldName, BinaryTypeId.Object);
// ReSharper disable once CompareNonConstrainedGenericWithNull
if (val == null)
WriteNullField();
else
Write(val);
}
/// <summary>
/// Write object value.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="val">Object value.</param>
public void WriteObject<T>(T val)
{
Write(val);
}
/// <summary>
/// Write named object array.
/// </summary>
/// <typeparam name="T">Element type.</typeparam>
/// <param name="fieldName">Field name.</param>
/// <param name="val">Object array.</param>
public void WriteArray<T>(string fieldName, T[] val)
{
WriteFieldId(fieldName, BinaryTypeId.Array);
WriteArray(val);
}
/// <summary>
/// Write object array.
/// </summary>
/// <typeparam name="T">Element type.</typeparam>
/// <param name="val">Object array.</param>
public void WriteArray<T>(T[] val)
{
WriteArrayInternal(val);
}
/// <summary>
/// Write object array.
/// </summary>
/// <param name="val">Object array.</param>
public void WriteArrayInternal(Array val)
{
if (val == null)
WriteNullRawField();
else
{
if (WriteHandle(_stream.Position, val))
return;
_stream.WriteByte(BinaryTypeId.Array);
BinaryUtils.WriteArray(val, this);
}
}
/// <summary>
/// Write named collection.
/// </summary>
/// <param name="fieldName">Field name.</param>
/// <param name="val">Collection.</param>
public void WriteCollection(string fieldName, ICollection val)
{
WriteFieldId(fieldName, BinaryTypeId.Collection);
WriteCollection(val);
}
/// <summary>
/// Write collection.
/// </summary>
/// <param name="val">Collection.</param>
public void WriteCollection(ICollection val)
{
if (val == null)
WriteNullField();
else
{
if (WriteHandle(_stream.Position, val))
return;
WriteByte(BinaryTypeId.Collection);
BinaryUtils.WriteCollection(val, this);
}
}
/// <summary>
/// Write named dictionary.
/// </summary>
/// <param name="fieldName">Field name.</param>
/// <param name="val">Dictionary.</param>
public void WriteDictionary(string fieldName, IDictionary val)
{
WriteFieldId(fieldName, BinaryTypeId.Dictionary);
WriteDictionary(val);
}
/// <summary>
/// Write dictionary.
/// </summary>
/// <param name="val">Dictionary.</param>
public void WriteDictionary(IDictionary val)
{
if (val == null)
WriteNullField();
else
{
if (WriteHandle(_stream.Position, val))
return;
WriteByte(BinaryTypeId.Dictionary);
BinaryUtils.WriteDictionary(val, this);
}
}
/// <summary>
/// Write NULL field.
/// </summary>
private void WriteNullField()
{
_stream.WriteByte(BinaryUtils.HdrNull);
}
/// <summary>
/// Write NULL raw field.
/// </summary>
private void WriteNullRawField()
{
_stream.WriteByte(BinaryUtils.HdrNull);
}
/// <summary>
/// Get raw writer.
/// </summary>
/// <returns>
/// Raw writer.
/// </returns>
public IBinaryRawWriter GetRawWriter()
{
if (_frame.RawPos == 0)
_frame.RawPos = _stream.Position;
return this;
}
/// <summary>
/// Set new builder.
/// </summary>
/// <param name="builder">Builder.</param>
/// <returns>Previous builder.</returns>
internal BinaryObjectBuilder SetBuilder(BinaryObjectBuilder builder)
{
BinaryObjectBuilder ret = _builder;
_builder = builder;
return ret;
}
/// <summary>
/// Constructor.
/// </summary>
/// <param name="marsh">Marshaller.</param>
/// <param name="stream">Stream.</param>
internal BinaryWriter(Marshaller marsh, IBinaryStream stream)
{
_marsh = marsh;
_stream = stream;
}
/// <summary>
/// Write object.
/// </summary>
/// <param name="obj">Object.</param>
public void Write<T>(T obj)
{
// Handle special case for null.
// ReSharper disable once CompareNonConstrainedGenericWithNull
if (obj == null)
{
_stream.WriteByte(BinaryUtils.HdrNull);
return;
}
// We use GetType() of a real object instead of typeof(T) to take advantage of
// automatic Nullable'1 unwrapping.
Type type = obj.GetType();
// Handle common case when primitive is written.
if (type.IsPrimitive)
{
WritePrimitive(obj, type);
return;
}
// Handle special case for builder.
if (WriteBuilderSpecials(obj))
return;
// Are we dealing with a well-known type?
var handler = BinarySystemHandlers.GetWriteHandler(type);
if (handler != null)
{
if (handler.SupportsHandles && WriteHandle(_stream.Position, obj))
return;
handler.Write(this, obj);
return;
}
// Wrap objects as required.
if (WrapperFunc != null && type != WrapperFunc.Method.ReturnType)
{
if (_isInWrapper)
{
_isInWrapper = false;
}
else
{
_isInWrapper = true;
Write(WrapperFunc(obj));
return;
}
}
// Suppose that we faced normal object and perform descriptor lookup.
var desc = _marsh.GetDescriptor(type);
// Writing normal object.
var pos = _stream.Position;
// Dealing with handles.
if (desc.Serializer.SupportsHandles && WriteHandle(pos, obj))
return;
// Skip header length as not everything is known now
_stream.Seek(BinaryObjectHeader.Size, SeekOrigin.Current);
// Write type name for unregistered types
if (!desc.IsRegistered)
{
WriteString(Marshaller.GetTypeName(type));
}
var headerSize = _stream.Position - pos;
// Preserve old frame.
var oldFrame = _frame;
// Push new frame.
_frame.RawPos = 0;
_frame.Pos = pos;
_frame.Struct = new BinaryStructureTracker(desc, desc.WriterTypeStructure);
_frame.HasCustomTypeData = false;
var schemaIdx = _schema.PushSchema();
try
{
// Write object fields.
desc.Serializer.WriteBinary(obj, this);
var dataEnd = _stream.Position;
// Write schema
var schemaOffset = dataEnd - pos;
int schemaId;
var flags = desc.UserType
? BinaryObjectHeader.Flag.UserType
: BinaryObjectHeader.Flag.None;
if (_frame.HasCustomTypeData)
flags |= BinaryObjectHeader.Flag.CustomDotNetType;
if (Marshaller.CompactFooter && desc.UserType)
flags |= BinaryObjectHeader.Flag.CompactFooter;
var hasSchema = _schema.WriteSchema(_stream, schemaIdx, out schemaId, ref flags);
if (hasSchema)
{
flags |= BinaryObjectHeader.Flag.HasSchema;
// Calculate and write header.
if (_frame.RawPos > 0)
_stream.WriteInt(_frame.RawPos - pos); // raw offset is in the last 4 bytes
// Update schema in type descriptor
if (desc.Schema.Get(schemaId) == null)
desc.Schema.Add(schemaId, _schema.GetSchema(schemaIdx));
}
else
schemaOffset = headerSize;
if (_frame.RawPos > 0)
flags |= BinaryObjectHeader.Flag.HasRaw;
var len = _stream.Position - pos;
var hashCode = BinaryArrayEqualityComparer.GetHashCode(Stream, pos + BinaryObjectHeader.Size,
dataEnd - pos - BinaryObjectHeader.Size);
var header = new BinaryObjectHeader(desc.IsRegistered ? desc.TypeId : BinaryTypeId.Unregistered,
hashCode, len, schemaId, schemaOffset, flags);
BinaryObjectHeader.Write(header, _stream, pos);
Stream.Seek(pos + len, SeekOrigin.Begin); // Seek to the end
}
finally
{
_schema.PopSchema(schemaIdx);
}
// Apply structure updates if any.
_frame.Struct.UpdateWriterStructure(this);
// Restore old frame.
_frame = oldFrame;
}
/// <summary>
/// Marks current object with a custom type data flag.
/// </summary>
public void SetCustomTypeDataFlag(bool hasCustomTypeData)
{
_frame.HasCustomTypeData = hasCustomTypeData;
}
/// <summary>
/// Write primitive type.
/// </summary>
/// <param name="val">Object.</param>
/// <param name="type">Type.</param>
private unsafe void WritePrimitive<T>(T val, Type type)
{
// .NET defines 14 primitive types.
// Types check sequence is designed to minimize comparisons for the most frequent types.
if (type == typeof(int))
WriteIntField(TypeCaster<int>.Cast(val));
else if (type == typeof(long))
WriteLongField(TypeCaster<long>.Cast(val));
else if (type == typeof(bool))
WriteBooleanField(TypeCaster<bool>.Cast(val));
else if (type == typeof(byte))
WriteByteField(TypeCaster<byte>.Cast(val));
else if (type == typeof(short))
WriteShortField(TypeCaster<short>.Cast(val));
else if (type == typeof(char))
WriteCharField(TypeCaster<char>.Cast(val));
else if (type == typeof(float))
WriteFloatField(TypeCaster<float>.Cast(val));
else if (type == typeof(double))
WriteDoubleField(TypeCaster<double>.Cast(val));
else if (type == typeof(sbyte))
{
var val0 = TypeCaster<sbyte>.Cast(val);
WriteByteField(*(byte*)&val0);
}
else if (type == typeof(ushort))
{
var val0 = TypeCaster<ushort>.Cast(val);
WriteShortField(*(short*) &val0);
}
else if (type == typeof(uint))
{
var val0 = TypeCaster<uint>.Cast(val);
WriteIntField(*(int*)&val0);
}
else if (type == typeof(ulong))
{
var val0 = TypeCaster<ulong>.Cast(val);
WriteLongField(*(long*)&val0);
}
else if (type == typeof(IntPtr))
{
var val0 = TypeCaster<IntPtr>.Cast(val).ToInt64();
WriteLongField(val0);
}
else if (type == typeof(UIntPtr))
{
var val0 = TypeCaster<UIntPtr>.Cast(val).ToUInt64();
WriteLongField(*(long*)&val0);
}
else
throw BinaryUtils.GetUnsupportedTypeException(type, val);
}
/// <summary>
/// Try writing object as special builder type.
/// </summary>
/// <param name="obj">Object.</param>
/// <returns>True if object was written, false otherwise.</returns>
private bool WriteBuilderSpecials<T>(T obj)
{
if (_builder != null)
{
// Special case for binary object during build.
BinaryObject portObj = obj as BinaryObject;
if (portObj != null)
{
if (!WriteHandle(_stream.Position, portObj))
_builder.ProcessBinary(_stream, portObj);
return true;
}
// Special case for builder during build.
BinaryObjectBuilder portBuilder = obj as BinaryObjectBuilder;
if (portBuilder != null)
{
if (!WriteHandle(_stream.Position, portBuilder))
_builder.ProcessBuilder(_stream, portBuilder);
return true;
}
}
return false;
}
/// <summary>
/// Add handle to handles map.
/// </summary>
/// <param name="pos">Position in stream.</param>
/// <param name="obj">Object.</param>
/// <returns><c>true</c> if object was written as handle.</returns>
private bool WriteHandle(long pos, object obj)
{
if (_hnds == null)
{
// Cache absolute handle position.
_hnds = new BinaryHandleDictionary<object, long>(obj, pos, ReferenceEqualityComparer<object>.Instance);
return false;
}
long hndPos;
if (!_hnds.TryGetValue(obj, out hndPos))
{
// Cache absolute handle position.
_hnds.Add(obj, pos);
return false;
}
_stream.WriteByte(BinaryUtils.HdrHnd);
// Handle is written as difference between position before header and handle position.
_stream.WriteInt((int)(pos - hndPos));
return true;
}
/// <summary>
/// Perform action with detached semantics.
/// </summary>
internal void WriteObjectDetached<T>(T o)
{
if (_detaching)
{
Write(o);
}
else
{
_detaching = true;
BinaryHandleDictionary<object, long> oldHnds = _hnds;
_hnds = null;
try
{
Write(o);
}
finally
{
_detaching = false;
if (oldHnds != null)
{
// Merge newly recorded handles with old ones and restore old on the stack.
// Otherwise we can use current handles right away.
if (_hnds != null)
oldHnds.Merge(_hnds);
_hnds = oldHnds;
}
}
}
}
/// <summary>
/// Gets or sets a function to wrap all serializer objects.
/// </summary>
internal Func<object, object> WrapperFunc { get; set; }
/// <summary>
/// Stream.
/// </summary>
internal IBinaryStream Stream
{
get { return _stream; }
}
/// <summary>
/// Gets collected metadatas.
/// </summary>
/// <returns>Collected metadatas (if any).</returns>
internal ICollection<BinaryType> GetBinaryTypes()
{
return _metas == null ? null : _metas.Values;
}
/// <summary>
/// Write field ID.
/// </summary>
/// <param name="fieldName">Field name.</param>
/// <param name="fieldTypeId">Field type ID.</param>
private void WriteFieldId(string fieldName, byte fieldTypeId)
{
if (_frame.RawPos != 0)
throw new BinaryObjectException("Cannot write named fields after raw data is written.");
var fieldId = _frame.Struct.GetFieldId(fieldName, fieldTypeId);
_schema.PushField(fieldId, _stream.Position - _frame.Pos);
}
/// <summary>
/// Saves metadata for this session.
/// </summary>
/// <param name="desc">The descriptor.</param>
/// <param name="fields">Fields metadata.</param>
internal void SaveMetadata(IBinaryTypeDescriptor desc, IDictionary<string, BinaryField> fields)
{
Debug.Assert(desc != null);
if (!desc.UserType && (fields == null || fields.Count == 0))
{
// System types with no fields (most of them) do not need to be sent.
// AffinityKey is an example of system type with metadata.
return;
}
if (_metas == null)
{
_metas = new Dictionary<int, BinaryType>(1)
{
{desc.TypeId, new BinaryType(desc, _marsh, fields)}
};
}
else
{
BinaryType meta;
if (_metas.TryGetValue(desc.TypeId, out meta))
meta.UpdateFields(fields);
else
_metas[desc.TypeId] = new BinaryType(desc, _marsh, fields);
}
}
/// <summary>
/// Stores current writer stack frame.
/// </summary>
private struct Frame
{
/** Current object start position. */
public int Pos;
/** Current raw position. */
public int RawPos;
/** Current type structure tracker. */
public BinaryStructureTracker Struct;
/** Custom type data. */
public bool HasCustomTypeData;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Windows.Forms;
using Aurora.Utils;
using Microsoft.Win32;
using SharpDX.Multimedia;
using SharpDX.RawInput;
namespace Aurora
{
/// <summary>
/// Class for subscribing to various HID input events
/// </summary>
public sealed class InputEvents : IDisposable
{
private readonly MessagePumpThread thread = new MessagePumpThread();
/// <summary>
/// Event for a Key pressed Down on a keyboard
/// </summary>
public event EventHandler<KeyboardInputEventArgs> KeyDown;
/// <summary>
/// Event for a Key released on a keyboard
/// </summary>
public event EventHandler<KeyboardInputEventArgs> KeyUp;
/// <summary>
/// Event that fires when a mouse button is pressed down.
/// </summary>
public event EventHandler<MouseInputEventArgs> MouseButtonDown;
/// <summary>
/// Event that fires when a mouse button is released.
/// </summary>
public event EventHandler<MouseInputEventArgs> MouseButtonUp;
/// <summary>
/// Event that fires when the mouse scroll wheel is scrolled.
/// </summary>
public event EventHandler<MouseInputEventArgs> Scroll;
private readonly List<Keys> pressedKeySequence = new List<Keys>();
private readonly List<MouseButtons> pressedMouseButtons = new List<MouseButtons>();
public Keys[] PressedKeys
{
get { return pressedKeySequence.ToArray(); }
}
public MouseButtons[] PressedButtons {
get { return pressedMouseButtons.ToArray(); }
}
public bool Shift => new[] {Keys.ShiftKey, Keys.RShiftKey, Keys.LShiftKey}
.Any(PressedKeys.Contains);
public bool Alt => new[] {Keys.Menu, Keys.RMenu, Keys.LMenu}
.Any(PressedKeys.Contains);
public bool Control => new[] {Keys.ControlKey, Keys.RControlKey, Keys.LControlKey}
.Any(PressedKeys.Contains);
public bool Windows => new[] { Keys.LWin, Keys.RWin }
.Any(PressedKeys.Contains);
public InputEvents()
{
try
{
thread.Start(MessagePumpInit);
SystemEvents.SessionSwitch += new SessionSwitchEventHandler(SystemEvents_SessionSwitch);
}
catch
{
Dispose();
throw;
}
}
void SystemEvents_SessionSwitch(object sender, SessionSwitchEventArgs e)
{
if (e.Reason == SessionSwitchReason.SessionLock || e.Reason == SessionSwitchReason.SessionUnlock)
this.pressedKeySequence.Clear();
}
private void MessagePumpInit()
{
using (var dummyForm = new Form())
using (new DisposableRawInputHook(UsagePage.Generic, UsageId.GenericKeyboard, UsageId.GenericMouse,
DeviceFlags.InputSink, dummyForm.Handle, DeviceOnKeyboardInput, DeviceOnMouseInput))
{
thread.EnterMessageLoop();
}
}
private void DeviceOnKeyboardInput(object sender, KeyboardInputEventArgs e)
{
if ((int)e.Key == 255)
{
// discard "fake keys" which are part of an escaped sequence
return;
}
try
{
KeyUtils.CorrectRawInputData(e);
//Debug.WriteLine($"RawInput {e.Key} {e.MakeCode} {e.ScanCodeFlags} {e.GetDeviceKey()}", "InputEvents");
if (e.ScanCodeFlags.HasFlag(ScanCodeFlags.Break))
{
pressedKeySequence.RemoveAll(k => k == e.Key);
KeyUp?.Invoke(sender, e);
}
else
{
if (!pressedKeySequence.Contains(e.Key))
pressedKeySequence.Add(e.Key);
KeyDown?.Invoke(sender, e);
}
}
catch (Exception exc)
{
Global.logger.Error("Exception while handling keyboard input. Error: " + exc.ToString());
}
}
/// <summary>
/// Handles a SharpDX MouseInput event and fires the relevant InputEvents event (Scroll, MouseButtonDown or MouseButtonUp).
/// </summary>
private void DeviceOnMouseInput(object sender, MouseInputEventArgs e) {
try
{
if (e.WheelDelta != 0)
Scroll?.Invoke(sender, e);
if (e.IsMouseDownEvent())
{
if (!pressedMouseButtons.Contains(e.GetMouseButton()))
pressedMouseButtons.Add(e.GetMouseButton());
MouseButtonDown?.Invoke(sender, e);
}
else if (e.IsMouseUpEvent())
{
pressedMouseButtons.Remove(e.GetMouseButton());
MouseButtonUp?.Invoke(sender, e);
}
}
catch (Exception exc)
{
Global.logger.Error("Exception while handling mouse input. Error: " + exc.ToString());
}
}
private sealed class DisposableRawInputHook : IDisposable
{
private readonly UsagePage usagePage;
private readonly UsageId usageIdKeyboard;
private readonly UsageId usageIdMouse;
private readonly EventHandler<KeyboardInputEventArgs> keyHandler;
private readonly EventHandler<MouseInputEventArgs> mouseHandler;
public DisposableRawInputHook(UsagePage usagePage, UsageId usageIdKeyboard, UsageId usageIdMouse, DeviceFlags flags, IntPtr target,
EventHandler<KeyboardInputEventArgs> keyHandler, EventHandler<MouseInputEventArgs> mouseHandler)
{
this.usagePage = usagePage;
this.usageIdKeyboard = usageIdKeyboard;
this.usageIdMouse = usageIdMouse;
this.keyHandler = keyHandler;
this.mouseHandler = mouseHandler;
Device.RegisterDevice(usagePage, usageIdKeyboard, flags, target);
Device.KeyboardInput += keyHandler;
Device.RegisterDevice(usagePage, usageIdMouse, flags, target);
Device.MouseInput += mouseHandler;
}
public void Dispose()
{
Device.KeyboardInput -= keyHandler;
Device.RegisterDevice(usagePage, usageIdKeyboard, DeviceFlags.Remove);
Device.MouseInput -= mouseHandler;
Device.RegisterDevice(usagePage, usageIdMouse, DeviceFlags.Remove);
}
}
private bool disposed;
public void Dispose()
{
if (!disposed)
{
disposed = true;
thread.Dispose();
}
}
}
}
| |
// Copyright 2017 Google Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using UnityEngine;
using UnityEngine.VR;
using System;
using System.Collections;
using System.ComponentModel;
using Gvr.Internal;
/// Main entry point for Standalone headset APIs.
///
/// To use this API, use the GvrHeadset prefab. There can be only one
/// such prefab in a scene.
///
/// This is a singleton object.
public class GvrHeadset : MonoBehaviour {
private static GvrHeadset instance;
private IHeadsetProvider headsetProvider;
private HeadsetState headsetState;
private IEnumerator standaloneUpdate;
private WaitForEndOfFrame waitForEndOfFrame = new WaitForEndOfFrame();
// Delegates for GVR events.
private OnSafetyRegionEvent safetyRegionDelegate;
private OnRecenterEvent recenterDelegate;
// Delegate definitions.
/// This delegate is called when the headset crosses the safety region boundary.
public delegate void OnSafetyRegionEvent(bool enter);
/// This delegate is called after the headset is recentered.
/// |recenterType| indicates the reason recentering occurred.
/// |recenterFlags| are flags related to recentering. See |GvrRecenterFlags|.
/// |recenteredPosition| is the positional offset from the session start pose.
/// |recenteredOrientation| is the rotational offset from the session start pose.
public delegate void OnRecenterEvent(GvrRecenterEventType recenterType,
GvrRecenterFlags recenterFlags,
Vector3 recenteredPosition,
Quaternion recenteredOrientation);
#region DELEGATE_HANDLERS
public static event OnSafetyRegionEvent OnSafetyRegionChange {
add {
if (instance != null) {
instance.safetyRegionDelegate += value;
}
}
remove {
if (instance != null) {
instance.safetyRegionDelegate -= value;
}
}
}
public static event OnRecenterEvent OnRecenter {
add {
if (instance != null) {
instance.recenterDelegate += value;
}
}
remove {
if (instance != null) {
instance.recenterDelegate -= value;
}
}
}
#endregion // DELEGATE_HANDLERS
#region GVR_STANDALONE_PROPERTIES
/// Returns |true| if the current headset supports positionally tracked, 6DOF head poses.
/// Returns |false| if only rotation-based head poses are supported.
public static bool SupportsPositionalTracking {
get {
if (instance == null) {
return false;
}
return instance.headsetProvider.SupportsPositionalTracking;
}
}
/// If a floor is found, populates floorHeight with the detected height.
/// Otherwise, leaves the value unchanged.
/// Returns true if value retrieval was successful, false otherwise (depends on tracking state).
public static bool TryGetFloorHeight(ref float floorHeight) {
if (instance == null) {
return false;
}
return instance.headsetProvider.TryGetFloorHeight(ref floorHeight);
}
/// If the last recentering transform is available, populates position and rotation with that
/// transform.
/// Returns true if value retrieval was successful, false otherwise (unlikely).
public static bool TryGetRecenterTransform(ref Vector3 position, ref Quaternion rotation) {
if (instance == null) {
return false;
}
return instance.headsetProvider.TryGetRecenterTransform(ref position, ref rotation);
}
/// Populates safetyType with the available safety region feature on the
/// currently-running device.
/// Returns true if value retrieval was successful, false otherwise (unlikely).
public static bool TryGetSafetyRegionType(ref GvrSafetyRegionType safetyType) {
if (instance == null) {
return false;
}
return instance.headsetProvider.TryGetSafetyRegionType(ref safetyType);
}
/// If the safety region is of type GvrSafetyRegionType.Cylinder, populates innerRadius with the
/// inner radius size (where fog starts appearing) of the safety cylinder in meters.
/// Assumes the safety region type has been previously checked by the caller.
/// Returns true if value retrieval was successful, false otherwise (if region type is
/// GvrSafetyRegionType.Invalid).
public static bool TryGetSafetyCylinderInnerRadius(ref float innerRadius) {
if (instance == null) {
return false;
}
return instance.headsetProvider.TryGetSafetyCylinderInnerRadius(ref innerRadius);
}
/// If the safety region is of type GvrSafetyRegionType.Cylinder, populates outerRadius with the
/// outer radius size (where fog is 100% opaque) of the safety cylinder in meters.
/// Assumes the safety region type has been previously checked by the caller.
/// Returns true if value retrieval was successful, false otherwise (if region type is
/// GvrSafetyRegionType.Invalid).
public static bool TryGetSafetyCylinderOuterRadius(ref float outerRadius) {
if (instance == null) {
return false;
}
return instance.headsetProvider.TryGetSafetyCylinderOuterRadius(ref outerRadius);
}
#endregion // GVR_STANDALONE_PROPERTIES
private GvrHeadset() {
headsetState.Initialize();
}
void Awake() {
if (!SupportsPositionalTracking) {
return;
}
if (instance != null) {
Debug.LogError("More than one GvrHeadset instance was found in your scene. "
+ "Ensure that there is only one GvrHeadset.");
this.enabled = false;
return;
}
instance = this;
if (headsetProvider == null) {
headsetProvider = HeadsetProviderFactory.CreateProvider();
}
}
void OnEnable() {
if (!SupportsPositionalTracking) {
return;
}
standaloneUpdate = EndOfFrame();
StartCoroutine(standaloneUpdate);
}
void OnDisable() {
if (!SupportsPositionalTracking) {
return;
}
StopCoroutine(standaloneUpdate);
}
void OnDestroy() {
if (!SupportsPositionalTracking) {
return;
}
instance = null;
}
private void UpdateStandalone() {
// Events are stored in a queue, so poll until we get Invalid.
headsetProvider.PollEventState(ref headsetState);
while (headsetState.eventType != GvrEventType.Invalid) {
switch (headsetState.eventType) {
case GvrEventType.Recenter:
if (recenterDelegate != null) {
recenterDelegate(headsetState.recenterEventType,
(GvrRecenterFlags) headsetState.recenterEventFlags,
headsetState.recenteredPosition,
headsetState.recenteredRotation);
}
break;
case GvrEventType.SafetyRegionEnter:
if (safetyRegionDelegate != null) {
safetyRegionDelegate(true);
}
break;
case GvrEventType.SafetyRegionExit:
if (safetyRegionDelegate != null) {
safetyRegionDelegate(false);
}
break;
case GvrEventType.Invalid:
throw new InvalidEnumArgumentException("Invalid headset event: " + headsetState.eventType);
default: // Fallthrough, should never get here.
break;
}
headsetProvider.PollEventState(ref headsetState);
}
}
IEnumerator EndOfFrame() {
while (true) {
// This must be done at the end of the frame to ensure that all GameObjects had a chance
// to read transient state (e.g. events, etc) for the current frame before it gets reset.
yield return waitForEndOfFrame;
UpdateStandalone();
}
}
}
| |
// Copyright 2007-2012 Chris Patterson, Dru Sellers, Travis Smith, et. al.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed
// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
// CONDITIONS OF ANY KIND, either express or implied. See the License for the
// specific language governing permissions and limitations under the License.
namespace Topshelf.Hosts
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceProcess;
using Logging;
using Runtime;
public class InstallHost :
Host
{
static readonly LogWriter _log = HostLogger.Get<InstallHost>();
readonly HostEnvironment _environment;
readonly InstallHostSettings _installSettings;
readonly IEnumerable<Action<InstallHostSettings>> _postActions;
readonly IEnumerable<Action<InstallHostSettings>> _preActions;
readonly IEnumerable<Action<InstallHostSettings>> _postRollbackActions;
readonly IEnumerable<Action<InstallHostSettings>> _preRollbackActions;
readonly HostSettings _settings;
readonly bool _sudo;
public InstallHost(HostEnvironment environment, HostSettings settings, HostStartMode startMode,
IEnumerable<string> dependencies,
Credentials credentials, IEnumerable<Action<InstallHostSettings>> preActions,
IEnumerable<Action<InstallHostSettings>> postActions,
IEnumerable<Action<InstallHostSettings>> preRollbackActions,
IEnumerable<Action<InstallHostSettings>> postRollbackActions,
bool sudo)
{
_environment = environment;
_settings = settings;
_installSettings = new InstallServiceSettingsImpl(settings, credentials, startMode, dependencies.ToArray());
_preActions = preActions;
_postActions = postActions;
_preRollbackActions = preRollbackActions;
_postRollbackActions = postRollbackActions;
_sudo = sudo;
}
public InstallHostSettings InstallSettings
{
get { return _installSettings; }
}
public HostSettings Settings
{
get { return _settings; }
}
public TopshelfExitCode Run()
{
if (_environment.IsServiceInstalled(_settings.ServiceName))
{
_log.ErrorFormat("The {0} service is already installed.", _settings.ServiceName);
return TopshelfExitCode.ServiceAlreadyInstalled;
}
if (!_environment.IsAdministrator)
{
if (_sudo)
{
if (_environment.RunAsAdministrator())
return TopshelfExitCode.Ok;
}
_log.ErrorFormat("The {0} service can only be installed as an administrator", _settings.ServiceName);
return TopshelfExitCode.SudoRequired;
}
_log.DebugFormat("Attempting to install '{0}'", _settings.ServiceName);
_environment.InstallService(_installSettings, ExecutePreActions, ExecutePostActions, ExecutePreRollbackActions, ExecutePostRollbackActions);
return TopshelfExitCode.Ok;
}
void ExecutePreActions()
{
foreach (Action<InstallHostSettings> action in _preActions)
{
action(_installSettings);
}
}
void ExecutePostActions()
{
foreach (Action<InstallHostSettings> action in _postActions)
{
action(_installSettings);
}
}
void ExecutePreRollbackActions()
{
foreach (Action<InstallHostSettings> action in _preRollbackActions)
{
action(_installSettings);
}
}
void ExecutePostRollbackActions()
{
foreach (Action<InstallHostSettings> action in _postRollbackActions)
{
action(_installSettings);
}
}
class InstallServiceSettingsImpl :
InstallHostSettings
{
readonly Credentials _credentials;
readonly string[] _dependencies;
readonly HostSettings _settings;
readonly HostStartMode _startMode;
public InstallServiceSettingsImpl(HostSettings settings, Credentials credentials, HostStartMode startMode,
string[] dependencies)
{
_credentials = credentials;
_settings = settings;
_startMode = startMode;
_dependencies = dependencies;
}
public string Name
{
get { return _settings.Name; }
}
public string DisplayName
{
get { return _settings.DisplayName; }
}
public string Description
{
get { return _settings.Description; }
}
public string InstanceName
{
get { return _settings.InstanceName; }
}
public string ServiceName
{
get { return _settings.ServiceName; }
}
public bool CanPauseAndContinue
{
get { return _settings.CanPauseAndContinue; }
}
public bool CanShutdown
{
get { return _settings.CanShutdown; }
}
public bool CanSessionChanged
{
get { return _settings.CanSessionChanged; }
}
public ServiceAccount Account
{
get { return _credentials.Account; }
}
public string Username
{
get { return _credentials.Username; }
}
public string Password
{
get { return _credentials.Password; }
}
public string[] Dependencies
{
get { return _dependencies; }
}
public HostStartMode StartMode
{
get { return _startMode; }
}
public TimeSpan StartTimeOut
{
get { return _settings.StartTimeOut; }
}
public TimeSpan StopTimeOut
{
get { return _settings.StopTimeOut; }
}
}
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
namespace Apache.Ignite.Core.Impl
{
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using Apache.Ignite.Core.Cache;
using Apache.Ignite.Core.Cluster;
using Apache.Ignite.Core.Compute;
using Apache.Ignite.Core.Datastream;
using Apache.Ignite.Core.Events;
using Apache.Ignite.Core.Impl.Cache;
using Apache.Ignite.Core.Impl.Cluster;
using Apache.Ignite.Core.Impl.Common;
using Apache.Ignite.Core.Impl.Datastream;
using Apache.Ignite.Core.Impl.Handle;
using Apache.Ignite.Core.Impl.Portable;
using Apache.Ignite.Core.Impl.Transactions;
using Apache.Ignite.Core.Impl.Unmanaged;
using Apache.Ignite.Core.Lifecycle;
using Apache.Ignite.Core.Messaging;
using Apache.Ignite.Core.Portable;
using Apache.Ignite.Core.Services;
using Apache.Ignite.Core.Transactions;
using UU = Apache.Ignite.Core.Impl.Unmanaged.UnmanagedUtils;
/// <summary>
/// Native Ignite wrapper.
/// </summary>
internal class Ignite : IIgnite, IClusterGroupEx, ICluster
{
/** */
private readonly IgniteConfiguration _cfg;
/** Grid name. */
private readonly string _name;
/** Unmanaged node. */
private readonly IUnmanagedTarget _proc;
/** Marshaller. */
private readonly PortableMarshaller _marsh;
/** Initial projection. */
private readonly ClusterGroupImpl _prj;
/** Portables. */
private readonly PortablesImpl _portables;
/** Cached proxy. */
private readonly IgniteProxy _proxy;
/** Lifecycle beans. */
private readonly IList<LifecycleBeanHolder> _lifecycleBeans;
/** Local node. */
private IClusterNode _locNode;
/** Transactions facade. */
private readonly TransactionsImpl _transactions;
/** Callbacks */
private readonly UnmanagedCallbacks _cbs;
/** Node info cache. */
private readonly ConcurrentDictionary<Guid, ClusterNodeImpl> _nodes =
new ConcurrentDictionary<Guid, ClusterNodeImpl>();
/// <summary>
/// Constructor.
/// </summary>
/// <param name="cfg">Configuration.</param>
/// <param name="name">Grid name.</param>
/// <param name="proc">Interop processor.</param>
/// <param name="marsh">Marshaller.</param>
/// <param name="lifecycleBeans">Lifecycle beans.</param>
/// <param name="cbs">Callbacks.</param>
public Ignite(IgniteConfiguration cfg, string name, IUnmanagedTarget proc, PortableMarshaller marsh,
IList<LifecycleBeanHolder> lifecycleBeans, UnmanagedCallbacks cbs)
{
Debug.Assert(cfg != null);
Debug.Assert(proc != null);
Debug.Assert(marsh != null);
Debug.Assert(lifecycleBeans != null);
Debug.Assert(cbs != null);
_cfg = cfg;
_name = name;
_proc = proc;
_marsh = marsh;
_lifecycleBeans = lifecycleBeans;
_cbs = cbs;
marsh.Ignite = this;
_prj = new ClusterGroupImpl(proc, UU.ProcessorProjection(proc), marsh, this, null);
_portables = new PortablesImpl(marsh);
_proxy = new IgniteProxy(this);
cbs.Initialize(this);
_transactions = new TransactionsImpl(UU.ProcessorTransactions(proc), marsh, LocalNode.Id);
}
/// <summary>
/// On-start routine.
/// </summary>
internal void OnStart()
{
foreach (var lifecycleBean in _lifecycleBeans)
lifecycleBean.OnStart(this);
}
/// <summary>
/// Gets Ignite proxy.
/// </summary>
/// <returns>Proxy.</returns>
public IgniteProxy Proxy
{
get { return _proxy; }
}
/** <inheritdoc /> */
public string Name
{
get { return _name; }
}
/** <inheritdoc /> */
public ICluster Cluster
{
get { return this; }
}
/** <inheritdoc /> */
IIgnite IClusterGroup.Ignite
{
get { return this; }
}
/** <inheritdoc /> */
public IClusterGroup ForLocal()
{
return _prj.ForNodes(LocalNode);
}
/** <inheritdoc /> */
public ICompute Compute()
{
return _prj.Compute();
}
/** <inheritdoc /> */
public ICompute Compute(IClusterGroup clusterGroup)
{
IgniteArgumentCheck.NotNull(clusterGroup, "clusterGroup");
return clusterGroup.Compute();
}
/** <inheritdoc /> */
public IClusterGroup ForNodes(IEnumerable<IClusterNode> nodes)
{
return ((IClusterGroup) _prj).ForNodes(nodes);
}
/** <inheritdoc /> */
public IClusterGroup ForNodes(params IClusterNode[] nodes)
{
return _prj.ForNodes(nodes);
}
/** <inheritdoc /> */
public IClusterGroup ForNodeIds(IEnumerable<Guid> ids)
{
return ((IClusterGroup) _prj).ForNodeIds(ids);
}
/** <inheritdoc /> */
public IClusterGroup ForNodeIds(ICollection<Guid> ids)
{
return _prj.ForNodeIds(ids);
}
/** <inheritdoc /> */
public IClusterGroup ForNodeIds(params Guid[] ids)
{
return _prj.ForNodeIds(ids);
}
/** <inheritdoc /> */
public IClusterGroup ForPredicate(Func<IClusterNode, bool> p)
{
IgniteArgumentCheck.NotNull(p, "p");
return _prj.ForPredicate(p);
}
/** <inheritdoc /> */
public IClusterGroup ForAttribute(string name, string val)
{
return _prj.ForAttribute(name, val);
}
/** <inheritdoc /> */
public IClusterGroup ForCacheNodes(string name)
{
return _prj.ForCacheNodes(name);
}
/** <inheritdoc /> */
public IClusterGroup ForDataNodes(string name)
{
return _prj.ForDataNodes(name);
}
/** <inheritdoc /> */
public IClusterGroup ForClientNodes(string name)
{
return _prj.ForClientNodes(name);
}
/** <inheritdoc /> */
public IClusterGroup ForRemotes()
{
return _prj.ForRemotes();
}
/** <inheritdoc /> */
public IClusterGroup ForHost(IClusterNode node)
{
IgniteArgumentCheck.NotNull(node, "node");
return _prj.ForHost(node);
}
/** <inheritdoc /> */
public IClusterGroup ForRandom()
{
return _prj.ForRandom();
}
/** <inheritdoc /> */
public IClusterGroup ForOldest()
{
return _prj.ForOldest();
}
/** <inheritdoc /> */
public IClusterGroup ForYoungest()
{
return _prj.ForYoungest();
}
/** <inheritdoc /> */
public IClusterGroup ForDotNet()
{
return _prj.ForDotNet();
}
/** <inheritdoc /> */
public ICollection<IClusterNode> Nodes()
{
return _prj.Nodes();
}
/** <inheritdoc /> */
public IClusterNode Node(Guid id)
{
return _prj.Node(id);
}
/** <inheritdoc /> */
public IClusterNode Node()
{
return _prj.Node();
}
/** <inheritdoc /> */
public IClusterMetrics Metrics()
{
return _prj.Metrics();
}
/** <inheritdoc /> */
public void Dispose()
{
Ignition.Stop(Name, true);
}
/// <summary>
/// Internal stop routine.
/// </summary>
/// <param name="cancel">Cancel flag.</param>
internal unsafe void Stop(bool cancel)
{
UU.IgnitionStop(_proc.Context, Name, cancel);
_cbs.Cleanup();
foreach (var bean in _lifecycleBeans)
bean.OnLifecycleEvent(LifecycleEventType.AfterNodeStop);
}
/** <inheritdoc /> */
public ICache<TK, TV> Cache<TK, TV>(string name)
{
return Cache<TK, TV>(UU.ProcessorCache(_proc, name));
}
/** <inheritdoc /> */
public ICache<TK, TV> GetOrCreateCache<TK, TV>(string name)
{
return Cache<TK, TV>(UU.ProcessorGetOrCreateCache(_proc, name));
}
/** <inheritdoc /> */
public ICache<TK, TV> CreateCache<TK, TV>(string name)
{
return Cache<TK, TV>(UU.ProcessorCreateCache(_proc, name));
}
/// <summary>
/// Gets cache from specified native cache object.
/// </summary>
/// <param name="nativeCache">Native cache.</param>
/// <param name="keepPortable">Portable flag.</param>
/// <returns>
/// New instance of cache wrapping specified native cache.
/// </returns>
public ICache<TK, TV> Cache<TK, TV>(IUnmanagedTarget nativeCache, bool keepPortable = false)
{
var cacheImpl = new CacheImpl<TK, TV>(this, nativeCache, _marsh, false, keepPortable, false, false);
return new CacheProxyImpl<TK, TV>(cacheImpl);
}
/** <inheritdoc /> */
public IClusterNode LocalNode
{
get
{
if (_locNode == null)
{
foreach (IClusterNode node in Nodes())
{
if (node.IsLocal)
{
_locNode = node;
break;
}
}
}
return _locNode;
}
}
/** <inheritdoc /> */
public bool PingNode(Guid nodeId)
{
return _prj.PingNode(nodeId);
}
/** <inheritdoc /> */
public long TopologyVersion
{
get { return _prj.TopologyVersion; }
}
/** <inheritdoc /> */
public ICollection<IClusterNode> Topology(long ver)
{
return _prj.Topology(ver);
}
/** <inheritdoc /> */
public void ResetMetrics()
{
UU.ProjectionResetMetrics(_prj.Target);
}
/** <inheritdoc /> */
public IDataStreamer<TK, TV> DataStreamer<TK, TV>(string cacheName)
{
return new DataStreamerImpl<TK, TV>(UU.ProcessorDataStreamer(_proc, cacheName, false),
_marsh, cacheName, false);
}
/** <inheritdoc /> */
public IPortables Portables()
{
return _portables;
}
/** <inheritdoc /> */
public ICacheAffinity Affinity(string cacheName)
{
return new CacheAffinityImpl(UU.ProcessorAffinity(_proc, cacheName), _marsh, false, this);
}
/** <inheritdoc /> */
public ITransactions Transactions
{
get { return _transactions; }
}
/** <inheritdoc /> */
public IMessaging Message()
{
return _prj.Message();
}
/** <inheritdoc /> */
public IMessaging Message(IClusterGroup clusterGroup)
{
IgniteArgumentCheck.NotNull(clusterGroup, "clusterGroup");
return clusterGroup.Message();
}
/** <inheritdoc /> */
public IEvents Events()
{
return _prj.Events();
}
/** <inheritdoc /> */
public IEvents Events(IClusterGroup clusterGroup)
{
if (clusterGroup == null)
throw new ArgumentNullException("clusterGroup");
return clusterGroup.Events();
}
/** <inheritdoc /> */
public IServices Services()
{
return _prj.Services();
}
/// <summary>
/// Gets internal projection.
/// </summary>
/// <returns>Projection.</returns>
internal ClusterGroupImpl ClusterGroup
{
get { return _prj; }
}
/// <summary>
/// Marshaller.
/// </summary>
internal PortableMarshaller Marshaller
{
get { return _marsh; }
}
/// <summary>
/// Configuration.
/// </summary>
internal IgniteConfiguration Configuration
{
get { return _cfg; }
}
/// <summary>
/// Put metadata to Grid.
/// </summary>
/// <param name="metas">Metadata.</param>
internal void PutMetadata(IDictionary<int, IPortableMetadata> metas)
{
_prj.PutMetadata(metas);
}
/** <inheritDoc /> */
public IPortableMetadata Metadata(int typeId)
{
return _prj.Metadata(typeId);
}
/// <summary>
/// Handle registry.
/// </summary>
public HandleRegistry HandleRegistry
{
get { return _cbs.HandleRegistry; }
}
/// <summary>
/// Updates the node information from stream.
/// </summary>
/// <param name="memPtr">Stream ptr.</param>
public void UpdateNodeInfo(long memPtr)
{
var stream = IgniteManager.Memory.Get(memPtr).Stream();
IPortableRawReader reader = Marshaller.StartUnmarshal(stream, false);
var node = new ClusterNodeImpl(reader);
node.Init(this);
_nodes[node.Id] = node;
}
/// <summary>
/// Gets the node from cache.
/// </summary>
/// <param name="id">Node id.</param>
/// <returns>Cached node.</returns>
public ClusterNodeImpl GetNode(Guid? id)
{
return id == null ? null : _nodes[id.Value];
}
/// <summary>
/// Gets the interop processor.
/// </summary>
internal IUnmanagedTarget InteropProcessor
{
get { return _proc; }
}
}
}
| |
#region Templates
CodeTemplates.Add("NetTiersMapInstance.Internal.cst", base.CreateTemplate<MappingInstance>()); this.PerformStep();
CodeTemplates.Add("vsnet2005.project.cst", base.CreateTemplate<vsnet2005Project>()); this.PerformStep();
CodeTemplates.Add("vsnet2005.solution.cst", base.CreateTemplate<vsnet2005Solution>()); this.PerformStep();
CodeTemplates.Add("vsnet2005.vsmdi.cst", base.CreateTemplate<vsnet2005Vsmdi>()); this.PerformStep();
CodeTemplates.Add("vsnet2005.localtestrun.testrunconfig.cst", base.CreateTemplate<vsnet2005LocaltestrunTestrunconfig>()); this.PerformStep();
CodeTemplates.Add("nAnt.cst", base.CreateTemplate<nAnt>()); this.PerformStep();
CodeTemplates.Add("AssemblyInfo.cst", base.CreateTemplate<AssemblyInfo>()); this.PerformStep();
CodeTemplates.Add("entlib.v3_1.config.cst", base.CreateTemplate<entlibv3_1config>()); this.PerformStep();
CodeTemplates.Add("entlib.v5_0.config.cst", base.CreateTemplate<entlibv5_0config>()); this.PerformStep();
CodeTemplates.Add("WeakRefDictionary.cst", base.CreateTemplate<WeakRefDictionary>()); this.PerformStep();
CodeTemplates.Add("App.config.2005.cst", base.CreateTemplate<AppConfig>()); this.PerformStep();
CodeTemplates.Add("Enum.cst", base.CreateTemplate<Enum>()); this.PerformStep();
CodeTemplates.Add("IEntity.cst", base.CreateTemplate<IEntity>()); this.PerformStep();
CodeTemplates.Add("IEntityId.cst", base.CreateTemplate<IEntityId>()); this.PerformStep();
CodeTemplates.Add("IEntityKey.cst", base.CreateTemplate<IEntityKey>()); this.PerformStep();
CodeTemplates.Add("EntityBase.cst", base.CreateTemplate<EntityBase>()); this.PerformStep();
CodeTemplates.Add("EntityBaseCore.generated.cst", base.CreateTemplate<EntityBaseCoreGenerated>()); this.PerformStep();
CodeTemplates.Add("EntityKeyBase.cst", base.CreateTemplate<EntityKeyBase>()); this.PerformStep();
CodeTemplates.Add("EntityKeyBaseCore.generated.cst", base.CreateTemplate<EntityKeyBaseCoreGenerated>()); this.PerformStep();
CodeTemplates.Add("EntityFilter.cst", base.CreateTemplate<EntityFilter>()); this.PerformStep();
CodeTemplates.Add("EntityHelper.cst", base.CreateTemplate<EntityHelper>()); this.PerformStep();
CodeTemplates.Add("EntityUtil.cst", base.CreateTemplate<EntityUtil>()); this.PerformStep();
CodeTemplates.Add("EntityPropertyComparer.cst", base.CreateTemplate<EntityPropertyComparer>()); this.PerformStep();
CodeTemplates.Add("GenericTypeConverter.cst", base.CreateTemplate<GenericTypeConverter>()); this.PerformStep();
CodeTemplates.Add("EntityFactory.cst", base.CreateTemplate<EntityFactory>()); this.PerformStep();
CodeTemplates.Add("EntityFactoryBase.cst", base.CreateTemplate<EntityFactoryBase>()); this.PerformStep();
CodeTemplates.Add("EntityCache.cst", base.CreateTemplate<EntityCache>()); this.PerformStep();
CodeTemplates.Add("EntityLocator.cst", base.CreateTemplate<EntityLocator>()); this.PerformStep();
CodeTemplates.Add("EntityLocator_EntLib5.cst", base.CreateTemplate<EntityLocator_EntLib5>()); this.PerformStep();
CodeTemplates.Add("EntityManager.cst", base.CreateTemplate<EntityManager>()); this.PerformStep();
CodeTemplates.Add("EntityManager_EntLib5.cst", base.CreateTemplate<EntityManager_EntLib5>()); this.PerformStep();
CodeTemplates.Add("IEntityFactory.cst", base.CreateTemplate<IEntityFactory>()); this.PerformStep();
CodeTemplates.Add("IEntityCacheItem.cst", base.CreateTemplate<IEntityCacheItem>()); this.PerformStep();
CodeTemplates.Add("EntityInstanceBase.generated.cst", base.CreateTemplate<EntityInstanceBaseGenerated>()); this.PerformStep();
CodeTemplates.Add("IEntityInstance.cst", base.CreateTemplate<IEntityInstance>()); this.PerformStep();
CodeTemplates.Add("EntityData.cst", base.CreateTemplate<EntityData>()); this.PerformStep();
CodeTemplates.Add("EntityInstance.cst", base.CreateTemplate<EntityInstance>()); this.PerformStep();
CodeTemplates.Add("TList.cst", base.CreateTemplate<TList>()); this.PerformStep();
CodeTemplates.Add("ListBase.cst", base.CreateTemplate<ListBase>()); this.PerformStep();
CodeTemplates.Add("VList.cst", base.CreateTemplate<VList>()); this.PerformStep();
CodeTemplates.Add("EntityViewBase.generated.cst", base.CreateTemplate<EntityViewBaseGenerated>()); this.PerformStep();
CodeTemplates.Add("EntityView.cst", base.CreateTemplate<EntityView>()); this.PerformStep();
CodeTemplates.Add("BrokenRule.cst", base.CreateTemplate<BrokenRule>()); this.PerformStep();
CodeTemplates.Add("BrokenRulesList.cst", base.CreateTemplate<BrokenRulesList>()); this.PerformStep();
CodeTemplates.Add("CommonRules.cst", base.CreateTemplate<CommonRules>()); this.PerformStep();
CodeTemplates.Add("ValidationRuleArgs.cst", base.CreateTemplate<ValidationRuleArgs>()); this.PerformStep();
CodeTemplates.Add("ValidationRuleHandler.cst", base.CreateTemplate<ValidationRuleHandler>()); this.PerformStep();
CodeTemplates.Add("ValidationRuleInfo.cst", base.CreateTemplate<ValidationRuleInfo>()); this.PerformStep();
CodeTemplates.Add("ValidationRules.cst", base.CreateTemplate<ValidationRules>()); this.PerformStep();
CodeTemplates.Add("PropertyValidator.cst", base.CreateTemplate<PropertyValidator>()); this.PerformStep();
CodeTemplates.Add("PropertyValidatorValueAccess.cst", base.CreateTemplate<PropertyValidatorValueAccess>()); this.PerformStep();
CodeTemplates.Add("PropertyValidatorValueAccessBuilder.cst", base.CreateTemplate<PropertyValidatorValueAccessBuilder>()); this.PerformStep();
CodeTemplates.Add("Component.cst", base.CreateTemplate<Component>()); this.PerformStep();
CodeTemplates.Add("ComponentBase.cst", base.CreateTemplate<ComponentBase>()); this.PerformStep();
CodeTemplates.Add("ComponentService.cst", base.CreateTemplate<ComponentService>()); this.PerformStep();
CodeTemplates.Add("ComponentServiceBase.cst", base.CreateTemplate<ComponentServiceBase>()); this.PerformStep();
CodeTemplates.Add("ComponentViewService.cst", base.CreateTemplate<ComponentViewService>()); this.PerformStep();
CodeTemplates.Add("ComponentViewServiceBase.cst", base.CreateTemplate<ComponentViewServiceBase>()); this.PerformStep();
CodeTemplates.Add("ComponentDataAccess.cst", base.CreateTemplate<ComponentDataAccess>()); this.PerformStep();
CodeTemplates.Add("ComponentViewDataAccess.cst", base.CreateTemplate<ComponentViewDataAccess>()); this.PerformStep();
CodeTemplates.Add("ComponentView.cst", base.CreateTemplate<ComponentView>()); this.PerformStep();
CodeTemplates.Add("ComponentViewBase.cst", base.CreateTemplate<ComponentViewBase>()); this.PerformStep();
CodeTemplates.Add("IComponentEntity.cst", base.CreateTemplate<IComponentEntity>()); this.PerformStep();
CodeTemplates.Add("IConnectionScope.cst", base.CreateTemplate<IConnectionScope>()); this.PerformStep();
CodeTemplates.Add("ConnectionScope.cst", base.CreateTemplate<ConnectionScope>()); this.PerformStep();
CodeTemplates.Add("ConnectionScopeBase.cst", base.CreateTemplate<ConnectionScopeBase>()); this.PerformStep();
CodeTemplates.Add("DomainUtil.cst", base.CreateTemplate<DomainUtil>()); this.PerformStep();
CodeTemplates.Add("IComponentService.cst", base.CreateTemplate<IComponentService>()); this.PerformStep();
CodeTemplates.Add("ServiceBase.cst", base.CreateTemplate<ServiceBase>()); this.PerformStep();
CodeTemplates.Add("ServiceBaseCore.cst", base.CreateTemplate<ServiceBaseCore>()); this.PerformStep();
CodeTemplates.Add("ServiceViewBase.cst", base.CreateTemplate<ServiceViewBase>()); this.PerformStep();
CodeTemplates.Add("ServiceViewBaseCore.cst", base.CreateTemplate<ServiceViewBaseCore>()); this.PerformStep();
CodeTemplates.Add("ServiceResult.cst", base.CreateTemplate<ServiceResult>()); this.PerformStep();
CodeTemplates.Add("ComponentEntityFactory.cst", base.CreateTemplate<ComponentEntityFactory>()); this.PerformStep();
CodeTemplates.Add("IProcessor.cst", base.CreateTemplate<IProcessor>()); this.PerformStep();
CodeTemplates.Add("IProcessorResult.cst", base.CreateTemplate<IProcessorResult>()); this.PerformStep();
CodeTemplates.Add("ProcessorBase.cst", base.CreateTemplate<ProcessorBase>()); this.PerformStep();
CodeTemplates.Add("GenericProcessorResult.cst", base.CreateTemplate<GenericProcessorResult>()); this.PerformStep();
CodeTemplates.Add("SecurityContext.cst", base.CreateTemplate<SecurityContext>()); this.PerformStep();
CodeTemplates.Add("SecurityContextBase.cst", base.CreateTemplate<SecurityContextBase>()); this.PerformStep();
CodeTemplates.Add("ContextView.cst", base.CreateTemplate<ContextView>()); this.PerformStep();
CodeTemplates.Add("DataRepository.cst", base.CreateTemplate<DataRepository>()); this.PerformStep();
CodeTemplates.Add("Utility.cst", base.CreateTemplate<Utility>()); this.PerformStep();
CodeTemplates.Add("ITransactionManager.cst", base.CreateTemplate<ITransactionManager>()); this.PerformStep();
CodeTemplates.Add("TransactionManager.cst", base.CreateTemplate<TransactionManager>()); this.PerformStep();
CodeTemplates.Add("FileConfigurationSouce_EntLib5.cst", base.CreateTemplate<FileConfigurationSouce_EntLib5>()); this.PerformStep();
CodeTemplates.Add("FileConfigurationSouceElement_EntLib5.cst", base.CreateTemplate<FileConfigurationSouceElement_EntLib5>()); this.PerformStep();
CodeTemplates.Add("IEntityProvider.cst", base.CreateTemplate<IEntityProvider>()); this.PerformStep();
CodeTemplates.Add("IEntityViewProvider.cst", base.CreateTemplate<IEntityViewProvider>()); this.PerformStep();
CodeTemplates.Add("INetTiersProvider.cst", base.CreateTemplate<INetTiersProvider>()); this.PerformStep();
CodeTemplates.Add("NetTiersProvider.cst", base.CreateTemplate<NetTiersProvider>()); this.PerformStep();
CodeTemplates.Add("NetTiersProviderBase.cst", base.CreateTemplate<NetTiersProviderBase>()); this.PerformStep();
CodeTemplates.Add("NetTiersProviderCollection.cst", base.CreateTemplate<NetTiersProviderCollection>()); this.PerformStep();
CodeTemplates.Add("NetTiersServiceSection.cst", base.CreateTemplate<NetTiersServiceSection>()); this.PerformStep();
CodeTemplates.Add("EntityProviderBaseCore.generated.cst", base.CreateTemplate<EntityProviderBaseCoreGenerated>()); this.PerformStep();
CodeTemplates.Add("EntityProviderBase.cst", base.CreateTemplate<EntityProviderBase>()); this.PerformStep();
CodeTemplates.Add("EntityViewProviderBase.cst", base.CreateTemplate<EntityViewProviderBase>()); this.PerformStep();
CodeTemplates.Add("EntityViewProviderBaseCore.generated.cst", base.CreateTemplate<EntityViewProviderBaseCoreGenerated>()); this.PerformStep();
CodeTemplates.Add("EntityProviderBaseClass.cst", base.CreateTemplate<EntityProviderBaseClass>()); this.PerformStep();
CodeTemplates.Add("EntityProviderBaseCoreClass.generated.cst", base.CreateTemplate<EntityProviderBaseCoreClassGenerated>()); this.PerformStep();
CodeTemplates.Add("EntityViewProviderBaseClass.cst", base.CreateTemplate<EntityViewProviderBaseClass>()); this.PerformStep();
CodeTemplates.Add("EntityViewProviderBaseCoreClass.generated.cst", base.CreateTemplate<EntityViewProviderBaseCoreClassGenerated>()); this.PerformStep();
CodeTemplates.Add("ExpressionParserBase.cst", base.CreateTemplate<ExpressionParserBase>()); this.PerformStep();
CodeTemplates.Add("SqlExpressionParser.cst", base.CreateTemplate<SqlExpressionParser>()); this.PerformStep();
CodeTemplates.Add("SqlStringBuilder.cst", base.CreateTemplate<SqlStringBuilder>()); this.PerformStep();
CodeTemplates.Add("SqlUtil.cst", base.CreateTemplate<SqlUtil>()); this.PerformStep();
CodeTemplates.Add("StringTokenizer.cst", base.CreateTemplate<StringTokenizer>()); this.PerformStep();
CodeTemplates.Add("SqlNetTiersProvider.cst", base.CreateTemplate<SqlNetTiersProvider>()); this.PerformStep();
CodeTemplates.Add("SqlEntityProviderBase.generated.cst", base.CreateTemplate<SqlEntityProviderBaseGenerated>()); this.PerformStep();
CodeTemplates.Add("SqlEntityProvider.cst", base.CreateTemplate<SqlEntityProvider>()); this.PerformStep();
CodeTemplates.Add("StoredProcedureProvider.cst", base.CreateTemplate<StoredProcedureProvider>()); this.PerformStep();
CodeTemplates.Add("StoredProceduresXml.cst", base.CreateTemplate<StoredProceduresXml>()); this.PerformStep();
CodeTemplates.Add("SqlEntityViewProviderBase.generated.cst", base.CreateTemplate<SqlEntityViewProviderBaseGenerated>()); this.PerformStep();
CodeTemplates.Add("SqlEntityViewProvider.cst", base.CreateTemplate<SqlEntityViewProvider>()); this.PerformStep();
CodeTemplates.Add("GenericEntityViewProviderBase.generated.cst", base.CreateTemplate<GenericEntityViewProviderBaseGenerated>()); this.PerformStep();
CodeTemplates.Add("GenericEntityViewProvider.cst", base.CreateTemplate<GenericEntityViewProvider>()); this.PerformStep();
CodeTemplates.Add("GenericNetTiersProvider.cst", base.CreateTemplate<GenericNetTiersProvider>()); this.PerformStep();
CodeTemplates.Add("GenericEntityProviderBase.generated.cst", base.CreateTemplate<GenericEntityProviderBaseGenerated>()); this.PerformStep();
CodeTemplates.Add("GenericEntityProvider.cst", base.CreateTemplate<GenericEntityProvider>()); this.PerformStep();
CodeTemplates.Add("DbCommandManager.cst", base.CreateTemplate<DbCommandManager>()); this.PerformStep();
CodeTemplates.Add("System.Data.SQLite.Procedures.cst", base.CreateTemplate<SystemDataSQLiteProcedures>()); this.PerformStep();
CodeTemplates.Add("System.Data.OleDb.Procedures.cst", base.CreateTemplate<SystemDataOleDbProcedures>()); this.PerformStep();
CodeTemplates.Add("MySql.Data.MySqlClient.Procedures.cst", base.CreateTemplate<MySqlDataMySqlClientProcedures>()); this.PerformStep();
CodeTemplates.Add("System.Data.Oracle.Procedures.cst", base.CreateTemplate<SystemDataOracleProcedures>()); this.PerformStep();
CodeTemplates.Add("ServiceLayer.WebService.cst", base.CreateTemplate<ServiceLayerWebService>()); this.PerformStep();
CodeTemplates.Add("WebService.cst", base.CreateTemplate<WebService>()); this.PerformStep();
//CodeTemplates.Add("WebInfo.cst", base.CreateTemplate<WebInfo>()); this.PerformStep();
CodeTemplates.Add("WsNetTiersProvider.cst", base.CreateTemplate<WsNetTiersProvider>()); this.PerformStep();
CodeTemplates.Add("WsEntityProvider.cst", base.CreateTemplate<WsEntityProvider>()); this.PerformStep();
CodeTemplates.Add("WsEntityProviderBase.generated.cst", base.CreateTemplate<WsEntityProviderBaseGenerated>()); this.PerformStep();
CodeTemplates.Add("WsEntityViewProvider.cst", base.CreateTemplate<WsEntityViewProvider>()); this.PerformStep();
CodeTemplates.Add("WsEntityViewProviderBase.generated.cst", base.CreateTemplate<WsEntityViewProviderBaseGenerated>()); this.PerformStep();
CodeTemplates.Add("EntityRepositoryTest.cst", base.CreateTemplate<EntityRepositoryTest>()); this.PerformStep();
CodeTemplates.Add("EntityRepositoryTest.generated.cst", base.CreateTemplate<EntityRepositoryTestGenerated>()); this.PerformStep();
CodeTemplates.Add("EntityViewRepositoryTest.cst", base.CreateTemplate<EntityViewRepositoryTest>()); this.PerformStep();
CodeTemplates.Add("EntityViewRepositoryTest.generated.cst", base.CreateTemplate<EntityViewRepositoryTestGenerated>()); this.PerformStep();
CodeTemplates.Add("OrderedEntityRepositoryTestList.cst", base.CreateTemplate<OrderedEntityRepositoryTestList>()); this.PerformStep();
CodeTemplates.Add("OrderedEntityViewRepositoryTestList.cst", base.CreateTemplate<OrderedEntityViewRepositoryTestList>()); this.PerformStep();
CodeTemplates.Add("TestUtility.cst", base.CreateTemplate<TestUtility>()); this.PerformStep();
CodeTemplates.Add("AdminEntityUC_Designer.cst", base.CreateTemplate<AdminEntityUC_Designer>()); this.PerformStep();
CodeTemplates.Add("AdminEntityUC_CodeBehind.cst", base.CreateTemplate<AdminEntityUC_CodeBehind>()); this.PerformStep();
CodeTemplates.Add("Menu_xml.cst", base.CreateTemplate<Menu_xml>()); this.PerformStep();
CodeTemplates.Add("Default.aspx.cs.cst", base.CreateTemplate<DefaultAspxCs>()); this.PerformStep();
CodeTemplates.Add("Default.aspx.cst", base.CreateTemplate<DefaultAspx>()); this.PerformStep();
CodeTemplates.Add("WebConfig.cst", base.CreateTemplate<WebConfig>()); this.PerformStep();
CodeTemplates.Add("WebConfigAtlas.cst", base.CreateTemplate<WebConfigAtlas>()); this.PerformStep();
CodeTemplates.Add("Default.aspx.designer.cs.cst", base.CreateTemplate<DefaultAspxDesigner>()); this.PerformStep();
CodeTemplates.Add("BaseDataSource.cst", base.CreateTemplate<BaseDataSource>()); this.PerformStep();
CodeTemplates.Add("BaseDataSourceDesigner.cst", base.CreateTemplate<BaseDataSourceDesigner>()); this.PerformStep();
CodeTemplates.Add("CustomDataSource.cst", base.CreateTemplate<CustomDataSource>()); this.PerformStep();
CodeTemplates.Add("CustomDataSourceDesigner.cst", base.CreateTemplate<CustomDataSourceDesigner>()); this.PerformStep();
CodeTemplates.Add("CustomParameter.cst", base.CreateTemplate<CustomParameter>()); this.PerformStep();
CodeTemplates.Add("DataParameter.cst", base.CreateTemplate<DataParameter>()); this.PerformStep();
CodeTemplates.Add("EntityDataSource.cst", base.CreateTemplate<EntityDataSource>()); this.PerformStep();
CodeTemplates.Add("EntityDataSourceFilter.cst", base.CreateTemplate<EntityDataSourceFilter>()); this.PerformStep();
CodeTemplates.Add("EntityRelationship.cst", base.CreateTemplate<EntityRelationship>()); this.PerformStep();
CodeTemplates.Add("EntityRelationshipMember.cst", base.CreateTemplate<EntityRelationshipMember>()); this.PerformStep();
CodeTemplates.Add("EntityTransactionModule.cst", base.CreateTemplate<EntityTransactionModule>()); this.PerformStep();
CodeTemplates.Add("ILinkedDataSource.cst", base.CreateTemplate<ILinkedDataSource>()); this.PerformStep();
CodeTemplates.Add("ManyToManyListRelationship.cst", base.CreateTemplate<ManyToManyListRelationship>()); this.PerformStep();
CodeTemplates.Add("ManyToManyViewRelationship.cst", base.CreateTemplate<ManyToManyViewRelationship>()); this.PerformStep();
CodeTemplates.Add("OneToManyGridRelationship.cst", base.CreateTemplate<OneToManyGridRelationship>()); this.PerformStep();
CodeTemplates.Add("OneToOneViewRelationship.cst", base.CreateTemplate<OneToOneViewRelationship>()); this.PerformStep();
CodeTemplates.Add("ProviderDataSource.cst", base.CreateTemplate<ProviderDataSource>()); this.PerformStep();
CodeTemplates.Add("ProviderDataSourceDesigner.cst", base.CreateTemplate<ProviderDataSourceDesigner>()); this.PerformStep();
CodeTemplates.Add("ReadOnlyDataSource.cst", base.CreateTemplate<ReadOnlyDataSource>()); this.PerformStep();
CodeTemplates.Add("ReadOnlyDataSourceDesigner.cst", base.CreateTemplate<ReadOnlyDataSourceDesigner>()); this.PerformStep();
CodeTemplates.Add("SqlParameter.cst", base.CreateTemplate<SqlParameter>()); this.PerformStep();
CodeTemplates.Add("TableDataSource.cst", base.CreateTemplate<TableDataSource>()); this.PerformStep();
CodeTemplates.Add("ViewDataSource.cst", base.CreateTemplate<ViewDataSource>()); this.PerformStep();
CodeTemplates.Add("FormUtil.cst", base.CreateTemplate<FormUtil>()); this.PerformStep();
CodeTemplates.Add("FormUtilBase.cst", base.CreateTemplate<FormUtilBase>()); this.PerformStep();
CodeTemplates.Add("MultiBindableTemplate.cst", base.CreateTemplate<MultiBindableTemplate>()); this.PerformStep();
CodeTemplates.Add("MultiFormView.cst", base.CreateTemplate<MultiFormView>()); this.PerformStep();
CodeTemplates.Add("EntityGridView.cs.cst", base.CreateTemplate<EntityGridView>()); this.PerformStep();
CodeTemplates.Add("EntityDropDownList.cs.cst", base.CreateTemplate<EntityDropDownList>()); this.PerformStep();
CodeTemplates.Add("BoundEntityDropDownField.cs.cst", base.CreateTemplate<BoundEntityDropDownField>()); this.PerformStep();
CodeTemplates.Add("BoundRadioButtonField.cs.cst", base.CreateTemplate<BoundRadioButtonField>()); this.PerformStep();
CodeTemplates.Add("GridViewSearchPanel.cs.cst", base.CreateTemplate<GridViewSearchPanel>()); this.PerformStep();
CodeTemplates.Add("GridViewSearchPanelState.cs.cst", base.CreateTemplate<GridViewSearchPanelState>()); this.PerformStep();
CodeTemplates.Add("EntityLabel.cs.cst", base.CreateTemplate<EntityLabel>()); this.PerformStep();
CodeTemplates.Add("HyperlinkField.cs.cst", base.CreateTemplate<HyperlinkField>()); this.PerformStep();
CodeTemplates.Add("TableRepeater.cst", base.CreateTemplate<TableRepeater>()); this.PerformStep();
CodeTemplates.Add("ViewRepeater.cst", base.CreateTemplate<ViewRepeater>()); this.PerformStep();
CodeTemplates.Add("Entity.aspx.cst", base.CreateTemplate<EntityAspx>()); this.PerformStep();
CodeTemplates.Add("Entity.aspx.cs.cst", base.CreateTemplate<EntityAspxCs>()); this.PerformStep();
CodeTemplates.Add("EntityEdit.aspx.cst", base.CreateTemplate<EntityEditAspx>()); this.PerformStep();
CodeTemplates.Add("EntityEdit.aspx.cs.cst", base.CreateTemplate<EntityEditAspxCs>()); this.PerformStep();
CodeTemplates.Add("EntityFields.ascx.cst", base.CreateTemplate<EntityFieldsAscx>()); this.PerformStep();
CodeTemplates.Add("Web.Sitemap.cst", base.CreateTemplate<WebSitemap>()); this.PerformStep();
CodeTemplates.Add("admin.master.cst", base.CreateTemplate<SiteMaster>()); this.PerformStep();
CodeTemplates.Add("TableEditControl.cst", base.CreateTemplate<TableEditControl>()); this.PerformStep();
CodeTemplates.Add("TableEditControlBase.cst", base.CreateTemplate<TableEditControlBase>()); this.PerformStep();
CodeTemplates.Add("TableGridView.cst", base.CreateTemplate<TableGridView>()); this.PerformStep();
CodeTemplates.Add("TableGridViewBase.cst", base.CreateTemplate<TableGridViewBase>()); this.PerformStep();
CodeTemplates.Add("TypedDataSource.cst", base.CreateTemplate<TypedDataSource>()); this.PerformStep();
CodeTemplates.Add("EntityMembershipProvider.cst", base.CreateTemplate<EntityMembershipProvider>()); this.PerformStep();
CodeTemplates.Add("EntityMembershipUser.cst", base.CreateTemplate<EntityMembershipUser>()); this.PerformStep();
CodeTemplates.Add("EntityMembershipProperty.cst", base.CreateTemplate<EntityMembershipProperty>()); this.PerformStep();
CodeTemplates.Add("OracleNetTiersProvider.cst", base.CreateTemplate<OracleNetTiersProvider>()); this.PerformStep();
CodeTemplates.Add("OracleEntityProvider.cst", base.CreateTemplate<OracleEntityProvider>()); this.PerformStep();
CodeTemplates.Add("OracleEntityProviderBase.generated.cst", base.CreateTemplate<OracleEntityProviderBaseGenerated>()); this.PerformStep();
CodeTemplates.Add("OracleEntityViewProvider.cst", base.CreateTemplate<OracleEntityViewProvider>()); this.PerformStep();
CodeTemplates.Add("OracleEntityViewProviderBase.generated.cst", base.CreateTemplate<OracleEntityViewProviderBaseGenerated>()); this.PerformStep();
CodeTemplates.Add("SqlCeNetTiersProvider.cst", base.CreateTemplate<SqlCeNetTiersProvider>()); this.PerformStep();
CodeTemplates.Add("SqlCeEntityProvider.cst", base.CreateTemplate<SqlCeEntityProvider>()); this.PerformStep();
CodeTemplates.Add("SqlCeEntityProviderBase.generated.cst", base.CreateTemplate<SqlCeEntityProviderBaseGenerated>()); this.PerformStep();
CodeTemplates.Add("SqlCeStoredProcedureProvider.cst", base.CreateTemplate<SqlCeStoredProcedureProvider>()); this.PerformStep();
CodeTemplates.Add("SqlCeStoredProceduresXml.cst", base.CreateTemplate<SqlCeStoredProceduresXml>()); this.PerformStep();
#endregion
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
#region Compact Binary format
/*
.----------.--------------. .----------.---------.
struct (v1) | fields | BT_STOP_BASE |...| fields | BT_STOP |
'----------'--------------' '----------'---------'
.----------.----------.--------------. .----------.---------.
struct (v2) | length | fields | BT_STOP_BASE |...| fields | BT_STOP |
'----------'----------'--------------' '----------'---------'
length variable int encoded uint32 length of following fields, up to and
including BT_STOP but excluding length itself.
.----------.----------. .----------.
fields | field | field |...| field |
'----------'----------' '----------'
.----------.----------.
field | id+type | value |
'----------'----------'
.---.---.---.---.---.---.---.---. i - id bits
id+type 0 <= id <= 5 | i | i | i | t | t | t | t | t | t - type bits
'---'---'---'---'---'---'---'---' v - value bits
2 0 4 0
.---.---.---.---.---.---.---.---.---. .---.
5 < id <= 0xff | 1 | 1 | 0 | t | t | t | t | t | i |...| i |
'---'---'---'---'---'---'---'---'---' '---'
4 0 7 0
.---.---.---.---.---.---.---.---.---. .---.---. .---.
0xff < id <= 0xffff | 1 | 1 | 1 | t | t | t | t | t | i |...| i | i |...| i |
'---'---'---'---'---'---'---'---'---' '---'---' '---'
4 0 7 0 15 8
.---.---.---.---.---.---.---.---.
value bool | | | | | | | | v |
'---'---'---'---'---'---'---'---'
0
.---.---.---.---.---.---.---.---.
int8, uint8 | v | v | v | v | v | v | v | v |
'---'---'---'---'---'---'---'---'
7 0
.---.---. .---.---.---. .---.
uint16, uint32, | 1 | v |...| v | 0 | v |...| v | [...]
uint64 '---'---' '---'---'---' '---'
6 0 13 7
variable encoding, high bit of every byte
indicates if there is another byte
int16, int32, zig zag encoded to unsigned integer:
int64
0 -> 0
-1 -> 1
1 -> 2
-2 -> 3
...
and then encoded as unsigned integer
float, double little endian
.-------.------------.
string, wstring | count | characters |
'-------'------------'
count variable encoded uint32 count of 1-byte or 2-byte characters
characters 1-byte or 2-byte characters
.-------.-------.-------.
blob, list, set, | type | count | items |
vector, nullable '-------'-------'-------'
.---.---.---.---.---.---.---.---.
type (v1) | | | | t | t | t | t | t |
'---'---'---'---'---'---'---'---'
4 0
.---.---.---.---.---.---.---.---.
type (v2) | c | c | c | t | t | t | t | t |
'---'---'---'---'---'---'---'---'
2 0 4 0
if count of items is < 7, 'c' are bit of (count + 1),
otherwise 'c' bits are 0.
count variable encoded uint32 count of items
omitted in v2 if 'c' bits within type byte are not 0
items each item encoded according to its type
.----------.------------.-------.-----.-------.
map | key type | value type | count | key | value |
'----------'------------'-------'-----'-------'
.---.---.---.---.---.---.---.---.
key type, | | | | t | t | t | t | t |
value type '---'---'---'---'---'---'---'---'
4 0
count variable encoded uint32 count of {key,mapped} pairs
key, mapped each item encoded according to its type
*/
#endregion
namespace Bond.Protocols
{
using System;
using System.IO;
using System.Runtime.CompilerServices;
using System.Text;
using System.Collections.Generic;
using System.Diagnostics;
using Bond.IO;
/// <summary>
/// Writer for the Compact Binary tagged protocol
/// </summary>
/// <typeparam name="O">Implementation of IOutputStream interface</typeparam>
[Reader(typeof(CompactBinaryReader<>))]
[FirstPassWriter(typeof(CompactBinaryCounter))]
public struct CompactBinaryWriter<O> : ITwoPassProtocolWriter
where O : IOutputStream
{
const ushort Magic = (ushort)ProtocolType.COMPACT_PROTOCOL;
readonly O output;
readonly ushort version;
readonly CompactBinaryCounter? firstPassWriter;
readonly LinkedList<uint> lengths;
Stack<long> lengthCheck;
/// <summary>
/// Create an instance of CompactBinaryWriter
/// </summary>
/// <param name="output">Serialized payload output</param>
/// <param name="version">Protocol version</param>
public CompactBinaryWriter(O output, ushort version = 1)
{
this.output = output;
this.version = version;
if (version == 2)
{
lengths = new LinkedList<uint>();
firstPassWriter = new CompactBinaryCounter(lengths);
}
else
{
lengths = null;
firstPassWriter = null;
}
lengthCheck = null;
InitLengthCheck();
}
public IProtocolWriter GetFirstPassWriter()
{
if (version == 2)
{
return firstPassWriter.Value;
}
return null;
}
/// <summary>
/// Write protocol magic number and version
/// </summary>
#if NET45
[MethodImpl(MethodImplOptions.AggressiveInlining)]
#endif
public void WriteVersion()
{
output.WriteUInt16(Magic);
output.WriteUInt16(version);
}
#region Complex types
/// <summary>
/// Start writing a struct
/// </summary>
/// <param name="metadata">Schema metadata</param>
#if NET45
[MethodImpl(MethodImplOptions.AggressiveInlining)]
#endif
public void WriteStructBegin(Metadata metadata)
{
if (version == 2)
{
uint length = lengths.First.Value;
lengths.RemoveFirst();
output.WriteVarUInt32(length);
PushLengthCheck(output.Position + length);
}
}
/// <summary>
/// Start writing a base struct
/// </summary>
/// <param name="metadata">Base schema metadata</param>
#if NET45
[MethodImpl(MethodImplOptions.AggressiveInlining)]
#endif
public void WriteBaseBegin(Metadata metadata)
{}
/// <summary>
/// End writing a struct
/// </summary>
#if NET45
[MethodImpl(MethodImplOptions.AggressiveInlining)]
#endif
public void WriteStructEnd()
{
output.WriteUInt8((Byte)BondDataType.BT_STOP);
PopLengthCheck(output.Position);
}
/// <summary>
/// End writing a base struct
/// </summary>
#if NET45
[MethodImpl(MethodImplOptions.AggressiveInlining)]
#endif
public void WriteBaseEnd()
{
output.WriteUInt8((Byte)BondDataType.BT_STOP_BASE);
}
/// <summary>
/// Start writing a field
/// </summary>
/// <param name="type">Type of the field</param>
/// <param name="id">Identifier of the field</param>
/// <param name="metadata">Metadata of the field</param>
#if NET45
[MethodImpl(MethodImplOptions.AggressiveInlining)]
#endif
public void WriteFieldBegin(BondDataType type, ushort id, Metadata metadata)
{
var fieldType = (uint)type;
if (id <= 5)
{
output.WriteUInt8((byte)(fieldType | ((uint)id << 5)));
}
else if (id <= 0xFF)
{
output.WriteUInt16((ushort)(fieldType | (uint)id << 8 | (0x06 << 5)));
}
else
{
output.WriteUInt8((byte)(fieldType | (0x07 << 5)));
output.WriteUInt16(id);
}
}
/// <summary>
/// Indicate that field was omitted because it was set to its default value
/// </summary>
/// <param name="dataType">Type of the field</param>
/// <param name="id">Identifier of the field</param>
/// <param name="metadata">Metadata of the field</param>
#if NET45
[MethodImpl(MethodImplOptions.AggressiveInlining)]
#endif
public void WriteFieldOmitted(BondDataType dataType, ushort id, Metadata metadata)
{}
/// <summary>
/// End writing a field
/// </summary>
#if NET45
[MethodImpl(MethodImplOptions.AggressiveInlining)]
#endif
public void WriteFieldEnd()
{}
/// <summary>
/// Start writing a list or set container
/// </summary>
/// <param name="count">Number of elements in the container</param>
/// <param name="elementType">Type of the elements</param>
#if NET45
[MethodImpl(MethodImplOptions.AggressiveInlining)]
#endif
public void WriteContainerBegin(int count, BondDataType elementType)
{
if (2 == version && count < 7)
{
output.WriteUInt8((byte)((uint)elementType | (((uint)count + 1) << 5)));
}
else
{
output.WriteUInt8((byte)elementType);
output.WriteVarUInt32((uint)count);
}
}
/// <summary>
/// Start writing a map container
/// </summary>
/// <param name="count">Number of elements in the container</param>
/// <param name="keyType">Type of the keys</param>
/// /// <param name="valueType">Type of the values</param>
#if NET45
[MethodImpl(MethodImplOptions.AggressiveInlining)]
#endif
public void WriteContainerBegin(int count, BondDataType keyType, BondDataType valueType)
{
output.WriteUInt8((byte)keyType);
output.WriteUInt8((byte)valueType);
output.WriteVarUInt32((uint)count);
}
/// <summary>
/// End writing a container
/// </summary>
#if NET45
[MethodImpl(MethodImplOptions.AggressiveInlining)]
#endif
public void WriteContainerEnd()
{}
/// <summary>
/// Write array of bytes verbatim
/// </summary>
#if NET45
[MethodImpl(MethodImplOptions.AggressiveInlining)]
#endif
public void WriteBytes(ArraySegment<byte> data)
{
output.WriteBytes(data);
}
#endregion
#region Primitive types
/// <summary>
/// Write an UInt8
/// </summary>
#if NET45
[MethodImpl(MethodImplOptions.AggressiveInlining)]
#endif
public void WriteUInt8(Byte value)
{
output.WriteUInt8(value);
}
/// <summary>
/// Write an UInt16
/// </summary>
#if NET45
[MethodImpl(MethodImplOptions.AggressiveInlining)]
#endif
public void WriteUInt16(UInt16 value)
{
output.WriteVarUInt16(value);
}
/// <summary>
/// Write an UInt16
/// </summary>
#if NET45
[MethodImpl(MethodImplOptions.AggressiveInlining)]
#endif
public void WriteUInt32(UInt32 value)
{
output.WriteVarUInt32(value);
}
/// <summary>
/// Write an UInt64
/// </summary>
#if NET45
[MethodImpl(MethodImplOptions.AggressiveInlining)]
#endif
public void WriteUInt64(UInt64 value)
{
output.WriteVarUInt64(value);
}
/// <summary>
/// Write an Int8
/// </summary>
#if NET45
[MethodImpl(MethodImplOptions.AggressiveInlining)]
#endif
public void WriteInt8(SByte value)
{
output.WriteUInt8((Byte)value);
}
/// <summary>
/// Write an Int16
/// </summary>
#if NET45
[MethodImpl(MethodImplOptions.AggressiveInlining)]
#endif
public void WriteInt16(Int16 value)
{
output.WriteVarUInt16(IntegerHelper.EncodeZigzag16(value));
}
/// <summary>
/// Write an Int32
/// </summary>
#if NET45
[MethodImpl(MethodImplOptions.AggressiveInlining)]
#endif
public void WriteInt32(Int32 value)
{
output.WriteVarUInt32(IntegerHelper.EncodeZigzag32(value));
}
/// <summary>
/// Write an Int64
/// </summary>
#if NET45
[MethodImpl(MethodImplOptions.AggressiveInlining)]
#endif
public void WriteInt64(Int64 value)
{
output.WriteVarUInt64(IntegerHelper.EncodeZigzag64(value));
}
/// <summary>
/// Write a float
/// </summary>
#if NET45
[MethodImpl(MethodImplOptions.AggressiveInlining)]
#endif
public void WriteFloat(float value)
{
output.WriteFloat(value);
}
/// <summary>
/// Write a double
/// </summary>
#if NET45
[MethodImpl(MethodImplOptions.AggressiveInlining)]
#endif
public void WriteDouble(double value)
{
output.WriteDouble(value);
}
/// <summary>
/// Write a bool
/// </summary>
#if NET45
[MethodImpl(MethodImplOptions.AggressiveInlining)]
#endif
public void WriteBool(bool value)
{
output.WriteUInt8((byte)(value ? 1 : 0));
}
/// <summary>
/// Write a UTF-8 string
/// </summary>
#if NET45
[MethodImpl(MethodImplOptions.AggressiveInlining)]
#endif
public void WriteString(string value)
{
if (value.Length == 0)
{
WriteUInt32(0);
}
else
{
var size = Encoding.UTF8.GetByteCount(value);
WriteUInt32((UInt32)size);
output.WriteString(Encoding.UTF8, value, size);
}
}
/// <summary>
/// Write a UTF-16 string
/// </summary>
#if NET45
[MethodImpl(MethodImplOptions.AggressiveInlining)]
#endif
public void WriteWString(string value)
{
if (value.Length == 0)
{
WriteUInt32(0);
}
else
{
WriteUInt32((UInt32)value.Length);
output.WriteString(Encoding.Unicode, value, value.Length << 1);
}
}
#endregion
#region Length check
[Conditional("DEBUG")]
private void InitLengthCheck()
{
if (version == 2)
{
lengthCheck = new Stack<long>();
}
}
[Conditional("DEBUG")]
private void PushLengthCheck(long position)
{
lengthCheck.Push(position);
}
[Conditional("DEBUG")]
private void PopLengthCheck(long position)
{
if (version == 2)
{
if (position != lengthCheck.Pop())
{
Throw.EndOfStreamException();
}
}
}
#endregion
}
/// <summary>
/// Reader for the Compact Binary tagged protocol
/// </summary>
/// <typeparam name="I">Implementation of IInputStream interface</typeparam>
public struct CompactBinaryReader<I> : IClonableTaggedProtocolReader, ICloneable<CompactBinaryReader<I>>
where I : IInputStream, ICloneable<I>
{
readonly I input;
readonly ushort version;
/// <summary>
/// Create an instance of CompactBinaryReader
/// </summary>
/// <param name="input">Input payload</param>
/// <param name="version">Protocol version</param>
public CompactBinaryReader(I input, ushort version = 1)
{
this.input = input;
this.version = version;
}
/// <summary>
/// Clone the reader
/// </summary>
#if NET45
[MethodImpl(MethodImplOptions.AggressiveInlining)]
#endif
CompactBinaryReader<I> ICloneable<CompactBinaryReader<I>>.Clone()
{
return new CompactBinaryReader<I>(input.Clone(), version);
}
#if NET45
[MethodImpl(MethodImplOptions.AggressiveInlining)]
#endif
IClonableTaggedProtocolReader ICloneable<IClonableTaggedProtocolReader>.Clone()
{
return (this as ICloneable<CompactBinaryReader<I>>).Clone();
}
#region Complex types
/// <summary>
/// Start reading a struct
/// </summary>
/// <exception cref="EndOfStreamException"/>
#if NET45
[MethodImpl(MethodImplOptions.AggressiveInlining)]
#endif
public void ReadStructBegin()
{
if (2 == version)
{
input.ReadVarUInt32();
}
}
/// <summary>
/// Start reading a base of a struct
/// </summary>
/// <exception cref="EndOfStreamException"/>
#if NET45
[MethodImpl(MethodImplOptions.AggressiveInlining)]
#endif
public void ReadBaseBegin()
{ }
/// <summary>
/// End reading a struct
/// </summary>
/// <exception cref="EndOfStreamException"/>
#if NET45
[MethodImpl(MethodImplOptions.AggressiveInlining)]
#endif
public void ReadStructEnd()
{ }
/// <summary>
/// End reading a base of a struct
/// </summary>
/// <exception cref="EndOfStreamException"/>
#if NET45
[MethodImpl(MethodImplOptions.AggressiveInlining)]
#endif
public void ReadBaseEnd()
{ }
/// <summary>
/// Start reading a field
/// </summary>
/// <param name="type">An out parameter set to the field type
/// or BT_STOP/BT_STOP_BASE if there is no more fields in current struct/base</param>
/// <param name="id">Out parameter set to the field identifier</param>
/// <exception cref="EndOfStreamException"/>
#if NET45
[MethodImpl(MethodImplOptions.AggressiveInlining)]
#endif
public void ReadFieldBegin(out BondDataType type, out ushort id)
{
uint raw = input.ReadUInt8();
type = (BondDataType)(raw & 0x1f);
raw >>= 5;
if (raw < 6)
{
id = (ushort)raw;
}
else if (raw == 6)
{
id = input.ReadUInt8();
}
else
{
id = input.ReadUInt16();
}
}
/// <summary>
/// End reading a field
/// </summary>
/// <exception cref="EndOfStreamException"/>
#if NET45
[MethodImpl(MethodImplOptions.AggressiveInlining)]
#endif
public void ReadFieldEnd()
{ }
/// <summary>
/// Start reading a list or set container
/// </summary>
/// <param name="count">An out parameter set to number of items in the container</param>
/// <param name="elementType">An out parameter set to type of container elements</param>
/// <exception cref="EndOfStreamException"/>
#if NET45
[MethodImpl(MethodImplOptions.AggressiveInlining)]
#endif
public void ReadContainerBegin(out int count, out BondDataType elementType)
{
var raw = input.ReadUInt8();
elementType = (BondDataType)(raw & 0x1f);
if (2 == version && (raw & (0x07 << 5)) != 0)
count = (raw >> 5) - 1;
else
count = (int)input.ReadVarUInt32();
}
/// <summary>
/// Start reading a map container
/// </summary>
/// <param name="count">An out parameter set to number of items in the container</param>
/// <param name="keyType">An out parameter set to the type of map keys</param>
/// <param name="valueType">An out parameter set to the type of map values</param>
/// <exception cref="EndOfStreamException"/>
#if NET45
[MethodImpl(MethodImplOptions.AggressiveInlining)]
#endif
public void ReadContainerBegin(out int count, out BondDataType keyType, out BondDataType valueType)
{
keyType = (BondDataType)input.ReadUInt8();
valueType = (BondDataType)input.ReadUInt8();
count = (int)input.ReadVarUInt32();
}
/// <summary>
/// End reading a container
/// </summary>
/// <exception cref="EndOfStreamException"/>
#if NET45
[MethodImpl(MethodImplOptions.AggressiveInlining)]
#endif
public void ReadContainerEnd()
{ }
#endregion
#region Primitive types
/// <summary>
/// Read an UInt8
/// </summary>
/// <exception cref="EndOfStreamException"/>
#if NET45
[MethodImpl(MethodImplOptions.AggressiveInlining)]
#endif
public byte ReadUInt8()
{
return input.ReadUInt8();
}
/// <summary>
/// Read an UInt16
/// </summary>
/// <exception cref="EndOfStreamException"/>
#if NET45
[MethodImpl(MethodImplOptions.AggressiveInlining)]
#endif
public ushort ReadUInt16()
{
return input.ReadVarUInt16();
}
/// <summary>
/// Read an UInt32
/// </summary>
/// <exception cref="EndOfStreamException"/>
#if NET45
[MethodImpl(MethodImplOptions.AggressiveInlining)]
#endif
public uint ReadUInt32()
{
return input.ReadVarUInt32();
}
/// <summary>
/// Read an UInt64
/// </summary>
/// <exception cref="EndOfStreamException"/>
#if NET45
[MethodImpl(MethodImplOptions.AggressiveInlining)]
#endif
public UInt64 ReadUInt64()
{
return input.ReadVarUInt64();
}
/// <summary>
/// Read an Int8
/// </summary>
/// <exception cref="EndOfStreamException"/>
#if NET45
[MethodImpl(MethodImplOptions.AggressiveInlining)]
#endif
public sbyte ReadInt8()
{
return (sbyte)input.ReadUInt8();
}
/// <summary>
/// Read an Int16
/// </summary>
/// <exception cref="EndOfStreamException"/>
#if NET45
[MethodImpl(MethodImplOptions.AggressiveInlining)]
#endif
public short ReadInt16()
{
return IntegerHelper.DecodeZigzag16(input.ReadVarUInt16());
}
/// <summary>
/// Read an Int32
/// </summary>
/// <exception cref="EndOfStreamException"/>
#if NET45
[MethodImpl(MethodImplOptions.AggressiveInlining)]
#endif
public int ReadInt32()
{
return IntegerHelper.DecodeZigzag32(input.ReadVarUInt32());
}
/// <summary>
/// Read an Int64
/// </summary>
/// <exception cref="EndOfStreamException"/>
#if NET45
[MethodImpl(MethodImplOptions.AggressiveInlining)]
#endif
public Int64 ReadInt64()
{
return IntegerHelper.DecodeZigzag64(input.ReadVarUInt64());
}
/// <summary>
/// Read a bool
/// </summary>
/// <exception cref="EndOfStreamException"/>
#if NET45
[MethodImpl(MethodImplOptions.AggressiveInlining)]
#endif
public bool ReadBool()
{
return input.ReadUInt8() != 0;
}
/// <summary>
/// Read a float
/// </summary>
/// <exception cref="EndOfStreamException"/>
#if NET45
[MethodImpl(MethodImplOptions.AggressiveInlining)]
#endif
public float ReadFloat()
{
return input.ReadFloat();
}
/// <summary>
/// Read a double
/// </summary>
/// <exception cref="EndOfStreamException"/>
#if NET45
[MethodImpl(MethodImplOptions.AggressiveInlining)]
#endif
public double ReadDouble()
{
return input.ReadDouble();
}
/// <summary>
/// Read a UTF-8 string
/// </summary>
/// <exception cref="EndOfStreamException"/>
#if NET45
[MethodImpl(MethodImplOptions.AggressiveInlining)]
#endif
public String ReadString()
{
var length = (int)input.ReadVarUInt32();
return length == 0 ? string.Empty : input.ReadString(Encoding.UTF8, length);
}
/// <summary>
/// Read a UTF-16 string
/// </summary>
/// <exception cref="EndOfStreamException"/>
#if NET45
[MethodImpl(MethodImplOptions.AggressiveInlining)]
#endif
public string ReadWString()
{
var length = (int)input.ReadVarUInt32();
return length == 0 ? string.Empty : input.ReadString(Encoding.Unicode, length << 1);
}
/// <summary>
/// Read an array of bytes verbatim
/// </summary>
/// <param name="count">Number of bytes to read</param>
/// <exception cref="EndOfStreamException"/>
#if NET45
[MethodImpl(MethodImplOptions.AggressiveInlining)]
#endif
public ArraySegment<byte> ReadBytes(int count)
{
return input.ReadBytes(count);
}
#endregion
#region Skip
/// <summary>
/// Skip a value of specified type
/// </summary>
/// <param name="type">Type of the value to skip</param>
/// <exception cref="EndOfStreamException"/>
public void Skip(BondDataType type)
{
switch (type)
{
case (BondDataType.BT_BOOL):
case (BondDataType.BT_UINT8):
case (BondDataType.BT_INT8):
input.SkipBytes(sizeof(byte));
break;
case (BondDataType.BT_UINT16):
case (BondDataType.BT_INT16):
input.ReadVarUInt16();
break;
case (BondDataType.BT_UINT32):
case (BondDataType.BT_INT32):
input.ReadVarUInt32();
break;
case (BondDataType.BT_FLOAT):
input.SkipBytes(sizeof(float));
break;
case (BondDataType.BT_DOUBLE):
input.SkipBytes(sizeof(double));
break;
case (BondDataType.BT_UINT64):
case (BondDataType.BT_INT64):
input.ReadVarUInt64();
break;
case (BondDataType.BT_STRING):
input.SkipBytes((int)input.ReadVarUInt32());
break;
case (BondDataType.BT_WSTRING):
input.SkipBytes((int)(input.ReadVarUInt32() << 1));
break;
case BondDataType.BT_LIST:
case BondDataType.BT_SET:
SkipContainer();
break;
case BondDataType.BT_MAP:
SkipMap();
break;
case BondDataType.BT_STRUCT:
SkipStruct();
break;
default:
Throw.InvalidBondDataType(type);
break;
}
}
void SkipContainer()
{
BondDataType elementType;
int count;
ReadContainerBegin(out count, out elementType);
if (elementType == BondDataType.BT_UINT8 || elementType == BondDataType.BT_INT8)
{
input.SkipBytes(count);
}
else if (elementType == BondDataType.BT_FLOAT)
{
input.SkipBytes(count * sizeof(float));
}
else if (elementType == BondDataType.BT_DOUBLE)
{
input.SkipBytes(count * sizeof(double));
}
else
{
while (0 <= --count)
{
Skip(elementType);
}
}
}
void SkipMap()
{
BondDataType keyType;
BondDataType valueType;
int count;
ReadContainerBegin(out count, out keyType, out valueType);
while (0 <= --count)
{
Skip(keyType);
Skip(valueType);
}
}
void SkipStruct()
{
if (2 == version)
{
input.SkipBytes((int)input.ReadVarUInt32());
}
else
{
while (true)
{
BondDataType type;
ushort id;
ReadFieldBegin(out type, out id);
if (type == BondDataType.BT_STOP_BASE) continue;
if (type == BondDataType.BT_STOP) break;
Skip(type);
}
}
}
#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.Runtime.CompilerServices;
using System.Threading;
using Xunit;
namespace System.Linq.Expressions.Tests
{
public static class CompilerTests
{
[Theory]
[ClassData(typeof(CompilationTypes))]
[OuterLoop("Takes over a minute to complete")]
public static void CompileDeepTree_NoStackOverflow(bool useInterpreter)
{
var e = (Expression)Expression.Constant(0);
int n = 10000;
for (var i = 0; i < n; i++)
e = Expression.Add(e, Expression.Constant(1));
Func<int> f = Expression.Lambda<Func<int>>(e).Compile(useInterpreter);
Assert.Equal(n, f());
}
[Theory, ClassData(typeof(CompilationTypes))]
public static void CompileDeepTree_NoStackOverflowFast(bool useInterpreter)
{
Expression e = Expression.Constant(0);
int n = 100;
for (int i = 0; i < n; i++)
e = Expression.Add(e, Expression.Constant(1));
Func<int> f = null;
// Request a stack size of 64K to get very small stack.
// This reduces the size of tree needed to risk a stack overflow.
// This though will only risk overflow once, so the outerloop test
// above is still needed.
Thread t = new Thread(() => f = Expression.Lambda<Func<int>>(e).Compile(useInterpreter), 65536);
t.Start();
t.Join();
Assert.Equal(n, f());
}
#if FEATURE_COMPILE
[Fact]
public static void EmitConstantsToIL_NonNullableValueTypes()
{
VerifyEmitConstantsToIL((bool)true);
VerifyEmitConstantsToIL((char)'a');
VerifyEmitConstantsToIL((sbyte)42);
VerifyEmitConstantsToIL((byte)42);
VerifyEmitConstantsToIL((short)42);
VerifyEmitConstantsToIL((ushort)42);
VerifyEmitConstantsToIL((int)42);
VerifyEmitConstantsToIL((uint)42);
VerifyEmitConstantsToIL((long)42);
VerifyEmitConstantsToIL((ulong)42);
VerifyEmitConstantsToIL((float)3.14);
VerifyEmitConstantsToIL((double)3.14);
VerifyEmitConstantsToIL((decimal)49.95m);
}
[Fact]
public static void EmitConstantsToIL_NullableValueTypes()
{
VerifyEmitConstantsToIL((bool?)null);
VerifyEmitConstantsToIL((bool?)true);
VerifyEmitConstantsToIL((char?)null);
VerifyEmitConstantsToIL((char?)'a');
VerifyEmitConstantsToIL((sbyte?)null);
VerifyEmitConstantsToIL((sbyte?)42);
VerifyEmitConstantsToIL((byte?)null);
VerifyEmitConstantsToIL((byte?)42);
VerifyEmitConstantsToIL((short?)null);
VerifyEmitConstantsToIL((short?)42);
VerifyEmitConstantsToIL((ushort?)null);
VerifyEmitConstantsToIL((ushort?)42);
VerifyEmitConstantsToIL((int?)null);
VerifyEmitConstantsToIL((int?)42);
VerifyEmitConstantsToIL((uint?)null);
VerifyEmitConstantsToIL((uint?)42);
VerifyEmitConstantsToIL((long?)null);
VerifyEmitConstantsToIL((long?)42);
VerifyEmitConstantsToIL((ulong?)null);
VerifyEmitConstantsToIL((ulong?)42);
VerifyEmitConstantsToIL((float?)null);
VerifyEmitConstantsToIL((float?)3.14);
VerifyEmitConstantsToIL((double?)null);
VerifyEmitConstantsToIL((double?)3.14);
VerifyEmitConstantsToIL((decimal?)null);
VerifyEmitConstantsToIL((decimal?)49.95m);
VerifyEmitConstantsToIL((DateTime?)null);
}
[Fact]
public static void EmitConstantsToIL_ReferenceTypes()
{
VerifyEmitConstantsToIL((string)null);
VerifyEmitConstantsToIL((string)"bar");
}
[Fact]
public static void EmitConstantsToIL_Enums()
{
VerifyEmitConstantsToIL(ConstantsEnum.A);
VerifyEmitConstantsToIL((ConstantsEnum?)null);
VerifyEmitConstantsToIL((ConstantsEnum?)ConstantsEnum.A);
}
[Fact]
public static void EmitConstantsToIL_ShareReferences()
{
var o = new object();
VerifyEmitConstantsToIL(Expression.Equal(Expression.Constant(o), Expression.Constant(o)), 1, true);
}
[Fact]
public static void EmitConstantsToIL_LiftedToClosure()
{
VerifyEmitConstantsToIL(DateTime.Now, 1);
VerifyEmitConstantsToIL((DateTime?)DateTime.Now, 1);
}
[Fact]
public static void VariableBinder_CatchBlock_Filter1()
{
// See https://github.com/dotnet/corefx/issues/11994 for reported issue
Verify_VariableBinder_CatchBlock_Filter(
Expression.Catch(
Expression.Parameter(typeof(Exception), "ex"),
Expression.Empty(),
Expression.Parameter(typeof(bool), "???")
)
);
}
[Fact]
public static void VariableBinder_CatchBlock_Filter2()
{
// See https://github.com/dotnet/corefx/issues/11994 for reported issue
Verify_VariableBinder_CatchBlock_Filter(
Expression.Catch(
typeof(Exception),
Expression.Empty(),
Expression.Parameter(typeof(bool), "???")
)
);
}
[Fact]
public static void VerifyIL_Simple()
{
Expression<Func<int>> f = () => Math.Abs(42);
f.VerifyIL(
@".method int32 ::lambda_method(class [System.Linq.Expressions]System.Runtime.CompilerServices.Closure)
{
.maxstack 1
IL_0000: ldc.i4.s 42
IL_0002: call int32 class [System.Private.CoreLib]System.Math::Abs(int32)
IL_0007: ret
}");
}
[Fact]
public static void VerifyIL_Exceptions()
{
ParameterExpression x = Expression.Parameter(typeof(int), "x");
Expression<Func<int, int>> f =
Expression.Lambda<Func<int, int>>(
Expression.TryCatchFinally(
Expression.Call(
typeof(Math).GetMethod(nameof(Math.Abs), new[] { typeof(int) }),
Expression.Divide(
Expression.Constant(42),
x
)
),
Expression.Empty(),
Expression.Catch(
typeof(DivideByZeroException),
Expression.Constant(-1)
)
),
x
);
f.VerifyIL(
@".method int32 ::lambda_method(class [System.Linq.Expressions]System.Runtime.CompilerServices.Closure,int32)
{
.maxstack 4
.locals init (
[0] int32
)
.try
{
.try
{
IL_0000: ldc.i4.s 42
IL_0002: ldarg.1
IL_0003: div
IL_0004: call int32 class [System.Private.CoreLib]System.Math::Abs(int32)
IL_0009: stloc.0
IL_000a: leave IL_0017
}
catch (class [System.Private.CoreLib]System.DivideByZeroException)
{
IL_000f: pop
IL_0010: ldc.i4.m1
IL_0011: stloc.0
IL_0012: leave IL_0017
}
IL_0017: leave IL_001d
}
finally
{
IL_001c: endfinally
}
IL_001d: ldloc.0
IL_001e: ret
}");
}
[Fact]
public static void VerifyIL_Closure1()
{
Expression<Func<Func<int>>> f = () => () => 42;
f.VerifyIL(
@".method class [System.Private.CoreLib]System.Func`1<int32> ::lambda_method(class [System.Linq.Expressions]System.Runtime.CompilerServices.Closure)
{
.maxstack 3
IL_0000: ldarg.0
IL_0001: ldfld class [System.Linq.Expressions]System.Runtime.CompilerServices.Closure::Constants
IL_0006: ldc.i4.0
IL_0007: ldelem.ref
IL_0008: castclass class [System.Private.CoreLib]System.Reflection.MethodInfo
IL_000d: ldtoken class [System.Private.CoreLib]System.Func`1<int32>
IL_0012: call class [System.Private.CoreLib]System.Type class [System.Private.CoreLib]System.Type::GetTypeFromHandle(valuetype [System.Private.CoreLib]System.RuntimeTypeHandle)
IL_0017: ldnull
IL_0018: callvirt instance class [System.Private.CoreLib]System.Delegate class [System.Private.CoreLib]System.Reflection.MethodInfo::CreateDelegate(class [System.Private.CoreLib]System.Type,object)
IL_001d: castclass class [System.Private.CoreLib]System.Func`1<int32>
IL_0022: ret
}
// closure.Constants[0]
.method int32 ::lambda_method(class [System.Linq.Expressions]System.Runtime.CompilerServices.Closure)
{
.maxstack 1
IL_0000: ldc.i4.s 42
IL_0002: ret
}",
appendInnerLambdas: true);
}
[Fact]
public static void VerifyIL_Closure2()
{
Expression<Func<int, Func<int>>> f = x => () => x;
f.VerifyIL(
@".method class [System.Private.CoreLib]System.Func`1<int32> ::lambda_method(class [System.Linq.Expressions]System.Runtime.CompilerServices.Closure,int32)
{
.maxstack 8
.locals init (
[0] object[]
)
IL_0000: ldc.i4.1
IL_0001: newarr object
IL_0006: dup
IL_0007: ldc.i4.0
IL_0008: ldarg.1
IL_0009: newobj instance void class [System.Runtime]System.Runtime.CompilerServices.StrongBox`1<int32>::.ctor(int32)
IL_000e: stelem.ref
IL_000f: stloc.0
IL_0010: ldarg.0
IL_0011: ldfld class [System.Linq.Expressions]System.Runtime.CompilerServices.Closure::Constants
IL_0016: ldc.i4.0
IL_0017: ldelem.ref
IL_0018: castclass class [System.Private.CoreLib]System.Reflection.MethodInfo
IL_001d: ldtoken class [System.Private.CoreLib]System.Func`1<int32>
IL_0022: call class [System.Private.CoreLib]System.Type class [System.Private.CoreLib]System.Type::GetTypeFromHandle(valuetype [System.Private.CoreLib]System.RuntimeTypeHandle)
IL_0027: ldnull
IL_0028: ldloc.0
IL_0029: newobj instance void class [System.Linq.Expressions]System.Runtime.CompilerServices.Closure::.ctor(object[],object[])
IL_002e: callvirt instance class [System.Private.CoreLib]System.Delegate class [System.Private.CoreLib]System.Reflection.MethodInfo::CreateDelegate(class [System.Private.CoreLib]System.Type,object)
IL_0033: castclass class [System.Private.CoreLib]System.Func`1<int32>
IL_0038: ret
}
// closure.Constants[0]
.method int32 ::lambda_method(class [System.Linq.Expressions]System.Runtime.CompilerServices.Closure)
{
.maxstack 2
.locals init (
[0] object[]
)
IL_0000: ldarg.0
IL_0001: ldfld class [System.Linq.Expressions]System.Runtime.CompilerServices.Closure::Locals
IL_0006: stloc.0
IL_0007: ldloc.0
IL_0008: ldc.i4.0
IL_0009: ldelem.ref
IL_000a: castclass class [System.Runtime]System.Runtime.CompilerServices.StrongBox`1<int32>
IL_000f: ldfld class [System.Runtime]System.Runtime.CompilerServices.StrongBox`1<int32>::Value
IL_0014: ret
}",
appendInnerLambdas: true);
}
[Fact]
public static void VerifyIL_Closure3()
{
// Using an unchecked addition to ensure that an add instruction is emitted (and not add.ovf)
Expression<Func<int, Func<int, int>>> f = x => y => unchecked(x + y);
f.VerifyIL(
@".method class [System.Private.CoreLib]System.Func`2<int32,int32> ::lambda_method(class [System.Linq.Expressions]System.Runtime.CompilerServices.Closure,int32)
{
.maxstack 8
.locals init (
[0] object[]
)
IL_0000: ldc.i4.1
IL_0001: newarr object
IL_0006: dup
IL_0007: ldc.i4.0
IL_0008: ldarg.1
IL_0009: newobj instance void class [System.Runtime]System.Runtime.CompilerServices.StrongBox`1<int32>::.ctor(int32)
IL_000e: stelem.ref
IL_000f: stloc.0
IL_0010: ldarg.0
IL_0011: ldfld class [System.Linq.Expressions]System.Runtime.CompilerServices.Closure::Constants
IL_0016: ldc.i4.0
IL_0017: ldelem.ref
IL_0018: castclass class [System.Private.CoreLib]System.Reflection.MethodInfo
IL_001d: ldtoken class [System.Private.CoreLib]System.Func`2<int32,int32>
IL_0022: call class [System.Private.CoreLib]System.Type class [System.Private.CoreLib]System.Type::GetTypeFromHandle(valuetype [System.Private.CoreLib]System.RuntimeTypeHandle)
IL_0027: ldnull
IL_0028: ldloc.0
IL_0029: newobj instance void class [System.Linq.Expressions]System.Runtime.CompilerServices.Closure::.ctor(object[],object[])
IL_002e: callvirt instance class [System.Private.CoreLib]System.Delegate class [System.Private.CoreLib]System.Reflection.MethodInfo::CreateDelegate(class [System.Private.CoreLib]System.Type,object)
IL_0033: castclass class [System.Private.CoreLib]System.Func`2<int32,int32>
IL_0038: ret
}
// closure.Constants[0]
.method int32 ::lambda_method(class [System.Linq.Expressions]System.Runtime.CompilerServices.Closure,int32)
{
.maxstack 2
.locals init (
[0] object[]
)
IL_0000: ldarg.0
IL_0001: ldfld class [System.Linq.Expressions]System.Runtime.CompilerServices.Closure::Locals
IL_0006: stloc.0
IL_0007: ldloc.0
IL_0008: ldc.i4.0
IL_0009: ldelem.ref
IL_000a: castclass class [System.Runtime]System.Runtime.CompilerServices.StrongBox`1<int32>
IL_000f: ldfld class [System.Runtime]System.Runtime.CompilerServices.StrongBox`1<int32>::Value
IL_0014: ldarg.1
IL_0015: add
IL_0016: ret
}",
appendInnerLambdas: true);
}
public static void VerifyIL(this LambdaExpression expression, string expected, bool appendInnerLambdas = false)
{
string actual = expression.GetIL(appendInnerLambdas);
string nExpected = Normalize(expected);
string nActual = Normalize(actual);
Assert.Equal(nExpected, nActual);
}
private static string Normalize(string s)
{
Collections.Generic.IEnumerable<string> lines =
s
.Replace("\r\n", "\n")
.Split(new[] { '\n' })
.Select(line => line.Trim())
.Where(line => line != "" && !line.StartsWith("//"));
return string.Join("\n", lines);
}
private static void VerifyEmitConstantsToIL<T>(T value)
{
VerifyEmitConstantsToIL<T>(value, 0);
}
private static void VerifyEmitConstantsToIL<T>(T value, int expectedCount)
{
VerifyEmitConstantsToIL(Expression.Constant(value, typeof(T)), expectedCount, value);
}
private static void VerifyEmitConstantsToIL(Expression e, int expectedCount, object expectedValue)
{
Delegate f = Expression.Lambda(e).Compile();
var c = f.Target as Closure;
Assert.NotNull(c);
Assert.Equal(expectedCount, c.Constants.Length);
object o = f.DynamicInvoke();
Assert.Equal(expectedValue, o);
}
private static void Verify_VariableBinder_CatchBlock_Filter(CatchBlock @catch)
{
Expression<Action> e =
Expression.Lambda<Action>(
Expression.TryCatch(
Expression.Empty(),
@catch
)
);
Assert.Throws<InvalidOperationException>(() => e.Compile());
}
#endif
}
public enum ConstantsEnum
{
A
}
}
| |
#pragma warning disable 162,108,618
using Casanova.Prelude;
using System.Linq;
using System;
using System.Collections.Generic;
using UnityEngine;
public class World : MonoBehaviour
{
void OnApplicationQuit() { file.Close(); }public static int frame;
void Update()
{
Update(Time.deltaTime, this);
frame++;
}
public bool JustEntered = true;
static public int StarSystemCounter;
static public int PlanetCounter;
static public int ShipCounter;
static public Dictionary<int, Tuple<StarSystem, RuleTable>> StarSystemWithActiveRules;
static public Dictionary<int, Tuple<Planet, RuleTable>> PlanetWithActiveRules;
static public Dictionary<int, Tuple<Ship, RuleTable>> ShipWithActiveRules;
static public List<int> StarSystemWithActiveRulesToRemove;
static public List<int> PlanetWithActiveRulesToRemove;
static public List<int> ShipWithActiveRulesToRemove;
static public Dictionary<int, List<StarSystem>> NotifySlotStarSystemShipsStarSystem1;
static public Dictionary<int, List<Planet>> NotifySlotStarSystemShipsPlanet2;
static public Dictionary<int, List<Ship>> NotifySlotShipArrivedShip0;
static public Dictionary<int, List<Ship>> NotifySlotShipArrivedShip1;
static public Dictionary<int, List<Ship>> NotifySlotShipDestroyedShip0;
System.IO.StreamWriter file;
public void Start()
{
file = new System.IO.StreamWriter(System.IO.Path.Combine(System.IO.Directory.GetCurrentDirectory(), "test.csv")); StarSystemCounter = 0;
PlanetCounter = 0;
ShipCounter = 0;
NotifySlotStarSystemShipsStarSystem1 = new Dictionary<int, List<StarSystem>>();
NotifySlotStarSystemShipsPlanet2 = new Dictionary<int, List<Planet>>();
NotifySlotShipArrivedShip0 = new Dictionary<int, List<Ship>>();
NotifySlotShipArrivedShip1 = new Dictionary<int, List<Ship>>();
NotifySlotShipDestroyedShip0 = new Dictionary<int, List<Ship>>();
StarSystemWithActiveRules = new Dictionary<int, Tuple<StarSystem, RuleTable>>();
PlanetWithActiveRules = new Dictionary<int, Tuple<Planet, RuleTable>>();
ShipWithActiveRules = new Dictionary<int, Tuple<Ship, RuleTable>>();
StarSystemWithActiveRulesToRemove = new List<int>();
PlanetWithActiveRulesToRemove = new List<int>();
ShipWithActiveRulesToRemove = new List<int>();
List<StarSystem> ___star_systems00;
___star_systems00 = (
(Enumerable.Range(0, (1) + ((10) - (0))).ToList<System.Int32>()).Select(__ContextSymbol0 => new { ___i00 = __ContextSymbol0 })
.SelectMany(__ContextSymbol1 => (Enumerable.Range(0, (1) + ((10) - (0))).ToList<System.Int32>()).Select(__ContextSymbol2 => new
{
___j00 = __ContextSymbol2,
prev = __ContextSymbol1
})
.Where(__ContextSymbol3 => ((((2) > (__ContextSymbol3.prev.___i00))) || (((__ContextSymbol3.___j00) > (5)))))
.Select(__ContextSymbol4 => new StarSystem())
.ToList<StarSystem>())).ToList<StarSystem>();
StarSystem = ___star_systems00;
Seed = new System.Random();
}
public System.Random Seed;
public List<StarSystem> __StarSystem;
public List<StarSystem> StarSystem
{
get { return __StarSystem; }
set
{
__StarSystem = value;
foreach (var e in value)
{
if (e.JustEntered)
{
e.JustEntered = false;
World.NotifySlotStarSystemShipsStarSystem1[e.ID].Add(e);
}
}
}
}
System.DateTime init_time = System.DateTime.Now;
public void Update(float dt, World world)
{
var t = System.DateTime.Now;
for (int x0 = 0; x0 < StarSystem.Count; x0++)
{
StarSystem[x0].Update(dt, world);
}
if (StarSystemWithActiveRules.Count > 0)
{
foreach (var x in StarSystemWithActiveRules)
x.Value.Item1.UpdateSuspendedRules(dt, this, StarSystemWithActiveRulesToRemove, x.Value.Item2);
if (StarSystemWithActiveRulesToRemove.Count > 0)
{
for (int i = 0; i < StarSystemWithActiveRulesToRemove.Count; i++)
StarSystemWithActiveRules.Remove(StarSystemWithActiveRulesToRemove[i]);
StarSystemWithActiveRulesToRemove.Clear();
}
}
if (PlanetWithActiveRules.Count > 0)
{
foreach (var x in PlanetWithActiveRules)
x.Value.Item1.UpdateSuspendedRules(dt, this, PlanetWithActiveRulesToRemove, x.Value.Item2);
if (PlanetWithActiveRulesToRemove.Count > 0)
{
for (int i = 0; i < PlanetWithActiveRulesToRemove.Count; i++)
PlanetWithActiveRules.Remove(PlanetWithActiveRulesToRemove[i]);
PlanetWithActiveRulesToRemove.Clear();
}
}
if (ShipWithActiveRules.Count > 0)
{
foreach (var x in ShipWithActiveRules)
x.Value.Item1.UpdateSuspendedRules(dt, this, ShipWithActiveRulesToRemove, x.Value.Item2);
if (ShipWithActiveRulesToRemove.Count > 0)
{
for (int i = 0; i < ShipWithActiveRulesToRemove.Count; i++)
ShipWithActiveRules.Remove(ShipWithActiveRulesToRemove[i]);
ShipWithActiveRulesToRemove.Clear();
}
}
var t1 = System.DateTime.Now;
file.WriteLine((t1 - t).Milliseconds + "," + (t1 - init_time).Seconds);
}
}
public class StarSystem
{
public int frame;
public bool JustEntered = true;
public int ID;
public StarSystem()
{
JustEntered = false;
frame = World.frame;
this.ID = World.StarSystemCounter++;
World.NotifySlotStarSystemShipsStarSystem1.Add(ID, new List<StarSystem>());
World.NotifySlotStarSystemShipsPlanet2.Add(ID, new List<Planet>());
World.NotifySlotStarSystemShipsStarSystem1[ID].Add(this);
Ships = (
Enumerable.Empty<Ship>()).ToList<Ship>();
Planets = (
Enumerable.Empty<Planet>()).ToList<Planet>();
StarSystem1 = new List<Ship>(Ships);
List<Ship> q;
q = (
(Ships).Select(__ContextSymbol7 => new { ___s10 = __ContextSymbol7 })
.Where(__ContextSymbol8 => ((!(__ContextSymbol8.___s10.Arrived)) && (!(__ContextSymbol8.___s10.Destroyed))))
.Select(__ContextSymbol9 => __ContextSymbol9.___s10)
.ToList<Ship>()).ToList<Ship>();
StarSystem1 = q;
}
public void Init()
{
Ships = (
Enumerable.Empty<Ship>()).ToList<Ship>();
Planets = (
Enumerable.Empty<Planet>()).ToList<Planet>();
StarSystem1 = new List<Ship>(Ships);
List<Ship> q;
q = (
(Ships).Select(__ContextSymbol12 => new { ___s10 = __ContextSymbol12 })
.Where(__ContextSymbol13 => ((!(__ContextSymbol13.___s10.Arrived)) && (!(__ContextSymbol13.___s10.Destroyed))))
.Select(__ContextSymbol14 => __ContextSymbol14.___s10)
.ToList<Ship>()).ToList<Ship>();
StarSystem1 = q;
}
public List<Planet> Planets;
public List<Ship> _Ships;
public List<Ship> StarSystem1;
public System.Boolean q_temp1;
public Ship s;
public System.Int32 counter3;
public System.Single count_down2;
public System.Single count_down1;
public RuleTable ActiveRules = new RuleTable(1);
public List<Ship> Ships
{
get { return _Ships; }
set
{
_Ships = value;
q_temp1 = true;
//q_temp2 = true;
for (int i = 0; i < World.NotifySlotStarSystemShipsStarSystem1[ID].Count; i++)
{
var entity = World.NotifySlotStarSystemShipsStarSystem1[ID][i];
if (entity.frame == World.frame)
{
if (!World.StarSystemWithActiveRules.ContainsKey(entity.ID))
World.StarSystemWithActiveRules.Add(entity.ID, new Tuple<StarSystem, RuleTable>(entity, new RuleTable(3))); World.StarSystemWithActiveRules[entity.ID].Item2.Add(1);
}
else
{
entity.JustEntered = true;
World.NotifySlotStarSystemShipsStarSystem1.Remove(entity.ID);
}
}
for (int i = 0; i < World.NotifySlotStarSystemShipsPlanet2[ID].Count; i++)
{
var entity = World.NotifySlotStarSystemShipsPlanet2[ID][i];
if (entity.frame == World.frame)
{
if (!World.PlanetWithActiveRules.ContainsKey(entity.ID))
World.PlanetWithActiveRules.Add(entity.ID, new Tuple<Planet, RuleTable>(entity, new RuleTable(3))); World.PlanetWithActiveRules[entity.ID].Item2.Add(2);
}
else
{
entity.JustEntered = true;
World.NotifySlotStarSystemShipsStarSystem1.Remove(entity.ID);
}
}
}
}
public void Update(float dt, World world)
{
frame = World.frame;
for (int x0 = 0; x0 < Planets.Count; x0++)
{
Planets[x0].Update(dt, world);
}
for (int x0 = 0; x0 < Ships.Count; x0++)
{
Ships[x0].Update(dt, world);
}
this.Rule0(dt, world);
this.Rule2(dt, world);
}
public void UpdateSuspendedRules(float dt, World world, List<int> toRemove, RuleTable ActiveRules)
{
if (ActiveRules.ActiveIndices.Top > 0 && frame == World.frame)
{
for (int i = 0; i < ActiveRules.ActiveIndices.Top; i++)
{
var x = ActiveRules.ActiveIndices.Elements[i];
switch (x)
{
case 1:
if (this.Rule1(dt, world) == RuleResult.Done)
{
ActiveRules.ActiveSlots[i] = false;
ActiveRules.ActiveIndices.Top--;
}
else
{
ActiveRules.SupportSlots[1] = true;
ActiveRules.SupportStack.Push(x);
}
break;
default:
break;
}
}
ActiveRules.ActiveIndices.Clear();
ActiveRules.Clear();
var tmp = ActiveRules.SupportStack;
var tmp1 = ActiveRules.SupportSlots;
ActiveRules.SupportStack = ActiveRules.ActiveIndices;
ActiveRules.SupportSlots = ActiveRules.ActiveSlots;
ActiveRules.ActiveIndices = tmp;
ActiveRules.ActiveSlots = tmp1;
if (ActiveRules.ActiveIndices.Top == 0)
toRemove.Add(ID);
}
else
{
if (this.frame != World.frame)
toRemove.Add(ID);
}
}
int s0 = -1;
public void Rule0(float dt, World world)
{
switch (s0)
{
case -1:
Planets = (
(PointGenerator.GeneratePoints(50)).Select(__ContextSymbol15 => new { ___p00 = __ContextSymbol15 })
.Select(__ContextSymbol16 => new Planet(__ContextSymbol16.___p00, this))
.ToList<Planet>()).ToList<Planet>();
s0 = 0;
return;
case 0:
if (!(false))
{
s0 = 0;
return;
}
else
{
s0 = -1;
return;
}
default: return;
}
}
int s2 = -1;
public void Rule2(float dt, World world)
{
switch (s2)
{
case -1:
count_down2 = 0.1f;
goto case 4;
case 4:
if (((count_down2) > (0f)))
{
count_down2 = ((count_down2) - (dt));
s2 = 4;
return;
}
else
{
goto case 2;
}
case 2:
Ships = ((
(Planets).Select(__ContextSymbol17 => new { ___p120 = __ContextSymbol17 })
.SelectMany(__ContextSymbol18 => (Planets).Select(__ContextSymbol19 => new
{
___p220 = __ContextSymbol19,
prev = __ContextSymbol18
})
.Where(__ContextSymbol20 => ((((!(((__ContextSymbol20.prev.___p120) == (__ContextSymbol20.___p220)))) && (__ContextSymbol20.prev.___p120.Selected))) && (__ContextSymbol20.___p220.Targeted)))
.Select(__ContextSymbol21 => new Ship(__ContextSymbol21.prev.___p120, __ContextSymbol21.___p220))
.ToList<Ship>())).ToList<Ship>()).Concat(Ships).ToList<Ship>();
s2 = 0;
return;
case 0:
count_down1 = 10f;
goto case 1;
case 1:
if (((count_down1) > (0f)))
{
count_down1 = ((count_down1) - (dt));
s2 = 1;
return;
}
else
{
s2 = -1;
return;
}
default: return;
}
}
int s1 = -1;
public RuleResult Rule1(float dt, World world)
{
switch (s1)
{
case -1:
goto case 16;
case 16:
if (!(q_temp1))
{
s1 = 16;
return RuleResult.Done;
}
else
{
goto case 15;
}
case 15:
q_temp1 = false;
if (((StarSystem1) == (Ships)))
{
goto case 13;
}
else
{
goto case 11;
}
case 13:
_Ships = new List<Ship>(Ships);
goto case 11;
case 11:
StarSystem1.Clear();
counter3 = -1;
if ((((Ships).Count) == (0)))
{
goto case 1;
}
else
{
s = (Ships)[0];
goto case 3;
}
case 3:
counter3 = ((counter3) + (1));
if ((((((Ships).Count) == (counter3))) || (((counter3) > ((Ships).Count)))))
{
goto case 1;
}
else
{
s = (Ships)[counter3];
goto case 4;
}
case 4:
if (((!(s.Arrived)) && (!(s.Destroyed))))
{
goto case 5;
}
else
{
goto case 6;
}
case 5:
s._StarSystem = this;
StarSystem1.Add(s);
goto case 3;
case 6:
s._StarSystem = null;
goto case 3;
case 1:
q_temp1 = false;
Ships = StarSystem1;
s1 = -1;
return RuleResult.Working;
default: return RuleResult.Done;
}
}
}
public class Planet
{
public int frame;
public bool JustEntered = true;
private UnityEngine.Vector3 p;
private StarSystem starSystem;
public int ID;
public Planet(UnityEngine.Vector3 p, StarSystem starSystem)
{
JustEntered = false;
frame = World.frame;
this.ID = World.PlanetCounter++;
World.NotifySlotStarSystemShipsPlanet2[starSystem.ID].Add(this);
UnitySphere = UnitySphere.Instantiate(p);
Targeted = false;
StarSystem = starSystem;
Selected = false;
LandedShips = (
Enumerable.Empty<Ship>()).ToList<Ship>();
Planet2 = new List<Ship>(StarSystem.Ships);
List<Ship> q;
q = (
(StarSystem.Ships).Select(__ContextSymbol23 => new { ___s21 = __ContextSymbol23 })
.Where(__ContextSymbol24 => ((__ContextSymbol24.___s21.Arrived) && (((__ContextSymbol24.___s21.Target) == (this)))))
.Select(__ContextSymbol25 => __ContextSymbol25.___s21)
.ToList<Ship>()).ToList<Ship>();
Planet2 = q;
}
public void Init()
{
UnitySphere = UnitySphere.Instantiate(p);
Targeted = false;
StarSystem = starSystem;
Selected = false;
LandedShips = (
Enumerable.Empty<Ship>()).ToList<Ship>();
Planet2 = new List<Ship>(StarSystem.Ships);
List<Ship> q;
q = (
(StarSystem.Ships).Select(__ContextSymbol27 => new { ___s21 = __ContextSymbol27 })
.Where(__ContextSymbol28 => ((__ContextSymbol28.___s21.Arrived) && (((__ContextSymbol28.___s21.Target) == (this)))))
.Select(__ContextSymbol29 => __ContextSymbol29.___s21)
.ToList<Ship>()).ToList<Ship>();
Planet2 = q;
}
public List<Ship> LandedShips;
public UnityEngine.Vector3 Position
{
get { return UnitySphere.Position; }
set { UnitySphere.Position = value; }
}
public System.Boolean Selected;
public StarSystem StarSystem;
public System.Boolean Targeted;
public UnitySphere UnitySphere;
public UnityEngine.Animation animation
{
get { return UnitySphere.animation; }
}
public UnityEngine.AudioSource audio
{
get { return UnitySphere.audio; }
}
public UnityEngine.Camera camera
{
get { return UnitySphere.camera; }
}
public UnityEngine.Collider collider
{
get { return UnitySphere.collider; }
}
public UnityEngine.Collider2D collider2D
{
get { return UnitySphere.collider2D; }
}
public UnityEngine.ConstantForce constantForce
{
get { return UnitySphere.constantForce; }
}
public System.Boolean enabled
{
get { return UnitySphere.enabled; }
set { UnitySphere.enabled = value; }
}
public UnityEngine.GameObject gameObject
{
get { return UnitySphere.gameObject; }
}
public UnityEngine.GUIElement guiElement
{
get { return UnitySphere.guiElement; }
}
public UnityEngine.GUIText guiText
{
get { return UnitySphere.guiText; }
}
public UnityEngine.GUITexture guiTexture
{
get { return UnitySphere.guiTexture; }
}
public UnityEngine.HideFlags hideFlags
{
get { return UnitySphere.hideFlags; }
set { UnitySphere.hideFlags = value; }
}
public UnityEngine.HingeJoint hingeJoint
{
get { return UnitySphere.hingeJoint; }
}
public UnityEngine.Light light
{
get { return UnitySphere.light; }
}
public System.String name
{
get { return UnitySphere.name; }
set { UnitySphere.name = value; }
}
public UnityEngine.ParticleEmitter particleEmitter
{
get { return UnitySphere.particleEmitter; }
}
public UnityEngine.ParticleSystem particleSystem
{
get { return UnitySphere.particleSystem; }
}
public UnityEngine.Renderer renderer
{
get { return UnitySphere.renderer; }
}
public UnityEngine.Rigidbody rigidbody
{
get { return UnitySphere.rigidbody; }
}
public UnityEngine.Rigidbody2D rigidbody2D
{
get { return UnitySphere.rigidbody2D; }
}
public System.String tag
{
get { return UnitySphere.tag; }
set { UnitySphere.tag = value; }
}
public UnityEngine.Transform transform
{
get { return UnitySphere.transform; }
}
public System.Boolean useGUILayout
{
get { return UnitySphere.useGUILayout; }
set { UnitySphere.useGUILayout = value; }
}
public List<Ship> Planet2;
public System.Single count_down4;
public System.Single count_down3;
public System.Single count_down6;
public System.Single count_down5;
public System.Boolean q_temp2;
public Ship s;
public System.Int32 counter3;
public RuleTable ActiveRules = new RuleTable(1);
public void Update(float dt, World world)
{
frame = World.frame;
this.Rule0(dt, world);
this.Rule1(dt, world);
}
public void UpdateSuspendedRules(float dt, World world, List<int> toRemove, RuleTable ActiveRules)
{
if (ActiveRules.ActiveIndices.Top > 0 && frame == World.frame)
{
for (int i = 0; i < ActiveRules.ActiveIndices.Top; i++)
{
var x = ActiveRules.ActiveIndices.Elements[i];
switch (x)
{
case 2:
if (this.Rule2(dt, world) == RuleResult.Done)
{
ActiveRules.ActiveSlots[i] = false;
ActiveRules.ActiveIndices.Top--;
}
else
{
ActiveRules.SupportSlots[2] = true;
ActiveRules.SupportStack.Push(x);
}
break;
default:
break;
}
}
ActiveRules.ActiveIndices.Clear();
ActiveRules.Clear();
var tmp = ActiveRules.SupportStack;
var tmp1 = ActiveRules.SupportSlots;
ActiveRules.SupportStack = ActiveRules.ActiveIndices;
ActiveRules.SupportSlots = ActiveRules.ActiveSlots;
ActiveRules.ActiveIndices = tmp;
ActiveRules.ActiveSlots = tmp1;
if (ActiveRules.ActiveIndices.Top == 0)
toRemove.Add(ID);
}
else
{
if (this.frame != World.frame)
toRemove.Add(ID);
}
}
int s0 = -1;
public void Rule0(float dt, World world)
{
switch (s0)
{
case -1:
if (!(!(Targeted)))
{
goto case 1;
}
else
{
goto case 4;
}
case 4:
count_down4 = 1f;
goto case 7;
case 7:
if (((count_down4) > (0f)))
{
count_down4 = ((count_down4) - (dt));
s0 = 7;
return;
}
else
{
goto case 5;
}
case 5:
Targeted = ((world.Seed.NextDouble()) > (0.8f));
s0 = -1;
return;
case 1:
count_down3 = world.Seed.Next(1, 5);
goto case 2;
case 2:
if (((count_down3) > (0f)))
{
count_down3 = ((count_down3) - (dt));
s0 = 2;
return;
}
else
{
goto case 0;
}
case 0:
Targeted = false;
s0 = -1;
return;
default: return;
}
}
int s1 = -1;
public void Rule1(float dt, World world)
{
switch (s1)
{
case -1:
if (!(!(Selected)))
{
goto case 1;
}
else
{
goto case 4;
}
case 4:
count_down6 = 1f;
goto case 7;
case 7:
if (((count_down6) > (0f)))
{
count_down6 = ((count_down6) - (dt));
s1 = 7;
return;
}
else
{
goto case 5;
}
case 5:
Selected = ((world.Seed.NextDouble()) > (0.8f));
s1 = -1;
return;
case 1:
count_down5 = world.Seed.Next(1, 5);
goto case 2;
case 2:
if (((count_down5) > (0f)))
{
count_down5 = ((count_down5) - (dt));
s1 = 2;
return;
}
else
{
goto case 0;
}
case 0:
Selected = false;
s1 = -1;
return;
default: return;
}
}
int s2 = -1;
public RuleResult Rule2(float dt, World world)
{
switch (s2)
{
case -1:
goto case 16;
case 16:
if (!(q_temp2))
{
s2 = 16;
return RuleResult.Done;
}
else
{
goto case 15;
}
case 15:
q_temp2 = false;
if (((Planet2) == (StarSystem.Ships)))
{
goto case 13;
}
else
{
goto case 11;
}
case 13:
StarSystem.Ships = new List<Ship>(StarSystem.Ships);
goto case 11;
case 11:
Planet2.Clear();
counter3 = -1;
if ((((StarSystem.Ships).Count) == (0)))
{
goto case 1;
}
else
{
s = (StarSystem.Ships)[0];
goto case 3;
}
case 3:
counter3 = ((counter3) + (1));
if ((((((StarSystem.Ships).Count) == (counter3))) || (((counter3) > ((StarSystem.Ships).Count)))))
{
goto case 1;
}
else
{
s = (StarSystem.Ships)[counter3];
goto case 4;
}
case 4:
if (((s.Arrived) && (((s.Target) == (s._Planet)))))
{
goto case 5;
}
else
{
goto case 6;
}
case 5:
s._Planet = this;
Planet2.Add(s);
goto case 3;
case 6:
s._Planet = null;
goto case 3;
case 1:
q_temp2 = false;
LandedShips = Planet2;
s2 = -1;
return RuleResult.Working;
default: return RuleResult.Done;
}
}
}
public class Ship
{
public int frame;
public bool JustEntered = true;
private Planet source;
private Planet target;
public int ID;
public Ship(Planet source, Planet target)
{
JustEntered = false;
frame = World.frame;
this.ID = World.ShipCounter++;
World.NotifySlotShipArrivedShip0.Add(ID, new List<Ship>());
World.NotifySlotShipArrivedShip1.Add(ID, new List<Ship>());
World.NotifySlotShipDestroyedShip0.Add(ID, new List<Ship>());
World.NotifySlotShipDestroyedShip0[ID].Add(this);
World.NotifySlotShipArrivedShip0[ID].Add(this);
World.NotifySlotShipArrivedShip1[ID].Add(this);
UnityEngine.Vector3 ___velocity00;
___velocity00 = (target.Position) - (source.Position);
UnityEngine.Vector3 ___velocity_normalized00;
___velocity_normalized00 = ___velocity00.normalized;
Velocity = (___velocity_normalized00) * (10f);
UnityCube = UnityCube.Instantiate(source.Position);
Target = target;
Arrived = false;
}
public void Init()
{
UnityEngine.Vector3 ___velocity00;
___velocity00 = (target.Position) - (source.Position);
UnityEngine.Vector3 ___velocity_normalized00;
___velocity_normalized00 = ___velocity00.normalized;
Velocity = (___velocity_normalized00) * (10f);
UnityCube = UnityCube.Instantiate(source.Position);
Target = target;
Arrived = false;
}
public System.Boolean _Arrived;
public System.Boolean _Destroyed
{
get { return UnityCube.Destroyed; }
set { UnityCube.Destroyed = value; }
}
public UnityEngine.Vector3 Position
{
get { return UnityCube.Position; }
set { UnityCube.Position = value; }
}
public Planet Target;
public UnityCube UnityCube;
public UnityEngine.Vector3 Velocity;
public UnityEngine.Animation animation
{
get { return UnityCube.animation; }
}
public UnityEngine.AudioSource audio
{
get { return UnityCube.audio; }
}
public UnityEngine.Camera camera
{
get { return UnityCube.camera; }
}
public UnityEngine.Collider collider
{
get { return UnityCube.collider; }
}
public UnityEngine.Collider2D collider2D
{
get { return UnityCube.collider2D; }
}
public UnityEngine.ConstantForce constantForce
{
get { return UnityCube.constantForce; }
}
public System.Boolean enabled
{
get { return UnityCube.enabled; }
set { UnityCube.enabled = value; }
}
public UnityEngine.GameObject gameObject
{
get { return UnityCube.gameObject; }
}
public UnityEngine.GUIElement guiElement
{
get { return UnityCube.guiElement; }
}
public UnityEngine.GUIText guiText
{
get { return UnityCube.guiText; }
}
public UnityEngine.GUITexture guiTexture
{
get { return UnityCube.guiTexture; }
}
public UnityEngine.HideFlags hideFlags
{
get { return UnityCube.hideFlags; }
set { UnityCube.hideFlags = value; }
}
public UnityEngine.HingeJoint hingeJoint
{
get { return UnityCube.hingeJoint; }
}
public UnityEngine.Light light
{
get { return UnityCube.light; }
}
public System.String name
{
get { return UnityCube.name; }
set { UnityCube.name = value; }
}
public UnityEngine.ParticleEmitter particleEmitter
{
get { return UnityCube.particleEmitter; }
}
public UnityEngine.ParticleSystem particleSystem
{
get { return UnityCube.particleSystem; }
}
public UnityEngine.Renderer renderer
{
get { return UnityCube.renderer; }
}
public UnityEngine.Rigidbody rigidbody
{
get { return UnityCube.rigidbody; }
}
public UnityEngine.Rigidbody2D rigidbody2D
{
get { return UnityCube.rigidbody2D; }
}
public System.String tag
{
get { return UnityCube.tag; }
set { UnityCube.tag = value; }
}
public UnityEngine.Transform transform
{
get { return UnityCube.transform; }
}
public System.Boolean useGUILayout
{
get { return UnityCube.useGUILayout; }
set { UnityCube.useGUILayout = value; }
}
public StarSystem _StarSystem;
public Planet _Planet;
public System.Boolean _cond01;
public System.Boolean _cond11;
public System.Boolean _cond02;
public Planet _cond12;
public RuleTable ActiveRules = new RuleTable(3);
public System.Boolean Arrived
{
get { return _Arrived; }
set
{
_Arrived = value;
for (int i = 0; i < World.NotifySlotShipArrivedShip0[ID].Count; i++)
{
var entity = World.NotifySlotShipArrivedShip0[ID][i];
if (entity.frame == World.frame)
{
if (!World.ShipWithActiveRules.ContainsKey(entity.ID))
World.ShipWithActiveRules.Add(entity.ID, new Tuple<Ship, RuleTable>(entity, new RuleTable(4))); World.ShipWithActiveRules[entity.ID].Item2.Add(0);
}
else
{
entity.JustEntered = true;
World.NotifySlotShipDestroyedShip0.Remove(entity.ID);
World.NotifySlotShipArrivedShip0.Remove(entity.ID);
World.NotifySlotShipArrivedShip1.Remove(entity.ID);
}
}
for (int i = 0; i < World.NotifySlotShipArrivedShip1[ID].Count; i++)
{
var entity = World.NotifySlotShipArrivedShip1[ID][i];
if (entity.frame == World.frame)
{
if (!World.ShipWithActiveRules.ContainsKey(entity.ID))
World.ShipWithActiveRules.Add(entity.ID, new Tuple<Ship, RuleTable>(entity, new RuleTable(4))); World.ShipWithActiveRules[entity.ID].Item2.Add(1);
}
else
{
entity.JustEntered = true;
World.NotifySlotShipDestroyedShip0.Remove(entity.ID);
World.NotifySlotShipArrivedShip0.Remove(entity.ID);
World.NotifySlotShipArrivedShip1.Remove(entity.ID);
}
}
}
}
public System.Boolean Destroyed
{
get { return _Destroyed; }
set
{
_Destroyed = value;
for (int i = 0; i < World.NotifySlotShipDestroyedShip0[ID].Count; i++)
{
var entity = World.NotifySlotShipDestroyedShip0[ID][i];
if (entity.frame == World.frame)
{
if (!World.ShipWithActiveRules.ContainsKey(entity.ID))
World.ShipWithActiveRules.Add(entity.ID, new Tuple<Ship, RuleTable>(entity, new RuleTable(4))); World.ShipWithActiveRules[entity.ID].Item2.Add(0);
}
else
{
entity.JustEntered = true;
World.NotifySlotShipDestroyedShip0.Remove(entity.ID);
World.NotifySlotShipArrivedShip0.Remove(entity.ID);
World.NotifySlotShipArrivedShip1.Remove(entity.ID);
}
}
}
}
public void Update(float dt, World world)
{
frame = World.frame; this.Rule2(dt, world);
this.Rule3(dt, world);
}
public void UpdateSuspendedRules(float dt, World world, List<int> toRemove, RuleTable ActiveRules)
{
if (ActiveRules.ActiveIndices.Top > 0 && frame == World.frame)
{
for (int i = 0; i < ActiveRules.ActiveIndices.Top; i++)
{
var x = ActiveRules.ActiveIndices.Elements[i];
switch (x)
{
case 0:
if (this.Rule0(dt, world) == RuleResult.Done)
{
ActiveRules.ActiveSlots[i] = false;
ActiveRules.ActiveIndices.Top--;
}
else
{
ActiveRules.SupportSlots[0] = true;
ActiveRules.SupportStack.Push(x);
}
break;
case 1:
if (this.Rule1(dt, world) == RuleResult.Done)
{
ActiveRules.ActiveSlots[i] = false;
ActiveRules.ActiveIndices.Top--;
}
else
{
ActiveRules.SupportSlots[1] = true;
ActiveRules.SupportStack.Push(x);
}
break;
default:
break;
}
}
ActiveRules.ActiveIndices.Clear();
ActiveRules.Clear();
var tmp = ActiveRules.SupportStack;
var tmp1 = ActiveRules.SupportSlots;
ActiveRules.SupportStack = ActiveRules.ActiveIndices;
ActiveRules.SupportSlots = ActiveRules.ActiveSlots;
ActiveRules.ActiveIndices = tmp;
ActiveRules.ActiveSlots = tmp1;
if (ActiveRules.ActiveIndices.Top == 0)
toRemove.Add(ID);
}
else
{
if (this.frame != World.frame)
toRemove.Add(ID);
}
}
public void Rule2(float dt, World world)
{
Position = (Position) + ((Velocity) * (dt));
}
int s3 = -1;
public void Rule3(float dt, World world)
{
switch (s3)
{
case -1:
if (!(((5f) > (UnityEngine.Vector3.Distance(Position, Target.Position)))))
{
s3 = -1;
return;
}
else
{
goto case 0;
}
case 0:
Arrived = true;
Position = Target.Position;
Velocity = Vector3.zero;
Destroyed = true;
s3 = -1;
return;
default: return;
}
}
int s0 = -1;
public RuleResult Rule0(float dt, World world)
{
switch (s0)
{
case -1:
_cond01 = Arrived;
_cond11 = Destroyed;
goto case 11;
case 11:
if (!(((!(((_cond11) == (Destroyed)))) || (((!(((_cond01) == (Arrived)))) || (false))))))
{
s0 = 11;
return RuleResult.Done;
}
else
{
goto case 2;
}
case 2:
if (((!(Arrived)) && (!(Destroyed))))
{
goto case 0;
}
else
{
goto case 1;
}
case 0:
if (!(_StarSystem.StarSystem1.Contains(this)))
{
goto case 3;
}
else
{
goto case 4;
}
case 3:
_StarSystem.StarSystem1.Add(this);
goto case -1;
case 4:
goto case -1;
case 1:
_StarSystem.StarSystem1.Remove(this);
goto case -1;
default: return RuleResult.Done;
}
}
int s1 = -1;
public RuleResult Rule1(float dt, World world)
{
switch (s1)
{
case -1:
_cond02 = Arrived;
_cond12 = Target;
goto case 11;
case 11:
if (!(((!(((_cond12) == (_Planet)))) || (((!(((_cond02) == (Arrived)))) || (false))))))
{
s1 = 11;
return RuleResult.Done;
}
else
{
goto case 2;
}
case 2:
if (((Arrived) && (((Target) == (_Planet)))))
{
goto case 0;
}
else
{
goto case 1;
}
case 0:
if (!(_Planet.Planet2.Contains(this)))
{
goto case 3;
}
else
{
goto case 4;
}
case 3:
_Planet.Planet2.Add(this);
goto case -1;
case 4:
goto case -1;
case 1:
_Planet.Planet2.Remove(this);
goto case -1;
default: return RuleResult.Done;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Linq;
using System.Runtime.InteropServices;
using Xunit;
namespace System.IO.Tests
{
public class Directory_Exists : FileSystemTest
{
#region Utilities
public bool Exists(string path)
{
return Directory.Exists(path);
}
#endregion
#region UniversalTests
[Fact]
public void NullAsPath_ReturnsFalse()
{
Assert.False(Exists(null));
}
[Fact]
public void EmptyAsPath_ReturnsFalse()
{
Assert.False(Exists(string.Empty));
}
[Fact]
public void NonExistentValidPath_ReturnsFalse()
{
Assert.All((IOInputs.GetValidPathComponentNames()), (path) =>
{
Assert.False(Exists(path), path);
});
}
[Fact]
public void ValidPathExists_ReturnsTrue()
{
Assert.All((IOInputs.GetValidPathComponentNames()), (component) =>
{
string path = Path.Combine(TestDirectory, component);
DirectoryInfo testDir = Directory.CreateDirectory(path);
Assert.True(Exists(path));
});
}
[Fact]
public void PathWithInvalidCharactersAsPath_ReturnsFalse()
{
// Checks that errors aren't thrown when calling Exists() on paths with impossible to create characters
char[] trimmed = { (char)0x9, (char)0xA, (char)0xB, (char)0xC, (char)0xD, (char)0x20, (char)0x85, (char)0xA0 };
Assert.All((IOInputs.GetPathsWithInvalidCharacters()), (component) =>
{
Assert.False(Exists(component));
if (!trimmed.Contains(component.ToCharArray()[0]))
Assert.False(Exists(TestDirectory + Path.DirectorySeparatorChar + component));
});
}
[Fact]
public void PathAlreadyExistsAsFile()
{
string path = GetTestFilePath();
File.Create(path).Dispose();
Assert.False(Exists(IOServices.RemoveTrailingSlash(path)));
Assert.False(Exists(IOServices.RemoveTrailingSlash(IOServices.RemoveTrailingSlash(path))));
Assert.False(Exists(IOServices.RemoveTrailingSlash(IOServices.AddTrailingSlashIfNeeded(path))));
}
[Fact]
public void PathAlreadyExistsAsDirectory()
{
string path = GetTestFilePath();
DirectoryInfo testDir = Directory.CreateDirectory(path);
Assert.True(Exists(IOServices.RemoveTrailingSlash(path)));
Assert.True(Exists(IOServices.RemoveTrailingSlash(IOServices.RemoveTrailingSlash(path))));
Assert.True(Exists(IOServices.RemoveTrailingSlash(IOServices.AddTrailingSlashIfNeeded(path))));
}
[Fact]
public void DotAsPath_ReturnsTrue()
{
Assert.True(Exists(Path.Combine(TestDirectory, ".")));
}
[Fact]
public void DirectoryGetCurrentDirectoryAsPath_ReturnsTrue()
{
Assert.True(Exists(Directory.GetCurrentDirectory()));
}
[Fact]
public void DotDotAsPath_ReturnsTrue()
{
Assert.True(Exists(Path.Combine(TestDirectory, GetTestFileName(), "..")));
}
[Fact]
public void DirectoryLongerThanMaxLongPath_DoesntThrow()
{
Assert.All((IOInputs.GetPathsLongerThanMaxLongPath(GetTestFilePath())), (path) =>
{
Assert.False(Exists(path), path);
});
}
#endregion
#region PlatformSpecific
[Fact]
[PlatformSpecific(PlatformID.Windows)]
public void ValidExtendedPathExists_ReturnsTrue()
{
Assert.All((IOInputs.GetValidPathComponentNames()), (component) =>
{
string path = IOInputs.ExtendedPrefix + Path.Combine(TestDirectory, "extended", component);
DirectoryInfo testDir = Directory.CreateDirectory(path);
Assert.True(Exists(path));
});
}
[Fact]
[PlatformSpecific(PlatformID.Windows)]
public void ExtendedPathAlreadyExistsAsFile()
{
string path = IOInputs.ExtendedPrefix + GetTestFilePath();
File.Create(path).Dispose();
Assert.False(Exists(IOServices.RemoveTrailingSlash(path)));
Assert.False(Exists(IOServices.RemoveTrailingSlash(IOServices.RemoveTrailingSlash(path))));
Assert.False(Exists(IOServices.RemoveTrailingSlash(IOServices.AddTrailingSlashIfNeeded(path))));
}
[Fact]
[PlatformSpecific(PlatformID.Windows)]
public void ExtendedPathAlreadyExistsAsDirectory()
{
string path = IOInputs.ExtendedPrefix + GetTestFilePath();
DirectoryInfo testDir = Directory.CreateDirectory(path);
Assert.True(Exists(IOServices.RemoveTrailingSlash(path)));
Assert.True(Exists(IOServices.RemoveTrailingSlash(IOServices.RemoveTrailingSlash(path))));
Assert.True(Exists(IOServices.RemoveTrailingSlash(IOServices.AddTrailingSlashIfNeeded(path))));
}
[Fact]
[PlatformSpecific(PlatformID.Windows)]
public void DirectoryLongerThanMaxDirectoryAsPath_DoesntThrow()
{
Assert.All((IOInputs.GetPathsLongerThanMaxDirectory(GetTestFilePath())), (path) =>
{
Assert.False(Exists(path));
});
}
[Fact]
[PlatformSpecific(PlatformID.Windows)] // Unix equivalent tested already in CreateDirectory
public void WindowsWhiteSpaceAsPath_ReturnsFalse()
{
// Checks that errors aren't thrown when calling Exists() on impossible paths
Assert.All(IOInputs.GetWhiteSpace(), (component) =>
{
Assert.False(Exists(component));
});
}
[Fact]
[PlatformSpecific(PlatformID.Windows | PlatformID.OSX)]
public void DoesCaseInsensitiveInvariantComparisons()
{
DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath());
Assert.True(Exists(testDir.FullName));
Assert.True(Exists(testDir.FullName.ToUpperInvariant()));
Assert.True(Exists(testDir.FullName.ToLowerInvariant()));
}
[Fact]
[PlatformSpecific(PlatformID.Linux | PlatformID.FreeBSD)]
public void DoesCaseSensitiveComparisons()
{
DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath());
Assert.True(Exists(testDir.FullName));
Assert.False(Exists(testDir.FullName.ToUpperInvariant()));
Assert.False(Exists(testDir.FullName.ToLowerInvariant()));
}
[Fact]
[PlatformSpecific(PlatformID.Windows)] // In Windows, trailing whitespace in a path is trimmed appropriately
public void TrailingWhitespaceExistence()
{
DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath());
Assert.All(IOInputs.GetWhiteSpace(), (component) =>
{
string path = testDir.FullName + component;
Assert.True(Exists(path), path); // string concat in case Path.Combine() trims whitespace before Exists gets to it
Assert.False(Exists(IOInputs.ExtendedPrefix + path), path);
});
Assert.All(IOInputs.GetSimpleWhiteSpace(), (component) =>
{
string path = GetTestFilePath(memberName: "Extended") + component;
testDir = Directory.CreateDirectory(IOInputs.ExtendedPrefix + path);
Assert.False(Exists(path), path);
Assert.True(Exists(testDir.FullName));
});
}
[Fact]
[PlatformSpecific(PlatformID.Windows)] // alternate data stream
public void PathWithAlternateDataStreams_ReturnsFalse()
{
Assert.All(IOInputs.GetWhiteSpace(), (component) =>
{
Assert.False(Exists(component));
});
}
[Fact]
[OuterLoop]
[PlatformSpecific(PlatformID.Windows)] // device names
public void PathWithReservedDeviceNameAsPath_ReturnsFalse()
{
Assert.All((IOInputs.GetPathsWithReservedDeviceNames()), (component) =>
{
Assert.False(Exists(component));
});
}
[Fact]
[PlatformSpecific(PlatformID.Windows)] // UNC paths
public void UncPathWithoutShareNameAsPath_ReturnsFalse()
{
Assert.All((IOInputs.GetUncPathsWithoutShareName()), (component) =>
{
Assert.False(Exists(component));
});
}
[Fact]
[PlatformSpecific(PlatformID.Windows)] // max directory length not fixed on Unix
public void DirectoryEqualToMaxDirectory_ReturnsTrue()
{
// Creates directories up to the maximum directory length all at once
DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath());
PathInfo path = IOServices.GetPath(testDir.FullName, IOInputs.MaxDirectory, maxComponent: 10);
Directory.CreateDirectory(path.FullPath);
Assert.True(Exists(path.FullPath));
}
[Fact]
[PlatformSpecific(PlatformID.Windows)] // max directory length not fixed on Unix
public void DirectoryWithComponentLongerThanMaxComponentAsPath_ReturnsFalse()
{
Assert.All((IOInputs.GetPathsWithComponentLongerThanMaxComponent()), (component) =>
{
Assert.False(Exists(component));
});
}
[Fact]
[ActiveIssue(1221)]
[PlatformSpecific(PlatformID.Windows)] // drive labels
public void NotReadyDriveAsPath_ReturnsFalse()
{
var drive = IOServices.GetNotReadyDrive();
if (drive == null)
{
Console.WriteLine("Skipping test. Unable to find a not-ready drive, such as CD-Rom with no disc inserted.");
return;
}
bool result = Exists(drive);
Assert.False(result);
}
[Fact]
[ActiveIssue(1221)]
[PlatformSpecific(PlatformID.Windows)] // drive labels
public void SubdirectoryOnNotReadyDriveAsPath_ReturnsFalse()
{
var drive = IOServices.GetNotReadyDrive();
if (drive == null)
{
Console.WriteLine("Skipping test. Unable to find a not-ready drive, such as CD-Rom with no disc inserted.");
return;
}
bool result = Exists(Path.Combine(drive, "Subdirectory"));
Assert.False(result);
}
[Fact]
[PlatformSpecific(PlatformID.Windows)] // drive labels
public void NonExistentDriveAsPath_ReturnsFalse()
{
Assert.False(Exists(IOServices.GetNonExistentDrive()));
}
[Fact]
[PlatformSpecific(PlatformID.Windows)] // drive labels
public void SubdirectoryOnNonExistentDriveAsPath_ReturnsFalse()
{
Assert.False(Exists(Path.Combine(IOServices.GetNonExistentDrive(), "nonexistentsubdir")));
}
[ConditionalFact("CanCreateSymbolicLinks")]
public void SymlinkToNewDirectory()
{
string targetPath = GetTestFilePath();
Directory.CreateDirectory(targetPath);
string linkPath = GetTestFilePath();
Assert.True(MountHelper.CreateSymbolicLink(linkPath, targetPath));
Assert.NotEqual(RuntimeInformation.IsOSPlatform(OSPlatform.Windows), Directory.Exists(linkPath));
}
#endregion
}
}
| |
using System;
using System.Threading;
namespace M2SA.AppGenome.Threading.Internal
{
#region WorkItemsQueue class
/// <summary>
/// WorkItemsQueue class.
/// </summary>
public class WorkItemsQueue : IDisposable
{
#region Member variables
/// <summary>
/// Waiters queue (implemented as stack).
/// </summary>
private readonly WaiterEntry _headWaiterEntry = new WaiterEntry();
/// <summary>
/// Waiters count
/// </summary>
private int _waitersCount = 0;
/// <summary>
/// Work items queue
/// </summary>
private readonly PriorityQueue _workItems = new PriorityQueue();
/// <summary>
/// Indicate that work items are allowed to be queued
/// </summary>
private bool _isWorkItemsQueueActive = true;
#if (_WINDOWS_CE)
private static LocalDataStoreSlot _waiterEntrySlot = Thread.AllocateDataSlot();
#else
[ThreadStatic]
private static WaiterEntry _waiterEntry;
#endif
/// <summary>
/// Each thread in the thread pool keeps its own waiter entry.
/// </summary>
private static WaiterEntry CurrentWaiterEntry
{
#if (_WINDOWS_CE)
get
{
return Thread.GetData(_waiterEntrySlot) as WaiterEntry;
}
set
{
Thread.SetData(_waiterEntrySlot, value);
}
#else
get
{
return _waiterEntry;
}
set
{
_waiterEntry = value;
}
#endif
}
/// <summary>
/// A flag that indicates if the WorkItemsQueue has been disposed.
/// </summary>
private bool _isDisposed = false;
#endregion
#region Public properties
/// <summary>
/// Returns the current number of work items in the queue
/// </summary>
public int Count
{
get
{
return _workItems.Count;
}
}
/// <summary>
/// Returns the current number of waiters
/// </summary>
public int WaitersCount
{
get
{
return _waitersCount;
}
}
#endregion
#region Public methods
/// <summary>
/// Enqueue a work item to the queue.
/// </summary>
public bool EnqueueWorkItem(WorkItem workItem)
{
// A work item cannot be null, since null is used in the
// WaitForWorkItem() method to indicate timeout or cancel
if (null == workItem)
{
throw new ArgumentNullException("workItem" , "workItem cannot be null");
}
bool enqueue = true;
// First check if there is a waiter waiting for work item. During
// the check, timed out waiters are ignored. If there is no
// waiter then the work item is queued.
lock(this)
{
ValidateNotDisposed();
if (!_isWorkItemsQueueActive)
{
return false;
}
while(_waitersCount > 0)
{
// Dequeue a waiter.
WaiterEntry waiterEntry = PopWaiter();
// Signal the waiter. On success break the loop
if (waiterEntry.Signal(workItem))
{
enqueue = false;
break;
}
}
if (enqueue)
{
// Enqueue the work item
_workItems.Enqueue(workItem);
}
}
return true;
}
/// <summary>
/// Waits for a work item or exits on timeout or cancel
/// </summary>
/// <param name="millisecondsTimeout">Timeout in milliseconds</param>
/// <param name="cancelEvent">Cancel wait handle</param>
/// <returns>Returns true if the resource was granted</returns>
public WorkItem DequeueWorkItem(
int millisecondsTimeout,
WaitHandle cancelEvent)
{
// This method cause the caller to wait for a work item.
// If there is at least one waiting work item then the
// method returns immidiately with it.
//
// If there are no waiting work items then the caller
// is queued between other waiters for a work item to arrive.
//
// If a work item didn't come within millisecondsTimeout or
// the user canceled the wait by signaling the cancelEvent
// then the method returns null to indicate that the caller
// didn't get a work item.
WaiterEntry waiterEntry;
WorkItem workItem = null;
try
{
while (!Monitor.TryEnter(this)) { }
//Stopwatch stopwatch = Stopwatch.StartNew();
//Monitor.Enter(this);
//stopwatch.Stop();
ValidateNotDisposed();
// If there are waiting work items then take one and return.
if (_workItems.Count > 0)
{
workItem = _workItems.Dequeue() as WorkItem;
return workItem;
}
// No waiting work items ...
// Get the waiter entry for the waiters queue
waiterEntry = GetThreadWaiterEntry();
// Put the waiter with the other waiters
PushWaiter(waiterEntry);
}
finally
{
Monitor.Exit(this);
}
// Prepare array of wait handle for the WaitHandle.WaitAny()
WaitHandle [] waitHandles = new WaitHandle[] {
waiterEntry.WaitHandle,
cancelEvent };
// Wait for an available resource, cancel event, or timeout.
// During the wait we are supposes to exit the synchronization
// domain. (Placing true as the third argument of the WaitAny())
// It just doesn't work, I don't know why, so I have two lock(this)
// statments instead of one.
int index = STPEventWaitHandle.WaitAny(
waitHandles,
millisecondsTimeout,
true);
lock(this)
{
// success is true if it got a work item.
bool success = (0 == index);
// The timeout variable is used only for readability.
// (We treat cancel as timeout)
bool timeout = !success;
// On timeout update the waiterEntry that it is timed out
if (timeout)
{
// The Timeout() fails if the waiter has already been signaled
timeout = waiterEntry.Timeout();
// On timeout remove the waiter from the queue.
// Note that the complexity is O(1).
if(timeout)
{
RemoveWaiter(waiterEntry, false);
}
// Again readability
success = !timeout;
}
// On success return the work item
if (success)
{
workItem = waiterEntry.WorkItem;
if (null == workItem)
{
workItem = _workItems.Dequeue() as WorkItem;
}
}
}
// On failure return null.
return workItem;
}
/// <summary>
/// Cleanup the work items queue, hence no more work
/// items are allowed to be queue
/// </summary>
private void Cleanup()
{
lock(this)
{
// Deactivate only once
if (!_isWorkItemsQueueActive)
{
return;
}
// Don't queue more work items
_isWorkItemsQueueActive = false;
foreach(WorkItem workItem in _workItems)
{
workItem.DisposeOfState();
}
// Clear the work items that are already queued
_workItems.Clear();
// Note:
// I don't iterate over the queue and dispose of work items's states,
// since if a work item has a state object that is still in use in the
// application then I must not dispose it.
// Tell the waiters that they were timed out.
// It won't signal them to exit, but to ignore their
// next work item.
while(_waitersCount > 0)
{
WaiterEntry waiterEntry = PopWaiter();
waiterEntry.Timeout();
}
if (null != this._headWaiterEntry)
{
this._headWaiterEntry.Close();
}
}
}
/// <summary>
///
/// </summary>
/// <returns></returns>
public object[] GetStates()
{
lock (this)
{
object[] states = new object[_workItems.Count];
int i = 0;
foreach (WorkItem workItem in _workItems)
{
states[i] = workItem.GetWorkItemResult().State;
++i;
}
return states;
}
}
#endregion
#region Private methods
/// <summary>
/// Returns the WaiterEntry of the current thread
/// </summary>
/// <returns></returns>
/// In order to avoid creation and destuction of WaiterEntry
/// objects each thread has its own WaiterEntry object.
private static WaiterEntry GetThreadWaiterEntry()
{
if (null == CurrentWaiterEntry)
{
CurrentWaiterEntry = new WaiterEntry();
}
CurrentWaiterEntry.Reset();
return CurrentWaiterEntry;
}
#region Waiters stack methods
/// <summary>
/// Push a new waiter into the waiter's stack
/// </summary>
/// <param name="newWaiterEntry">A waiter to put in the stack</param>
public void PushWaiter(WaiterEntry newWaiterEntry)
{
if (null == newWaiterEntry)
throw new ArgumentNullException("newWaiterEntry");
// Remove the waiter if it is already in the stack and
// update waiter's count as needed
RemoveWaiter(newWaiterEntry, false);
// If the stack is empty then newWaiterEntry is the new head of the stack
if (null == _headWaiterEntry._nextWaiterEntry)
{
_headWaiterEntry._nextWaiterEntry = newWaiterEntry;
newWaiterEntry._prevWaiterEntry = _headWaiterEntry;
}
// If the stack is not empty then put newWaiterEntry as the new head
// of the stack.
else
{
// Save the old first waiter entry
WaiterEntry oldFirstWaiterEntry = _headWaiterEntry._nextWaiterEntry;
// Update the links
_headWaiterEntry._nextWaiterEntry = newWaiterEntry;
newWaiterEntry._nextWaiterEntry = oldFirstWaiterEntry;
newWaiterEntry._prevWaiterEntry = _headWaiterEntry;
oldFirstWaiterEntry._prevWaiterEntry = newWaiterEntry;
}
// Increment the number of waiters
++_waitersCount;
}
/// <summary>
/// Pop a waiter from the waiter's stack
/// </summary>
/// <returns>Returns the first waiter in the stack</returns>
private WaiterEntry PopWaiter()
{
// Store the current stack head
WaiterEntry oldFirstWaiterEntry = _headWaiterEntry._nextWaiterEntry;
// Store the new stack head
WaiterEntry newHeadWaiterEntry = oldFirstWaiterEntry._nextWaiterEntry;
// Update the old stack head list links and decrement the number
// waiters.
RemoveWaiter(oldFirstWaiterEntry, true);
// Update the new stack head
_headWaiterEntry._nextWaiterEntry = newHeadWaiterEntry;
if (null != newHeadWaiterEntry)
{
newHeadWaiterEntry._prevWaiterEntry = _headWaiterEntry;
}
// Return the old stack head
return oldFirstWaiterEntry;
}
/// <summary>
/// Remove a waiter from the stack
/// </summary>
/// <param name="waiterEntry">A waiter entry to remove</param>
/// <param name="popDecrement">If true the waiter count is always decremented</param>
private void RemoveWaiter(WaiterEntry waiterEntry, bool popDecrement)
{
// Store the prev entry in the list
WaiterEntry prevWaiterEntry = waiterEntry._prevWaiterEntry;
// Store the next entry in the list
WaiterEntry nextWaiterEntry = waiterEntry._nextWaiterEntry;
// A flag to indicate if we need to decrement the waiters count.
// If we got here from PopWaiter then we must decrement.
// If we got here from PushWaiter then we decrement only if
// the waiter was already in the stack.
bool decrementCounter = popDecrement;
// Null the waiter's entry links
waiterEntry._prevWaiterEntry = null;
waiterEntry._nextWaiterEntry = null;
// If the waiter entry had a prev link then update it.
// It also means that the waiter is already in the list and we
// need to decrement the waiters count.
if (null != prevWaiterEntry)
{
prevWaiterEntry._nextWaiterEntry = nextWaiterEntry;
decrementCounter = true;
}
// If the waiter entry had a next link then update it.
// It also means that the waiter is already in the list and we
// need to decrement the waiters count.
if (null != nextWaiterEntry)
{
nextWaiterEntry._prevWaiterEntry = prevWaiterEntry;
decrementCounter = true;
}
// Decrement the waiters count if needed
if (decrementCounter)
{
--_waitersCount;
}
}
#endregion
#endregion
#region WaiterEntry class
/// <summary>
/// A waiter entry in the _waiters queue.
/// </summary>
public sealed class WaiterEntry : IDisposable
{
#region Member variables
/// <summary>
/// Event to signal the waiter that it got the work item.
/// </summary>
//private AutoResetEvent _waitHandle = new AutoResetEvent(false);
private AutoResetEvent _waitHandle = EventWaitHandleFactory.CreateAutoResetEvent();
/// <summary>
/// Flag to know if this waiter already quited from the queue
/// because of a timeout.
/// </summary>
private bool _isTimedout = false;
/// <summary>
/// Flag to know if the waiter was signaled and got a work item.
/// </summary>
private bool _isSignaled = false;
/// <summary>
/// A work item that passed directly to the waiter withou going
/// through the queue
/// </summary>
private WorkItem _workItem = null;
private bool _isDisposed = false;
// Linked list members
internal WaiterEntry _nextWaiterEntry = null;
internal WaiterEntry _prevWaiterEntry = null;
#endregion
#region Construction
/// <summary>
///
/// </summary>
public WaiterEntry()
{
Reset();
}
#endregion
#region Public methods
/// <summary>
///
/// </summary>
public WaitHandle WaitHandle
{
get { return _waitHandle; }
}
/// <summary>
///
/// </summary>
public WorkItem WorkItem
{
get
{
return _workItem;
}
}
/// <summary>
/// Signal the waiter that it got a work item.
/// </summary>
/// <returns>Return true on success</returns>
/// The method fails if Timeout() preceded its call
public bool Signal(WorkItem workItem)
{
lock(this)
{
if (!_isTimedout)
{
_workItem = workItem;
_isSignaled = true;
_waitHandle.Set();
return true;
}
}
return false;
}
/// <summary>
/// Mark the wait entry that it has been timed out
/// </summary>
/// <returns>Return true on success</returns>
/// The method fails if Signal() preceded its call
public bool Timeout()
{
lock(this)
{
// Time out can happen only if the waiter wasn't marked as
// signaled
if (!_isSignaled)
{
// We don't remove the waiter from the queue, the DequeueWorkItem
// method skips _waiters that were timed out.
_isTimedout = true;
return true;
}
}
return false;
}
/// <summary>
/// Reset the wait entry so it can be used again
/// </summary>
public void Reset()
{
_workItem = null;
_isTimedout = false;
_isSignaled = false;
_waitHandle.Reset();
}
/// <summary>
/// Free resources
/// </summary>
public void Close()
{
if (null != _waitHandle)
{
_waitHandle.Close();
_waitHandle = null;
}
}
#endregion
#region IDisposable Members
/// <summary>
///
/// </summary>
public void Dispose()
{
lock (this)
{
if (!_isDisposed)
{
Close();
}
_isDisposed = true;
}
}
#endregion
}
#endregion
#region IDisposable Members
/// <summary>
///
/// </summary>
public void Dispose()
{
if (!_isDisposed)
{
Cleanup();
}
_isDisposed = true;
}
private void ValidateNotDisposed()
{
if(_isDisposed)
{
throw new ObjectDisposedException(GetType().ToString(), "The SmartThreadPool has been shutdown");
}
}
#endregion
}
#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;
// Test case for fix 20838
// We are a missing check for ZeroOffsetFldSeq values on LclVar reads
// without the fix several cases in this test fail because value numbering
// gives us the old value instead of the modified value.
//
// CoreRun.exe GitHub_18259.exe
// Failed - Test_e0_S2_F3_F1() - 640 -- 512 + 128
// Failed - Test_e0_S2_F4_F1() - 960 -- 512 + 256 + 128 + 64
// Failed - Test_e1_S2_F3_F1() - 640
// Failed - Test_e1_S2_F4_F1() - 960
struct S1
{
public int F1;
public int F2;
public S1(int a1, int a2) { F1 = a1; F2 = a2; }
}
struct S2
{
public S1 F3;
public S1 F4;
public S2(S1 a1, S1 a2) { F3 = a1; F4 = a2; }
}
public class Program
{
static S1 ss_S1a = new S1(101, 102);
static S1 ss_S1b = new S1(103, 104);
static S1 ss_S1c = new S1(105, 106);
static S1 ss_S1d = new S1(107, 108);
static S2 ss_S2a = new S2(ss_S1a, ss_S1b);
static S2 ss_S2b = new S2(ss_S1c, ss_S1d);
static S2[] sa_S2 = new S2[] { ss_S2a, ss_S2b };
static bool Test_e0_S2_F3_F1()
{
ref S2 ref_e0_S2 = ref sa_S2[0];
ref S1 ref_e0_S2_F3 = ref sa_S2[0].F3;
ref int ref_e0_S2_F3_F1 = ref sa_S2[0].F3.F1;
int result = 0;
if (sa_S2[0].F3.F1 != 101)
{
result |= 1;
}
if (ref_e0_S2_F3_F1 != 101)
{
result |= 2;
}
if (ref_e0_S2_F3.F1 != 101)
{
result |= 4;
}
if (ref_e0_S2.F3.F1 != 101)
{
result |= 8;
}
if (ref_e0_S2_F3.F1 != 101)
{
result |= 16;
}
ref_e0_S2_F3.F1 = 99;
if (sa_S2[0].F3.F1 != 99)
{
result |= 32;
}
if (ref_e0_S2_F3_F1 != 99)
{
result |= 64;
}
if (ref_e0_S2_F3.F1 != 99)
{
result |= 128;
}
if (ref_e0_S2.F3.F1 != 99)
{
result |= 256;
}
if (ref_e0_S2_F3.F1 != 99)
{
result |= 512;
}
if (result != 0)
{
Console.WriteLine("Failed - Test_e0_S2_F3_F1() - " + result);
return false;
}
return true;
}
static bool Test_e0_S2_F3_F2()
{
ref S2 ref_e0_S2 = ref sa_S2[0];
ref S1 ref_e0_S2_F3 = ref sa_S2[0].F3;
ref int ref_e0_S2_F3_F2 = ref sa_S2[0].F3.F2;
int result = 0;
if (sa_S2[0].F3.F2 != 102)
{
result |= 1;
}
if (ref_e0_S2_F3_F2 != 102)
{
result |= 2;
}
if (ref_e0_S2_F3.F2 != 102)
{
result |= 4;
}
if (ref_e0_S2.F3.F2 != 102)
{
result |= 8;
}
if (ref_e0_S2_F3.F2 != 102)
{
result |= 16;
}
ref_e0_S2_F3.F2 = 98;
if (sa_S2[0].F3.F2 != 98)
{
result |= 32;
}
if (ref_e0_S2_F3_F2 != 98)
{
result |= 64;
}
if (ref_e0_S2_F3.F2 != 98)
{
result |= 128;
}
if (ref_e0_S2.F3.F2 != 98)
{
result |= 256;
}
if (ref_e0_S2_F3.F2 != 98)
{
result |= 512;
}
if (result != 0)
{
Console.WriteLine("Failed - Test_e0_S2_F3_F2() - " + result);
return false;
}
return true;
}
static bool Test_e0_S2_F4_F1()
{
ref S2 ref_e0_S2 = ref sa_S2[0];
ref S1 ref_e0_S2_F4 = ref sa_S2[0].F4;
ref int ref_e0_S2_F4_F1 = ref sa_S2[0].F4.F1;
int result = 0;
if (sa_S2[0].F4.F1 != 103)
{
result |= 1;
}
if (ref_e0_S2_F4_F1 != 103)
{
result |= 2;
}
if (ref_e0_S2_F4.F1 != 103)
{
result |= 4;
}
if (ref_e0_S2.F4.F1 != 103)
{
result |= 8;
}
if (ref_e0_S2_F4.F1 != 103)
{
result |= 16;
}
ref_e0_S2_F4.F1 = 97;
if (sa_S2[0].F4.F1 != 97)
{
result |= 32;
}
if (ref_e0_S2_F4_F1 != 97)
{
result |= 64;
}
if (ref_e0_S2_F4.F1 != 97)
{
result |= 128;
}
if (ref_e0_S2.F4.F1 != 97)
{
result |= 256;
}
if (ref_e0_S2_F4.F1 != 97)
{
result |= 512;
}
if (result != 0)
{
Console.WriteLine("Failed - Test_e0_S2_F4_F1() - " + result);
return false;
}
return true;
}
static bool Test_e0_S2_F4_F2()
{
ref S2 ref_e0_S2 = ref sa_S2[0];
ref S1 ref_e0_S2_F4 = ref sa_S2[0].F4;
ref int ref_e0_S2_F4_F2 = ref sa_S2[0].F4.F2;
int result = 0;
if (sa_S2[0].F4.F2 != 104)
{
result |= 1;
}
if (ref_e0_S2_F4_F2 != 104)
{
result |= 2;
}
if (ref_e0_S2_F4.F2 != 104)
{
result |= 4;
}
if (ref_e0_S2.F4.F2 != 104)
{
result |= 8;
}
if (ref_e0_S2_F4.F2 != 104)
{
result |= 16;
}
ref_e0_S2_F4.F2 = 96;
if (sa_S2[0].F4.F2 != 96)
{
result |= 32;
}
if (ref_e0_S2_F4_F2 != 96)
{
result |= 64;
}
if (ref_e0_S2_F4.F2 != 96)
{
result |= 128;
}
if (ref_e0_S2.F4.F2 != 96)
{
result |= 256;
}
if (ref_e0_S2_F4.F2 != 96)
{
result |= 512;
}
if (result != 0)
{
Console.WriteLine("Failed - Test_e0_S2_F4_F2() - " + result);
return false;
}
return true;
}
static bool Test_e1_S2_F3_F1()
{
ref S2 ref_e1_S2 = ref sa_S2[1];
ref S1 ref_e1_S2_F3 = ref sa_S2[1].F3;
ref int ref_e1_S2_F3_F1 = ref sa_S2[1].F3.F1;
int result = 0;
if (sa_S2[1].F3.F1 != 105)
{
result |= 1;
}
if (ref_e1_S2_F3_F1 != 105)
{
result |= 2;
}
if (ref_e1_S2_F3.F1 != 105)
{
result |= 4;
}
if (ref_e1_S2.F3.F1 != 105)
{
result |= 8;
}
if (ref_e1_S2_F3.F1 != 105)
{
result |= 16;
}
ref_e1_S2_F3.F1 = 95;
if (sa_S2[1].F3.F1 != 95)
{
result |= 32;
}
if (ref_e1_S2_F3_F1 != 95)
{
result |= 64;
}
if (ref_e1_S2_F3.F1 != 95)
{
result |= 128;
}
if (ref_e1_S2.F3.F1 != 95)
{
result |= 256;
}
if (ref_e1_S2_F3.F1 != 95)
{
result |= 512;
}
if (result != 0)
{
Console.WriteLine("Failed - Test_e1_S2_F3_F1() - " + result);
return false;
}
return true;
}
static bool Test_e1_S2_F3_F2()
{
ref S2 ref_e1_S2 = ref sa_S2[1];
ref S1 ref_e1_S2_F3 = ref sa_S2[1].F3;
ref int ref_e1_S2_F3_F2 = ref sa_S2[1].F3.F2;
int result = 0;
if (sa_S2[1].F3.F2 != 106)
{
result |= 1;
}
if (ref_e1_S2_F3_F2 != 106)
{
result |= 2;
}
if (ref_e1_S2_F3.F2 != 106)
{
result |= 4;
}
if (ref_e1_S2.F3.F2 != 106)
{
result |= 8;
}
if (ref_e1_S2_F3.F2 != 106)
{
result |= 16;
}
ref_e1_S2_F3.F2 = 94;
if (sa_S2[1].F3.F2 != 94)
{
result |= 32;
}
if (ref_e1_S2_F3_F2 != 94)
{
result |= 64;
}
if (ref_e1_S2_F3.F2 != 94)
{
result |= 128;
}
if (ref_e1_S2.F3.F2 != 94)
{
result |= 256;
}
if (ref_e1_S2_F3.F2 != 94)
{
result |= 512;
}
if (result != 0)
{
Console.WriteLine("Failed - Test_e1_S2_F3_F2() - " + result);
return false;
}
return true;
}
static bool Test_e1_S2_F4_F1()
{
ref S2 ref_e1_S2 = ref sa_S2[1];
ref S1 ref_e1_S2_F4 = ref sa_S2[1].F4;
ref int ref_e1_S2_F4_F1 = ref sa_S2[1].F4.F1;
int result = 0;
if (sa_S2[1].F4.F1 != 107)
{
result |= 1;
}
if (ref_e1_S2_F4_F1 != 107)
{
result |= 2;
}
if (ref_e1_S2_F4.F1 != 107)
{
result |= 4;
}
if (ref_e1_S2.F4.F1 != 107)
{
result |= 8;
}
if (ref_e1_S2_F4.F1 != 107)
{
result |= 16;
}
ref_e1_S2_F4.F1 = 93;
if (sa_S2[1].F4.F1 != 93)
{
result |= 32;
}
if (ref_e1_S2_F4_F1 != 93)
{
result |= 64;
}
if (ref_e1_S2_F4.F1 != 93)
{
result |= 128;
}
if (ref_e1_S2.F4.F1 != 93)
{
result |= 256;
}
if (ref_e1_S2_F4.F1 != 93)
{
result |= 512;
}
if (result != 0)
{
Console.WriteLine("Failed - Test_e1_S2_F4_F1() - " + result);
return false;
}
return true;
}
static bool Test_e1_S2_F4_F2()
{
ref S2 ref_e1_S2 = ref sa_S2[1];
ref S1 ref_e1_S2_F4 = ref sa_S2[1].F4;
ref int ref_e1_S2_F4_F2 = ref sa_S2[1].F4.F2;
int result = 0;
if (sa_S2[1].F4.F2 != 108)
{
result |= 1;
}
if (ref_e1_S2_F4_F2 != 108)
{
result |= 2;
}
if (ref_e1_S2_F4.F2 != 108)
{
result |= 4;
}
if (ref_e1_S2.F4.F2 != 108)
{
result |= 8;
}
if (ref_e1_S2_F4.F2 != 108)
{
result |= 16;
}
ref_e1_S2_F4.F2 = 92;
if (sa_S2[1].F4.F2 != 92)
{
result |= 32;
}
if (ref_e1_S2_F4_F2 != 92)
{
result |= 64;
}
if (ref_e1_S2_F4.F2 != 92)
{
result |= 128;
}
if (ref_e1_S2.F4.F2 != 92)
{
result |= 256;
}
if (ref_e1_S2_F4.F2 != 92)
{
result |= 512;
}
if (result != 0)
{
Console.WriteLine("Failed - Test_e1_S2_F4_F2() - " + result);
return false;
}
return true;
}
public static int Main()
{
bool isPassing = true;
isPassing &= Test_e0_S2_F3_F1();
isPassing &= Test_e0_S2_F3_F2();
isPassing &= Test_e0_S2_F4_F1();
isPassing &= Test_e0_S2_F4_F2();
isPassing &= Test_e1_S2_F3_F1();
isPassing &= Test_e1_S2_F3_F2();
isPassing &= Test_e1_S2_F4_F1();
isPassing &= Test_e1_S2_F4_F2();
if (isPassing)
{
Console.WriteLine("Passed");
return 100;
}
else
{
Console.WriteLine("Failed");
return 101;
}
}
}
| |
using Orleans;
using Orleans.Runtime;
using System;
using System.Diagnostics;
using System.Threading.Tasks;
using Orleans.TestingHost.Utils;
using UnitTests.GrainInterfaces;
using UnitTests.Tester;
using Xunit;
namespace UnitTests.General
{
/// <summary>
/// Summary description for ObserverTests
/// </summary>
public class ObserverTests : HostedTestClusterEnsureDefaultStarted
{
private readonly TimeSpan timeout = Debugger.IsAttached ? TimeSpan.FromMinutes(5) : TimeSpan.FromSeconds(10);
private int callbackCounter;
private readonly bool[] callbacksRecieved = new bool[2];
// we keep the observer objects as instance variables to prevent them from
// being garbage collected permaturely (the runtime stores them as weak references).
private SimpleGrainObserver observer1;
private SimpleGrainObserver observer2;
public void TestInitialize()
{
callbackCounter = 0;
callbacksRecieved[0] = false;
callbacksRecieved[1] = false;
observer1 = null;
observer2 = null;
}
private ISimpleObserverableGrain GetGrain()
{
return GrainFactory.GetGrain<ISimpleObserverableGrain>(GetRandomGrainId());
}
[Fact, TestCategory("BVT"), TestCategory("Functional")]
public async Task ObserverTest_SimpleNotification()
{
TestInitialize();
var result = new AsyncResultHandle();
ISimpleObserverableGrain grain = GetGrain();
observer1 = new SimpleGrainObserver(ObserverTest_SimpleNotification_Callback, result);
ISimpleGrainObserver reference = await GrainFactory.CreateObjectReference<ISimpleGrainObserver>(this.observer1);
await grain.Subscribe(reference);
await grain.SetA(3);
await grain.SetB(2);
Assert.True(await result.WaitForFinished(timeout));
await GrainFactory.DeleteObjectReference<ISimpleGrainObserver>(reference);
}
[Fact, TestCategory("BVT"), TestCategory("Functional")]
public async Task ObserverTest_SimpleNotification_GeneratedFactory()
{
TestInitialize();
var result = new AsyncResultHandle();
ISimpleObserverableGrain grain = GetGrain();
observer1 = new SimpleGrainObserver(ObserverTest_SimpleNotification_Callback, result);
ISimpleGrainObserver reference = await GrainFactory.CreateObjectReference<ISimpleGrainObserver>(observer1);
await grain.Subscribe(reference);
await grain.SetA(3);
await grain.SetB(2);
Assert.True(await result.WaitForFinished(timeout));
await GrainFactory.DeleteObjectReference<ISimpleGrainObserver>(reference);
}
void ObserverTest_SimpleNotification_Callback(int a, int b, AsyncResultHandle result)
{
callbackCounter++;
logger.Info("Invoking ObserverTest_SimpleNotification_Callback for {0} time with a = {1} and b = {2}", callbackCounter, a, b);
if (a == 3 && b == 0)
callbacksRecieved[0] = true;
else if (a == 3 && b == 2)
callbacksRecieved[1] = true;
else
throw new ArgumentOutOfRangeException("Unexpected callback with values: a=" + a + ",b=" + b);
if (callbackCounter == 1)
{
// Allow for callbacks occurring in any order
Assert.True(callbacksRecieved[0] || callbacksRecieved[1]);
}
else if (callbackCounter == 2)
{
Assert.True(callbacksRecieved[0] && callbacksRecieved[1]);
result.Done = true;
}
else
{
Assert.True(false);
}
}
[Fact, TestCategory("SlowBVT"), TestCategory("Functional")]
public async Task ObserverTest_DoubleSubscriptionSameReference()
{
TestInitialize();
var result = new AsyncResultHandle();
ISimpleObserverableGrain grain = GetGrain();
observer1 = new SimpleGrainObserver(ObserverTest_DoubleSubscriptionSameReference_Callback, result);
ISimpleGrainObserver reference = await GrainFactory.CreateObjectReference<ISimpleGrainObserver>(observer1);
await grain.Subscribe(reference);
await grain.SetA(1); // Use grain
try
{
await grain.Subscribe(reference);
}
catch (TimeoutException)
{
throw;
}
catch (Exception exc)
{
Exception baseException = exc.GetBaseException();
logger.Info("Received exception: {0}", baseException);
Assert.IsAssignableFrom<OrleansException>(baseException);
if (!baseException.Message.StartsWith("Cannot subscribe already subscribed observer"))
{
Assert.True(false, "Unexpected exception message: " + baseException);
}
}
await grain.SetA(2); // Use grain
Assert.False(await result.WaitForFinished(timeout), string.Format("Should timeout waiting {0} for SetA(2)", timeout));
await GrainFactory.DeleteObjectReference<ISimpleGrainObserver>(reference);
}
void ObserverTest_DoubleSubscriptionSameReference_Callback(int a, int b, AsyncResultHandle result)
{
callbackCounter++;
logger.Info("Invoking ObserverTest_DoubleSubscriptionSameReference_Callback for {0} time with a={1} and b={2}", callbackCounter, a, b);
Assert.True(callbackCounter <= 2, "Callback has been called more times than was expected " + callbackCounter);
if (callbackCounter == 2)
{
result.Continue = true;
}
}
[Fact, TestCategory("SlowBVT"), TestCategory("Functional")]
public async Task ObserverTest_SubscribeUnsubscribe()
{
TestInitialize();
var result = new AsyncResultHandle();
ISimpleObserverableGrain grain = GetGrain();
observer1 = new SimpleGrainObserver(ObserverTest_SubscribeUnsubscribe_Callback, result);
ISimpleGrainObserver reference = await GrainFactory.CreateObjectReference<ISimpleGrainObserver>(observer1);
await grain.Subscribe(reference);
await grain.SetA(5);
Assert.True(await result.WaitForContinue(timeout), string.Format("Should not timeout waiting {0} for SetA", timeout));
await grain.Unsubscribe(reference);
await grain.SetB(3);
Assert.False(await result.WaitForFinished(timeout), string.Format("Should timeout waiting {0} for SetB", timeout));
await GrainFactory.DeleteObjectReference<ISimpleGrainObserver>(reference);
}
void ObserverTest_SubscribeUnsubscribe_Callback(int a, int b, AsyncResultHandle result)
{
callbackCounter++;
logger.Info("Invoking ObserverTest_SubscribeUnsubscribe_Callback for {0} time with a = {1} and b = {2}", callbackCounter, a, b);
Assert.True(callbackCounter < 2, "Callback has been called more times than was expected.");
Assert.Equal(5, a);
Assert.Equal(0, b);
result.Continue = true;
}
[Fact, TestCategory("BVT"), TestCategory("Functional")]
public async Task ObserverTest_Unsubscribe()
{
TestInitialize();
ISimpleObserverableGrain grain = GetGrain();
observer1 = new SimpleGrainObserver(null, null);
ISimpleGrainObserver reference = await GrainFactory.CreateObjectReference<ISimpleGrainObserver>(observer1);
try
{
await grain.Unsubscribe(reference);
await GrainFactory.DeleteObjectReference<ISimpleGrainObserver>(reference);
}
catch (TimeoutException)
{
throw;
}
catch (Exception exc)
{
Exception baseException = exc.GetBaseException();
if (!(baseException is OrleansException))
Assert.True(false);
}
}
[Fact, TestCategory("BVT"), TestCategory("Functional")]
public async Task ObserverTest_DoubleSubscriptionDifferentReferences()
{
TestInitialize();
var result = new AsyncResultHandle();
ISimpleObserverableGrain grain = GetGrain();
observer1 = new SimpleGrainObserver(ObserverTest_DoubleSubscriptionDifferentReferences_Callback, result);
ISimpleGrainObserver reference1 = await GrainFactory.CreateObjectReference<ISimpleGrainObserver>(observer1);
observer2 = new SimpleGrainObserver(ObserverTest_DoubleSubscriptionDifferentReferences_Callback, result);
ISimpleGrainObserver reference2 = await GrainFactory.CreateObjectReference<ISimpleGrainObserver>(observer2);
await grain.Subscribe(reference1);
await grain.Subscribe(reference2);
grain.SetA(6).Ignore();
Assert.True(await result.WaitForFinished(timeout), string.Format("Should not timeout waiting {0} for SetA", timeout));
await GrainFactory.DeleteObjectReference<ISimpleGrainObserver>(reference1);
await GrainFactory.DeleteObjectReference<ISimpleGrainObserver>(reference2);
}
void ObserverTest_DoubleSubscriptionDifferentReferences_Callback(int a, int b, AsyncResultHandle result)
{
callbackCounter++;
logger.Info("Invoking ObserverTest_DoubleSubscriptionDifferentReferences_Callback for {0} time with a = {1} and b = {2}", callbackCounter, a, b);
Assert.True(callbackCounter < 3, "Callback has been called more times than was expected.");
Assert.Equal(6, a);
Assert.Equal(0, b);
if (callbackCounter == 2)
result.Done = true;
}
[Fact, TestCategory("SlowBVT"), TestCategory("Functional")]
public async Task ObserverTest_DeleteObject()
{
TestInitialize();
var result = new AsyncResultHandle();
ISimpleObserverableGrain grain = GetGrain();
observer1 = new SimpleGrainObserver(ObserverTest_DeleteObject_Callback, result);
ISimpleGrainObserver reference = await GrainFactory.CreateObjectReference<ISimpleGrainObserver>(observer1);
await grain.Subscribe(reference);
await grain.SetA(5);
Assert.True(await result.WaitForContinue(timeout), string.Format("Should not timeout waiting {0} for SetA", timeout));
await GrainFactory.DeleteObjectReference<ISimpleGrainObserver>(reference);
await grain.SetB(3);
Assert.False(await result.WaitForFinished(timeout), string.Format("Should timeout waiting {0} for SetB", timeout));
}
void ObserverTest_DeleteObject_Callback(int a, int b, AsyncResultHandle result)
{
callbackCounter++;
logger.Info("Invoking ObserverTest_DeleteObject_Callback for {0} time with a = {1} and b = {2}", callbackCounter, a, b);
Assert.True(callbackCounter < 2, "Callback has been called more times than was expected.");
Assert.Equal(5, a);
Assert.Equal(0, b);
result.Continue = true;
}
[Fact, TestCategory("BVT"), TestCategory("Functional")]
public async Task ObserverTest_SubscriberMustBeGrainReference()
{
TestInitialize();
await Xunit.Assert.ThrowsAsync(typeof(NotSupportedException), async () =>
{
var result = new AsyncResultHandle();
ISimpleObserverableGrain grain = GetGrain();
observer1 = new SimpleGrainObserver(ObserverTest_SimpleNotification_Callback, result);
ISimpleGrainObserver reference = observer1;
// Should be: GrainFactory.CreateObjectReference<ISimpleGrainObserver>(obj);
await grain.Subscribe(reference);
// Not reached
});
}
internal class SimpleGrainObserver : ISimpleGrainObserver
{
readonly Action<int, int, AsyncResultHandle> action;
readonly AsyncResultHandle result;
public SimpleGrainObserver(Action<int, int, AsyncResultHandle> action, AsyncResultHandle result)
{
this.action = action;
this.result = result;
}
#region ISimpleGrainObserver Members
public void StateChanged(int a, int b)
{
GrainClient.Logger.Verbose("SimpleGrainObserver.StateChanged a={0} b={1}", a, b);
action?.Invoke(a, b, result);
}
#endregion
}
}
}
| |
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
/**
* Namespace: System.Web.UI.WebControls
* Struct: Unit
*
* Author: Gaurav Vaish
* Maintainer: gvaish@iitk.ac.in
* Contact: <my_scripts2001@yahoo.com>, <gvaish@iitk.ac.in>
* Implementation: yes
* Status: 100%
*
* (C) Gaurav Vaish (2001)
*/
using System;
using System.Globalization;
using System.ComponentModel;
using System.Web;
using System.Web.UI;
namespace System.Web.UI.WebControls
{
[TypeConverter(typeof(UnitConverter))]
[Serializable]
public struct Unit
{
public static readonly Unit Empty = new Unit();
private static int Min = -32768;
private static int Max = +32767;
private UnitType type;
private double val;
public static Unit Parse(string s)
{
return new Unit(s);
}
public static Unit Parse(string s, CultureInfo culture)
{
return new Unit(s, culture);
}
public static Unit Percentage(double n)
{
return new Unit (n, UnitType.Percentage);
}
public static Unit Pixel(int n)
{
return new Unit (n, UnitType.Pixel);
}
public static Unit Point(int n)
{
return new Unit(n, UnitType.Point);
}
public static bool operator ==(Unit left, Unit right)
{
return (left.type == right.type && left.val == right.val);
}
public static bool operator !=(Unit left, Unit right)
{
return !(left == right);
}
public static implicit operator Unit(int n)
{
return new Unit(n);
}
public Unit(double value)
{
if(value < Min || value > Max)
{
throw new ArgumentOutOfRangeException();
}
val = value;
type = UnitType.Pixel;
}
public Unit(int value)
{
if(value < Min || value > Max)
{
throw new ArgumentOutOfRangeException();
}
val = value;
type = UnitType.Pixel;
}
public Unit(string value): this(value, CultureInfo.CurrentCulture)
{
}
public Unit(double value, UnitType type)
{
if(value < Min || value > Max)
{
throw new ArgumentOutOfRangeException();
}
val = value;
this.type = type;
}
public Unit(string value, CultureInfo culture): this(value, culture, UnitType.Pixel)
{
}
internal Unit(string value, CultureInfo culture, UnitType defType)
{
string valueTrim;
if (value == null || (valueTrim = value.Trim ()).Length == 0) {
val = 0;
type = (UnitType)0;
return;
}
if (culture == null)
culture = CultureInfo.CurrentCulture;
string strVal = valueTrim.ToLower ();
int length = strVal.Length;
char c;
int start = -1;
for (int i = 0; i < length; i++) {
c = strVal [i];
if( (c >= '0' && c <= '9') || (c == '-' || c == '.' || c == ',') )
start = i;
}
if (start == -1)
throw new ArgumentException("No digits in 'value'");
start++;
if (start < length) {
type = GetTypeFromString (strVal.Substring (start).Trim ());
val = 0;
} else {
type = defType;
}
try {
string numbers = strVal.Substring (0, start);
if (type == UnitType.Pixel)
val = (double) Int32.Parse (numbers, culture);
else
val = (double) Single.Parse (numbers, culture);
} catch (Exception) {
throw new FormatException ("Error parsing " + value);
}
if (val < Min || val > Max)
throw new ArgumentOutOfRangeException ();
}
private static UnitType GetTypeFromString(string s)
{
if(s == null || s.Length == 0)
return UnitType.Pixel;
switch(s)
{
case "px":
return UnitType.Pixel;
case "pt":
return UnitType.Point;
case "pc":
return UnitType.Pica;
case "in":
return UnitType.Inch;
case "mm":
return UnitType.Mm;
case "cm":
return UnitType.Cm;
case "%":
return UnitType.Percentage;
case "em":
return UnitType.Em;
case "ex":
return UnitType.Ex;
default:
return UnitType.Pixel;
}
}
private string GetStringFromPixel(UnitType ut)
{
switch(ut)
{
case UnitType.Pixel:
return "px";
case UnitType.Point:
return "pt";
case UnitType.Pica:
return "pc";
case UnitType.Inch:
return "in";
case UnitType.Mm:
return "mm";
case UnitType.Cm:
return "cm";
case UnitType.Percentage:
return "%";
case UnitType.Em:
return "em";
case UnitType.Ex:
return "ex";
default:
return String.Empty;
}
}
public bool IsEmpty
{
get
{
return (type == 0);
}
}
public UnitType Type
{
get
{
if(IsEmpty)
return UnitType.Pixel;
return type;
}
}
public double Value
{
get
{
return val;
}
}
public override bool Equals(object obj)
{
if(obj != null && obj is Unit)
{
Unit that = (Unit)obj;
return ( this.type == that.type && this.val == that.val );
}
return false;
}
public override int GetHashCode()
{
return ( (type.GetHashCode() << 2) | (val.GetHashCode()) );
}
public override string ToString()
{
if(IsEmpty)
return String.Empty;
return ( val.ToString() + GetStringFromPixel(type) );
}
public string ToString(CultureInfo culture)
{
if(IsEmpty)
return String.Empty;
return (val.ToString(culture) + GetStringFromPixel(type));
}
}
}
| |
/********************************************************************++
Copyright (c) Microsoft Corporation. All rights reserved.
--********************************************************************/
using System.IO;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Reflection;
using System.Management.Automation.Runspaces;
namespace System.Management.Automation
{
/// <summary>
///
/// Class HelpProvider defines the interface to be implemented by help providers.
///
/// Help Providers:
/// The basic contract for help providers is to provide help based on the
/// search target.
///
/// The result of help provider invocation can be three things:
/// a. Full help info. (in the case of exact-match and single search result)
/// b. Short help info. (in the case of multiple search result)
/// c. Partial help info. (in the case of some commandlet help info, which
/// should be supplemented by provider help info)
/// d. Help forwarding info. (in the case of alias, which will change the target
/// for alias)
///
/// Help providers may need to provide functionality in following two area,
/// a. caching and indexing to boost performance
/// b. localization
///
/// Basic properties of a Help Provider
/// 1. Name
/// 2. Type
/// 3. Assembly
///
/// Help Provider Interface
/// 1. Initialize:
/// 2. ExactMatchHelp:
/// 3. SearchHelp:
/// 4. ProcessForwardedHelp
///
/// </summary>
internal abstract class HelpProvider
{
/// <summary>
/// Constructor for HelpProvider
/// </summary>
internal HelpProvider(HelpSystem helpSystem)
{
_helpSystem = helpSystem;
}
private HelpSystem _helpSystem;
internal HelpSystem HelpSystem
{
get
{
return _helpSystem;
}
}
#region Common Properties
/// <summary>
/// Name for the help provider
/// </summary>
/// <value>Name for the help provider</value>
/// <remarks>Derived classes should set this.</remarks>
internal abstract string Name
{
get;
}
/// <summary>
/// Help category for the help provider
/// </summary>
/// <value>Help category for the help provider</value>
/// <remarks>Derived classes should set this.</remarks>
internal abstract HelpCategory HelpCategory
{
get;
}
#if V2
/// <summary>
/// Assembly that contains the help provider.
/// </summary>
/// <value>Assembly name</value>
virtual internal string AssemblyName
{
get
{
return Assembly.GetExecutingAssembly().FullName;
}
}
/// <summary>
/// Class that implements the help provider
/// </summary>
/// <value>Class name</value>
virtual internal string ClassName
{
get
{
return this.GetType().FullName;
}
}
/// <summary>
/// Get an provider info object based on the basic information in this provider.
/// </summary>
/// <value>An mshObject that contains the providerInfo</value>
internal PSObject ProviderInfo
{
get
{
PSObject result = new PSObject();
result.Properties.Add(new PSNoteProperty("Name", this.Name));
result.Properties.Add(new PSNoteProperty("Category", this.HelpCategory.ToString()));
result.Properties.Add(new PSNoteProperty("ClassName", this.ClassName));
result.Properties.Add(new PSNoteProperty("AssemblyName", this.AssemblyName));
Collection<string> typeNames = new Collection<string>();
typeNames.Add("HelpProviderInfo");
result.TypeNames = typeNames;
return result;
}
}
#endif
#endregion
#region Help Provider Interface
/// <summary>
/// Retrieve help info that exactly match the target.
/// </summary>
/// <param name="helpRequest">help request object</param>
/// <returns>List of HelpInfo objects retrieved</returns>
internal abstract IEnumerable<HelpInfo> ExactMatchHelp(HelpRequest helpRequest);
/// <summary>
/// Search help info that match the target search pattern.
/// </summary>
/// <param name="helpRequest">help request object</param>
/// <param name="searchOnlyContent">
/// If true, searches for pattern in the help content. Individual
/// provider can decide which content to search in.
///
/// If false, searches for pattern in the command names.
/// </param>
/// <returns>a collection of help info objects</returns>
internal abstract IEnumerable<HelpInfo> SearchHelp(HelpRequest helpRequest, bool searchOnlyContent);
/// <summary>
/// Process a helpinfo forwarded over by another help provider.
///
/// HelpProvider can choose to process the helpInfo or not,
///
/// 1. If a HelpProvider chooses not to process the helpInfo, it can return null to indicate
/// helpInfo is not processed.
/// 2. If a HelpProvider indeed processes the helpInfo, it should create a new helpInfo
/// object instead of modifying the passed-in helpInfo object. This is very important
/// since the helpInfo object passed in is usually stored in cache, which can
/// used in later queries.
/// </summary>
/// <param name="helpInfo">helpInfo passed over by another HelpProvider</param>
/// <param name="helpRequest">help request object</param>
/// <returns></returns>
internal virtual IEnumerable<HelpInfo> ProcessForwardedHelp(HelpInfo helpInfo, HelpRequest helpRequest)
{
// Win8: 508648. Remove the current provides category for resolving forward help as the current
// help provider already process it.
helpInfo.ForwardHelpCategory = helpInfo.ForwardHelpCategory ^ this.HelpCategory;
yield return helpInfo;
}
/// <summary>
/// Reset help provider.
///
/// Normally help provider are reset after a help culture change.
/// </summary>
internal virtual void Reset()
{
return;
}
#endregion
#region Utility functions
/// <summary>
/// Report help file load errors.
///
/// Currently three cases are handled,
///
/// 1. IOException: not able to read the file
/// 2. SecurityException: not authorized to read the file
/// 3. XmlException: xml schema error.
///
/// This will be called either from search help or exact match help
/// to find the error.
///
/// </summary>
/// <param name="exception"></param>
/// <param name="target"></param>
/// <param name="helpFile"></param>
internal void ReportHelpFileError(Exception exception, string target, string helpFile)
{
ErrorRecord errorRecord = new ErrorRecord(exception, "LoadHelpFileForTargetFailed", ErrorCategory.OpenError, null);
errorRecord.ErrorDetails = new ErrorDetails(typeof(HelpProvider).GetTypeInfo().Assembly, "HelpErrors", "LoadHelpFileForTargetFailed", target, helpFile, exception.Message);
this.HelpSystem.LastErrors.Add(errorRecord);
return;
}
/// <summary>
/// Each Shell ( minishell ) will have its own path specified by the
/// registry HKLM\software\microsoft\msh\1\ShellIds\<ShellID>\path. Every help
/// provider should search this path for content.
/// </summary>
/// <returns>string representing base directory of the executing shell.</returns>
internal string GetDefaultShellSearchPath()
{
string shellID = this.HelpSystem.ExecutionContext.ShellID;
string returnValue = CommandDiscovery.GetShellPathFromRegistry(shellID);
if (returnValue == null)
{
// use executing assemblies location in case registry entry not found
returnValue = Path.GetDirectoryName(PsUtils.GetMainModule(System.Diagnostics.Process.GetCurrentProcess()).FileName);
}
else
{
// Get the directory path of the executing shell
returnValue = Path.GetDirectoryName(returnValue);
if (!Directory.Exists(returnValue))
{
// use executing assemblies location in case registry entry not found
returnValue = Path.GetDirectoryName(PsUtils.GetMainModule(System.Diagnostics.Process.GetCurrentProcess()).FileName);
}
}
return returnValue;
}
/// <summary>
/// Helper function which checks whether PSSnapIns are supported in current invocation.
/// </summary>
/// <returns>true if supported,false otherwise.</returns>
internal bool AreSnapInsSupported()
{
RunspaceConfigForSingleShell runspace = _helpSystem.ExecutionContext.RunspaceConfiguration as RunspaceConfigForSingleShell;
return (null == runspace ? false : true);
}
/// <summary>
/// Gets the search paths. If the current shell is single-shell based, then the returned
/// search path contains all the directories of currently active PSSnapIns
/// </summary>
/// <returns>a collection of string representing locations</returns>
internal Collection<string> GetSearchPaths()
{
Collection<String> searchPaths = this.HelpSystem.GetSearchPaths();
Diagnostics.Assert(searchPaths != null,
"HelpSystem returned an null search path");
searchPaths.Add(GetDefaultShellSearchPath());
return searchPaths;
}
#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 defines many COM dual interfaces which are legacy and,
// cannot be changed. Tolerate possible obsoletion.
//
#pragma warning disable CS0618 // Type or member is obsolete
namespace System.DirectoryServices.AccountManagement
{
using System.Runtime.InteropServices;
using System;
using System.Security;
using System.Security.Permissions;
using System.Text;
internal class Constants
{
private Constants() { }
internal static Byte[] GUID_USERS_CONTAINER_BYTE = new Byte[] { 0xa9, 0xd1, 0xca, 0x15, 0x76, 0x88, 0x11, 0xd1, 0xad, 0xed, 0x00, 0xc0, 0x4f, 0xd8, 0xd5, 0xcd };
internal static Byte[] GUID_COMPUTRS_CONTAINER_BYTE = new Byte[] { 0xaa, 0x31, 0x28, 0x25, 0x76, 0x88, 0x11, 0xd1, 0xad, 0xed, 0x00, 0xc0, 0x4f, 0xd8, 0xd5, 0xcd };
internal static Byte[] GUID_FOREIGNSECURITYPRINCIPALS_CONTAINER_BYTE = new Byte[] { 0x22, 0xb7, 0x0c, 0x67, 0xd5, 0x6e, 0x4e, 0xfb, 0x91, 0xe9, 0x30, 0x0f, 0xca, 0x3d, 0xc1, 0xaa };
}
internal class SafeNativeMethods
{
// To stop the compiler from autogenerating a constructor for this class
private SafeNativeMethods() { }
[DllImport("kernel32.dll", CallingConvention = CallingConvention.StdCall, EntryPoint = "GetCurrentThreadId", CharSet = CharSet.Unicode)]
static extern public int GetCurrentThreadId();
[DllImport("advapi32.dll", CallingConvention = CallingConvention.StdCall, EntryPoint = "LsaNtStatusToWinError", CharSet = CharSet.Unicode)]
static extern public int LsaNtStatusToWinError(int ntStatus);
}
internal class UnsafeNativeMethods
{
// To stop the compiler from autogenerating a constructor for this class
private UnsafeNativeMethods() { }
[DllImport(ExternDll.Activeds, ExactSpelling = true, EntryPoint = "ADsOpenObject", CharSet = System.Runtime.InteropServices.CharSet.Unicode)]
private static extern int IntADsOpenObject(string path, string userName, string password, int flags, [In, Out] ref Guid iid, [Out, MarshalAs(UnmanagedType.Interface)] out object ppObject);
public static int ADsOpenObject(string path, string userName, string password, int flags, [In, Out] ref Guid iid, [Out, MarshalAs(UnmanagedType.Interface)] out object ppObject)
{
try
{
return IntADsOpenObject(path, userName, password, flags, ref iid, out ppObject);
}
catch (EntryPointNotFoundException)
{
throw new InvalidOperationException(SR.AdsiNotInstalled);
}
}
//
// ADSI Interopt
//
internal enum ADS_PASSWORD_ENCODING_ENUM
{
ADS_PASSWORD_ENCODE_REQUIRE_SSL = 0,
ADS_PASSWORD_ENCODE_CLEAR = 1
}
internal enum ADS_OPTION_ENUM
{
ADS_OPTION_SERVERNAME = 0,
ADS_OPTION_REFERRALS = 1,
ADS_OPTION_PAGE_SIZE = 2,
ADS_OPTION_SECURITY_MASK = 3,
ADS_OPTION_MUTUAL_AUTH_STATUS = 4,
ADS_OPTION_QUOTA = 5,
ADS_OPTION_PASSWORD_PORTNUMBER = 6,
ADS_OPTION_PASSWORD_METHOD = 7,
ADS_OPTION_ACCUMULATIVE_MODIFICATION = 8,
ADS_OPTION_SKIP_SID_LOOKUP = 9
}
[ComImport, Guid("7E99C0A2-F935-11D2-BA96-00C04FB6D0D1"), InterfaceTypeAttribute(ComInterfaceType.InterfaceIsDual)]
public interface IADsDNWithBinary
{
object BinaryValue { get; set; }
string DNString { get; set; }
}
[ComImport, Guid("9068270b-0939-11D1-8be1-00c04fd8d503"), InterfaceTypeAttribute(ComInterfaceType.InterfaceIsDual)]
public interface IADsLargeInteger
{
int HighPart { get; set; }
int LowPart { get; set; }
}
[ComImport, Guid("927971f5-0939-11d1-8be1-00c04fd8d503")]
public class ADsLargeInteger
{
}
[ComImport, Guid("46f14fda-232b-11d1-a808-00c04fd8d5a8"), InterfaceTypeAttribute(ComInterfaceType.InterfaceIsDual)]
public interface IAdsObjectOptions
{
[return: MarshalAs(UnmanagedType.Struct)]
Object GetOption(
[In]
int option);
void PutOption(
[In]
int option,
[In, MarshalAs(UnmanagedType.Struct)]
Object vProp);
}
[ComImport, Guid("FD8256D0-FD15-11CE-ABC4-02608C9E7553"), InterfaceTypeAttribute(ComInterfaceType.InterfaceIsDual)]
public interface IADs
{
string Name
{
[return: MarshalAs(UnmanagedType.BStr)]
get;
}
string Class
{
[return: MarshalAs(UnmanagedType.BStr)]
get;
}
string GUID
{
[return: MarshalAs(UnmanagedType.BStr)]
get;
}
string ADsPath
{
[return: MarshalAs(UnmanagedType.BStr)]
get;
}
string Parent
{
[return: MarshalAs(UnmanagedType.BStr)]
get;
}
string Schema
{
[return: MarshalAs(UnmanagedType.BStr)]
get;
}
void GetInfo();
void SetInfo();
[return: MarshalAs(UnmanagedType.Struct)]
Object Get(
[In, MarshalAs(UnmanagedType.BStr)]
string bstrName);
void Put(
[In, MarshalAs(UnmanagedType.BStr)]
string bstrName,
[In, MarshalAs(UnmanagedType.Struct)]
Object vProp);
[return: MarshalAs(UnmanagedType.Struct)]
Object GetEx(
[In, MarshalAs(UnmanagedType.BStr)]
String bstrName);
void PutEx(
[In, MarshalAs(UnmanagedType.U4)]
int lnControlCode,
[In, MarshalAs(UnmanagedType.BStr)]
string bstrName,
[In, MarshalAs(UnmanagedType.Struct)]
Object vProp);
void GetInfoEx(
[In, MarshalAs(UnmanagedType.Struct)]
Object vProperties,
[In, MarshalAs(UnmanagedType.U4)]
int lnReserved);
}
[ComImport, Guid("27636b00-410f-11cf-b1ff-02608c9e7553"), InterfaceTypeAttribute(ComInterfaceType.InterfaceIsDual)]
public interface IADsGroup
{
string Name
{
[return: MarshalAs(UnmanagedType.BStr)]
get;
}
string Class
{
[return: MarshalAs(UnmanagedType.BStr)]
get;
}
string GUID
{
[return: MarshalAs(UnmanagedType.BStr)]
get;
}
string ADsPath
{
[return: MarshalAs(UnmanagedType.BStr)]
get;
}
string Parent
{
[return: MarshalAs(UnmanagedType.BStr)]
get;
}
string Schema
{
[return: MarshalAs(UnmanagedType.BStr)]
get;
}
void GetInfo();
void SetInfo();
[return: MarshalAs(UnmanagedType.Struct)]
Object Get(
[In, MarshalAs(UnmanagedType.BStr)]
string bstrName);
void Put(
[In, MarshalAs(UnmanagedType.BStr)]
string bstrName,
[In, MarshalAs(UnmanagedType.Struct)]
Object vProp);
[return: MarshalAs(UnmanagedType.Struct)]
Object GetEx(
[In, MarshalAs(UnmanagedType.BStr)]
String bstrName);
void PutEx(
[In, MarshalAs(UnmanagedType.U4)]
int lnControlCode,
[In, MarshalAs(UnmanagedType.BStr)]
string bstrName,
[In, MarshalAs(UnmanagedType.Struct)]
Object vProp);
void GetInfoEx(
[In, MarshalAs(UnmanagedType.Struct)]
Object vProperties,
[In, MarshalAs(UnmanagedType.U4)]
int lnReserved);
string Description
{
[return: MarshalAs(UnmanagedType.BStr)]
get;
[param: MarshalAs(UnmanagedType.BStr)]
set;
}
IADsMembers Members();
bool IsMember([In, MarshalAs(UnmanagedType.BStr)] string bstrMember);
void Add([In, MarshalAs(UnmanagedType.BStr)] string bstrNewItem);
void Remove([In, MarshalAs(UnmanagedType.BStr)] string bstrItemToBeRemoved);
}
[ComImport, Guid("451a0030-72ec-11cf-b03b-00aa006e0975"), InterfaceTypeAttribute(ComInterfaceType.InterfaceIsDual)]
public interface IADsMembers
{
int Count
{
[return: MarshalAs(UnmanagedType.U4)]
get;
}
object _NewEnum
{
[return: MarshalAs(UnmanagedType.Interface)]
get;
}
object Filter
{
[return: MarshalAs(UnmanagedType.Struct)]
get;
[param: MarshalAs(UnmanagedType.Struct)]
set;
}
}
[ComImport, Guid("080d0d78-f421-11d0-a36e-00c04fb950dc")]
public class Pathname
{
}
[ComImport, Guid("d592aed4-f420-11d0-a36e-00c04fb950dc"), InterfaceTypeAttribute(ComInterfaceType.InterfaceIsDual)]
public interface IADsPathname
{
void Set(
[In, MarshalAs(UnmanagedType.BStr)] string bstrADsPath,
[In, MarshalAs(UnmanagedType.U4)] int lnSetType
);
void SetDisplayType(
[In, MarshalAs(UnmanagedType.U4)] int lnDisplayType
);
[return: MarshalAs(UnmanagedType.BStr)]
string Retrieve(
[In, MarshalAs(UnmanagedType.U4)] int lnFormatType
);
[return: MarshalAs(UnmanagedType.U4)]
int GetNumElements();
[return: MarshalAs(UnmanagedType.BStr)]
string
GetElement(
[In, MarshalAs(UnmanagedType.U4)] int lnElementIndex
);
void AddLeafElement(
[In, MarshalAs(UnmanagedType.BStr)] string bstrLeafElement
);
void RemoveLeafElement();
[return: MarshalAs(UnmanagedType.Struct)]
Object CopyPath();
[return: MarshalAs(UnmanagedType.BStr)]
string GetEscapedElement(
[In, MarshalAs(UnmanagedType.U4)] int lnReserved,
[In, MarshalAs(UnmanagedType.BStr)] string bstrInStr
);
int EscapedMode
{
[return: MarshalAs(UnmanagedType.U4)]
get;
[param: MarshalAs(UnmanagedType.U4)]
set;
}
}
//
// DSInteropt
//
/*
typedef enum
{
DsRole_RoleStandaloneWorkstation,
DsRole_RoleMemberWorkstation,
DsRole_RoleStandaloneServer,
DsRole_RoleMemberServer,
DsRole_RoleBackupDomainController,
DsRole_RolePrimaryDomainController,
DsRole_WorkstationWithSharedAccountDomain,
DsRole_ServerWithSharedAccountDomain,
DsRole_MemberWorkstationWithSharedAccountDomain,
DsRole_MemberServerWithSharedAccountDomain
}DSROLE_MACHINE_ROLE;
*/
public enum DSROLE_MACHINE_ROLE
{
DsRole_RoleStandaloneWorkstation,
DsRole_RoleMemberWorkstation,
DsRole_RoleStandaloneServer,
DsRole_RoleMemberServer,
DsRole_RoleBackupDomainController,
DsRole_RolePrimaryDomainController,
DsRole_WorkstationWithSharedAccountDomain,
DsRole_ServerWithSharedAccountDomain,
DsRole_MemberWorkstationWithSharedAccountDomain,
DsRole_MemberServerWithSharedAccountDomain
}
/*
typedef enum
{
DsRolePrimaryDomainInfoBasic,
DsRoleUpgradeStatus,
DsRoleOperationState,
DsRolePrimaryDomainInfoBasicEx
}DSROLE_PRIMARY_DOMAIN_INFO_LEVEL;
*/
public enum DSROLE_PRIMARY_DOMAIN_INFO_LEVEL
{
DsRolePrimaryDomainInfoBasic = 1,
DsRoleUpgradeStatus = 2,
DsRoleOperationState = 3,
DsRolePrimaryDomainInfoBasicEx = 4
}
/*
typedef struct _DSROLE_PRIMARY_DOMAIN_INFO_BASIC {
DSROLE_MACHINE_ROLE MachineRole;
ULONG Flags;
LPWSTR DomainNameFlat;
LPWSTR DomainNameDns;
LPWSTR DomainForestName;
GUID DomainGuid;
} DSROLE_PRIMARY_DOMAIN_INFO_BASIC, *PDSROLE_PRIMARY_DOMAIN_INFO_BASIC;
*/
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public sealed class DSROLE_PRIMARY_DOMAIN_INFO_BASIC
{
public DSROLE_MACHINE_ROLE MachineRole;
public uint Flags;
[MarshalAs(UnmanagedType.LPWStr)]
public string DomainNameFlat;
[MarshalAs(UnmanagedType.LPWStr)]
public string DomainNameDns;
[MarshalAs(UnmanagedType.LPWStr)]
public string DomainForestName;
public Guid DomainGuid = new Guid();
}
/*
DWORD DsRoleGetPrimaryDomainInformation(
LPCWSTR lpServer,
DSROLE_PRIMARY_DOMAIN_INFO_LEVEL InfoLevel,
PBYTE* Buffer
); */
[DllImport("dsrole.dll", CallingConvention = CallingConvention.StdCall, EntryPoint = "DsRoleGetPrimaryDomainInformation", CharSet = CharSet.Unicode)]
public static extern int DsRoleGetPrimaryDomainInformation(
[MarshalAs(UnmanagedType.LPTStr)] string lpServer,
[In] DSROLE_PRIMARY_DOMAIN_INFO_LEVEL InfoLevel,
out IntPtr Buffer);
/*typedef struct _DOMAIN_CONTROLLER_INFO {
LPTSTR DomainControllerName;
LPTSTR DomainControllerAddress;
ULONG DomainControllerAddressType;
GUID DomainGuid;
LPTSTR DomainName;
LPTSTR DnsForestName;
ULONG Flags;
LPTSTR DcSiteName;
LPTSTR ClientSiteName;
} DOMAIN_CONTROLLER_INFO, *PDOMAIN_CONTROLLER_INFO; */
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public sealed class DomainControllerInfo
{
public string DomainControllerName = null;
public string DomainControllerAddress = null;
public int DomainControllerAddressType = 0;
public Guid DomainGuid = new Guid();
public string DomainName = null;
public string DnsForestName = null;
public int Flags = 0;
public string DcSiteName = null;
public string ClientSiteName = null;
}
/*
void DsRoleFreeMemory(
PVOID Buffer
);
*/
[DllImport("dsrole.dll")]
public static extern int DsRoleFreeMemory(
[In] IntPtr buffer);
/*DWORD DsGetDcName(
LPCTSTR ComputerName,
LPCTSTR DomainName,
GUID* DomainGuid,
LPCTSTR SiteName,
ULONG Flags,
PDOMAIN_CONTROLLER_INFO* DomainControllerInfo
);*/
[DllImport("logoncli.dll", CallingConvention = CallingConvention.StdCall, EntryPoint = "DsGetDcNameW", CharSet = CharSet.Unicode)]
public static extern int DsGetDcName(
[In] string computerName,
[In] string domainName,
[In] IntPtr domainGuid,
[In] string siteName,
[In] int flags,
[Out] out IntPtr domainControllerInfo);
/* typedef struct _WKSTA_INFO_100 {
DWORD wki100_platform_id;
LMSTR wki100_computername;
LMSTR wki100_langroup;
DWORD wki100_ver_major;
DWORD wki100_ver_minor;
} WKSTA_INFO_100, *PWKSTA_INFO_100; */
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public sealed class WKSTA_INFO_100
{
public int wki100_platform_id = 0;
public string wki100_computername = null;
public string wki100_langroup = null;
public int wki100_ver_major = 0;
public int wki100_ver_minor = 0;
};
[DllImport("wkscli.dll", CallingConvention = CallingConvention.StdCall, EntryPoint = "NetWkstaGetInfo", CharSet = CharSet.Unicode)]
public static extern int NetWkstaGetInfo(string server, int level, ref IntPtr buffer);
[DllImport("netutils.dll")]
public static extern int NetApiBufferFree(
[In] IntPtr buffer);
//
// SID
//
[DllImport("advapi32.dll", SetLastError = true, CallingConvention = CallingConvention.StdCall, EntryPoint = "ConvertSidToStringSidW", CharSet = CharSet.Unicode)]
public static extern bool ConvertSidToStringSid(IntPtr sid, ref string stringSid);
[DllImport("advapi32.dll", CallingConvention = CallingConvention.StdCall, EntryPoint = "ConvertStringSidToSidW", CharSet = CharSet.Unicode)]
public static extern bool ConvertStringSidToSid(string stringSid, ref IntPtr sid);
[DllImport("advapi32.dll")]
public static extern int GetLengthSid(IntPtr sid);
[DllImport("advapi32.dll", SetLastError = true)]
public static extern bool IsValidSid(IntPtr sid);
[DllImport("advapi32.dll")]
public static extern IntPtr GetSidIdentifierAuthority(IntPtr sid);
[DllImport("advapi32.dll")]
public static extern IntPtr GetSidSubAuthority(IntPtr sid, int index);
[DllImport("advapi32.dll")]
public static extern IntPtr GetSidSubAuthorityCount(IntPtr sid);
[DllImport("advapi32.dll")]
public static extern bool EqualDomainSid(IntPtr pSid1, IntPtr pSid2, ref bool equal);
[DllImport("advapi32.dll", SetLastError = true)]
public static extern bool CopySid(int destinationLength, IntPtr pSidDestination, IntPtr pSidSource);
[DllImport("kernel32.dll")]
public static extern IntPtr LocalFree(IntPtr ptr);
[DllImport("Credui.dll", SetLastError = true, CallingConvention = CallingConvention.StdCall, EntryPoint = "CredUIParseUserNameW", CharSet = CharSet.Unicode)]
public static extern int CredUIParseUserName(
string pszUserName,
StringBuilder pszUser,
System.UInt32 ulUserMaxChars,
StringBuilder pszDomain,
System.UInt32 ulDomainMaxChars
);
// These contants were taken from the wincred.h file
public const int CRED_MAX_USERNAME_LENGTH = 514;
public const int CRED_MAX_DOMAIN_TARGET_LENGTH = 338;
/*
BOOL LookupAccountSid(
LPCTSTR lpSystemName,
PSID lpSid,
LPTSTR lpName,
LPDWORD cchName,
LPTSTR lpReferencedDomainName,
LPDWORD cchReferencedDomainName,
PSID_NAME_USE peUse
);
*/
[DllImport("advapi32.dll", SetLastError = true, CallingConvention = CallingConvention.StdCall, EntryPoint = "LookupAccountSidW", CharSet = CharSet.Unicode)]
public static extern bool LookupAccountSid(
string computerName,
IntPtr sid,
StringBuilder name,
ref int nameLength,
StringBuilder domainName,
ref int domainNameLength,
ref int usage);
//
// AuthZ functions
//
internal sealed class AUTHZ_RM_FLAG
{
private AUTHZ_RM_FLAG() { }
public static int AUTHZ_RM_FLAG_NO_AUDIT = 0x1;
public static int AUTHZ_RM_FLAG_INITIALIZE_UNDER_IMPERSONATION = 0x2;
public static int AUTHZ_VALID_RM_INIT_FLAGS = (AUTHZ_RM_FLAG_NO_AUDIT | AUTHZ_RM_FLAG_INITIALIZE_UNDER_IMPERSONATION);
}
[DllImport("authz.dll", SetLastError = true, CallingConvention = CallingConvention.StdCall, EntryPoint = "AuthzInitializeResourceManager", CharSet = CharSet.Unicode)]
static extern public bool AuthzInitializeResourceManager(
int flags,
IntPtr pfnAccessCheck,
IntPtr pfnComputeDynamicGroups,
IntPtr pfnFreeDynamicGroups,
string name,
out IntPtr rm
);
/*
BOOL WINAPI AuthzInitializeContextFromSid(
DWORD Flags,
PSID UserSid,
AUTHZ_RESOURCE_MANAGER_HANDLE AuthzResourceManager,
PLARGE_INTEGER pExpirationTime,
LUID Identifier,
PVOID DynamicGroupArgs,
PAUTHZ_CLIENT_CONTEXT_HANDLE pAuthzClientContext
);
*/
[DllImport("authz.dll", SetLastError = true, CallingConvention = CallingConvention.StdCall, EntryPoint = "AuthzInitializeContextFromSid", CharSet = CharSet.Unicode)]
static extern public bool AuthzInitializeContextFromSid(
int Flags,
IntPtr UserSid,
IntPtr AuthzResourceManager,
IntPtr pExpirationTime,
LUID Identitifier,
IntPtr DynamicGroupArgs,
out IntPtr pAuthzClientContext
);
/*
[DllImport("authz.dll", SetLastError=true, CallingConvention=CallingConvention.StdCall, EntryPoint="AuthzInitializeContextFromToken", CharSet=CharSet.Unicode)]
static extern public bool AuthzInitializeContextFromToken(
int Flags,
IntPtr TokenHandle,
IntPtr AuthzResourceManager,
IntPtr pExpirationTime,
LUID Identitifier,
IntPtr DynamicGroupArgs,
out IntPtr pAuthzClientContext
);
*/
[DllImport("authz.dll", SetLastError = true, CallingConvention = CallingConvention.StdCall, EntryPoint = "AuthzGetInformationFromContext", CharSet = CharSet.Unicode)]
static extern public bool AuthzGetInformationFromContext(
IntPtr hAuthzClientContext,
int InfoClass,
int BufferSize,
out int pSizeRequired,
IntPtr Buffer
);
[DllImport("authz.dll", CallingConvention = CallingConvention.StdCall, EntryPoint = "AuthzFreeContext", CharSet = CharSet.Unicode)]
static extern public bool AuthzFreeContext(
IntPtr AuthzClientContext
);
[DllImport("authz.dll", CallingConvention = CallingConvention.StdCall, EntryPoint = "AuthzFreeResourceManager", CharSet = CharSet.Unicode)]
static extern public bool AuthzFreeResourceManager(
IntPtr rm
);
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public struct LUID
{
public int low;
public int high;
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public sealed class TOKEN_GROUPS
{
public int groupCount = 0;
public IntPtr groups = IntPtr.Zero;
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public sealed class SID_AND_ATTR
{
public IntPtr pSid = IntPtr.Zero;
public int attrs = 0;
}
//
// Token
//
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public sealed class TOKEN_USER
{
public SID_AND_ATTR sidAndAttributes = new SID_AND_ATTR();
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public sealed class SID_IDENTIFIER_AUTHORITY
{
public byte b1 = 0;
public byte b2 = 0;
public byte b3 = 0;
public byte b4 = 0;
public byte b5 = 0;
public byte b6 = 0;
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public sealed class LSA_OBJECT_ATTRIBUTES
{
public int length = 0;
public IntPtr rootDirectory = IntPtr.Zero;
public IntPtr objectName = IntPtr.Zero;
public int attributes = 0;
public IntPtr securityDescriptor = IntPtr.Zero;
public IntPtr securityQualityOfService = IntPtr.Zero;
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public sealed class POLICY_ACCOUNT_DOMAIN_INFO
{
public LSA_UNICODE_STRING domainName = new LSA_UNICODE_STRING();
public IntPtr domainSid = IntPtr.Zero;
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public sealed class LSA_UNICODE_STRING
{
public ushort length = 0;
public ushort maximumLength = 0;
public IntPtr buffer = IntPtr.Zero;
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public sealed class LSA_UNICODE_STRING_Managed
{
public ushort length = 0;
public ushort maximumLength = 0;
public string buffer;
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public sealed class LSA_TRANSLATED_NAME
{
public int use = 0;
public LSA_UNICODE_STRING name = new LSA_UNICODE_STRING();
public int domainIndex = 0;
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public sealed class LSA_REFERENCED_DOMAIN_LIST
{
// To stop the compiler from autogenerating a constructor for this class
private LSA_REFERENCED_DOMAIN_LIST() { }
public int entries = 0;
public IntPtr domains = IntPtr.Zero;
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public sealed class LSA_TRUST_INFORMATION
{
public LSA_UNICODE_STRING name = new LSA_UNICODE_STRING();
private IntPtr _pSid = IntPtr.Zero;
}
[DllImport("advapi32.dll", SetLastError = true, CallingConvention = CallingConvention.StdCall, EntryPoint = "OpenThreadToken", CharSet = CharSet.Unicode)]
static extern public bool OpenThreadToken(
IntPtr threadHandle,
int desiredAccess,
bool openAsSelf,
ref IntPtr tokenHandle
);
[DllImport("advapi32.dll", SetLastError = true, CallingConvention = CallingConvention.StdCall, EntryPoint = "OpenProcessToken", CharSet = CharSet.Unicode)]
static extern public bool OpenProcessToken(
IntPtr processHandle,
int desiredAccess,
ref IntPtr tokenHandle
);
[DllImport("kernel32.dll", CallingConvention = CallingConvention.StdCall, EntryPoint = "CloseHandle", CharSet = CharSet.Unicode)]
static extern public bool CloseHandle(IntPtr handle);
[DllImport("kernel32.dll", CallingConvention = CallingConvention.StdCall, EntryPoint = "GetCurrentThread", CharSet = CharSet.Unicode)]
static extern public IntPtr GetCurrentThread();
[DllImport("kernel32.dll", CallingConvention = CallingConvention.StdCall, EntryPoint = "GetCurrentProcess", CharSet = CharSet.Unicode)]
static extern public IntPtr GetCurrentProcess();
[DllImport("advapi32.dll", SetLastError = true, CallingConvention = CallingConvention.StdCall, EntryPoint = "GetTokenInformation", CharSet = CharSet.Unicode)]
static extern public bool GetTokenInformation(
IntPtr tokenHandle,
int tokenInformationClass,
IntPtr buffer,
int bufferSize,
ref int returnLength
);
[DllImport("advapi32.dll", CallingConvention = CallingConvention.StdCall, EntryPoint = "LsaOpenPolicy", CharSet = CharSet.Unicode)]
static extern public int LsaOpenPolicy(
IntPtr lsaUnicodeString,
IntPtr lsaObjectAttributes,
int desiredAccess,
ref IntPtr policyHandle);
[DllImport("advapi32.dll", CallingConvention = CallingConvention.StdCall, EntryPoint = "LsaQueryInformationPolicy", CharSet = CharSet.Unicode)]
static extern public int LsaQueryInformationPolicy(
IntPtr policyHandle,
int policyInformationClass,
ref IntPtr buffer
);
[DllImport("advapi32.dll", CallingConvention = CallingConvention.StdCall, EntryPoint = "LsaLookupSids", CharSet = CharSet.Unicode)]
public static extern int LsaLookupSids(
IntPtr policyHandle,
int count,
IntPtr[] sids,
out IntPtr referencedDomains,
out IntPtr names
);
[DllImport("advapi32.dll", CallingConvention = CallingConvention.StdCall, EntryPoint = "LsaFreeMemory", CharSet = CharSet.Unicode)]
static extern public int LsaFreeMemory(IntPtr buffer);
[DllImport("advapi32.dll", CallingConvention = CallingConvention.StdCall, EntryPoint = "LsaClose", CharSet = CharSet.Unicode)]
static extern public int LsaClose(IntPtr policyHandle);
//
// Impersonation
//
[DllImport("advapi32.dll", SetLastError = true, CallingConvention = CallingConvention.StdCall, EntryPoint = "LogonUserW", CharSet = CharSet.Unicode)]
static extern public int LogonUser(
string lpszUsername,
string lpszDomain,
string lpszPassword,
int dwLogonType,
int dwLogonProvider,
ref IntPtr phToken);
[DllImport("advapi32.dll", SetLastError = true, CallingConvention = CallingConvention.StdCall, EntryPoint = "ImpersonateLoggedOnUser", CharSet = CharSet.Unicode)]
static extern public int ImpersonateLoggedOnUser(IntPtr hToken);
[DllImport("Advapi32.dll", CallingConvention = CallingConvention.StdCall, EntryPoint = "RevertToSelf", CharSet = CharSet.Unicode)]
static extern public int RevertToSelf();
public const int FORMAT_MESSAGE_ALLOCATE_BUFFER = 0x00000100,
FORMAT_MESSAGE_IGNORE_INSERTS = 0x00000200,
FORMAT_MESSAGE_FROM_STRING = 0x00000400,
FORMAT_MESSAGE_FROM_HMODULE = 0x00000800,
FORMAT_MESSAGE_FROM_SYSTEM = 0x00001000,
FORMAT_MESSAGE_ARGUMENT_ARRAY = 0x00002000,
FORMAT_MESSAGE_MAX_WIDTH_MASK = 0x000000FF;
[DllImport("kernel32.dll", CharSet = System.Runtime.InteropServices.CharSet.Unicode)]
public static extern int FormatMessageW(int dwFlags, IntPtr lpSource, int dwMessageId,
int dwLanguageId, StringBuilder lpBuffer, int nSize, IntPtr arguments);
}
}
| |
// 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; // for TraceInformation
using System.Runtime.CompilerServices;
using Internal.Runtime.Augments;
// TODO: Delete this and use the implementation from CoreFX
namespace System.Threading
{
public enum LockRecursionPolicy
{
NoRecursion = 0,
SupportsRecursion = 1,
}
//
// ReaderWriterCount tracks how many of each kind of lock is held by each thread.
// We keep a linked list for each thread, attached to a ThreadStatic field.
// These are reused wherever possible, so that a given thread will only
// allocate N of these, where N is the maximum number of locks held simultaneously
// by that thread.
//
internal class ReaderWriterCount
{
// Which lock does this object belong to? This is a numeric ID for two reasons:
// 1) We don't want this field to keep the lock object alive, and a WeakReference would
// be too expensive.
// 2) Setting the value of a long is faster than setting the value of a reference.
// The "hot" paths in ReaderWriterLockSlim are short enough that this actually
// matters.
public long lockID;
// How many reader locks does this thread hold on this ReaderWriterLockSlim instance?
public int readercount;
// Ditto for writer/upgrader counts. These are only used if the lock allows recursion.
// But we have to have the fields on every ReaderWriterCount instance, because
// we reuse it for different locks.
public int writercount;
public int upgradecount;
// Next RWC in this thread's list.
public ReaderWriterCount next;
}
/// <summary>
/// A reader-writer lock implementation that is intended to be simple, yet very
/// efficient. In particular only 1 interlocked operation is taken for any lock
/// operation (we use spin locks to achieve this). The spin lock is never held
/// for more than a few instructions (in particular, we never call event APIs
/// or in fact any non-trivial API while holding the spin lock).
/// </summary>
public class ReaderWriterLockSlim : IDisposable
{
//Specifying if locked can be reacquired recursively.
private bool _fIsReentrant;
// Lock specification for myLock: This lock protects exactly the local fields associated with this
// instance of ReaderWriterLockSlim. It does NOT protect the memory associated with
// the events that hang off this lock (eg writeEvent, readEvent upgradeEvent).
private int _myLock;
//The variables controlling spinning behavior of Mylock(which is a spin-lock)
private const int LockSpinCycles = 20;
private const int LockSpinCount = 10;
private const int LockSleep0Count = 5;
// These variables allow use to avoid Setting events (which is expensive) if we don't have to.
private uint _numWriteWaiters; // maximum number of threads that can be doing a WaitOne on the writeEvent
private uint _numReadWaiters; // maximum number of threads that can be doing a WaitOne on the readEvent
private uint _numWriteUpgradeWaiters; // maximum number of threads that can be doing a WaitOne on the upgradeEvent (at most 1).
private uint _numUpgradeWaiters;
//Variable used for quick check when there are no waiters.
private bool _fNoWaiters;
private int _upgradeLockOwnerId;
private int _writeLockOwnerId;
// conditions we wait on.
private EventWaitHandle _writeEvent; // threads waiting to aquire a write lock go here.
private EventWaitHandle _readEvent; // threads waiting to aquire a read lock go here (will be released in bulk)
private EventWaitHandle _upgradeEvent; // thread waiting to acquire the upgrade lock
private EventWaitHandle _waitUpgradeEvent; // thread waiting to upgrade from the upgrade lock to a write lock go here (at most one)
// Every lock instance has a unique ID, which is used by ReaderWriterCount to associate itself with the lock
// without holding a reference to it.
private static long s_nextLockID;
private long _lockID;
// See comments on ReaderWriterCount.
[ThreadStatic]
private static ReaderWriterCount t_rwc;
private bool _fUpgradeThreadHoldingRead;
private const int MaxSpinCount = 20;
//The uint, that contains info like if the writer lock is held, num of
//readers etc.
private uint _owners;
//Various R/W masks
//Note:
//The Uint is divided as follows:
//
//Writer-Owned Waiting-Writers Waiting Upgraders Num-Readers
// 31 30 29 28.......0
//
//Dividing the uint, allows to vastly simplify logic for checking if a
//reader should go in etc. Setting the writer bit will automatically
//make the value of the uint much larger than the max num of readers
//allowed, thus causing the check for max_readers to fail.
private const uint WRITER_HELD = 0x80000000;
private const uint WAITING_WRITERS = 0x40000000;
private const uint WAITING_UPGRADER = 0x20000000;
//The max readers is actually one less then its theoretical max.
//This is done in order to prevent reader count overflows. If the reader
//count reaches max, other readers will wait.
private const uint MAX_READER = 0x10000000 - 2;
private const uint READER_MASK = 0x10000000 - 1;
private bool _fDisposed;
private void InitializeThreadCounts()
{
_upgradeLockOwnerId = -1;
_writeLockOwnerId = -1;
}
public ReaderWriterLockSlim()
: this(LockRecursionPolicy.NoRecursion)
{
}
public ReaderWriterLockSlim(LockRecursionPolicy recursionPolicy)
{
if (recursionPolicy == LockRecursionPolicy.SupportsRecursion)
{
_fIsReentrant = true;
}
InitializeThreadCounts();
_fNoWaiters = true;
_lockID = Interlocked.Increment(ref s_nextLockID);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static bool IsRWEntryEmpty(ReaderWriterCount rwc)
{
if (rwc.lockID == 0)
return true;
else if (rwc.readercount == 0 && rwc.writercount == 0 && rwc.upgradecount == 0)
return true;
else
return false;
}
private bool IsRwHashEntryChanged(ReaderWriterCount lrwc)
{
return lrwc.lockID != _lockID;
}
/// <summary>
/// This routine retrieves/sets the per-thread counts needed to enforce the
/// various rules related to acquiring the lock.
///
/// DontAllocate is set to true if the caller just wants to get an existing
/// entry for this thread, but doesn't want to add one if an existing one
/// could not be found.
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private ReaderWriterCount GetThreadRWCount(bool dontAllocate)
{
ReaderWriterCount rwc = t_rwc;
ReaderWriterCount empty = null;
while (rwc != null)
{
if (rwc.lockID == _lockID)
return rwc;
if (!dontAllocate && empty == null && IsRWEntryEmpty(rwc))
empty = rwc;
rwc = rwc.next;
}
if (dontAllocate)
return null;
if (empty == null)
{
empty = new ReaderWriterCount();
empty.next = t_rwc;
t_rwc = empty;
}
empty.lockID = _lockID;
return empty;
}
public void EnterReadLock()
{
TryEnterReadLock(-1);
}
//
// Common timeout support
//
private struct TimeoutTracker
{
private int _total;
private int _start;
public TimeoutTracker(TimeSpan timeout)
{
long ltm = (long)timeout.TotalMilliseconds;
if (ltm < -1 || ltm > (long)Int32.MaxValue)
throw new ArgumentOutOfRangeException(nameof(timeout));
_total = (int)ltm;
if (_total != -1 && _total != 0)
_start = Environment.TickCount;
else
_start = 0;
}
public TimeoutTracker(int millisecondsTimeout)
{
if (millisecondsTimeout < -1)
throw new ArgumentOutOfRangeException(nameof(millisecondsTimeout));
_total = millisecondsTimeout;
if (_total != -1 && _total != 0)
_start = Environment.TickCount;
else
_start = 0;
}
public int RemainingMilliseconds
{
get
{
if (_total == -1 || _total == 0)
return _total;
int elapsed = Environment.TickCount - _start;
// elapsed may be negative if TickCount has overflowed by 2^31 milliseconds.
if (elapsed < 0 || elapsed >= _total)
return 0;
return _total - elapsed;
}
}
public bool IsExpired
{
get
{
return RemainingMilliseconds == 0;
}
}
}
public bool TryEnterReadLock(TimeSpan timeout)
{
return TryEnterReadLock(new TimeoutTracker(timeout));
}
public bool TryEnterReadLock(int millisecondsTimeout)
{
return TryEnterReadLock(new TimeoutTracker(millisecondsTimeout));
}
private bool TryEnterReadLock(TimeoutTracker timeout)
{
return TryEnterReadLockCore(timeout);
}
private bool TryEnterReadLockCore(TimeoutTracker timeout)
{
if (_fDisposed)
throw new ObjectDisposedException(null);
ReaderWriterCount lrwc = null;
int id = Environment.CurrentManagedThreadId;
if (!_fIsReentrant)
{
if (id == _writeLockOwnerId)
{
//Check for AW->AR
throw new LockRecursionException(SR.LockRecursionException_ReadAfterWriteNotAllowed);
}
EnterMyLock();
lrwc = GetThreadRWCount(false);
//Check if the reader lock is already acquired. Note, we could
//check the presence of a reader by not allocating rwc (But that
//would lead to two lookups in the common case. It's better to keep
//a count in the structure).
if (lrwc.readercount > 0)
{
ExitMyLock();
throw new LockRecursionException(SR.LockRecursionException_RecursiveReadNotAllowed);
}
else if (id == _upgradeLockOwnerId)
{
//The upgrade lock is already held.
//Update the global read counts and exit.
lrwc.readercount++;
_owners++;
ExitMyLock();
return true;
}
}
else
{
EnterMyLock();
lrwc = GetThreadRWCount(false);
if (lrwc.readercount > 0)
{
lrwc.readercount++;
ExitMyLock();
return true;
}
else if (id == _upgradeLockOwnerId)
{
//The upgrade lock is already held.
//Update the global read counts and exit.
lrwc.readercount++;
_owners++;
ExitMyLock();
_fUpgradeThreadHoldingRead = true;
return true;
}
else if (id == _writeLockOwnerId)
{
//The write lock is already held.
//Update global read counts here,
lrwc.readercount++;
_owners++;
ExitMyLock();
return true;
}
}
bool retVal = true;
int spincount = 0;
for (;;)
{
// We can enter a read lock if there are only read-locks have been given out
// and a writer is not trying to get in.
if (_owners < MAX_READER)
{
// Good case, there is no contention, we are basically done
_owners++; // Indicate we have another reader
lrwc.readercount++;
break;
}
if (spincount < MaxSpinCount)
{
ExitMyLock();
if (timeout.IsExpired)
return false;
spincount++;
SpinWait(spincount);
EnterMyLock();
//The per-thread structure may have been recycled as the lock is acquired (due to message pumping), load again.
if (IsRwHashEntryChanged(lrwc))
lrwc = GetThreadRWCount(false);
continue;
}
// Drat, we need to wait. Mark that we have waiters and wait.
if (_readEvent == null) // Create the needed event
{
LazyCreateEvent(ref _readEvent, false);
if (IsRwHashEntryChanged(lrwc))
lrwc = GetThreadRWCount(false);
continue; // since we left the lock, start over.
}
retVal = WaitOnEvent(_readEvent, ref _numReadWaiters, timeout);
if (!retVal)
{
return false;
}
if (IsRwHashEntryChanged(lrwc))
lrwc = GetThreadRWCount(false);
}
ExitMyLock();
return retVal;
}
public void EnterWriteLock()
{
TryEnterWriteLock(-1);
}
public bool TryEnterWriteLock(TimeSpan timeout)
{
return TryEnterWriteLock(new TimeoutTracker(timeout));
}
public bool TryEnterWriteLock(int millisecondsTimeout)
{
return TryEnterWriteLock(new TimeoutTracker(millisecondsTimeout));
}
private bool TryEnterWriteLock(TimeoutTracker timeout)
{
return TryEnterWriteLockCore(timeout);
}
private bool TryEnterWriteLockCore(TimeoutTracker timeout)
{
if (_fDisposed)
throw new ObjectDisposedException(null);
int id = Environment.CurrentManagedThreadId;
ReaderWriterCount lrwc;
bool upgradingToWrite = false;
if (!_fIsReentrant)
{
if (id == _writeLockOwnerId)
{
//Check for AW->AW
throw new LockRecursionException(SR.LockRecursionException_RecursiveWriteNotAllowed);
}
else if (id == _upgradeLockOwnerId)
{
//AU->AW case is allowed once.
upgradingToWrite = true;
}
EnterMyLock();
lrwc = GetThreadRWCount(true);
//Can't acquire write lock with reader lock held.
if (lrwc != null && lrwc.readercount > 0)
{
ExitMyLock();
throw new LockRecursionException(SR.LockRecursionException_WriteAfterReadNotAllowed);
}
}
else
{
EnterMyLock();
lrwc = GetThreadRWCount(false);
if (id == _writeLockOwnerId)
{
lrwc.writercount++;
ExitMyLock();
return true;
}
else if (id == _upgradeLockOwnerId)
{
upgradingToWrite = true;
}
else if (lrwc.readercount > 0)
{
//Write locks may not be acquired if only read locks have been
//acquired.
ExitMyLock();
throw new LockRecursionException(SR.LockRecursionException_WriteAfterReadNotAllowed);
}
}
int spincount = 0;
bool retVal = true;
for (;;)
{
if (IsWriterAcquired())
{
// Good case, there is no contention, we are basically done
SetWriterAcquired();
break;
}
//Check if there is just one upgrader, and no readers.
//Assumption: Only one thread can have the upgrade lock, so the
//following check will fail for all other threads that may sneak in
//when the upgrading thread is waiting.
if (upgradingToWrite)
{
uint readercount = GetNumReaders();
if (readercount == 1)
{
//Good case again, there is just one upgrader, and no readers.
SetWriterAcquired(); // indicate we have a writer.
break;
}
else if (readercount == 2)
{
if (lrwc != null)
{
if (IsRwHashEntryChanged(lrwc))
lrwc = GetThreadRWCount(false);
if (lrwc.readercount > 0)
{
//This check is needed for EU->ER->EW case, as the owner count will be two.
Debug.Assert(_fIsReentrant);
Debug.Assert(_fUpgradeThreadHoldingRead);
//Good case again, there is just one upgrader, and no readers.
SetWriterAcquired(); // indicate we have a writer.
break;
}
}
}
}
if (spincount < MaxSpinCount)
{
ExitMyLock();
if (timeout.IsExpired)
return false;
spincount++;
SpinWait(spincount);
EnterMyLock();
continue;
}
if (upgradingToWrite)
{
if (_waitUpgradeEvent == null) // Create the needed event
{
LazyCreateEvent(ref _waitUpgradeEvent, true);
continue; // since we left the lock, start over.
}
Debug.Assert(_numWriteUpgradeWaiters == 0, "There can be at most one thread with the upgrade lock held.");
retVal = WaitOnEvent(_waitUpgradeEvent, ref _numWriteUpgradeWaiters, timeout);
//The lock is not held in case of failure.
if (!retVal)
return false;
}
else
{
// Drat, we need to wait. Mark that we have waiters and wait.
if (_writeEvent == null) // create the needed event.
{
LazyCreateEvent(ref _writeEvent, true);
continue; // since we left the lock, start over.
}
retVal = WaitOnEvent(_writeEvent, ref _numWriteWaiters, timeout);
//The lock is not held in case of failure.
if (!retVal)
return false;
}
}
Debug.Assert((_owners & WRITER_HELD) > 0);
if (_fIsReentrant)
{
if (IsRwHashEntryChanged(lrwc))
lrwc = GetThreadRWCount(false);
lrwc.writercount++;
}
ExitMyLock();
_writeLockOwnerId = id;
return true;
}
public void EnterUpgradeableReadLock()
{
TryEnterUpgradeableReadLock(-1);
}
public bool TryEnterUpgradeableReadLock(TimeSpan timeout)
{
return TryEnterUpgradeableReadLock(new TimeoutTracker(timeout));
}
public bool TryEnterUpgradeableReadLock(int millisecondsTimeout)
{
return TryEnterUpgradeableReadLock(new TimeoutTracker(millisecondsTimeout));
}
private bool TryEnterUpgradeableReadLock(TimeoutTracker timeout)
{
return TryEnterUpgradeableReadLockCore(timeout);
}
private bool TryEnterUpgradeableReadLockCore(TimeoutTracker timeout)
{
if (_fDisposed)
throw new ObjectDisposedException(null);
int id = Environment.CurrentManagedThreadId;
ReaderWriterCount lrwc;
if (!_fIsReentrant)
{
if (id == _upgradeLockOwnerId)
{
//Check for AU->AU
throw new LockRecursionException(SR.LockRecursionException_RecursiveUpgradeNotAllowed);
}
else if (id == _writeLockOwnerId)
{
//Check for AU->AW
throw new LockRecursionException(SR.LockRecursionException_UpgradeAfterWriteNotAllowed);
}
EnterMyLock();
lrwc = GetThreadRWCount(true);
//Can't acquire upgrade lock with reader lock held.
if (lrwc != null && lrwc.readercount > 0)
{
ExitMyLock();
throw new LockRecursionException(SR.LockRecursionException_UpgradeAfterReadNotAllowed);
}
}
else
{
EnterMyLock();
lrwc = GetThreadRWCount(false);
if (id == _upgradeLockOwnerId)
{
lrwc.upgradecount++;
ExitMyLock();
return true;
}
else if (id == _writeLockOwnerId)
{
//Write lock is already held, Just update the global state
//to show presence of upgrader.
Debug.Assert((_owners & WRITER_HELD) > 0);
_owners++;
_upgradeLockOwnerId = id;
lrwc.upgradecount++;
if (lrwc.readercount > 0)
_fUpgradeThreadHoldingRead = true;
ExitMyLock();
return true;
}
else if (lrwc.readercount > 0)
{
//Upgrade locks may not be acquired if only read locks have been
//acquired.
ExitMyLock();
throw new LockRecursionException(SR.LockRecursionException_UpgradeAfterReadNotAllowed);
}
}
bool retVal = true;
int spincount = 0;
for (;;)
{
//Once an upgrade lock is taken, it's like having a reader lock held
//until upgrade or downgrade operations are performed.
if ((_upgradeLockOwnerId == -1) && (_owners < MAX_READER))
{
_owners++;
_upgradeLockOwnerId = id;
break;
}
if (spincount < MaxSpinCount)
{
ExitMyLock();
if (timeout.IsExpired)
return false;
spincount++;
SpinWait(spincount);
EnterMyLock();
continue;
}
// Drat, we need to wait. Mark that we have waiters and wait.
if (_upgradeEvent == null) // Create the needed event
{
LazyCreateEvent(ref _upgradeEvent, true);
continue; // since we left the lock, start over.
}
//Only one thread with the upgrade lock held can proceed.
retVal = WaitOnEvent(_upgradeEvent, ref _numUpgradeWaiters, timeout);
if (!retVal)
return false;
}
if (_fIsReentrant)
{
//The lock may have been dropped getting here, so make a quick check to see whether some other
//thread did not grab the entry.
if (IsRwHashEntryChanged(lrwc))
lrwc = GetThreadRWCount(false);
lrwc.upgradecount++;
}
ExitMyLock();
return true;
}
public void ExitReadLock()
{
ReaderWriterCount lrwc = null;
EnterMyLock();
lrwc = GetThreadRWCount(true);
if (lrwc == null || lrwc.readercount < 1)
{
//You have to be holding the read lock to make this call.
ExitMyLock();
throw new SynchronizationLockException(SR.SynchronizationLockException_MisMatchedRead);
}
if (_fIsReentrant)
{
if (lrwc.readercount > 1)
{
lrwc.readercount--;
ExitMyLock();
return;
}
if (Environment.CurrentManagedThreadId == _upgradeLockOwnerId)
{
_fUpgradeThreadHoldingRead = false;
}
}
Debug.Assert(_owners > 0, "ReleasingReaderLock: releasing lock and no read lock taken");
--_owners;
Debug.Assert(lrwc.readercount == 1);
lrwc.readercount--;
ExitAndWakeUpAppropriateWaiters();
}
public void ExitWriteLock()
{
ReaderWriterCount lrwc;
if (!_fIsReentrant)
{
if (Environment.CurrentManagedThreadId != _writeLockOwnerId)
{
//You have to be holding the write lock to make this call.
throw new SynchronizationLockException(SR.SynchronizationLockException_MisMatchedWrite);
}
EnterMyLock();
}
else
{
EnterMyLock();
lrwc = GetThreadRWCount(false);
if (lrwc == null)
{
ExitMyLock();
throw new SynchronizationLockException(SR.SynchronizationLockException_MisMatchedWrite);
}
if (lrwc.writercount < 1)
{
ExitMyLock();
throw new SynchronizationLockException(SR.SynchronizationLockException_MisMatchedWrite);
}
lrwc.writercount--;
if (lrwc.writercount > 0)
{
ExitMyLock();
return;
}
}
Debug.Assert((_owners & WRITER_HELD) > 0, "Calling ReleaseWriterLock when no write lock is held");
ClearWriterAcquired();
_writeLockOwnerId = -1;
ExitAndWakeUpAppropriateWaiters();
}
public void ExitUpgradeableReadLock()
{
ReaderWriterCount lrwc;
if (!_fIsReentrant)
{
if (Environment.CurrentManagedThreadId != _upgradeLockOwnerId)
{
//You have to be holding the upgrade lock to make this call.
throw new SynchronizationLockException(SR.SynchronizationLockException_MisMatchedUpgrade);
}
EnterMyLock();
}
else
{
EnterMyLock();
lrwc = GetThreadRWCount(true);
if (lrwc == null)
{
ExitMyLock();
throw new SynchronizationLockException(SR.SynchronizationLockException_MisMatchedUpgrade);
}
if (lrwc.upgradecount < 1)
{
ExitMyLock();
throw new SynchronizationLockException(SR.SynchronizationLockException_MisMatchedUpgrade);
}
lrwc.upgradecount--;
if (lrwc.upgradecount > 0)
{
ExitMyLock();
return;
}
_fUpgradeThreadHoldingRead = false;
}
_owners--;
_upgradeLockOwnerId = -1;
ExitAndWakeUpAppropriateWaiters();
}
/// <summary>
/// A routine for lazily creating a event outside the lock (so if errors
/// happen they are outside the lock and that we don't do much work
/// while holding a spin lock). If all goes well, reenter the lock and
/// set 'waitEvent'
/// </summary>
private void LazyCreateEvent(ref EventWaitHandle waitEvent, bool makeAutoResetEvent)
{
#if DEBUG
Debug.Assert(MyLockHeld);
Debug.Assert(waitEvent == null);
#endif
ExitMyLock();
EventWaitHandle newEvent;
if (makeAutoResetEvent)
newEvent = new AutoResetEvent(false);
else
newEvent = new ManualResetEvent(false);
EnterMyLock();
if (waitEvent == null) // maybe someone snuck in.
waitEvent = newEvent;
else
newEvent.Dispose();
}
/// <summary>
/// Waits on 'waitEvent' with a timeout
/// Before the wait 'numWaiters' is incremented and is restored before leaving this routine.
/// </summary>
private bool WaitOnEvent(EventWaitHandle waitEvent, ref uint numWaiters, TimeoutTracker timeout)
{
#if DEBUG
Debug.Assert(MyLockHeld);
#endif
waitEvent.Reset();
numWaiters++;
_fNoWaiters = false;
//Setting these bits will prevent new readers from getting in.
if (_numWriteWaiters == 1)
SetWritersWaiting();
if (_numWriteUpgradeWaiters == 1)
SetUpgraderWaiting();
bool waitSuccessful = false;
ExitMyLock(); // Do the wait outside of any lock
try
{
waitSuccessful = waitEvent.WaitOne(timeout.RemainingMilliseconds);
}
finally
{
EnterMyLock();
--numWaiters;
if (_numWriteWaiters == 0 && _numWriteUpgradeWaiters == 0 && _numUpgradeWaiters == 0 && _numReadWaiters == 0)
_fNoWaiters = true;
if (_numWriteWaiters == 0)
ClearWritersWaiting();
if (_numWriteUpgradeWaiters == 0)
ClearUpgraderWaiting();
if (!waitSuccessful) // We may also be about to throw for some reason. Exit myLock.
ExitMyLock();
}
return waitSuccessful;
}
/// <summary>
/// Determines the appropriate events to set, leaves the locks, and sets the events.
/// </summary>
private void ExitAndWakeUpAppropriateWaiters()
{
#if DEBUG
Debug.Assert(MyLockHeld);
#endif
if (_fNoWaiters)
{
ExitMyLock();
return;
}
ExitAndWakeUpAppropriateWaitersPreferringWriters();
}
private void ExitAndWakeUpAppropriateWaitersPreferringWriters()
{
bool setUpgradeEvent = false;
bool setReadEvent = false;
uint readercount = GetNumReaders();
//We need this case for EU->ER->EW case, as the read count will be 2 in
//that scenario.
if (_fIsReentrant)
{
if (_numWriteUpgradeWaiters > 0 && _fUpgradeThreadHoldingRead && readercount == 2)
{
ExitMyLock(); // Exit before signaling to improve efficiency (wakee will need the lock)
_waitUpgradeEvent.Set(); // release all upgraders (however there can be at most one).
return;
}
}
if (readercount == 1 && _numWriteUpgradeWaiters > 0)
{
//We have to be careful now, as we are droppping the lock.
//No new writes should be allowed to sneak in if an upgrade
//was pending.
ExitMyLock(); // Exit before signaling to improve efficiency (wakee will need the lock)
_waitUpgradeEvent.Set(); // release all upgraders (however there can be at most one).
}
else if (readercount == 0 && _numWriteWaiters > 0)
{
ExitMyLock(); // Exit before signaling to improve efficiency (wakee will need the lock)
_writeEvent.Set(); // release one writer.
}
else if (readercount >= 0)
{
if (_numReadWaiters != 0 || _numUpgradeWaiters != 0)
{
if (_numReadWaiters != 0)
setReadEvent = true;
if (_numUpgradeWaiters != 0 && _upgradeLockOwnerId == -1)
{
setUpgradeEvent = true;
}
ExitMyLock(); // Exit before signaling to improve efficiency (wakee will need the lock)
if (setReadEvent)
_readEvent.Set(); // release all readers.
if (setUpgradeEvent)
_upgradeEvent.Set(); //release one upgrader.
}
else
ExitMyLock();
}
else
ExitMyLock();
}
private bool IsWriterAcquired()
{
return (_owners & ~WAITING_WRITERS) == 0;
}
private void SetWriterAcquired()
{
_owners |= WRITER_HELD; // indicate we have a writer.
}
private void ClearWriterAcquired()
{
_owners &= ~WRITER_HELD;
}
private void SetWritersWaiting()
{
_owners |= WAITING_WRITERS;
}
private void ClearWritersWaiting()
{
_owners &= ~WAITING_WRITERS;
}
private void SetUpgraderWaiting()
{
_owners |= WAITING_UPGRADER;
}
private void ClearUpgraderWaiting()
{
_owners &= ~WAITING_UPGRADER;
}
private uint GetNumReaders()
{
return _owners & READER_MASK;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private void EnterMyLock()
{
if (Interlocked.CompareExchange(ref _myLock, 1, 0) != 0)
EnterMyLockSpin();
}
private void EnterMyLockSpin()
{
int pc = Environment.ProcessorCount;
for (int i = 0; ; i++)
{
if (i < LockSpinCount && pc > 1)
{
RuntimeThread.SpinWait(LockSpinCycles * (i + 1)); // Wait a few dozen instructions to let another processor release lock.
}
else if (i < (LockSpinCount + LockSleep0Count))
{
RuntimeThread.Sleep(0); // Give up my quantum.
}
else
{
RuntimeThread.Sleep(1); // Give up my quantum.
}
if (_myLock == 0 && Interlocked.CompareExchange(ref _myLock, 1, 0) == 0)
return;
}
}
private void ExitMyLock()
{
Debug.Assert(_myLock != 0, "Exiting spin lock that is not held");
Volatile.Write(ref _myLock, 0);
}
#if DEBUG
private bool MyLockHeld { get { return _myLock != 0; } }
#endif
private static void SpinWait(int SpinCount)
{
//Exponential backoff
if ((SpinCount < 5) && (Environment.ProcessorCount > 1))
{
RuntimeThread.SpinWait(LockSpinCycles * SpinCount);
}
else if (SpinCount < MaxSpinCount - 3)
{
RuntimeThread.Sleep(0);
}
else
{
RuntimeThread.Sleep(1);
}
}
public void Dispose()
{
Dispose(true);
}
private void Dispose(bool disposing)
{
if (disposing && !_fDisposed)
{
if (WaitingReadCount > 0 || WaitingUpgradeCount > 0 || WaitingWriteCount > 0)
throw new SynchronizationLockException(SR.SynchronizationLockException_IncorrectDispose);
if (IsReadLockHeld || IsUpgradeableReadLockHeld || IsWriteLockHeld)
throw new SynchronizationLockException(SR.SynchronizationLockException_IncorrectDispose);
if (_writeEvent != null)
{
_writeEvent.Dispose();
_writeEvent = null;
}
if (_readEvent != null)
{
_readEvent.Dispose();
_readEvent = null;
}
if (_upgradeEvent != null)
{
_upgradeEvent.Dispose();
_upgradeEvent = null;
}
if (_waitUpgradeEvent != null)
{
_waitUpgradeEvent.Dispose();
_waitUpgradeEvent = null;
}
_fDisposed = true;
}
}
public bool IsReadLockHeld
{
get
{
if (RecursiveReadCount > 0)
return true;
else
return false;
}
}
public bool IsUpgradeableReadLockHeld
{
get
{
if (RecursiveUpgradeCount > 0)
return true;
else
return false;
}
}
public bool IsWriteLockHeld
{
get
{
if (RecursiveWriteCount > 0)
return true;
else
return false;
}
}
public LockRecursionPolicy RecursionPolicy
{
get
{
if (_fIsReentrant)
{
return LockRecursionPolicy.SupportsRecursion;
}
else
{
return LockRecursionPolicy.NoRecursion;
}
}
}
public int CurrentReadCount
{
get
{
int numreaders = (int)GetNumReaders();
if (_upgradeLockOwnerId != -1)
return numreaders - 1;
else
return numreaders;
}
}
public int RecursiveReadCount
{
get
{
int count = 0;
ReaderWriterCount lrwc = GetThreadRWCount(true);
if (lrwc != null)
count = lrwc.readercount;
return count;
}
}
public int RecursiveUpgradeCount
{
get
{
if (_fIsReentrant)
{
int count = 0;
ReaderWriterCount lrwc = GetThreadRWCount(true);
if (lrwc != null)
count = lrwc.upgradecount;
return count;
}
else
{
if (Environment.CurrentManagedThreadId == _upgradeLockOwnerId)
return 1;
else
return 0;
}
}
}
public int RecursiveWriteCount
{
get
{
if (_fIsReentrant)
{
int count = 0;
ReaderWriterCount lrwc = GetThreadRWCount(true);
if (lrwc != null)
count = lrwc.writercount;
return count;
}
else
{
if (Environment.CurrentManagedThreadId == _writeLockOwnerId)
return 1;
else
return 0;
}
}
}
public int WaitingReadCount
{
get
{
return (int)_numReadWaiters;
}
}
public int WaitingUpgradeCount
{
get
{
return (int)_numUpgradeWaiters;
}
}
public int WaitingWriteCount
{
get
{
return (int)_numWriteWaiters;
}
}
}
}
| |
/*
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
namespace Amazon.CloudWatch.Model
{
/// <summary>
/// <para> The MetricAlarm data type represents an alarm. You can use PutMetricAlarm to create or update an alarm. </para>
/// </summary>
public class MetricAlarm
{
private string alarmName;
private string alarmArn;
private string alarmDescription;
private DateTime? alarmConfigurationUpdatedTimestamp;
private bool? actionsEnabled;
private List<string> oKActions = new List<string>();
private List<string> alarmActions = new List<string>();
private List<string> insufficientDataActions = new List<string>();
private string stateValue;
private string stateReason;
private string stateReasonData;
private DateTime? stateUpdatedTimestamp;
private string metricName;
private string namespaceValue;
private string statistic;
private List<Dimension> dimensions = new List<Dimension>();
private int? period;
private string unit;
private int? evaluationPeriods;
private double? threshold;
private string comparisonOperator;
/// <summary>
/// The name of the alarm.
///
/// <para>
/// <b>Constraints:</b>
/// <list type="definition">
/// <item>
/// <term>Length</term>
/// <description>1 - 255</description>
/// </item>
/// </list>
/// </para>
/// </summary>
public string AlarmName
{
get { return this.alarmName; }
set { this.alarmName = value; }
}
/// <summary>
/// Sets the AlarmName property
/// </summary>
/// <param name="alarmName">The value to set for the AlarmName property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public MetricAlarm WithAlarmName(string alarmName)
{
this.alarmName = alarmName;
return this;
}
// Check to see if AlarmName property is set
internal bool IsSetAlarmName()
{
return this.alarmName != null;
}
/// <summary>
/// The Amazon Resource Name (ARN) of the alarm.
///
/// <para>
/// <b>Constraints:</b>
/// <list type="definition">
/// <item>
/// <term>Length</term>
/// <description>1 - 1600</description>
/// </item>
/// </list>
/// </para>
/// </summary>
public string AlarmArn
{
get { return this.alarmArn; }
set { this.alarmArn = value; }
}
/// <summary>
/// Sets the AlarmArn property
/// </summary>
/// <param name="alarmArn">The value to set for the AlarmArn property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public MetricAlarm WithAlarmArn(string alarmArn)
{
this.alarmArn = alarmArn;
return this;
}
// Check to see if AlarmArn property is set
internal bool IsSetAlarmArn()
{
return this.alarmArn != null;
}
/// <summary>
/// The description for the alarm.
///
/// <para>
/// <b>Constraints:</b>
/// <list type="definition">
/// <item>
/// <term>Length</term>
/// <description>0 - 255</description>
/// </item>
/// </list>
/// </para>
/// </summary>
public string AlarmDescription
{
get { return this.alarmDescription; }
set { this.alarmDescription = value; }
}
/// <summary>
/// Sets the AlarmDescription property
/// </summary>
/// <param name="alarmDescription">The value to set for the AlarmDescription property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public MetricAlarm WithAlarmDescription(string alarmDescription)
{
this.alarmDescription = alarmDescription;
return this;
}
// Check to see if AlarmDescription property is set
internal bool IsSetAlarmDescription()
{
return this.alarmDescription != null;
}
/// <summary>
/// The time stamp of the last update to the alarm configuration.
///
/// </summary>
public DateTime AlarmConfigurationUpdatedTimestamp
{
get { return this.alarmConfigurationUpdatedTimestamp ?? default(DateTime); }
set { this.alarmConfigurationUpdatedTimestamp = value; }
}
/// <summary>
/// Sets the AlarmConfigurationUpdatedTimestamp property
/// </summary>
/// <param name="alarmConfigurationUpdatedTimestamp">The value to set for the AlarmConfigurationUpdatedTimestamp property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public MetricAlarm WithAlarmConfigurationUpdatedTimestamp(DateTime alarmConfigurationUpdatedTimestamp)
{
this.alarmConfigurationUpdatedTimestamp = alarmConfigurationUpdatedTimestamp;
return this;
}
// Check to see if AlarmConfigurationUpdatedTimestamp property is set
internal bool IsSetAlarmConfigurationUpdatedTimestamp()
{
return this.alarmConfigurationUpdatedTimestamp.HasValue;
}
/// <summary>
/// Indicates whether actions should be executed during any changes to the alarm's state.
///
/// </summary>
public bool ActionsEnabled
{
get { return this.actionsEnabled ?? default(bool); }
set { this.actionsEnabled = value; }
}
/// <summary>
/// Sets the ActionsEnabled property
/// </summary>
/// <param name="actionsEnabled">The value to set for the ActionsEnabled property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public MetricAlarm WithActionsEnabled(bool actionsEnabled)
{
this.actionsEnabled = actionsEnabled;
return this;
}
// Check to see if ActionsEnabled property is set
internal bool IsSetActionsEnabled()
{
return this.actionsEnabled.HasValue;
}
/// <summary>
/// The list of actions to execute when this alarm transitions into an <c>OK</c> state from any other state. Each action is specified as an
/// Amazon Resource Number (ARN). Currently the only actions supported are publishing to an Amazon SNS topic and triggering an Auto Scaling
/// policy.
///
/// <para>
/// <b>Constraints:</b>
/// <list type="definition">
/// <item>
/// <term>Length</term>
/// <description>0 - 5</description>
/// </item>
/// </list>
/// </para>
/// </summary>
public List<string> OKActions
{
get { return this.oKActions; }
set { this.oKActions = value; }
}
/// <summary>
/// Adds elements to the OKActions collection
/// </summary>
/// <param name="oKActions">The values to add to the OKActions collection </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public MetricAlarm WithOKActions(params string[] oKActions)
{
foreach (string element in oKActions)
{
this.oKActions.Add(element);
}
return this;
}
/// <summary>
/// Adds elements to the OKActions collection
/// </summary>
/// <param name="oKActions">The values to add to the OKActions collection </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public MetricAlarm WithOKActions(IEnumerable<string> oKActions)
{
foreach (string element in oKActions)
{
this.oKActions.Add(element);
}
return this;
}
// Check to see if OKActions property is set
internal bool IsSetOKActions()
{
return this.oKActions.Count > 0;
}
/// <summary>
/// The list of actions to execute when this alarm transitions into an <c>ALARM</c> state from any other state. Each action is specified as an
/// Amazon Resource Number (ARN). Currently the only actions supported are publishing to an Amazon SNS topic and triggering an Auto Scaling
/// policy.
///
/// <para>
/// <b>Constraints:</b>
/// <list type="definition">
/// <item>
/// <term>Length</term>
/// <description>0 - 5</description>
/// </item>
/// </list>
/// </para>
/// </summary>
public List<string> AlarmActions
{
get { return this.alarmActions; }
set { this.alarmActions = value; }
}
/// <summary>
/// Adds elements to the AlarmActions collection
/// </summary>
/// <param name="alarmActions">The values to add to the AlarmActions collection </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public MetricAlarm WithAlarmActions(params string[] alarmActions)
{
foreach (string element in alarmActions)
{
this.alarmActions.Add(element);
}
return this;
}
/// <summary>
/// Adds elements to the AlarmActions collection
/// </summary>
/// <param name="alarmActions">The values to add to the AlarmActions collection </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public MetricAlarm WithAlarmActions(IEnumerable<string> alarmActions)
{
foreach (string element in alarmActions)
{
this.alarmActions.Add(element);
}
return this;
}
// Check to see if AlarmActions property is set
internal bool IsSetAlarmActions()
{
return this.alarmActions.Count > 0;
}
/// <summary>
/// The list of actions to execute when this alarm transitions into an <c>INSUFFICIENT_DATA</c> state from any other state. Each action is
/// specified as an Amazon Resource Number (ARN). Currently the only actions supported are publishing to an Amazon SNS topic or triggering an
/// Auto Scaling policy. <important>The current WSDL lists this attribute as <c>UnknownActions</c>.</important>
///
/// <para>
/// <b>Constraints:</b>
/// <list type="definition">
/// <item>
/// <term>Length</term>
/// <description>0 - 5</description>
/// </item>
/// </list>
/// </para>
/// </summary>
public List<string> InsufficientDataActions
{
get { return this.insufficientDataActions; }
set { this.insufficientDataActions = value; }
}
/// <summary>
/// Adds elements to the InsufficientDataActions collection
/// </summary>
/// <param name="insufficientDataActions">The values to add to the InsufficientDataActions collection </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public MetricAlarm WithInsufficientDataActions(params string[] insufficientDataActions)
{
foreach (string element in insufficientDataActions)
{
this.insufficientDataActions.Add(element);
}
return this;
}
/// <summary>
/// Adds elements to the InsufficientDataActions collection
/// </summary>
/// <param name="insufficientDataActions">The values to add to the InsufficientDataActions collection </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public MetricAlarm WithInsufficientDataActions(IEnumerable<string> insufficientDataActions)
{
foreach (string element in insufficientDataActions)
{
this.insufficientDataActions.Add(element);
}
return this;
}
// Check to see if InsufficientDataActions property is set
internal bool IsSetInsufficientDataActions()
{
return this.insufficientDataActions.Count > 0;
}
/// <summary>
/// The state value for the alarm.
///
/// <para>
/// <b>Constraints:</b>
/// <list type="definition">
/// <item>
/// <term>Allowed Values</term>
/// <description>OK, ALARM, INSUFFICIENT_DATA</description>
/// </item>
/// </list>
/// </para>
/// </summary>
public string StateValue
{
get { return this.stateValue; }
set { this.stateValue = value; }
}
/// <summary>
/// Sets the StateValue property
/// </summary>
/// <param name="stateValue">The value to set for the StateValue property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public MetricAlarm WithStateValue(string stateValue)
{
this.stateValue = stateValue;
return this;
}
// Check to see if StateValue property is set
internal bool IsSetStateValue()
{
return this.stateValue != null;
}
/// <summary>
/// A human-readable explanation for the alarm's state.
///
/// <para>
/// <b>Constraints:</b>
/// <list type="definition">
/// <item>
/// <term>Length</term>
/// <description>0 - 1023</description>
/// </item>
/// </list>
/// </para>
/// </summary>
public string StateReason
{
get { return this.stateReason; }
set { this.stateReason = value; }
}
/// <summary>
/// Sets the StateReason property
/// </summary>
/// <param name="stateReason">The value to set for the StateReason property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public MetricAlarm WithStateReason(string stateReason)
{
this.stateReason = stateReason;
return this;
}
// Check to see if StateReason property is set
internal bool IsSetStateReason()
{
return this.stateReason != null;
}
/// <summary>
/// An explanation for the alarm's state in machine-readable JSON format
///
/// <para>
/// <b>Constraints:</b>
/// <list type="definition">
/// <item>
/// <term>Length</term>
/// <description>0 - 4000</description>
/// </item>
/// </list>
/// </para>
/// </summary>
public string StateReasonData
{
get { return this.stateReasonData; }
set { this.stateReasonData = value; }
}
/// <summary>
/// Sets the StateReasonData property
/// </summary>
/// <param name="stateReasonData">The value to set for the StateReasonData property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public MetricAlarm WithStateReasonData(string stateReasonData)
{
this.stateReasonData = stateReasonData;
return this;
}
// Check to see if StateReasonData property is set
internal bool IsSetStateReasonData()
{
return this.stateReasonData != null;
}
/// <summary>
/// The time stamp of the last update to the alarm's state.
///
/// </summary>
public DateTime StateUpdatedTimestamp
{
get { return this.stateUpdatedTimestamp ?? default(DateTime); }
set { this.stateUpdatedTimestamp = value; }
}
/// <summary>
/// Sets the StateUpdatedTimestamp property
/// </summary>
/// <param name="stateUpdatedTimestamp">The value to set for the StateUpdatedTimestamp property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public MetricAlarm WithStateUpdatedTimestamp(DateTime stateUpdatedTimestamp)
{
this.stateUpdatedTimestamp = stateUpdatedTimestamp;
return this;
}
// Check to see if StateUpdatedTimestamp property is set
internal bool IsSetStateUpdatedTimestamp()
{
return this.stateUpdatedTimestamp.HasValue;
}
/// <summary>
/// The name of the alarm's metric.
///
/// <para>
/// <b>Constraints:</b>
/// <list type="definition">
/// <item>
/// <term>Length</term>
/// <description>1 - 255</description>
/// </item>
/// </list>
/// </para>
/// </summary>
public string MetricName
{
get { return this.metricName; }
set { this.metricName = value; }
}
/// <summary>
/// Sets the MetricName property
/// </summary>
/// <param name="metricName">The value to set for the MetricName property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public MetricAlarm WithMetricName(string metricName)
{
this.metricName = metricName;
return this;
}
// Check to see if MetricName property is set
internal bool IsSetMetricName()
{
return this.metricName != null;
}
/// <summary>
/// The namespace of alarm's associated metric.
///
/// <para>
/// <b>Constraints:</b>
/// <list type="definition">
/// <item>
/// <term>Length</term>
/// <description>1 - 255</description>
/// </item>
/// <item>
/// <term>Pattern</term>
/// <description>[^:].*</description>
/// </item>
/// </list>
/// </para>
/// </summary>
public string Namespace
{
get { return this.namespaceValue; }
set { this.namespaceValue = value; }
}
/// <summary>
/// Sets the Namespace property
/// </summary>
/// <param name="namespaceValue">The value to set for the Namespace property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public MetricAlarm WithNamespace(string namespaceValue)
{
this.namespaceValue = namespaceValue;
return this;
}
// Check to see if Namespace property is set
internal bool IsSetNamespace()
{
return this.namespaceValue != null;
}
/// <summary>
/// The statistic to apply to the alarm's associated metric.
///
/// <para>
/// <b>Constraints:</b>
/// <list type="definition">
/// <item>
/// <term>Allowed Values</term>
/// <description>SampleCount, Average, Sum, Minimum, Maximum</description>
/// </item>
/// </list>
/// </para>
/// </summary>
public string Statistic
{
get { return this.statistic; }
set { this.statistic = value; }
}
/// <summary>
/// Sets the Statistic property
/// </summary>
/// <param name="statistic">The value to set for the Statistic property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public MetricAlarm WithStatistic(string statistic)
{
this.statistic = statistic;
return this;
}
// Check to see if Statistic property is set
internal bool IsSetStatistic()
{
return this.statistic != null;
}
/// <summary>
/// The list of dimensions associated with the alarm's associated metric.
///
/// <para>
/// <b>Constraints:</b>
/// <list type="definition">
/// <item>
/// <term>Length</term>
/// <description>0 - 10</description>
/// </item>
/// </list>
/// </para>
/// </summary>
public List<Dimension> Dimensions
{
get { return this.dimensions; }
set { this.dimensions = value; }
}
/// <summary>
/// Adds elements to the Dimensions collection
/// </summary>
/// <param name="dimensions">The values to add to the Dimensions collection </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public MetricAlarm WithDimensions(params Dimension[] dimensions)
{
foreach (Dimension element in dimensions)
{
this.dimensions.Add(element);
}
return this;
}
/// <summary>
/// Adds elements to the Dimensions collection
/// </summary>
/// <param name="dimensions">The values to add to the Dimensions collection </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public MetricAlarm WithDimensions(IEnumerable<Dimension> dimensions)
{
foreach (Dimension element in dimensions)
{
this.dimensions.Add(element);
}
return this;
}
// Check to see if Dimensions property is set
internal bool IsSetDimensions()
{
return this.dimensions.Count > 0;
}
/// <summary>
/// The period in seconds over which the statistic is applied.
///
/// <para>
/// <b>Constraints:</b>
/// <list type="definition">
/// <item>
/// <term>Range</term>
/// <description>60 - </description>
/// </item>
/// </list>
/// </para>
/// </summary>
public int Period
{
get { return this.period ?? default(int); }
set { this.period = value; }
}
/// <summary>
/// Sets the Period property
/// </summary>
/// <param name="period">The value to set for the Period property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public MetricAlarm WithPeriod(int period)
{
this.period = period;
return this;
}
// Check to see if Period property is set
internal bool IsSetPeriod()
{
return this.period.HasValue;
}
/// <summary>
/// The unit of the alarm's associated metric.
///
/// <para>
/// <b>Constraints:</b>
/// <list type="definition">
/// <item>
/// <term>Allowed Values</term>
/// <description>Seconds, Microseconds, Milliseconds, Bytes, Kilobytes, Megabytes, Gigabytes, Terabytes, Bits, Kilobits, Megabits, Gigabits, Terabits, Percent, Count, Bytes/Second, Kilobytes/Second, Megabytes/Second, Gigabytes/Second, Terabytes/Second, Bits/Second, Kilobits/Second, Megabits/Second, Gigabits/Second, Terabits/Second, Count/Second, None</description>
/// </item>
/// </list>
/// </para>
/// </summary>
public string Unit
{
get { return this.unit; }
set { this.unit = value; }
}
/// <summary>
/// Sets the Unit property
/// </summary>
/// <param name="unit">The value to set for the Unit property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public MetricAlarm WithUnit(string unit)
{
this.unit = unit;
return this;
}
// Check to see if Unit property is set
internal bool IsSetUnit()
{
return this.unit != null;
}
/// <summary>
/// The number of periods over which data is compared to the specified threshold.
///
/// <para>
/// <b>Constraints:</b>
/// <list type="definition">
/// <item>
/// <term>Range</term>
/// <description>1 - </description>
/// </item>
/// </list>
/// </para>
/// </summary>
public int EvaluationPeriods
{
get { return this.evaluationPeriods ?? default(int); }
set { this.evaluationPeriods = value; }
}
/// <summary>
/// Sets the EvaluationPeriods property
/// </summary>
/// <param name="evaluationPeriods">The value to set for the EvaluationPeriods property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public MetricAlarm WithEvaluationPeriods(int evaluationPeriods)
{
this.evaluationPeriods = evaluationPeriods;
return this;
}
// Check to see if EvaluationPeriods property is set
internal bool IsSetEvaluationPeriods()
{
return this.evaluationPeriods.HasValue;
}
/// <summary>
/// The value against which the specified statistic is compared.
///
/// </summary>
public double Threshold
{
get { return this.threshold ?? default(double); }
set { this.threshold = value; }
}
/// <summary>
/// Sets the Threshold property
/// </summary>
/// <param name="threshold">The value to set for the Threshold property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public MetricAlarm WithThreshold(double threshold)
{
this.threshold = threshold;
return this;
}
// Check to see if Threshold property is set
internal bool IsSetThreshold()
{
return this.threshold.HasValue;
}
/// <summary>
/// The arithmetic operation to use when comparing the specified <c>Statistic</c> and <c>Threshold</c>. The specified <c>Statistic</c> value is
/// used as the first operand.
///
/// <para>
/// <b>Constraints:</b>
/// <list type="definition">
/// <item>
/// <term>Allowed Values</term>
/// <description>GreaterThanOrEqualToThreshold, GreaterThanThreshold, LessThanThreshold, LessThanOrEqualToThreshold</description>
/// </item>
/// </list>
/// </para>
/// </summary>
public string ComparisonOperator
{
get { return this.comparisonOperator; }
set { this.comparisonOperator = value; }
}
/// <summary>
/// Sets the ComparisonOperator property
/// </summary>
/// <param name="comparisonOperator">The value to set for the ComparisonOperator property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public MetricAlarm WithComparisonOperator(string comparisonOperator)
{
this.comparisonOperator = comparisonOperator;
return this;
}
// Check to see if ComparisonOperator property is set
internal bool IsSetComparisonOperator()
{
return this.comparisonOperator != null;
}
}
}
| |
using System;
using System.Collections.Generic;
using UnityEngine;
using KSP.Localization;
namespace KERBALISM
{
public sealed class Drive
{
public Drive(string name, double dataCapacity, int sampleCapacity, bool is_private = false)
{
this.files = new Dictionary<SubjectData, File>();
this.samples = new Dictionary<SubjectData, Sample>();
this.fileSendFlags = new Dictionary<string, bool>();
this.dataCapacity = dataCapacity;
this.sampleCapacity = sampleCapacity;
this.name = name;
this.is_private = is_private;
}
public Drive(ConfigNode node)
{
// parse science files
files = new Dictionary<SubjectData, File>();
if (node.HasNode("files"))
{
foreach (var file_node in node.GetNode("files").GetNodes())
{
string subject_id = DB.From_safe_key(file_node.name);
File file = File.Load(subject_id, file_node);
if (file != null)
{
if(files.ContainsKey(file.subjectData))
{
Lib.Log("discarding duplicate subject " + file.subjectData, Lib.LogLevel.Warning);
}
else
{
files.Add(file.subjectData, file);
file.subjectData.AddDataCollectedInFlight(file.size);
}
}
else
{
file = File.LoadOldFormat(subject_id, file_node);
if (file != null)
{
Lib.Log("Drive file load : converted '" + subject_id + "' to new format");
if(files.ContainsKey(file.subjectData))
{
Lib.Log("discarding duplicate converted subject " + file.subjectData, Lib.LogLevel.Warning);
}
else
{
files.Add(file.subjectData, file);
file.subjectData.AddDataCollectedInFlight(file.size);
}
}
}
}
}
// parse science samples
samples = new Dictionary<SubjectData, Sample>();
if (node.HasNode("samples"))
{
foreach (var sample_node in node.GetNode("samples").GetNodes())
{
string subject_id = DB.From_safe_key(sample_node.name);
Sample sample = Sample.Load(subject_id, sample_node);
if (sample != null)
{
samples.Add(sample.subjectData, sample);
sample.subjectData.AddDataCollectedInFlight(sample.size);
}
else
{
sample = Sample.LoadOldFormat(subject_id, sample_node);
if (sample != null)
{
Lib.Log("Drive sample load : converted '" + subject_id + "' to new format");
samples.Add(sample.subjectData, sample);
sample.subjectData.AddDataCollectedInFlight(sample.size);
}
}
}
}
name = Lib.ConfigValue(node, "name", "DRIVE");
is_private = Lib.ConfigValue(node, "is_private", false);
// parse capacities. be generous with default values for backwards
// compatibility (drives had unlimited storage before this)
dataCapacity = Lib.ConfigValue(node, "dataCapacity", 100000.0);
sampleCapacity = Lib.ConfigValue(node, "sampleCapacity", 1000);
fileSendFlags = new Dictionary<string, bool>();
string fileNames = Lib.ConfigValue(node, "sendFileNames", string.Empty);
foreach (string fileName in Lib.Tokenize(fileNames, ','))
{
Send(fileName, true);
}
}
public void Save(ConfigNode node)
{
// save science files
var files_node = node.AddNode("files");
foreach (File file in files.Values)
{
file.Save(files_node.AddNode(DB.To_safe_key(file.subjectData.Id)));
}
// save science samples
var samples_node = node.AddNode("samples");
foreach (Sample sample in samples.Values)
{
sample.Save(samples_node.AddNode(DB.To_safe_key(sample.subjectData.Id)));
}
node.AddValue("name", name);
node.AddValue("is_private", is_private);
node.AddValue("dataCapacity", dataCapacity);
node.AddValue("sampleCapacity", sampleCapacity);
string fileNames = string.Empty;
foreach (string subjectId in fileSendFlags.Keys)
{
if (fileNames.Length > 0) fileNames += ",";
fileNames += subjectId;
}
node.AddValue("sendFileNames", fileNames);
}
public static double StoreFile(Vessel vessel, SubjectData subjectData, double size, bool include_private = false)
{
if (size < double.Epsilon)
return 0;
// store what we can
var drives = GetDrives(vessel, include_private);
drives.Insert(0, Cache.WarpCache(vessel));
foreach (var d in drives)
{
var available = d.FileCapacityAvailable();
var chunk = Math.Min(size, available);
if (!d.Record_file(subjectData, chunk, true))
break;
size -= chunk;
if (size < double.Epsilon)
break;
}
return size;
}
// add science data, creating new file or incrementing existing one
public bool Record_file(SubjectData subjectData, double amount, bool allowImmediateTransmission = true, bool useStockCrediting = false)
{
if (dataCapacity >= 0 && FilesSize() + amount > dataCapacity)
return false;
// create new data or get existing one
File file;
if (!files.TryGetValue(subjectData, out file))
{
file = new File(subjectData, 0.0, useStockCrediting);
files.Add(subjectData, file);
if (!allowImmediateTransmission) Send(subjectData.Id, false);
}
// increase amount of data stored in the file
file.size += amount;
// keep track of data collected
subjectData.AddDataCollectedInFlight(amount);
return true;
}
public void Send(string subjectId, bool send)
{
if (!fileSendFlags.ContainsKey(subjectId)) fileSendFlags.Add(subjectId, send);
else fileSendFlags[subjectId] = send;
}
public bool GetFileSend(string subjectId)
{
if (!fileSendFlags.ContainsKey(subjectId)) return PreferencesScience.Instance.transmitScience;
return fileSendFlags[subjectId];
}
// add science sample, creating new sample or incrementing existing one
public bool Record_sample(SubjectData subjectData, double amount, double mass, bool useStockCrediting = false)
{
int currentSampleSlots = SamplesSize();
if (sampleCapacity >= 0)
{
if (!samples.ContainsKey(subjectData) && currentSampleSlots >= sampleCapacity)
{
// can't take a new sample if we're already at capacity
return false;
}
}
Sample sample;
if (samples.ContainsKey(subjectData) && sampleCapacity >= 0)
{
// test if adding the amount to the sample would exceed our capacity
sample = samples[subjectData];
int existingSampleSlots = Lib.SampleSizeToSlots(sample.size);
int newSampleSlots = Lib.SampleSizeToSlots(sample.size + amount);
if (currentSampleSlots - existingSampleSlots + newSampleSlots > sampleCapacity)
return false;
}
// create new data or get existing one
if (!samples.TryGetValue(subjectData, out sample))
{
sample = new Sample(subjectData, 0.0, useStockCrediting);
sample.analyze = PreferencesScience.Instance.analyzeSamples;
samples.Add(subjectData, sample);
}
// increase amount of data stored in the sample
sample.size += amount;
sample.mass += mass;
// keep track of data collected
subjectData.AddDataCollectedInFlight(amount);
return true;
}
// remove science data, deleting the file when it is empty
public void Delete_file(SubjectData subjectData, double amount = 0.0)
{
// get data
File file;
if (files.TryGetValue(subjectData, out file))
{
// decrease amount of data stored in the file
if (amount == 0.0)
amount = file.size;
else
amount = Math.Min(amount, file.size);
file.size -= amount;
// keep track of data collected
subjectData.RemoveDataCollectedInFlight(amount);
// remove file if empty
if (file.size <= 0.0) files.Remove(subjectData);
}
}
// remove science sample, deleting the sample when it is empty
public double Delete_sample(SubjectData subjectData, double amount = 0.0)
{
// get data
Sample sample;
if (samples.TryGetValue(subjectData, out sample))
{
// decrease amount of data stored in the sample
if (amount == 0.0)
amount = sample.size;
else
amount = Math.Min(amount, sample.size);
double massDelta = sample.mass * amount / sample.size;
sample.size -= amount;
sample.mass -= massDelta;
// keep track of data collected
subjectData.RemoveDataCollectedInFlight(amount);
// remove sample if empty
if (sample.size <= 0.0) samples.Remove(subjectData);
return massDelta;
}
return 0.0;
}
// set analyze flag for a sample
public void Analyze(SubjectData subjectData, bool b)
{
Sample sample;
if (samples.TryGetValue(subjectData, out sample))
{
sample.analyze = b;
}
}
// move all data to another drive
public bool Move(Drive destination, bool moveSamples)
{
bool result = true;
// copy files
List<SubjectData> filesList = new List<SubjectData>();
foreach (File file in files.Values)
{
double size = Math.Min(file.size, destination.FileCapacityAvailable());
if (destination.Record_file(file.subjectData, size, true, file.useStockCrediting))
{
file.size -= size;
file.subjectData.RemoveDataCollectedInFlight(size);
if (file.size < double.Epsilon)
{
filesList.Add(file.subjectData);
}
else
{
result = false;
break;
}
}
else
{
result = false;
break;
}
}
foreach (SubjectData id in filesList) files.Remove(id);
if (!moveSamples) return result;
// move samples
List<SubjectData> samplesList = new List<SubjectData>();
foreach (Sample sample in samples.Values)
{
double size = Math.Min(sample.size, destination.SampleCapacityAvailable(sample.subjectData));
if (size < double.Epsilon)
{
result = false;
break;
}
double mass = sample.mass * (sample.size / size);
if (destination.Record_sample(sample.subjectData, size, mass, sample.useStockCrediting))
{
sample.size -= size;
sample.subjectData.RemoveDataCollectedInFlight(size);
sample.mass -= mass;
if (sample.size < double.Epsilon)
{
samplesList.Add(sample.subjectData);
}
else
{
result = false;
break;
}
}
else
{
result = false;
break;
}
}
foreach (var id in samplesList) samples.Remove(id);
return result; // true if everything was moved, false otherwise
}
public double FileCapacityAvailable()
{
if (dataCapacity < 0) return double.MaxValue;
return Math.Max(dataCapacity - FilesSize(), 0.0); // clamp to 0 due to fp precision in FilesSize()
}
public double FilesSize()
{
double amount = 0.0;
foreach (var p in files)
{
amount += p.Value.size;
}
return amount;
}
public double SampleCapacityAvailable(SubjectData subject = null)
{
if (sampleCapacity < 0) return double.MaxValue;
double result = Lib.SlotsToSampleSize(sampleCapacity - SamplesSize());
if (subject != null && samples.ContainsKey(subject))
{
int slotsForMyFile = Lib.SampleSizeToSlots(samples[subject].size);
double amountLostToSlotting = Lib.SlotsToSampleSize(slotsForMyFile) - samples[subject].size;
result += amountLostToSlotting;
}
return result;
}
public int SamplesSize()
{
int amount = 0;
foreach (var p in samples)
{
amount += Lib.SampleSizeToSlots(p.Value.size);
}
return amount;
}
// return size of data stored in Mb (including samples)
public string Size()
{
var f = FilesSize();
var s = SamplesSize();
var result = f > double.Epsilon ? Lib.HumanReadableDataSize(f) : "";
if (result.Length > 0) result += " ";
if (s > 0) result += Lib.HumanReadableSampleSize(s);
return result;
}
public bool Empty()
{
return files.Count + samples.Count == 0;
}
// transfer data from a vessel to a drive
public static bool Transfer(Vessel src, Drive dst, bool samples)
{
double dataAmount = 0.0;
int sampleSlots = 0;
foreach (var drive in GetDrives(src, true))
{
dataAmount += drive.FilesSize();
sampleSlots += drive.SamplesSize();
}
if (dataAmount < double.Epsilon && (sampleSlots == 0 || !samples))
return true;
// get drives
var allSrc = GetDrives(src, true);
bool allMoved = true;
foreach (var a in allSrc)
{
if (a.Move(dst, samples))
{
allMoved = true;
break;
}
}
return allMoved;
}
// transfer data from a drive to a vessel
public static bool Transfer(Drive drive, Vessel dst, bool samples)
{
double dataAmount = drive.FilesSize();
int sampleSlots = drive.SamplesSize();
if (dataAmount < double.Epsilon && (sampleSlots == 0 || !samples))
return true;
// get drives
var allDst = GetDrives(dst);
bool allMoved = true;
foreach (var b in allDst)
{
if (drive.Move(b, samples))
{
allMoved = true;
break;
}
}
return allMoved;
}
// transfer data between two vessels
public static void Transfer(Vessel src, Vessel dst, bool samples)
{
double dataAmount = 0.0;
int sampleSlots = 0;
foreach (var drive in GetDrives(src, true))
{
dataAmount += drive.FilesSize();
sampleSlots += drive.SamplesSize();
}
if (dataAmount < double.Epsilon && (sampleSlots == 0 || !samples))
return;
var allSrc = GetDrives(src, true);
bool allMoved = false;
foreach (var a in allSrc)
{
if (Transfer(a, dst, samples))
{
allMoved = true;
break;
}
}
// inform the user
if (allMoved)
Message.Post
(
Lib.HumanReadableDataSize(dataAmount) + " " + Local.Science_ofdatatransfer,
Lib.BuildString(Local.Generic_FROM, " <b>", src.vesselName, "</b> ", Local.Generic_TO, " <b>", dst.vesselName, "</b>")
);
else
Message.Post
(
Lib.Color(Lib.BuildString("WARNING: not evering copied"), Lib.Kolor.Red, true),
Lib.BuildString(Local.Generic_FROM, " <b>", src.vesselName, "</b> ", Local.Generic_TO, " <b>", dst.vesselName, "</b>")
);
}
/// <summary> delete all files/samples in the drive</summary>
public void DeleteDriveData()
{
foreach (File file in files.Values)
file.subjectData.RemoveDataCollectedInFlight(file.size);
foreach (Sample sample in samples.Values)
sample.subjectData.RemoveDataCollectedInFlight(sample.size);
files.Clear();
samples.Clear();
}
/// <summary> delete all files/samples in the vessel drives</summary>
public static void DeleteDrivesData(Vessel vessel)
{
foreach (PartData partData in vessel.KerbalismData().PartDatas)
{
if (partData.Drive != null)
{
partData.Drive.DeleteDriveData();
}
}
}
public static List<Drive> GetDrives (VesselData vd, bool includePrivate = false)
{
UnityEngine.Profiling.Profiler.BeginSample("Kerbalism.Drive.GetDrives");
List<Drive> drives = new List<Drive>();
foreach (PartData partData in vd.PartDatas)
{
if (partData.Drive != null && (includePrivate || !partData.Drive.is_private))
{
drives.Add(partData.Drive);
}
}
UnityEngine.Profiling.Profiler.EndSample();
return drives;
}
public static List<Drive> GetDrives(Vessel v, bool includePrivate = false)
{
return GetDrives(v.KerbalismData(), includePrivate);
}
public static List<Drive> GetDrives(ProtoVessel pv, bool includePrivate = false)
{
return GetDrives(pv.KerbalismData(), includePrivate);
}
public static void GetCapacity(VesselData vesseldata, out double free_capacity, out double total_capacity)
{
free_capacity = 0;
total_capacity = 0;
if (Features.Science)
{
foreach (var drive in GetDrives(vesseldata))
{
if (drive.dataCapacity < 0 || free_capacity < 0)
{
free_capacity = -1;
}
else
{
free_capacity += drive.FileCapacityAvailable();
total_capacity += drive.dataCapacity;
}
}
if (free_capacity < 0)
{
free_capacity = double.MaxValue;
total_capacity = double.MaxValue;
}
}
}
/// <summary> Get a drive for storing files. Will return null if there are no drives on the vessel </summary>
public static Drive FileDrive(VesselData vesselData, double size = 0.0)
{
Drive result = null;
foreach (var drive in GetDrives(vesselData))
{
if (result == null)
{
result = drive;
if (size > 0.0 && result.FileCapacityAvailable() >= size)
return result;
continue;
}
if (size > 0.0 && drive.FileCapacityAvailable() >= size)
{
return drive;
}
// if we're not looking for a minimum capacity, look for the biggest drive
if (drive.dataCapacity > result.dataCapacity)
{
result = drive;
}
}
return result;
}
/// <summary> Get a drive for storing samples. Will return null if there are no drives on the vessel </summary>
public static Drive SampleDrive(VesselData vesselData, double size = 0, SubjectData subject = null)
{
Drive result = null;
foreach (var drive in GetDrives(vesselData))
{
if (result == null)
{
result = drive;
continue;
}
double available = drive.SampleCapacityAvailable(subject);
if (size > double.Epsilon && available < size)
continue;
if (available > result.SampleCapacityAvailable(subject))
result = drive;
}
return result;
}
public Dictionary<SubjectData, File> files; // science files
public Dictionary<SubjectData, Sample> samples; // science samples
public Dictionary<string, bool> fileSendFlags; // file send flags
public double dataCapacity;
public int sampleCapacity;
public string name = String.Empty;
public bool is_private = false;
}
} // KERBALISM
| |
namespace SuperSimple.Worker
{
using System;
using System.Data;
using System.Collections.Generic;
#if WINDOWS
public class RepositoryMonoSQLite
{
public RepositoryMonoSQLite (){
throw new NotImplementedException("Mono SQLite is not implemented for Windows.");
}
}
#else
using Mono.Data.Sqlite;
/// <summary>
/// Repository mono SQ lite.
/// </summary>
public class RepositoryMonoSQLite : IRepository
{
private string _connectionString;
/// <summary>
/// Gets or sets the connection string.
/// </summary>
/// <value>The connection string.</value>
public string ConnectionString
{
get
{
return _connectionString;
}
set
{
_connectionString = value;
}
}
/// <summary>
/// Initializes a new instance of the <see cref="DelayedJob.RepositoryMonoSQLite"/> class.
/// </summary>
public RepositoryMonoSQLite (){ }
/// <summary>
/// Initializes a new instance of the <see cref="DelayedJob.RepositoryMonoSQLite"/> class.
/// </summary>
/// <param name="connectionString">Connection string.</param>
public RepositoryMonoSQLite(string connectionString)
{
_connectionString = connectionString;
}
/// <summary>
/// Remove the specified job with ID.
/// </summary>
/// <param name="jobID">Job I.</param>
public void Remove(int jobID)
{
using(SqliteConnection dbcon = new SqliteConnection(_connectionString))
{
dbcon.Open();
SqliteCommand dbcmd = dbcon.CreateCommand();
string delete = "DELETE FROM ssw WHERE id = @JobID";
dbcmd.CommandText = delete;
dbcmd.Parameters.AddWithValue("@JobID", jobID);
dbcmd.ExecuteNonQuery();
dbcmd.Dispose();
dbcmd = null;
dbcon.Close();
}
}
/// <summary>
/// Gets the next ready jobs.
/// </summary>
/// <returns>.</returns>
/// <param name="limit">Limit is how many jobs will be returned</param>
public Job[] GetNextReadyJobs(int limit = 1)
{
List<Job> jobs = new List<Job>();
using(SqliteConnection dbcon = new SqliteConnection(_connectionString))
{
dbcon.Open();
SqliteCommand dbcmd = dbcon.CreateCommand();
string next = "select * from ssw where " +
"locked_by is null and " +
"run_at <= @time " +
"order by priority desc, run_at asc limit @limit";
dbcmd.CommandText = next;
dbcmd.Parameters.AddWithValue("@limit", limit);
dbcmd.Parameters.AddWithValue("@time", DateTime.Now);
Job job = new Job();
IDataReader reader = dbcmd.ExecuteReader();
while(reader.Read())
{
job = new Job();
job.Attempts = int.Parse(reader["attempts"].ToString());
job.ID = int.Parse(reader["id"].ToString());
if(reader["failed_at"].ToString() != "")
{
job.FailedAt = DateTime.Parse(reader["failed_at"].ToString());
}
job.ObjectType = reader["type"].ToString();
job.JobAssembly = reader["assembly"].ToString();
job.Handler = reader["handler"].ToString();
job.LastError = reader["last_error"].ToString();
if(reader["locked_at"].ToString() != "")
{
job.LockedAt = DateTime.Parse(reader["locked_at"].ToString());
}
job.LockedBy = reader["locked_by"].ToString();
job.Priority = int.Parse(reader["priority"].ToString());
job.RunAt = DateTime.Parse(reader["run_at"].ToString());
jobs.Add(job);
}
dbcmd.Dispose();
dbcmd = null;
dbcon.Close();
}
return jobs.ToArray();
}
/// <summary>
/// Updates the job.
/// </summary>
/// <param name="job">Job.</param>
public void UpdateJob(Job job)
{
using(SqliteConnection dbcon = new SqliteConnection(_connectionString))
{
dbcon.Open();
SqliteCommand dbcmd = dbcon.CreateCommand();
string update = "update ssw " +
"set " +
"priority = @priority," +
"attempts = @attempts," +
"last_error = @last_error," +
"run_at = @run_at," +
"failed_at = @failed_at," +
"locked_by = @locked_by, " +
"locked_at = @locked_at " +
"where ID = @ID";
dbcmd.CommandText = update;
dbcmd.Parameters.AddWithValue("@ID", job.ID);
dbcmd.Parameters.AddWithValue("@priority", job.Priority);
dbcmd.Parameters.AddWithValue("@attempts", job.Attempts);
dbcmd.Parameters.AddWithValue("@last_error", job.LastError);
dbcmd.Parameters.AddWithValue("@run_at", job.RunAt);
dbcmd.Parameters.AddWithValue("@failed_at", job.FailedAt);
dbcmd.Parameters.AddWithValue("@locked_by", job.LockedBy);
dbcmd.Parameters.AddWithValue("@locked_at", job.LockedAt);
dbcmd.ExecuteNonQuery();
dbcmd.Dispose();
dbcmd = null;
dbcon.Close();
}
}
/// <summary>
/// Clears the jobs.
/// </summary>
/// <param name="workerName">Worker name.</param>
public void ClearJobs(string workerName)
{
using(SqliteConnection dbcon = new SqliteConnection(_connectionString))
{
dbcon.Open();
SqliteCommand dbcmd = dbcon.CreateCommand();
string update = "update ssw " +
"set locked_by = null, " +
"locked_at = null " +
"where locked_by = @WorkerName";
dbcmd.CommandText = update;
dbcmd.Parameters.AddWithValue("@WorkerName", workerName);
dbcmd.ExecuteNonQuery();
dbcmd.Dispose();
dbcmd = null;
dbcon.Close();
}
}
/// <summary>
/// Pass a job object and that object will be created in the database.
/// </summary>
/// <returns>After creation of the object it will return the object with its ID</returns>
/// <param name="job">Job.</param>
public Job CreateJob(Job job)
{
using(SqliteConnection dbcon = new SqliteConnection(_connectionString))
{
dbcon.Open();
SqliteCommand dbcmd = dbcon.CreateCommand();
string insertRecord = "insert into ssw (" +
"type," +
"assembly," +
"priority," +
"attempts," +
"handler," +
"last_error," +
"run_at," +
"locked_at," +
"failed_at," +
"locked_by" +
") values (" +
"@type," +
"@assembly," +
"@priority," +
"@attempts," +
"@handler," +
"@last_error," +
"@run_at," +
"@locked_at," +
"@failed_at," +
"@locked_by" +
");select last_insert_rowid();";
dbcmd.CommandText = insertRecord;
dbcmd.Parameters.AddWithValue("@type",job.ObjectType);
dbcmd.Parameters.AddWithValue("@assembly",job.JobAssembly);
dbcmd.Parameters.AddWithValue("@priority",job.Priority);
dbcmd.Parameters.AddWithValue("@attempts",job.Attempts);
dbcmd.Parameters.AddWithValue("@handler", job.Handler);
dbcmd.Parameters.AddWithValue("@last_error",job.LastError);
dbcmd.Parameters.AddWithValue("@run_at",job.RunAt);
dbcmd.Parameters.AddWithValue("@locked_at", job.LockedAt);
dbcmd.Parameters.AddWithValue("@failed_at", job.FailedAt);
dbcmd.Parameters.AddWithValue("@locked_by", job.LockedBy);
var id = dbcmd.ExecuteScalar();
job.ID = int.Parse(id.ToString());
dbcmd.Dispose();
dbcmd = null;
dbcon.Close();
}
return job;
}
/// <summary>
/// Gets a job with the specified id.
/// </summary>
/// <returns>A job object with that has the id provided.</returns>
/// <param name="pid">Pid.</param>
public Job GetJob(int pid)
{
Job job = new Job();
using(SqliteConnection dbcon = new SqliteConnection(_connectionString))
{
dbcon.Open();
SqliteCommand dbcmd = dbcon.CreateCommand();
string query = "select * from ssw where id = @pid";
dbcmd.CommandText = query;
dbcmd.Parameters.AddWithValue("@pid",pid);
IDataReader reader = dbcmd.ExecuteReader();
while(reader.Read())
{
job.Attempts = int.Parse(reader["attempts"].ToString());
job.ID = int.Parse(reader["id"].ToString());
job.ObjectType = reader["type"].ToString();
job.JobAssembly = reader["assembly"].ToString();
if(reader["failed_at"].ToString() != "")
{
job.FailedAt = DateTime.Parse(reader["failed_at"].ToString());
}
job.Handler = reader["handler"].ToString();
job.LastError = reader["last_error"].ToString();
if(reader["failed_at"].ToString() != "")
{
job.LockedAt = DateTime.Parse(reader["locked_at"].ToString());
}
job.LockedBy = reader["locked_by"].ToString();
job.Priority = int.Parse(reader["priority"].ToString());
job.RunAt = DateTime.Parse(reader["run_at"].ToString());
}
}
return job;
}
/// <summary>
/// This will get all jobs.
/// </summary>
/// <returns>an array of job objects</returns>
public Job[] GetJobs(){
List<Job> jobs = new List<Job>();
using(SqliteConnection dbcon = new SqliteConnection(_connectionString))
{
dbcon.Open();
SqliteCommand dbcmd = dbcon.CreateCommand();
string query = "select * from ssw";
dbcmd.CommandText = query;
IDataReader reader = dbcmd.ExecuteReader();
Job job = new Job();
while(reader.Read())
{
job = new Job();
job.ObjectType = reader["type"].ToString();
job.JobAssembly = reader["assembly"].ToString();
job.Attempts = int.Parse(reader["attempts"].ToString());
job.ID = int.Parse(reader["id"].ToString());
if (reader ["failed_at"].ToString () != "")
{
job.FailedAt = DateTime.Parse (reader["failed_at"].ToString());
}
job.Handler = reader["handler"].ToString();
job.LastError = reader["last_error"].ToString();
if (reader ["locked_at"].ToString () != "")
{
job.LockedAt = DateTime.Parse (reader["locked_at"].ToString());
}
job.LockedBy = reader["locked_by"].ToString();
job.Priority = int.Parse(reader["priority"].ToString());
job.RunAt = DateTime.Parse(reader["run_at"].ToString());
jobs.Add(job);
}
}
return jobs.ToArray();
}
}
#endif
}
| |
#region Apache Notice
/*****************************************************************************
* $Revision: 663728 $
* $LastChangedDate: 2008-06-05 14:40:05 -0600 (Thu, 05 Jun 2008) $
* $LastChangedBy: gbayon $
*
* iBATIS.NET Data Mapper
* Copyright (C) 2006/2005 - The Apache Software Foundation
*
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
********************************************************************************/
#endregion
#region Remarks
// Inpspired from Spring.NET
#endregion
#region Using
using System;
#if dotnet2
using System.Collections.Generic;
#endif
using System.Reflection;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
#endregion
namespace IBatisNet.Common.Utilities.TypesResolver
{
/// <summary>
/// Resolves a <see cref="System.Type"/> by name.
/// </summary>
/// <remarks>
/// <p>
/// The rationale behind the creation of this class is to centralise the
/// resolution of type names to <see cref="System.Type"/> instances beyond that
/// offered by the plain vanilla System.Type.GetType method call.
/// </p>
/// </remarks>
/// <version>$Id: TypeResolver.cs,v 1.5 2004/09/28 07:51:47 springboy Exp $</version>
public class TypeResolver : ITypeResolver
{
private const string NULLABLE_TYPE = "System.Nullable";
#region ITypeResolver Members
/// <summary>
/// Resolves the supplied <paramref name="typeName"/> to a
/// <see cref="System.Type"/> instance.
/// </summary>
/// <param name="typeName">
/// The unresolved name of a <see cref="System.Type"/>.
/// </param>
/// <returns>
/// A resolved <see cref="System.Type"/> instance.
/// </returns>
/// <exception cref="System.TypeLoadException">
/// If the supplied <paramref name="typeName"/> could not be resolved
/// to a <see cref="System.Type"/>.
/// </exception>
public virtual Type Resolve(string typeName)
{
#if dotnet2
Type type = ResolveGenericType(typeName.Replace(" ", string.Empty));
if (type == null)
{
type = ResolveType(typeName.Replace(" ", string.Empty));
}
return type;
#else
return ResolveType(typeName.Replace(" ", string.Empty));
#endif
}
#endregion
#if dotnet2
/// <summary>
/// Resolves the supplied generic <paramref name="typeName"/>,
/// substituting recursively all its type parameters.,
/// to a <see cref="System.Type"/> instance.
/// </summary>
/// <param name="typeName">
/// The (possibly generic) name of a <see cref="System.Type"/>.
/// </param>
/// <returns>
/// A resolved <see cref="System.Type"/> instance.
/// </returns>
/// <exception cref="System.TypeLoadException">
/// If the supplied <paramref name="typeName"/> could not be resolved
/// to a <see cref="System.Type"/>.
/// </exception>
private Type ResolveGenericType(string typeName)
{
#region Sanity Check
if (typeName == null || typeName.Trim().Length==0)
{
throw BuildTypeLoadException(typeName);
}
#endregion
if (typeName.StartsWith(NULLABLE_TYPE))
{
return null;
}
else
{
GenericArgumentsInfo genericInfo = new GenericArgumentsInfo(typeName);
Type type = null;
try
{
if (genericInfo.ContainsGenericArguments)
{
type = TypeUtils.ResolveType(genericInfo.GenericTypeName);
if (!genericInfo.IsGenericDefinition)
{
string[] unresolvedGenericArgs = genericInfo.GetGenericArguments();
Type[] genericArgs = new Type[unresolvedGenericArgs.Length];
for (int i = 0; i < unresolvedGenericArgs.Length; i++)
{
genericArgs[i] = TypeUtils.ResolveType(unresolvedGenericArgs[i]);
}
type = type.MakeGenericType(genericArgs);
}
}
}
catch (Exception ex)
{
if (ex is TypeLoadException)
{
throw;
}
throw BuildTypeLoadException(typeName, ex);
}
return type;
}
}
#endif
/// <summary>
/// Resolves the supplied <paramref name="typeName"/> to a
/// <see cref="System.Type"/>
/// instance.
/// </summary>
/// <param name="typeName">
/// The (possibly partially assembly qualified) name of a
/// <see cref="System.Type"/>.
/// </param>
/// <returns>
/// A resolved <see cref="System.Type"/> instance.
/// </returns>
/// <exception cref="System.TypeLoadException">
/// If the supplied <paramref name="typeName"/> could not be resolved
/// to a <see cref="System.Type"/>.
/// </exception>
private Type ResolveType(string typeName)
{
#region Sanity Check
if (typeName == null || typeName.Trim().Length == 0)
{
throw BuildTypeLoadException(typeName);
}
#endregion
TypeAssemblyInfo typeInfo = new TypeAssemblyInfo(typeName);
Type type = null;
try
{
type = (typeInfo.IsAssemblyQualified) ?
LoadTypeDirectlyFromAssembly(typeInfo) :
LoadTypeByIteratingOverAllLoadedAssemblies(typeInfo);
}
catch (Exception ex)
{
throw BuildTypeLoadException(typeName, ex);
}
if (type == null)
{
throw BuildTypeLoadException(typeName);
}
return type;
}
/// <summary>
/// Uses <see cref="System.Reflection.Assembly.LoadWithPartialName(string)"/>
/// to load an <see cref="System.Reflection.Assembly"/> and then the attendant
/// <see cref="System.Type"/> referred to by the <paramref name="typeInfo"/>
/// parameter.
/// </summary>
/// <remarks>
/// <p>
/// <see cref="System.Reflection.Assembly.LoadWithPartialName(string)"/> is
/// deprecated in .NET 2.0, but is still used here (even when this class is
/// compiled for .NET 2.0);
/// <see cref="System.Reflection.Assembly.LoadWithPartialName(string)"/> will
/// still resolve (non-.NET Framework) local assemblies when given only the
/// display name of an assembly (the behaviour for .NET Framework assemblies
/// and strongly named assemblies is documented in the docs for the
/// <see cref="System.Reflection.Assembly.LoadWithPartialName(string)"/> method).
/// </p>
/// </remarks>
/// <param name="typeInfo">
/// The assembly and type to be loaded.
/// </param>
/// <returns>
/// A <see cref="System.Type"/>, or <see lang="null"/>.
/// </returns>
/// <exception cref="System.Exception">
/// <see cref="System.Reflection.Assembly.LoadWithPartialName(string)"/>
/// </exception>
private static Type LoadTypeDirectlyFromAssembly(TypeAssemblyInfo typeInfo)
{
Type type = null;
// assembly qualified... load the assembly, then the Type
Assembly assembly = null;
#if dotnet2
assembly = Assembly.Load(typeInfo.AssemblyName);
#else
assembly = Assembly.LoadWithPartialName (typeInfo.AssemblyName);
#endif
if (assembly != null)
{
type = assembly.GetType(typeInfo.TypeName, true, true);
}
return type;
}
/// <summary>
/// Check all assembly
/// to load the attendant <see cref="System.Type"/> referred to by
/// the <paramref name="typeInfo"/> parameter.
/// </summary>
/// <param name="typeInfo">
/// The type to be loaded.
/// </param>
/// <returns>
/// A <see cref="System.Type"/>, or <see lang="null"/>.
/// </returns>
private static Type LoadTypeByIteratingOverAllLoadedAssemblies(TypeAssemblyInfo typeInfo)
{
Type type = null;
Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies();
foreach (Assembly assembly in assemblies)
{
type = assembly.GetType(typeInfo.TypeName, false, false);
if (type != null)
{
break;
}
}
return type;
}
private static TypeLoadException BuildTypeLoadException(string typeName)
{
return new TypeLoadException("Could not load type from string value '" + typeName + "'.");
}
private static TypeLoadException BuildTypeLoadException(string typeName, Exception ex)
{
return new TypeLoadException("Could not load type from string value '" + typeName + "'.", ex);
}
#if dotnet2
#region Inner Class : GenericArgumentsInfo
/// <summary>
/// Holder for the generic arguments when using type parameters.
/// </summary>
/// <remarks>
/// <p>
/// Type parameters can be applied to classes, interfaces,
/// structures, methods, delegates, etc...
/// </p>
/// </remarks>
internal class GenericArgumentsInfo
{
#region Constants
/// <summary>
/// The generic arguments prefix.
/// </summary>
public const string GENERIC_ARGUMENTS_PREFIX = "[[";
/// <summary>
/// The generic arguments suffix.
/// </summary>
public const string GENERIC_ARGUMENTS_SUFFIX = "]]";
/// <summary>
/// The character that separates a list of generic arguments.
/// </summary>
public const string GENERIC_ARGUMENTS_SEPARATOR = "],[";
#endregion
#region Fields
private string _unresolvedGenericTypeName = string.Empty;
private string[] _unresolvedGenericArguments = null;
private readonly static Regex generic = new Regex(@"`\d*\[\[", RegexOptions.Compiled);
#endregion
#region Constructor (s) / Destructor
/// <summary>
/// Creates a new instance of the GenericArgumentsInfo class.
/// </summary>
/// <param name="value">
/// The string value to parse looking for a generic definition
/// and retrieving its generic arguments.
/// </param>
public GenericArgumentsInfo(string value)
{
ParseGenericArguments(value);
}
#endregion
#region Properties
/// <summary>
/// The (unresolved) generic type name portion
/// of the original value when parsing a generic type.
/// </summary>
public string GenericTypeName
{
get { return _unresolvedGenericTypeName; }
}
/// <summary>
/// Is the string value contains generic arguments ?
/// </summary>
/// <remarks>
/// <p>
/// A generic argument can be a type parameter or a type argument.
/// </p>
/// </remarks>
public bool ContainsGenericArguments
{
get
{
return (_unresolvedGenericArguments != null &&
_unresolvedGenericArguments.Length > 0);
}
}
/// <summary>
/// Is generic arguments only contains type parameters ?
/// </summary>
public bool IsGenericDefinition
{
get
{
if (_unresolvedGenericArguments == null)
return false;
foreach (string arg in _unresolvedGenericArguments)
{
if (arg.Length > 0)
return false;
}
return true;
}
}
#endregion
#region Methods
/// <summary>
/// Returns an array of unresolved generic arguments types.
/// </summary>
/// <remarks>
/// <p>
/// A empty string represents a type parameter that
/// did not have been substituted by a specific type.
/// </p>
/// </remarks>
/// <returns>
/// An array of strings that represents the unresolved generic
/// arguments types or an empty array if not generic.
/// </returns>
public string[] GetGenericArguments()
{
if (_unresolvedGenericArguments == null)
{
return new string[] { };
}
return _unresolvedGenericArguments;
}
private void ParseGenericArguments(string originalString)
{
// Check for match
bool isMatch = generic.IsMatch(originalString);
if (!isMatch)
{
_unresolvedGenericTypeName = originalString;
}
else
{
int argsStartIndex = originalString.IndexOf(GENERIC_ARGUMENTS_PREFIX);
int argsEndIndex = originalString.LastIndexOf(GENERIC_ARGUMENTS_SUFFIX);
if (argsEndIndex != -1)
{
SplitGenericArguments(originalString.Substring(
argsStartIndex + 1, argsEndIndex - argsStartIndex));
_unresolvedGenericTypeName = originalString.Remove(argsStartIndex, argsEndIndex - argsStartIndex + 2);
}
}
}
private void SplitGenericArguments(string originalArgs)
{
IList<string> arguments = new List<string>();
if (originalArgs.Contains(GENERIC_ARGUMENTS_SEPARATOR))
{
arguments = Parse(originalArgs);
}
else
{
string argument = originalArgs.Substring(1, originalArgs.Length - 2).Trim();
arguments.Add(argument);
}
_unresolvedGenericArguments = new string[arguments.Count];
arguments.CopyTo(_unresolvedGenericArguments, 0);
}
private IList<string> Parse(string args)
{
StringBuilder argument = new StringBuilder();
IList<string> arguments = new List<string>();
TextReader input = new StringReader(args);
int nbrOfRightDelimiter = 0;
bool findRight = false;
do
{
char ch = (char)input.Read();
if (ch == '[')
{
nbrOfRightDelimiter++;
findRight = true;
}
else if (ch == ']')
{
nbrOfRightDelimiter--;
}
argument.Append(ch);
//Find one argument
if (findRight && nbrOfRightDelimiter == 0)
{
string arg = argument.ToString();
arg = arg.Substring(1, arg.Length - 2);
arguments.Add(arg);
input.Read();
argument = new StringBuilder();
}
}
while (input.Peek() != -1);
return arguments;
}
#endregion
}
#endregion
#endif
#region Inner Class : TypeAssemblyInfo
/// <summary>
/// Holds data about a <see cref="System.Type"/> and it's
/// attendant <see cref="System.Reflection.Assembly"/>.
/// </summary>
internal class TypeAssemblyInfo
{
#region Constants
/// <summary>
/// The string that separates a <see cref="System.Type"/> name
/// from the name of it's attendant <see cref="System.Reflection.Assembly"/>
/// in an assembly qualified type name.
/// </summary>
public const string TYPE_ASSEMBLY_SEPARATOR = ",";
public const string NULLABLE_TYPE = "System.Nullable";
public const string NULLABLE_TYPE_ASSEMBLY_SEPARATOR = "]],";
#endregion
#region Fields
private string _unresolvedAssemblyName = string.Empty;
private string _unresolvedTypeName = string.Empty;
#endregion
#region Constructor (s) / Destructor
/// <summary>
/// Creates a new instance of the TypeAssemblyInfo class.
/// </summary>
/// <param name="unresolvedTypeName">
/// The unresolved name of a <see cref="System.Type"/>.
/// </param>
public TypeAssemblyInfo(string unresolvedTypeName)
{
SplitTypeAndAssemblyNames(unresolvedTypeName);
}
#endregion
#region Properties
/// <summary>
/// The (unresolved) type name portion of the original type name.
/// </summary>
public string TypeName
{
get { return _unresolvedTypeName; }
}
/// <summary>
/// The (unresolved, possibly partial) name of the attandant assembly.
/// </summary>
public string AssemblyName
{
get { return _unresolvedAssemblyName; }
}
/// <summary>
/// Is the type name being resolved assembly qualified?
/// </summary>
public bool IsAssemblyQualified
{
get { return HasText(AssemblyName); }
}
#endregion
#region Methods
private bool HasText(string target)
{
if (target == null)
{
return false;
}
else
{
return HasLength(target.Trim());
}
}
private bool HasLength(string target)
{
return (target != null && target.Length > 0);
}
private void SplitTypeAndAssemblyNames(string originalTypeName)
{
if (originalTypeName.StartsWith(NULLABLE_TYPE))
{
int typeAssemblyIndex = originalTypeName.IndexOf(NULLABLE_TYPE_ASSEMBLY_SEPARATOR);
if (typeAssemblyIndex < 0)
{
_unresolvedTypeName = originalTypeName;
}
else
{
_unresolvedTypeName = originalTypeName.Substring(0, typeAssemblyIndex + 2).Trim();
_unresolvedAssemblyName = originalTypeName.Substring(typeAssemblyIndex + 3).Trim();
}
}
else
{
int typeAssemblyIndex = originalTypeName.IndexOf(TYPE_ASSEMBLY_SEPARATOR);
if (typeAssemblyIndex < 0)
{
_unresolvedTypeName = originalTypeName;
}
else
{
_unresolvedTypeName = originalTypeName.Substring(0, typeAssemblyIndex).Trim();
_unresolvedAssemblyName = originalTypeName.Substring(typeAssemblyIndex + 1).Trim();
}
}
}
#endregion
}
#endregion
}
}
| |
/***************************************************************************
* AsyncGroupStatusManager.cs
*
* Copyright (C) 2007 Michael C. Urbanski
* Written by Mike Urbanski <michael.c.urbanski@gmail.com>
****************************************************************************/
/* THIS FILE IS LICENSED UNDER THE MIT LICENSE AS OUTLINED IMMEDIATELY BELOW:
*
* 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.Threading;
namespace Migo.TaskCore
{
public class GroupStatusManager : IDisposable
{
private bool disposed;
private bool suspendUpdate;
private int runningTasks;
private int completedTasks;
private int remainingTasks;
private int maxRunningTasks = 0;
private ManualResetEvent mre;
public event EventHandler<GroupStatusChangedEventArgs> StatusChanged;
public virtual int CompletedTasks
{
get {
CheckDisposed ();
return completedTasks;
}
}
public virtual int RunningTasks
{
get {
CheckDisposed ();
return runningTasks;
}
}
public virtual bool SuspendUpdate
{
get {
CheckDisposed ();
return suspendUpdate;
}
set {
CheckDisposed ();
suspendUpdate = value;
}
}
public virtual int RemainingTasks
{
get {
CheckDisposed ();
return remainingTasks;
}
set {
CheckDisposed ();
SetRemainingTasks (value);
}
}
public virtual int MaxRunningTasks
{
get {
CheckDisposed ();
return maxRunningTasks;
}
set {
CheckDisposed ();
SetMaxRunningTasks (value);
}
}
public virtual WaitHandle Handle {
get {
CheckDisposed ();
return mre;
}
}
public GroupStatusManager () : this (0, 0) {}
public GroupStatusManager (int totalTasks) : this (totalTasks, 0) {}
public GroupStatusManager (int maxRunningTasks, int totalTasks)
{
mre = new ManualResetEvent (false);
SetRemainingTasks (totalTasks);
SetMaxRunningTasks (maxRunningTasks);
}
public virtual void Dispose ()
{
if (!disposed) {
disposed = true;
if (mre != null) {
mre.Close ();
mre = null;
}
}
}
public virtual int IncrementCompletedTaskCount ()
{
CheckDisposed ();
++completedTasks;
OnStatusChanged ();
return completedTasks;
}
public virtual int DecrementCompletedTaskCount ()
{
CheckDisposed ();
if (completedTasks == 0) {
throw new InvalidOperationException (
"Completed task count cannot be less than 0"
);
}
--completedTasks;
OnStatusChanged ();
return completedTasks;
}
public virtual int IncrementRunningTaskCount ()
{
CheckDisposed ();
if (runningTasks >= remainingTasks) {
throw new InvalidOperationException (
"Running task count cannot be > remaining task count"
);
}
++runningTasks;
OnStatusChanged ();
Evaluate ();
return runningTasks;
}
public virtual int DecrementRunningTaskCount ()
{
CheckDisposed ();
if (runningTasks == 0) {
throw new InvalidOperationException (
"Runing task count cannot be less than 0"
);
}
--runningTasks;
OnStatusChanged ();
Evaluate ();
return runningTasks;
}
public virtual int IncrementRemainingTaskCount ()
{
CheckDisposed ();
SetRemainingTasks (remainingTasks + 1);
Evaluate ();
return remainingTasks;
}
public virtual int DecrementRemainingTaskCount ()
{
CheckDisposed ();
if (remainingTasks == 0) {
throw new InvalidOperationException (
"Remaining task count cannot be less than 0"
);
}
SetRemainingTasks (remainingTasks - 1);
Evaluate ();
return remainingTasks;
}
public virtual void ResetWait ()
{
CheckDisposed ();
mre.Reset ();
}
public virtual void Reset ()
{
completedTasks = 0;
suspendUpdate = false;
}
public virtual bool SetRemainingTasks (int newRemainingTasks)
{
CheckDisposed ();
if (newRemainingTasks < 0) {
throw new ArgumentException ("newRemainingTasks must be >= 0");
}
bool ret = false;
if (remainingTasks != newRemainingTasks) {
ret = true;
remainingTasks = newRemainingTasks;
OnStatusChanged ();
Evaluate ();
}
return ret;
}
public virtual void Update ()
{
CheckDisposed ();
OnStatusChanged ();
Evaluate ();
}
public virtual void Wait ()
{
CheckDisposed ();
mre.WaitOne ();
}
protected virtual void CheckDisposed ()
{
if (disposed) {
throw new ObjectDisposedException (GetType ().FullName);
}
}
public virtual void Evaluate ()
{
if (suspendUpdate) {
return;
}
if ((remainingTasks == 0 && maxRunningTasks > 0) ||
(runningTasks < maxRunningTasks &&
(remainingTasks - runningTasks) > 0)) {
mre.Set ();
}
}
protected virtual void SetMaxRunningTasks (int newMaxTasks)
{
CheckDisposed ();
if (newMaxTasks < 0) {
throw new ArgumentException ("newMaxTasks must be >= 0");
}
if (maxRunningTasks != newMaxTasks) {
maxRunningTasks = newMaxTasks;
Evaluate ();
}
}
protected virtual void OnStatusChanged (GroupStatusChangedEventArgs e)
{
if (suspendUpdate) {
return;
}
EventHandler<GroupStatusChangedEventArgs> handler = StatusChanged;
if (handler != null) {
handler (this, e);
}
}
protected virtual void OnStatusChanged ()
{
if (suspendUpdate) {
return;
}
OnStatusChanged (
new GroupStatusChangedEventArgs (
remainingTasks, runningTasks, completedTasks
)
);
}
}
}
| |
/********************************************************************++
Copyright (c) Microsoft Corporation. All rights reserved.
--********************************************************************/
using System.IO;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Management.Automation.Internal;
using System.Management.Automation.Language;
using System.Reflection;
using PipelineResultTypes = System.Management.Automation.Runspaces.PipelineResultTypes;
namespace System.Management.Automation
{
#region Auxiliary
/// <summary>
/// An interface that a
/// <see cref="Cmdlet"/> or <see cref="Provider.CmdletProvider"/>
/// must implement to indicate that it has dynamic parameters.
/// </summary>
/// <remarks>
/// Dynamic parameters allow a
/// <see cref="Cmdlet"/> or <see cref="Provider.CmdletProvider"/>
/// to define additional parameters based on the value of
/// the formal arguments. For example, the parameters of
/// "set-itemproperty" for the file system provider vary
/// depending on whether the target object is a file or directory.
/// </remarks>
/// <seealso cref="Cmdlet"/>
/// <seealso cref="PSCmdlet"/>
/// <seealso cref="RuntimeDefinedParameter"/>
/// <seealso cref="RuntimeDefinedParameterDictionary"/>
public interface IDynamicParameters
{
/// <summary>
/// Returns an instance of an object that defines the
/// dynamic parameters for this
/// <see cref="Cmdlet"/> or <see cref="Provider.CmdletProvider"/>.
/// </summary>
/// <returns>
/// This method should return an object that has properties and fields
/// decorated with parameter attributes similar to a
/// <see cref="Cmdlet"/> or <see cref="Provider.CmdletProvider"/>.
/// These attributes include <see cref="ParameterAttribute"/>,
/// <see cref="AliasAttribute"/>, argument transformation and
/// validation attributes, etc.
///
/// Alternately, it can return a
/// <see cref="System.Management.Automation.RuntimeDefinedParameterDictionary"/>
/// instead.
///
/// The <see cref="Cmdlet"/> or <see cref="Provider.CmdletProvider"/>
/// should hold on to a reference to the object which it returns from
/// this method, since the argument values for the dynamic parameters
/// specified by that object will be set in that object.
///
/// This method will be called after all formal (command-line)
/// parameters are set, but before <see cref="Cmdlet.BeginProcessing"/>
/// is called and before any incoming pipeline objects are read.
/// Therefore, parameters which allow input from the pipeline
/// may not be set at the time this method is called,
/// even if the parameters are mandatory.
/// </returns>
object GetDynamicParameters();
}
/// <summary>
/// Type used to define a parameter on a cmdlet script of function that
/// can only be used as a switch.
/// </summary>
public struct SwitchParameter
{
private bool _isPresent;
/// <summary>
/// Returns true if the parameter was specified on the command line, false otherwise.
/// </summary>
/// <value>True if the parameter was specified, false otherwise</value>
public bool IsPresent
{
get { return _isPresent; }
}
/// <summary>
/// Implicit cast operator for casting SwitchParameter to bool.
/// </summary>
/// <param name="switchParameter">The SwitchParameter object to convert to bool</param>
/// <returns>The corresponding boolean value.</returns>
public static implicit operator bool (SwitchParameter switchParameter)
{
return switchParameter.IsPresent;
}
/// <summary>
/// Implicit cast operator for casting bool to SwitchParameter.
/// </summary>
/// <param name="value">The bool to convert to SwitchParameter</param>
/// <returns>The corresponding boolean value.</returns>
public static implicit operator SwitchParameter(bool value)
{
return new SwitchParameter(value);
}
/// <summary>
/// Explicit method to convert a SwitchParameter to a boolean value.
/// </summary>
/// <returns>The boolean equivalent of the SwitchParameter</returns>
public bool ToBool()
{
return _isPresent;
}
/// <summary>
/// Construct a SwitchParameter instance with a particular value.
/// </summary>
/// <param name="isPresent">
/// If true, it indicates that the switch is present, flase otherwise.
/// </param>
public SwitchParameter(bool isPresent)
{
_isPresent = isPresent;
}
/// <summary>
/// Static method that returns a instance of SwitchParameter that indicates that it is present.
/// </summary>
/// <value>An instance of a switch parameter that will convert to true in a boolean context</value>
public static SwitchParameter Present
{
get { return new SwitchParameter(true); }
}
/// <summary>
/// Compare this switch parameter to another object.
/// </summary>
/// <param name="obj">An object to compare against</param>
/// <returns>True if the objects are the same value.</returns>
public override bool Equals(object obj)
{
if (obj is bool)
{
return _isPresent == (bool)obj;
}
else if (obj is SwitchParameter)
{
return _isPresent == ((SwitchParameter)obj).IsPresent;
}
else
{
return false;
}
}
/// <summary>
/// Returns the hash code for this switch parameter.
/// </summary>
/// <returns>The hash code for this cobject.</returns>
public override int GetHashCode()
{
return _isPresent.GetHashCode();
}
/// <summary>
/// Implement the == operator for switch parameters objects.
/// </summary>
/// <param name="first">first object to compare</param>
/// <param name="second">second object to compare</param>
/// <returns>True if they are the same</returns>
public static bool operator ==(SwitchParameter first, SwitchParameter second)
{
return first.Equals(second);
}
/// <summary>
/// Implement the != operator for switch parameters
/// </summary>
/// <param name="first">first object to compare</param>
/// <param name="second">second object to compare</param>
/// <returns>True if they are different</returns>
public static bool operator !=(SwitchParameter first, SwitchParameter second)
{
return !first.Equals(second);
}
/// <summary>
/// Implement the == operator for switch parameters and booleans.
/// </summary>
/// <param name="first">first object to compare</param>
/// <param name="second">second object to compare</param>
/// <returns>True if they are the same</returns>
public static bool operator ==(SwitchParameter first, bool second)
{
return first.Equals(second);
}
/// <summary>
/// Implement the != operator for switch parameters and booleans.
/// </summary>
/// <param name="first">first object to compare</param>
/// <param name="second">second object to compare</param>
/// <returns>True if they are different</returns>
public static bool operator !=(SwitchParameter first, bool second)
{
return !first.Equals(second);
}
/// <summary>
/// Implement the == operator for bool and switch parameters
/// </summary>
/// <param name="first">first object to compare</param>
/// <param name="second">second object to compare</param>
/// <returns>True if they are the same</returns>
public static bool operator ==(bool first, SwitchParameter second)
{
return first.Equals(second);
}
/// <summary>
/// Implement the != operator for bool and switch parameters
/// </summary>
/// <param name="first">first object to compare</param>
/// <param name="second">second object to compare</param>
/// <returns>True if they are different</returns>
public static bool operator !=(bool first, SwitchParameter second)
{
return !first.Equals(second);
}
/// <summary>
/// Returns the string representation for this object
/// </summary>
/// <returns>The string for this object.</returns>
public override string ToString()
{
return _isPresent.ToString();
}
}
/// <summary>
/// Interfaces that cmdlets can use to build script blocks and execute scripts.
/// </summary>
public class CommandInvocationIntrinsics
{
private ExecutionContext _context;
private PSCmdlet _cmdlet;
private MshCommandRuntime _commandRuntime;
internal CommandInvocationIntrinsics(ExecutionContext context, PSCmdlet cmdlet)
{
_context = context;
if (cmdlet != null)
{
_cmdlet = cmdlet;
_commandRuntime = cmdlet.CommandRuntime as MshCommandRuntime;
}
}
internal CommandInvocationIntrinsics(ExecutionContext context)
: this(context, null)
{
}
/// <summary>
/// If an error occurred while executing the cmdlet, this will be set to true.
/// </summary>
public bool HasErrors
{
get
{
return _commandRuntime.PipelineProcessor.ExecutionFailed;
}
set
{
_commandRuntime.PipelineProcessor.ExecutionFailed = value;
}
}
/// <summary>
/// Returns a string with all of the variable and expression substitutions done.
/// </summary>
/// <param name="source">The string to expand.
/// </param>
/// <returns>The expanded string.</returns>
/// <exception cref="ParseException">
/// Thrown if a parse exception occurred during subexpression substitution.
/// </exception>
public string ExpandString(string source)
{
if (null != _cmdlet)
_cmdlet.ThrowIfStopping();
return _context.Engine.Expand(source);
}
/// <summary>
///
/// </summary>
/// <param name="commandName"></param>
/// <param name="type"></param>
/// <returns></returns>
public CommandInfo GetCommand(string commandName, CommandTypes type)
{
return GetCommand(commandName, type, null);
}
/// <summary>
/// Returns a command info for a given command name and type, using the specified arguments
/// to resolve dynamic parameters.
/// </summary>
/// <param name="commandName">The command name to search for</param>
/// <param name="type">The command type to search for</param>
/// <param name="arguments">The command arguments used to resolve dynamic parameters</param>
/// <returns>A CommandInfo result that represents the resolved command</returns>
public CommandInfo GetCommand(string commandName, CommandTypes type, object[] arguments)
{
CommandInfo result = null;
try
{
CommandOrigin commandOrigin = CommandOrigin.Runspace;
if (_cmdlet != null)
{
commandOrigin = _cmdlet.CommandOrigin;
}
else if (_context != null)
{
commandOrigin = _context.EngineSessionState.CurrentScope.ScopeOrigin;
}
result = CommandDiscovery.LookupCommandInfo(commandName, type, SearchResolutionOptions.None, commandOrigin, _context);
if ((result != null) && (arguments != null) && (arguments.Length > 0))
{
// We've been asked to retrieve dynamic parameters
if (result.ImplementsDynamicParameters)
{
result = result.CreateGetCommandCopy(arguments);
}
}
}
catch (CommandNotFoundException) { }
return result;
}
/// <summary>
/// This event handler is called when a command is not found.
/// If should have a single string parameter that is the name
/// of the command and should return a CommandInfo object or null. By default
/// it will search the module path looking for a module that exports the
/// desired command.
/// </summary>
public System.EventHandler<CommandLookupEventArgs> CommandNotFoundAction { get; set; }
/// <summary>
/// This event handler is called before the command lookup is done.
/// If should have a single string parameter that is the name
/// of the command and should return a CommandInfo object or null.
/// </summary>
public System.EventHandler<CommandLookupEventArgs> PreCommandLookupAction { get; set; }
/// <summary>
/// This event handler is after the command lookup is done but before the event object is
/// returned to the caller. This allows things like interning scripts to work.
/// If should have a single string parameter that is the name
/// of the command and should return a CommandInfo object or null.
/// </summary>
public System.EventHandler<CommandLookupEventArgs> PostCommandLookupAction { get; set; }
/// <summary>
/// Returns the CmdletInfo object that corresponds to the name argument
/// </summary>
/// <param name="commandName">The name of the cmdlet to look for</param>
/// <returns>The cmdletInfo object if found, null otherwise</returns>
public CmdletInfo GetCmdlet(string commandName)
{
return GetCmdlet(commandName, _context);
}
/// <summary>
/// Returns the CmdletInfo object that corresponds to the name argument
/// </summary>
/// <param name="commandName">The name of the cmdlet to look for</param>
/// <param name="context">The execution context instance to use for lookup</param>
/// <returns>The cmdletInfo object if found, null otherwise</returns>
internal static CmdletInfo GetCmdlet(string commandName, ExecutionContext context)
{
CmdletInfo current = null;
CommandSearcher searcher = new CommandSearcher(
commandName,
SearchResolutionOptions.None,
CommandTypes.Cmdlet,
context);
do
{
try
{
if (!searcher.MoveNext())
{
break;
}
}
catch (ArgumentException)
{
continue;
}
catch (PathTooLongException)
{
continue;
}
catch (FileLoadException)
{
continue;
}
catch (MetadataException)
{
continue;
}
catch (FormatException)
{
continue;
}
current = ((IEnumerator)searcher).Current as CmdletInfo;
} while (true);
return current;
}
/// <summary>
/// Get the cmdlet info using the name of the cmdlet's implementing type. This bypasses
/// session state and retrieves the command directly. Note that the help file and snapin/module
/// info will both be null on returned object.
/// </summary>
/// <param name="cmdletTypeName">the type name of the class implementing this cmdlet</param>
/// <returns>CmdletInfo for the cmdlet if found, null otherwise</returns>
public CmdletInfo GetCmdletByTypeName(string cmdletTypeName)
{
if (string.IsNullOrEmpty(cmdletTypeName))
{
throw PSTraceSource.NewArgumentNullException("cmdletTypeName");
}
Exception e = null;
Type cmdletType = TypeResolver.ResolveType(cmdletTypeName, out e);
if (e != null)
{
throw e;
}
if (cmdletType == null)
{
return null;
}
CmdletAttribute ca = null;
foreach (var attr in cmdletType.GetTypeInfo().GetCustomAttributes(true))
{
ca = attr as CmdletAttribute;
if (ca != null)
break;
}
if (ca == null)
{
throw PSTraceSource.NewNotSupportedException();
}
string noun = ca.NounName;
string verb = ca.VerbName;
string cmdletName = verb + "-" + noun;
return new CmdletInfo(cmdletName, cmdletType, null, null, _context);
}
/// <summary>
/// Returns a list of all cmdlets...
/// </summary>
/// <returns></returns>
public List<CmdletInfo> GetCmdlets()
{
return GetCmdlets("*");
}
/// <summary>
/// Returns all cmdlets whose names match the pattern...
/// </summary>
/// <returns>A list of CmdletInfo objects...</returns>
public List<CmdletInfo> GetCmdlets(string pattern)
{
if (pattern == null)
throw PSTraceSource.NewArgumentNullException("pattern");
List<CmdletInfo> cmdlets = new List<CmdletInfo>();
CmdletInfo current = null;
CommandSearcher searcher = new CommandSearcher(
pattern,
SearchResolutionOptions.CommandNameIsPattern,
CommandTypes.Cmdlet,
_context);
do
{
try
{
if (!searcher.MoveNext())
{
break;
}
}
catch (ArgumentException)
{
continue;
}
catch (PathTooLongException)
{
continue;
}
catch (FileLoadException)
{
continue;
}
catch (MetadataException)
{
continue;
}
catch (FormatException)
{
continue;
}
current = ((IEnumerator)searcher).Current as CmdletInfo;
if (current != null)
cmdlets.Add(current);
} while (true);
return cmdlets;
}
/// <summary>
/// Searches for PowerShell commands, optionally using wildcard patterns
/// and optionally return the full path to applications and scripts rather than
/// the simple command name.
/// </summary>
/// <param name="name">The name of the command to use</param>
/// <param name="nameIsPattern">If true treat the name as a pattern to search for</param>
/// <param name="returnFullName">If true, return the full path to scripts and applications</param>
/// <returns>A list of command names...</returns>
public List<string> GetCommandName(string name, bool nameIsPattern, bool returnFullName)
{
if (name == null)
{
throw PSTraceSource.NewArgumentNullException("name");
}
List<string> commands = new List<string>();
foreach (CommandInfo current in this.GetCommands(name, CommandTypes.All, nameIsPattern))
{
if (current.CommandType == CommandTypes.Application)
{
string cmdExtension = System.IO.Path.GetExtension(current.Name);
if (!String.IsNullOrEmpty(cmdExtension))
{
// Only add the application in PATHEXT...
foreach (string extension in CommandDiscovery.PathExtensions)
{
if (extension.Equals(cmdExtension, StringComparison.OrdinalIgnoreCase))
{
if (returnFullName)
{
commands.Add(current.Definition);
}
else
{
commands.Add(current.Name);
}
}
}
}
}
else if (current.CommandType == CommandTypes.ExternalScript)
{
if (returnFullName)
{
commands.Add(current.Definition);
}
else
{
commands.Add(current.Name);
}
}
else
{
commands.Add(current.Name);
}
}
return commands;
}
/// <summary>
/// Searches for PowerShell commands, optionally using wildcard patterns
/// </summary>
/// <param name="name">The name of the command to use</param>
/// <param name="commandTypes">Type of commands to support</param>
/// <param name="nameIsPattern">If true treat the name as a pattern to search for</param>
/// <returns>Collection of command names...</returns>
public IEnumerable<CommandInfo> GetCommands(string name, CommandTypes commandTypes, bool nameIsPattern)
{
if (name == null)
{
throw PSTraceSource.NewArgumentNullException("name");
}
SearchResolutionOptions options = nameIsPattern ?
(SearchResolutionOptions.CommandNameIsPattern | SearchResolutionOptions.ResolveFunctionPatterns | SearchResolutionOptions.ResolveAliasPatterns)
: SearchResolutionOptions.None;
return GetCommands(name, commandTypes, options);
}
internal IEnumerable<CommandInfo> GetCommands(string name, CommandTypes commandTypes, SearchResolutionOptions options, CommandOrigin? commandOrigin = null)
{
CommandSearcher searcher = new CommandSearcher(
name,
options,
commandTypes,
_context);
if (commandOrigin != null)
{
searcher.CommandOrigin = commandOrigin.Value;
}
do
{
try
{
if (!searcher.MoveNext())
{
break;
}
}
catch (ArgumentException)
{
continue;
}
catch (PathTooLongException)
{
continue;
}
catch (FileLoadException)
{
continue;
}
catch (MetadataException)
{
continue;
}
catch (FormatException)
{
continue;
}
CommandInfo commandInfo = ((IEnumerator)searcher).Current as CommandInfo;
if (commandInfo != null)
{
yield return commandInfo;
}
} while (true);
}
/// <summary>
/// Executes a piece of text as a script synchronously.
/// </summary>
/// <param name="script">The script text to evaluate</param>
/// <returns>A collection of MshCobjects generated by the script.</returns>
/// <exception cref="ParseException">Thrown if there was a parsing error in the script.</exception>
/// <exception cref="RuntimeException">Represents a script-level exception</exception>
/// <exception cref="FlowControlException"></exception>
public Collection<PSObject> InvokeScript(string script)
{
return InvokeScript(script, true, PipelineResultTypes.None, null);
}
/// <summary>
/// Executes a piece of text as a script synchronously.
/// </summary>
/// <param name="script">The script text to evaluate</param>
/// <param name="args">The arguments to the script</param>
/// <returns>A collection of MshCobjects generated by the script.</returns>
/// <exception cref="ParseException">Thrown if there was a parsing error in the script.</exception>
/// <exception cref="RuntimeException">Represents a script-level exception</exception>
/// <exception cref="FlowControlException"></exception>
public Collection<PSObject> InvokeScript(string script, params object[] args)
{
return InvokeScript(script, true, PipelineResultTypes.None, args);
}
/// <summary>
///
/// </summary>
/// <param name="sessionState"></param>
/// <param name="scriptBlock"></param>
/// <param name="args"></param>
/// <returns></returns>
public Collection<PSObject> InvokeScript(
SessionState sessionState, ScriptBlock scriptBlock, params object[] args)
{
if (scriptBlock == null)
{
throw PSTraceSource.NewArgumentNullException("scriptBlock");
}
if (sessionState == null)
{
throw PSTraceSource.NewArgumentNullException("sessionState");
}
SessionStateInternal _oldSessionState = _context.EngineSessionState;
try
{
_context.EngineSessionState = sessionState.Internal;
return InvokeScript(scriptBlock, false, PipelineResultTypes.None, null, args);
}
finally
{
_context.EngineSessionState = _oldSessionState;
}
}
/// <summary>
/// Invoke a scriptblock in the current runspace, controlling if it gets a new scope.
/// </summary>
/// <param name="useLocalScope">If true, a new scope will be created</param>
/// <param name="scriptBlock">The scriptblock to execute</param>
/// <param name="input">Optionall input to the command</param>
/// <param name="args">Arguments to pass to the scriptblock</param>
/// <returns>The result of the evaluation</returns>
public Collection<PSObject> InvokeScript(
bool useLocalScope, ScriptBlock scriptBlock, IList input, params object[] args)
{
if (scriptBlock == null)
{
throw PSTraceSource.NewArgumentNullException("scriptBlock");
}
// Force the current runspace onto the callers thread - this is needed
// if this API is going to be callable through the SessionStateProxy on the runspace.
var old = System.Management.Automation.Runspaces.Runspace.DefaultRunspace;
System.Management.Automation.Runspaces.Runspace.DefaultRunspace = _context.CurrentRunspace;
try
{
return InvokeScript(scriptBlock, useLocalScope, PipelineResultTypes.None, input, args);
}
finally
{
System.Management.Automation.Runspaces.Runspace.DefaultRunspace = old;
}
}
/// <summary>
/// Executes a piece of text as a script synchronously using the options provided.
/// </summary>
/// <param name="script">The script to evaluate.</param>
/// <param name="useNewScope">If true, evaluate the script in its own scope.
/// If false, the script will be evaluated in the current scope i.e. it will be "dotted"</param>
/// <param name="writeToPipeline">If set to Output, all output will be streamed
/// to the output pipe of the calling cmdlet. If set to None, the result will be returned
/// to the caller as a collection of PSObjects. No other flags are supported at this time and
/// will result in an exception if used.</param>
/// <param name="input">The list of objects to use as input to the script.</param>
/// <param name="args">The array of arguments to the command.</param>
/// <returns>A collection of MshCobjects generated by the script. This will be
/// empty if output was redirected.</returns>
/// <exception cref="ParseException">Thrown if there was a parsing error in the script.</exception>
/// <exception cref="RuntimeException">Represents a script-level exception</exception>
/// <exception cref="NotImplementedException">Thrown if any redirect other than output is attempted</exception>
/// <exception cref="FlowControlException"></exception>
public Collection<PSObject> InvokeScript(string script, bool useNewScope,
PipelineResultTypes writeToPipeline, IList input, params object[] args)
{
if (script == null)
throw new ArgumentNullException("script");
// Compile the script text into an executable script block.
ScriptBlock sb = ScriptBlock.Create(_context, script);
return InvokeScript(sb, useNewScope, writeToPipeline, input, args);
}
private Collection<PSObject> InvokeScript(ScriptBlock sb, bool useNewScope,
PipelineResultTypes writeToPipeline, IList input, params object[] args)
{
if (null != _cmdlet)
_cmdlet.ThrowIfStopping();
Cmdlet cmdletToUse = null;
ScriptBlock.ErrorHandlingBehavior errorHandlingBehavior = ScriptBlock.ErrorHandlingBehavior.WriteToExternalErrorPipe;
// Check if they want output
if ((writeToPipeline & PipelineResultTypes.Output) == PipelineResultTypes.Output)
{
cmdletToUse = _cmdlet;
writeToPipeline &= (~PipelineResultTypes.Output);
}
// Check if they want error
if ((writeToPipeline & PipelineResultTypes.Error) == PipelineResultTypes.Error)
{
errorHandlingBehavior = ScriptBlock.ErrorHandlingBehavior.WriteToCurrentErrorPipe;
writeToPipeline &= (~PipelineResultTypes.Error);
}
if (writeToPipeline != PipelineResultTypes.None)
{
// The only output types are Output and Error.
throw PSTraceSource.NewNotImplementedException();
}
// If the cmdletToUse is not null, then the result of the evaluation will be
// streamed out the output pipe of the cmdlet.
object rawResult;
if (cmdletToUse != null)
{
sb.InvokeUsingCmdlet(
contextCmdlet: cmdletToUse,
useLocalScope: useNewScope,
errorHandlingBehavior: errorHandlingBehavior,
dollarUnder: AutomationNull.Value,
input: input,
scriptThis: AutomationNull.Value,
args: args);
rawResult = AutomationNull.Value;
}
else
{
rawResult = sb.DoInvokeReturnAsIs(
useLocalScope: useNewScope,
errorHandlingBehavior: errorHandlingBehavior,
dollarUnder: AutomationNull.Value,
input: input,
scriptThis: AutomationNull.Value,
args: args);
}
if (rawResult == AutomationNull.Value)
{
return new Collection<PSObject>();
}
// If the result is already a collection of PSObjects, just return it...
Collection<PSObject> result = rawResult as Collection<PSObject>;
if (result != null)
return result;
result = new Collection<PSObject>();
IEnumerator list = null;
list = LanguagePrimitives.GetEnumerator(rawResult);
if (list != null)
{
while (list.MoveNext())
{
object val = list.Current;
result.Add(LanguagePrimitives.AsPSObjectOrNull(val));
}
}
else
{
result.Add(LanguagePrimitives.AsPSObjectOrNull(rawResult));
}
return result;
}
/// <summary>
/// Compile a string into a script block.
/// </summary>
/// <param name="scriptText">The source text to compile</param>
/// <returns>The compiled script block</returns>
/// <exception cref="ParseException"></exception>
public ScriptBlock NewScriptBlock(string scriptText)
{
if (null != _commandRuntime)
_commandRuntime.ThrowIfStopping();
ScriptBlock result = ScriptBlock.Create(_context, scriptText);
return result;
}
} //CommandInvocationIntrinsics
#endregion Auxiliary
/// <summary>
/// Defines members used by Cmdlets.
/// All Cmdlets must derive from
/// <see cref="System.Management.Automation.Cmdlet"/>.
/// </summary>
/// <remarks>
/// Do not attempt to create instances of
/// <see cref="System.Management.Automation.Cmdlet"/>
/// or its subclasses.
/// Instead, derive your own subclasses and mark them with
/// <see cref="System.Management.Automation.CmdletAttribute"/>,
/// and when your assembly is included in a shell, the Engine will
/// take care of instantiating your subclass.
/// </remarks>
public abstract partial class PSCmdlet : Cmdlet
{
#region private_members
internal bool HasDynamicParameters
{
get { return this is IDynamicParameters; }
}
#endregion private_members
#region public members
/// <summary>
/// The name of the parameter set in effect.
/// </summary>
/// <value>the parameter set name</value>
public string ParameterSetName
{
get
{
using (PSTransactionManager.GetEngineProtectionScope())
{
return _ParameterSetName;
}
}
}
/// <summary>
/// Contains information about the identity of this cmdlet
/// and how it was invoked.
/// </summary>
/// <value></value>
public new InvocationInfo MyInvocation
{
get
{
using (PSTransactionManager.GetEngineProtectionScope())
{
return base.MyInvocation;
}
}
}
/// <summary>
/// If the cmdlet declares paging support (via <see cref="CmdletCommonMetadataAttribute.SupportsPaging"/>),
/// then <see cref="PagingParameters"/> property contains arguments of the paging parameters.
/// Otherwise <see cref="PagingParameters"/> property is <c>null</c>.
/// </summary>
public PagingParameters PagingParameters
{
get
{
using (PSTransactionManager.GetEngineProtectionScope())
{
if (!this.CommandInfo.CommandMetadata.SupportsPaging)
{
return null;
}
if (_pagingParameters == null)
{
MshCommandRuntime mshCommandRuntime = this.CommandRuntime as MshCommandRuntime;
if (mshCommandRuntime != null)
{
_pagingParameters = mshCommandRuntime.PagingParameters ?? new PagingParameters(mshCommandRuntime);
}
}
return _pagingParameters;
}
}
}
private PagingParameters _pagingParameters;
#region InvokeCommand
private CommandInvocationIntrinsics _invokeCommand;
/// <summary>
/// Provides access to utility routines for executing scripts
/// and creating script blocks.
/// </summary>
/// <value>Returns an object exposing the utility routines.</value>
public CommandInvocationIntrinsics InvokeCommand
{
get
{
using (PSTransactionManager.GetEngineProtectionScope())
{
return _invokeCommand ?? (_invokeCommand = new CommandInvocationIntrinsics(Context, this));
}
}
} //InvokeCommand
#endregion InvokeCommand
#endregion public members
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.IO;
using System.Reflection;
using System.Text;
using log4net;
namespace OpenSim.Framework.Serialization
{
/// <summary>
/// Temporary code to do the bare minimum required to read a tar archive for our purposes
/// </summary>
public class TarArchiveReader
{
//private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
public enum TarEntryType
{
TYPE_UNKNOWN = 0,
TYPE_NORMAL_FILE = 1,
TYPE_HARD_LINK = 2,
TYPE_SYMBOLIC_LINK = 3,
TYPE_CHAR_SPECIAL = 4,
TYPE_BLOCK_SPECIAL = 5,
TYPE_DIRECTORY = 6,
TYPE_FIFO = 7,
TYPE_CONTIGUOUS_FILE = 8,
}
protected static ASCIIEncoding m_asciiEncoding = new ASCIIEncoding();
/// <summary>
/// Binary reader for the underlying stream
/// </summary>
protected BinaryReader m_br;
/// <summary>
/// Used to trim off null chars
/// </summary>
protected static char[] m_nullCharArray = new char[] { '\0' };
/// <summary>
/// Used to trim off space chars
/// </summary>
protected static char[] m_spaceCharArray = new char[] { ' ' };
/// <summary>
/// Generate a tar reader which reads from the given stream.
/// </summary>
/// <param name="s"></param>
public TarArchiveReader(Stream s)
{
m_br = new BinaryReader(s);
}
/// <summary>
/// Read the next entry in the tar file.
/// </summary>
/// <param name="filePath"></param>
/// <returns>the data for the entry. Returns null if there are no more entries</returns>
public byte[] ReadEntry(out string filePath, out TarEntryType entryType)
{
filePath = String.Empty;
entryType = TarEntryType.TYPE_UNKNOWN;
TarHeader header = ReadHeader();
if (null == header)
return null;
entryType = header.EntryType;
filePath = header.FilePath;
return ReadData(header.FileSize);
}
/// <summary>
/// Read the next 512 byte chunk of data as a tar header.
/// </summary>
/// <returns>A tar header struct. null if we have reached the end of the archive.</returns>
protected TarHeader ReadHeader()
{
byte[] header = m_br.ReadBytes(512);
// If there are no more bytes in the stream, return null header
if (header.Length == 0)
return null;
// If we've reached the end of the archive we'll be in null block territory, which means
// the next byte will be 0
if (header[0] == 0)
return null;
TarHeader tarHeader = new TarHeader();
// If we're looking at a GNU tar long link then extract the long name and pull up the next header
if (header[156] == (byte)'L')
{
int longNameLength = ConvertOctalBytesToDecimal(header, 124, 11);
tarHeader.FilePath = m_asciiEncoding.GetString(ReadData(longNameLength));
//m_log.DebugFormat("[TAR ARCHIVE READER]: Got long file name {0}", tarHeader.FilePath);
header = m_br.ReadBytes(512);
}
else
{
tarHeader.FilePath = m_asciiEncoding.GetString(header, 0, 100);
tarHeader.FilePath = tarHeader.FilePath.Trim(m_nullCharArray);
//m_log.DebugFormat("[TAR ARCHIVE READER]: Got short file name {0}", tarHeader.FilePath);
}
tarHeader.FileSize = ConvertOctalBytesToDecimal(header, 124, 11);
switch (header[156])
{
case 0:
tarHeader.EntryType = TarEntryType.TYPE_NORMAL_FILE;
break;
case (byte)'0':
tarHeader.EntryType = TarEntryType.TYPE_NORMAL_FILE;
break;
case (byte)'1':
tarHeader.EntryType = TarEntryType.TYPE_HARD_LINK;
break;
case (byte)'2':
tarHeader.EntryType = TarEntryType.TYPE_SYMBOLIC_LINK;
break;
case (byte)'3':
tarHeader.EntryType = TarEntryType.TYPE_CHAR_SPECIAL;
break;
case (byte)'4':
tarHeader.EntryType = TarEntryType.TYPE_BLOCK_SPECIAL;
break;
case (byte)'5':
tarHeader.EntryType = TarEntryType.TYPE_DIRECTORY;
break;
case (byte)'6':
tarHeader.EntryType = TarEntryType.TYPE_FIFO;
break;
case (byte)'7':
tarHeader.EntryType = TarEntryType.TYPE_CONTIGUOUS_FILE;
break;
}
return tarHeader;
}
/// <summary>
/// Read data following a header
/// </summary>
/// <param name="fileSize"></param>
/// <returns></returns>
protected byte[] ReadData(int fileSize)
{
byte[] data = m_br.ReadBytes(fileSize);
//m_log.DebugFormat("[TAR ARCHIVE READER]: fileSize {0}", fileSize);
// Read the rest of the empty padding in the 512 byte block
if (fileSize % 512 != 0)
{
int paddingLeft = 512 - (fileSize % 512);
//m_log.DebugFormat("[TAR ARCHIVE READER]: Reading {0} padding bytes", paddingLeft);
m_br.ReadBytes(paddingLeft);
}
return data;
}
public void Close()
{
m_br.Close();
}
/// <summary>
/// Convert octal bytes to a decimal representation
/// </summary>
/// <param name="bytes"></param>
/// <returns></returns>
public static int ConvertOctalBytesToDecimal(byte[] bytes, int startIndex, int count)
{
// Trim leading white space: ancient tars do that instead
// of leading 0s :-( don't ask. really.
string oString = m_asciiEncoding.GetString(bytes, startIndex, count).TrimStart(m_spaceCharArray);
int d = 0;
foreach (char c in oString)
{
d <<= 3;
d |= c - '0';
}
return d;
}
}
public class TarHeader
{
public string FilePath;
public int FileSize;
public TarArchiveReader.TarEntryType EntryType;
}
}
| |
//------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//------------------------------------------------------------
namespace System.Xml
{
using System;
using System.Xml;
using System.Xml.XPath;
using System.IO;
using System.Text;
using System.Collections.Generic;
using System.Globalization;
using System.Threading;
using System.Runtime.Serialization;
public interface IXmlMtomWriterInitializer
{
void SetOutput(Stream stream, Encoding encoding, int maxSizeInBytes, string startInfo, string boundary, string startUri, bool writeMessageHeaders, bool ownsStream);
}
class XmlMtomWriter : XmlDictionaryWriter, IXmlMtomWriterInitializer
{
// Maximum number of bytes that are inlined as base64 data without being MTOM-optimized as xop:Include
const int MaxInlinedBytes = 767; // 768 will be the first MIMEd length
int maxSizeInBytes;
XmlDictionaryWriter writer;
XmlDictionaryWriter infosetWriter;
MimeWriter mimeWriter;
Encoding encoding;
bool isUTF8;
string contentID;
string contentType;
string initialContentTypeForRootPart;
string initialContentTypeForMimeMessage;
MemoryStream contentTypeStream;
List<MimePart> mimeParts;
IList<MtomBinaryData> binaryDataChunks;
int depth;
int totalSizeOfMimeParts;
int sizeOfBufferedBinaryData;
char[] chars;
byte[] bytes;
bool isClosed;
bool ownsStream;
public XmlMtomWriter()
{
}
public void SetOutput(Stream stream, Encoding encoding, int maxSizeInBytes, string startInfo, string boundary, string startUri, bool writeMessageHeaders, bool ownsStream)
{
if (encoding == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("encoding");
if (maxSizeInBytes < 0)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("maxSizeInBytes", SR.GetString(SR.ValueMustBeNonNegative)));
this.maxSizeInBytes = maxSizeInBytes;
this.encoding = encoding;
this.isUTF8 = IsUTF8Encoding(encoding);
Initialize(stream, startInfo, boundary, startUri, writeMessageHeaders, ownsStream);
}
XmlDictionaryWriter Writer
{
get
{
if (!IsInitialized)
{
Initialize();
}
return writer;
}
}
bool IsInitialized
{
get { return (initialContentTypeForRootPart == null); }
}
void Initialize(Stream stream, string startInfo, string boundary, string startUri, bool writeMessageHeaders, bool ownsStream)
{
if (stream == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("stream");
if (startInfo == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("startInfo");
if (boundary == null)
boundary = GetBoundaryString();
if (startUri == null)
startUri = GenerateUriForMimePart(0);
if (!MailBnfHelper.IsValidMimeBoundary(boundary))
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.GetString(SR.MtomBoundaryInvalid, boundary), "boundary"));
this.ownsStream = ownsStream;
this.isClosed = false;
this.depth = 0;
this.totalSizeOfMimeParts = 0;
this.sizeOfBufferedBinaryData = 0;
this.binaryDataChunks = null;
this.contentType = null;
this.contentTypeStream = null;
this.contentID = startUri;
if (this.mimeParts != null)
this.mimeParts.Clear();
this.mimeWriter = new MimeWriter(stream, boundary);
this.initialContentTypeForRootPart = GetContentTypeForRootMimePart(this.encoding, startInfo);
if (writeMessageHeaders)
this.initialContentTypeForMimeMessage = GetContentTypeForMimeMessage(boundary, startUri, startInfo);
}
void Initialize()
{
if (this.isClosed)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.XmlWriterClosed)));
if (this.initialContentTypeForRootPart != null)
{
if (this.initialContentTypeForMimeMessage != null)
{
mimeWriter.StartPreface();
mimeWriter.WriteHeader(MimeGlobals.MimeVersionHeader, MimeGlobals.DefaultVersion);
mimeWriter.WriteHeader(MimeGlobals.ContentTypeHeader, this.initialContentTypeForMimeMessage);
this.initialContentTypeForMimeMessage = null;
}
WriteMimeHeaders(this.contentID, this.initialContentTypeForRootPart, this.isUTF8 ? MimeGlobals.Encoding8bit : MimeGlobals.EncodingBinary);
Stream infosetContentStream = this.mimeWriter.GetContentStream();
IXmlTextWriterInitializer initializer = writer as IXmlTextWriterInitializer;
if (initializer == null)
writer = XmlDictionaryWriter.CreateTextWriter(infosetContentStream, this.encoding, this.ownsStream);
else
initializer.SetOutput(infosetContentStream, this.encoding, this.ownsStream);
this.contentID = null;
this.initialContentTypeForRootPart = null;
}
}
static string GetBoundaryString()
{
return MimeBoundaryGenerator.Next();
}
internal static bool IsUTF8Encoding(Encoding encoding)
{
return encoding.WebName == "utf-8";
}
static string GetContentTypeForMimeMessage(string boundary, string startUri, string startInfo)
{
StringBuilder contentTypeBuilder = new StringBuilder(
String.Format(CultureInfo.InvariantCulture, "{0}/{1};{2}=\"{3}\";{4}=\"{5}\"",
MtomGlobals.MediaType, MtomGlobals.MediaSubtype,
MtomGlobals.TypeParam, MtomGlobals.XopType,
MtomGlobals.BoundaryParam, boundary));
if (startUri != null && startUri.Length > 0)
contentTypeBuilder.AppendFormat(CultureInfo.InvariantCulture, ";{0}=\"<{1}>\"", MtomGlobals.StartParam, startUri);
if (startInfo != null && startInfo.Length > 0)
contentTypeBuilder.AppendFormat(CultureInfo.InvariantCulture, ";{0}=\"{1}\"", MtomGlobals.StartInfoParam, startInfo);
return contentTypeBuilder.ToString();
}
static string GetContentTypeForRootMimePart(Encoding encoding, string startInfo)
{
string contentType = String.Format(CultureInfo.InvariantCulture, "{0};{1}={2}", MtomGlobals.XopType, MtomGlobals.CharsetParam, CharSet(encoding));
if (startInfo != null)
contentType = String.Format(CultureInfo.InvariantCulture, "{0};{1}=\"{2}\"", contentType, MtomGlobals.TypeParam, startInfo);
return contentType;
}
static string CharSet(Encoding enc)
{
string name = enc.WebName;
if (String.Compare(name, Encoding.UTF8.WebName, StringComparison.OrdinalIgnoreCase) == 0)
return name;
if (String.Compare(name, Encoding.Unicode.WebName, StringComparison.OrdinalIgnoreCase) == 0)
return "utf-16LE";
if (String.Compare(name, Encoding.BigEndianUnicode.WebName, StringComparison.OrdinalIgnoreCase) == 0)
return "utf-16BE";
return name;
}
public override void WriteStartElement(string prefix, string localName, string ns)
{
WriteBase64InlineIfPresent();
ThrowIfElementIsXOPInclude(prefix, localName, ns);
Writer.WriteStartElement(prefix, localName, ns);
depth++;
}
public override void WriteStartElement(string prefix, XmlDictionaryString localName, XmlDictionaryString ns)
{
if (localName == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("localName");
WriteBase64InlineIfPresent();
ThrowIfElementIsXOPInclude(prefix, localName.Value, ns == null ? null : ns.Value);
Writer.WriteStartElement(prefix, localName, ns);
depth++;
}
void ThrowIfElementIsXOPInclude(string prefix, string localName, string ns)
{
if (ns == null)
{
XmlBaseWriter w = this.Writer as XmlBaseWriter;
if (w != null)
ns = w.LookupNamespace(prefix);
}
if (localName == MtomGlobals.XopIncludeLocalName && ns == MtomGlobals.XopIncludeNamespace)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(SR.GetString(SR.MtomDataMustNotContainXopInclude, MtomGlobals.XopIncludeLocalName, MtomGlobals.XopIncludeNamespace)));
}
public override void WriteEndElement()
{
WriteXOPInclude();
Writer.WriteEndElement();
depth--;
WriteXOPBinaryParts();
}
public override void WriteFullEndElement()
{
WriteXOPInclude();
Writer.WriteFullEndElement();
depth--;
WriteXOPBinaryParts();
}
public override void WriteValue(IStreamProvider value)
{
if (value == null)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("value"));
if (Writer.WriteState == WriteState.Element)
{
if (binaryDataChunks == null)
{
binaryDataChunks = new List<MtomBinaryData>();
contentID = GenerateUriForMimePart((mimeParts == null) ? 1 : mimeParts.Count + 1);
}
binaryDataChunks.Add(new MtomBinaryData(value));
}
else
Writer.WriteValue(value);
}
public override void WriteBase64(byte[] buffer, int index, int count)
{
if (Writer.WriteState == WriteState.Element)
{
if (buffer == null)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("buffer"));
// Not checking upper bound because it will be caught by "count". This is what XmlTextWriter does.
if (index < 0)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("index", SR.GetString(SR.ValueMustBeNonNegative)));
if (count < 0)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("count", SR.GetString(SR.ValueMustBeNonNegative)));
if (count > buffer.Length - index)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("count", SR.GetString(SR.SizeExceedsRemainingBufferSpace, buffer.Length - index)));
if (binaryDataChunks == null)
{
binaryDataChunks = new List<MtomBinaryData>();
contentID = GenerateUriForMimePart((mimeParts == null) ? 1 : mimeParts.Count + 1);
}
int totalSize = ValidateSizeOfMessage(maxSizeInBytes, 0, totalSizeOfMimeParts);
totalSize += ValidateSizeOfMessage(maxSizeInBytes, totalSize, sizeOfBufferedBinaryData);
totalSize += ValidateSizeOfMessage(maxSizeInBytes, totalSize, count);
sizeOfBufferedBinaryData += count;
binaryDataChunks.Add(new MtomBinaryData(buffer, index, count));
}
else
Writer.WriteBase64(buffer, index, count);
}
internal static int ValidateSizeOfMessage(int maxSize, int offset, int size)
{
if (size > (maxSize - offset))
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(SR.GetString(SR.MtomExceededMaxSizeInBytes, maxSize)));
return size;
}
void WriteBase64InlineIfPresent()
{
if (binaryDataChunks != null)
{
WriteBase64Inline();
}
}
void WriteBase64Inline()
{
foreach (MtomBinaryData data in binaryDataChunks)
{
if (data.type == MtomBinaryDataType.Provider)
{
Writer.WriteValue(data.provider);
}
else
{
Writer.WriteBase64(data.chunk, 0, data.chunk.Length);
}
}
this.sizeOfBufferedBinaryData = 0;
binaryDataChunks = null;
contentType = null;
contentID = null;
}
void WriteXOPInclude()
{
if (binaryDataChunks == null)
return;
bool inline = true;
long size = 0;
foreach (MtomBinaryData data in binaryDataChunks)
{
long len = data.Length;
if (len < 0 || len > (MaxInlinedBytes - size))
{
inline = false;
break;
}
size += len;
}
if (inline)
WriteBase64Inline();
else
{
if (mimeParts == null)
mimeParts = new List<MimePart>();
MimePart mimePart = new MimePart(binaryDataChunks, contentID, contentType, MimeGlobals.EncodingBinary, sizeOfBufferedBinaryData, maxSizeInBytes);
mimeParts.Add(mimePart);
totalSizeOfMimeParts += ValidateSizeOfMessage(maxSizeInBytes, totalSizeOfMimeParts, mimePart.sizeInBytes);
totalSizeOfMimeParts += ValidateSizeOfMessage(maxSizeInBytes, totalSizeOfMimeParts, mimeWriter.GetBoundarySize());
Writer.WriteStartElement(MtomGlobals.XopIncludePrefix, MtomGlobals.XopIncludeLocalName, MtomGlobals.XopIncludeNamespace);
Writer.WriteStartAttribute(MtomGlobals.XopIncludeHrefLocalName, MtomGlobals.XopIncludeHrefNamespace);
Writer.WriteValue(String.Format(CultureInfo.InvariantCulture, "{0}{1}", MimeGlobals.ContentIDScheme, contentID));
Writer.WriteEndAttribute();
Writer.WriteEndElement();
binaryDataChunks = null;
sizeOfBufferedBinaryData = 0;
contentType = null;
contentID = null;
}
}
public static string GenerateUriForMimePart(int index)
{
return String.Format(CultureInfo.InvariantCulture, "http://tempuri.org/{0}/{1}", index, DateTime.Now.Ticks);
}
void WriteXOPBinaryParts()
{
if (depth > 0 || mimeWriter.WriteState == MimeWriterState.Closed)
return;
if (Writer.WriteState != WriteState.Closed)
Writer.Flush();
if (mimeParts != null)
{
foreach (MimePart part in mimeParts)
{
WriteMimeHeaders(part.contentID, part.contentType, part.contentTransferEncoding);
Stream s = mimeWriter.GetContentStream();
int blockSize = 256;
int bytesRead = 0;
byte[] block = new byte[blockSize];
Stream stream = null;
foreach (MtomBinaryData data in part.binaryData)
{
if (data.type == MtomBinaryDataType.Provider)
{
stream = data.provider.GetStream();
if (stream == null)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(SR.GetString(SR.XmlInvalidStream)));
while (true)
{
bytesRead = stream.Read(block, 0, blockSize);
if (bytesRead > 0)
s.Write(block, 0, bytesRead);
else
break;
if (blockSize < 65536 && bytesRead == blockSize)
{
blockSize = blockSize * 16;
block = new byte[blockSize];
}
}
data.provider.ReleaseStream(stream);
}
else
{
s.Write(data.chunk, 0, data.chunk.Length);
}
}
}
mimeParts.Clear();
}
mimeWriter.Close();
}
void WriteMimeHeaders(string contentID, string contentType, string contentTransferEncoding)
{
mimeWriter.StartPart();
if (contentID != null)
mimeWriter.WriteHeader(MimeGlobals.ContentIDHeader, String.Format(CultureInfo.InvariantCulture, "<{0}>", contentID));
if (contentTransferEncoding != null)
mimeWriter.WriteHeader(MimeGlobals.ContentTransferEncodingHeader, contentTransferEncoding);
if (contentType != null)
mimeWriter.WriteHeader(MimeGlobals.ContentTypeHeader, contentType);
}
#if NO
public override bool CanSubsetElements
{
get { return Writer.CanSubsetElements; }
}
#endif
public override void Close()
{
if (!this.isClosed)
{
this.isClosed = true;
if (IsInitialized)
{
WriteXOPInclude();
if (Writer.WriteState == WriteState.Element ||
Writer.WriteState == WriteState.Attribute ||
Writer.WriteState == WriteState.Content)
{
Writer.WriteEndDocument();
}
Writer.Flush();
depth = 0;
WriteXOPBinaryParts();
Writer.Close();
}
}
}
void CheckIfStartContentTypeAttribute(string localName, string ns)
{
if (localName != null && localName == MtomGlobals.MimeContentTypeLocalName
&& ns != null && (ns == MtomGlobals.MimeContentTypeNamespace200406 || ns == MtomGlobals.MimeContentTypeNamespace200505))
{
contentTypeStream = new MemoryStream();
this.infosetWriter = Writer;
this.writer = XmlDictionaryWriter.CreateBinaryWriter(contentTypeStream);
Writer.WriteStartElement("Wrapper");
Writer.WriteStartAttribute(localName, ns);
}
}
void CheckIfEndContentTypeAttribute()
{
if (contentTypeStream != null)
{
Writer.WriteEndAttribute();
Writer.WriteEndElement();
Writer.Flush();
contentTypeStream.Position = 0;
XmlReader contentTypeReader = XmlDictionaryReader.CreateBinaryReader(contentTypeStream, null, XmlDictionaryReaderQuotas.Max, null, null);
while (contentTypeReader.Read())
{
if (contentTypeReader.IsStartElement("Wrapper"))
{
contentType = contentTypeReader.GetAttribute(MtomGlobals.MimeContentTypeLocalName, MtomGlobals.MimeContentTypeNamespace200406);
if (contentType == null)
{
contentType = contentTypeReader.GetAttribute(MtomGlobals.MimeContentTypeLocalName, MtomGlobals.MimeContentTypeNamespace200505);
}
break;
}
}
this.writer = infosetWriter;
this.infosetWriter = null;
contentTypeStream = null;
if (contentType != null)
Writer.WriteString(contentType);
}
}
#if NO
public override bool ElementSubsetting
{
get
{
return Writer.ElementSubsetting;
}
set
{
Writer.ElementSubsetting = value;
}
}
#endif
public override void Flush()
{
if (IsInitialized)
Writer.Flush();
}
public override string LookupPrefix(string ns)
{
return Writer.LookupPrefix(ns);
}
public override XmlWriterSettings Settings
{
get
{
return Writer.Settings;
}
}
public override void WriteAttributes(XmlReader reader, bool defattr)
{
Writer.WriteAttributes(reader, defattr);
}
public override void WriteBinHex(byte[] buffer, int index, int count)
{
WriteBase64InlineIfPresent();
Writer.WriteBinHex(buffer, index, count);
}
public override void WriteCData(string text)
{
WriteBase64InlineIfPresent();
Writer.WriteCData(text);
}
public override void WriteCharEntity(char ch)
{
WriteBase64InlineIfPresent();
Writer.WriteCharEntity(ch);
}
public override void WriteChars(char[] buffer, int index, int count)
{
WriteBase64InlineIfPresent();
Writer.WriteChars(buffer, index, count);
}
public override void WriteComment(string text)
{
// Don't write comments after the document element
if (depth == 0 && mimeWriter.WriteState == MimeWriterState.Closed)
return;
WriteBase64InlineIfPresent();
Writer.WriteComment(text);
}
public override void WriteDocType(string name, string pubid, string sysid, string subset)
{
WriteBase64InlineIfPresent();
Writer.WriteDocType(name, pubid, sysid, subset);
}
#if NO
public override void WriteElementSubset(ArraySegment<byte> buffer)
{
Writer.WriteElementSubset(buffer);
}
#endif
public override void WriteEndAttribute()
{
CheckIfEndContentTypeAttribute();
Writer.WriteEndAttribute();
}
public override void WriteEndDocument()
{
WriteXOPInclude();
Writer.WriteEndDocument();
depth = 0;
WriteXOPBinaryParts();
}
public override void WriteEntityRef(string name)
{
WriteBase64InlineIfPresent();
Writer.WriteEntityRef(name);
}
public override void WriteName(string name)
{
WriteBase64InlineIfPresent();
Writer.WriteName(name);
}
public override void WriteNmToken(string name)
{
WriteBase64InlineIfPresent();
Writer.WriteNmToken(name);
}
protected override void WriteTextNode(XmlDictionaryReader reader, bool attribute)
{
Type type = reader.ValueType;
if (type == typeof(string))
{
if (reader.CanReadValueChunk)
{
if (chars == null)
{
chars = new char[256];
}
int count;
while ((count = reader.ReadValueChunk(chars, 0, chars.Length)) > 0)
{
this.WriteChars(chars, 0, count);
}
}
else
{
WriteString(reader.Value);
}
if (!attribute)
{
reader.Read();
}
}
else if (type == typeof(byte[]))
{
if (reader.CanReadBinaryContent)
{
// Its best to read in buffers that are a multiple of 3 so we don't break base64 boundaries when converting text
if (bytes == null)
{
bytes = new byte[384];
}
int count;
while ((count = reader.ReadValueAsBase64(bytes, 0, bytes.Length)) > 0)
{
this.WriteBase64(bytes, 0, count);
}
}
else
{
WriteString(reader.Value);
}
if (!attribute)
{
reader.Read();
}
}
else
{
base.WriteTextNode(reader, attribute);
}
}
public override void WriteNode(XPathNavigator navigator, bool defattr)
{
WriteBase64InlineIfPresent();
Writer.WriteNode(navigator, defattr);
}
public override void WriteProcessingInstruction(string name, string text)
{
WriteBase64InlineIfPresent();
Writer.WriteProcessingInstruction(name, text);
}
public override void WriteQualifiedName(string localName, string namespaceUri)
{
WriteBase64InlineIfPresent();
Writer.WriteQualifiedName(localName, namespaceUri);
}
public override void WriteRaw(char[] buffer, int index, int count)
{
WriteBase64InlineIfPresent();
Writer.WriteRaw(buffer, index, count);
}
public override void WriteRaw(string data)
{
WriteBase64InlineIfPresent();
Writer.WriteRaw(data);
}
public override void WriteStartAttribute(string prefix, string localName, string ns)
{
Writer.WriteStartAttribute(prefix, localName, ns);
CheckIfStartContentTypeAttribute(localName, ns);
}
public override void WriteStartAttribute(string prefix, XmlDictionaryString localName, XmlDictionaryString ns)
{
Writer.WriteStartAttribute(prefix, localName, ns);
if (localName != null && ns != null)
CheckIfStartContentTypeAttribute(localName.Value, ns.Value);
}
public override void WriteStartDocument()
{
Writer.WriteStartDocument();
}
public override void WriteStartDocument(bool standalone)
{
Writer.WriteStartDocument(standalone);
}
public override WriteState WriteState
{
get
{
return Writer.WriteState;
}
}
public override void WriteString(string text)
{
// Don't write whitespace after the document element
if (depth == 0 && mimeWriter.WriteState == MimeWriterState.Closed && XmlConverter.IsWhitespace(text))
return;
WriteBase64InlineIfPresent();
Writer.WriteString(text);
}
public override void WriteString(XmlDictionaryString value)
{
// Don't write whitespace after the document element
if (depth == 0 && mimeWriter.WriteState == MimeWriterState.Closed && XmlConverter.IsWhitespace(value.Value))
return;
WriteBase64InlineIfPresent();
Writer.WriteString(value);
}
public override void WriteSurrogateCharEntity(char lowChar, char highChar)
{
WriteBase64InlineIfPresent();
Writer.WriteSurrogateCharEntity(lowChar, highChar);
}
public override void WriteWhitespace(string whitespace)
{
// Don't write whitespace after the document element
if (depth == 0 && mimeWriter.WriteState == MimeWriterState.Closed)
return;
WriteBase64InlineIfPresent();
Writer.WriteWhitespace(whitespace);
}
public override void WriteValue(object value)
{
IStreamProvider sp = value as IStreamProvider;
if (sp != null)
{
WriteValue(sp);
}
else
{
WriteBase64InlineIfPresent();
Writer.WriteValue(value);
}
}
public override void WriteValue(string value)
{
// Don't write whitespace after the document element
if (depth == 0 && mimeWriter.WriteState == MimeWriterState.Closed && XmlConverter.IsWhitespace(value))
return;
WriteBase64InlineIfPresent();
Writer.WriteValue(value);
}
public override void WriteValue(bool value)
{
WriteBase64InlineIfPresent();
Writer.WriteValue(value);
}
public override void WriteValue(DateTime value)
{
WriteBase64InlineIfPresent();
Writer.WriteValue(value);
}
public override void WriteValue(double value)
{
WriteBase64InlineIfPresent();
Writer.WriteValue(value);
}
public override void WriteValue(int value)
{
WriteBase64InlineIfPresent();
Writer.WriteValue(value);
}
public override void WriteValue(long value)
{
WriteBase64InlineIfPresent();
Writer.WriteValue(value);
}
#if DECIMAL_FLOAT_API
public override void WriteValue(decimal value)
{
WriteBase64InlineIfPresent();
Writer.WriteValue(value);
}
public override void WriteValue(float value)
{
WriteBase64InlineIfPresent();
Writer.WriteValue(value);
}
#endif
public override void WriteValue(XmlDictionaryString value)
{
// Don't write whitespace after the document element
if (depth == 0 && mimeWriter.WriteState == MimeWriterState.Closed && XmlConverter.IsWhitespace(value.Value))
return;
WriteBase64InlineIfPresent();
Writer.WriteValue(value);
}
public override void WriteXmlnsAttribute(string prefix, string ns)
{
Writer.WriteXmlnsAttribute(prefix, ns);
}
public override void WriteXmlnsAttribute(string prefix, XmlDictionaryString ns)
{
Writer.WriteXmlnsAttribute(prefix, ns);
}
public override string XmlLang
{
get
{
return Writer.XmlLang;
}
}
public override XmlSpace XmlSpace
{
get
{
return Writer.XmlSpace;
}
}
static class MimeBoundaryGenerator
{
static long id;
static string prefix;
static MimeBoundaryGenerator()
{
prefix = string.Concat(Guid.NewGuid().ToString(), "+id=");
}
internal static string Next()
{
long nextId = Interlocked.Increment(ref id);
return String.Format(CultureInfo.InvariantCulture, "{0}{1}", prefix, nextId);
}
}
class MimePart
{
internal IList<MtomBinaryData> binaryData;
internal string contentID;
internal string contentType;
internal string contentTransferEncoding;
internal int sizeInBytes;
internal MimePart(IList<MtomBinaryData> binaryData, string contentID, string contentType, string contentTransferEncoding, int sizeOfBufferedBinaryData, int maxSizeInBytes)
{
this.binaryData = binaryData;
this.contentID = contentID;
this.contentType = contentType ?? MtomGlobals.DefaultContentTypeForBinary;
this.contentTransferEncoding = contentTransferEncoding;
this.sizeInBytes = GetSize(contentID, contentType, contentTransferEncoding, sizeOfBufferedBinaryData, maxSizeInBytes);
}
static int GetSize(string contentID, string contentType, string contentTransferEncoding, int sizeOfBufferedBinaryData, int maxSizeInBytes)
{
int size = XmlMtomWriter.ValidateSizeOfMessage(maxSizeInBytes, 0, MimeGlobals.CRLF.Length * 3);
if (contentTransferEncoding != null)
size += XmlMtomWriter.ValidateSizeOfMessage(maxSizeInBytes, size, MimeWriter.GetHeaderSize(MimeGlobals.ContentTransferEncodingHeader, contentTransferEncoding, maxSizeInBytes));
if (contentType != null)
size += XmlMtomWriter.ValidateSizeOfMessage(maxSizeInBytes, size, MimeWriter.GetHeaderSize(MimeGlobals.ContentTypeHeader, contentType, maxSizeInBytes));
if (contentID != null)
{
size += XmlMtomWriter.ValidateSizeOfMessage(maxSizeInBytes, size, MimeWriter.GetHeaderSize(MimeGlobals.ContentIDHeader, contentID, maxSizeInBytes));
size += XmlMtomWriter.ValidateSizeOfMessage(maxSizeInBytes, size, 2); // include '<' and '>'
}
size += XmlMtomWriter.ValidateSizeOfMessage(maxSizeInBytes, size, sizeOfBufferedBinaryData);
return size;
}
}
}
internal static class MtomGlobals
{
internal static string XopIncludeLocalName = "Include";
internal static string XopIncludeNamespace = "http://www.w3.org/2004/08/xop/include";
internal static string XopIncludePrefix = "xop";
internal static string XopIncludeHrefLocalName = "href";
internal static string XopIncludeHrefNamespace = String.Empty;
internal static string MediaType = "multipart";
internal static string MediaSubtype = "related";
internal static string BoundaryParam = "boundary";
internal static string TypeParam = "type";
internal static string XopMediaType = "application";
internal static string XopMediaSubtype = "xop+xml";
internal static string XopType = "application/xop+xml";
internal static string StartParam = "start";
internal static string StartInfoParam = "start-info";
internal static string ActionParam = "action";
internal static string CharsetParam = "charset";
internal static string MimeContentTypeLocalName = "contentType";
internal static string MimeContentTypeNamespace200406 = "http://www.w3.org/2004/06/xmlmime";
internal static string MimeContentTypeNamespace200505 = "http://www.w3.org/2005/05/xmlmime";
internal static string DefaultContentTypeForBinary = "application/octet-stream";
}
internal static class MimeGlobals
{
internal static string MimeVersionHeader = "MIME-Version";
internal static string DefaultVersion = "1.0";
internal static string ContentIDScheme = "cid:";
internal static string ContentIDHeader = "Content-ID";
internal static string ContentTypeHeader = "Content-Type";
internal static string ContentTransferEncodingHeader = "Content-Transfer-Encoding";
internal static string EncodingBinary = "binary";
internal static string Encoding8bit = "8bit";
internal static byte[] COLONSPACE = new byte[] { (byte)':', (byte)' ' };
internal static byte[] DASHDASH = new byte[] { (byte)'-', (byte)'-' };
internal static byte[] CRLF = new byte[] { (byte)'\r', (byte)'\n' };
// Per RFC2045, preceding CRLF sequence is part of the boundary. MIME boundary tags begin with --
internal static byte[] BoundaryPrefix = new byte[] { (byte)'\r', (byte)'\n', (byte)'-', (byte)'-' };
}
enum MimeWriterState
{
Start,
StartPreface,
StartPart,
Header,
Content,
Closed,
}
internal class MimeWriter
{
Stream stream;
byte[] boundaryBytes;
MimeWriterState state;
BufferedWrite bufferedWrite;
Stream contentStream;
internal MimeWriter(Stream stream, string boundary)
{
if (stream == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("stream");
if (boundary == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("boundary");
this.stream = stream;
this.boundaryBytes = MimeWriter.GetBoundaryBytes(boundary);
this.state = MimeWriterState.Start;
this.bufferedWrite = new BufferedWrite();
}
internal static int GetHeaderSize(string name, string value, int maxSizeInBytes)
{
if (name == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("name");
if (value == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("value");
int size = XmlMtomWriter.ValidateSizeOfMessage(maxSizeInBytes, 0, MimeGlobals.COLONSPACE.Length + MimeGlobals.CRLF.Length);
size += XmlMtomWriter.ValidateSizeOfMessage(maxSizeInBytes, size, name.Length);
size += XmlMtomWriter.ValidateSizeOfMessage(maxSizeInBytes, size, value.Length);
return size;
}
internal static byte[] GetBoundaryBytes(string boundary)
{
byte[] boundaryBytes = new byte[boundary.Length + MimeGlobals.BoundaryPrefix.Length];
for (int i = 0; i < MimeGlobals.BoundaryPrefix.Length; i++)
boundaryBytes[i] = MimeGlobals.BoundaryPrefix[i];
Encoding.ASCII.GetBytes(boundary, 0, boundary.Length, boundaryBytes, MimeGlobals.BoundaryPrefix.Length);
return boundaryBytes;
}
internal MimeWriterState WriteState
{
get
{
return state;
}
}
internal int GetBoundarySize()
{
return this.boundaryBytes.Length;
}
internal void StartPreface()
{
if (state != MimeWriterState.Start)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.MimeWriterInvalidStateForStartPreface, state.ToString())));
state = MimeWriterState.StartPreface;
}
internal void StartPart()
{
switch (state)
{
case MimeWriterState.StartPart:
case MimeWriterState.Closed:
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.MimeWriterInvalidStateForStartPart, state.ToString())));
default:
break;
}
state = MimeWriterState.StartPart;
if (contentStream != null)
{
contentStream.Flush();
contentStream = null;
}
bufferedWrite.Write(boundaryBytes);
bufferedWrite.Write(MimeGlobals.CRLF);
}
internal void Close()
{
switch (state)
{
case MimeWriterState.Closed:
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.MimeWriterInvalidStateForClose, state.ToString())));
default:
break;
}
state = MimeWriterState.Closed;
if (contentStream != null)
{
contentStream.Flush();
contentStream = null;
}
bufferedWrite.Write(boundaryBytes);
bufferedWrite.Write(MimeGlobals.DASHDASH);
bufferedWrite.Write(MimeGlobals.CRLF);
Flush();
}
void Flush()
{
if (bufferedWrite.Length > 0)
{
stream.Write(bufferedWrite.GetBuffer(), 0, bufferedWrite.Length);
bufferedWrite.Reset();
}
}
internal void WriteHeader(string name, string value)
{
if (name == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("name");
if (value == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("value");
switch (state)
{
case MimeWriterState.Start:
case MimeWriterState.Content:
case MimeWriterState.Closed:
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.MimeWriterInvalidStateForHeader, state.ToString())));
default:
break;
}
state = MimeWriterState.Header;
bufferedWrite.Write(name);
bufferedWrite.Write(MimeGlobals.COLONSPACE);
bufferedWrite.Write(value);
bufferedWrite.Write(MimeGlobals.CRLF);
}
internal Stream GetContentStream()
{
switch (state)
{
case MimeWriterState.Start:
case MimeWriterState.Content:
case MimeWriterState.Closed:
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.MimeWriterInvalidStateForContent, state.ToString())));
default:
break;
}
state = MimeWriterState.Content;
bufferedWrite.Write(MimeGlobals.CRLF);
Flush();
contentStream = stream;
return contentStream;
}
}
internal class BufferedWrite
{
byte[] buffer;
int offset;
internal BufferedWrite()
: this(256)
{
}
internal BufferedWrite(int initialSize)
{
buffer = new byte[initialSize];
}
void EnsureBuffer(int count)
{
int currSize = buffer.Length;
if (count > currSize - offset)
{
int newSize = currSize;
do
{
if (newSize == Int32.MaxValue)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(SR.GetString(SR.WriteBufferOverflow)));
newSize = (newSize < Int32.MaxValue / 2) ? newSize * 2 : Int32.MaxValue;
}
while (count > newSize - offset);
byte[] newBuffer = new byte[newSize];
Buffer.BlockCopy(buffer, 0, newBuffer, 0, offset);
buffer = newBuffer;
}
}
internal int Length
{
get
{
return offset;
}
}
internal byte[] GetBuffer()
{
return buffer;
}
internal void Reset()
{
offset = 0;
}
internal void Write(byte[] value)
{
Write(value, 0, value.Length);
}
internal void Write(byte[] value, int index, int count)
{
EnsureBuffer(count);
Buffer.BlockCopy(value, index, buffer, offset, count);
offset += count;
}
internal void Write(string value)
{
Write(value, 0, value.Length);
}
internal void Write(string value, int index, int count)
{
EnsureBuffer(count);
for (int i = 0; i < count; i++)
{
char c = value[index + i];
if ((ushort)c > 0xFF)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new FormatException(SR.GetString(SR.MimeHeaderInvalidCharacter, c, ((int)c).ToString("X", CultureInfo.InvariantCulture))));
buffer[offset + i] = (byte)c;
}
offset += count;
}
#if NO
internal void Write(byte value)
{
EnsureBuffer(1);
buffer[offset++] = value;
}
internal void Write(char value)
{
EnsureBuffer(1);
if ((ushort)value > 0xFF)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new FormatException(SR.GetString(SR.MimeHeaderInvalidCharacter, value, ((int)value).ToString("X", CultureInfo.InvariantCulture)))));
buffer[offset++] = (byte)value;
}
internal void Write(int value)
{
Write(value.ToString());
}
internal void Write(char[] value)
{
Write(value, 0, value.Length);
}
internal void Write(char[] value, int index, int count)
{
EnsureBuffer(count);
for (int i = 0; i < count; i++)
{
char c = value[index + i];
if ((ushort)c > 0xFF)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new FormatException(SR.GetString(SR.MimeHeaderInvalidCharacter, c, ((int)c).ToString("X", CultureInfo.InvariantCulture)))));
buffer[offset + i] = (byte)c;
}
offset += count;
}
#endif
}
enum MtomBinaryDataType { Provider, Segment }
class MtomBinaryData
{
internal MtomBinaryDataType type;
internal IStreamProvider provider;
internal byte[] chunk;
internal MtomBinaryData(IStreamProvider provider)
{
this.type = MtomBinaryDataType.Provider;
this.provider = provider;
}
internal MtomBinaryData(byte[] buffer, int offset, int count)
{
this.type = MtomBinaryDataType.Segment;
this.chunk = new byte[count];
Buffer.BlockCopy(buffer, offset, this.chunk, 0, count);
}
internal long Length
{
get
{
if (this.type == MtomBinaryDataType.Segment)
return this.chunk.Length;
return -1;
}
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.