context
stringlengths 2.52k
185k
| gt
stringclasses 1
value |
---|---|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics.Contracts;
using System.Globalization;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
namespace System
{
[Serializable]
[CLSCompliant(false)] [StructLayout(LayoutKind.Sequential)]
[TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")]
public struct SByte : IComparable, IConvertible, IFormattable, IComparable<SByte>, IEquatable<SByte>
{
private sbyte m_value; // Do not rename (binary serialization)
// The maximum value that a Byte may represent: 127.
public const sbyte MaxValue = (sbyte)0x7F;
// The minimum value that a Byte may represent: -128.
public const sbyte MinValue = unchecked((sbyte)0x80);
// Compares this object to another object, returning an integer that
// indicates the relationship.
// Returns a value less than zero if this object
// null is considered to be less than any instance.
// If object is not of type SByte, this method throws an ArgumentException.
//
public int CompareTo(Object obj)
{
if (obj == null)
{
return 1;
}
if (!(obj is SByte))
{
throw new ArgumentException(SR.Arg_MustBeSByte);
}
return m_value - ((SByte)obj).m_value;
}
public int CompareTo(SByte value)
{
return m_value - value;
}
// Determines whether two Byte objects are equal.
public override bool Equals(Object obj)
{
if (!(obj is SByte))
{
return false;
}
return m_value == ((SByte)obj).m_value;
}
[NonVersionable]
public bool Equals(SByte obj)
{
return m_value == obj;
}
// Gets a hash code for this instance.
public override int GetHashCode()
{
return ((int)m_value ^ (int)m_value << 8);
}
// Provides a string representation of a byte.
public override String ToString()
{
Contract.Ensures(Contract.Result<String>() != null);
return Number.FormatInt32(m_value, null, NumberFormatInfo.CurrentInfo);
}
public String ToString(IFormatProvider provider)
{
Contract.Ensures(Contract.Result<String>() != null);
return Number.FormatInt32(m_value, null, NumberFormatInfo.GetInstance(provider));
}
public String ToString(String format)
{
Contract.Ensures(Contract.Result<String>() != null);
return ToString(format, NumberFormatInfo.CurrentInfo);
}
public String ToString(String format, IFormatProvider provider)
{
Contract.Ensures(Contract.Result<String>() != null);
return ToString(format, NumberFormatInfo.GetInstance(provider));
}
private String ToString(String format, NumberFormatInfo info)
{
Contract.Ensures(Contract.Result<String>() != null);
if (m_value < 0 && format != null && format.Length > 0 && (format[0] == 'X' || format[0] == 'x'))
{
uint temp = (uint)(m_value & 0x000000FF);
return Number.FormatUInt32(temp, format, info);
}
return Number.FormatInt32(m_value, format, info);
}
[CLSCompliant(false)]
public static sbyte Parse(String s)
{
return Parse(s, NumberStyles.Integer, NumberFormatInfo.CurrentInfo);
}
[CLSCompliant(false)]
public static sbyte Parse(String s, NumberStyles style)
{
NumberFormatInfo.ValidateParseStyleInteger(style);
return Parse(s, style, NumberFormatInfo.CurrentInfo);
}
[CLSCompliant(false)]
public static sbyte Parse(String s, IFormatProvider provider)
{
return Parse(s, NumberStyles.Integer, NumberFormatInfo.GetInstance(provider));
}
// Parses a signed byte from a String in the given style. If
// a NumberFormatInfo isn't specified, the current culture's
// NumberFormatInfo is assumed.
//
[CLSCompliant(false)]
public static sbyte Parse(String s, NumberStyles style, IFormatProvider provider)
{
NumberFormatInfo.ValidateParseStyleInteger(style);
return Parse(s, style, NumberFormatInfo.GetInstance(provider));
}
private static sbyte Parse(String s, NumberStyles style, NumberFormatInfo info)
{
int i = 0;
try
{
i = Number.ParseInt32(s, style, info);
}
catch (OverflowException e)
{
throw new OverflowException(SR.Overflow_SByte, e);
}
if ((style & NumberStyles.AllowHexSpecifier) != 0)
{ // We are parsing a hexadecimal number
if ((i < 0) || i > Byte.MaxValue)
{
throw new OverflowException(SR.Overflow_SByte);
}
return (sbyte)i;
}
if (i < MinValue || i > MaxValue) throw new OverflowException(SR.Overflow_SByte);
return (sbyte)i;
}
[CLSCompliant(false)]
public static bool TryParse(String s, out SByte result)
{
return TryParse(s, NumberStyles.Integer, NumberFormatInfo.CurrentInfo, out result);
}
[CLSCompliant(false)]
public static bool TryParse(String s, NumberStyles style, IFormatProvider provider, out SByte result)
{
NumberFormatInfo.ValidateParseStyleInteger(style);
return TryParse(s, style, NumberFormatInfo.GetInstance(provider), out result);
}
private static bool TryParse(String s, NumberStyles style, NumberFormatInfo info, out SByte result)
{
result = 0;
int i;
if (!Number.TryParseInt32(s, style, info, out i))
{
return false;
}
if ((style & NumberStyles.AllowHexSpecifier) != 0)
{ // We are parsing a hexadecimal number
if ((i < 0) || i > Byte.MaxValue)
{
return false;
}
result = (sbyte)i;
return true;
}
if (i < MinValue || i > MaxValue)
{
return false;
}
result = (sbyte)i;
return true;
}
//
// IConvertible implementation
//
public TypeCode GetTypeCode()
{
return TypeCode.SByte;
}
bool IConvertible.ToBoolean(IFormatProvider provider)
{
return Convert.ToBoolean(m_value);
}
char IConvertible.ToChar(IFormatProvider provider)
{
return Convert.ToChar(m_value);
}
sbyte IConvertible.ToSByte(IFormatProvider provider)
{
return m_value;
}
byte IConvertible.ToByte(IFormatProvider provider)
{
return Convert.ToByte(m_value);
}
short IConvertible.ToInt16(IFormatProvider provider)
{
return Convert.ToInt16(m_value);
}
ushort IConvertible.ToUInt16(IFormatProvider provider)
{
return Convert.ToUInt16(m_value);
}
int IConvertible.ToInt32(IFormatProvider provider)
{
return m_value;
}
uint IConvertible.ToUInt32(IFormatProvider provider)
{
return Convert.ToUInt32(m_value);
}
long IConvertible.ToInt64(IFormatProvider provider)
{
return Convert.ToInt64(m_value);
}
ulong IConvertible.ToUInt64(IFormatProvider provider)
{
return Convert.ToUInt64(m_value);
}
float IConvertible.ToSingle(IFormatProvider provider)
{
return Convert.ToSingle(m_value);
}
double IConvertible.ToDouble(IFormatProvider provider)
{
return Convert.ToDouble(m_value);
}
Decimal IConvertible.ToDecimal(IFormatProvider provider)
{
return Convert.ToDecimal(m_value);
}
DateTime IConvertible.ToDateTime(IFormatProvider provider)
{
throw new InvalidCastException(SR.Format(SR.InvalidCast_FromTo, "SByte", "DateTime"));
}
Object IConvertible.ToType(Type type, IFormatProvider provider)
{
return Convert.DefaultToType((IConvertible)this, type, provider);
}
}
}
| |
/*
* Copyright (c) 2014 All Rights Reserved by the SDL Group.
*
* 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.Management.Automation;
using Trisoft.ISHRemote.Objects;
using Trisoft.ISHRemote.Objects.Public;
using Trisoft.ISHRemote.Exceptions;
using Trisoft.ISHRemote.HelperClasses;
using System.Linq;
namespace Trisoft.ISHRemote.Cmdlets.DocumentObj
{
/// <summary>
/// <para type="synopsis">Retrieves the metadata and optionally blob of document objects</para>
/// <para type="description">Gets IshObject entries through logical id filtering or language card ids, optionally providing the blob.</para>
/// <para type="description">Uses DocumentObj25 API to retrieve ishobjects.</para>
/// <para type="description">The Get-IshDocumentObj cmdlet retrieves metadata of the document objects that are passed through the pipeline or determined via provided parameters. This commandlet allows to retrieve all types of objects(Illustrations, Maps, etc. ), except for publication(outputs). For publication(outputs) you need to use Get-IshPublicationOutput.</para>
/// </summary>
/// <example>
/// <code>
/// $ishSession = New-IshSession -WsBaseUrl "https://example.com/InfoShareWS/" -PSCredential Admin
/// Get-IshDocumentObj -LogicalId ISHPUBLILLUSTRATIONMISSING
/// </code>
/// <para>New-IshSession will submit into SessionState, so it can be reused by this cmdlet. Returns all versions/language of object identified through LogicalId Get-IshDocumentObj -LogicalId ISHPUBLILLUSTRATIONMISSING (typically also GUIDs).</para>
/// </example>
[Cmdlet(VerbsCommon.Get, "IshDocumentObj", SupportsShouldProcess = false)]
[OutputType(typeof(IshDocumentObj))]
public sealed class GetIshDocumentObj : DocumentObjCmdlet
{
/// <summary>
/// <para type="description">The IshSession variable holds the authentication and contract information. This object can be initialized using the New-IshSession cmdlet.</para>
/// </summary>
[Parameter(Mandatory =false, ValueFromPipelineByPropertyName = false, ParameterSetName = "ParameterGroup")]
[Parameter(Mandatory =false, ValueFromPipelineByPropertyName = false, ParameterSetName = "IshObjectsGroup")]
[ValidateNotNullOrEmpty]
public IshSession IshSession { get; set; }
/// <summary>
/// <para type="description">The logical identifiers of the document objects for which to retrieve the metadata</para>
/// </summary>
[Parameter(Mandatory = true, ValueFromPipelineByPropertyName = false, ParameterSetName = "ParameterGroup"), ValidateNotNullOrEmpty]
public string[] LogicalId { get; set; }
/// <summary>
/// <para type="description">The metadata filter with the filter fields to limit the amount of objects returned. Default is no filtering.</para>
/// </summary>
[Parameter(Mandatory = false, ValueFromPipelineByPropertyName = false, ParameterSetName = "ParameterGroup")]
[Parameter(Mandatory = false, ValueFromPipelineByPropertyName = false, ParameterSetName = "IshObjectsGroup")]
[ValidateNotNullOrEmpty]
public IshField[] MetadataFilter { get; set; }
/// <summary>
/// <para type="description">The metadata fields to retrieve</para>
/// </summary>
[Parameter(Mandatory = false, ValueFromPipelineByPropertyName = false, ParameterSetName = "ParameterGroup")]
[Parameter(Mandatory = false, ValueFromPipelineByPropertyName = false, ParameterSetName = "IshObjectsGroup")]
[ValidateNotNullOrEmpty]
public IshField[] RequestedMetadata { get; set; }
/// <summary>
/// <para type="description">The status filter to limit the amount of objects returned. Default is no filtering.</para>
/// </summary>
[Parameter(Mandatory = false, ValueFromPipelineByPropertyName = false, ParameterSetName = "ParameterGroup")]
[Parameter(Mandatory = false, ValueFromPipelineByPropertyName = false, ParameterSetName = "IshObjectsGroup")]
[ValidateNotNullOrEmpty]
public Enumerations.StatusFilter StatusFilter
{
get { return _statusFilter; }
set { _statusFilter = value; }
}
/// <summary>
/// <para type="description">Switch patameter that specifies if the return objects should hold the blob (ishdata) sections, potentially conditionally published if IshFeature was passed</para>
/// </summary>
[Parameter(Mandatory = false, ParameterSetName = "ParameterGroup")]
[Parameter(Mandatory = false, ParameterSetName = "IshObjectsGroup")]
public SwitchParameter IncludeData
{
get { return _includeData; }
set { _includeData = value; }
}
/// <summary>
/// <para type="description">The condition context to use for conditional filtering. If no context is provided, the elements containing ishcondition attributes will always remain in the data content. You can use the Set-IshFeature cmdlet to create a condition context.</para>
/// </summary>
[Parameter(Mandatory = false, ValueFromPipelineByPropertyName = false, ParameterSetName = "ParameterGroup")]
[Parameter(Mandatory = false, ValueFromPipelineByPropertyName = false, ParameterSetName = "IshObjectsGroup")]
public IshFeature[] IshFeature { get; set; }
/// <summary>
/// <para type="description">Array with the objects for which to retrieve the metadata. This array can be passed through the pipeline or explicitly passed via the parameter.</para>
/// </summary>
[Parameter(Mandatory = true, ValueFromPipeline = true, ParameterSetName = "IshObjectsGroup")]
[AllowEmptyCollection]
public IshObject[] IshObject { get; set; }
#region Private fields
/// <summary>
/// Private field to store the IshType and provide a default for non-mandatory parameters
/// </summary>
private Enumerations.StatusFilter _statusFilter = Enumerations.StatusFilter.ISHNoStatusFilter;
/// <summary>
/// Switch patameter that specifies if the return objects should hold the blob (ishdata) sections, potentially conditionally published if IshFeature was passed
/// </summary>
private bool _includeData = false;
#endregion
protected override void BeginProcessing()
{
if (IshSession == null) { IshSession = (IshSession)SessionState.PSVariable.GetValue(ISHRemoteSessionStateIshSession); }
if (IshSession == null) { throw new ArgumentException(ISHRemoteSessionStateIshSessionException); }
WriteDebug($"Using IshSession[{IshSession.Name}] from SessionState.{ISHRemoteSessionStateIshSession}");
base.BeginProcessing();
}
/// <summary>
/// Process the Get-IshDocumentObj commandlet.
/// </summary>
/// <exception cref="TrisoftAutomationException"></exception>
/// <exception cref="Exception"></exception>
/// <remarks>Writes an <see cref="IshObject"/> array to the pipeline.</remarks>
protected override void ProcessRecord()
{
try
{
// 1. Validating the input
WriteDebug("Validating");
List<IshObject> returnIshObjects = new List<IshObject>();
if (IshObject != null && IshObject.Length == 0)
{
// Do nothing
WriteVerbose("IshObject is empty, so nothing to retrieve");
}
else
{
WriteDebug("Retrieving");
IshFields requestedMetadata = IshSession.IshTypeFieldSetup.ToIshRequestedMetadataFields(IshSession.DefaultRequestedMetadata, ISHType, new IshFields(RequestedMetadata), Enumerations.ActionMode.Read);
if (IshObject != null)
{
// 2a. Retrieve using LngCardIds
IshObjects ishObjects = new IshObjects(IshObject);
var lngCardIds =
ishObjects.Objects.Select(
ishObject => Convert.ToInt64(ishObject.ObjectRef[Enumerations.ReferenceType.Lng])).ToList();
if (!_includeData)
{
//RetrieveMetadata
WriteDebug("Retrieving CardIds.length[{lngCardIds.Count}] RequestedMetadata.length[{requestedMetadata.ToXml().Length}] 0/{lngCardIds.Count}");
// Devides the list of language card ids in different lists that all have maximally MetadataBatchSize elements
List<List<long>> devidedlngCardIdsList = DevideListInBatches<long>(lngCardIds, IshSession.MetadataBatchSize);
int currentLngCardIdCount = 0;
foreach (List<long> lngCardIdBatch in devidedlngCardIdsList)
{
// Process language card ids in batches
string xmlIshObjects = IshSession.DocumentObj25.RetrieveMetadataByIshLngRefs(
lngCardIdBatch.ToArray(),
requestedMetadata.ToXml());
IshObjects retrievedObjects = new IshObjects(ISHType, xmlIshObjects);
returnIshObjects.AddRange(retrievedObjects.Objects);
currentLngCardIdCount += lngCardIdBatch.Count;
WriteDebug($"Retrieving CardIds.length[{lngCardIdBatch.Count}] RequestedMetadata.length[{requestedMetadata.ToXml().Length}] including data {currentLngCardIdCount}/{lngCardIds.Count}");
}
}
else
{
//RetrieveObjects
WriteDebug($"Retrieving CardIds.length[{lngCardIds.Count}] RequestedMetadata.length[{requestedMetadata.ToXml().Length}] including data 0/{lngCardIds.Count}");
IshFeatures productDefinitionFeatures = new IshFeatures(IshFeature);
// Devides the list of language card ids in different lists that all have maximally BlobBatchSize elements
List<List<long>> devidedlngCardIdsList = DevideListInBatches<long>(lngCardIds, IshSession.BlobBatchSize);
int currentLngCardIdCount = 0;
foreach (List<long> lngCardIdBatch in devidedlngCardIdsList)
{
// Process language card ids in batches
string xmlIshObjects = IshSession.DocumentObj25.RetrieveObjectsByIshLngRefs(
lngCardIdBatch.ToArray(),
productDefinitionFeatures.ToXml(),
requestedMetadata.ToXml());
IshObjects retrievedObjects = new IshObjects(ISHType, xmlIshObjects);
returnIshObjects.AddRange(retrievedObjects.Objects);
currentLngCardIdCount += lngCardIdBatch.Count;
WriteDebug($"Retrieving CardIds.length[{lngCardIdBatch.Count}] RequestedMetadata.length[{requestedMetadata.ToXml().Length}] including data {currentLngCardIdCount}/{lngCardIds.Count}");
}
}
}
else
{
// 2b. Retrieve using LogicalId
IshFields metadataFilter = new IshFields(MetadataFilter);
var statusFilter = EnumConverter.ToStatusFilter<DocumentObj25ServiceReference.StatusFilter>(StatusFilter);
if (!_includeData)
{
//RetrieveMetadata
WriteDebug($"Retrieving LogicalId.length[{LogicalId.Length}] StatusFilter[{statusFilter}] MetadataFilter.length[{metadataFilter.ToXml().Length}] RequestedMetadata.length[{requestedMetadata.ToXml().Length}] 0/{LogicalId.Length}");
// Devides the list of language card ids in different lists that all have maximally MetadataBatchSize elements
List<List<string>> devidedlogicalIdsList = DevideListInBatches<string>(LogicalId.ToList(), IshSession.MetadataBatchSize);
int currentLogicalIdCount = 0;
foreach (List<string> logicalIdBatch in devidedlogicalIdsList)
{
// Process language card ids in batches
string xmlIshObjects = IshSession.DocumentObj25.RetrieveMetadata(
logicalIdBatch.ToArray(),
statusFilter,
metadataFilter.ToXml(),
requestedMetadata.ToXml());
IshObjects retrievedObjects = new IshObjects(ISHType, xmlIshObjects);
returnIshObjects.AddRange(retrievedObjects.Objects);
currentLogicalIdCount += logicalIdBatch.Count;
WriteDebug($"Retrieving LogicalId.length[{logicalIdBatch.Count}] StatusFilter[{statusFilter}] MetadataFilter.length[{metadataFilter.ToXml().Length}] RequestedMetadata.length[{requestedMetadata.ToXml().Length}] {currentLogicalIdCount}/{LogicalId.Length}");
}
}
else
{
//RetrieveObjects
WriteDebug($"Retrieving LogicalId.length[{LogicalId.Length}] StatusFilter[{statusFilter}] MetadataFilter.length[{metadataFilter.ToXml().Length}] RequestedMetadata.length[{requestedMetadata.ToXml().Length}] 0/{LogicalId.Length}");
IshFeatures productDefinitionFeatures = new IshFeatures(IshFeature);
// Devides the list of language card ids in different lists that all have maximally BlobBatchSize elements
List<List<string>> devidedlogicalIdsList = DevideListInBatches<string>(LogicalId.ToList(), IshSession.BlobBatchSize);
int currentLogicalIdCount = 0;
foreach (List<string> logicalIdBatch in devidedlogicalIdsList)
{
// Process language card ids in batches
string xmlIshObjects = IshSession.DocumentObj25.RetrieveObjects(
logicalIdBatch.ToArray(),
statusFilter,
metadataFilter.ToXml(),
productDefinitionFeatures.ToXml(),
requestedMetadata.ToXml());
IshObjects retrievedObjects = new IshObjects(ISHType, xmlIshObjects);
returnIshObjects.AddRange(retrievedObjects.Objects);
currentLogicalIdCount += logicalIdBatch.Count;
WriteDebug($"Retrieving LogicalId.length[{logicalIdBatch.Count}] StatusFilter[{statusFilter}] MetadataFilter.length[{metadataFilter.ToXml().Length}] RequestedMetadata.length[{requestedMetadata.ToXml().Length}] {currentLogicalIdCount}/{LogicalId.Length}");
}
}
}
}
WriteVerbose("returned object count[" + returnIshObjects.Count + "]");
WriteObject(IshSession, ISHType, returnIshObjects.ConvertAll(x => (IshBaseObject)x), true);
}
catch (TrisoftAutomationException trisoftAutomationException)
{
ThrowTerminatingError(new ErrorRecord(trisoftAutomationException, base.GetType().Name, ErrorCategory.InvalidOperation, null));
}
catch (Exception exception)
{
ThrowTerminatingError(new ErrorRecord(exception, base.GetType().Name, ErrorCategory.NotSpecified, null));
}
}
}
}
| |
/*
* Copyright (c) 2006, Clutch, Inc.
* Original Author: Jeff Cesnik
* 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.
* - Neither the name of the openmetaverse.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.
*/
using System;
using System.Net;
using System.Net.Sockets;
using System.Threading;
namespace OpenMetaverse
{
/// <summary>
///
/// </summary>
public abstract class UDPBase
{
// these abstract methods must be implemented in a derived class to actually do
// something with the packets that are sent and received.
protected abstract void PacketReceived(UDPPacketBuffer buffer);
protected abstract void PacketSent(UDPPacketBuffer buffer, int bytesSent);
// the port to listen on
internal int udpPort;
// the UDP socket
private Socket udpSocket;
// the ReaderWriterLock is used solely for the purposes of shutdown (Stop()).
// since there are potentially many "reader" threads in the internal .NET IOCP
// thread pool, this is a cheaper synchronization primitive than using
// a Mutex object. This allows many UDP socket "reads" concurrently - when
// Stop() is called, it attempts to obtain a writer lock which will then
// wait until all outstanding operations are completed before shutting down.
// this avoids the problem of closing the socket with outstanding operations
// and trying to catch the inevitable ObjectDisposedException.
#if PocketPC
private OpenMetaverse.ReaderWriterLock rwLock = new OpenMetaverse.ReaderWriterLock();
#else
private ReaderWriterLock rwLock = new ReaderWriterLock();
#endif
// number of outstanding operations. This is a reference count
// which we use to ensure that the threads exit cleanly. Note that
// we need this because the threads will potentially still need to process
// data even after the socket is closed.
private int rwOperationCount = 0;
// the all important shutdownFlag. This is synchronized through the ReaderWriterLock.
private volatile bool shutdownFlag = true;
//
private IPEndPoint remoteEndPoint = null;
/// <summary>
/// Initialize the UDP packet handler in server mode
/// </summary>
/// <param name="port">Port to listening for incoming UDP packets on</param>
public UDPBase(int port)
{
udpPort = port;
}
/// <summary>
/// Initialize the UDP packet handler in client mode
/// </summary>
/// <param name="endPoint">Remote UDP server to connect to</param>
public UDPBase(IPEndPoint endPoint)
{
remoteEndPoint = endPoint;
udpPort = 0;
}
/// <summary>
///
/// </summary>
public void Start()
{
if (shutdownFlag)
{
if (remoteEndPoint == null)
{
// Server mode
// create and bind the socket
IPEndPoint ipep = new IPEndPoint(Settings.BIND_ADDR, udpPort);
udpSocket = new Socket(
AddressFamily.InterNetwork,
SocketType.Dgram,
ProtocolType.Udp);
udpSocket.Bind(ipep);
}
else
{
// Client mode
IPEndPoint ipep = new IPEndPoint(Settings.BIND_ADDR, udpPort);
udpSocket = new Socket(
AddressFamily.InterNetwork,
SocketType.Dgram,
ProtocolType.Udp);
udpSocket.Bind(ipep);
//udpSocket.Connect(remoteEndPoint);
}
// we're not shutting down, we're starting up
shutdownFlag = false;
// kick off an async receive. The Start() method will return, the
// actual receives will occur asynchronously and will be caught in
// AsyncEndRecieve().
AsyncBeginReceive();
}
}
/// <summary>
///
/// </summary>
public void Stop()
{
if (!shutdownFlag)
{
// wait indefinitely for a writer lock. Once this is called, the .NET runtime
// will deny any more reader locks, in effect blocking all other send/receive
// threads. Once we have the lock, we set shutdownFlag to inform the other
// threads that the socket is closed.
rwLock.AcquireWriterLock(-1);
shutdownFlag = true;
udpSocket.Close();
rwLock.ReleaseWriterLock();
// wait for any pending operations to complete on other
// threads before exiting.
const int FORCE_STOP = 100;
int i = 0;
while (rwOperationCount > 0 && i < FORCE_STOP)
{
Thread.Sleep(10);
++i;
}
if (i >= FORCE_STOP)
{
Logger.Log("UDPBase.Stop() forced shutdown while waiting on pending operations",
Helpers.LogLevel.Warning);
}
}
}
/// <summary>
///
/// </summary>
public bool IsRunning
{
get { return !shutdownFlag; }
}
private void AsyncBeginReceive()
{
// this method actually kicks off the async read on the socket.
// we aquire a reader lock here to ensure that no other thread
// is trying to set shutdownFlag and close the socket.
rwLock.AcquireReaderLock(-1);
if (!shutdownFlag)
{
// increment the count of pending operations
Interlocked.Increment(ref rwOperationCount);
// allocate a packet buffer
//WrappedObject<UDPPacketBuffer> wrappedBuffer = Pool.CheckOut();
UDPPacketBuffer buf = new UDPPacketBuffer();
try
{
// kick off an async read
udpSocket.BeginReceiveFrom(
//wrappedBuffer.Instance.Data,
buf.Data,
0,
UDPPacketBuffer.BUFFER_SIZE,
SocketFlags.None,
//ref wrappedBuffer.Instance.RemoteEndPoint,
ref buf.RemoteEndPoint,
new AsyncCallback(AsyncEndReceive),
//wrappedBuffer);
buf);
}
catch (SocketException)
{
// something bad happened
//Logger.Log(
// "A SocketException occurred in UDPServer.AsyncBeginReceive()",
// Helpers.LogLevel.Error, se);
// an error occurred, therefore the operation is void. Decrement the reference count.
Interlocked.Decrement(ref rwOperationCount);
}
}
// we're done with the socket for now, release the reader lock.
rwLock.ReleaseReaderLock();
}
private void AsyncEndReceive(IAsyncResult iar)
{
// Asynchronous receive operations will complete here through the call
// to AsyncBeginReceive
// aquire a reader lock
rwLock.AcquireReaderLock(-1);
if (!shutdownFlag)
{
// start another receive - this keeps the server going!
AsyncBeginReceive();
// get the buffer that was created in AsyncBeginReceive
// this is the received data
//WrappedObject<UDPPacketBuffer> wrappedBuffer = (WrappedObject<UDPPacketBuffer>)iar.AsyncState;
//UDPPacketBuffer buffer = wrappedBuffer.Instance;
UDPPacketBuffer buffer = (UDPPacketBuffer)iar.AsyncState;
try
{
// get the length of data actually read from the socket, store it with the
// buffer
buffer.DataLength = udpSocket.EndReceiveFrom(iar, ref buffer.RemoteEndPoint);
// this operation is now complete, decrement the reference count
Interlocked.Decrement(ref rwOperationCount);
// we're done with the socket, release the reader lock
rwLock.ReleaseReaderLock();
// call the abstract method PacketReceived(), passing the buffer that
// has just been filled from the socket read.
PacketReceived(buffer);
}
catch (SocketException)
{
// an error occurred, therefore the operation is void. Decrement the reference count.
Interlocked.Decrement(ref rwOperationCount);
// we're done with the socket for now, release the reader lock.
rwLock.ReleaseReaderLock();
}
finally
{
//wrappedBuffer.Dispose();
}
}
else
{
// nothing bad happened, but we are done with the operation
// decrement the reference count and release the reader lock
Interlocked.Decrement(ref rwOperationCount);
rwLock.ReleaseReaderLock();
}
}
public void AsyncBeginSend(UDPPacketBuffer buf)
{
rwLock.AcquireReaderLock(-1);
if (!shutdownFlag)
{
try
{
Interlocked.Increment(ref rwOperationCount);
udpSocket.BeginSendTo(
buf.Data,
0,
buf.DataLength,
SocketFlags.None,
buf.RemoteEndPoint,
new AsyncCallback(AsyncEndSend),
buf);
}
catch (SocketException)
{
//Logger.Log(
// "A SocketException occurred in UDPServer.AsyncBeginSend()",
// Helpers.LogLevel.Error, se);
}
}
rwLock.ReleaseReaderLock();
}
private void AsyncEndSend(IAsyncResult iar)
{
rwLock.AcquireReaderLock(-1);
if (!shutdownFlag)
{
UDPPacketBuffer buffer = (UDPPacketBuffer)iar.AsyncState;
try
{
int bytesSent = udpSocket.EndSendTo(iar);
// note that call to the abstract PacketSent() method - we are passing the number
// of bytes sent in a separate parameter, since we can't use buffer.DataLength which
// is the number of bytes to send (or bytes received depending upon whether this
// buffer was part of a send or a receive).
PacketSent(buffer, bytesSent);
}
catch (SocketException)
{
//Logger.Log(
// "A SocketException occurred in UDPServer.AsyncEndSend()",
// Helpers.LogLevel.Error, se);
}
}
Interlocked.Decrement(ref rwOperationCount);
rwLock.ReleaseReaderLock();
}
}
}
| |
/*
* 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.Text;
using System.IO;
using System.Collections.Generic;
using System.Reflection;
using log4net;
using Tools;
using OpenSim.Region.Framework.Interfaces;
namespace OpenSim.Region.ScriptEngine.Shared.CodeTools
{
public class CSCodeGenerator : ICodeConverter
{
// private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private static yyLSLSyntax yyLSL = new yyLSLSyntax();
private SYMBOL m_astRoot = null;
private Dictionary<KeyValuePair<int, int>, KeyValuePair<int, int>> m_positionMap;
private int m_braceCount; // for indentation
private int m_CSharpLine; // the current line of generated C# code
private int m_CSharpCol; // the current column of generated C# code
private List<string> m_warnings = new List<string>();
private IScriptModuleComms m_comms = null;
private bool m_insertCoopTerminationChecks;
private static string m_coopTerminationCheck = "opensim_reserved_CheckForCoopTermination();";
/// <summary>
/// Keep a record of the previous node when we do the parsing.
/// </summary>
/// <remarks>
/// We do this here because the parser generated by CSTools does not retain a reference to its parent node.
/// The previous node is required so we can correctly insert co-op termination checks when required.
/// </remarks>
// private SYMBOL m_previousNode;
/// <summary>
/// Creates an 'empty' CSCodeGenerator instance.
/// </summary>
public CSCodeGenerator()
{
m_comms = null;
ResetCounters();
}
public CSCodeGenerator(IScriptModuleComms comms, bool insertCoopTerminationChecks)
{
m_comms = comms;
m_insertCoopTerminationChecks = insertCoopTerminationChecks;
ResetCounters();
}
/// <summary>
/// Get the mapping between LSL and C# line/column number.
/// </summary>
/// <returns>Dictionary\<KeyValuePair\<int, int\>, KeyValuePair\<int, int\>\>.</returns>
public Dictionary<KeyValuePair<int, int>, KeyValuePair<int, int>> PositionMap
{
get { return m_positionMap; }
}
/// <summary>
/// Get the mapping between LSL and C# line/column number.
/// </summary>
/// <returns>SYMBOL pointing to root of the abstract syntax tree.</returns>
public SYMBOL ASTRoot
{
get { return m_astRoot; }
}
public void Clear()
{
m_astRoot.kids = null;
m_astRoot.yylx = null;
m_astRoot.yyps = null;
m_astRoot = null;
m_positionMap = null;
m_warnings.Clear();
m_comms = null;
}
/// <summary>
/// Resets various counters and metadata.
/// </summary>
private void ResetCounters()
{
m_braceCount = 0;
m_CSharpLine = 0;
m_CSharpCol = 1;
m_positionMap = new Dictionary<KeyValuePair<int, int>, KeyValuePair<int, int>>();
m_astRoot = null;
}
public string Convert(string script)
{
StringBuilder sb = new StringBuilder(4096);
Convert(script, sb);
return sb.ToString();
}
/// <summary>
/// Generate the code from the AST we have.
/// </summary>
/// <param name="script">The LSL source as a string.</param>
/// <returns>String containing the generated C# code.</returns>
public void Convert(string script, StringBuilder sb)
{
// m_log.DebugFormat("[CS CODE GENERATOR]: Converting to C#\n{0}", script);
m_warnings.Clear();
ResetCounters();
ErrorHandler errorHandler = new ErrorHandler(true);
Parser p = new LSLSyntax(yyLSL, errorHandler);
LSL2CSCodeTransformer codeTransformer;
try
{
codeTransformer = new LSL2CSCodeTransformer(p.Parse(script));
}
catch (CSToolsException e)
{
string message;
// LL start numbering lines at 0 - geeks!
// Also need to subtract one line we prepend!
//
string emessage = e.Message;
string slinfo = e.slInfo.ToString();
// Remove wrong line number info
//
if (emessage.StartsWith(slinfo+": "))
emessage = emessage.Substring(slinfo.Length+2);
message = String.Format("({0},{1}) {2}",
e.slInfo.lineNumber - 1,
e.slInfo.charPosition - 1, emessage);
throw new Exception(message);
}
m_astRoot = codeTransformer.Transform();
// standard preamble
m_braceCount++;
m_braceCount++;
// line number
m_CSharpLine += 10;
// here's the payload
sb.Append("\n");
foreach (SYMBOL s in m_astRoot.kids)
GenerateNodeToSB(m_astRoot, s, sb);
codeTransformer = null;
p.m_lexer.m_buf=null;
p.m_lexer.yytext = null;
p.m_lexer = null;
p.m_symbols = null;
p = null;
errorHandler = null;
// close braces!
// m_braceCount--;
//retstr += GenerateIndentedLine("}");
// m_braceCount--;
//retstr += GenerateLine("}");
// Removes all carriage return characters which may be generated in Windows platform. Is there
// cleaner way of doing this?
// sb.Replace("\r", "");
}
/// <summary>
/// Get the set of warnings generated during compilation.
/// </summary>
/// <returns></returns>
public string[] GetWarnings()
{
return m_warnings.ToArray();
}
private void AddWarning(string warning)
{
if (!m_warnings.Contains(warning))
{
m_warnings.Add(warning);
}
}
/// <summary>
/// Recursively called to generate each type of node. Will generate this
/// node, then all it's children.
/// </summary>
/// <param name="previousSymbol">The parent node.</param>
/// <param name="s">The current node to generate code for.</param>
/// <returns>String containing C# code for SYMBOL s.</returns>
private void GenerateNodeToSB(SYMBOL previousSymbol, SYMBOL s, StringBuilder sb)
{
// make sure to put type lower in the inheritance hierarchy first
// ie: since IdentArgument and ExpressionArgument inherit from
// Argument, put IdentArgument and ExpressionArgument before Argument
if (s is GlobalFunctionDefinition)
GenerateGlobalFunctionDefinition((GlobalFunctionDefinition) s, sb);
else if (s is GlobalVariableDeclaration)
GenerateGlobalVariableDeclaration((GlobalVariableDeclaration) s , sb);
else if (s is State)
GenerateState((State) s, sb);
else if (s is CompoundStatement)
GenerateCompoundStatement(previousSymbol, (CompoundStatement) s, sb);
else if (s is Declaration)
GenerateDeclaration((Declaration) s, sb);
else if (s is Statement)
GenerateStatement(previousSymbol, (Statement) s, sb);
else if (s is ReturnStatement)
GenerateReturnStatement((ReturnStatement) s, sb);
else if (s is JumpLabel)
GenerateJumpLabel((JumpLabel) s, sb);
else if (s is JumpStatement)
GenerateJumpStatement((JumpStatement) s, sb);
else if (s is StateChange)
GenerateStateChange((StateChange) s, sb);
else if (s is IfStatement)
GenerateIfStatement((IfStatement) s, sb);
else if (s is WhileStatement)
GenerateWhileStatement((WhileStatement) s, sb);
else if (s is DoWhileStatement)
GenerateDoWhileStatement((DoWhileStatement) s, sb);
else if (s is ForLoop)
GenerateForLoop((ForLoop) s, sb);
else if (s is ArgumentList)
GenerateArgumentList((ArgumentList) s, sb);
else if (s is Assignment)
GenerateAssignment((Assignment) s, sb);
else if (s is BinaryExpression)
GenerateBinaryExpression((BinaryExpression) s, sb);
else if (s is ParenthesisExpression)
GenerateParenthesisExpression((ParenthesisExpression) s, sb);
else if (s is UnaryExpression)
GenerateUnaryExpression((UnaryExpression) s, sb);
else if (s is IncrementDecrementExpression)
GenerateIncrementDecrementExpression((IncrementDecrementExpression) s, sb);
else if (s is TypecastExpression)
GenerateTypecastExpression((TypecastExpression) s, sb);
else if (s is FunctionCall)
GenerateFunctionCall((FunctionCall) s, sb);
else if (s is VectorConstant)
GenerateVectorConstant((VectorConstant) s, sb);
else if (s is RotationConstant)
GenerateRotationConstant((RotationConstant) s, sb);
else if (s is ListConstant)
GenerateListConstant((ListConstant) s, sb);
else if (s is Constant)
GenerateConstant((Constant) s, sb);
else if (s is IdentDotExpression)
Generate(CheckName(((IdentDotExpression) s).Name) + "." + ((IdentDotExpression) s).Member, s, sb);
else if (s is IdentExpression)
GenerateIdentifier(((IdentExpression) s).Name, s, sb);
else if (s is IDENT)
Generate(CheckName(((TOKEN) s).yytext), s, sb);
else
{
foreach (SYMBOL kid in s.kids)
GenerateNodeToSB(s, kid,sb);
}
return;
}
/// <summary>
/// Generates the code for a GlobalFunctionDefinition node.
/// </summary>
/// <param name="gf">The GlobalFunctionDefinition node.</param>
/// <returns>String containing C# code for GlobalFunctionDefinition gf.</returns>
private void GenerateGlobalFunctionDefinition(GlobalFunctionDefinition gf, StringBuilder sb)
{
// we need to separate the argument declaration list from other kids
List<SYMBOL> argumentDeclarationListKids = new List<SYMBOL>();
List<SYMBOL> remainingKids = new List<SYMBOL>();
foreach (SYMBOL kid in gf.kids)
if (kid is ArgumentDeclarationList)
argumentDeclarationListKids.Add(kid);
else
remainingKids.Add(kid);
GenerateIndented(String.Format("{0} {1}(", gf.ReturnType, CheckName(gf.Name)), gf, sb);
// print the state arguments, if any
foreach (SYMBOL kid in argumentDeclarationListKids)
GenerateArgumentDeclarationList((ArgumentDeclarationList) kid, sb);
GenerateLine(")", sb);
foreach (SYMBOL kid in remainingKids)
GenerateNodeToSB(gf, kid,sb);
}
/// <summary>
/// Generates the code for a GlobalVariableDeclaration node.
/// </summary>
/// <param name="gv">The GlobalVariableDeclaration node.</param>
/// <returns>String containing C# code for GlobalVariableDeclaration gv.</returns>
private void GenerateGlobalVariableDeclaration(GlobalVariableDeclaration gv, StringBuilder sb)
{
foreach (SYMBOL s in gv.kids)
{
Indent(sb);
GenerateNodeToSB(gv, s ,sb);
GenerateLine(";", sb);
}
}
/// <summary>
/// Generates the code for a State node.
/// </summary>
/// <param name="s">The State node.</param>
/// <returns>String containing C# code for State s.</returns>
private void GenerateState(State s, StringBuilder sb)
{
foreach (SYMBOL kid in s.kids)
if (kid is StateEvent)
GenerateStateEvent((StateEvent) kid, s.Name, sb);
}
/// <summary>
/// Generates the code for a StateEvent node.
/// </summary>
/// <param name="se">The StateEvent node.</param>
/// <param name="parentStateName">The name of the parent state.</param>
/// <returns>String containing C# code for StateEvent se.</returns>
private void GenerateStateEvent(StateEvent se, string parentStateName, StringBuilder sb)
{
// we need to separate the argument declaration list from other kids
List<SYMBOL> argumentDeclarationListKids = new List<SYMBOL>();
List<SYMBOL> remainingKids = new List<SYMBOL>();
foreach (SYMBOL kid in se.kids)
if (kid is ArgumentDeclarationList)
argumentDeclarationListKids.Add(kid);
else
remainingKids.Add(kid);
// "state" (function) declaration
GenerateIndented(String.Format("public void {0}_event_{1}(", parentStateName, se.Name), se , sb);
// print the state arguments, if any
foreach (SYMBOL kid in argumentDeclarationListKids)
GenerateArgumentDeclarationList((ArgumentDeclarationList) kid, sb);
GenerateLine(")", sb);
foreach (SYMBOL kid in remainingKids)
GenerateNodeToSB(se, kid, sb);
}
/// <summary>
/// Generates the code for an ArgumentDeclarationList node.
/// </summary>
/// <param name="adl">The ArgumentDeclarationList node.</param>
/// <returns>String containing C# code for ArgumentDeclarationList adl.</returns>
private void GenerateArgumentDeclarationList(ArgumentDeclarationList adl, StringBuilder sb)
{
int comma = adl.kids.Count - 1; // tells us whether to print a comma
foreach (Declaration d in adl.kids)
{
Generate(String.Format("{0} {1}", d.Datatype, CheckName(d.Id)), d, sb);
if (0 < comma--)
Generate(", ", sb);
}
}
/// <summary>
/// Generates the code for an ArgumentList node.
/// </summary>
/// <param name="al">The ArgumentList node.</param>
/// <returns>String containing C# code for ArgumentList al.</returns>
private void GenerateArgumentList(ArgumentList al, StringBuilder sb)
{
int comma = al.kids.Count - 1; // tells us whether to print a comma
foreach (SYMBOL s in al.kids)
{
GenerateNodeToSB(al, s, sb);
if (0 < comma--)
Generate(", ", sb);
}
}
/// <summary>
/// Generates the code for a CompoundStatement node.
/// </summary>
/// <param name="cs">The CompoundStatement node.</param>
/// <returns>String containing C# code for CompoundStatement cs.</returns>
private void GenerateCompoundStatement(SYMBOL previousSymbol, CompoundStatement cs, StringBuilder sb)
{
// opening brace
GenerateIndentedLine("{", sb);
m_braceCount++;
if (m_insertCoopTerminationChecks)
{
// We have to check in event functions as well because the user can manually call these.
if (previousSymbol is GlobalFunctionDefinition
|| previousSymbol is WhileStatement
|| previousSymbol is DoWhileStatement
|| previousSymbol is ForLoop
|| previousSymbol is StateEvent)
GenerateIndentedLine(m_coopTerminationCheck, sb);
}
foreach (SYMBOL kid in cs.kids)
GenerateNodeToSB(cs, kid, sb);
// closing brace
m_braceCount--;
GenerateIndentedLine("}", sb);
}
/// <summary>
/// Generates the code for a Declaration node.
/// </summary>
/// <param name="d">The Declaration node.</param>
/// <returns>String containing C# code for Declaration d.</returns>
private void GenerateDeclaration(Declaration d, StringBuilder sb)
{
Generate(String.Format("{0} {1}", d.Datatype, CheckName(d.Id)), d, sb);
}
/// <summary>
/// Generates the code for a Statement node.
/// </summary>
/// <param name="s">The Statement node.</param>
/// <returns>String containing C# code for Statement s.</returns>
private void GenerateStatement(SYMBOL previousSymbol, Statement s, StringBuilder sb)
{
string retstr = String.Empty;
bool printSemicolon = true;
bool transformToBlock = false;
if (m_insertCoopTerminationChecks)
{
// A non-braced single line do while structure cannot contain multiple statements.
// So to insert the termination check we change this to a braced control structure instead.
if (previousSymbol is WhileStatement
|| previousSymbol is DoWhileStatement
|| previousSymbol is ForLoop)
{
transformToBlock = true;
// FIXME: This will be wrongly indented because the previous for/while/dowhile will have already indented.
GenerateIndentedLine("{", sb);
GenerateIndentedLine(m_coopTerminationCheck, sb);
}
}
Indent(sb);
if (0 < s.kids.Count)
{
// Jump label prints its own colon, we don't need a semicolon.
printSemicolon = !(s.kids.Top is JumpLabel);
// If we encounter a lone Ident, we skip it, since that's a C#
// (MONO) error.
if (!(s.kids.Top is IdentExpression && 1 == s.kids.Count))
foreach (SYMBOL kid in s.kids)
GenerateNodeToSB(s, kid, sb);
}
if (printSemicolon)
GenerateLine(";", sb);
if (transformToBlock)
{
// FIXME: This will be wrongly indented because the for/while/dowhile is currently handling the unindent
GenerateIndentedLine("}", sb);
}
}
/// <summary>
/// Generates the code for an Assignment node.
/// </summary>
/// <param name="a">The Assignment node.</param>
/// <returns>String containing C# code for Assignment a.</returns>
private void GenerateAssignment(Assignment a, StringBuilder sb)
{
List<string> identifiers = new List<string>();
checkForMultipleAssignments(identifiers, a);
GenerateNodeToSB(a, (SYMBOL) a.kids.Pop(), sb);
Generate(String.Format(" {0} ", a.AssignmentType), a, sb);
foreach (SYMBOL kid in a.kids)
GenerateNodeToSB(a, kid, sb);
}
// This code checks for LSL of the following forms, and generates a
// warning if it finds them.
//
// list l = [ "foo" ];
// l = (l=[]) + l + ["bar"];
// (produces l=["foo","bar"] in SL but l=["bar"] in OS)
//
// integer i;
// integer j;
// i = (j = 3) + (j = 4) + (j = 5);
// (produces j=3 in SL but j=5 in OS)
//
// Without this check, that code passes compilation, but does not do what
// the end user expects, because LSL in SL evaluates right to left instead
// of left to right.
//
// The theory here is that producing an error and alerting the end user that
// something needs to change is better than silently generating incorrect code.
private void checkForMultipleAssignments(List<string> identifiers, SYMBOL s)
{
if (s is Assignment)
{
Assignment a = (Assignment)s;
string newident = null;
if (a.kids[0] is Declaration)
{
newident = ((Declaration)a.kids[0]).Id;
}
else if (a.kids[0] is IDENT)
{
newident = ((IDENT)a.kids[0]).yytext;
}
else if (a.kids[0] is IdentDotExpression)
{
newident = ((IdentDotExpression)a.kids[0]).Name; // +"." + ((IdentDotExpression)a.kids[0]).Member;
}
else
{
AddWarning(String.Format("Multiple assignments checker internal error '{0}' at line {1} column {2}.", a.kids[0].GetType(), ((SYMBOL)a.kids[0]).Line - 1, ((SYMBOL)a.kids[0]).Position));
}
if (identifiers.Contains(newident))
{
AddWarning(String.Format("Multiple assignments to '{0}' at line {1} column {2}; results may differ between LSL and OSSL.", newident, ((SYMBOL)a.kids[0]).Line - 1, ((SYMBOL)a.kids[0]).Position));
}
identifiers.Add(newident);
}
int index;
for (index = 0; index < s.kids.Count; index++)
{
checkForMultipleAssignments(identifiers, (SYMBOL) s.kids[index]);
}
}
/// <summary>
/// Generates the code for a ReturnStatement node.
/// </summary>
/// <param name="rs">The ReturnStatement node.</param>
/// <returns>String containing C# code for ReturnStatement rs.</returns>
private void GenerateReturnStatement(ReturnStatement rs, StringBuilder sb)
{
Generate("return ", rs, sb);
foreach (SYMBOL kid in rs.kids)
GenerateNodeToSB(rs, kid, sb);
}
/// <summary>
/// Generates the code for a JumpLabel node.
/// </summary>
/// <param name="jl">The JumpLabel node.</param>
/// <returns>String containing C# code for JumpLabel jl.</returns>
private void GenerateJumpLabel(JumpLabel jl, StringBuilder sb)
{
string labelStatement;
if (m_insertCoopTerminationChecks)
labelStatement = m_coopTerminationCheck;
else
labelStatement = "NoOp();";
GenerateLine(String.Format("{0}: {1}", CheckName(jl.LabelName), labelStatement), jl, sb);
}
/// <summary>
/// Generates the code for a JumpStatement node.
/// </summary>
/// <param name="js">The JumpStatement node.</param>
/// <returns>String containing C# code for JumpStatement js.</returns>
private void GenerateJumpStatement(JumpStatement js, StringBuilder sb)
{
Generate(String.Format("goto {0}", CheckName(js.TargetName)), js, sb);
}
/// <summary>
/// Generates the code for an IfStatement node.
/// </summary>
/// <param name="ifs">The IfStatement node.</param>
/// <returns>String containing C# code for IfStatement ifs.</returns>
private void GenerateIfStatement(IfStatement ifs, StringBuilder sb)
{
GenerateIndented("if (", ifs, sb);
GenerateNodeToSB(ifs, (SYMBOL) ifs.kids.Pop(), sb);
GenerateLine(")", sb);
// CompoundStatement handles indentation itself but we need to do it
// otherwise.
bool indentHere = ifs.kids.Top is Statement;
if (indentHere) m_braceCount++;
GenerateNodeToSB(ifs, (SYMBOL) ifs.kids.Pop(), sb);
if (indentHere) m_braceCount--;
if (0 < ifs.kids.Count) // do it again for an else
{
GenerateIndentedLine("else", ifs, sb);
indentHere = ifs.kids.Top is Statement;
if (indentHere) m_braceCount++;
GenerateNodeToSB(ifs, (SYMBOL) ifs.kids.Pop(), sb);
if (indentHere) m_braceCount--;
}
}
/// <summary>
/// Generates the code for a StateChange node.
/// </summary>
/// <param name="sc">The StateChange node.</param>
/// <returns>String containing C# code for StateChange sc.</returns>
private void GenerateStateChange(StateChange sc, StringBuilder sb)
{
Generate(String.Format("state(\"{0}\")", sc.NewState), sc, sb);
}
/// <summary>
/// Generates the code for a WhileStatement node.
/// </summary>
/// <param name="ws">The WhileStatement node.</param>
/// <returns>String containing C# code for WhileStatement ws.</returns>
private void GenerateWhileStatement(WhileStatement ws, StringBuilder sb)
{
GenerateIndented("while (", ws, sb);
GenerateNodeToSB(ws, (SYMBOL) ws.kids.Pop(), sb);
GenerateLine(")", sb);
// CompoundStatement handles indentation itself but we need to do it
// otherwise.
bool indentHere = ws.kids.Top is Statement;
if (indentHere) m_braceCount++;
GenerateNodeToSB(ws, (SYMBOL) ws.kids.Pop(), sb);
if (indentHere) m_braceCount--;
}
/// <summary>
/// Generates the code for a DoWhileStatement node.
/// </summary>
/// <param name="dws">The DoWhileStatement node.</param>
/// <returns>String containing C# code for DoWhileStatement dws.</returns>
private void GenerateDoWhileStatement(DoWhileStatement dws, StringBuilder sb)
{
GenerateIndentedLine("do", dws, sb);
// CompoundStatement handles indentation itself but we need to do it
// otherwise.
bool indentHere = dws.kids.Top is Statement;
if (indentHere) m_braceCount++;
GenerateNodeToSB(dws, (SYMBOL) dws.kids.Pop(), sb);
if (indentHere) m_braceCount--;
GenerateIndented("while (", dws ,sb);
GenerateNodeToSB(dws, (SYMBOL) dws.kids.Pop(), sb);
GenerateLine(");", sb);
}
/// <summary>
/// Generates the code for a ForLoop node.
/// </summary>
/// <param name="fl">The ForLoop node.</param>
/// <returns>String containing C# code for ForLoop fl.</returns>
private void GenerateForLoop(ForLoop fl, StringBuilder sb)
{
GenerateIndented("for (", fl, sb);
// It's possible that we don't have an assignment, in which case
// the child will be null and we only print the semicolon.
// for (x = 0; x < 10; x++)
// ^^^^^
ForLoopStatement s = (ForLoopStatement) fl.kids.Pop();
if (null != s)
{
GenerateForLoopStatement(s, sb);
}
Generate("; ", sb);
// for (x = 0; x < 10; x++)
// ^^^^^^
GenerateNodeToSB(fl, (SYMBOL) fl.kids.Pop(), sb);
Generate("; ", sb);
// for (x = 0; x < 10; x++)
// ^^^
GenerateForLoopStatement((ForLoopStatement) fl.kids.Pop(), sb);
GenerateLine(")", sb);
// CompoundStatement handles indentation itself but we need to do it
// otherwise.
bool indentHere = fl.kids.Top is Statement;
if (indentHere) m_braceCount++;
GenerateNodeToSB(fl, (SYMBOL) fl.kids.Pop(), sb);
if (indentHere) m_braceCount--;
}
/// <summary>
/// Generates the code for a ForLoopStatement node.
/// </summary>
/// <param name="fls">The ForLoopStatement node.</param>
/// <returns>String containing C# code for ForLoopStatement fls.</returns>
private void GenerateForLoopStatement(ForLoopStatement fls, StringBuilder sb)
{
int comma = fls.kids.Count - 1; // tells us whether to print a comma
// It's possible that all we have is an empty Ident, for example:
//
// for (x; x < 10; x++) { ... }
//
// Which is illegal in C# (MONO). We'll skip it.
if (fls.kids.Top is IdentExpression && 1 == fls.kids.Count)
return;
for (int i = 0; i < fls.kids.Count; i++)
{
SYMBOL s = (SYMBOL)fls.kids[i];
// Statements surrounded by parentheses in for loops
//
// e.g. for ((i = 0), (j = 7); (i < 10); (++i))
//
// are legal in LSL but not in C# so we need to discard the parentheses
//
// The following, however, does not appear to be legal in LLS
//
// for ((i = 0, j = 7); (i < 10); (++i))
//
// As of Friday 20th November 2009, the Linden Lab simulators appear simply never to compile or run this
// script but with no debug or warnings at all! Therefore, we won't deal with this yet (which looks
// like it would be considerably more complicated to handle).
while (s is ParenthesisExpression)
s = (SYMBOL)s.kids.Pop();
GenerateNodeToSB(fls, s, sb);
if (0 < comma--)
Generate(", ", sb);
}
}
/// <summary>
/// Generates the code for a BinaryExpression node.
/// </summary>
/// <param name="be">The BinaryExpression node.</param>
/// <returns>String containing C# code for BinaryExpression be.</returns>
private void GenerateBinaryExpression(BinaryExpression be, StringBuilder sb)
{
if (be.ExpressionSymbol.Equals("&&") || be.ExpressionSymbol.Equals("||"))
{
// special case handling for logical and/or, see Mantis 3174
sb.Append("((bool)(");
GenerateNodeToSB(be, (SYMBOL)be.kids.Pop(), sb);
sb.Append("))");
Generate(String.Format(" {0} ", be.ExpressionSymbol.Substring(0,1)), be, sb);
sb.Append("((bool)(");
foreach (SYMBOL kid in be.kids)
GenerateNodeToSB(be, kid, sb);
sb.Append("))");
}
else
{
GenerateNodeToSB(be, (SYMBOL)be.kids.Pop(), sb);
Generate(String.Format(" {0} ", be.ExpressionSymbol), be, sb);
foreach (SYMBOL kid in be.kids)
GenerateNodeToSB(be, kid, sb);
}
}
/// <summary>
/// Generates the code for a UnaryExpression node.
/// </summary>
/// <param name="ue">The UnaryExpression node.</param>
/// <returns>String containing C# code for UnaryExpression ue.</returns>
private void GenerateUnaryExpression(UnaryExpression ue, StringBuilder sb)
{
Generate(ue.UnarySymbol, ue, sb);
GenerateNodeToSB(ue, (SYMBOL) ue.kids.Pop(), sb);
}
/// <summary>
/// Generates the code for a ParenthesisExpression node.
/// </summary>
/// <param name="pe">The ParenthesisExpression node.</param>
/// <returns>String containing C# code for ParenthesisExpression pe.</returns>
private void GenerateParenthesisExpression(ParenthesisExpression pe, StringBuilder sb)
{
string retstr = String.Empty;
Generate("(", sb);
foreach (SYMBOL kid in pe.kids)
GenerateNodeToSB(pe, kid, sb);
Generate(")", sb);
}
/// <summary>
/// Generates the code for a IncrementDecrementExpression node.
/// </summary>
/// <param name="ide">The IncrementDecrementExpression node.</param>
/// <returns>String containing C# code for IncrementDecrementExpression ide.</returns>
private void GenerateIncrementDecrementExpression(IncrementDecrementExpression ide, StringBuilder sb)
{
if (0 < ide.kids.Count)
{
IdentDotExpression dot = (IdentDotExpression) ide.kids.Top;
Generate(String.Format("{0}", ide.PostOperation ? CheckName(dot.Name) + "." + dot.Member + ide.Operation : ide.Operation + CheckName(dot.Name) + "." + dot.Member), ide, sb);
}
else
Generate(String.Format("{0}", ide.PostOperation ? CheckName(ide.Name) + ide.Operation : ide.Operation + CheckName(ide.Name)), ide, sb);
}
/// <summary>
/// Generates the code for a TypecastExpression node.
/// </summary>
/// <param name="te">The TypecastExpression node.</param>
/// <returns>String containing C# code for TypecastExpression te.</returns>
private void GenerateTypecastExpression(TypecastExpression te, StringBuilder sb)
{
// we wrap all typecasted statements in parentheses
Generate(String.Format("({0}) (", te.TypecastType), te, sb);
GenerateNodeToSB(te, (SYMBOL) te.kids.Pop(), sb);
Generate(")", sb);
}
/// <summary>
/// Generates the code for an identifier
/// </summary>
/// <param name="id">The symbol name</param>
/// <param name="s">The Symbol node.</param>
/// <returns>String containing C# code for identifier reference.</returns>
private void GenerateIdentifier(string id, SYMBOL s, StringBuilder sb)
{
if (m_comms != null)
{
object value = m_comms.LookupModConstant(id);
if (value != null)
{
string retval = null;
if (value is int)
retval = String.Format("new LSL_Types.LSLInteger({0})",((int)value).ToString());
else if (value is float)
retval = String.Format("new LSL_Types.LSLFloat({0})",((float)value).ToString());
else if (value is string)
retval = String.Format("new LSL_Types.LSLString(\"{0}\")",((string)value));
else if (value is OpenMetaverse.UUID)
retval = String.Format("new LSL_Types.key(\"{0}\")",((OpenMetaverse.UUID)value).ToString());
else if (value is OpenMetaverse.Vector3)
retval = String.Format("new LSL_Types.Vector3(\"{0}\")",((OpenMetaverse.Vector3)value).ToString());
else if (value is OpenMetaverse.Quaternion)
retval = String.Format("new LSL_Types.Quaternion(\"{0}\")",((OpenMetaverse.Quaternion)value).ToString());
else retval = id;
Generate(retval, s, sb);
return;
}
}
Generate(CheckName(id), s, sb);
return;
}
/// <summary>
/// Generates the code for a FunctionCall node.
/// </summary>
/// <param name="fc">The FunctionCall node.</param>
/// <returns>String containing C# code for FunctionCall fc.</returns>
private void GenerateFunctionCall(FunctionCall fc, StringBuilder sb)
{
string modinvoke = null;
if (m_comms != null)
modinvoke = m_comms.LookupModInvocation(fc.Id);
if (modinvoke != null)
{
if (fc.kids[0] is ArgumentList)
{
if ((fc.kids[0] as ArgumentList).kids.Count == 0)
Generate(String.Format("{0}(\"{1}\"",modinvoke,fc.Id), fc, sb);
else
Generate(String.Format("{0}(\"{1}\",",modinvoke,fc.Id), fc, sb);
}
}
else
{
Generate(String.Format("{0}(", CheckName(fc.Id)), fc, sb);
}
foreach (SYMBOL kid in fc.kids)
GenerateNodeToSB(fc, kid, sb);
Generate(")", sb);
}
/// <summary>
/// Generates the code for a Constant node.
/// </summary>
/// <param name="c">The Constant node.</param>
/// <returns>String containing C# code for Constant c.</returns>
private void GenerateConstant(Constant c, StringBuilder sb)
{
// Supprt LSL's weird acceptance of floats with no trailing digits
// after the period. Turn float x = 10.; into float x = 10.0;
if ("LSL_Types.LSLFloat" == c.Type)
{
int dotIndex = c.Value.IndexOf('.') + 1;
if (0 < dotIndex && (dotIndex == c.Value.Length || !Char.IsDigit(c.Value[dotIndex])))
c.Value = c.Value.Insert(dotIndex, "0");
c.Value = "new LSL_Types.LSLFloat("+c.Value+")";
}
else if ("LSL_Types.LSLInteger" == c.Type)
{
c.Value = "new LSL_Types.LSLInteger("+c.Value+")";
}
else if ("LSL_Types.LSLString" == c.Type)
{
c.Value = "new LSL_Types.LSLString(\""+c.Value+"\")";
}
Generate(c.Value, c, sb);
}
/// <summary>
/// Generates the code for a VectorConstant node.
/// </summary>
/// <param name="vc">The VectorConstant node.</param>
/// <returns>String containing C# code for VectorConstant vc.</returns>
private void GenerateVectorConstant(VectorConstant vc, StringBuilder sb)
{
Generate(String.Format("new {0}(", vc.Type), vc, sb);
GenerateNodeToSB(vc, (SYMBOL) vc.kids.Pop(), sb);
Generate(", ", sb);
GenerateNodeToSB(vc, (SYMBOL) vc.kids.Pop(), sb);
Generate(", ", sb);
GenerateNodeToSB(vc, (SYMBOL) vc.kids.Pop(), sb);
Generate(")", sb);
}
/// <summary>
/// Generates the code for a RotationConstant node.
/// </summary>
/// <param name="rc">The RotationConstant node.</param>
/// <returns>String containing C# code for RotationConstant rc.</returns>
private void GenerateRotationConstant(RotationConstant rc, StringBuilder sb)
{
Generate(String.Format("new {0}(", rc.Type), rc, sb);
GenerateNodeToSB(rc, (SYMBOL) rc.kids.Pop(), sb);
Generate(", ", sb);
GenerateNodeToSB(rc, (SYMBOL) rc.kids.Pop(), sb);
Generate(", ", sb);
GenerateNodeToSB(rc, (SYMBOL) rc.kids.Pop(), sb);
Generate(", ", sb);
GenerateNodeToSB(rc, (SYMBOL) rc.kids.Pop(), sb);
Generate(")", sb);
}
/// <summary>
/// Generates the code for a ListConstant node.
/// </summary>
/// <param name="lc">The ListConstant node.</param>
/// <returns>String containing C# code for ListConstant lc.</returns>
private void GenerateListConstant(ListConstant lc, StringBuilder sb)
{
Generate(String.Format("new {0}(", lc.Type), lc, sb);
foreach (SYMBOL kid in lc.kids)
GenerateNodeToSB(lc, kid, sb);
Generate(")", sb);
}
/// <summary>
/// Prints a newline.
/// </summary>
/// <returns>A newline.</returns>
private void GenerateLine(StringBuilder sb)
{
sb.Append("\n");
m_CSharpLine++;
m_CSharpCol = 1;
}
/// <summary>
/// Prints text, followed by a newline.
/// </summary>
/// <param name="s">String of text to print.</param>
/// <returns>String s followed by newline.</returns>
private void GenerateLine(string s, StringBuilder sb)
{
sb.Append(s);
sb.Append("\n");
m_CSharpLine++;
m_CSharpCol = 1;
}
/// <summary>
/// Prints text, followed by a newline.
/// </summary>
/// <param name="s">String of text to print.</param>
/// <param name="sym">Symbol being generated to extract original line
/// number and column from.</param>
/// <returns>String s followed by newline.</returns>
private void GenerateLine(string s, SYMBOL sym, StringBuilder sb)
{
Generate(s, sym, sb);
sb.Append("\n");
m_CSharpLine++;
m_CSharpCol = 1;
}
/// <summary>
/// Prints text.
/// </summary>
/// <param name="s">String of text to print.</param>
/// <returns>String s.</returns>
private void Generate(string s, StringBuilder sb)
{
sb.Append(s);
m_CSharpCol += s.Length;
}
/// <summary>
/// Prints text.
/// </summary>
/// <param name="s">String of text to print.</param>
/// <param name="sym">Symbol being generated to extract original line
/// number and column from.</param>
/// <returns>String s.</returns>
private void Generate(string s, SYMBOL sym, StringBuilder sb)
{
sb.Append(s);
if (null != sym)
m_positionMap.Add(new KeyValuePair<int, int>(m_CSharpLine, m_CSharpCol), new KeyValuePair<int, int>(sym.Line, sym.Position));
m_CSharpCol += s.Length;
}
/// <summary>
/// Prints text correctly indented, followed by a newline.
/// </summary>
/// <param name="s">String of text to print.</param>
/// <returns>Properly indented string s followed by newline.</returns>
private void GenerateIndentedLine(string s, StringBuilder sb)
{
GenerateIndentedLine(s, null, sb);
}
/// <summary>
/// Prints text correctly indented, followed by a newline.
/// </summary>
/// <param name="s">String of text to print.</param>
/// <param name="sym">Symbol being generated to extract original line
/// number and column from.</param>
/// <returns>Properly indented string s followed by newline.</returns>
private void GenerateIndentedLine(string s, SYMBOL sym, StringBuilder sb)
{
GenerateIndented(s, sym , sb );
sb.Append("\n");
m_CSharpLine++;
m_CSharpCol = 1;
}
/// <summary>
/// Prints text correctly indented.
/// </summary>
/// <param name="s">String of text to print.</param>
/// <returns>Properly indented string s.</returns>
//private string GenerateIndented(string s)
//{
// return GenerateIndented(s, null);
//}
// THIS FUNCTION IS COMMENTED OUT TO SUPPRESS WARNINGS
/// <summary>
/// Prints text correctly indented.
/// </summary>
/// <param name="s">String of text to print.</param>
/// <param name="sym">Symbol being generated to extract original line
/// number and column from.</param>
/// <returns>Properly indented string s.</returns>
private void GenerateIndented(string s, SYMBOL sym, StringBuilder sb)
{
Indent(sb);
sb.Append(s);
if (null != sym)
m_positionMap.Add(new KeyValuePair<int, int>(m_CSharpLine, m_CSharpCol), new KeyValuePair<int, int>(sym.Line, sym.Position));
m_CSharpCol += s.Length;
}
/// <summary>
/// Prints correct indentation.
/// </summary>
/// <returns>Indentation based on brace count.</returns>
private void Indent(StringBuilder sb)
{
for (int i = 0; i < m_braceCount; i++)
{
sb.Append(" ");
m_CSharpCol += 4;
}
}
/// <summary>
/// Returns the passed name with an underscore prepended if that name is a reserved word in C#
/// and not resevered in LSL otherwise it just returns the passed name.
///
/// This makes no attempt to cache the results to minimise future lookups. For a non trivial
/// scripts the number of unique identifiers could easily grow to the size of the reserved word
/// list so maintaining a list or dictionary and doing the lookup there firstwould probably not
/// give any real speed advantage.
///
/// I believe there is a class Microsoft.CSharp.CSharpCodeProvider that has a function
/// CreateValidIdentifier(str) that will return either the value of str if it is not a C#
/// key word or "_"+str if it is. But availability under Mono?
/// </summary>
private string CheckName(string s)
{
if (CSReservedWords.IsReservedWord(s))
return "@" + s;
else
return s;
}
}
}
| |
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
namespace Google.Area120.Tables.V1Alpha1.Snippets
{
using Google.Api.Gax;
using Google.Protobuf.WellKnownTypes;
using System;
using System.Linq;
using System.Threading.Tasks;
/// <summary>Generated snippets.</summary>
public sealed class GeneratedTablesServiceClientSnippets
{
/// <summary>Snippet for GetTable</summary>
public void GetTableRequestObject()
{
// Snippet: GetTable(GetTableRequest, CallSettings)
// Create client
TablesServiceClient tablesServiceClient = TablesServiceClient.Create();
// Initialize request argument(s)
GetTableRequest request = new GetTableRequest
{
TableName = TableName.FromTable("[TABLE]"),
};
// Make the request
Table response = tablesServiceClient.GetTable(request);
// End snippet
}
/// <summary>Snippet for GetTableAsync</summary>
public async Task GetTableRequestObjectAsync()
{
// Snippet: GetTableAsync(GetTableRequest, CallSettings)
// Additional: GetTableAsync(GetTableRequest, CancellationToken)
// Create client
TablesServiceClient tablesServiceClient = await TablesServiceClient.CreateAsync();
// Initialize request argument(s)
GetTableRequest request = new GetTableRequest
{
TableName = TableName.FromTable("[TABLE]"),
};
// Make the request
Table response = await tablesServiceClient.GetTableAsync(request);
// End snippet
}
/// <summary>Snippet for GetTable</summary>
public void GetTable()
{
// Snippet: GetTable(string, CallSettings)
// Create client
TablesServiceClient tablesServiceClient = TablesServiceClient.Create();
// Initialize request argument(s)
string name = "tables/[TABLE]";
// Make the request
Table response = tablesServiceClient.GetTable(name);
// End snippet
}
/// <summary>Snippet for GetTableAsync</summary>
public async Task GetTableAsync()
{
// Snippet: GetTableAsync(string, CallSettings)
// Additional: GetTableAsync(string, CancellationToken)
// Create client
TablesServiceClient tablesServiceClient = await TablesServiceClient.CreateAsync();
// Initialize request argument(s)
string name = "tables/[TABLE]";
// Make the request
Table response = await tablesServiceClient.GetTableAsync(name);
// End snippet
}
/// <summary>Snippet for GetTable</summary>
public void GetTableResourceNames()
{
// Snippet: GetTable(TableName, CallSettings)
// Create client
TablesServiceClient tablesServiceClient = TablesServiceClient.Create();
// Initialize request argument(s)
TableName name = TableName.FromTable("[TABLE]");
// Make the request
Table response = tablesServiceClient.GetTable(name);
// End snippet
}
/// <summary>Snippet for GetTableAsync</summary>
public async Task GetTableResourceNamesAsync()
{
// Snippet: GetTableAsync(TableName, CallSettings)
// Additional: GetTableAsync(TableName, CancellationToken)
// Create client
TablesServiceClient tablesServiceClient = await TablesServiceClient.CreateAsync();
// Initialize request argument(s)
TableName name = TableName.FromTable("[TABLE]");
// Make the request
Table response = await tablesServiceClient.GetTableAsync(name);
// End snippet
}
/// <summary>Snippet for ListTables</summary>
public void ListTablesRequestObject()
{
// Snippet: ListTables(ListTablesRequest, CallSettings)
// Create client
TablesServiceClient tablesServiceClient = TablesServiceClient.Create();
// Initialize request argument(s)
ListTablesRequest request = new ListTablesRequest { };
// Make the request
PagedEnumerable<ListTablesResponse, Table> response = tablesServiceClient.ListTables(request);
// Iterate over all response items, lazily performing RPCs as required
foreach (Table item in response)
{
// Do something with each item
Console.WriteLine(item);
}
// Or iterate over pages (of server-defined size), performing one RPC per page
foreach (ListTablesResponse page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (Table item in page)
{
// Do something with each item
Console.WriteLine(item);
}
}
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<Table> singlePage = response.ReadPage(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (Table item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListTablesAsync</summary>
public async Task ListTablesRequestObjectAsync()
{
// Snippet: ListTablesAsync(ListTablesRequest, CallSettings)
// Create client
TablesServiceClient tablesServiceClient = await TablesServiceClient.CreateAsync();
// Initialize request argument(s)
ListTablesRequest request = new ListTablesRequest { };
// Make the request
PagedAsyncEnumerable<ListTablesResponse, Table> response = tablesServiceClient.ListTablesAsync(request);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((Table item) =>
{
// Do something with each item
Console.WriteLine(item);
});
// Or iterate over pages (of server-defined size), performing one RPC per page
await response.AsRawResponses().ForEachAsync((ListTablesResponse page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (Table item in page)
{
// Do something with each item
Console.WriteLine(item);
}
});
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<Table> singlePage = await response.ReadPageAsync(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (Table item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for GetWorkspace</summary>
public void GetWorkspaceRequestObject()
{
// Snippet: GetWorkspace(GetWorkspaceRequest, CallSettings)
// Create client
TablesServiceClient tablesServiceClient = TablesServiceClient.Create();
// Initialize request argument(s)
GetWorkspaceRequest request = new GetWorkspaceRequest
{
WorkspaceName = WorkspaceName.FromWorkspace("[WORKSPACE]"),
};
// Make the request
Workspace response = tablesServiceClient.GetWorkspace(request);
// End snippet
}
/// <summary>Snippet for GetWorkspaceAsync</summary>
public async Task GetWorkspaceRequestObjectAsync()
{
// Snippet: GetWorkspaceAsync(GetWorkspaceRequest, CallSettings)
// Additional: GetWorkspaceAsync(GetWorkspaceRequest, CancellationToken)
// Create client
TablesServiceClient tablesServiceClient = await TablesServiceClient.CreateAsync();
// Initialize request argument(s)
GetWorkspaceRequest request = new GetWorkspaceRequest
{
WorkspaceName = WorkspaceName.FromWorkspace("[WORKSPACE]"),
};
// Make the request
Workspace response = await tablesServiceClient.GetWorkspaceAsync(request);
// End snippet
}
/// <summary>Snippet for GetWorkspace</summary>
public void GetWorkspace()
{
// Snippet: GetWorkspace(string, CallSettings)
// Create client
TablesServiceClient tablesServiceClient = TablesServiceClient.Create();
// Initialize request argument(s)
string name = "workspaces/[WORKSPACE]";
// Make the request
Workspace response = tablesServiceClient.GetWorkspace(name);
// End snippet
}
/// <summary>Snippet for GetWorkspaceAsync</summary>
public async Task GetWorkspaceAsync()
{
// Snippet: GetWorkspaceAsync(string, CallSettings)
// Additional: GetWorkspaceAsync(string, CancellationToken)
// Create client
TablesServiceClient tablesServiceClient = await TablesServiceClient.CreateAsync();
// Initialize request argument(s)
string name = "workspaces/[WORKSPACE]";
// Make the request
Workspace response = await tablesServiceClient.GetWorkspaceAsync(name);
// End snippet
}
/// <summary>Snippet for GetWorkspace</summary>
public void GetWorkspaceResourceNames()
{
// Snippet: GetWorkspace(WorkspaceName, CallSettings)
// Create client
TablesServiceClient tablesServiceClient = TablesServiceClient.Create();
// Initialize request argument(s)
WorkspaceName name = WorkspaceName.FromWorkspace("[WORKSPACE]");
// Make the request
Workspace response = tablesServiceClient.GetWorkspace(name);
// End snippet
}
/// <summary>Snippet for GetWorkspaceAsync</summary>
public async Task GetWorkspaceResourceNamesAsync()
{
// Snippet: GetWorkspaceAsync(WorkspaceName, CallSettings)
// Additional: GetWorkspaceAsync(WorkspaceName, CancellationToken)
// Create client
TablesServiceClient tablesServiceClient = await TablesServiceClient.CreateAsync();
// Initialize request argument(s)
WorkspaceName name = WorkspaceName.FromWorkspace("[WORKSPACE]");
// Make the request
Workspace response = await tablesServiceClient.GetWorkspaceAsync(name);
// End snippet
}
/// <summary>Snippet for ListWorkspaces</summary>
public void ListWorkspacesRequestObject()
{
// Snippet: ListWorkspaces(ListWorkspacesRequest, CallSettings)
// Create client
TablesServiceClient tablesServiceClient = TablesServiceClient.Create();
// Initialize request argument(s)
ListWorkspacesRequest request = new ListWorkspacesRequest { };
// Make the request
PagedEnumerable<ListWorkspacesResponse, Workspace> response = tablesServiceClient.ListWorkspaces(request);
// Iterate over all response items, lazily performing RPCs as required
foreach (Workspace item in response)
{
// Do something with each item
Console.WriteLine(item);
}
// Or iterate over pages (of server-defined size), performing one RPC per page
foreach (ListWorkspacesResponse page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (Workspace item in page)
{
// Do something with each item
Console.WriteLine(item);
}
}
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<Workspace> singlePage = response.ReadPage(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (Workspace item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListWorkspacesAsync</summary>
public async Task ListWorkspacesRequestObjectAsync()
{
// Snippet: ListWorkspacesAsync(ListWorkspacesRequest, CallSettings)
// Create client
TablesServiceClient tablesServiceClient = await TablesServiceClient.CreateAsync();
// Initialize request argument(s)
ListWorkspacesRequest request = new ListWorkspacesRequest { };
// Make the request
PagedAsyncEnumerable<ListWorkspacesResponse, Workspace> response = tablesServiceClient.ListWorkspacesAsync(request);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((Workspace item) =>
{
// Do something with each item
Console.WriteLine(item);
});
// Or iterate over pages (of server-defined size), performing one RPC per page
await response.AsRawResponses().ForEachAsync((ListWorkspacesResponse page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (Workspace item in page)
{
// Do something with each item
Console.WriteLine(item);
}
});
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<Workspace> singlePage = await response.ReadPageAsync(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (Workspace item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for GetRow</summary>
public void GetRowRequestObject()
{
// Snippet: GetRow(GetRowRequest, CallSettings)
// Create client
TablesServiceClient tablesServiceClient = TablesServiceClient.Create();
// Initialize request argument(s)
GetRowRequest request = new GetRowRequest
{
RowName = RowName.FromTableRow("[TABLE]", "[ROW]"),
View = View.Unspecified,
};
// Make the request
Row response = tablesServiceClient.GetRow(request);
// End snippet
}
/// <summary>Snippet for GetRowAsync</summary>
public async Task GetRowRequestObjectAsync()
{
// Snippet: GetRowAsync(GetRowRequest, CallSettings)
// Additional: GetRowAsync(GetRowRequest, CancellationToken)
// Create client
TablesServiceClient tablesServiceClient = await TablesServiceClient.CreateAsync();
// Initialize request argument(s)
GetRowRequest request = new GetRowRequest
{
RowName = RowName.FromTableRow("[TABLE]", "[ROW]"),
View = View.Unspecified,
};
// Make the request
Row response = await tablesServiceClient.GetRowAsync(request);
// End snippet
}
/// <summary>Snippet for GetRow</summary>
public void GetRow()
{
// Snippet: GetRow(string, CallSettings)
// Create client
TablesServiceClient tablesServiceClient = TablesServiceClient.Create();
// Initialize request argument(s)
string name = "tables/[TABLE]/rows/[ROW]";
// Make the request
Row response = tablesServiceClient.GetRow(name);
// End snippet
}
/// <summary>Snippet for GetRowAsync</summary>
public async Task GetRowAsync()
{
// Snippet: GetRowAsync(string, CallSettings)
// Additional: GetRowAsync(string, CancellationToken)
// Create client
TablesServiceClient tablesServiceClient = await TablesServiceClient.CreateAsync();
// Initialize request argument(s)
string name = "tables/[TABLE]/rows/[ROW]";
// Make the request
Row response = await tablesServiceClient.GetRowAsync(name);
// End snippet
}
/// <summary>Snippet for GetRow</summary>
public void GetRowResourceNames()
{
// Snippet: GetRow(RowName, CallSettings)
// Create client
TablesServiceClient tablesServiceClient = TablesServiceClient.Create();
// Initialize request argument(s)
RowName name = RowName.FromTableRow("[TABLE]", "[ROW]");
// Make the request
Row response = tablesServiceClient.GetRow(name);
// End snippet
}
/// <summary>Snippet for GetRowAsync</summary>
public async Task GetRowResourceNamesAsync()
{
// Snippet: GetRowAsync(RowName, CallSettings)
// Additional: GetRowAsync(RowName, CancellationToken)
// Create client
TablesServiceClient tablesServiceClient = await TablesServiceClient.CreateAsync();
// Initialize request argument(s)
RowName name = RowName.FromTableRow("[TABLE]", "[ROW]");
// Make the request
Row response = await tablesServiceClient.GetRowAsync(name);
// End snippet
}
/// <summary>Snippet for ListRows</summary>
public void ListRowsRequestObject()
{
// Snippet: ListRows(ListRowsRequest, CallSettings)
// Create client
TablesServiceClient tablesServiceClient = TablesServiceClient.Create();
// Initialize request argument(s)
ListRowsRequest request = new ListRowsRequest
{
Parent = "",
View = View.Unspecified,
Filter = "",
};
// Make the request
PagedEnumerable<ListRowsResponse, Row> response = tablesServiceClient.ListRows(request);
// Iterate over all response items, lazily performing RPCs as required
foreach (Row item in response)
{
// Do something with each item
Console.WriteLine(item);
}
// Or iterate over pages (of server-defined size), performing one RPC per page
foreach (ListRowsResponse page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (Row item in page)
{
// Do something with each item
Console.WriteLine(item);
}
}
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<Row> singlePage = response.ReadPage(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (Row item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListRowsAsync</summary>
public async Task ListRowsRequestObjectAsync()
{
// Snippet: ListRowsAsync(ListRowsRequest, CallSettings)
// Create client
TablesServiceClient tablesServiceClient = await TablesServiceClient.CreateAsync();
// Initialize request argument(s)
ListRowsRequest request = new ListRowsRequest
{
Parent = "",
View = View.Unspecified,
Filter = "",
};
// Make the request
PagedAsyncEnumerable<ListRowsResponse, Row> response = tablesServiceClient.ListRowsAsync(request);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((Row item) =>
{
// Do something with each item
Console.WriteLine(item);
});
// Or iterate over pages (of server-defined size), performing one RPC per page
await response.AsRawResponses().ForEachAsync((ListRowsResponse page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (Row item in page)
{
// Do something with each item
Console.WriteLine(item);
}
});
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<Row> singlePage = await response.ReadPageAsync(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (Row item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListRows</summary>
public void ListRows()
{
// Snippet: ListRows(string, string, int?, CallSettings)
// Create client
TablesServiceClient tablesServiceClient = TablesServiceClient.Create();
// Initialize request argument(s)
string parent = "";
// Make the request
PagedEnumerable<ListRowsResponse, Row> response = tablesServiceClient.ListRows(parent);
// Iterate over all response items, lazily performing RPCs as required
foreach (Row item in response)
{
// Do something with each item
Console.WriteLine(item);
}
// Or iterate over pages (of server-defined size), performing one RPC per page
foreach (ListRowsResponse page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (Row item in page)
{
// Do something with each item
Console.WriteLine(item);
}
}
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<Row> singlePage = response.ReadPage(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (Row item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListRowsAsync</summary>
public async Task ListRowsAsync()
{
// Snippet: ListRowsAsync(string, string, int?, CallSettings)
// Create client
TablesServiceClient tablesServiceClient = await TablesServiceClient.CreateAsync();
// Initialize request argument(s)
string parent = "";
// Make the request
PagedAsyncEnumerable<ListRowsResponse, Row> response = tablesServiceClient.ListRowsAsync(parent);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((Row item) =>
{
// Do something with each item
Console.WriteLine(item);
});
// Or iterate over pages (of server-defined size), performing one RPC per page
await response.AsRawResponses().ForEachAsync((ListRowsResponse page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (Row item in page)
{
// Do something with each item
Console.WriteLine(item);
}
});
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<Row> singlePage = await response.ReadPageAsync(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (Row item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for CreateRow</summary>
public void CreateRowRequestObject()
{
// Snippet: CreateRow(CreateRowRequest, CallSettings)
// Create client
TablesServiceClient tablesServiceClient = TablesServiceClient.Create();
// Initialize request argument(s)
CreateRowRequest request = new CreateRowRequest
{
Parent = "",
Row = new Row(),
View = View.Unspecified,
};
// Make the request
Row response = tablesServiceClient.CreateRow(request);
// End snippet
}
/// <summary>Snippet for CreateRowAsync</summary>
public async Task CreateRowRequestObjectAsync()
{
// Snippet: CreateRowAsync(CreateRowRequest, CallSettings)
// Additional: CreateRowAsync(CreateRowRequest, CancellationToken)
// Create client
TablesServiceClient tablesServiceClient = await TablesServiceClient.CreateAsync();
// Initialize request argument(s)
CreateRowRequest request = new CreateRowRequest
{
Parent = "",
Row = new Row(),
View = View.Unspecified,
};
// Make the request
Row response = await tablesServiceClient.CreateRowAsync(request);
// End snippet
}
/// <summary>Snippet for CreateRow</summary>
public void CreateRow()
{
// Snippet: CreateRow(string, Row, CallSettings)
// Create client
TablesServiceClient tablesServiceClient = TablesServiceClient.Create();
// Initialize request argument(s)
string parent = "";
Row row = new Row();
// Make the request
Row response = tablesServiceClient.CreateRow(parent, row);
// End snippet
}
/// <summary>Snippet for CreateRowAsync</summary>
public async Task CreateRowAsync()
{
// Snippet: CreateRowAsync(string, Row, CallSettings)
// Additional: CreateRowAsync(string, Row, CancellationToken)
// Create client
TablesServiceClient tablesServiceClient = await TablesServiceClient.CreateAsync();
// Initialize request argument(s)
string parent = "";
Row row = new Row();
// Make the request
Row response = await tablesServiceClient.CreateRowAsync(parent, row);
// End snippet
}
/// <summary>Snippet for BatchCreateRows</summary>
public void BatchCreateRowsRequestObject()
{
// Snippet: BatchCreateRows(BatchCreateRowsRequest, CallSettings)
// Create client
TablesServiceClient tablesServiceClient = TablesServiceClient.Create();
// Initialize request argument(s)
BatchCreateRowsRequest request = new BatchCreateRowsRequest
{
Parent = "",
Requests =
{
new CreateRowRequest(),
},
};
// Make the request
BatchCreateRowsResponse response = tablesServiceClient.BatchCreateRows(request);
// End snippet
}
/// <summary>Snippet for BatchCreateRowsAsync</summary>
public async Task BatchCreateRowsRequestObjectAsync()
{
// Snippet: BatchCreateRowsAsync(BatchCreateRowsRequest, CallSettings)
// Additional: BatchCreateRowsAsync(BatchCreateRowsRequest, CancellationToken)
// Create client
TablesServiceClient tablesServiceClient = await TablesServiceClient.CreateAsync();
// Initialize request argument(s)
BatchCreateRowsRequest request = new BatchCreateRowsRequest
{
Parent = "",
Requests =
{
new CreateRowRequest(),
},
};
// Make the request
BatchCreateRowsResponse response = await tablesServiceClient.BatchCreateRowsAsync(request);
// End snippet
}
/// <summary>Snippet for UpdateRow</summary>
public void UpdateRowRequestObject()
{
// Snippet: UpdateRow(UpdateRowRequest, CallSettings)
// Create client
TablesServiceClient tablesServiceClient = TablesServiceClient.Create();
// Initialize request argument(s)
UpdateRowRequest request = new UpdateRowRequest
{
Row = new Row(),
UpdateMask = new FieldMask(),
View = View.Unspecified,
};
// Make the request
Row response = tablesServiceClient.UpdateRow(request);
// End snippet
}
/// <summary>Snippet for UpdateRowAsync</summary>
public async Task UpdateRowRequestObjectAsync()
{
// Snippet: UpdateRowAsync(UpdateRowRequest, CallSettings)
// Additional: UpdateRowAsync(UpdateRowRequest, CancellationToken)
// Create client
TablesServiceClient tablesServiceClient = await TablesServiceClient.CreateAsync();
// Initialize request argument(s)
UpdateRowRequest request = new UpdateRowRequest
{
Row = new Row(),
UpdateMask = new FieldMask(),
View = View.Unspecified,
};
// Make the request
Row response = await tablesServiceClient.UpdateRowAsync(request);
// End snippet
}
/// <summary>Snippet for UpdateRow</summary>
public void UpdateRow()
{
// Snippet: UpdateRow(Row, FieldMask, CallSettings)
// Create client
TablesServiceClient tablesServiceClient = TablesServiceClient.Create();
// Initialize request argument(s)
Row row = new Row();
FieldMask updateMask = new FieldMask();
// Make the request
Row response = tablesServiceClient.UpdateRow(row, updateMask);
// End snippet
}
/// <summary>Snippet for UpdateRowAsync</summary>
public async Task UpdateRowAsync()
{
// Snippet: UpdateRowAsync(Row, FieldMask, CallSettings)
// Additional: UpdateRowAsync(Row, FieldMask, CancellationToken)
// Create client
TablesServiceClient tablesServiceClient = await TablesServiceClient.CreateAsync();
// Initialize request argument(s)
Row row = new Row();
FieldMask updateMask = new FieldMask();
// Make the request
Row response = await tablesServiceClient.UpdateRowAsync(row, updateMask);
// End snippet
}
/// <summary>Snippet for BatchUpdateRows</summary>
public void BatchUpdateRowsRequestObject()
{
// Snippet: BatchUpdateRows(BatchUpdateRowsRequest, CallSettings)
// Create client
TablesServiceClient tablesServiceClient = TablesServiceClient.Create();
// Initialize request argument(s)
BatchUpdateRowsRequest request = new BatchUpdateRowsRequest
{
Parent = "",
Requests =
{
new UpdateRowRequest(),
},
};
// Make the request
BatchUpdateRowsResponse response = tablesServiceClient.BatchUpdateRows(request);
// End snippet
}
/// <summary>Snippet for BatchUpdateRowsAsync</summary>
public async Task BatchUpdateRowsRequestObjectAsync()
{
// Snippet: BatchUpdateRowsAsync(BatchUpdateRowsRequest, CallSettings)
// Additional: BatchUpdateRowsAsync(BatchUpdateRowsRequest, CancellationToken)
// Create client
TablesServiceClient tablesServiceClient = await TablesServiceClient.CreateAsync();
// Initialize request argument(s)
BatchUpdateRowsRequest request = new BatchUpdateRowsRequest
{
Parent = "",
Requests =
{
new UpdateRowRequest(),
},
};
// Make the request
BatchUpdateRowsResponse response = await tablesServiceClient.BatchUpdateRowsAsync(request);
// End snippet
}
/// <summary>Snippet for DeleteRow</summary>
public void DeleteRowRequestObject()
{
// Snippet: DeleteRow(DeleteRowRequest, CallSettings)
// Create client
TablesServiceClient tablesServiceClient = TablesServiceClient.Create();
// Initialize request argument(s)
DeleteRowRequest request = new DeleteRowRequest
{
RowName = RowName.FromTableRow("[TABLE]", "[ROW]"),
};
// Make the request
tablesServiceClient.DeleteRow(request);
// End snippet
}
/// <summary>Snippet for DeleteRowAsync</summary>
public async Task DeleteRowRequestObjectAsync()
{
// Snippet: DeleteRowAsync(DeleteRowRequest, CallSettings)
// Additional: DeleteRowAsync(DeleteRowRequest, CancellationToken)
// Create client
TablesServiceClient tablesServiceClient = await TablesServiceClient.CreateAsync();
// Initialize request argument(s)
DeleteRowRequest request = new DeleteRowRequest
{
RowName = RowName.FromTableRow("[TABLE]", "[ROW]"),
};
// Make the request
await tablesServiceClient.DeleteRowAsync(request);
// End snippet
}
/// <summary>Snippet for DeleteRow</summary>
public void DeleteRow()
{
// Snippet: DeleteRow(string, CallSettings)
// Create client
TablesServiceClient tablesServiceClient = TablesServiceClient.Create();
// Initialize request argument(s)
string name = "tables/[TABLE]/rows/[ROW]";
// Make the request
tablesServiceClient.DeleteRow(name);
// End snippet
}
/// <summary>Snippet for DeleteRowAsync</summary>
public async Task DeleteRowAsync()
{
// Snippet: DeleteRowAsync(string, CallSettings)
// Additional: DeleteRowAsync(string, CancellationToken)
// Create client
TablesServiceClient tablesServiceClient = await TablesServiceClient.CreateAsync();
// Initialize request argument(s)
string name = "tables/[TABLE]/rows/[ROW]";
// Make the request
await tablesServiceClient.DeleteRowAsync(name);
// End snippet
}
/// <summary>Snippet for DeleteRow</summary>
public void DeleteRowResourceNames()
{
// Snippet: DeleteRow(RowName, CallSettings)
// Create client
TablesServiceClient tablesServiceClient = TablesServiceClient.Create();
// Initialize request argument(s)
RowName name = RowName.FromTableRow("[TABLE]", "[ROW]");
// Make the request
tablesServiceClient.DeleteRow(name);
// End snippet
}
/// <summary>Snippet for DeleteRowAsync</summary>
public async Task DeleteRowResourceNamesAsync()
{
// Snippet: DeleteRowAsync(RowName, CallSettings)
// Additional: DeleteRowAsync(RowName, CancellationToken)
// Create client
TablesServiceClient tablesServiceClient = await TablesServiceClient.CreateAsync();
// Initialize request argument(s)
RowName name = RowName.FromTableRow("[TABLE]", "[ROW]");
// Make the request
await tablesServiceClient.DeleteRowAsync(name);
// End snippet
}
/// <summary>Snippet for BatchDeleteRows</summary>
public void BatchDeleteRowsRequestObject()
{
// Snippet: BatchDeleteRows(BatchDeleteRowsRequest, CallSettings)
// Create client
TablesServiceClient tablesServiceClient = TablesServiceClient.Create();
// Initialize request argument(s)
BatchDeleteRowsRequest request = new BatchDeleteRowsRequest
{
ParentAsTableName = TableName.FromTable("[TABLE]"),
RowNames =
{
RowName.FromTableRow("[TABLE]", "[ROW]"),
},
};
// Make the request
tablesServiceClient.BatchDeleteRows(request);
// End snippet
}
/// <summary>Snippet for BatchDeleteRowsAsync</summary>
public async Task BatchDeleteRowsRequestObjectAsync()
{
// Snippet: BatchDeleteRowsAsync(BatchDeleteRowsRequest, CallSettings)
// Additional: BatchDeleteRowsAsync(BatchDeleteRowsRequest, CancellationToken)
// Create client
TablesServiceClient tablesServiceClient = await TablesServiceClient.CreateAsync();
// Initialize request argument(s)
BatchDeleteRowsRequest request = new BatchDeleteRowsRequest
{
ParentAsTableName = TableName.FromTable("[TABLE]"),
RowNames =
{
RowName.FromTableRow("[TABLE]", "[ROW]"),
},
};
// Make the request
await tablesServiceClient.BatchDeleteRowsAsync(request);
// End snippet
}
}
}
| |
// 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 TestNotZAndNotCInt16()
{
var test = new BooleanTwoComparisonOpTest__TestNotZAndNotCInt16();
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 BooleanTwoComparisonOpTest__TestNotZAndNotCInt16
{
private const int VectorSize = 16;
private const int Op1ElementCount = VectorSize / sizeof(Int16);
private const int Op2ElementCount = VectorSize / sizeof(Int16);
private static Int16[] _data1 = new Int16[Op1ElementCount];
private static Int16[] _data2 = new Int16[Op2ElementCount];
private static Vector128<Int16> _clsVar1;
private static Vector128<Int16> _clsVar2;
private Vector128<Int16> _fld1;
private Vector128<Int16> _fld2;
private BooleanTwoComparisonOpTest__DataTable<Int16, Int16> _dataTable;
static BooleanTwoComparisonOpTest__TestNotZAndNotCInt16()
{
var random = new Random();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (short)(random.Next(short.MinValue, short.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int16>, byte>(ref _clsVar1), ref Unsafe.As<Int16, byte>(ref _data1[0]), VectorSize);
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (short)(random.Next(short.MinValue, short.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int16>, byte>(ref _clsVar2), ref Unsafe.As<Int16, byte>(ref _data2[0]), VectorSize);
}
public BooleanTwoComparisonOpTest__TestNotZAndNotCInt16()
{
Succeeded = true;
var random = new Random();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (short)(random.Next(short.MinValue, short.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int16>, byte>(ref _fld1), ref Unsafe.As<Int16, byte>(ref _data1[0]), VectorSize);
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (short)(random.Next(short.MinValue, short.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int16>, byte>(ref _fld2), ref Unsafe.As<Int16, byte>(ref _data2[0]), VectorSize);
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (short)(random.Next(short.MinValue, short.MaxValue)); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (short)(random.Next(short.MinValue, short.MaxValue)); }
_dataTable = new BooleanTwoComparisonOpTest__DataTable<Int16, Int16>(_data1, _data2, VectorSize);
}
public bool IsSupported => Sse41.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
var result = Sse41.TestNotZAndNotC(
Unsafe.Read<Vector128<Int16>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Int16>>(_dataTable.inArray2Ptr)
);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, result);
}
public void RunBasicScenario_Load()
{
var result = Sse41.TestNotZAndNotC(
Sse2.LoadVector128((Int16*)(_dataTable.inArray1Ptr)),
Sse2.LoadVector128((Int16*)(_dataTable.inArray2Ptr))
);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, result);
}
public void RunBasicScenario_LoadAligned()
{
var result = Sse41.TestNotZAndNotC(
Sse2.LoadAlignedVector128((Int16*)(_dataTable.inArray1Ptr)),
Sse2.LoadAlignedVector128((Int16*)(_dataTable.inArray2Ptr))
);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, result);
}
public void RunReflectionScenario_UnsafeRead()
{
var method = typeof(Sse41).GetMethod(nameof(Sse41.TestNotZAndNotC), new Type[] { typeof(Vector128<Int16>), typeof(Vector128<Int16>) });
if (method != null)
{
var result = method.Invoke(null, new object[] {
Unsafe.Read<Vector128<Int16>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Int16>>(_dataTable.inArray2Ptr)
});
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, (bool)(result));
}
}
public void RunReflectionScenario_Load()
{
var method = typeof(Sse41).GetMethod(nameof(Sse41.TestNotZAndNotC), new Type[] { typeof(Vector128<Int16>), typeof(Vector128<Int16>) });
if (method != null)
{
var result = method.Invoke(null, new object[] {
Sse2.LoadVector128((Int16*)(_dataTable.inArray1Ptr)),
Sse2.LoadVector128((Int16*)(_dataTable.inArray2Ptr))
});
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, (bool)(result));
}
}
public void RunReflectionScenario_LoadAligned()
{var method = typeof(Sse41).GetMethod(nameof(Sse41.TestNotZAndNotC), new Type[] { typeof(Vector128<Int16>), typeof(Vector128<Int16>) });
if (method != null)
{
var result = method.Invoke(null, new object[] {
Sse2.LoadAlignedVector128((Int16*)(_dataTable.inArray1Ptr)),
Sse2.LoadAlignedVector128((Int16*)(_dataTable.inArray2Ptr))
});
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, (bool)(result));
}
}
public void RunClsVarScenario()
{
var result = Sse41.TestNotZAndNotC(
_clsVar1,
_clsVar2
);
ValidateResult(_clsVar1, _clsVar2, result);
}
public void RunLclVarScenario_UnsafeRead()
{
var left = Unsafe.Read<Vector128<Int16>>(_dataTable.inArray1Ptr);
var right = Unsafe.Read<Vector128<Int16>>(_dataTable.inArray2Ptr);
var result = Sse41.TestNotZAndNotC(left, right);
ValidateResult(left, right, result);
}
public void RunLclVarScenario_Load()
{
var left = Sse2.LoadVector128((Int16*)(_dataTable.inArray1Ptr));
var right = Sse2.LoadVector128((Int16*)(_dataTable.inArray2Ptr));
var result = Sse41.TestNotZAndNotC(left, right);
ValidateResult(left, right, result);
}
public void RunLclVarScenario_LoadAligned()
{
var left = Sse2.LoadAlignedVector128((Int16*)(_dataTable.inArray1Ptr));
var right = Sse2.LoadAlignedVector128((Int16*)(_dataTable.inArray2Ptr));
var result = Sse41.TestNotZAndNotC(left, right);
ValidateResult(left, right, result);
}
public void RunLclFldScenario()
{
var test = new BooleanTwoComparisonOpTest__TestNotZAndNotCInt16();
var result = Sse41.TestNotZAndNotC(test._fld1, test._fld2);
ValidateResult(test._fld1, test._fld2, result);
}
public void RunFldScenario()
{
var result = Sse41.TestNotZAndNotC(_fld1, _fld2);
ValidateResult(_fld1, _fld2, result);
}
public void RunUnsupportedScenario()
{
Succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
Succeeded = true;
}
}
private void ValidateResult(Vector128<Int16> left, Vector128<Int16> right, bool result, [CallerMemberName] string method = "")
{
Int16[] inArray1 = new Int16[Op1ElementCount];
Int16[] inArray2 = new Int16[Op2ElementCount];
Unsafe.Write(Unsafe.AsPointer(ref inArray1[0]), left);
Unsafe.Write(Unsafe.AsPointer(ref inArray2[0]), right);
ValidateResult(inArray1, inArray2, result, method);
}
private void ValidateResult(void* left, void* right, bool result, [CallerMemberName] string method = "")
{
Int16[] inArray1 = new Int16[Op1ElementCount];
Int16[] inArray2 = new Int16[Op2ElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(left), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(right), VectorSize);
ValidateResult(inArray1, inArray2, result, method);
}
private void ValidateResult(Int16[] left, Int16[] right, bool result, [CallerMemberName] string method = "")
{
var expectedResult1 = true;
for (var i = 0; i < Op1ElementCount; i++)
{
expectedResult1 &= (((left[i] & right[i]) == 0));
}
var expectedResult2 = true;
for (var i = 0; i < Op1ElementCount; i++)
{
expectedResult2 &= (((~left[i] & right[i]) == 0));
}
if (((expectedResult1 == false) && (expectedResult2 == false)) != result)
{
Succeeded = false;
Console.WriteLine($"{nameof(Sse41)}.{nameof(Sse41.TestNotZAndNotC)}<Int16>(Vector128<Int16>, Vector128<Int16>): {method} failed:");
Console.WriteLine($" left: ({string.Join(", ", left)})");
Console.WriteLine($" right: ({string.Join(", ", right)})");
Console.WriteLine($" result: ({string.Join(", ", result)})");
Console.WriteLine();
}
}
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="_HTTPDateParse.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
using System.Globalization;
namespace System.Net {
internal static class HttpDateParse {
private const int BASE_DEC = 10; // base 10
//
// Date indicies used to figure out what each entry is.
//
private const int DATE_INDEX_DAY_OF_WEEK = 0;
private const int DATE_1123_INDEX_DAY = 1;
private const int DATE_1123_INDEX_MONTH = 2;
private const int DATE_1123_INDEX_YEAR = 3;
private const int DATE_1123_INDEX_HRS = 4;
private const int DATE_1123_INDEX_MINS = 5;
private const int DATE_1123_INDEX_SECS = 6;
private const int DATE_ANSI_INDEX_MONTH = 1;
private const int DATE_ANSI_INDEX_DAY = 2;
private const int DATE_ANSI_INDEX_HRS = 3;
private const int DATE_ANSI_INDEX_MINS = 4;
private const int DATE_ANSI_INDEX_SECS = 5;
private const int DATE_ANSI_INDEX_YEAR = 6;
private const int DATE_INDEX_TZ = 7;
private const int DATE_INDEX_LAST = DATE_INDEX_TZ;
private const int MAX_FIELD_DATE_ENTRIES = (DATE_INDEX_LAST+1);
//
// DATE_TOKEN's DWORD values used to determine what day/month we're on
//
private const int DATE_TOKEN_JANUARY = 1;
private const int DATE_TOKEN_FEBRUARY = 2;
private const int DATE_TOKEN_MARCH = 3;
private const int DATE_TOKEN_APRIL = 4;
private const int DATE_TOKEN_MAY = 5;
private const int DATE_TOKEN_JUNE = 6;
private const int DATE_TOKEN_JULY = 7;
private const int DATE_TOKEN_AUGUST = 8;
private const int DATE_TOKEN_SEPTEMBER = 9;
private const int DATE_TOKEN_OCTOBER = 10;
private const int DATE_TOKEN_NOVEMBER = 11;
private const int DATE_TOKEN_DECEMBER = 12;
private const int DATE_TOKEN_LAST_MONTH = (DATE_TOKEN_DECEMBER+1);
private const int DATE_TOKEN_SUNDAY = 0;
private const int DATE_TOKEN_MONDAY = 1;
private const int DATE_TOKEN_TUESDAY = 2;
private const int DATE_TOKEN_WEDNESDAY = 3;
private const int DATE_TOKEN_THURSDAY = 4;
private const int DATE_TOKEN_FRIDAY = 5;
private const int DATE_TOKEN_SATURDAY = 6;
private const int DATE_TOKEN_LAST_DAY = (DATE_TOKEN_SATURDAY+1);
private const int DATE_TOKEN_GMT = -1000;
private const int DATE_TOKEN_LAST = DATE_TOKEN_GMT;
private const int DATE_TOKEN_ERROR = (DATE_TOKEN_LAST+1);
//
// MAKE_UPPER - takes an assumed lower character and bit manipulates into a upper.
// (make sure the character is Lower case alpha char to begin,
// otherwise it corrupts)
//
private
static
char
MAKE_UPPER(char c) {
return(Char.ToUpper(c, CultureInfo.InvariantCulture));
}
/*++
Routine Description:
Looks at the first three bytes of string to determine if we're looking
at a Day of the Week, or Month, or "GMT" string. Is inlined so that
the compiler can optimize this code into the caller FInternalParseHttpDate.
Arguments:
lpszDay - a string ptr to the first byte of the string in question.
Return Value:
DWORD
Success - The Correct date token, 0-6 for day of the week, 1-14 for month, etc
Failure - DATE_TOKEN_ERROR
--*/
private
static
int
MapDayMonthToDword(
char [] lpszDay,
int index
) {
switch (MAKE_UPPER(lpszDay[index])) { // make uppercase
case 'A':
switch (MAKE_UPPER(lpszDay[index+1])) {
case 'P':
return DATE_TOKEN_APRIL;
case 'U':
return DATE_TOKEN_AUGUST;
}
return DATE_TOKEN_ERROR;
case 'D':
return DATE_TOKEN_DECEMBER;
case 'F':
switch (MAKE_UPPER(lpszDay[index+1])) {
case 'R':
return DATE_TOKEN_FRIDAY;
case 'E':
return DATE_TOKEN_FEBRUARY;
}
return DATE_TOKEN_ERROR;
case 'G':
return DATE_TOKEN_GMT;
case 'M':
switch (MAKE_UPPER(lpszDay[index+1])) {
case 'O':
return DATE_TOKEN_MONDAY;
case 'A':
switch (MAKE_UPPER(lpszDay[index+2])) {
case 'R':
return DATE_TOKEN_MARCH;
case 'Y':
return DATE_TOKEN_MAY;
}
// fall through to error
break;
}
return DATE_TOKEN_ERROR;
case 'N':
return DATE_TOKEN_NOVEMBER;
case 'J':
switch (MAKE_UPPER(lpszDay[index+1])) {
case 'A':
return DATE_TOKEN_JANUARY;
case 'U':
switch (MAKE_UPPER(lpszDay[index+2])) {
case 'N':
return DATE_TOKEN_JUNE;
case 'L':
return DATE_TOKEN_JULY;
}
// fall through to error
break;
}
return DATE_TOKEN_ERROR;
case 'O':
return DATE_TOKEN_OCTOBER;
case 'S':
switch (MAKE_UPPER(lpszDay[index+1])) {
case 'A':
return DATE_TOKEN_SATURDAY;
case 'U':
return DATE_TOKEN_SUNDAY;
case 'E':
return DATE_TOKEN_SEPTEMBER;
}
return DATE_TOKEN_ERROR;
case 'T':
switch (MAKE_UPPER(lpszDay[index+1])) {
case 'U':
return DATE_TOKEN_TUESDAY;
case 'H':
return DATE_TOKEN_THURSDAY;
}
return DATE_TOKEN_ERROR;
case 'U':
return DATE_TOKEN_GMT;
case 'W':
return DATE_TOKEN_WEDNESDAY;
}
return DATE_TOKEN_ERROR;
}
/*++
Routine Description:
Parses through a ANSI, RFC850, or RFC1123 date format and covents it into
a FILETIME/SYSTEMTIME time format.
Important this a time-critical function and should only be changed
with the intention of optimizing or a critical need work item.
Arguments:
lpft - Ptr to FILETIME structure. Used to store converted result.
Must be NULL if not intended to be used !!!
lpSysTime - Ptr to SYSTEMTIME struture. Used to return Systime if needed.
lpcszDateStr - Const Date string to parse.
Return Value:
BOOL
Success - TRUE
Failure - FALSE
--*/
public
static
bool
ParseHttpDate(
String DateString,
out DateTime dtOut
) {
int index = 0;
int i = 0, iLastLettered = -1;
bool fIsANSIDateFormat = false;
int [] rgdwDateParseResults = new int[MAX_FIELD_DATE_ENTRIES];
bool fRet = true;
char [] lpInputBuffer = DateString.ToCharArray();
dtOut = new DateTime();
//
// Date Parsing v2 (1 more to go), and here is how it works...
// We take a date string and churn through it once, converting
// integers to integers, Month,Day, and GMT strings into integers,
// and all is then placed IN order in a temp array.
//
// At the completetion of the parse stage, we simple look at
// the data, and then map the results into the correct
// places in the SYSTIME structure. Simple, No allocations, and
// No dirting the data.
//
// The end of the function does something munging and pretting
// up of the results to handle the year 2000, and TZ offsets
// Note: do we need to fully handle TZs anymore?
//
while (index < DateString.Length && i < MAX_FIELD_DATE_ENTRIES) {
if (lpInputBuffer[index] >= '0' && lpInputBuffer[index] <= '9') {
//
// we have a numerical entry, scan through it and convent to DWORD
//
rgdwDateParseResults[i] = 0;
do {
rgdwDateParseResults[i] *= BASE_DEC;
rgdwDateParseResults[i] += (lpInputBuffer[index] - '0');
index++;
} while (index < DateString.Length &&
lpInputBuffer[index] >= '0' &&
lpInputBuffer[index] <= '9');
i++; // next token
}
else if ((lpInputBuffer[index] >= 'A' && lpInputBuffer[index] <= 'Z') ||
(lpInputBuffer[index] >= 'a' && lpInputBuffer[index] <= 'z')) {
//
// we have a string, should be a day, month, or GMT
// lets skim to the end of the string
//
rgdwDateParseResults[i] =
MapDayMonthToDword(lpInputBuffer, index);
iLastLettered = i;
// We want to ignore the possibility of a time zone such as PST or EST in a non-standard
// date format such as "Thu Dec 17 16:01:28 PST 1998" (Notice that the year is _after_ the time zone
if ((rgdwDateParseResults[i] == DATE_TOKEN_ERROR)
&&
!(fIsANSIDateFormat && (i==DATE_ANSI_INDEX_YEAR))) {
fRet = false;
goto quit;
}
//
// At this point if we have a vaild string
// at this index, we know for sure that we're
// looking at a ANSI type DATE format.
//
if (i == DATE_ANSI_INDEX_MONTH) {
fIsANSIDateFormat = true;
}
//
// Read past the end of the current set of alpha characters,
// as MapDayMonthToDword only peeks at a few characters
//
do {
index++;
} while (index < DateString.Length &&
( (lpInputBuffer[index] >= 'A' && lpInputBuffer[index] <= 'Z') ||
(lpInputBuffer[index] >= 'a' && lpInputBuffer[index] <= 'z') ));
i++; // next token
}
else {
//
// For the generic case its either a space, comma, semi-colon, etc.
// the point is we really don't care, nor do we need to waste time
// worring about it (the orginal code did). The point is we
// care about the actual date information, So we just advance to the
// next lexume.
//
index++;
}
}
//
// We're finished parsing the string, now take the parsed tokens
// and turn them to the actual structured information we care about.
// So we build lpSysTime from the Array, using a local if none is passed in.
//
int year;
int month;
int day;
int hour;
int minute;
int second;
int millisecond;
millisecond = 0;
if (fIsANSIDateFormat) {
day = rgdwDateParseResults[DATE_ANSI_INDEX_DAY];
month = rgdwDateParseResults[DATE_ANSI_INDEX_MONTH];
hour = rgdwDateParseResults[DATE_ANSI_INDEX_HRS];
minute = rgdwDateParseResults[DATE_ANSI_INDEX_MINS];
second = rgdwDateParseResults[DATE_ANSI_INDEX_SECS];
if (iLastLettered != DATE_ANSI_INDEX_YEAR) {
year = rgdwDateParseResults[DATE_ANSI_INDEX_YEAR];
}
else {
// This is a fix to get around toString/toGMTstring (where the timezone is
// appended at the end. (See above)
year = rgdwDateParseResults[DATE_INDEX_TZ];
}
}
else {
day = rgdwDateParseResults[DATE_1123_INDEX_DAY];
month = rgdwDateParseResults[DATE_1123_INDEX_MONTH];
year = rgdwDateParseResults[DATE_1123_INDEX_YEAR];
hour = rgdwDateParseResults[DATE_1123_INDEX_HRS];
minute = rgdwDateParseResults[DATE_1123_INDEX_MINS];
second = rgdwDateParseResults[DATE_1123_INDEX_SECS];
}
//
// Normalize the year, 90 == 1990, handle the year 2000, 02 == 2002
// This is Year 2000 handling folks!!! We get this wrong and
// we all look bad.
//
if (year < 100) {
year += ((year < 80) ? 2000 : 1900);
}
//
// if we got misformed time, then plug in the current time
// !lpszHrs || !lpszMins || !lpszSec
//
if ((i < 4)
|| (day > 31)
|| (hour > 23)
|| (minute > 59)
|| (second > 59)) {
fRet = false;
goto quit;
}
//
// Now do the DateTime conversion
//
dtOut = new DateTime (year, month, day, hour, minute, second, millisecond);
//
// we want the system time to be accurate. This is _suhlow_
// The time passed in is in the local time zone; we have to convert this into GMT.
//
if (iLastLettered==DATE_ANSI_INDEX_YEAR) {
// this should be an unusual case.
dtOut = dtOut.ToUniversalTime();
}
//
// If we have an Offset to another Time Zone
// then convert to appropriate GMT time
//
if ((i > DATE_INDEX_TZ &&
rgdwDateParseResults[DATE_INDEX_TZ] != DATE_TOKEN_GMT)) {
//
// if we received +/-nnnn as offset (hhmm), modify the output FILETIME
//
double offset;
offset = (double) rgdwDateParseResults[DATE_INDEX_TZ];
dtOut.AddHours(offset);
}
// In the end, we leave it all in LocalTime
dtOut = dtOut.ToLocalTime();
quit:
return fRet;
}
}
} // namespace System.Net
| |
using System;
using System.Collections;
using Server;
namespace Knives.Chat3
{
public class Avatar
{
private static Hashtable s_Avatars = new Hashtable();
public static Hashtable Avatars { get { return s_Avatars; } }
public static ArrayList AvaKeys { get { return new ArrayList(s_Avatars.Keys); } }
public static void Initialize()
{
new Avatar(0x69, 8, 8);
new Avatar(0x6A, 8, 8);
new Avatar(0x6B, 8, 8);
new Avatar(0x6C, 8, 8);
new Avatar(0x6D, 8, 8);
new Avatar(0x6E, 8, 8);
new Avatar(0x6F, 8, 8);
new Avatar(0x70, 8, 8);
new Avatar(0x71, 25, 25);
new Avatar(0x8BA, 20, 17);
new Avatar(0x8C0, 18, 18);
new Avatar(0x8C1, 18, 18);
new Avatar(0x8C2, 18, 18);
new Avatar(0x8C3, 18, 18);
new Avatar(0x8C4, 18, 18);
new Avatar(0x8C5, 18, 18);
new Avatar(0x8C6, 18, 18);
new Avatar(0x8C7, 18, 18);
new Avatar(0x8C8, 18, 18);
new Avatar(0x8C9, 18, 18);
new Avatar(0x8CA, 18, 18);
new Avatar(0x8CB, 18, 18);
new Avatar(0x8CC, 18, 18);
new Avatar(0x8CD, 18, 18);
new Avatar(0x8CE, 18, 18);
new Avatar(0x8CF, 18, 18);
new Avatar(0x8D0, 18, 18);
new Avatar(0x8D1, 18, 18);
new Avatar(0x8D2, 18, 18);
new Avatar(0x8D3, 18, 18);
new Avatar(0x8D4, 18, 18);
new Avatar(0x8D5, 18, 18);
new Avatar(0x8D6, 18, 18);
new Avatar(0x8D7, 18, 18);
new Avatar(0x8D8, 18, 18);
new Avatar(0x8D9, 18, 18);
new Avatar(0x8DA, 18, 18);
new Avatar(0x8DB, 18, 18);
new Avatar(0x8DC, 18, 18);
new Avatar(0x8DD, 18, 18);
new Avatar(0x8DE, 18, 18);
new Avatar(0x8DF, 18, 18);
new Avatar(0x8E0, 18, 18);
new Avatar(0x8E1, 18, 18);
new Avatar(0x8E2, 18, 18);
new Avatar(0x8E3, 18, 18);
new Avatar(0x8E4, 18, 18);
new Avatar(0x8E5, 18, 18);
new Avatar(0x8E6, 18, 18);
new Avatar(0x8E7, 18, 18);
new Avatar(0x8E8, 18, 18);
new Avatar(0x8E9, 18, 18);
new Avatar(0x8EA, 18, 18);
new Avatar(0x8EB, 18, 18);
new Avatar(0x8EC, 18, 18);
new Avatar(0x8ED, 18, 18);
new Avatar(0x8EE, 18, 18);
new Avatar(0x8EF, 18, 18);
new Avatar(0x8F0, 18, 18);
new Avatar(0x8F1, 18, 18);
new Avatar(0x8F2, 18, 18);
new Avatar(0x8F3, 18, 18);
new Avatar(0x8F4, 18, 18);
new Avatar(0x8F5, 18, 18);
new Avatar(0x8F6, 18, 18);
new Avatar(0x8F7, 18, 18);
new Avatar(0x8F8, 18, 18);
new Avatar(0x8F9, 18, 18);
new Avatar(0x8FA, 18, 18);
new Avatar(0x8FB, 18, 18);
new Avatar(0x8FC, 18, 18);
new Avatar(0x8FD, 18, 18);
new Avatar(0x8FE, 18, 18);
new Avatar(0x8FF, 18, 18);
new Avatar(0x139D, 18, 16);
new Avatar(0x15A9, 10, 10);
new Avatar(0x15AB, 10, 10);
new Avatar(0x15AD, 10, 10);
new Avatar(0x15AF, 10, 10);
new Avatar(0x15B1, 10, 10);
new Avatar(0x15B3, 10, 10);
new Avatar(0x15B5, 10, 10);
new Avatar(0x15B7, 10, 10);
new Avatar(0x15B9, 10, 10);
new Avatar(0x15BB, 10, 10);
new Avatar(0x15BD, 10, 10);
new Avatar(0x15BF, 10, 10);
new Avatar(0x15C1, 10, 10);
new Avatar(0x15C3, 10, 10);
new Avatar(0x15C5, 10, 10);
new Avatar(0x15C7, 10, 10);
new Avatar(0x15C9, 10, 10);
new Avatar(0x15CB, 10, 10);
new Avatar(0x15CD, 10, 10);
new Avatar(0x15CF, 10, 10);
new Avatar(0x15D1, 10, 10);
new Avatar(0x15D3, 10, 10);
new Avatar(0x15D5, 10, 10);
new Avatar(0x15D7, 10, 10);
new Avatar(0x15E8, 10, 10);
new Avatar(0x264C, 5, 20);
new Avatar(0x28D2, 25, 16);
new Avatar(0x28E0, 21, 17);
new Avatar(0x2B03, 20, 17);
new Avatar(0x2B04, 20, 17);
new Avatar(0x2B05, 20, 17);
new Avatar(0x2B08, 20, 17);
new Avatar(0x2B09, 20, 17);
new Avatar(0x2B2D, 20, 17);
new Avatar(0x5000, 18, 18);
new Avatar(0x5001, 18, 18);
new Avatar(0x5002, 18, 18);
new Avatar(0x5003, 18, 18);
new Avatar(0x5004, 18, 18);
new Avatar(0x5005, 18, 18);
new Avatar(0x5006, 18, 18);
new Avatar(0x5007, 18, 18);
new Avatar(0x5008, 18, 18);
new Avatar(0x5009, 18, 18);
new Avatar(0x500A, 18, 18);
new Avatar(0x500B, 18, 18);
new Avatar(0x500C, 18, 18);
new Avatar(0x500D, 18, 18);
new Avatar(0x500E, 18, 18);
new Avatar(0x500F, 18, 18);
new Avatar(0x5010, 18, 18);
new Avatar(0x5100, 18, 18);
new Avatar(0x5101, 18, 18);
new Avatar(0x5102, 18, 18);
new Avatar(0x5103, 18, 18);
new Avatar(0x5104, 18, 18);
new Avatar(0x5105, 18, 18);
new Avatar(0x5106, 18, 18);
new Avatar(0x5107, 18, 18);
new Avatar(0x5108, 18, 18);
new Avatar(0x5109, 18, 18);
new Avatar(0x5200, 18, 18);
new Avatar(0x5201, 18, 18);
new Avatar(0x5202, 18, 18);
new Avatar(0x5203, 18, 18);
new Avatar(0x5204, 18, 18);
new Avatar(0x5205, 18, 18);
new Avatar(0x5206, 18, 18);
new Avatar(0x5207, 18, 18);
new Avatar(0x5208, 18, 18);
new Avatar(0x5209, 18, 18);
new Avatar(0x520A, 18, 18);
new Avatar(0x520B, 18, 18);
new Avatar(0x520C, 18, 18);
new Avatar(0x520D, 18, 18);
new Avatar(0x520E, 18, 18);
new Avatar(0x520F, 18, 18);
new Avatar(0x5210, 18, 18);
new Avatar(0x5211, 18, 18);
new Avatar(0x5212, 18, 18);
new Avatar(0x5213, 18, 18);
new Avatar(0x5214, 18, 18);
new Avatar(0x5215, 18, 18);
new Avatar(0x5216, 18, 18);
new Avatar(0x5217, 18, 18);
new Avatar(0x5218, 18, 18);
new Avatar(0x5219, 18, 18);
new Avatar(0x521A, 18, 18);
new Avatar(0x521B, 18, 18);
new Avatar(0x521C, 18, 18);
new Avatar(0x5308, 18, 18);
new Avatar(0x5309, 18, 18);
new Avatar(0x5320, 18, 18);
new Avatar(0x5321, 18, 18);
new Avatar(0x5322, 18, 18);
new Avatar(0x5323, 18, 18);
new Avatar(0x5324, 18, 18);
new Avatar(0x5325, 18, 18);
new Avatar(0x5326, 18, 18);
new Avatar(0x5327, 18, 18);
new Avatar(0x5420, 18, 18);
new Avatar(0x5421, 18, 18);
new Avatar(0x5422, 18, 18);
new Avatar(0x5423, 18, 18);
new Avatar(0x5424, 18, 18);
new Avatar(0x5425, 18, 18);
new Avatar(0x5426, 18, 18);
new Avatar(0x59D8, 18, 18);
new Avatar(0x59D9, 18, 18);
new Avatar(0x59DA, 18, 18);
new Avatar(0x59DB, 18, 18);
new Avatar(0x59DC, 18, 18);
new Avatar(0x59DD, 18, 18);
new Avatar(0x59DE, 18, 18);
new Avatar(0x59DF, 18, 18);
new Avatar(0x59E1, 18, 18);
new Avatar(0x59E2, 18, 18);
new Avatar(0x59E3, 18, 18);
new Avatar(0x59E4, 18, 18);
new Avatar(0x59E5, 18, 18);
new Avatar(0x59E6, 18, 18);
new Avatar(0x59E7, 18, 18);
new Avatar(104354, 15, 16);
General.LoadAvatarFile();
}
public static Avatar GetAvatar(Mobile m)
{
if (s_Avatars[Data.GetData(m).Avatar] == null)
Data.GetData(m).Avatar = (int)AvaKeys[0];
return (Avatar)s_Avatars[Data.GetData(m).Avatar];
}
private int c_Id, c_X, c_Y;
public int Id { get { return c_Id; } }
public int X { get { return c_X; } }
public int Y { get { return c_Y; } }
public Avatar(int id, int x, int y)
{
c_Id = id;
c_X = x;
c_Y = y;
s_Avatars[id] = this;
}
}
}
| |
using System;
using Shouldly;
using Xunit;
namespace ProGaudi.MsgPack.Light.Tests.Writer
{
public class Nullable
{
[Fact]
public void WriteNullAsNullableBool()
{
MsgPackSerializer.Serialize(default(bool?)).ShouldBe(new[] { (byte)DataTypes.Null });
((MsgPackToken)default(bool?)).RawBytes.ShouldBe(new[] { (byte)DataTypes.Null });
}
[Fact]
public void WriteNullAsNullableFloat()
{
MsgPackSerializer.Serialize(default(float?)).ShouldBe(new[] { (byte)DataTypes.Null });
((MsgPackToken)default(float?)).RawBytes.ShouldBe(new[] { (byte)DataTypes.Null });
}
[Fact]
public void WriteNullAsNullableDouble()
{
MsgPackSerializer.Serialize(default(double?)).ShouldBe(new[] { (byte)DataTypes.Null });
((MsgPackToken)default(double?)).RawBytes.ShouldBe(new[] { (byte)DataTypes.Null });
}
[Fact]
public void WriteNullAsNullableByte()
{
MsgPackSerializer.Serialize(default(byte?)).ShouldBe(new[] { (byte)DataTypes.Null });
((MsgPackToken)default(byte?)).RawBytes.ShouldBe(new[] { (byte)DataTypes.Null });
}
[Fact]
public void WriteNullAsNullableSbyte()
{
MsgPackSerializer.Serialize(default(sbyte?)).ShouldBe(new[] { (byte)DataTypes.Null });
((MsgPackToken)default(sbyte?)).RawBytes.ShouldBe(new[] { (byte)DataTypes.Null });
}
[Fact]
public void WriteNullAsNullableShort()
{
MsgPackSerializer.Serialize(default(short?)).ShouldBe(new[] { (byte)DataTypes.Null });
((MsgPackToken)default(short?)).RawBytes.ShouldBe(new[] { (byte)DataTypes.Null });
}
[Fact]
public void WriteNullAsNullableUshort()
{
MsgPackSerializer.Serialize(default(ushort?)).ShouldBe(new[] { (byte)DataTypes.Null });
((MsgPackToken)default(ushort?)).RawBytes.ShouldBe(new[] { (byte)DataTypes.Null });
}
[Fact]
public void WriteNullAsNullableInt()
{
MsgPackSerializer.Serialize(default(int?)).ShouldBe(new[] { (byte)DataTypes.Null });
((MsgPackToken)default(int?)).RawBytes.ShouldBe(new[] { (byte)DataTypes.Null });
}
[Fact]
public void WriteNullAsNullableUint()
{
MsgPackSerializer.Serialize(default(uint?)).ShouldBe(new[] { (byte)DataTypes.Null });
((MsgPackToken)default(uint?)).RawBytes.ShouldBe(new[] { (byte)DataTypes.Null });
}
[Fact]
public void WriteNullAsNullableLong()
{
MsgPackSerializer.Serialize(default(long?)).ShouldBe(new[] { (byte)DataTypes.Null });
((MsgPackToken)default(long?)).RawBytes.ShouldBe(new[] { (byte)DataTypes.Null });
}
[Fact]
public void WriteNullAsNullableUlong()
{
MsgPackSerializer.Serialize(default(ulong?)).ShouldBe(new[] { (byte)DataTypes.Null });
((MsgPackToken)default(ulong?)).RawBytes.ShouldBe(new[] { (byte)DataTypes.Null });
}
[Fact]
public void False()
{
MsgPackSerializer.Serialize((bool?)false).ShouldBe(new[] { (byte)DataTypes.False });
((MsgPackToken)(bool?)false).RawBytes.ShouldBe(new[] { (byte)DataTypes.False });
}
[Fact]
public void True()
{
MsgPackSerializer.Serialize((bool?)true).ShouldBe(new[] { (byte)DataTypes.True });
((MsgPackToken)(bool?)true).RawBytes.ShouldBe(new[] { (byte)DataTypes.True });
}
[Theory]
[InlineData(0, new byte[] { 203, 0, 0, 0, 0, 0, 0, 0, 0 })]
[InlineData(1, new byte[] { 203, 63, 240, 0, 0, 0, 0, 0, 0 })]
[InlineData(-1, new byte[] { 203, 191, 240, 0, 0, 0, 0, 0, 0 })]
[InlineData(Math.E, new byte[] { 203, 64, 5, 191, 10, 139, 20, 87, 105 })]
[InlineData(Math.PI, new byte[] { 203, 64, 9, 33, 251, 84, 68, 45, 24 })]
[InlineData(224, new byte[] { 203, 64, 108, 0, 0, 0, 0, 0, 0 })]
[InlineData(256, new byte[] { 203, 64, 112, 0, 0, 0, 0, 0, 0 })]
[InlineData(65530, new byte[] { 203, 64, 239, 255, 64, 0, 0, 0, 0 })]
[InlineData(65540, new byte[] { 203, 64, 240, 0, 64, 0, 0, 0, 0 })]
[InlineData(double.NaN, new byte[] { 203, 255, 248, 0, 0, 0, 0, 0, 0 })]
[InlineData(double.MaxValue, new byte[] { 203, 127, 239, 255, 255, 255, 255, 255, 255 })]
[InlineData(double.MinValue, new byte[] { 203, 255, 239, 255, 255, 255, 255, 255, 255 })]
[InlineData(double.PositiveInfinity, new byte[] { 203, 127, 240, 0, 0, 0, 0, 0, 0 })]
[InlineData(double.NegativeInfinity, new byte[] { 203, 255, 240, 0, 0, 0, 0, 0, 0 })]
public void TestDouble(double value, byte[] bytes)
{
MsgPackSerializer.Serialize((double?)value).ShouldBe(bytes);
((MsgPackToken)value).RawBytes.ShouldBe(bytes);
}
[Theory]
[InlineData(0, new byte[] { 202, 0, 0, 0, 0 })]
[InlineData(1, new byte[] { 202, 63, 128, 0, 0 })]
[InlineData(-1, new byte[] { 202, 191, 128, 0, 0 })]
[InlineData(2.71828, new byte[] { 202, 64, 45, 248, 77 })]
[InlineData(3.14159, new byte[] { 202, 64, 73, 15, 208 })]
[InlineData(224, new byte[] { 202, 67, 96, 0, 0 })]
[InlineData(256, new byte[] { 202, 67, 128, 0, 0 })]
[InlineData(65530, new byte[] { 202, 71, 127, 250, 0 })]
[InlineData(65540, new byte[] { 202, 71, 128, 2, 0 })]
[InlineData(float.NaN, new byte[] { 202, 255, 192, 0, 0 })]
[InlineData(float.MaxValue, new byte[] { 202, 127, 127, 255, 255 })]
[InlineData(float.MinValue, new byte[] { 202, 255, 127, 255, 255 })]
[InlineData(float.PositiveInfinity, new byte[] { 202, 127, 128, 0, 0 })]
[InlineData(float.NegativeInfinity, new byte[] { 202, 255, 128, 0, 0 })]
public void TestFloat(float value, byte[] bytes)
{
MsgPackSerializer.Serialize((float?)value).ShouldBe(bytes);
((MsgPackToken)value).RawBytes.ShouldBe(bytes);
}
[Theory]
[InlineData(0, new byte[] { 0x00 })]
[InlineData(1, new byte[] { 1 })]
[InlineData(-1, new byte[] { 0xff })]
[InlineData(sbyte.MinValue, new byte[] { 208, 128 })]
[InlineData(sbyte.MaxValue, new byte[] { 127 })]
[InlineData(short.MinValue, new byte[] { 209, 128, 0 })]
[InlineData(short.MaxValue, new byte[] { 205, 127, 0xff })]
[InlineData(int.MinValue, new byte[] { 210, 128, 0, 0, 0 })]
[InlineData(int.MaxValue, new byte[] { 206, 127, 0xff, 0xff, 0xff })]
[InlineData(long.MaxValue, new byte[] { 207, 127, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff })]
[InlineData(long.MinValue, new byte[] { 211, 128, 0, 0, 0, 0, 0, 0, 0 })]
public void TestSignedLong(long number, byte[] data)
{
MsgPackSerializer.Serialize((long?)number).ShouldBe(data);
((MsgPackToken)number).RawBytes.ShouldBe(data);
}
[Theory]
[InlineData(0, new byte[] { 0x00 })]
[InlineData(1, new byte[] { 1 })]
[InlineData(-1, new byte[] { 0xff })]
[InlineData(sbyte.MinValue, new byte[] { 208, 128 })]
[InlineData(sbyte.MaxValue, new byte[] { 127 })]
[InlineData(short.MinValue, new byte[] { 209, 128, 0 })]
[InlineData(short.MaxValue, new byte[] { 205, 127, 0xff })]
[InlineData(int.MinValue, new byte[] { 210, 128, 0, 0, 0 })]
[InlineData(int.MaxValue, new byte[] { 206, 127, 0xff, 0xff, 0xff })]
[InlineData(50505, new byte[] { 205, 197, 73 })]
public void TestSignedInt(int number, byte[] data)
{
MsgPackSerializer.Serialize((int?)number).ShouldBe(data);
((MsgPackToken)number).RawBytes.ShouldBe(data);
}
[Theory]
[InlineData(0, new byte[] { 0x00 })]
[InlineData(1, new byte[] { 1 })]
[InlineData(-1, new byte[] { 0xff })]
[InlineData(sbyte.MinValue, new byte[] { 208, 128 })]
[InlineData(sbyte.MaxValue, new byte[] { 127 })]
[InlineData(short.MinValue, new byte[] { 209, 128, 0 })]
[InlineData(short.MaxValue, new byte[] { 205, 127, 0xff })]
public void TestSignedShort(short number, byte[] data)
{
MsgPackSerializer.Serialize((short?)number).ShouldBe(data);
((MsgPackToken)number).RawBytes.ShouldBe(data);
}
[Theory]
[InlineData(0, new byte[] { 0x00 })]
[InlineData(1, new byte[] { 1 })]
[InlineData(-1, new byte[] { 0xff })]
[InlineData(sbyte.MinValue, new byte[] { 208, 128 })]
[InlineData(sbyte.MaxValue, new byte[] { 127 })]
public void TestSignedByte(sbyte number, byte[] data)
{
MsgPackSerializer.Serialize((sbyte?)number).ShouldBe(data);
((MsgPackToken)number).RawBytes.ShouldBe(data);
}
[Theory]
[InlineData(0, new byte[] { 0x00 })]
[InlineData(1, new byte[] { 1 })]
[InlineData(byte.MaxValue, new byte[] { 0xcc, 0xff })]
[InlineData(ushort.MaxValue, new byte[] { 0xcd, 0xff, 0xff })]
[InlineData(uint.MaxValue, new byte[] { 0xce, 0xff, 0xff, 0xff, 0xff })]
[InlineData(ulong.MaxValue, new byte[] { 0xcf, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff })]
public void TetsUnsignedLong(ulong number, byte[] data)
{
MsgPackSerializer.Serialize((ulong?)number).ShouldBe(data);
((MsgPackToken)number).RawBytes.ShouldBe(data);
}
[Theory]
[InlineData(0, new byte[] { 0x00 })]
[InlineData(1, new byte[] { 1 })]
[InlineData(byte.MaxValue, new byte[] { 0xcc, 0xff })]
[InlineData(ushort.MaxValue, new byte[] { 0xcd, 0xff, 0xff })]
[InlineData(uint.MaxValue, new byte[] { 0xce, 0xff, 0xff, 0xff, 0xff })]
public void TetsUnsignedInt(uint number, byte[] data)
{
MsgPackSerializer.Serialize((uint?)number).ShouldBe(data);
((MsgPackToken)number).RawBytes.ShouldBe(data);
}
[Theory]
[InlineData(0, new byte[] { 0x00 })]
[InlineData(1, new byte[] { 1 })]
[InlineData(byte.MaxValue, new byte[] { 0xcc, 0xff })]
[InlineData(ushort.MaxValue, new byte[] { 0xcd, 0xff, 0xff })]
public void TetsUnsignedShort(ushort number, byte[] data)
{
MsgPackSerializer.Serialize((ushort?)number).ShouldBe(data);
((MsgPackToken)number).RawBytes.ShouldBe(data);
}
[Theory]
[InlineData(0, new byte[] { 0x00 })]
[InlineData(1, new byte[] { 1 })]
[InlineData(byte.MaxValue, new byte[] { 0xcc, 0xff })]
public void TetsUnsignedByte(byte number, byte[] data)
{
MsgPackSerializer.Serialize((byte?)number).ShouldBe(data);
((MsgPackToken)number).RawBytes.ShouldBe(data);
}
}
}
| |
/*
* 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.
*/
#pragma warning disable S2360 // Optional parameters should not be used
namespace Apache.Ignite.Core.Tests
{
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using Apache.Ignite.Core.Discovery.Tcp;
using Apache.Ignite.Core.Discovery.Tcp.Static;
using Apache.Ignite.Core.Impl;
using Apache.Ignite.Core.Impl.Common;
using Apache.Ignite.Core.Tests.Process;
using NUnit.Framework;
/// <summary>
/// Test utility methods.
/// </summary>
public static class TestUtils
{
/** Indicates long running and/or memory/cpu intensive test. */
public const string CategoryIntensive = "LONG_TEST";
/** */
public const int DfltBusywaitSleepInterval = 200;
/** */
private static readonly IList<string> TestJvmOpts = Environment.Is64BitProcess
? new List<string>
{
"-XX:+HeapDumpOnOutOfMemoryError",
"-Xms1g",
"-Xmx4g",
"-ea"
}
: new List<string>
{
"-XX:+HeapDumpOnOutOfMemoryError",
"-Xms512m",
"-Xmx512m",
"-ea",
"-DIGNITE_ATOMIC_CACHE_DELETE_HISTORY_SIZE=1000"
};
/** */
private static readonly IList<string> JvmDebugOpts =
new List<string> { "-Xdebug", "-Xnoagent", "-Djava.compiler=NONE", "-agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=5005" };
/** */
public static bool JvmDebug = true;
/** */
[ThreadStatic]
private static Random _random;
/** */
private static int _seed = Environment.TickCount;
/// <summary>
/// Kill Ignite processes.
/// </summary>
public static void KillProcesses()
{
IgniteProcess.KillAll();
}
/// <summary>
///
/// </summary>
public static Random Random
{
get { return _random ?? (_random = new Random(Interlocked.Increment(ref _seed))); }
}
/// <summary>
///
/// </summary>
/// <returns></returns>
public static IList<string> TestJavaOptions(bool? jvmDebug = null)
{
IList<string> ops = new List<string>(TestJvmOpts);
if (jvmDebug ?? JvmDebug)
{
foreach (string opt in JvmDebugOpts)
ops.Add(opt);
}
return ops;
}
/// <summary>
///
/// </summary>
/// <returns></returns>
public static string CreateTestClasspath()
{
return Classpath.CreateClasspath(forceTestClasspath: true);
}
/// <summary>
///
/// </summary>
/// <param name="action"></param>
/// <param name="threadNum"></param>
public static void RunMultiThreaded(Action action, int threadNum)
{
List<Thread> threads = new List<Thread>(threadNum);
var errors = new ConcurrentBag<Exception>();
for (int i = 0; i < threadNum; i++)
{
threads.Add(new Thread(() =>
{
try
{
action();
}
catch (Exception e)
{
errors.Add(e);
}
}));
}
foreach (Thread thread in threads)
thread.Start();
foreach (Thread thread in threads)
thread.Join();
foreach (var ex in errors)
Assert.Fail("Unexpected exception: " + ex);
}
/// <summary>
///
/// </summary>
/// <param name="action"></param>
/// <param name="threadNum"></param>
/// <param name="duration">Duration of test execution in seconds</param>
public static void RunMultiThreaded(Action action, int threadNum, int duration)
{
List<Thread> threads = new List<Thread>(threadNum);
var errors = new ConcurrentBag<Exception>();
bool stop = false;
for (int i = 0; i < threadNum; i++)
{
threads.Add(new Thread(() =>
{
try
{
while (true)
{
Thread.MemoryBarrier();
// ReSharper disable once AccessToModifiedClosure
if (stop)
break;
action();
}
}
catch (Exception e)
{
errors.Add(e);
}
}));
}
foreach (Thread thread in threads)
thread.Start();
Thread.Sleep(duration * 1000);
stop = true;
Thread.MemoryBarrier();
foreach (Thread thread in threads)
thread.Join();
foreach (var ex in errors)
Assert.Fail("Unexpected exception: " + ex);
}
/// <summary>
/// Wait for particular topology size.
/// </summary>
/// <param name="grid">Grid.</param>
/// <param name="size">Size.</param>
/// <param name="timeout">Timeout.</param>
/// <returns>
/// <c>True</c> if topology took required size.
/// </returns>
public static bool WaitTopology(this IIgnite grid, int size, int timeout = 30000)
{
int left = timeout;
while (true)
{
if (grid.GetCluster().GetNodes().Count != size)
{
if (left > 0)
{
Thread.Sleep(100);
left -= 100;
}
else
break;
}
else
return true;
}
return false;
}
/// <summary>
/// Asserts that the handle registry is empty.
/// </summary>
/// <param name="timeout">Timeout, in milliseconds.</param>
/// <param name="grids">Grids to check.</param>
public static void AssertHandleRegistryIsEmpty(int timeout, params IIgnite[] grids)
{
foreach (var g in grids)
AssertHandleRegistryHasItems(g, 0, timeout);
}
/// <summary>
/// Asserts that the handle registry has specified number of entries.
/// </summary>
/// <param name="timeout">Timeout, in milliseconds.</param>
/// <param name="expectedCount">Expected item count.</param>
/// <param name="grids">Grids to check.</param>
public static void AssertHandleRegistryHasItems(int timeout, int expectedCount, params IIgnite[] grids)
{
foreach (var g in grids)
AssertHandleRegistryHasItems(g, expectedCount, timeout);
}
/// <summary>
/// Asserts that the handle registry has specified number of entries.
/// </summary>
/// <param name="grid">The grid to check.</param>
/// <param name="expectedCount">Expected item count.</param>
/// <param name="timeout">Timeout, in milliseconds.</param>
public static void AssertHandleRegistryHasItems(IIgnite grid, int expectedCount, int timeout)
{
var handleRegistry = ((Ignite)grid).HandleRegistry;
expectedCount++; // Skip default lifecycle bean
if (WaitForCondition(() => handleRegistry.Count == expectedCount, timeout))
return;
var items = handleRegistry.GetItems().Where(x => !(x.Value is LifecycleBeanHolder)).ToList();
if (items.Any())
Assert.Fail("HandleRegistry is not empty in grid '{0}':\n '{1}'", grid.Name,
items.Select(x => x.ToString()).Aggregate((x, y) => x + "\n" + y));
}
/// <summary>
/// Waits for condition, polling in busy wait loop.
/// </summary>
/// <param name="cond">Condition.</param>
/// <param name="timeout">Timeout, in milliseconds.</param>
/// <returns>True if condition predicate returned true within interval; false otherwise.</returns>
public static bool WaitForCondition(Func<bool> cond, int timeout)
{
if (timeout <= 0)
return cond();
var maxTime = DateTime.Now.AddMilliseconds(timeout + DfltBusywaitSleepInterval);
while (DateTime.Now < maxTime)
{
if (cond())
return true;
Thread.Sleep(DfltBusywaitSleepInterval);
}
return false;
}
/// <summary>
/// Gets the static discovery.
/// </summary>
public static TcpDiscoverySpi GetStaticDiscovery()
{
return new TcpDiscoverySpi
{
IpFinder = new TcpDiscoveryStaticIpFinder
{
Endpoints = new[] { "127.0.0.1:47500" }
},
SocketTimeout = TimeSpan.FromSeconds(0.3)
};
}
/// <summary>
/// Gets the default code-based test configuration.
/// </summary>
public static IgniteConfiguration GetTestConfiguration(bool? jvmDebug = null)
{
return new IgniteConfiguration
{
DiscoverySpi = GetStaticDiscovery(),
Localhost = "127.0.0.1",
JvmOptions = TestJavaOptions(jvmDebug),
JvmClasspath = CreateTestClasspath()
};
}
/// <summary>
/// Runs the test in new process.
/// </summary>
public static void RunTestInNewProcess(string fixtureName, string testName)
{
var procStart = new ProcessStartInfo
{
FileName = typeof(TestUtils).Assembly.Location,
Arguments = fixtureName + " " + testName,
CreateNoWindow = true,
UseShellExecute = false,
RedirectStandardOutput = true,
RedirectStandardError = true
};
var proc = System.Diagnostics.Process.Start(procStart);
Assert.IsNotNull(proc);
Console.WriteLine(proc.StandardOutput.ReadToEnd());
Console.WriteLine(proc.StandardError.ReadToEnd());
Assert.IsTrue(proc.WaitForExit(15000));
Assert.AreEqual(0, proc.ExitCode);
}
}
}
| |
//
// MetadataDisplay.cs
//
// Author:
// Ruben Vermeersch <[email protected]>
//
// Copyright (C) 2008-2010 Novell, Inc.
// Copyright (C) 2008, 2010 Ruben Vermeersch
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED AS IS, WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.IO;
using System.Text;
using System.Collections.Generic;
using Gtk;
using Mono.Unix;
using FSpot.Core;
using FSpot.Utils;
using FSpot.Extensions;
using FSpot.Imaging;
namespace FSpot.Widgets {
public class MetadataDisplayPage : SidebarPage {
public MetadataDisplayPage() : base(new MetadataDisplayWidget(),
Catalog.GetString ("Metadata"),
"gtk-info") {
(SidebarWidget as MetadataDisplayWidget).Page = this;
}
protected override void AddedToSidebar ()
{
MetadataDisplayWidget widget = SidebarWidget as MetadataDisplayWidget;
(Sidebar as Sidebar).SelectionChanged += widget.HandleSelectionChanged;
(Sidebar as Sidebar).SelectionItemsChanged += widget.HandleSelectionItemsChanged;
}
}
public class MetadataDisplayWidget : ScrolledWindow {
DelayedOperation update_delay;
/* This VBox only contains exif-data,
so it is seperated from other information */
VBox metadata_vbox;
VBox main_vbox;
Label metadata_message;
State display;
private MetadataDisplayPage page;
public MetadataDisplayPage Page {
set { page = value; }
get { return page; }
}
// stores list of the expanded expanders
List<string> open_list;
ListStore extended_metadata;
bool up_to_date = false;
enum State {
metadata,
message
};
public MetadataDisplayWidget ()
{
main_vbox = new VBox ();
main_vbox.Spacing = 6;
metadata_message = new Label (String.Empty);
metadata_message.UseMarkup = true;
metadata_message.LineWrap = true;
metadata_vbox = new VBox ();
metadata_vbox.Spacing = 6;
main_vbox.PackStart (metadata_vbox, false, false, 0);
AddWithViewport (metadata_message);
((Viewport) Child).ShadowType = ShadowType.None;
BorderWidth = 3;
display = State.message;
ExposeEvent += HandleExposeEvent;
open_list = new List<string> ();
// Create Expander and TreeView for
// extended metadata
TreeView tree_view = new TreeView ();
tree_view.HeadersVisible = false;
tree_view.RulesHint = true;
TreeViewColumn col = new TreeViewColumn ();
col.Sizing = TreeViewColumnSizing.Autosize;
CellRenderer colr = new CellRendererText ();
col.PackStart (colr, false);
col.AddAttribute (colr, "markup", 0);
tree_view.AppendColumn (col);
extended_metadata = new ListStore (typeof(string));
tree_view.Model = extended_metadata;
Expander expander = new Expander (String.Format("<span weight=\"bold\"><small>{0}</small></span>", Catalog.GetString ("Extended Metadata")));
expander.UseMarkup = true;
expander.Add (tree_view);
expander.Expanded = true;
main_vbox.PackStart (expander, false, false, 6);
expander.ShowAll ();
update_delay = new DelayedOperation (Update);
update_delay.Start ();
}
private IPhoto photo;
public IPhoto Photo {
get { return photo; }
set {
photo = value;
if (!Visible) {
up_to_date = false;
} else {
update_delay.Start ();
}
}
}
private void HandleExposeEvent (object sender, ExposeEventArgs args)
{
if (!up_to_date) {
update_delay.Start ();
}
}
internal void HandleSelectionChanged (IBrowsableCollection collection) {
// Don't show metadata when multiple photos are selected.
Photo = (collection != null && collection.Count == 1) ? collection [0] : null;
}
internal void HandleSelectionItemsChanged (IBrowsableCollection collection, BrowsableEventArgs args) {
if (!args.Changes.MetadataChanged)
return;
if (!Visible) {
up_to_date = false;
} else {
update_delay.Start ();
}
}
private new bool Visible {
get {
return (Page.Sidebar as Sidebar).IsActive (Page);
}
}
private ListStore AddExpander (string name, int pos)
{
TreeView tree_view = new TreeView ();
tree_view.HeadersVisible = false;
tree_view.RulesHint = true;
TreeViewColumn col = new TreeViewColumn ();
col.Sizing = TreeViewColumnSizing.Autosize;
CellRenderer colr = new CellRendererText ();
col.PackStart (colr, false);
col.AddAttribute (colr, "markup", 0);
tree_view.AppendColumn (col);
ListStore model = new ListStore (typeof(string));
tree_view.Model = model;
Expander expander = new Expander (String.Format ("<span weight=\"bold\"><small>{0}</small></span>", name));
expander.UseMarkup = true;
expander.Add (tree_view);
expander.Expanded = true;
metadata_vbox.PackStart (expander, false, false, 6);
metadata_vbox.ReorderChild (expander, pos);
if (open_list.Contains (name))
expander.Expanded = true;
expander.Activated += HandleExpanderActivated;
expander.ShowAll ();
return model;
}
public void HandleExpanderActivated (object sender, EventArgs e)
{
Expander expander = (Expander) sender;
if (expander.Expanded)
open_list.Add (expander.Label);
else
open_list.Remove (expander.Label);
}
private bool Update ()
{
bool empty = true;
int index_of_expander = 0;
bool missing = false;
System.Exception error = null;
/*
// FIXME: The stuff below needs to be ported to Taglib#.
TreeIter iter;
ListStore model;
string name;
up_to_date = true;
int i = 0;
// Write Exif-Data
if (exif_info != null) {
foreach (ExifContent content in exif_info.GetContents ()) {
ExifEntry [] entries = content.GetEntries ();
i++;
if (entries.Length < 1)
continue;
empty = false;
name = ExifUtil.GetIfdNameExtended ((Ifd)i - 1);
if (index_of_expander >= metadata_vbox.Children.Length)
model = AddExpander (name, index_of_expander);
else {
Expander expander = (Expander)metadata_vbox.Children[index_of_expander];
if (expander.Label == name)
model = (ListStore)((TreeView)expander.Child).Model;
else {
model = AddExpander (name, index_of_expander);
}
}
model.GetIterFirst(out iter);
foreach (ExifEntry entry in entries) {
string s;
if (entry.Title != null)
s = String.Format ("{0}\n\t<small>{1}</small>", entry.Title, entry.Value);
else
s = String.Format ("Unknown Tag ID={0}\n\t<small>{1}</small>", entry.Tag.ToString (), entry.Value);
if (model.IterIsValid(iter)) {
model.SetValue (iter, 0, s);
model.IterNext(ref iter);
} else
model.AppendValues (s);
}
// remove rows, that are not used
while (model.IterIsValid(iter)) {
model.Remove (ref iter);
}
index_of_expander++;
}
}
// Write Extended Metadata
if (photo != null) {
MetadataStore store = new MetadataStore ();
try {
using (var img = ImageFile.Create (photo.DefaultVersion.Uri)) {
if (img is SemWeb.StatementSource) {
StatementSource source = (StatementSource)img;
source.Select (store);
}
}
} catch (System.IO.FileNotFoundException) {
missing = true;
} catch (System.Exception e){
// Sometimes we don't get the right exception, check for the file
if (!System.IO.File.Exists (photo.DefaultVersion.Uri.LocalPath)) {
missing = true;
} else {
// if the file is there but we still got an exception display it.
error = e;
}
}
model = extended_metadata;
model.GetIterFirst(out iter);
if (store.StatementCount > 0) {
empty = false;
foreach (Statement stmt in store) {
// Skip anonymous subjects because they are
// probably part of a collection
if (stmt.Subject.Uri == null && store.SelectSubjects (null, stmt.Subject).Length > 0)
continue;
string title;
string value;
string s;
Description.GetDescription (store, stmt, out title, out value);
if (value == null)
{
MemoryStore substore = store.Select (new Statement ((Entity)stmt.Object, null, null, null)).Load();
StringBuilder collection = new StringBuilder ();
collection.Append (title);
WriteCollection (substore, collection);
if (model.IterIsValid(iter))
{
model.SetValue (iter, 0, collection.ToString ());
model.IterNext(ref iter);
} else
model.AppendValues (collection.ToString ());
} else {
s = String.Format ("{0}\n\t<small>{1}</small>", title, value);
if (model.IterIsValid(iter))
{
model.SetValue (iter, 0, s);
model.IterNext(ref iter);
} else
model.AppendValues (s);
}
}
} else {
// clear Extended Metadata
String s = String.Format ("<small>{0}</small>", Catalog.GetString ("No Extended Metadata Available"));
if (model.IterIsValid(iter))
{
model.SetValue (iter, 0, s);
model.IterNext(ref iter);
} else
model.AppendValues (s);
}
// remove rows, that are not used
while (model.IterIsValid(iter)) {
model.Remove (ref iter);
}
}*/
if (empty) {
string msg;
if (photo == null) {
msg = Catalog.GetString ("No active photo");
} else if (missing) {
msg = String.Format (Catalog.GetString ("The photo \"{0}\" does not exist"), photo.DefaultVersion.Uri);
} else {
msg = Catalog.GetString ("No metadata available");
if (error != null) {
msg = String.Format ("<i>{0}</i>", error);
}
}
metadata_message.Markup = "<span weight=\"bold\">" + msg + "</span>";
if (display == State.metadata) {
// Child is a Viewport, (AddWithViewport in ctor)
((Viewport)Child).Remove (main_vbox);
((Viewport)Child).Add (metadata_message);
display = State.message;
metadata_message.Show ();
}
} else {
// remove Expanders, that are not used
while (index_of_expander < metadata_vbox.Children.Length)
metadata_vbox.Remove (metadata_vbox.Children[index_of_expander]);
if (display == State.message) {
// Child is a Viewport, (AddWithViewport in ctor)
((Viewport)Child).Remove (metadata_message);
((Viewport)Child).Add (main_vbox);
display = State.metadata;
main_vbox.ShowAll ();
}
}
return false;
}
/*
private void WriteCollection (MemoryStore substore, StringBuilder collection)
{
string type = null;
foreach (Statement stmt in substore) {
if (stmt.Predicate.Uri == MetadataStore.Namespaces.Resolve ("rdf:type")) {
string prefix;
MetadataStore.Namespaces.Normalize (stmt.Object.Uri, out prefix, out type);
}
}
foreach (Statement sub in substore) {
if (sub.Object is SemWeb.Literal) {
string title;
string value = ((SemWeb.Literal)sub.Object).Value;
Description.GetDescription (substore, sub, out title, out value);
if (type == null)
collection.AppendFormat ("\n\t<small>{0}: {1}</small>", title, value);
else
collection.AppendFormat ("\n\t<small>{0}</small>", value);
} else {
if (type == null) {
MemoryStore substore2 = substore.Select (new Statement ((Entity)sub.Object, null, null, null)).Load();
if (substore.StatementCount > 0)
WriteCollection (substore2, collection);
}
}
}
}*/
}
}
| |
// Python Tools for Visual Studio
// Copyright(c) Microsoft Corporation
// All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the License); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at http://www.apache.org/licenses/LICENSE-2.0
//
// THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS
// OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY
// IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
// MERCHANTABLITY OR NON-INFRINGEMENT.
//
// See the Apache Version 2.0 License for specific language governing
// permissions and limitations under the License.
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.ComponentModel.Composition.Hosting;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Text.RegularExpressions;
using Microsoft.PythonTools;
using Microsoft.PythonTools.Infrastructure;
using Microsoft.PythonTools.Interpreter;
using Microsoft.PythonTools.Parsing;
using Microsoft.VisualStudio.Shell.Interop;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using TestUtilities;
using TestUtilities.Mocks;
using TestUtilities.Python;
namespace VSInterpretersTests {
[TestClass]
public class VSInterpretersTests {
[ClassInitialize]
public static void DoDeployment(TestContext context) {
AssertListener.Initialize();
PythonTestData.Deploy(includeTestData: false);
}
private static readonly List<string> _tempFiles = new List<string>();
[ClassCleanup]
public static void RemoveFiles() {
foreach (var file in _tempFiles) {
try {
File.Delete(file);
} catch {
}
}
}
private static string CompileString(string csharpCode, string outFile) {
var provider = new Microsoft.CSharp.CSharpCodeProvider();
var parameters = new System.CodeDom.Compiler.CompilerParameters {
OutputAssembly = outFile,
GenerateExecutable = false,
GenerateInMemory = false
};
parameters.ReferencedAssemblies.Add(typeof(ExportAttribute).Assembly.Location);
parameters.ReferencedAssemblies.Add(typeof(IPythonInterpreterFactoryProvider).Assembly.Location);
var result = provider.CompileAssemblyFromSource(parameters, csharpCode);
if (result.Errors.HasErrors) {
foreach (var err in result.Errors) {
Console.WriteLine(err);
}
}
if (!File.Exists(outFile)) {
Assert.Fail("Failed to compile {0}", outFile);
}
_tempFiles.Add(outFile);
return outFile;
}
private static string FactoryProviderSuccessPath {
get {
var path = Path.ChangeExtension(Path.GetTempFileName(), "dll");
if (File.Exists(path)) {
return path;
}
return CompileString(@"
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using Microsoft.PythonTools.Interpreter;
namespace FactoryProviderSuccess {
[Export(typeof(IPythonInterpreterFactoryProvider))]
[InterpreterFactoryId(""Success"")]
public class FactoryProviderSuccess : IPythonInterpreterFactoryProvider {
public IPythonInterpreterFactory GetInterpreterFactory(string id) {
return null;
}
public IEnumerable<InterpreterConfiguration> GetInterpreterConfigurations() { yield break; }
public event EventHandler InterpreterFactoriesChanged { add { } remove { } }
public object GetProperty(string id, string propName) { return null; }
}
}", path);
}
}
[TestMethod, Priority(1)]
public void ProviderLoadLog_Success() {
var path = FactoryProviderTypeLoadErrorPath;
var catalogLog = new MockLogger();
var container = InterpreterCatalog.CreateContainer(
catalogLog,
typeof(IInterpreterOptionsService).Assembly.Location,
typeof(IInterpreterRegistryService).Assembly.Location,
GetType().Assembly.Location
);
var log = container.GetExport<MockLogger>().Value;
var service = container.GetExportedValue<IInterpreterOptionsService>();
var registry = container.GetExportedValue<IInterpreterRegistryService>();
foreach (var interpreter in registry.Configurations) {
Console.WriteLine(interpreter);
}
foreach (var item in log.AllItems) {
Console.WriteLine(item);
}
Assert.AreEqual(0, log.AllItems.Count);
}
[TestMethod, Priority(1)]
public void ProviderLoadLog_FileNotFound() {
var catalogLog = new MockLogger();
var path = Path.ChangeExtension(Path.GetTempFileName(), "dll");
File.Delete(path);
Assert.IsFalse(File.Exists(path));
var container = InterpreterCatalog.CreateContainer(
catalogLog,
typeof(IInterpreterOptionsService).Assembly.Location,
typeof(IInterpreterRegistryService).Assembly.Location,
GetType().Assembly.Location,
path
);
var log = container.GetExport<MockLogger>().Value;
var service = container.GetExportedValue<IInterpreterOptionsService>();
var registry = container.GetExportedValue<IInterpreterRegistryService>();
foreach (var interpreter in registry.Configurations) {
Console.WriteLine(interpreter);
}
var error = catalogLog.AllItems.Single();
Assert.IsTrue(error.StartsWith("Failed to load interpreter provider assembly"));
Assert.AreNotEqual(-1, error.IndexOf("System.IO.FileNotFoundException: "));
}
private static string FactoryProviderCorruptPath {
get {
var path = Path.ChangeExtension(Path.GetTempFileName(), "dll");
if (File.Exists(path)) {
return path;
}
using (var src = new FileStream(FactoryProviderSuccessPath, FileMode.Open, FileAccess.Read))
using (var dest = new FileStream(path, FileMode.Create, FileAccess.Write)) {
var rnd = new Random();
var buffer = new byte[4096];
int read = src.Read(buffer, 0, buffer.Length);
while (read > 0) {
for (int count = 64; count > 0; --count) {
var i = rnd.Next(buffer.Length);
buffer[i] = (byte)(buffer[i] + rnd.Next(byte.MaxValue));
}
dest.Write(buffer, 0, read);
read = src.Read(buffer, 0, buffer.Length);
}
}
return path;
}
}
[TestMethod, Priority(1)]
public void ProviderLoadLog_CorruptImage() {
var catalogLog = new MockLogger();
var path = Path.ChangeExtension(Path.GetTempFileName(), "dll");
File.Delete(path);
Assert.IsFalse(File.Exists(path));
var container = InterpreterCatalog.CreateContainer(
catalogLog,
typeof(IInterpreterOptionsService).Assembly.Location,
typeof(IInterpreterRegistryService).Assembly.Location,
GetType().Assembly.Location,
FactoryProviderCorruptPath
);
var log = container.GetExport<MockLogger>().Value;
var service = container.GetExportedValue<IInterpreterOptionsService>();
var registry = container.GetExportedValue<IInterpreterRegistryService>();
foreach (var interpreter in registry.Configurations) {
Console.WriteLine(interpreter);
}
var error = catalogLog.AllItems.Single();
Assert.IsTrue(error.StartsWith("Failed to load interpreter provider assembly"));
Assert.AreNotEqual(-1, error.IndexOf("System.BadImageFormatException: "));
}
private static string FactoryProviderTypeLoadErrorPath {
get {
var path = Path.ChangeExtension(Path.GetTempFileName(), "dll");
if (File.Exists(path)) {
return path;
}
return CompileString(@"
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using Microsoft.PythonTools.Interpreter;
namespace FactoryProviderTypeLoadException {
[Export(typeof(IPythonInterpreterFactoryProvider))]
[InterpreterFactoryId(""TypeError"")]
public class FactoryProviderTypeLoadException : IPythonInterpreterFactoryProvider {
static FactoryProviderTypeLoadException() {
throw new Exception();
}
public IPythonInterpreterFactory GetInterpreterFactory(string id) {
return null;
}
public IEnumerable<InterpreterConfiguration> GetInterpreterConfigurations() { yield break; }
public event EventHandler InterpreterFactoriesChanged { add { } remove { } }
public object GetProperty(string id, string propName) { return null; }
}
}", path);
}
}
[TestMethod, Priority(1)]
public void ProviderLoadLog_TypeLoadException() {
var path = FactoryProviderTypeLoadErrorPath;
var catalogLog = new MockLogger();
var container = InterpreterCatalog.CreateContainer(
catalogLog,
FactoryProviderTypeLoadErrorPath,
typeof(IInterpreterOptionsService).Assembly.Location,
typeof(IInterpreterRegistryService).Assembly.Location,
GetType().Assembly.Location
);
var log = container.GetExport<MockLogger>().Value;
var service = container.GetExportedValue<IInterpreterOptionsService>();
var registry = container.GetExportedValue<IInterpreterRegistryService>();
foreach (var interpreter in registry.Configurations) {
Console.WriteLine(interpreter);
}
bool isMatch = false;
foreach (var msg in log.AllItems) {
Console.WriteLine(msg);
isMatch |= new Regex(@"Failed to get interpreter factory value:.*System\.ComponentModel\.Composition\.CompositionException").IsMatch(msg);
}
Assert.IsTrue(isMatch);
Assert.IsNotNull(registry.Configurations.FirstOrDefault());
}
[TestMethod, Priority(1)]
public void ProviderLoadLog_SuccessAndFailure() {
var path = FactoryProviderTypeLoadErrorPath;
var catalogLog = new MockLogger();
var container = InterpreterCatalog.CreateContainer(
catalogLog,
FactoryProviderTypeLoadErrorPath,
FactoryProviderSuccessPath,
typeof(IInterpreterOptionsService).Assembly.Location,
typeof(IInterpreterRegistryService).Assembly.Location,
GetType().Assembly.Location
);
var log = container.GetExport<MockLogger>().Value;
var service = container.GetExportedValue<IInterpreterOptionsService>();
var registry = container.GetExportedValue<IInterpreterRegistryService>();
foreach (var interpreter in registry.Configurations) {
Console.WriteLine(interpreter);
}
foreach (var item in log.AllItems) {
Console.WriteLine(item);
}
Assert.AreEqual(1, log.AllItems.Count);
}
[TestMethod, Priority(0)]
public void InvalidInterpreterVersion() {
try {
var lv = new Version(1, 0).ToLanguageVersion();
Assert.Fail("Expected InvalidOperationException");
} catch (InvalidOperationException) {
}
try {
InterpreterFactoryCreator.CreateInterpreterFactory(new InterpreterConfiguration(
Guid.NewGuid().ToString(),
"Test Interpreter",
version: new Version(1, 0)
));
Assert.Fail("Expected ArgumentException");
} catch (ArgumentException ex) {
// Expect version number in message
AssertUtil.Contains(ex.Message, "1.0");
}
}
}
[Export(typeof(IInterpreterLog))]
[Export(typeof(MockLogger))]
[PartCreationPolicy(CreationPolicy.Shared)]
class MockLogger : ICatalogLog, IInterpreterLog {
public readonly List<string> AllItems = new List<string>();
public void Log(string msg) {
AllItems.Add(msg);
}
}
}
| |
#region File Description
//-----------------------------------------------------------------------------
// StatisticsRange.cs
//
// Microsoft XNA Community Game Platform
// Copyright (C) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
#endregion
#region Using Statements
using System;
using System.Text;
using Microsoft.Xna.Framework.Content;
#endregion
namespace RolePlayingGameData
{
/// <summary>
/// A range of character statistics values.
/// </summary>
/// <remarks>Typically used for constrained random modifiers.</remarks>
public class StatisticsRange
{
[ContentSerializer(Optional = true)]
public Int32Range HealthPointsRange;
[ContentSerializer(Optional = true)]
public Int32Range MagicPointsRange;
[ContentSerializer(Optional = true)]
public Int32Range PhysicalOffenseRange;
[ContentSerializer(Optional = true)]
public Int32Range PhysicalDefenseRange;
[ContentSerializer(Optional = true)]
public Int32Range MagicalOffenseRange;
[ContentSerializer(Optional = true)]
public Int32Range MagicalDefenseRange;
#region Value Generation
/// <summary>
/// Generate a random value between the minimum and maximum, inclusively.
/// </summary>
/// <param name="random">The Random object used to generate the value.</param>
public StatisticsValue GenerateValue(Random random)
{
// check the parameters
Random usedRandom = random;
if (usedRandom == null)
{
usedRandom = new Random();
}
// generate the new value
StatisticsValue outputValue = new StatisticsValue();
outputValue.HealthPoints = HealthPointsRange.GenerateValue(usedRandom);
outputValue.MagicPoints = MagicPointsRange.GenerateValue(usedRandom);
outputValue.PhysicalOffense = PhysicalOffenseRange.GenerateValue(usedRandom);
outputValue.PhysicalDefense = PhysicalDefenseRange.GenerateValue(usedRandom);
outputValue.MagicalOffense = MagicalOffenseRange.GenerateValue(usedRandom);
outputValue.MagicalDefense = MagicalDefenseRange.GenerateValue(usedRandom);
return outputValue;
}
#endregion
#region String Output
/// <summary>
/// Builds a string that describes this object.
/// </summary>
public override string ToString()
{
StringBuilder sb = new StringBuilder();
sb.Append("HP:");
sb.Append(HealthPointsRange.ToString());
sb.Append("; MP:");
sb.Append(MagicPointsRange.ToString());
sb.Append("; PO:");
sb.Append(PhysicalOffenseRange.ToString());
sb.Append("; PD:");
sb.Append(PhysicalDefenseRange.ToString());
sb.Append("; MO:");
sb.Append(MagicalOffenseRange.ToString());
sb.Append("; MD:");
sb.Append(MagicalDefenseRange.ToString());
return sb.ToString();
}
/// <summary>
/// Builds a string that describes a modifier, where non-zero stats are skipped.
/// </summary>
public string GetModifierString()
{
StringBuilder sb = new StringBuilder();
bool firstStatistic = true;
// add the health points value, if any
if ((HealthPointsRange.Minimum != 0) || (HealthPointsRange.Maximum != 0))
{
if (firstStatistic)
{
firstStatistic = false;
}
else
{
sb.Append("; ");
}
sb.Append("HP:");
sb.Append(HealthPointsRange.ToString());
}
// add the magic points value, if any
if ((MagicPointsRange.Minimum != 0) || (MagicPointsRange.Maximum != 0))
{
if (firstStatistic)
{
firstStatistic = false;
}
else
{
sb.Append("; ");
}
sb.Append("MP:");
sb.Append(MagicPointsRange.ToString());
}
// add the physical offense value, if any
if ((PhysicalOffenseRange.Minimum != 0) ||
(PhysicalOffenseRange.Maximum != 0))
{
if (firstStatistic)
{
firstStatistic = false;
}
else
{
sb.Append("; ");
}
sb.Append("PO:");
sb.Append(PhysicalOffenseRange.ToString());
}
// add the physical defense value, if any
if ((PhysicalDefenseRange.Minimum != 0) ||
(PhysicalDefenseRange.Maximum != 0))
{
if (firstStatistic)
{
firstStatistic = false;
}
else
{
sb.Append("; ");
}
sb.Append("PD:");
sb.Append(PhysicalDefenseRange.ToString());
}
// add the magical offense value, if any
if ((MagicalOffenseRange.Minimum != 0) ||
(MagicalOffenseRange.Maximum != 0))
{
if (firstStatistic)
{
firstStatistic = false;
}
else
{
sb.Append("; ");
}
sb.Append("MO:");
sb.Append(MagicalOffenseRange.ToString());
}
// add the magical defense value, if any
if ((MagicalDefenseRange.Minimum != 0) ||
(MagicalDefenseRange.Maximum != 0))
{
if (firstStatistic)
{
firstStatistic = false;
}
else
{
sb.Append("; ");
}
sb.Append("MD:");
sb.Append(MagicalDefenseRange.ToString());
}
return sb.ToString();
}
#endregion
#region Operator: StatisticsRange + StatisticsValue
/// <summary>
/// Add one value to another, piecewise, and return the result.
/// </summary>
public static StatisticsRange Add(StatisticsRange value1,
StatisticsValue value2)
{
StatisticsRange outputRange = new StatisticsRange();
outputRange.HealthPointsRange =
value1.HealthPointsRange + value2.HealthPoints;
outputRange.MagicPointsRange =
value1.MagicPointsRange + value2.MagicPoints;
outputRange.PhysicalOffenseRange =
value1.PhysicalOffenseRange + value2.PhysicalOffense;
outputRange.PhysicalDefenseRange =
value1.PhysicalDefenseRange + value2.PhysicalDefense;
outputRange.MagicalOffenseRange =
value1.MagicalOffenseRange + value2.MagicalOffense;
outputRange.MagicalDefenseRange =
value1.MagicalDefenseRange + value2.MagicalDefense;
return outputRange;
}
/// <summary>
/// Add one value to another, piecewise, and return the result.
/// </summary>
public static StatisticsRange operator +(StatisticsRange value1,
StatisticsValue value2)
{
return Add(value1, value2);
}
#endregion
#region Content Type Reader
/// <summary>
/// Reads a StatisticsRange object from the content pipeline.
/// </summary>
public class StatisticsRangeReader : ContentTypeReader<StatisticsRange>
{
protected override StatisticsRange Read(ContentReader input,
StatisticsRange existingInstance)
{
StatisticsRange output = new StatisticsRange();
output.HealthPointsRange = input.ReadObject<Int32Range>();
output.MagicPointsRange = input.ReadObject<Int32Range>();
output.PhysicalOffenseRange = input.ReadObject<Int32Range>();
output.PhysicalDefenseRange = input.ReadObject<Int32Range>();
output.MagicalOffenseRange = input.ReadObject<Int32Range>();
output.MagicalDefenseRange = input.ReadObject<Int32Range>();
return output;
}
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Globalization;
using Abp.Configuration.Startup;
using Abp.Dependency;
using Abp.Extensions;
using Castle.Core.Logging;
namespace Abp.Localization.Dictionaries
{
/// <summary>
/// This class is used to build a localization source
/// which works on memory based dictionaries to find strings.
/// </summary>
public class DictionaryBasedLocalizationSource : IDictionaryBasedLocalizationSource
{
/// <summary>
/// Unique Name of the source.
/// </summary>
public string Name { get; }
public ILocalizationDictionaryProvider DictionaryProvider { get; }
protected ILocalizationConfiguration LocalizationConfiguration { get; private set; }
private ILogger _logger;
/// <summary>
///
/// </summary>
/// <param name="name"></param>
/// <param name="dictionaryProvider"></param>
public DictionaryBasedLocalizationSource(string name, ILocalizationDictionaryProvider dictionaryProvider)
{
Check.NotNullOrEmpty(name, nameof(name));
Check.NotNull(dictionaryProvider, nameof(dictionaryProvider));
Name = name;
DictionaryProvider = dictionaryProvider;
}
/// <inheritdoc/>
public virtual void Initialize(ILocalizationConfiguration configuration, IIocResolver iocResolver)
{
LocalizationConfiguration = configuration;
_logger = iocResolver.IsRegistered(typeof(ILoggerFactory))
? iocResolver.Resolve<ILoggerFactory>().Create(typeof(DictionaryBasedLocalizationSource))
: NullLogger.Instance;
DictionaryProvider.Initialize(Name);
}
/// <inheritdoc/>
public string GetString(string name)
{
return GetString(name, CultureInfo.CurrentUICulture);
}
/// <inheritdoc/>
public string GetString(string name, CultureInfo culture)
{
var value = GetStringOrNull(name, culture);
if (value == null)
{
return ReturnGivenNameOrThrowException(name, culture);
}
return value;
}
public string GetStringOrNull(string name, bool tryDefaults = true)
{
return GetStringOrNull(name, CultureInfo.CurrentUICulture, tryDefaults);
}
public string GetStringOrNull(string name, CultureInfo culture, bool tryDefaults = true)
{
var cultureName = culture.Name;
var dictionaries = DictionaryProvider.Dictionaries;
//Try to get from original dictionary (with country code)
ILocalizationDictionary originalDictionary;
if (dictionaries.TryGetValue(cultureName, out originalDictionary))
{
var strOriginal = originalDictionary.GetOrNull(name);
if (strOriginal != null)
{
return strOriginal.Value;
}
}
if (!tryDefaults)
{
return null;
}
//Try to get from same language dictionary (without country code)
if (cultureName.Contains("-")) //Example: "tr-TR" (length=5)
{
ILocalizationDictionary langDictionary;
if (dictionaries.TryGetValue(GetBaseCultureName(cultureName), out langDictionary))
{
var strLang = langDictionary.GetOrNull(name);
if (strLang != null)
{
return strLang.Value;
}
}
}
//Try to get from default language
var defaultDictionary = DictionaryProvider.DefaultDictionary;
if (defaultDictionary == null)
{
return null;
}
var strDefault = defaultDictionary.GetOrNull(name);
if (strDefault == null)
{
return null;
}
return strDefault.Value;
}
/// <inheritdoc/>
public IReadOnlyList<LocalizedString> GetAllStrings(bool includeDefaults = true)
{
return GetAllStrings(CultureInfo.CurrentUICulture, includeDefaults);
}
/// <inheritdoc/>
public IReadOnlyList<LocalizedString> GetAllStrings(CultureInfo culture, bool includeDefaults = true)
{
//TODO: Can be optimized (example: if it's already default dictionary, skip overriding)
var dictionaries = DictionaryProvider.Dictionaries;
//Create a temp dictionary to build
var allStrings = new Dictionary<string, LocalizedString>();
if (includeDefaults)
{
//Fill all strings from default dictionary
var defaultDictionary = DictionaryProvider.DefaultDictionary;
if (defaultDictionary != null)
{
foreach (var defaultDictString in defaultDictionary.GetAllStrings())
{
allStrings[defaultDictString.Name] = defaultDictString;
}
}
//Overwrite all strings from the language based on country culture
if (culture.Name.Contains("-"))
{
ILocalizationDictionary langDictionary;
if (dictionaries.TryGetValue(GetBaseCultureName(culture.Name), out langDictionary))
{
foreach (var langString in langDictionary.GetAllStrings())
{
allStrings[langString.Name] = langString;
}
}
}
}
//Overwrite all strings from the original dictionary
ILocalizationDictionary originalDictionary;
if (dictionaries.TryGetValue(culture.Name, out originalDictionary))
{
foreach (var originalLangString in originalDictionary.GetAllStrings())
{
allStrings[originalLangString.Name] = originalLangString;
}
}
return allStrings.Values.ToImmutableList();
}
/// <summary>
/// Extends the source with given dictionary.
/// </summary>
/// <param name="dictionary">Dictionary to extend the source</param>
public virtual void Extend(ILocalizationDictionary dictionary)
{
DictionaryProvider.Extend(dictionary);
}
protected virtual string ReturnGivenNameOrThrowException(string name, CultureInfo culture)
{
return LocalizationSourceHelper.ReturnGivenNameOrThrowException(
LocalizationConfiguration,
Name,
name,
culture,
_logger
);
}
private static string GetBaseCultureName(string cultureName)
{
return cultureName.Contains("-")
? cultureName.Left(cultureName.IndexOf("-", StringComparison.Ordinal))
: cultureName;
}
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System.Collections.Generic;
using NUnit.Framework;
using OpenSim.Tests.Common;
using OpenSim.Region.ScriptEngine.Shared;
namespace OpenSim.Region.ScriptEngine.Shared.Tests
{
[TestFixture]
public class LSL_TypesTestLSLFloat : OpenSimTestCase
{
// Used for testing equality of two floats.
private double _lowPrecisionTolerance = 0.000001;
private Dictionary<int, double> m_intDoubleSet;
private Dictionary<double, double> m_doubleDoubleSet;
private Dictionary<double, int> m_doubleIntSet;
private Dictionary<double, int> m_doubleUintSet;
private Dictionary<string, double> m_stringDoubleSet;
private Dictionary<double, string> m_doubleStringSet;
private List<int> m_intList;
private List<double> m_doubleList;
/// <summary>
/// Sets up dictionaries and arrays used in the tests.
/// </summary>
[TestFixtureSetUp]
public void SetUpDataSets()
{
m_intDoubleSet = new Dictionary<int, double>();
m_intDoubleSet.Add(2, 2.0);
m_intDoubleSet.Add(-2, -2.0);
m_intDoubleSet.Add(0, 0.0);
m_intDoubleSet.Add(1, 1.0);
m_intDoubleSet.Add(-1, -1.0);
m_intDoubleSet.Add(999999999, 999999999.0);
m_intDoubleSet.Add(-99999999, -99999999.0);
m_doubleDoubleSet = new Dictionary<double, double>();
m_doubleDoubleSet.Add(2.0, 2.0);
m_doubleDoubleSet.Add(-2.0, -2.0);
m_doubleDoubleSet.Add(0.0, 0.0);
m_doubleDoubleSet.Add(1.0, 1.0);
m_doubleDoubleSet.Add(-1.0, -1.0);
m_doubleDoubleSet.Add(999999999.0, 999999999.0);
m_doubleDoubleSet.Add(-99999999.0, -99999999.0);
m_doubleDoubleSet.Add(0.5, 0.5);
m_doubleDoubleSet.Add(0.0005, 0.0005);
m_doubleDoubleSet.Add(0.6805, 0.6805);
m_doubleDoubleSet.Add(-0.5, -0.5);
m_doubleDoubleSet.Add(-0.0005, -0.0005);
m_doubleDoubleSet.Add(-0.6805, -0.6805);
m_doubleDoubleSet.Add(548.5, 548.5);
m_doubleDoubleSet.Add(2.0005, 2.0005);
m_doubleDoubleSet.Add(349485435.6805, 349485435.6805);
m_doubleDoubleSet.Add(-548.5, -548.5);
m_doubleDoubleSet.Add(-2.0005, -2.0005);
m_doubleDoubleSet.Add(-349485435.6805, -349485435.6805);
m_doubleIntSet = new Dictionary<double, int>();
m_doubleIntSet.Add(2.0, 2);
m_doubleIntSet.Add(-2.0, -2);
m_doubleIntSet.Add(0.0, 0);
m_doubleIntSet.Add(1.0, 1);
m_doubleIntSet.Add(-1.0, -1);
m_doubleIntSet.Add(999999999.0, 999999999);
m_doubleIntSet.Add(-99999999.0, -99999999);
m_doubleIntSet.Add(0.5, 0);
m_doubleIntSet.Add(0.0005, 0);
m_doubleIntSet.Add(0.6805, 0);
m_doubleIntSet.Add(-0.5, 0);
m_doubleIntSet.Add(-0.0005, 0);
m_doubleIntSet.Add(-0.6805, 0);
m_doubleIntSet.Add(548.5, 548);
m_doubleIntSet.Add(2.0005, 2);
m_doubleIntSet.Add(349485435.6805, 349485435);
m_doubleIntSet.Add(-548.5, -548);
m_doubleIntSet.Add(-2.0005, -2);
m_doubleIntSet.Add(-349485435.6805, -349485435);
m_doubleUintSet = new Dictionary<double, int>();
m_doubleUintSet.Add(2.0, 2);
m_doubleUintSet.Add(-2.0, 2);
m_doubleUintSet.Add(0.0, 0);
m_doubleUintSet.Add(1.0, 1);
m_doubleUintSet.Add(-1.0, 1);
m_doubleUintSet.Add(999999999.0, 999999999);
m_doubleUintSet.Add(-99999999.0, 99999999);
m_doubleUintSet.Add(0.5, 0);
m_doubleUintSet.Add(0.0005, 0);
m_doubleUintSet.Add(0.6805, 0);
m_doubleUintSet.Add(-0.5, 0);
m_doubleUintSet.Add(-0.0005, 0);
m_doubleUintSet.Add(-0.6805, 0);
m_doubleUintSet.Add(548.5, 548);
m_doubleUintSet.Add(2.0005, 2);
m_doubleUintSet.Add(349485435.6805, 349485435);
m_doubleUintSet.Add(-548.5, 548);
m_doubleUintSet.Add(-2.0005, 2);
m_doubleUintSet.Add(-349485435.6805, 349485435);
m_stringDoubleSet = new Dictionary<string, double>();
m_stringDoubleSet.Add("2", 2.0);
m_stringDoubleSet.Add("-2", -2.0);
m_stringDoubleSet.Add("1", 1.0);
m_stringDoubleSet.Add("-1", -1.0);
m_stringDoubleSet.Add("0", 0.0);
m_stringDoubleSet.Add("999999999.0", 999999999.0);
m_stringDoubleSet.Add("-99999999.0", -99999999.0);
m_stringDoubleSet.Add("0.5", 0.5);
m_stringDoubleSet.Add("0.0005", 0.0005);
m_stringDoubleSet.Add("0.6805", 0.6805);
m_stringDoubleSet.Add("-0.5", -0.5);
m_stringDoubleSet.Add("-0.0005", -0.0005);
m_stringDoubleSet.Add("-0.6805", -0.6805);
m_stringDoubleSet.Add("548.5", 548.5);
m_stringDoubleSet.Add("2.0005", 2.0005);
m_stringDoubleSet.Add("349485435.6805", 349485435.6805);
m_stringDoubleSet.Add("-548.5", -548.5);
m_stringDoubleSet.Add("-2.0005", -2.0005);
m_stringDoubleSet.Add("-349485435.6805", -349485435.6805);
// some oddball combinations and exponents
m_stringDoubleSet.Add("", 0.0);
m_stringDoubleSet.Add("1.0E+5", 100000.0);
m_stringDoubleSet.Add("-1.0E+5", -100000.0);
m_stringDoubleSet.Add("-1E+5", -100000.0);
m_stringDoubleSet.Add("-1.E+5", -100000.0);
m_stringDoubleSet.Add("-1.E+5.0", -100000.0);
m_stringDoubleSet.Add("1ef", 1.0);
m_stringDoubleSet.Add("e10", 0.0);
m_stringDoubleSet.Add("1.e0.0", 1.0);
m_doubleStringSet = new Dictionary<double, string>();
m_doubleStringSet.Add(2.0, "2.000000");
m_doubleStringSet.Add(-2.0, "-2.000000");
m_doubleStringSet.Add(1.0, "1.000000");
m_doubleStringSet.Add(-1.0, "-1.000000");
m_doubleStringSet.Add(0.0, "0.000000");
m_doubleStringSet.Add(999999999.0, "999999999.000000");
m_doubleStringSet.Add(-99999999.0, "-99999999.000000");
m_doubleStringSet.Add(0.5, "0.500000");
m_doubleStringSet.Add(0.0005, "0.000500");
m_doubleStringSet.Add(0.6805, "0.680500");
m_doubleStringSet.Add(-0.5, "-0.500000");
m_doubleStringSet.Add(-0.0005, "-0.000500");
m_doubleStringSet.Add(-0.6805, "-0.680500");
m_doubleStringSet.Add(548.5, "548.500000");
m_doubleStringSet.Add(2.0005, "2.000500");
m_doubleStringSet.Add(349485435.6805, "349485435.680500");
m_doubleStringSet.Add(-548.5, "-548.500000");
m_doubleStringSet.Add(-2.0005, "-2.000500");
m_doubleStringSet.Add(-349485435.6805, "-349485435.680500");
m_doubleList = new List<double>();
m_doubleList.Add(2.0);
m_doubleList.Add(-2.0);
m_doubleList.Add(1.0);
m_doubleList.Add(-1.0);
m_doubleList.Add(999999999.0);
m_doubleList.Add(-99999999.0);
m_doubleList.Add(0.5);
m_doubleList.Add(0.0005);
m_doubleList.Add(0.6805);
m_doubleList.Add(-0.5);
m_doubleList.Add(-0.0005);
m_doubleList.Add(-0.6805);
m_doubleList.Add(548.5);
m_doubleList.Add(2.0005);
m_doubleList.Add(349485435.6805);
m_doubleList.Add(-548.5);
m_doubleList.Add(-2.0005);
m_doubleList.Add(-349485435.6805);
m_intList = new List<int>();
m_intList.Add(2);
m_intList.Add(-2);
m_intList.Add(0);
m_intList.Add(1);
m_intList.Add(-1);
m_intList.Add(999999999);
m_intList.Add(-99999999);
}
/// <summary>
/// Tests constructing a LSLFloat from an integer.
/// </summary>
[Test]
public void TestConstructFromInt()
{
TestHelpers.InMethod();
LSL_Types.LSLFloat testFloat;
foreach (KeyValuePair<int, double> number in m_intDoubleSet)
{
testFloat = new LSL_Types.LSLFloat(number.Key);
Assert.That(testFloat.value, new DoubleToleranceConstraint(number.Value, _lowPrecisionTolerance));
}
}
/// <summary>
/// Tests constructing a LSLFloat from a double.
/// </summary>
[Test]
public void TestConstructFromDouble()
{
TestHelpers.InMethod();
LSL_Types.LSLFloat testFloat;
foreach (KeyValuePair<double, double> number in m_doubleDoubleSet)
{
testFloat = new LSL_Types.LSLFloat(number.Key);
Assert.That(testFloat.value, new DoubleToleranceConstraint(number.Value, _lowPrecisionTolerance));
}
}
/// <summary>
/// Tests LSLFloat is correctly cast explicitly to integer.
/// </summary>
[Test]
public void TestExplicitCastLSLFloatToInt()
{
TestHelpers.InMethod();
int testNumber;
foreach (KeyValuePair<double, int> number in m_doubleIntSet)
{
testNumber = (int) new LSL_Types.LSLFloat(number.Key);
Assert.AreEqual(number.Value, testNumber, "Converting double " + number.Key + ", expecting int " + number.Value);
}
}
/// <summary>
/// Tests LSLFloat is correctly cast explicitly to unsigned integer.
/// </summary>
[Test]
public void TestExplicitCastLSLFloatToUint()
{
TestHelpers.InMethod();
uint testNumber;
foreach (KeyValuePair<double, int> number in m_doubleUintSet)
{
testNumber = (uint) new LSL_Types.LSLFloat(number.Key);
Assert.AreEqual(number.Value, testNumber, "Converting double " + number.Key + ", expecting uint " + number.Value);
}
}
/// <summary>
/// Tests LSLFloat is correctly cast implicitly to Boolean if non-zero.
/// </summary>
[Test]
public void TestImplicitCastLSLFloatToBooleanTrue()
{
TestHelpers.InMethod();
LSL_Types.LSLFloat testFloat;
bool testBool;
foreach (double number in m_doubleList)
{
testFloat = new LSL_Types.LSLFloat(number);
testBool = testFloat;
Assert.IsTrue(testBool);
}
}
/// <summary>
/// Tests LSLFloat is correctly cast implicitly to Boolean if zero.
/// </summary>
[Test]
public void TestImplicitCastLSLFloatToBooleanFalse()
{
TestHelpers.InMethod();
LSL_Types.LSLFloat testFloat = new LSL_Types.LSLFloat(0.0);
bool testBool = testFloat;
Assert.IsFalse(testBool);
}
/// <summary>
/// Tests integer is correctly cast implicitly to LSLFloat.
/// </summary>
[Test]
public void TestImplicitCastIntToLSLFloat()
{
TestHelpers.InMethod();
LSL_Types.LSLFloat testFloat;
foreach (int number in m_intList)
{
testFloat = number;
Assert.That(testFloat.value, new DoubleToleranceConstraint(number, _lowPrecisionTolerance));
}
}
/// <summary>
/// Tests LSLInteger is correctly cast implicitly to LSLFloat.
/// </summary>
[Test]
public void TestImplicitCastLSLIntegerToLSLFloat()
{
TestHelpers.InMethod();
LSL_Types.LSLFloat testFloat;
foreach (int number in m_intList)
{
testFloat = new LSL_Types.LSLInteger(number);
Assert.That(testFloat.value, new DoubleToleranceConstraint(number, _lowPrecisionTolerance));
}
}
/// <summary>
/// Tests LSLInteger is correctly cast explicitly to LSLFloat.
/// </summary>
[Test]
public void TestExplicitCastLSLIntegerToLSLFloat()
{
TestHelpers.InMethod();
LSL_Types.LSLFloat testFloat;
foreach (int number in m_intList)
{
testFloat = (LSL_Types.LSLFloat) new LSL_Types.LSLInteger(number);
Assert.That(testFloat.value, new DoubleToleranceConstraint(number, _lowPrecisionTolerance));
}
}
/// <summary>
/// Tests string is correctly cast explicitly to LSLFloat.
/// </summary>
[Test]
public void TestExplicitCastStringToLSLFloat()
{
TestHelpers.InMethod();
LSL_Types.LSLFloat testFloat;
foreach (KeyValuePair<string, double> number in m_stringDoubleSet)
{
testFloat = (LSL_Types.LSLFloat) number.Key;
Assert.That(testFloat.value, new DoubleToleranceConstraint(number.Value, _lowPrecisionTolerance));
}
}
/// <summary>
/// Tests LSLString is correctly cast implicitly to LSLFloat.
/// </summary>
[Test]
public void TestExplicitCastLSLStringToLSLFloat()
{
TestHelpers.InMethod();
LSL_Types.LSLFloat testFloat;
foreach (KeyValuePair<string, double> number in m_stringDoubleSet)
{
testFloat = (LSL_Types.LSLFloat) new LSL_Types.LSLString(number.Key);
Assert.That(testFloat.value, new DoubleToleranceConstraint(number.Value, _lowPrecisionTolerance));
}
}
/// <summary>
/// Tests double is correctly cast implicitly to LSLFloat.
/// </summary>
[Test]
public void TestImplicitCastDoubleToLSLFloat()
{
TestHelpers.InMethod();
LSL_Types.LSLFloat testFloat;
foreach (double number in m_doubleList)
{
testFloat = number;
Assert.That(testFloat.value, new DoubleToleranceConstraint(number, _lowPrecisionTolerance));
}
}
/// <summary>
/// Tests LSLFloat is correctly cast implicitly to double.
/// </summary>
[Test]
public void TestImplicitCastLSLFloatToDouble()
{
TestHelpers.InMethod();
double testNumber;
LSL_Types.LSLFloat testFloat;
foreach (double number in m_doubleList)
{
testFloat = new LSL_Types.LSLFloat(number);
testNumber = testFloat;
Assert.That(testNumber, new DoubleToleranceConstraint(number, _lowPrecisionTolerance));
}
}
/// <summary>
/// Tests LSLFloat is correctly cast explicitly to float
/// </summary>
[Test]
public void TestExplicitCastLSLFloatToFloat()
{
TestHelpers.InMethod();
float testFloat;
float numberAsFloat;
LSL_Types.LSLFloat testLSLFloat;
foreach (double number in m_doubleList)
{
testLSLFloat = new LSL_Types.LSLFloat(number);
numberAsFloat = (float)number;
testFloat = (float)testLSLFloat;
Assert.That((double)testFloat, new DoubleToleranceConstraint((double)numberAsFloat, _lowPrecisionTolerance));
}
}
/// <summary>
/// Tests the equality (==) operator.
/// </summary>
[Test]
public void TestEqualsOperator()
{
TestHelpers.InMethod();
LSL_Types.LSLFloat testFloatA, testFloatB;
foreach (double number in m_doubleList)
{
testFloatA = new LSL_Types.LSLFloat(number);
testFloatB = new LSL_Types.LSLFloat(number);
Assert.IsTrue(testFloatA == testFloatB);
testFloatB = new LSL_Types.LSLFloat(number + 1.0);
Assert.IsFalse(testFloatA == testFloatB);
}
}
/// <summary>
/// Tests the inequality (!=) operator.
/// </summary>
[Test]
public void TestNotEqualOperator()
{
TestHelpers.InMethod();
LSL_Types.LSLFloat testFloatA, testFloatB;
foreach (double number in m_doubleList)
{
testFloatA = new LSL_Types.LSLFloat(number);
testFloatB = new LSL_Types.LSLFloat(number + 1.0);
Assert.IsTrue(testFloatA != testFloatB);
testFloatB = new LSL_Types.LSLFloat(number);
Assert.IsFalse(testFloatA != testFloatB);
}
}
/// <summary>
/// Tests the increment operator.
/// </summary>
[Test]
public void TestIncrementOperator()
{
TestHelpers.InMethod();
LSL_Types.LSLFloat testFloat;
double testNumber;
foreach (double number in m_doubleList)
{
testFloat = new LSL_Types.LSLFloat(number);
testNumber = testFloat++;
Assert.That(testNumber, new DoubleToleranceConstraint(number, _lowPrecisionTolerance));
testNumber = testFloat;
Assert.That(testNumber, new DoubleToleranceConstraint(number + 1.0, _lowPrecisionTolerance));
testNumber = ++testFloat;
Assert.That(testNumber, new DoubleToleranceConstraint(number + 2.0, _lowPrecisionTolerance));
}
}
/// <summary>
/// Tests the decrement operator.
/// </summary>
[Test]
public void TestDecrementOperator()
{
TestHelpers.InMethod();
LSL_Types.LSLFloat testFloat;
double testNumber;
foreach (double number in m_doubleList)
{
testFloat = new LSL_Types.LSLFloat(number);
testNumber = testFloat--;
Assert.That(testNumber, new DoubleToleranceConstraint(number, _lowPrecisionTolerance));
testNumber = testFloat;
Assert.That(testNumber, new DoubleToleranceConstraint(number - 1.0, _lowPrecisionTolerance));
testNumber = --testFloat;
Assert.That(testNumber, new DoubleToleranceConstraint(number - 2.0, _lowPrecisionTolerance));
}
}
/// <summary>
/// Tests LSLFloat.ToString().
/// </summary>
[Test]
public void TestToString()
{
TestHelpers.InMethod();
LSL_Types.LSLFloat testFloat;
foreach (KeyValuePair<double, string> number in m_doubleStringSet)
{
testFloat = new LSL_Types.LSLFloat(number.Key);
Assert.AreEqual(number.Value, testFloat.ToString());
}
}
/// <summary>
/// Tests addition of two LSLFloats.
/// </summary>
[Test]
public void TestAddTwoLSLFloats()
{
TestHelpers.InMethod();
LSL_Types.LSLFloat testResult;
foreach (KeyValuePair<double, double> number in m_doubleDoubleSet)
{
testResult = new LSL_Types.LSLFloat(number.Key) + new LSL_Types.LSLFloat(number.Value);
Assert.That(testResult.value, new DoubleToleranceConstraint(number.Key + number.Value, _lowPrecisionTolerance));
}
}
/// <summary>
/// Tests subtraction of two LSLFloats.
/// </summary>
[Test]
public void TestSubtractTwoLSLFloats()
{
TestHelpers.InMethod();
LSL_Types.LSLFloat testResult;
foreach (KeyValuePair<double, double> number in m_doubleDoubleSet)
{
testResult = new LSL_Types.LSLFloat(number.Key) - new LSL_Types.LSLFloat(number.Value);
Assert.That(testResult.value, new DoubleToleranceConstraint(number.Key - number.Value, _lowPrecisionTolerance));
}
}
/// <summary>
/// Tests multiplication of two LSLFloats.
/// </summary>
[Test]
public void TestMultiplyTwoLSLFloats()
{
TestHelpers.InMethod();
LSL_Types.LSLFloat testResult;
foreach (KeyValuePair<double, double> number in m_doubleDoubleSet)
{
testResult = new LSL_Types.LSLFloat(number.Key) * new LSL_Types.LSLFloat(number.Value);
Assert.That(testResult.value, new DoubleToleranceConstraint(number.Key * number.Value, _lowPrecisionTolerance));
}
}
/// <summary>
/// Tests division of two LSLFloats.
/// </summary>
[Test]
public void TestDivideTwoLSLFloats()
{
TestHelpers.InMethod();
LSL_Types.LSLFloat testResult;
foreach (KeyValuePair<double, double> number in m_doubleDoubleSet)
{
if (number.Value != 0.0) // Let's avoid divide by zero.
{
testResult = new LSL_Types.LSLFloat(number.Key) / new LSL_Types.LSLFloat(number.Value);
Assert.That(testResult.value, new DoubleToleranceConstraint(number.Key / number.Value, _lowPrecisionTolerance));
}
}
}
/// <summary>
/// Tests boolean correctly cast implicitly to LSLFloat.
/// </summary>
[Test]
public void TestImplicitCastBooleanToLSLFloat()
{
TestHelpers.InMethod();
LSL_Types.LSLFloat testFloat;
testFloat = (1 == 0);
Assert.That(testFloat.value, new DoubleToleranceConstraint(0.0, _lowPrecisionTolerance));
testFloat = (1 == 1);
Assert.That(testFloat.value, new DoubleToleranceConstraint(1.0, _lowPrecisionTolerance));
testFloat = false;
Assert.That(testFloat.value, new DoubleToleranceConstraint(0.0, _lowPrecisionTolerance));
testFloat = true;
Assert.That(testFloat.value, new DoubleToleranceConstraint(1.0, _lowPrecisionTolerance));
}
}
}
| |
//
// Copyright 2014-2015 Amazon.com,
// Inc. or its affiliates. All Rights Reserved.
//
// Licensed under the Amazon Software License (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/asl/
//
// or in the "license" file accompanying this file. This file is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
// CONDITIONS OF ANY KIND, express or implied. See the License
// for the specific language governing permissions and
// limitations under the License.
//
using System;
using System.Text;
using System.Collections.Generic;
using Amazon.Runtime;
using System.Runtime.InteropServices;
namespace Amazon.Util.Storage.Internal
{
public class SQLiteDatabase
{
public enum Result : int
{
SQLITE_OK = 0, /* Successful result */
SQLITE_ERROR = 1, /* SQL error or missing database */
SQLITE_INTERNAL = 2, /* An internal logic error in SQLite */
SQLITE_PERM = 3, /* Access permission denied */
SQLITE_ABORT = 4, /* Callback routine requested an abort */
SQLITE_BUSY = 5, /* The database file is locked */
SQLITE_LOCKED = 6, /* A table in the database is locked */
SQLITE_NOMEM = 7, /* A malloc() failed */
SQLITE_READONLY = 8, /* Attempt to write a readonly database */
SQLITE_INTERRUPT = 9, /* Operation terminated by sqlite_interrupt() */
SQLITE_IOERR = 10, /* Some kind of disk I/O error occurred */
SQLITE_CORRUPT = 11, /* The database disk image is malformed */
SQLITE_NOTFOUND = 12, /* (Internal Only) Table or record not found */
SQLITE_FULL = 13, /* Insertion failed because database is full */
SQLITE_CANTOPEN = 14, /* Unable to open the database file */
SQLITE_PROTOCOL = 15, /* Database lock protocol error */
SQLITE_EMPTY = 16, /* (Internal Only) Database table is empty */
SQLITE_SCHEMA = 17, /* The database schema changed */
SQLITE_TOOBIG = 18, /* Too much data for one row of a table */
SQLITE_CONSTRAINT = 19, /* Abort due to constraint violation */
SQLITE_MISMATCH = 20, /* Data type mismatch */
SQLITE_MISUSE = 21, /* Library used incorrectly */
SQLITE_NOLFS = 22, /* Uses OS features not supported on host */
SQLITE_AUTH = 23, /* Authorization denied */
SQLITE_FORMAT = 24, /* Auxiliary database format error */
SQLITE_RANGE = 25, /* 2nd parameter to sqlite3_bind out of range */
SQLITE_NOTADB = 26, /* File opened that is not a database file */
SQLITE_NOTICE = 27, /* Notifications from sqlite3_log() */
SQLITE_WARNING = 28, /* Warnings from sqlite3_log() */
SQLITE_ROW = 100, /* sqlite_step() has another row ready */
SQLITE_DONE = 101 /* sqlite_step() has finished executing */
}
public enum DataType : int
{
INTEGER = 1,
FLOAT = 2,
TEXT = 3,
BLOB = 4,
NULL = 5
}
[DllImport("sqlite3", EntryPoint = "sqlite3_open")]
public static extern Result sqlite3_open(string filename, out IntPtr db);
[DllImport("sqlite3", EntryPoint = "sqlite3_close")]
public static extern Result sqlite3_close(IntPtr db);
[DllImport("sqlite3", EntryPoint = "sqlite3_prepare_v2")]
public static extern Result sqlite3_prepare_v2(IntPtr db, string zSql, int nByte, out IntPtr ppStmpt, IntPtr pzTail);
[DllImport("sqlite3.dll", EntryPoint = "sqlite3_exec")]
public static extern Result exec(IntPtr hDb, string sql, IntPtr callback, IntPtr args, out IntPtr errorMessage);
[DllImport("sqlite3", EntryPoint = "sqlite3_step")]
public static extern Result sqlite3_step(IntPtr hStmt);
[DllImport("sqlite3", EntryPoint = "sqlite3_finalize")]
public static extern Result sqlite3_finalize(IntPtr hStmt);
[DllImport("sqlite3", EntryPoint = "sqlite3_errmsg")]
public static extern IntPtr sqlite3_errmsg(IntPtr db);
[DllImport("sqlite3", EntryPoint = "sqlite3_column_count")]
public static extern int sqlite3_column_count(IntPtr hStmt);
[DllImport("sqlite3", EntryPoint = "sqlite3_column_name")]
public static extern IntPtr sqlite3_column_name(IntPtr hStmt, int iCol);
[DllImport("sqlite3", EntryPoint = "sqlite3_column_type")]
public static extern DataType sqlite3_column_type(IntPtr hStmt, int iCol);
[DllImport("sqlite3.dll", EntryPoint = "sqlite3_column_int64")]
public static extern long sqlite3_column_int64(IntPtr hStmt, int nCol);
[DllImport("sqlite3", EntryPoint = "sqlite3_column_text")]
public static extern IntPtr sqlite3_column_text(IntPtr hStmt, int iCol);
[DllImport("sqlite3", EntryPoint = "sqlite3_column_blob")]
public static extern IntPtr sqlite3_column_blob(IntPtr hStmt, int iCol);
[DllImport("sqlite3", EntryPoint = "sqlite3_column_bytes")]
public static extern Result sqlite3_column_bytes(IntPtr hStmt, int iCol);
[DllImport("sqlite3.dll", EntryPoint = "sqlite3_bind_int64")]
public static extern Result sqlite3_bind_int64(IntPtr hStmt, int n, long value);
[DllImport("sqlite3.dll", EntryPoint = "sqlite3_bind_null")]
public static extern Result sqlite3_bind_null(IntPtr hStmt, int n);
[DllImport("sqlite3.dll", EntryPoint = "sqlite3_bind_text")]
public static extern Result sqlite3_bind_text(IntPtr hStmt, int n, byte[] value, int length, IntPtr freetype);
[DllImport("sqlite3.dll", EntryPoint = "sqlite3_last_insert_rowid")]
public static extern long sqlite3_last_insert_rowid(IntPtr hDb);
[DllImport("sqlite3.dll", EntryPoint = "sqlite3_reset")]
public static extern Result sqlite3_reset(IntPtr hStmt);
[DllImport("sqlite3.dll", EntryPoint = "sqlite3_clear_bindings")] //
public static extern Result sqlite3_clear_bindings(IntPtr hStmt);
public static byte[] StringToUTF8ByteArray(string sText)
{
byte[] byteArray;
int nLen = Encoding.UTF8.GetByteCount(sText) + 1;
byteArray = new byte[nLen];
nLen = Encoding.UTF8.GetBytes(sText, 0, sText.Length, byteArray, 0);
byteArray[nLen] = 0;
return byteArray;
}
public static string PtrToString(IntPtr ptr)
{
return Marshal.PtrToStringAnsi(ptr);
}
private string dbPath;
internal IntPtr hDb = IntPtr.Zero;
public SQLiteDatabase(string dbPath)
{
if (dbPath == null)
throw new ArgumentNullException("dataPath");
this.dbPath = dbPath;
if (SQLiteDatabase.sqlite3_open(dbPath, out hDb) != SQLiteDatabase.Result.SQLITE_OK)
throw new AmazonClientException("Could not open database file: " + dbPath);
}
public void CloseDatabase()
{
if (hDb != IntPtr.Zero)
{
SQLiteDatabase.sqlite3_close(hDb);
hDb = IntPtr.Zero;
}
}
public SQLiteStatement Prepare(string SQL)
{
if (hDb == IntPtr.Zero)
throw new AmazonClientException("Database closed: " + dbPath);
return new SQLiteStatement(this, SQL);
}
public void OpenDatabase()
{
if (SQLiteDatabase.sqlite3_open(dbPath, out hDb) != SQLiteDatabase.Result.SQLITE_OK)
throw new AmazonClientException("Could not open database file: " + dbPath);
}
public long LastInsertRowid()
{
return SQLiteDatabase.sqlite3_last_insert_rowid(hDb);
}
public void Exec(string SQL)
{
IntPtr hError;
Result exitCode;
if (hDb == IntPtr.Zero)
throw new AmazonClientException("SQLite database is not open.");
exitCode = SQLiteDatabase.exec(hDb, SQL, IntPtr.Zero, IntPtr.Zero, out hError);
if (exitCode != SQLiteDatabase.Result.SQLITE_OK)
throw new AmazonClientException("Could not execute SQL statement." + ErrorMsg());
}
public String ErrorMsg()
{
return PtrToString(sqlite3_errmsg(this.hDb));
}
}
public class SQLiteStatement
{
private IntPtr hStmt = IntPtr.Zero;
private SQLiteDatabase db;
internal SQLiteStatement(SQLiteDatabase db, string query)
{
this.db = db;
SQLiteDatabase.Result exitCode = SQLiteDatabase.sqlite3_prepare_v2(db.hDb, query, -1, out hStmt, IntPtr.Zero);
if (exitCode != SQLiteDatabase.Result.SQLITE_OK)
throw new AmazonClientException(exitCode + " - " + db.ErrorMsg());
}
public SQLiteStatement Step()
{
SQLiteDatabase.Result eResult = SQLiteDatabase.sqlite3_step(this.hStmt);
if (eResult != SQLiteDatabase.Result.SQLITE_DONE)
throw new AmazonClientException(db.ErrorMsg());
return this;
}
public SQLiteStatement BindText(int column, string inputString)
{
SQLiteDatabase.Result exitCode;
if (inputString == null)
exitCode = SQLiteDatabase.sqlite3_bind_null(hStmt, column);
else
exitCode = SQLiteDatabase.sqlite3_bind_text(hStmt, column, SQLiteDatabase.StringToUTF8ByteArray(inputString), -1, new IntPtr(-1));
if (exitCode != SQLiteDatabase.Result.SQLITE_OK)
throw new AmazonServiceException(exitCode + " - " + db.ErrorMsg());
return this;
}
public SQLiteStatement BindInt(int column, long? inputInt)
{
SQLiteDatabase.Result exitCode;
if (inputInt == null)
exitCode = SQLiteDatabase.sqlite3_bind_null(hStmt, column);
else
exitCode = SQLiteDatabase.sqlite3_bind_int64(hStmt, column, (long)inputInt);
if (exitCode != SQLiteDatabase.Result.SQLITE_OK)
throw new AmazonClientException(exitCode + " - " + db.ErrorMsg());
return this;
}
public SQLiteStatement BindDateTime(int column, DateTime? inputDateTime)
{
return BindText(column, (inputDateTime == null ? null : inputDateTime.Value.ToUniversalTime().Ticks.ToString()));
}
public Dictionary<string, SQLiteField> Fields = new Dictionary<string, SQLiteField>();
public bool Read()
{
bool bContinue = false;
SQLiteField field;
SQLiteDatabase.Result exitCode = SQLiteDatabase.sqlite3_step(this.hStmt);
if (exitCode == SQLiteDatabase.Result.SQLITE_DONE)
{
//return false;
}
else if (exitCode == SQLiteDatabase.Result.SQLITE_ROW)
{
int columns = SQLiteDatabase.sqlite3_column_count(hStmt);
Fields.Clear();
for (int column = 0; column < columns; column++)
{
field = new SQLiteField(hStmt);
field.column = column;
field.name = Marshal.PtrToStringAnsi(SQLiteDatabase.sqlite3_column_name(hStmt, column));
field.Read();
Fields.Add(field.name, field);
}
bContinue = true;
}
else
{
throw new AmazonClientException(exitCode + "\n" + SQLiteDatabase.sqlite3_errmsg(db.hDb));
}
return bContinue;
}
public SQLiteStatement Reset()
{
if (SQLiteDatabase.sqlite3_reset(hStmt) != SQLiteDatabase.Result.SQLITE_OK)
throw new AmazonClientException(db.ErrorMsg());
return this;
}
public SQLiteStatement ClearBindings()
{
if (SQLiteDatabase.sqlite3_clear_bindings(hStmt) != SQLiteDatabase.Result.SQLITE_OK)
throw new AmazonClientException(db.ErrorMsg());
return this;
}
public SQLiteStatement FinalizeStm()
{
if (SQLiteDatabase.sqlite3_finalize(hStmt) != SQLiteDatabase.Result.SQLITE_OK)
throw new AmazonClientException(db.ErrorMsg());
this.hStmt = IntPtr.Zero;
return this;
}
}
public class SQLiteField
{
public string name;
public int column;
public SQLiteDatabase.DataType eType;
public long nValue;
public string sValue;
public double fValue;
public bool bNull;
private IntPtr hStm = IntPtr.Zero;
public SQLiteField(IntPtr hStm)
{
this.hStm = hStm;
}
public void Read()
{
bNull = false;
nValue = 0;
sValue = "";
fValue = 0d;
eType = SQLiteDatabase.sqlite3_column_type(hStm, column);
switch (eType)
{
case SQLiteDatabase.DataType.NULL:
bNull = true;
break;
case SQLiteDatabase.DataType.INTEGER:
nValue = SQLiteDatabase.sqlite3_column_int64(hStm, column);
break;
case SQLiteDatabase.DataType.TEXT:
sValue = SQLiteDatabase.PtrToString(SQLiteDatabase.sqlite3_column_text(hStm, column));
break;
default:
throw new AmazonClientException("Unknown datatype");
}
}
public bool IsNull()
{
return bNull;
}
public bool BOOL
{
get
{
if (eType != SQLiteDatabase.DataType.INTEGER)
throw new AmazonClientException("Datatype: " + eType.ToString());
return (nValue != 0);
}
}
public string TEXT
{
get
{
if (IsNull())
return null;
if (eType != SQLiteDatabase.DataType.TEXT)
throw new AmazonClientException("Datatype: " + eType.ToString());
return sValue;
}
}
public long INTEGER
{
get
{
if (eType != SQLiteDatabase.DataType.INTEGER)
throw new AmazonClientException("Datatype: " + eType.ToString());
return nValue;
}
}
public DateTime? DATETIME
{
get
{
if (IsNull())
return null;
if (eType != SQLiteDatabase.DataType.TEXT)
throw new AmazonClientException("Datatype: " + eType.ToString());
return sValue == null ? (DateTime?)null : new DateTime(long.Parse(sValue)).ToLocalTime();
}
}
}
}
| |
using System;
using System.Linq;
using System.Collections;
using System.Xml;
using Umbraco.Core;
using Umbraco.Core.Cache;
using Umbraco.Core.Configuration;
using Umbraco.Core.IO;
using Umbraco.Core.Logging;
using umbraco.DataLayer;
using System.Text.RegularExpressions;
using System.IO;
using System.Collections.Generic;
using umbraco.cms.businesslogic.cache;
using umbraco.BusinessLogic;
using umbraco.cms.businesslogic.web;
namespace umbraco.cms.businesslogic.template
{
/// <summary>
/// Summary description for Template.
/// </summary>
//[Obsolete("Obsolete, This class will eventually be phased out - Use Umbraco.Core.Models.Template", false)]
public class Template : CMSNode
{
#region Private members
private string _OutputContentType;
private string _design;
private string _alias;
private string _oldAlias;
private int _mastertemplate;
private bool _hasChildrenInitialized = false;
private bool _hasChildren;
#endregion
#region Static members
public static readonly string UmbracoMasterTemplate = SystemDirectories.Umbraco + "/masterpages/default.master";
private static Hashtable _templateAliases = new Hashtable();
private static volatile bool _templateAliasesInitialized = false;
private static readonly object TemplateLoaderLocker = new object();
private static readonly Guid ObjectType = new Guid(Constants.ObjectTypes.Template);
private static readonly char[] NewLineChars = Environment.NewLine.ToCharArray();
#endregion
[Obsolete("Use TemplateFilePath instead")]
public string MasterPageFile
{
get { return TemplateFilePath; }
}
/// <summary>
/// Returns the file path for the current template
/// </summary>
public string TemplateFilePath
{
get
{
switch (DetermineRenderingEngine(this))
{
case RenderingEngine.Mvc:
return ViewHelper.GetFilePath(this);
case RenderingEngine.WebForms:
return MasterPageHelper.GetFilePath(this);
default:
throw new ArgumentOutOfRangeException();
}
}
}
public static Hashtable TemplateAliases
{
get { return _templateAliases; }
set { _templateAliases = value; }
}
#region Constructors
public Template(int id) : base(id) { }
public Template(Guid id) : base(id) { }
#endregion
/// <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)
{
base.Save();
FireAfterSave(e);
}
}
public string GetRawText()
{
return base.Text;
}
public override string Text
{
get
{
string tempText = base.Text;
if (!tempText.StartsWith("#"))
return tempText;
else
{
language.Language lang = language.Language.GetByCultureCode(System.Threading.Thread.CurrentThread.CurrentCulture.Name);
if (lang != null)
{
if (Dictionary.DictionaryItem.hasKey(tempText.Substring(1, tempText.Length - 1)))
{
Dictionary.DictionaryItem di = new Dictionary.DictionaryItem(tempText.Substring(1, tempText.Length - 1));
if (di != null)
return di.Value(lang.id);
}
}
return "[" + tempText + "]";
}
}
set
{
FlushCache();
base.Text = value;
}
}
public string OutputContentType
{
get { return _OutputContentType; }
set { _OutputContentType = value; }
}
protected override void setupNode()
{
base.setupNode();
IRecordsReader dr = SqlHelper.ExecuteReader("Select alias,design,master from cmsTemplate where nodeId = " + this.Id);
bool hasRows = dr.Read();
if (hasRows)
{
_alias = dr.GetString("alias");
_design = dr.GetString("design");
//set the master template to zero if it's null
_mastertemplate = dr.IsNull("master") ? 0 : dr.GetInt("master");
}
dr.Close();
if (UmbracoConfig.For.UmbracoSettings().Templates.DefaultRenderingEngine == RenderingEngine.Mvc && ViewHelper.ViewExists(this))
_design = ViewHelper.GetFileContents(this);
else
_design = MasterPageHelper.GetFileContents(this);
}
public new string Path
{
get
{
List<int> path = new List<int>();
Template working = this;
while (working != null)
{
path.Add(working.Id);
try
{
if (working.MasterTemplate != 0)
{
working = new Template(working.MasterTemplate);
}
else
{
working = null;
}
}
catch (ArgumentException)
{
working = null;
}
}
path.Add(-1);
path.Reverse();
string sPath = string.Join(",", path.ConvertAll(item => item.ToString()).ToArray());
return sPath;
}
set
{
base.Path = value;
}
}
public string Alias
{
get { return _alias; }
set
{
FlushCache();
_oldAlias = _alias;
_alias = value.ToSafeAlias();
SqlHelper.ExecuteNonQuery("Update cmsTemplate set alias = @alias where NodeId = " + this.Id, SqlHelper.CreateParameter("@alias", _alias));
_templateAliasesInitialized = false;
InitTemplateAliases();
}
}
public bool HasMasterTemplate
{
get { return (_mastertemplate > 0); }
}
public override bool HasChildren
{
get
{
if (!_hasChildrenInitialized)
{
_hasChildren = SqlHelper.ExecuteScalar<int>("select count(NodeId) as tmp from cmsTemplate where master = " + Id) > 0;
}
return _hasChildren;
}
set
{
_hasChildrenInitialized = true;
_hasChildren = value;
}
}
public int MasterTemplate
{
get { return _mastertemplate; }
set
{
FlushCache();
_mastertemplate = value;
//set to null if it's zero
object masterVal = value;
if (value == 0) masterVal = DBNull.Value;
SqlHelper.ExecuteNonQuery("Update cmsTemplate set master = @master where NodeId = @nodeId",
SqlHelper.CreateParameter("@master", masterVal),
SqlHelper.CreateParameter("@nodeId", this.Id));
}
}
public string Design
{
get { return _design; }
set
{
FlushCache();
_design = value.Trim(NewLineChars);
//we only switch to MVC View editing if the template has a view file, and MVC editing is enabled
if (UmbracoConfig.For.UmbracoSettings().Templates.DefaultRenderingEngine == RenderingEngine.Mvc && !MasterPageHelper.IsMasterPageSyntax(_design))
{
MasterPageHelper.RemoveMasterPageFile(this.Alias);
MasterPageHelper.RemoveMasterPageFile(_oldAlias);
_design = ViewHelper.UpdateViewFile(this, _oldAlias);
}
else if (UmbracoConfig.For.UmbracoSettings().Templates.UseAspNetMasterPages)
{
ViewHelper.RemoveViewFile(this.Alias);
ViewHelper.RemoveViewFile(_oldAlias);
_design = MasterPageHelper.UpdateMasterPageFile(this, _oldAlias);
}
SqlHelper.ExecuteNonQuery("Update cmsTemplate set design = @design where NodeId = @id",
SqlHelper.CreateParameter("@design", _design),
SqlHelper.CreateParameter("@id", Id));
}
}
public XmlNode ToXml(XmlDocument doc)
{
XmlNode template = doc.CreateElement("Template");
template.AppendChild(xmlHelper.addTextNode(doc, "Name", base.Text));
template.AppendChild(xmlHelper.addTextNode(doc, "Alias", this.Alias));
if (this.MasterTemplate != 0)
{
template.AppendChild(xmlHelper.addTextNode(doc, "Master", new Template(this.MasterTemplate).Alias));
}
template.AppendChild(xmlHelper.addCDataNode(doc, "Design", this.Design));
return template;
}
/// <summary>
/// Removes any references to this templates from child templates, documenttypes and documents
/// </summary>
public void RemoveAllReferences()
{
if (HasChildren)
{
foreach (Template t in Template.GetAllAsList().FindAll(delegate(Template t) { return t.MasterTemplate == this.Id; }))
{
t.MasterTemplate = 0;
}
}
RemoveFromDocumentTypes();
// remove from documents
Document.RemoveTemplateFromDocument(this.Id);
}
public void RemoveFromDocumentTypes()
{
foreach (DocumentType dt in DocumentType.GetAllAsList().Where(x => x.allowedTemplates.Select(t => t.Id).Contains(this.Id)))
{
dt.RemoveTemplate(this.Id);
dt.Save();
}
}
public IEnumerable<DocumentType> GetDocumentTypes()
{
return DocumentType.GetAllAsList().Where(x => x.allowedTemplates.Select(t => t.Id).Contains(this.Id));
}
/// <summary>
/// This checks what the default rendering engine is set in config but then also ensures that there isn't already
/// a template that exists in the opposite rendering engine's template folder, then returns the appropriate
/// rendering engine to use.
/// </summary>
/// <param name="t"></param>
/// <param name="design">If a template body is specified we'll check if it contains master page markup, if it does we'll auto assume its webforms </param>
/// <returns></returns>
/// <remarks>
/// The reason this is required is because for example, if you have a master page file already existing under ~/masterpages/Blah.aspx
/// and then you go to create a template in the tree called Blah and the default rendering engine is MVC, it will create a Blah.cshtml
/// empty template in ~/Views. This means every page that is using Blah will go to MVC and render an empty page.
/// This is mostly related to installing packages since packages install file templates to the file system and then create the
/// templates in business logic. Without this, it could cause the wrong rendering engine to be used for a package.
/// </remarks>
private static RenderingEngine DetermineRenderingEngine(Template t, string design = null)
{
var engine = UmbracoConfig.For.UmbracoSettings().Templates.DefaultRenderingEngine;
if (!design.IsNullOrWhiteSpace() && MasterPageHelper.IsMasterPageSyntax(design))
{
//there is a design but its definitely a webforms design
return RenderingEngine.WebForms;
}
switch (engine)
{
case RenderingEngine.Mvc:
//check if there's a view in ~/masterpages
if (MasterPageHelper.MasterPageExists(t) && !ViewHelper.ViewExists(t))
{
//change this to webforms since there's already a file there for this template alias
engine = RenderingEngine.WebForms;
}
break;
case RenderingEngine.WebForms:
//check if there's a view in ~/views
if (ViewHelper.ViewExists(t) && !MasterPageHelper.MasterPageExists(t))
{
//change this to mvc since there's already a file there for this template alias
engine = RenderingEngine.Mvc;
}
break;
}
return engine;
}
public static Template MakeNew(string Name, BusinessLogic.User u, Template master)
{
return MakeNew(Name, u, master, null);
}
private static Template MakeNew(string name, BusinessLogic.User u, string design)
{
return MakeNew(name, u, null, design);
}
public static Template MakeNew(string name, BusinessLogic.User u)
{
return MakeNew(name, u, design: null);
}
private static Template MakeNew(string name, BusinessLogic.User u, Template master, string design)
{
// CMSNode MakeNew(int parentId, Guid objectType, int userId, int level, string text, Guid uniqueID)
var node = MakeNew(-1, ObjectType, u.Id, 1, name, Guid.NewGuid());
//ensure unique alias
name = name.ToSafeAlias();
if (GetByAlias(name) != null)
name = EnsureUniqueAlias(name, 1);
//name = name.Replace("/", ".").Replace("\\", ""); //why? ToSafeAlias() already removes those chars
if (name.Length > 100)
name = name.Substring(0, 98); // + "..."; // no, these are invalid alias chars
SqlHelper.ExecuteNonQuery("INSERT INTO cmsTemplate (NodeId, Alias, design, master) VALUES (@nodeId, @alias, @design, @master)",
SqlHelper.CreateParameter("@nodeId", node.Id),
SqlHelper.CreateParameter("@alias", name),
SqlHelper.CreateParameter("@design", ' '),
SqlHelper.CreateParameter("@master", DBNull.Value));
var template = new Template(node.Id);
if (master != null)
template.MasterTemplate = master.Id;
switch (DetermineRenderingEngine(template, design))
{
case RenderingEngine.Mvc:
ViewHelper.CreateViewFile(template);
break;
case RenderingEngine.WebForms:
MasterPageHelper.CreateMasterPage(template);
break;
}
//if a design is supplied ensure it is updated.
if (design.IsNullOrWhiteSpace() == false)
{
template.ImportDesign(design);
}
var e = new NewEventArgs();
template.OnNew(e);
return template;
}
private static string EnsureUniqueAlias(string alias, int attempts)
{
if (GetByAlias(alias + attempts.ToString()) == null)
return alias + attempts.ToString();
else
{
attempts++;
return EnsureUniqueAlias(alias, attempts);
}
}
public static Template GetByAlias(string Alias)
{
return GetByAlias(Alias, false);
}
public static Template GetByAlias(string Alias, bool useCache)
{
if (!useCache)
{
try
{
return new Template(SqlHelper.ExecuteScalar<int>("select nodeId from cmsTemplate where alias = @alias", SqlHelper.CreateParameter("@alias", Alias)));
}
catch
{
return null;
}
}
//return from cache instead
var id = GetTemplateIdFromAlias(Alias);
return id == 0 ? null : GetTemplate(id);
}
[Obsolete("Obsolete, please use GetAllAsList() method instead", true)]
public static Template[] getAll()
{
return GetAllAsList().ToArray();
}
public static List<Template> GetAllAsList()
{
Guid[] ids = CMSNode.TopMostNodeIds(ObjectType);
List<Template> retVal = new List<Template>();
foreach (Guid id in ids)
{
retVal.Add(new Template(id));
}
retVal.Sort(delegate(Template t1, Template t2) { return t1.Text.CompareTo(t2.Text); });
return retVal;
}
public static int GetTemplateIdFromAlias(string alias)
{
alias = alias.ToLower();
InitTemplateAliases();
if (TemplateAliases.ContainsKey(alias))
return (int)TemplateAliases[alias];
else
return 0;
}
private static void InitTemplateAliases()
{
if (!_templateAliasesInitialized)
{
lock (TemplateLoaderLocker)
{
//double check
if (!_templateAliasesInitialized)
{
_templateAliases.Clear();
foreach (Template t in GetAllAsList())
TemplateAliases.Add(t.Alias.ToLower(), t.Id);
_templateAliasesInitialized = true;
}
}
}
}
public override void delete()
{
// don't allow template deletion if it has child templates
if (this.HasChildren)
{
var ex = new InvalidOperationException("Can't delete a master template. Remove any bindings from child templates first.");
LogHelper.Error<Template>("Can't delete a master template. Remove any bindings from child templates first.", ex);
throw ex;
}
// NH: Changed this; if you delete a template we'll remove all references instead of
// throwing an exception
if (DocumentType.GetAllAsList().Where(x => x.allowedTemplates.Select(t => t.Id).Contains(this.Id)).Count() > 0)
RemoveAllReferences();
DeleteEventArgs e = new DeleteEventArgs();
FireBeforeDelete(e);
if (!e.Cancel)
{
//re-set the template aliases
_templateAliasesInitialized = false;
InitTemplateAliases();
//delete the template
SqlHelper.ExecuteNonQuery("delete from cmsTemplate where NodeId =" + this.Id);
base.delete();
// remove masterpages
if (System.IO.File.Exists(MasterPageFile))
System.IO.File.Delete(MasterPageFile);
if (System.IO.File.Exists(Umbraco.Core.IO.IOHelper.MapPath(ViewHelper.ViewPath(this.Alias))))
System.IO.File.Delete(Umbraco.Core.IO.IOHelper.MapPath(ViewHelper.ViewPath(this.Alias)));
FireAfterDelete(e);
}
}
[Obsolete("This method, doesnt actually do anything, as the file is created when the design is set", false)]
public void _SaveAsMasterPage()
{
//SaveMasterPageFile(ConvertToMasterPageSyntax(Design));
}
public string GetMasterContentElement(int masterTemplateId)
{
if (masterTemplateId != 0)
{
string masterAlias = new Template(masterTemplateId).Alias.Replace(" ", "");
return
String.Format("<asp:Content ContentPlaceHolderID=\"{1}ContentPlaceHolder\" runat=\"server\">",
Alias.Replace(" ", ""), masterAlias);
}
else
return
String.Format("<asp:Content ContentPlaceHolderID=\"ContentPlaceHolderDefault\" runat=\"server\">",
Alias.Replace(" ", ""));
}
public List<string> contentPlaceholderIds()
{
List<string> retVal = new List<string>();
string masterPageFile = this.MasterPageFile;
string mp = System.IO.File.ReadAllText(masterPageFile);
string pat = "<asp:ContentPlaceHolder+(\\s+[a-zA-Z]+\\s*=\\s*(\"([^\"]*)\"|'([^']*)'))*\\s*/?>";
Regex r = new Regex(pat, RegexOptions.IgnoreCase);
Match m = r.Match(mp);
while (m.Success)
{
CaptureCollection cc = m.Groups[3].Captures;
foreach (Capture c in cc)
{
if (c.Value != "server")
retVal.Add(c.Value);
}
m = m.NextMatch();
}
return retVal;
}
public string ConvertToMasterPageSyntax(string templateDesign)
{
string masterPageContent = GetMasterContentElement(MasterTemplate) + Environment.NewLine;
masterPageContent += templateDesign;
// Parse the design for getitems
masterPageContent = EnsureMasterPageSyntax(masterPageContent);
// append ending asp:content element
masterPageContent += Environment.NewLine
+ "</asp:Content>"
+ Environment.NewLine;
return masterPageContent;
}
public string EnsureMasterPageSyntax(string masterPageContent)
{
ReplaceElement(ref masterPageContent, "?UMBRACO_GETITEM", "umbraco:Item", true);
ReplaceElement(ref masterPageContent, "?UMBRACO_GETITEM", "umbraco:Item", false);
// Parse the design for macros
ReplaceElement(ref masterPageContent, "?UMBRACO_MACRO", "umbraco:Macro", true);
ReplaceElement(ref masterPageContent, "?UMBRACO_MACRO", "umbraco:Macro", false);
// Parse the design for load childs
masterPageContent = masterPageContent.Replace("<?UMBRACO_TEMPLATE_LOAD_CHILD/>", GetAspNetMasterPageContentContainer()).Replace("<?UMBRACO_TEMPLATE_LOAD_CHILD />", GetAspNetMasterPageContentContainer());
// Parse the design for aspnet forms
GetAspNetMasterPageForm(ref masterPageContent);
masterPageContent = masterPageContent.Replace("</?ASPNET_FORM>", "</form>");
// Parse the design for aspnet heads
masterPageContent = masterPageContent.Replace("</ASPNET_HEAD>", String.Format("<head id=\"{0}Head\" runat=\"server\">", Alias.Replace(" ", "")));
masterPageContent = masterPageContent.Replace("</?ASPNET_HEAD>", "</head>");
return masterPageContent;
}
public void ImportDesign(string design)
{
Design = design;
}
public void SaveMasterPageFile(string masterPageContent)
{
//this will trigger the helper and store everything
this.Design = masterPageContent;
}
private void GetAspNetMasterPageForm(ref string design)
{
Match formElement = Regex.Match(design, GetElementRegExp("?ASPNET_FORM", false), RegexOptions.IgnoreCase | RegexOptions.IgnorePatternWhitespace);
if (formElement != null && formElement.Value != "")
{
string formReplace = String.Format("<form id=\"{0}Form\" runat=\"server\">", Alias.Replace(" ", ""));
if (formElement.Groups.Count == 0)
{
formReplace += "<asp:scriptmanager runat=\"server\"></asp:scriptmanager>";
}
design = design.Replace(formElement.Value, formReplace);
}
}
private string GetAspNetMasterPageContentContainer()
{
return String.Format(
"<asp:ContentPlaceHolder ID=\"{0}ContentPlaceHolder\" runat=\"server\"></asp:ContentPlaceHolder>",
Alias.Replace(" ", ""));
}
private void ReplaceElement(ref string design, string elementName, string newElementName, bool checkForQuotes)
{
MatchCollection m =
Regex.Matches(design, GetElementRegExp(elementName, checkForQuotes),
RegexOptions.IgnoreCase | RegexOptions.IgnorePatternWhitespace);
foreach (Match match in m)
{
GroupCollection groups = match.Groups;
// generate new element (compensate for a closing trail on single elements ("/"))
string elementAttributes = groups[1].Value;
// test for macro alias
if (elementName == "?UMBRACO_MACRO")
{
Hashtable tags = helpers.xhtml.ReturnAttributes(match.Value);
if (tags["macroAlias"] != null)
elementAttributes = String.Format(" Alias=\"{0}\"", tags["macroAlias"].ToString()) + elementAttributes;
else if (tags["macroalias"] != null)
elementAttributes = String.Format(" Alias=\"{0}\"", tags["macroalias"].ToString()) + elementAttributes;
}
string newElement = "<" + newElementName + " runat=\"server\" " + elementAttributes.Trim() + ">";
if (elementAttributes.EndsWith("/"))
{
elementAttributes = elementAttributes.Substring(0, elementAttributes.Length - 1);
}
else if (groups[0].Value.StartsWith("</"))
// It's a closing element, so generate that instead of a starting element
newElement = "</" + newElementName + ">";
if (checkForQuotes)
{
// if it's inside quotes, we'll change element attribute quotes to single quotes
newElement = newElement.Replace("\"", "'");
newElement = String.Format("\"{0}\"", newElement);
}
design = design.Replace(match.Value, newElement);
}
}
private string GetElementRegExp(string elementName, bool checkForQuotes)
{
if (checkForQuotes)
return String.Format("\"<[^>\\s]*\\b{0}(\\b[^>]*)>\"", elementName);
else
return String.Format("<[^>\\s]*\\b{0}(\\b[^>]*)>", elementName);
}
[Obsolete("Umbraco automatically ensures that template cache is cleared when saving or deleting")]
protected virtual void FlushCache()
{
ApplicationContext.Current.ApplicationCache.ClearCacheItem(GetCacheKey(Id));
}
public static Template GetTemplate(int id)
{
return ApplicationContext.Current.ApplicationCache.GetCacheItem(
GetCacheKey(id),
TimeSpan.FromMinutes(30),
() =>
{
try
{
return new Template(id);
}
catch
{
return null;
}
});
}
private static string GetCacheKey(int id)
{
return CacheKeys.TemplateBusinessLogicCacheKey + id;
}
public static Template Import(XmlNode n, User u)
{
var element = System.Xml.Linq.XElement.Parse(n.OuterXml);
var templates = ApplicationContext.Current.Services.PackagingService.ImportTemplates(element, u.Id);
return new Template(templates.First().Id);
}
#region Events
//EVENTS
/// <summary>
/// The save event handler
/// </summary>
public delegate void SaveEventHandler(Template sender, SaveEventArgs e);
/// <summary>
/// The new event handler
/// </summary>
public delegate void NewEventHandler(Template sender, NewEventArgs e);
/// <summary>
/// The delete event handler
/// </summary>
public delegate void DeleteEventHandler(Template sender, DeleteEventArgs e);
/// <summary>
/// Occurs when [before save].
/// </summary>
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>
protected virtual void FireBeforeSave(SaveEventArgs e)
{
if (BeforeSave != null)
BeforeSave(this, e);
}
/// <summary>
/// Occurs when [after save].
/// </summary>
public static event SaveEventHandler AfterSave;
/// <summary>
/// Raises the <see cref="E:AfterSave"/> event.
/// </summary>
/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
protected virtual void FireAfterSave(SaveEventArgs e)
{
if (AfterSave != null)
AfterSave(this, e);
}
/// <summary>
/// Occurs when [new].
/// </summary>
public static event NewEventHandler New;
/// <summary>
/// Raises the <see cref="E:New"/> event.
/// </summary>
/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
protected virtual void OnNew(NewEventArgs e)
{
if (New != null)
New(this, e);
}
/// <summary>
/// Occurs when [before delete].
/// </summary>
public static event DeleteEventHandler BeforeDelete;
/// <summary>
/// Raises the <see cref="E:BeforeDelete"/> event.
/// </summary>
/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
protected virtual void FireBeforeDelete(DeleteEventArgs e)
{
if (BeforeDelete != null)
BeforeDelete(this, e);
}
/// <summary>
/// Occurs when [after delete].
/// </summary>
public static event DeleteEventHandler AfterDelete;
/// <summary>
/// Raises the <see cref="E:AfterDelete"/> event.
/// </summary>
/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
protected virtual void FireAfterDelete(DeleteEventArgs e)
{
if (AfterDelete != null)
AfterDelete(this, e);
}
#endregion
}
}
| |
#region License
/* **********************************************************************************
* Copyright (c) Roman Ivantsov
* This source code is subject to terms and conditions of the MIT License
* for Irony. A copy of the license can be found in the License.txt file
* at the root of this distribution.
* By using this source code in any fashion, you are agreeing to be bound by the terms of the
* MIT License.
* You must not remove this notice from this software.
* **********************************************************************************/
#endregion
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq.Expressions;
using System.Text;
using Irony.Ast;
namespace Irony.Parsing {
public class Grammar {
#region properties
/// <summary>
/// Gets case sensitivity of the grammar. Read-only, true by default.
/// Can be set to false only through a parameter to grammar constructor.
/// </summary>
public readonly bool CaseSensitive;
//List of chars that unambigously identify the start of new token.
//used in scanner error recovery, and in quick parse path in NumberLiterals, Identifiers
public string Delimiters = null;
[Obsolete("Override Grammar.SkipWhitespace method instead.")]
// Not used anymore
public string WhitespaceChars = " \t\r\n\v";
public LanguageFlags LanguageFlags = LanguageFlags.Default;
public TermReportGroupList TermReportGroups = new TermReportGroupList();
//Terminals not present in grammar expressions and not reachable from the Root
// (Comment terminal is usually one of them)
// Tokens produced by these terminals will be ignored by parser input.
public readonly TerminalSet NonGrammarTerminals = new TerminalSet();
/// <summary>
/// The main root entry for the grammar.
/// </summary>
public NonTerminal Root;
/// <summary>
/// Alternative roots for parsing code snippets.
/// </summary>
public NonTerminalSet SnippetRoots = new NonTerminalSet();
public string GrammarComments; //shown in Grammar info tab
public CultureInfo DefaultCulture = CultureInfo.InvariantCulture;
//Console-related properties, initialized in grammar constructor
public string ConsoleTitle;
public string ConsoleGreeting;
public string ConsolePrompt; //default prompt
public string ConsolePromptMoreInput; //prompt to show when more input is expected
#endregion
#region constructors
public Grammar() : this(true) { } //case sensitive by default
public Grammar(bool caseSensitive) {
_currentGrammar = this;
this.CaseSensitive = caseSensitive;
bool ignoreCase = !this.CaseSensitive;
var stringComparer = StringComparer.Create(System.Globalization.CultureInfo.InvariantCulture, ignoreCase);
KeyTerms = new KeyTermTable(stringComparer);
//Initialize console attributes
ConsoleTitle = Resources.MsgDefaultConsoleTitle;
ConsoleGreeting = string.Format(Resources.MsgDefaultConsoleGreeting, this.GetType().Name);
ConsolePrompt = ">";
ConsolePromptMoreInput = ".";
}
#endregion
#region Reserved words handling
//Reserved words handling
public void MarkReservedWords(params string[] reservedWords) {
foreach (var word in reservedWords) {
var wdTerm = ToTerm(word);
wdTerm.SetFlag(TermFlags.IsReservedWord);
}
}
#endregion
#region Register/Mark methods
public void RegisterOperators(int precedence, params string[] opSymbols) {
RegisterOperators(precedence, Associativity.Left, opSymbols);
}
public void RegisterOperators(int precedence, Associativity associativity, params string[] opSymbols) {
foreach (string op in opSymbols) {
KeyTerm opSymbol = ToTerm(op);
opSymbol.SetFlag(TermFlags.IsOperator);
opSymbol.Precedence = precedence;
opSymbol.Associativity = associativity;
}
}//method
public void RegisterOperators(int precedence, params BnfTerm[] opTerms) {
RegisterOperators(precedence, Associativity.Left, opTerms);
}
public void RegisterOperators(int precedence, Associativity associativity, params BnfTerm[] opTerms) {
foreach (var term in opTerms) {
term.SetFlag(TermFlags.IsOperator);
term.Precedence = precedence;
term.Associativity = associativity;
}
}
public void RegisterBracePair(string openBrace, string closeBrace) {
KeyTerm openS = ToTerm(openBrace);
KeyTerm closeS = ToTerm(closeBrace);
openS.SetFlag(TermFlags.IsOpenBrace);
openS.IsPairFor = closeS;
closeS.SetFlag(TermFlags.IsCloseBrace);
closeS.IsPairFor = openS;
}
public void MarkPunctuation(params string[] symbols) {
foreach (string symbol in symbols) {
KeyTerm term = ToTerm(symbol);
term.SetFlag(TermFlags.IsPunctuation|TermFlags.NoAstNode);
}
}
public void MarkPunctuation(params BnfTerm[] terms) {
foreach (BnfTerm term in terms)
term.SetFlag(TermFlags.IsPunctuation|TermFlags.NoAstNode);
}
public void MarkTransient(params NonTerminal[] nonTerminals) {
foreach (NonTerminal nt in nonTerminals)
nt.Flags |= TermFlags.IsTransient | TermFlags.NoAstNode;
}
//MemberSelect are symbols invoking member list dropdowns in editor; for ex: . (dot), ::
public void MarkMemberSelect(params string[] symbols) {
foreach (var symbol in symbols)
ToTerm(symbol).SetFlag(TermFlags.IsMemberSelect);
}
//Sets IsNotReported flag on terminals. As a result the terminal wouldn't appear in expected terminal list
// in syntax error messages
public void MarkNotReported(params BnfTerm[] terms) {
foreach (var term in terms)
term.SetFlag(TermFlags.IsNotReported);
}
public void MarkNotReported(params string[] symbols) {
foreach (var symbol in symbols)
ToTerm(symbol).SetFlag(TermFlags.IsNotReported);
}
#endregion
#region virtual methods: CreateTokenFilters, TryMatch
public virtual void CreateTokenFilters(LanguageData language, TokenFilterList filters) {
}
//This method is called if Scanner fails to produce a token; it offers custom method a chance to produce the token
public virtual Token TryMatch(ParsingContext context, ISourceStream source) {
return null;
}
//Gives a way to customize parse tree nodes captions in the tree view.
public virtual string GetParseNodeCaption(ParseTreeNode node) {
if (node.IsError)
return node.Term.Name + " (Syntax error)";
if (node.Token != null)
return node.Token.ToString();
if(node.Term == null) //special case for initial node pushed into the stack at parser start
return (node.State != null ? string.Empty : "(State " + node.State.Name + ")"); // Resources.LabelInitialState;
var ntTerm = node.Term as NonTerminal;
if(ntTerm != null && !string.IsNullOrEmpty(ntTerm.NodeCaptionTemplate))
return ntTerm.GetNodeCaption(node);
return node.Term.Name;
}
/// <summary>
/// Override this method to help scanner select a terminal to create token when there are more than one candidates
/// for an input char. context.CurrentTerminals contains candidate terminals; leave a single terminal in this list
/// as the one to use.
/// </summary>
public virtual void OnScannerSelectTerminal(ParsingContext context) { }
/// <summary>Skips whitespace characters in the input stream. </summary>
/// <remarks>Override this method if your language has non-standard whitespace characters.</remarks>
/// <param name="source">Source stream.</param>
public virtual void SkipWhitespace(ISourceStream source) {
while (!source.EOF()) {
switch (source.PreviewChar) {
case ' ': case '\t':
break;
case '\r': case '\n': case '\v':
if (UsesNewLine) return; //do not treat as whitespace if language is line-based
break;
default:
return;
}//switch
source.PreviewPosition++;
}//while
}//method
/// <summary>Returns true if a character is whitespace or delimiter. Used in quick-scanning versions of some terminals. </summary>
/// <param name="ch">The character to check.</param>
/// <returns>True if a character is whitespace or delimiter; otherwise, false.</returns>
/// <remarks>Does not have to be completely accurate, should recognize most common characters that are special chars by themselves
/// and may never be part of other multi-character tokens. </remarks>
public virtual bool IsWhitespaceOrDelimiter(char ch) {
switch (ch) {
case ' ': case '\t': case '\r': case '\n': case '\v': //whitespaces
case '(': case ')': case ',': case ';': case '[': case ']': case '{': case '}':
case (char)0: //EOF
return true;
default:
return false;
}//switch
}//method
//The method is called after GrammarData is constructed
public virtual void OnGrammarDataConstructed(LanguageData language) {
}
public virtual void OnLanguageDataConstructed(LanguageData language) {
}
//Constructs the error message in situation when parser has no available action for current input.
// override this method if you want to change this message
public virtual string ConstructParserErrorMessage(ParsingContext context, StringSet expectedTerms) {
if(expectedTerms.Count > 0)
return string.Format(Resources.ErrSyntaxErrorExpected, expectedTerms.ToString(", "));
else
return Resources.ErrParserUnexpectedInput;
}
// Override this method to perform custom error processing
public virtual void ReportParseError(ParsingContext context) {
string error = null;
if (context.CurrentParserInput.Term == this.SyntaxError)
error = context.CurrentParserInput.Token.Value as string; //scanner error
else if (context.CurrentParserInput.Term == this.Indent)
error = Resources.ErrUnexpIndent;
else if (context.CurrentParserInput.Term == this.Eof && context.OpenBraces.Count > 0) {
if (context.OpenBraces.Count > 0) {
//report unclosed braces/parenthesis
var openBrace = context.OpenBraces.Peek();
error = string.Format(Resources.ErrNoClosingBrace, openBrace.Text);
} else
error = Resources.ErrUnexpEof;
}else {
var expectedTerms = context.GetExpectedTermSet();
error = ConstructParserErrorMessage(context, expectedTerms);
}
context.AddParserError(error);
}//method
#endregion
#region MakePlusRule, MakeStarRule methods
public BnfExpression MakePlusRule(NonTerminal listNonTerminal, BnfTerm listMember) {
return MakeListRule(listNonTerminal, null, listMember);
}
public BnfExpression MakePlusRule(NonTerminal listNonTerminal, BnfTerm delimiter, BnfTerm listMember) {
return MakeListRule(listNonTerminal, delimiter, listMember);
}
public BnfExpression MakeStarRule(NonTerminal listNonTerminal, BnfTerm listMember) {
return MakeListRule(listNonTerminal, null, listMember, TermListOptions.StarList);
}
public BnfExpression MakeStarRule(NonTerminal listNonTerminal, BnfTerm delimiter, BnfTerm listMember) {
return MakeListRule(listNonTerminal, delimiter, listMember, TermListOptions.StarList);
}
protected BnfExpression MakeListRule(NonTerminal list, BnfTerm delimiter, BnfTerm listMember, TermListOptions options = TermListOptions.PlusList) {
//If it is a star-list (allows empty), then we first build plus-list
var isPlusList = !options.IsSet(TermListOptions.AllowEmpty);
var allowTrailingDelim = options.IsSet(TermListOptions.AllowTrailingDelimiter) && delimiter != null;
//"plusList" is the list for which we will construct expression - it is either extra plus-list or original list.
// In the former case (extra plus-list) we will use it later to construct expression for list
NonTerminal plusList = isPlusList ? list : new NonTerminal(listMember.Name + "+");
plusList.SetFlag(TermFlags.IsList);
plusList.Rule = plusList; // rule => list
if (delimiter != null)
plusList.Rule += delimiter; // rule => list + delim
if (options.IsSet(TermListOptions.AddPreferShiftHint))
plusList.Rule += PreferShiftHere(); // rule => list + delim + PreferShiftHere()
plusList.Rule += listMember; // rule => list + delim + PreferShiftHere() + elem
plusList.Rule |= listMember; // rule => list + delim + PreferShiftHere() + elem | elem
if (isPlusList) {
// if we build plus list - we're almost done; plusList == list
// add trailing delimiter if necessary; for star list we'll add it to final expression
if (allowTrailingDelim)
plusList.Rule |= list + delimiter; // rule => list + delim + PreferShiftHere() + elem | elem | list + delim
} else {
// Setup list.Rule using plus-list we just created
list.Rule = Empty | plusList;
if (allowTrailingDelim)
list.Rule |= plusList + delimiter | delimiter;
plusList.SetFlag(TermFlags.NoAstNode);
list.SetFlag(TermFlags.IsListContainer); //indicates that real list is one level lower
}
return list.Rule;
}//method
#endregion
#region Hint utilities
protected GrammarHint PreferShiftHere() {
return new PreferredActionHint(PreferredActionType.Shift);
}
protected GrammarHint ReduceHere() {
return new PreferredActionHint(PreferredActionType.Reduce);
}
protected TokenPreviewHint ReduceIf(string thisSymbol, params string[] comesBefore) {
return new TokenPreviewHint(PreferredActionType.Reduce, thisSymbol, comesBefore);
}
protected TokenPreviewHint ReduceIf(Terminal thisSymbol, params Terminal[] comesBefore) {
return new TokenPreviewHint(PreferredActionType.Reduce, thisSymbol, comesBefore);
}
protected TokenPreviewHint ShiftIf(string thisSymbol, params string[] comesBefore) {
return new TokenPreviewHint(PreferredActionType.Shift, thisSymbol, comesBefore);
}
protected TokenPreviewHint ShiftIf(Terminal thisSymbol, params Terminal[] comesBefore) {
return new TokenPreviewHint(PreferredActionType.Shift, thisSymbol, comesBefore);
}
protected GrammarHint ImplyPrecedenceHere(int precedence) {
return ImplyPrecedenceHere(precedence, Associativity.Left);
}
protected GrammarHint ImplyPrecedenceHere(int precedence, Associativity associativity) {
return new ImpliedPrecedenceHint(precedence, associativity);
}
protected CustomActionHint CustomActionHere(ExecuteActionMethod executeMethod, PreviewActionMethod previewMethod = null) {
return new CustomActionHint(executeMethod, previewMethod);
}
#endregion
#region Term report group methods
/// <summary>
/// Creates a terminal reporting group, so all terminals in the group will be reported as a single "alias" in syntex error messages like
/// "Syntax error, expected: [list of terms]"
/// </summary>
/// <param name="alias">An alias for all terminals in the group.</param>
/// <param name="symbols">Symbols to be included into the group.</param>
protected void AddTermsReportGroup(string alias, params string[] symbols) {
TermReportGroups.Add(new TermReportGroup(alias, TermReportGroupType.Normal, SymbolsToTerms(symbols)));
}
/// <summary>
/// Creates a terminal reporting group, so all terminals in the group will be reported as a single "alias" in syntex error messages like
/// "Syntax error, expected: [list of terms]"
/// </summary>
/// <param name="alias">An alias for all terminals in the group.</param>
/// <param name="terminals">Terminals to be included into the group.</param>
protected void AddTermsReportGroup(string alias, params Terminal[] terminals) {
TermReportGroups.Add(new TermReportGroup(alias, TermReportGroupType.Normal, terminals));
}
/// <summary>
/// Adds symbols to a group with no-report type, so symbols will not be shown in expected lists in syntax error messages.
/// </summary>
/// <param name="symbols">Symbols to exclude.</param>
protected void AddToNoReportGroup(params string[] symbols) {
TermReportGroups.Add(new TermReportGroup(string.Empty, TermReportGroupType.DoNotReport, SymbolsToTerms(symbols)));
}
/// <summary>
/// Adds symbols to a group with no-report type, so symbols will not be shown in expected lists in syntax error messages.
/// </summary>
/// <param name="symbols">Symbols to exclude.</param>
protected void AddToNoReportGroup(params Terminal[] terminals) {
TermReportGroups.Add(new TermReportGroup(string.Empty, TermReportGroupType.DoNotReport, terminals));
}
/// <summary>
/// Adds a group and an alias for all operator symbols used in the grammar.
/// </summary>
/// <param name="alias">An alias for operator symbols.</param>
protected void AddOperatorReportGroup(string alias) {
TermReportGroups.Add(new TermReportGroup(alias, TermReportGroupType.Operator, null)); //operators will be filled later
}
private IEnumerable<Terminal> SymbolsToTerms(IEnumerable<string> symbols) {
var termList = new TerminalList();
foreach(var symbol in symbols)
termList.Add(ToTerm(symbol));
return termList;
}
#endregion
#region Standard terminals: EOF, Empty, NewLine, Indent, Dedent
// Empty object is used to identify optional element:
// term.Rule = term1 | Empty;
public readonly Terminal Empty = new Terminal("EMPTY");
public readonly NewLineTerminal NewLine = new NewLineTerminal("LF");
//set to true automatically by NewLine terminal; prevents treating new-line characters as whitespaces
public bool UsesNewLine;
// The following terminals are used in indent-sensitive languages like Python;
// they are not produced by scanner but are produced by CodeOutlineFilter after scanning
public readonly Terminal Indent = new Terminal("INDENT", TokenCategory.Outline, TermFlags.IsNonScanner);
public readonly Terminal Dedent = new Terminal("DEDENT", TokenCategory.Outline, TermFlags.IsNonScanner);
//End-of-Statement terminal - used in indentation-sensitive language to signal end-of-statement;
// it is not always synced with CRLF chars, and CodeOutlineFilter carefully produces Eos tokens
// (as well as Indent and Dedent) based on line/col information in incoming content tokens.
public readonly Terminal Eos = new Terminal("EOS", Resources.LabelEosLabel, TokenCategory.Outline, TermFlags.IsNonScanner);
// Identifies end of file
// Note: using Eof in grammar rules is optional. Parser automatically adds this symbol
// as a lookahead to Root non-terminal
public readonly Terminal Eof = new Terminal("EOF", TokenCategory.Outline);
//Artificial terminal to use for injected/replaced tokens that must be ignored by parser.
public readonly Terminal Skip = new Terminal("(SKIP)", TokenCategory.Outline, TermFlags.IsNonGrammar);
//Used as a "line-start" indicator
public readonly Terminal LineStartTerminal = new Terminal("LINE_START", TokenCategory.Outline);
//Used for error tokens
public readonly Terminal SyntaxError = new Terminal("SYNTAX_ERROR", TokenCategory.Error, TermFlags.IsNonScanner);
public NonTerminal NewLinePlus {
get {
if(_newLinePlus == null) {
_newLinePlus = new NonTerminal("LF+");
//We do no use MakePlusRule method; we specify the rule explicitly to add PrefereShiftHere call - this solves some unintended shift-reduce conflicts
// when using NewLinePlus
_newLinePlus.Rule = NewLine | _newLinePlus + PreferShiftHere() + NewLine;
MarkPunctuation(_newLinePlus);
_newLinePlus.SetFlag(TermFlags.IsList);
}
return _newLinePlus;
}
} NonTerminal _newLinePlus;
public NonTerminal NewLineStar {
get {
if(_newLineStar == null) {
_newLineStar = new NonTerminal("LF*");
MarkPunctuation(_newLineStar);
_newLineStar.Rule = MakeStarRule(_newLineStar, NewLine);
}
return _newLineStar;
}
} NonTerminal _newLineStar;
#endregion
#region KeyTerms (keywords + special symbols)
public KeyTermTable KeyTerms;
public KeyTerm ToTerm(string text) {
return ToTerm(text, text);
}
public KeyTerm ToTerm(string text, string name) {
KeyTerm term;
if (KeyTerms.TryGetValue(text, out term)) {
//update name if it was specified now and not before
if (string.IsNullOrEmpty(term.Name) && !string.IsNullOrEmpty(name))
term.Name = name;
return term;
}
//create new term
if (!CaseSensitive)
text = text.ToLower(CultureInfo.InvariantCulture);
string.Intern(text);
term = new KeyTerm(text, name);
KeyTerms[text] = term;
return term;
}
#endregion
#region CurrentGrammar static field
//Static per-thread instance; Grammar constructor sets it to self (this).
// This field/property is used by operator overloads (which are static) to access Grammar's predefined terminals like Empty,
// and SymbolTerms dictionary to convert string literals to symbol terminals and add them to the SymbolTerms dictionary
[ThreadStatic]
private static Grammar _currentGrammar;
public static Grammar CurrentGrammar {
get { return _currentGrammar; }
}
internal static void ClearCurrentGrammar() {
_currentGrammar = null;
}
#endregion
#region AST construction
public virtual void BuildAst(LanguageData language, ParseTree parseTree) {
if (!LanguageFlags.IsSet(LanguageFlags.CreateAst))
return;
var astContext = new AstContext(language);
var astBuilder = new AstBuilder(astContext);
astBuilder.BuildAst(parseTree);
}
#endregion
}//class
}//namespace
| |
// <file>
// <copyright see="prj:///doc/copyright.txt"/>
// <license see="prj:///doc/license.txt"/>
// <owner name="none" email=""/>
// <version>$Revision: 3205 $</version>
// </file>
using System.Drawing;
using System.Text;
using WorldBankBBS.ICSharpCode.TextEditor.Src.Document.HighlightingStrategy;
namespace WorldBankBBS.ICSharpCode.TextEditor.Src.Document
{
public enum BracketMatchingStyle {
Before,
After
}
public class DefaultTextEditorProperties : ITextEditorProperties
{
int tabIndent = 4;
int indentationSize = 4;
IndentStyle indentStyle = IndentStyle.Smart;
DocumentSelectionMode documentSelectionMode = DocumentSelectionMode.Normal;
Encoding encoding = System.Text.Encoding.UTF8;
BracketMatchingStyle bracketMatchingStyle = BracketMatchingStyle.After;
FontContainer fontContainer;
static Font DefaultFont;
public DefaultTextEditorProperties()
{
if (DefaultFont == null) {
DefaultFont = new Font("Courier New", 10);
}
this.fontContainer = new FontContainer(DefaultFont);
}
bool allowCaretBeyondEOL = false;
bool showMatchingBracket = true;
bool showLineNumbers = true;
bool showSpaces = false;
bool showTabs = false;
bool showEOLMarker = false;
bool showInvalidLines = false;
bool isIconBarVisible = false;
bool enableFolding = true;
bool showHorizontalRuler = false;
bool showVerticalRuler = true;
bool convertTabsToSpaces = false;
System.Drawing.Text.TextRenderingHint textRenderingHint = System.Drawing.Text.TextRenderingHint.SystemDefault;
bool mouseWheelScrollDown = true;
bool mouseWheelTextZoom = true;
bool hideMouseCursor = false;
bool cutCopyWholeLine = true;
int verticalRulerRow = 80;
LineViewerStyle lineViewerStyle = LineViewerStyle.None;
string lineTerminator = "\r\n";
bool autoInsertCurlyBracket = true;
bool supportReadOnlySegments = false;
public int TabIndent {
get {
return tabIndent;
}
set {
tabIndent = value;
}
}
public int IndentationSize {
get { return indentationSize; }
set { indentationSize = value; }
}
public IndentStyle IndentStyle {
get {
return indentStyle;
}
set {
indentStyle = value;
}
}
public DocumentSelectionMode DocumentSelectionMode {
get {
return documentSelectionMode;
}
set {
documentSelectionMode = value;
}
}
public bool AllowCaretBeyondEOL {
get {
return allowCaretBeyondEOL;
}
set {
allowCaretBeyondEOL = value;
}
}
public bool ShowMatchingBracket {
get {
return showMatchingBracket;
}
set {
showMatchingBracket = value;
}
}
public bool ShowLineNumbers {
get {
return showLineNumbers;
}
set {
showLineNumbers = value;
}
}
public bool ShowSpaces {
get {
return showSpaces;
}
set {
showSpaces = value;
}
}
public bool ShowTabs {
get {
return showTabs;
}
set {
showTabs = value;
}
}
public bool ShowEOLMarker {
get {
return showEOLMarker;
}
set {
showEOLMarker = value;
}
}
public bool ShowInvalidLines {
get {
return showInvalidLines;
}
set {
showInvalidLines = value;
}
}
public bool IsIconBarVisible {
get {
return isIconBarVisible;
}
set {
isIconBarVisible = value;
}
}
public bool EnableFolding {
get {
return enableFolding;
}
set {
enableFolding = value;
}
}
public bool ShowHorizontalRuler {
get {
return showHorizontalRuler;
}
set {
showHorizontalRuler = value;
}
}
public bool ShowVerticalRuler {
get {
return showVerticalRuler;
}
set {
showVerticalRuler = value;
}
}
public bool ConvertTabsToSpaces {
get {
return convertTabsToSpaces;
}
set {
convertTabsToSpaces = value;
}
}
public System.Drawing.Text.TextRenderingHint TextRenderingHint {
get { return textRenderingHint; }
set { textRenderingHint = value; }
}
public bool MouseWheelScrollDown {
get {
return mouseWheelScrollDown;
}
set {
mouseWheelScrollDown = value;
}
}
public bool MouseWheelTextZoom {
get {
return mouseWheelTextZoom;
}
set {
mouseWheelTextZoom = value;
}
}
public bool HideMouseCursor {
get {
return hideMouseCursor;
}
set {
hideMouseCursor = value;
}
}
public bool CutCopyWholeLine {
get {
return cutCopyWholeLine;
}
set {
cutCopyWholeLine = value;
}
}
public Encoding Encoding {
get {
return encoding;
}
set {
encoding = value;
}
}
public int VerticalRulerRow {
get {
return verticalRulerRow;
}
set {
verticalRulerRow = value;
}
}
public LineViewerStyle LineViewerStyle {
get {
return lineViewerStyle;
}
set {
lineViewerStyle = value;
}
}
public string LineTerminator {
get {
return lineTerminator;
}
set {
lineTerminator = value;
}
}
public bool AutoInsertCurlyBracket {
get {
return autoInsertCurlyBracket;
}
set {
autoInsertCurlyBracket = value;
}
}
public Font Font {
get {
return fontContainer.DefaultFont;
}
set {
fontContainer.DefaultFont = value;
}
}
public FontContainer FontContainer {
get {
return fontContainer;
}
}
public BracketMatchingStyle BracketMatchingStyle {
get {
return bracketMatchingStyle;
}
set {
bracketMatchingStyle = value;
}
}
public bool SupportReadOnlySegments {
get {
return supportReadOnlySegments;
}
set {
supportReadOnlySegments = value;
}
}
}
}
| |
//
// Copyright (c) 2004-2020 Jaroslaw Kowalski <[email protected]>, Kim Christensen, Julian Verdurmen
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of Jaroslaw Kowalski nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
#define DEBUG
using NLog.Config;
namespace NLog.UnitTests
{
using System;
using System.Globalization;
using System.Threading;
using System.Diagnostics;
using Xunit;
public class NLogTraceListenerTests : NLogTestBase, IDisposable
{
private readonly CultureInfo previousCultureInfo;
public NLogTraceListenerTests()
{
previousCultureInfo = Thread.CurrentThread.CurrentCulture;
// set the culture info with the decimal separator (comma) different from InvariantCulture separator (point)
Thread.CurrentThread.CurrentCulture = new CultureInfo("fr-FR");
}
public void Dispose()
{
// restore previous culture info
Thread.CurrentThread.CurrentCulture = previousCultureInfo;
}
#if !NETSTANDARD1_5
[Fact]
public void TraceWriteTest()
{
LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@"
<nlog>
<targets><target name='debug' type='Debug' layout='${logger} ${level} ${message}' /></targets>
<rules>
<logger name='*' minlevel='Debug' writeTo='debug' />
</rules>
</nlog>");
Trace.Listeners.Clear();
Trace.Listeners.Add(new NLogTraceListener { Name = "Logger1" });
Trace.Write("Hello");
AssertDebugLastMessage("debug", "Logger1 Debug Hello");
Trace.Write("Hello", "Cat1");
AssertDebugLastMessage("debug", "Logger1 Debug Cat1: Hello");
Trace.Write(3.1415);
AssertDebugLastMessage("debug", $"Logger1 Debug {3.1415}");
Trace.Write(3.1415, "Cat2");
AssertDebugLastMessage("debug", $"Logger1 Debug Cat2: {3.1415}");
}
[Fact]
public void TraceWriteLineTest()
{
LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@"
<nlog>
<targets><target name='debug' type='Debug' layout='${logger} ${level} ${message}' /></targets>
<rules>
<logger name='*' minlevel='Debug' writeTo='debug' />
</rules>
</nlog>");
Trace.Listeners.Clear();
Trace.Listeners.Add(new NLogTraceListener { Name = "Logger1" });
Trace.WriteLine("Hello");
AssertDebugLastMessage("debug", "Logger1 Debug Hello");
Trace.WriteLine("Hello", "Cat1");
AssertDebugLastMessage("debug", "Logger1 Debug Cat1: Hello");
Trace.WriteLine(3.1415);
AssertDebugLastMessage("debug", $"Logger1 Debug {3.1415}");
Trace.WriteLine(3.1415, "Cat2");
AssertDebugLastMessage("debug", $"Logger1 Debug Cat2: {3.1415}");
}
[Fact]
public void TraceWriteNonDefaultLevelTest()
{
LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@"
<nlog>
<targets><target name='debug' type='Debug' layout='${logger} ${level} ${message}' /></targets>
<rules>
<logger name='*' minlevel='Trace' writeTo='debug' />
</rules>
</nlog>");
Trace.Listeners.Clear();
Trace.Listeners.Add(new NLogTraceListener { Name = "Logger1", DefaultLogLevel = LogLevel.Trace });
Trace.Write("Hello");
AssertDebugLastMessage("debug", "Logger1 Trace Hello");
}
[Fact]
public void TraceConfiguration()
{
var listener = new NLogTraceListener();
listener.Attributes.Add("defaultLogLevel", "Warn");
listener.Attributes.Add("forceLogLevel", "Error");
listener.Attributes.Add("autoLoggerName", "1");
listener.Attributes.Add("DISABLEFLUSH", "true");
Assert.Equal(LogLevel.Warn, listener.DefaultLogLevel);
Assert.Equal(LogLevel.Error, listener.ForceLogLevel);
Assert.True(listener.AutoLoggerName);
Assert.True(listener.DisableFlush);
}
[Fact]
public void TraceFailTest()
{
LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@"
<nlog>
<targets><target name='debug' type='Debug' layout='${logger} ${level} ${message}' /></targets>
<rules>
<logger name='*' minlevel='Debug' writeTo='debug' />
</rules>
</nlog>");
Trace.Listeners.Clear();
Trace.Listeners.Add(new NLogTraceListener { Name = "Logger1" });
Trace.Fail("Message");
AssertDebugLastMessage("debug", "Logger1 Error Message");
Trace.Fail("Message", "Detailed Message");
AssertDebugLastMessage("debug", "Logger1 Error Message Detailed Message");
}
[Fact]
public void AutoLoggerNameTest()
{
LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@"
<nlog>
<targets><target name='debug' type='Debug' layout='${logger} ${level} ${message}' /></targets>
<rules>
<logger name='*' minlevel='Debug' writeTo='debug' />
</rules>
</nlog>");
Trace.Listeners.Clear();
Trace.Listeners.Add(new NLogTraceListener { Name = "Logger1", AutoLoggerName = true });
Trace.Write("Hello");
AssertDebugLastMessage("debug", GetType().FullName + " Debug Hello");
}
[Fact]
public void TraceDataTests()
{
LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@"
<nlog>
<targets><target name='debug' type='Debug' layout='${logger} ${level} ${message} ${event-context:EventID}' /></targets>
<rules>
<logger name='*' minlevel='Trace' writeTo='debug' />
</rules>
</nlog>");
TraceSource ts = CreateTraceSource();
ts.Listeners.Add(new NLogTraceListener { Name = "Logger1", DefaultLogLevel = LogLevel.Trace });
ts.TraceData(TraceEventType.Critical, 123, 42);
AssertDebugLastMessage("debug", "MySource1 Fatal 42 123");
ts.TraceData(TraceEventType.Critical, 145, 42, 3.14, "foo");
AssertDebugLastMessage("debug", $"MySource1 Fatal 42, {3.14.ToString(CultureInfo.CurrentCulture)}, foo 145");
}
#if MONO
[Fact(Skip="Not working under MONO - not sure if unit test is wrong, or the code")]
#else
[Fact]
#endif
public void LogInformationTest()
{
LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@"
<nlog>
<targets><target name='debug' type='Debug' layout='${logger} ${level} ${message} ${event-context:EventID}' /></targets>
<rules>
<logger name='*' minlevel='Trace' writeTo='debug' />
</rules>
</nlog>");
TraceSource ts = CreateTraceSource();
ts.Listeners.Add(new NLogTraceListener { Name = "Logger1", DefaultLogLevel = LogLevel.Trace });
ts.TraceInformation("Quick brown fox");
AssertDebugLastMessage("debug", "MySource1 Info Quick brown fox 0");
ts.TraceInformation("Mary had {0} lamb", "a little");
AssertDebugLastMessage("debug", "MySource1 Info Mary had a little lamb 0");
}
[Fact]
public void TraceEventTests()
{
LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@"
<nlog>
<targets><target name='debug' type='Debug' layout='${logger} ${level} ${message} ${event-context:EventID}' /></targets>
<rules>
<logger name='*' minlevel='Trace' writeTo='debug' />
</rules>
</nlog>");
TraceSource ts = CreateTraceSource();
ts.Listeners.Add(new NLogTraceListener { Name = "Logger1", DefaultLogLevel = LogLevel.Trace });
ts.TraceEvent(TraceEventType.Information, 123, "Quick brown {0} jumps over the lazy {1}.", "fox", "dog");
AssertDebugLastMessage("debug", "MySource1 Info Quick brown fox jumps over the lazy dog. 123");
ts.TraceEvent(TraceEventType.Information, 123);
AssertDebugLastMessage("debug", "MySource1 Info 123");
ts.TraceEvent(TraceEventType.Verbose, 145, "Bar");
AssertDebugLastMessage("debug", "MySource1 Trace Bar 145");
ts.TraceEvent(TraceEventType.Error, 145, "Foo");
AssertDebugLastMessage("debug", "MySource1 Error Foo 145");
ts.TraceEvent(TraceEventType.Suspend, 145, "Bar");
AssertDebugLastMessage("debug", "MySource1 Debug Bar 145");
ts.TraceEvent(TraceEventType.Resume, 145, "Foo");
AssertDebugLastMessage("debug", "MySource1 Debug Foo 145");
ts.TraceEvent(TraceEventType.Warning, 145, "Bar");
AssertDebugLastMessage("debug", "MySource1 Warn Bar 145");
ts.TraceEvent(TraceEventType.Critical, 145, "Foo");
AssertDebugLastMessage("debug", "MySource1 Fatal Foo 145");
}
#if MONO
[Fact(Skip="Not working under MONO - not sure if unit test is wrong, or the code")]
#else
[Fact]
#endif
public void ForceLogLevelTest()
{
LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@"
<nlog>
<targets><target name='debug' type='Debug' layout='${logger} ${level} ${message} ${event-context:EventID}' /></targets>
<rules>
<logger name='*' minlevel='Trace' writeTo='debug' />
</rules>
</nlog>");
TraceSource ts = CreateTraceSource();
ts.Listeners.Add(new NLogTraceListener { Name = "Logger1", DefaultLogLevel = LogLevel.Trace, ForceLogLevel = LogLevel.Warn });
// force all logs to be Warn, DefaultLogLevel has no effect on TraceSource
ts.TraceInformation("Quick brown fox");
AssertDebugLastMessage("debug", "MySource1 Warn Quick brown fox 0");
ts.TraceInformation("Mary had {0} lamb", "a little");
AssertDebugLastMessage("debug", "MySource1 Warn Mary had a little lamb 0");
}
[Fact]
public void FilterTraceTest()
{
LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@"
<nlog>
<targets><target name='debug' type='Debug' layout='${logger} ${level} ${message} ${event-context:EventID}' /></targets>
<rules>
<logger name='*' minlevel='Trace' writeTo='debug' />
</rules>
</nlog>");
TraceSource ts = CreateTraceSource();
ts.Listeners.Add(new NLogTraceListener { Name = "Logger1", DefaultLogLevel = LogLevel.Trace, ForceLogLevel = LogLevel.Warn, Filter = new EventTypeFilter(SourceLevels.Error) });
// force all logs to be Warn, DefaultLogLevel has no effect on TraceSource
ts.TraceEvent(TraceEventType.Error, 0, "Quick brown fox");
AssertDebugLastMessage("debug", "MySource1 Warn Quick brown fox 0");
ts.TraceInformation("Mary had {0} lamb", "a little");
AssertDebugLastMessage("debug", "MySource1 Warn Quick brown fox 0");
}
#endif
[Fact]
public void TraceTargetWriteLineTest()
{
LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@"
<nlog>
<targets>
<target name='trace' type='Trace' layout='${logger} ${level} ${message}' rawWrite='true' />
</targets>
<rules>
<logger name='*' minlevel='Trace' writeTo='trace' />
</rules>
</nlog>");
var logger = LogManager.GetLogger("MySource1");
var sw = new System.IO.StringWriter();
try
{
Trace.Listeners.Clear();
Trace.Listeners.Add(new TextWriterTraceListener(sw));
foreach (var logLevel in LogLevel.AllLevels)
{
if (logLevel == LogLevel.Off)
continue;
logger.Log(logLevel, "Quick brown fox");
Trace.Flush();
Assert.Equal($"MySource1 {logLevel} Quick brown fox" + Environment.NewLine, sw.GetStringBuilder().ToString());
sw.GetStringBuilder().Length = 0;
}
Trace.Flush();
}
finally
{
Trace.Listeners.Clear();
}
}
[Theory]
[InlineData(true)]
[InlineData(false)]
public void TraceTargetEnableTraceFailTest(bool enableTraceFail)
{
LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString($@"
<nlog>
<targets>
<target name='trace' type='Trace' layout='${{logger}} ${{level}} ${{message}}' enableTraceFail='{enableTraceFail}' />
</targets>
<rules>
<logger name='*' minlevel='Trace' writeTo='trace' />
</rules>
</nlog>");
var logger = LogManager.GetLogger(nameof(TraceTargetEnableTraceFailTest));
var sw = new System.IO.StringWriter();
try
{
Trace.Listeners.Clear();
Trace.Listeners.Add(new TextWriterTraceListener(sw));
foreach (var logLevel in LogLevel.AllLevels)
{
if (logLevel == LogLevel.Off)
continue;
logger.Log(logLevel, "Quick brown fox");
Trace.Flush();
if (logLevel == LogLevel.Fatal)
{
if (enableTraceFail)
Assert.Equal($"Fail: {logger.Name} Fatal Quick brown fox" + Environment.NewLine, sw.GetStringBuilder().ToString());
else
Assert.NotEqual($"Fail: {logger.Name} Fatal Quick brown fox" + Environment.NewLine, sw.GetStringBuilder().ToString());
}
Assert.Contains($"{logger.Name} {logLevel} Quick brown fox" + Environment.NewLine, sw.GetStringBuilder().ToString());
sw.GetStringBuilder().Length = 0;
}
}
finally
{
Trace.Listeners.Clear();
}
}
private static TraceSource CreateTraceSource()
{
var ts = new TraceSource("MySource1", SourceLevels.All);
#if MONO
// for some reason needed on Mono
ts.Switch = new SourceSwitch("MySource1", "Verbose");
ts.Switch.Level = SourceLevels.All;
#endif
return ts;
}
}
}
| |
// 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.Globalization;
using System.Runtime.CompilerServices;
namespace System
{
public partial class String
{
public bool Contains(string value)
{
return (IndexOf(value, StringComparison.Ordinal) >= 0);
}
public bool Contains(string value, StringComparison comparisonType)
{
return (IndexOf(value, comparisonType) >= 0);
}
// Returns the index of the first occurrence of a specified character in the current instance.
// The search starts at startIndex and runs thorough the next count characters.
//
public int IndexOf(char value)
{
return IndexOf(value, 0, this.Length);
}
public int IndexOf(char value, int startIndex)
{
return IndexOf(value, startIndex, this.Length - startIndex);
}
public unsafe int IndexOf(char value, int startIndex, int count)
{
if (startIndex < 0 || startIndex > Length)
throw new ArgumentOutOfRangeException(nameof(startIndex), SR.ArgumentOutOfRange_Index);
if (count < 0 || count > Length - startIndex)
throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_Count);
fixed (char* pChars = &_firstChar)
{
char* pCh = pChars + startIndex;
while (count >= 4)
{
if (*pCh == value) goto ReturnIndex;
if (*(pCh + 1) == value) goto ReturnIndex1;
if (*(pCh + 2) == value) goto ReturnIndex2;
if (*(pCh + 3) == value) goto ReturnIndex3;
count -= 4;
pCh += 4;
}
while (count > 0)
{
if (*pCh == value)
goto ReturnIndex;
count--;
pCh++;
}
return -1;
ReturnIndex3: pCh++;
ReturnIndex2: pCh++;
ReturnIndex1: pCh++;
ReturnIndex:
return (int)(pCh - pChars);
}
}
// Returns the index of the first occurrence of any specified character in the current instance.
// The search starts at startIndex and runs to startIndex + count -1.
//
public int IndexOfAny(char[] anyOf)
{
return IndexOfAny(anyOf, 0, this.Length);
}
public int IndexOfAny(char[] anyOf, int startIndex)
{
return IndexOfAny(anyOf, startIndex, this.Length - startIndex);
}
public int IndexOfAny(char[] anyOf, int startIndex, int count)
{
if (anyOf == null)
{
throw new ArgumentNullException(nameof(anyOf));
}
if ((uint)startIndex > (uint)Length)
{
throw new ArgumentOutOfRangeException(nameof(startIndex), SR.ArgumentOutOfRange_Index);
}
if ((uint)count > (uint)(Length - startIndex))
{
throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_Count);
}
if (anyOf.Length == 2)
{
// Very common optimization for directory separators (/, \), quotes (", '), brackets, etc
return IndexOfAny(anyOf[0], anyOf[1], startIndex, count);
}
else if (anyOf.Length == 3)
{
return IndexOfAny(anyOf[0], anyOf[1], anyOf[2], startIndex, count);
}
else if (anyOf.Length > 3)
{
return IndexOfCharArray(anyOf, startIndex, count);
}
else if (anyOf.Length == 1)
{
return IndexOf(anyOf[0], startIndex, count);
}
else // anyOf.Length == 0
{
return -1;
}
}
private unsafe int IndexOfAny(char value1, char value2, int startIndex, int count)
{
fixed (char* pChars = &_firstChar)
{
char* pCh = pChars + startIndex;
while (count > 0)
{
char c = *pCh;
if (c == value1 || c == value2)
return (int)(pCh - pChars);
// Possibly reads outside of count and can include null terminator
// Handled in the return logic
c = *(pCh + 1);
if (c == value1 || c == value2)
return (count == 1 ? -1 : (int)(pCh - pChars) + 1);
pCh += 2;
count -= 2;
}
return -1;
}
}
private unsafe int IndexOfAny(char value1, char value2, char value3, int startIndex, int count)
{
fixed (char* pChars = &_firstChar)
{
char* pCh = pChars + startIndex;
while (count > 0)
{
char c = *pCh;
if (c == value1 || c == value2 || c == value3)
return (int)(pCh - pChars);
pCh++;
count--;
}
return -1;
}
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private extern int IndexOfCharArray(char[] anyOf, int startIndex, int count);
// Determines the position within this string of the first occurrence of the specified
// string, according to the specified search criteria. The search begins at
// the first character of this string, it is case-sensitive and the current culture
// comparison is used.
//
public int IndexOf(String value)
{
return IndexOf(value, StringComparison.CurrentCulture);
}
// Determines the position within this string of the first occurrence of the specified
// string, according to the specified search criteria. The search begins at
// startIndex, it is case-sensitive and the current culture comparison is used.
//
public int IndexOf(String value, int startIndex)
{
return IndexOf(value, startIndex, StringComparison.CurrentCulture);
}
// Determines the position within this string of the first occurrence of the specified
// string, according to the specified search criteria. The search begins at
// startIndex, ends at endIndex and the current culture comparison is used.
//
public int IndexOf(String value, int startIndex, int count)
{
if (startIndex < 0 || startIndex > this.Length)
{
throw new ArgumentOutOfRangeException(nameof(startIndex), SR.ArgumentOutOfRange_Index);
}
if (count < 0 || count > this.Length - startIndex)
{
throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_Count);
}
return IndexOf(value, startIndex, count, StringComparison.CurrentCulture);
}
public int IndexOf(String value, StringComparison comparisonType)
{
return IndexOf(value, 0, this.Length, comparisonType);
}
public int IndexOf(String value, int startIndex, StringComparison comparisonType)
{
return IndexOf(value, startIndex, this.Length - startIndex, comparisonType);
}
public int IndexOf(String value, int startIndex, int count, StringComparison comparisonType)
{
// Validate inputs
if (value == null)
throw new ArgumentNullException(nameof(value));
if (startIndex < 0 || startIndex > this.Length)
throw new ArgumentOutOfRangeException(nameof(startIndex), SR.ArgumentOutOfRange_Index);
if (count < 0 || startIndex > this.Length - count)
throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_Count);
switch (comparisonType)
{
case StringComparison.CurrentCulture:
return CultureInfo.CurrentCulture.CompareInfo.IndexOf(this, value, startIndex, count, CompareOptions.None);
case StringComparison.CurrentCultureIgnoreCase:
return CultureInfo.CurrentCulture.CompareInfo.IndexOf(this, value, startIndex, count, CompareOptions.IgnoreCase);
case StringComparison.InvariantCulture:
return CultureInfo.InvariantCulture.CompareInfo.IndexOf(this, value, startIndex, count, CompareOptions.None);
case StringComparison.InvariantCultureIgnoreCase:
return CultureInfo.InvariantCulture.CompareInfo.IndexOf(this, value, startIndex, count, CompareOptions.IgnoreCase);
case StringComparison.Ordinal:
return CultureInfo.InvariantCulture.CompareInfo.IndexOf(this, value, startIndex, count, CompareOptions.Ordinal);
case StringComparison.OrdinalIgnoreCase:
if (value.IsAscii() && this.IsAscii())
return CultureInfo.InvariantCulture.CompareInfo.IndexOf(this, value, startIndex, count, CompareOptions.IgnoreCase);
else
return TextInfo.IndexOfStringOrdinalIgnoreCase(this, value, startIndex, count);
default:
throw new ArgumentException(SR.NotSupported_StringComparison, nameof(comparisonType));
}
}
// Returns the index of the last occurrence of a specified character in the current instance.
// The search starts at startIndex and runs backwards to startIndex - count + 1.
// The character at position startIndex is included in the search. startIndex is the larger
// index within the string.
//
public int LastIndexOf(char value)
{
return LastIndexOf(value, this.Length - 1, this.Length);
}
public int LastIndexOf(char value, int startIndex)
{
return LastIndexOf(value, startIndex, startIndex + 1);
}
public unsafe int LastIndexOf(char value, int startIndex, int count)
{
if (Length == 0)
return -1;
if (startIndex < 0 || startIndex >= Length)
throw new ArgumentOutOfRangeException(nameof(startIndex), SR.ArgumentOutOfRange_Index);
if (count < 0 || count - 1 > startIndex)
throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_Count);
fixed (char* pChars = &_firstChar)
{
char* pCh = pChars + startIndex;
//We search [startIndex..EndIndex]
while (count >= 4)
{
if (*pCh == value) goto ReturnIndex;
if (*(pCh - 1) == value) goto ReturnIndex1;
if (*(pCh - 2) == value) goto ReturnIndex2;
if (*(pCh - 3) == value) goto ReturnIndex3;
count -= 4;
pCh -= 4;
}
while (count > 0)
{
if (*pCh == value)
goto ReturnIndex;
count--;
pCh--;
}
return -1;
ReturnIndex3: pCh--;
ReturnIndex2: pCh--;
ReturnIndex1: pCh--;
ReturnIndex:
return (int)(pCh - pChars);
}
}
// Returns the index of the last occurrence of any specified character in the current instance.
// The search starts at startIndex and runs backwards to startIndex - count + 1.
// The character at position startIndex is included in the search. startIndex is the larger
// index within the string.
//
//ForceInline ... Jit can't recognize String.get_Length to determine that this is "fluff"
public int LastIndexOfAny(char[] anyOf)
{
return LastIndexOfAny(anyOf, this.Length - 1, this.Length);
}
public int LastIndexOfAny(char[] anyOf, int startIndex)
{
return LastIndexOfAny(anyOf, startIndex, startIndex + 1);
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public extern int LastIndexOfAny(char[] anyOf, int startIndex, int count);
// Returns the index of the last occurrence of any character in value in the current instance.
// The search starts at startIndex and runs backwards to startIndex - count + 1.
// The character at position startIndex is included in the search. startIndex is the larger
// index within the string.
//
public int LastIndexOf(String value)
{
return LastIndexOf(value, this.Length - 1, this.Length, StringComparison.CurrentCulture);
}
public int LastIndexOf(String value, int startIndex)
{
return LastIndexOf(value, startIndex, startIndex + 1, StringComparison.CurrentCulture);
}
public int LastIndexOf(String value, int startIndex, int count)
{
if (count < 0)
{
throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_Count);
}
return LastIndexOf(value, startIndex, count, StringComparison.CurrentCulture);
}
public int LastIndexOf(String value, StringComparison comparisonType)
{
return LastIndexOf(value, this.Length - 1, this.Length, comparisonType);
}
public int LastIndexOf(String value, int startIndex, StringComparison comparisonType)
{
return LastIndexOf(value, startIndex, startIndex + 1, comparisonType);
}
public int LastIndexOf(String value, int startIndex, int count, StringComparison comparisonType)
{
if (value == null)
throw new ArgumentNullException(nameof(value));
// Special case for 0 length input strings
if (this.Length == 0 && (startIndex == -1 || startIndex == 0))
return (value.Length == 0) ? 0 : -1;
// Now after handling empty strings, make sure we're not out of range
if (startIndex < 0 || startIndex > this.Length)
throw new ArgumentOutOfRangeException(nameof(startIndex), SR.ArgumentOutOfRange_Index);
// Make sure that we allow startIndex == this.Length
if (startIndex == this.Length)
{
startIndex--;
if (count > 0)
count--;
// If we are looking for nothing, just return 0
if (value.Length == 0 && count >= 0 && startIndex - count + 1 >= 0)
return startIndex;
}
// 2nd half of this also catches when startIndex == MAXINT, so MAXINT - 0 + 1 == -1, which is < 0.
if (count < 0 || startIndex - count + 1 < 0)
throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_Count);
switch (comparisonType)
{
case StringComparison.CurrentCulture:
return CultureInfo.CurrentCulture.CompareInfo.LastIndexOf(this, value, startIndex, count, CompareOptions.None);
case StringComparison.CurrentCultureIgnoreCase:
return CultureInfo.CurrentCulture.CompareInfo.LastIndexOf(this, value, startIndex, count, CompareOptions.IgnoreCase);
case StringComparison.InvariantCulture:
return CultureInfo.InvariantCulture.CompareInfo.LastIndexOf(this, value, startIndex, count, CompareOptions.None);
case StringComparison.InvariantCultureIgnoreCase:
return CultureInfo.InvariantCulture.CompareInfo.LastIndexOf(this, value, startIndex, count, CompareOptions.IgnoreCase);
case StringComparison.Ordinal:
return CultureInfo.InvariantCulture.CompareInfo.LastIndexOf(this, value, startIndex, count, CompareOptions.Ordinal);
case StringComparison.OrdinalIgnoreCase:
if (value.IsAscii() && this.IsAscii())
return CultureInfo.InvariantCulture.CompareInfo.LastIndexOf(this, value, startIndex, count, CompareOptions.IgnoreCase);
else
return TextInfo.LastIndexOfStringOrdinalIgnoreCase(this, value, startIndex, count);
default:
throw new ArgumentException(SR.NotSupported_StringComparison, nameof(comparisonType));
}
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using System.Data;
using System.Reflection.Emit;
using System.Reflection;
using Volte.Data.Json;
namespace Volte.Data.Dapper
{
internal class AutoCompiler<T> {
const string ZFILE_NAME = "AutoCompiler";
public static object _PENDING;
public static Dictionary<string, MyDelegate> Convert_Dict;
public delegate List<T> MyDelegate(IDataReader _DataReader);
private static readonly MethodInfo DataRecord_IsDBNull = typeof(IDataRecord).GetMethod("IsDBNull", new Type[] { typeof(int) });
private static readonly MethodInfo DataReader_Read = typeof(IDataReader).GetMethod("Read");
static AutoCompiler()
{
Convert_Dict = new Dictionary<string, MyDelegate>();
_PENDING = new object();
}
public static void WhileLoopByAttributeMapping(ILGenerator gen, Type classType, List<AttributeMapping> _Attributes)
{
// Preparing locals
LocalBuilder list = gen.DeclareLocal(typeof(System.Collections.Generic.List<>).MakeGenericType(classType));
Label Loop = gen.DefineLabel();
Label Exit = gen.DefineLabel();
// Writing body
gen.Emit(OpCodes.Nop);
//*** List<ZULABELMEntity> list = new List<ZULABELMEntity>();
gen.Emit(OpCodes.Newobj, typeof(System.Collections.Generic.List<>).MakeGenericType(classType).GetConstructor(Type.EmptyTypes));
gen.Emit(OpCodes.Stloc_S, list);
//*** while (IDataReader.Read()) {
gen.MarkLabel(Loop);
gen.Emit(OpCodes.Ldarg_0);
gen.Emit(OpCodes.Callvirt, DataReader_Read);
gen.Emit(OpCodes.Brfalse, Exit);
LocalBuilder item = gen.DeclareLocal(classType);
LocalBuilder[] colIndices = new LocalBuilder[_Attributes.Count];
for (int i = 0; i < _Attributes.Count; i++) {
colIndices[i] = gen.DeclareLocal(typeof(int));
}
setValueByAttributeMapping(gen, classType, _Attributes, item);
gen.Emit(OpCodes.Ldloc_1);
gen.Emit(OpCodes.Ldc_I4_1);
gen.Emit(OpCodes.Callvirt, typeof(EntityObject).GetMethod("set_Verified"));
//*** list.Add(item);
gen.Emit(OpCodes.Ldloc_S, list);
gen.Emit(OpCodes.Ldloc_S, item);
gen.Emit(OpCodes.Callvirt, typeof(System.Collections.Generic.List<>).MakeGenericType(classType).GetMethod("Add"));
//***}
gen.Emit(OpCodes.Br, Loop);
gen.MarkLabel(Exit);
//*** _DataReader.Close();
gen.Emit(OpCodes.Ldarg_0);
gen.Emit(OpCodes.Callvirt, typeof(IDataReader).GetMethod("Close"));
//*** return list;
gen.Emit(OpCodes.Ldloc_S, list);
gen.Emit(OpCodes.Ret);
}
private static void setValueByAttributeMapping(ILGenerator gen, Type classType, List<AttributeMapping> _Attributes, LocalBuilder item)
{
// classType item = new classType();
gen.Emit(OpCodes.Newobj, classType.GetConstructor(Type.EmptyTypes));
gen.Emit(OpCodes.Stloc_S, item);
int i = 0;
foreach (AttributeMapping _Attribute in _Attributes) {
Label common = gen.DefineLabel();
//** if(!_DataReader.IsDBNull(0))
gen.Emit(OpCodes.Ldarg_0);
gen.Emit(OpCodes.Ldc_I4_S, i);
gen.Emit(OpCodes.Callvirt, DataRecord_IsDBNull);
gen.Emit(OpCodes.Stloc_3);
gen.Emit(OpCodes.Ldloc_3);
gen.Emit(OpCodes.Brtrue_S, common);
gen.Emit(OpCodes.Ldloc_1);
//obj.LABEL_ID=_DataReader.GetXXX(0);
gen.Emit(OpCodes.Ldarg_0);
gen.Emit(OpCodes.Ldc_I4_S, i);
gen.Emit(OpCodes.Callvirt, typeof(IDataRecord).GetMethod("Get" + _Attribute.Type));
gen.Emit(OpCodes.Callvirt, classType.GetMethod("set_" + _Attribute.Name));
//ZZTrace.Debug(ZFILE_NAME,"set_" + _Attribute.Name+" "+"Get" + _Attribute.Type );
gen.Emit(OpCodes.Nop);
gen.MarkLabel(common);
i++;
}
}
public static void WhileLoopByField(ILGenerator gen, Type classType, IDataReader _DataReader)
{
// Preparing locals
LocalBuilder list = gen.DeclareLocal(typeof(System.Collections.Generic.List<>).MakeGenericType(classType));
Label Loop = gen.DefineLabel();
Label Exit = gen.DefineLabel();
// Writing body
gen.Emit(OpCodes.Nop);
//*** List<ZULABELMEntity> list = new List<ZULABELMEntity>();
gen.Emit(OpCodes.Newobj, typeof(System.Collections.Generic.List<>).MakeGenericType(classType).GetConstructor(Type.EmptyTypes));
gen.Emit(OpCodes.Stloc_S, list);
//*** while (IDataReader.Read()) {
gen.MarkLabel(Loop);
gen.Emit(OpCodes.Ldarg_0);
gen.Emit(OpCodes.Callvirt, DataReader_Read);
gen.Emit(OpCodes.Brfalse, Exit);
LocalBuilder item = gen.DeclareLocal(classType);
LocalBuilder[] colIndices = new LocalBuilder[_DataReader.FieldCount];
for (int i = 0; i < _DataReader.FieldCount; i++) {
colIndices[i] = gen.DeclareLocal(typeof(int));
}
setValueByField(gen, classType, _DataReader, item);
//*** list.Add(item);
gen.Emit(OpCodes.Ldloc_S, list);
gen.Emit(OpCodes.Ldloc_S, item);
gen.Emit(OpCodes.Callvirt, typeof(System.Collections.Generic.List<>).MakeGenericType(classType).GetMethod("Add"));
//***}
gen.Emit(OpCodes.Br, Loop);
gen.MarkLabel(Exit);
//*** _DataReader.Close();
gen.Emit(OpCodes.Ldarg_0);
gen.Emit(OpCodes.Callvirt, typeof(IDataReader).GetMethod("Close"));
//*** return list;
gen.Emit(OpCodes.Ldloc_S, list);
gen.Emit(OpCodes.Ret);
}
private static void setValueByField(ILGenerator gen, Type classType, IDataReader _DataReader, LocalBuilder item)
{
// classType item = new classType();
gen.Emit(OpCodes.Newobj, classType.GetConstructor(Type.EmptyTypes));
gen.Emit(OpCodes.Stloc_S, item);
int i = 0;
int fieldCount = _DataReader.FieldCount;
Dictionary<string, PropertyInfo> _Columns = new Dictionary<string, PropertyInfo>();
PropertyInfo[] properties = classType.GetProperties(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
foreach (PropertyInfo p in properties) {
_Columns[p.Name.ToLower()] = p;
}
while (i < fieldCount) {
string cKey = _DataReader.GetName(i).ToLower();
if (_Columns.ContainsKey(cKey)) {
string Name = _Columns[cKey].Name;
string PropertyType = Type.GetTypeCode(_Columns[cKey].PropertyType).ToString();
Label common = gen.DefineLabel();
//** if(!_DataReader.IsDBNull(0))
gen.Emit(OpCodes.Ldarg_0);
gen.Emit(OpCodes.Ldc_I4_S, i);
gen.Emit(OpCodes.Callvirt, DataRecord_IsDBNull);
gen.Emit(OpCodes.Stloc_3);
gen.Emit(OpCodes.Ldloc_3);
gen.Emit(OpCodes.Brtrue_S, common);
gen.Emit(OpCodes.Ldloc_1);
//**obj.LABEL_ID=_DataReader.GetXXX(0);
gen.Emit(OpCodes.Ldarg_0);
gen.Emit(OpCodes.Ldc_I4_S, i);
gen.Emit(OpCodes.Callvirt, typeof(IDataRecord).GetMethod("Get" + PropertyType));
gen.Emit(OpCodes.Callvirt, classType.GetMethod("set_" + Name));
//ZZTrace.Debug(ZFILE_NAME,"ByField set_" + Name+" "+"Get" + PropertyType);
gen.Emit(OpCodes.Nop);
gen.MarkLabel(common);
}
//ZZTrace.Error(ZFILE_NAME,"["+cKey+"]");
if (cKey == "verified") {
gen.Emit(OpCodes.Ldloc_1);
gen.Emit(OpCodes.Ldc_I4_1);
gen.Emit(OpCodes.Callvirt, typeof(EntityObject).GetMethod("set_Verified"));
}
i++;
}
}
public static List<T> ConvertToEntity(Type classType, List<AttributeMapping> _Attributes, IDataReader _DataReader)
{
string entityName = classType.ToString();
//ZZTrace.Debug(ZFILE_NAME,"ByAttributeMapping set_" + entityName);
MyDelegate handler;
lock (_PENDING) {
if (Convert_Dict.ContainsKey(entityName)) {
handler = Convert_Dict[entityName];
} else {
var _dynamicMethod = new DynamicMethod(string.Empty, typeof(List<T>), new Type[] { typeof(IDataReader) }, typeof(AutoCompiler<T>));
ParameterBuilder _DataReader2 = _dynamicMethod.DefineParameter(1, ParameterAttributes.None, "_DataReader");
ILGenerator ilgen = _dynamicMethod.GetILGenerator();
WhileLoopByAttributeMapping(ilgen, classType, _Attributes);
handler = (MyDelegate) _dynamicMethod.CreateDelegate(typeof(MyDelegate));
Convert_Dict[entityName] = handler;
}
}
return handler(_DataReader);
}
public static List<T> ConvertToEntity(IDataReader _DataReader)
{
Type classType = typeof(T);
string entityName = "part_" + classType.ToString();
//ZZTrace.Debug(ZFILE_NAME,entityName);
MyDelegate handler;
lock (_PENDING) {
if (Convert_Dict.ContainsKey(entityName)) {
handler = Convert_Dict[entityName];
} else {
DynamicMethod _dynamicMethod = new DynamicMethod(string.Empty, typeof(List<T>), new Type[] { typeof(IDataReader) }, typeof(AutoCompiler<T>));
ParameterBuilder _DataReader2 = _dynamicMethod.DefineParameter(1, ParameterAttributes.None, "_DataReader");
ILGenerator ilgen = _dynamicMethod.GetILGenerator();
WhileLoopByField(ilgen, classType, _DataReader);
handler = (MyDelegate) _dynamicMethod.CreateDelegate(typeof(MyDelegate));
Convert_Dict[entityName] = handler;
}
}
return handler(_DataReader);
}
}
}
| |
using System;
using System.Net;
using System.Threading.Tasks;
using PillowSharp.BaseObject;
using RestSharp;
using RestSharp.Authenticators;
using PillowSharp.Helper;
using System.Linq;
using PillowSharp.Client;
using System.Collections.Generic;
using System.IO;
using PillowSharp.CouchType;
using System.Web;
using pillowsharp.Middleware;
using pillowsharp.Middleware.Default;
using pillowsharp.Helper;
using System.Diagnostics;
namespace PillowSharp.Middleware.Default
{
public class BasicWebRequestHelper : AWebRequestHelper
{
//RestSharp client
RestClient client = null;
//Cookie storage for autehntication, optional
CookieContainer cookieContainer = null;
//URI to server, used for Cookie
Uri serverURI = null;
//If set call time is traced
public bool Trace { get; set; } //TODO add trace to the right places, #endregion
public Action<TraceInformation> TraceCallBack { get; set; } //TODO call this if trace is true and provide running time in ms
//Create the Middleware and pass server data to it
public BasicWebRequestHelper(ICouchdbServer Server) : base(Server)
{
UpdateServerData(Server);
}
public override void UpdateServerData(ICouchdbServer Server)
{
//Creteate the rest clinet
client = new RestClient(Server.GetServerURL());
//Generate needed data for selected auth type
if (Server.LoginType == ELoginTypes.BasicAuth)
{
client.Authenticator = new HttpBasicAuthenticator(Server.GetLoginData().UserName, Server.GetLoginData().Password);
}
else if (Server.LoginType == ELoginTypes.TokenLogin)
{
cookieContainer = new CookieContainer();
client.CookieContainer = cookieContainer;
serverURI = new Uri(Server.GetServerURL());
}
}
private RestRequest BuildRequestBase(string Resource, Method Method = Method.GET, int TimeOut = 30, KeyValuePair<string, object>[] QueryParameter = null)
{
var request = new RestRequest
{
Method = Method,
Timeout = TimeOut * 1000,
Resource = Resource
};
if (QueryParameter != null)
{
foreach (var keyValue in QueryParameter)
{
if (keyValue.Key != null && keyValue.Value != null)
request.AddQueryParameter(keyValue.Key, keyValue.Value.ToString());
}
}
return request;
}
private RestRequest AddJSONBody(RestRequest request, string Body)
{
//add a json body to the request
request.AddParameter("application/json", Body, ParameterType.RequestBody); //todo add type as constant
return request;
}
//Base function for all requests
private Task<pillowsharp.Middleware.RestResponse> RequestAsync(RestRequest Request)
{
return Task.Factory.StartNew(() => { return this.Request(Request); });
// return client.GetResponseAsync(Request).Then(Response => new RestSharpResponse(Response) as pillowsharp.Middleware.RestResponse);
}
private pillowsharp.Middleware.RestResponse Request(RestRequest Request)
{
var stopwatch = new Stopwatch();
if (Trace)
{
stopwatch.Start();
}
var result = new RestSharpResponse(client.Execute(Request)) as pillowsharp.Middleware.RestResponse;
if (Trace)
{
stopwatch.Stop();
TraceCallBack?.Invoke(new TraceInformation()
{
RequestTimeInMs = stopwatch.ElapsedMilliseconds,
RequestUrl = Request.Resource,
RequestMethod = Request.Method.ToString("g")
});
}
return result;
}
public override pillowsharp.Middleware.RestResponse GetDocument(string ID, string Database, string Revision = null)
{
return Get(BuildURL(Database, ID), new KeyValuePair<string, object>(Rev, Revision));
}
//Get a single document with the given revesion number from the db
public override Task<pillowsharp.Middleware.RestResponse> GetDocumentAsync(string ID, string Database, string Revision = null)
{
return Task.Factory.StartNew(() =>
{
return this.GetDocument(ID, Database, Revision);
});
}
//Get request to the given URL
public override pillowsharp.Middleware.RestResponse Get(string Url)
{
return Request(BuildRequestBase(Url));
}
public override Task<pillowsharp.Middleware.RestResponse> GetAsync(string Url, params KeyValuePair<string, object>[] Parameter)
{
return Task.Factory.StartNew(() =>
{
return this.Get(Url, Parameter);
});
}
//Get request to the given URL include Request parameters
public override pillowsharp.Middleware.RestResponse Get(string Url, params KeyValuePair<string, object>[] Parameter)
{
var getRequest = BuildRequestBase(Url);
if (Parameter != null)
{
foreach (var keyValue in Parameter)
{
if (keyValue.Key != null && keyValue.Value != null)
getRequest.AddQueryParameter(keyValue.Key, keyValue.Value.ToString());
}
}
return Request(getRequest);
}
public override Task<pillowsharp.Middleware.RestResponse> PutAsync(string Url, string Body = null, KeyValuePair<string, object>[] QueryParameter = null)
{
return Task.Factory.StartNew(() =>
{
return this.Put(Url, Body, QueryParameter);
});
}
//PUT request to the given URL with optional body
public override pillowsharp.Middleware.RestResponse Put(string Url, string Body = null, KeyValuePair<string, object>[] QueryParameter = null)
{
var putRequest = BuildRequestBase(Url, Method.PUT, QueryParameter: QueryParameter);
if (!string.IsNullOrEmpty(Body))
AddJSONBody(putRequest, Body);
return Request(putRequest);
}
//DELETE request to the given URL
public override Task<pillowsharp.Middleware.RestResponse> DeleteAsync(string Uri)
{
return Task.Factory.StartNew(() =>
{
return this.Delete(Uri);
});
}
public override pillowsharp.Middleware.RestResponse Delete(string Uri)
{
return Request(BuildRequestBase(Uri, Method.DELETE));
}
public override Task<pillowsharp.Middleware.RestResponse> PostAsync(string Uri, string Body = null)
{
return Task.Factory.StartNew(() =>
{
return this.Post(Uri, Body);
});
}
//Post requrest to the given URL with an optional Body
public override pillowsharp.Middleware.RestResponse Post(string Uri, string Body = null)
{
var postRequest = BuildRequestBase(Uri, Method.POST);
if (!string.IsNullOrEmpty(Body))
AddJSONBody(postRequest, Body);
return Request(postRequest);
}
private RestRequest BuildFileBaseRequest(string ID, string AttachmentName, string Revision, string Database, Method Method)
{
AttachmentName = HttpUtility.UrlEncode(AttachmentName);
var getRequest = BuildRequestBase($"{Database}/{ID}/{AttachmentName}", Method);
getRequest.AddQueryParameter(Rev, Revision);
return getRequest;
}
public override Task<pillowsharp.Middleware.RestResponse> UploadFileAsync(string ID, string AttachmentName, string Revision, string Database, string File)
{
return Task.Factory.StartNew(() =>
{
return UploadFile(ID, AttachmentName, Revision, Database, File);
});
}
//Add a file to an existing document
public override pillowsharp.Middleware.RestResponse UploadFile(string ID, string AttachmentName, string Revision, string Database, string File)
{
var putRequest = BuildFileBaseRequest(ID, AttachmentName, Revision, Database, Method.PUT);
var contentType = MimeMapping.GetMimeType(File);
putRequest.AlwaysMultipartFormData = false;
putRequest.AddHeader("Content-Type", contentType);
putRequest.AddParameter(contentType, System.IO.File.ReadAllBytes(File), ParameterType.RequestBody);
return Request(putRequest);
}
public override Task<pillowsharp.Middleware.RestResponse> DeleteFileAsync(string ID, string AttachmentName, string Revision, string Database)
{
return Task.Factory.StartNew(() =>
{
return DeleteFile(ID, AttachmentName, Revision, Database);
});
}
//Delete a file from an existing document
public override pillowsharp.Middleware.RestResponse DeleteFile(string ID, string AttachmentName, string Revision, string Database)
{
var deleteRequest = BuildFileBaseRequest(ID, AttachmentName, Revision, Database, Method.DELETE);
return Request(deleteRequest);
}
//Get a file from an existing document
public override pillowsharp.Middleware.RestResponse GetFile(string ID, string AttachmentName, string Revision, string Database)
{
return Request(BuildFileBaseRequest(ID, AttachmentName, Revision, Database, Method.GET));
}
//Set the given value for the coo
public override void SetCookie(string CookieName, string Value)
{
var currentCookie = client.CookieContainer.GetCookies(serverURI)[CookieName];
if (currentCookie != null)
{
currentCookie.Value = Value;
}
else
{
client.CookieContainer.Add(serverURI, new Cookie(CookieName, Value, "/"));
}
}
public override Task<pillowsharp.Middleware.RestResponse> ViewAsync(string Database, string DocumentName, string ViewFunctionName, KeyValuePair<string, object>[] QueryParameter, HttpRequestMethod HTTPMethod, string Filter)
{
return Task.Factory.StartNew(() =>
{
return View(Database, DocumentName, ViewFunctionName, QueryParameter, HTTPMethod, Filter);
});
}
//Run, change or create the given view
public override pillowsharp.Middleware.RestResponse View(string Database, string DocumentName, string ViewFunctionName, KeyValuePair<string, object>[] QueryParameter, HttpRequestMethod HTTPMethod, string Filter)
{
if (!Enum.IsDefined(typeof(Method), HTTPMethod.ToString()))
throw new PillowException($"Unable to use {HTTPMethod} as a request method in the default WebRequestHelper");
var viewRequest = BuildRequestBase(BuildURL(Database, DocumentName, CouchEntryPoints.ViewDoc, ViewFunctionName),
QueryParameter: QueryParameter, Method: (Method)HTTPMethod);
if (!string.IsNullOrEmpty(Filter))
AddJSONBody(viewRequest, Filter);
return Request(viewRequest);
}
public override pillowsharp.Middleware.RestResponse List(string database, string designDocumentId, string listName, string ViewName, KeyValuePair<string, object>[] queryParameter)
{
var listRequest = BuildRequestBase(BuildURL(database,designDocumentId,CouchEntryPoints.List,listName,ViewName),(Method)HttpRequestMethod.GET, QueryParameter: queryParameter);
return Request(listRequest);
}
public override Task<pillowsharp.Middleware.RestResponse> HeadAsync(string Uri)
{
return Task.Factory.StartNew(() =>
{
return Head(Uri);
});
}
public override pillowsharp.Middleware.RestResponse Head(string Uri)
{
return Request(BuildRequestBase(Uri, Method.HEAD));
}
public override Task<pillowsharp.Middleware.RestResponse> GetAsync(string Url)
{
return Task.Factory.StartNew(() =>
{
return this.Get(Url);
});
}
public override Task<pillowsharp.Middleware.RestResponse> GetFileAsync(string ID, string AttachmentName, string Revision, string Database)
{
return Task.Factory.StartNew(() =>
{
return GetFile(ID, AttachmentName, Revision, Database);
});
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.IO.Packaging;
using System.Linq;
using Microsoft.Internal.Web.Utils;
using NuGet.Resources;
namespace NuGet
{
public class ZipPackage : IPackage
{
private const string AssemblyReferencesDir = "lib";
private const string ResourceAssemblyExtension = ".resources.dll";
private const string CacheKeyFormat = "NUGET_ZIP_PACKAGE_{0}_{1}{2}";
private const string AssembliesCacheKey = "ASSEMBLIES";
private const string FilesCacheKey = "FILES";
private readonly bool _enableCaching;
private static readonly string[] AssemblyReferencesExtensions = new[] { ".dll", ".exe", ".winmd" };
private static readonly TimeSpan CacheTimeout = TimeSpan.FromSeconds(15);
// paths to exclude
private static readonly string[] _excludePaths = new[] { "_rels", "package" };
// We don't store the steam itself, just a way to open the stream on demand
// so we don't have to hold on to that resource
private readonly Func<Stream> _streamFactory;
private HashSet<string> _references;
public ZipPackage(string fileName)
: this(fileName, enableCaching: false)
{
}
public ZipPackage(Stream stream)
{
if (stream == null)
{
throw new ArgumentNullException("stream");
}
_enableCaching = false;
_streamFactory = stream.ToStreamFactory();
EnsureManifest();
}
internal ZipPackage(string fileName, bool enableCaching)
{
if (String.IsNullOrEmpty(fileName))
{
throw new ArgumentException(CommonResources.Argument_Cannot_Be_Null_Or_Empty, "fileName");
}
_enableCaching = enableCaching;
_streamFactory = () => File.OpenRead(fileName);
EnsureManifest();
}
internal ZipPackage(Func<Stream> streamFactory, bool enableCaching)
{
if (streamFactory == null)
{
throw new ArgumentNullException("streamFactory");
}
_enableCaching = enableCaching;
_streamFactory = streamFactory;
EnsureManifest();
}
public string Id
{
get;
set;
}
public SemanticVersion Version
{
get;
set;
}
public string Title
{
get;
set;
}
public IEnumerable<string> Authors
{
get;
set;
}
public IEnumerable<string> Owners
{
get;
set;
}
public Uri IconUrl
{
get;
set;
}
public Uri LicenseUrl
{
get;
set;
}
public Uri ProjectUrl
{
get;
set;
}
public Uri ReportAbuseUrl
{
get
{
return null;
}
}
public int DownloadCount
{
get
{
return -1;
}
}
public bool RequireLicenseAcceptance
{
get;
set;
}
public string Description
{
get;
set;
}
public string Summary
{
get;
set;
}
public string ReleaseNotes
{
get;
set;
}
public string Language
{
get;
set;
}
public string Tags
{
get;
set;
}
public bool IsAbsoluteLatestVersion
{
get
{
return true;
}
}
public bool IsLatestVersion
{
get
{
return this.IsReleaseVersion();
}
}
public bool Listed
{
get
{
return true;
}
}
public DateTimeOffset? Published
{
get;
set;
}
public string Copyright
{
get;
set;
}
public IEnumerable<PackageDependency> Dependencies
{
get;
set;
}
public IEnumerable<IPackageAssemblyReference> AssemblyReferences
{
get
{
if (_enableCaching)
{
return MemoryCache.Instance.GetOrAdd(GetAssembliesCacheKey(), GetAssembliesNoCache, CacheTimeout);
}
return GetAssembliesNoCache();
}
}
public IEnumerable<FrameworkAssemblyReference> FrameworkAssemblies
{
get;
set;
}
public IEnumerable<IPackageFile> GetFiles()
{
if (_enableCaching)
{
return MemoryCache.Instance.GetOrAdd(GetFilesCacheKey(), GetFilesNoCache, CacheTimeout);
}
return GetFilesNoCache();
}
public Stream GetStream()
{
return _streamFactory();
}
private List<IPackageAssemblyReference> GetAssembliesNoCache()
{
return (from file in GetFiles()
where IsAssemblyReference(file, _references)
select (IPackageAssemblyReference)new ZipPackageAssemblyReference(file)
).ToList();
}
private List<IPackageFile> GetFilesNoCache()
{
using (Stream stream = _streamFactory())
{
Package package = Package.Open(stream);
return (from part in package.GetParts()
where IsPackageFile(part)
select (IPackageFile)new ZipPackageFile(part)).ToList();
}
}
private void EnsureManifest()
{
using (Stream stream = _streamFactory())
{
Package package = Package.Open(stream);
PackageRelationship relationshipType = package.GetRelationshipsByType(Constants.PackageRelationshipNamespace + PackageBuilder.ManifestRelationType).SingleOrDefault();
if (relationshipType == null)
{
throw new InvalidOperationException(NuGetResources.PackageDoesNotContainManifest);
}
PackagePart manifestPart = package.GetPart(relationshipType.TargetUri);
if (manifestPart == null)
{
throw new InvalidOperationException(NuGetResources.PackageDoesNotContainManifest);
}
using (Stream manifestStream = manifestPart.GetStream())
{
Manifest manifest = Manifest.ReadFrom(manifestStream);
IPackageMetadata metadata = manifest.Metadata;
Id = metadata.Id;
Version = metadata.Version;
Title = metadata.Title;
Authors = metadata.Authors;
Owners = metadata.Owners;
IconUrl = metadata.IconUrl;
LicenseUrl = metadata.LicenseUrl;
ProjectUrl = metadata.ProjectUrl;
RequireLicenseAcceptance = metadata.RequireLicenseAcceptance;
Description = metadata.Description;
Summary = metadata.Summary;
ReleaseNotes = metadata.ReleaseNotes;
Language = metadata.Language;
Tags = metadata.Tags;
Dependencies = metadata.Dependencies;
FrameworkAssemblies = metadata.FrameworkAssemblies;
Copyright = metadata.Copyright;
IEnumerable<string> references = (manifest.Metadata.References ?? Enumerable.Empty<ManifestReference>()).Select(c => c.File);
_references = new HashSet<string>(references, StringComparer.OrdinalIgnoreCase);
// Ensure tags start and end with an empty " " so we can do contains filtering reliably
if (!String.IsNullOrEmpty(Tags))
{
Tags = " " + Tags + " ";
}
}
}
}
internal static bool IsAssemblyReference(IPackageFile file, IEnumerable<string> references)
{
// Assembly references are in lib/ and have a .dll/.exe/.winmd extension
var path = file.Path;
var fileName = Path.GetFileName(path);
return path.StartsWith(AssemblyReferencesDir, StringComparison.OrdinalIgnoreCase) &&
// Exclude resource assemblies
!path.EndsWith(ResourceAssemblyExtension, StringComparison.OrdinalIgnoreCase) &&
AssemblyReferencesExtensions.Contains(Path.GetExtension(path), StringComparer.OrdinalIgnoreCase) &&
// If references are listed, ensure that the file is listed in it.
(references.IsEmpty() || references.Contains(fileName));
}
private static bool IsPackageFile(PackagePart part)
{
string path = UriUtility.GetPath(part.Uri);
// We exclude any opc files and the manifest file (.nuspec)
return !_excludePaths.Any(p => path.StartsWith(p, StringComparison.OrdinalIgnoreCase)) &&
!PackageUtility.IsManifest(path);
}
public override string ToString()
{
return this.GetFullName();
}
private string GetFilesCacheKey()
{
return String.Format(CultureInfo.InvariantCulture, CacheKeyFormat, FilesCacheKey, Id, Version);
}
private string GetAssembliesCacheKey()
{
return String.Format(CultureInfo.InvariantCulture, CacheKeyFormat, AssembliesCacheKey, Id, Version);
}
internal static void ClearCache(IPackage package)
{
var zipPackage = package as ZipPackage;
// Remove the cache entries for files and assemblies
if (zipPackage != null)
{
MemoryCache.Instance.Remove(zipPackage.GetAssembliesCacheKey());
MemoryCache.Instance.Remove(zipPackage.GetFilesCacheKey());
}
}
}
}
| |
using System;
using System.Diagnostics.CodeAnalysis;
namespace Microsoft.Msagl.Core.Geometry.Curves {
/// <summary>
/// 2 by 3 matrix of plane affine transformations
/// </summary>
#if TEST_MSAGL
[Serializable]
#endif
public class PlaneTransformation {
/// <summary>
/// hash function
/// </summary>
/// <returns></returns>
public override int GetHashCode() {
return (elements != null ? elements.GetHashCode() : 0);
}
/// <summary>
/// Determines whether the specified <see cref="T:System.Object"/> is equal to the current <see cref="T:System.Object"/>.
/// </summary>
/// <returns>
/// true if the specified <see cref="T:System.Object"/> is equal to the current <see cref="T:System.Object"/>; otherwise, false.
/// </returns>
/// <param name="obj">The object to compare with the current object. </param><filterpriority>2</filterpriority>
public override bool Equals(object obj) {
var t = obj as PlaneTransformation;
return t != null && t == this;
}
readonly double[][] elements = new double[2][];
/// <summary>
/// the matrix elements
/// </summary>
internal double[][] Elements {
get { return elements; }
}
/// <summary>
/// i,j th element
/// </summary>
/// <param name="rowIndex"></param>
/// <param name="columnIndex"></param>
/// <returns></returns>
[SuppressMessage("Microsoft.Design", "CA1023:IndexersShouldNotBeMultidimensional")]
public double this[int rowIndex, int columnIndex] {
get { return Elements[rowIndex][columnIndex]; }
set { Elements[rowIndex][columnIndex] = value; }
}
/// <summary>
/// constructs the an identity transformation
/// </summary>
public PlaneTransformation() {
elements[0] = new double[3];
elements[1] = new double[3];
this[0, 0] = this[1, 1] = 1; //create a unit transform
}
/// <summary>
/// first row, second row
/// </summary>
/// <param name="matrixElement00">0,0</param>
/// <param name="matrixElement01">0,1</param>
/// <param name="matrixElement02">0,2</param>
/// <param name="matrixElement10">1,0</param>
/// <param name="matrixElement11">1,1</param>
/// <param name="matrixElement12">1,2</param>
[SuppressMessage("Microsoft.Design", "CA1025:ReplaceRepetitiveArgumentsWithParamsArray")]
public PlaneTransformation(double matrixElement00, double matrixElement01, double matrixElement02,
double matrixElement10, double matrixElement11, double matrixElement12) {
elements[0] = new double[3];
elements[1] = new double[3];
elements[0][0] = matrixElement00; elements[0][1] = matrixElement01; elements[0][2] = matrixElement02;
elements[1][0] = matrixElement10; elements[1][1] = matrixElement11; elements[1][2] = matrixElement12;
}
/// <summary>
/// the matrix by point multiplication
/// </summary>
/// <param name="transformation"></param>
/// <param name="point"></param>
/// <returns></returns>
static public Point operator *(PlaneTransformation transformation, Point point) {
return Multiply(transformation, point);
}
/// <summary>
/// Point by matrix multiplication
/// </summary>
/// <param name="transformation"></param>
/// <param name="point"></param>
/// <returns></returns>
static public Point Multiply(PlaneTransformation transformation, Point point) {
if (transformation != null)
return new Point(transformation[0, 0] * point.X + transformation[0, 1] * point.Y + transformation[0, 2], transformation[1, 0] * point.X + transformation[1, 1] * point.Y + transformation[1, 2]);
return new Point();
}
/// <summary>
/// matrix matrix multiplication
/// </summary>
/// <param name="transformation"></param>][
/// <param name="transformation0"></param>
/// <returns></returns>
static public PlaneTransformation operator *(PlaneTransformation transformation, PlaneTransformation transformation0) {
return Multiply(transformation, transformation0);
}
/// <summary>
/// matrix matrix multiplication
/// </summary>
/// <param name="a"></param>
/// <param name="b"></param>
/// <returns></returns>
static public PlaneTransformation Multiply(PlaneTransformation a, PlaneTransformation b) {
if (a != null && b != null)
return new PlaneTransformation(
a[0, 0] * b[0, 0] + a[0, 1] * b[1, 0], a[0, 0] * b[0, 1] + a[0, 1] * b[1, 1], a[0, 0] * b[0, 2] + a[0, 1] * b[1, 2] + a[0, 2],
a[1, 0] * b[0, 0] + a[1, 1] * b[1, 0], a[1, 0] * b[0, 1] + a[1, 1] * b[1, 1], a[1, 0] * b[0, 2] + a[1, 1] * b[1, 2] + a[1, 2]);
return null;
}
/// <summary>
/// matrix divided by matrix
/// </summary>
/// <param name="transform0"></param>
/// <param name="transform1"></param>
/// <returns></returns>
static public PlaneTransformation operator /(PlaneTransformation transform0, PlaneTransformation transform1) {
if (transform0 != null && transform1 != null)
return transform0 * transform1.Inverse;
return null;
}
/// <summary>
/// Divid matrix by a matrix
/// </summary>
/// <param name="transformation0"></param>
/// <param name="transformation1"></param>
/// <returns></returns>
static public PlaneTransformation Divide(PlaneTransformation transformation0, PlaneTransformation transformation1) {
return transformation0 / transformation1;
}
/// <summary>
/// returns the inversed matrix
/// </summary>
public PlaneTransformation Inverse {
get {
double det = Elements[0][0] * Elements[1][1] - Elements[1][0] * Elements[0][1];
// if (ApproximateComparer.Close(det, 0))
// throw new InvalidOperationException();//"trying to reverse a singular matrix");
double a00 = Elements[1][1] / det;
double a01 = -Elements[0][1] / det;
double a10 = -Elements[1][0] / det;
double a11 = Elements[0][0] / det;
double a02 = -a00 * Elements[0][2] - a01 * Elements[1][2];
double a12 = -a10 * Elements[0][2] - a11 * Elements[1][2];
return new PlaneTransformation(a00, a01, a02, a10, a11, a12);
}
}
/// <summary>
/// unit matrix
/// </summary>
static public PlaneTransformation UnitTransformation {
get { return new PlaneTransformation(1, 0, 0, 0, 1, 0); }
}
/// <summary>
/// Rotation matrix
/// </summary>
/// <param name="angle">the angle of rotation</param>
/// <returns></returns>
static public PlaneTransformation Rotation(double angle) {
double cos = Math.Cos(angle);
double sin = Math.Sin(angle);
return new PlaneTransformation(cos, -sin, 0, sin, cos, 0);
}
/// <summary>
/// checks if the matrix is an identity one
/// </summary>
public bool IsIdentity {
get {
return
ApproximateComparer.Close(Elements[0][0], 1) &&
ApproximateComparer.Close(Elements[0][1], 0) &&
ApproximateComparer.Close(Elements[0][2], 0) &&
ApproximateComparer.Close(Elements[1][0], 0) &&
ApproximateComparer.Close(Elements[1][1], 1) &&
ApproximateComparer.Close(Elements[1][2], 0);
}
}
/// <summary>
/// returns the point of the matrix offset
/// </summary>
public Point Offset {
get {
return new Point(Elements[0][2], Elements[1][2]);
}
}
/// <summary>
///
/// </summary>
/// <param name="a"></param>
/// <param name="b"></param>
/// <returns></returns>
public static bool operator ==(PlaneTransformation a, PlaneTransformation b) {
if ((object)a == null &&(object)b == null)
return true;
if ((object)a == null)
return false;
if ((object)b == null)
return false;
for (int i = 0; i < 2; i++)
for (int j = 0; j < 3;j++ )
if (a[i,j] != b[i,j])
return false;
return true;
}
/// <summary>
/// the inequality operator
/// </summary>
/// <param name="a"></param>
/// <param name="b"></param>
/// <returns></returns>
public static bool operator !=(PlaneTransformation a, PlaneTransformation b) {
return !(a == b);
}
/// <summary>
/// clones the transform
/// </summary>
/// <returns></returns>
public PlaneTransformation Clone() {
return new PlaneTransformation(this[0, 0], this[0, 1], this[0, 2], this[1, 0], this[1, 1], this[1, 2]);
}
/// <summary>
///
/// </summary>
/// <param name="scale"></param>
/// <param name="center"></param>
/// <returns></returns>
public static PlaneTransformation ScaleAroundCenterTransformation(double scale, Point center) {
/*var toOrigin = new PlaneTransformation(1, 0, -center.X, 0, 1, -center.Y);
var scaleTr = new PlaneTransformation(scale, 0, 0,
0, scale, 0);
var toCenter = new PlaneTransformation(1, 0, center.X, 0, 1, center.Y);
var t = toCenter*scaleTr*toOrigin;
return t;*/
var d = 1 - scale;
return new PlaneTransformation(scale, 0, d * center.X, 0, scale, d * center.Y);
}
public static PlaneTransformation ScaleAroundCenterTransformation(double xScale, double yScale, Point center)
{
/*var toOrigin = new PlaneTransformation(1, 0, -center.X, 0, 1, -center.Y);
var scaleTr = new PlaneTransformation(scale, 0, 0,
0, scale, 0);
var toCenter = new PlaneTransformation(1, 0, center.X, 0, 1, center.Y);
var t = toCenter*scaleTr*toOrigin;
return t;*/
var dX = 1 - xScale;
var dY = 1 - yScale;
return new PlaneTransformation(xScale, 0, dX * center.X, 0, yScale, dY * center.Y);
}
}
}
| |
using System;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using EventStore.Common.Log;
using EventStore.Common.Utils;
using EventStore.Core.Authentication;
using EventStore.Core.Bus;
using EventStore.Core.Cluster.Settings;
using EventStore.Core.Data;
using EventStore.Core.Messages;
using EventStore.Core.Messaging;
using EventStore.Core.Services.Storage.EpochManager;
using EventStore.Core.Services.Transport.Tcp;
using EventStore.Core.Settings;
using EventStore.Core.TransactionLog.Chunks;
using EventStore.Core.TransactionLog.LogRecords;
using EventStore.Transport.Tcp;
namespace EventStore.Core.Services.Replication
{
public class ReplicaService : IHandle<SystemMessage.StateChangeMessage>,
IHandle<ReplicationMessage.ReconnectToMaster>,
IHandle<ReplicationMessage.SubscribeToMaster>,
IHandle<ReplicationMessage.AckLogPosition>,
IHandle<StorageMessage.PrepareAck>,
IHandle<StorageMessage.CommitAck>,
IHandle<ClientMessage.TcpForwardMessage>
{
private static readonly ILogger Log = LogManager.GetLoggerFor<ReplicaService>();
private readonly TcpClientConnector _connector;
private readonly IPublisher _publisher;
private readonly TFChunkDb _db;
private readonly IEpochManager _epochManager;
private readonly IPublisher _networkSendQueue;
private readonly IAuthenticationProvider _authProvider;
private readonly VNodeInfo _nodeInfo;
private readonly bool _useSsl;
private readonly string _sslTargetHost;
private readonly bool _sslValidateServer;
private readonly InternalTcpDispatcher _tcpDispatcher = new InternalTcpDispatcher();
private VNodeState _state = VNodeState.Initializing;
private TcpConnectionManager _connection;
public ReplicaService(IPublisher publisher,
TFChunkDb db,
IEpochManager epochManager,
IPublisher networkSendQueue,
IAuthenticationProvider authProvider,
VNodeInfo nodeInfo,
bool useSsl,
string sslTargetHost,
bool sslValidateServer)
{
Ensure.NotNull(publisher, "publisher");
Ensure.NotNull(db, "db");
Ensure.NotNull(epochManager, "epochManager");
Ensure.NotNull(networkSendQueue, "networkSendQueue");
Ensure.NotNull(authProvider, "authProvider");
Ensure.NotNull(nodeInfo, "nodeInfo");
if (useSsl) Ensure.NotNull(sslTargetHost, "sslTargetHost");
_publisher = publisher;
_db = db;
_epochManager = epochManager;
_networkSendQueue = networkSendQueue;
_authProvider = authProvider;
_nodeInfo = nodeInfo;
_useSsl = useSsl;
_sslTargetHost = sslTargetHost;
_sslValidateServer = sslValidateServer;
_connector = new TcpClientConnector();
}
public void Handle(SystemMessage.StateChangeMessage message)
{
_state = message.State;
switch (message.State)
{
case VNodeState.Initializing:
case VNodeState.Unknown:
case VNodeState.PreMaster:
case VNodeState.Master:
case VNodeState.ShuttingDown:
case VNodeState.Shutdown:
{
Disconnect();
break;
}
case VNodeState.PreReplica:
{
var m = (SystemMessage.BecomePreReplica) message;
ConnectToMaster(m.Master);
break;
}
case VNodeState.CatchingUp:
case VNodeState.Clone:
case VNodeState.Slave:
{
// nothing changed, essentially
break;
}
default:
throw new ArgumentOutOfRangeException();
}
}
private void Disconnect()
{
if (_connection != null)
{
_connection.Stop(string.Format("Node state changed to {0}. Closing replication connection.", _state));
_connection = null;
}
}
private void OnConnectionEstablished(TcpConnectionManager manager)
{
_publisher.Publish(new SystemMessage.VNodeConnectionEstablished(manager.RemoteEndPoint, manager.ConnectionId));
}
private void OnConnectionClosed(TcpConnectionManager manager, SocketError socketError)
{
_publisher.Publish(new SystemMessage.VNodeConnectionLost(manager.RemoteEndPoint, manager.ConnectionId));
}
public void Handle(ReplicationMessage.ReconnectToMaster message)
{
ConnectToMaster(message.Master);
}
private void ConnectToMaster(VNodeInfo master)
{
Debug.Assert(_state == VNodeState.PreReplica);
var masterEndPoint = GetMasterEndPoint(master, _useSsl);
if (_connection != null)
_connection.Stop(string.Format("Reconnecting from old master [{0}] to new master: [{1}].",
_connection.RemoteEndPoint, masterEndPoint));
_connection = new TcpConnectionManager(_useSsl ? "master-secure" : "master-normal",
Guid.NewGuid(),
_tcpDispatcher,
_publisher,
masterEndPoint,
_connector,
_useSsl,
_sslTargetHost,
_sslValidateServer,
_networkSendQueue,
_authProvider,
ESConsts.InternalHeartbeatInterval,
ESConsts.InternalHeartbeatTimeout,
OnConnectionEstablished,
OnConnectionClosed);
_connection.StartReceiving();
}
private static IPEndPoint GetMasterEndPoint(VNodeInfo master, bool useSsl)
{
Ensure.NotNull(master, "master");
if (useSsl && master.InternalSecureTcp == null)
Log.Error("Internal secure connections are required, but no internal secure TCP end point is specified for master [{0}]!", master);
return useSsl ? master.InternalSecureTcp ?? master.InternalTcp : master.InternalTcp;
}
public void Handle(ReplicationMessage.SubscribeToMaster message)
{
if (_state != VNodeState.PreReplica)
throw new Exception(string.Format("_state is {0}, but is expected to be {1}", _state, VNodeState.PreReplica));
var logPosition = _db.Config.WriterCheckpoint.ReadNonFlushed();
var epochs = _epochManager.GetLastEpochs(ClusterConsts.SubscriptionLastEpochCount).ToArray();
Log.Info("Subscribing at LogPosition: {0} (0x{0:X}) to MASTER [{1}, {2:B}] as replica with SubscriptionId: {3:B}, "
+ "ConnectionId: {4:B}, LocalEndPoint: [{5}], Epochs:\n{6}...\n.",
logPosition, _connection.RemoteEndPoint, message.MasterId, message.SubscriptionId,
_connection.ConnectionId, _connection.LocalEndPoint, string.Join("\n", epochs.Select(x => x.AsString())));
var chunk = _db.Manager.GetChunkFor(logPosition);
if (chunk == null) throw new Exception(string.Format("Chunk was null during subscribing at {0} (0x{0:X}).", logPosition));
SendTcpMessage(_connection,
new ReplicationMessage.SubscribeReplica(
logPosition, chunk.ChunkHeader.ChunkId, epochs, _nodeInfo.InternalTcp,
message.MasterId, message.SubscriptionId, isPromotable: true));
}
public void Handle(ReplicationMessage.AckLogPosition message)
{
if (!_state.IsReplica()) throw new Exception("!_state.IsReplica()");
if (_connection == null) throw new Exception("_connection == null");
SendTcpMessage(_connection, message);
}
public void Handle(StorageMessage.PrepareAck message)
{
if (_state == VNodeState.Slave)
{
Debug.Assert(_connection != null, "_connection == null");
SendTcpMessage(_connection, message);
}
}
public void Handle(StorageMessage.CommitAck message)
{
if (_state == VNodeState.Slave)
{
Debug.Assert(_connection != null, "_connection == null");
SendTcpMessage(_connection, message);
}
}
public void Handle(ClientMessage.TcpForwardMessage message)
{
switch (_state)
{
case VNodeState.PreReplica:
{
if (_connection != null)
SendTcpMessage(_connection, message.Message);
break;
}
case VNodeState.CatchingUp:
case VNodeState.Clone:
case VNodeState.Slave:
{
Debug.Assert(_connection != null, "Connection manager is null in slave/clone/catching up state");
SendTcpMessage(_connection, message.Message);
break;
}
default:
throw new Exception(string.Format("Unexpected state: {0}", _state));
}
}
private void SendTcpMessage(TcpConnectionManager manager, Message msg)
{
_networkSendQueue.Publish(new TcpMessage.TcpSend(manager, msg));
}
}
}
| |
/*
* Qa full api
*
* No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)
*
* OpenAPI spec version: all
*
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Linq;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System.ComponentModel.DataAnnotations;
namespace HostMe.Sdk.Model
{
/// <summary>
/// WaitingReportItem
/// </summary>
[DataContract]
public partial class WaitingReportItem : IEquatable<WaitingReportItem>, IValidatableObject
{
/// <summary>
/// Initializes a new instance of the <see cref="WaitingReportItem" /> class.
/// </summary>
/// <param name="Status">Status.</param>
/// <param name="Created">Created.</param>
/// <param name="GroupSize">GroupSize.</param>
/// <param name="StartPosition">StartPosition.</param>
/// <param name="TimeToCall">TimeToCall.</param>
/// <param name="TimeToSeat">TimeToSeat.</param>
/// <param name="TimeToCancel">TimeToCancel.</param>
public WaitingReportItem(string Status = null, DateTimeOffset? Created = null, int? GroupSize = null, int? StartPosition = null, int? TimeToCall = null, int? TimeToSeat = null, int? TimeToCancel = null)
{
this.Status = Status;
this.Created = Created;
this.GroupSize = GroupSize;
this.StartPosition = StartPosition;
this.TimeToCall = TimeToCall;
this.TimeToSeat = TimeToSeat;
this.TimeToCancel = TimeToCancel;
}
/// <summary>
/// Gets or Sets Status
/// </summary>
[DataMember(Name="status", EmitDefaultValue=true)]
public string Status { get; set; }
/// <summary>
/// Gets or Sets Created
/// </summary>
[DataMember(Name="created", EmitDefaultValue=true)]
public DateTimeOffset? Created { get; set; }
/// <summary>
/// Gets or Sets GroupSize
/// </summary>
[DataMember(Name="groupSize", EmitDefaultValue=true)]
public int? GroupSize { get; set; }
/// <summary>
/// Gets or Sets StartPosition
/// </summary>
[DataMember(Name="startPosition", EmitDefaultValue=true)]
public int? StartPosition { get; set; }
/// <summary>
/// Gets or Sets TimeToCall
/// </summary>
[DataMember(Name="timeToCall", EmitDefaultValue=true)]
public int? TimeToCall { get; set; }
/// <summary>
/// Gets or Sets TimeToSeat
/// </summary>
[DataMember(Name="timeToSeat", EmitDefaultValue=true)]
public int? TimeToSeat { get; set; }
/// <summary>
/// Gets or Sets TimeToCancel
/// </summary>
[DataMember(Name="timeToCancel", EmitDefaultValue=true)]
public int? TimeToCancel { get; set; }
/// <summary>
/// Returns the string presentation of the object
/// </summary>
/// <returns>String presentation of the object</returns>
public override string ToString()
{
var sb = new StringBuilder();
sb.Append("class WaitingReportItem {\n");
sb.Append(" Status: ").Append(Status).Append("\n");
sb.Append(" Created: ").Append(Created).Append("\n");
sb.Append(" GroupSize: ").Append(GroupSize).Append("\n");
sb.Append(" StartPosition: ").Append(StartPosition).Append("\n");
sb.Append(" TimeToCall: ").Append(TimeToCall).Append("\n");
sb.Append(" TimeToSeat: ").Append(TimeToSeat).Append("\n");
sb.Append(" TimeToCancel: ").Append(TimeToCancel).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
/// <summary>
/// Returns the JSON string presentation of the object
/// </summary>
/// <returns>JSON string presentation of the object</returns>
public string ToJson()
{
return JsonConvert.SerializeObject(this, Formatting.Indented);
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
/// <param name="obj">Object to be compared</param>
/// <returns>Boolean</returns>
public override bool Equals(object obj)
{
// credit: http://stackoverflow.com/a/10454552/677735
return this.Equals(obj as WaitingReportItem);
}
/// <summary>
/// Returns true if WaitingReportItem instances are equal
/// </summary>
/// <param name="other">Instance of WaitingReportItem to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(WaitingReportItem other)
{
// credit: http://stackoverflow.com/a/10454552/677735
if (other == null)
return false;
return
(
this.Status == other.Status ||
this.Status != null &&
this.Status.Equals(other.Status)
) &&
(
this.Created == other.Created ||
this.Created != null &&
this.Created.Equals(other.Created)
) &&
(
this.GroupSize == other.GroupSize ||
this.GroupSize != null &&
this.GroupSize.Equals(other.GroupSize)
) &&
(
this.StartPosition == other.StartPosition ||
this.StartPosition != null &&
this.StartPosition.Equals(other.StartPosition)
) &&
(
this.TimeToCall == other.TimeToCall ||
this.TimeToCall != null &&
this.TimeToCall.Equals(other.TimeToCall)
) &&
(
this.TimeToSeat == other.TimeToSeat ||
this.TimeToSeat != null &&
this.TimeToSeat.Equals(other.TimeToSeat)
) &&
(
this.TimeToCancel == other.TimeToCancel ||
this.TimeToCancel != null &&
this.TimeToCancel.Equals(other.TimeToCancel)
);
}
/// <summary>
/// Gets the hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
// credit: http://stackoverflow.com/a/263416/677735
unchecked // Overflow is fine, just wrap
{
int hash = 41;
// Suitable nullity checks etc, of course :)
if (this.Status != null)
hash = hash * 59 + this.Status.GetHashCode();
if (this.Created != null)
hash = hash * 59 + this.Created.GetHashCode();
if (this.GroupSize != null)
hash = hash * 59 + this.GroupSize.GetHashCode();
if (this.StartPosition != null)
hash = hash * 59 + this.StartPosition.GetHashCode();
if (this.TimeToCall != null)
hash = hash * 59 + this.TimeToCall.GetHashCode();
if (this.TimeToSeat != null)
hash = hash * 59 + this.TimeToSeat.GetHashCode();
if (this.TimeToCancel != null)
hash = hash * 59 + this.TimeToCancel.GetHashCode();
return hash;
}
}
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
yield break;
}
}
}
| |
//-------------------------------------------------------------------------------
// <copyright file="IExtension.cs" company="Appccelerate">
// Copyright (c) 2008-2019 Appccelerate
//
// 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.
// </copyright>
//-------------------------------------------------------------------------------
namespace Appccelerate.StateMachine.Machine
{
using System;
using System.Collections.Generic;
using Infrastructure;
using States;
using Transitions;
/// <summary>
/// Extensions for a state machine have to implement this interface.
/// </summary>
/// <typeparam name="TState">The type of the state.</typeparam>
/// <typeparam name="TEvent">The type of the event.</typeparam>
public interface IExtension<TState, TEvent>
where TState : IComparable
where TEvent : IComparable
{
/// <summary>
/// Called after the state machine was started.
/// </summary>
/// <param name="stateMachine">The state machine.</param>
void StartedStateMachine(IStateMachineInformation<TState, TEvent> stateMachine);
/// <summary>
/// Called after the state machine stopped.
/// </summary>
/// <param name="stateMachine">The state machine.</param>
void StoppedStateMachine(IStateMachineInformation<TState, TEvent> stateMachine);
/// <summary>
/// Called after an events was queued.
/// </summary>
/// <param name="stateMachine">The state machine.</param>
/// <param name="eventId">The event id.</param>
/// <param name="eventArgument">The event argument.</param>
void EventQueued(IStateMachineInformation<TState, TEvent> stateMachine, TEvent eventId, object eventArgument);
/// <summary>
/// Called after an events was queued with priority.
/// </summary>
/// <param name="stateMachine">The state machine.</param>
/// <param name="eventId">The event id.</param>
/// <param name="eventArgument">The event argument.</param>
void EventQueuedWithPriority(IStateMachineInformation<TState, TEvent> stateMachine, TEvent eventId, object eventArgument);
/// <summary>
/// Called after the state machine switched states.
/// </summary>
/// <param name="stateMachine">The state machine.</param>
/// <param name="oldState">The old state.</param>
/// <param name="newState">The new state.</param>
void SwitchedState(
IStateMachineInformation<TState, TEvent> stateMachine,
IStateDefinition<TState, TEvent> oldState,
IStateDefinition<TState, TEvent> newState);
/// <summary>
/// Called when the state machine enters the initial state.
/// </summary>
/// <param name="stateMachine">The state machine.</param>
/// <param name="state">The state.</param>
void EnteringInitialState(IStateMachineInformation<TState, TEvent> stateMachine, TState state);
/// <summary>
/// Called when the state machine entered the initial state.
/// </summary>
/// <param name="stateMachine">The state machine.</param>
/// <param name="state">The state.</param>
/// <param name="context">The context.</param>
void EnteredInitialState(IStateMachineInformation<TState, TEvent> stateMachine, TState state, ITransitionContext<TState, TEvent> context);
/// <summary>
/// Called when an event is firing on the state machine.
/// </summary>
/// <param name="stateMachine">The state machine.</param>
/// <param name="eventId">The event id. Can be replaced by the extension.</param>
/// <param name="eventArgument">The event argument. Can be replaced by the extension.</param>
void FiringEvent(
IStateMachineInformation<TState, TEvent> stateMachine,
ref TEvent eventId,
ref object eventArgument);
/// <summary>
/// Called when an event was fired on the state machine.
/// </summary>
/// <param name="stateMachine">The state machine.</param>
/// <param name="context">The transition context.</param>
void FiredEvent(
IStateMachineInformation<TState, TEvent> stateMachine,
ITransitionContext<TState, TEvent> context);
/// <summary>
/// Called before an entry action exception is handled.
/// </summary>
/// <param name="stateMachine">The state machine.</param>
/// <param name="stateDefinition">The state definition.</param>
/// <param name="context">The context.</param>
/// <param name="exception">The exception. Can be replaced by the extension.</param>
void HandlingEntryActionException(
IStateMachineInformation<TState, TEvent> stateMachine,
IStateDefinition<TState, TEvent> stateDefinition,
ITransitionContext<TState, TEvent> context,
ref Exception exception);
/// <summary>
/// Called after an entry action exception was handled.
/// </summary>
/// <param name="stateMachine">The state machine.</param>
/// <param name="stateDefinition">The state definition.</param>
/// <param name="context">The context.</param>
/// <param name="exception">The exception.</param>
void HandledEntryActionException(
IStateMachineInformation<TState, TEvent> stateMachine,
IStateDefinition<TState, TEvent> stateDefinition,
ITransitionContext<TState, TEvent> context,
Exception exception);
/// <summary>
/// Called before an exit action exception is handled.
/// </summary>
/// <param name="stateMachine">The state machine.</param>
/// <param name="stateDefinition">The state definition.</param>
/// <param name="context">The context.</param>
/// <param name="exception">The exception. Can be replaced by the extension.</param>
void HandlingExitActionException(
IStateMachineInformation<TState, TEvent> stateMachine,
IStateDefinition<TState, TEvent> stateDefinition,
ITransitionContext<TState, TEvent> context,
ref Exception exception);
/// <summary>
/// Called after an exit action exception was handled.
/// </summary>
/// <param name="stateMachine">The state machine.</param>
/// <param name="stateDefinition">The state definition.</param>
/// <param name="context">The context.</param>
/// <param name="exception">The exception.</param>
void HandledExitActionException(
IStateMachineInformation<TState, TEvent> stateMachine,
IStateDefinition<TState, TEvent> stateDefinition,
ITransitionContext<TState, TEvent> context,
Exception exception);
/// <summary>
/// Called before a guard exception is handled.
/// </summary>
/// <param name="stateMachine">The state machine.</param>
/// <param name="transitionDefinition">The transition definition.</param>
/// <param name="transitionContext">The transition context.</param>
/// <param name="exception">The exception. Can be replaced by the extension.</param>
void HandlingGuardException(
IStateMachineInformation<TState, TEvent> stateMachine,
ITransitionDefinition<TState, TEvent> transitionDefinition,
ITransitionContext<TState, TEvent> transitionContext,
ref Exception exception);
/// <summary>
/// Called after a guard exception was handled.
/// </summary>
/// <param name="stateMachine">The state machine.</param>
/// <param name="transitionDefinition">The transition definition.</param>
/// <param name="transitionContext">The transition context.</param>
/// <param name="exception">The exception.</param>
void HandledGuardException(
IStateMachineInformation<TState, TEvent> stateMachine,
ITransitionDefinition<TState, TEvent> transitionDefinition,
ITransitionContext<TState, TEvent> transitionContext,
Exception exception);
/// <summary>
/// Called before a transition exception is handled.
/// </summary>
/// <param name="stateMachine">The state machine.</param>
/// <param name="transitionDefinition">The transition definition.</param>
/// <param name="context">The context.</param>
/// <param name="exception">The exception. Can be replaced by the extension.</param>
void HandlingTransitionException(
IStateMachineInformation<TState, TEvent> stateMachine,
ITransitionDefinition<TState, TEvent> transitionDefinition,
ITransitionContext<TState, TEvent> context,
ref Exception exception);
/// <summary>
/// Called after a transition exception is handled.
/// </summary>
/// <param name="stateMachine">The state machine.</param>
/// <param name="transitionDefinition">The transition definition.</param>
/// <param name="transitionContext">The transition context.</param>
/// <param name="exception">The exception.</param>
void HandledTransitionException(
IStateMachineInformation<TState, TEvent> stateMachine,
ITransitionDefinition<TState, TEvent> transitionDefinition,
ITransitionContext<TState, TEvent> transitionContext,
Exception exception);
/// <summary>
/// Called when a guard of a transition returns false and therefore the transition is not executed.
/// </summary>
/// <param name="stateMachineInformation">The state machine.</param>
/// <param name="transitionDefinition">The transition definition.</param>
/// <param name="context">The transition context.</param>
void SkippedTransition(
IStateMachineInformation<TState, TEvent> stateMachineInformation,
ITransitionDefinition<TState, TEvent> transitionDefinition,
ITransitionContext<TState, TEvent> context);
/// <summary>
/// Called when a transition is going to be executed. After the guard of the transition evaluated to true.
/// </summary>
/// <param name="stateMachineInformation">The state machine.</param>
/// <param name="transitionDefinition">The transition definition.</param>
/// <param name="context">The transition context.</param>
void ExecutingTransition(
IStateMachineInformation<TState, TEvent> stateMachineInformation,
ITransitionDefinition<TState, TEvent> transitionDefinition,
ITransitionContext<TState, TEvent> context);
/// <summary>
/// Called when a transition was executed.
/// </summary>
/// <param name="stateMachineInformation">The state machine.</param>
/// <param name="transitionDefinition">The transition definition.</param>
/// <param name="context">The transition context.</param>
void ExecutedTransition(
IStateMachineInformation<TState, TEvent> stateMachineInformation,
ITransitionDefinition<TState, TEvent> transitionDefinition,
ITransitionContext<TState, TEvent> context);
void EnteringState(
IStateMachineInformation<TState, TEvent> stateMachine,
IStateDefinition<TState, TEvent> state,
ITransitionContext<TState, TEvent> context);
void Loaded(
IStateMachineInformation<TState, TEvent> stateMachineInformation,
IInitializable<TState> loadedCurrentState,
IReadOnlyDictionary<TState, TState> loadedHistoryStates,
IReadOnlyCollection<EventInformation<TEvent>> events);
}
}
| |
/*
* 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.Unmanaged
{
using System;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.InteropServices;
using Apache.Ignite.Core.Common;
using JNI = IgniteJniNativeMethods;
/// <summary>
/// Unmanaged utility classes.
/// </summary>
internal static unsafe class UnmanagedUtils
{
/** Interop factory ID for .Net. */
private const int InteropFactoryId = 1;
/// <summary>
/// Initializer.
/// </summary>
[SuppressMessage("Microsoft.Design", "CA1065:DoNotRaiseExceptionsInUnexpectedLocations")]
static UnmanagedUtils()
{
var platfrom = Environment.Is64BitProcess ? "x64" : "x86";
var resName = string.Format("{0}.{1}", platfrom, IgniteUtils.FileIgniteJniDll);
var path = IgniteUtils.UnpackEmbeddedResource(resName, IgniteUtils.FileIgniteJniDll);
var ptr = NativeMethods.LoadLibrary(path);
if (ptr == IntPtr.Zero)
throw new IgniteException(string.Format("Failed to load {0}: {1}",
IgniteUtils.FileIgniteJniDll, Marshal.GetLastWin32Error()));
}
/// <summary>
/// No-op initializer used to force type loading and static constructor call.
/// </summary>
internal static void Initialize()
{
// No-op.
}
#region NATIVE METHODS: PROCESSOR
internal static void IgnitionStart(UnmanagedContext ctx, string cfgPath, string gridName,
bool clientMode)
{
using (var mem = IgniteManager.Memory.Allocate().GetStream())
{
mem.WriteBool(clientMode);
sbyte* cfgPath0 = IgniteUtils.StringToUtf8Unmanaged(cfgPath);
sbyte* gridName0 = IgniteUtils.StringToUtf8Unmanaged(gridName);
try
{
// OnStart receives the same InteropProcessor as here (just as another GlobalRef) and stores it.
// Release current reference immediately.
void* res = JNI.IgnitionStart(ctx.NativeContext, cfgPath0, gridName0, InteropFactoryId,
mem.SynchronizeOutput());
JNI.Release(res);
}
finally
{
Marshal.FreeHGlobal(new IntPtr(cfgPath0));
Marshal.FreeHGlobal(new IntPtr(gridName0));
}
}
}
internal static bool IgnitionStop(void* ctx, string gridName, bool cancel)
{
sbyte* gridName0 = IgniteUtils.StringToUtf8Unmanaged(gridName);
try
{
return JNI.IgnitionStop(ctx, gridName0, cancel);
}
finally
{
Marshal.FreeHGlobal(new IntPtr(gridName0));
}
}
internal static void IgnitionStopAll(void* ctx, bool cancel)
{
JNI.IgnitionStopAll(ctx, cancel);
}
internal static void ProcessorReleaseStart(IUnmanagedTarget target)
{
JNI.ProcessorReleaseStart(target.Context, target.Target);
}
internal static IUnmanagedTarget ProcessorProjection(IUnmanagedTarget target)
{
void* res = JNI.ProcessorProjection(target.Context, target.Target);
return target.ChangeTarget(res);
}
internal static IUnmanagedTarget ProcessorCache(IUnmanagedTarget target, string name)
{
sbyte* name0 = IgniteUtils.StringToUtf8Unmanaged(name);
try
{
void* res = JNI.ProcessorCache(target.Context, target.Target, name0);
return target.ChangeTarget(res);
}
finally
{
Marshal.FreeHGlobal(new IntPtr(name0));
}
}
internal static IUnmanagedTarget ProcessorCreateCache(IUnmanagedTarget target, string name)
{
sbyte* name0 = IgniteUtils.StringToUtf8Unmanaged(name);
try
{
void* res = JNI.ProcessorCreateCache(target.Context, target.Target, name0);
return target.ChangeTarget(res);
}
finally
{
Marshal.FreeHGlobal(new IntPtr(name0));
}
}
internal static IUnmanagedTarget ProcessorCreateCache(IUnmanagedTarget target, long memPtr)
{
void* res = JNI.ProcessorCreateCacheFromConfig(target.Context, target.Target, memPtr);
return target.ChangeTarget(res);
}
internal static IUnmanagedTarget ProcessorGetOrCreateCache(IUnmanagedTarget target, string name)
{
sbyte* name0 = IgniteUtils.StringToUtf8Unmanaged(name);
try
{
void* res = JNI.ProcessorGetOrCreateCache(target.Context, target.Target, name0);
return target.ChangeTarget(res);
}
finally
{
Marshal.FreeHGlobal(new IntPtr(name0));
}
}
internal static IUnmanagedTarget ProcessorGetOrCreateCache(IUnmanagedTarget target, long memPtr)
{
void* res = JNI.ProcessorGetOrCreateCacheFromConfig(target.Context, target.Target, memPtr);
return target.ChangeTarget(res);
}
internal static IUnmanagedTarget ProcessorCreateNearCache(IUnmanagedTarget target, string name, long memPtr)
{
sbyte* name0 = IgniteUtils.StringToUtf8Unmanaged(name);
try
{
void* res = JNI.ProcessorCreateNearCache(target.Context, target.Target, name0, memPtr);
return target.ChangeTarget(res);
}
finally
{
Marshal.FreeHGlobal(new IntPtr(name0));
}
}
internal static IUnmanagedTarget ProcessorGetOrCreateNearCache(IUnmanagedTarget target, string name, long memPtr)
{
sbyte* name0 = IgniteUtils.StringToUtf8Unmanaged(name);
try
{
void* res = JNI.ProcessorGetOrCreateNearCache(target.Context, target.Target, name0, memPtr);
return target.ChangeTarget(res);
}
finally
{
Marshal.FreeHGlobal(new IntPtr(name0));
}
}
internal static void ProcessorDestroyCache(IUnmanagedTarget target, string name)
{
sbyte* name0 = IgniteUtils.StringToUtf8Unmanaged(name);
try
{
JNI.ProcessorDestroyCache(target.Context, target.Target, name0);
}
finally
{
Marshal.FreeHGlobal(new IntPtr(name0));
}
}
internal static IUnmanagedTarget ProcessorAffinity(IUnmanagedTarget target, string name)
{
sbyte* name0 = IgniteUtils.StringToUtf8Unmanaged(name);
try
{
void* res = JNI.ProcessorAffinity(target.Context, target.Target, name0);
return target.ChangeTarget(res);
}
finally
{
Marshal.FreeHGlobal(new IntPtr(name0));
}
}
internal static IUnmanagedTarget ProcessorDataStreamer(IUnmanagedTarget target, string name, bool keepBinary)
{
sbyte* name0 = IgniteUtils.StringToUtf8Unmanaged(name);
try
{
void* res = JNI.ProcessorDataStreamer(target.Context, target.Target, name0, keepBinary);
return target.ChangeTarget(res);
}
finally
{
Marshal.FreeHGlobal(new IntPtr(name0));
}
}
internal static IUnmanagedTarget ProcessorTransactions(IUnmanagedTarget target)
{
void* res = JNI.ProcessorTransactions(target.Context, target.Target);
return target.ChangeTarget(res);
}
internal static IUnmanagedTarget ProcessorCompute(IUnmanagedTarget target, IUnmanagedTarget prj)
{
void* res = JNI.ProcessorCompute(target.Context, target.Target, prj.Target);
return target.ChangeTarget(res);
}
internal static IUnmanagedTarget ProcessorMessage(IUnmanagedTarget target, IUnmanagedTarget prj)
{
void* res = JNI.ProcessorMessage(target.Context, target.Target, prj.Target);
return target.ChangeTarget(res);
}
internal static IUnmanagedTarget ProcessorEvents(IUnmanagedTarget target, IUnmanagedTarget prj)
{
void* res = JNI.ProcessorEvents(target.Context, target.Target, prj.Target);
return target.ChangeTarget(res);
}
internal static IUnmanagedTarget ProcessorServices(IUnmanagedTarget target, IUnmanagedTarget prj)
{
void* res = JNI.ProcessorServices(target.Context, target.Target, prj.Target);
return target.ChangeTarget(res);
}
internal static IUnmanagedTarget ProcessorExtensions(IUnmanagedTarget target)
{
void* res = JNI.ProcessorExtensions(target.Context, target.Target);
return target.ChangeTarget(res);
}
internal static IUnmanagedTarget ProcessorAtomicLong(IUnmanagedTarget target, string name, long initialValue,
bool create)
{
var name0 = IgniteUtils.StringToUtf8Unmanaged(name);
try
{
var res = JNI.ProcessorAtomicLong(target.Context, target.Target, name0, initialValue, create);
return res == null ? null : target.ChangeTarget(res);
}
finally
{
Marshal.FreeHGlobal(new IntPtr(name0));
}
}
internal static IUnmanagedTarget ProcessorAtomicSequence(IUnmanagedTarget target, string name, long initialValue,
bool create)
{
var name0 = IgniteUtils.StringToUtf8Unmanaged(name);
try
{
var res = JNI.ProcessorAtomicSequence(target.Context, target.Target, name0, initialValue, create);
return res == null ? null : target.ChangeTarget(res);
}
finally
{
Marshal.FreeHGlobal(new IntPtr(name0));
}
}
internal static IUnmanagedTarget ProcessorAtomicReference(IUnmanagedTarget target, string name, long memPtr,
bool create)
{
var name0 = IgniteUtils.StringToUtf8Unmanaged(name);
try
{
var res = JNI.ProcessorAtomicReference(target.Context, target.Target, name0, memPtr, create);
return res == null ? null : target.ChangeTarget(res);
}
finally
{
Marshal.FreeHGlobal(new IntPtr(name0));
}
}
internal static void ProcessorGetIgniteConfiguration(IUnmanagedTarget target, long memPtr)
{
JNI.ProcessorGetIgniteConfiguration(target.Context, target.Target, memPtr);
}
internal static void ProcessorGetCacheNames(IUnmanagedTarget target, long memPtr)
{
JNI.ProcessorGetCacheNames(target.Context, target.Target, memPtr);
}
#endregion
#region NATIVE METHODS: TARGET
internal static long TargetInStreamOutLong(IUnmanagedTarget target, int opType, long memPtr)
{
return JNI.TargetInStreamOutLong(target.Context, target.Target, opType, memPtr);
}
internal static void TargetInStreamOutStream(IUnmanagedTarget target, int opType, long inMemPtr, long outMemPtr)
{
JNI.TargetInStreamOutStream(target.Context, target.Target, opType, inMemPtr, outMemPtr);
}
internal static IUnmanagedTarget TargetInStreamOutObject(IUnmanagedTarget target, int opType, long inMemPtr)
{
void* res = JNI.TargetInStreanOutObject(target.Context, target.Target, opType, inMemPtr);
return target.ChangeTarget(res);
}
internal static void TargetInObjectStreamOutStream(IUnmanagedTarget target, int opType, void* arg, long inMemPtr, long outMemPtr)
{
JNI.TargetInObjectStreamOutStream(target.Context, target.Target, opType, arg, inMemPtr, outMemPtr);
}
internal static long TargetOutLong(IUnmanagedTarget target, int opType)
{
return JNI.TargetOutLong(target.Context, target.Target, opType);
}
internal static void TargetOutStream(IUnmanagedTarget target, int opType, long memPtr)
{
JNI.TargetOutStream(target.Context, target.Target, opType, memPtr);
}
internal static IUnmanagedTarget TargetOutObject(IUnmanagedTarget target, int opType)
{
void* res = JNI.TargetOutObject(target.Context, target.Target, opType);
return target.ChangeTarget(res);
}
internal static void TargetListenFuture(IUnmanagedTarget target, long futId, int typ)
{
JNI.TargetListenFut(target.Context, target.Target, futId, typ);
}
internal static void TargetListenFutureForOperation(IUnmanagedTarget target, long futId, int typ, int opId)
{
JNI.TargetListenFutForOp(target.Context, target.Target, futId, typ, opId);
}
internal static IUnmanagedTarget TargetListenFutureAndGet(IUnmanagedTarget target, long futId, int typ)
{
var res = JNI.TargetListenFutAndGet(target.Context, target.Target, futId, typ);
return target.ChangeTarget(res);
}
internal static IUnmanagedTarget TargetListenFutureForOperationAndGet(IUnmanagedTarget target, long futId,
int typ, int opId)
{
var res = JNI.TargetListenFutForOpAndGet(target.Context, target.Target, futId, typ, opId);
return target.ChangeTarget(res);
}
#endregion
#region NATIVE METHODS: AFFINITY
internal static int AffinityPartitions(IUnmanagedTarget target)
{
return JNI.AffinityParts(target.Context, target.Target);
}
#endregion
#region NATIVE METHODS: CACHE
internal static IUnmanagedTarget CacheWithSkipStore(IUnmanagedTarget target)
{
void* res = JNI.CacheWithSkipStore(target.Context, target.Target);
return target.ChangeTarget(res);
}
internal static IUnmanagedTarget CacheWithNoRetries(IUnmanagedTarget target)
{
void* res = JNI.CacheWithNoRetries(target.Context, target.Target);
return target.ChangeTarget(res);
}
internal static IUnmanagedTarget CacheWithExpiryPolicy(IUnmanagedTarget target, long create, long update, long access)
{
void* res = JNI.CacheWithExpiryPolicy(target.Context, target.Target, create, update, access);
return target.ChangeTarget(res);
}
internal static IUnmanagedTarget CacheWithAsync(IUnmanagedTarget target)
{
void* res = JNI.CacheWithAsync(target.Context, target.Target);
return target.ChangeTarget(res);
}
internal static IUnmanagedTarget CacheWithKeepBinary(IUnmanagedTarget target)
{
void* res = JNI.CacheWithKeepBinary(target.Context, target.Target);
return target.ChangeTarget(res);
}
internal static void CacheClear(IUnmanagedTarget target)
{
JNI.CacheClear(target.Context, target.Target);
}
internal static void CacheRemoveAll(IUnmanagedTarget target)
{
JNI.CacheRemoveAll(target.Context, target.Target);
}
internal static IUnmanagedTarget CacheOutOpQueryCursor(IUnmanagedTarget target, int type, long memPtr)
{
void* res = JNI.CacheOutOpQueryCursor(target.Context, target.Target, type, memPtr);
return target.ChangeTarget(res);
}
internal static IUnmanagedTarget CacheOutOpContinuousQuery(IUnmanagedTarget target, int type, long memPtr)
{
void* res = JNI.CacheOutOpContinuousQuery(target.Context, target.Target, type, memPtr);
return target.ChangeTarget(res);
}
internal static IUnmanagedTarget CacheIterator(IUnmanagedTarget target)
{
void* res = JNI.CacheIterator(target.Context, target.Target);
return target.ChangeTarget(res);
}
internal static IUnmanagedTarget CacheLocalIterator(IUnmanagedTarget target, int peekModes)
{
void* res = JNI.CacheLocalIterator(target.Context, target.Target, peekModes);
return target.ChangeTarget(res);
}
internal static void CacheEnterLock(IUnmanagedTarget target, long id)
{
JNI.CacheEnterLock(target.Context, target.Target, id);
}
internal static void CacheExitLock(IUnmanagedTarget target, long id)
{
JNI.CacheExitLock(target.Context, target.Target, id);
}
internal static bool CacheTryEnterLock(IUnmanagedTarget target, long id, long timeout)
{
return JNI.CacheTryEnterLock(target.Context, target.Target, id, timeout);
}
internal static void CacheCloseLock(IUnmanagedTarget target, long id)
{
JNI.CacheCloseLock(target.Context, target.Target, id);
}
internal static void CacheRebalance(IUnmanagedTarget target, long futId)
{
JNI.CacheRebalance(target.Context, target.Target, futId);
}
internal static void CacheStoreCallbackInvoke(IUnmanagedTarget target, long memPtr)
{
JNI.CacheStoreCallbackInvoke(target.Context, target.Target, memPtr);
}
internal static int CacheSize(IUnmanagedTarget target, int modes, bool loc)
{
return JNI.CacheSize(target.Context, target.Target, modes, loc);
}
#endregion
#region NATIVE METHODS: COMPUTE
internal static void ComputeWithNoFailover(IUnmanagedTarget target)
{
JNI.ComputeWithNoFailover(target.Context, target.Target);
}
internal static void ComputeWithTimeout(IUnmanagedTarget target, long timeout)
{
JNI.ComputeWithTimeout(target.Context, target.Target, timeout);
}
internal static IUnmanagedTarget ComputeExecuteNative(IUnmanagedTarget target, long taskPtr, long topVer)
{
void* res = JNI.ComputeExecuteNative(target.Context, target.Target, taskPtr, topVer);
return target.ChangeTarget(res);
}
#endregion
#region NATIVE METHODS: CONTINUOUS QUERY
internal static void ContinuousQueryClose(IUnmanagedTarget target)
{
JNI.ContinuousQryClose(target.Context, target.Target);
}
internal static IUnmanagedTarget ContinuousQueryGetInitialQueryCursor(IUnmanagedTarget target)
{
void* res = JNI.ContinuousQryGetInitialQueryCursor(target.Context, target.Target);
return res == null ? null : target.ChangeTarget(res);
}
#endregion
#region NATIVE METHODS: DATA STREAMER
internal static void DataStreamerListenTopology(IUnmanagedTarget target, long ptr)
{
JNI.DataStreamerListenTop(target.Context, target.Target, ptr);
}
internal static bool DataStreamerAllowOverwriteGet(IUnmanagedTarget target)
{
return JNI.DataStreamerAllowOverwriteGet(target.Context, target.Target);
}
internal static void DataStreamerAllowOverwriteSet(IUnmanagedTarget target, bool val)
{
JNI.DataStreamerAllowOverwriteSet(target.Context, target.Target, val);
}
internal static bool DataStreamerSkipStoreGet(IUnmanagedTarget target)
{
return JNI.DataStreamerSkipStoreGet(target.Context, target.Target);
}
internal static void DataStreamerSkipStoreSet(IUnmanagedTarget target, bool val)
{
JNI.DataStreamerSkipStoreSet(target.Context, target.Target, val);
}
internal static int DataStreamerPerNodeBufferSizeGet(IUnmanagedTarget target)
{
return JNI.DataStreamerPerNodeBufferSizeGet(target.Context, target.Target);
}
internal static void DataStreamerPerNodeBufferSizeSet(IUnmanagedTarget target, int val)
{
JNI.DataStreamerPerNodeBufferSizeSet(target.Context, target.Target, val);
}
internal static int DataStreamerPerNodeParallelOperationsGet(IUnmanagedTarget target)
{
return JNI.DataStreamerPerNodeParallelOpsGet(target.Context, target.Target);
}
internal static void DataStreamerPerNodeParallelOperationsSet(IUnmanagedTarget target, int val)
{
JNI.DataStreamerPerNodeParallelOpsSet(target.Context, target.Target, val);
}
#endregion
#region NATIVE METHODS: MESSAGING
internal static IUnmanagedTarget MessagingWithASync(IUnmanagedTarget target)
{
void* res = JNI.MessagingWithAsync(target.Context, target.Target);
return target.ChangeTarget(res);
}
#endregion
#region NATIVE METHODS: PROJECTION
internal static IUnmanagedTarget ProjectionForOthers(IUnmanagedTarget target, IUnmanagedTarget prj)
{
void* res = JNI.ProjectionForOthers(target.Context, target.Target, prj.Target);
return target.ChangeTarget(res);
}
internal static IUnmanagedTarget ProjectionForRemotes(IUnmanagedTarget target)
{
void* res = JNI.ProjectionForRemotes(target.Context, target.Target);
return target.ChangeTarget(res);
}
internal static IUnmanagedTarget ProjectionForDaemons(IUnmanagedTarget target)
{
void* res = JNI.ProjectionForDaemons(target.Context, target.Target);
return target.ChangeTarget(res);
}
internal static IUnmanagedTarget ProjectionForRandom(IUnmanagedTarget target)
{
void* res = JNI.ProjectionForRandom(target.Context, target.Target);
return target.ChangeTarget(res);
}
internal static IUnmanagedTarget ProjectionForOldest(IUnmanagedTarget target)
{
void* res = JNI.ProjectionForOldest(target.Context, target.Target);
return target.ChangeTarget(res);
}
internal static IUnmanagedTarget ProjectionForYoungest(IUnmanagedTarget target)
{
void* res = JNI.ProjectionForYoungest(target.Context, target.Target);
return target.ChangeTarget(res);
}
internal static IUnmanagedTarget ProjectionForServers(IUnmanagedTarget target)
{
void* res = JNI.ProjectionForServers(target.Context, target.Target);
return target.ChangeTarget(res);
}
internal static void ProjectionResetMetrics(IUnmanagedTarget target)
{
JNI.ProjectionResetMetrics(target.Context, target.Target);
}
internal static IUnmanagedTarget ProjectionOutOpRet(IUnmanagedTarget target, int type, long memPtr)
{
void* res = JNI.ProjectionOutOpRet(target.Context, target.Target, type, memPtr);
return target.ChangeTarget(res);
}
#endregion
#region NATIVE METHODS: QUERY CURSOR
internal static void QueryCursorIterator(IUnmanagedTarget target)
{
JNI.QryCursorIterator(target.Context, target.Target);
}
internal static void QueryCursorClose(IUnmanagedTarget target)
{
JNI.QryCursorClose(target.Context, target.Target);
}
#endregion
#region NATIVE METHODS: TRANSACTIONS
internal static long TransactionsStart(IUnmanagedTarget target, int concurrency, int isolation, long timeout, int txSize)
{
return JNI.TxStart(target.Context, target.Target, concurrency, isolation, timeout, txSize);
}
internal static int TransactionsCommit(IUnmanagedTarget target, long id)
{
return JNI.TxCommit(target.Context, target.Target, id);
}
internal static void TransactionsCommitAsync(IUnmanagedTarget target, long id, long futId)
{
JNI.TxCommitAsync(target.Context, target.Target, id, futId);
}
internal static int TransactionsRollback(IUnmanagedTarget target, long id)
{
return JNI.TxRollback(target.Context, target.Target, id);
}
internal static void TransactionsRollbackAsync(IUnmanagedTarget target, long id, long futId)
{
JNI.TxRollbackAsync(target.Context, target.Target, id, futId);
}
internal static int TransactionsClose(IUnmanagedTarget target, long id)
{
return JNI.TxClose(target.Context, target.Target, id);
}
internal static int TransactionsState(IUnmanagedTarget target, long id)
{
return JNI.TxState(target.Context, target.Target, id);
}
internal static bool TransactionsSetRollbackOnly(IUnmanagedTarget target, long id)
{
return JNI.TxSetRollbackOnly(target.Context, target.Target, id);
}
internal static void TransactionsResetMetrics(IUnmanagedTarget target)
{
JNI.TxResetMetrics(target.Context, target.Target);
}
#endregion
#region NATIVE METHODS: MISCELANNEOUS
internal static void Reallocate(long memPtr, int cap)
{
int res = JNI.Reallocate(memPtr, cap);
if (res != 0)
throw new IgniteException("Failed to reallocate external memory [ptr=" + memPtr +
", capacity=" + cap + ']');
}
internal static IUnmanagedTarget Acquire(UnmanagedContext ctx, void* target)
{
void* target0 = JNI.Acquire(ctx.NativeContext, target);
return new UnmanagedTarget(ctx, target0);
}
internal static void Release(IUnmanagedTarget target)
{
JNI.Release(target.Target);
}
internal static void ThrowToJava(void* ctx, Exception e)
{
char* msgChars = (char*)IgniteUtils.StringToUtf8Unmanaged(e.Message);
try
{
JNI.ThrowToJava(ctx, msgChars);
}
finally
{
Marshal.FreeHGlobal(new IntPtr(msgChars));
}
}
internal static int HandlersSize()
{
return JNI.HandlersSize();
}
internal static void* CreateContext(void* opts, int optsLen, void* cbs)
{
return JNI.CreateContext(opts, optsLen, cbs);
}
internal static void DeleteContext(void* ctx)
{
JNI.DeleteContext(ctx);
}
internal static void DestroyJvm(void* ctx)
{
JNI.DestroyJvm(ctx);
}
#endregion
#region NATIVE METHODS: EVENTS
internal static IUnmanagedTarget EventsWithAsync(IUnmanagedTarget target)
{
return target.ChangeTarget(JNI.EventsWithAsync(target.Context, target.Target));
}
internal static bool EventsStopLocalListen(IUnmanagedTarget target, long handle)
{
return JNI.EventsStopLocalListen(target.Context, target.Target, handle);
}
internal static bool EventsIsEnabled(IUnmanagedTarget target, int type)
{
return JNI.EventsIsEnabled(target.Context, target.Target, type);
}
internal static void EventsLocalListen(IUnmanagedTarget target, long handle, int type)
{
JNI.EventsLocalListen(target.Context, target.Target, handle, type);
}
#endregion
#region NATIVE METHODS: SERVICES
internal static IUnmanagedTarget ServicesWithAsync(IUnmanagedTarget target)
{
return target.ChangeTarget(JNI.ServicesWithAsync(target.Context, target.Target));
}
internal static IUnmanagedTarget ServicesWithServerKeepBinary(IUnmanagedTarget target)
{
return target.ChangeTarget(JNI.ServicesWithServerKeepBinary(target.Context, target.Target));
}
internal static void ServicesCancel(IUnmanagedTarget target, string name)
{
var nameChars = (char*)IgniteUtils.StringToUtf8Unmanaged(name);
try
{
JNI.ServicesCancel(target.Context, target.Target, nameChars);
}
finally
{
Marshal.FreeHGlobal(new IntPtr(nameChars));
}
}
internal static void ServicesCancelAll(IUnmanagedTarget target)
{
JNI.ServicesCancelAll(target.Context, target.Target);
}
internal static IUnmanagedTarget ServicesGetServiceProxy(IUnmanagedTarget target, string name, bool sticky)
{
var nameChars = (char*)IgniteUtils.StringToUtf8Unmanaged(name);
try
{
return target.ChangeTarget(JNI.ServicesGetServiceProxy(target.Context, target.Target, nameChars, sticky));
}
finally
{
Marshal.FreeHGlobal(new IntPtr(nameChars));
}
}
#endregion
#region NATIVE METHODS: DATA STRUCTURES
internal static long AtomicLongGet(IUnmanagedTarget target)
{
return JNI.AtomicLongGet(target.Context, target.Target);
}
internal static long AtomicLongIncrementAndGet(IUnmanagedTarget target)
{
return JNI.AtomicLongIncrementAndGet(target.Context, target.Target);
}
internal static long AtomicLongAddAndGet(IUnmanagedTarget target, long value)
{
return JNI.AtomicLongAddAndGet(target.Context, target.Target, value);
}
internal static long AtomicLongDecrementAndGet(IUnmanagedTarget target)
{
return JNI.AtomicLongDecrementAndGet(target.Context, target.Target);
}
internal static long AtomicLongGetAndSet(IUnmanagedTarget target, long value)
{
return JNI.AtomicLongGetAndSet(target.Context, target.Target, value);
}
internal static long AtomicLongCompareAndSetAndGet(IUnmanagedTarget target, long expVal, long newVal)
{
return JNI.AtomicLongCompareAndSetAndGet(target.Context, target.Target, expVal, newVal);
}
internal static bool AtomicLongIsClosed(IUnmanagedTarget target)
{
return JNI.AtomicLongIsClosed(target.Context, target.Target);
}
internal static void AtomicLongClose(IUnmanagedTarget target)
{
JNI.AtomicLongClose(target.Context, target.Target);
}
internal static long AtomicSequenceGet(IUnmanagedTarget target)
{
return JNI.AtomicSequenceGet(target.Context, target.Target);
}
internal static long AtomicSequenceIncrementAndGet(IUnmanagedTarget target)
{
return JNI.AtomicSequenceIncrementAndGet(target.Context, target.Target);
}
internal static long AtomicSequenceAddAndGet(IUnmanagedTarget target, long value)
{
return JNI.AtomicSequenceAddAndGet(target.Context, target.Target, value);
}
internal static int AtomicSequenceGetBatchSize(IUnmanagedTarget target)
{
return JNI.AtomicSequenceGetBatchSize(target.Context, target.Target);
}
internal static void AtomicSequenceSetBatchSize(IUnmanagedTarget target, int size)
{
JNI.AtomicSequenceSetBatchSize(target.Context, target.Target, size);
}
internal static bool AtomicSequenceIsClosed(IUnmanagedTarget target)
{
return JNI.AtomicSequenceIsClosed(target.Context, target.Target);
}
internal static void AtomicSequenceClose(IUnmanagedTarget target)
{
JNI.AtomicSequenceClose(target.Context, target.Target);
}
internal static bool AtomicReferenceIsClosed(IUnmanagedTarget target)
{
return JNI.AtomicReferenceIsClosed(target.Context, target.Target);
}
internal static void AtomicReferenceClose(IUnmanagedTarget target)
{
JNI.AtomicReferenceClose(target.Context, target.Target);
}
internal static bool ListenableCancel(IUnmanagedTarget target)
{
return JNI.ListenableCancel(target.Context, target.Target);
}
internal static bool ListenableIsCancelled(IUnmanagedTarget target)
{
return JNI.ListenableIsCancelled(target.Context, target.Target);
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Web.Http;
using System.Web.Http.Controllers;
using System.Web.Http.Description;
using LearningAzure.Areas.HelpPage.ModelDescriptions;
using LearningAzure.Areas.HelpPage.Models;
namespace LearningAzure.Areas.HelpPage
{
public static class HelpPageConfigurationExtensions
{
private const string ApiModelPrefix = "MS_HelpPageApiModel_";
/// <summary>
/// Sets the documentation provider for help page.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="documentationProvider">The documentation provider.</param>
public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider)
{
config.Services.Replace(typeof(IDocumentationProvider), documentationProvider);
}
/// <summary>
/// Sets the objects that will be used by the formatters to produce sample requests/responses.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleObjects">The sample objects.</param>
public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects)
{
config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects;
}
/// <summary>
/// Sets the sample request directly for the specified media type and action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type and action with parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type of the action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample response directly for the specified media type of the action with specific parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified type and media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="type">The parameter type or return type of an action.</param>
public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Gets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <returns>The help page sample generator.</returns>
public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config)
{
return (HelpPageSampleGenerator)config.Properties.GetOrAdd(
typeof(HelpPageSampleGenerator),
k => new HelpPageSampleGenerator());
}
/// <summary>
/// Sets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleGenerator">The help page sample generator.</param>
public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator)
{
config.Properties.AddOrUpdate(
typeof(HelpPageSampleGenerator),
k => sampleGenerator,
(k, o) => sampleGenerator);
}
/// <summary>
/// Gets the model description generator.
/// </summary>
/// <param name="config">The configuration.</param>
/// <returns>The <see cref="ModelDescriptionGenerator"/></returns>
public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config)
{
return (ModelDescriptionGenerator)config.Properties.GetOrAdd(
typeof(ModelDescriptionGenerator),
k => InitializeModelDescriptionGenerator(config));
}
/// <summary>
/// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param>
/// <returns>
/// An <see cref="HelpPageApiModel"/>
/// </returns>
public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId)
{
object model;
string modelId = ApiModelPrefix + apiDescriptionId;
if (!config.Properties.TryGetValue(modelId, out model))
{
Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions;
ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase));
if (apiDescription != null)
{
model = GenerateApiModel(apiDescription, config);
config.Properties.TryAdd(modelId, model);
}
}
return (HelpPageApiModel)model;
}
private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config)
{
HelpPageApiModel apiModel = new HelpPageApiModel()
{
ApiDescription = apiDescription,
};
ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator();
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
GenerateUriParameters(apiModel, modelGenerator);
GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator);
GenerateResourceDescription(apiModel, modelGenerator);
GenerateSamples(apiModel, sampleGenerator);
return apiModel;
}
private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromUri)
{
HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor;
Type parameterType = null;
ModelDescription typeDescription = null;
ComplexTypeModelDescription complexTypeDescription = null;
if (parameterDescriptor != null)
{
parameterType = parameterDescriptor.ParameterType;
typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
complexTypeDescription = typeDescription as ComplexTypeModelDescription;
}
if (complexTypeDescription != null)
{
foreach (ParameterDescription uriParameter in complexTypeDescription.Properties)
{
apiModel.UriParameters.Add(uriParameter);
}
}
else if (parameterDescriptor != null)
{
ParameterDescription uriParameter =
AddParameterDescription(apiModel, apiParameter, typeDescription);
if (!parameterDescriptor.IsOptional)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" });
}
object defaultValue = parameterDescriptor.DefaultValue;
if (defaultValue != null)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) });
}
}
else
{
Debug.Assert(parameterDescriptor == null);
// If parameterDescriptor is null, this is an undeclared route parameter which only occurs
// when source is FromUri. Ignored in request model and among resource parameters but listed
// as a simple string here.
ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string));
AddParameterDescription(apiModel, apiParameter, modelDescription);
}
}
}
}
private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel,
ApiParameterDescription apiParameter, ModelDescription typeDescription)
{
ParameterDescription parameterDescription = new ParameterDescription
{
Name = apiParameter.Name,
Documentation = apiParameter.Documentation,
TypeDescription = typeDescription,
};
apiModel.UriParameters.Add(parameterDescription);
return parameterDescription;
}
private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromBody)
{
Type parameterType = apiParameter.ParameterDescriptor.ParameterType;
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
apiModel.RequestDocumentation = apiParameter.Documentation;
}
else if (apiParameter.ParameterDescriptor != null &&
apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))
{
Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
if (parameterType != null)
{
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
}
}
private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ResponseDescription response = apiModel.ApiDescription.ResponseDescription;
Type responseType = response.ResponseType ?? response.DeclaredType;
if (responseType != null && responseType != typeof(void))
{
apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType);
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")]
private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator)
{
try
{
foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription))
{
apiModel.SampleRequests.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription))
{
apiModel.SampleResponses.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
}
catch (Exception e)
{
apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture,
"An exception has occurred while generating the sample. Exception message: {0}",
HelpPageSampleGenerator.UnwrapException(e).Message));
}
}
private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType)
{
parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault(
p => p.Source == ApiParameterSource.FromBody ||
(p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)));
if (parameterDescription == null)
{
resourceType = null;
return false;
}
resourceType = parameterDescription.ParameterDescriptor.ParameterType;
if (resourceType == typeof(HttpRequestMessage))
{
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
}
if (resourceType == null)
{
parameterDescription = null;
return false;
}
return true;
}
private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config)
{
ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config);
Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions;
foreach (ApiDescription api in apis)
{
ApiParameterDescription parameterDescription;
Type parameterType;
if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType))
{
modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
return modelGenerator;
}
private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample)
{
InvalidSample invalidSample = sample as InvalidSample;
if (invalidSample != null)
{
apiModel.ErrorMessages.Add(invalidSample.ErrorMessage);
}
}
}
}
| |
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="Login.cs" company="The Watcher">
// Copyright (c) The Watcher Partial Rights Reserved.
// // This software is licensed under the MIT license. See license.txt for details.
// </copyright>
// <summary>
// Code Named: VG-Ripper
// Function : Extracts Images posted on RiP forums and attempts to fetch them to disk.
// </summary>
// --------------------------------------------------------------------------------------------------------------------
namespace Ripper
{
using System;
using System.Diagnostics;
using System.Drawing;
using System.Reflection;
using System.Resources;
using System.Windows.Forms;
using Ripper.Core.Components;
/// <summary>
/// The Login Dialog
/// </summary>
public partial class Login : Form
{
/// <summary>
/// Initializes a new instance of the <see cref="Login"/> class.
/// </summary>
public Login()
{
this.InitializeComponent();
}
/// <summary>
/// Gets or sets the Resource Manager
/// </summary>
private ResourceManager _ResourceManager { get; set; }
/// <summary>
/// Set Language Strings
/// </summary>
private void AdjustCulture()
{
this.groupBox1.Text = this._ResourceManager.GetString("gbLoginHead");
this.groupBox2.Text = this._ResourceManager.GetString("gbGuestLoginHead");
this.label1.Text = this._ResourceManager.GetString("lblUser");
this.label2.Text = this._ResourceManager.GetString("lblPass");
this.label4.Text = this._ResourceManager.GetString("lblWarningLogin");
this.label5.Text = this._ResourceManager.GetString("gbLanguage");
this.checkBox1.Text = this._ResourceManager.GetString("chRememberCred");
this.LoginBtn.Text = this._ResourceManager.GetString("logintext");
this.GuestLoginButton.Text = this._ResourceManager.GetString("guestLoginButton");
}
/// <summary>
/// Load Language Settings
/// </summary>
/// <param name="sender">The sender.</param>
/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
private void LoginLoad(object sender, EventArgs e)
{
try
{
var language = SettingsHelper.LoadSetting("UserLanguage");
switch (language)
{
case "de-DE":
this.comboBox2.SelectedIndex = 0;
break;
case "fr-FR":
this.comboBox2.SelectedIndex = 1;
break;
case "en-EN":
this.comboBox2.SelectedIndex = 2;
break;
/*case "zh-CN":
this.comboBox2.SelectedIndex = 3;
break;*/
default:
this.comboBox2.SelectedIndex = 2;
break;
}
}
catch (Exception)
{
this.comboBox2.SelectedIndex = 2;
}
}
/// <summary>
/// Try to Login to the Forums
/// </summary>
/// <param name="sender">The sender.</param>
/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
private void LoginBtnClick(object sender, EventArgs e)
{
// Encrypt Password
this.textBox2.Text = Utility.EncodePassword(this.textBox2.Text).Replace("-", string.Empty).ToLower();
var loginManager = new LoginManager(this.textBox1.Text, this.textBox2.Text);
var welcomeMessage = this._ResourceManager.GetString("lblWelcome");
var failedMessage = this._ResourceManager.GetString("lblFailed");
if (loginManager.DoLogin(CacheController.Instance().UserSettings.ForumURL))
{
this.label3.Text = string.Format("{0}{1}", welcomeMessage, this.textBox1.Text);
this.label3.ForeColor = Color.Green;
this.LoginBtn.Enabled = false;
SettingsHelper.SaveSetting("User", this.textBox1.Text);
SettingsHelper.SaveSetting("Password", this.textBox2.Text);
this.timer1.Enabled = true;
}
else
{
this.label3.Text = failedMessage;
this.label3.ForeColor = Color.Red;
}
}
/// <summary>
/// TODO : Remove Timer
/// If Login successfully send user data to MainForm
/// </summary>
/// <param name="sender">The sender.</param>
/// <param name="e">The <see cref="System.Timers.ElapsedEventArgs"/> instance containing the event data.</param>
private void Timer1Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
this.timer1.Enabled = false;
((MainForm)Owner).cameThroughCorrectLogin = true;
var cacheController = CacheController.Instance();
cacheController.UserSettings.User = this.textBox1.Text;
cacheController.UserSettings.Pass = this.textBox2.Text;
this.Close();
}
/// <summary>
/// Changes the UI Language based on the selected Language
/// </summary>
/// <param name="sender">The sender.</param>
/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
private void ComboBox2SelectedIndexChanged(object sender, EventArgs e)
{
switch (this.comboBox2.SelectedIndex)
{
case 0:
this._ResourceManager = new ResourceManager("Ripper.Languages.german", Assembly.GetExecutingAssembly());
SettingsHelper.SaveSetting("UserLanguage", "de-DE");
break;
case 1:
this._ResourceManager = new ResourceManager("Ripper.Languages.french", Assembly.GetExecutingAssembly());
SettingsHelper.SaveSetting("UserLanguage", "fr-FR");
break;
case 2:
this._ResourceManager = new ResourceManager("Ripper.Languages.english", Assembly.GetExecutingAssembly());
SettingsHelper.SaveSetting("UserLanguage", "en-EN");
break;
/*case 3:
this._ResourceManager = new ResourceManager("Ripper.Languages.chinese-cn", Assembly.GetExecutingAssembly());
SettingsHelper.SaveSetting("UserLanguage", "zh-CN");
break;*/
}
this.AdjustCulture();
}
/// <summary>
/// Login as Guest
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
private void GuestLoginButton_Click(object sender, EventArgs e)
{
((MainForm)Owner).cameThroughCorrectLogin = true;
var cacheController = CacheController.Instance();
cacheController.UserSettings.GuestMode = true;
SettingsHelper.SaveSetting("GuestMode", cacheController.UserSettings.GuestMode.ToString());
this.Close();
}
/// <summary>
/// Handles the LinkClicked event of the RegisterLink control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="LinkLabelLinkClickedEventArgs"/> instance containing the event data.</param>
private void RegisterLink_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
Process.Start(string.Format("{0}register.php", CacheController.Instance().UserSettings.ForumURL));
}
}
}
| |
using System;
using System.Data;
using System.Data.SqlClient;
using Csla;
using Csla.Data;
namespace ParentLoad.Business.ERCLevel
{
/// <summary>
/// B05Level111Child (editable child object).<br/>
/// This is a generated base class of <see cref="B05Level111Child"/> business object.
/// </summary>
/// <remarks>
/// This class is an item of <see cref="B04Level11"/> collection.
/// </remarks>
[Serializable]
public partial class B05Level111Child : BusinessBase<B05Level111Child>
{
#region State Fields
[NotUndoable]
[NonSerialized]
internal int cMarentID1 = 0;
#endregion
#region Business Properties
/// <summary>
/// Maintains metadata about <see cref="Level_1_1_1_Child_Name"/> property.
/// </summary>
public static readonly PropertyInfo<string> Level_1_1_1_Child_NameProperty = RegisterProperty<string>(p => p.Level_1_1_1_Child_Name, "Level_1_1_1 Child Name");
/// <summary>
/// Gets or sets the Level_1_1_1 Child Name.
/// </summary>
/// <value>The Level_1_1_1 Child Name.</value>
public string Level_1_1_1_Child_Name
{
get { return GetProperty(Level_1_1_1_Child_NameProperty); }
set { SetProperty(Level_1_1_1_Child_NameProperty, value); }
}
#endregion
#region Factory Methods
/// <summary>
/// Factory method. Creates a new <see cref="B05Level111Child"/> object.
/// </summary>
/// <returns>A reference to the created <see cref="B05Level111Child"/> object.</returns>
internal static B05Level111Child NewB05Level111Child()
{
return DataPortal.CreateChild<B05Level111Child>();
}
/// <summary>
/// Factory method. Loads a <see cref="B05Level111Child"/> object from the given SafeDataReader.
/// </summary>
/// <param name="dr">The SafeDataReader to use.</param>
/// <returns>A reference to the fetched <see cref="B05Level111Child"/> object.</returns>
internal static B05Level111Child GetB05Level111Child(SafeDataReader dr)
{
B05Level111Child obj = new B05Level111Child();
// show the framework that this is a child object
obj.MarkAsChild();
obj.Fetch(dr);
obj.MarkOld();
return obj;
}
#endregion
#region Constructor
/// <summary>
/// Initializes a new instance of the <see cref="B05Level111Child"/> class.
/// </summary>
/// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks>
private B05Level111Child()
{
// Prevent direct creation
// show the framework that this is a child object
MarkAsChild();
}
#endregion
#region Data Access
/// <summary>
/// Loads default values for the <see cref="B05Level111Child"/> object properties.
/// </summary>
[Csla.RunLocal]
protected override void Child_Create()
{
var args = new DataPortalHookArgs();
OnCreate(args);
base.Child_Create();
}
/// <summary>
/// Loads a <see cref="B05Level111Child"/> object from the given SafeDataReader.
/// </summary>
/// <param name="dr">The SafeDataReader to use.</param>
private void Fetch(SafeDataReader dr)
{
// Value properties
LoadProperty(Level_1_1_1_Child_NameProperty, dr.GetString("Level_1_1_1_Child_Name"));
cMarentID1 = dr.GetInt32("CMarentID1");
var args = new DataPortalHookArgs(dr);
OnFetchRead(args);
}
/// <summary>
/// Inserts a new <see cref="B05Level111Child"/> object in the database.
/// </summary>
/// <param name="parent">The parent object.</param>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_Insert(B04Level11 parent)
{
using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad"))
{
using (var cmd = new SqlCommand("AddB05Level111Child", ctx.Connection))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@Level_1_1_ID", parent.Level_1_1_ID).DbType = DbType.Int32;
cmd.Parameters.AddWithValue("@Level_1_1_1_Child_Name", ReadProperty(Level_1_1_1_Child_NameProperty)).DbType = DbType.String;
var args = new DataPortalHookArgs(cmd);
OnInsertPre(args);
cmd.ExecuteNonQuery();
OnInsertPost(args);
}
}
}
/// <summary>
/// Updates in the database all changes made to the <see cref="B05Level111Child"/> object.
/// </summary>
/// <param name="parent">The parent object.</param>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_Update(B04Level11 parent)
{
using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad"))
{
using (var cmd = new SqlCommand("UpdateB05Level111Child", ctx.Connection))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@Level_1_1_ID", parent.Level_1_1_ID).DbType = DbType.Int32;
cmd.Parameters.AddWithValue("@Level_1_1_1_Child_Name", ReadProperty(Level_1_1_1_Child_NameProperty)).DbType = DbType.String;
var args = new DataPortalHookArgs(cmd);
OnUpdatePre(args);
cmd.ExecuteNonQuery();
OnUpdatePost(args);
}
}
}
/// <summary>
/// Self deletes the <see cref="B05Level111Child"/> object from database.
/// </summary>
/// <param name="parent">The parent object.</param>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_DeleteSelf(B04Level11 parent)
{
using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad"))
{
using (var cmd = new SqlCommand("DeleteB05Level111Child", ctx.Connection))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@Level_1_1_ID", parent.Level_1_1_ID).DbType = DbType.Int32;
var args = new DataPortalHookArgs(cmd);
OnDeletePre(args);
cmd.ExecuteNonQuery();
OnDeletePost(args);
}
}
}
#endregion
#region Pseudo Events
/// <summary>
/// Occurs after setting all defaults for object creation.
/// </summary>
partial void OnCreate(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Delete, after setting query parameters and before the delete operation.
/// </summary>
partial void OnDeletePre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Delete, after the delete operation, before Commit().
/// </summary>
partial void OnDeletePost(DataPortalHookArgs args);
/// <summary>
/// Occurs after setting query parameters and before the fetch operation.
/// </summary>
partial void OnFetchPre(DataPortalHookArgs args);
/// <summary>
/// Occurs after the fetch operation (object or collection is fully loaded and set up).
/// </summary>
partial void OnFetchPost(DataPortalHookArgs args);
/// <summary>
/// Occurs after the low level fetch operation, before the data reader is destroyed.
/// </summary>
partial void OnFetchRead(DataPortalHookArgs args);
/// <summary>
/// Occurs after setting query parameters and before the update operation.
/// </summary>
partial void OnUpdatePre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after the update operation, before setting back row identifiers (RowVersion) and Commit().
/// </summary>
partial void OnUpdatePost(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after setting query parameters and before the insert operation.
/// </summary>
partial void OnInsertPre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after the insert operation, before setting back row identifiers (ID and RowVersion) and Commit().
/// </summary>
partial void OnInsertPost(DataPortalHookArgs args);
#endregion
}
}
| |
namespace Fixtures.SwaggerBatBodyComplex
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Rest;
using Models;
public static partial class PrimitiveExtensions
{
/// <summary>
/// Get complex types with integer properties
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method
/// </param>
public static IntWrapper GetInt(this IPrimitive operations)
{
return Task.Factory.StartNew(s => ((IPrimitive)s).GetIntAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Get complex types with integer properties
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
public static async Task<IntWrapper> GetIntAsync( this IPrimitive operations, CancellationToken cancellationToken = default(CancellationToken))
{
HttpOperationResponse<IntWrapper> result = await operations.GetIntWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false);
return result.Body;
}
/// <summary>
/// Put complex types with integer properties
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method
/// </param>
/// <param name='complexBody'>
/// Please put -1 and 2
/// </param>
public static void PutInt(this IPrimitive operations, IntWrapper complexBody)
{
Task.Factory.StartNew(s => ((IPrimitive)s).PutIntAsync(complexBody), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Put complex types with integer properties
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method
/// </param>
/// <param name='complexBody'>
/// Please put -1 and 2
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
public static async Task PutIntAsync( this IPrimitive operations, IntWrapper complexBody, CancellationToken cancellationToken = default(CancellationToken))
{
await operations.PutIntWithHttpMessagesAsync(complexBody, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Get complex types with long properties
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method
/// </param>
public static LongWrapper GetLong(this IPrimitive operations)
{
return Task.Factory.StartNew(s => ((IPrimitive)s).GetLongAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Get complex types with long properties
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
public static async Task<LongWrapper> GetLongAsync( this IPrimitive operations, CancellationToken cancellationToken = default(CancellationToken))
{
HttpOperationResponse<LongWrapper> result = await operations.GetLongWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false);
return result.Body;
}
/// <summary>
/// Put complex types with long properties
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method
/// </param>
/// <param name='complexBody'>
/// Please put 1099511627775 and -999511627788
/// </param>
public static void PutLong(this IPrimitive operations, LongWrapper complexBody)
{
Task.Factory.StartNew(s => ((IPrimitive)s).PutLongAsync(complexBody), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Put complex types with long properties
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method
/// </param>
/// <param name='complexBody'>
/// Please put 1099511627775 and -999511627788
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
public static async Task PutLongAsync( this IPrimitive operations, LongWrapper complexBody, CancellationToken cancellationToken = default(CancellationToken))
{
await operations.PutLongWithHttpMessagesAsync(complexBody, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Get complex types with float properties
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method
/// </param>
public static FloatWrapper GetFloat(this IPrimitive operations)
{
return Task.Factory.StartNew(s => ((IPrimitive)s).GetFloatAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Get complex types with float properties
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
public static async Task<FloatWrapper> GetFloatAsync( this IPrimitive operations, CancellationToken cancellationToken = default(CancellationToken))
{
HttpOperationResponse<FloatWrapper> result = await operations.GetFloatWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false);
return result.Body;
}
/// <summary>
/// Put complex types with float properties
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method
/// </param>
/// <param name='complexBody'>
/// Please put 1.05 and -0.003
/// </param>
public static void PutFloat(this IPrimitive operations, FloatWrapper complexBody)
{
Task.Factory.StartNew(s => ((IPrimitive)s).PutFloatAsync(complexBody), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Put complex types with float properties
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method
/// </param>
/// <param name='complexBody'>
/// Please put 1.05 and -0.003
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
public static async Task PutFloatAsync( this IPrimitive operations, FloatWrapper complexBody, CancellationToken cancellationToken = default(CancellationToken))
{
await operations.PutFloatWithHttpMessagesAsync(complexBody, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Get complex types with double properties
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method
/// </param>
public static DoubleWrapper GetDouble(this IPrimitive operations)
{
return Task.Factory.StartNew(s => ((IPrimitive)s).GetDoubleAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Get complex types with double properties
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
public static async Task<DoubleWrapper> GetDoubleAsync( this IPrimitive operations, CancellationToken cancellationToken = default(CancellationToken))
{
HttpOperationResponse<DoubleWrapper> result = await operations.GetDoubleWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false);
return result.Body;
}
/// <summary>
/// Put complex types with double properties
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method
/// </param>
/// <param name='complexBody'>
/// Please put 3e-100 and
/// -0.000000000000000000000000000000000000000000000000000000005
/// </param>
public static void PutDouble(this IPrimitive operations, DoubleWrapper complexBody)
{
Task.Factory.StartNew(s => ((IPrimitive)s).PutDoubleAsync(complexBody), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Put complex types with double properties
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method
/// </param>
/// <param name='complexBody'>
/// Please put 3e-100 and
/// -0.000000000000000000000000000000000000000000000000000000005
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
public static async Task PutDoubleAsync( this IPrimitive operations, DoubleWrapper complexBody, CancellationToken cancellationToken = default(CancellationToken))
{
await operations.PutDoubleWithHttpMessagesAsync(complexBody, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Get complex types with bool properties
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method
/// </param>
public static BooleanWrapper GetBool(this IPrimitive operations)
{
return Task.Factory.StartNew(s => ((IPrimitive)s).GetBoolAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Get complex types with bool properties
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
public static async Task<BooleanWrapper> GetBoolAsync( this IPrimitive operations, CancellationToken cancellationToken = default(CancellationToken))
{
HttpOperationResponse<BooleanWrapper> result = await operations.GetBoolWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false);
return result.Body;
}
/// <summary>
/// Put complex types with bool properties
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method
/// </param>
/// <param name='complexBody'>
/// Please put true and false
/// </param>
public static void PutBool(this IPrimitive operations, BooleanWrapper complexBody)
{
Task.Factory.StartNew(s => ((IPrimitive)s).PutBoolAsync(complexBody), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Put complex types with bool properties
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method
/// </param>
/// <param name='complexBody'>
/// Please put true and false
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
public static async Task PutBoolAsync( this IPrimitive operations, BooleanWrapper complexBody, CancellationToken cancellationToken = default(CancellationToken))
{
await operations.PutBoolWithHttpMessagesAsync(complexBody, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Get complex types with string properties
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method
/// </param>
public static StringWrapper GetString(this IPrimitive operations)
{
return Task.Factory.StartNew(s => ((IPrimitive)s).GetStringAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Get complex types with string properties
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
public static async Task<StringWrapper> GetStringAsync( this IPrimitive operations, CancellationToken cancellationToken = default(CancellationToken))
{
HttpOperationResponse<StringWrapper> result = await operations.GetStringWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false);
return result.Body;
}
/// <summary>
/// Put complex types with string properties
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method
/// </param>
/// <param name='complexBody'>
/// Please put 'goodrequest', '', and null
/// </param>
public static void PutString(this IPrimitive operations, StringWrapper complexBody)
{
Task.Factory.StartNew(s => ((IPrimitive)s).PutStringAsync(complexBody), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Put complex types with string properties
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method
/// </param>
/// <param name='complexBody'>
/// Please put 'goodrequest', '', and null
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
public static async Task PutStringAsync( this IPrimitive operations, StringWrapper complexBody, CancellationToken cancellationToken = default(CancellationToken))
{
await operations.PutStringWithHttpMessagesAsync(complexBody, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Get complex types with date properties
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method
/// </param>
public static DateWrapper GetDate(this IPrimitive operations)
{
return Task.Factory.StartNew(s => ((IPrimitive)s).GetDateAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Get complex types with date properties
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
public static async Task<DateWrapper> GetDateAsync( this IPrimitive operations, CancellationToken cancellationToken = default(CancellationToken))
{
HttpOperationResponse<DateWrapper> result = await operations.GetDateWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false);
return result.Body;
}
/// <summary>
/// Put complex types with date properties
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method
/// </param>
/// <param name='complexBody'>
/// Please put '0001-01-01' and '2016-02-29'
/// </param>
public static void PutDate(this IPrimitive operations, DateWrapper complexBody)
{
Task.Factory.StartNew(s => ((IPrimitive)s).PutDateAsync(complexBody), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Put complex types with date properties
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method
/// </param>
/// <param name='complexBody'>
/// Please put '0001-01-01' and '2016-02-29'
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
public static async Task PutDateAsync( this IPrimitive operations, DateWrapper complexBody, CancellationToken cancellationToken = default(CancellationToken))
{
await operations.PutDateWithHttpMessagesAsync(complexBody, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Get complex types with datetime properties
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method
/// </param>
public static DatetimeWrapper GetDateTime(this IPrimitive operations)
{
return Task.Factory.StartNew(s => ((IPrimitive)s).GetDateTimeAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Get complex types with datetime properties
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
public static async Task<DatetimeWrapper> GetDateTimeAsync( this IPrimitive operations, CancellationToken cancellationToken = default(CancellationToken))
{
HttpOperationResponse<DatetimeWrapper> result = await operations.GetDateTimeWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false);
return result.Body;
}
/// <summary>
/// Put complex types with datetime properties
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method
/// </param>
/// <param name='complexBody'>
/// Please put '0001-01-01T12:00:00-04:00' and '2015-05-18T11:38:00-08:00'
/// </param>
public static void PutDateTime(this IPrimitive operations, DatetimeWrapper complexBody)
{
Task.Factory.StartNew(s => ((IPrimitive)s).PutDateTimeAsync(complexBody), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Put complex types with datetime properties
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method
/// </param>
/// <param name='complexBody'>
/// Please put '0001-01-01T12:00:00-04:00' and '2015-05-18T11:38:00-08:00'
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
public static async Task PutDateTimeAsync( this IPrimitive operations, DatetimeWrapper complexBody, CancellationToken cancellationToken = default(CancellationToken))
{
await operations.PutDateTimeWithHttpMessagesAsync(complexBody, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Get complex types with byte properties
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method
/// </param>
public static ByteWrapper GetByte(this IPrimitive operations)
{
return Task.Factory.StartNew(s => ((IPrimitive)s).GetByteAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Get complex types with byte properties
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
public static async Task<ByteWrapper> GetByteAsync( this IPrimitive operations, CancellationToken cancellationToken = default(CancellationToken))
{
HttpOperationResponse<ByteWrapper> result = await operations.GetByteWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false);
return result.Body;
}
/// <summary>
/// Put complex types with byte properties
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method
/// </param>
/// <param name='complexBody'>
/// Please put non-ascii byte string hex(FF FE FD FC 00 FA F9 F8 F7 F6)
/// </param>
public static void PutByte(this IPrimitive operations, ByteWrapper complexBody)
{
Task.Factory.StartNew(s => ((IPrimitive)s).PutByteAsync(complexBody), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Put complex types with byte properties
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method
/// </param>
/// <param name='complexBody'>
/// Please put non-ascii byte string hex(FF FE FD FC 00 FA F9 F8 F7 F6)
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
public static async Task PutByteAsync( this IPrimitive operations, ByteWrapper complexBody, CancellationToken cancellationToken = default(CancellationToken))
{
await operations.PutByteWithHttpMessagesAsync(complexBody, null, cancellationToken).ConfigureAwait(false);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections;
using System.Collections.Generic;
namespace System.Linq.Expressions.Tests
{
public interface I
{
void M();
}
public class C : IEquatable<C>, I
{
void I.M()
{
}
public override bool Equals(object o)
{
return o is C && Equals((C)o);
}
public bool Equals(C c)
{
return c != null;
}
public override int GetHashCode()
{
return 0;
}
}
public class D : C, IEquatable<D>
{
public int Val;
public string S;
public D()
{
}
public D(int val)
: this(val, "")
{
}
public D(int val, string s)
{
Val = val;
S = s;
}
public override bool Equals(object o)
{
return o is D && Equals((D)o);
}
public bool Equals(D d)
{
return d != null && d.Val == Val;
}
public override int GetHashCode()
{
return Val;
}
}
public enum E
{
A = 1,
B = 2,
Red = 0,
Green,
Blue
}
public enum El : long
{
A,
B,
C
}
public enum Eu : uint
{
Foo,
Bar,
Baz
}
public struct S : IEquatable<S>
{
public override bool Equals(object o)
{
return (o is S) && Equals((S)o);
}
public bool Equals(S other)
{
return true;
}
public override int GetHashCode()
{
return 0;
}
}
public struct Sp : IEquatable<Sp>
{
public Sp(int i, double d)
{
I = i;
D = d;
}
public int I;
public double D;
public override bool Equals(object o)
{
return (o is Sp) && Equals((Sp)o);
}
public bool Equals(Sp other)
{
return other.I == I && other.D.Equals(D);
}
public override int GetHashCode()
{
return I.GetHashCode() ^ D.GetHashCode();
}
}
public struct Ss : IEquatable<Ss>
{
public Ss(S s)
{
Val = s;
}
public S Val;
public override bool Equals(object o)
{
return (o is Ss) && Equals((Ss)o);
}
public bool Equals(Ss other)
{
return other.Val.Equals(Val);
}
public override int GetHashCode()
{
return Val.GetHashCode();
}
}
public struct Sc : IEquatable<Sc>
{
public Sc(string s)
{
S = s;
}
public string S;
public override bool Equals(object o)
{
return (o is Sc) && Equals((Sc)o);
}
public bool Equals(Sc other)
{
return other.S == S;
}
public override int GetHashCode()
{
return S.GetHashCode();
}
}
public struct Scs : IEquatable<Scs>
{
public Scs(string s, S val)
{
S = s;
Val = val;
}
public string S;
public S Val;
public override bool Equals(object o)
{
return (o is Scs) && Equals((Scs)o);
}
public bool Equals(Scs other)
{
return other.S == S && other.Val.Equals(Val);
}
public override int GetHashCode()
{
return S.GetHashCode() ^ Val.GetHashCode();
}
}
public class BaseClass
{
}
public class FC
{
public int II;
public static int SI;
public const int CI = 42;
public static readonly int RI = 42;
}
public struct FS
{
public int II;
public static int SI;
public const int CI = 42;
public static readonly int RI = 42;
}
public class PC
{
public int II { get; set; }
public static int SI { get; set; }
public int this[int i]
{
get { return 1; }
set { }
}
}
public struct PS
{
public int II { get; set; }
public static int SI { get; set; }
}
internal class CompilationTypes : IEnumerable<object[]>
{
private static readonly object[] False = new object[] { false };
private static readonly object[] True = new object[] { true };
public IEnumerator<object[]> GetEnumerator()
{
yield return False;
yield return True;
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}
internal class NoOpVisitor : ExpressionVisitor
{
internal static readonly NoOpVisitor Instance = new NoOpVisitor();
private NoOpVisitor()
{
}
}
public static class Unreadable<T>
{
public static T WriteOnly { set { } }
}
public class GenericClass<T>
{
public void Method() { }
}
public class NonGenericClass
{
#pragma warning disable 0067
public event EventHandler Event;
#pragma warning restore 0067
public void GenericMethod<T>() { }
public static void StaticMethod() { }
}
public enum ByteEnum : byte { A = Byte.MaxValue }
public enum SByteEnum : sbyte { A = SByte.MaxValue }
public enum Int16Enum : short { A = Int16.MaxValue }
public enum UInt16Enum : ushort { A = UInt16.MaxValue }
public enum Int32Enum : int { A = Int32.MaxValue }
public enum UInt32Enum : uint { A = UInt32.MaxValue }
public enum Int64Enum : long { A = Int64.MaxValue }
public enum UInt64Enum : ulong { A = UInt64.MaxValue }
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Newtonsoft.Json;
using Orleans.Hosting;
using Orleans.Runtime.TestHooks;
using Orleans.Configuration;
using Orleans.Messaging;
using Orleans.Runtime;
using Orleans.Runtime.MembershipService;
using Orleans.Statistics;
using Orleans.TestingHost.Utils;
using Orleans.TestingHost.Logging;
using Orleans.Configuration.Internal;
namespace Orleans.TestingHost
{
/// <summary>
/// Utility for creating silos given a name and collection of configuration sources.
/// </summary>
public class TestClusterHostFactory
{
/// <summary>
/// Creates an returns a new silo.
/// </summary>
/// <param name="hostName">The silo name if it is not already specified in the configuration.</param>
/// <param name="configuration">The configuration.</param>
/// <returns>A new silo.</returns>
public static IHost CreateSiloHost(string hostName, IConfiguration configuration)
{
string siloName = configuration[nameof(TestSiloSpecificOptions.SiloName)] ?? hostName;
var hostBuilder = new HostBuilder();
hostBuilder.Properties["Configuration"] = configuration;
hostBuilder.ConfigureHostConfiguration(cb => cb.AddConfiguration(configuration));
hostBuilder.UseOrleans(siloBuilder =>
{
siloBuilder
.Configure<ClusterOptions>(configuration)
.Configure<SiloOptions>(options => options.SiloName = siloName)
.Configure<HostOptions>(options => options.ShutdownTimeout = TimeSpan.FromSeconds(30));
});
ConfigureAppServices(configuration, hostBuilder);
hostBuilder.ConfigureServices((context, services) =>
{
services.AddSingleton<TestHooksHostEnvironmentStatistics>();
services.AddFromExisting<IHostEnvironmentStatistics, TestHooksHostEnvironmentStatistics>();
services.AddSingleton<TestHooksSystemTarget>();
ConfigureListeningPorts(context.Configuration, services);
TryConfigureClusterMembership(context.Configuration, services);
TryConfigureFileLogging(configuration, services, siloName);
if (Debugger.IsAttached)
{
// Test is running inside debugger - Make timeout ~= infinite
services.Configure<SiloMessagingOptions>(op => op.ResponseTimeout = TimeSpan.FromMilliseconds(1000000));
}
});
var host = hostBuilder.Build();
var silo = host.Services.GetRequiredService<IHost>();
InitializeTestHooksSystemTarget(silo);
return silo;
}
/// <summary>
/// Creates the cluster client.
/// </summary>
/// <param name="hostName">Name of the host.</param>
/// <param name="configurationSources">The configuration sources.</param>
/// <returns>The cluster client host.</returns>
public static IHost CreateClusterClient(string hostName, IEnumerable<IConfigurationSource> configurationSources)
{
var configBuilder = new ConfigurationBuilder();
foreach (var source in configurationSources)
{
configBuilder.Add(source);
}
var configuration = configBuilder.Build();
var hostBuilder = new HostBuilder();
hostBuilder.Properties["Configuration"] = configuration;
hostBuilder.ConfigureHostConfiguration(cb => cb.AddConfiguration(configuration))
.UseOrleansClient(clientBuilder =>
{
clientBuilder.Configure<ClusterOptions>(configuration);
ConfigureAppServices(configuration, clientBuilder);
})
.ConfigureServices(services =>
{
TryConfigureClientMembership(configuration, services);
TryConfigureFileLogging(configuration, services, hostName);
});
var host = hostBuilder.Build();
return host;
}
/// <summary>
/// Serializes configuration to a string.
/// </summary>
/// <param name="configuration">The configuration.</param>
/// <returns>The serialized configuration.</returns>
public static string SerializeConfiguration(IConfiguration configuration)
{
var settings = new JsonSerializerSettings
{
TypeNameHandling = TypeNameHandling.Auto,
Formatting = Formatting.None,
};
KeyValuePair<string, string>[] enumerated = configuration.AsEnumerable().ToArray();
return JsonConvert.SerializeObject(enumerated, settings);
}
/// <summary>
/// Deserializes a configuration string.
/// </summary>
/// <param name="serializedSources">The serialized sources.</param>
/// <returns>The deserialzied configuration.</returns>
public static IConfiguration DeserializeConfiguration(string serializedSources)
{
var settings = new JsonSerializerSettings
{
TypeNameHandling = TypeNameHandling.Auto,
};
var builder = new ConfigurationBuilder();
var enumerated = JsonConvert.DeserializeObject<KeyValuePair<string, string>[]>(serializedSources, settings);
builder.AddInMemoryCollection(enumerated);
return builder.Build();
}
private static void ConfigureListeningPorts(IConfiguration configuration, IServiceCollection services)
{
int siloPort = int.Parse(configuration[nameof(TestSiloSpecificOptions.SiloPort)]);
int gatewayPort = int.Parse(configuration[nameof(TestSiloSpecificOptions.GatewayPort)]);
services.Configure<EndpointOptions>(options =>
{
options.AdvertisedIPAddress = IPAddress.Loopback;
options.SiloPort = siloPort;
options.GatewayPort = gatewayPort;
options.SiloListeningEndpoint = new IPEndPoint(IPAddress.Loopback, siloPort);
if (gatewayPort != 0)
{
options.GatewayListeningEndpoint = new IPEndPoint(IPAddress.Loopback, gatewayPort);
}
});
}
private static void ConfigureAppServices(IConfiguration configuration, IHostBuilder hostBuilder)
{
var builderConfiguratorTypes = configuration.GetSection(nameof(TestClusterOptions.SiloBuilderConfiguratorTypes))?.Get<string[]>();
if (builderConfiguratorTypes == null) return;
foreach (var builderConfiguratorType in builderConfiguratorTypes)
{
if (!string.IsNullOrWhiteSpace(builderConfiguratorType))
{
var configurator = Activator.CreateInstance(Type.GetType(builderConfiguratorType, true));
(configurator as IHostConfigurator)?.Configure(hostBuilder);
hostBuilder.UseOrleans(siloBuilder => (configurator as ISiloConfigurator)?.Configure(siloBuilder));
}
}
}
private static void ConfigureAppServices(IConfiguration configuration, IClientBuilder clientBuilder)
{
var builderConfiguratorTypes = configuration.GetSection(nameof(TestClusterOptions.ClientBuilderConfiguratorTypes))?.Get<string[]>();
if (builderConfiguratorTypes == null) return;
foreach (var builderConfiguratorType in builderConfiguratorTypes)
{
if (!string.IsNullOrWhiteSpace(builderConfiguratorType))
{
var builderConfigurator = (IClientBuilderConfigurator)Activator.CreateInstance(Type.GetType(builderConfiguratorType, true));
builderConfigurator?.Configure(configuration, clientBuilder);
}
}
}
private static void TryConfigureClusterMembership(IConfiguration configuration, IServiceCollection services)
{
bool.TryParse(configuration[nameof(TestClusterOptions.UseTestClusterMembership)], out bool useTestClusterMembership);
// Configure test cluster membership if requested and if no membership table implementation has been registered.
// If the test involves a custom membership oracle and no membership table, special care will be required
if (useTestClusterMembership && services.All(svc => svc.ServiceType != typeof(IMembershipTable)))
{
var primarySiloEndPoint = new IPEndPoint(IPAddress.Loopback, int.Parse(configuration[nameof(TestSiloSpecificOptions.PrimarySiloPort)]));
services.Configure<DevelopmentClusterMembershipOptions>(options => options.PrimarySiloEndpoint = primarySiloEndPoint);
services
.AddSingleton<SystemTargetBasedMembershipTable>()
.AddFromExisting<IMembershipTable, SystemTargetBasedMembershipTable>();
}
}
private static void TryConfigureClientMembership(IConfiguration configuration, IClientBuilder clientBuilder)
{
bool.TryParse(configuration[nameof(TestClusterOptions.UseTestClusterMembership)], out bool useTestClusterMembership);
if (useTestClusterMembership)
{
Action<StaticGatewayListProviderOptions> configureOptions = options =>
{
int baseGatewayPort = int.Parse(configuration[nameof(TestClusterOptions.BaseGatewayPort)]);
int initialSilosCount = int.Parse(configuration[nameof(TestClusterOptions.InitialSilosCount)]);
bool gatewayPerSilo = bool.Parse(configuration[nameof(TestClusterOptions.GatewayPerSilo)]);
if (gatewayPerSilo)
{
options.Gateways = Enumerable.Range(baseGatewayPort, initialSilosCount)
.Select(port => new IPEndPoint(IPAddress.Loopback, port).ToGatewayUri())
.ToList();
}
else
{
options.Gateways = new List<Uri> { new IPEndPoint(IPAddress.Loopback, baseGatewayPort).ToGatewayUri() };
}
};
clientBuilder.Configure(configureOptions);
clientBuilder.ConfigureServices(services =>
{
services.AddSingleton<IGatewayListProvider, StaticGatewayListProvider>()
.ConfigureFormatter<StaticGatewayListProviderOptions>();
});
}
}
private static void TryConfigureClientMembership(IConfiguration configuration, IServiceCollection services)
{
bool.TryParse(configuration[nameof(TestClusterOptions.UseTestClusterMembership)], out bool useTestClusterMembership);
if (useTestClusterMembership && services.All(svc => svc.ServiceType != typeof(IGatewayListProvider)))
{
Action<StaticGatewayListProviderOptions> configureOptions = options =>
{
int baseGatewayPort = int.Parse(configuration[nameof(TestClusterOptions.BaseGatewayPort)]);
int initialSilosCount = int.Parse(configuration[nameof(TestClusterOptions.InitialSilosCount)]);
bool gatewayPerSilo = bool.Parse(configuration[nameof(TestClusterOptions.GatewayPerSilo)]);
if (gatewayPerSilo)
{
options.Gateways = Enumerable.Range(baseGatewayPort, initialSilosCount)
.Select(port => new IPEndPoint(IPAddress.Loopback, port).ToGatewayUri())
.ToList();
}
else
{
options.Gateways = new List<Uri> { new IPEndPoint(IPAddress.Loopback, baseGatewayPort).ToGatewayUri() };
}
};
if (configureOptions != null)
{
services.Configure(configureOptions);
}
services.AddSingleton<IGatewayListProvider, StaticGatewayListProvider>()
.ConfigureFormatter<StaticGatewayListProviderOptions>();
}
}
private static void TryConfigureFileLogging(IConfiguration configuration, IServiceCollection services, string name)
{
bool.TryParse(configuration[nameof(TestClusterOptions.ConfigureFileLogging)], out bool configureFileLogging);
if (configureFileLogging)
{
var fileName = TestingUtils.CreateTraceFileName(name, configuration[nameof(TestClusterOptions.ClusterId)]);
services.AddLogging(loggingBuilder => loggingBuilder.AddFile(fileName));
}
}
private static void InitializeTestHooksSystemTarget(IHost host)
{
var testHook = host.Services.GetRequiredService<TestHooksSystemTarget>();
var catalog = host.Services.GetRequiredService<Catalog>();
catalog.RegisterSystemTarget(testHook);
}
}
}
| |
using UnityEngine;
using UnityEditor;
using System.Collections;
[CustomEditor(typeof(BezierCurve))]
public class BezierCurveEditor : Editor
{
BezierCurve curve;
SerializedProperty resolutionProp;
SerializedProperty closeProp;
SerializedProperty pointsProp;
SerializedProperty colorProp;
private static bool showPoints = true;
void OnEnable()
{
curve = (BezierCurve)target;
resolutionProp = serializedObject.FindProperty("resolution");
closeProp = serializedObject.FindProperty("_close");
pointsProp = serializedObject.FindProperty("points");
colorProp = serializedObject.FindProperty("drawColor");
}
public override void OnInspectorGUI()
{
serializedObject.Update();
EditorGUILayout.PropertyField(resolutionProp);
EditorGUILayout.PropertyField(closeProp);
EditorGUILayout.PropertyField(colorProp);
showPoints = EditorGUILayout.Foldout(showPoints, "Points");
if(showPoints)
{
int pointCount = pointsProp.arraySize;
for(int i = 0; i < pointCount; i++)
{
DrawPointInspector(curve[i], i);
}
if(GUILayout.Button("Add Point"))
{
Undo.RegisterSceneUndo("Add Point");
GameObject pointObject = new GameObject("Point "+pointsProp.arraySize);
pointObject.transform.parent = curve.transform;
pointObject.transform.localPosition = Vector3.zero;
BezierPoint newPoint = pointObject.AddComponent<BezierPoint>();
newPoint.curve = curve;
newPoint.handle1 = Vector3.right*0.1f;
newPoint.handle2 = -Vector3.right*0.1f;
pointsProp.InsertArrayElementAtIndex(pointsProp.arraySize);
pointsProp.GetArrayElementAtIndex(pointsProp.arraySize - 1).objectReferenceValue = newPoint;
}
}
if(GUI.changed)
{
serializedObject.ApplyModifiedProperties();
EditorUtility.SetDirty(target);
}
}
void OnSceneGUI()
{
for(int i = 0; i < curve.pointCount; i++)
{
DrawPointSceneGUI(curve[i]);
}
}
void DrawPointInspector(BezierPoint point, int index)
{
SerializedObject serObj = new SerializedObject(point);
SerializedProperty handleStyleProp = serObj.FindProperty("handleStyle");
SerializedProperty handle1Prop = serObj.FindProperty("_handle1");
SerializedProperty handle2Prop = serObj.FindProperty("_handle2");
EditorGUILayout.BeginHorizontal();
if(GUILayout.Button("X", GUILayout.Width(20)))
{
Undo.RegisterSceneUndo("Remove Point");
pointsProp.MoveArrayElement(curve.GetPointIndex(point), curve.pointCount - 1);
pointsProp.arraySize--;
DestroyImmediate(point.gameObject);
return;
}
EditorGUILayout.ObjectField(point.gameObject, typeof(GameObject), true);
if(index != 0 && GUILayout.Button(@"/\", GUILayout.Width(25)))
{
UnityEngine.Object other = pointsProp.GetArrayElementAtIndex(index - 1).objectReferenceValue;
pointsProp.GetArrayElementAtIndex(index - 1).objectReferenceValue = point;
pointsProp.GetArrayElementAtIndex(index).objectReferenceValue = other;
}
if(index != pointsProp.arraySize - 1 && GUILayout.Button(@"\/", GUILayout.Width(25)))
{
UnityEngine.Object other = pointsProp.GetArrayElementAtIndex(index + 1).objectReferenceValue;
pointsProp.GetArrayElementAtIndex(index + 1).objectReferenceValue = point;
pointsProp.GetArrayElementAtIndex(index).objectReferenceValue = other;
}
EditorGUILayout.EndHorizontal();
EditorGUI.indentLevel++;
EditorGUI.indentLevel++;
int newType = (int)((object)EditorGUILayout.EnumPopup("Handle Type", (BezierPoint.HandleStyle)handleStyleProp.enumValueIndex));
if(newType != handleStyleProp.enumValueIndex)
{
handleStyleProp.enumValueIndex = newType;
if(newType == 0)
{
if(handle1Prop.vector3Value != Vector3.zero) handle2Prop.vector3Value = -handle1Prop.vector3Value;
else if(handle2Prop.vector3Value != Vector3.zero) handle1Prop.vector3Value = -handle2Prop.vector3Value;
else
{
handle1Prop.vector3Value = new Vector3(0.1f, 0, 0);
handle2Prop.vector3Value = new Vector3(-0.1f, 0, 0);
}
}
else if(newType == 1)
{
if(handle1Prop.vector3Value == Vector3.zero && handle2Prop.vector3Value == Vector3.zero)
{
handle1Prop.vector3Value = new Vector3(0.1f, 0, 0);
handle2Prop.vector3Value = new Vector3(-0.1f, 0, 0);
}
}
else if(newType == 2)
{
handle1Prop.vector3Value = Vector3.zero;
handle2Prop.vector3Value = Vector3.zero;
}
}
Vector3 newPointPos = EditorGUILayout.Vector3Field("Position : ", point.transform.localPosition);
if(newPointPos != point.transform.localPosition)
{
Undo.RegisterUndo(point.transform, "Move Bezier Point");
point.transform.localPosition = newPointPos;
}
if(handleStyleProp.enumValueIndex == 0)
{
Vector3 newPosition;
newPosition = EditorGUILayout.Vector3Field("Handle 1", handle1Prop.vector3Value);
if(newPosition != handle1Prop.vector3Value)
{
handle1Prop.vector3Value = newPosition;
handle2Prop.vector3Value = -newPosition;
}
newPosition = EditorGUILayout.Vector3Field("Handle 2", handle2Prop.vector3Value);
if(newPosition != handle2Prop.vector3Value)
{
handle1Prop.vector3Value = -newPosition;
handle2Prop.vector3Value = newPosition;
}
}
else if(handleStyleProp.enumValueIndex == 1)
{
EditorGUILayout.PropertyField(handle1Prop);
EditorGUILayout.PropertyField(handle2Prop);
}
EditorGUI.indentLevel--;
EditorGUI.indentLevel--;
if(GUI.changed)
{
serObj.ApplyModifiedProperties();
EditorUtility.SetDirty(serObj.targetObject);
}
}
static void DrawPointSceneGUI(BezierPoint point)
{
Handles.Label(point.position + new Vector3(0, HandleUtility.GetHandleSize(point.position) * 0.4f, 0), point.gameObject.name);
Handles.color = Color.green;
Vector3 newPosition = Handles.FreeMoveHandle(point.position, point.transform.rotation, HandleUtility.GetHandleSize(point.position)*0.1f, Vector3.zero, Handles.RectangleCap);
if(newPosition != point.position)
{
Undo.RegisterUndo(point.transform, "Move Point");
point.transform.position = newPosition;
}
if(point.handleStyle != BezierPoint.HandleStyle.None)
{
Handles.color = Color.cyan;
Vector3 newGlobal1 = Handles.FreeMoveHandle(point.globalHandle1, point.transform.rotation, HandleUtility.GetHandleSize(point.globalHandle1)*0.075f, Vector3.zero, Handles.CircleCap);
if(point.globalHandle1 != newGlobal1)
{
Undo.RegisterUndo(point, "Move Handle");
point.globalHandle1 = newGlobal1;
if(point.handleStyle == BezierPoint.HandleStyle.Connected) point.globalHandle2 = -(newGlobal1 - point.position) + point.position;
}
Vector3 newGlobal2 = Handles.FreeMoveHandle(point.globalHandle2, point.transform.rotation, HandleUtility.GetHandleSize(point.globalHandle2)*0.075f, Vector3.zero, Handles.CircleCap);
if(point.globalHandle2 != newGlobal2)
{
Undo.RegisterUndo(point, "Move Handle");
point.globalHandle2 = newGlobal2;
if(point.handleStyle == BezierPoint.HandleStyle.Connected) point.globalHandle1 = -(newGlobal2 - point.position) + point.position;
}
Handles.color = Color.yellow;
Handles.DrawLine(point.position, point.globalHandle1);
Handles.DrawLine(point.position, point.globalHandle2);
}
}
public static void DrawOtherPoints(BezierCurve curve, BezierPoint caller)
{
foreach(BezierPoint p in curve.GetAnchorPoints())
{
if(p != caller) DrawPointSceneGUI(p);
}
}
[MenuItem("GameObject/Create Other/Bezier Curve")]
public static void CreateCurve(MenuCommand command)
{
GameObject curveObject = new GameObject("BezierCurve");
Undo.RegisterUndo(curveObject, "Undo Create Curve");
BezierCurve curve = curveObject.AddComponent<BezierCurve>();
BezierPoint p1 = curve.AddPointAt(Vector3.forward * 0.5f);
p1.handleStyle = BezierPoint.HandleStyle.Connected;
p1.handle1 = new Vector3(-0.28f, 0, 0);
BezierPoint p2 = curve.AddPointAt(Vector3.right * 0.5f);
p2.handleStyle = BezierPoint.HandleStyle.Connected;
p2.handle1 = new Vector3(0, 0, 0.28f);
BezierPoint p3 = curve.AddPointAt(-Vector3.forward * 0.5f);
p3.handleStyle = BezierPoint.HandleStyle.Connected;
p3.handle1 = new Vector3(0.28f, 0, 0);
BezierPoint p4 = curve.AddPointAt(-Vector3.right * 0.5f);
p4.handleStyle = BezierPoint.HandleStyle.Connected;
p4.handle1 = new Vector3(0, 0, -0.28f);
curve.close = true;
}
}
| |
using System;
using Google.GData.Client;
using Google.GData.Extensions.Apps;
namespace Google.GData.Apps.Groups
{
/// <summary>
/// Base service for accessing Google Groups item feeds from the
/// Google Apps Google Groups API.
/// </summary>
public class GroupsService : AppsPropertyService
{
/// <summary>
/// Constructor
/// </summary>
/// <param name="domain">The hosted domain in which the Google Groups are
/// being set up</param>
/// <param name="applicationName">The name of the client application
/// using this service.</param>
public GroupsService(string domain, string applicationName)
: base(domain, applicationName)
{
NewFeed += OnNewFeed;
}
/// <summary>
/// Retrieves a group in the domain.
/// </summary>
/// <param name="groupId">The ID of the group to be retrieved</param>
/// <returns>The requested group</returns>
public GroupEntry RetrieveGroup(string groupId)
{
string requestUri = string.Format("{0}/{1}/{2}",
AppsGroupsNameTable.AppsGoogleGroupsBaseFeedUri,
domain,
groupId);
return Get(requestUri) as GroupEntry;
}
/// <summary>
/// Retrieves all groups in the domain.
/// </summary>
/// <returns>The details of the existing groups for the domain</returns>
public GroupFeed RetrieveAllGroups()
{
string requestUri = string.Format("{0}/{1}",
AppsGroupsNameTable.AppsGoogleGroupsBaseFeedUri,
domain);
return QueryExtendedFeed(requestUri, true) as GroupFeed;
}
/// <summary>
/// Retrieves all groups for a member.
/// </summary>
/// <param name="memberId">The user for which you want to retrieve group subscriptions</param>
/// <param name="directOnly">Whether to identify only members with direct association with the group</param>
/// <returns>The details of the existing groups for the member</returns>
public GroupFeed RetrieveGroups(string memberId, bool directOnly)
{
string requestUri = string.Format("{0}/{1}?{2}={3}&{4}={5}",
AppsGroupsNameTable.AppsGoogleGroupsBaseFeedUri,
domain,
AppsGroupsNameTable.member,
memberId,
AppsGroupsNameTable.directOnly,
directOnly);
return QueryExtendedFeed(requestUri, true) as GroupFeed;
}
/// <summary>
/// Creates a new group for the domain.
/// </summary>
/// <param name="groupId">The ID of the group</param>
/// <param name="groupName">The name of the group</param>
/// <param name="description">The general description of the group</param>
/// <param name="emailPermission">The permission level of the group</param>
/// <returns>The entry being created</returns>
public GroupEntry CreateGroup(string groupId, string groupName, string description,
PermissionLevel? emailPermission)
{
string requestUri = string.Format("{0}/{1}",
AppsGroupsNameTable.AppsGoogleGroupsBaseFeedUri,
domain);
GroupEntry entry = new GroupEntry();
entry.GroupId = groupId;
entry.GroupName = groupName;
if (!string.IsNullOrEmpty(description))
{
entry.Description = description;
}
if (emailPermission != null)
{
entry.EmailPermission = (PermissionLevel) emailPermission;
}
return Insert(requestUri, entry);
}
/// <summary>
/// Updates an existing group in the domain.
/// </summary>
/// <param name="groupId">The ID of the group to be updated</param>
/// <param name="groupName">The name of the group</param>
/// <param name="description">The general description of the group</param>
/// <param name="emailPermission">The permission level of the group</param>
/// <returns>The updated entry</returns>
public GroupEntry UpdateGroup(string groupId, string groupName, string description,
PermissionLevel? emailPermission)
{
string requestUri = string.Format("{0}/{1}/{2}",
AppsGroupsNameTable.AppsGoogleGroupsBaseFeedUri,
domain,
groupId);
GroupEntry entry = new GroupEntry();
entry.EditUri = requestUri;
entry.GroupId = groupId;
entry.GroupName = groupName;
if (!string.IsNullOrEmpty(description))
{
entry.Description = description;
}
if (emailPermission != null)
{
entry.EmailPermission = (PermissionLevel) emailPermission;
}
return Update(entry);
}
/// <summary>
/// Deletes a group in the domain.
/// </summary>
/// <param name="groupId">The ID of the group to be deleted</param>
public void DeleteGroup(string groupId)
{
string requestUri = string.Format("{0}/{1}/{2}",
AppsGroupsNameTable.AppsGoogleGroupsBaseFeedUri,
domain,
groupId);
Delete(requestUri);
}
/// <summary>
/// Adds a member to a group.
/// </summary>
/// <param name="memberId">Username of the member that is being added to the group</param>
/// <param name="groupId">The group to which the member is being added</param>
/// <returns>a <code>MemberEntry</code> containing the results of the
/// creation</returns>
public MemberEntry AddMemberToGroup(string memberId, string groupId)
{
string requestUri = string.Format("{0}/{1}/{2}/{3}",
AppsGroupsNameTable.AppsGoogleGroupsBaseFeedUri,
domain,
groupId,
AppsGroupsNameTable.member);
MemberEntry entry = new MemberEntry();
entry.MemberId = memberId;
return Insert(requestUri, entry);
}
/// <summary>
/// Retrieves all members of a group.
/// </summary>
/// <param name="groupId">The ID of the group for which you wish to retrieve a member list</param>
/// <returns>The list of members for the group</returns>
public MemberFeed RetrieveAllMembers(string groupId)
{
return RetrieveAllMembers(groupId, true);
}
/// <summary>
/// Retrieves all members of a group.
/// </summary>
/// <param name="groupId">The ID of the group for which you wish to retrieve a member list</param>
/// <param name="includeSuspendedUsers">Whether to include suspended users</param>
/// <returns>The list of members for the group</returns>
public MemberFeed RetrieveAllMembers(string groupId, bool includeSuspendedUsers)
{
string requestUri = string.Format("{0}/{1}/{2}/{3}?{4}={5}",
AppsGroupsNameTable.AppsGoogleGroupsBaseFeedUri,
domain,
groupId,
AppsGroupsNameTable.member,
AppsGroupsNameTable.includeSuspendedUsers,
includeSuspendedUsers);
return QueryExtendedFeed(requestUri, true) as MemberFeed;
}
/// <summary>
/// Retrieves a group member.
/// </summary>
/// <param name="memberId">Username of the member that is being retrieved from the group</param>
/// <param name="groupId">The ID of the group for which you wish to retrieve a member</param>
/// <returns>The retrieved group member</returns>
public MemberEntry RetrieveMember(string memberId, string groupId)
{
string requestUri = string.Format("{0}/{1}/{2}/{3}/{4}",
AppsGroupsNameTable.AppsGoogleGroupsBaseFeedUri,
domain,
groupId,
AppsGroupsNameTable.member,
memberId);
return Get(requestUri) as MemberEntry;
}
/// <summary>
/// Checks whether an user is a group member.
/// </summary>
/// <param name="memberEmail">Email of the member that is being checked</param>
/// <param name="groupId">The ID of the group for which you wish to check the membership</param>
/// <returns>True if the user is a member of the group, false otherwise</returns>
public bool IsMember(string memberEmail, string groupId)
{
try
{
MemberEntry entry = RetrieveMember(memberEmail, groupId);
return entry != null;
}
catch (GDataRequestException e)
{
AppsException appsException = AppsException.ParseAppsException(e);
if (appsException == null)
{
return false;
}
if (appsException.ErrorCode.Equals(AppsException.EntityDoesNotExist))
{
return false;
}
throw appsException;
}
}
/// <summary>
/// Removes a member from a group
/// </summary>
/// <param name="memberId">Username of the member that is being removed from the group</param>
/// <param name="groupId">The group from which the member is being removed</param>
public void RemoveMemberFromGroup(string memberId, string groupId)
{
string requestUri = string.Format("{0}/{1}/{2}/{3}/{4}",
AppsGroupsNameTable.AppsGoogleGroupsBaseFeedUri,
domain,
groupId,
AppsGroupsNameTable.member,
memberId);
Delete(requestUri);
}
/// <summary>
/// Adds an owner to a group.
/// </summary>
/// <param name="ownerEmail">Email of the owner that is being added to the group</param>
/// <param name="groupId">The group to which the member is being added</param>
/// <returns>a <code>OwnerEntry</code> containing the results of the
/// creation</returns>
public OwnerEntry AddOwnerToGroup(string ownerEmail, string groupId)
{
string requestUri = string.Format("{0}/{1}/{2}/{3}",
AppsGroupsNameTable.AppsGoogleGroupsBaseFeedUri,
domain,
groupId,
AppsGroupsNameTable.owner);
OwnerEntry entry = new OwnerEntry();
entry.Email = ownerEmail;
return Insert(requestUri, entry);
}
/// <summary>
/// Retrieves a group owner.
/// </summary>
/// <param name="ownerEmail">Email of the owner that is being retrieved from the group</param>
/// <param name="groupId">The ID of the group for which you wish to retrieve an owner</param>
/// <returns>The retrieved group owner</returns>
public OwnerEntry RetrieveOwner(string ownerEmail, string groupId)
{
string requestUri = string.Format("{0}/{1}/{2}/{3}/{4}",
AppsGroupsNameTable.AppsGoogleGroupsBaseFeedUri,
domain,
groupId,
AppsGroupsNameTable.owner,
ownerEmail);
return Get(requestUri) as OwnerEntry;
}
/// <summary>
/// Retrieves all owners of a group.
/// </summary>
/// <param name="groupId">The ID of the group for which you wish to retrieve the owner list</param>
/// <returns>The list of owners for the group</returns>
public OwnerFeed RetrieveAllOwners(string groupId)
{
string requestUri = string.Format("{0}/{1}/{2}/{3}",
AppsGroupsNameTable.AppsGoogleGroupsBaseFeedUri,
domain,
groupId,
AppsGroupsNameTable.owner);
return QueryExtendedFeed(requestUri, true) as OwnerFeed;
}
/// <summary>
/// Checks whether an user is a group owner.
/// </summary>
/// <param name="ownerEmail">Email of the owner that is being checked</param>
/// <param name="groupId">The ID of the group for which you wish to check the ownership</param>
/// <returns>True if the user is an owner of the group, false otherwise</returns>
public bool IsOwner(string ownerEmail, string groupId)
{
try
{
OwnerEntry entry = RetrieveOwner(ownerEmail, groupId);
return entry != null;
}
catch (GDataRequestException e)
{
AppsException appsException = AppsException.ParseAppsException(e);
if (appsException == null)
{
return false;
}
if (appsException.ErrorCode.Equals(AppsException.EntityDoesNotExist))
{
return false;
}
throw appsException;
}
}
/// <summary>
/// Removes an owner from a group
/// </summary>
/// <param name="ownerEmail">Email of the owner that is being removed from the group</param>
/// <param name="groupId">The group from which the owner is being removed</param>
public void RemoveOwnerFromGroup(string ownerEmail, string groupId)
{
string requestUri = string.Format("{0}/{1}/{2}/{3}/{4}",
AppsGroupsNameTable.AppsGoogleGroupsBaseFeedUri,
domain,
groupId,
AppsGroupsNameTable.owner,
ownerEmail);
Delete(requestUri);
}
/// <summary>
/// Overridden so that new feeds are returned as <code>AppsExtendedFeed</code>s
/// instead of base <code>AtomFeed</code>s.
/// </summary>
/// <param name="sender"> the object which sent the event</param>
/// <param name="e">FeedParserEventArguments, holds the FeedEntry</param>
protected void OnNewFeed(object sender, ServiceEventArgs e)
{
Tracing.TraceMsg("Created new Google Groups Item Feed");
if (e == null)
{
throw new ArgumentNullException("e");
}
e.Feed = getFeed(e.Uri, e.Service);
}
protected override AppsExtendedFeed getFeed(Uri uri, IService service)
{
string baseUri = uri.ToString();
if (baseUri.Contains("/member"))
{
return new MemberFeed(uri, service);
}
if (baseUri.Contains("/owner"))
{
return new OwnerFeed(uri, service);
}
return new GroupFeed(uri, service);
}
}
public class GroupFeed : GenericFeed<GroupEntry>
{
public GroupFeed(Uri uriBase, IService iService)
: base(uriBase, iService)
{
}
}
public class MemberFeed : GenericFeed<MemberEntry>
{
public MemberFeed(Uri uriBase, IService iService)
: base(uriBase, iService)
{
}
}
public class OwnerFeed : GenericFeed<OwnerEntry>
{
public OwnerFeed(Uri uriBase, IService iService)
: base(uriBase, iService)
{
}
}
}
| |
/*
* 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.Datastream
{
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using System.Threading.Tasks;
using Apache.Ignite.Core.Datastream;
using Apache.Ignite.Core.Impl.Binary;
using Apache.Ignite.Core.Impl.Common;
/// <summary>
/// Data streamer internal interface to get rid of generics.
/// </summary>
internal interface IDataStreamer
{
/// <summary>
/// Callback invoked on topology size change.
/// </summary>
/// <param name="topVer">New topology version.</param>
/// <param name="topSize">New topology size.</param>
void TopologyChange(long topVer, int topSize);
}
/// <summary>
/// Data streamer implementation.
/// </summary>
internal class DataStreamerImpl<TK, TV> : PlatformDisposableTargetAdapter, IDataStreamer, IDataStreamer<TK, TV>
{
#pragma warning disable 0420
/** Policy: continue. */
internal const int PlcContinue = 0;
/** Policy: close. */
internal const int PlcClose = 1;
/** Policy: cancel and close. */
internal const int PlcCancelClose = 2;
/** Policy: flush. */
internal const int PlcFlush = 3;
/** Operation: update. */
private const int OpUpdate = 1;
/** Operation: set receiver. */
private const int OpReceiver = 2;
/** */
private const int OpAllowOverwrite = 3;
/** */
private const int OpSetAllowOverwrite = 4;
/** */
private const int OpSkipStore = 5;
/** */
private const int OpSetSkipStore = 6;
/** */
private const int OpPerNodeBufferSize = 7;
/** */
private const int OpSetPerNodeBufferSize = 8;
/** */
private const int OpPerNodeParallelOps = 9;
/** */
private const int OpSetPerNodeParallelOps = 10;
/** */
private const int OpListenTopology = 11;
/** */
private const int OpGetTimeout = 12;
/** */
private const int OpSetTimeout = 13;
/** */
private const int OpPerThreadBufferSize = 14;
/** */
private const int OpSetPerThreadBufferSize = 15;
/** Cache name. */
private readonly string _cacheName;
/** Lock. */
private readonly ReaderWriterLockSlim _rwLock = new ReaderWriterLockSlim();
/** Closed event. */
private readonly ManualResetEventSlim _closedEvt = new ManualResetEventSlim(false);
/** Close future. */
private readonly Future<object> _closeFut = new Future<object>();
/** GC handle to this streamer. */
private readonly long _hnd;
/** Topology version. */
private long _topVer;
/** Topology size. */
private int _topSize = 1;
/** Buffer send size. */
private volatile int _bufSndSize;
/** Current data streamer batch. */
private volatile DataStreamerBatch<TK, TV> _batch;
/** Flusher. */
private readonly Flusher<TK, TV> _flusher;
/** Receiver. */
private volatile IStreamReceiver<TK, TV> _rcv;
/** Receiver handle. */
private long _rcvHnd;
/** Receiver binary mode. */
private readonly bool _keepBinary;
/// <summary>
/// Constructor.
/// </summary>
/// <param name="target">Target.</param>
/// <param name="marsh">Marshaller.</param>
/// <param name="cacheName">Cache name.</param>
/// <param name="keepBinary">Binary flag.</param>
public DataStreamerImpl(IPlatformTargetInternal target, Marshaller marsh, string cacheName, bool keepBinary)
: base(target)
{
_cacheName = cacheName;
_keepBinary = keepBinary;
// Create empty batch.
_batch = new DataStreamerBatch<TK, TV>();
// Allocate GC handle so that this data streamer could be easily dereferenced from native code.
WeakReference thisRef = new WeakReference(this);
_hnd = marsh.Ignite.HandleRegistry.Allocate(thisRef);
// Start topology listening. This call will ensure that buffer size member is updated.
DoOutInOp(OpListenTopology, _hnd);
// Membar to ensure fields initialization before leaving constructor.
Thread.MemoryBarrier();
// Start flusher after everything else is initialized.
_flusher = new Flusher<TK, TV>(thisRef);
_flusher.RunThread();
}
/** <inheritDoc /> */
public string CacheName
{
get { return _cacheName; }
}
/** <inheritDoc /> */
public bool AllowOverwrite
{
get
{
_rwLock.EnterReadLock();
try
{
ThrowIfDisposed();
return DoOutInOp(OpAllowOverwrite) == True;
}
finally
{
_rwLock.ExitReadLock();
}
}
set
{
_rwLock.EnterWriteLock();
try
{
ThrowIfDisposed();
DoOutInOp(OpSetAllowOverwrite, value ? True : False);
}
finally
{
_rwLock.ExitWriteLock();
}
}
}
/** <inheritDoc /> */
public bool SkipStore
{
get
{
_rwLock.EnterReadLock();
try
{
ThrowIfDisposed();
return DoOutInOp(OpSkipStore) == True;
}
finally
{
_rwLock.ExitReadLock();
}
}
set
{
_rwLock.EnterWriteLock();
try
{
ThrowIfDisposed();
DoOutInOp(OpSetSkipStore, value ? True : False);
}
finally
{
_rwLock.ExitWriteLock();
}
}
}
/** <inheritDoc /> */
public int PerNodeBufferSize
{
get
{
_rwLock.EnterReadLock();
try
{
ThrowIfDisposed();
return (int) DoOutInOp(OpPerNodeBufferSize);
}
finally
{
_rwLock.ExitReadLock();
}
}
set
{
_rwLock.EnterWriteLock();
try
{
ThrowIfDisposed();
DoOutInOp(OpSetPerNodeBufferSize, value);
_bufSndSize = _topSize * value;
}
finally
{
_rwLock.ExitWriteLock();
}
}
}
/** <inheritDoc /> */
public int PerThreadBufferSize
{
get
{
_rwLock.EnterReadLock();
try
{
ThrowIfDisposed();
return (int) DoOutInOp(OpPerThreadBufferSize);
}
finally
{
_rwLock.ExitReadLock();
}
}
set
{
_rwLock.EnterWriteLock();
try
{
ThrowIfDisposed();
DoOutInOp(OpSetPerThreadBufferSize, value);
}
finally
{
_rwLock.ExitWriteLock();
}
}
}
/** <inheritDoc /> */
public int PerNodeParallelOperations
{
get
{
_rwLock.EnterReadLock();
try
{
ThrowIfDisposed();
return (int) DoOutInOp(OpPerNodeParallelOps);
}
finally
{
_rwLock.ExitReadLock();
}
}
set
{
_rwLock.EnterWriteLock();
try
{
ThrowIfDisposed();
DoOutInOp(OpSetPerNodeParallelOps, value);
}
finally
{
_rwLock.ExitWriteLock();
}
}
}
/** <inheritDoc /> */
public long AutoFlushFrequency
{
get
{
_rwLock.EnterReadLock();
try
{
ThrowIfDisposed();
return _flusher.Frequency;
}
finally
{
_rwLock.ExitReadLock();
}
}
set
{
_rwLock.EnterWriteLock();
try
{
ThrowIfDisposed();
_flusher.Frequency = value;
}
finally
{
_rwLock.ExitWriteLock();
}
}
}
/** <inheritDoc /> */
public Task Task
{
get
{
return _closeFut.Task;
}
}
/** <inheritDoc /> */
public IStreamReceiver<TK, TV> Receiver
{
get
{
ThrowIfDisposed();
return _rcv;
}
set
{
IgniteArgumentCheck.NotNull(value, "value");
var handleRegistry = Marshaller.Ignite.HandleRegistry;
_rwLock.EnterWriteLock();
try
{
ThrowIfDisposed();
if (_rcv == value)
return;
var rcvHolder = new StreamReceiverHolder(value,
(rec, grid, cache, stream, keepBinary) =>
StreamReceiverHolder.InvokeReceiver((IStreamReceiver<TK, TV>) rec, grid, cache, stream,
keepBinary));
var rcvHnd0 = handleRegistry.Allocate(rcvHolder);
try
{
DoOutOp(OpReceiver, w =>
{
w.WriteLong(rcvHnd0);
w.WriteObject(rcvHolder);
});
}
catch (Exception)
{
handleRegistry.Release(rcvHnd0);
throw;
}
if (_rcv != null)
handleRegistry.Release(_rcvHnd);
_rcv = value;
_rcvHnd = rcvHnd0;
}
finally
{
_rwLock.ExitWriteLock();
}
}
}
/** <inheritDoc /> */
public Task AddData(TK key, TV val)
{
ThrowIfDisposed();
IgniteArgumentCheck.NotNull(key, "key");
return Add0(new DataStreamerEntry<TK, TV>(key, val), 1);
}
/** <inheritDoc /> */
public Task AddData(KeyValuePair<TK, TV> pair)
{
ThrowIfDisposed();
return Add0(new DataStreamerEntry<TK, TV>(pair.Key, pair.Value), 1);
}
/** <inheritDoc /> */
public Task AddData(ICollection<KeyValuePair<TK, TV>> entries)
{
ThrowIfDisposed();
IgniteArgumentCheck.NotNull(entries, "entries");
return Add0(entries, entries.Count);
}
/** <inheritDoc /> */
public Task RemoveData(TK key)
{
ThrowIfDisposed();
IgniteArgumentCheck.NotNull(key, "key");
return Add0(new DataStreamerRemoveEntry<TK>(key), 1);
}
/** <inheritDoc /> */
public void TryFlush()
{
ThrowIfDisposed();
DataStreamerBatch<TK, TV> batch0 = _batch;
if (batch0 != null)
Flush0(batch0, false, PlcFlush);
}
/** <inheritDoc /> */
public void Flush()
{
ThrowIfDisposed();
DataStreamerBatch<TK, TV> batch0 = _batch;
if (batch0 != null)
Flush0(batch0, true, PlcFlush);
else
{
// Batch is null, i.e. data streamer is closing. Wait for close to complete.
_closedEvt.Wait();
}
}
/** <inheritDoc /> */
public void Close(bool cancel)
{
_flusher.Stop();
while (true)
{
DataStreamerBatch<TK, TV> batch0 = _batch;
if (batch0 == null)
{
// Wait for concurrent close to finish.
_closedEvt.Wait();
return;
}
if (Flush0(batch0, true, cancel ? PlcCancelClose : PlcClose))
{
_closeFut.OnDone(null, null);
_rwLock.EnterWriteLock();
try
{
base.Dispose(true);
if (_rcv != null)
Marshaller.Ignite.HandleRegistry.Release(_rcvHnd);
_closedEvt.Set();
}
finally
{
_rwLock.ExitWriteLock();
}
Marshaller.Ignite.HandleRegistry.Release(_hnd);
break;
}
}
}
/** <inheritDoc /> */
public IDataStreamer<TK1, TV1> WithKeepBinary<TK1, TV1>()
{
if (_keepBinary)
{
var result = this as IDataStreamer<TK1, TV1>;
if (result == null)
throw new InvalidOperationException(
"Can't change type of binary streamer. WithKeepBinary has been called on an instance of " +
"binary streamer with incompatible generic arguments.");
return result;
}
return Marshaller.Ignite.GetDataStreamer<TK1, TV1>(_cacheName, true);
}
/** <inheritDoc /> */
public TimeSpan Timeout
{
get
{
_rwLock.EnterReadLock();
try
{
ThrowIfDisposed();
return BinaryUtils.LongToTimeSpan(DoOutInOp(OpGetTimeout));
}
finally
{
_rwLock.ExitReadLock();
}
}
set
{
_rwLock.EnterWriteLock();
try
{
ThrowIfDisposed();
DoOutInOp(OpSetTimeout, (long) value.TotalMilliseconds);
}
finally
{
_rwLock.ExitWriteLock();
}
}
}
/** <inheritDoc /> */
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
protected override void Dispose(bool disposing)
{
if (disposing)
Close(false); // Normal dispose: do not cancel
else
{
// Finalizer: just close Java streamer
try
{
if (_batch != null)
_batch.Send(this, PlcCancelClose);
}
// ReSharper disable once EmptyGeneralCatchClause
catch (Exception)
{
// Finalizers should never throw
}
Marshaller.Ignite.HandleRegistry.Release(_hnd, true);
Marshaller.Ignite.HandleRegistry.Release(_rcvHnd, true);
}
base.Dispose(false);
}
/** <inheritDoc /> */
~DataStreamerImpl()
{
Dispose(false);
}
/** <inheritDoc /> */
public void TopologyChange(long topVer, int topSize)
{
_rwLock.EnterWriteLock();
try
{
ThrowIfDisposed();
if (_topVer < topVer)
{
_topVer = topVer;
_topSize = topSize > 0 ? topSize : 1; // Do not set to 0 to avoid 0 buffer size.
_bufSndSize = (int) (_topSize * DoOutInOp(OpPerNodeBufferSize));
}
}
finally
{
_rwLock.ExitWriteLock();
}
}
/// <summary>
/// Internal add/remove routine.
/// </summary>
/// <param name="val">Value.</param>
/// <param name="cnt">Items count.</param>
/// <returns>Future.</returns>
private Task Add0(object val, int cnt)
{
int bufSndSize0 = _bufSndSize;
Debug.Assert(bufSndSize0 > 0);
while (true)
{
var batch0 = _batch;
if (batch0 == null)
throw new InvalidOperationException("Data streamer is stopped.");
int size = batch0.Add(val, cnt);
if (size == -1)
{
// Batch is blocked, perform CAS.
Interlocked.CompareExchange(ref _batch,
new DataStreamerBatch<TK, TV>(batch0), batch0);
continue;
}
if (size >= bufSndSize0)
// Batch is too big, schedule flush.
Flush0(batch0, false, PlcContinue);
return batch0.Task;
}
}
/// <summary>
/// Internal flush routine.
/// </summary>
/// <param name="curBatch"></param>
/// <param name="wait">Whether to wait for flush to complete.</param>
/// <param name="plc">Whether this is the last batch.</param>
/// <returns>Whether this call was able to CAS previous batch</returns>
private bool Flush0(DataStreamerBatch<TK, TV> curBatch, bool wait, int plc)
{
// 1. Try setting new current batch to help further adders.
bool res = Interlocked.CompareExchange(ref _batch,
(plc == PlcContinue || plc == PlcFlush) ?
new DataStreamerBatch<TK, TV>(curBatch) : null, curBatch) == curBatch;
// 2. Perform actual send.
Debug.Assert(curBatch != null, "curBatch != null");
curBatch.Send(this, plc);
if (wait)
// 3. Wait for all futures to finish.
curBatch.AwaitCompletion();
return res;
}
/// <summary>
/// Start write.
/// </summary>
/// <returns>Writer.</returns>
internal void Update(Action<BinaryWriter> action)
{
_rwLock.EnterReadLock();
try
{
ThrowIfDisposed();
DoOutOp(OpUpdate, action);
}
finally
{
_rwLock.ExitReadLock();
}
}
/// <summary>
/// Flusher.
/// </summary>
private class Flusher<TK1, TV1>
{
/** State: running. */
private const int StateRunning = 0;
/** State: stopping. */
private const int StateStopping = 1;
/** State: stopped. */
private const int StateStopped = 2;
/** Data streamer. */
[SuppressMessage("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields",
Justification = "Incorrect warning")]
private readonly WeakReference _ldrRef;
/** Finish flag. */
[SuppressMessage("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields",
Justification = "Incorrect warning")]
private int _state;
/** Flush frequency. */
[SuppressMessage("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields",
Justification = "Incorrect warning")]
private long _freq;
/// <summary>
/// Constructor.
/// </summary>
/// <param name="ldrRef">Data streamer weak reference..</param>
public Flusher(WeakReference ldrRef)
{
_ldrRef = ldrRef;
lock (this)
{
_state = StateRunning;
}
}
/// <summary>
/// Main flusher routine.
/// </summary>
private void Run()
{
bool force = false;
long curFreq = 0;
try
{
while (true)
{
if (curFreq > 0 || force)
{
var ldr = _ldrRef.Target as DataStreamerImpl<TK1, TV1>;
if (ldr == null)
return;
ldr.TryFlush();
force = false;
}
lock (this)
{
// Stop immediately.
if (_state == StateStopping)
return;
if (curFreq == _freq)
{
// Frequency is unchanged
if (curFreq == 0)
// Just wait for a second and re-try.
Monitor.Wait(this, 1000);
else
{
// Calculate remaining time.
DateTime now = DateTime.Now;
long ticks;
try
{
ticks = now.AddMilliseconds(curFreq).Ticks - now.Ticks;
if (ticks > int.MaxValue)
ticks = int.MaxValue;
}
catch (ArgumentOutOfRangeException)
{
// Handle possible overflow.
ticks = int.MaxValue;
}
Monitor.Wait(this, TimeSpan.FromTicks(ticks));
}
}
else
{
if (curFreq != 0)
force = true;
curFreq = _freq;
}
}
}
}
finally
{
// Let streamer know about stop.
lock (this)
{
_state = StateStopped;
Monitor.PulseAll(this);
}
}
}
/// <summary>
/// Frequency.
/// </summary>
public long Frequency
{
get
{
return Interlocked.Read(ref _freq);
}
set
{
lock (this)
{
if (_freq != value)
{
_freq = value;
Monitor.PulseAll(this);
}
}
}
}
/// <summary>
/// Stop flusher.
/// </summary>
public void Stop()
{
lock (this)
{
if (_state == StateRunning)
{
_state = StateStopping;
Monitor.PulseAll(this);
}
while (_state != StateStopped)
Monitor.Wait(this);
}
}
/// <summary>
/// Runs the flusher thread.
/// </summary>
public void RunThread()
{
TaskRunner.Run(Run);
}
}
#pragma warning restore 0420
}
}
| |
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Copyright (c) Microsoft Corporation. All rights reserved.
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
using System;
namespace Microsoft.Zelig.Test
{
public class BoxingTests : TestBase, ITestInterface
{
[SetUp]
public InitializeResult Initialize()
{
Log.Comment("Adding set up for the tests.");
Log.Comment("The Boxing tests determine if a type's data can survive being stored in");
Log.Comment("an object and then re-cast as their original type.");
Log.Comment("The tests are named for the type they test.");
// Add your functionality here.
return InitializeResult.ReadyToGo;
}
[TearDown]
public void CleanUp()
{
Log.Comment("Cleaning up after the tests");
}
public override TestResult Run( string[] args )
{
TestResult result = TestResult.Pass;
result |= Assert.CheckFailed( Boxingbyte_Test( ) );
result |= Assert.CheckFailed( Boxingchar_Test( ) );
result |= Assert.CheckFailed( Boxingdouble_Test( ) );
result |= Assert.CheckFailed( Boxingfloat_Test( ) );
result |= Assert.CheckFailed( Boxingint_Test( ) );
result |= Assert.CheckFailed( Boxinglong_Test( ) );
result |= Assert.CheckFailed( Boxingsbyte_Test( ) );
result |= Assert.CheckFailed( Boxingshort_Test( ) );
result |= Assert.CheckFailed( Boxinguint_Test( ) );
result |= Assert.CheckFailed( Boxingulong_Test( ) );
result |= Assert.CheckFailed( Boxingushort_Test( ) );
result |= Assert.CheckFailed( Boxingstruct_to_ValType_Test( ) );
result |= Assert.CheckFailed( BoxingValType_to_struct_Test( ) );
return result;
}
//Boxing Test methods
//The following tests were ported from folder current\test\cases\client\CLR\Conformance\10_classes\Boxing
//byte,char,double,float,int,long,sbyte,short,uint,ulong,ushort,struct_to_ValType,ValType_to_struct
//Test Case Calls
[TestMethod]
public TestResult Boxingbyte_Test()
{
if (BoxingTestClassbyte.testMethod())
{
return TestResult.Pass;
}
return TestResult.Fail;
}
[TestMethod]
public TestResult Boxingchar_Test()
{
if (BoxingTestClasschar.testMethod())
{
return TestResult.Pass;
}
return TestResult.Fail;
}
[TestMethod]
public TestResult Boxingdouble_Test()
{
if (BoxingTestClassdouble.testMethod())
{
return TestResult.Pass;
}
return TestResult.Fail;
}
[TestMethod]
public TestResult Boxingfloat_Test()
{
if (BoxingTestClassfloat.testMethod())
{
return TestResult.Pass;
}
return TestResult.Fail;
}
[TestMethod]
public TestResult Boxingint_Test()
{
if (BoxingTestClassint.testMethod())
{
return TestResult.Pass;
}
return TestResult.Fail;
}
[TestMethod]
public TestResult Boxinglong_Test()
{
if (BoxingTestClasslong.testMethod())
{
return TestResult.Pass;
}
return TestResult.Fail;
}
[TestMethod]
public TestResult Boxingsbyte_Test()
{
if (BoxingTestClasssbyte.testMethod())
{
return TestResult.Pass;
}
return TestResult.Fail;
}
[TestMethod]
public TestResult Boxingshort_Test()
{
if (BoxingTestClassshort.testMethod())
{
return TestResult.Pass;
}
return TestResult.Fail;
}
[TestMethod]
public TestResult Boxinguint_Test()
{
if (BoxingTestClassuint.testMethod())
{
return TestResult.Pass;
}
return TestResult.Fail;
}
[TestMethod]
public TestResult Boxingulong_Test()
{
if (BoxingTestClassulong.testMethod())
{
return TestResult.Pass;
}
return TestResult.Fail;
}
[TestMethod]
public TestResult Boxingushort_Test()
{
if (BoxingTestClassushort.testMethod())
{
return TestResult.Pass;
}
return TestResult.Fail;
}
[TestMethod]
public TestResult Boxingstruct_to_ValType_Test()
{
if (BoxingTestClassStruct_to_ValType.testMethod())
{
return TestResult.Pass;
}
return TestResult.Fail;
}
[TestMethod]
public TestResult BoxingValType_to_struct_Test()
{
if (BoxingTestClassValType_to_struct.testMethod())
{
return TestResult.Pass;
}
return TestResult.Fail;
}
//Compiled Test Cases
public class BoxingTestClassbyte
{
public static bool testMethod()
{
byte value = 1;
object obj;
obj = value; // box
byte value2;
value2 = (byte) obj; // unbox
if (value2 == value)
return true;
else
return false;
}
}
public class BoxingTestClasschar
{
public static bool testMethod()
{
char value = '\x1';
object obj;
obj = value; // box
char value2;
value2 = (char) obj; // unbox
if (value2 == value)
return true;
else
return false;
}
}
public class BoxingTestClassdouble
{
public static bool testMethod()
{
double value = 1.0;
object obj;
obj = value; // box
double value2;
value2 = (double) obj; // unbox
if (value2 == value)
return true;
else
return false;
}
}
public class BoxingTestClassfloat
{
public static bool testMethod()
{
float value = 1F;
object obj;
obj = value; // box
float value2;
value2 = (float) obj; // unbox
if (value2 == value)
return true;
else
return false;
}
}
public class BoxingTestClassint
{
public static bool testMethod()
{
int value = 1;
object obj;
obj = value; // box
int value2;
value2 = (int) obj; // unbox
if (value2 == value)
return true;
else
return false;
}
}
public class BoxingTestClasslong
{
public static bool testMethod()
{
long value = 1;
object obj;
obj = value; // box
long value2;
value2 = (long) obj; // unbox
if (value2 == value)
return true;
else
return false;
}
}
public class BoxingTestClasssbyte
{
public static bool testMethod()
{
sbyte value = 1;
object obj;
obj = value; // box
sbyte value2;
value2 = (sbyte) obj; // unbox
if (value2 == value)
return true;
else
return false;
}
}
public class BoxingTestClassshort
{
public static bool testMethod()
{
short value = 1;
object obj;
obj = value; // box
short value2;
value2 = (short) obj; // unbox
if (value2 == value)
return true;
else
return false;
}
}
public class BoxingTestClassuint
{
public static bool testMethod()
{
uint value = 1;
object obj;
obj = value; // box
uint value2;
value2 = (uint) obj; // unbox
if (value2 == value)
return true;
else
return false;
}
}
public class BoxingTestClassulong
{
public static bool testMethod()
{
ulong value = 1;
object obj;
obj = value; // box
ulong value2;
value2 = (ulong) obj; // unbox
if (value2 == value)
return true;
else
return false;
}
}
public class BoxingTestClassushort
{
public static bool testMethod()
{
ushort value = 1;
object obj;
obj = value; // box
ushort value2;
value2 = (ushort) obj; // unbox
if (value2 == value)
return true;
else
return false;
}
}
struct BoxingTestClassStruct_to_ValTypeTest_struct { }
class BoxingTestClassStruct_to_ValType
{
public static bool testMethod()
{
BoxingTestClassStruct_to_ValTypeTest_struct src = new BoxingTestClassStruct_to_ValTypeTest_struct();
System.ValueType dst = src;
return true;
}
}
struct BoxingTestClassValType_to_struct_struct { }
class BoxingTestClassValType_to_struct
{
public static bool testMethod()
{
System.ValueType src = new BoxingTestClassValType_to_struct_struct();
BoxingTestClassValType_to_struct_struct dst = (BoxingTestClassValType_to_struct_struct) src;
return true;
}
}
}
}
| |
using UnityEngine;
using System.Collections;
using System.Runtime.InteropServices;
using System.IO;
using System;
//Dive Head Tracking
// copyright by Shoogee GmbH & Co. KG Refer to LICENCE.txt
//[ExecuteInEditMode]
public class OpenDiveSensor : MonoBehaviour {
// This is used for rotating the camera with another object
//for example tilting the camera while going along a racetrack or rollercoaster
public bool add_rotation_gameobject=false;
public GameObject rotation_gameobject;
// mouse emulation
public bool emulateMouseInEditor=true;
public enum RotationAxes { MouseXAndY = 0, MouseX = 1, MouseY = 2 }
public RotationAxes axes = RotationAxes.MouseXAndY;
public Texture nogyrotexture;
/// Offset projection for 2 cameras in VR
private float offset =0.0f;
private float max_offset=0.002f;
//public float max_offcenter_warp=0.1f;
public Camera cameraleft;
public Camera cameraright;
public float zoom=0.1f;
private float IPDCorrection=0.0f;
private float aspectRatio;
public float znear=0.1f;
public float zfar=10000.0f;
private float time_since_last_fullscreen=0;
private int is_tablet;
AndroidJavaObject mConfig;
AndroidJavaObject mWindowManager;
private float q0,q1,q2,q3;
private float m0,m1,m2;
Quaternion rot;
private bool show_gyro_error_message=false;
string errormessage;
#if UNITY_EDITOR
private float sensitivityX = 15F;
private float sensitivityY = 15F;
private float minimumX = -360F;
private float maximumX = 360F;
private float minimumY = -90F;
private float maximumY = 90F;
float rotationY = 0F;
#elif UNITY_ANDROID
private static AndroidJavaClass javadivepluginclass;
private static AndroidJavaClass javaunityplayerclass;
private static AndroidJavaObject currentactivity;
private static AndroidJavaObject javadiveplugininstance;
[DllImport("divesensor")] private static extern void initialize_sensors();
[DllImport("divesensor")] private static extern int get_q(ref float q0,ref float q1,ref float q2,ref float q3);
[DllImport("divesensor")] private static extern int get_m(ref float m0,ref float m1,ref float m2);
[DllImport("divesensor")] private static extern int get_error();
[DllImport("divesensor")] private static extern void dive_command(string command);
#elif UNITY_IPHONE
[DllImport("__Internal")] private static extern void initialize_sensors();
[DllImport("__Internal")] private static extern float get_q0();
[DllImport("__Internal")] private static extern float get_q1();
[DllImport("__Internal")] private static extern float get_q2();
[DllImport("__Internal")] private static extern float get_q3();
[DllImport("__Internal")] private static extern void DiveUpdateGyroData();
[DllImport("__Internal")] private static extern int get_q(ref float q0,ref float q1,ref float q2,ref float q3);
#endif
public static void divecommand(string command){
#if UNITY_EDITOR
#elif UNITY_ANDROID
dive_command(command);
#elif UNITY_IPHONE
#endif
}
public static void setFullscreen(){
#if UNITY_EDITOR
#elif UNITY_ANDROID
String answer;
answer= javadiveplugininstance.Call<string>("setFullscreen");
#elif UNITY_IPHONE
#endif
return;
}
void Start () {
rot=Quaternion.identity;
// Disable screen dimming
Screen.sleepTimeout = SleepTimeout.NeverSleep;
Application.targetFrameRate = 60;
#if UNITY_EDITOR
if (rigidbody)
rigidbody.freezeRotation = true;
#elif UNITY_ANDROID
// Java part
javadivepluginclass = new AndroidJavaClass("com.shoogee.divejava.divejava") ;
javaunityplayerclass= new AndroidJavaClass("com.unity3d.player.UnityPlayer");
currentactivity = javaunityplayerclass.GetStatic<AndroidJavaObject>("currentActivity");
javadiveplugininstance = javadivepluginclass.CallStatic<AndroidJavaObject>("instance");
object[] args={currentactivity};
javadiveplugininstance.Call<string>("set_activity",args);
initialize_sensors ();
String answer;
answer= javadiveplugininstance.Call<string>("initializeDive");
answer= javadiveplugininstance.Call<string>("getDeviceType");
if (answer=="Tablet"){
is_tablet=1;
Debug.Log("Dive Unity Tablet Mode activated");
}
else{
Debug.Log("Dive Phone Mode activated "+answer);
}
answer= javadiveplugininstance.Call<string>("setFullscreen");
show_gyro_error_message=true;
Network.logLevel = NetworkLogLevel.Full;
int err = get_error();
if (err==0){ errormessage="";
show_gyro_error_message=false;
}
if (err==1){
show_gyro_error_message=true;
errormessage="ERROR: Dive needs a Gyroscope and your telephone has none, we are trying to go to Accelerometer compatibility mode. Dont expect too much.";
}
#elif UNITY_IPHONE
initialize_sensors();
#endif
float tabletcorrection=-0.028f;
//is_tablet=0;
if (is_tablet==1)
{
Debug.Log ("Is tablet, using tabletcorrection");
IPDCorrection=tabletcorrection;
}
else
{
IPDCorrection=IPDCorrection;
}
//setIPDCorrection(IPDCorrection);
}
void Update () {
aspectRatio=(Screen.height*2.0f)/Screen.width;
setIPDCorrection(IPDCorrection);
//Debug.Log ("Divecamera"+cameraleft.aspect+"1/asp "+1/cameraleft.aspect+" Screen Width/Height "+ aspectRatio);
#if UNITY_EDITOR
#elif UNITY_ANDROID
time_since_last_fullscreen+=Time.deltaTime;
if (time_since_last_fullscreen >8){
setFullscreen ();
time_since_last_fullscreen=0;
}
get_q(ref q0,ref q1,ref q2,ref q3);
//get_m(ref m0,ref m1,ref m2);
rot.x=-q2;rot.y=q3;rot.z=-q1;rot.w=q0;
if (add_rotation_gameobject){
transform.rotation =rotation_gameobject.transform.rotation* rot;
}
else
{
transform.rotation = rot;
if (is_tablet==1)transform.rotation=rot*Quaternion.AngleAxis(90,Vector3.forward);
}
#elif UNITY_IPHONE
DiveUpdateGyroData();
get_q(ref q0,ref q1,ref q2,ref q3);
rot.x=-q2;
rot.y=q3;
rot.z=-q1;
rot.w=q0;
transform.rotation = rot;
if (add_rotation_gameobject){
transform.rotation =rotation_gameobject.transform.rotation* rot;
}
else
{
transform.rotation = rot;
if (is_tablet==1)transform.rotation=rot*Quaternion.AngleAxis(90,Vector3.forward);
}
#endif
#if UNITY_EDITOR
if (emulateMouseInEditor){
if (axes == RotationAxes.MouseXAndY)
{
float rotationX = transform.localEulerAngles.y + Input.GetAxis("Mouse X") * sensitivityX;
rotationY += Input.GetAxis("Mouse Y") * sensitivityY;
rotationY = Mathf.Clamp (rotationY, minimumY, maximumY);
transform.localEulerAngles = new Vector3(-rotationY, rotationX, 0);
}
else if (axes == RotationAxes.MouseX)
{
transform.Rotate(0, Input.GetAxis("Mouse X") * sensitivityX, 0);
}
else
{
rotationY += Input.GetAxis("Mouse Y") * sensitivityY;
rotationY = Mathf.Clamp (rotationY, minimumY, maximumY);
transform.localEulerAngles = new Vector3(-rotationY, transform.localEulerAngles.y, 0);
}
}
#endif
}
void OnGUI ()
{
/* if (GUI.Button(new Rect(Screen.width/4-150, Screen.height-100, 300,100), "+IPD")){
Debug.Log("Clicked the button with an image");
IPDCorrection=IPDCorrection+0.01f;
setIPDCorrection(IPDCorrection);
}
if (GUI.Button(new Rect(Screen.width-Screen.width/4-150, Screen.height-100, 300,100), "-IPD")){
Debug.Log("Clicked the button with an image");
IPDCorrection=IPDCorrection-0.01f;
setIPDCorrection(IPDCorrection);
}
*/
if (show_gyro_error_message)
{
if(GUI.Button(new Rect(0,0, Screen.width, Screen.height) , "Error: \n\n No Gyro detected \n \n Touch screen to continue anyway")) {
show_gyro_error_message=false;
}
GUI.DrawTexture(new Rect(Screen.width/2-320, Screen.height/2-240, 640, 480), nogyrotexture, ScaleMode.ScaleToFit, true, 0);
return;
}
}
void setIPDCorrection(float correction) {
// not using camera nearclipplane value because that leads to problems with field of view in different projects
cameraleft.projectionMatrix = PerspectiveOffCenter((-zoom+correction)*(znear/0.1f), (zoom+correction)*(znear/0.1f), -zoom*(znear/0.1f)*aspectRatio, zoom*(znear/0.1f)*aspectRatio, znear, zfar);;
cameraright.projectionMatrix = PerspectiveOffCenter((-zoom-correction)*(znear/0.1f), (zoom-correction)*(znear/0.1f), -zoom*(znear/0.1f)*aspectRatio, zoom*(znear/0.1f)*aspectRatio, znear, zfar);;
}
static Matrix4x4 PerspectiveOffCenter(float left, float right, float bottom, float top, float near, float far) {
float x = 2.0F * near / (right - left);
float y = 2.0F * near / (top - bottom);
float a = (right + left) / (right - left);
float b = (top + bottom) / (top - bottom);
float c = -(far + near) / (far - near);
float d = -(2.0F * far * near) / (far - near);
float e = -1.0F;
Matrix4x4 m = new Matrix4x4();
m[0, 0] = x;
m[0, 1] = 0;
m[0, 2] = a;
m[0, 3] = 0;
m[1, 0] = 0;
m[1, 1] = y;
m[1, 2] = b;
m[1, 3] = 0;
m[2, 0] = 0;
m[2, 1] = 0;
m[2, 2] = c;
m[2, 3] = d;
m[3, 0] = 0;
m[3, 1] = 0;
m[3, 2] = e;
m[3, 3] = 0;
return m;
}
}
| |
using System;
using System.Drawing;
using System.Runtime.InteropServices;
using System.Windows.Forms;
namespace GuiLabs.Utils
{
[CLSCompliant(false)]
public static class API
{
#region GDI
#region Bitmaps
[DllImport("gdi32", CharSet = CharSet.Ansi, SetLastError = true, ExactSpelling = true)]
public static extern bool BitBlt(IntPtr hDestDC, int X, int Y, int nWidth, int nHeight, IntPtr hSrcDC, int xSrc, int ySrc, int dwRop);
[DllImport("gdi32", CharSet = CharSet.Ansi, SetLastError = true, ExactSpelling = true)]
public static extern int StretchBlt(IntPtr hDC, int X, int Y, int nWidth, int nHeight, int hSrcDC, int xSrc, int ySrc, int nSrcWidth, int nSrcHeight, int dwRop);
[DllImport("msimg32", CharSet = CharSet.Ansi, SetLastError = true, ExactSpelling = true)]
public static extern bool TransparentBlt(
IntPtr hDestDC,
int X,
int Y,
int nWidth,
int nHeight,
IntPtr hSrcDC,
int xSrc,
int ySrc,
int nWidthSrc,
int nHeightSrc,
int nTransparentColor);
[DllImport("gdi32", CharSet = CharSet.Ansi, SetLastError = true, ExactSpelling = true)]
public static extern IntPtr CreateCompatibleBitmap(IntPtr hDC, int nWidth, int nHeight);
#endregion
#region DC
[DllImport("user32", CharSet = CharSet.Ansi, SetLastError = true, ExactSpelling = true)]
public static extern IntPtr GetWindowDC(IntPtr hWnd);
[DllImport("user32", CharSet = CharSet.Ansi, SetLastError = true, ExactSpelling = true)]
public static extern IntPtr GetDC(IntPtr hWnd);
[DllImport("user32", CharSet = CharSet.Ansi, SetLastError = true, ExactSpelling = true)]
public static extern IntPtr ReleaseDC(IntPtr hWnd, IntPtr hDC);
[DllImport("gdi32", CharSet = CharSet.Ansi, SetLastError = true, ExactSpelling = true)]
public static extern IntPtr CreateCompatibleDC(IntPtr hDC);
[DllImport("gdi32", CharSet = CharSet.Ansi, SetLastError = true, ExactSpelling = true)]
public static extern int DeleteDC(IntPtr hDC);
#endregion
#region Objects
[DllImport("gdi32", CharSet = CharSet.Ansi, SetLastError = true, ExactSpelling = true)]
public static extern IntPtr SelectObject(IntPtr hDC, IntPtr hObject);
[DllImport("gdi32", CharSet = CharSet.Ansi, SetLastError = true, ExactSpelling = true)]
public static extern int DeleteObject(IntPtr hObject);
public const int WHITE_BRUSH = 0;
public const int LTGRAY_BRUSH = 1;
public const int GRAY_BRUSH = 2;
public const int DKGRAY_BRUSH = 3;
public const int BLACK_BRUSH = 4;
public const int NULL_BRUSH = 5;
public const int HOLLOW_BRUSH = NULL_BRUSH;
public const int WHITE_PEN = 6;
public const int BLACK_PEN = 7;
public const int NULL_PEN = 8;
public const int OEM_FIXED_FONT = 10;
public const int ANSI_FIXED_FONT = 11;
public const int ANSI_VAR_FONT = 12;
public const int SYSTEM_FONT = 13;
public const int DEVICE_DEFAULT_FONT = 14;
public const int DEFAULT_PALETTE = 15;
public const int SYSTEM_FIXED_FONT = 16;
public const int DEFAULT_GUI_FONT = 17;
public const int DC_BRUSH = 18;
public const int DC_PEN = 19;
[DllImport("gdi32", CharSet = CharSet.Ansi, SetLastError = true, ExactSpelling = true)]
public static extern IntPtr GetStockObject(int hObject);
[DllImport("gdi32", CharSet = CharSet.Unicode, SetLastError = true)]
public static extern IntPtr CreateFont(int nHeight, int nWidth, int nEscapement, int nOrientation, int fnWeight, int fdwItalic, int fdwUnderline, int fdwStrikeOut, int fdwCharSet, int fdwOutputPrecision, int fdwClipPrecision, int fdwQuality, int fdwPitchAndFamily, string lpszFace);
[DllImport("gdi32", CharSet = CharSet.Ansi, SetLastError = true, ExactSpelling = true)]
public static extern IntPtr CreatePen(PenStyle nPenStyle, int nWidth, int crColor);
public enum PenStyle : int
{
PS_SOLID = 0, //The pen is solid.
PS_DASH = 1, //The pen is dashed.
PS_DOT = 2, //The pen is dotted.
PS_DASHDOT = 3, //The pen has alternating dashes and dots.
PS_DASHDOTDOT = 4, //The pen has alternating dashes and double dots.
PS_NULL = 5, //The pen is invisible.
PS_INSIDEFRAME = 6
};
[DllImport("gdi32", CharSet = CharSet.Ansi, SetLastError = true, ExactSpelling = true)]
public static extern IntPtr CreateSolidBrush(int crColor);
#endregion
#region GDI Drawing
[DllImport("gdi32", CharSet = CharSet.Ansi, SetLastError = true, ExactSpelling = true)]
public static extern int SetPixelV(IntPtr hDC, int X, int Y, int crColor);
[DllImport("gdi32.dll")]
public static extern int MoveToEx(IntPtr hDC, int X, int Y, ref POINT lpPoint);
[DllImport("gdi32", CharSet = CharSet.Ansi, SetLastError = true, ExactSpelling = true)]
public static extern int LineTo(IntPtr hDC, int X, int Y);
#region Rectangle
[DllImport("user32", CharSet = CharSet.Ansi, SetLastError = true, ExactSpelling = true)]
public static extern int DrawFocusRect(IntPtr hDC, ref RECT lpRect);
[DllImport("user32", CharSet = CharSet.Ansi, SetLastError = true, ExactSpelling = true)]
public static extern int FillRect(IntPtr hDC, ref RECT lpRect, IntPtr hBrush);
public static void FillRectangle(IntPtr DC, Color Col, Rectangle r)
{
IntPtr hBrush = API.CreateSolidBrush(ColorTranslator.ToWin32(Col));
RECT rect1 = ToRECT(r);
FillRect(DC, ref rect1, hBrush);
DeleteObject(hBrush);
}
public static void FillRectangle(IntPtr dc, Color col, RECT rectStruct)
{
IntPtr hBrush = API.CreateSolidBrush(ColorTranslator.ToWin32(col));
FillRect(dc, ref rectStruct, hBrush);
DeleteObject(hBrush);
}
//public static void FillRectangle(IntPtr DC, int Col, Rect r)
//{
// IntPtr hBrush = API.CreateSolidBrush(Col);
// RECT rect1 = ToRECT(r);
// FillRect(DC, ref rect1, hBrush);
// DeleteObject(hBrush);
//}
[DllImport("gdi32", CharSet = CharSet.Ansi, SetLastError = true, ExactSpelling = true)]
public static extern int Rectangle(IntPtr hDC, int X1, int Y1, int X2, int Y2);
[DllImport("gdi32", CharSet = CharSet.Ansi, SetLastError = true, ExactSpelling = true)]
public static extern int RoundRect(IntPtr hDC, int X1, int Y1, int X2, int Y2, int X3, int Y3);
#endregion
[DllImport("gdi32", CharSet = CharSet.Ansi, SetLastError = true, ExactSpelling = true)]
public static extern int Ellipse(IntPtr hDC, int X1, int Y1, int X2, int Y2);
[DllImport("gdi32.dll")]
public static extern bool Pie(
IntPtr hDC,
int nLeftRect,
int nTopRect,
int nRightRect,
int nBottomRect,
int nXRadial1,
int nYRadial1,
int nXRadial2,
int nYRadial2);
[DllImport("gdi32", CharSet = CharSet.Ansi, SetLastError = true, ExactSpelling = true)]
public static extern int Polygon(IntPtr hDC, POINT[] lpPoint, int nCount);
#region Surface properties
[DllImport("gdi32", CharSet = CharSet.Ansi, SetLastError = true, ExactSpelling = true)]
public static extern int SetBkColor(IntPtr hDC, int crColor);
[DllImport("gdi32", CharSet = CharSet.Ansi, SetLastError = true, ExactSpelling = true)]
public static extern int SetBkMode(IntPtr hDC, int nBkMode);
[DllImport("gdi32", CharSet = CharSet.Ansi, SetLastError = true, ExactSpelling = true)]
public static extern int SetROP2(IntPtr hDC, System.Int32 nDrawMode);
#endregion
#region Text
[DllImport("user32", CharSet = CharSet.Unicode, SetLastError = true, ExactSpelling = true)]
public static extern int DrawText(IntPtr hDC, string lpStr, int nCount, ref RECT lpRect, int wFormat);
[DllImport("gdi32.dll", CharSet = CharSet.Unicode)]
//[CLSCompliant(false)]
public static extern bool ExtTextOut(IntPtr hdc, int X, int Y, uint fuOptions,
[In] ref RECT lprc, string lpString, uint cbCount, int[] lpDx);
[DllImport("gdi32.dll")]
public static extern bool GetTextExtentPoint32(
IntPtr hdc,
string lpString,
int cbString,
out SIZE lpSize);
//[DllImport("gdi32", CharSet = CharSet.Ansi, SetLastError = true, ExactSpelling = true)]
//public static extern bool GetTextExtentPoint32(IntPtr hdc, string lpString, int cbString, out SIZE lpSize);
[DllImport("gdi32", CharSet = CharSet.Ansi, SetLastError = true, ExactSpelling = true)]
public static extern int SetTextColor(IntPtr hDC, int crColor);
[DllImport("gdi32", CharSet = CharSet.Ansi, SetLastError = true, ExactSpelling = true)]
public static extern int TextOut(int hDC, int X, int Y, [MarshalAs(UnmanagedType.VBByRefStr)] ref string lpString, int nCount);
#endregion
public const int SRCCOPY = 0xcc0020;
public static int RGB(int R, int G, int B)
{
return ((R | (G * 0x100)) | (B * 0x10000));
}
[DllImport("gdi32", CharSet = CharSet.Ansi, SetLastError = true, ExactSpelling = true)]
public static extern int GetDeviceCaps(IntPtr hDC, int nIndex);
#endregion
#region POINT RECT SIZE Structs
public static RECT ToRECT(Rectangle r)
{
RECT rect1;
rect1.Left = r.Left;
rect1.Top = r.Top;
rect1.Right = r.Right;
rect1.Bottom = r.Bottom;
return rect1;
}
[StructLayout(LayoutKind.Sequential)]
public struct RECT
{
public int Left;
public int Top;
public int Right;
public int Bottom;
}
[StructLayout(LayoutKind.Sequential)]
public struct POINT
{
public int x;
public int y;
}
[StructLayout(LayoutKind.Sequential)]
public struct SIZE
{
public int x;
public int y;
}
#endregion
#region Fonts
public enum FontWeight
{
FW_DONTCARE = 0,
FW_THIN = 100,
FW_EXTRALIGHT = 200,
FW_ULTRALIGHT = 200,
FW_LIGHT = 300,
FW_NORMAL = 400,
FW_REGULAR = 400,
FW_MEDIUM = 500,
FW_SEMIBOLD = 600,
FW_DEMIBOLD = 600,
FW_BOLD = 700,
FW_EXTRABOLD = 800,
FW_ULTRABOLD = 800,
FW_BLACK = 900,
FW_HEAVY = 900
}
public enum CHARSET
{
ANSI_CHARSET = 0,
DEFAULT_CHARSET = 1,
SYMBOL_CHARSET = 2,
SHIFTJIS_CHARSET = 128,
OEM_CHARSET = 255
}
public enum OutputPrecision
{
OUT_DEFAULT_PRECIS = 0,
OUT_STRING_PRECIS = 1,
OUT_CHARACTER_PRECIS = 2,
OUT_STROKE_PRECIS = 3,
OUT_TT_PRECIS = 4,
OUT_DEVICE_PRECIS = 5,
OUT_RASTER_PRECIS = 6,
OUT_TT_ONLY_PRECIS = 7,
OUT_OUTLINE_PRECIS = 8,
OUT_SCREEN_OUTLINE_PRECIS = 9,
OUT_PS_ONLY_PRECIS = 10
}
public enum ClipPrecision
{
CLIP_DEFAULT_PRECIS = 0,
CLIP_CHARACTER_PRECIS = 1,
CLIP_STROKE_PRECIS = 2,
CLIP_MASK = 0xf,
CLIP_LH_ANGLES = (1 << 4),
CLIP_TT_ALWAYS = (2 << 4),
CLIP_EMBEDDED = (8 << 4)
}
public enum Quality
{
DEFAULT_QUALITY = 0,
DRAFT_QUALITY = 1,
PROOF_QUALITY = 2,
NONANTIALIASED_QUALITY = 3,
ANTIALIASED_QUALITY = 4,
CLEARTYPE_QUALITY = 5,
CLEARTYPE_NATURAL_QUALITY = 6
}
public enum PitchAndFamily
{
DEFAULT_PITCH = 0,
FIXED_PITCH = 1,
VARIABLE_PITCH = 2,
MONO_FONT = 8
}
#endregion
#endregion
#region Windows
[DllImport("user32.dll")]
public static extern bool ShowWindow(IntPtr hWnd, enumShowWindow nCmdShow);
[DllImport("user32.dll")]
public static extern int SetWindowLong(IntPtr hWnd, int nIndex, int dwNewLong);
[DllImport("user32.dll")]
//[CLSCompliant(false)]
public static extern bool SetWindowPos(
IntPtr hWnd,
IntPtr hWndInsertAfter,
int X,
int Y,
int cx,
int cy,
uint uFlags);
public static readonly IntPtr HWND_TOPMOST = new IntPtr(-1);
public static readonly IntPtr HWND_NOTOPMOST = new IntPtr(-2);
public static readonly IntPtr HWND_TOP = new IntPtr(0);
public static readonly IntPtr HWND_BOTTOM = new IntPtr(1);
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = false)]
public static extern IntPtr SendMessage(IntPtr hWnd, uint Msg, int wParam, int lParam);
[DllImport("user32.dll")]
public static extern IntPtr SetParent(IntPtr hWndChild, IntPtr hWndNewParent);
[DllImport("user32", CharSet = CharSet.Ansi, SetLastError = true, ExactSpelling = true)]
public static extern IntPtr GetDesktopWindow();
public enum enumShowWindow : int
{
Hide = 0,
Normal = 1,
ShowMinimized = 2,
ShowMaximized = 3,
ShowNoActivate = 4,
Show = 5,
Minimize = 6,
ShowMinNoActive = 7,
ShowNA = 8,
Restore = 9,
ShowDefault = 10,
ForceMinimize = 11,
Max = 11
}
[DllImport("user32.dll")]
public static extern bool LockWindowUpdate(IntPtr hwndLock);
public const UInt32 WM_SETREDRAW = 0x000B;
public const UInt32 WM_VSCROLL = 0x0115;
public const UInt32 WM_ERASEBKGND = 0x0014;
public const UInt32 WM_MOUSEWHEEL = 0x020A;
public const UInt32 WM_KEYDOWN = 0x0100;
internal static void SetRedraw(IntPtr hWnd, bool shouldRedraw)
{
if (hWnd == IntPtr.Zero)
{
return;
}
SendMessage(hWnd, WM_SETREDRAW, shouldRedraw ? 1 : 0, 0);
}
public static void SetRedraw(Control control, bool shouldRedraw)
{
if (control == null || !control.IsHandleCreated || control.Handle == IntPtr.Zero)
{
return;
}
SetRedraw(control.Handle, shouldRedraw);
}
public const int SPI_SETDESKWALLPAPER = 0X14;
public const int SPIF_UPDATEINIFILE = 0X1;
public const int SPIF_SENDWININICHANGE = 0X2;
[DllImport("USER32.DLL", EntryPoint = "SystemParametersInfo", SetLastError = true)]
public static extern int SystemParametersInfo(int uAction, int uParam, string lpvParam, int fuWinIni);
public static void SetDesktopWallpaper(string fileName)
{
SystemParametersInfo(
SPI_SETDESKWALLPAPER,
0,
fileName,
SPIF_UPDATEINIFILE | SPIF_SENDWININICHANGE);
}
#endregion
#region Misc
[DllImport("kernel32", CharSet = CharSet.Ansi, SetLastError = true, ExactSpelling = true)]
public static extern int MulDiv(int nNumber, int nNumerator, int nDenominator);
#region Timers
public static long Ticks()
{
long num1 = 0;
QueryPerformanceCounter(ref num1);
return num1;
}
public static double Milliseconds()
{
return Ticks() / PerformanceCounterFrequency() * 1000;
}
[DllImport("WinMM.dll", CharSet = CharSet.Ansi, SetLastError = true, ExactSpelling = true)]
public static extern int timeGetTime();
public static long PerformanceCounterFrequency()
{
long num2 = 0;
QueryPerformanceFrequency(ref num2);
return num2;
}
[DllImport("kernel32", CharSet = CharSet.Ansi, SetLastError = true, ExactSpelling = true)]
public static extern int QueryPerformanceCounter(ref long PC);
[DllImport("kernel32", CharSet = CharSet.Ansi, SetLastError = true, ExactSpelling = true)]
public static extern int QueryPerformanceFrequency(ref long PC);
#endregion
#endregion
}
}
| |
// Copyright 2005-2010 Gallio Project - http://www.gallio.org/
// Portions Copyright 2000-2004 Jonathan de Halleux
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using Gallio.Common.IO;
using Gallio.Icarus.Controllers;
using Gallio.Icarus.Controllers.EventArgs;
using Gallio.Icarus.Events;
using Gallio.Icarus.Models;
using Gallio.Icarus.Properties;
using Gallio.Icarus.Remoting;
using Gallio.Icarus.Tests.Utilities;
using Gallio.Model.Filters;
using Gallio.Runner.Projects;
using Gallio.Runner.Projects.Schema;
using Gallio.Runtime.ProgressMonitoring;
using Gallio.UI.Common.Policies;
using Gallio.UI.Events;
using MbUnit.Framework;
using Rhino.Mocks;
using System;
using Path = System.IO.Path;
namespace Gallio.Icarus.Tests.Controllers
{
[Category("Controllers"), Author("Graham Hay"), TestsOn(typeof(ProjectController))]
public class ProjectControllerTest
{
private ProjectController projectController;
private IProjectTreeModel projectTreeModel;
private IFileSystem fileSystem;
private IFileWatcher fileWatcher;
private IUnhandledExceptionPolicy unhandledExceptionPolicy;
private IEventAggregator eventAggregator;
private ITestProjectManager testProjectManager;
[SetUp]
public void SetUp()
{
projectTreeModel = MockRepository.GenerateStub<IProjectTreeModel>();
fileSystem = MockRepository.GenerateStub<IFileSystem>();
fileWatcher = MockRepository.GenerateStub<IFileWatcher>();
unhandledExceptionPolicy = MockRepository.GenerateStub<IUnhandledExceptionPolicy>();
eventAggregator = MockRepository.GenerateStub<IEventAggregator>();
testProjectManager = MockRepository.GenerateStub<ITestProjectManager>();
projectController = new ProjectController(projectTreeModel, eventAggregator, fileSystem, fileWatcher,
unhandledExceptionPolicy, testProjectManager);
}
[Test]
public void AddFiles_Test()
{
TestProject testProject = new TestProject();
projectTreeModel.TestProject = testProject;
string fileName = Assembly.GetExecutingAssembly().Location;
List<string> list = new List<string>(new[] { fileName });
fileSystem.Stub(fs => fs.FileExists(fileName)).Return(true);
var progressMonitor = MockProgressMonitor.Instance;
Assert.Count(0, projectController.TestPackage.Files);
projectController.AddFiles(progressMonitor, list);
Assert.Count(1, projectController.TestPackage.Files);
Assert.AreEqual(fileName, projectController.TestPackage.Files[0].ToString());
}
[Test]
public void DeleteFilter_Test()
{
var testProject = new TestProject();
projectTreeModel.TestProject = testProject;
var progressMonitor = MockProgressMonitor.Instance;
Assert.Count(0, projectController.TestFilters.Value);
FilterInfo filterInfo = new FilterInfo("filterName", new NoneFilter<ITestDescriptor>().ToFilterExpr());
projectController.TestFilters.Value.Add(filterInfo);
Assert.Count(1, projectController.TestFilters.Value);
projectController.DeleteFilter(progressMonitor, filterInfo);
Assert.Count(0, projectController.TestFilters.Value);
}
[Test]
public void Model_Test()
{
Assert.AreEqual(projectTreeModel, projectController.Model);
}
[Test]
public void TestPackage_Test()
{
var testProject = new TestProject();
projectTreeModel.TestProject = testProject;
Assert.AreEqual(testProject.TestPackage, projectController.TestPackage);
}
[Test]
public void TestFilters_Test()
{
Assert.Count(0, projectController.TestFilters.Value);
}
[Test]
public void ProjectFileName_Test()
{
const string fileName = "fileName";
projectTreeModel.FileName = fileName;
Assert.AreEqual(fileName, projectController.ProjectFileName);
}
[Test]
public void New_project_creates_the_default_project()
{
testProjectManager.Stub(tpm => tpm.NewProject(Arg<string>.Is.Anything))
.Return(new TestProject());
projectController.NewProject(MockProgressMonitor.Instance);
testProjectManager.AssertWasCalled(tpm => tpm.NewProject(Paths.DefaultProject));
}
[Test]
public void RemoveAllFiles_Test()
{
projectTreeModel.TestProject = new TestProject();
projectController.RemoveAllFiles();
}
[Test]
public void RemoveFile_Test()
{
var project = new TestProject();
string fileName = Path.GetFullPath("test");
project.TestPackage.AddFile(new FileInfo(fileName));
projectTreeModel.TestProject = project;
Assert.Count(1, project.TestPackage.Files);
projectController.RemoveFile(fileName);
Assert.Count(0, project.TestPackage.Files);
}
[Test]
public void SaveFilter_Test()
{
projectTreeModel.TestProject = new TestProject();
Assert.Count(0, projectController.TestFilters.Value);
projectController.SaveFilterSet("filterName", new FilterSet<ITestDescriptor>(new NoneFilter<ITestDescriptor>()));
Assert.Count(1, projectController.TestFilters.Value);
projectController.SaveFilterSet("filterName", new FilterSet<ITestDescriptor>(new NoneFilter<ITestDescriptor>()));
Assert.Count(1, projectController.TestFilters.Value);
projectController.SaveFilterSet("aDifferentFilterName", new FilterSet<ITestDescriptor>(new NoneFilter<ITestDescriptor>()));
Assert.Count(2, projectController.TestFilters.Value);
}
[Test]
public void Save_should_announce_before_saving_the_project()
{
using (eventAggregator.GetMockRepository().Ordered())
{
eventAggregator.Expect(ea => ea.Send(Arg.Is(projectController), Arg<SavingProject>.Is.Anything));
testProjectManager.Expect(tpm => tpm.SaveProject(Arg<TestProject>.Is.Anything,
Arg<FileInfo>.Is.Anything));
}
eventAggregator.Replay();
projectController.Save("projectName", NullProgressMonitor.CreateInstance());
eventAggregator.VerifyAllExpectations();
}
[Test]
public void Save_should_save_the_project()
{
var testProject = new TestProject();
projectTreeModel.TestProject = testProject;
const string projectName = "projectName";
projectController.Save(projectName, NullProgressMonitor.CreateInstance());
testProjectManager.AssertWasCalled(tpm => tpm.SaveProject(Arg.Is(testProject),
Arg<FileInfo>.Matches(fi => fi.Name == projectName)));
}
[Test]
public void An_event_should_be_sent_when_the_project_is_saved()
{
const string projectLocation = "projectLocation";
projectController.Save(projectLocation, NullProgressMonitor.CreateInstance());
eventAggregator.Expect(ea => ea.Send(Arg.Is(projectController), Arg<ProjectSaved>.Matches(e =>
e.ProjectLocation == projectLocation)));
}
[Test]
public void Create_directory_for_project_if_necessary()
{
var testProject = new TestProject();
projectTreeModel.TestProject = testProject;
projectTreeModel.FileName = Paths.DefaultProject;
var progressMonitor = MockProgressMonitor.Instance;
fileSystem.Stub(fs => fs.DirectoryExists(Paths.IcarusAppDataFolder))
.Return(false);
projectController.Save("", progressMonitor);
fileSystem.AssertWasCalled(fs => fs.CreateDirectory(Paths.IcarusAppDataFolder));
}
[Test]
public void Hint_directories_come_from_test_package()
{
var project = new TestProject();
projectTreeModel.TestProject = project;
var hintDirectories = projectController.HintDirectories;
Assert.AreEqual(hintDirectories, project.TestPackage.HintDirectories);
}
[Test]
public void Add_hint_directory_adds_to_test_package()
{
var project = new TestProject();
projectTreeModel.TestProject = project;
const string hintDirectory = @"c:\test";
projectController.AddHintDirectory(hintDirectory);
Assert.Count(1, project.TestPackage.HintDirectories);
Assert.AreEqual(hintDirectory, project.TestPackage.HintDirectories[0].FullName);
}
[Test]
public void Remove_hint_directory_removes_from_test_package()
{
var project = new TestProject();
projectTreeModel.TestProject = project;
const string hintDirectory = @"c:\test";
project.TestPackage.AddHintDirectory(new DirectoryInfo(hintDirectory));
projectController.RemoveHintDirectory(hintDirectory);
Assert.Count(0, project.TestPackage.HintDirectories);
}
[Test]
public void Test_runner_extension_specifications_come_from_project()
{
var project = new TestProject();
projectTreeModel.TestProject = project;
var testRunnerExtensionSpecifications = projectController.TestRunnerExtensionSpecifications;
Assert.AreEqual(testRunnerExtensionSpecifications, project.TestRunnerExtensionSpecifications);
}
[Test]
public void Add_test_runner_extension_specification_adds_to_test_package()
{
var project = new TestProject();
projectTreeModel.TestProject = project;
const string testRunnerExtensionSpecification = "testRunnerExtensionSpecification";
projectController.AddTestRunnerExtensionSpecification(testRunnerExtensionSpecification);
Assert.Count(1, project.TestRunnerExtensionSpecifications);
Assert.AreEqual(testRunnerExtensionSpecification, project.TestRunnerExtensionSpecifications[0]);
}
[Test]
public void Remove_test_runner_extension_specification_removes_from_test_package()
{
var project = new TestProject();
projectTreeModel.TestProject = project;
const string extensionSpecification = "extensionSpecification";
project.AddTestRunnerExtensionSpecification(extensionSpecification);
projectController.RemoveTestRunnerExtensionSpecification(extensionSpecification);
Assert.Count(0, project.TestRunnerExtensionSpecifications);
}
[Test]
public void FileWatcher_fires_FileChanged_event()
{
var changedFlag = false;
const string fileName = "test";
projectController.FileChanged += delegate(object sender, FileChangedEventArgs e)
{
changedFlag = true;
Assert.AreEqual(fileName, e.FileName);
};
fileWatcher.Raise(aw => aw.FileChangedEvent += null, new object[] { fileName });
Assert.AreEqual(true, changedFlag);
}
[Test]
public void Open_project_loads_the_file()
{
var projectName = Path.GetFullPath("projectName");
testProjectManager.Stub(tpm => tpm.LoadProject(Arg<FileInfo>.Is.Anything))
.Return(new TestProject());
projectController.OpenProject(MockProgressMonitor.Instance, projectName);
testProjectManager.AssertWasCalled(tpm => tpm.LoadProject(Arg<FileInfo>.Matches(fi =>
fi.FullName == projectName)));
}
[Test]
public void Opening_project_should_succeed_even_if_file_cannot_be_loaded()
{
testProjectManager.Stub(tpm => tpm.LoadProject(Arg<FileInfo>.Is.Anything))
.Throw(new Exception());
Assert.DoesNotThrow(() => projectController.OpenProject(MockProgressMonitor.Instance,
Path.GetFullPath("projectName")));
}
[Test]
public void Opening_project_should_report_any_errors_that_occur()
{
var exception = new Exception();
testProjectManager.Stub(tpm => tpm.LoadProject(Arg<FileInfo>.Is.Anything)).Throw(exception);
projectController.OpenProject(MockProgressMonitor.Instance, Path.GetFullPath("projectName"));
unhandledExceptionPolicy.AssertWasCalled(uep => uep.Report(Arg.Is(Resources.ProjectController_Error_loading_project_file),
Arg.Is(exception)));
}
}
}
| |
#region License
/*---------------------------------------------------------------------------------*\
Distributed under the terms of an MIT-style license:
The MIT License
Copyright (c) 2006-2010 Stephen M. McKamey
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 License
using System;
using System.Collections.Generic;
using System.IO;
using System.Text.RegularExpressions;
using JsonFx.EcmaScript;
using JsonFx.Markup;
using JsonFx.Model;
using JsonFx.Serialization;
namespace JsonFx.Jbst
{
/// <summary>
/// The result from compiling a template
/// </summary>
internal class CompilationState : JbstCommand
{
#region Constants
private static readonly Regex Regex_JbstName = new Regex(@"[^0-9a-zA-Z$_\.]+", RegexOptions.Compiled|RegexOptions.CultureInvariant|RegexOptions.ExplicitCapture);
#endregion Constants
#region Fields
public readonly string FilePath;
private readonly IDataTransformer<MarkupTokenType, ModelTokenType> Transformer;
private readonly EcmaScriptIdentifier DefaultNamespace;
private List<string> imports;
private JbstDeclarationBlock declarationBlock;
private IDictionary<string, IEnumerable<Token<MarkupTokenType>>> namedTemplates;
private IEnumerable<Token<MarkupTokenType>> content;
private IEnumerable<Token<ModelTokenType>> transformedContent;
#endregion Fields
#region Init
/// <summary>
/// Ctor
/// </summary>
/// <param name="filePath"></param>
public CompilationState(IDataTransformer<MarkupTokenType, ModelTokenType> transformer, string filePath, EcmaScriptIdentifier defaultNamespace)
{
this.Transformer = transformer;
this.DefaultNamespace = defaultNamespace ?? String.Empty;
this.FilePath = filePath ?? String.Empty;
}
#endregion Init
#region Properties
/// <summary>
/// Gets the command type
/// </summary>
public override JbstCommandType CommandType
{
get { return JbstCommandType.RootTemplate; }
}
public List<string> Imports
{
get
{
if (this.imports == null)
{
this.imports = new List<string>();
}
return this.imports;
}
}
public string JbstName
{
get;
set;
}
public JbstDeclarationBlock DeclarationBlock
{
get
{
if (this.declarationBlock == null)
{
this.declarationBlock = new JbstDeclarationBlock();
}
return this.declarationBlock;
}
}
public IEnumerable<Token<MarkupTokenType>> Content
{
get { return this.content; }
set
{
this.content = value;
this.transformedContent = null;
}
}
public EngineType Engine
{
get;
set;
}
#endregion Properties
#region ITextFormattable<ModelTokenType> Members
public override void Format(ITextFormatter<ModelTokenType> formatter, TextWriter writer)
{
this.EnsureName();
this.FormatGlobals(writer);
// emit namespace or variable
if (!EcmaScriptFormatter.WriteNamespaceDeclaration(writer, this.JbstName, null, true))
{
writer.Write("var ");
}
// assign to named var
writer.Write(this.JbstName);
// emit template body and wrap with ctor
writer.Write(" = JsonML.BST(");
if (this.content == null)
{
base.Format(formatter, writer);
}
else
{
var transformed = this.TransformContent();
formatter.Format(transformed, writer);
}
writer.WriteLine(");");
if (this.declarationBlock != null)
{
// emit init block
this.declarationBlock.OwnerName = this.JbstName;
this.declarationBlock.Format(formatter, writer);
}
}
public IEnumerable<Token<ModelTokenType>> TransformContent()
{
if (this.transformedContent == null &&
this.content != null)
{
this.transformedContent = this.Transformer.Transform(this.content);
}
return this.transformedContent;
}
#endregion ITextFormattable<ModelTokenType> Members
#region Named Template Methods
public void AddNamedTemplate(string name, IEnumerable<Token<MarkupTokenType>> content)
{
if (name == null)
{
name = String.Empty;
}
if (this.namedTemplates == null)
{
this.namedTemplates = new Dictionary<string, IEnumerable<Token<MarkupTokenType>>>(StringComparer.OrdinalIgnoreCase);
}
this.namedTemplates[name] = content;
}
public IEnumerable<Token<ModelTokenType>> NamedTemplates()
{
if (this.transformedContent == null &&
this.content != null)
{
this.transformedContent = this.TransformNamedTemplates();
}
return this.transformedContent;
}
private IEnumerable<Token<ModelTokenType>> TransformNamedTemplates()
{
List<Token<ModelTokenType>> templates = new List<Token<ModelTokenType>>();
templates.Add(new Token<ModelTokenType>(ModelTokenType.ObjectBegin));
if (this.Content != null)
{
templates.Add(new Token<ModelTokenType>(ModelTokenType.Property, new DataName(JbstPlaceholder.InlinePrefix)));
var output = this.Transformer.Transform(this.Content);
templates.AddRange(output);
}
if (this.namedTemplates != null)
{
foreach (var template in this.namedTemplates)
{
templates.Add(new Token<ModelTokenType>(ModelTokenType.Property, new DataName(JbstPlaceholder.InlinePrefix+template.Key)));
if (template.Value != null)
{
var output = this.Transformer.Transform(template.Value);
templates.AddRange(output);
}
}
}
templates.Add(new Token<ModelTokenType>(ModelTokenType.ObjectEnd));
return templates;
}
#endregion Named Template Methods
#region Utility Methods
public void EnsureName()
{
if (!String.IsNullOrEmpty(this.JbstName))
{
return;
}
this.JbstName = CompilationState.GenerateJbstName(this.FilePath, this.DefaultNamespace);
}
/// <summary>
/// Generates a globals list from import directives
/// </summary>
private void FormatGlobals(TextWriter writer)
{
this.Imports.Insert(0, "JsonML.BST");
bool hasGlobals = false;
foreach (string import in this.Imports)
{
string ident = EcmaScriptIdentifier.VerifyIdentifier(import, true);
if (String.IsNullOrEmpty(ident))
{
continue;
}
if (hasGlobals)
{
writer.Write(", ");
}
else
{
hasGlobals = true;
writer.Write("/*global ");
}
int dot = ident.IndexOf('.');
writer.Write((dot < 0) ? ident : ident.Substring(0, dot));
}
if (hasGlobals)
{
writer.WriteLine(" */");
}
}
private static string GenerateJbstName(string filePath, EcmaScriptIdentifier defaultNamespace)
{
if (String.IsNullOrEmpty(filePath))
{
filePath = String.Concat('$', Guid.NewGuid().ToString("n"));
}
else
{
filePath = Path.GetFileNameWithoutExtension(filePath);
filePath = Regex_JbstName.Replace(filePath, "_");
}
if (String.IsNullOrEmpty(defaultNamespace))
{
return filePath;
}
return String.Concat(defaultNamespace, '.', filePath);
}
#endregion Utility Methods
}
}
| |
using System;
using System.Collections.Generic;
using System.Composition;
using System.Composition.Hosting;
using System.IO;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.CodeAnalysis;
using Microsoft.Extensions.Configuration;
using Newtonsoft.Json;
using OmniSharp.Mef;
using OmniSharp.Middleware;
using OmniSharp.Models;
using OmniSharp.Models.FindSymbols;
using OmniSharp.Models.GotoDefinition;
using OmniSharp.Models.UpdateBuffer;
using OmniSharp.Models.WorkspaceInformation;
using OmniSharp.Options;
using OmniSharp.Services;
using OmniSharp.Utilities;
using TestUtility;
using Xunit;
using Xunit.Abstractions;
namespace OmniSharp.Tests
{
public class EndpointMiddlewareFacts : AbstractTestFixture
{
public EndpointMiddlewareFacts(ITestOutputHelper output)
: base(output)
{
}
[OmniSharpHandler(OmniSharpEndpoints.GotoDefinition, LanguageNames.CSharp)]
public class GotoDefinitionService : IRequestHandler<GotoDefinitionRequest, GotoDefinitionResponse>
{
[Import]
public OmniSharpWorkspace Workspace { get; set; }
public Task<GotoDefinitionResponse> Handle(GotoDefinitionRequest request)
{
return Task.FromResult<GotoDefinitionResponse>(null);
}
}
[OmniSharpHandler(OmniSharpEndpoints.FindSymbols, LanguageNames.CSharp)]
public class FindSymbolsService : IRequestHandler<FindSymbolsRequest, QuickFixResponse>
{
[Import]
public OmniSharpWorkspace Workspace { get; set; }
public Task<QuickFixResponse> Handle(FindSymbolsRequest request)
{
return Task.FromResult<QuickFixResponse>(null);
}
}
[OmniSharpHandler(OmniSharpEndpoints.UpdateBuffer, LanguageNames.CSharp)]
public class UpdateBufferService : IRequestHandler<UpdateBufferRequest, object>
{
[Import]
public OmniSharpWorkspace Workspace { get; set; }
public Task<object> Handle(UpdateBufferRequest request)
{
return Task.FromResult<object>(null);
}
}
class Response { }
[Export(typeof(IProjectSystem))]
class FakeProjectSystem : IProjectSystem
{
public string Key { get { return "Fake"; } }
public string Language { get { return LanguageNames.CSharp; } }
public IEnumerable<string> Extensions { get; } = new[] { ".cs" };
public Task<object> GetWorkspaceModelAsync(WorkspaceInformationRequest request)
{
throw new NotImplementedException();
}
public Task<object> GetProjectModelAsync(string path)
{
throw new NotImplementedException();
}
public void Initalize(IConfiguration configuration) { }
}
private class PlugInHost : DisposableObject
{
private readonly TestServiceProvider _serviceProvider;
public CompositionHost CompositionHost { get; }
public PlugInHost(TestServiceProvider serviceProvider, CompositionHost compositionHost)
{
this._serviceProvider = serviceProvider;
this.CompositionHost = compositionHost;
}
protected override void DisposeCore(bool disposing)
{
this._serviceProvider.Dispose();
this.CompositionHost.Dispose();
}
}
protected Assembly GetAssembly<T>()
{
return typeof(T).GetTypeInfo().Assembly;
}
private PlugInHost CreatePlugInHost(params Assembly[] assemblies)
{
var environment = new OmniSharpEnvironment();
var sharedTextWriter = new TestSharedTextWriter(this.TestOutput);
var serviceProvider = new TestServiceProvider(environment, this.LoggerFactory, sharedTextWriter);
var compositionHost = Startup.CreateCompositionHost(
serviceProvider: serviceProvider,
options: new OmniSharpOptions(),
assemblies: assemblies);
return new PlugInHost(serviceProvider, compositionHost);
}
[Fact]
public async Task Passes_through_for_invalid_path()
{
RequestDelegate _next = _ => Task.Run(() => { throw new NotImplementedException(); });
using (var host = CreatePlugInHost(GetAssembly<EndpointMiddlewareFacts>()))
{
var middleware = new EndpointMiddleware(_next, host.CompositionHost, this.LoggerFactory);
var context = new DefaultHttpContext();
context.Request.Path = PathString.FromUriComponent("/notvalid");
await Assert.ThrowsAsync<NotImplementedException>(() => middleware.Invoke(context));
}
}
[Fact]
public async Task Does_not_throw_for_valid_path()
{
RequestDelegate _next = _ => Task.Run(() => { throw new NotImplementedException(); });
using (var host = CreatePlugInHost(
GetAssembly<EndpointMiddlewareFacts>(),
GetAssembly<OmniSharpEndpointMetadata>()))
{
var middleware = new EndpointMiddleware(_next, host.CompositionHost, this.LoggerFactory);
var context = new DefaultHttpContext();
context.Request.Path = PathString.FromUriComponent("/gotodefinition");
context.Request.Body = new MemoryStream(
Encoding.UTF8.GetBytes(
JsonConvert.SerializeObject(new GotoDefinitionRequest
{
FileName = "bar.cs",
Line = 2,
Column = 14,
Timeout = 60000
})
)
);
await middleware.Invoke(context);
Assert.True(true);
}
}
[Fact]
public async Task Passes_through_to_services()
{
RequestDelegate _next = _ => Task.Run(() => { throw new NotImplementedException(); });
using (var host = CreatePlugInHost(
GetAssembly<EndpointMiddlewareFacts>(),
GetAssembly<OmniSharpEndpointMetadata>()))
{
var middleware = new EndpointMiddleware(_next, host.CompositionHost, this.LoggerFactory);
var context = new DefaultHttpContext();
context.Request.Path = PathString.FromUriComponent("/gotodefinition");
context.Request.Body = new MemoryStream(
Encoding.UTF8.GetBytes(
JsonConvert.SerializeObject(new GotoDefinitionRequest
{
FileName = "bar.cs",
Line = 2,
Column = 14,
Timeout = 60000
})
)
);
await middleware.Invoke(context);
Assert.True(true);
}
}
[Fact]
public async Task Passes_through_to_all_services_with_delegate()
{
RequestDelegate _next = _ => Task.Run(() => { throw new NotImplementedException(); });
using (var host = CreatePlugInHost(
GetAssembly<EndpointMiddlewareFacts>(),
GetAssembly<OmniSharpEndpointMetadata>()))
{
var middleware = new EndpointMiddleware(_next, host.CompositionHost, this.LoggerFactory);
var context = new DefaultHttpContext();
context.Request.Path = PathString.FromUriComponent("/findsymbols");
context.Request.Body = new MemoryStream(
Encoding.UTF8.GetBytes(
JsonConvert.SerializeObject(new FindSymbolsRequest
{
})
)
);
await middleware.Invoke(context);
Assert.True(true);
}
}
[Fact]
public async Task Passes_through_to_specific_service_with_delegate()
{
RequestDelegate _next = _ => Task.Run(() => { throw new NotImplementedException(); });
using (var host = CreatePlugInHost(
typeof(EndpointMiddlewareFacts).GetTypeInfo().Assembly,
typeof(OmniSharpEndpointMetadata).GetTypeInfo().Assembly))
{
var middleware = new EndpointMiddleware(_next, host.CompositionHost, this.LoggerFactory);
var context = new DefaultHttpContext();
context.Request.Path = PathString.FromUriComponent("/findsymbols");
context.Request.Body = new MemoryStream(
Encoding.UTF8.GetBytes(
JsonConvert.SerializeObject(new FindSymbolsRequest
{
Language = LanguageNames.CSharp
})
)
);
await middleware.Invoke(context);
Assert.True(true);
}
}
public Func<ThrowRequest, Task<ThrowResponse>> ThrowDelegate = (request) =>
{
return Task.FromResult<ThrowResponse>(null);
};
[OmniSharpEndpoint("/throw", typeof(ThrowRequest), typeof(ThrowResponse))]
public class ThrowRequest : IRequest { }
public class ThrowResponse { }
[Fact]
public async Task Should_throw_if_type_is_not_mergeable()
{
RequestDelegate _next = async (ctx) => await Task.Run(() => { throw new NotImplementedException(); });
using (var host = CreatePlugInHost(GetAssembly<EndpointMiddlewareFacts>()))
{
var middleware = new EndpointMiddleware(_next, host.CompositionHost, this.LoggerFactory);
var context = new DefaultHttpContext();
context.Request.Path = PathString.FromUriComponent("/throw");
context.Request.Body = new MemoryStream(
Encoding.UTF8.GetBytes(
JsonConvert.SerializeObject(new ThrowRequest())
)
);
await Assert.ThrowsAsync<NotSupportedException>(async () => await middleware.Invoke(context));
}
}
}
}
| |
using System;
using ChainUtils.BouncyCastle.Crypto.Digests;
using ChainUtils.BouncyCastle.Crypto.Modes;
using ChainUtils.BouncyCastle.Crypto.Parameters;
using ChainUtils.BouncyCastle.Security;
using ChainUtils.BouncyCastle.Utilities;
namespace ChainUtils.BouncyCastle.Crypto.Engines
{
/**
* Wrap keys according to RFC 3217 - RC2 mechanism
*/
public class RC2WrapEngine
: IWrapper
{
/** Field engine */
private CbcBlockCipher engine;
/** Field param */
private ICipherParameters parameters;
/** Field paramPlusIV */
private ParametersWithIV paramPlusIV;
/** Field iv */
private byte[] iv;
/** Field forWrapping */
private bool forWrapping;
private SecureRandom sr;
/** Field IV2 */
private static readonly byte[] IV2 =
{
(byte) 0x4a, (byte) 0xdd, (byte) 0xa2,
(byte) 0x2c, (byte) 0x79, (byte) 0xe8,
(byte) 0x21, (byte) 0x05
};
//
// checksum digest
//
IDigest sha1 = new Sha1Digest();
byte[] digest = new byte[20];
/**
* Method init
*
* @param forWrapping
* @param param
*/
public void Init(
bool forWrapping,
ICipherParameters parameters)
{
this.forWrapping = forWrapping;
engine = new CbcBlockCipher(new RC2Engine());
if (parameters is ParametersWithRandom)
{
var pWithR = (ParametersWithRandom)parameters;
sr = pWithR.Random;
parameters = pWithR.Parameters;
}
else
{
sr = new SecureRandom();
}
if (parameters is ParametersWithIV)
{
if (!forWrapping)
throw new ArgumentException("You should not supply an IV for unwrapping");
paramPlusIV = (ParametersWithIV)parameters;
iv = paramPlusIV.GetIV();
this.parameters = paramPlusIV.Parameters;
if (iv.Length != 8)
throw new ArgumentException("IV is not 8 octets");
}
else
{
this.parameters = parameters;
if (this.forWrapping)
{
// Hm, we have no IV but we want to wrap ?!?
// well, then we have to create our own IV.
iv = new byte[8];
sr.NextBytes(iv);
paramPlusIV = new ParametersWithIV(this.parameters, iv);
}
}
}
/**
* Method GetAlgorithmName
*
* @return
*/
public string AlgorithmName
{
get { return "RC2"; }
}
/**
* Method wrap
*
* @param in
* @param inOff
* @param inLen
* @return
*/
public byte[] Wrap(
byte[] input,
int inOff,
int length)
{
if (!forWrapping)
{
throw new InvalidOperationException("Not initialized for wrapping");
}
var len = length + 1;
if ((len % 8) != 0)
{
len += 8 - (len % 8);
}
var keyToBeWrapped = new byte[len];
keyToBeWrapped[0] = (byte)length;
Array.Copy(input, inOff, keyToBeWrapped, 1, length);
var pad = new byte[keyToBeWrapped.Length - length - 1];
if (pad.Length > 0)
{
sr.NextBytes(pad);
Array.Copy(pad, 0, keyToBeWrapped, length + 1, pad.Length);
}
// Compute the CMS Key Checksum, (section 5.6.1), call this CKS.
var CKS = CalculateCmsKeyChecksum(keyToBeWrapped);
// Let WKCKS = WK || CKS where || is concatenation.
var WKCKS = new byte[keyToBeWrapped.Length + CKS.Length];
Array.Copy(keyToBeWrapped, 0, WKCKS, 0, keyToBeWrapped.Length);
Array.Copy(CKS, 0, WKCKS, keyToBeWrapped.Length, CKS.Length);
// Encrypt WKCKS in CBC mode using KEK as the key and IV as the
// initialization vector. Call the results TEMP1.
var TEMP1 = new byte[WKCKS.Length];
Array.Copy(WKCKS, 0, TEMP1, 0, WKCKS.Length);
var noOfBlocks = WKCKS.Length / engine.GetBlockSize();
var extraBytes = WKCKS.Length % engine.GetBlockSize();
if (extraBytes != 0)
{
throw new InvalidOperationException("Not multiple of block length");
}
engine.Init(true, paramPlusIV);
for (var i = 0; i < noOfBlocks; i++)
{
var currentBytePos = i * engine.GetBlockSize();
engine.ProcessBlock(TEMP1, currentBytePos, TEMP1, currentBytePos);
}
// Left TEMP2 = IV || TEMP1.
var TEMP2 = new byte[iv.Length + TEMP1.Length];
Array.Copy(iv, 0, TEMP2, 0, iv.Length);
Array.Copy(TEMP1, 0, TEMP2, iv.Length, TEMP1.Length);
// Reverse the order of the octets in TEMP2 and call the result TEMP3.
var TEMP3 = new byte[TEMP2.Length];
for (var i = 0; i < TEMP2.Length; i++)
{
TEMP3[i] = TEMP2[TEMP2.Length - (i + 1)];
}
// Encrypt TEMP3 in CBC mode using the KEK and an initialization vector
// of 0x 4a dd a2 2c 79 e8 21 05. The resulting cipher text is the desired
// result. It is 40 octets long if a 168 bit key is being wrapped.
var param2 = new ParametersWithIV(parameters, IV2);
engine.Init(true, param2);
for (var i = 0; i < noOfBlocks + 1; i++)
{
var currentBytePos = i * engine.GetBlockSize();
engine.ProcessBlock(TEMP3, currentBytePos, TEMP3, currentBytePos);
}
return TEMP3;
}
/**
* Method unwrap
*
* @param in
* @param inOff
* @param inLen
* @return
* @throws InvalidCipherTextException
*/
public byte[] Unwrap(
byte[] input,
int inOff,
int length)
{
if (forWrapping)
{
throw new InvalidOperationException("Not set for unwrapping");
}
if (input == null)
{
throw new InvalidCipherTextException("Null pointer as ciphertext");
}
if (length % engine.GetBlockSize() != 0)
{
throw new InvalidCipherTextException("Ciphertext not multiple of "
+ engine.GetBlockSize());
}
/*
// Check if the length of the cipher text is reasonable given the key
// type. It must be 40 bytes for a 168 bit key and either 32, 40, or
// 48 bytes for a 128, 192, or 256 bit key. If the length is not supported
// or inconsistent with the algorithm for which the key is intended,
// return error.
//
// we do not accept 168 bit keys. it has to be 192 bit.
int lengthA = (estimatedKeyLengthInBit / 8) + 16;
int lengthB = estimatedKeyLengthInBit % 8;
if ((lengthA != keyToBeUnwrapped.Length) || (lengthB != 0)) {
throw new XMLSecurityException("empty");
}
*/
// Decrypt the cipher text with TRIPLedeS in CBC mode using the KEK
// and an initialization vector (IV) of 0x4adda22c79e82105. Call the output TEMP3.
var param2 = new ParametersWithIV(parameters, IV2);
engine.Init(false, param2);
var TEMP3 = new byte[length];
Array.Copy(input, inOff, TEMP3, 0, length);
for (var i = 0; i < (TEMP3.Length / engine.GetBlockSize()); i++)
{
var currentBytePos = i * engine.GetBlockSize();
engine.ProcessBlock(TEMP3, currentBytePos, TEMP3, currentBytePos);
}
// Reverse the order of the octets in TEMP3 and call the result TEMP2.
var TEMP2 = new byte[TEMP3.Length];
for (var i = 0; i < TEMP3.Length; i++)
{
TEMP2[i] = TEMP3[TEMP3.Length - (i + 1)];
}
// Decompose TEMP2 into IV, the first 8 octets, and TEMP1, the remaining octets.
iv = new byte[8];
var TEMP1 = new byte[TEMP2.Length - 8];
Array.Copy(TEMP2, 0, iv, 0, 8);
Array.Copy(TEMP2, 8, TEMP1, 0, TEMP2.Length - 8);
// Decrypt TEMP1 using TRIPLedeS in CBC mode using the KEK and the IV
// found in the previous step. Call the result WKCKS.
paramPlusIV = new ParametersWithIV(parameters, iv);
engine.Init(false, paramPlusIV);
var LCEKPADICV = new byte[TEMP1.Length];
Array.Copy(TEMP1, 0, LCEKPADICV, 0, TEMP1.Length);
for (var i = 0; i < (LCEKPADICV.Length / engine.GetBlockSize()); i++)
{
var currentBytePos = i * engine.GetBlockSize();
engine.ProcessBlock(LCEKPADICV, currentBytePos, LCEKPADICV, currentBytePos);
}
// Decompose LCEKPADICV. CKS is the last 8 octets and WK, the wrapped key, are
// those octets before the CKS.
var result = new byte[LCEKPADICV.Length - 8];
var CKStoBeVerified = new byte[8];
Array.Copy(LCEKPADICV, 0, result, 0, LCEKPADICV.Length - 8);
Array.Copy(LCEKPADICV, LCEKPADICV.Length - 8, CKStoBeVerified, 0, 8);
// Calculate a CMS Key Checksum, (section 5.6.1), over the WK and compare
// with the CKS extracted in the above step. If they are not equal, return error.
if (!CheckCmsKeyChecksum(result, CKStoBeVerified))
{
throw new InvalidCipherTextException(
"Checksum inside ciphertext is corrupted");
}
if ((result.Length - ((result[0] & 0xff) + 1)) > 7)
{
throw new InvalidCipherTextException(
"too many pad bytes (" + (result.Length - ((result[0] & 0xff) + 1)) + ")");
}
// CEK is the wrapped key, now extracted for use in data decryption.
var CEK = new byte[result[0]];
Array.Copy(result, 1, CEK, 0, CEK.Length);
return CEK;
}
/**
* Some key wrap algorithms make use of the Key Checksum defined
* in CMS [CMS-Algorithms]. This is used to provide an integrity
* check value for the key being wrapped. The algorithm is
*
* - Compute the 20 octet SHA-1 hash on the key being wrapped.
* - Use the first 8 octets of this hash as the checksum value.
*
* @param key
* @return
* @throws Exception
* @see http://www.w3.org/TR/xmlenc-core/#sec-CMSKeyChecksum
*/
private byte[] CalculateCmsKeyChecksum(
byte[] key)
{
sha1.BlockUpdate(key, 0, key.Length);
sha1.DoFinal(digest, 0);
var result = new byte[8];
Array.Copy(digest, 0, result, 0, 8);
return result;
}
/**
* @param key
* @param checksum
* @return
* @see http://www.w3.org/TR/xmlenc-core/#sec-CMSKeyChecksum
*/
private bool CheckCmsKeyChecksum(
byte[] key,
byte[] checksum)
{
return Arrays.ConstantTimeAreEqual(CalculateCmsKeyChecksum(key), checksum);
}
}
}
| |
//-----------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
namespace System.IdentityModel.Selectors
{
using System;
using System.Security.Cryptography;
using System.Security.Cryptography.Xml;
using System.IdentityModel.Tokens;
using IDT = Microsoft.InfoCards.Diagnostics.InfoCardTrace;
//
// For common & resources
//
using Microsoft.InfoCards;
//
// Summary:
// This class implements the IAsymmetricCrypto interface and is used as an adapter between the
// InfoCard system and Indigo.
//
internal class InfoCardAsymmetricCrypto : AsymmetricSecurityKey, IDisposable
{
InfoCardRSACryptoProvider m_rsa;
//
// Summary:
// Constructs a new InfoCardAsymmetricCrypto given an InfoCardRSACryptoProvider.
//
// Parameters:
// cryptoHandle - the handle to the asymmetric key to base this crypto object on.
public InfoCardAsymmetricCrypto(AsymmetricCryptoHandle cryptoHandle)
{
m_rsa = new InfoCardRSACryptoProvider(cryptoHandle);
}
//
// Summary:
// Returns the size of the asymmetric key
//
public override int KeySize
{
get { return m_rsa.KeySize; }
}
//
// Summary:
// Indicates whether this IAsymmetricCrypto has access to the private key.
// In our case, that's the whole point, so it always returns true.
//
public override bool HasPrivateKey()
{
return true;
}
//
// Summary:
// Returns a reference to the InfoCardRSACryptoProvider that give Indigo access to
// the private key associated with the infocard, recipient tuple.
//
// Parameters:
// algorithmUri - The URI of the algorithm being requested.
// privateKey - set to true if access to the private key is required.
//
public override AsymmetricAlgorithm GetAsymmetricAlgorithm(string algorithmUri, bool privateKey)
{
switch (algorithmUri)
{
case SignedXml.XmlDsigRSASHA1Url:
case EncryptedXml.XmlEncRSA15Url:
case EncryptedXml.XmlEncRSAOAEPUrl:
return m_rsa;
default:
throw IDT.ThrowHelperError(new NotSupportedException(SR.GetString(SR.ClientUnsupportedCryptoAlgorithm, algorithmUri)));
}
}
//
// Sumamry:
// Returns a HashAlgorithm
//
// Parameters:
// algorithmUri - the uri of the hash algorithm being requested.
//
public override HashAlgorithm GetHashAlgorithmForSignature(string algorithmUri)
{
switch (algorithmUri)
{
case SignedXml.XmlDsigRSASHA1Url:
return new SHA1Managed();
default:
throw IDT.ThrowHelperError(new NotSupportedException(SR.GetString(SR.ClientUnsupportedCryptoAlgorithm, algorithmUri)));
}
}
//
// Summary:
// Returns a Signature deformatter.
//
// Parameters:
// algorithmUri - the uri of signature deformatter being requeted.
//
public override AsymmetricSignatureDeformatter GetSignatureDeformatter(string algorithmUri)
{
switch (algorithmUri)
{
case SignedXml.XmlDsigRSASHA1Url:
return new InfoCardRSAPKCS1SignatureDeformatter(m_rsa);
default:
throw IDT.ThrowHelperError(new NotSupportedException(SR.GetString(SR.ClientUnsupportedCryptoAlgorithm, algorithmUri)));
}
}
//
// Summary:
// Returns a Signature formatter.
//
// Parameters:
// algorithmUri - the uri of signature formatter being requeted.
//
public override AsymmetricSignatureFormatter GetSignatureFormatter(string algorithmUri)
{
switch (algorithmUri)
{
case SignedXml.XmlDsigRSASHA1Url:
return new InfoCardRSAPKCS1SignatureFormatter(m_rsa);
default:
throw IDT.ThrowHelperError(new NotSupportedException(SR.GetString(SR.ClientUnsupportedCryptoAlgorithm, algorithmUri)));
}
}
//
// Summary:
// Decrypts a symmetric key using the private key of a public/private key pair.
//
// Parameters:
// algorithmUri - The algorithm to use to decrypt the key.
// keyData - the key to decrypt.
//
public override byte[] DecryptKey(string algorithmUri, byte[] keyData)
{
AsymmetricKeyExchangeDeformatter deformatter;
switch (algorithmUri)
{
case EncryptedXml.XmlEncRSA15Url:
deformatter = new InfoCardRSAPKCS1KeyExchangeDeformatter(m_rsa);
return deformatter.DecryptKeyExchange(keyData);
case EncryptedXml.XmlEncRSAOAEPUrl:
deformatter = new InfoCardRSAOAEPKeyExchangeDeformatter(m_rsa);
return deformatter.DecryptKeyExchange(keyData);
default:
throw IDT.ThrowHelperError(new NotSupportedException(SR.GetString(SR.ClientUnsupportedCryptoAlgorithm, algorithmUri)));
}
}
//
// Summary:
// Encrypts a symmetric key using the public key of a public/private key pair.
//
// Parameters:
// algorithmUri - The algorithm to use to encrypt the key.
// keyData - the key to encrypt.
//
public override byte[] EncryptKey(string algorithmUri, byte[] keyData)
{
AsymmetricKeyExchangeFormatter formatter;
switch (algorithmUri)
{
case EncryptedXml.XmlEncRSA15Url:
formatter = new InfoCardRSAPKCS1KeyExchangeFormatter(m_rsa);
return formatter.CreateKeyExchange(keyData);
case EncryptedXml.XmlEncRSAOAEPUrl:
formatter = new InfoCardRSAOAEPKeyExchangeFormatter(m_rsa);
return formatter.CreateKeyExchange(keyData);
default:
throw IDT.ThrowHelperError(new NotSupportedException(SR.GetString(SR.ClientUnsupportedCryptoAlgorithm, algorithmUri)));
}
}
public override bool IsSupportedAlgorithm(string algorithmUri)
{
switch (algorithmUri)
{
case SignedXml.XmlDsigRSASHA1Url:
case EncryptedXml.XmlEncRSA15Url:
case EncryptedXml.XmlEncRSAOAEPUrl:
return true;
default:
return false;
}
}
public override bool IsSymmetricAlgorithm(string algorithmUri)
{
return InfoCardCryptoHelper.IsSymmetricAlgorithm(algorithmUri);
}
public override bool IsAsymmetricAlgorithm(string algorithmUri)
{
return InfoCardCryptoHelper.IsAsymmetricAlgorithm(algorithmUri);
}
public void Dispose()
{
((IDisposable)m_rsa).Dispose();
m_rsa = null;
}
}
}
| |
//---------------------------------------------------------------------------
//
// <copyright file="AccessorTable.cs" company="Microsoft">
// Copyright (C) Microsoft Corporation. All rights reserved.
// </copyright>
//
// Description: Mapping of (SourceValueType, type, name) to (info, propertyType, args)
//
//---------------------------------------------------------------------------
/***************************************************************************\
Data binding uses reflection to obtain accessors for source properties,
where an "accessor" can be a DependencyProperty, a PropertyInfo, or a
PropertyDescriptor, depending on the nature of the source item and the
property. We cache the result of this discovery process in the
AccessorTable; table lookup is cheaper than doing reflection again.
\***************************************************************************/
using System;
using System.Collections;
using System.ComponentModel; // IBindingList
using System.Reflection; // TypeDescriptor
using System.Windows; // SR
using System.Windows.Threading; // Dispatcher
using MS.Internal; // Invariant.Assert
namespace MS.Internal.Data
{
internal sealed class AccessorInfo
{
internal AccessorInfo(object accessor, Type propertyType, object[] args)
{
_accessor = accessor;
_propertyType = propertyType;
_args = args;
}
internal object Accessor { get { return _accessor; } }
internal Type PropertyType { get { return _propertyType; } }
internal object[] Args { get { return _args; } }
internal int Generation { get { return _generation; } set { _generation = value; } }
object _accessor; // DP, PD, or PI
Type _propertyType; // type of the property
object[] _args; // args for indexed property
int _generation; // used for discarding aged entries
}
internal sealed class AccessorTable
{
internal AccessorTable()
{
}
// map (SourceValueType, type, name) to (accessor, propertyType, args)
internal AccessorInfo this[SourceValueType sourceValueType, Type type, string name]
{
get
{
if (type == null || name == null)
return null;
AccessorInfo info = (AccessorInfo)_table[new AccessorTableKey(sourceValueType, type, name)];
if (info != null)
{
#if DEBUG
// record the age of cache hits
int age = _generation - info.Generation;
if (age >= _ages.Length)
{
int[] newAges = new int[2*age];
_ages.CopyTo(newAges, 0);
_ages = newAges;
}
++ _ages[age];
++ _hits;
#endif
info.Generation = _generation;
}
#if DEBUG
else
{
++ _misses;
}
#endif
return info;
}
set
{
if (type != null && name != null)
{
value.Generation = _generation;
_table[new AccessorTableKey(sourceValueType, type, name)] = value;
if (!_cleanupRequested)
RequestCleanup();
}
}
}
// request a cleanup pass
private void RequestCleanup()
{
_cleanupRequested = true;
Dispatcher.CurrentDispatcher.BeginInvoke(DispatcherPriority.ContextIdle, new DispatcherOperationCallback(CleanupOperation), null);
}
// run a cleanup pass
private object CleanupOperation(object arg)
{
// find entries that are sufficiently old
object[] keysToRemove = new object[_table.Count];
int n = 0;
IDictionaryEnumerator ide = _table.GetEnumerator();
while (ide.MoveNext())
{
AccessorInfo info = (AccessorInfo)ide.Value;
int age = _generation - info.Generation;
if (age >= AgeLimit)
{
keysToRemove[n++] = ide.Key;
}
}
#if DEBUG
if (_traceSize)
{
Console.WriteLine("After generation {0}, removing {1} of {2} entries from AccessorTable, new count is {3}",
_generation, n, _table.Count, _table.Count - n);
}
#endif
// remove those entries
for (int i=0; i<n; ++i)
{
_table.Remove(keysToRemove[i]);
}
++ _generation;
_cleanupRequested = false;
return null;
}
// print data about how the cache behaved
internal void PrintStats()
{
#if DEBUG
if (_generation == 0 || _hits == 0)
{
Console.WriteLine("No stats available for AccessorTable.");
return;
}
Console.WriteLine("AccessorTable had {0} hits, {1} misses ({2,2}%) in {3} generations.",
_hits, _misses, (100*_hits)/(_hits+_misses), _generation);
Console.WriteLine(" Age Hits Pct ----");
int cumulativeHits = 0;
for (int i=0; i<_ages.Length; ++i)
{
if (_ages[i] > 0)
{
cumulativeHits += _ages[i];
Console.WriteLine("{0,5} {1,6} {2,5} {3,5}",
i, _ages[i], 100*_ages[i]/_hits, 100*cumulativeHits/_hits);
}
}
#endif
}
internal bool TraceSize
{
get { return _traceSize; }
set { _traceSize = value; }
}
private const int AgeLimit = 10; // entries older than this get removed.
private Hashtable _table = new Hashtable();
private int _generation;
private bool _cleanupRequested;
bool _traceSize;
#if DEBUG
private int[] _ages = new int[10];
private int _hits, _misses;
#endif
private struct AccessorTableKey
{
public AccessorTableKey(SourceValueType sourceValueType, Type type, string name)
{
Invariant.Assert(type != null && type != null);
_sourceValueType = sourceValueType;
_type = type;
_name = name;
}
public override bool Equals(object o)
{
if (o is AccessorTableKey)
return this == (AccessorTableKey)o;
else
return false;
}
public static bool operator==(AccessorTableKey k1, AccessorTableKey k2)
{
return k1._sourceValueType == k2._sourceValueType
&& k1._type == k2._type
&& k1._name == k2._name;
}
public static bool operator!=(AccessorTableKey k1, AccessorTableKey k2)
{
return !(k1 == k2);
}
public override int GetHashCode()
{
return unchecked(_type.GetHashCode() + _name.GetHashCode());
}
SourceValueType _sourceValueType;
Type _type;
string _name;
}
}
}
| |
using EDDiscovery.DB;
using EDDiscovery.EliteDangerous;
using EDDiscovery2.DB;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Windows.Forms;
namespace EDDiscovery
{
public class TravelHistoryFilter
{
public TimeSpan? MaximumDataAge { get; }
public int? MaximumNumberOfItems { get; }
public string Label { get; }
public static TravelHistoryFilter NoFilter { get; } = new TravelHistoryFilter();
private TravelHistoryFilter(TimeSpan maximumDataAge, string label)
{
MaximumDataAge = maximumDataAge;
Label = label;
}
private TravelHistoryFilter(int maximumNumberOfItems, string label)
{
MaximumNumberOfItems = maximumNumberOfItems;
Label = label;
}
private TravelHistoryFilter()
{
Label = "All";
}
public static TravelHistoryFilter FromHours(int hours)
{
return new TravelHistoryFilter(TimeSpan.FromHours(hours), $"{hours} hours");
}
public static TravelHistoryFilter FromDays(int days)
{
return new TravelHistoryFilter(TimeSpan.FromDays(days), $"{days} days");
}
public static TravelHistoryFilter FromWeeks(int weeks)
{
return new TravelHistoryFilter(TimeSpan.FromDays(7 * weeks), weeks == 1 ? "week" : $"{weeks} weeks");
}
public static TravelHistoryFilter LastMonth()
{
return new TravelHistoryFilter(TimeSpan.FromDays(30), "month");
}
public static TravelHistoryFilter Last(int number)
{
return new TravelHistoryFilter(number, $"last {number}");
}
public List<HistoryEntry> Filter(HistoryList hl )
{
if (MaximumNumberOfItems.HasValue)
{
return hl.FilterByNumber(MaximumNumberOfItems.Value);
}
else if (MaximumDataAge.HasValue)
{
return hl.FilterByDate(MaximumDataAge.Value);
}
else
{
return hl.LastFirst;
}
}
public List<MaterialCommoditiesLedger.Transaction> Filter(List<MaterialCommoditiesLedger.Transaction> txlist )
{
if (MaximumDataAge.HasValue)
{
var oldestData = DateTime.UtcNow.Subtract(MaximumDataAge.Value);
return (from tx in txlist where tx.utctime >= oldestData orderby tx.utctime descending select tx).ToList();
}
else
return txlist;
}
public const int DefaultTravelHistoryFilterIndex = 8;
public static void InitaliseComboBox( ExtendedControls.ComboBoxCustom cc , string dbname )
{
cc.Enabled = false;
cc.DataSource = new[]
{
TravelHistoryFilter.FromHours(6),
TravelHistoryFilter.FromHours(12),
TravelHistoryFilter.FromHours(24),
TravelHistoryFilter.FromDays(3),
TravelHistoryFilter.FromWeeks(1),
TravelHistoryFilter.FromWeeks(2),
TravelHistoryFilter.LastMonth(),
TravelHistoryFilter.Last(20),
TravelHistoryFilter.NoFilter,
};
cc.DisplayMember = nameof(TravelHistoryFilter.Label);
cc.SelectedIndex = SQLiteDBClass.GetSettingInt(dbname, DefaultTravelHistoryFilterIndex);
cc.Enabled = true;
}
}
public class EventFilterSelector
{
ExtendedControls.CheckedListControlCustom cc;
string dbstring;
public event EventHandler Changed;
private string selectedlist;
private string selectedlistname;
private int reserved = 2;
public void ConfigureThirdOption(string n , string l ) // could be extended later for more..
{
selectedlistname = n;
selectedlist = l;
reserved = 3;
}
public void FilterButton(string db, Control ctr, Color back, Color fore, Form parent)
{
FilterButton(db, ctr, back, fore, parent, JournalEntry.GetListOfEventsWithOptMethod(true));
}
public void FilterButton(string db, Control ctr, Color back, Color fore, Form parent, List<string> list)
{
FilterButton(db, ctr.PointToScreen(new Point(0, ctr.Size.Height)), new Size(ctr.Width * 2, 400), back, fore, parent, list);
}
public void FilterButton(string db, Point p, Size s, Color back, Color fore, Form parent)
{
FilterButton(db, p, s, back, fore, parent, JournalEntry.GetListOfEventsWithOptMethod(true));
}
public void FilterButton(string db, Point p, Size s, Color back, Color fore, Form parent, List<string> list)
{
if (cc == null)
{
dbstring = db;
cc = new ExtendedControls.CheckedListControlCustom();
cc.Items.Add("All");
cc.Items.Add("None");
if (selectedlist != null)
cc.Items.Add(selectedlistname);
cc.Items.AddRange(list.ToArray());
cc.SetChecked(SQLiteDBClass.GetSettingString(dbstring, "All"));
SetFilterSet();
cc.FormClosed += FilterClosed;
cc.CheckedChanged += FilterCheckChanged;
cc.PositionSize(p,s);
cc.SetColour(back,fore);
cc.Show(parent);
}
else
cc.Close();
}
private void SetFilterSet()
{
string list = cc.GetChecked(reserved);
//Console.WriteLine("List {0}", list);
cc.SetChecked(list.Equals("All"), 0, 1);
cc.SetChecked(list.Equals("None"), 1, 1);
if ( selectedlist!=null)
cc.SetChecked(list.Equals(selectedlist), 2, 1);
}
private void FilterCheckChanged(Object sender, ItemCheckEventArgs e)
{
//Console.WriteLine("Changed " + e.Index);
cc.SetChecked(e.NewValue == CheckState.Checked, e.Index, 1); // force check now (its done after it) so our functions work..
if (e.Index == 0 && e.NewValue == CheckState.Checked)
cc.SetChecked(true, reserved);
if ((e.Index == 1 && e.NewValue == CheckState.Checked) || (e.Index <= 2 && e.NewValue == CheckState.Unchecked))
cc.SetChecked(false, reserved);
if (selectedlist != null && e.Index == 2 && e.NewValue == CheckState.Checked)
{
cc.SetChecked(false, reserved);
cc.SetChecked(selectedlist);
}
SetFilterSet();
}
private void FilterClosed(Object sender, FormClosedEventArgs e)
{
SQLiteDBClass.PutSettingString(dbstring, cc.GetChecked(3));
cc = null;
if (Changed != null)
Changed(sender, e);
}
}
public class StaticFilters
{
public static void FilterGridView(DataGridView vw, string searchstr)
{
vw.SuspendLayout();
DataGridViewRow[] theRows = new DataGridViewRow[vw.Rows.Count];
vw.Rows.CopyTo(theRows, 0);
vw.Rows.Clear();
for (int loop = 0; loop < theRows.Length; loop++)
{
bool found = false;
if (searchstr.Length < 1)
found = true;
else
{
foreach (DataGridViewCell cell in theRows[loop].Cells)
{
if (cell.Value != null)
{
if (cell.Value.ToString().IndexOf(searchstr, 0, StringComparison.CurrentCultureIgnoreCase) >= 0)
{
found = true;
break;
}
}
}
}
theRows[loop].Visible = found;
}
vw.Rows.AddRange(theRows);
vw.ResumeLayout();
}
}
}
| |
using System;
using System.Threading.Tasks;
using System.Linq;
using System.Collections.Generic;
using NUnit.Framework;
using NUnit.Framework.Constraints;
using System.Globalization;
using TimeAndDate.Services.DataTypes.Astro;
using TimeAndDate.Services.DataTypes.Places;
using TimeAndDate.Services.DataTypes.Time;
using TimeAndDate.Services.Common;
namespace TimeAndDate.Services.Tests.IntegrationTests
{
[TestFixture()]
public class TimeServiceTestsAsync
{
#region Location
[Test]
public async Task Calling_TimeService_WithNumericId_Should_ReturnCorrectLocation ()
{
// Arrange
var placeId = 179;
// Act
var timeservice = new TimeService (Config.AccessKey, Config.SecretKey);
var result = await timeservice.CurrentTimeForPlaceAsync (new LocationId(placeId));
var firstLocation = result.SingleOrDefault ();
// Assert
Assert.AreEqual (placeId.ToString (), firstLocation.Id);
}
[Test]
public async Task Calling_TimeService_WithTextualId_Should_ReturnCorrectLocation ()
{
// Arrange
var placeName = "norway/oslo";
var placeId = "187";
// Act
var timeservice = new TimeService (Config.AccessKey, Config.SecretKey);
var result = await timeservice.CurrentTimeForPlaceAsync (new LocationId(placeName));
var firstLocation = result.SingleOrDefault ();
// Assert
Assert.AreEqual (placeId, firstLocation.Id);
}
[Test]
public async Task Calling_TimeService_WithCoordinates_Should_ReturnCorrectLocation ()
{
// Arrange
var osloCoords = new Coordinates (59.914m, 10.752m);
var expectedId = String.Format ("+{0}+{1}", osloCoords.Latitude.ToString (CultureInfo.InvariantCulture),
osloCoords.Longitude.ToString (CultureInfo.InvariantCulture));
// Act
var timeservice = new TimeService (Config.AccessKey, Config.SecretKey);
var result = await timeservice.CurrentTimeForPlaceAsync (new LocationId(osloCoords));
var firstLocation = result.SingleOrDefault ();
// Assert
Assert.AreEqual (expectedId, firstLocation.Id);
}
#endregion
#region Geo
[Test]
public async Task Calling_TimeService_WithCoordinates_Should_ReturnCorrectGeo ()
{
// Arrange
var osloCoords = new Coordinates (59.914m, 10.752m);
var expectedId = String.Format ("+{0}+{1}", osloCoords.Latitude.ToString (CultureInfo.InvariantCulture),
osloCoords.Longitude.ToString (CultureInfo.InvariantCulture));
// Act
var timeservice = new TimeService (Config.AccessKey, Config.SecretKey);
var result = await timeservice.CurrentTimeForPlaceAsync (new LocationId (osloCoords));
var firstLocation = result.SingleOrDefault ();
// Assert
Assert.AreEqual (osloCoords.Latitude, firstLocation.Geography.Coordinates.Latitude);
Assert.AreEqual (osloCoords.Longitude, firstLocation.Geography.Coordinates.Longitude);
Assert.AreEqual (expectedId, firstLocation.Id);
Assert.IsNull (firstLocation.Geography.State);
Assert.IsNull (firstLocation.Geography.Name);
}
[Test]
public async Task Calling_TimeService_WithTextualId_Should_ReturnCorrectGeo ()
{
// Arrange
var expectedCountry = "Norway";
var expectedPlace = "Oslo";
var placeName = String.Format ("{0}/{1}", expectedCountry, expectedPlace).ToLower ();
var expectedCountryId = "no";
var expectedPlaceId = "187";
// Act
var timeservice = new TimeService (Config.AccessKey, Config.SecretKey);
var result = await timeservice.CurrentTimeForPlaceAsync (new LocationId(placeName));
var firstLocation = result.SingleOrDefault ();
// Assert
Assert.AreEqual (expectedCountry, firstLocation.Geography.Country.Name);
Assert.AreEqual (expectedCountryId, firstLocation.Geography.Country.Id);
Assert.AreEqual (expectedPlace, firstLocation.Geography.Name);
Assert.AreEqual (expectedPlaceId, firstLocation.Id);
}
[Test]
public async Task Calling_TimeService_WithNumericId_Should_ReturnCorrectGeo ()
{
// Arrange
var expectedCountry = "Norway";
var expectedPlace = "Oslo";
var expectedCountryId = "no";
var placeId = 187;
// Act
var timeservice = new TimeService (Config.AccessKey, Config.SecretKey);
var result = await timeservice.CurrentTimeForPlaceAsync (new LocationId(placeId));
var firstLocation = result.SingleOrDefault ();
// Assert
Assert.AreEqual (expectedCountry, firstLocation.Geography.Country.Name);
Assert.AreEqual (expectedCountryId, firstLocation.Geography.Country.Id);
Assert.AreEqual (expectedPlace, firstLocation.Geography.Name);
Assert.AreEqual (placeId.ToString(), firstLocation.Id);
}
#endregion
#region Time
[Test]
public async Task Calling_TimeService_WithNumericId_Should_ReturnCorrectTime ()
{
// Arrange
var placeId = 187;
var now = DateTime.Now;
// Act
var timeservice = new TimeService (Config.AccessKey, Config.SecretKey);
var result = await timeservice.CurrentTimeForPlaceAsync (new LocationId(placeId));
var firstLocation = result.SingleOrDefault ();
// Assert
Assert.AreEqual (now.Year, firstLocation.Time.DateTime.Year);
}
[Test]
public async Task Calling_TimeService_WithTextualId_Should_ReturnCorrectTime ()
{
// Arrange
var placeName = "norway/oslo";
var now = DateTime.Now;
// Act
var timeservice = new TimeService (Config.AccessKey, Config.SecretKey);
var result = await timeservice.CurrentTimeForPlaceAsync (new LocationId(placeName));
var firstLocation = result.SingleOrDefault ();
// Assert
Assert.AreEqual (now.Year, firstLocation.Time.DateTime.Year);
}
[Test]
public async Task Calling_TimeService_WithCoordinates_Should_ReturnCorrectTime ()
{
// Arrange
var osloCoords = new Coordinates (59.914m, 10.752m);
var expectedId = String.Format ("+{0}+{1}", osloCoords.Latitude.ToString (CultureInfo.InvariantCulture),
osloCoords.Longitude.ToString (CultureInfo.InvariantCulture));
var now = DateTime.Now;
// Act
var timeservice = new TimeService (Config.AccessKey, Config.SecretKey);
timeservice.IncludeCoordinates = true;
var result = await timeservice.CurrentTimeForPlaceAsync (new LocationId (osloCoords));
var firstLocation = result.SingleOrDefault ();
// Assert
Assert.AreEqual (now.Year, firstLocation.Time.DateTime.Year);
Assert.AreEqual (expectedId, firstLocation.Id);
}
#endregion
#region Timezone
[Test]
public async Task Calling_TimeService_WithNumericId_Should_ReturnCorrectTimezone ()
{
// Arrange
var placeId = 187;
var expectedTimezoneAbbr1 = "CEST";
var expectedTimezoneAbbr2 = "CET";
var expectedTimezoneName1 = "Central European Summer Time";
var expectedTimezoneName2 = "Central European Time";
var expectedOffsetHour1 = 1;
var expectedOffsetHour2 = 2;
var expectedOffsetMinute = 0;
var expectedBasicOffset = 3600;
var expectedDstOffset1 = 3600;
var expectedDstOffset2 = 0;
var expectedTotalOffset1 = 7200;
var expectedTotalOffset2 = 3600;
// Act
var timeservice = new TimeService (Config.AccessKey, Config.SecretKey);
var result = await timeservice.CurrentTimeForPlaceAsync (new LocationId(placeId));
var firstLocation = result.SingleOrDefault ();
var abbr = firstLocation.Time.Timezone.Abbrevation;
// Assert
Assert.That(firstLocation.Time.Timezone.Abbrevation, Is.EqualTo(expectedTimezoneAbbr1) | Is.EqualTo(expectedTimezoneAbbr2));
Assert.That(firstLocation.Time.Timezone.Name, Is.EqualTo(expectedTimezoneName1) | Is.EqualTo(expectedTimezoneName2));
Assert.That(firstLocation.Time.Timezone.Offset.Hours, Is.EqualTo(expectedOffsetHour1) | Is.EqualTo(expectedOffsetHour2));
Assert.That(firstLocation.Time.Timezone.DSTOffset, Is.EqualTo(expectedDstOffset1) | Is.EqualTo(expectedDstOffset2));
Assert.That(firstLocation.Time.Timezone.TotalOffset, Is.EqualTo(expectedTotalOffset1) | Is.EqualTo(expectedTotalOffset2));
Assert.AreEqual (expectedOffsetMinute, firstLocation.Time.Timezone.Offset.Minutes);
Assert.AreEqual (expectedBasicOffset, firstLocation.Time.Timezone.BasicOffset);
}
[Test]
public async Task Calling_TimeService_WithTextualId_Should_ReturnCorrectTimezone ()
{
// Arrange
var placeName = "norway/oslo";
var expectedTimezoneAbbr1 = "CEST";
var expectedTimezoneAbbr2 = "CET";
var expectedTimezoneName1 = "Central European Summer Time";
var expectedTimezoneName2 = "Central European Time";
var expectedOffsetHour1 = 1;
var expectedOffsetHour2 = 2;
var expectedOffsetMinute = 0;
var expectedBasicOffset = 3600;
var expectedDstOffset1 = 3600;
var expectedDstOffset2 = 0;
var expectedTotalOffset1 = 7200;
var expectedTotalOffset2 = 3600;
// Act
var timeservice = new TimeService (Config.AccessKey, Config.SecretKey);
var result = await timeservice.CurrentTimeForPlaceAsync (new LocationId(placeName));
var firstLocation = result.SingleOrDefault ();
// Assert
Assert.That(firstLocation.Time.Timezone.Abbrevation, Is.EqualTo(expectedTimezoneAbbr1) | Is.EqualTo(expectedTimezoneAbbr2));
Assert.That(firstLocation.Time.Timezone.Name, Is.EqualTo(expectedTimezoneName1) | Is.EqualTo(expectedTimezoneName2));
Assert.That(firstLocation.Time.Timezone.Offset.Hours, Is.EqualTo(expectedOffsetHour1) | Is.EqualTo(expectedOffsetHour2));
Assert.That(firstLocation.Time.Timezone.DSTOffset, Is.EqualTo(expectedDstOffset1) | Is.EqualTo(expectedDstOffset2));
Assert.That(firstLocation.Time.Timezone.TotalOffset, Is.EqualTo(expectedTotalOffset1) | Is.EqualTo(expectedTotalOffset2));
Assert.AreEqual (expectedOffsetMinute, firstLocation.Time.Timezone.Offset.Minutes);
Assert.AreEqual (expectedBasicOffset, firstLocation.Time.Timezone.BasicOffset);
}
[Test]
public async Task Calling_TimeService_WithCoordinates_Should_ReturnCorrectTimezone ()
{
// Arrange
var osloCoords = new Coordinates (59.914m, 10.752m);
var expectedTimezoneAbbr1 = "CEST";
var expectedTimezoneAbbr2 = "CET";
var expectedTimezoneName1 = "Central European Summer Time";
var expectedTimezoneName2 = "Central European Time";
var expectedOffsetHour1 = 1;
var expectedOffsetHour2 = 2;
var expectedOffsetMinute = 0;
var expectedBasicOffset1 = 3600;
var expectedBasicOffset2 = 0;
var expectedDstOffset1 = 3600;
var expectedDstOffset2 = 0;
var expectedTotalOffset1 = 7200;
var expectedTotalOffset2 = 3600;
// Act
var timeservice = new TimeService (Config.AccessKey, Config.SecretKey);
var result = await timeservice.CurrentTimeForPlaceAsync (new LocationId(osloCoords));
var firstLocation = result.SingleOrDefault ();
// Assert
Assert.That(firstLocation.Time.Timezone.Abbrevation, Is.EqualTo(expectedTimezoneAbbr1) | Is.EqualTo(expectedTimezoneAbbr2));
Assert.That(firstLocation.Time.Timezone.Name, Is.EqualTo(expectedTimezoneName1) | Is.EqualTo(expectedTimezoneName2));
Assert.That(firstLocation.Time.Timezone.Offset.Hours, Is.EqualTo(expectedOffsetHour1) | Is.EqualTo(expectedOffsetHour2));
Assert.That(firstLocation.Time.Timezone.BasicOffset, Is.EqualTo(expectedBasicOffset1) | Is.EqualTo(expectedBasicOffset2));
Assert.That(firstLocation.Time.Timezone.DSTOffset, Is.EqualTo(expectedDstOffset1) | Is.EqualTo(expectedDstOffset2));
Assert.That(firstLocation.Time.Timezone.TotalOffset, Is.EqualTo(expectedTotalOffset1) | Is.EqualTo(expectedTotalOffset2));
Assert.AreEqual (expectedOffsetMinute, firstLocation.Time.Timezone.Offset.Minutes);
}
#endregion
#region TimeChanges
[Test]
public async Task Calling_TimeService_WithNumericId_Should_ReturnCorrectTimeChanges ()
{
// Arrange
var placeId = 187;
var expectedFirstNewOffset = 7200;
var expectedFirstNewDstOffset = 3600;
var expectedSecondNewOffset = 3600;
// Act
var timeservice = new TimeService (Config.AccessKey, Config.SecretKey);
var result = await timeservice.CurrentTimeForPlaceAsync (new LocationId(placeId));
var firstLocation = result.SingleOrDefault ();
var firstChange = firstLocation.TimeChanges.FirstOrDefault ();
var secondChange = firstLocation.TimeChanges.Skip (1).FirstOrDefault ();
// Assert
Assert.IsTrue (firstChange.NewDaylightSavingTime.HasValue);
Assert.AreEqual (expectedFirstNewDstOffset, firstChange.NewDaylightSavingTime.Value);
Assert.AreEqual (expectedFirstNewOffset, firstChange.NewTotalOffset);
Assert.AreEqual (expectedSecondNewOffset, secondChange.NewTotalOffset);
}
[Test]
public async Task Calling_TimeService_WithTextualId_Should_ReturnCorrectTimeChanges ()
{
// Arrange
var placeName = "norway/oslo";
var expectedFirstNewOffset = 7200;
var expectedFirstNewDstOffset = 3600;
var expectedSecondNewOffset = 3600;
// Act
var timeservice = new TimeService (Config.AccessKey, Config.SecretKey);
var result = await timeservice.CurrentTimeForPlaceAsync (new LocationId(placeName));
var firstLocation = result.SingleOrDefault ();
var firstChange = firstLocation.TimeChanges.FirstOrDefault ();
var secondChange = firstLocation.TimeChanges.Skip (1).FirstOrDefault ();
// Assert
Assert.IsTrue (firstChange.NewDaylightSavingTime.HasValue);
Assert.AreEqual (expectedFirstNewDstOffset, firstChange.NewDaylightSavingTime.Value);
Assert.AreEqual (expectedFirstNewOffset, firstChange.NewTotalOffset);
Assert.AreEqual (expectedSecondNewOffset, secondChange.NewTotalOffset);
}
[Test]
public async Task Calling_TimeService_WithCoordinates_Should_ReturnCorrectTimeChanges ()
{
// Arrange
var osloCoords = new Coordinates (59.914m, 10.752m);
var expectedFirstNewOffset = 7200;
var expectedFirstNewDstOffset = 3600;
var expectedSecondNewOffset = 3600;
// Act
var timeservice = new TimeService (Config.AccessKey, Config.SecretKey);
var result = await timeservice.CurrentTimeForPlaceAsync (new LocationId(osloCoords));
var firstLocation = result.SingleOrDefault ();
var firstChange = firstLocation.TimeChanges.FirstOrDefault ();
var secondChange = firstLocation.TimeChanges.Skip (1).FirstOrDefault ();
// Assert
Assert.IsTrue (firstChange.NewDaylightSavingTime.HasValue);
Assert.AreEqual (expectedFirstNewDstOffset, firstChange.NewDaylightSavingTime.Value);
Assert.AreEqual (expectedFirstNewOffset, firstChange.NewTotalOffset);
Assert.AreEqual (expectedSecondNewOffset, secondChange.NewTotalOffset);
}
#endregion
#region AstronomyTests
[Test]
// This test checks on sunset, but the check criteria can have changed from day to day
// TODO to find a way around this
public async Task Calling_TimeService_WithNumericId_Should_ReturnCorrectAstronomy ()
{
// Arrange
var placeId = 187;
var expectedObjectName = AstronomyObjectType.Sun;
var expectedRise = AstronomyEventType.Rise;
var expectedSet = AstronomyEventType.Set;
// Act
var timeservice = new TimeService (Config.AccessKey, Config.SecretKey);
var result = await timeservice.CurrentTimeForPlaceAsync (new LocationId(placeId));
var firstLocation = result.SingleOrDefault ();
var firstObject = firstLocation.Astronomy.SingleOrDefault ();
var rise = firstObject.Events.FirstOrDefault ();
var set = firstObject.Events.Skip (1).FirstOrDefault ();
// Assert
Assert.AreEqual (expectedObjectName, firstObject.Name);
Assert.AreEqual (expectedRise, rise.Type);
Assert.AreEqual (expectedSet, set.Type);
// Sunrise in Oslo is most likely never before 3 and never after 10
// Sunset in Oslo is most likely never before 14 and never after 22
Assert.IsTrue (rise.Time.Hour >= 3 && rise.Time.Hour <= 10);
Assert.IsTrue (set.Time.Hour >= 14 && set.Time.Hour <= 22);
}
[Test]
// This test checks on sunset, but the check criteria can have changed from day to day
// TODO to find a way around this
public async Task Calling_TimeService_WithTextualId_Should_ReturnCorrectAstronomy ()
{
// Arrange
var placeName = "norway/oslo";
var expectedObjectName = AstronomyObjectType.Sun;
var expectedRise = AstronomyEventType.Rise;
var expectedSet = AstronomyEventType.Set;
// Act
var timeservice = new TimeService (Config.AccessKey, Config.SecretKey);
var result = await timeservice.CurrentTimeForPlaceAsync (new LocationId(placeName));
var firstLocation = result.SingleOrDefault ();
var firstObject = firstLocation.Astronomy.FirstOrDefault ();
var rise = firstObject.Events.FirstOrDefault ();
var set = firstObject.Events.Skip (1).FirstOrDefault ();
// Assert
Assert.AreEqual (expectedObjectName, firstObject.Name);
Assert.AreEqual (expectedRise, rise.Type);
Assert.AreEqual (expectedSet, set.Type);
// Sunrise in Oslo is most likely never before 3 and never after 10
// Sunset in Oslo is most likely never before 14 and never after 22
Assert.IsTrue (rise.Time.Hour >= 3 && rise.Time.Hour <= 10);
Assert.IsTrue (set.Time.Hour >= 14 && set.Time.Hour <= 22);
}
[Test]
// This test checks on sunset, but the check criteria can have changed from day to day
// TODO to find a way around this
public async Task Calling_TimeService_WithCoordinates_Should_ReturnCorrectAstronomy ()
{
// Arrange
var osloCoords = new Coordinates (59.914m, 10.752m);
var expectedObjectName = AstronomyObjectType.Sun;
var expectedRise = AstronomyEventType.Rise;
var expectedSet = AstronomyEventType.Set;
// Act
var timeservice = new TimeService (Config.AccessKey, Config.SecretKey);
var result = await timeservice.CurrentTimeForPlaceAsync (new LocationId(osloCoords));
var firstLocation = result.SingleOrDefault ();
var firstObject = firstLocation.Astronomy.SingleOrDefault ();
var rise = firstObject.Events.FirstOrDefault ();
var set = firstObject.Events.Skip (1).FirstOrDefault ();
// Assert
Assert.AreEqual (expectedObjectName, firstObject.Name);
Assert.AreEqual (expectedRise, rise.Type);
Assert.AreEqual (expectedSet, set.Type);
// Sunrise in Oslo is most likely never before 3 and never after 10
// Sunset in Oslo is most likely never before 14 and never after 22
Assert.IsTrue (rise.Time.Hour >= 3 && rise.Time.Hour <= 10);
Assert.IsTrue (set.Time.Hour >= 14 && set.Time.Hour <= 22);
}
#endregion
}
}
| |
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Reflection;
using System.Text;
using System.Collections;
#if NET20
using Arch.CMessaging.Client.Newtonsoft.Json.Utilities.LinqBridge;
#else
using System.Linq;
#endif
using System.Globalization;
using Arch.CMessaging.Client.Newtonsoft.Json.Serialization;
namespace Arch.CMessaging.Client.Newtonsoft.Json.Utilities
{
internal static class CollectionUtils
{
/// <summary>
/// Determines whether the collection is null or empty.
/// </summary>
/// <param name="collection">The collection.</param>
/// <returns>
/// <c>true</c> if the collection is null or empty; otherwise, <c>false</c>.
/// </returns>
public static bool IsNullOrEmpty<T>(ICollection<T> collection)
{
if (collection != null)
{
return (collection.Count == 0);
}
return true;
}
/// <summary>
/// Adds the elements of the specified collection to the specified generic IList.
/// </summary>
/// <param name="initial">The list to add to.</param>
/// <param name="collection">The collection of elements to add.</param>
public static void AddRange<T>(this IList<T> initial, IEnumerable<T> collection)
{
if (initial == null)
throw new ArgumentNullException("initial");
if (collection == null)
return;
foreach (T value in collection)
{
initial.Add(value);
}
}
#if (NET20 || NET35 || PORTABLE40)
public static void AddRange<T>(this IList<T> initial, IEnumerable collection)
{
ValidationUtils.ArgumentNotNull(initial, "initial");
// because earlier versions of .NET didn't support covariant generics
initial.AddRange(collection.Cast<T>());
}
#endif
public static bool IsDictionaryType(Type type)
{
ValidationUtils.ArgumentNotNull(type, "type");
if (typeof(IDictionary).IsAssignableFrom(type))
return true;
if (ReflectionUtils.ImplementsGenericDefinition(type, typeof(IDictionary<,>)))
return true;
return false;
}
public static ConstructorInfo ResolveEnumerableCollectionConstructor(Type collectionType, Type collectionItemType)
{
Type genericEnumerable = typeof(IEnumerable<>).MakeGenericType(collectionItemType);
ConstructorInfo match = null;
foreach (ConstructorInfo constructor in collectionType.GetConstructors(BindingFlags.Public | BindingFlags.Instance))
{
IList<ParameterInfo> parameters = constructor.GetParameters();
if (parameters.Count == 1)
{
if (genericEnumerable == parameters[0].ParameterType)
{
// exact match
match = constructor;
break;
}
// incase we can't find an exact match, use first inexact
if (match == null)
{
if (genericEnumerable.IsAssignableFrom(parameters[0].ParameterType))
match = constructor;
}
}
}
return match;
}
public static bool AddDistinct<T>(this IList<T> list, T value)
{
return list.AddDistinct(value, EqualityComparer<T>.Default);
}
public static bool AddDistinct<T>(this IList<T> list, T value, IEqualityComparer<T> comparer)
{
if (list.ContainsValue(value, comparer))
return false;
list.Add(value);
return true;
}
// this is here because LINQ Bridge doesn't support Contains with IEqualityComparer<T>
public static bool ContainsValue<TSource>(this IEnumerable<TSource> source, TSource value, IEqualityComparer<TSource> comparer)
{
if (comparer == null)
comparer = EqualityComparer<TSource>.Default;
if (source == null)
throw new ArgumentNullException("source");
foreach (TSource local in source)
{
if (comparer.Equals(local, value))
return true;
}
return false;
}
public static bool AddRangeDistinct<T>(this IList<T> list, IEnumerable<T> values, IEqualityComparer<T> comparer)
{
bool allAdded = true;
foreach (T value in values)
{
if (!list.AddDistinct(value, comparer))
allAdded = false;
}
return allAdded;
}
public static int IndexOf<T>(this IEnumerable<T> collection, Func<T, bool> predicate)
{
int index = 0;
foreach (T value in collection)
{
if (predicate(value))
return index;
index++;
}
return -1;
}
/// <summary>
/// Returns the index of the first occurrence in a sequence by using a specified IEqualityComparer.
/// </summary>
/// <typeparam name="TSource">The type of the elements of source.</typeparam>
/// <param name="list">A sequence in which to locate a value.</param>
/// <param name="value">The object to locate in the sequence</param>
/// <param name="comparer">An equality comparer to compare values.</param>
/// <returns>The zero-based index of the first occurrence of value within the entire sequence, if found; otherwise, ?.</returns>
public static int IndexOf<TSource>(this IEnumerable<TSource> list, TSource value, IEqualityComparer<TSource> comparer)
{
int index = 0;
foreach (TSource item in list)
{
if (comparer.Equals(item, value))
{
return index;
}
index++;
}
return -1;
}
private static IList<int> GetDimensions(IList values, int dimensionsCount)
{
IList<int> dimensions = new List<int>();
IList currentArray = values;
while (true)
{
dimensions.Add(currentArray.Count);
// don't keep calculating dimensions for arrays inside the value array
if (dimensions.Count == dimensionsCount)
break;
if (currentArray.Count == 0)
break;
object v = currentArray[0];
if (v is IList)
currentArray = (IList)v;
else
break;
}
return dimensions;
}
private static void CopyFromJaggedToMultidimensionalArray(IList values, Array multidimensionalArray, int[] indices)
{
int dimension = indices.Length;
if (dimension == multidimensionalArray.Rank)
{
multidimensionalArray.SetValue(JaggedArrayGetValue(values, indices), indices);
return;
}
int dimensionLength = multidimensionalArray.GetLength(dimension);
IList list = (IList)JaggedArrayGetValue(values, indices);
int currentValuesLength = list.Count;
if (currentValuesLength != dimensionLength)
throw new Exception("Cannot deserialize non-cubical array as multidimensional array.");
int[] newIndices = new int[dimension + 1];
for (int i = 0; i < dimension; i++)
{
newIndices[i] = indices[i];
}
for (int i = 0; i < multidimensionalArray.GetLength(dimension); i++)
{
newIndices[dimension] = i;
CopyFromJaggedToMultidimensionalArray(values, multidimensionalArray, newIndices);
}
}
private static object JaggedArrayGetValue(IList values, int[] indices)
{
IList currentList = values;
for (int i = 0; i < indices.Length; i++)
{
int index = indices[i];
if (i == indices.Length - 1)
return currentList[index];
else
currentList = (IList)currentList[index];
}
return currentList;
}
public static Array ToMultidimensionalArray(IList values, Type type, int rank)
{
IList<int> dimensions = GetDimensions(values, rank);
while (dimensions.Count < rank)
{
dimensions.Add(0);
}
Array multidimensionalArray = Array.CreateInstance(type, dimensions.ToArray());
CopyFromJaggedToMultidimensionalArray(values, multidimensionalArray, new int[0]);
return multidimensionalArray;
}
}
}
| |
#if !NOT_UNITY3D
using System;
using System.Collections.Generic;
using ModestTree;
using UnityEngine;
using UnityEngine.Serialization;
using Zenject.Internal;
#pragma warning disable 649
namespace Zenject
{
public class GameObjectContext : RunnableContext
{
public event Action PreInstall;
public event Action PostInstall;
public event Action PreResolve;
public event Action PostResolve;
[SerializeField]
[Tooltip("Note that this field is optional and can be ignored in most cases. This is really only needed if you want to control the 'Script Execution Order' of your subcontainer. In this case, define a new class that derives from MonoKernel, add it to this game object, then drag it into this field. Then you can set a value for 'Script Execution Order' for this new class and this will control when all ITickable/IInitializable classes bound within this subcontainer get called.")]
[FormerlySerializedAs("_facade")]
MonoKernel _kernel;
DiContainer _container;
// Need to cache this when auto run is false
DiContainer _parentContainer;
bool _hasInstalled;
public override DiContainer Container
{
get { return _container; }
}
public override IEnumerable<GameObject> GetRootGameObjects()
{
return new[] { gameObject };
}
[Inject]
public void Construct(
DiContainer parentContainer)
{
Assert.IsNull(_parentContainer);
_parentContainer = parentContainer;
Initialize();
}
protected override void RunInternal()
{
Install(_parentContainer);
ResolveAndStart();
}
public void Install(DiContainer parentContainer)
{
Assert.That(_parentContainer == null || _parentContainer == parentContainer);
// We allow calling this explicitly instead of relying on the [Inject] event above
// so that we can follow the two-pass construction-injection pattern in the providers
if (_hasInstalled)
{
return;
}
_hasInstalled = true;
Assert.IsNull(_container);
_container = parentContainer.CreateSubContainer();
// Do this after creating DiContainer in case it's needed by the pre install logic
if (PreInstall != null)
{
PreInstall();
}
var injectableMonoBehaviours = new List<MonoBehaviour>();
GetInjectableMonoBehaviours(injectableMonoBehaviours);
foreach (var instance in injectableMonoBehaviours)
{
if (instance is MonoKernel)
{
Assert.That(ReferenceEquals(instance, _kernel),
"Found MonoKernel derived class that is not hooked up to GameObjectContext. If you use MonoKernel, you must indicate this to GameObjectContext by dragging and dropping it to the Kernel field in the inspector");
}
_container.QueueForInject(instance);
}
_container.IsInstalling = true;
try
{
InstallBindings(injectableMonoBehaviours);
}
finally
{
_container.IsInstalling = false;
}
if (PostInstall != null)
{
PostInstall();
}
}
void ResolveAndStart()
{
if (PreResolve != null)
{
PreResolve();
}
_container.ResolveRoots();
if (PostResolve != null)
{
PostResolve();
}
// Normally, the IInitializable.Initialize method would be called during MonoKernel.Start
// However, this behaviour is undesirable for dynamically created objects, since Unity
// has the strange behaviour of waiting until the end of the frame to call Start() on
// dynamically created objects, which means that any GameObjectContext that is created
// dynamically via a factory cannot be used immediately after calling Create(), since
// it will not have been initialized
// So we have chosen to diverge from Unity behaviour here and trigger IInitializable.Initialize
// immediately - but only when the GameObjectContext is created dynamically. For any
// GameObjectContext's that are placed in the scene, we still want to execute
// IInitializable.Initialize during Start()
if (gameObject.scene.isLoaded && !_container.IsValidating)
{
_kernel = _container.Resolve<MonoKernel>();
_kernel.Initialize();
}
}
protected override void GetInjectableMonoBehaviours(List<MonoBehaviour> monoBehaviours)
{
ZenUtilInternal.AddStateMachineBehaviourAutoInjectersUnderGameObject(gameObject);
// We inject on all components on the root except ourself
foreach (var monoBehaviour in GetComponents<MonoBehaviour>())
{
if (monoBehaviour == null)
{
// Missing script
continue;
}
if (!ZenUtilInternal.IsInjectableMonoBehaviourType(monoBehaviour.GetType()))
{
continue;
}
if (monoBehaviour == this)
{
continue;
}
monoBehaviours.Add(monoBehaviour);
}
for (int i = 0; i < transform.childCount; i++)
{
var child = transform.GetChild(i);
if (child != null)
{
ZenUtilInternal.GetInjectableMonoBehavioursUnderGameObject(
child.gameObject, monoBehaviours);
}
}
}
void InstallBindings(List<MonoBehaviour> injectableMonoBehaviours)
{
_container.DefaultParent = transform;
_container.Bind<Context>().FromInstance(this);
_container.Bind<GameObjectContext>().FromInstance(this);
if (_kernel == null)
{
_container.Bind<MonoKernel>()
.To<DefaultGameObjectKernel>().FromNewComponentOn(gameObject).AsSingle().NonLazy();
}
else
{
_container.Bind<MonoKernel>().FromInstance(_kernel).AsSingle().NonLazy();
}
InstallSceneBindings(injectableMonoBehaviours);
InstallInstallers();
}
}
}
#endif
| |
//
// Copyright (c) 2008-2011, Kenneth Bell
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
namespace DiscUtils
{
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
/// <summary>
/// The concatenation of multiple streams (read-only, for now).
/// </summary>
internal class ConcatStream : SparseStream
{
private SparseStream[] _streams;
private Ownership _ownsStreams;
private bool _canWrite;
private long _position;
public ConcatStream(Ownership ownsStreams, params SparseStream[] streams)
{
_ownsStreams = ownsStreams;
_streams = streams;
// Only allow writes if all streams can be written
_canWrite = true;
foreach (var stream in streams)
{
if (!stream.CanWrite)
{
_canWrite = false;
}
}
}
public override bool CanRead
{
get
{
CheckDisposed();
return true;
}
}
public override bool CanSeek
{
get
{
CheckDisposed();
return true;
}
}
public override bool CanWrite
{
get
{
CheckDisposed();
return _canWrite;
}
}
public override long Length
{
get
{
CheckDisposed();
long length = 0;
for (int i = 0; i < _streams.Length; ++i)
{
length += _streams[i].Length;
}
return length;
}
}
public override long Position
{
get
{
CheckDisposed();
return _position;
}
set
{
CheckDisposed();
_position = value;
}
}
public override IEnumerable<StreamExtent> Extents
{
get
{
CheckDisposed();
List<StreamExtent> extents = new List<StreamExtent>();
long pos = 0;
for (int i = 0; i < _streams.Length; ++i)
{
foreach (StreamExtent extent in _streams[i].Extents)
{
extents.Add(new StreamExtent(extent.Start + pos, extent.Length));
}
pos += _streams[i].Length;
}
return extents;
}
}
public override void Flush()
{
CheckDisposed();
for (int i = 0; i < _streams.Length; ++i)
{
_streams[i].Flush();
}
}
public override int Read(byte[] buffer, int offset, int count)
{
CheckDisposed();
int totalRead = 0;
int numRead = 0;
do
{
long activeStreamStartPos;
int activeStream = GetActiveStream(out activeStreamStartPos);
_streams[activeStream].Position = _position - activeStreamStartPos;
numRead = _streams[activeStream].Read(buffer, offset + totalRead, count - totalRead);
totalRead += numRead;
_position += numRead;
}
while (numRead != 0);
return totalRead;
}
public override long Seek(long offset, System.IO.SeekOrigin origin)
{
CheckDisposed();
long effectiveOffset = offset;
if (origin == SeekOrigin.Current)
{
effectiveOffset += _position;
}
else if (origin == SeekOrigin.End)
{
effectiveOffset += Length;
}
if (effectiveOffset < 0)
{
throw new IOException("Attempt to move before beginning of disk");
}
else
{
Position = effectiveOffset;
return Position;
}
}
public override void SetLength(long value)
{
CheckDisposed();
long lastStreamOffset;
int lastStream = GetStream(Length, out lastStreamOffset);
if (value < lastStreamOffset)
{
throw new IOException(string.Format(CultureInfo.InvariantCulture, "Unable to reduce stream length to less than {0}", lastStreamOffset));
}
_streams[lastStream].SetLength(value - lastStreamOffset);
}
public override void Write(byte[] buffer, int offset, int count)
{
CheckDisposed();
int totalWritten = 0;
while (totalWritten != count)
{
// Offset of the stream = streamOffset
long streamOffset;
int streamIdx = GetActiveStream(out streamOffset);
// Offset within the stream = streamPos
long streamPos = _position - streamOffset;
_streams[streamIdx].Position = streamPos;
// Write (limited to the stream's length), except for final stream - that may be
// extendable
int numToWrite;
if (streamIdx == _streams.Length - 1)
{
numToWrite = count - totalWritten;
}
else
{
numToWrite = (int)Math.Min(count - totalWritten, _streams[streamIdx].Length - streamPos);
}
_streams[streamIdx].Write(buffer, offset + totalWritten, numToWrite);
totalWritten += numToWrite;
_position += numToWrite;
}
}
protected override void Dispose(bool disposing)
{
try
{
if (disposing && _ownsStreams == Ownership.Dispose && _streams != null)
{
foreach (var stream in _streams)
{
stream.Dispose();
}
_streams = null;
}
}
finally
{
base.Dispose(disposing);
}
}
private int GetActiveStream(out long startPos)
{
return GetStream(_position, out startPos);
}
private int GetStream(long targetPos, out long streamStartPos)
{
// Find the stream that _position is within
streamStartPos = 0;
int focusStream = 0;
while (focusStream < _streams.Length - 1 && streamStartPos + _streams[focusStream].Length <= targetPos)
{
streamStartPos += _streams[focusStream].Length;
focusStream++;
}
return focusStream;
}
private void CheckDisposed()
{
if (_streams == null)
{
throw new ObjectDisposedException("ConcatStream");
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Security.Claims;
using Microsoft.AspNet.Authorization;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Mvc;
using Microsoft.Extensions.Logging;
using Mobile_Digital_Forensics.Models;
using Mobile_Digital_Forensics.Services;
using Mobile_Digital_Forensics.ViewModels.Manage;
namespace Mobile_Digital_Forensics.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);
}
//
// GET: /Manage/RemovePhoneNumber
[HttpGet]
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, User.GetUserId());
return new ChallengeResult(provider, properties);
}
//
// GET: /Manage/LinkLoginCallback
[HttpGet]
public async Task<ActionResult> LinkLoginCallback()
{
var user = await GetCurrentUserAsync();
if (user == null)
{
return View("Error");
}
var info = await _signInManager.GetExternalLoginInfoAsync(User.GetUserId());
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 async Task<ApplicationUser> GetCurrentUserAsync()
{
return await _userManager.FindByIdAsync(HttpContext.User.GetUserId());
}
#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.Collections.Generic;
using System.Linq;
using System.Net.Security;
using System.Net.Test.Common;
using System.Runtime.InteropServices;
using System.Security.Authentication.ExtendedProtection;
using System.Security.Cryptography.X509Certificates;
using System.Threading.Tasks;
using Xunit;
namespace System.Net.Http.Functional.Tests
{
using Configuration = System.Net.Test.Common.Configuration;
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, ".NET Framework throws PNSE for ServerCertificateCustomValidationCallback")]
public abstract partial class HttpClientHandler_ServerCertificates_Test : HttpClientHandlerTestBase
{
private static bool ClientSupportsDHECipherSuites => (!PlatformDetection.IsWindows || PlatformDetection.IsWindows10Version1607OrGreater);
private bool BackendSupportsCustomCertificateHandlingAndClientSupportsDHECipherSuites =>
(BackendSupportsCustomCertificateHandling && ClientSupportsDHECipherSuites);
[Fact]
[SkipOnTargetFramework(~TargetFrameworkMonikers.Uap)]
public void Ctor_ExpectedDefaultPropertyValues_UapPlatform()
{
using (HttpClientHandler handler = CreateHttpClientHandler())
{
Assert.Null(handler.ServerCertificateCustomValidationCallback);
Assert.True(handler.CheckCertificateRevocationList);
}
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.Uap)]
public void Ctor_ExpectedDefaultValues_NotUapPlatform()
{
using (HttpClientHandler handler = CreateHttpClientHandler())
{
Assert.Null(handler.ServerCertificateCustomValidationCallback);
Assert.False(handler.CheckCertificateRevocationList);
}
}
[Fact]
public void ServerCertificateCustomValidationCallback_SetGet_Roundtrips()
{
using (HttpClientHandler handler = CreateHttpClientHandler())
{
Assert.Null(handler.ServerCertificateCustomValidationCallback);
Func<HttpRequestMessage, X509Certificate2, X509Chain, SslPolicyErrors, bool> callback1 = (req, cert, chain, policy) => throw new NotImplementedException("callback1");
Func<HttpRequestMessage, X509Certificate2, X509Chain, SslPolicyErrors, bool> callback2 = (req, cert, chain, policy) => throw new NotImplementedException("callback2");
handler.ServerCertificateCustomValidationCallback = callback1;
Assert.Same(callback1, handler.ServerCertificateCustomValidationCallback);
handler.ServerCertificateCustomValidationCallback = callback2;
Assert.Same(callback2, handler.ServerCertificateCustomValidationCallback);
handler.ServerCertificateCustomValidationCallback = null;
Assert.Null(handler.ServerCertificateCustomValidationCallback);
}
}
[OuterLoop("Uses external server")]
[Fact]
public async Task NoCallback_ValidCertificate_SuccessAndExpectedPropertyBehavior()
{
HttpClientHandler handler = CreateHttpClientHandler();
using (var client = new HttpClient(handler))
{
using (HttpResponseMessage response = await client.GetAsync(Configuration.Http.SecureRemoteEchoServer))
{
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
}
Assert.Throws<InvalidOperationException>(() => handler.ServerCertificateCustomValidationCallback = null);
Assert.Throws<InvalidOperationException>(() => handler.CheckCertificateRevocationList = false);
}
}
[SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "UAP won't send requests through a custom proxy")]
[OuterLoop("Uses external server")]
[Fact]
public async Task UseCallback_HaveCredsAndUseAuthenticatedCustomProxyAndPostToSecureServer_Success()
{
if (!BackendSupportsCustomCertificateHandling)
{
return;
}
if (IsWinHttpHandler && PlatformDetection.IsWindows7)
{
// Issue #27612
return;
}
var options = new LoopbackProxyServer.Options
{ AuthenticationSchemes = AuthenticationSchemes.Basic,
ConnectionCloseAfter407 = true
};
using (LoopbackProxyServer proxyServer = LoopbackProxyServer.Create(options))
{
HttpClientHandler handler = CreateHttpClientHandler();
handler.ServerCertificateCustomValidationCallback = delegate { return true; };
handler.Proxy = new WebProxy(proxyServer.Uri)
{
Credentials = new NetworkCredential("rightusername", "rightpassword")
};
const string content = "This is a test";
using (var client = new HttpClient(handler))
using (HttpResponseMessage response = await client.PostAsync(
Configuration.Http.SecureRemoteEchoServer,
new StringContent(content)))
{
string responseContent = await response.Content.ReadAsStringAsync();
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
TestHelper.VerifyResponseBody(
responseContent,
response.Content.Headers.ContentMD5,
false,
content);
}
}
}
[SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "UAP won't send requests through a custom proxy")]
[OuterLoop("Uses external server")]
[Fact]
public async Task UseCallback_HaveNoCredsAndUseAuthenticatedCustomProxyAndPostToSecureServer_ProxyAuthenticationRequiredStatusCode()
{
if (!BackendSupportsCustomCertificateHandling)
{
return;
}
var options = new LoopbackProxyServer.Options
{ AuthenticationSchemes = AuthenticationSchemes.Basic,
ConnectionCloseAfter407 = true
};
using (LoopbackProxyServer proxyServer = LoopbackProxyServer.Create(options))
{
HttpClientHandler handler = CreateHttpClientHandler();
handler.Proxy = new WebProxy(proxyServer.Uri);
handler.ServerCertificateCustomValidationCallback = delegate { return true; };
using (var client = new HttpClient(handler))
using (HttpResponseMessage response = await client.PostAsync(
Configuration.Http.SecureRemoteEchoServer,
new StringContent("This is a test")))
{
Assert.Equal(HttpStatusCode.ProxyAuthenticationRequired, response.StatusCode);
}
}
}
[OuterLoop("Uses external server")]
[Fact]
public async Task UseCallback_NotSecureConnection_CallbackNotCalled()
{
if (!BackendSupportsCustomCertificateHandling)
{
Console.WriteLine($"Skipping {nameof(UseCallback_NotSecureConnection_CallbackNotCalled)}()");
return;
}
HttpClientHandler handler = CreateHttpClientHandler();
using (var client = new HttpClient(handler))
{
bool callbackCalled = false;
handler.ServerCertificateCustomValidationCallback = delegate { callbackCalled = true; return true; };
using (HttpResponseMessage response = await client.GetAsync(Configuration.Http.RemoteEchoServer))
{
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
}
Assert.False(callbackCalled);
}
}
public static IEnumerable<object[]> UseCallback_ValidCertificate_ExpectedValuesDuringCallback_Urls()
{
foreach (bool checkRevocation in new[] { true, false })
{
yield return new object[] { Configuration.Http.SecureRemoteEchoServer, checkRevocation };
yield return new object[] {
Configuration.Http.RedirectUriForDestinationUri(
secure:true,
statusCode:302,
destinationUri:Configuration.Http.SecureRemoteEchoServer,
hops:1),
checkRevocation };
}
}
[OuterLoop("Uses external server")]
[Theory]
[MemberData(nameof(UseCallback_ValidCertificate_ExpectedValuesDuringCallback_Urls))]
public async Task UseCallback_ValidCertificate_ExpectedValuesDuringCallback(Uri url, bool checkRevocation)
{
if (!BackendSupportsCustomCertificateHandling)
{
Console.WriteLine($"Skipping {nameof(UseCallback_ValidCertificate_ExpectedValuesDuringCallback)}({url}, {checkRevocation})");
return;
}
HttpClientHandler handler = CreateHttpClientHandler();
using (var client = new HttpClient(handler))
{
bool callbackCalled = false;
handler.CheckCertificateRevocationList = checkRevocation;
handler.ServerCertificateCustomValidationCallback = (request, cert, chain, errors) => {
callbackCalled = true;
Assert.NotNull(request);
X509ChainStatusFlags flags = chain.ChainStatus.Aggregate(X509ChainStatusFlags.NoError, (cur, status) => cur | status.Status);
bool ignoreErrors = // https://github.com/dotnet/corefx/issues/21922#issuecomment-315555237
RuntimeInformation.IsOSPlatform(OSPlatform.OSX) &&
checkRevocation &&
errors == SslPolicyErrors.RemoteCertificateChainErrors &&
flags == X509ChainStatusFlags.RevocationStatusUnknown;
Assert.True(ignoreErrors || errors == SslPolicyErrors.None, $"Expected {SslPolicyErrors.None}, got {errors} with chain status {flags}");
Assert.True(chain.ChainElements.Count > 0);
Assert.NotEmpty(cert.Subject);
// UWP always uses CheckCertificateRevocationList=true regardless of setting the property and
// the getter always returns true. So, for this next Assert, it is better to get the property
// value back from the handler instead of using the parameter value of the test.
Assert.Equal(
handler.CheckCertificateRevocationList ? X509RevocationMode.Online : X509RevocationMode.NoCheck,
chain.ChainPolicy.RevocationMode);
return true;
};
using (HttpResponseMessage response = await client.GetAsync(url))
{
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
}
Assert.True(callbackCalled);
}
}
[OuterLoop("Uses external server")]
[Fact]
public async Task UseCallback_CallbackReturnsFailure_ThrowsException()
{
if (!BackendSupportsCustomCertificateHandling)
{
Console.WriteLine($"Skipping {nameof(UseCallback_CallbackReturnsFailure_ThrowsException)}()");
return;
}
HttpClientHandler handler = CreateHttpClientHandler();
using (var client = new HttpClient(handler))
{
handler.ServerCertificateCustomValidationCallback = delegate { return false; };
await Assert.ThrowsAsync<HttpRequestException>(() => client.GetAsync(Configuration.Http.SecureRemoteEchoServer));
}
}
[OuterLoop("Uses external server")]
[Fact]
public async Task UseCallback_CallbackThrowsException_ExceptionPropagatesAsBaseException()
{
if (!BackendSupportsCustomCertificateHandling)
{
Console.WriteLine($"Skipping {nameof(UseCallback_CallbackThrowsException_ExceptionPropagatesAsBaseException)}()");
return;
}
HttpClientHandler handler = CreateHttpClientHandler();
using (var client = new HttpClient(handler))
{
var e = new DivideByZeroException();
handler.ServerCertificateCustomValidationCallback = delegate { throw e; };
HttpRequestException ex = await Assert.ThrowsAsync<HttpRequestException>(() => client.GetAsync(Configuration.Http.SecureRemoteEchoServer));
Assert.Same(e, ex.GetBaseException());
}
}
public static readonly object[][] CertificateValidationServers =
{
new object[] { Configuration.Http.ExpiredCertRemoteServer },
new object[] { Configuration.Http.SelfSignedCertRemoteServer },
new object[] { Configuration.Http.WrongHostNameCertRemoteServer },
};
[OuterLoop("Uses external server")]
[ConditionalTheory(nameof(ClientSupportsDHECipherSuites))]
[MemberData(nameof(CertificateValidationServers))]
public async Task NoCallback_BadCertificate_ThrowsException(string url)
{
using (HttpClient client = CreateHttpClient())
{
await Assert.ThrowsAsync<HttpRequestException>(() => client.GetAsync(url));
}
}
[SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "UAP doesn't allow revocation checking to be turned off")]
[OuterLoop("Uses external server")]
[ConditionalFact(nameof(ClientSupportsDHECipherSuites))]
public async Task NoCallback_RevokedCertificate_NoRevocationChecking_Succeeds()
{
// On macOS (libcurl+darwinssl) we cannot turn revocation off.
// But we also can't realistically say that the default value for
// CheckCertificateRevocationList throws in the general case.
try
{
using (HttpClient client = CreateHttpClient())
using (HttpResponseMessage response = await client.GetAsync(Configuration.Http.RevokedCertRemoteServer))
{
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
}
}
catch (HttpRequestException)
{
if (UseSocketsHttpHandler || !ShouldSuppressRevocationException)
throw;
}
}
[OuterLoop("Uses external server")]
[Fact]
public async Task NoCallback_RevokedCertificate_RevocationChecking_Fails()
{
if (!BackendSupportsCustomCertificateHandling)
{
Console.WriteLine($"Skipping {nameof(NoCallback_RevokedCertificate_RevocationChecking_Fails)}()");
return;
}
HttpClientHandler handler = CreateHttpClientHandler();
handler.CheckCertificateRevocationList = true;
using (var client = new HttpClient(handler))
{
await Assert.ThrowsAsync<HttpRequestException>(() => client.GetAsync(Configuration.Http.RevokedCertRemoteServer));
}
}
public static readonly object[][] CertificateValidationServersAndExpectedPolicies =
{
new object[] { Configuration.Http.ExpiredCertRemoteServer, SslPolicyErrors.RemoteCertificateChainErrors },
new object[] { Configuration.Http.SelfSignedCertRemoteServer, SslPolicyErrors.RemoteCertificateChainErrors },
new object[] { Configuration.Http.WrongHostNameCertRemoteServer , SslPolicyErrors.RemoteCertificateNameMismatch},
};
private async Task UseCallback_BadCertificate_ExpectedPolicyErrors_Helper(string url, bool useSocketsHttpHandler, SslPolicyErrors expectedErrors)
{
if (!BackendSupportsCustomCertificateHandling)
{
Console.WriteLine($"Skipping {nameof(UseCallback_BadCertificate_ExpectedPolicyErrors)}({url}, {expectedErrors})");
return;
}
HttpClientHandler handler = CreateHttpClientHandler(useSocketsHttpHandler);
using (var client = new HttpClient(handler))
{
bool callbackCalled = false;
handler.ServerCertificateCustomValidationCallback = (request, cert, chain, errors) =>
{
callbackCalled = true;
Assert.NotNull(request);
Assert.NotNull(cert);
Assert.NotNull(chain);
Assert.Equal(expectedErrors, errors);
return true;
};
using (HttpResponseMessage response = await client.GetAsync(url))
{
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
}
Assert.True(callbackCalled);
}
}
[ActiveIssue(30054, TargetFrameworkMonikers.Uap)]
[OuterLoop("Uses external server")]
[Theory]
[MemberData(nameof(CertificateValidationServersAndExpectedPolicies))]
public async Task UseCallback_BadCertificate_ExpectedPolicyErrors(string url, SslPolicyErrors expectedErrors)
{
const int SEC_E_BUFFER_TOO_SMALL = unchecked((int)0x80090321);
if (!BackendSupportsCustomCertificateHandlingAndClientSupportsDHECipherSuites)
{
return;
}
try
{
if (PlatformDetection.IsUap)
{
// UAP HTTP stack caches connections per-process. This causes interference when these tests run in
// the same process as the other tests. Each test needs to be isolated to its own process.
// See dicussion: https://github.com/dotnet/corefx/issues/21945
RemoteInvoke((remoteUrl, remoteExpectedErrors, useSocketsHttpHandlerString) =>
{
UseCallback_BadCertificate_ExpectedPolicyErrors_Helper(
remoteUrl,
bool.Parse(useSocketsHttpHandlerString),
(SslPolicyErrors)Enum.Parse(typeof(SslPolicyErrors), remoteExpectedErrors)).Wait();
return SuccessExitCode;
}, url, expectedErrors.ToString(), UseSocketsHttpHandler.ToString()).Dispose();
}
else
{
await UseCallback_BadCertificate_ExpectedPolicyErrors_Helper(url, UseSocketsHttpHandler, expectedErrors);
}
}
catch (HttpRequestException e) when (e.InnerException?.GetType().Name == "WinHttpException" &&
e.InnerException.HResult == SEC_E_BUFFER_TOO_SMALL &&
!PlatformDetection.IsWindows10Version1607OrGreater)
{
// Testing on old Windows versions can hit https://github.com/dotnet/corefx/issues/7812
// Ignore SEC_E_BUFFER_TOO_SMALL error on such cases.
}
}
[OuterLoop("Uses external server")]
[Fact]
public async Task SSLBackendNotSupported_Callback_ThrowsPlatformNotSupportedException()
{
if (BackendSupportsCustomCertificateHandling)
{
return;
}
HttpClientHandler handler = CreateHttpClientHandler();
handler.ServerCertificateCustomValidationCallback = delegate { return true; };
using (var client = new HttpClient(handler))
{
await Assert.ThrowsAsync<PlatformNotSupportedException>(() => client.GetAsync(Configuration.Http.SecureRemoteEchoServer));
}
}
[OuterLoop("Uses external server")]
[Fact]
// For macOS the "custom handling" means that revocation can't be *disabled*. So this test does not apply.
[PlatformSpecific(~TestPlatforms.OSX)]
public async Task SSLBackendNotSupported_Revocation_ThrowsPlatformNotSupportedException()
{
if (BackendSupportsCustomCertificateHandling)
{
return;
}
HttpClientHandler handler = CreateHttpClientHandler();
handler.CheckCertificateRevocationList = true;
using (var client = new HttpClient(handler))
{
await Assert.ThrowsAsync<PlatformNotSupportedException>(() => client.GetAsync(Configuration.Http.SecureRemoteEchoServer));
}
}
[OuterLoop("Uses external server")]
[PlatformSpecific(TestPlatforms.Windows)] // CopyToAsync(Stream, TransportContext) isn't used on unix
[Fact]
public async Task PostAsync_Post_ChannelBinding_ConfiguredCorrectly()
{
var content = new ChannelBindingAwareContent("Test contest");
using (HttpClient client = CreateHttpClient())
using (HttpResponseMessage response = await client.PostAsync(Configuration.Http.SecureRemoteEchoServer, content))
{
// Validate status.
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
// Validate the ChannelBinding object exists.
ChannelBinding channelBinding = content.ChannelBinding;
if (PlatformDetection.IsUap)
{
// UAP currently doesn't expose channel binding information.
Assert.Null(channelBinding);
}
else
{
Assert.NotNull(channelBinding);
// Validate the ChannelBinding's validity.
if (BackendSupportsCustomCertificateHandling)
{
Assert.False(channelBinding.IsInvalid, "Expected valid binding");
Assert.NotEqual(IntPtr.Zero, channelBinding.DangerousGetHandle());
// Validate the ChannelBinding's description.
string channelBindingDescription = channelBinding.ToString();
Assert.NotNull(channelBindingDescription);
Assert.NotEmpty(channelBindingDescription);
Assert.True((channelBindingDescription.Length + 1) % 3 == 0, $"Unexpected length {channelBindingDescription.Length}");
for (int i = 0; i < channelBindingDescription.Length; i++)
{
char c = channelBindingDescription[i];
if (i % 3 == 2)
{
Assert.Equal(' ', c);
}
else
{
Assert.True((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F'), $"Expected hex, got {c}");
}
}
}
else
{
// Backend doesn't support getting the details to create the CBT.
Assert.True(channelBinding.IsInvalid, "Expected invalid binding");
Assert.Equal(IntPtr.Zero, channelBinding.DangerousGetHandle());
Assert.Null(channelBinding.ToString());
}
}
}
}
}
}
| |
using System;
namespace Lucene.Net.Codecs.Lucene40
{
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using IndexFileNames = Lucene.Net.Index.IndexFileNames;
using SegmentReadState = Lucene.Net.Index.SegmentReadState;
using SegmentWriteState = Lucene.Net.Index.SegmentWriteState;
/// <summary>
/// Lucene 4.0 DocValues format.
/// <para/>
/// Files:
/// <list type="bullet">
/// <item><description><c>.dv.cfs</c>: compound container (<see cref="Store.CompoundFileDirectory"/>)</description></item>
/// <item><description><c>.dv.cfe</c>: compound entries (<see cref="Store.CompoundFileDirectory"/>)</description></item>
/// </list>
/// Entries within the compound file:
/// <list type="bullet">
/// <item><description><c><segment>_<fieldNumber>.dat</c>: data values</description></item>
/// <item><description><c><segment>_<fieldNumber>.idx</c>: index into the .dat for DEREF types</description></item>
/// </list>
/// <para>
/// There are several many types of <see cref="Index.DocValues"/> with different encodings.
/// From the perspective of filenames, all types store their values in <c>.dat</c>
/// entries within the compound file. In the case of dereferenced/sorted types, the <c>.dat</c>
/// actually contains only the unique values, and an additional <c>.idx</c> file contains
/// pointers to these unique values.
/// </para>
/// Formats:
/// <list type="bullet">
/// <item><description><see cref="LegacyDocValuesType.VAR_INTS"/> .dat --> Header, PackedType, MinValue,
/// DefaultValue, PackedStream</description></item>
/// <item><description><see cref="LegacyDocValuesType.FIXED_INTS_8"/> .dat --> Header, ValueSize,
/// Byte (<see cref="Store.DataOutput.WriteByte(byte)"/>) <sup>maxdoc</sup></description></item>
/// <item><description><see cref="LegacyDocValuesType.FIXED_INTS_16"/> .dat --> Header, ValueSize,
/// Short (<see cref="Store.DataOutput.WriteInt16(short)"/>) <sup>maxdoc</sup></description></item>
/// <item><description><see cref="LegacyDocValuesType.FIXED_INTS_32"/> .dat --> Header, ValueSize,
/// Int32 (<see cref="Store.DataOutput.WriteInt32(int)"/>) <sup>maxdoc</sup></description></item>
/// <item><description><see cref="LegacyDocValuesType.FIXED_INTS_64"/> .dat --> Header, ValueSize,
/// Int64 (<see cref="Store.DataOutput.WriteInt64(long)"/>) <sup>maxdoc</sup></description></item>
/// <item><description><see cref="LegacyDocValuesType.FLOAT_32"/> .dat --> Header, ValueSize, Float32<sup>maxdoc</sup></description></item>
/// <item><description><see cref="LegacyDocValuesType.FLOAT_64"/> .dat --> Header, ValueSize, Float64<sup>maxdoc</sup></description></item>
/// <item><description><see cref="LegacyDocValuesType.BYTES_FIXED_STRAIGHT"/> .dat --> Header, ValueSize,
/// (Byte (<see cref="Store.DataOutput.WriteByte(byte)"/>) * ValueSize)<sup>maxdoc</sup></description></item>
/// <item><description><see cref="LegacyDocValuesType.BYTES_VAR_STRAIGHT"/> .idx --> Header, TotalBytes, Addresses</description></item>
/// <item><description><see cref="LegacyDocValuesType.BYTES_VAR_STRAIGHT"/> .dat --> Header,
/// (Byte (<see cref="Store.DataOutput.WriteByte(byte)"/>) * <i>variable ValueSize</i>)<sup>maxdoc</sup></description></item>
/// <item><description><see cref="LegacyDocValuesType.BYTES_FIXED_DEREF"/> .idx --> Header, NumValues, Addresses</description></item>
/// <item><description><see cref="LegacyDocValuesType.BYTES_FIXED_DEREF"/> .dat --> Header, ValueSize,
/// (Byte (<see cref="Store.DataOutput.WriteByte(byte)"/>) * ValueSize)<sup>NumValues</sup></description></item>
/// <item><description><see cref="LegacyDocValuesType.BYTES_VAR_DEREF"/> .idx --> Header, TotalVarBytes, Addresses</description></item>
/// <item><description><see cref="LegacyDocValuesType.BYTES_VAR_DEREF"/> .dat --> Header,
/// (LengthPrefix + Byte (<see cref="Store.DataOutput.WriteByte(byte)"/>) * <i>variable ValueSize</i>)<sup>NumValues</sup></description></item>
/// <item><description><see cref="LegacyDocValuesType.BYTES_FIXED_SORTED"/> .idx --> Header, NumValues, Ordinals</description></item>
/// <item><description><see cref="LegacyDocValuesType.BYTES_FIXED_SORTED"/> .dat --> Header, ValueSize,
/// (Byte (<see cref="Store.DataOutput.WriteByte(byte)"/>) * ValueSize)<sup>NumValues</sup></description></item>
/// <item><description><see cref="LegacyDocValuesType.BYTES_VAR_SORTED"/> .idx --> Header, TotalVarBytes, Addresses, Ordinals</description></item>
/// <item><description><see cref="LegacyDocValuesType.BYTES_VAR_SORTED"/> .dat --> Header,
/// (Byte (<see cref="Store.DataOutput.WriteByte(byte)"/>) * <i>variable ValueSize</i>)<sup>NumValues</sup></description></item>
/// </list>
/// Data Types:
/// <list type="bullet">
/// <item><description>Header --> CodecHeader (<see cref="CodecUtil.WriteHeader(Store.DataOutput, string, int)"/>) </description></item>
/// <item><description>PackedType --> Byte (<see cref="Store.DataOutput.WriteByte(byte)"/>)</description></item>
/// <item><description>MaxAddress, MinValue, DefaultValue --> Int64 (<see cref="Store.DataOutput.WriteInt64(long)"/>) </description></item>
/// <item><description>PackedStream, Addresses, Ordinals --> <see cref="Util.Packed.PackedInt32s"/></description></item>
/// <item><description>ValueSize, NumValues --> Int32 (<see cref="Store.DataOutput.WriteInt32(int)"/>) </description></item>
/// <item><description>Float32 --> 32-bit float encoded with <see cref="Support.Number.SingleToRawInt32Bits(float)"/>
/// then written as Int32 (<see cref="Store.DataOutput.WriteInt32(int)"/>) </description></item>
/// <item><description>Float64 --> 64-bit float encoded with <see cref="Support.Number.DoubleToRawInt64Bits(double)"/>
/// then written as Int64 (<see cref="Store.DataOutput.WriteInt64(long)"/>) </description></item>
/// <item><description>TotalBytes --> VLong (<see cref="Store.DataOutput.WriteVInt64(long)"/>) </description></item>
/// <item><description>TotalVarBytes --> Int64 (<see cref="Store.DataOutput.WriteInt64(long)"/>) </description></item>
/// <item><description>LengthPrefix --> Length of the data value as VInt (<see cref="Store.DataOutput.WriteVInt32(int)"/>) (maximum
/// of 2 bytes)</description></item>
/// </list>
/// Notes:
/// <list type="bullet">
/// <item><description>PackedType is a 0 when compressed, 1 when the stream is written as 64-bit integers.</description></item>
/// <item><description>Addresses stores pointers to the actual byte location (indexed by docid). In the VAR_STRAIGHT
/// case, each entry can have a different length, so to determine the length, docid+1 is
/// retrieved. A sentinel address is written at the end for the VAR_STRAIGHT case, so the Addresses
/// stream contains maxdoc+1 indices. For the deduplicated VAR_DEREF case, each length
/// is encoded as a prefix to the data itself as a VInt (<see cref="Store.DataOutput.WriteVInt32(int)"/>)
/// (maximum of 2 bytes).</description></item>
/// <item><description>Ordinals stores the term ID in sorted order (indexed by docid). In the FIXED_SORTED case,
/// the address into the .dat can be computed from the ordinal as
/// <c>Header+ValueSize+(ordinal*ValueSize)</c> because the byte length is fixed.
/// In the VAR_SORTED case, there is double indirection (docid -> ordinal -> address), but
/// an additional sentinel ordinal+address is always written (so there are NumValues+1 ordinals). To
/// determine the length, ord+1's address is looked up as well.</description></item>
/// <item><description><see cref="LegacyDocValuesType.BYTES_VAR_STRAIGHT"/> in contrast to other straight
/// variants uses a <c>.idx</c> file to improve lookup perfromance. In contrast to
/// <see cref="LegacyDocValuesType.BYTES_VAR_DEREF"/> it doesn't apply deduplication of the document values.
/// </description></item>
/// </list>
/// <para/>
/// Limitations:
/// <list type="bullet">
/// <item><description> Binary doc values can be at most <see cref="MAX_BINARY_FIELD_LENGTH"/> in length.</description></item>
/// </list>
/// </summary>
[Obsolete("Only for reading old 4.0 and 4.1 segments")]
[DocValuesFormatName("Lucene40")] // LUCENENET specific - using DocValuesFormatName attribute to ensure the default name passed from subclasses is the same as this class name
public class Lucene40DocValuesFormat : DocValuesFormat
// NOTE: not registered in SPI, doesnt respect segment suffix, etc
// for back compat only!
{
/// <summary>
/// Maximum length for each binary doc values field. </summary>
public static readonly int MAX_BINARY_FIELD_LENGTH = (1 << 15) - 2;
/// <summary>
/// Sole constructor. </summary>
public Lucene40DocValuesFormat()
: base()
{
}
public override DocValuesConsumer FieldsConsumer(SegmentWriteState state)
{
throw new System.NotSupportedException("this codec can only be used for reading");
}
public override DocValuesProducer FieldsProducer(SegmentReadState state)
{
string filename = IndexFileNames.SegmentFileName(state.SegmentInfo.Name, "dv", IndexFileNames.COMPOUND_FILE_EXTENSION);
return new Lucene40DocValuesReader(state, filename, Lucene40FieldInfosReader.LEGACY_DV_TYPE_KEY);
}
// constants for VAR_INTS
internal const string VAR_INTS_CODEC_NAME = "PackedInts";
internal const int VAR_INTS_VERSION_START = 0;
internal const int VAR_INTS_VERSION_CURRENT = VAR_INTS_VERSION_START;
internal const sbyte VAR_INTS_PACKED = 0x00;
internal const sbyte VAR_INTS_FIXED_64 = 0x01;
// constants for FIXED_INTS_8, FIXED_INTS_16, FIXED_INTS_32, FIXED_INTS_64
internal const string INTS_CODEC_NAME = "Ints";
internal const int INTS_VERSION_START = 0;
internal const int INTS_VERSION_CURRENT = INTS_VERSION_START;
// constants for FLOAT_32, FLOAT_64
internal const string FLOATS_CODEC_NAME = "Floats";
internal const int FLOATS_VERSION_START = 0;
internal const int FLOATS_VERSION_CURRENT = FLOATS_VERSION_START;
// constants for BYTES_FIXED_STRAIGHT
internal const string BYTES_FIXED_STRAIGHT_CODEC_NAME = "FixedStraightBytes";
internal const int BYTES_FIXED_STRAIGHT_VERSION_START = 0;
internal const int BYTES_FIXED_STRAIGHT_VERSION_CURRENT = BYTES_FIXED_STRAIGHT_VERSION_START;
// constants for BYTES_VAR_STRAIGHT
internal const string BYTES_VAR_STRAIGHT_CODEC_NAME_IDX = "VarStraightBytesIdx";
internal const string BYTES_VAR_STRAIGHT_CODEC_NAME_DAT = "VarStraightBytesDat";
internal const int BYTES_VAR_STRAIGHT_VERSION_START = 0;
internal const int BYTES_VAR_STRAIGHT_VERSION_CURRENT = BYTES_VAR_STRAIGHT_VERSION_START;
// constants for BYTES_FIXED_DEREF
internal const string BYTES_FIXED_DEREF_CODEC_NAME_IDX = "FixedDerefBytesIdx";
internal const string BYTES_FIXED_DEREF_CODEC_NAME_DAT = "FixedDerefBytesDat";
internal const int BYTES_FIXED_DEREF_VERSION_START = 0;
internal const int BYTES_FIXED_DEREF_VERSION_CURRENT = BYTES_FIXED_DEREF_VERSION_START;
// constants for BYTES_VAR_DEREF
internal const string BYTES_VAR_DEREF_CODEC_NAME_IDX = "VarDerefBytesIdx";
internal const string BYTES_VAR_DEREF_CODEC_NAME_DAT = "VarDerefBytesDat";
internal const int BYTES_VAR_DEREF_VERSION_START = 0;
internal const int BYTES_VAR_DEREF_VERSION_CURRENT = BYTES_VAR_DEREF_VERSION_START;
// constants for BYTES_FIXED_SORTED
internal const string BYTES_FIXED_SORTED_CODEC_NAME_IDX = "FixedSortedBytesIdx";
internal const string BYTES_FIXED_SORTED_CODEC_NAME_DAT = "FixedSortedBytesDat";
internal const int BYTES_FIXED_SORTED_VERSION_START = 0;
internal const int BYTES_FIXED_SORTED_VERSION_CURRENT = BYTES_FIXED_SORTED_VERSION_START;
// constants for BYTES_VAR_SORTED
// NOTE this IS NOT A BUG! 4.0 actually screwed this up (VAR_SORTED and VAR_DEREF have same codec header)
internal const string BYTES_VAR_SORTED_CODEC_NAME_IDX = "VarDerefBytesIdx";
internal const string BYTES_VAR_SORTED_CODEC_NAME_DAT = "VarDerefBytesDat";
internal const int BYTES_VAR_SORTED_VERSION_START = 0;
internal const int BYTES_VAR_SORTED_VERSION_CURRENT = BYTES_VAR_SORTED_VERSION_START;
}
}
| |
using ICSharpCode.SharpZipLib.Checksum;
using ICSharpCode.SharpZipLib.Zip.Compression.Streams;
using System;
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>IsNeedingInput() returns true because the input buffer is empty.
/// You have to provide more input with <code>SetInput()</code>.
/// NOTE: IsNeedingInput() also returns true when, the stream is finished.
/// </li>
/// <li>IsNeedingDictionary() returns true, you have to provide a preset
/// dictionary with <code>SetDictionary()</code>.</li>
/// <li>IsFinished 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
{
#region Constants/Readonly
/// <summary>
/// Copy lengths for literal codes 257..285
/// </summary>
private static readonly 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>
private static readonly 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>
private static readonly 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>
private static readonly 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>
private const int DECODE_HEADER = 0;
private const int DECODE_DICT = 1;
private const int DECODE_BLOCKS = 2;
private const int DECODE_STORED_LEN1 = 3;
private const int DECODE_STORED_LEN2 = 4;
private const int DECODE_STORED = 5;
private const int DECODE_DYN_HEADER = 6;
private const int DECODE_HUFFMAN = 7;
private const int DECODE_HUFFMAN_LENBITS = 8;
private const int DECODE_HUFFMAN_DIST = 9;
private const int DECODE_HUFFMAN_DISTBITS = 10;
private const int DECODE_CHKSUM = 11;
private const int FINISHED = 12;
#endregion Constants/Readonly
#region Instance Fields
/// <summary>
/// This variable contains the current state.
/// </summary>
private 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>
private 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>
private int neededBits;
private int repLength;
private int repDist;
private 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>
private bool isLastBlock;
/// <summary>
/// The total number of inflated bytes.
/// </summary>
private long 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>
private long 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>
private bool noHeader;
private readonly StreamManipulator input;
private OutputWindow outputWindow;
private InflaterDynHeader dynHeader;
private InflaterHuffmanTree litlenTree, distTree;
private Adler32 adler;
#endregion Instance Fields
#region Constructors
/// <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;
if (!noHeader)
this.adler = new Adler32();
input = new StreamManipulator();
outputWindow = new OutputWindow();
mode = noHeader ? DECODE_BLOCKS : DECODE_HEADER;
}
#endregion Constructors
/// <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 = 0;
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="SharpZipBaseException">
/// 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 SharpZipBaseException("Header checksum illegal");
}
if ((header & 0x0f00) != (Deflater.DEFLATED << 8))
{
throw new SharpZipBaseException("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="SharpZipBaseException">
/// 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 SharpZipBaseException("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 SharpZipBaseException("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 SharpZipBaseException("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="SharpZipBaseException">
/// 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 SharpZipBaseException("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="SharpZipBaseException">
/// 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);
isLastBlock |= (type & 1) != 0;
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(input);
mode = DECODE_DYN_HEADER;
break;
default:
throw new SharpZipBaseException("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 SharpZipBaseException("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.AttemptRead())
{
return false;
}
litlenTree = dynHeader.LiteralLengthTree;
distTree = dynHeader.DistanceTree;
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 SharpZipBaseException("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>
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="index">
/// The index into buffer where the dictionary starts.
/// </param>
/// <param name="count">
/// The number of bytes in the dictionary.
/// </param>
/// <exception cref="System.InvalidOperationException">
/// No dictionary is needed.
/// </exception>
/// <exception cref="SharpZipBaseException">
/// The adler checksum for the buffer is invalid
/// </exception>
public void SetDictionary(byte[] buffer, int index, int count)
{
if (buffer == null)
{
throw new ArgumentNullException(nameof(buffer));
}
if (index < 0)
{
throw new ArgumentOutOfRangeException(nameof(index));
}
if (count < 0)
{
throw new ArgumentOutOfRangeException(nameof(count));
}
if (!IsNeedingDictionary)
{
throw new InvalidOperationException("Dictionary is not needed");
}
adler?.Update(new ArraySegment<byte>(buffer, index, count));
if (adler != null && (int)adler.Value != readAdler)
{
throw new SharpZipBaseException("Wrong adler checksum");
}
adler?.Reset();
outputWindow.CopyDict(buffer, index, count);
mode = DECODE_BLOCKS;
}
/// <summary>
/// Sets the input. This should only be called, if needsInput()
/// returns true.
/// </summary>
/// <param name="buffer">
/// the input.
/// </param>
public void SetInput(byte[] buffer)
{
SetInput(buffer, 0, buffer.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="index">
/// The index into buffer where the input starts.
/// </param>
/// <param name="count">
/// The number of bytes of input to use.
/// </param>
/// <exception cref="System.InvalidOperationException">
/// No input is needed.
/// </exception>
/// <exception cref="System.ArgumentOutOfRangeException">
/// The index and/or count are wrong.
/// </exception>
public void SetInput(byte[] buffer, int index, int count)
{
input.SetInput(buffer, index, count);
totalIn += (long)count;
}
/// <summary>
/// Inflates the compressed stream to the output buffer. If this
/// returns 0, you should check, whether IsNeedingDictionary(),
/// IsNeedingInput() or IsFinished() returns true, to determine why no
/// further output is produced.
/// </summary>
/// <param name="buffer">
/// 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 buffer has length 0.
/// </exception>
/// <exception cref="System.FormatException">
/// if deflated stream is invalid.
/// </exception>
public int Inflate(byte[] buffer)
{
if (buffer == null)
{
throw new ArgumentNullException(nameof(buffer));
}
return Inflate(buffer, 0, buffer.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="buffer">
/// the output buffer.
/// </param>
/// <param name="offset">
/// the offset in buffer where storing starts.
/// </param>
/// <param name="count">
/// the maximum number of bytes to 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 count is less than 0.
/// </exception>
/// <exception cref="System.ArgumentOutOfRangeException">
/// if the index and / or count are wrong.
/// </exception>
/// <exception cref="System.FormatException">
/// if deflated stream is invalid.
/// </exception>
public int Inflate(byte[] buffer, int offset, int count)
{
if (buffer == null)
{
throw new ArgumentNullException(nameof(buffer));
}
if (count < 0)
{
throw new ArgumentOutOfRangeException(nameof(count), "count cannot be negative");
}
if (offset < 0)
{
throw new ArgumentOutOfRangeException(nameof(offset), "offset cannot be negative");
}
if (offset + count > buffer.Length)
{
throw new ArgumentException("count exceeds buffer bounds");
}
// Special case: count may be zero
if (count == 0)
{
if (!IsFinished)
{ // -jr- 08-Nov-2003 INFLATE_BUG fix..
Decode();
}
return 0;
}
int bytesCopied = 0;
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:
* IsNeedingInput() and not IsFinished()
* implies more output can be produced.
*/
int more = outputWindow.CopyOutput(buffer, offset, count);
if (more > 0)
{
adler?.Update(new ArraySegment<byte>(buffer, offset, more));
offset += more;
bytesCopied += more;
totalOut += (long)more;
count -= more;
if (count == 0)
{
return bytesCopied;
}
}
}
} while (Decode() || ((outputWindow.GetAvailable() > 0) && (mode != DECODE_CHKSUM)));
return bytesCopied;
}
/// <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
{
if (IsNeedingDictionary)
{
return readAdler;
}
else if (adler != null)
{
return (int)adler.Value;
}
else
{
return 0;
}
}
}
/// <summary>
/// Gets the total number of output bytes returned by Inflate().
/// </summary>
/// <returns>
/// the total number of output bytes.
/// </returns>
public long 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 long TotalIn
{
get
{
return totalIn - (long)RemainingInput;
}
}
/// <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
{
// TODO: This should be a long?
get
{
return input.AvailableBytes;
}
}
}
}
| |
#region License
/*
* All content copyright Terracotta, Inc., unless otherwise indicated. 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.
*
*/
#endregion
using System;
using System.Globalization;
using Common.Logging;
using Quartz.Impl.Matchers;
using Quartz.Spi;
namespace Quartz.Plugin.History
{
/// <summary>
/// Logs a history of all trigger firings via the Jakarta Commons-Logging
/// framework.
/// </summary>
/// <remarks>
/// <para>
/// The logged message is customizable by setting one of the following message
/// properties to a string that conforms to the syntax of <see cref="String.Format(string, object[])" />.
/// </para>
///
/// <para>
/// TriggerFiredMessage - available message data are: <table>
/// <tr>
/// <th>Element</th>
/// <th>Data Type</th>
/// <th>Description</th>
/// </tr>
/// <tr>
/// <td>0</td>
/// <td>String</td>
/// <td>The Trigger's Name.</td>
/// </tr>
/// <tr>
/// <td>1</td>
/// <td>String</td>
/// <td>The Trigger's Group.</td>
/// </tr>
/// <tr>
/// <td>2</td>
/// <td>Date</td>
/// <td>The scheduled fire time.</td>
/// </tr>
/// <tr>
/// <td>3</td>
/// <td>Date</td>
/// <td>The next scheduled fire time.</td>
/// </tr>
/// <tr>
/// <td>4</td>
/// <td>Date</td>
/// <td>The actual fire time.</td>
/// </tr>
/// <tr>
/// <td>5</td>
/// <td>String</td>
/// <td>The Job's name.</td>
/// </tr>
/// <tr>
/// <td>6</td>
/// <td>String</td>
/// <td>The Job's group.</td>
/// </tr>
/// <tr>
/// <td>7</td>
/// <td>Integer</td>
/// <td>The re-fire count from the JobExecutionContext.</td>
/// </tr>
/// </table>
///
/// The default message text is <i>"Trigger {1}.{0} fired job {6}.{5} at: {4,
/// date, HH:mm:ss MM/dd/yyyy"</i>
/// </para>
///
/// <para>
/// TriggerMisfiredMessage - available message data are: <table>
/// <tr>
/// <th>Element</th>
/// <th>Data Type</th>
/// <th>Description</th>
/// </tr>
/// <tr>
/// <td>0</td>
/// <td>String</td>
/// <td>The Trigger's Name.</td>
/// </tr>
/// <tr>
/// <td>1</td>
/// <td>String</td>
/// <td>The Trigger's Group.</td>
/// </tr>
/// <tr>
/// <td>2</td>
/// <td>Date</td>
/// <td>The scheduled fire time.</td>
/// </tr>
/// <tr>
/// <td>3</td>
/// <td>Date</td>
/// <td>The next scheduled fire time.</td>
/// </tr>
/// <tr>
/// <td>4</td>
/// <td>Date</td>
/// <td>The actual fire time. (the time the misfire was detected/handled)</td>
/// </tr>
/// <tr>
/// <td>5</td>
/// <td>String</td>
/// <td>The Job's name.</td>
/// </tr>
/// <tr>
/// <td>6</td>
/// <td>String</td>
/// <td>The Job's group.</td>
/// </tr>
/// </table>
///
/// The default message text is <i>"Trigger {1}.{0} misfired job {6}.{5} at:
/// {4, date, HH:mm:ss MM/dd/yyyy}. Should have fired at: {3, date, HH:mm:ss
/// MM/dd/yyyy"</i>
/// </para>
///
/// <para>
/// TriggerCompleteMessage - available message data are: <table>
/// <tr>
/// <th>Element</th>
/// <th>Data Type</th>
/// <th>Description</th>
/// </tr>
/// <tr>
/// <td>0</td>
/// <td>String</td>
/// <td>The Trigger's Name.</td>
/// </tr>
/// <tr>
/// <td>1</td>
/// <td>String</td>
/// <td>The Trigger's Group.</td>
/// </tr>
/// <tr>
/// <td>2</td>
/// <td>Date</td>
/// <td>The scheduled fire time.</td>
/// </tr>
/// <tr>
/// <td>3</td>
/// <td>Date</td>
/// <td>The next scheduled fire time.</td>
/// </tr>
/// <tr>
/// <td>4</td>
/// <td>Date</td>
/// <td>The job completion time.</td>
/// </tr>
/// <tr>
/// <td>5</td>
/// <td>String</td>
/// <td>The Job's name.</td>
/// </tr>
/// <tr>
/// <td>6</td>
/// <td>String</td>
/// <td>The Job's group.</td>
/// </tr>
/// <tr>
/// <td>7</td>
/// <td>Integer</td>
/// <td>The re-fire count from the JobExecutionContext.</td>
/// </tr>
/// <tr>
/// <td>8</td>
/// <td>Integer</td>
/// <td>The trigger's resulting instruction code.</td>
/// </tr>
/// <tr>
/// <td>9</td>
/// <td>String</td>
/// <td>A human-readable translation of the trigger's resulting instruction
/// code.</td>
/// </tr>
/// </table>
///
/// The default message text is <i>"Trigger {1}.{0} completed firing job
/// {6}.{5} at {4, date, HH:mm:ss MM/dd/yyyy} with resulting trigger instruction
/// code: {9"</i>
/// </para>
/// </remarks>
/// <author>James House</author>
/// <author>Marko Lahma (.NET)</author>
public class LoggingTriggerHistoryPlugin : ISchedulerPlugin, ITriggerListener
{
private string name;
private string triggerFiredMessage = "Trigger {1}.{0} fired job {6}.{5} at: {4:HH:mm:ss MM/dd/yyyy} ";
private string triggerMisfiredMessage = "Trigger {1}.{0} misfired job {6}.{5} at: {4:HH:mm:ss MM/dd/yyyy}. Should have fired at: {3:HH:mm:ss MM/dd/yyyy}";
private string triggerCompleteMessage = "Trigger {1}.{0} completed firing job {6}.{5} at {4:HH:mm:ss MM/dd/yyyy} with resulting trigger instruction code: {9}";
private ILog log = LogManager.GetLogger(typeof (LoggingTriggerHistoryPlugin));
/// <summary>
/// Logger instance to use. Defaults to common logging.
/// </summary>
public ILog Log
{
get { return log; }
set { log = value; }
}
/// <summary>
/// Get or set the message that is printed upon the completion of a trigger's
/// firing.
/// </summary>
public virtual string TriggerCompleteMessage
{
get { return triggerCompleteMessage; }
set { triggerCompleteMessage = value; }
}
/// <summary>
/// Get or set the message that is printed upon a trigger's firing.
/// </summary>
public virtual string TriggerFiredMessage
{
get { return triggerFiredMessage; }
set { triggerFiredMessage = value; }
}
/// <summary>
/// Get or set the message that is printed upon a trigger's mis-firing.
/// </summary>
public virtual string TriggerMisfiredMessage
{
get { return triggerMisfiredMessage; }
set { triggerMisfiredMessage = value; }
}
/// <summary>
/// Get the name of the <see cref="ITriggerListener" />.
/// </summary>
/// <value></value>
public virtual string Name
{
get { return name; }
}
/// <summary>
/// Called during creation of the <see cref="IScheduler" /> in order to give
/// the <see cref="ISchedulerPlugin" /> a chance to Initialize.
/// </summary>
public virtual void Initialize(string pluginName, IScheduler sched)
{
name = pluginName;
sched.ListenerManager.AddTriggerListener(this, EverythingMatcher<TriggerKey>.AllTriggers());
}
/// <summary>
/// Called when the associated <see cref="IScheduler" /> is started, in order
/// to let the plug-in know it can now make calls into the scheduler if it
/// needs to.
/// </summary>
public virtual void Start()
{
// do nothing...
}
/// <summary>
/// Called in order to inform the <see cref="ISchedulerPlugin" /> that it
/// should free up all of it's resources because the scheduler is shutting
/// down.
/// </summary>
public virtual void Shutdown()
{
// nothing to do...
}
/// <summary>
/// Called by the <see cref="IScheduler" /> when a <see cref="ITrigger" />
/// has fired, and it's associated <see cref="IJobDetail" />
/// is about to be executed.
/// <para>
/// It is called before the <see cref="VetoJobExecution" /> method of this
/// interface.
/// </para>
/// </summary>
/// <param name="trigger">The <see cref="ITrigger" /> that has fired.</param>
/// <param name="context">The <see cref="IJobExecutionContext" /> that will be passed to the <see cref="IJob" />'s <see cref="IJob.Execute" /> method.</param>
public virtual void TriggerFired(ITrigger trigger, IJobExecutionContext context)
{
if (!Log.IsInfoEnabled)
{
return;
}
object[] args =
new object[]
{
trigger.Key.Name, trigger.Key.Group, trigger.GetPreviousFireTimeUtc(), trigger.GetNextFireTimeUtc(), SystemTime.UtcNow(),
context.JobDetail.Key.Name, context.JobDetail.Key.Group, context.RefireCount
};
Log.Info(String.Format(CultureInfo.InvariantCulture, TriggerFiredMessage, args));
}
/// <summary>
/// Called by the <see cref="IScheduler" /> when a <see cref="ITrigger" />
/// has misfired.
/// <para>
/// Consideration should be given to how much time is spent in this method,
/// as it will affect all triggers that are misfiring. If you have lots
/// of triggers misfiring at once, it could be an issue it this method
/// does a lot.
/// </para>
/// </summary>
/// <param name="trigger">The <see cref="ITrigger" /> that has misfired.</param>
public virtual void TriggerMisfired(ITrigger trigger)
{
if (!Log.IsInfoEnabled)
{
return;
}
object[] args =
new object[]
{
trigger.Key.Name, trigger.Key.Group, trigger.GetPreviousFireTimeUtc(), trigger.GetNextFireTimeUtc(), SystemTime.UtcNow(),
trigger.JobKey.Name, trigger.JobKey.Group
};
Log.Info(String.Format(CultureInfo.InvariantCulture, TriggerMisfiredMessage, args));
}
/// <summary>
/// Called by the <see cref="IScheduler" /> when a <see cref="ITrigger" />
/// has fired, it's associated <see cref="IJobDetail" />
/// has been executed, and it's <see cref="IOperableTrigger.Triggered" /> method has been
/// called.
/// </summary>
/// <param name="trigger">The <see cref="ITrigger" /> that was fired.</param>
/// <param name="context">The <see cref="IJobExecutionContext" /> that was passed to the
/// <see cref="IJob" />'s <see cref="IJob.Execute" /> method.</param>
/// <param name="triggerInstructionCode">The result of the call on the <see cref="IOperableTrigger" />'s <see cref="IOperableTrigger.Triggered" /> method.</param>
public virtual void TriggerComplete(ITrigger trigger, IJobExecutionContext context, SchedulerInstruction triggerInstructionCode)
{
if (!Log.IsInfoEnabled)
{
return;
}
string instrCode = "UNKNOWN";
if (triggerInstructionCode == SchedulerInstruction.DeleteTrigger)
{
instrCode = "DELETE TRIGGER";
}
else if (triggerInstructionCode == SchedulerInstruction.NoInstruction)
{
instrCode = "DO NOTHING";
}
else if (triggerInstructionCode == SchedulerInstruction.ReExecuteJob)
{
instrCode = "RE-EXECUTE JOB";
}
else if (triggerInstructionCode ==SchedulerInstruction.SetAllJobTriggersComplete)
{
instrCode = "SET ALL OF JOB'S TRIGGERS COMPLETE";
}
else if (triggerInstructionCode == SchedulerInstruction.SetTriggerComplete)
{
instrCode = "SET THIS TRIGGER COMPLETE";
}
object[] args =
new object[]
{
trigger.Key.Name, trigger.Key.Group, trigger.GetPreviousFireTimeUtc(), trigger.GetNextFireTimeUtc(), SystemTime.UtcNow(),
context.JobDetail.Key.Name, context.JobDetail.Key.Group, context.RefireCount, triggerInstructionCode, instrCode
};
Log.Info(String.Format(CultureInfo.InvariantCulture, TriggerCompleteMessage, args));
}
/// <summary>
/// Called by the <see cref="IScheduler" /> when a <see cref="ITrigger" />
/// has fired, and it's associated <see cref="IJobDetail" />
/// is about to be executed.
/// <para>
/// It is called after the <see cref="TriggerFired" /> method of this
/// interface.
/// </para>
/// </summary>
/// <param name="trigger">The <see cref="ITrigger" /> that has fired.</param>
/// <param name="context">The <see cref="IJobExecutionContext" /> that will be passed to
/// the <see cref="IJob" />'s <see cref="IJob.Execute" /> method.</param>
/// <returns></returns>
public virtual bool VetoJobExecution(ITrigger trigger, IJobExecutionContext context)
{
return false;
}
}
}
| |
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
namespace Google.Cloud.Debugger.V2.Snippets
{
using System.Threading.Tasks;
/// <summary>Generated snippets.</summary>
public sealed class GeneratedDebugger2ClientSnippets
{
/// <summary>Snippet for SetBreakpoint</summary>
public void SetBreakpointRequestObject()
{
// Snippet: SetBreakpoint(SetBreakpointRequest, CallSettings)
// Create client
Debugger2Client debugger2Client = Debugger2Client.Create();
// Initialize request argument(s)
SetBreakpointRequest request = new SetBreakpointRequest
{
DebuggeeId = "",
Breakpoint = new Breakpoint(),
ClientVersion = "",
};
// Make the request
SetBreakpointResponse response = debugger2Client.SetBreakpoint(request);
// End snippet
}
/// <summary>Snippet for SetBreakpointAsync</summary>
public async Task SetBreakpointRequestObjectAsync()
{
// Snippet: SetBreakpointAsync(SetBreakpointRequest, CallSettings)
// Additional: SetBreakpointAsync(SetBreakpointRequest, CancellationToken)
// Create client
Debugger2Client debugger2Client = await Debugger2Client.CreateAsync();
// Initialize request argument(s)
SetBreakpointRequest request = new SetBreakpointRequest
{
DebuggeeId = "",
Breakpoint = new Breakpoint(),
ClientVersion = "",
};
// Make the request
SetBreakpointResponse response = await debugger2Client.SetBreakpointAsync(request);
// End snippet
}
/// <summary>Snippet for SetBreakpoint</summary>
public void SetBreakpoint()
{
// Snippet: SetBreakpoint(string, Breakpoint, string, CallSettings)
// Create client
Debugger2Client debugger2Client = Debugger2Client.Create();
// Initialize request argument(s)
string debuggeeId = "";
Breakpoint breakpoint = new Breakpoint();
string clientVersion = "";
// Make the request
SetBreakpointResponse response = debugger2Client.SetBreakpoint(debuggeeId, breakpoint, clientVersion);
// End snippet
}
/// <summary>Snippet for SetBreakpointAsync</summary>
public async Task SetBreakpointAsync()
{
// Snippet: SetBreakpointAsync(string, Breakpoint, string, CallSettings)
// Additional: SetBreakpointAsync(string, Breakpoint, string, CancellationToken)
// Create client
Debugger2Client debugger2Client = await Debugger2Client.CreateAsync();
// Initialize request argument(s)
string debuggeeId = "";
Breakpoint breakpoint = new Breakpoint();
string clientVersion = "";
// Make the request
SetBreakpointResponse response = await debugger2Client.SetBreakpointAsync(debuggeeId, breakpoint, clientVersion);
// End snippet
}
/// <summary>Snippet for GetBreakpoint</summary>
public void GetBreakpointRequestObject()
{
// Snippet: GetBreakpoint(GetBreakpointRequest, CallSettings)
// Create client
Debugger2Client debugger2Client = Debugger2Client.Create();
// Initialize request argument(s)
GetBreakpointRequest request = new GetBreakpointRequest
{
DebuggeeId = "",
BreakpointId = "",
ClientVersion = "",
};
// Make the request
GetBreakpointResponse response = debugger2Client.GetBreakpoint(request);
// End snippet
}
/// <summary>Snippet for GetBreakpointAsync</summary>
public async Task GetBreakpointRequestObjectAsync()
{
// Snippet: GetBreakpointAsync(GetBreakpointRequest, CallSettings)
// Additional: GetBreakpointAsync(GetBreakpointRequest, CancellationToken)
// Create client
Debugger2Client debugger2Client = await Debugger2Client.CreateAsync();
// Initialize request argument(s)
GetBreakpointRequest request = new GetBreakpointRequest
{
DebuggeeId = "",
BreakpointId = "",
ClientVersion = "",
};
// Make the request
GetBreakpointResponse response = await debugger2Client.GetBreakpointAsync(request);
// End snippet
}
/// <summary>Snippet for GetBreakpoint</summary>
public void GetBreakpoint()
{
// Snippet: GetBreakpoint(string, string, string, CallSettings)
// Create client
Debugger2Client debugger2Client = Debugger2Client.Create();
// Initialize request argument(s)
string debuggeeId = "";
string breakpointId = "";
string clientVersion = "";
// Make the request
GetBreakpointResponse response = debugger2Client.GetBreakpoint(debuggeeId, breakpointId, clientVersion);
// End snippet
}
/// <summary>Snippet for GetBreakpointAsync</summary>
public async Task GetBreakpointAsync()
{
// Snippet: GetBreakpointAsync(string, string, string, CallSettings)
// Additional: GetBreakpointAsync(string, string, string, CancellationToken)
// Create client
Debugger2Client debugger2Client = await Debugger2Client.CreateAsync();
// Initialize request argument(s)
string debuggeeId = "";
string breakpointId = "";
string clientVersion = "";
// Make the request
GetBreakpointResponse response = await debugger2Client.GetBreakpointAsync(debuggeeId, breakpointId, clientVersion);
// End snippet
}
/// <summary>Snippet for DeleteBreakpoint</summary>
public void DeleteBreakpointRequestObject()
{
// Snippet: DeleteBreakpoint(DeleteBreakpointRequest, CallSettings)
// Create client
Debugger2Client debugger2Client = Debugger2Client.Create();
// Initialize request argument(s)
DeleteBreakpointRequest request = new DeleteBreakpointRequest
{
DebuggeeId = "",
BreakpointId = "",
ClientVersion = "",
};
// Make the request
debugger2Client.DeleteBreakpoint(request);
// End snippet
}
/// <summary>Snippet for DeleteBreakpointAsync</summary>
public async Task DeleteBreakpointRequestObjectAsync()
{
// Snippet: DeleteBreakpointAsync(DeleteBreakpointRequest, CallSettings)
// Additional: DeleteBreakpointAsync(DeleteBreakpointRequest, CancellationToken)
// Create client
Debugger2Client debugger2Client = await Debugger2Client.CreateAsync();
// Initialize request argument(s)
DeleteBreakpointRequest request = new DeleteBreakpointRequest
{
DebuggeeId = "",
BreakpointId = "",
ClientVersion = "",
};
// Make the request
await debugger2Client.DeleteBreakpointAsync(request);
// End snippet
}
/// <summary>Snippet for DeleteBreakpoint</summary>
public void DeleteBreakpoint()
{
// Snippet: DeleteBreakpoint(string, string, string, CallSettings)
// Create client
Debugger2Client debugger2Client = Debugger2Client.Create();
// Initialize request argument(s)
string debuggeeId = "";
string breakpointId = "";
string clientVersion = "";
// Make the request
debugger2Client.DeleteBreakpoint(debuggeeId, breakpointId, clientVersion);
// End snippet
}
/// <summary>Snippet for DeleteBreakpointAsync</summary>
public async Task DeleteBreakpointAsync()
{
// Snippet: DeleteBreakpointAsync(string, string, string, CallSettings)
// Additional: DeleteBreakpointAsync(string, string, string, CancellationToken)
// Create client
Debugger2Client debugger2Client = await Debugger2Client.CreateAsync();
// Initialize request argument(s)
string debuggeeId = "";
string breakpointId = "";
string clientVersion = "";
// Make the request
await debugger2Client.DeleteBreakpointAsync(debuggeeId, breakpointId, clientVersion);
// End snippet
}
/// <summary>Snippet for ListBreakpoints</summary>
public void ListBreakpointsRequestObject()
{
// Snippet: ListBreakpoints(ListBreakpointsRequest, CallSettings)
// Create client
Debugger2Client debugger2Client = Debugger2Client.Create();
// Initialize request argument(s)
ListBreakpointsRequest request = new ListBreakpointsRequest
{
DebuggeeId = "",
IncludeAllUsers = false,
IncludeInactive = false,
Action = new ListBreakpointsRequest.Types.BreakpointActionValue(),
WaitToken = "",
ClientVersion = "",
};
// Make the request
ListBreakpointsResponse response = debugger2Client.ListBreakpoints(request);
// End snippet
}
/// <summary>Snippet for ListBreakpointsAsync</summary>
public async Task ListBreakpointsRequestObjectAsync()
{
// Snippet: ListBreakpointsAsync(ListBreakpointsRequest, CallSettings)
// Additional: ListBreakpointsAsync(ListBreakpointsRequest, CancellationToken)
// Create client
Debugger2Client debugger2Client = await Debugger2Client.CreateAsync();
// Initialize request argument(s)
ListBreakpointsRequest request = new ListBreakpointsRequest
{
DebuggeeId = "",
IncludeAllUsers = false,
IncludeInactive = false,
Action = new ListBreakpointsRequest.Types.BreakpointActionValue(),
WaitToken = "",
ClientVersion = "",
};
// Make the request
ListBreakpointsResponse response = await debugger2Client.ListBreakpointsAsync(request);
// End snippet
}
/// <summary>Snippet for ListBreakpoints</summary>
public void ListBreakpoints()
{
// Snippet: ListBreakpoints(string, string, CallSettings)
// Create client
Debugger2Client debugger2Client = Debugger2Client.Create();
// Initialize request argument(s)
string debuggeeId = "";
string clientVersion = "";
// Make the request
ListBreakpointsResponse response = debugger2Client.ListBreakpoints(debuggeeId, clientVersion);
// End snippet
}
/// <summary>Snippet for ListBreakpointsAsync</summary>
public async Task ListBreakpointsAsync()
{
// Snippet: ListBreakpointsAsync(string, string, CallSettings)
// Additional: ListBreakpointsAsync(string, string, CancellationToken)
// Create client
Debugger2Client debugger2Client = await Debugger2Client.CreateAsync();
// Initialize request argument(s)
string debuggeeId = "";
string clientVersion = "";
// Make the request
ListBreakpointsResponse response = await debugger2Client.ListBreakpointsAsync(debuggeeId, clientVersion);
// End snippet
}
/// <summary>Snippet for ListDebuggees</summary>
public void ListDebuggeesRequestObject()
{
// Snippet: ListDebuggees(ListDebuggeesRequest, CallSettings)
// Create client
Debugger2Client debugger2Client = Debugger2Client.Create();
// Initialize request argument(s)
ListDebuggeesRequest request = new ListDebuggeesRequest
{
Project = "",
IncludeInactive = false,
ClientVersion = "",
};
// Make the request
ListDebuggeesResponse response = debugger2Client.ListDebuggees(request);
// End snippet
}
/// <summary>Snippet for ListDebuggeesAsync</summary>
public async Task ListDebuggeesRequestObjectAsync()
{
// Snippet: ListDebuggeesAsync(ListDebuggeesRequest, CallSettings)
// Additional: ListDebuggeesAsync(ListDebuggeesRequest, CancellationToken)
// Create client
Debugger2Client debugger2Client = await Debugger2Client.CreateAsync();
// Initialize request argument(s)
ListDebuggeesRequest request = new ListDebuggeesRequest
{
Project = "",
IncludeInactive = false,
ClientVersion = "",
};
// Make the request
ListDebuggeesResponse response = await debugger2Client.ListDebuggeesAsync(request);
// End snippet
}
/// <summary>Snippet for ListDebuggees</summary>
public void ListDebuggees()
{
// Snippet: ListDebuggees(string, string, CallSettings)
// Create client
Debugger2Client debugger2Client = Debugger2Client.Create();
// Initialize request argument(s)
string project = "";
string clientVersion = "";
// Make the request
ListDebuggeesResponse response = debugger2Client.ListDebuggees(project, clientVersion);
// End snippet
}
/// <summary>Snippet for ListDebuggeesAsync</summary>
public async Task ListDebuggeesAsync()
{
// Snippet: ListDebuggeesAsync(string, string, CallSettings)
// Additional: ListDebuggeesAsync(string, string, CancellationToken)
// Create client
Debugger2Client debugger2Client = await Debugger2Client.CreateAsync();
// Initialize request argument(s)
string project = "";
string clientVersion = "";
// Make the request
ListDebuggeesResponse response = await debugger2Client.ListDebuggeesAsync(project, clientVersion);
// End snippet
}
}
}
| |
using System;
using System.Collections;
namespace io {
public class IoLexer {
public static string specialChars = ":._";
public string s;
public int currentPos;
public char current { get { return s[currentPos]; } }
public ArrayList charLineIndex = new ArrayList();
public long lineHint;
public long maxChar;
public Stack posStack = new Stack();
public Stack tokenStack = new Stack();
public ArrayList tokenStream = new ArrayList();
public int resultIndex = 0;
public IoToken errorToken;
public string errorDescription;
public void print()
{
IoToken first = tokenStream[0] as IoToken;
if (first != null)
{
first.print();
}
Console.WriteLine();
}
public void printTokens()
{
int i;
for (i = 0; i < tokenStream.Count; i ++)
{
IoToken t = tokenStream[i] as IoToken;
Console.Write("'{0}' {1}", t.name, t.typeName());
if (i < tokenStream.Count - 1)
{
Console.Write(", ");
}
}
Console.WriteLine();
}
public int lex()
{
pushPos();
messageChain();
if (!onNULL())
{
if (errorToken == null)
{
if (tokenStream.Count != 0)
{
errorToken = currentToken();
}
else
{
errorToken = addTokenStringType(s.Substring(currentPos, 30), IoTokenType.NO_TOKEN);
}
errorToken.error = "Syntax error near this location";
}
return -1;
}
return 0;
}
public IoToken top()
{
if (resultIndex >= tokenStream.Count) return null;
return tokenStream[resultIndex] as IoToken;
}
public int lastPos()
{
return Convert.ToInt32(posStack.Peek());
}
public void pushPos()
{
tokenStack.Push(tokenStream.Count-1);
posStack.Push(currentPos);
}
public void popPos()
{
tokenStack.Pop();
posStack.Pop();
}
public IoTokenType topType()
{
if (top() == null) return 0;
return top().type;
}
public IoToken pop()
{
IoToken first = top();
resultIndex++;
return first;
}
public void popPosBack()
{
int i = Convert.ToInt32(tokenStack.Pop());
int topIndex = Convert.ToInt32(tokenStack.Peek());
if (i > -1)
{
if (i != topIndex)
{
IoToken parent = currentToken();
if (parent != null)
{
parent.nextToken = null;
}
}
}
currentPos = Convert.ToInt32(posStack.Pop());
}
public char nextChar()
{
if (currentPos >= s.Length)
return '\0';
char c = current;
currentPos++;
return c;
}
public char peekChar()
{
if (currentPos >= s.Length)
return '\0';
char c = current;
return c;
}
public char prevChar()
{
currentPos--;
char c = current;
return c;
}
public int readPadding()
{
int r = 0;
while (readWhitespace() != 0|| readComment() != 0)
{
r = 1;
}
return r;
}
// grabbing
public int grabLength()
{
int i1 = lastPos();
int i2 = currentPos;
return i2 - i1;
}
public IoToken grabTokenType(IoTokenType type)
{
int len = grabLength();
string s1 = s.Substring(lastPos(), len);
if (len == 0)
{
throw new Exception("IoLexer fatal error: empty token\n");
}
return addTokenStringType(s1, type);
}
public int currentLineNumber()
{
return 0;
}
public IoToken addTokenStringType(string s1, IoTokenType type)
{
IoToken top = currentToken();
IoToken t = new IoToken();
t.lineNumber = currentLineNumber();
t.charNumber = currentPos;
if (t.charNumber < 0)
{
System.Console.WriteLine("bad t->charNumber = %i\n", t.charNumber);
}
t.name = s1;
t.type = type;
if (top != null)
{
top.nextToken = t;
}
tokenStream.Add(t);
return t;
}
public IoToken currentToken()
{
if (tokenStream.Count == 0) return null;
return tokenStream[tokenStream.Count-1] as IoToken;
}
// message chain
public void messageChain()
{
do {
while ( readTerminator() != 0 || readSeparator() != 0|| readComment()!=0);
} while (readMessage()!=0);
}
// symbols
public int readSymbol()
{
if (readNumber() != 0 || readOperator() != 0 || readIdentifier() != 0 || readQuote() != 0) return 1;
return 0;
}
public int readIdentifier()
{
pushPos();
while (readLetter() != 0 || readDigit() != 0 || readSpecialChar() != 0);
if (grabLength() != 0)
{
if (s[currentPos - 1] == ':' && s[currentPos] == '=') prevChar();
grabTokenType(IoTokenType.IDENTIFIER_TOKEN);
popPos();
return 1;
}
return 0;
}
public int readOperator()
{
char c;
pushPos();
c = nextChar();
if (c == 0)
{
popPosBack();
return 0;
} else {
prevChar();
}
while (readOpChar() != 0);
if (grabLength() != 0)
{
grabTokenType(IoTokenType.IDENTIFIER_TOKEN);
popPos();
return 1;
}
popPosBack();
return 0;
}
public bool onNULL()
{
return currentPos == s.Length;
}
// helpers
public int readTokenCharsType(string chars, IoTokenType type)
{
foreach (char c in chars)
{
if (readTokenCharType(c, type) != 0)
return 1;
}
return 0;
}
public int readTokenCharType(char c, IoTokenType type)
{
pushPos();
if (readChar(c) != 0)
{
grabTokenType(type);
popPos();
return 1;
}
popPosBack();
return 0;
}
public int readTokenString(string s)
{
pushPos();
if (readString(s) != 0)
{
grabTokenType(IoTokenType.IDENTIFIER_TOKEN);
popPos();
return 1;
}
popPosBack();
return 0;
}
public int readString(string str)
{
int len = str.Length;
if (len > s.Length - currentPos)
len = s.Length - currentPos;
if (onNULL())
{
return 0;
}
string inmem = s.Substring(currentPos, len);
if (inmem.Equals(str))
{
currentPos += len;
return 1;
}
return 0;
}
public int readCharIn(string s)
{
if (!onNULL())
{
char c = nextChar();
if (s.IndexOf(c) != -1)
{
return 1;
}
prevChar();
}
return 0;
}
public int readCharInRange(char first, char last)
{
if (!onNULL())
{
char c = nextChar();
if ((int)c >= (int)first && (int)c <= (int)last) {
return 1;
}
prevChar();
}
return 0;
}
public int readNonASCIIChar()
{
if (!onNULL())
{
char nc = nextChar();
if (nc >= 0x80)
return 1;
prevChar();
}
return 0;
}
public int readChar(char ch)
{
if (!onNULL())
{
char c = nextChar();
if (c == ch) {
return 1;
}
prevChar();
}
return 0;
}
public int readCharAnyCase(char ch)
{
if (!onNULL())
{
char c = nextChar();
if (Char.ToLower(c) == Char.ToLower(ch)) {
return 1;
}
prevChar();
}
return 0;
}
public bool readNonReturn()
{
if (onNULL()) return false;
if (nextChar() != '\n') return true;
prevChar();
return false;
}
public bool readNonQuote()
{
if (onNULL()) return false;
if (nextChar() != '"') return true;
prevChar();
return false;
}
// character definitions
public int readCharacters()
{
int read = 0;
while (readCharacter() != 0)
{
read = 1;
}
return read;
}
public int readCharacter()
{
return Convert.ToInt32(readLetter() != 0 || readDigit() != 0 || readSpecialChar() != 0 || readOpChar() != 0);
}
public int readOpChar()
{
return readCharIn(":'~!@$%^&*-+=|\\<>?/");
}
public int readSpecialChar()
{
return readCharIn(IoLexer.specialChars);
}
public int readDigit()
{
return readCharInRange('0', '9');
}
public int readLetter() // grab all symbols
{
return Convert.ToInt32(readCharInRange('A', 'Z') !=0|| readCharInRange('a', 'z')!=0
|| readNonASCIIChar()!=0);
/*
if (!onNULL())
{
char c = nextChar();
return 1;
}
*/
//return 0;
}
// comments
public int readComment()
{
///return 0;
//return (readSlashStarComment() || readSlashSlashComment() || readPoundComment());
return readSlashSlashComment();
}
private int readSlashSlashComment()
{
this.pushPos();
if (nextChar() == '/')
{
if (nextChar() == '/')
{
while (readNonReturn()) { }
popPos();
return 1;
}
}
popPosBack();
return 0;
}
// quotes
public int readQuote()
{
return Convert.ToInt32(readTriQuote() != 0 || readMonoQuote() != 0);
}
public int readMonoQuote()
{
pushPos();
if (nextChar() == '"')
{
while (true)
{
char c = nextChar();
if (c == '"')
{
break;
}
if (c == '\\')
{
nextChar();
continue;
}
if (c == 0)
{
errorToken = currentToken();
if (errorToken != null)
{
errorToken.error = "unterminated quote";
}
popPosBack();
return 0;
}
}
grabTokenType(IoTokenType.MONOQUOTE_TOKEN);
popPos();
return 1;
}
popPosBack();
return 0;
}
public int readTriQuote()
{
pushPos();
if (readString("\"\"\"") != 0)
{
while (readString("\"\"\"") == 0)
{
char c = nextChar();
if (c == 0)
{
popPosBack();
return 0;
}
}
grabTokenType(IoTokenType.TRIQUOTE_TOKEN);
popPos();
return 1;
}
popPosBack();
return 0;
}
// terminators
public int readTerminator()
{
int terminated = 0;
pushPos();
readSeparator();
while (readTerminatorChar() != 0)
{
terminated = 1;
readSeparator();
}
if (terminated != 0)
{
IoToken top = currentToken();
// avoid double terminators
if (top != null && top.type == IoTokenType.TERMINATOR_TOKEN)
{
return 1;
}
addTokenStringType(";", IoTokenType.TERMINATOR_TOKEN);
popPos();
return 1;
}
popPosBack();
return 0;
}
public int readTerminatorChar()
{
return readCharIn(";\n");
}
// separators
public int readSeparator()
{
pushPos();
while (readSeparatorChar() != 0);
if (grabLength() != 0)
{
popPos();
return 1;
}
popPosBack();
return 0;
}
public int readSeparatorChar()
{
if (readCharIn(" \f\r\t\v") != 0)
{
return 1;
}
else
{
pushPos();
if (readCharIn("\\") != 0)
{
while (readCharIn(" \f\r\t\v") != 0);
if (readCharIn("\n") != 0)
{
popPos();
return 1;
}
}
popPosBack();
return 0;
}
}
// whitespace
int readWhitespace()
{
pushPos();
while (readWhitespaceChar() != 0);
if (grabLength() != 0)
{
popPos();
return 1;
}
popPosBack();
return 0;
}
public int readWhitespaceChar()
{
return readCharIn(" \f\r\t\v\n");
}
///
public int readDigits()
{
int read = 0;
pushPos();
while (readDigit() != 0)
{
read = 1;
}
if (read == 0)
{
popPosBack();
return 0;
}
popPos();
return read;
}
public int readNumber()
{
return Convert.ToInt32(readHexNumber() != 0 || readDecimal() != 0);
}
public int readExponent()
{
if (readCharAnyCase('e') != 0)
{
if (readChar('-') !=0 || readChar('+')!=0) { }
if (readDigits() == 0)
{
return -1;
}
return 1;
}
return 0;
}
public int readDecimalPlaces()
{
if (readChar('.')!=0)
{
if (readDigits() == 0)
{
return -1;
}
return 1;
}
return 0;
}
public int readDecimal()
{
pushPos();
if (readDigits()!=0)
{
if (readDecimalPlaces() == -1)
{
goto error;
}
}
else
{
if (readDecimalPlaces() != 1)
{
goto error;
}
}
if (readExponent() == -1)
{
goto error;
}
if (grabLength()!=0)
{
grabTokenType(IoTokenType.NUMBER_TOKEN);
popPos();
return 1;
}
error:
popPosBack();
return 0;
}
public int readHexNumber()
{
int read = 0;
pushPos();
if (readChar('0') != 0 && readCharAnyCase('x') != 0)
{
while (readDigits() != 0|| readCharacters() != 0)
{
read ++;
}
}
if (read != 0 && grabLength() != 0)
{
grabTokenType(IoTokenType.HEXNUMBER_TOKEN);
popPos();
return 1;
}
popPosBack();
return 0;
}
/// message
public string nameForGroupChar(char groupChar)
{
switch (groupChar)
{
case '(': return "";
case '[': return "squareBrackets";
case '{': return "curlyBrackets";
}
throw new Exception("IoLexer: fatal error - invalid group char" + groupChar);
}
public void readMessageError(string name)
{
popPosBack();
errorToken = currentToken();
errorToken.error = name;
}
public int readMessage()
{
int foundSymbol = 0;
pushPos();
readPadding();
foundSymbol = readSymbol();
char groupChar;
while (readSeparator() != 0 || readComment() != 0);
groupChar = peekChar();
// this is bug in original IoVM so I've commented this out
if ("[{".IndexOf(groupChar) != -1 || (foundSymbol == 0 &&
groupChar == '('))
{
string groupName = nameForGroupChar(groupChar);
addTokenStringType(groupName, IoTokenType.IDENTIFIER_TOKEN);
}
if (readTokenCharsType("([{", IoTokenType.OPENPAREN_TOKEN) != 0)
{
readPadding();
do {
IoTokenType type = currentToken().type;
readPadding();
// Empty argument: (... ,)
if (IoTokenType.COMMA_TOKEN == type)
{
char c = current;
if (',' == c || ")]}".IndexOf(c) != -1)
{
readMessageError("missing argument in argument list");
return 0;
}
}
if (groupChar == '[') specialChars = "._";
messageChain();
if (groupChar == '[') specialChars = ":._";
readPadding();
} while (readTokenCharType(',', IoTokenType.COMMA_TOKEN) != 0);
if (readTokenCharsType(")]}", IoTokenType.CLOSEPAREN_TOKEN) == 0)
{
if (groupChar == '(')
{
readMessageError("unmatched ()s");
}
else if (groupChar == '[')
{
readMessageError("unmatched []s");
}
else if (groupChar == '{')
{
readMessageError("unmatched {}s");
}
return 0;
}
popPos();
return 1;
}
if (foundSymbol != 0)
{
popPos();
return 1;
}
popPosBack();
return 0;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using GitVersion.Logging;
using GitVersion.OutputVariables;
namespace GitVersion.VersionConverters.AssemblyInfo
{
public interface IAssemblyInfoFileUpdater : IVersionConverter<AssemblyInfoContext>
{
}
public class AssemblyInfoFileUpdater : IAssemblyInfoFileUpdater
{
private readonly List<Action> restoreBackupTasks = new List<Action>();
private readonly List<Action> cleanupBackupTasks = new List<Action>();
private readonly IDictionary<string, Regex> assemblyAttributeRegexes = new Dictionary<string, Regex>
{
{".cs", new Regex( @"(\s*\[\s*assembly:\s*(?:.*)\s*\]\s*$(\r?\n)?)", RegexOptions.Multiline) },
{".fs", new Regex( @"(\s*\[\s*\<assembly:\s*(?:.*)\>\s*\]\s*$(\r?\n)?)", RegexOptions.Multiline) },
{".vb", new Regex( @"(\s*\<Assembly:\s*(?:.*)\>\s*$(\r?\n)?)", RegexOptions.Multiline) },
};
private readonly Regex assemblyVersionRegex = new Regex(@"AssemblyVersion(Attribute)?\s*\(.*\)\s*");
private readonly Regex assemblyInfoVersionRegex = new Regex(@"AssemblyInformationalVersion(Attribute)?\s*\(.*\)\s*");
private readonly Regex assemblyFileVersionRegex = new Regex(@"AssemblyFileVersion(Attribute)?\s*\(.*\)\s*");
private const string NewLine = "\r\n";
private readonly IFileSystem fileSystem;
private readonly ILog log;
private readonly TemplateManager templateManager;
public AssemblyInfoFileUpdater(ILog log, IFileSystem fileSystem)
{
this.fileSystem = fileSystem;
this.log = log;
templateManager = new TemplateManager(TemplateType.AssemblyInfo);
}
public void Execute(VersionVariables variables, AssemblyInfoContext context)
{
var assemblyInfoFiles = GetAssemblyInfoFiles(context).ToList();
log.Info("Updating assembly info files");
log.Info($"Found {assemblyInfoFiles.Count} files");
var assemblyVersion = variables.AssemblySemVer;
var assemblyVersionString = !string.IsNullOrWhiteSpace(assemblyVersion) ? $"AssemblyVersion(\"{assemblyVersion}\")" : null;
var assemblyInfoVersion = variables.InformationalVersion;
var assemblyInfoVersionString = !string.IsNullOrWhiteSpace(assemblyInfoVersion) ? $"AssemblyInformationalVersion(\"{assemblyInfoVersion}\")" : null;
var assemblyFileVersion = variables.AssemblySemFileVer;
var assemblyFileVersionString = !string.IsNullOrWhiteSpace(assemblyFileVersion) ? $"AssemblyFileVersion(\"{assemblyFileVersion}\")" : null;
foreach (var assemblyInfoFile in assemblyInfoFiles)
{
var localAssemblyInfo = assemblyInfoFile.FullName;
var backupAssemblyInfo = localAssemblyInfo + ".bak";
fileSystem.Copy(localAssemblyInfo, backupAssemblyInfo, true);
restoreBackupTasks.Add(() =>
{
if (fileSystem.Exists(localAssemblyInfo))
{
fileSystem.Delete(localAssemblyInfo);
}
fileSystem.Move(backupAssemblyInfo, localAssemblyInfo);
});
cleanupBackupTasks.Add(() => fileSystem.Delete(backupAssemblyInfo));
var originalFileContents = fileSystem.ReadAllText(localAssemblyInfo);
var fileContents = originalFileContents;
var appendedAttributes = false;
if (!string.IsNullOrWhiteSpace(assemblyVersion))
{
fileContents = ReplaceOrInsertAfterLastAssemblyAttributeOrAppend(assemblyVersionRegex, fileContents, assemblyVersionString, assemblyInfoFile.Extension, ref appendedAttributes);
}
if (!string.IsNullOrWhiteSpace(assemblyFileVersion))
{
fileContents = ReplaceOrInsertAfterLastAssemblyAttributeOrAppend(assemblyFileVersionRegex, fileContents, assemblyFileVersionString, assemblyInfoFile.Extension, ref appendedAttributes);
}
if (!string.IsNullOrWhiteSpace(assemblyInfoVersion))
{
fileContents = ReplaceOrInsertAfterLastAssemblyAttributeOrAppend(assemblyInfoVersionRegex, fileContents, assemblyInfoVersionString, assemblyInfoFile.Extension, ref appendedAttributes);
}
if (appendedAttributes)
{
// If we appended any attributes, put a new line after them
fileContents += NewLine;
}
if (originalFileContents != fileContents)
{
fileSystem.WriteAllText(localAssemblyInfo, fileContents);
}
}
CommitChanges();
}
public void Dispose()
{
foreach (var restoreBackup in restoreBackupTasks)
{
restoreBackup();
}
cleanupBackupTasks.Clear();
restoreBackupTasks.Clear();
}
private void CommitChanges()
{
foreach (var cleanupBackupTask in cleanupBackupTasks)
{
cleanupBackupTask();
}
cleanupBackupTasks.Clear();
restoreBackupTasks.Clear();
}
private string ReplaceOrInsertAfterLastAssemblyAttributeOrAppend(Regex replaceRegex, string inputString, string replaceString, string fileExtension, ref bool appendedAttributes)
{
var assemblyAddFormat = templateManager.GetAddFormatFor(fileExtension);
if (replaceRegex.IsMatch(inputString))
{
return replaceRegex.Replace(inputString, replaceString);
}
if (assemblyAttributeRegexes.TryGetValue(fileExtension, out var assemblyRegex))
{
var assemblyMatches = assemblyRegex.Matches(inputString);
if (assemblyMatches.Count > 0)
{
var lastMatch = assemblyMatches[assemblyMatches.Count - 1];
var replacementString = lastMatch.Value;
if (!lastMatch.Value.EndsWith(NewLine)) replacementString += NewLine;
replacementString += string.Format(assemblyAddFormat, replaceString);
replacementString += NewLine;
return inputString.Replace(lastMatch.Value, replacementString);
}
}
inputString += NewLine + string.Format(assemblyAddFormat, replaceString);
appendedAttributes = true;
return inputString;
}
private IEnumerable<FileInfo> GetAssemblyInfoFiles(AssemblyInfoContext context)
{
var workingDirectory = context.WorkingDirectory;
var ensureAssemblyInfo = context.EnsureAssemblyInfo;
var assemblyInfoFileNames = new HashSet<string>(context.AssemblyInfoFiles);
if (assemblyInfoFileNames.Any(x => !string.IsNullOrWhiteSpace(x)))
{
foreach (var item in assemblyInfoFileNames)
{
var fullPath = Path.Combine(workingDirectory, item);
if (EnsureVersionAssemblyInfoFile(fullPath, ensureAssemblyInfo))
{
yield return new FileInfo(fullPath);
}
}
}
else
{
foreach (var item in fileSystem.DirectoryGetFiles(workingDirectory, "AssemblyInfo.*", SearchOption.AllDirectories))
{
var assemblyInfoFile = new FileInfo(item);
if (templateManager.IsSupported(assemblyInfoFile.Extension))
{
yield return assemblyInfoFile;
}
}
}
}
private bool EnsureVersionAssemblyInfoFile(string fullPath, bool ensureAssemblyInfo)
{
fullPath = fullPath ?? throw new ArgumentNullException(nameof(fullPath));
if (fileSystem.Exists(fullPath))
{
return true;
}
if (!ensureAssemblyInfo)
{
return false;
}
var assemblyInfoSource = templateManager.GetTemplateFor(Path.GetExtension(fullPath));
if (!string.IsNullOrWhiteSpace(assemblyInfoSource))
{
var fileInfo = new FileInfo(fullPath);
if (fileInfo.Directory != null && !fileSystem.DirectoryExists(fileInfo.Directory.FullName))
{
fileSystem.CreateDirectory(fileInfo.Directory.FullName);
}
fileSystem.WriteAllText(fullPath, assemblyInfoSource);
return true;
}
log.Warning($"No version assembly info template available to create source file '{fullPath}'");
return false;
}
}
}
| |
using System;
using System.Net;
using System.IO;
using System.Text;
using System.Net.Sockets;
using System.Diagnostics;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Messaging;
/*
* FTP Client library in C#
* Author: Jaimon Mathew
* mailto:[email protected]
* http://www.csharphelp.com/archives/archive9.html
*
* Addapted for use by Dan Glass 07/03/03
*/
namespace VillaUserManager
{
public class FtpClient
{
public class FtpException : Exception
{
public FtpException(string message) : base(message){}
public FtpException(string message, Exception innerException) : base(message,innerException){}
}
private static int BUFFER_SIZE = 512;
private static Encoding ASCII = Encoding.ASCII;
private bool verboseDebugging = false;
// defaults
private string server = "localhost";
private string remotePath = ".";
private string username = "anonymous";
private string password = "[email protected]";
private string message = null;
private string result = null;
private int port = 21;
private int bytes = 0;
private int resultCode = 0;
private bool loggedin = false;
private bool binMode = false;
private Byte[] buffer = new Byte[BUFFER_SIZE];
private Socket clientSocket = null;
private int timeoutSeconds = 10;
/// <summary>
/// Default contructor
/// </summary>
public FtpClient()
{
}
/// <summary>
///
/// </summary>
/// <param name="server"></param>
/// <param name="username"></param>
/// <param name="password"></param>
public FtpClient(string server, string username, string password)
{
this.server = server;
this.username = username;
this.password = password;
}
/// <summary>
///
/// </summary>
/// <param name="server"></param>
/// <param name="username"></param>
/// <param name="password"></param>
/// <param name="timeoutSeconds"></param>
/// <param name="port"></param>
public FtpClient(string server, string username, string password, int timeoutSeconds, int port)
{
this.server = server;
this.username = username;
this.password = password;
this.timeoutSeconds = timeoutSeconds;
this.port = port;
}
/// <summary>
/// Display all communications to the debug log
/// </summary>
public bool VerboseDebugging
{
get
{
return this.verboseDebugging;
}
set
{
this.verboseDebugging = value;
}
}
/// <summary>
/// Remote server port. Typically TCP 21
/// </summary>
public int Port
{
get
{
return this.port;
}
set
{
this.port = value;
}
}
/// <summary>
/// Timeout waiting for a response from server, in seconds.
/// </summary>
public int Timeout
{
get
{
return this.timeoutSeconds;
}
set
{
this.timeoutSeconds = value;
}
}
/// <summary>
/// Gets and Sets the name of the FTP server.
/// </summary>
/// <returns></returns>
public string Server
{
get
{
return this.server;
}
set
{
this.server = value;
}
}
/// <summary>
/// Gets and Sets the port number.
/// </summary>
/// <returns></returns>
public int RemotePort
{
get
{
return this.port;
}
set
{
this.port = value;
}
}
/// <summary>
/// GetS and Sets the remote directory.
/// </summary>
public string RemotePath
{
get
{
return this.remotePath;
}
set
{
this.remotePath = value;
}
}
/// <summary>
/// Gets and Sets the username.
/// </summary>
public string Username
{
get
{
return this.username;
}
set
{
this.username = value;
}
}
/// <summary>
/// Gets and Set the password.
/// </summary>
public string Password
{
get
{
return this.password;
}
set
{
this.password = value;
}
}
/// <summary>
/// If the value of mode is true, set binary mode for downloads, else, Ascii mode.
/// </summary>
public bool BinaryMode
{
get
{
return this.binMode;
}
set
{
if ( this.binMode == value ) return;
if ( value )
sendCommand("TYPE I");
else
sendCommand("TYPE A");
if ( this.resultCode != 200 ) throw new FtpException(result.Substring(4));
}
}
/// <summary>
/// Login to the remote server.
/// </summary>
public void Login()
{
if ( this.loggedin ) this.Close();
Debug.WriteLine("Opening connection to " + this.server, "FtpClient" );
IPAddress addr = null;
IPEndPoint ep = null;
try
{
this.clientSocket = new Socket( AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp );
addr = Dns.Resolve(this.server).AddressList[0];
ep = new IPEndPoint( addr, this.port );
this.clientSocket.Connect(ep);
}
catch(Exception ex)
{
// doubtfull
if ( this.clientSocket != null && this.clientSocket.Connected ) this.clientSocket.Close();
throw new FtpException("Couldn't connect to remote server",ex);
}
this.readResponse();
if(this.resultCode != 220)
{
this.Close();
throw new FtpException(this.result.Substring(4));
}
this.sendCommand( "USER " + username );
if( !(this.resultCode == 331 || this.resultCode == 230) )
{
this.cleanup();
throw new FtpException(this.result.Substring(4));
}
if( this.resultCode != 230 )
{
this.sendCommand( "PASS " + password );
if( !(this.resultCode == 230 || this.resultCode == 202) )
{
this.cleanup();
throw new FtpException(this.result.Substring(4));
}
}
this.loggedin = true;
Debug.WriteLine( "Connected to " + this.server, "FtpClient" );
this.ChangeDir(this.remotePath);
}
/// <summary>
/// Close the FTP connection.
/// </summary>
public void Close()
{
Debug.WriteLine("Closing connection to " + this.server, "FtpClient" );
if( this.clientSocket != null )
{
this.sendCommand("QUIT");
}
this.cleanup();
}
/// <summary>
/// Return a string array containing the remote directory's file list.
/// </summary>
/// <returns></returns>
public string[] GetFileList()
{
return this.GetFileList("*.*");
}
/// <summary>
/// Return a string array containing the remote directory's file list.
/// </summary>
/// <param name="mask"></param>
/// <returns></returns>
public string[] GetFileList(string mask)
{
if ( !this.loggedin ) this.Login();
Socket cSocket = createDataSocket();
this.sendCommand("NLST " + mask);
if(!(this.resultCode == 150 || this.resultCode == 125)) throw new FtpException(this.result.Substring(4));
this.message = "";
DateTime timeout = DateTime.Now.AddSeconds(this.timeoutSeconds);
while( timeout > DateTime.Now )
{
int bytes = cSocket.Receive(buffer, buffer.Length, 0);
this.message += ASCII.GetString(buffer, 0, bytes);
if ( bytes < this.buffer.Length ) break;
}
string[] msg = this.message.Replace("\r","").Split('\n');
cSocket.Close();
if ( this.message.IndexOf( "No such file or directory" ) != -1 )
msg = new string[]{};
this.readResponse();
if ( this.resultCode != 226 )
msg = new string[]{};
// throw new FtpException(result.Substring(4));
return msg;
}
/// <summary>
/// Return the size of a file.
/// </summary>
/// <param name="fileName"></param>
/// <returns></returns>
public long GetFileSize(string fileName)
{
if ( !this.loggedin ) this.Login();
this.sendCommand("SIZE " + fileName);
long size=0;
if ( this.resultCode == 213 )
size = long.Parse(this.result.Substring(4));
else
throw new FtpException(this.result.Substring(4));
return size;
}
/// <summary>
/// Download a file to the Assembly's local directory,
/// keeping the same file name.
/// </summary>
/// <param name="remFileName"></param>
public void Download(string remFileName)
{
this.Download(remFileName,"",false);
}
/// <summary>
/// Download a remote file to the Assembly's local directory,
/// keeping the same file name, and set the resume flag.
/// </summary>
/// <param name="remFileName"></param>
/// <param name="resume"></param>
public void Download(string remFileName,Boolean resume)
{
this.Download(remFileName,"",resume);
}
/// <summary>
/// Download a remote file to a local file name which can include
/// a path. The local file name will be created or overwritten,
/// but the path must exist.
/// </summary>
/// <param name="remFileName"></param>
/// <param name="locFileName"></param>
public void Download(string remFileName,string locFileName)
{
this.Download(remFileName,locFileName,false);
}
/// <summary>
/// Download a remote file to a local file name which can include
/// a path, and set the resume flag. The local file name will be
/// created or overwritten, but the path must exist.
/// </summary>
/// <param name="remFileName"></param>
/// <param name="locFileName"></param>
/// <param name="resume"></param>
public void Download(string remFileName,string locFileName,Boolean resume)
{
if ( !this.loggedin ) this.Login();
this.BinaryMode = true;
Debug.WriteLine("Downloading file " + remFileName + " from " + server + "/" + remotePath, "FtpClient" );
if (locFileName.Equals(""))
{
locFileName = remFileName;
}
FileStream output = null;
if ( !File.Exists(locFileName) )
output = File.Create(locFileName);
else
output = new FileStream(locFileName,FileMode.Open);
Socket cSocket = createDataSocket();
long offset = 0;
if ( resume )
{
offset = output.Length;
if ( offset > 0 )
{
this.sendCommand( "REST " + offset );
if ( this.resultCode != 350 )
{
//Server dosnt support resuming
offset = 0;
Debug.WriteLine("Resuming not supported:" + result.Substring(4), "FtpClient" );
}
else
{
Debug.WriteLine("Resuming at offset " + offset, "FtpClient" );
output.Seek( offset, SeekOrigin.Begin );
}
}
}
this.sendCommand("RETR " + remFileName);
if ( this.resultCode != 150 && this.resultCode != 125 )
{
throw new FtpException(this.result.Substring(4));
}
DateTime timeout = DateTime.Now.AddSeconds(this.timeoutSeconds);
while ( timeout > DateTime.Now )
{
this.bytes = cSocket.Receive(buffer, buffer.Length, 0);
output.Write(this.buffer,0,this.bytes);
if ( this.bytes <= 0)
{
break;
}
}
output.Close();
if ( cSocket.Connected ) cSocket.Close();
this.readResponse();
if( this.resultCode != 226 && this.resultCode != 250 )
throw new FtpException(this.result.Substring(4));
}
/// <summary>
/// Upload a file.
/// </summary>
/// <param name="fileName"></param>
public void Upload(string fileName)
{
this.Upload(fileName,false);
}
/// <summary>
/// Upload a file and set the resume flag.
/// </summary>
/// <param name="fileName"></param>
/// <param name="resume"></param>
public void Upload(string fileName, bool resume)
{
if ( !this.loggedin ) this.Login();
Socket cSocket = null ;
long offset = 0;
if ( resume )
{
try
{
this.BinaryMode = true;
offset = GetFileSize( Path.GetFileName(fileName) );
}
catch(Exception)
{
// file not exist
offset = 0;
}
}
// open stream to read file
FileStream input = new FileStream(fileName,FileMode.Open);
if ( resume && input.Length < offset )
{
// different file size
Debug.WriteLine("Overwriting " + fileName, "FtpClient");
offset = 0;
}
else if ( resume && input.Length == offset )
{
// file done
input.Close();
Debug.WriteLine("Skipping completed " + fileName + " - turn resume off to not detect.", "FtpClient");
return;
}
// dont create untill we know that we need it
cSocket = this.createDataSocket();
if ( offset > 0 )
{
this.sendCommand( "REST " + offset );
if ( this.resultCode != 350 )
{
Debug.WriteLine("Resuming not supported", "FtpClient");
offset = 0;
}
}
this.sendCommand( "STOR " + Path.GetFileName(fileName) );
if ( this.resultCode != 125 && this.resultCode != 150 ) throw new FtpException(result.Substring(4));
if ( offset != 0 )
{
Debug.WriteLine("Resuming at offset " + offset, "FtpClient" );
input.Seek(offset,SeekOrigin.Begin);
}
Debug.WriteLine( "Uploading file " + fileName + " to " + remotePath, "FtpClient" );
while ((bytes = input.Read(buffer,0,buffer.Length)) > 0)
{
cSocket.Send(buffer, bytes, 0);
}
input.Close();
if (cSocket.Connected)
{
cSocket.Close();
}
this.readResponse();
if( this.resultCode != 226 && this.resultCode != 250 ) throw new FtpException(this.result.Substring(4));
}
/// <summary>
/// Upload a directory and its file contents
/// </summary>
/// <param name="path"></param>
/// <param name="recurse">Whether to recurse sub directories</param>
public void UploadDirectory(string path, bool recurse)
{
this.UploadDirectory(path,recurse,"*.*");
}
/// <summary>
/// Upload a directory and its file contents
/// </summary>
/// <param name="path"></param>
/// <param name="recurse">Whether to recurse sub directories</param>
/// <param name="mask">Only upload files of the given mask - everything is '*.*'</param>
public void UploadDirectory(string path, bool recurse, string mask)
{
string[] dirs = path.Replace("/",@"\").Split('\\');
string rootDir = dirs[ dirs.Length - 1 ];
// make the root dir if it doed not exist
if ( this.GetFileList(rootDir).Length < 1 ) this.MakeDir(rootDir);
this.ChangeDir(rootDir);
foreach ( string file in Directory.GetFiles(path,mask) )
{
this.Upload(file,true);
}
if ( recurse )
{
foreach ( string directory in Directory.GetDirectories(path) )
{
this.UploadDirectory(directory,recurse,mask);
}
}
this.ChangeDir("..");
}
/// <summary>
/// Delete a file from the remote FTP server.
/// </summary>
/// <param name="fileName"></param>
public void DeleteFile(string fileName)
{
if ( !this.loggedin ) this.Login();
this.sendCommand( "DELE " + fileName );
if ( this.resultCode != 250 ) throw new FtpException(this.result.Substring(4));
Debug.WriteLine( "Deleted file " + fileName, "FtpClient" );
}
/// <summary>
/// Rename a file on the remote FTP server.
/// </summary>
/// <param name="oldFileName"></param>
/// <param name="newFileName"></param>
/// <param name="overwrite">setting to false will throw exception if it exists</param>
public void RenameFile(string oldFileName,string newFileName, bool overwrite)
{
if ( !this.loggedin ) this.Login();
this.sendCommand( "RNFR " + oldFileName );
if ( this.resultCode != 350 ) throw new FtpException(this.result.Substring(4));
if ( !overwrite && this.GetFileList(newFileName).Length > 0 ) throw new FtpException("File already exists");
this.sendCommand( "RNTO " + newFileName );
if ( this.resultCode != 250 ) throw new FtpException(this.result.Substring(4));
Debug.WriteLine( "Renamed file " + oldFileName + " to " + newFileName, "FtpClient" );
}
/// <summary>
/// Create a directory on the remote FTP server.
/// </summary>
/// <param name="dirName"></param>
public void MakeDir(string dirName)
{
if ( !this.loggedin ) this.Login();
this.sendCommand( "MKD " + dirName );
if ( this.resultCode != 250 && this.resultCode != 257 ) throw new FtpException(this.result.Substring(4));
Debug.WriteLine( "Created directory " + dirName, "FtpClient" );
}
/// <summary>
/// Delete a directory on the remote FTP server.
/// </summary>
/// <param name="dirName"></param>
public void RemoveDir(string dirName)
{
if ( !this.loggedin ) this.Login();
this.sendCommand( "RMD " + dirName );
if ( this.resultCode != 250 ) throw new FtpException(this.result.Substring(4));
Debug.WriteLine( "Removed directory " + dirName, "FtpClient" );
}
/// <summary>
/// Change the current working directory on the remote FTP server.
/// </summary>
/// <param name="dirName"></param>
public void ChangeDir(string dirName)
{
if( dirName == null || dirName.Equals(".") || dirName.Length == 0 )
{
return;
}
if ( !this.loggedin ) this.Login();
this.sendCommand( "CWD " + dirName );
if ( this.resultCode != 250 ) throw new FtpException(result.Substring(4));
this.sendCommand( "PWD" );
if ( this.resultCode != 257 ) throw new FtpException(result.Substring(4));
// gonna have to do better than this....
this.remotePath = this.message.Split('"')[1];
Debug.WriteLine( "Current directory is " + this.remotePath, "FtpClient" );
}
/// <summary>
///
/// </summary>
private void readResponse()
{
this.message = "";
this.result = this.readLine();
if ( this.result.Length > 3 )
this.resultCode = int.Parse( this.result.Substring(0,3) );
else
this.result = null;
}
/// <summary>
///
/// </summary>
/// <returns></returns>
private string readLine()
{
while(true)
{
this.bytes = clientSocket.Receive( this.buffer, this.buffer.Length, 0 );
this.message += ASCII.GetString( this.buffer, 0, this.bytes );
if ( this.bytes < this.buffer.Length )
{
break;
}
}
string[] msg = this.message.Split('\n');
if ( this.message.Length > 2 )
this.message = msg[ msg.Length - 2 ];
else
this.message = msg[0];
if ( this.message.Length > 4 && !this.message.Substring(3,1).Equals(" ") ) return this.readLine();
if ( this.verboseDebugging )
{
for(int i = 0; i < msg.Length - 1; i++)
{
Debug.Write( msg[i], "FtpClient" );
}
}
return message;
}
/// <summary>
///
/// </summary>
/// <param name="command"></param>
private void sendCommand(String command)
{
if ( this.verboseDebugging ) Debug.WriteLine(command,"FtpClient");
Byte[] cmdBytes = Encoding.ASCII.GetBytes( ( command + "\r\n" ).ToCharArray() );
clientSocket.Send( cmdBytes, cmdBytes.Length, 0);
this.readResponse();
}
/// <summary>
/// when doing data transfers, we need to open another socket for it.
/// </summary>
/// <returns>Connected socket</returns>
private Socket createDataSocket()
{
this.sendCommand("PASV");
if ( this.resultCode != 227 ) throw new FtpException(this.result.Substring(4));
int index1 = this.result.IndexOf('(');
int index2 = this.result.IndexOf(')');
string ipData = this.result.Substring(index1+1,index2-index1-1);
int[] parts = new int[6];
int len = ipData.Length;
int partCount = 0;
string buf="";
for (int i = 0; i < len && partCount <= 6; i++)
{
char ch = char.Parse( ipData.Substring(i,1) );
if ( char.IsDigit(ch) )
buf+=ch;
else if (ch != ',')
throw new FtpException("Malformed PASV result: " + result);
if ( ch == ',' || i+1 == len )
{
try
{
parts[partCount++] = int.Parse(buf);
buf = "";
}
catch (Exception ex)
{
throw new FtpException("Malformed PASV result (not supported?): " + this.result, ex);
}
}
}
string ipAddress = parts[0] + "."+ parts[1]+ "." + parts[2] + "." + parts[3];
int port = (parts[4] << 8) + parts[5];
Socket socket = null;
IPEndPoint ep = null;
try
{
socket = new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);
ep = new IPEndPoint(Dns.Resolve(ipAddress).AddressList[0], port);
socket.Connect(ep);
}
catch(Exception ex)
{
// doubtfull....
if ( socket != null && socket.Connected ) socket.Close();
throw new FtpException("Can't connect to remote server", ex);
}
return socket;
}
/// <summary>
/// Always release those sockets.
/// </summary>
private void cleanup()
{
if ( this.clientSocket!=null )
{
this.clientSocket.Close();
this.clientSocket = null;
}
this.loggedin = false;
}
/// <summary>
/// Destuctor
/// </summary>
~FtpClient()
{
this.cleanup();
}
/**************************************************************************************************************/
#region Async methods (auto generated)
/*
WinInetApi.FtpClient ftp = new WinInetApi.FtpClient();
MethodInfo[] methods = ftp.GetType().GetMethods(BindingFlags.DeclaredOnly|BindingFlags.Instance|BindingFlags.Public);
foreach ( MethodInfo method in methods )
{
string param = "";
string values = "";
foreach ( ParameterInfo i in method.GetParameters() )
{
param += i.ParameterType.Name + " " + i.Name + ",";
values += i.Name + ",";
}
Debug.WriteLine("private delegate " + method.ReturnType.Name + " " + method.Name + "Callback(" + param.TrimEnd(',') + ");");
Debug.WriteLine("public System.IAsyncResult Begin" + method.Name + "( " + param + " System.AsyncCallback callback )");
Debug.WriteLine("{");
Debug.WriteLine("" + method.Name + "Callback ftpCallback = new " + method.Name + "Callback(" + values + " this." + method.Name + ");");
Debug.WriteLine("return ftpCallback.BeginInvoke(callback, null);");
Debug.WriteLine("}");
Debug.WriteLine("public void End" + method.Name + "(System.IAsyncResult asyncResult)");
Debug.WriteLine("{");
Debug.WriteLine(method.Name + "Callback fc = (" + method.Name + "Callback) ((AsyncResult)asyncResult).AsyncDelegate;");
Debug.WriteLine("fc.EndInvoke(asyncResult);");
Debug.WriteLine("}");
//Debug.WriteLine(method);
}
*/
private delegate void LoginCallback();
public System.IAsyncResult BeginLogin( System.AsyncCallback callback )
{
LoginCallback ftpCallback = new LoginCallback( this.Login);
return ftpCallback.BeginInvoke(callback, null);
}
private delegate void CloseCallback();
public System.IAsyncResult BeginClose( System.AsyncCallback callback )
{
CloseCallback ftpCallback = new CloseCallback( this.Close);
return ftpCallback.BeginInvoke(callback, null);
}
private delegate String[] GetFileListCallback();
public System.IAsyncResult BeginGetFileList( System.AsyncCallback callback )
{
GetFileListCallback ftpCallback = new GetFileListCallback( this.GetFileList);
return ftpCallback.BeginInvoke(callback, null);
}
private delegate String[] GetFileListMaskCallback(String mask);
public System.IAsyncResult BeginGetFileList( String mask, System.AsyncCallback callback )
{
GetFileListMaskCallback ftpCallback = new GetFileListMaskCallback(this.GetFileList);
return ftpCallback.BeginInvoke(mask, callback, null);
}
private delegate Int64 GetFileSizeCallback(String fileName);
public System.IAsyncResult BeginGetFileSize( String fileName, System.AsyncCallback callback )
{
GetFileSizeCallback ftpCallback = new GetFileSizeCallback(this.GetFileSize);
return ftpCallback.BeginInvoke(fileName, callback, null);
}
private delegate void DownloadCallback(String remFileName);
public System.IAsyncResult BeginDownload( String remFileName, System.AsyncCallback callback )
{
DownloadCallback ftpCallback = new DownloadCallback(this.Download);
return ftpCallback.BeginInvoke(remFileName, callback, null);
}
private delegate void DownloadFileNameResumeCallback(String remFileName,Boolean resume);
public System.IAsyncResult BeginDownload( String remFileName,Boolean resume, System.AsyncCallback callback )
{
DownloadFileNameResumeCallback ftpCallback = new DownloadFileNameResumeCallback(this.Download);
return ftpCallback.BeginInvoke(remFileName, resume, callback, null);
}
private delegate void DownloadFileNameFileNameCallback(String remFileName,String locFileName);
public System.IAsyncResult BeginDownload( String remFileName,String locFileName, System.AsyncCallback callback )
{
DownloadFileNameFileNameCallback ftpCallback = new DownloadFileNameFileNameCallback(this.Download);
return ftpCallback.BeginInvoke(remFileName, locFileName, callback, null);
}
private delegate void DownloadFileNameFileNameResumeCallback(String remFileName,String locFileName,Boolean resume);
public System.IAsyncResult BeginDownload( String remFileName,String locFileName,Boolean resume, System.AsyncCallback callback )
{
DownloadFileNameFileNameResumeCallback ftpCallback = new DownloadFileNameFileNameResumeCallback(this.Download);
return ftpCallback.BeginInvoke(remFileName, locFileName, resume, callback, null);
}
private delegate void UploadCallback(String fileName);
public System.IAsyncResult BeginUpload( String fileName, System.AsyncCallback callback )
{
UploadCallback ftpCallback = new UploadCallback(this.Upload);
return ftpCallback.BeginInvoke(fileName, callback, null);
}
private delegate void UploadFileNameResumeCallback(String fileName,Boolean resume);
public System.IAsyncResult BeginUpload( String fileName,Boolean resume, System.AsyncCallback callback )
{
UploadFileNameResumeCallback ftpCallback = new UploadFileNameResumeCallback(this.Upload);
return ftpCallback.BeginInvoke(fileName, resume, callback, null);
}
private delegate void UploadDirectoryCallback(String path,Boolean recurse);
public System.IAsyncResult BeginUploadDirectory( String path,Boolean recurse, System.AsyncCallback callback )
{
UploadDirectoryCallback ftpCallback = new UploadDirectoryCallback(this.UploadDirectory);
return ftpCallback.BeginInvoke(path, recurse, callback, null);
}
private delegate void UploadDirectoryPathRecurseMaskCallback(String path,Boolean recurse,String mask);
public System.IAsyncResult BeginUploadDirectory( String path,Boolean recurse,String mask, System.AsyncCallback callback )
{
UploadDirectoryPathRecurseMaskCallback ftpCallback = new UploadDirectoryPathRecurseMaskCallback(this.UploadDirectory);
return ftpCallback.BeginInvoke(path, recurse, mask, callback, null);
}
private delegate void DeleteFileCallback(String fileName);
public System.IAsyncResult BeginDeleteFile( String fileName, System.AsyncCallback callback )
{
DeleteFileCallback ftpCallback = new DeleteFileCallback(this.DeleteFile);
return ftpCallback.BeginInvoke(fileName, callback, null);
}
private delegate void RenameFileCallback(String oldFileName,String newFileName,Boolean overwrite);
public System.IAsyncResult BeginRenameFile( String oldFileName,String newFileName,Boolean overwrite, System.AsyncCallback callback )
{
RenameFileCallback ftpCallback = new RenameFileCallback(this.RenameFile);
return ftpCallback.BeginInvoke(oldFileName, newFileName, overwrite, callback, null);
}
private delegate void MakeDirCallback(String dirName);
public System.IAsyncResult BeginMakeDir( String dirName, System.AsyncCallback callback )
{
MakeDirCallback ftpCallback = new MakeDirCallback(this.MakeDir);
return ftpCallback.BeginInvoke(dirName, callback, null);
}
private delegate void RemoveDirCallback(String dirName);
public System.IAsyncResult BeginRemoveDir( String dirName, System.AsyncCallback callback )
{
RemoveDirCallback ftpCallback = new RemoveDirCallback(this.RemoveDir);
return ftpCallback.BeginInvoke(dirName, callback, null);
}
private delegate void ChangeDirCallback(String dirName);
public System.IAsyncResult BeginChangeDir( String dirName, System.AsyncCallback callback )
{
ChangeDirCallback ftpCallback = new ChangeDirCallback(this.ChangeDir);
return ftpCallback.BeginInvoke(dirName, callback, null);
}
#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.ComponentModel;
using System.Globalization;
using System.Runtime.CompilerServices;
using System.Threading;
namespace System.Diagnostics
{
/// <summary>
/// Performance Counter component.
/// This class provides support for NT Performance counters.
/// It handles both the existing counters (accesible by Perf Registry Interface)
/// and user defined (extensible) counters.
/// This class is a part of a larger framework, that includes the perf dll object and
/// perf service.
/// </summary>
public sealed class PerformanceCounter : Component, ISupportInitialize
{
private string _machineName;
private string _categoryName;
private string _counterName;
private string _instanceName;
private PerformanceCounterInstanceLifetime _instanceLifetime = PerformanceCounterInstanceLifetime.Global;
private bool _isReadOnly;
private bool _initialized = false;
private string _helpMsg = null;
private int _counterType = -1;
// Cached old sample
private CounterSample _oldSample = CounterSample.Empty;
// Cached IP Shared Performanco counter
private SharedPerformanceCounter _sharedCounter;
[ObsoleteAttribute("This field has been deprecated and is not used. Use machine.config or an application configuration file to set the size of the PerformanceCounter file mapping.")]
public static int DefaultFileMappingSize = 524288;
private Object _instanceLockObject;
private Object InstanceLockObject
{
get
{
if (_instanceLockObject == null)
{
Object o = new Object();
Interlocked.CompareExchange(ref _instanceLockObject, o, null);
}
return _instanceLockObject;
}
}
/// <summary>
/// The defaut constructor. Creates the perf counter object
/// </summary>
public PerformanceCounter()
{
_machineName = ".";
_categoryName = string.Empty;
_counterName = string.Empty;
_instanceName = string.Empty;
_isReadOnly = true;
GC.SuppressFinalize(this);
}
/// <summary>
/// Creates the Performance Counter Object
/// </summary>
public PerformanceCounter(string categoryName, string counterName, string instanceName, string machineName)
{
MachineName = machineName;
CategoryName = categoryName;
CounterName = counterName;
InstanceName = instanceName;
_isReadOnly = true;
Initialize();
GC.SuppressFinalize(this);
}
internal PerformanceCounter(string categoryName, string counterName, string instanceName, string machineName, bool skipInit)
{
MachineName = machineName;
CategoryName = categoryName;
CounterName = counterName;
InstanceName = instanceName;
_isReadOnly = true;
_initialized = true;
GC.SuppressFinalize(this);
}
/// <summary>
/// Creates the Performance Counter Object on local machine.
/// </summary>
public PerformanceCounter(string categoryName, string counterName, string instanceName) :
this(categoryName, counterName, instanceName, true)
{
}
/// <summary>
/// Creates the Performance Counter Object on local machine.
/// </summary>
public PerformanceCounter(string categoryName, string counterName, string instanceName, bool readOnly)
{
if (!readOnly)
{
VerifyWriteableCounterAllowed();
}
MachineName = ".";
CategoryName = categoryName;
CounterName = counterName;
InstanceName = instanceName;
_isReadOnly = readOnly;
Initialize();
GC.SuppressFinalize(this);
}
/// <summary>
/// Creates the Performance Counter Object, assumes that it's a single instance
/// </summary>
public PerformanceCounter(string categoryName, string counterName) :
this(categoryName, counterName, true)
{
}
/// <summary>
/// Creates the Performance Counter Object, assumes that it's a single instance
/// </summary>
public PerformanceCounter(string categoryName, string counterName, bool readOnly) :
this(categoryName, counterName, "", readOnly)
{
}
/// <summary>
/// Returns the performance category name for this performance counter
/// </summary>
public string CategoryName
{
get
{
return _categoryName;
}
set
{
if (value == null)
throw new ArgumentNullException(nameof(value));
if (_categoryName == null || !string.Equals(_categoryName, value, StringComparison.OrdinalIgnoreCase))
{
_categoryName = value;
Close();
}
}
}
/// <summary>
/// Returns the description message for this performance counter
/// </summary>
public string CounterHelp
{
get
{
string currentCategoryName = _categoryName;
string currentMachineName = _machineName;
Initialize();
if (_helpMsg == null)
_helpMsg = PerformanceCounterLib.GetCounterHelp(currentMachineName, currentCategoryName, _counterName);
return _helpMsg;
}
}
/// <summary>
/// Sets/returns the performance counter name for this performance counter
/// </summary>
public string CounterName
{
get
{
return _counterName;
}
set
{
if (value == null)
throw new ArgumentNullException(nameof(value));
if (_counterName == null || !string.Equals(_counterName, value, StringComparison.OrdinalIgnoreCase))
{
_counterName = value;
Close();
}
}
}
/// <summary>
/// Sets/Returns the counter type for this performance counter
/// </summary>
public PerformanceCounterType CounterType
{
get
{
if (_counterType == -1)
{
string currentCategoryName = _categoryName;
string currentMachineName = _machineName;
// This is the same thing that NextSample does, except that it doesn't try to get the actual counter
// value. If we wanted the counter value, we would need to have an instance name.
Initialize();
CategorySample categorySample = PerformanceCounterLib.GetCategorySample(currentMachineName, currentCategoryName);
CounterDefinitionSample counterSample = categorySample.GetCounterDefinitionSample(_counterName);
_counterType = counterSample._counterType;
}
return (PerformanceCounterType)_counterType;
}
}
public PerformanceCounterInstanceLifetime InstanceLifetime
{
get { return _instanceLifetime; }
set
{
if (value > PerformanceCounterInstanceLifetime.Process || value < PerformanceCounterInstanceLifetime.Global)
throw new ArgumentOutOfRangeException(nameof(value));
if (_initialized)
throw new InvalidOperationException(SR.Format(SR.CantSetLifetimeAfterInitialized));
_instanceLifetime = value;
}
}
/// <summary>
/// Sets/returns an instance name for this performance counter
/// </summary>
public string InstanceName
{
get
{
return _instanceName;
}
set
{
if (value == null && _instanceName == null)
return;
if ((value == null && _instanceName != null) ||
(value != null && _instanceName == null) ||
!string.Equals(_instanceName, value, StringComparison.OrdinalIgnoreCase))
{
_instanceName = value;
Close();
}
}
}
/// <summary>
/// Returns true if counter is read only (system counter, foreign extensible counter or remote counter)
/// </summary>
public bool ReadOnly
{
get
{
return _isReadOnly;
}
set
{
if (value != _isReadOnly)
{
if (value == false)
{
VerifyWriteableCounterAllowed();
}
_isReadOnly = value;
Close();
}
}
}
/// <summary>
/// Set/returns the machine name for this performance counter
/// </summary>
public string MachineName
{
get
{
return _machineName;
}
set
{
if (!SyntaxCheck.CheckMachineName(value))
throw new ArgumentException(SR.Format(SR.InvalidProperty, nameof(MachineName), value), nameof(value));
if (_machineName != value)
{
_machineName = value;
Close();
}
}
}
/// <summary>
/// Directly accesses the raw value of this counter. If counter type is of a 32-bit size, it will truncate
/// the value given to 32 bits. This can be significantly more performant for scenarios where
/// the raw value is sufficient. Note that this only works for custom counters created using
/// this component, non-custom counters will throw an exception if this property is accessed.
/// </summary>
public long RawValue
{
get
{
if (ReadOnly)
{
//No need to initialize or Demand, since NextSample already does.
return NextSample().RawValue;
}
else
{
Initialize();
return _sharedCounter.Value;
}
}
set
{
if (ReadOnly)
ThrowReadOnly();
Initialize();
_sharedCounter.Value = value;
}
}
/// <summary>
/// </summary>
public void BeginInit()
{
Close();
}
/// <summary>
/// Frees all the resources allocated by this counter
/// </summary>
public void Close()
{
_helpMsg = null;
_oldSample = CounterSample.Empty;
_sharedCounter = null;
_initialized = false;
_counterType = -1;
}
/// <summary>
/// Frees all the resources allocated for all performance
/// counters, frees File Mapping used by extensible counters,
/// unloads dll's used to read counters.
/// </summary>
public static void CloseSharedResources()
{
PerformanceCounterLib.CloseAllLibraries();
}
/// <internalonly/>
/// <summary>
/// </summary>
protected override void Dispose(bool disposing)
{
// safe to call while finalizing or disposing
if (disposing)
{
//Dispose managed and unmanaged resources
Close();
}
base.Dispose(disposing);
}
/// <summary>
/// Decrements counter by one using an efficient atomic operation.
/// </summary>
public long Decrement()
{
if (ReadOnly)
ThrowReadOnly();
Initialize();
return _sharedCounter.Decrement();
}
/// <summary>
/// </summary>
public void EndInit()
{
Initialize();
}
/// <summary>
/// Increments the value of this counter. If counter type is of a 32-bit size, it'll truncate
/// the value given to 32 bits. This method uses a mutex to guarantee correctness of
/// the operation in case of multiple writers. This method should be used with caution because of the negative
/// impact on performance due to creation of the mutex.
/// </summary>
public long IncrementBy(long value)
{
if (_isReadOnly)
ThrowReadOnly();
Initialize();
return _sharedCounter.IncrementBy(value);
}
/// <summary>
/// Increments counter by one using an efficient atomic operation.
/// </summary>
public long Increment()
{
if (_isReadOnly)
ThrowReadOnly();
Initialize();
return _sharedCounter.Increment();
}
private void ThrowReadOnly()
{
throw new InvalidOperationException(SR.Format(SR.ReadOnlyCounter));
}
private static void VerifyWriteableCounterAllowed()
{
if (EnvironmentHelpers.IsAppContainerProcess)
{
throw new NotSupportedException(SR.Format(SR.PCNotSupportedUnderAppContainer));
}
}
private void Initialize()
{
// Keep this method small so the JIT will inline it.
if (!_initialized && !DesignMode)
{
InitializeImpl();
}
}
/// <summary>
/// Intializes required resources
/// </summary>
private void InitializeImpl()
{
bool tookLock = false;
try
{
Monitor.Enter(InstanceLockObject, ref tookLock);
if (!_initialized)
{
string currentCategoryName = _categoryName;
string currentMachineName = _machineName;
if (currentCategoryName == string.Empty)
throw new InvalidOperationException(SR.Format(SR.CategoryNameMissing));
if (_counterName == string.Empty)
throw new InvalidOperationException(SR.Format(SR.CounterNameMissing));
if (ReadOnly)
{
if (!PerformanceCounterLib.CounterExists(currentMachineName, currentCategoryName, _counterName))
throw new InvalidOperationException(SR.Format(SR.CounterExists, currentCategoryName, _counterName));
PerformanceCounterCategoryType categoryType = PerformanceCounterLib.GetCategoryType(currentMachineName, currentCategoryName);
if (categoryType == PerformanceCounterCategoryType.MultiInstance)
{
if (string.IsNullOrEmpty(_instanceName))
throw new InvalidOperationException(SR.Format(SR.MultiInstanceOnly, currentCategoryName));
}
else if (categoryType == PerformanceCounterCategoryType.SingleInstance)
{
if (!string.IsNullOrEmpty(_instanceName))
throw new InvalidOperationException(SR.Format(SR.SingleInstanceOnly, currentCategoryName));
}
if (_instanceLifetime != PerformanceCounterInstanceLifetime.Global)
throw new InvalidOperationException(SR.Format(SR.InstanceLifetimeProcessonReadOnly));
_initialized = true;
}
else
{
if (currentMachineName != "." && !string.Equals(currentMachineName, PerformanceCounterLib.ComputerName, StringComparison.OrdinalIgnoreCase))
throw new InvalidOperationException(SR.Format(SR.RemoteWriting));
if (!PerformanceCounterLib.IsCustomCategory(currentMachineName, currentCategoryName))
throw new InvalidOperationException(SR.Format(SR.NotCustomCounter));
// check category type
PerformanceCounterCategoryType categoryType = PerformanceCounterLib.GetCategoryType(currentMachineName, currentCategoryName);
if (categoryType == PerformanceCounterCategoryType.MultiInstance)
{
if (string.IsNullOrEmpty(_instanceName))
throw new InvalidOperationException(SR.Format(SR.MultiInstanceOnly, currentCategoryName));
}
else if (categoryType == PerformanceCounterCategoryType.SingleInstance)
{
if (!string.IsNullOrEmpty(_instanceName))
throw new InvalidOperationException(SR.Format(SR.SingleInstanceOnly, currentCategoryName));
}
if (string.IsNullOrEmpty(_instanceName) && InstanceLifetime == PerformanceCounterInstanceLifetime.Process)
throw new InvalidOperationException(SR.Format(SR.InstanceLifetimeProcessforSingleInstance));
_sharedCounter = new SharedPerformanceCounter(currentCategoryName.ToLower(CultureInfo.InvariantCulture), _counterName.ToLower(CultureInfo.InvariantCulture), _instanceName.ToLower(CultureInfo.InvariantCulture), _instanceLifetime);
_initialized = true;
}
}
}
finally
{
if (tookLock)
Monitor.Exit(InstanceLockObject);
}
}
// Will cause an update, raw value
/// <summary>
/// Obtains a counter sample and returns the raw value for it.
/// </summary>
public CounterSample NextSample()
{
string currentCategoryName = _categoryName;
string currentMachineName = _machineName;
Initialize();
CategorySample categorySample = PerformanceCounterLib.GetCategorySample(currentMachineName, currentCategoryName);
CounterDefinitionSample counterSample = categorySample.GetCounterDefinitionSample(_counterName);
_counterType = counterSample._counterType;
if (!categorySample._isMultiInstance)
{
if (_instanceName != null && _instanceName.Length != 0)
throw new InvalidOperationException(SR.Format(SR.InstanceNameProhibited, _instanceName));
return counterSample.GetSingleValue();
}
else
{
if (_instanceName == null || _instanceName.Length == 0)
throw new InvalidOperationException(SR.Format(SR.InstanceNameRequired));
return counterSample.GetInstanceValue(_instanceName);
}
}
/// <summary>
/// Obtains a counter sample and returns the calculated value for it.
/// NOTE: For counters whose calculated value depend upon 2 counter reads,
/// the very first read will return 0.0.
/// </summary>
public float NextValue()
{
//No need to initialize or Demand, since NextSample already does.
CounterSample newSample = NextSample();
float retVal = 0.0f;
retVal = CounterSample.Calculate(_oldSample, newSample);
_oldSample = newSample;
return retVal;
}
/// <summary>
/// Removes this counter instance from the shared memory
/// </summary>
public void RemoveInstance()
{
if (_isReadOnly)
throw new InvalidOperationException(SR.Format(SR.ReadOnlyRemoveInstance));
Initialize();
_sharedCounter.RemoveInstance(_instanceName.ToLower(CultureInfo.InvariantCulture), _instanceLifetime);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace System.Globalization {
//
// N.B.:
// A lot of this code is directly from DateTime.cs. If you update that class,
// update this one as well.
// However, we still need these duplicated code because we will add era support
// in this class.
//
//
using System.Threading;
using System;
using System.Globalization;
using System.Runtime.Serialization;
using System.Diagnostics.Contracts;
// This calendar recognizes two era values:
// 0 CurrentEra (AD)
// 1 BeforeCurrentEra (BC)
[System.Runtime.InteropServices.ComVisible(true)]
[Serializable]
public class GregorianCalendar : Calendar
{
/*
A.D. = anno Domini
*/
public const int ADEra = 1;
internal const int DatePartYear = 0;
internal const int DatePartDayOfYear = 1;
internal const int DatePartMonth = 2;
internal const int DatePartDay = 3;
//
// This is the max Gregorian year can be represented by DateTime class. The limitation
// is derived from DateTime class.
//
internal const int MaxYear = 9999;
internal GregorianCalendarTypes m_type;
internal static readonly int[] DaysToMonth365 =
{
0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365
};
internal static readonly int[] DaysToMonth366 =
{
0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335, 366
};
private static volatile Calendar s_defaultInstance;
#region Serialization
[OnDeserialized]
private void OnDeserialized(StreamingContext ctx)
{
if (m_type < GregorianCalendarTypes.Localized ||
m_type > GregorianCalendarTypes.TransliteratedFrench)
{
throw new SerializationException(
String.Format(
CultureInfo.CurrentCulture,
Environment.GetResourceString(
"Serialization_MemberOutOfRange"),
"type",
"GregorianCalendar"));
}
}
#endregion Serialization
[System.Runtime.InteropServices.ComVisible(false)]
public override DateTime MinSupportedDateTime
{
get
{
return (DateTime.MinValue);
}
}
[System.Runtime.InteropServices.ComVisible(false)]
public override DateTime MaxSupportedDateTime
{
get
{
return (DateTime.MaxValue);
}
}
// Return the type of the Gregorian calendar.
//
[System.Runtime.InteropServices.ComVisible(false)]
public override CalendarAlgorithmType AlgorithmType
{
get
{
return CalendarAlgorithmType.SolarCalendar;
}
}
/*=================================GetDefaultInstance==========================
**Action: Internal method to provide a default intance of GregorianCalendar. Used by NLS+ implementation
** and other calendars.
**Returns:
**Arguments:
**Exceptions:
============================================================================*/
internal static Calendar GetDefaultInstance() {
if (s_defaultInstance == null) {
s_defaultInstance = new GregorianCalendar();
}
return (s_defaultInstance);
}
// Construct an instance of gregorian calendar.
public GregorianCalendar() :
this(GregorianCalendarTypes.Localized) {
}
public GregorianCalendar(GregorianCalendarTypes type) {
if ((int)type < (int)GregorianCalendarTypes.Localized || (int)type > (int)GregorianCalendarTypes.TransliteratedFrench) {
throw new ArgumentOutOfRangeException(
"type",
Environment.GetResourceString("ArgumentOutOfRange_Range",
GregorianCalendarTypes.Localized, GregorianCalendarTypes.TransliteratedFrench));
}
Contract.EndContractBlock();
this.m_type = type;
}
public virtual GregorianCalendarTypes CalendarType {
get {
return (m_type);
}
set {
VerifyWritable();
switch (value) {
case GregorianCalendarTypes.Localized:
case GregorianCalendarTypes.USEnglish:
case GregorianCalendarTypes.MiddleEastFrench:
case GregorianCalendarTypes.Arabic:
case GregorianCalendarTypes.TransliteratedEnglish:
case GregorianCalendarTypes.TransliteratedFrench:
m_type = value;
break;
default:
throw new ArgumentOutOfRangeException("m_type", Environment.GetResourceString("ArgumentOutOfRange_Enum"));
}
}
}
internal override int ID {
get {
// By returning different ID for different variations of GregorianCalendar,
// we can support the Transliterated Gregorian calendar.
// DateTimeFormatInfo will use this ID to get formatting information about
// the calendar.
return ((int)m_type);
}
}
// Returns a given date part of this DateTime. This method is used
// to compute the year, day-of-year, month, or day part.
internal virtual int GetDatePart(long ticks, int part)
{
// n = number of days since 1/1/0001
int n = (int)(ticks / TicksPerDay);
// y400 = number of whole 400-year periods since 1/1/0001
int y400 = n / DaysPer400Years;
// n = day number within 400-year period
n -= y400 * DaysPer400Years;
// y100 = number of whole 100-year periods within 400-year period
int y100 = n / DaysPer100Years;
// Last 100-year period has an extra day, so decrement result if 4
if (y100 == 4) y100 = 3;
// n = day number within 100-year period
n -= y100 * DaysPer100Years;
// y4 = number of whole 4-year periods within 100-year period
int y4 = n / DaysPer4Years;
// n = day number within 4-year period
n -= y4 * DaysPer4Years;
// y1 = number of whole years within 4-year period
int y1 = n / DaysPerYear;
// Last year has an extra day, so decrement result if 4
if (y1 == 4) y1 = 3;
// If year was requested, compute and return it
if (part == DatePartYear)
{
return (y400 * 400 + y100 * 100 + y4 * 4 + y1 + 1);
}
// n = day number within year
n -= y1 * DaysPerYear;
// If day-of-year was requested, return it
if (part == DatePartDayOfYear)
{
return (n + 1);
}
// Leap year calculation looks different from IsLeapYear since y1, y4,
// and y100 are relative to year 1, not year 0
bool leapYear = (y1 == 3 && (y4 != 24 || y100 == 3));
int[] days = leapYear? DaysToMonth366: DaysToMonth365;
// All months have less than 32 days, so n >> 5 is a good conservative
// estimate for the month
int m = (n >> 5) + 1;
// m = 1-based month number
while (n >= days[m]) m++;
// If month was requested, return it
if (part == DatePartMonth) return (m);
// Return 1-based day-of-month
return (n - days[m - 1] + 1);
}
/*=================================GetAbsoluteDate==========================
**Action: Gets the absolute date for the given Gregorian date. The absolute date means
** the number of days from January 1st, 1 A.D.
**Returns: the absolute date
**Arguments:
** year the Gregorian year
** month the Gregorian month
** day the day
**Exceptions:
** ArgumentOutOfRangException if year, month, day value is valid.
**Note:
** This is an internal method used by DateToTicks() and the calculations of Hijri and Hebrew calendars.
** Number of Days in Prior Years (both common and leap years) +
** Number of Days in Prior Months of Current Year +
** Number of Days in Current Month
**
============================================================================*/
internal static long GetAbsoluteDate(int year, int month, int day) {
if (year >= 1 && year <= MaxYear && month >= 1 && month <= 12)
{
int[] days = ((year % 4 == 0 && (year % 100 != 0 || year % 400 == 0))) ? DaysToMonth366: DaysToMonth365;
if (day >= 1 && (day <= days[month] - days[month - 1])) {
int y = year - 1;
int absoluteDate = y * 365 + y / 4 - y / 100 + y / 400 + days[month - 1] + day - 1;
return (absoluteDate);
}
}
throw new ArgumentOutOfRangeException(null, Environment.GetResourceString("ArgumentOutOfRange_BadYearMonthDay"));
}
// Returns the tick count corresponding to the given year, month, and day.
// Will check the if the parameters are valid.
internal virtual long DateToTicks(int year, int month, int day) {
return (GetAbsoluteDate(year, month, day)* TicksPerDay);
}
// Returns the DateTime resulting from adding the given number of
// months to the specified DateTime. The result is computed by incrementing
// (or decrementing) the year and month parts of the specified DateTime by
// value months, and, if required, adjusting the day part of the
// resulting date downwards to the last day of the resulting month in the
// resulting year. The time-of-day part of the result is the same as the
// time-of-day part of the specified DateTime.
//
// In more precise terms, considering the specified DateTime to be of the
// form y / m / d + t, where y is the
// year, m is the month, d is the day, and t is the
// time-of-day, the result is y1 / m1 / d1 + t,
// where y1 and m1 are computed by adding value months
// to y and m, and d1 is the largest value less than
// or equal to d that denotes a valid day in month m1 of year
// y1.
//
public override DateTime AddMonths(DateTime time, int months)
{
if (months < -120000 || months > 120000) {
throw new ArgumentOutOfRangeException(
"months",
String.Format(
CultureInfo.CurrentCulture,
Environment.GetResourceString("ArgumentOutOfRange_Range"),
-120000,
120000));
}
Contract.EndContractBlock();
int y = GetDatePart(time.Ticks, DatePartYear);
int m = GetDatePart(time.Ticks, DatePartMonth);
int d = GetDatePart(time.Ticks, DatePartDay);
int i = m - 1 + months;
if (i >= 0)
{
m = i % 12 + 1;
y = y + i / 12;
}
else
{
m = 12 + (i + 1) % 12;
y = y + (i - 11) / 12;
}
int[] daysArray = (y % 4 == 0 && (y % 100 != 0 || y % 400 == 0)) ? DaysToMonth366: DaysToMonth365;
int days = (daysArray[m] - daysArray[m - 1]);
if (d > days)
{
d = days;
}
long ticks = DateToTicks(y, m, d) + time.Ticks % TicksPerDay;
Calendar.CheckAddResult(ticks, MinSupportedDateTime, MaxSupportedDateTime);
return (new DateTime(ticks));
}
// Returns the DateTime resulting from adding the given number of
// years to the specified DateTime. The result is computed by incrementing
// (or decrementing) the year part of the specified DateTime by value
// years. If the month and day of the specified DateTime is 2/29, and if the
// resulting year is not a leap year, the month and day of the resulting
// DateTime becomes 2/28. Otherwise, the month, day, and time-of-day
// parts of the result are the same as those of the specified DateTime.
//
public override DateTime AddYears(DateTime time, int years)
{
return (AddMonths(time, years * 12));
}
// Returns the day-of-month part of the specified DateTime. The returned
// value is an integer between 1 and 31.
//
public override int GetDayOfMonth(DateTime time)
{
return (GetDatePart(time.Ticks, DatePartDay));
}
// Returns the day-of-week part of the specified DateTime. The returned value
// is an integer between 0 and 6, where 0 indicates Sunday, 1 indicates
// Monday, 2 indicates Tuesday, 3 indicates Wednesday, 4 indicates
// Thursday, 5 indicates Friday, and 6 indicates Saturday.
//
public override DayOfWeek GetDayOfWeek(DateTime time)
{
return ((DayOfWeek)((int)(time.Ticks / TicksPerDay + 1) % 7));
}
// Returns the day-of-year part of the specified DateTime. The returned value
// is an integer between 1 and 366.
//
public override int GetDayOfYear(DateTime time)
{
return (GetDatePart(time.Ticks, DatePartDayOfYear));
}
// Returns the number of days in the month given by the year and
// month arguments.
//
public override int GetDaysInMonth(int year, int month, int era) {
if (era == CurrentEra || era == ADEra) {
if (year < 1 || year > MaxYear) {
throw new ArgumentOutOfRangeException("year", Environment.GetResourceString("ArgumentOutOfRange_Range",
1, MaxYear));
}
if (month < 1 || month > 12) {
throw new ArgumentOutOfRangeException("month", Environment.GetResourceString("ArgumentOutOfRange_Month"));
}
int[] days = ((year % 4 == 0 && (year % 100 != 0 || year % 400 == 0)) ? DaysToMonth366: DaysToMonth365);
return (days[month] - days[month - 1]);
}
throw new ArgumentOutOfRangeException("era", Environment.GetResourceString("ArgumentOutOfRange_InvalidEraValue"));
}
// Returns the number of days in the year given by the year argument for the current era.
//
public override int GetDaysInYear(int year, int era)
{
if (era == CurrentEra || era == ADEra) {
if (year >= 1 && year <= MaxYear) {
return ((year % 4 == 0 && (year % 100 != 0 || year % 400 == 0)) ? 366:365);
}
throw new ArgumentOutOfRangeException(
"year",
String.Format(
CultureInfo.CurrentCulture,
Environment.GetResourceString("ArgumentOutOfRange_Range"),
1,
MaxYear));
}
throw new ArgumentOutOfRangeException("era", Environment.GetResourceString("ArgumentOutOfRange_InvalidEraValue"));
}
// Returns the era for the specified DateTime value.
public override int GetEra(DateTime time)
{
return (ADEra);
}
public override int[] Eras {
get {
return (new int[] {ADEra} );
}
}
// Returns the month part of the specified DateTime. The returned value is an
// integer between 1 and 12.
//
public override int GetMonth(DateTime time)
{
return (GetDatePart(time.Ticks, DatePartMonth));
}
// Returns the number of months in the specified year and era.
public override int GetMonthsInYear(int year, int era)
{
if (era == CurrentEra || era == ADEra) {
if (year >= 1 && year <= MaxYear)
{
return (12);
}
throw new ArgumentOutOfRangeException(
"year",
String.Format(
CultureInfo.CurrentCulture,
Environment.GetResourceString("ArgumentOutOfRange_Range"),
1,
MaxYear));
}
throw new ArgumentOutOfRangeException("era", Environment.GetResourceString("ArgumentOutOfRange_InvalidEraValue"));
}
// Returns the year part of the specified DateTime. The returned value is an
// integer between 1 and 9999.
//
public override int GetYear(DateTime time)
{
return (GetDatePart(time.Ticks, DatePartYear));
}
// Checks whether a given day in the specified era is a leap day. This method returns true if
// the date is a leap day, or false if not.
//
public override bool IsLeapDay(int year, int month, int day, int era)
{
if (month < 1 || month > 12) {
throw new ArgumentOutOfRangeException("month", Environment.GetResourceString("ArgumentOutOfRange_Range",
1, 12));
}
Contract.EndContractBlock();
if (era != CurrentEra && era != ADEra)
{
throw new ArgumentOutOfRangeException("era", Environment.GetResourceString("ArgumentOutOfRange_InvalidEraValue"));
}
if (year < 1 || year > MaxYear) {
throw new ArgumentOutOfRangeException(
"year",
Environment.GetResourceString("ArgumentOutOfRange_Range", 1, MaxYear));
}
if (day < 1 || day > GetDaysInMonth(year, month)) {
throw new ArgumentOutOfRangeException("day", Environment.GetResourceString("ArgumentOutOfRange_Range",
1, GetDaysInMonth(year, month)));
}
if (!IsLeapYear(year)) {
return (false);
}
if (month == 2 && day == 29) {
return (true);
}
return (false);
}
// Returns the leap month in a calendar year of the specified era. This method returns 0
// if this calendar does not have leap month, or this year is not a leap year.
//
[System.Runtime.InteropServices.ComVisible(false)]
public override int GetLeapMonth(int year, int era)
{
if (era != CurrentEra && era != ADEra)
{
throw new ArgumentOutOfRangeException("era", Environment.GetResourceString("ArgumentOutOfRange_InvalidEraValue"));
}
if (year < 1 || year > MaxYear) {
throw new ArgumentOutOfRangeException(
"year",
String.Format(
CultureInfo.CurrentCulture,
Environment.GetResourceString("ArgumentOutOfRange_Range"), 1, MaxYear));
}
Contract.EndContractBlock();
return (0);
}
// Checks whether a given month in the specified era is a leap month. This method returns true if
// month is a leap month, or false if not.
//
public override bool IsLeapMonth(int year, int month, int era)
{
if (era != CurrentEra && era != ADEra) {
throw new ArgumentOutOfRangeException("era", Environment.GetResourceString("ArgumentOutOfRange_InvalidEraValue"));
}
if (year < 1 || year > MaxYear) {
throw new ArgumentOutOfRangeException(
"year",
String.Format(
CultureInfo.CurrentCulture,
Environment.GetResourceString("ArgumentOutOfRange_Range"), 1, MaxYear));
}
if (month < 1 || month > 12) {
throw new ArgumentOutOfRangeException("month", Environment.GetResourceString("ArgumentOutOfRange_Range",
1, 12));
}
Contract.EndContractBlock();
return (false);
}
// Checks whether a given year in the specified era is a leap year. This method returns true if
// year is a leap year, or false if not.
//
public override bool IsLeapYear(int year, int era) {
if (era == CurrentEra || era == ADEra) {
if (year >= 1 && year <= MaxYear) {
return (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0));
}
throw new ArgumentOutOfRangeException(
"year",
String.Format(
CultureInfo.CurrentCulture,
Environment.GetResourceString("ArgumentOutOfRange_Range"), 1, MaxYear));
}
throw new ArgumentOutOfRangeException("era", Environment.GetResourceString("ArgumentOutOfRange_InvalidEraValue"));
}
// Returns the date and time converted to a DateTime value. Throws an exception if the n-tuple is invalid.
//
public override DateTime ToDateTime(int year, int month, int day, int hour, int minute, int second, int millisecond, int era)
{
if (era == CurrentEra || era == ADEra) {
return new DateTime(year, month, day, hour, minute, second, millisecond);
}
throw new ArgumentOutOfRangeException("era", Environment.GetResourceString("ArgumentOutOfRange_InvalidEraValue"));
}
internal override Boolean TryToDateTime(int year, int month, int day, int hour, int minute, int second, int millisecond, int era, out DateTime result) {
if (era == CurrentEra || era == ADEra) {
return DateTime.TryCreate(year, month, day, hour, minute, second, millisecond, out result);
}
result = DateTime.MinValue;
return false;
}
private const int DEFAULT_TWO_DIGIT_YEAR_MAX = 2029;
public override int TwoDigitYearMax
{
get {
if (twoDigitYearMax == -1) {
twoDigitYearMax = GetSystemTwoDigitYearSetting(ID, DEFAULT_TWO_DIGIT_YEAR_MAX);
}
return (twoDigitYearMax);
}
set {
VerifyWritable();
if (value < 99 || value > MaxYear) {
throw new ArgumentOutOfRangeException(
"year",
String.Format(
CultureInfo.CurrentCulture,
Environment.GetResourceString("ArgumentOutOfRange_Range"),
99,
MaxYear));
}
twoDigitYearMax = value;
}
}
public override int ToFourDigitYear(int year) {
if (year < 0) {
throw new ArgumentOutOfRangeException("year",
Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
}
Contract.EndContractBlock();
if (year > MaxYear) {
throw new ArgumentOutOfRangeException(
"year",
String.Format(
CultureInfo.CurrentCulture,
Environment.GetResourceString("ArgumentOutOfRange_Range"), 1, MaxYear));
}
return (base.ToFourDigitYear(year));
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator 1.0.1.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.Sql
{
using Microsoft.Azure;
using Microsoft.Azure.Management;
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// Extension methods for RecommendedElasticPoolsOperations.
/// </summary>
public static partial class RecommendedElasticPoolsOperationsExtensions
{
/// <summary>
/// Gets a recommented elastic pool.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group that contains the resource. You can obtain
/// this value from the Azure Resource Manager API or the portal.
/// </param>
/// <param name='serverName'>
/// The name of the server.
/// </param>
/// <param name='recommendedElasticPoolName'>
/// The name of the recommended elastic pool to be retrieved.
/// </param>
public static RecommendedElasticPool Get(this IRecommendedElasticPoolsOperations operations, string resourceGroupName, string serverName, string recommendedElasticPoolName)
{
return operations.GetAsync(resourceGroupName, serverName, recommendedElasticPoolName).GetAwaiter().GetResult();
}
/// <summary>
/// Gets a recommented elastic pool.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group that contains the resource. You can obtain
/// this value from the Azure Resource Manager API or the portal.
/// </param>
/// <param name='serverName'>
/// The name of the server.
/// </param>
/// <param name='recommendedElasticPoolName'>
/// The name of the recommended elastic pool to be retrieved.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<RecommendedElasticPool> GetAsync(this IRecommendedElasticPoolsOperations operations, string resourceGroupName, string serverName, string recommendedElasticPoolName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetWithHttpMessagesAsync(resourceGroupName, serverName, recommendedElasticPoolName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Gets a database inside of a recommented elastic pool.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group that contains the resource. You can obtain
/// this value from the Azure Resource Manager API or the portal.
/// </param>
/// <param name='serverName'>
/// The name of the server.
/// </param>
/// <param name='recommendedElasticPoolName'>
/// The name of the elastic pool to be retrieved.
/// </param>
/// <param name='databaseName'>
/// The name of the database to be retrieved.
/// </param>
public static Database GetDatabases(this IRecommendedElasticPoolsOperations operations, string resourceGroupName, string serverName, string recommendedElasticPoolName, string databaseName)
{
return operations.GetDatabasesAsync(resourceGroupName, serverName, recommendedElasticPoolName, databaseName).GetAwaiter().GetResult();
}
/// <summary>
/// Gets a database inside of a recommented elastic pool.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group that contains the resource. You can obtain
/// this value from the Azure Resource Manager API or the portal.
/// </param>
/// <param name='serverName'>
/// The name of the server.
/// </param>
/// <param name='recommendedElasticPoolName'>
/// The name of the elastic pool to be retrieved.
/// </param>
/// <param name='databaseName'>
/// The name of the database to be retrieved.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<Database> GetDatabasesAsync(this IRecommendedElasticPoolsOperations operations, string resourceGroupName, string serverName, string recommendedElasticPoolName, string databaseName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetDatabasesWithHttpMessagesAsync(resourceGroupName, serverName, recommendedElasticPoolName, databaseName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Returns recommended elastic pools.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group that contains the resource. You can obtain
/// this value from the Azure Resource Manager API or the portal.
/// </param>
/// <param name='serverName'>
/// The name of the server.
/// </param>
public static IEnumerable<RecommendedElasticPool> ListByServer(this IRecommendedElasticPoolsOperations operations, string resourceGroupName, string serverName)
{
return operations.ListByServerAsync(resourceGroupName, serverName).GetAwaiter().GetResult();
}
/// <summary>
/// Returns recommended elastic pools.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group that contains the resource. You can obtain
/// this value from the Azure Resource Manager API or the portal.
/// </param>
/// <param name='serverName'>
/// The name of the server.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IEnumerable<RecommendedElasticPool>> ListByServerAsync(this IRecommendedElasticPoolsOperations operations, string resourceGroupName, string serverName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListByServerWithHttpMessagesAsync(resourceGroupName, serverName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Returns a list of databases inside a recommented elastic pool.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group that contains the resource. You can obtain
/// this value from the Azure Resource Manager API or the portal.
/// </param>
/// <param name='serverName'>
/// The name of the server.
/// </param>
/// <param name='recommendedElasticPoolName'>
/// The name of the recommended elastic pool to be retrieved.
/// </param>
public static IEnumerable<Database> ListDatabases(this IRecommendedElasticPoolsOperations operations, string resourceGroupName, string serverName, string recommendedElasticPoolName)
{
return operations.ListDatabasesAsync(resourceGroupName, serverName, recommendedElasticPoolName).GetAwaiter().GetResult();
}
/// <summary>
/// Returns a list of databases inside a recommented elastic pool.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group that contains the resource. You can obtain
/// this value from the Azure Resource Manager API or the portal.
/// </param>
/// <param name='serverName'>
/// The name of the server.
/// </param>
/// <param name='recommendedElasticPoolName'>
/// The name of the recommended elastic pool to be retrieved.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IEnumerable<Database>> ListDatabasesAsync(this IRecommendedElasticPoolsOperations operations, string resourceGroupName, string serverName, string recommendedElasticPoolName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListDatabasesWithHttpMessagesAsync(resourceGroupName, serverName, recommendedElasticPoolName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Returns a recommented elastic pool metrics.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group that contains the resource. You can obtain
/// this value from the Azure Resource Manager API or the portal.
/// </param>
/// <param name='serverName'>
/// The name of the server.
/// </param>
/// <param name='recommendedElasticPoolName'>
/// The name of the recommended elastic pool to be retrieved.
/// </param>
public static IEnumerable<RecommendedElasticPoolMetric> ListMetrics(this IRecommendedElasticPoolsOperations operations, string resourceGroupName, string serverName, string recommendedElasticPoolName)
{
return operations.ListMetricsAsync(resourceGroupName, serverName, recommendedElasticPoolName).GetAwaiter().GetResult();
}
/// <summary>
/// Returns a recommented elastic pool metrics.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group that contains the resource. You can obtain
/// this value from the Azure Resource Manager API or the portal.
/// </param>
/// <param name='serverName'>
/// The name of the server.
/// </param>
/// <param name='recommendedElasticPoolName'>
/// The name of the recommended elastic pool to be retrieved.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IEnumerable<RecommendedElasticPoolMetric>> ListMetricsAsync(this IRecommendedElasticPoolsOperations operations, string resourceGroupName, string serverName, string recommendedElasticPoolName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListMetricsWithHttpMessagesAsync(resourceGroupName, serverName, recommendedElasticPoolName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
}
}
| |
using System;
using System.Threading;
using System.Threading.Tasks;
using System.Diagnostics;
using STM.Implementation.Lockbased;
using System.Collections.Immutable;
using System.Collections.Generic;
using Evaluation.Common;
namespace LanguagedBasedHashMap
{
public class Program
{
public static void Main()
{
var map = new StmHashMap<int, int>();
TestMap(map);
map = new StmHashMap<int, int>();
TestMapConcurrent(map);
}
private static void TestMapConcurrent(IMap<int, int> map)
{
const int t1From = 0;
const int t1To = 1000;
const int t2From = -1000;
const int t2To = 0;
const int expectedSize = 2000;
var t1 = new Thread(() => MapAdd(map, t1From, t1To));
var t2 = new Thread(() => MapAdd(map, t2From, t2To));
t1.Start();
t2.Start();
t1.Join();
t2.Join();
Debug.Assert(expectedSize == map.Count);
t1 = new Thread(() => MapAddIfAbsent(map, t1From, t1To));
t2 = new Thread(() => MapAddIfAbsent(map, t2From, t2To));
t1.Start();
t2.Start();
t1.Join();
t2.Join();
Debug.Assert(expectedSize == map.Count);
t1 = new Thread(() => MapGet(map, t1From, t1To));
t2 = new Thread(() => MapGet(map, t2From, t2To));
t1.Start();
t2.Start();
t1.Join();
t2.Join();
t1 = new Thread(() => MapForeach(map));
t2 = new Thread(() => MapForeach(map));
t1.Start();
t2.Start();
t1.Join();
t2.Join();
t1 = new Thread(() => MapRemove(map, t1From, t1To));
t2 = new Thread(() => MapRemove(map, t2From, t2To));
t1.Start();
t2.Start();
t1.Join();
t2.Join();
Debug.Assert(0 == map.Count);
}
private static void TestMap(IMap<int, int> map)
{
const int from = -50;
const int to = 50;
Debug.Assert(map.Count == 0);
MapAdd(map, from, to);
Debug.Assert(map.Count == 100);
MapAddIfAbsent(map, from, to);
Debug.Assert(map.Count == 100);
MapGet(map, from, to);
MapRemove(map, from, to);
Debug.Assert(map.Count == 0);
}
public static void MapAdd(IMap<int, int> map, int from, int to)
{
for (var i = from; i < to; i++)
{
map[i] = i;
}
}
public static void MapAddIfAbsent(IMap<int, int> map, int from, int to)
{
for (var i = from; i < to; i++)
{
map.AddIfAbsent(i, i);
}
}
public static void MapRemove(IMap<int, int> map, int from, int to)
{
for (var i = from; i < to; i++)
{
map.Remove(i);
}
}
public static void MapGet(IMap<int, int> map, int from, int to)
{
for (var i = from; i < to; i++)
{
Debug.Assert(i == map.Get(i));
}
}
public static void MapForeach(IMap<int, int> map)
{
foreach (var kvPair in map)
{
Debug.Assert(kvPair.Key == kvPair.Value);
}
}
}
public class StmHashMap<K,V> : BaseHashMap<K,V>
{
private atomic Bucket[] _buckets;
private atomic int _threshold;
private atomic int _size;
public StmHashMap() : this(DefaultNrBuckets)
{
}
public StmHashMap(int nrBuckets)
{
_buckets = MakeBuckets(nrBuckets);
_threshold = CalculateThreshold(nrBuckets);
}
private Bucket[] MakeBuckets(int nrBuckets)
{
var temp = new Bucket[nrBuckets];
for (int i = 0; i < nrBuckets; i++)
{
temp[i] = new Bucket();
}
return temp;
}
#region Utility
private Node CreateNode(K key, V value)
{
return new Node(key, value);
}
private int GetBucketIndex(K key)
{
return GetBucketIndex(_buckets.Length, key);
}
private Node FindNode(K key)
{
return FindNode(key, GetBucketIndex(key));
}
private Node FindNode(K key, int bucketIndex)
{
return FindNode(key, _buckets[bucketIndex].Value);
}
private Node FindNode(K key, Node node)
{
while (node != null && !key.Equals(node.Key))
node = node.Next;
return node;
}
private void InsertInBucket(Bucket bucketVar, Node node)
{
var curNode = bucketVar.Value;
if (curNode != null)
{
node.Next = curNode;
}
bucketVar.Value = node;
}
#endregion Utility
public override bool ContainsKey(K key)
{
return FindNode(key) != null;
}
public override V Get(K key)
{
atomic
{
var node = FindNode(key);
if(node == null)
{
//If node == null key is not present in dictionary
throw new KeyNotFoundException("Key not found. Key: " + key);
}
return node.Value;
}
}
public override void Add(K key, V value)
{
atomic
{
var bucketIndex = GetBucketIndex(key);
//TMVar wrapping the immutable chain list
var bucketVar = _buckets[bucketIndex];
var node = FindNode(key, bucketVar.Value);
if (node != null)
{
//If node is not null key exist in map. Update the value
node.Value = value;
}
else
{
//Else insert the node
InsertInBucket(bucketVar, CreateNode(key, value));
_size++;
ResizeIfNeeded();
}
}
}
public override bool AddIfAbsent(K key, V value)
{
atomic
{
var bucketIndex = GetBucketIndex(key);
//TMVar wrapping the immutable chain list
var bucketVar = _buckets[bucketIndex];
var node = FindNode(key, bucketVar.Value);
if (node == null)
{
//If node is not found key does not exist so insert
InsertInBucket(bucketVar, CreateNode(key, value));
_size++;
ResizeIfNeeded();
return true;
}
return false;
}
}
private void ResizeIfNeeded()
{
if (_size >= _threshold)
{
Resize();
}
}
private void Resize()
{
//Construct new backing array
var newBucketSize = _buckets.Length * 2;
var newBuckets = MakeBuckets(newBucketSize);
//For each key in the map rehash
for (var i = 0; i < _buckets.Length; i++)
{
var bucket = _buckets[i];
var node = bucket.Value;
while (node != null)
{
var bucketIndex = GetBucketIndex(newBucketSize, node.Key);
InsertInBucket(newBuckets[bucketIndex], CreateNode(node.Key, node.Value));
node = node.Next;
}
}
//Calculate new resize threshold and assign the rehashed backing array
_threshold = CalculateThreshold(newBucketSize);
_buckets = newBuckets;
}
public override bool Remove(K key)
{
atomic
{
var bucketIndex = GetBucketIndex(key);
//TMVar wrapping the immutable chain list
var bucketVar = _buckets[bucketIndex];
var firstNode = bucketVar.Value;
return RemoveNode(key, firstNode, bucketVar);
}
}
private bool RemoveNode(K key, Node node, Bucket bucketVar)
{
if (node == null)
{
return false;
}
if (node.Key.Equals(key))
{
_size--;
bucketVar.Value = node.Next;
return true;
}
while (node.Next != null && !key.Equals(node.Next.Key))
node = node.Next;
//node.Next == null || node.Next.Key == key
if (node.Next == null) return false;
_size--;
node.Next = node.Next.Next;
return true;
}
public override IEnumerator<KeyValuePair<K, V>> GetEnumerator()
{
atomic
{
var list = new List<KeyValuePair<K, V>>(_size);
for (var i = 0; i < _buckets.Length; i++)
{
var bucket = _buckets[i];
var node = bucket.Value;
while (node != null)
{
var keyValuePair = new KeyValuePair<K, V>(node.Key, node.Value);
list.Add(keyValuePair);
node = node.Next;
}
}
return list.GetEnumerator();
}
}
public override V this[K key]
{
get { return Get(key); }
set { Add(key, value); }
}
public override int Count
{
get { return _size; }
}
private class Bucket
{
public atomic Node Value { get; set; }
}
private class Node
{
public K Key { get; private set; }
public atomic V Value { get; set; }
public atomic Node Next { get; set; }
public Node(K key, V value)
{
Key = key;
Value = value;
}
}
}
}
| |
// Copyright 2018 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 ArcGISRuntime.Samples.Managers;
using Esri.ArcGISRuntime.Mapping;
using Esri.ArcGISRuntime.Rasters;
using Esri.ArcGISRuntime.UI.Controls;
using Foundation;
using System;
using System.Collections.Generic;
using UIKit;
namespace ArcGISRuntime.Samples.ChangeStretchRenderer
{
[Register("ChangeStretchRenderer")]
[ArcGISRuntime.Samples.Shared.Attributes.OfflineData("95392f99970d4a71bd25951beb34a508")]
[ArcGISRuntime.Samples.Shared.Attributes.Sample(
name: "Stretch renderer",
category: "Layers",
description: "Use a stretch renderer to enhance the visual contrast of raster data for analysis.",
instructions: "Choose one of the stretch parameter types:",
tags: new[] { "analysis", "deviation", "histogram", "imagery", "interpretation", "min-max", "percent clip", "pixel", "raster", "stretch", "symbology", "visualization" })]
public class ChangeStretchRenderer : UIViewController
{
// Hold references to UI controls.
private MapView _myMapView;
private UISegmentedControl _rendererTypes;
private UILabel _labelParameter1;
private UITextField _inputParameter1;
private UILabel _labelParameter2;
private UITextField _inputParameter2;
private UIButton _updateRendererButton;
public ChangeStretchRenderer()
{
Title = "Stretch renderer";
}
private async void Initialize()
{
// Add an imagery basemap.
_myMapView.Map = new Map(BasemapStyle.ArcGISImageryStandard);
// Get the file name.
string filepath = DataManager.GetDataFolder("95392f99970d4a71bd25951beb34a508", "shasta", "ShastaBW.tif");
// Load the raster file.
Raster rasterFile = new Raster(filepath);
// Create the layer.
RasterLayer rasterLayer = new RasterLayer(rasterFile);
// Add the layer to the map.
_myMapView.Map.OperationalLayers.Add(rasterLayer);
try
{
// Wait for the layer to load.
await rasterLayer.LoadAsync();
// Set the viewpoint
await _myMapView.SetViewpointGeometryAsync(rasterLayer.FullExtent);
}
catch (Exception e)
{
new UIAlertView("Error", e.ToString(), (IUIAlertViewDelegate)null, "OK", null).Show();
}
}
private void rendererTypes_ValueChanged(object sender, EventArgs e)
{
// This function modifies the UI parameter controls depending on which stretch
// renderer is chosen by the user.
switch (_rendererTypes.SelectedSegment)
{
case 0: // Min Max.
// Make sure all the GUI items are visible.
_labelParameter1.Hidden = false;
_labelParameter2.Hidden = false;
_inputParameter1.Hidden = false;
_inputParameter2.Hidden = false;
// Define what values/options the user sees.
_labelParameter1.Text = "Minimum value (0 - 255):";
_labelParameter2.Text = "Maximum value (0 - 255):";
_inputParameter1.Text = "10";
_inputParameter2.Text = "150";
break;
case 1: // Percent Clip.
// Make sure all the GUI items are visible.
_labelParameter1.Hidden = false;
_labelParameter2.Hidden = false;
_inputParameter1.Hidden = false;
_inputParameter2.Hidden = false;
// Define what values/options the user sees.
_labelParameter1.Text = "Minimum (0 - 100):";
_labelParameter2.Text = "Maximum (0 - 100):";
_inputParameter1.Text = "0";
_inputParameter2.Text = "50";
break;
case 2: // Standard Deviation.
// Make sure that only the necessary GUI items are visible.
_labelParameter1.Hidden = false;
_labelParameter2.Hidden = true;
_inputParameter1.Hidden = false;
_inputParameter2.Hidden = true;
// Define what values/options the user sees.
_labelParameter1.Text = "Factor (.25 to 4):";
_inputParameter1.Text = "0.5";
break;
}
}
private void UpdateRendererButton_Clicked(object sender, EventArgs e)
{
// This function acquires the user selection of the stretch renderer from the table view
// along with the parameters specified, then a stretch renderer is created and applied to
// the raster layer.
// Convert the input text to doubles and return if they're invalid.
double input1;
double input2;
try
{
input1 = Convert.ToDouble(_inputParameter1.Text);
input2 = Convert.ToDouble(_inputParameter2.Text);
}
catch (Exception ex)
{
new UIAlertView("alert", ex.Message, (IUIAlertViewDelegate)null, "OK", null).Show();
return;
}
// Create an IEnumerable from an empty list of doubles for the gamma values in the stretch render.
IEnumerable<double> gammaValues = new List<double>();
// Create a color ramp for the stretch renderer.
ColorRamp colorRamp = ColorRamp.Create(PresetColorRampType.DemLight, 1000);
// Create the place holder for the stretch renderer.
StretchRenderer stretchRenderer = null;
switch (_rendererTypes.SelectedSegment)
{
case 0:
// This section creates a stretch renderer based on a MinMaxStretchParameters.
// TODO: Add you own logic to ensure that accurate min/max stretch values are used.
try
{
// Create an IEnumerable from a list of double min stretch value doubles.
IEnumerable<double> minValues = new List<double> { input1 };
// Create an IEnumerable from a list of double max stretch value doubles.
IEnumerable<double> maxValues = new List<double> { input2 };
// Create a new MinMaxStretchParameters based on the user choice for min and max stretch values.
MinMaxStretchParameters minMaxStretchParameters = new MinMaxStretchParameters(minValues, maxValues);
// Create the stretch renderer based on the user defined min/max stretch values, empty gamma values, statistic estimates, and a predefined color ramp.
stretchRenderer = new StretchRenderer(minMaxStretchParameters, gammaValues, true, colorRamp);
}
catch (ArgumentException)
{
ShowMessage("Error configuring renderer.", "Ensure all values are valid and try again.");
return;
}
break;
case 1:
// This section creates a stretch renderer based on a PercentClipStretchParameters.
// TODO: Add you own logic to ensure that accurate min/max percent clip values are used.
try
{
// Create a new PercentClipStretchParameters based on the user choice for min and max percent clip values.
PercentClipStretchParameters percentClipStretchParameters = new PercentClipStretchParameters(input1, input2);
// Create the percent clip renderer based on the user defined min/max percent clip values, empty gamma values, statistic estimates, and a predefined color ramp.
stretchRenderer = new StretchRenderer(percentClipStretchParameters, gammaValues, true, colorRamp);
}
catch (Exception)
{
ShowMessage("Error configuring renderer.", "Ensure all values are valid and try again.");
return;
}
break;
case 2:
// This section creates a stretch renderer based on a StandardDeviationStretchParameters.
// TODO: Add you own logic to ensure that an accurate standard deviation value is used
try
{
// Create a new StandardDeviationStretchParameters based on the user choice for standard deviation value.
StandardDeviationStretchParameters standardDeviationStretchParameters = new StandardDeviationStretchParameters(input1);
// Create the standard deviation renderer based on the user defined standard deviation value, empty gamma values, statistic estimates, and a predefined color ramp.
stretchRenderer = new StretchRenderer(standardDeviationStretchParameters, gammaValues, true, colorRamp);
}
catch (Exception)
{
ShowMessage("Error configuring renderer.", "Ensure all values are valid and try again.");
return;
}
break;
}
// Get the existing raster layer in the map.
RasterLayer rasterLayer = (RasterLayer)_myMapView.Map.OperationalLayers[0];
// Apply the stretch renderer to the raster layer.
rasterLayer.Renderer = stretchRenderer;
}
private void ShowMessage(string title, string message)
{
new UIAlertView(title, message, (IUIAlertViewDelegate)null, "OK", null).Show();
}
public override void ViewDidLoad()
{
base.ViewDidLoad();
Initialize();
}
public override void LoadView()
{
// Create the views.
View = new UIView { BackgroundColor = ApplicationTheme.BackgroundColor };
UIView formContainer = new UIView();
formContainer.TranslatesAutoresizingMaskIntoConstraints = false;
formContainer.BackgroundColor = ApplicationTheme.BackgroundColor;
_myMapView = new MapView();
_myMapView.TranslatesAutoresizingMaskIntoConstraints = false;
_inputParameter1 = new UITextField();
_inputParameter1.TranslatesAutoresizingMaskIntoConstraints = false;
_inputParameter1.BorderStyle = UITextBorderStyle.RoundedRect;
_inputParameter2 = new UITextField();
_inputParameter2.TranslatesAutoresizingMaskIntoConstraints = false;
_inputParameter2.BorderStyle = UITextBorderStyle.RoundedRect;
_labelParameter1 = new UILabel();
_labelParameter1.TextAlignment = UITextAlignment.Right;
_labelParameter1.TranslatesAutoresizingMaskIntoConstraints = false;
_labelParameter2 = new UILabel();
_labelParameter2.TextAlignment = UITextAlignment.Right;
_labelParameter2.TranslatesAutoresizingMaskIntoConstraints = false;
_updateRendererButton = new UIButton();
_updateRendererButton.SetTitle("Update renderer", UIControlState.Normal);
_updateRendererButton.SetTitleColor(View.TintColor, UIControlState.Normal);
_updateRendererButton.TranslatesAutoresizingMaskIntoConstraints = false;
_rendererTypes = new UISegmentedControl("Min/Max", "% Clip", "Std. Deviation");
_rendererTypes.SelectedSegment = 0;
_rendererTypes.TintColor = View.TintColor;
_rendererTypes.TranslatesAutoresizingMaskIntoConstraints = false;
// Call a function to configure the labels appropriately
rendererTypes_ValueChanged(_rendererTypes, null);
// Add the views.
View.AddSubviews(_myMapView, formContainer, _rendererTypes, _inputParameter1,
_inputParameter2, _labelParameter1, _labelParameter2, _updateRendererButton);
// Lay out the views.
NSLayoutConstraint.ActivateConstraints(new[]
{
_rendererTypes.TopAnchor.ConstraintEqualTo(View.SafeAreaLayoutGuide.TopAnchor, 8),
_rendererTypes.LeadingAnchor.ConstraintEqualTo(View.SafeAreaLayoutGuide.LeadingAnchor, 8),
_rendererTypes.TrailingAnchor.ConstraintEqualTo(View.SafeAreaLayoutGuide.TrailingAnchor, -8),
_inputParameter1.TopAnchor.ConstraintEqualTo(_rendererTypes.BottomAnchor, 8),
_inputParameter1.TrailingAnchor.ConstraintEqualTo(View.SafeAreaLayoutGuide.TrailingAnchor, -8),
_inputParameter1.WidthAnchor.ConstraintEqualTo(72),
_inputParameter2.TopAnchor.ConstraintEqualTo(_inputParameter1.BottomAnchor, 8),
_inputParameter2.TrailingAnchor.ConstraintEqualTo(_inputParameter1.TrailingAnchor),
_inputParameter2.WidthAnchor.ConstraintEqualTo(_inputParameter1.WidthAnchor),
_updateRendererButton.TopAnchor.ConstraintEqualTo(_inputParameter2.BottomAnchor, 8),
_updateRendererButton.LeadingAnchor.ConstraintEqualTo(View.SafeAreaLayoutGuide.LeadingAnchor),
_updateRendererButton.TrailingAnchor.ConstraintEqualTo(View.SafeAreaLayoutGuide.TrailingAnchor),
_labelParameter1.TopAnchor.ConstraintEqualTo(_inputParameter1.TopAnchor),
_labelParameter1.LeadingAnchor.ConstraintEqualTo(_rendererTypes.LeadingAnchor),
_labelParameter1.TrailingAnchor.ConstraintEqualTo(_inputParameter1.LeadingAnchor, -8),
_labelParameter1.BottomAnchor.ConstraintEqualTo(_inputParameter1.BottomAnchor),
_labelParameter2.TopAnchor.ConstraintEqualTo(_inputParameter2.TopAnchor),
_labelParameter2.BottomAnchor.ConstraintEqualTo(_inputParameter2.BottomAnchor),
_labelParameter2.LeadingAnchor.ConstraintEqualTo(_labelParameter1.LeadingAnchor),
_labelParameter2.TrailingAnchor.ConstraintEqualTo(_labelParameter1.TrailingAnchor),
formContainer.TopAnchor.ConstraintEqualTo(View.SafeAreaLayoutGuide.TopAnchor),
formContainer.LeadingAnchor.ConstraintEqualTo(View.LeadingAnchor),
formContainer.BottomAnchor.ConstraintEqualTo(_updateRendererButton.BottomAnchor, 8),
formContainer.TrailingAnchor.ConstraintEqualTo(View.TrailingAnchor),
_myMapView.TopAnchor.ConstraintEqualTo(formContainer.BottomAnchor),
_myMapView.LeadingAnchor.ConstraintEqualTo(View.LeadingAnchor),
_myMapView.TrailingAnchor.ConstraintEqualTo(View.TrailingAnchor),
_myMapView.BottomAnchor.ConstraintEqualTo(View.BottomAnchor)
});
}
private bool HandleTextField(UITextField textField)
{
// This method allows pressing 'return' to dismiss the software keyboard.
textField.ResignFirstResponder();
return true;
}
public override void ViewWillAppear(bool animated)
{
base.ViewWillAppear(animated);
// Subscribe to events.
_inputParameter1.ShouldReturn += HandleTextField;
_inputParameter2.ShouldReturn += HandleTextField;
_updateRendererButton.TouchUpInside += UpdateRendererButton_Clicked;
_rendererTypes.ValueChanged += rendererTypes_ValueChanged;
}
public override void ViewDidDisappear(bool animated)
{
base.ViewDidDisappear(animated);
// Unsubscribe from events, per best practice.
_inputParameter1.ShouldReturn -= HandleTextField;
_inputParameter2.ShouldReturn -= HandleTextField;
_updateRendererButton.TouchUpInside -= UpdateRendererButton_Clicked;
_rendererTypes.ValueChanged -= rendererTypes_ValueChanged;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using Lucene.Net.Documents;
namespace Lucene.Net.Index
{
using Lucene.Net.Randomized.Generators;
using NUnit.Framework;
using Bits = Lucene.Net.Util.Bits;
using BytesRef = Lucene.Net.Util.BytesRef;
using Directory = Lucene.Net.Store.Directory;
using DocIdSetIterator = Lucene.Net.Search.DocIdSetIterator;
using Document = Documents.Document;
using Field = Field;
using FieldType = FieldType;
using LuceneTestCase = Lucene.Net.Util.LuceneTestCase;
/*
* 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 MockAnalyzer = Lucene.Net.Analysis.MockAnalyzer;
using TestUtil = Lucene.Net.Util.TestUtil;
using TextField = TextField;
[TestFixture]
public class TestDocsAndPositions : LuceneTestCase
{
private string FieldName;
[SetUp]
public override void SetUp()
{
base.SetUp();
FieldName = "field" + Random().Next();
}
/// <summary>
/// Simple testcase for <seealso cref="DocsAndPositionsEnum"/>
/// </summary>
[Test]
public virtual void TestPositionsSimple()
{
Directory directory = NewDirectory();
RandomIndexWriter writer = new RandomIndexWriter(Random(), directory, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random())));
for (int i = 0; i < 39; i++)
{
Document doc = new Document();
FieldType customType = new FieldType(TextField.TYPE_NOT_STORED);
customType.OmitNorms = true;
doc.Add(NewField(FieldName, "1 2 3 4 5 6 7 8 9 10 " + "1 2 3 4 5 6 7 8 9 10 " + "1 2 3 4 5 6 7 8 9 10 " + "1 2 3 4 5 6 7 8 9 10", customType));
writer.AddDocument(doc);
}
IndexReader reader = writer.Reader;
writer.Dispose();
int num = AtLeast(13);
for (int i = 0; i < num; i++)
{
BytesRef bytes = new BytesRef("1");
IndexReaderContext topReaderContext = reader.Context;
foreach (AtomicReaderContext atomicReaderContext in topReaderContext.Leaves)
{
DocsAndPositionsEnum docsAndPosEnum = GetDocsAndPositions((AtomicReader)atomicReaderContext.Reader, bytes, null);
Assert.IsNotNull(docsAndPosEnum);
if (atomicReaderContext.Reader.MaxDoc == 0)
{
continue;
}
int advance = docsAndPosEnum.Advance(Random().Next(atomicReaderContext.Reader.MaxDoc));
do
{
string msg = "Advanced to: " + advance + " current doc: " + docsAndPosEnum.DocID(); // TODO: + " usePayloads: " + usePayload;
Assert.AreEqual(4, docsAndPosEnum.Freq(), msg);
Assert.AreEqual(0, docsAndPosEnum.NextPosition(), msg);
Assert.AreEqual(4, docsAndPosEnum.Freq(), msg);
Assert.AreEqual(10, docsAndPosEnum.NextPosition(), msg);
Assert.AreEqual(4, docsAndPosEnum.Freq(), msg);
Assert.AreEqual(20, docsAndPosEnum.NextPosition(), msg);
Assert.AreEqual(4, docsAndPosEnum.Freq(), msg);
Assert.AreEqual(30, docsAndPosEnum.NextPosition(), msg);
} while (docsAndPosEnum.NextDoc() != DocIdSetIterator.NO_MORE_DOCS);
}
}
reader.Dispose();
directory.Dispose();
}
public virtual DocsAndPositionsEnum GetDocsAndPositions(AtomicReader reader, BytesRef bytes, Bits liveDocs)
{
Terms terms = reader.Terms(FieldName);
if (terms != null)
{
TermsEnum te = terms.Iterator(null);
if (te.SeekExact(bytes))
{
return te.DocsAndPositions(liveDocs, null);
}
}
return null;
}
/// <summary>
/// this test indexes random numbers within a range into a field and checks
/// their occurrences by searching for a number from that range selected at
/// random. All positions for that number are saved up front and compared to
/// the enums positions.
/// </summary>
[Test]
public virtual void TestRandomPositions()
{
Directory dir = NewDirectory();
RandomIndexWriter writer = new RandomIndexWriter(Random(), dir, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random())).SetMergePolicy(NewLogMergePolicy()));
int numDocs = AtLeast(47);
int max = 1051;
int term = Random().Next(max);
int?[][] positionsInDoc = new int?[numDocs][];
FieldType customType = new FieldType(TextField.TYPE_NOT_STORED);
customType.OmitNorms = true;
for (int i = 0; i < numDocs; i++)
{
Document doc = new Document();
List<int?> positions = new List<int?>();
StringBuilder builder = new StringBuilder();
int num = AtLeast(131);
for (int j = 0; j < num; j++)
{
int nextInt = Random().Next(max);
builder.Append(nextInt).Append(" ");
if (nextInt == term)
{
positions.Add(Convert.ToInt32(j));
}
}
if (positions.Count == 0)
{
builder.Append(term);
positions.Add(num);
}
doc.Add(NewField(FieldName, builder.ToString(), customType));
positionsInDoc[i] = positions.ToArray();
writer.AddDocument(doc);
}
IndexReader reader = writer.Reader;
writer.Dispose();
int num_ = AtLeast(13);
for (int i = 0; i < num_; i++)
{
BytesRef bytes = new BytesRef("" + term);
IndexReaderContext topReaderContext = reader.Context;
foreach (AtomicReaderContext atomicReaderContext in topReaderContext.Leaves)
{
DocsAndPositionsEnum docsAndPosEnum = GetDocsAndPositions((AtomicReader)atomicReaderContext.Reader, bytes, null);
Assert.IsNotNull(docsAndPosEnum);
int initDoc = 0;
int maxDoc = atomicReaderContext.Reader.MaxDoc;
// initially advance or do next doc
if (Random().NextBoolean())
{
initDoc = docsAndPosEnum.NextDoc();
}
else
{
initDoc = docsAndPosEnum.Advance(Random().Next(maxDoc));
}
// now run through the scorer and check if all positions are there...
do
{
int docID = docsAndPosEnum.DocID();
if (docID == DocIdSetIterator.NO_MORE_DOCS)
{
break;
}
int?[] pos = positionsInDoc[atomicReaderContext.DocBase + docID];
Assert.AreEqual(pos.Length, docsAndPosEnum.Freq());
// number of positions read should be random - don't read all of them
// allways
int howMany = Random().Next(20) == 0 ? pos.Length - Random().Next(pos.Length) : pos.Length;
for (int j = 0; j < howMany; j++)
{
Assert.AreEqual(pos[j], docsAndPosEnum.NextPosition(), "iteration: " + i + " initDoc: " + initDoc + " doc: " + docID + " base: " + atomicReaderContext.DocBase + " positions: " + pos); /* TODO: + " usePayloads: "
+ usePayload*/
}
if (Random().Next(10) == 0) // once is a while advance
{
if (docsAndPosEnum.Advance(docID + 1 + Random().Next((maxDoc - docID))) == DocIdSetIterator.NO_MORE_DOCS)
{
break;
}
}
} while (docsAndPosEnum.NextDoc() != DocIdSetIterator.NO_MORE_DOCS);
}
}
reader.Dispose();
dir.Dispose();
}
[Test]
public virtual void TestRandomDocs()
{
Directory dir = NewDirectory();
RandomIndexWriter writer = new RandomIndexWriter(Random(), dir, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random())).SetMergePolicy(NewLogMergePolicy()));
int numDocs = AtLeast(49);
int max = 15678;
int term = Random().Next(max);
int[] freqInDoc = new int[numDocs];
FieldType customType = new FieldType(TextField.TYPE_NOT_STORED);
customType.OmitNorms = true;
for (int i = 0; i < numDocs; i++)
{
Document doc = new Document();
StringBuilder builder = new StringBuilder();
for (int j = 0; j < 199; j++)
{
int nextInt = Random().Next(max);
builder.Append(nextInt).Append(' ');
if (nextInt == term)
{
freqInDoc[i]++;
}
}
doc.Add(NewField(FieldName, builder.ToString(), customType));
writer.AddDocument(doc);
}
IndexReader reader = writer.Reader;
writer.Dispose();
int num = AtLeast(13);
for (int i = 0; i < num; i++)
{
BytesRef bytes = new BytesRef("" + term);
IndexReaderContext topReaderContext = reader.Context;
foreach (AtomicReaderContext context in topReaderContext.Leaves)
{
int maxDoc = context.AtomicReader.MaxDoc;
DocsEnum docsEnum = TestUtil.Docs(Random(), context.Reader, FieldName, bytes, null, null, DocsEnum.FLAG_FREQS);
if (FindNext(freqInDoc, context.DocBase, context.DocBase + maxDoc) == int.MaxValue)
{
Assert.IsNull(docsEnum);
continue;
}
Assert.IsNotNull(docsEnum);
docsEnum.NextDoc();
for (int j = 0; j < maxDoc; j++)
{
if (freqInDoc[context.DocBase + j] != 0)
{
Assert.AreEqual(j, docsEnum.DocID());
Assert.AreEqual(docsEnum.Freq(), freqInDoc[context.DocBase + j]);
if (i % 2 == 0 && Random().Next(10) == 0)
{
int next = FindNext(freqInDoc, context.DocBase + j + 1, context.DocBase + maxDoc) - context.DocBase;
int advancedTo = docsEnum.Advance(next);
if (next >= maxDoc)
{
Assert.AreEqual(DocIdSetIterator.NO_MORE_DOCS, advancedTo);
}
else
{
Assert.IsTrue(next >= advancedTo, "advanced to: " + advancedTo + " but should be <= " + next);
}
}
else
{
docsEnum.NextDoc();
}
}
}
Assert.AreEqual(DocIdSetIterator.NO_MORE_DOCS, docsEnum.DocID(), "DocBase: " + context.DocBase + " maxDoc: " + maxDoc + " " + docsEnum.GetType());
}
}
reader.Dispose();
dir.Dispose();
}
private static int FindNext(int[] docs, int pos, int max)
{
for (int i = pos; i < max; i++)
{
if (docs[i] != 0)
{
return i;
}
}
return int.MaxValue;
}
/// <summary>
/// tests retrieval of positions for terms that have a large number of
/// occurrences to force test of buffer refill during positions iteration.
/// </summary>
[Test]
public virtual void TestLargeNumberOfPositions()
{
Directory dir = NewDirectory();
RandomIndexWriter writer = new RandomIndexWriter(Random(), dir, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random())));
int howMany = 1000;
FieldType customType = new FieldType(TextField.TYPE_NOT_STORED);
customType.OmitNorms = true;
for (int i = 0; i < 39; i++)
{
Document doc = new Document();
StringBuilder builder = new StringBuilder();
for (int j = 0; j < howMany; j++)
{
if (j % 2 == 0)
{
builder.Append("even ");
}
else
{
builder.Append("odd ");
}
}
doc.Add(NewField(FieldName, builder.ToString(), customType));
writer.AddDocument(doc);
}
// now do searches
IndexReader reader = writer.Reader;
writer.Dispose();
int num = AtLeast(13);
for (int i = 0; i < num; i++)
{
BytesRef bytes = new BytesRef("even");
IndexReaderContext topReaderContext = reader.Context;
foreach (AtomicReaderContext atomicReaderContext in topReaderContext.Leaves)
{
DocsAndPositionsEnum docsAndPosEnum = GetDocsAndPositions((AtomicReader)atomicReaderContext.Reader, bytes, null);
Assert.IsNotNull(docsAndPosEnum);
int initDoc = 0;
int maxDoc = atomicReaderContext.Reader.MaxDoc;
// initially advance or do next doc
if (Random().NextBoolean())
{
initDoc = docsAndPosEnum.NextDoc();
}
else
{
initDoc = docsAndPosEnum.Advance(Random().Next(maxDoc));
}
string msg = "Iteration: " + i + " initDoc: " + initDoc; // TODO: + " payloads: " + usePayload;
Assert.AreEqual(howMany / 2, docsAndPosEnum.Freq());
for (int j = 0; j < howMany; j += 2)
{
Assert.AreEqual(j, docsAndPosEnum.NextPosition(), "position missmatch index: " + j + " with freq: " + docsAndPosEnum.Freq() + " -- " + msg);
}
}
}
reader.Dispose();
dir.Dispose();
}
[Test]
public virtual void TestDocsEnumStart()
{
Directory dir = NewDirectory();
RandomIndexWriter writer = new RandomIndexWriter(Random(), dir);
Document doc = new Document();
doc.Add(NewStringField("foo", "bar", Field.Store.NO));
writer.AddDocument(doc);
DirectoryReader reader = writer.Reader;
AtomicReader r = GetOnlySegmentReader(reader);
DocsEnum disi = TestUtil.Docs(Random(), r, "foo", new BytesRef("bar"), null, null, DocsEnum.FLAG_NONE);
int docid = disi.DocID();
Assert.AreEqual(-1, docid);
Assert.IsTrue(disi.NextDoc() != DocIdSetIterator.NO_MORE_DOCS);
// now reuse and check again
TermsEnum te = r.Terms("foo").Iterator(null);
Assert.IsTrue(te.SeekExact(new BytesRef("bar")));
disi = TestUtil.Docs(Random(), te, null, disi, DocsEnum.FLAG_NONE);
docid = disi.DocID();
Assert.AreEqual(-1, docid);
Assert.IsTrue(disi.NextDoc() != DocIdSetIterator.NO_MORE_DOCS);
writer.Dispose();
r.Dispose();
dir.Dispose();
}
[Test]
public virtual void TestDocsAndPositionsEnumStart()
{
Directory dir = NewDirectory();
RandomIndexWriter writer = new RandomIndexWriter(Random(), dir);
Document doc = new Document();
doc.Add(NewTextField("foo", "bar", Field.Store.NO));
writer.AddDocument(doc);
DirectoryReader reader = writer.Reader;
AtomicReader r = GetOnlySegmentReader(reader);
DocsAndPositionsEnum disi = r.TermPositionsEnum(new Term("foo", "bar"));
int docid = disi.DocID();
Assert.AreEqual(-1, docid);
Assert.IsTrue(disi.NextDoc() != DocIdSetIterator.NO_MORE_DOCS);
// now reuse and check again
TermsEnum te = r.Terms("foo").Iterator(null);
Assert.IsTrue(te.SeekExact(new BytesRef("bar")));
disi = te.DocsAndPositions(null, disi);
docid = disi.DocID();
Assert.AreEqual(-1, docid);
Assert.IsTrue(disi.NextDoc() != DocIdSetIterator.NO_MORE_DOCS);
writer.Dispose();
r.Dispose();
dir.Dispose();
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Reflection;
namespace AcadBlog.WebApi.Areas.HelpPage
{
/// <summary>
/// This class will create an object of a given type and populate it with sample data.
/// </summary>
public class ObjectGenerator
{
private const int DefaultCollectionSize = 3;
private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator();
/// <summary>
/// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types:
/// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc.
/// Complex types: POCO types.
/// Nullables: <see cref="Nullable{T}"/>.
/// Arrays: arrays of simple types or complex types.
/// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/>
/// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc
/// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>.
/// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>.
/// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>An object of the given type.</returns>
public object GenerateObject(Type type)
{
return GenerateObject(type, new Dictionary<Type, object>());
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")]
private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
try
{
if (SimpleTypeObjectGenerator.CanGenerateObject(type))
{
return SimpleObjectGenerator.GenerateObject(type);
}
if (type.IsArray)
{
return GenerateArray(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsGenericType)
{
return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IDictionary))
{
return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IDictionary).IsAssignableFrom(type))
{
return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IList) ||
type == typeof(IEnumerable) ||
type == typeof(ICollection))
{
return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IList).IsAssignableFrom(type))
{
return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IQueryable))
{
return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsEnum)
{
return GenerateEnum(type);
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
}
catch
{
// Returns null if anything fails
return null;
}
return null;
}
private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences)
{
Type genericTypeDefinition = type.GetGenericTypeDefinition();
if (genericTypeDefinition == typeof(Nullable<>))
{
return GenerateNullable(type, createdObjectReferences);
}
if (genericTypeDefinition == typeof(KeyValuePair<,>))
{
return GenerateKeyValuePair(type, createdObjectReferences);
}
if (IsTuple(genericTypeDefinition))
{
return GenerateTuple(type, createdObjectReferences);
}
Type[] genericArguments = type.GetGenericArguments();
if (genericArguments.Length == 1)
{
if (genericTypeDefinition == typeof(IList<>) ||
genericTypeDefinition == typeof(IEnumerable<>) ||
genericTypeDefinition == typeof(ICollection<>))
{
Type collectionType = typeof(List<>).MakeGenericType(genericArguments);
return GenerateCollection(collectionType, collectionSize, createdObjectReferences);
}
if (genericTypeDefinition == typeof(IQueryable<>))
{
return GenerateQueryable(type, collectionSize, createdObjectReferences);
}
Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]);
if (closedCollectionType.IsAssignableFrom(type))
{
return GenerateCollection(type, collectionSize, createdObjectReferences);
}
}
if (genericArguments.Length == 2)
{
if (genericTypeDefinition == typeof(IDictionary<,>))
{
Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments);
return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences);
}
Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]);
if (closedDictionaryType.IsAssignableFrom(type))
{
return GenerateDictionary(type, collectionSize, createdObjectReferences);
}
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
return null;
}
private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = type.GetGenericArguments();
object[] parameterValues = new object[genericArgs.Length];
bool failedToCreateTuple = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < genericArgs.Length; i++)
{
parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences);
failedToCreateTuple &= parameterValues[i] == null;
}
if (failedToCreateTuple)
{
return null;
}
object result = Activator.CreateInstance(type, parameterValues);
return result;
}
private static bool IsTuple(Type genericTypeDefinition)
{
return genericTypeDefinition == typeof(Tuple<>) ||
genericTypeDefinition == typeof(Tuple<,>) ||
genericTypeDefinition == typeof(Tuple<,,>) ||
genericTypeDefinition == typeof(Tuple<,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,,>);
}
private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = keyValuePairType.GetGenericArguments();
Type typeK = genericArgs[0];
Type typeV = genericArgs[1];
ObjectGenerator objectGenerator = new ObjectGenerator();
object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences);
object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences);
if (keyObject == null && valueObject == null)
{
// Failed to create key and values
return null;
}
object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject);
return result;
}
private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = arrayType.GetElementType();
Array result = Array.CreateInstance(type, size);
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
result.SetValue(element, i);
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type typeK = typeof(object);
Type typeV = typeof(object);
if (dictionaryType.IsGenericType)
{
Type[] genericArgs = dictionaryType.GetGenericArguments();
typeK = genericArgs[0];
typeV = genericArgs[1];
}
object result = Activator.CreateInstance(dictionaryType);
MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd");
MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey");
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences);
if (newKey == null)
{
// Cannot generate a valid key
return null;
}
bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey });
if (!containsKey)
{
object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences);
addMethod.Invoke(result, new object[] { newKey, newValue });
}
}
return result;
}
private static object GenerateEnum(Type enumType)
{
Array possibleValues = Enum.GetValues(enumType);
if (possibleValues.Length > 0)
{
return possibleValues.GetValue(0);
}
return null;
}
private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences)
{
bool isGeneric = queryableType.IsGenericType;
object list;
if (isGeneric)
{
Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments());
list = GenerateCollection(listType, size, createdObjectReferences);
}
else
{
list = GenerateArray(typeof(object[]), size, createdObjectReferences);
}
if (list == null)
{
return null;
}
if (isGeneric)
{
Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments());
MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType });
return asQueryableMethod.Invoke(null, new[] { list });
}
return Queryable.AsQueryable((IEnumerable)list);
}
private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = collectionType.IsGenericType ?
collectionType.GetGenericArguments()[0] :
typeof(object);
object result = Activator.CreateInstance(collectionType);
MethodInfo addMethod = collectionType.GetMethod("Add");
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
addMethod.Invoke(result, new object[] { element });
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences)
{
Type type = nullableType.GetGenericArguments()[0];
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type, createdObjectReferences);
}
private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
object result = null;
if (createdObjectReferences.TryGetValue(type, out result))
{
// The object has been created already, just return it. This will handle the circular reference case.
return result;
}
if (type.IsValueType)
{
result = Activator.CreateInstance(type);
}
else
{
ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes);
if (defaultCtor == null)
{
// Cannot instantiate the type because it doesn't have a default constructor
return null;
}
result = defaultCtor.Invoke(new object[0]);
}
createdObjectReferences.Add(type, result);
SetPublicProperties(type, result, createdObjectReferences);
SetPublicFields(type, result, createdObjectReferences);
return result;
}
private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (PropertyInfo property in properties)
{
if (property.CanWrite)
{
object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences);
property.SetValue(obj, propertyValue, null);
}
}
}
private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (FieldInfo field in fields)
{
object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences);
field.SetValue(obj, fieldValue);
}
}
private class SimpleTypeObjectGenerator
{
private long _index = 0;
private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators();
[SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")]
private static Dictionary<Type, Func<long, object>> InitializeGenerators()
{
return new Dictionary<Type, Func<long, object>>
{
{ typeof(Boolean), index => true },
{ typeof(Byte), index => (Byte)64 },
{ typeof(Char), index => (Char)65 },
{ typeof(DateTime), index => DateTime.Now },
{ typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) },
{ typeof(DBNull), index => DBNull.Value },
{ typeof(Decimal), index => (Decimal)index },
{ typeof(Double), index => (Double)(index + 0.1) },
{ typeof(Guid), index => Guid.NewGuid() },
{ typeof(Int16), index => (Int16)(index % Int16.MaxValue) },
{ typeof(Int32), index => (Int32)(index % Int32.MaxValue) },
{ typeof(Int64), index => (Int64)index },
{ typeof(Object), index => new object() },
{ typeof(SByte), index => (SByte)64 },
{ typeof(Single), index => (Single)(index + 0.1) },
{
typeof(String), index =>
{
return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index);
}
},
{
typeof(TimeSpan), index =>
{
return TimeSpan.FromTicks(1234567);
}
},
{ typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) },
{ typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) },
{ typeof(UInt64), index => (UInt64)index },
{
typeof(Uri), index =>
{
return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index));
}
},
};
}
public static bool CanGenerateObject(Type type)
{
return DefaultGenerators.ContainsKey(type);
}
public object GenerateObject(Type type)
{
return DefaultGenerators[type](++_index);
}
}
}
}
| |
// <copyright file="RemoteWebDriver.cs" company="WebDriver Committers">
// Licensed to the Software Freedom Conservancy (SFC) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The SFC 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.
// </copyright>
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using OpenQA.Selenium.DevTools;
using OpenQA.Selenium.Html5;
using OpenQA.Selenium.Internal;
namespace OpenQA.Selenium.Remote
{
/// <summary>
/// Provides a way to use the driver through
/// </summary>
/// /// <example>
/// <code>
/// [TestFixture]
/// public class Testing
/// {
/// private IWebDriver driver;
/// <para></para>
/// [SetUp]
/// public void SetUp()
/// {
/// driver = new RemoteWebDriver(new Uri("http://127.0.0.1:4444/wd/hub"),DesiredCapabilities.InternetExplorer());
/// }
/// <para></para>
/// [Test]
/// public void TestGoogle()
/// {
/// driver.Navigate().GoToUrl("http://www.google.co.uk");
/// /*
/// * Rest of the test
/// */
/// }
/// <para></para>
/// [TearDown]
/// public void TearDown()
/// {
/// driver.Quit();
/// }
/// }
/// </code>
/// </example>
public class RemoteWebDriver : WebDriver, IDevTools, IFindsById, IFindsByClassName, IFindsByLinkText, IFindsByName, IFindsByTagName, IFindsByXPath, IFindsByPartialLinkText, IFindsByCssSelector
{
public readonly string RemoteDevToolsEndPointCapabilityName = "se:cdp";
public readonly string RemoteDevToolsVersionCapabilityName = "se:cdpVersion";
private const string DefaultRemoteServerUrl = "http://127.0.0.1:4444/wd/hub";
private DevToolsSession devToolsSession;
/// <summary>
/// Initializes a new instance of the <see cref="RemoteWebDriver"/> class. This constructor defaults proxy to http://127.0.0.1:4444/wd/hub
/// </summary>
/// <param name="options">An <see cref="DriverOptions"/> object containing the desired capabilities of the browser.</param>
public RemoteWebDriver(DriverOptions options)
: this(ConvertOptionsToCapabilities(options))
{
}
/// <summary>
/// Initializes a new instance of the <see cref="RemoteWebDriver"/> class. This constructor defaults proxy to http://127.0.0.1:4444/wd/hub
/// </summary>
/// <param name="desiredCapabilities">An <see cref="ICapabilities"/> object containing the desired capabilities of the browser.</param>
public RemoteWebDriver(ICapabilities desiredCapabilities)
: this(new Uri(DefaultRemoteServerUrl), desiredCapabilities)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="RemoteWebDriver"/> class. This constructor defaults proxy to http://127.0.0.1:4444/wd/hub
/// </summary>
/// <param name="remoteAddress">URI containing the address of the WebDriver remote server (e.g. http://127.0.0.1:4444/wd/hub).</param>
/// <param name="options">An <see cref="DriverOptions"/> object containing the desired capabilities of the browser.</param>
public RemoteWebDriver(Uri remoteAddress, DriverOptions options)
: this(remoteAddress, ConvertOptionsToCapabilities(options))
{
}
/// <summary>
/// Initializes a new instance of the <see cref="RemoteWebDriver"/> class
/// </summary>
/// <param name="remoteAddress">URI containing the address of the WebDriver remote server (e.g. http://127.0.0.1:4444/wd/hub).</param>
/// <param name="desiredCapabilities">An <see cref="ICapabilities"/> object containing the desired capabilities of the browser.</param>
public RemoteWebDriver(Uri remoteAddress, ICapabilities desiredCapabilities)
: this(remoteAddress, desiredCapabilities, RemoteWebDriver.DefaultCommandTimeout)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="RemoteWebDriver"/> class using the specified remote address, desired capabilities, and command timeout.
/// </summary>
/// <param name="remoteAddress">URI containing the address of the WebDriver remote server (e.g. http://127.0.0.1:4444/wd/hub).</param>
/// <param name="desiredCapabilities">An <see cref="ICapabilities"/> object containing the desired capabilities of the browser.</param>
/// <param name="commandTimeout">The maximum amount of time to wait for each command.</param>
public RemoteWebDriver(Uri remoteAddress, ICapabilities desiredCapabilities, TimeSpan commandTimeout)
: this(new HttpCommandExecutor(remoteAddress, commandTimeout), desiredCapabilities)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="RemoteWebDriver"/> class
/// </summary>
/// <param name="commandExecutor">An <see cref="ICommandExecutor"/> object which executes commands for the driver.</param>
/// <param name="desiredCapabilities">An <see cref="ICapabilities"/> object containing the desired capabilities of the browser.</param>
public RemoteWebDriver(ICommandExecutor commandExecutor, ICapabilities desiredCapabilities)
:base(commandExecutor, desiredCapabilities)
{
}
/// <summary>
/// Gets a value indicating whether a DevTools session is active.
/// </summary>
public bool HasActiveDevToolsSession
{
get { return this.devToolsSession != null; }
}
/// <summary>
/// Finds the first element in the page that matches the ID supplied
/// </summary>
/// <param name="id">ID of the element</param>
/// <returns>IWebElement object so that you can interact with that object</returns>
/// <example>
/// <code>
/// IWebDriver driver = new RemoteWebDriver(DesiredCapabilities.Firefox());
/// IWebElement elem = driver.FindElementById("id")
/// </code>
/// </example>
public IWebElement FindElementById(string id)
{
return this.FindElement("css selector", "#" + By.EscapeCssSelector(id));
}
/// <summary>
/// Finds the first element in the page that matches the ID supplied
/// </summary>
/// <param name="id">ID of the Element</param>
/// <returns>ReadOnlyCollection of Elements that match the object so that you can interact that object</returns>
/// <example>
/// <code>
/// IWebDriver driver = new RemoteWebDriver(DesiredCapabilities.Firefox());
/// ReadOnlyCollection<![CDATA[<IWebElement>]]> elem = driver.FindElementsById("id")
/// </code>
/// </example>
public ReadOnlyCollection<IWebElement> FindElementsById(string id)
{
string selector = By.EscapeCssSelector(id);
if (string.IsNullOrEmpty(selector))
{
// Finding multiple elements with an empty ID will return
// an empty list. However, finding by a CSS selector of '#'
// throws an exception, even in the multiple elements case,
// which means we need to short-circuit that behavior.
return new List<IWebElement>().AsReadOnly();
}
return this.FindElements("css selector", "#" + selector);
}
/// <summary>
/// Finds the first element in the page that matches the CSS Class supplied
/// </summary>
/// <param name="className">className of the</param>
/// <returns>IWebElement object so that you can interact that object</returns>
/// <example>
/// <code>
/// IWebDriver driver = new RemoteWebDriver(DesiredCapabilities.Firefox());
/// IWebElement elem = driver.FindElementByClassName("classname")
/// </code>
/// </example>
public IWebElement FindElementByClassName(string className)
{
string selector = By.EscapeCssSelector(className);
if (selector.Contains(" "))
{
// Finding elements by class name with whitespace is not allowed.
// However, converting the single class name to a valid CSS selector
// by prepending a '.' may result in a still-valid, but incorrect
// selector. Thus, we short-ciruit that behavior here.
throw new InvalidSelectorException("Compound class names not allowed. Cannot have whitespace in class name. Use CSS selectors instead.");
}
return this.FindElement("css selector", "." + selector);
}
/// <summary>
/// Finds a list of elements that match the class name supplied
/// </summary>
/// <param name="className">CSS class Name on the element</param>
/// <returns>ReadOnlyCollection of IWebElement object so that you can interact with those objects</returns>
/// <example>
/// <code>
/// IWebDriver driver = new RemoteWebDriver(DesiredCapabilities.Firefox());
/// ReadOnlyCollection<![CDATA[<IWebElement>]]> elem = driver.FindElementsByClassName("classname")
/// </code>
/// </example>
public ReadOnlyCollection<IWebElement> FindElementsByClassName(string className)
{
string selector = By.EscapeCssSelector(className);
if (selector.Contains(" "))
{
// Finding elements by class name with whitespace is not allowed.
// However, converting the single class name to a valid CSS selector
// by prepending a '.' may result in a still-valid, but incorrect
// selector. Thus, we short-ciruit that behavior here.
throw new InvalidSelectorException("Compound class names not allowed. Cannot have whitespace in class name. Use CSS selectors instead.");
}
return this.FindElements("css selector", "." + selector);
}
/// <summary>
/// Finds the first of elements that match the link text supplied
/// </summary>
/// <param name="linkText">Link text of element </param>
/// <returns>IWebElement object so that you can interact that object</returns>
/// <example>
/// <code>
/// IWebDriver driver = new RemoteWebDriver(DesiredCapabilities.Firefox());
/// IWebElement elem = driver.FindElementsByLinkText("linktext")
/// </code>
/// </example>
public IWebElement FindElementByLinkText(string linkText)
{
return this.FindElement("link text", linkText);
}
/// <summary>
/// Finds a list of elements that match the link text supplied
/// </summary>
/// <param name="linkText">Link text of element</param>
/// <returns>ReadOnlyCollection<![CDATA[<IWebElement>]]> object so that you can interact with those objects</returns>
/// <example>
/// <code>
/// IWebDriver driver = new RemoteWebDriver(DesiredCapabilities.Firefox());
/// ReadOnlyCollection<![CDATA[<IWebElement>]]> elem = driver.FindElementsByClassName("classname")
/// </code>
/// </example>
public ReadOnlyCollection<IWebElement> FindElementsByLinkText(string linkText)
{
return this.FindElements("link text", linkText);
}
/// <summary>
/// Finds the first of elements that match the part of the link text supplied
/// </summary>
/// <param name="partialLinkText">part of the link text</param>
/// <returns>IWebElement object so that you can interact that object</returns>
/// <example>
/// <code>
/// IWebDriver driver = new RemoteWebDriver(DesiredCapabilities.Firefox());
/// IWebElement elem = driver.FindElementsByPartialLinkText("partOfLink")
/// </code>
/// </example>
public IWebElement FindElementByPartialLinkText(string partialLinkText)
{
return this.FindElement("partial link text", partialLinkText);
}
/// <summary>
/// Finds a list of elements that match the class name supplied
/// </summary>
/// <param name="partialLinkText">part of the link text</param>
/// <returns>ReadOnlyCollection<![CDATA[<IWebElement>]]> objects so that you can interact that object</returns>
/// <example>
/// <code>
/// IWebDriver driver = new RemoteWebDriver(DesiredCapabilities.Firefox());
/// ReadOnlyCollection<![CDATA[<IWebElement>]]> elem = driver.FindElementsByPartialLinkText("partOfTheLink")
/// </code>
/// </example>
public ReadOnlyCollection<IWebElement> FindElementsByPartialLinkText(string partialLinkText)
{
return this.FindElements("partial link text", partialLinkText);
}
/// <summary>
/// Finds the first of elements that match the name supplied
/// </summary>
/// <param name="name">Name of the element on the page</param>
/// <returns>IWebElement object so that you can interact that object</returns>
/// <example>
/// <code>
/// IWebDriver driver = new RemoteWebDriver(DesiredCapabilities.Firefox());
/// elem = driver.FindElementsByName("name")
/// </code>
/// </example>
public IWebElement FindElementByName(string name)
{
return this.FindElement("css selector", "*[name=\"" + name + "\"]");
}
/// <summary>
/// Finds a list of elements that match the name supplied
/// </summary>
/// <param name="name">Name of element</param>
/// <returns>ReadOnlyCollect of IWebElement objects so that you can interact that object</returns>
/// <example>
/// <code>
/// IWebDriver driver = new RemoteWebDriver(DesiredCapabilities.Firefox());
/// ReadOnlyCollection<![CDATA[<IWebElement>]]> elem = driver.FindElementsByName("name")
/// </code>
/// </example>
public ReadOnlyCollection<IWebElement> FindElementsByName(string name)
{
return this.FindElements("css selector", "*[name=\"" + name + "\"]");
}
/// <summary>
/// Finds the first of elements that match the DOM Tag supplied
/// </summary>
/// <param name="tagName">DOM tag Name of the element being searched</param>
/// <returns>IWebElement object so that you can interact that object</returns>
/// <example>
/// <code>
/// IWebDriver driver = new RemoteWebDriver(DesiredCapabilities.Firefox());
/// IWebElement elem = driver.FindElementsByTagName("tag")
/// </code>
/// </example>
public IWebElement FindElementByTagName(string tagName)
{
return this.FindElement("css selector", tagName);
}
/// <summary>
/// Finds a list of elements that match the DOM Tag supplied
/// </summary>
/// <param name="tagName">DOM tag Name of element being searched</param>
/// <returns>IWebElement object so that you can interact that object</returns>
/// <example>
/// <code>
/// IWebDriver driver = new RemoteWebDriver(DesiredCapabilities.Firefox());
/// ReadOnlyCollection<![CDATA[<IWebElement>]]> elem = driver.FindElementsByTagName("tag")
/// </code>
/// </example>
public ReadOnlyCollection<IWebElement> FindElementsByTagName(string tagName)
{
return this.FindElements("css selector", tagName);
}
/// <summary>
/// Finds the first of elements that match the XPath supplied
/// </summary>
/// <param name="xpath">xpath to the element</param>
/// <returns>IWebElement object so that you can interact that object</returns>
/// <example>
/// <code>
/// IWebDriver driver = new RemoteWebDriver(DesiredCapabilities.Firefox());
/// IWebElement elem = driver.FindElementsByXPath("//table/tbody/tr/td/a");
/// </code>
/// </example>
public IWebElement FindElementByXPath(string xpath)
{
return this.FindElement("xpath", xpath);
}
/// <summary>
/// Finds a list of elements that match the XPath supplied
/// </summary>
/// <param name="xpath">xpath to the element</param>
/// <returns>ReadOnlyCollection of IWebElement objects so that you can interact that object</returns>
/// <example>
/// <code>
/// IWebDriver driver = new RemoteWebDriver(DesiredCapabilities.Firefox());
/// ReadOnlyCollection<![CDATA[<IWebElement>]]> elem = driver.FindElementsByXpath("//tr/td/a")
/// </code>
/// </example>
public ReadOnlyCollection<IWebElement> FindElementsByXPath(string xpath)
{
return this.FindElements("xpath", xpath);
}
/// <summary>
/// Finds the first element matching the specified CSS selector.
/// </summary>
/// <param name="cssSelector">The CSS selector to match.</param>
/// <returns>The first <see cref="IWebElement"/> matching the criteria.</returns>
public IWebElement FindElementByCssSelector(string cssSelector)
{
return this.FindElement("css selector", cssSelector);
}
/// <summary>
/// Finds all elements matching the specified CSS selector.
/// </summary>
/// <param name="cssSelector">The CSS selector to match.</param>
/// <returns>A <see cref="ReadOnlyCollection{T}"/> containing all
/// <see cref="IWebElement">IWebElements</see> matching the criteria.</returns>
public ReadOnlyCollection<IWebElement> FindElementsByCssSelector(string cssSelector)
{
return this.FindElements("css selector", cssSelector);
}
public DevToolsSession GetDevToolsSession()
{
return GetDevToolsSession(DevToolsSession.AutoDetectDevToolsProtocolVersion);
}
public DevToolsSession GetDevToolsSession(int protocolVersion)
{
if (this.devToolsSession == null)
{
if (!this.Capabilities.HasCapability(RemoteDevToolsEndPointCapabilityName))
{
throw new WebDriverException("Cannot find " + RemoteDevToolsEndPointCapabilityName + " capability for driver");
}
if (!this.Capabilities.HasCapability(RemoteDevToolsVersionCapabilityName))
{
throw new WebDriverException("Cannot find " + RemoteDevToolsVersionCapabilityName + " capability for driver");
}
string debuggerAddress = this.Capabilities.GetCapability(RemoteDevToolsEndPointCapabilityName).ToString();
string version = this.Capabilities.GetCapability(RemoteDevToolsVersionCapabilityName).ToString();
bool versionParsed = int.TryParse(version.Substring(0, version.IndexOf(".")), out int devToolsProtocolVersion);
if (!versionParsed)
{
throw new WebDriverException("Cannot parse protocol version from reported version string: " + version);
}
try
{
DevToolsSession session = new DevToolsSession(debuggerAddress);
session.StartSession(devToolsProtocolVersion).ConfigureAwait(false).GetAwaiter().GetResult();
this.devToolsSession = session;
}
catch (Exception e)
{
throw new WebDriverException("Unexpected error creating WebSocket DevTools session.", e);
}
}
return this.devToolsSession;
}
/// <summary>
/// Closes a DevTools session.
/// </summary>
public void CloseDevToolsSession()
{
if (this.devToolsSession != null)
{
this.devToolsSession.StopSession(true).ConfigureAwait(false).GetAwaiter().GetResult();
}
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
if (this.devToolsSession != null)
{
this.devToolsSession.Dispose();
this.devToolsSession = null;
}
}
base.Dispose(disposing);
}
private static ICapabilities ConvertOptionsToCapabilities(DriverOptions options)
{
if (options == null)
{
throw new ArgumentNullException(nameof(options), "Driver options must not be null");
}
return options.ToCapabilities();
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using Xunit;
using System;
using System.Collections;
using System.Collections.Specialized;
using GenStrings;
namespace System.Collections.Specialized.Tests
{
public class SetStrStrTests
{
public const int MAX_LEN = 50; // max length of random strings
[Fact]
public void Test01()
{
IntlStrings intl;
NameValueCollection nvc;
// simple string values
string[] values =
{
"",
" ",
"a",
"aA",
"text",
" SPaces",
"1",
"$%^#",
"2222222222222222222222222",
System.DateTime.Today.ToString(),
Int32.MaxValue.ToString()
};
// keys for simple string values
string[] keys =
{
"zero",
"oNe",
" ",
"",
"aa",
"1",
System.DateTime.Today.ToString(),
"$%^#",
Int32.MaxValue.ToString(),
" spaces",
"2222222222222222222222222"
};
int cnt = 0; // Count
// initialize IntStrings
intl = new IntlStrings();
// [] NameValueCollection is constructed as expected
//-----------------------------------------------------------------
nvc = new NameValueCollection();
// [] Set() - new simple strings
//
for (int i = 0; i < values.Length; i++)
{
cnt = nvc.Count;
nvc.Set(keys[i], values[i]);
if (nvc.Count != cnt + 1)
{
Assert.False(true, string.Format("Error, count is {1} instead of {2}", i, nvc.Count, cnt + 1));
}
// verify that collection contains newly added item
//
if (Array.IndexOf(nvc.AllKeys, keys[i]) < 0)
{
Assert.False(true, string.Format("Error, collection doesn't contain key of new item", i));
}
// access the item
//
if (String.Compare(nvc[keys[i]], values[i]) != 0)
{
Assert.False(true, string.Format("Error, returned item \"{1}\" instead of \"{2}\"", i, nvc[keys[i]], values[i]));
}
}
//
// Intl strings
// [] Set() - new Intl strings
//
int len = values.Length;
string[] intlValues = new string[len * 2];
// fill array with unique strings
//
for (int i = 0; i < len * 2; i++)
{
string val = intl.GetRandomString(MAX_LEN);
while (Array.IndexOf(intlValues, val) != -1)
val = intl.GetRandomString(MAX_LEN);
intlValues[i] = val;
}
Boolean caseInsensitive = false;
for (int i = 0; i < len * 2; i++)
{
if (intlValues[i].Length != 0 && intlValues[i].ToLowerInvariant() == intlValues[i].ToUpperInvariant())
caseInsensitive = true;
}
//
// will use first half of array as values and second half as keys
//
for (int i = 0; i < len; i++)
{
cnt = nvc.Count;
nvc.Set(intlValues[i + len], intlValues[i]);
if (nvc.Count != cnt + 1)
{
Assert.False(true, string.Format("Error, count is {1} instead of {2}", i, nvc.Count, cnt + 1));
}
// verify that collection contains newly added item
//
if (Array.IndexOf(nvc.AllKeys, intlValues[i + len]) < 0)
{
Assert.False(true, string.Format("Error, collection doesn't contain key of new item", i));
}
// access the item
//
if (String.Compare(nvc[intlValues[i + len]], intlValues[i]) != 0)
{
Assert.False(true, string.Format("Error, returned item \"{1}\" instead of \"{2}\"", i, nvc[intlValues[i + len]], intlValues[i]));
}
}
//
// [] Case sensitivity
// Casing doesn't change ( keys are not converted to lower!)
//
string[] intlValuesLower = new string[len * 2];
// fill array with unique strings
//
for (int i = 0; i < len * 2; i++)
{
intlValues[i] = intlValues[i].ToUpperInvariant();
}
for (int i = 0; i < len * 2; i++)
{
intlValuesLower[i] = intlValues[i].ToLowerInvariant();
}
nvc.Clear();
//
// will use first half of array as values and second half as keys
//
for (int i = 0; i < len; i++)
{
cnt = nvc.Count;
// add uppercase items
nvc.Set(intlValues[i + len], intlValues[i]);
if (nvc.Count != cnt + 1)
{
Assert.False(true, string.Format("Error, count is {1} instead of {2}", i, nvc.Count, cnt + 1));
}
// verify that collection contains newly added uppercase item
//
if (Array.IndexOf(nvc.AllKeys, intlValues[i + len]) < 0)
{
Assert.False(true, string.Format("Error, collection doesn't contain key of new item", i));
}
// access the item
//
if (String.Compare(nvc[intlValues[i + len]], intlValues[i]) != 0)
{
Assert.False(true, string.Format("Error, returned item \"{1}\" instead of \"{2}\"", i, nvc[intlValues[i + len]], intlValues[i]));
}
// verify that collection doesn't contains lowercase item
//
if (!caseInsensitive && String.Compare(nvc[intlValuesLower[i + len]], intlValuesLower[i]) == 0)
{
Assert.False(true, string.Format("Error, returned item \"{1}\" is lowercase after adding uppercase", i, nvc[intlValuesLower[i + len]]));
}
// key is not converted to lower
if (!caseInsensitive && Array.IndexOf(nvc.AllKeys, intlValuesLower[i + len]) >= 0)
{
Assert.False(true, string.Format("Error, key was converted to lower", i));
}
// but search among keys is case-insensitive
if (String.Compare(nvc[intlValuesLower[i + len]], intlValues[i]) != 0)
{
Assert.False(true, string.Format("Error, could not find item using differently cased key", i));
}
}
//
// [] Set multiple values with the same key
//
nvc.Clear();
len = values.Length;
string k = "keykey";
for (int i = 0; i < len; i++)
{
nvc.Set(k, "Value" + i);
// should replace previous value
if (nvc.Count != 1)
{
Assert.False(true, string.Format("Error, count is {0} instead of 1", nvc.Count, i));
}
if (String.Compare(nvc[k], "Value" + i) != 0)
{
Assert.False(true, string.Format("Error, didn't replace value", i));
}
}
if (nvc.AllKeys.Length != 1)
{
Assert.False(true, "Error, should contain only 1 key");
}
// verify that collection contains newly added item
//
if (Array.IndexOf(nvc.AllKeys, k) < 0)
{
Assert.False(true, "Error, collection doesn't contain key of new item");
}
// access the item
//
string[] vals = nvc.GetValues(k);
if (vals.Length != 1)
{
Assert.False(true, string.Format("Error, number of values at given key is {0} instead of {1}", vals.Length, 1));
}
if (Array.IndexOf(vals, "Value" + (len - 1).ToString()) < 0)
{
Assert.False(true, string.Format("Error, value is not {0}", "Value" + (len - 1)));
}
//
// [] Set(string, null)
//
k = "kk";
nvc.Remove(k); // make sure there is no such item already
cnt = nvc.Count;
nvc.Set(k, null);
if (nvc.Count != cnt + 1)
{
Assert.False(true, string.Format("Error, count is {0} instead of {1}", nvc.Count, cnt + 1));
}
if (Array.IndexOf(nvc.AllKeys, k) < 0)
{
Assert.False(true, "Error, collection doesn't contain key of new item");
}
// verify that collection contains null
//
if (nvc[k] != null)
{
Assert.False(true, "Error, returned non-null on place of null");
}
nvc.Remove(k); // make sure there is no such item already
nvc.Add(k, "kItem");
cnt = nvc.Count;
nvc.Set(k, null);
if (nvc.Count != cnt)
{
Assert.False(true, string.Format("Error, count has changed: {0} instead of {1}", nvc.Count, cnt));
}
if (Array.IndexOf(nvc.AllKeys, k) < 0)
{
Assert.False(true, "Error, collection doesn't contain key of new item");
}
// verify that item at k-key was replaced with null
//
if (nvc[k] != null)
{
Assert.False(true, "Error, non-null was not replaced with null");
}
//
// Set item with null key - no NullReferenceException expected
// [] Set(null, string)
//
nvc.Remove(null);
cnt = nvc.Count;
nvc.Set(null, "item");
if (nvc.Count != cnt + 1)
{
Assert.False(true, string.Format("Error, count is {0} instead of {1}", nvc.Count, cnt + 1));
}
if (Array.IndexOf(nvc.AllKeys, null) < 0)
{
Assert.False(true, "Error, collection doesn't contain null key ");
}
// verify that collection contains null
//
if (nvc[null] != "item")
{
Assert.False(true, "Error, returned wrong value at null key");
}
// replace item with null key
cnt = nvc.Count;
nvc.Set(null, "newItem");
if (nvc.Count != cnt)
{
Assert.False(true, string.Format("Error, count has changed: {0} instead of {1}", nvc.Count, cnt));
}
if (Array.IndexOf(nvc.AllKeys, null) < 0)
{
Assert.False(true, "Error, collection doesn't contain null key ");
}
// verify that item with null key was replaced
//
if (nvc[null] != "newItem")
{
Assert.False(true, "Error, didn't replace value at null key");
}
}
}
}
| |
using System;
using System.Collections;
using NBM.Plugin;
using IO = System.IO;
using Net = System.Net;
using Sockets = System.Net.Sockets;
using Regex = System.Text.RegularExpressions;
public delegate void ResponseReceivedHandler(MessageRouter router, Message message, object tag);
/// <summary>
/// Controls incoming and outgoing MSN protocol messages.
/// </summary>
public class MessageRouter
{
private const int maxMessageSize = 2048;
private const string md5MagicHash = @"Q1P7W2E4J9R8U3S5";
private ResponseReceivedHandler defaultMessageSink, onDisconnectHandler;
private Protocol protocol;
private Proxy.IConnection connection;
private byte[] receiveBuffer = new byte[ maxMessageSize ];
private CircularStream circStream = new CircularStream(maxMessageSize * 3);
private Hashtable codeEvents = new Hashtable(); // keeps a hashtable of strings (codes) for the key and events for the value.
private Hashtable transactionEvents = new Hashtable(); // keeps a ht of ints (transaction IDs) for the key and events for the value.
public volatile bool ExpectingDisconnection = false;
public ResponseReceivedHandler DefaultMessageSink
{
get { return defaultMessageSink; }
set { defaultMessageSink = value; }
}
private void onDisconnect(MessageRouter router, Message message, object tag)
{
if (ExpectingDisconnection)
this.connection.Disconnect();
else
{
if (this.onDisconnectHandler != null)
this.onDisconnectHandler(router, message, tag);
}
}
public MessageRouter(Protocol protocol, Proxy.IConnection connection, ResponseReceivedHandler defaultMessageSink, ResponseReceivedHandler onDisconnect)
{
this.protocol = protocol;
this.connection = connection;
this.defaultMessageSink = defaultMessageSink;
this.onDisconnectHandler = onDisconnect;
// set up receiving async call
this.connection.BeginReceive(receiveBuffer, new AsyncCallback(OnDataReceive), null);
}
public void RemoveMessageEvent(Message message)
{
if (this.transactionEvents.Contains(message.TransactionID))
this.transactionEvents.Remove(message.TransactionID);
}
public void AddCodeEvent(string code, ResponseReceivedHandler messageHandler)
{
AddCodeEvent(code, messageHandler, null);
}
public void AddCodeEvent(string code, ResponseReceivedHandler messageHandler, object tag)
{
if (!codeEvents.Contains(code))
codeEvents.Add(code, new Pair(messageHandler, tag));
else
codeEvents[code] = new Pair(messageHandler, tag);
}
public void SendMessage(Message message)
{
SendMessage(message, null, null);
}
public void SendMessage(Message message, bool addLineEnding)
{
SendMessage(message, null, null, addLineEnding);
}
public void SendMessage(Message message, ResponseReceivedHandler responseReceivedEvent, object tag)
{
SendMessage(message, responseReceivedEvent, tag, true);
}
public void SendMessage(Message message, ResponseReceivedHandler responseReceivedEvent, object tag, bool addLineEnding)
{
byte[] byteMessage = System.Text.Encoding.ASCII.GetBytes(message.RawMessage + (addLineEnding ? "\r\n" : ""));
try
{
this.connection.Send(byteMessage);
this.protocol.control.WriteDebug("-----------------------------------------");
this.protocol.control.WriteDebug("Sent");
this.protocol.control.WriteDebug(System.Text.ASCIIEncoding.ASCII.GetString(byteMessage));
this.protocol.control.WriteDebug("-----------------------------------------");
if (responseReceivedEvent != null)
{
transactionEvents.Add(message.TransactionID, new Pair(responseReceivedEvent, tag));
}
}
catch
{
// couldn't write to the stream. we've been disconnected
this.onDisconnect(this, null, null);
}
}
private void OnDataReceive(IAsyncResult result)
{
lock (this)
{
int bytesRead = this.connection.EndReceive(result);
if (bytesRead > 0)
{
// shove data into memory stream
circStream.Write(this.receiveBuffer, 0, bytesRead);
// get raw data from circular stream
byte[] rawData = new byte[ circStream.DataAvailable ];
circStream.Read(rawData, 0, rawData.Length);
// split the message into composite messages
string rawMessage = System.Text.Encoding.ASCII.GetString(rawData);
string subMessage = string.Empty;
int position = 0;
while (position < rawMessage.Length)
{
// see if we have enough to determine the message code
if (rawMessage.Length - position >= 3)
{
string messageCode = rawMessage.Substring(position, 3);
if (messageCode == "MSG")
{
// if its a MSG, then read until the length is satified
Regex.Regex regex = new Regex.Regex(@"MSG\s+\S+\s+\S+\s+(?<length>\d+)");
Regex.Match match = regex.Match(rawMessage.Substring(position));
if (match.Success)
{
int length = int.Parse(match.Groups["length"].Value);
int endOfHeader = rawMessage.IndexOf("\r\n", position);
if (endOfHeader >= 0 && position + endOfHeader + length + 2 <= rawMessage.Length)
subMessage = rawMessage.Substring(position, endOfHeader + length + 2 - position);
else
{
this.SetToDataStream(rawMessage.Substring(position));
break;
}
}
else
{
// we didnt get enough of the string to determine the message length -
// set it to the data stream and wait till the next rush of data
this.SetToDataStream(rawMessage.Substring(position));
break;
}
}
else
{
// otherwise it isnt a MSG, so read up until the first \r\n
int newPosition = rawMessage.IndexOf("\r\n", position);
if (newPosition < 0)
{
// we dont have the entire message - clear out the left over data stream
// and add the incomplete message to the stream
this.SetToDataStream(rawMessage.Substring(position));
break;
}
else
{
newPosition += 2;
subMessage = rawMessage.Substring(position, newPosition - position);
}
}
}
else
{
// we dont even have enough to determine the message code - add it to the data stream
// and forget about it
this.SetToDataStream(rawMessage.Substring(position));
break;
}
position += subMessage.Length;
this.protocol.control.WriteDebug("-----------------------------------------");
this.protocol.control.WriteDebug("Received");
this.protocol.control.WriteDebug(subMessage);
this.protocol.control.WriteDebug("-----------------------------------------");
Message message = new Message(subMessage);
switch (message.Code)
{
case "CHL":
{
// we received a challenge. Respond to it appropriately.
string hash = message.Arguments;
// md5 encrypt hash
hash += md5MagicHash;
MD5Encryption encryption = new MD5Encryption();
string md5hash = encryption.Encrypt(hash);
Message responseMessage = Message.ConstructMessage("QRY", @"[email protected] 32"+"\r\n" + md5hash);
this.SendMessage(responseMessage, false);
}
break;
}
try
{
// see if theres a transaction ID registered with it
if (this.transactionEvents.Contains(message.TransactionID))
{
Pair pair = (Pair)this.transactionEvents[message.TransactionID];
((ResponseReceivedHandler)pair.First)(this, message, pair.Second);
}
// else check if the code is registered
else if (this.codeEvents.Contains(message.Code))
{
Pair pair = (Pair)this.codeEvents[message.Code];
((ResponseReceivedHandler)pair.First)(this, message, pair.Second);
}
// otherwise uses the default message sink
else
{
if (defaultMessageSink != null)
defaultMessageSink(this, message, null);
}
}
catch
{}
}
try
{
// restart async call
this.connection.BeginReceive(receiveBuffer, new AsyncCallback(OnDataReceive), null);
}
catch
{
this.onDisconnect(this, null, null);
}
}
else if (!ExpectingDisconnection)
{
this.onDisconnect(this, null, null);
}
}
}
private void SetToDataStream(string message)
{
byte[] b = System.Text.ASCIIEncoding.ASCII.GetBytes(message);
this.circStream.Write(b, 0, message.Length);
}
public void Close()
{
this.connection.Disconnect();
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
namespace Apache.Ignite.Core.Impl.Compute
{
using System;
using System.Collections.Generic;
using System.Diagnostics;
using Apache.Ignite.Core.Cluster;
using Apache.Ignite.Core.Common;
using Apache.Ignite.Core.Compute;
/// <summary>
/// Synchronous Compute facade.
/// </summary>
internal class Compute : ICompute
{
/** */
private readonly ComputeImpl _compute;
/// <summary>
/// Initializes a new instance of the <see cref="Compute"/> class.
/// </summary>
/// <param name="computeImpl">The compute implementation.</param>
public Compute(ComputeImpl computeImpl)
{
Debug.Assert(computeImpl != null);
_compute = computeImpl;
}
/** <inheritDoc /> */
public ICompute WithAsync()
{
return new ComputeAsync(_compute);
}
/** <inheritDoc /> */
public bool IsAsync
{
get { return false; }
}
/** <inheritDoc /> */
public IFuture GetFuture()
{
throw IgniteUtils.GetAsyncModeDisabledException();
}
/** <inheritDoc /> */
public IFuture<TResult> GetFuture<TResult>()
{
throw IgniteUtils.GetAsyncModeDisabledException();
}
/** <inheritDoc /> */
public IClusterGroup ClusterGroup
{
get { return _compute.ClusterGroup; }
}
/** <inheritDoc /> */
public ICompute WithNoFailover()
{
_compute.WithNoFailover();
return this;
}
/** <inheritDoc /> */
public ICompute WithTimeout(long timeout)
{
_compute.WithTimeout(timeout);
return this;
}
/** <inheritDoc /> */
public ICompute WithKeepPortable()
{
_compute.WithKeepPortable();
return this;
}
/** <inheritDoc /> */
public T ExecuteJavaTask<T>(string taskName, object taskArg)
{
return _compute.ExecuteJavaTask<T>(taskName, taskArg);
}
/** <inheritDoc /> */
public TR Execute<TA, T, TR>(IComputeTask<TA, T, TR> task, TA taskArg)
{
return _compute.Execute(task, taskArg).Get();
}
/** <inheritDoc /> */
public TR Execute<T, TR>(IComputeTask<T, TR> task)
{
return _compute.Execute(task, null).Get();
}
/** <inheritDoc /> */
public TR Execute<TA, T, TR>(Type taskType, TA taskArg)
{
return _compute.Execute<TA, T, TR>(taskType, taskArg).Get();
}
public TR Execute<T, TR>(Type taskType)
{
return _compute.Execute<object, T, TR>(taskType, null).Get();
}
/** <inheritDoc /> */
public TR Call<TR>(IComputeFunc<TR> clo)
{
return _compute.Execute(clo).Get();
}
/** <inheritDoc /> */
public TR AffinityCall<TR>(string cacheName, object affinityKey, IComputeFunc<TR> clo)
{
return _compute.AffinityCall(cacheName, affinityKey, clo).Get();
}
/** <inheritDoc /> */
public TR Call<TR>(Func<TR> func)
{
return _compute.Execute(func).Get();
}
/** <inheritDoc /> */
public ICollection<TR> Call<TR>(IEnumerable<IComputeFunc<TR>> clos)
{
return _compute.Execute(clos).Get();
}
/** <inheritDoc /> */
public TR2 Call<TR1, TR2>(IEnumerable<IComputeFunc<TR1>> clos, IComputeReducer<TR1, TR2> rdc)
{
return _compute.Execute(clos, rdc).Get();
}
/** <inheritDoc /> */
public ICollection<TR> Broadcast<TR>(IComputeFunc<TR> clo)
{
return _compute.Broadcast(clo).Get();
}
/** <inheritDoc /> */
public ICollection<TR> Broadcast<T, TR>(IComputeFunc<T, TR> clo, T arg)
{
return _compute.Broadcast(clo, arg).Get();
}
/** <inheritDoc /> */
public void Broadcast(IComputeAction action)
{
_compute.Broadcast(action).Get();
}
/** <inheritDoc /> */
public void Run(IComputeAction action)
{
_compute.Run(action).Get();
}
/** <inheritDoc /> */
public void AffinityRun(string cacheName, object affinityKey, IComputeAction action)
{
_compute.AffinityRun(cacheName, affinityKey, action).Get();
}
/** <inheritDoc /> */
public void Run(IEnumerable<IComputeAction> actions)
{
_compute.Run(actions).Get();
}
/** <inheritDoc /> */
public TR Apply<T, TR>(IComputeFunc<T, TR> clo, T arg)
{
return _compute.Apply(clo, arg).Get();
}
/** <inheritDoc /> */
public ICollection<TR> Apply<T, TR>(IComputeFunc<T, TR> clo, IEnumerable<T> args)
{
return _compute.Apply(clo, args).Get();
}
/** <inheritDoc /> */
public TR2 Apply<T, TR1, TR2>(IComputeFunc<T, TR1> clo, IEnumerable<T> args, IComputeReducer<TR1, TR2> rdc)
{
return _compute.Apply(clo, args, rdc).Get();
}
}
}
| |
using System;
using System.Collections.Generic;
using Csla;
using ParentLoadSoftDelete.DataAccess;
using ParentLoadSoftDelete.DataAccess.ERLevel;
namespace ParentLoadSoftDelete.Business.ERLevel
{
/// <summary>
/// E09_CityColl (editable child list).<br/>
/// This is a generated base class of <see cref="E09_CityColl"/> business object.
/// </summary>
/// <remarks>
/// This class is child of <see cref="E08_Region"/> editable child object.<br/>
/// The items of the collection are <see cref="E10_City"/> objects.
/// </remarks>
[Serializable]
public partial class E09_CityColl : BusinessListBase<E09_CityColl, E10_City>
{
#region Collection Business Methods
/// <summary>
/// Removes a <see cref="E10_City"/> item from the collection.
/// </summary>
/// <param name="city_ID">The City_ID of the item to be removed.</param>
public void Remove(int city_ID)
{
foreach (var e10_City in this)
{
if (e10_City.City_ID == city_ID)
{
Remove(e10_City);
break;
}
}
}
/// <summary>
/// Determines whether a <see cref="E10_City"/> item is in the collection.
/// </summary>
/// <param name="city_ID">The City_ID of the item to search for.</param>
/// <returns><c>true</c> if the E10_City is a collection item; otherwise, <c>false</c>.</returns>
public bool Contains(int city_ID)
{
foreach (var e10_City in this)
{
if (e10_City.City_ID == city_ID)
{
return true;
}
}
return false;
}
/// <summary>
/// Determines whether a <see cref="E10_City"/> item is in the collection's DeletedList.
/// </summary>
/// <param name="city_ID">The City_ID of the item to search for.</param>
/// <returns><c>true</c> if the E10_City is a deleted collection item; otherwise, <c>false</c>.</returns>
public bool ContainsDeleted(int city_ID)
{
foreach (var e10_City in DeletedList)
{
if (e10_City.City_ID == city_ID)
{
return true;
}
}
return false;
}
#endregion
#region Find Methods
/// <summary>
/// Finds a <see cref="E10_City"/> item of the <see cref="E09_CityColl"/> collection, based on item key properties.
/// </summary>
/// <param name="city_ID">The City_ID.</param>
/// <returns>A <see cref="E10_City"/> object.</returns>
public E10_City FindE10_CityByParentProperties(int city_ID)
{
for (var i = 0; i < this.Count; i++)
{
if (this[i].City_ID.Equals(city_ID))
{
return this[i];
}
}
return null;
}
#endregion
#region Factory Methods
/// <summary>
/// Factory method. Creates a new <see cref="E09_CityColl"/> collection.
/// </summary>
/// <returns>A reference to the created <see cref="E09_CityColl"/> collection.</returns>
internal static E09_CityColl NewE09_CityColl()
{
return DataPortal.CreateChild<E09_CityColl>();
}
/// <summary>
/// Factory method. Loads a <see cref="E09_CityColl"/> object from the given list of E10_CityDto.
/// </summary>
/// <param name="data">The list of <see cref="E10_CityDto"/>.</param>
/// <returns>A reference to the fetched <see cref="E09_CityColl"/> object.</returns>
internal static E09_CityColl GetE09_CityColl(List<E10_CityDto> data)
{
E09_CityColl obj = new E09_CityColl();
// show the framework that this is a child object
obj.MarkAsChild();
obj.Fetch(data);
return obj;
}
#endregion
#region Constructor
/// <summary>
/// Initializes a new instance of the <see cref="E09_CityColl"/> class.
/// </summary>
/// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks>
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public E09_CityColl()
{
// Use factory methods and do not use direct creation.
// show the framework that this is a child object
MarkAsChild();
var rlce = RaiseListChangedEvents;
RaiseListChangedEvents = false;
AllowNew = true;
AllowEdit = true;
AllowRemove = true;
RaiseListChangedEvents = rlce;
}
#endregion
#region Data Access
/// <summary>
/// Loads all <see cref="E09_CityColl"/> collection items from the given list of E10_CityDto.
/// </summary>
/// <param name="data">The list of <see cref="E10_CityDto"/>.</param>
private void Fetch(List<E10_CityDto> data)
{
var rlce = RaiseListChangedEvents;
RaiseListChangedEvents = false;
var args = new DataPortalHookArgs(data);
OnFetchPre(args);
foreach (var dto in data)
{
Add(E10_City.GetE10_City(dto));
}
OnFetchPost(args);
RaiseListChangedEvents = rlce;
}
/// <summary>
/// Loads <see cref="E10_City"/> items on the E09_CityObjects collection.
/// </summary>
/// <param name="collection">The grand parent <see cref="E07_RegionColl"/> collection.</param>
internal void LoadItems(E07_RegionColl collection)
{
foreach (var item in this)
{
var obj = collection.FindE08_RegionByParentProperties(item.parent_Region_ID);
var rlce = obj.E09_CityObjects.RaiseListChangedEvents;
obj.E09_CityObjects.RaiseListChangedEvents = false;
obj.E09_CityObjects.Add(item);
obj.E09_CityObjects.RaiseListChangedEvents = rlce;
}
}
#endregion
#region DataPortal Hooks
/// <summary>
/// Occurs after setting query parameters and before the fetch operation.
/// </summary>
partial void OnFetchPre(DataPortalHookArgs args);
/// <summary>
/// Occurs after the fetch operation (object or collection is fully loaded and set up).
/// </summary>
partial void OnFetchPost(DataPortalHookArgs args);
#endregion
}
}
| |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for details.
using System;
using System.ComponentModel;
using System.Diagnostics;
using System.Drawing;
using System.Globalization;
using System.Windows.Forms;
using OpenLiveWriter.Api;
using OpenLiveWriter.Controls;
using OpenLiveWriter.CoreServices;
using OpenLiveWriter.CoreServices.Layout;
using OpenLiveWriter.CoreServices.Marketization;
using OpenLiveWriter.Localization;
using OpenLiveWriter.Localization.Bidi;
using OpenLiveWriter.ApplicationFramework;
using OpenLiveWriter.ApplicationFramework.Preferences;
using OpenLiveWriter.PostEditor.ContentSources;
namespace OpenLiveWriter.PostEditor
{
public class PluginsPreferencesPanel : PreferencesPanel
{
private System.ComponentModel.IContainer components;
private System.Windows.Forms.Label labelInstalledPlugins;
private System.Windows.Forms.Label labelCaption;
private System.Windows.Forms.Panel panelPluginDetails;
private System.Windows.Forms.ListView listViewInstalledPlugins;
private System.Windows.Forms.GroupBox groupBoxPluginDetails;
private System.Windows.Forms.PictureBox pictureBoxPluginImage;
private System.Windows.Forms.RadioButton radioButtonEnablePlugin;
private System.Windows.Forms.RadioButton radioButtonDisablePlugin;
private System.Windows.Forms.Label labelPluginDescription;
private System.Windows.Forms.ImageList imageListPlugins;
private System.Windows.Forms.ColumnHeader columnHeaderName;
private System.Windows.Forms.ColumnHeader columnHeaderStatus;
private System.Windows.Forms.Label labelNoPluginSelected;
private System.Windows.Forms.LinkLabel linkLabelPluginName;
private ToolTip2 toolTip;
private System.Windows.Forms.Button buttonOptions;
private System.Windows.Forms.LinkLabel linkLabelDownloadPlugins;
private System.Windows.Forms.PictureBox pictureBoxAddPlugin;
private PluginsPreferences _pluginsPreferences;
public PluginsPreferencesPanel()
{
// This call is required by the Windows.Forms Form Designer.
InitializeComponent();
columnHeaderName.Text = Res.Get(StringId.PluginPrefNameCol);
columnHeaderStatus.Text = Res.Get(StringId.PluginPrefStatCol);
labelInstalledPlugins.Text = Res.Get(StringId.PluginPrefInstalled);
groupBoxPluginDetails.Text = Res.Get(StringId.PluginPrefDetails);
buttonOptions.Text = Res.Get(StringId.OptionsButton);
toolTip.SetToolTip(this.linkLabelPluginName, Res.Get(StringId.PluginPrefTooltip));
labelPluginDescription.Text = "";
radioButtonDisablePlugin.Text = Res.Get(StringId.PluginPrefDisable);
radioButtonEnablePlugin.Text = Res.Get(StringId.PluginPrefEnable);
labelNoPluginSelected.Text = Res.Get(StringId.PluginPrefNone);
linkLabelDownloadPlugins.Text = Res.Get(StringId.PluginPrefLink);
linkLabelDownloadPlugins.UseCompatibleTextRendering = false;
labelCaption.Text = Res.Get(StringId.PluginPrefCaption);
PanelName = Res.Get(StringId.PluginPrefName);
//marketization
if (!MarketizationOptions.IsFeatureEnabled(MarketizationOptions.Feature.WLGallery))
linkLabelDownloadPlugins.Visible = false;
else
{
pictureBoxAddPlugin.Image = ResourceHelper.LoadAssemblyResourceBitmap("Images.AddPlugin.png");
}
// set our bitmaps
PanelBitmap = ResourceHelper.LoadAssemblyResourceBitmap("Images.PluginsSmall.png");
// paramaterize caption with product name
labelCaption.Text = String.Format(CultureInfo.CurrentCulture, labelCaption.Text, ApplicationEnvironment.ProductName);
// initialize preferences
_pluginsPreferences = new PluginsPreferences();
_pluginsPreferences.PreferencesModified += new EventHandler(_pluginsPreferences_PreferencesModified);
// signup for events
listViewInstalledPlugins.SelectedIndexChanged += new EventHandler(listViewInstalledPlugins_SelectedIndexChanged);
radioButtonEnablePlugin.CheckedChanged += new EventHandler(radioButtonEnablePlugin_CheckedChanged);
radioButtonDisablePlugin.CheckedChanged += new EventHandler(radioButtonEnablePlugin_CheckedChanged);
linkLabelPluginName.LinkClicked += new LinkLabelLinkClickedEventHandler(linkLabelPluginName_LinkClicked);
linkLabelDownloadPlugins.LinkClicked += new LinkLabelLinkClickedEventHandler(linkLabelDownloadPlugins_LinkClicked);
// update list of plugins
UpdatePluginList();
// signup for global plugin-list changed event
ContentSourceManager.GlobalContentSourceListChanged += new EventHandler(ContentSourceManager_GlobalContentSourceListChanged);
}
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
if (!DesignMode)
{
LayoutHelper.NaturalizeHeightAndDistribute(8, Controls);
linkLabelDownloadPlugins.Top = pictureBoxAddPlugin.Top + 1;
LayoutHelper.NaturalizeHeight(linkLabelPluginName);
DisplayHelper.AutoFitSystemRadioButton(radioButtonEnablePlugin, 0, int.MaxValue);
DisplayHelper.AutoFitSystemRadioButton(radioButtonDisablePlugin, 0, int.MaxValue);
radioButtonEnablePlugin.BringToFront();
DisplayHelper.AutoFitSystemButton(buttonOptions);
}
}
private void ContentSourceManager_GlobalContentSourceListChanged(object sender, EventArgs e)
{
// post back to ourselves if necessary
if (InvokeRequired)
{
BeginInvoke(new EventHandler(ContentSourceManager_GlobalContentSourceListChanged), new object[] { sender, e });
return;
}
// update plugin list
UpdatePluginList();
}
private void UpdatePluginList()
{
// clear existing list
listViewInstalledPlugins.Items.Clear();
imageListPlugins.Images.Clear();
// re-initialize list
int imageIndex = 0;
ContentSourceInfo[] pluginContentSources = ContentSourceManager.PluginContentSources;
foreach (ContentSourceInfo pluginContentSource in pluginContentSources)
{
imageListPlugins.Images.Add(BidiHelper.Mirror(pluginContentSource.Image));
ListViewItem listViewItem = new ListViewItem();
listViewItem.Tag = pluginContentSource;
listViewItem.ImageIndex = imageIndex++;
RefreshListViewItem(listViewItem);
listViewInstalledPlugins.Items.Add(listViewItem);
}
// select first item if possible
if (listViewInstalledPlugins.Items.Count > 0)
listViewInstalledPlugins.Items[0].Selected = true;
// update the details pane
UpdateDetailsPane();
}
public override void Save()
{
if (_pluginsPreferences.IsModified())
{
_pluginsPreferences.Save();
DisplayMessage.Show(MessageId.PluginStatusChanged, this);
}
}
private void _pluginsPreferences_PreferencesModified(object sender, EventArgs e)
{
OnModified(EventArgs.Empty);
}
private void listViewInstalledPlugins_SelectedIndexChanged(object sender, EventArgs e)
{
UpdateDetailsPane();
}
private void radioButtonEnablePlugin_CheckedChanged(object sender, EventArgs e)
{
ContentSourceInfo selectedContentSource = GetSelectedPlugin();
if (selectedContentSource != null)
{
// if our underlying state has changed then update underlying prefs
if (_pluginsPreferences.GetPluginEnabledState(selectedContentSource) != radioButtonEnablePlugin.Checked)
{
_pluginsPreferences.SetPluginEnabledState(selectedContentSource, radioButtonEnablePlugin.Checked);
RefreshSelectedListViewItem();
}
}
}
private void linkLabelPluginName_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
ContentSourceInfo selectedContentSource = GetSelectedPlugin();
if (selectedContentSource != null)
{
if (selectedContentSource.WriterPluginPublisherUrl != String.Empty)
ShellHelper.LaunchUrl(selectedContentSource.WriterPluginPublisherUrl);
}
}
private void linkLabelDownloadPlugins_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
ShellHelper.LaunchUrl(GLink.Instance.DownloadPlugins);
}
private void buttonOptions_Click(object sender, System.EventArgs e)
{
ContentSourceInfo selectedContentSource = GetSelectedPlugin();
if (selectedContentSource != null)
{
if (selectedContentSource.WriterPluginHasEditableOptions)
{
try
{
selectedContentSource.Instance.EditOptions(FindForm());
}
catch (NotImplementedException ex)
{
ContentSourceManager.DisplayContentRetreivalError(FindForm(), ex, selectedContentSource);
}
catch (Exception exception)
{
Trace.Fail(exception.ToString());
DisplayableException dex = new DisplayableException(
Res.Get(StringId.UnexpectedErrorPluginTitle),
string.Format(CultureInfo.CurrentCulture, Res.Get(StringId.UnexpectedErrorPluginDescription), selectedContentSource.Name, exception.Message));
DisplayableExceptionDisplayForm.Show(FindForm(), dex);
}
}
}
}
private void RefreshSelectedListViewItem()
{
if (listViewInstalledPlugins.SelectedItems.Count > 0)
RefreshListViewItem(listViewInstalledPlugins.SelectedItems[0]);
}
private void RefreshListViewItem(ListViewItem listViewItem)
{
ContentSourceInfo itemContentSource = listViewItem.Tag as ContentSourceInfo;
listViewItem.SubItems.Clear();
listViewItem.Text = " " + itemContentSource.Name;
listViewItem.SubItems.Add(new ListViewItem.ListViewSubItem(listViewItem, _pluginsPreferences.GetPluginEnabledState(itemContentSource) ? Res.Get(StringId.Enabled) : Res.Get(StringId.Disabled)));
}
private void UpdateDetailsPane()
{
ContentSourceInfo selectedContentSource = GetSelectedPlugin();
if (selectedContentSource != null)
{
panelPluginDetails.Visible = true;
labelNoPluginSelected.Visible = false;
pictureBoxPluginImage.Image = selectedContentSource.Image;
linkLabelPluginName.Text = selectedContentSource.Name;
labelPluginDescription.Text = selectedContentSource.WriterPluginDescription;
radioButtonEnablePlugin.Checked = selectedContentSource.Enabled;
radioButtonDisablePlugin.Checked = !selectedContentSource.Enabled;
buttonOptions.Visible = selectedContentSource.WriterPluginHasEditableOptions;
}
else
{
labelNoPluginSelected.Visible = true;
panelPluginDetails.Visible = false;
}
}
private ContentSourceInfo GetSelectedPlugin()
{
if (listViewInstalledPlugins.SelectedItems.Count > 0)
return listViewInstalledPlugins.SelectedItems[0].Tag as ContentSourceInfo;
else
return null;
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose(bool disposing)
{
if (disposing)
{
ContentSourceManager.GlobalContentSourceListChanged -= new EventHandler(ContentSourceManager_GlobalContentSourceListChanged);
_pluginsPreferences.PreferencesModified -= new EventHandler(_pluginsPreferences_PreferencesModified);
if (components != null)
{
components.Dispose();
}
}
base.Dispose(disposing);
}
#region Component Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
System.Resources.ResourceManager resources = new System.Resources.ResourceManager(typeof(PluginsPreferencesPanel));
this.listViewInstalledPlugins = new System.Windows.Forms.ListView();
this.columnHeaderName = new System.Windows.Forms.ColumnHeader();
this.columnHeaderStatus = new System.Windows.Forms.ColumnHeader();
this.imageListPlugins = new System.Windows.Forms.ImageList(this.components);
this.labelInstalledPlugins = new System.Windows.Forms.Label();
this.groupBoxPluginDetails = new System.Windows.Forms.GroupBox();
this.panelPluginDetails = new System.Windows.Forms.Panel();
this.buttonOptions = new System.Windows.Forms.Button();
this.linkLabelPluginName = new System.Windows.Forms.LinkLabel();
this.labelPluginDescription = new System.Windows.Forms.Label();
this.radioButtonDisablePlugin = new System.Windows.Forms.RadioButton();
this.radioButtonEnablePlugin = new System.Windows.Forms.RadioButton();
this.pictureBoxPluginImage = new System.Windows.Forms.PictureBox();
this.labelNoPluginSelected = new System.Windows.Forms.Label();
this.labelCaption = new System.Windows.Forms.Label();
this.toolTip = new ToolTip2(this.components);
this.linkLabelDownloadPlugins = new System.Windows.Forms.LinkLabel();
this.pictureBoxAddPlugin = new System.Windows.Forms.PictureBox();
this.groupBoxPluginDetails.SuspendLayout();
this.panelPluginDetails.SuspendLayout();
this.SuspendLayout();
//
// listViewInstalledPlugins
//
this.listViewInstalledPlugins.AutoArrange = false;
this.listViewInstalledPlugins.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] {
this.columnHeaderName,
this.columnHeaderStatus});
this.listViewInstalledPlugins.FullRowSelect = true;
this.listViewInstalledPlugins.HeaderStyle = System.Windows.Forms.ColumnHeaderStyle.Nonclickable;
this.listViewInstalledPlugins.HideSelection = false;
this.listViewInstalledPlugins.Location = new System.Drawing.Point(8, 83);
this.listViewInstalledPlugins.MultiSelect = false;
this.listViewInstalledPlugins.Name = "listViewInstalledPlugins";
this.listViewInstalledPlugins.RightToLeftLayout = BidiHelper.IsRightToLeft;
this.listViewInstalledPlugins.Size = new System.Drawing.Size(348, 148);
this.listViewInstalledPlugins.SmallImageList = this.imageListPlugins;
this.listViewInstalledPlugins.TabIndex = 3;
this.listViewInstalledPlugins.View = System.Windows.Forms.View.Details;
//
// columnHeaderName
//
this.columnHeaderName.Text = "Plugin";
this.columnHeaderName.Width = 229;
//
// columnHeaderStatus
//
this.columnHeaderStatus.Text = "Status";
this.columnHeaderStatus.Width = 95;
//
// imageListPlugins
//
this.imageListPlugins.ColorDepth = System.Windows.Forms.ColorDepth.Depth32Bit;
this.imageListPlugins.ImageSize = new System.Drawing.Size(16, 16);
this.imageListPlugins.TransparentColor = System.Drawing.Color.Transparent;
//
// labelInstalledPlugins
//
this.labelInstalledPlugins.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.labelInstalledPlugins.Location = new System.Drawing.Point(8, 66);
this.labelInstalledPlugins.Name = "labelInstalledPlugins";
this.labelInstalledPlugins.Size = new System.Drawing.Size(341, 15);
this.labelInstalledPlugins.TabIndex = 2;
this.labelInstalledPlugins.Text = "&Plugins currently installed:";
//
// groupBoxPluginDetails
//
this.groupBoxPluginDetails.Controls.Add(this.panelPluginDetails);
this.groupBoxPluginDetails.Controls.Add(this.labelNoPluginSelected);
this.groupBoxPluginDetails.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.groupBoxPluginDetails.Location = new System.Drawing.Point(8, 237);
this.groupBoxPluginDetails.Name = "groupBoxPluginDetails";
this.groupBoxPluginDetails.Size = new System.Drawing.Size(349, 149);
this.groupBoxPluginDetails.TabIndex = 4;
this.groupBoxPluginDetails.TabStop = false;
this.groupBoxPluginDetails.Text = "Plugin details";
//
// panelPluginDetails
//
this.panelPluginDetails.Controls.Add(this.buttonOptions);
this.panelPluginDetails.Controls.Add(this.linkLabelPluginName);
this.panelPluginDetails.Controls.Add(this.labelPluginDescription);
this.panelPluginDetails.Controls.Add(this.radioButtonDisablePlugin);
this.panelPluginDetails.Controls.Add(this.radioButtonEnablePlugin);
this.panelPluginDetails.Controls.Add(this.pictureBoxPluginImage);
this.panelPluginDetails.Location = new System.Drawing.Point(7, 18);
this.panelPluginDetails.Name = "panelPluginDetails";
this.panelPluginDetails.Size = new System.Drawing.Size(339, 123);
this.panelPluginDetails.TabIndex = 0;
//
// buttonOptions
//
this.buttonOptions.Anchor = AnchorStyles.Top | AnchorStyles.Right;
this.buttonOptions.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.buttonOptions.Location = new System.Drawing.Point(250, 61);
this.buttonOptions.Name = "buttonOptions";
this.buttonOptions.Size = new System.Drawing.Size(83, 23);
this.buttonOptions.TabIndex = 4;
this.buttonOptions.Text = "Options...";
this.buttonOptions.Click += new System.EventHandler(this.buttonOptions_Click);
//
// linkLabelPluginName
//
this.linkLabelPluginName.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.linkLabelPluginName.LinkBehavior = System.Windows.Forms.LinkBehavior.HoverUnderline;
this.linkLabelPluginName.LinkColor = System.Drawing.SystemColors.HotTrack;
this.linkLabelPluginName.Location = new System.Drawing.Point(21, 2);
this.linkLabelPluginName.Name = "linkLabelPluginName";
this.linkLabelPluginName.Size = new System.Drawing.Size(222, 16);
this.linkLabelPluginName.TabIndex = 0;
this.linkLabelPluginName.TabStop = true;
this.linkLabelPluginName.Text = "YouTube Video Publisher";
this.toolTip.SetToolTip(this.linkLabelPluginName, "Click here to find out more about this plugin.");
//
// labelPluginDescription
//
this.labelPluginDescription.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.labelPluginDescription.Location = new System.Drawing.Point(2, 21);
this.labelPluginDescription.Name = "labelPluginDescription";
this.labelPluginDescription.Size = new System.Drawing.Size(241, 100);
this.labelPluginDescription.TabIndex = 1;
this.labelPluginDescription.Text = "Publish videos to your weblog from YouTube, the leading free online video streami" +
"ng service.";
//
// radioButtonDisablePlugin
//
this.radioButtonDisablePlugin.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.radioButtonDisablePlugin.Location = new System.Drawing.Point(254, 30);
this.radioButtonDisablePlugin.Name = "radioButtonDisablePlugin";
this.radioButtonDisablePlugin.Size = new System.Drawing.Size(84, 24);
this.radioButtonDisablePlugin.TabIndex = 3;
this.radioButtonDisablePlugin.Text = "&Disable";
//
// radioButtonEnablePlugin
//
this.radioButtonEnablePlugin.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.radioButtonEnablePlugin.Location = new System.Drawing.Point(254, 10);
this.radioButtonEnablePlugin.Name = "radioButtonEnablePlugin";
this.radioButtonEnablePlugin.Size = new System.Drawing.Size(84, 24);
this.radioButtonEnablePlugin.TabIndex = 2;
this.radioButtonEnablePlugin.Text = "&Enable";
//
// pictureBoxPluginImage
//
this.pictureBoxPluginImage.Image = ((System.Drawing.Image)(resources.GetObject("pictureBoxPluginImage.Image")));
this.pictureBoxPluginImage.Location = new System.Drawing.Point(0, 0);
this.pictureBoxPluginImage.Name = "pictureBoxPluginImage";
this.pictureBoxPluginImage.Size = new System.Drawing.Size(20, 18);
this.pictureBoxPluginImage.TabIndex = 0;
this.pictureBoxPluginImage.TabStop = false;
//
// labelNoPluginSelected
//
this.labelNoPluginSelected.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.labelNoPluginSelected.Location = new System.Drawing.Point(16, 43);
this.labelNoPluginSelected.Name = "labelNoPluginSelected";
this.labelNoPluginSelected.Size = new System.Drawing.Size(316, 23);
this.labelNoPluginSelected.TabIndex = 1;
this.labelNoPluginSelected.Text = "(No Plugin selected)";
this.labelNoPluginSelected.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
//
// labelCaption
//
this.labelCaption.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.labelCaption.Location = new System.Drawing.Point(8, 32);
this.labelCaption.Name = "labelCaption";
this.labelCaption.Size = new System.Drawing.Size(341, 32);
this.labelCaption.TabIndex = 1;
this.labelCaption.Text = "Plugins are programs that extend the functionality of {0}. You can enable and dis" +
"able Plugins using this dialog.";
//
// linkLabelDownloadPlugins
//
this.linkLabelDownloadPlugins.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.linkLabelDownloadPlugins.LinkBehavior = System.Windows.Forms.LinkBehavior.HoverUnderline;
this.linkLabelDownloadPlugins.LinkColor = System.Drawing.SystemColors.HotTrack;
this.linkLabelDownloadPlugins.Location = new System.Drawing.Point(32, 394);
this.linkLabelDownloadPlugins.Name = "linkLabelDownloadPlugins";
this.linkLabelDownloadPlugins.Size = new System.Drawing.Size(316, 15);
this.linkLabelDownloadPlugins.TabIndex = 5;
this.linkLabelDownloadPlugins.TabStop = true;
this.linkLabelDownloadPlugins.Text = "Add a Plugin...";
this.linkLabelDownloadPlugins.AutoSize = true;
//
// pictureBoxAddPlugin
//
this.pictureBoxAddPlugin.Location = new System.Drawing.Point(13, 393);
this.pictureBoxAddPlugin.Name = "pictureBoxAddPlugin";
this.pictureBoxAddPlugin.Size = new System.Drawing.Size(16, 16);
this.pictureBoxAddPlugin.TabIndex = 6;
this.pictureBoxAddPlugin.TabStop = false;
//
// PluginsPreferencesPanel
//
this.Controls.Add(this.pictureBoxAddPlugin);
this.Controls.Add(this.labelCaption);
this.Controls.Add(this.linkLabelDownloadPlugins);
this.Controls.Add(this.groupBoxPluginDetails);
this.Controls.Add(this.labelInstalledPlugins);
this.Controls.Add(this.listViewInstalledPlugins);
this.Name = "PluginsPreferencesPanel";
this.PanelName = "Plugins";
this.Size = new System.Drawing.Size(370, 428);
this.Controls.SetChildIndex(this.listViewInstalledPlugins, 0);
this.Controls.SetChildIndex(this.labelInstalledPlugins, 0);
this.Controls.SetChildIndex(this.groupBoxPluginDetails, 0);
this.Controls.SetChildIndex(this.linkLabelDownloadPlugins, 0);
this.Controls.SetChildIndex(this.labelCaption, 0);
this.Controls.SetChildIndex(this.pictureBoxAddPlugin, 0);
this.groupBoxPluginDetails.ResumeLayout(false);
this.panelPluginDetails.ResumeLayout(false);
this.ResumeLayout(false);
}
#endregion
}
}
| |
//
// TrackActions.cs
//
// Author:
// Gabriel Burt <[email protected]>
//
// Copyright (C) 2007-2008 Novell, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Collections.Generic;
using Mono.Unix;
using Gtk;
using Hyena;
using Hyena.Widgets;
using Banshee.Query;
using Banshee.Sources;
using Banshee.Library;
using Banshee.Playlist;
using Banshee.Collection;
using Banshee.Collection.Database;
using Banshee.ServiceStack;
using Banshee.MediaEngine;
using Banshee.Widgets;
using Banshee.Gui;
using Banshee.Gui.Widgets;
using Hyena.Data;
namespace Banshee.Gui
{
public class TrackActions : BansheeActionGroup
{
private RatingActionProxy selected_tracks_rating_proxy;
private RatingActionProxy playing_track_rating_proxy;
private bool chosen_from_playing_track_submenu;
private static readonly string [] require_selection_actions = new string [] {
// Selected Track(s) >
"SelectedTracksAction", "AddSelectedTracksToPlaylistAction", "RateSelectedTracksAction",
"RemoveSelectedTracksAction", "RemoveTracksFromLibraryAction", "OpenSelectedTracksFolderAction",
"DeleteSelectedTracksFromDriveAction", "SelectedTracksPropertiesAction",
// Others >
"SelectNoneAction", "PlayTrack"
};
private static readonly string [] disable_for_filter_actions = new string [] {
"SelectAllAction", "SelectNoneAction", "SearchMenuAction",
// FIXME should be able to do this, just need to implement it
"RateSelectedTracksAction"
};
private Hyena.Collections.Selection filter_selection = new Hyena.Collections.Selection ();
private bool filter_focused;
public bool FilterFocused {
get { return filter_focused; }
set {
if (filter_focused == value)
return;
filter_focused = value;
if (value) {
Selection = filter_selection;
SuppressSelectActions ();
} else {
Selection = current_source.TrackModel.Selection;
UnsuppressSelectActions ();
}
UpdateActions ();
OnSelectionChanged ();
}
}
public event EventHandler SelectionChanged;
public Hyena.Collections.Selection Selection { get; private set; }
public ModelSelection<TrackInfo> SelectedTracks {
get {
return FilterFocused
? new ModelSelection<TrackInfo> (current_source.TrackModel, Selection)
: current_source.TrackModel.SelectedItems;
}
}
public TrackActions () : base ("Track")
{
Add (new ActionEntry [] {
/*
* Playing Track ActionsEntries
*/
new ActionEntry ("PlayingTrackAction", null,
Catalog.GetString ("Playing Track"), "",
Catalog.GetString ("Options for playing track"),
(o, e) => { ResetRating (); }),
new ActionEntry ("AddPlayingTrackToPlaylistAction", null,
Catalog.GetString ("Add _to Playlist"), "",
Catalog.GetString ("Append playing items to playlist or create new playlist from playing track"),
OnAddPlayingTrackToPlaylistMenu),
new ActionEntry ("RatePlayingTrackAction", null,
String.Empty, null, null, OnRatePlayingTrack),
new ActionEntry ("PlayingTrackEditorAction", Stock.Edit,
Catalog.GetString ("_Edit Track Information"), "E",
Catalog.GetString ("Edit information on playing track"), OnPlayingTrackEditor),
new ActionEntry ("RemovePlayingTrackAction", Stock.Remove,
Catalog.GetString ("_Remove"), "",
Catalog.GetString ("Remove playing track from this source"), OnRemovePlayingTrack),
new ActionEntry ("DeletePlayingTrackFromDriveAction", null,
Catalog.GetString ("_Delete From Drive"), "",
Catalog.GetString ("Permanently delete playing item from medium"), OnDeletePlayingTrackFromDrive),
new ActionEntry ("OpenPlayingTrackFolderAction", null,
Catalog.GetString ("_Open Containing Folder"), "",
Catalog.GetString ("Open the folder that contains playing item"), OnOpenPlayingTrackFolder),
new ActionEntry ("PlayingTrackPropertiesAction", Stock.Properties,
Catalog.GetString ("Properties"), "",
Catalog.GetString ("View information on playing track"), OnPlayingTrackProperties),
/*
* Selected Track(s) ActionEntries
*/
new ActionEntry ("SelectedTracksAction", null,
Catalog.GetString ("Selected Track(s)"), "",
Catalog.GetString ("Options for selected track(s)"),
(o, e) => { ResetRating (); }),
new ActionEntry ("AddSelectedTracksToPlaylistAction", null,
Catalog.GetString ("Add _to Playlist"), "",
Catalog.GetString ("Append selected items to playlist or create new playlist from selection"),
OnAddSelectedTracksToPlaylistMenu),
new ActionEntry ("RateSelectedTracksAction", null,
String.Empty, null, null, OnRateSelectedTracks),
new ActionEntry ("SelectedTracksEditorAction", Stock.Edit,
Catalog.GetString ("_Edit Track Information"), "",
Catalog.GetString ("Edit information on selected tracks"), OnSelectedTracksEditor),
new ActionEntry ("RemoveSelectedTracksAction", Stock.Remove,
Catalog.GetString ("_Remove"), "Delete",
Catalog.GetString ("Remove selected track(s) from this source"), OnRemoveSelectedTracks),
new ActionEntry ("RemoveTracksFromLibraryAction", null,
Catalog.GetString ("Remove From _Library"), "",
Catalog.GetString ("Remove selected track(s) from library"), OnRemoveTracksFromLibrary),
new ActionEntry ("DeleteSelectedTracksFromDriveAction", null,
Catalog.GetString ("_Delete From Drive"), "",
Catalog.GetString ("Permanently delete selected item(s) from medium"), OnDeleteSelectedTracksFromDrive),
new ActionEntry ("OpenSelectedTracksFolderAction", null,
Catalog.GetString ("_Open Containing Folder"), "",
Catalog.GetString ("Open the folder that contains the selected item"), OnOpenSelectedTracksFolder),
new ActionEntry ("SelectedTracksPropertiesAction", Stock.Properties,
Catalog.GetString ("Properties"), "",
Catalog.GetString ("View information on selected tracks"), OnSelectedTracksProperties),
/*
* Others
*/
new ActionEntry ("AddToNewPlaylistAction", Stock.New,
Catalog.GetString ("New Playlist"), null,
Catalog.GetString ("Create new playlist from selected tracks"),
OnAddToNewPlaylist),
new ActionEntry("SelectAllAction", null,
Catalog.GetString("Select _All"), "<control>A",
Catalog.GetString("Select all tracks"), OnSelectAll),
new ActionEntry("SelectNoneAction", null,
Catalog.GetString("Select _None"), "<control><shift>A",
Catalog.GetString("Unselect all tracks"), OnSelectNone),
new ActionEntry("TrackContextMenuAction", null,
String.Empty, null, null, OnTrackContextMenu),
new ActionEntry ("PlayTrack", null,
Catalog.GetString ("_Play"), "",
Catalog.GetString ("Play the selected item"), OnPlayTrack),
new ActionEntry ("SearchMenuAction", Stock.Find,
Catalog.GetString ("_Search"), null,
Catalog.GetString ("Search for items matching certain criteria"), null),
new ActionEntry ("SearchForSameAlbumAction", null,
Catalog.GetString ("By Matching _Album"), "",
Catalog.GetString ("Search all songs of this album"), OnSearchForSameAlbum),
new ActionEntry ("SearchForSameArtistAction", null,
Catalog.GetString ("By Matching A_rtist"), "",
Catalog.GetString ("Search all songs of this artist"), OnSearchForSameArtist),
});
Actions.UIManager.ActionsChanged += HandleActionsChanged;
Actions.GlobalActions["EditMenuAction"].Activated += HandleEditMenuActivated;
ServiceManager.SourceManager.ActiveSourceChanged += HandleActiveSourceChanged;
ServiceManager.PlayerEngine.ConnectEvent (OnPlayerEvent, PlayerEvent.StateChange);
this["AddPlayingTrackToPlaylistAction"].HideIfEmpty = false;
this["AddSelectedTracksToPlaylistAction"].HideIfEmpty = false;
this["PlayTrack"].StockId = Gtk.Stock.MediaPlay;
}
#region State Event Handlers
private ITrackModelSource current_source;
private void HandleActiveSourceChanged (SourceEventArgs args)
{
FilterFocused = false;
if (current_source != null && current_source.TrackModel != null) {
current_source.TrackModel.Reloaded -= OnReloaded;
current_source.TrackModel.Selection.Changed -= HandleSelectionChanged;
current_source = null;
}
ITrackModelSource new_source = ActiveSource as ITrackModelSource;
if (new_source != null) {
new_source.TrackModel.Selection.Changed += HandleSelectionChanged;
new_source.TrackModel.Reloaded += OnReloaded;
current_source = new_source;
Selection = new_source.TrackModel.Selection;
}
ThreadAssist.ProxyToMain (UpdateActions);
}
private void OnReloaded (object sender, EventArgs args)
{
ThreadAssist.ProxyToMain (delegate {
UpdateActions ();
});
}
private void OnPlayerEvent (PlayerEventArgs args)
{
ThreadAssist.ProxyToMain (() => {
UpdateActions ();
});
}
private void HandleActionsChanged (object sender, EventArgs args)
{
if (Actions.UIManager.GetAction ("/MainMenu/EditMenu/SelectedTracks") != null &&
Actions.UIManager.GetAction ("/MainMenu/EditMenu/PlayingTrack") != null) {
selected_tracks_rating_proxy = new RatingActionProxy (Actions.UIManager, this["RateSelectedTracksAction"]);
playing_track_rating_proxy = new RatingActionProxy (Actions.UIManager, this["RatePlayingTrackAction"]);
playing_track_rating_proxy.AddPath ("/MainMenu/EditMenu/PlayingTrack", "AddToPlaylist");
selected_tracks_rating_proxy.AddPath ("/MainMenu/EditMenu/SelectedTracks", "AddToPlaylist");
selected_tracks_rating_proxy.AddPath ("/TrackContextMenu", "AddToPlaylist");
Actions.UIManager.ActionsChanged -= HandleActionsChanged;
}
}
private void HandleSelectionChanged (object sender, EventArgs args)
{
ThreadAssist.ProxyToMain (delegate {
OnSelectionChanged ();
UpdateActions ();
});
}
private void HandleEditMenuActivated (object sender, EventArgs args)
{
// inside the "Edit" menu it's a bit redundant to have a label that starts as "Edit Track..."
this["PlayingTrackEditorAction"].Label = Catalog.GetString ("Track _Information");
this["SelectedTracksEditorAction"].Label = Catalog.GetString ("Track _Information");
if (Selection.Count > 1) {
this ["SelectedTracksAction"].Label = Catalog.GetString ("Selected Tracks");
} else {
this ["SelectedTracksAction"].Label = Catalog.GetString ("Selected Track");
}
}
private void OnSelectionChanged ()
{
EventHandler handler = SelectionChanged;
if (handler != null) {
handler (this, EventArgs.Empty);
}
}
#endregion
#region Utility Methods
private bool select_actions_suppressed = false;
private void SuppressSelectActions ()
{
if (!select_actions_suppressed) {
this ["SelectAllAction"].DisconnectAccelerator ();
this ["SelectNoneAction"].DisconnectAccelerator ();
select_actions_suppressed = true;
}
}
private void UnsuppressSelectActions ()
{
if (select_actions_suppressed) {
this ["SelectAllAction"].ConnectAccelerator ();
this ["SelectNoneAction"].ConnectAccelerator ();
select_actions_suppressed = false;
}
}
public void UpdateActions ()
{
Source source = ServiceManager.SourceManager.ActiveSource;
if (source == null) {
Sensitive = Visible = false;
return;
}
bool in_database = source is DatabaseSource;
PrimarySource primary_source = (source as PrimarySource) ?? (source.Parent as PrimarySource);
var track_source = source as ITrackModelSource;
if (track_source != null) {
if (FilterFocused) {
if (Selection == filter_selection) {
filter_selection.MaxIndex = track_source.TrackModel.Selection.MaxIndex;
filter_selection.Clear (false);
filter_selection.SelectAll ();
} else {
Log.Error (new Exception ("Filter focused, but selection is not filter selection!"));
}
} else {
UpdateActions (true, true, disable_for_filter_actions);
}
var selection = Selection;
var playing_track = ServiceManager.PlayerEngine.CurrentTrack;
var playback_source = ServiceManager.PlaybackController.Source;
var database_source = playback_source as DatabaseSource;
int count = selection.Count;
Sensitive = Visible = true;
bool has_selection = count > 0;
bool has_single_selection = count == 1;
bool is_playing_or_paused = ServiceManager.PlayerEngine.CurrentState == PlayerState.Playing ||
ServiceManager.PlayerEngine.CurrentState == PlayerState.Paused;
bool is_idle = ServiceManager.PlayerEngine.CurrentState == PlayerState.Idle;
foreach (string action in require_selection_actions) {
this[action].Sensitive = has_selection;
}
UpdateActions (source.CanSearch && !FilterFocused, has_single_selection,
"SearchMenuAction", "SearchForSameArtistAction", "SearchForSameAlbumAction"
);
this["SelectAllAction"].Sensitive = track_source.Count > 0 && !selection.AllSelected;
UpdateAction ("PlayingTrackAction", !is_idle && playing_track is DatabaseTrackInfo, is_playing_or_paused, null);
UpdateAction ("AddPlayingTrackToPlaylistAction", source is MusicLibrarySource, is_playing_or_paused, null);
UpdateAction ("RatePlayingTrackAction", database_source != null && database_source.HasEditableTrackProperties, is_playing_or_paused, null);
UpdateAction ("PlayingTrackPropertiesAction", database_source != null && database_source.HasViewableTrackProperties, is_playing_or_paused, source);
UpdateAction ("PlayingTrackEditorAction", database_source != null && database_source.HasEditableTrackProperties, is_playing_or_paused, source);
UpdateAction ("RemovePlayingTrackAction", playback_source.CanRemoveTracks, is_playing_or_paused, source);
UpdateAction ("DeletePlayingTrackFromDriveAction", playback_source.CanDeleteTracks, is_playing_or_paused, source);
UpdateAction ("OpenPlayingTrackFolderAction", playback_source.CanDeleteTracks, is_playing_or_paused, source);
UpdateAction ("SelectedTracksAction", has_selection, has_selection, null);
UpdateAction ("AddSelectedTracksToPlaylistAction", in_database && primary_source != null &&
primary_source.SupportsPlaylists && !primary_source.PlaylistsReadOnly, has_selection, null);
UpdateAction ("RateSelectedTracksAction", source.HasEditableTrackProperties, has_selection, null);
UpdateAction ("SelectedTracksEditorAction", source.HasEditableTrackProperties, has_selection, source);
UpdateAction ("RemoveSelectedTracksAction", track_source.CanRemoveTracks, has_selection, source);
UpdateAction ("RemoveTracksFromLibraryAction", source.Parent is LibrarySource, has_selection, null);
UpdateAction ("DeleteSelectedTracksFromDriveAction", track_source.CanDeleteTracks, has_selection, source);
//if it can delete tracks, most likely it can open their folder
UpdateAction ("OpenSelectedTracksFolderAction", track_source.CanDeleteTracks, has_single_selection, source);
UpdateAction ("SelectedTracksPropertiesAction", source.HasViewableTrackProperties, has_selection, source);
if (primary_source != null &&
!(primary_source is LibrarySource) &&
primary_source.StorageName != null) {
this["DeleteSelectedTracksFromDriveAction"].Label = String.Format (
Catalog.GetString ("_Delete From \"{0}\""), primary_source.StorageName);
this["DeletePlayingTrackFromDriveAction"].Label = String.Format (
Catalog.GetString ("_Delete From \"{0}\""), primary_source.StorageName);
}
if (FilterFocused) {
UpdateActions (false, false, disable_for_filter_actions);
}
} else {
Sensitive = Visible = false;
}
}
private void ResetRating ()
{
if (current_source != null) {
int rating = 0;
// If there is only one track, get the preset rating
if (Selection.Count == 1) {
foreach (TrackInfo track in SelectedTracks) {
rating = track.Rating;
}
}
selected_tracks_rating_proxy.Reset (rating);
var playing_track = ServiceManager.PlayerEngine.CurrentTrack as TrackInfo;
if (playing_track != null) {
rating = playing_track.Rating;
playing_track_rating_proxy.Reset (rating);
}
}
}
#endregion
#region Action Handlers
private void OnSelectAll (object o, EventArgs args)
{
if (current_source != null)
current_source.TrackModel.Selection.SelectAll ();
}
private void OnSelectNone (object o, EventArgs args)
{
if (current_source != null)
current_source.TrackModel.Selection.Clear ();
}
private void OnTrackContextMenu (object o, EventArgs args)
{
ResetRating ();
UpdateActions ();
ShowContextMenu ("/TrackContextMenu");
}
private bool RunSourceOverrideHandler (string sourceOverrideHandler)
{
Source source = current_source as Source;
InvokeHandler handler = source != null
? source.GetInheritedProperty<InvokeHandler> (sourceOverrideHandler)
: null;
if (handler != null) {
handler ();
return true;
}
return false;
}
private void OnPlayingTrackProperties (object o, EventArgs args)
{
var track = ServiceManager.PlayerEngine.CurrentTrack as TrackInfo;
if (track != null && current_source != null && !RunSourceOverrideHandler ("PlayingTrackPropertiesActionHandler")) {
var s = current_source as Source;
var readonly_tabs = s != null && !s.HasEditableTrackProperties;
TrackEditor.TrackEditorDialog.RunView (track, readonly_tabs);
}
}
private void OnSelectedTracksProperties (object o, EventArgs args)
{
if (current_source != null && !RunSourceOverrideHandler ("SelectedTracksPropertiesActionHandler")) {
var s = current_source as Source;
var readonly_tabs = s != null && !s.HasEditableTrackProperties;
TrackEditor.TrackEditorDialog.RunView (current_source.TrackModel, Selection, readonly_tabs);
}
}
private void OnPlayingTrackEditor (object o, EventArgs args)
{
var track = ServiceManager.PlayerEngine.CurrentTrack as TrackInfo;
if (track != null && current_source != null && !RunSourceOverrideHandler ("PlayingTrackEditorActionHandler")) {
TrackEditor.TrackEditorDialog.RunEdit (track);
}
}
private void OnSelectedTracksEditor (object o, EventArgs args)
{
if (current_source != null && !RunSourceOverrideHandler ("SelectedTracksEditorActionHandler")) {
TrackEditor.TrackEditorDialog.RunEdit (current_source.TrackModel, Selection);
}
}
private void OnPlayTrack (object o, EventArgs args)
{
var source = ServiceManager.SourceManager.ActiveSource as ITrackModelSource;
if (source != null) {
var track = source.TrackModel [FilterFocused ? 0 : source.TrackModel.Selection.FocusedIndex];
if (track.HasAttribute (TrackMediaAttributes.ExternalResource)) {
System.Diagnostics.Process.Start (track.Uri);
} else {
ServiceManager.PlaybackController.Source = source;
ServiceManager.PlayerEngine.OpenPlay (track);
}
}
}
// TODO This function works only for music library source now
// but it should act on a source where a track is playing.
private void OnAddPlayingTrackToPlaylistMenu (object o, EventArgs args)
{
List<Source> children;
chosen_from_playing_track_submenu = true;
lock (ServiceManager.SourceManager.MusicLibrary.Children) {
children = new List<Source> (ServiceManager.SourceManager.MusicLibrary.Children);
}
OnAddToPlaylistMenu (o, children);
}
private void OnAddSelectedTracksToPlaylistMenu (object o, EventArgs args)
{
List<Source> children;
chosen_from_playing_track_submenu = false;
lock (ActivePrimarySource.Children) {
children = new List<Source> (ActivePrimarySource.Children);
}
OnAddToPlaylistMenu (o, children);
}
// Called when the Add to Playlist action is highlighted.
// Generates the menu of playlists to which you can add the selected tracks.
private void OnAddToPlaylistMenu (object o, List<Source> children)
{
Source active_source = ServiceManager.SourceManager.ActiveSource;
// TODO find just the menu that was activated instead of modifying all proxies
foreach (Widget proxy_widget in ((Gtk.Action)o).Proxies) {
MenuItem menu = proxy_widget as MenuItem;
if (menu == null)
continue;
Menu submenu = new Menu ();
menu.Submenu = submenu;
submenu.Append (this ["AddToNewPlaylistAction"].CreateMenuItem ());
bool separator_added = false;
foreach (Source child in children) {
PlaylistSource playlist = child as PlaylistSource;
if (playlist != null) {
if (!separator_added) {
submenu.Append (new SeparatorMenuItem ());
separator_added = true;
}
PlaylistMenuItem item = new PlaylistMenuItem (playlist);
item.Image = new Gtk.Image ("playlist-source", IconSize.Menu);
item.Activated += OnAddToExistingPlaylist;
item.Sensitive = playlist != active_source;
submenu.Append (item);
}
}
submenu.ShowAll ();
}
}
private void OnAddToNewPlaylist (object o, EventArgs args)
{
// TODO generate name based on the track selection, or begin editing it
PlaylistSource playlist = new PlaylistSource (Catalog.GetString ("New Playlist"), ActivePrimarySource);
playlist.Save ();
playlist.PrimarySource.AddChildSource (playlist);
AddToPlaylist (playlist);
}
private void OnAddToExistingPlaylist (object o, EventArgs args)
{
AddToPlaylist (((PlaylistMenuItem)o).Playlist);
}
private void AddToPlaylist (PlaylistSource playlist)
{
if (!FilterFocused) {
var track = ServiceManager.PlayerEngine.CurrentTrack as DatabaseTrackInfo;
if (chosen_from_playing_track_submenu && track != null) {
playlist.AddTrack (track);
} else {
playlist.AddSelectedTracks (ActiveSource);
}
} else {
playlist.AddAllTracks (ActiveSource);
}
}
private void OnRemovePlayingTrack (object o, EventArgs args)
{
var playback_src = ServiceManager.PlaybackController.Source as DatabaseSource;
var track = ServiceManager.PlayerEngine.CurrentTrack as DatabaseTrackInfo;
if (playback_src != null && track != null) {
if (!ConfirmRemove (playback_src, false, 1)) {
return;
}
if (playback_src != null && playback_src.CanRemoveTracks) {
playback_src.RemoveTrack (track);
}
}
}
private void OnRemoveSelectedTracks (object o, EventArgs args)
{
ITrackModelSource source = ActiveSource as ITrackModelSource;
if (!ConfirmRemove (source, false, Selection.Count))
return;
if (source != null && source.CanRemoveTracks) {
source.RemoveTracks (Selection);
}
}
private void OnRemoveTracksFromLibrary (object o, EventArgs args)
{
ITrackModelSource source = ActiveSource as ITrackModelSource;
if (source != null) {
LibrarySource library = source.Parent as LibrarySource;
if (library != null) {
if (!ConfirmRemove (library, false, Selection.Count)) {
return;
}
ThreadAssist.SpawnFromMain (delegate {
library.RemoveTracks (source.TrackModel as DatabaseTrackListModel, Selection);
});
}
}
}
private void OnOpenPlayingTrackFolder (object o, EventArgs args)
{
var track = ServiceManager.PlayerEngine.CurrentTrack as TrackInfo;
if (track != null) {
var path = System.IO.Path.GetDirectoryName (track.Uri.AbsolutePath);
OpenContainingFolder (path);
}
}
private void OnOpenSelectedTracksFolder (object o, EventArgs args)
{
var source = ActiveSource as ITrackModelSource;
if (source == null || source.TrackModel == null)
return;
var items = SelectedTracks;
if (items == null || items.Count != 1) {
Log.Error ("Could not open containing folder");
return;
}
foreach (var track in items) {
var path = System.IO.Path.GetDirectoryName (track.Uri.AbsolutePath);
OpenContainingFolder (path);
}
}
private void OpenContainingFolder (String path)
{
if (Banshee.IO.Directory.Exists (path)) {
System.Diagnostics.Process.Start (path);
return;
}
var md = new HigMessageDialog (
ServiceManager.Get<GtkElementsService> ().PrimaryWindow,
DialogFlags.DestroyWithParent, MessageType.Warning,
ButtonsType.None, Catalog.GetString ("The folder could not be found."),
Catalog.GetString ("Please check that the track's location is accessible by the system.")
);
md.AddButton ("gtk-ok", ResponseType.Ok, true);
try {
md.Run ();
} finally {
md.Destroy ();
}
}
private void OnDeletePlayingTrackFromDrive (object o, EventArgs args)
{
var playback_src = ServiceManager.PlaybackController.Source as DatabaseSource;
var track = ServiceManager.PlayerEngine.CurrentTrack as DatabaseTrackInfo;
if (playback_src != null && track != null) {
if (!ConfirmRemove (playback_src, true, 1)) {
return;
}
if (playback_src != null && playback_src.CanDeleteTracks) {
var selection = new Hyena.Collections.Selection ();
selection.Select (playback_src.TrackModel.IndexOf (track));
playback_src.DeleteTracks (selection);
}
}
}
private void OnDeleteSelectedTracksFromDrive (object o, EventArgs args)
{
ITrackModelSource source = ActiveSource as ITrackModelSource;
if (!ConfirmRemove (source, true, Selection.Count))
return;
if (source != null && source.CanDeleteTracks) {
source.DeleteTracks (Selection);
}
}
// FIXME filter
private void OnRateSelectedTracks (object o, EventArgs args)
{
ThreadAssist.SpawnFromMain (delegate {
((DatabaseSource)ActiveSource).RateSelectedTracks (selected_tracks_rating_proxy.LastRating);
});
}
private void OnRatePlayingTrack (object o, EventArgs args)
{
var track = ServiceManager.PlayerEngine.CurrentTrack as DatabaseTrackInfo;
if (track != null) {
track.SavedRating = playing_track_rating_proxy.LastRating;
}
}
private void OnSearchForSameArtist (object o, EventArgs args)
{
if (current_source != null) {
foreach (TrackInfo track in current_source.TrackModel.SelectedItems) {
if (!String.IsNullOrEmpty (track.ArtistName)) {
ActiveSource.FilterQuery = BansheeQuery.ArtistField.ToTermString (":", track.ArtistName);
}
break;
}
}
}
private void OnSearchForSameAlbum (object o, EventArgs args)
{
if (current_source != null) {
foreach (TrackInfo track in current_source.TrackModel.SelectedItems) {
if (!String.IsNullOrEmpty (track.AlbumTitle)) {
ActiveSource.FilterQuery = BansheeQuery.AlbumField.ToTermString (":", track.AlbumTitle);
}
break;
}
}
}
#endregion
private static bool ConfirmRemove (ITrackModelSource source, bool delete, int selCount)
{
if (!source.ConfirmRemoveTracks) {
return true;
}
bool ret = false;
string header = null;
string message = null;
string button_label = null;
if (delete) {
header = String.Format (
Catalog.GetPluralString (
"Are you sure you want to permanently delete this item?",
"Are you sure you want to permanently delete the selected {0} items?", selCount
), selCount
);
message = Catalog.GetString ("If you delete the selection, it will be permanently lost.");
button_label = "gtk-delete";
} else {
header = String.Format (Catalog.GetString ("Remove selection from {0}?"), source.Name);
message = String.Format (
Catalog.GetPluralString (
"Are you sure you want to remove the selected item from your {1}?",
"Are you sure you want to remove the selected {0} items from your {1}?", selCount
), selCount, source.GenericName
);
button_label = "gtk-remove";
}
HigMessageDialog md = new HigMessageDialog (
ServiceManager.Get<GtkElementsService> ().PrimaryWindow,
DialogFlags.DestroyWithParent, delete ? MessageType.Warning : MessageType.Question,
ButtonsType.None, header, message
);
// Delete from Disk defaults to Cancel and the others to OK/Confirm.
md.AddButton ("gtk-cancel", ResponseType.No, delete);
md.AddButton (button_label, ResponseType.Yes, !delete);
try {
if (md.Run () == (int) ResponseType.Yes) {
ret = true;
}
} finally {
md.Destroy ();
}
return ret;
}
public static bool ConfirmRemove (string header)
{
string message = Catalog.GetString ("Are you sure you want to continue?");
bool remove_tracks = false;
ThreadAssist.BlockingProxyToMain (() => {
var md = new HigMessageDialog (
ServiceManager.Get<GtkElementsService> ().PrimaryWindow,
DialogFlags.DestroyWithParent, MessageType.Warning,
ButtonsType.None, header, message
);
md.AddButton ("gtk-cancel", ResponseType.No, true);
md.AddButton (Catalog.GetString ("Remove tracks"), ResponseType.Yes, false);
try {
if (md.Run () == (int) ResponseType.Yes) {
remove_tracks = true;
}
} finally {
md.Destroy ();
}
});
return remove_tracks;
}
}
}
| |
//
// Copyright (c) 2004-2018 Jaroslaw Kowalski <[email protected]>, Kim Christensen, Julian Verdurmen
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of Jaroslaw Kowalski nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
namespace NLog.UnitTests
{
using System;
using System.IO;
using System.Threading;
using System.Reflection;
using NLog.Config;
using Xunit;
public class LogFactoryTests : NLogTestBase
{
[Fact]
public void Flush_DoNotThrowExceptionsAndTimeout_DoesNotThrow()
{
LogManager.Configuration = CreateConfigurationFromString(@"
<nlog throwExceptions='false'>
<targets><target type='MethodCall' name='test' methodName='Throws' className='NLog.UnitTests.LogFactoryTests, NLog.UnitTests.netfx40' /></targets>
<rules>
<logger name='*' minlevel='Debug' writeto='test'></logger>
</rules>
</nlog>");
ILogger logger = LogManager.GetCurrentClassLogger();
logger.Factory.Flush(_ => { }, TimeSpan.FromMilliseconds(1));
}
[Fact]
public void InvalidXMLConfiguration_DoesNotThrowErrorWhen_ThrowExceptionFlagIsNotSet()
{
LogManager.ThrowExceptions = false;
LogManager.Configuration = CreateConfigurationFromString(@"
<nlog internalLogIncludeTimestamp='IamNotBooleanValue'>
<targets><target type='MethodCall' name='test' methodName='Throws' className='NLog.UnitTests.LogFactoryTests, NLog.UnitTests.netfx40' /></targets>
<rules>
<logger name='*' minlevel='Debug' writeto='test'></logger>
</rules>
</nlog>");
}
[Fact]
public void InvalidXMLConfiguration_ThrowErrorWhen_ThrowExceptionFlagIsSet()
{
Boolean ExceptionThrown = false;
try
{
LogManager.ThrowExceptions = true;
LogManager.Configuration = CreateConfigurationFromString(@"
<nlog internalLogIncludeTimestamp='IamNotBooleanValue'>
<targets><target type='MethodCall' name='test' methodName='Throws' className='NLog.UnitTests.LogFactoryTests, NLog.UnitTests.netfx40' /></targets>
<rules>
<logger name='*' minlevel='Debug' writeto='test'></logger>
</rules>
</nlog>");
}
catch (Exception)
{
ExceptionThrown = true;
}
Assert.True(ExceptionThrown);
}
[Fact]
public void SecondaryLogFactoryDoesNotTakePrimaryLogFactoryLock()
{
File.WriteAllText("NLog.config", "<nlog />");
try
{
bool threadTerminated;
var primaryLogFactory = LogManager.factory;
var primaryLogFactoryLock = primaryLogFactory._syncRoot;
// Simulate a potential deadlock.
// If the creation of the new LogFactory takes the lock of the global LogFactory, the thread will deadlock.
lock (primaryLogFactoryLock)
{
var thread = new Thread(() =>
{
(new LogFactory()).GetCurrentClassLogger();
});
thread.Start();
threadTerminated = thread.Join(TimeSpan.FromSeconds(1));
}
Assert.True(threadTerminated);
}
finally
{
try
{
File.Delete("NLog.config");
}
catch { }
}
}
[Fact]
public void ReloadConfigOnTimer_DoesNotThrowConfigException_IfConfigChangedInBetween()
{
EventHandler<LoggingConfigurationChangedEventArgs> testChanged = null;
try
{
LogManager.Configuration = null;
var loggingConfiguration = new LoggingConfiguration();
LogManager.Configuration = loggingConfiguration;
var logFactory = new LogFactory(loggingConfiguration);
var differentConfiguration = new LoggingConfiguration();
// Verify that the random configuration change is ignored (Only the final reset is reacted upon)
bool called = false;
LoggingConfiguration oldConfiguration = null, newConfiguration = null;
testChanged = (s, e) => { called = true; oldConfiguration = e.DeactivatedConfiguration; newConfiguration = e.ActivatedConfiguration; };
LogManager.LogFactory.ConfigurationChanged += testChanged;
var exRecorded = Record.Exception(() => logFactory.ReloadConfigOnTimer(differentConfiguration));
Assert.Null(exRecorded);
// Final reset clears the configuration, so it is changed to null
LogManager.Configuration = null;
Assert.True(called);
Assert.Equal(loggingConfiguration, oldConfiguration);
Assert.Null(newConfiguration);
}
finally
{
if (testChanged != null)
LogManager.LogFactory.ConfigurationChanged -= testChanged;
}
}
private class ReloadNullConfiguration : LoggingConfiguration
{
public override LoggingConfiguration Reload()
{
return null;
}
}
[Fact]
public void ReloadConfigOnTimer_DoesNotThrowConfigException_IfConfigReloadReturnsNull()
{
var loggingConfiguration = new ReloadNullConfiguration();
LogManager.Configuration = loggingConfiguration;
var logFactory = new LogFactory(loggingConfiguration);
var exRecorded = Record.Exception(() => logFactory.ReloadConfigOnTimer(loggingConfiguration));
Assert.Null(exRecorded);
}
[Fact]
public void ReloadConfigOnTimer_Raises_ConfigurationReloadedEvent()
{
var called = false;
var loggingConfiguration = new LoggingConfiguration();
LogManager.Configuration = loggingConfiguration;
var logFactory = new LogFactory(loggingConfiguration);
logFactory.ConfigurationReloaded += (sender, args) => { called = true; };
logFactory.ReloadConfigOnTimer(loggingConfiguration);
Assert.True(called);
}
[Fact]
public void ReloadConfigOnTimer_When_No_Exception_Raises_ConfigurationReloadedEvent_With_Correct_Sender()
{
object calledBy = null;
var loggingConfiguration = new LoggingConfiguration();
LogManager.Configuration = loggingConfiguration;
var logFactory = new LogFactory(loggingConfiguration);
logFactory.ConfigurationReloaded += (sender, args) => { calledBy = sender; };
logFactory.ReloadConfigOnTimer(loggingConfiguration);
Assert.Same(calledBy, logFactory);
}
[Fact]
public void ReloadConfigOnTimer_When_No_Exception_Raises_ConfigurationReloadedEvent_With_Argument_Indicating_Success()
{
LoggingConfigurationReloadedEventArgs arguments = null;
var loggingConfiguration = new LoggingConfiguration();
LogManager.Configuration = loggingConfiguration;
var logFactory = new LogFactory(loggingConfiguration);
logFactory.ConfigurationReloaded += (sender, args) => { arguments = args; };
logFactory.ReloadConfigOnTimer(loggingConfiguration);
Assert.True(arguments.Succeeded);
}
/// <summary>
/// We should be forward compatible so that we can add easily attributes in the future.
/// </summary>
[Fact]
public void NewAttrOnNLogLevelShouldNotThrowError()
{
LogManager.Configuration = CreateConfigurationFromString(@"
<nlog throwExceptions='true' imAnewAttribute='noError'>
<targets><target type='file' name='f1' filename='test.log' /></targets>
<rules>
<logger name='*' minlevel='Debug' writeto='f1'></logger>
</rules>
</nlog>");
}
[Fact]
public void ValueWithVariableMustNotCauseInfiniteRecursion()
{
LogManager.Configuration = null;
var filename = "NLog.config";
File.WriteAllText(filename, @"
<nlog>
<variable name='dir' value='c:\mylogs' />
<targets>
<target name='f' type='file' fileName='${var:dir}\test.log' />
</targets>
<rules>
<logger name='*' writeTo='f' />
</rules>
</nlog>");
try
{
var x = LogManager.Configuration;
//2nd call
var config = new XmlLoggingConfiguration(filename);
}
finally
{
File.Delete(filename);
}
}
[Fact]
public void EnableAndDisableLogging()
{
LogFactory factory = new LogFactory();
#pragma warning disable 618
// In order Suspend => Resume
Assert.True(factory.IsLoggingEnabled());
factory.DisableLogging();
Assert.False(factory.IsLoggingEnabled());
factory.EnableLogging();
Assert.True(factory.IsLoggingEnabled());
#pragma warning restore 618
}
[Fact]
public void SuspendAndResumeLogging_InOrder()
{
LogFactory factory = new LogFactory();
// In order Suspend => Resume [Case 1]
Assert.True(factory.IsLoggingEnabled());
factory.SuspendLogging();
Assert.False(factory.IsLoggingEnabled());
factory.ResumeLogging();
Assert.True(factory.IsLoggingEnabled());
// In order Suspend => Resume [Case 2]
using (var factory2 = new LogFactory())
{
Assert.True(factory.IsLoggingEnabled());
factory.SuspendLogging();
Assert.False(factory.IsLoggingEnabled());
factory.ResumeLogging();
Assert.True(factory.IsLoggingEnabled());
}
}
[Fact]
public void SuspendAndResumeLogging_OutOfOrder()
{
LogFactory factory = new LogFactory();
// Out of order Resume => Suspend => (Suspend => Resume)
factory.ResumeLogging();
Assert.True(factory.IsLoggingEnabled());
factory.SuspendLogging();
Assert.True(factory.IsLoggingEnabled());
factory.SuspendLogging();
Assert.False(factory.IsLoggingEnabled());
factory.ResumeLogging();
Assert.True(factory.IsLoggingEnabled());
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using FluentAssertions;
using NSubstitute;
using Toggl.Core.Extensions;
using Toggl.Core.Interactors;
using Toggl.Core.Tests.Generators;
using Toggl.Core.Tests.TestExtensions;
using Toggl.Networking.Models.Calendar;
using Toggl.Shared.Models.Calendar;
using Xunit;
namespace Toggl.Core.Tests.Interactors.ExternalCalendars
{
public class PullExternalCalendarEventsInteractorTests
{
public abstract class PullExternalCalendarEventsInteractorBaseTest : BaseInteractorTests
{
protected ICalendarIntegration Integration = new CalendarIntegration
{
Id = 42,
};
protected IExternalCalendar Calendar = new ExternalCalendar
{
SyncId = "Calendar-0",
Name = "Memes",
};
public PullExternalCalendarEventsInteractorBaseTest()
{
TimeService.Now().Returns(new DateTimeOffset(2020, 7, 24, 15, 46, 0, TimeSpan.Zero));
}
}
public sealed class TheConstructor : PullExternalCalendarEventsInteractorBaseTest
{
[Theory, LogIfTooSlow]
[ConstructorData]
public void ThrowsIfAnyOfTheArgumentsIsNull(bool useApi, bool useTimeService, bool hasIntegration,
bool hasCalendar)
{
var theApi = useApi ? Api : null;
var theTimeService = useTimeService ? TimeService : null;
var theIntegration = hasIntegration ? Integration : null;
var theCalendar = hasCalendar ? Calendar : null;
Action tryingToConstructWithNull = () =>
new PullExternalCalendarEventsInteractor(theApi, theTimeService, theIntegration, theCalendar);
tryingToConstructWithNull.Should().Throw<ArgumentNullException>();
}
}
public sealed class TheExecuteMethod : PullExternalCalendarEventsInteractorBaseTest
{
public sealed class WhenItHasASinglePage : PullExternalCalendarEventsInteractorBaseTest
{
private IExternalCalendarEventsPage page = new ExternalCalendarEventsPage
{
Events = new List<IExternalCalendarEvent>
{
new ExternalCalendarEvent
{
SyncId = "0",
ICalId = "0",
Title = "Memes Meeting",
StartTime = new DateTimeOffset(2020, 7, 24, 15, 46, 0, TimeSpan.Zero),
EndTime = new DateTimeOffset(2020, 7, 24, 15, 46, 0, TimeSpan.Zero),
Updated = new DateTimeOffset(2020, 7, 24, 15, 46, 0, TimeSpan.Zero),
BackgroundColor = "#ffffff",
ForegroundColor = "#000000",
},
new ExternalCalendarEvent
{
SyncId = "1",
ICalId = "1",
Title = "Memes Meeting",
StartTime = new DateTimeOffset(2020, 7, 24, 15, 46, 0, TimeSpan.Zero),
EndTime = new DateTimeOffset(2020, 7, 24, 15, 46, 0, TimeSpan.Zero),
Updated = new DateTimeOffset(2020, 7, 24, 15, 46, 0, TimeSpan.Zero),
BackgroundColor = "#ffffff",
ForegroundColor = "#000000",
},
},
NextPageToken = null,
};
[Fact, LogIfTooSlow]
public async Task ItReturnsTheExpectedEvents()
{
Api.ExternalCalendars.GetCalendarEvents(
Integration.Id,
Calendar.SyncId,
Arg.Any<DateTimeOffset>(),
Arg.Any<DateTimeOffset>(),
Arg.Any<string>(), Arg.Any<long?>()).Returns(page);
var interactor = new PullExternalCalendarEventsInteractor(Api, TimeService, Integration, Calendar);
var actual = await interactor.Execute();
actual.Should().BeEquivalentTo(page.Events);
}
}
public sealed class WhenItHasMultiplePages : PullExternalCalendarEventsInteractorBaseTest
{
private IExternalCalendarEventsPage firstPage = new ExternalCalendarEventsPage
{
Events = new List<IExternalCalendarEvent>
{
new ExternalCalendarEvent
{
SyncId = "0",
ICalId = "0",
Title = "Memes Meeting",
StartTime = new DateTimeOffset(2020, 7, 24, 15, 46, 0, TimeSpan.Zero),
EndTime = new DateTimeOffset(2020, 7, 24, 15, 46, 0, TimeSpan.Zero),
Updated = new DateTimeOffset(2020, 7, 24, 15, 46, 0, TimeSpan.Zero),
BackgroundColor = "#ffffff",
ForegroundColor = "#000000",
},
new ExternalCalendarEvent
{
SyncId = "1",
ICalId = "1",
Title = "Memes Meeting",
StartTime = new DateTimeOffset(2020, 7, 24, 15, 46, 0, TimeSpan.Zero),
EndTime = new DateTimeOffset(2020, 7, 24, 15, 46, 0, TimeSpan.Zero),
Updated = new DateTimeOffset(2020, 7, 24, 15, 46, 0, TimeSpan.Zero),
BackgroundColor = "#ffffff",
ForegroundColor = "#000000",
},
},
NextPageToken = "next_page_token",
};
private IExternalCalendarEventsPage secondPage = new ExternalCalendarEventsPage
{
Events = new List<IExternalCalendarEvent>
{
new ExternalCalendarEvent
{
SyncId = "3",
ICalId = "0",
Title = "Memes Meeting",
StartTime = new DateTimeOffset(2020, 7, 24, 15, 46, 0, TimeSpan.Zero),
EndTime = new DateTimeOffset(2020, 7, 24, 15, 46, 0, TimeSpan.Zero),
Updated = new DateTimeOffset(2020, 7, 24, 15, 46, 0, TimeSpan.Zero),
BackgroundColor = "#ffffff",
ForegroundColor = "#000000",
},
},
NextPageToken = null,
};
[Fact, LogIfTooSlow]
public async Task ItReturnsTheExpectedEvents()
{
Api.ExternalCalendars.GetCalendarEvents(
Integration.Id,
Calendar.SyncId,
Arg.Any<DateTimeOffset>(),
Arg.Any<DateTimeOffset>(),
null, Arg.Any<long?>()).Returns(firstPage);
Api.ExternalCalendars.GetCalendarEvents(
Integration.Id,
Calendar.SyncId,
Arg.Any<DateTimeOffset>(),
Arg.Any<DateTimeOffset>(),
"next_page_token", Arg.Any<long?>()).Returns(secondPage);
var interactor = new PullExternalCalendarEventsInteractor(Api, TimeService, Integration, Calendar);
var actual = await interactor.Execute();
var expected = firstPage.Events.Concat(secondPage.Events);
actual.Should().BeEquivalentTo(expected);
}
}
public sealed class WhenItFailsImmediately : PullExternalCalendarEventsInteractorBaseTest
{
[Fact, LogIfTooSlow]
public async Task ItThrows()
{
Api.ExternalCalendars.GetCalendarEvents(
Integration.Id,
Calendar.SyncId,
Arg.Any<DateTimeOffset>(),
Arg.Any<DateTimeOffset>(),
null, Arg.Any<long?>())
.ReturnsThrowingTaskOf(new Exception("Something bad happened"));
var interactor = new PullExternalCalendarEventsInteractor(Api, TimeService, Integration, Calendar);
Action tryingToExecute = () =>
interactor.Execute().Wait();
tryingToExecute.Should().Throw<Exception>();
}
}
public sealed class WhenItFailsAfterSomePageWasFetched : PullExternalCalendarEventsInteractorBaseTest
{
private IExternalCalendarEventsPage page = new ExternalCalendarEventsPage
{
Events = new List<IExternalCalendarEvent>
{
new ExternalCalendarEvent
{
SyncId = "0",
ICalId = "0",
Title = "Memes Meeting",
StartTime = new DateTimeOffset(2020, 7, 24, 15, 46, 0, TimeSpan.Zero),
EndTime = new DateTimeOffset(2020, 7, 24, 15, 46, 0, TimeSpan.Zero),
Updated = new DateTimeOffset(2020, 7, 24, 15, 46, 0, TimeSpan.Zero),
BackgroundColor = "#ffffff",
ForegroundColor = "#000000",
},
},
NextPageToken = "next_page_token",
};
[Fact, LogIfTooSlow]
public async Task ItThrows()
{
Api.ExternalCalendars.GetCalendarEvents(
Integration.Id,
Calendar.SyncId,
Arg.Any<DateTimeOffset>(),
Arg.Any<DateTimeOffset>(),
null, Arg.Any<long?>()).Returns(page);
Api.ExternalCalendars.GetCalendarEvents(
Integration.Id,
Calendar.SyncId,
Arg.Any<DateTimeOffset>(),
Arg.Any<DateTimeOffset>(),
null, Arg.Any<long?>())
.ReturnsThrowingTaskOf(new Exception("Something bad happened"));
var interactor = new PullExternalCalendarEventsInteractor(Api, TimeService, Integration, Calendar);
Action tryingToExecute = () =>
interactor.Execute().Wait();
tryingToExecute.Should().Throw<Exception>();
}
}
}
}
}
| |
using System;
using System.Globalization;
using OpenTK.Mathematics;
namespace Bearded.Utilities.SpaceTime;
/// <summary>
/// A type-safe representation of a 3d directed velocity vector.
/// </summary>
public readonly struct Velocity3 : IEquatable<Velocity3>, IFormattable
{
private readonly Vector3 value;
#region construction
public Velocity3(Vector3 value)
{
this.value = value;
}
public Velocity3(float x, float y, float z)
: this(new Vector3(x, y, z))
{
}
public Velocity3(Speed x, Speed y, Speed z)
: this(new Vector3(x.NumericValue, y.NumericValue, z.NumericValue))
{
}
#endregion
#region properties
/// <summary>
/// Returns the numeric vector value of the velocity vector.
/// </summary>
public Vector3 NumericValue => value;
/// <summary>
/// Returns the X component of the velocity vector.
/// </summary>
public Speed X => new Speed(value.X);
/// <summary>
/// Returns the Y component of the velocity vector.
/// </summary>
public Speed Y => new Speed(value.Y);
/// <summary>
/// Returns the Z component of the velocity vector.
/// </summary>
public Speed Z => new Speed(value.Z);
/// <summary>
/// Returns the typed magnitude of the velocity vector.
/// </summary>
public Speed Length => new Speed(value.Length);
/// <summary>
/// Returns the typed square of the magnitude of the velocity vector.
/// </summary>
public Squared<Speed> LengthSquared => new Squared<Speed>(value.LengthSquared);
/// <summary>
/// Returns a Velocity3 type with value 0.
/// </summary>
public static Velocity3 Zero => new Velocity3(0, 0, 0);
#endregion
#region methods
#region lerp
/// <summary>
/// Linearly interpolates between two typed velocity vectors.
/// </summary>
/// <param name="v0">The velocity vector at t = 0.</param>
/// <param name="v1">The velocity vector at t = 1.</param>
/// <param name="t">The interpolation scalar.</param>
public static Velocity3 Lerp(Velocity3 v0, Velocity3 v1, float t) => v0 + (v1 - v0) * t;
/// <summary>
/// Linearly interpolates towards another typed velocity vector.
/// </summary>
/// <param name="v">The velocity vector at t = 1.</param>
/// <param name="t">The interpolation scalar.</param>
public Velocity3 LerpTo(Velocity3 v, float t) => Lerp(this, v, t);
#endregion
#region projection
/// <summary>
/// Projects the velocity vector onto an untyped vector, returning the speed component in that vector's direction.
/// </summary>
public Speed ProjectedOn(Vector3 vector) => projectedOn(vector.NormalizedSafe());
/// <summary>
/// Projects the velocity vector onto a difference vector, returning the speed component in that vector's direction.
/// </summary>
public Speed ProjectedOn(Difference3 vector) => projectedOn(vector.NumericValue.NormalizedSafe());
private Speed projectedOn(Vector3 normalisedVector) => new Speed(Vector3.Dot(value, normalisedVector));
#endregion
#region equality and hashcode
public bool Equals(Velocity3 other) => value == other.value;
public override bool Equals(object? obj) => obj is Velocity3 v && Equals(v);
public override int GetHashCode() => value.GetHashCode();
#endregion
#region tostring
public override string ToString() => ToString(null, CultureInfo.CurrentCulture);
public string ToString(string? format, IFormatProvider? formatProvider) => "(" +
$"{value.X.ToString(format, formatProvider)}, " +
$"{value.Y.ToString(format, formatProvider)}, " +
$"{value.Z.ToString(format, formatProvider)}) u/t";
public string ToString(string? format)
=> ToString(format, CultureInfo.CurrentCulture);
#endregion
#endregion
#region operators
#region algebra
/// <summary>
/// Adds two velocity vectors.
/// </summary>
public static Velocity3 operator +(Velocity3 v0, Velocity3 v1) => new Velocity3(v0.value + v1.value);
/// <summary>
/// Subtracts a velocity vector from another.
/// </summary>
public static Velocity3 operator -(Velocity3 v0, Velocity3 v1) => new Velocity3(v0.value - v1.value);
#endregion
#region scaling
/// <summary>
/// Inverts the velocity vector.
/// </summary>
public static Velocity3 operator -(Velocity3 v) => new Velocity3(-v.value);
/// <summary>
/// Multiplies the velocity vector with a scalar.
/// </summary>
public static Velocity3 operator *(Velocity3 v, float scalar) => new Velocity3(v.value * scalar);
/// <summary>
/// Multiplies the velocity vector with a scalar.
/// </summary>
public static Velocity3 operator *(float scalar, Velocity3 v) => new Velocity3(v.value * scalar);
/// <summary>
/// Divides the velocity vector by a divisor.
/// </summary>
public static Velocity3 operator /(Velocity3 v, float divisor) => new Velocity3(v.value / divisor);
#endregion
#region ratio
/// <summary>
/// Divides a velocity vector by a speed, returning an untyped vector.
/// </summary>
public static Vector3 operator /(Velocity3 v, Speed divisor) => v.value / divisor.NumericValue;
#endregion
#region differentiate
/// <summary>
/// Divides a velocity vector by a timespan, returning an acceleration vector.
/// </summary>
public static Acceleration3 operator /(Velocity3 v, TimeSpan t) =>
new Acceleration3(v.value / (float)t.NumericValue);
public static Acceleration3 operator *(Velocity3 v, Frequency f) =>
new Acceleration3(v.value * (float)f.NumericValue);
public static Acceleration3 operator *(Frequency f, Velocity3 v) =>
new Acceleration3(v.value * (float)f.NumericValue);
#endregion
#region integrate
/// <summary>
/// Multiplies a velocity vector by a timespan, returning a difference vector.
/// </summary>
public static Difference3 operator *(Velocity3 v, TimeSpan t) =>
new Difference3(v.value * (float)t.NumericValue);
/// <summary>
/// Multiplies a velocity vector by a timespan, returning a difference vector.
/// </summary>
public static Difference3 operator *(TimeSpan t, Velocity3 v) =>
new Difference3(v.value * (float)t.NumericValue);
public static Difference3 operator /(Velocity3 v, Frequency f) =>
new Difference3(v.value / (float)f.NumericValue);
#endregion
#region comparison
/// <summary>
/// Compares two velocity vectors for equality.
/// </summary>
public static bool operator ==(Velocity3 v0, Velocity3 v1) => v0.Equals(v1);
/// <summary>
/// Compares two velocity vectors for inequality.
/// </summary>
public static bool operator !=(Velocity3 v0, Velocity3 v1) => !(v0 == v1);
#endregion
#endregion
}
| |
using MatterHackers.Agg.VertexSource;
using MatterHackers.VectorMath;
//----------------------------------------------------------------------------
// Anti-Grain Geometry - Version 2.4
// Copyright (C) 2002-2005 Maxim Shemanarev (http://www.antigrain.com)
//
// Permission to copy, use, modify, sell and distribute this software
// is granted provided this copyright notice appears in all copies.
// This software is provided "as is" without express or implied
// warranty, and with no claim as to its suitability for any purpose.
//
//----------------------------------------------------------------------------
// Contact: [email protected]
// [email protected]
// http://www.antigrain.com
//----------------------------------------------------------------------------
//
// class gamma_ctrl
//
//----------------------------------------------------------------------------
using System;
using System.Collections.Generic;
namespace MatterHackers.Agg.UI
{
//------------------------------------------------------------------------
// Class that can be used to create an interactive control to set up
// gamma arrays.
//------------------------------------------------------------------------
public class gamma_ctrl : SimpleVertexSourceWidget
{
private gamma_spline m_gamma_spline = new gamma_spline();
private double m_border_width;
private double m_border_extra;
private double m_curve_width;
private double m_grid_width;
private double m_text_thickness;
private double m_point_size;
private double m_text_height;
private double m_xc1;
private double m_yc1;
private double m_xc2;
private double m_yc2;
private double m_xs1;
private double m_ys1;
private double m_xs2;
private double m_ys2;
private double m_xt1;
private double m_yt1;
private double m_xt2;
private double m_yt2;
private Stroke m_curve_poly;
private VertexSource.Ellipse m_ellipse = new MatterHackers.Agg.VertexSource.Ellipse();
private gsv_text m_text = new gsv_text();
private Stroke m_text_poly;
private int m_idx;
private int m_vertex;
private double[] gridVertexX = new double[32];
private double[] gridVertexY = new double[32];
private double m_xp1;
private double m_yp1;
private double m_xp2;
private double m_yp2;
private bool m_p1_active;
private int m_mouse_point;
private double m_pdx;
private double m_pdy;
private RGBA_Bytes m_background_color;
private RGBA_Bytes m_border_color;
private RGBA_Bytes m_curve_color;
private RGBA_Bytes m_grid_color;
private RGBA_Bytes m_inactive_pnt_color;
private RGBA_Bytes m_active_pnt_color;
private RGBA_Bytes m_text_color;
private RGBA_Bytes[] m_colors = new RGBA_Bytes[7];
// Set colors
public void background_color(RGBA_Bytes c)
{
m_background_color = c;
}
public void border_color(RGBA_Bytes c)
{
m_border_color = c;
}
public void curve_color(RGBA_Bytes c)
{
m_curve_color = c;
}
public void grid_color(RGBA_Bytes c)
{
m_grid_color = c;
}
public void inactive_pnt_color(RGBA_Bytes c)
{
m_inactive_pnt_color = c;
}
public void active_pnt_color(RGBA_Bytes c)
{
m_active_pnt_color = c;
}
public void text_color(RGBA_Bytes c)
{
m_text_color = c;
}
public override IColorType color(int i)
{
return m_colors[i];
}
public gamma_ctrl(Vector2 position, Vector2 size)
: base(position, false)
{
Vector2 location = position;// Vector2.Zero;
LocalBounds = new RectangleDouble(0, 0, size.x, size.y);
m_border_width = (2.0);
m_border_extra = (0.0);
m_curve_width = (2.0);
m_grid_width = (0.2);
m_text_thickness = (1.5);
m_point_size = (5.0);
m_text_height = (9.0);
double x2 = location.x + size.x;
double y2 = location.y + size.y;
m_xc1 = location.x;
m_yc1 = location.y;
m_xc2 = (x2);
m_yc2 = (y2 - m_text_height * 2.0);
m_xt1 = location.x;
m_yt1 = (y2 - m_text_height * 2.0);
m_xt2 = (x2);
m_yt2 = (y2);
m_curve_poly = new Stroke(m_gamma_spline);
m_text_poly = new Stroke(m_text);
m_idx = (0);
m_vertex = (0);
m_p1_active = (true);
m_mouse_point = (0);
m_pdx = (0.0);
m_pdy = (0.0);
calc_spline_box();
m_background_color = new RGBA_Bytes(1.0, 1.0, 0.9);
m_border_color = new RGBA_Bytes(0.0, 0.0, 0.0);
m_curve_color = new RGBA_Bytes(0.0, 0.0, 0.0);
m_grid_color = new RGBA_Bytes(0.2, 0.2, 0.0);
m_inactive_pnt_color = new RGBA_Bytes(0.0, 0.0, 0.0);
m_active_pnt_color = new RGBA_Bytes(1.0, 0.0, 0.0);
m_text_color = new RGBA_Bytes(0.0, 0.0, 0.0);
m_colors[0] = m_curve_color;
m_colors[1] = m_grid_color;
m_colors[2] = m_inactive_pnt_color;
m_colors[3] = m_active_pnt_color;
m_colors[4] = m_text_color;
}
// Set other parameters
public void border_width(double t)
{
border_width(t, 0);
}
public void border_width(double t, double extra)
{
m_border_width = t;
m_border_extra = extra;
calc_spline_box();
}
public void curve_width(double t)
{
m_curve_width = t;
}
public void grid_width(double t)
{
m_grid_width = t;
}
public void text_thickness(double t)
{
m_text_thickness = t;
}
public void text_size(double h)
{
m_text_height = h;
m_yc2 = BoundsRelativeToParent.Top - m_text_height * 2.0;
m_yt1 = BoundsRelativeToParent.Top - m_text_height * 2.0;
calc_spline_box();
}
public void point_size(double s)
{
m_point_size = s;
}
public override void OnMouseDown(MouseEventArgs mouseEvent)
{
double x = mouseEvent.X;
double y = mouseEvent.Y;
calc_points();
if (agg_math.calc_distance(x, y, m_xp1, m_yp1) <= m_point_size + 1)
{
m_mouse_point = 1;
m_pdx = m_xp1 - x;
m_pdy = m_yp1 - y;
m_p1_active = true;
}
if (agg_math.calc_distance(x, y, m_xp2, m_yp2) <= m_point_size + 1)
{
m_mouse_point = 2;
m_pdx = m_xp2 - x;
m_pdy = m_yp2 - y;
m_p1_active = false;
}
base.OnMouseDown(mouseEvent);
}
public override void OnMouseUp(MouseEventArgs mouseEvent)
{
if (m_mouse_point != 0)
{
m_mouse_point = 0;
}
base.OnMouseUp(mouseEvent);
}
public override void OnMouseMove(MouseEventArgs mouseEvent)
{
double x = mouseEvent.X;
double y = mouseEvent.Y;
if (m_mouse_point == 1)
{
m_xp1 = x + m_pdx;
m_yp1 = y + m_pdy;
calc_values();
}
if (m_mouse_point == 2)
{
m_xp2 = x + m_pdx;
m_yp2 = y + m_pdy;
calc_values();
}
base.OnMouseMove(mouseEvent);
}
public override void OnKeyDown(KeyEventArgs keyEvent)
{
double kx1, ky1, kx2, ky2;
bool ret = false;
m_gamma_spline.values(out kx1, out ky1, out kx2, out ky2);
if (m_p1_active)
{
if (keyEvent.KeyCode == Keys.Left) { kx1 -= 0.005; ret = true; }
if (keyEvent.KeyCode == Keys.Right) { kx1 += 0.005; ret = true; }
if (keyEvent.KeyCode == Keys.Down) { ky1 -= 0.005; ret = true; }
if (keyEvent.KeyCode == Keys.Up) { ky1 += 0.005; ret = true; }
}
else
{
if (keyEvent.KeyCode == Keys.Left) { kx2 += 0.005; ret = true; }
if (keyEvent.KeyCode == Keys.Right) { kx2 -= 0.005; ret = true; }
if (keyEvent.KeyCode == Keys.Down) { ky2 += 0.005; ret = true; }
if (keyEvent.KeyCode == Keys.Up) { ky2 -= 0.005; ret = true; }
}
if (ret)
{
m_gamma_spline.values(kx1, ky1, kx2, ky2);
keyEvent.Handled = true;
}
base.OnKeyDown(keyEvent);
}
public void change_active_point()
{
m_p1_active = m_p1_active ? false : true;
}
// A copy of agg::gamma_spline interface
public void values(double kx1, double ky1, double kx2, double ky2)
{
m_gamma_spline.values(kx1, ky1, kx2, ky2);
}
public void values(out double kx1, out double ky1, out double kx2, out double ky2)
{
m_gamma_spline.values(out kx1, out ky1, out kx2, out ky2);
}
public byte[] gamma()
{
return m_gamma_spline.gamma();
}
public double y(double x)
{
return m_gamma_spline.y(x);
}
//public double operator() (double x) { return m_gamma_spline.y(x); }
public gamma_spline get_gamma_spline()
{
return m_gamma_spline;
}
// Vertex soutce interface
public override int num_paths()
{
return 5;
}
public override void OnDraw(Graphics2D graphics2D)
{
RectangleDouble backgroundRect = new RectangleDouble(LocalBounds.Left - m_border_extra,
LocalBounds.Bottom - m_border_extra,
LocalBounds.Right + m_border_extra,
LocalBounds.Top + m_border_extra);
graphics2D.FillRectangle(backgroundRect, m_background_color);
PathStorage border = new PathStorage();
border.LineTo(LocalBounds.Left, LocalBounds.Bottom);
border.LineTo(LocalBounds.Right, LocalBounds.Bottom);
border.LineTo(LocalBounds.Right, LocalBounds.Top);
border.LineTo(LocalBounds.Left, LocalBounds.Top);
border.LineTo(LocalBounds.Left + m_border_width, LocalBounds.Bottom + m_border_width);
border.LineTo(LocalBounds.Left + m_border_width, LocalBounds.Top - m_border_width);
border.LineTo(LocalBounds.Right - m_border_width, LocalBounds.Top - m_border_width);
border.LineTo(LocalBounds.Right - m_border_width, LocalBounds.Bottom + m_border_width);
graphics2D.Render(border, m_border_color);
rewind(0);
graphics2D.Render(this, m_curve_color);
rewind(1);
graphics2D.Render(this, m_grid_color);
rewind(2);
graphics2D.Render(this, m_inactive_pnt_color);
rewind(3);
graphics2D.Render(this, m_active_pnt_color);
rewind(4);
graphics2D.Render(this, m_text_color);
base.OnDraw(graphics2D);
}
public override IEnumerable<VertexData> Vertices()
{
throw new NotImplementedException();
}
public override void rewind(int idx)
{
double kx1, ky1, kx2, ky2;
string tbuf;
m_idx = idx;
switch (idx)
{
default:
case 0: // Curve
m_gamma_spline.box(m_xs1, m_ys1, m_xs2, m_ys2);
m_curve_poly.width(m_curve_width);
m_curve_poly.rewind(0);
break;
case 1: // Grid
m_vertex = 0;
gridVertexX[0] = m_xs1;
gridVertexY[0] = (m_ys1 + m_ys2) * 0.5 - m_grid_width * 0.5;
gridVertexX[1] = m_xs2;
gridVertexY[1] = (m_ys1 + m_ys2) * 0.5 - m_grid_width * 0.5;
gridVertexX[2] = m_xs2;
gridVertexY[2] = (m_ys1 + m_ys2) * 0.5 + m_grid_width * 0.5;
gridVertexX[3] = m_xs1;
gridVertexY[3] = (m_ys1 + m_ys2) * 0.5 + m_grid_width * 0.5;
gridVertexX[4] = (m_xs1 + m_xs2) * 0.5 - m_grid_width * 0.5;
gridVertexY[4] = m_ys1;
gridVertexX[5] = (m_xs1 + m_xs2) * 0.5 - m_grid_width * 0.5;
gridVertexY[5] = m_ys2;
gridVertexX[6] = (m_xs1 + m_xs2) * 0.5 + m_grid_width * 0.5;
gridVertexY[6] = m_ys2;
gridVertexX[7] = (m_xs1 + m_xs2) * 0.5 + m_grid_width * 0.5;
gridVertexY[7] = m_ys1;
calc_points();
gridVertexX[8] = m_xs1;
gridVertexY[8] = m_yp1 - m_grid_width * 0.5;
gridVertexX[9] = m_xp1 - m_grid_width * 0.5;
gridVertexY[9] = m_yp1 - m_grid_width * 0.5;
gridVertexX[10] = m_xp1 - m_grid_width * 0.5;
gridVertexY[10] = m_ys1;
gridVertexX[11] = m_xp1 + m_grid_width * 0.5;
gridVertexY[11] = m_ys1;
gridVertexX[12] = m_xp1 + m_grid_width * 0.5;
gridVertexY[12] = m_yp1 + m_grid_width * 0.5;
gridVertexX[13] = m_xs1;
gridVertexY[13] = m_yp1 + m_grid_width * 0.5;
gridVertexX[14] = m_xs2;
gridVertexY[14] = m_yp2 + m_grid_width * 0.5;
gridVertexX[15] = m_xp2 + m_grid_width * 0.5;
gridVertexY[15] = m_yp2 + m_grid_width * 0.5;
gridVertexX[16] = m_xp2 + m_grid_width * 0.5;
gridVertexY[16] = m_ys2;
gridVertexX[17] = m_xp2 - m_grid_width * 0.5;
gridVertexY[17] = m_ys2;
gridVertexX[18] = m_xp2 - m_grid_width * 0.5;
gridVertexY[18] = m_yp2 - m_grid_width * 0.5;
gridVertexX[19] = m_xs2;
gridVertexY[19] = m_yp2 - m_grid_width * 0.5;
break;
case 2: // Point1
calc_points();
if (m_p1_active) m_ellipse.init(m_xp2, m_yp2, m_point_size, m_point_size, 32);
else m_ellipse.init(m_xp1, m_yp1, m_point_size, m_point_size, 32);
break;
case 3: // Point2
calc_points();
if (m_p1_active) m_ellipse.init(m_xp1, m_yp1, m_point_size, m_point_size, 32);
else m_ellipse.init(m_xp2, m_yp2, m_point_size, m_point_size, 32);
break;
case 4: // Text
m_gamma_spline.values(out kx1, out ky1, out kx2, out ky2);
tbuf = string.Format("{0:F3} {1:F3} {2:F3} {3:F3}", kx1, ky1, kx2, ky2);
m_text.text(tbuf);
m_text.SetFontSize(m_text_height);
m_text.start_point(m_xt1 + m_border_width * 2.0, (m_yt1 + m_yt2) * 0.5 - m_text_height * 0.5);
m_text_poly.width(m_text_thickness);
m_text_poly.line_join(LineJoin.Round);
m_text_poly.line_cap(LineCap.Round);
m_text_poly.rewind(0);
break;
}
}
public override ShapePath.FlagsAndCommand vertex(out double x, out double y)
{
x = 0;
y = 0;
ShapePath.FlagsAndCommand cmd = ShapePath.FlagsAndCommand.CommandLineTo;
switch (m_idx)
{
case 0:
cmd = m_curve_poly.vertex(out x, out y);
break;
case 1:
if (m_vertex == 0 ||
m_vertex == 4 ||
m_vertex == 8 ||
m_vertex == 14) cmd = ShapePath.FlagsAndCommand.CommandMoveTo;
if (m_vertex >= 20) cmd = ShapePath.FlagsAndCommand.CommandStop;
x = gridVertexX[m_vertex];
y = gridVertexY[m_vertex];
m_vertex++;
break;
case 2: // Point1
case 3: // Point2
cmd = m_ellipse.vertex(out x, out y);
break;
case 4:
cmd = m_text_poly.vertex(out x, out y);
break;
default:
cmd = ShapePath.FlagsAndCommand.CommandStop;
break;
}
return cmd;
}
private void calc_spline_box()
{
m_xs1 = m_xc1 + m_border_width;
m_ys1 = m_yc1 + m_border_width;
m_xs2 = m_xc2 - m_border_width;
m_ys2 = m_yc2 - m_border_width * 0.5;
}
private void calc_points()
{
double kx1, ky1, kx2, ky2;
m_gamma_spline.values(out kx1, out ky1, out kx2, out ky2);
m_xp1 = m_xs1 + (m_xs2 - m_xs1) * kx1 * 0.25;
m_yp1 = m_ys1 + (m_ys2 - m_ys1) * ky1 * 0.25;
m_xp2 = m_xs2 - (m_xs2 - m_xs1) * kx2 * 0.25;
m_yp2 = m_ys2 - (m_ys2 - m_ys1) * ky2 * 0.25;
}
private void calc_values()
{
double kx1, ky1, kx2, ky2;
kx1 = (m_xp1 - m_xs1) * 4.0 / (m_xs2 - m_xs1);
ky1 = (m_yp1 - m_ys1) * 4.0 / (m_ys2 - m_ys1);
kx2 = (m_xs2 - m_xp2) * 4.0 / (m_xs2 - m_xs1);
ky2 = (m_ys2 - m_yp2) * 4.0 / (m_ys2 - m_ys1);
m_gamma_spline.values(kx1, ky1, kx2, ky2);
}
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Net;
using System.IO;
using System.Timers;
using System.Drawing;
using System.Drawing.Imaging;
using log4net;
using Mono.Addins;
using Nini.Config;
using OpenSim.Framework;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Services.Interfaces;
using OpenSim.Server.Base;
using OpenMetaverse;
using OpenMetaverse.StructuredData;
namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.MapImage
{
/// <summary>
/// </summary>
/// <remarks>
/// </remarks>
[Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "MapImageServiceModule")]
public class MapImageServiceModule : ISharedRegionModule
{
private static readonly ILog m_log =
LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private bool m_enabled = false;
private IMapImageService m_MapService;
private Dictionary<UUID, Scene> m_scenes = new Dictionary<UUID, Scene>();
private int m_refreshtime = 0;
private int m_lastrefresh = 0;
private System.Timers.Timer m_refreshTimer = new System.Timers.Timer();
#region ISharedRegionModule
public Type ReplaceableInterface { get { return null; } }
public string Name { get { return "MapImageServiceModule"; } }
public void RegionLoaded(Scene scene) { }
public void Close() { }
public void PostInitialise() { }
///<summary>
///
///</summary>
public void Initialise(IConfigSource source)
{
IConfig moduleConfig = source.Configs["Modules"];
if (moduleConfig != null)
{
string name = moduleConfig.GetString("MapImageService", "");
if (name != Name)
return;
}
IConfig config = source.Configs["MapImageService"];
if (config == null)
return;
int refreshminutes = Convert.ToInt32(config.GetString("RefreshTime"));
if (refreshminutes <= 0)
{
m_log.WarnFormat("[MAP IMAGE SERVICE MODULE]: No refresh time given in config. Module disabled.");
return;
}
m_refreshtime = refreshminutes * 60 * 1000; // convert from minutes to ms
string service = config.GetString("LocalServiceModule", string.Empty);
if (service == string.Empty)
{
m_log.WarnFormat("[MAP IMAGE SERVICE MODULE]: No service dll given in config. Unable to proceed.");
return;
}
Object[] args = new Object[] { source };
m_MapService = ServerUtils.LoadPlugin<IMapImageService>(service, args);
if (m_MapService == null)
{
m_log.WarnFormat("[MAP IMAGE SERVICE MODULE]: Unable to load LocalServiceModule from {0}. MapService module disabled. Please fix the configuration.", service);
return;
}
m_refreshTimer.Enabled = true;
m_refreshTimer.AutoReset = true;
m_refreshTimer.Interval = m_refreshtime;
m_refreshTimer.Elapsed += new ElapsedEventHandler(HandleMaptileRefresh);
m_log.InfoFormat("[MAP IMAGE SERVICE MODULE]: enabled with refresh time {0}min and service object {1}",
refreshminutes, service);
m_enabled = true;
}
///<summary>
///
///</summary>
public void AddRegion(Scene scene)
{
if (!m_enabled)
return;
// Every shared region module has to maintain an indepedent list of
// currently running regions
lock (m_scenes)
m_scenes[scene.RegionInfo.RegionID] = scene;
scene.EventManager.OnRegionReadyStatusChange += s => { if (s.Ready) UploadMapTile(s); };
}
///<summary>
///
///</summary>
public void RemoveRegion(Scene scene)
{
if (! m_enabled)
return;
lock (m_scenes)
m_scenes.Remove(scene.RegionInfo.RegionID);
}
#endregion ISharedRegionModule
///<summary>
///
///</summary>
private void HandleMaptileRefresh(object sender, EventArgs ea)
{
// this approach is a bit convoluted becase we want to wait for the
// first upload to happen on startup but after all the objects are
// loaded and initialized
if (m_lastrefresh > 0 && Util.EnvironmentTickCountSubtract(m_lastrefresh) < m_refreshtime)
return;
m_log.DebugFormat("[MAP IMAGE SERVICE MODULE]: map refresh!");
lock (m_scenes)
{
foreach (IScene scene in m_scenes.Values)
{
try
{
UploadMapTile(scene);
}
catch (Exception ex)
{
m_log.WarnFormat("[MAP IMAGE SERVICE MODULE]: something bad happened {0}", ex.Message);
}
}
}
m_lastrefresh = Util.EnvironmentTickCount();
}
///<summary>
///
///</summary>
private void UploadMapTile(IScene scene)
{
m_log.DebugFormat("[MAP IMAGE SERVICE MODULE]: upload maptile for {0}", scene.RegionInfo.RegionName);
// Create a JPG map tile and upload it to the AddMapTile API
byte[] jpgData = Utils.EmptyBytes;
IMapImageGenerator tileGenerator = scene.RequestModuleInterface<IMapImageGenerator>();
if (tileGenerator == null)
{
m_log.Warn("[MAP IMAGE SERVICE MODULE]: Cannot upload PNG map tile without an ImageGenerator");
return;
}
using (Image mapTile = tileGenerator.CreateMapTile())
{
// XXX: The MapImageModule will return a null if the user has chosen not to create map tiles and there
// is no static map tile.
if (mapTile == null)
return;
using (MemoryStream stream = new MemoryStream())
{
mapTile.Save(stream, ImageFormat.Jpeg);
jpgData = stream.ToArray();
}
}
if (jpgData == Utils.EmptyBytes)
{
m_log.WarnFormat("[MAP IMAGE SERVICE MODULE]: Tile image generation failed");
return;
}
string reason = string.Empty;
if (!m_MapService.AddMapTile((int)scene.RegionInfo.RegionLocX, (int)scene.RegionInfo.RegionLocY, jpgData, out reason))
{
m_log.DebugFormat("[MAP IMAGE SERVICE MODULE]: Unable to upload tile image for {0} at {1}-{2}: {3}",
scene.RegionInfo.RegionName, scene.RegionInfo.RegionLocX, scene.RegionInfo.RegionLocY, reason);
}
}
}
}
| |
#region license
// Copyright (c) 2004, Rodrigo B. de Oliveira ([email protected])
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
// * Neither the name of Rodrigo B. de Oliveira nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#endregion
namespace BooCompiler.Tests
{
using NUnit.Framework;
[TestFixture]
public class SmokeTest : AbstractCompilerTestCase
{
protected override void CopyDependencies()
{
base.CopyDependencies();
CopyAssembly(typeof(Boo.Lang.PatternMatching.MatchMacro).Assembly);
}
[Test]
public void ExternalModuleWithNoNamespace()
{
RunCompilerTestCase("ExternalModuleWithNoNamespace.boo");
}
[Test]
public void InternalMacroBootstrapping()
{
RunCompilerTestCase("InternalMacroBootstrapping.boo");
}
[Test]
public void InternalMacrosInSeparateModules()
{
RunCompilerTestCase("InternalMacrosInSeparateModules.boo");
}
[Test]
public void DuckTyping()
{
RunCompilerTestCase("DuckTyping.boo");
}
[Test]
public void InternalArrayType()
{
RunCompilerTestCase("InternalArrayType.boo");
}
[Test]
public void UndeclaredDefaultConstructor()
{
RunCompilerTestCase("UndeclaredDefaultConstructor.boo");
}
[Test]
public void InternalMacro()
{
RunCompilerTestCase("InternalMacro.boo");
}
[Test]
public void InternalClassGenerator()
{
RunCompilerTestCase("InternalClassGenerator.boo");
}
[Test]
public void CodeLiteralInNamespaceWithBooLangPrefix()
{
string code = @"
namespace Boo.Lang.Useful.Attributes
print [| 42 |]";
Assert.AreEqual("42\n", RunString(code));
}
[Test]
public void TestHello()
{
Assert.AreEqual("Hello!\n", RunString("print('Hello!')"));
}
[Test]
public void TestHello2()
{
string stdin = "Test2\n";
string code = "name = prompt(''); print(\"Hello, ${name}!\")";
Assert.AreEqual("Hello, Test2!\n", RunString(code, stdin));
}
[Test]
public void TypeReferenceRepresentsType()
{
RunCompilerTestCase("typereference0.boo");
}
[Test]
public void TestIfModifier0()
{
RunCompilerTestCase("if0.boo");
}
[Test]
public void TimeSpanLiteral()
{
RunCompilerTestCase("timespan0.boo");
}
[Test]
public void TestMatch0()
{
RunCompilerTestCase("match0.boo");
}
[Test]
public void TestMatch1()
{
RunCompilerTestCase("match1.boo");
}
[Test]
public void TestNot0()
{
RunCompilerTestCase("not0.boo");
}
[Test]
public void ArrayMember()
{
RunCompilerTestCase("in0.boo");
}
[Test]
public void ArrayNotMember()
{
RunCompilerTestCase("in1.boo");
}
[Test]
public void IsNotIs()
{
RunCompilerTestCase("is0.boo");
}
[Test]
public void RealType()
{
RunCompilerTestCase("double0.boo");
}
[Test]
public void PreIncrement()
{
RunCompilerTestCase("preincrement0.boo");
}
[Test]
public void PreDecrement()
{
RunCompilerTestCase("predecrement0.boo");
}
[Test]
public void SumLocals()
{
RunCompilerTestCase("sum0.boo");
}
[Test]
public void MultLocals()
{
RunCompilerTestCase("mult0.boo");
}
[Test]
public void InPlaceAddLocals()
{
RunCompilerTestCase("inplaceadd0.boo");
}
[Test]
public void InPlaceField()
{
RunCompilerTestCase("inplace1.boo");
}
[Test]
public void LongLiterals()
{
RunCompilerTestCase("long0.boo");
}
[Test]
public void DecimalLiterals()
{
RunCompilerTestCase("decimal0.boo");
}
[Test]
public void BooleanFromBoxedValueTypes()
{
RunCompilerTestCase("bool0.boo");
}
[Test]
public void GreaterThanEqualForInts()
{
RunCompilerTestCase("gte_int.boo");
}
[Test]
public void LessThanEqualForInts()
{
RunCompilerTestCase("lte_int.boo");
}
[Test]
public void IndexedProperty()
{
RunCompilerTestCase("indexed.boo");
}
[Test]
public void IndexPropertyWithSyntacticAttribute()
{
RunCompilerTestCase("indexed2.boo");
}
[Test]
public void ImportInternalNamespace()
{
RunMultiFileTestCase("multifile0.boo", "Character.boo");
}
[Test]
public void ImportAutomaticallyFromModulesInTheSameNamespace()
{
RunMultiFileTestCase("multifile1.boo", "Character.boo");
}
[Test]
public void ImportFunctionsFromModulesInTheGlobalNamespace()
{
RunMultiFileTestCase("multifile2.boo", "math.boo");
}
[Test]
public void ImportFunctionsFromModulesInTheSameNamespace()
{
RunMultiFileTestCase("multifile3.boo", "mathwithns.boo");
}
[Test]
public void ClassesCanUseModuleMethods()
{
RunCompilerTestCase("module_methods0.boo");
}
[Test]
public void RangeBuiltin()
{
RunCompilerTestCase("range.boo");
}
[Test]
public void StringAddition()
{
RunCompilerTestCase("stringadd0.boo");
}
[Test]
public void StringMultiplyByInt()
{
RunCompilerTestCase("stringmultiply0.boo");
}
[Test]
public void ListRichOperators()
{
RunCompilerTestCase("listoperators.boo");
}
[Test]
public void CustomerAddresses()
{
RunCompilerTestCase("customer_addresses.boo");
}
[Test]
public void NumberExponentiation()
{
RunCompilerTestCase("pow0.boo");
}
[Test]
public void UnlessModifier()
{
RunCompilerTestCase("unless.boo");
}
[Test]
public void StringFormattingWithTripleQuotedString()
{
RunCompilerTestCase("formatting0.boo");
}
[Test]
public void UnpackLocals()
{
RunCompilerTestCase("unpack_locals.boo");
}
[Test]
public void StatementModifierOnUnpack()
{
RunCompilerTestCase("modifiers0.boo");
}
[Test]
public void StaticFieldSimple()
{
RunCompilerTestCase("static_field0.boo");
}
[Test]
public void StaticLiteralField()
{
RunCompilerTestCase("static_literalfield0.boo");
}
[Test]
public void StaticConstructorIsCalledBeforeFirstStaticFieldAccess()
{
RunCompilerTestCase("static_constructor0.boo");
}
[Test]
public void IncrementProperty()
{
RunCompilerTestCase("increment_property0.boo");
}
[Test]
public void IncrementPropertyAndUseValue()
{
RunCompilerTestCase("increment_property1.boo");
}
[Test]
public void EnumComparisons()
{
RunCompilerTestCase("enum_comparisons.boo");
}
[Test]
public void TypeIsCallable()
{
RunCompilerTestCase("typeiscallable.boo");
}
[Test]
public void TypeAsICallable()
{
RunCompilerTestCase("typeiscallable1.boo");
}
[Test]
public void OverloadedMethodsCanBeDeclaredInAnyOrder()
{
RunCompilerTestCase("logservice.boo");
}
[Test]
public void ParameterAsLValue()
{
RunCompilerTestCase("parameter_as_lvalue.boo");
}
[Test]
public void NullIsCompatibleWithInternalClasses()
{
RunCompilerTestCase("null0.boo");
}
[Test]
public void TextReaderIsEnumerable()
{
RunCompilerTestCase("textreaderisenumerable.boo");
}
[Test]
public void RegularExpressionLiteralIsRegex()
{
RunCompilerTestCase("re0.boo");
}
[Test]
public void RegularExpressionMatch()
{
RunCompilerTestCase("re1.boo");
}
[Test]
public void CaseInsensitiveHash()
{
RunCompilerTestCase("caseinsensitivehash.boo");
}
[Test]
public void EnumeratorItemTypeForClasses()
{
RunCompilerTestCase("enumeratoritemtype0.boo");
}
[Test]
public void EnumeratorItemTypeForInternalClasses()
{
RunCompilerTestCase("enumeratoritemtype1.boo");
}
[Test]
public void EnumeratorItemTypeForMethods()
{
RunCompilerTestCase("enumeratoritemtype2.boo");
}
[Test]
public void UnaryMinusWithLocal()
{
RunCompilerTestCase("unary0.boo");
}
[Test]
public void RedefineBuiltin()
{
RunCompilerTestCase("redefine_builtin.boo");
}
[Test]
public void ExternalConstants()
{
RunCompilerTestCase("const0.boo");
}
[Test]
public void ListSort()
{
RunCompilerTestCase("sort.boo");
}
[Test]
public void CustomCollection()
{
RunCompilerTestCase("CustomCollection.boo");
}
[Test]
public void UsingNestedType()
{
RunCompilerTestCase("UsingNestedType.boo");
}
}
}
| |
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using System;
using System.Collections.Generic;
using System.Management.Automation.Internal;
using System.Xml;
namespace Microsoft.PowerShell.Commands.Internal.Format
{
/// <summary>
/// Class to load the XML document into data structures.
/// It encapsulates the file format specific code.
/// </summary>
internal sealed partial class TypeInfoDataBaseLoader : XmlLoaderBase
{
private ComplexControlBody LoadComplexControl(XmlNode controlNode)
{
using (this.StackFrame(controlNode))
{
ComplexControlBody complexBody = new ComplexControlBody();
bool entriesFound = false;
foreach (XmlNode n in controlNode.ChildNodes)
{
if (MatchNodeName(n, XmlTags.ComplexEntriesNode))
{
if (entriesFound)
{
this.ProcessDuplicateNode(n);
continue;
}
entriesFound = true;
// now read the columns section
LoadComplexControlEntries(n, complexBody);
if (complexBody.defaultEntry == null)
{
return null; // fatal error
}
}
else
{
this.ProcessUnknownNode(n);
}
}
if (!entriesFound)
{
this.ReportMissingNode(XmlTags.ComplexEntriesNode);
return null; // fatal error
}
return complexBody;
}
}
private void LoadComplexControlEntries(XmlNode complexControlEntriesNode, ComplexControlBody complexBody)
{
using (this.StackFrame(complexControlEntriesNode))
{
int entryIndex = 0;
foreach (XmlNode n in complexControlEntriesNode.ChildNodes)
{
if (MatchNodeName(n, XmlTags.ComplexEntryNode))
{
ComplexControlEntryDefinition cced = LoadComplexControlEntryDefinition(n, entryIndex++);
if (cced == null)
{
// Error at XPath {0} in file {1}: {2} failed to load.
this.ReportError(StringUtil.Format(FormatAndOutXmlLoadingStrings.LoadTagFailed, ComputeCurrentXPath(), FilePath, XmlTags.ComplexEntryNode));
complexBody.defaultEntry = null;
return; // fatal error
}
// determine if we have a default entry and if it's already set
if (cced.appliesTo == null)
{
if (complexBody.defaultEntry == null)
{
complexBody.defaultEntry = cced;
}
else
{
// Error at XPath {0} in file {1}: There cannot be more than one default {2}.
this.ReportError(StringUtil.Format(FormatAndOutXmlLoadingStrings.TooManyDefaultShapeEntry, ComputeCurrentXPath(), FilePath, XmlTags.ComplexEntryNode));
complexBody.defaultEntry = null;
return; // fatal error
}
}
else
{
complexBody.optionalEntryList.Add(cced);
}
}
else
{
this.ProcessUnknownNode(n);
}
}
if (complexBody.defaultEntry == null)
{
// Error at XPath {0} in file {1}: There must be at least one default {2}.
this.ReportError(StringUtil.Format(FormatAndOutXmlLoadingStrings.NoDefaultShapeEntry, ComputeCurrentXPath(), FilePath, XmlTags.ComplexEntryNode));
}
}
}
private ComplexControlEntryDefinition LoadComplexControlEntryDefinition(XmlNode complexControlEntryNode, int index)
{
using (this.StackFrame(complexControlEntryNode, index))
{
bool appliesToNodeFound = false; // cardinality 0..1
bool bodyNodeFound = false; // cardinality 1
ComplexControlEntryDefinition cced = new ComplexControlEntryDefinition();
foreach (XmlNode n in complexControlEntryNode.ChildNodes)
{
if (MatchNodeName(n, XmlTags.EntrySelectedByNode))
{
if (appliesToNodeFound)
{
this.ProcessDuplicateNode(n);
return null; // fatal
}
appliesToNodeFound = true;
// optional section
cced.appliesTo = LoadAppliesToSection(n, true);
}
else if (MatchNodeName(n, XmlTags.ComplexItemNode))
{
if (bodyNodeFound)
{
this.ProcessDuplicateNode(n);
return null; // fatal
}
bodyNodeFound = true;
cced.itemDefinition.formatTokenList = LoadComplexControlTokenListDefinitions(n);
}
else
{
this.ProcessUnknownNode(n);
}
}
if (cced.itemDefinition.formatTokenList == null)
{
// MissingNode=Error at XPath {0} in file {1}: Missing Node {2}.
this.ReportError(StringUtil.Format(FormatAndOutXmlLoadingStrings.MissingNode, ComputeCurrentXPath(), FilePath, XmlTags.ComplexItemNode));
return null;
}
return cced;
}
}
private List<FormatToken> LoadComplexControlTokenListDefinitions(XmlNode bodyNode)
{
using (this.StackFrame(bodyNode))
{
List<FormatToken> formatTokenList = new List<FormatToken>();
int compoundPropertyIndex = 0;
int newLineIndex = 0;
int textIndex = 0;
int frameIndex = 0;
foreach (XmlNode n in bodyNode.ChildNodes)
{
if (MatchNodeName(n, XmlTags.ExpressionBindingNode))
{
CompoundPropertyToken cpt = LoadCompoundProperty(n, compoundPropertyIndex++);
if (cpt == null)
{
// Error at XPath {0} in file {1}: {2} failed to load.
this.ReportError(StringUtil.Format(FormatAndOutXmlLoadingStrings.LoadTagFailed, ComputeCurrentXPath(), FilePath, XmlTags.ExpressionBindingNode));
return null;
}
formatTokenList.Add(cpt);
}
else if (MatchNodeName(n, XmlTags.NewLineNode))
{
NewLineToken nlt = LoadNewLine(n, newLineIndex++);
if (nlt == null)
{
// Error at XPath {0} in file {1}: {2} failed to load.
this.ReportError(StringUtil.Format(FormatAndOutXmlLoadingStrings.LoadTagFailed, ComputeCurrentXPath(), FilePath, XmlTags.NewLineNode));
return null;
}
formatTokenList.Add(nlt);
}
else if (MatchNodeNameWithAttributes(n, XmlTags.TextNode))
{
TextToken tt = LoadText(n, textIndex++);
if (tt == null)
{
// Error at XPath {0} in file {1}: {2} failed to load.
this.ReportError(StringUtil.Format(FormatAndOutXmlLoadingStrings.LoadTagFailed, ComputeCurrentXPath(), FilePath, XmlTags.TextNode));
return null;
}
formatTokenList.Add(tt);
}
else if (MatchNodeName(n, XmlTags.FrameNode))
{
FrameToken frame = LoadFrameDefinition(n, frameIndex++);
if (frame == null)
{
// Error at XPath {0} in file {1}: {2} failed to load.
this.ReportError(StringUtil.Format(FormatAndOutXmlLoadingStrings.LoadTagFailed, ComputeCurrentXPath(), FilePath, XmlTags.FrameNode));
return null;
}
formatTokenList.Add(frame);
}
else
{
this.ProcessUnknownNode(n);
}
}
if (formatTokenList.Count == 0)
{
// Error at XPath {0} in file {1}: Empty custom control token list.
this.ReportError(StringUtil.Format(FormatAndOutXmlLoadingStrings.EmptyCustomControlList, ComputeCurrentXPath(), FilePath));
return null;
}
return formatTokenList;
}
}
private bool LoadPropertyBaseHelper(XmlNode propertyBaseNode, PropertyTokenBase ptb, List<XmlNode> unprocessedNodes)
{
ExpressionNodeMatch expressionMatch = new ExpressionNodeMatch(this);
bool expressionNodeFound = false; // cardinality 0..1
bool collectionNodeFound = false; // cardinality 0..1
bool itemSelectionConditionNodeFound = false; // cardinality 0..1
ExpressionToken condition = null;
foreach (XmlNode n in propertyBaseNode.ChildNodes)
{
if (expressionMatch.MatchNode(n))
{
if (expressionNodeFound)
{
this.ProcessDuplicateNode(n);
return false; // fatal error
}
expressionNodeFound = true;
if (!expressionMatch.ProcessNode(n))
return false; // fatal error
}
else if (MatchNodeName(n, XmlTags.EnumerateCollectionNode))
{
if (collectionNodeFound)
{
this.ProcessDuplicateNode(n);
return false;
}
collectionNodeFound = true;
if (!ReadBooleanNode(n, out ptb.enumerateCollection))
return false;
}
else if (MatchNodeName(n, XmlTags.ItemSelectionConditionNode))
{
if (itemSelectionConditionNodeFound)
{
this.ProcessDuplicateNode(n);
return false;
}
itemSelectionConditionNodeFound = true;
condition = LoadItemSelectionCondition(n);
if (condition == null)
{
return false;
}
}
else
{
if (!IsFilteredOutNode(n))
unprocessedNodes.Add(n);
}
}
if (expressionNodeFound)
{
// we add only if we encountered one, since it's not mandatory
ExpressionToken expression = expressionMatch.GenerateExpressionToken();
if (expression == null)
{
return false; // fatal error
}
ptb.expression = expression;
ptb.conditionToken = condition;
}
return true;
}
// No used currently
#if false
private FieldPropertyToken LoadFieldProperty (XmlNode fieldPropertyNode, int index)
{
using (this.StackFrame (fieldPropertyNode, index))
{
FieldPropertyToken fpt = new FieldPropertyToken ();
List<XmlNode> unprocessedNodes = new List<XmlNode> ();
bool success = LoadPropertyBaseHelper (fieldPropertyNode, fpt, unprocessedNodes);
foreach (XmlNode n in unprocessedNodes)
{
this.ProcessUnknownNode (n);
}
if (success && unprocessedNodes.Count == 0)
{
return fpt; // success
}
return null; // failure
}
}
#endif
private CompoundPropertyToken LoadCompoundProperty(XmlNode compoundPropertyNode, int index)
{
using (this.StackFrame(compoundPropertyNode, index))
{
CompoundPropertyToken cpt = new CompoundPropertyToken();
List<XmlNode> unprocessedNodes = new List<XmlNode>();
bool success = LoadPropertyBaseHelper(compoundPropertyNode, cpt, unprocessedNodes);
if (!success)
{
return null;
}
cpt.control = null;
// mutually exclusive
bool complexControlFound = false; // cardinality 0..1
bool fieldControlFound = false; // cardinality 0..1
ComplexControlMatch controlMatch = new ComplexControlMatch(this);
FieldControlBody fieldControlBody = null;
foreach (XmlNode n in unprocessedNodes)
{
if (controlMatch.MatchNode(n))
{
if (complexControlFound)
{
this.ProcessDuplicateAlternateNode(n, XmlTags.ComplexControlNode, XmlTags.ComplexControlNameNode);
return null;
}
complexControlFound = true;
if (!controlMatch.ProcessNode(n))
return null; // fatal error
}
else if (MatchNodeName(n, XmlTags.FieldControlNode))
{
if (fieldControlFound)
{
this.ProcessDuplicateAlternateNode(n, XmlTags.ComplexControlNode, XmlTags.ComplexControlNameNode);
return null; // fatal error
}
fieldControlFound = true;
fieldControlBody = new FieldControlBody();
fieldControlBody.fieldFormattingDirective.formatString = GetMandatoryInnerText(n);
if (fieldControlBody.fieldFormattingDirective.formatString == null)
{
return null; // fatal error
}
}
else
{
ProcessUnknownNode(n);
}
}
if (fieldControlFound && complexControlFound)
{
this.ProcessDuplicateAlternateNode(XmlTags.ComplexControlNode, XmlTags.ComplexControlNameNode);
return null; // fatal error
}
if (fieldControlFound)
{
cpt.control = fieldControlBody;
}
else
{
cpt.control = controlMatch.Control;
}
/*
if (cpt.control == null)
{
this.ReportMissingNodes (
new string[] { XmlTags.FieldControlNode, XmlTags.ComplexControlNode, XmlTags.ComplexControlNameNode });
return null;
}
*/
return cpt;
}
}
private NewLineToken LoadNewLine(XmlNode newLineNode, int index)
{
using (this.StackFrame(newLineNode, index))
{
if (!VerifyNodeHasNoChildren(newLineNode))
{
return null;
}
NewLineToken nlt = new NewLineToken();
return nlt;
}
}
private TextToken LoadText(XmlNode textNode, int index)
{
using (this.StackFrame(textNode, index))
{
return LoadTextToken(textNode);
}
}
internal TextToken LoadText(XmlNode textNode)
{
using (this.StackFrame(textNode))
{
return LoadTextToken(textNode);
}
}
private int LoadIntegerValue(XmlNode node, out bool success)
{
using (this.StackFrame(node))
{
success = false;
int retVal = 0;
if (!VerifyNodeHasNoChildren(node))
{
return retVal;
}
string val = this.GetMandatoryInnerText(node);
if (val == null)
{
// Error at XPath {0} in file {1}: Missing inner text value.
this.ReportError(StringUtil.Format(FormatAndOutXmlLoadingStrings.MissingInnerText, ComputeCurrentXPath(), FilePath));
return retVal;
}
if (!int.TryParse(val, out retVal))
{
// Error at XPath {0} in file {1}: An integer is expected.
this.ReportError(StringUtil.Format(FormatAndOutXmlLoadingStrings.ExpectInteger, ComputeCurrentXPath(), FilePath));
return retVal;
}
success = true;
return retVal;
}
}
private int LoadPositiveOrZeroIntegerValue(XmlNode node, out bool success)
{
int val = LoadIntegerValue(node, out success);
if (!success)
return val;
using (this.StackFrame(node))
{
if (val < 0)
{
// Error at XPath {0} in file {1}: A non-negative integer is expected.
this.ReportError(StringUtil.Format(FormatAndOutXmlLoadingStrings.ExpectNaturalNumber, ComputeCurrentXPath(), FilePath));
success = false;
}
return val;
}
}
private FrameToken LoadFrameDefinition(XmlNode frameNode, int index)
{
using (this.StackFrame(frameNode, index))
{
bool itemNodeFound = false; // cardinality 1
bool leftIndentFound = false; // cardinality 0..1
bool rightIndentFound = false; // cardinality 0..1
// mutually exclusive
bool firstLineIndentFound = false; // cardinality 0..1
bool firstLineHangingFound = false; // cardinality 0..1
bool success; // scratch variable
FrameToken frame = new FrameToken();
foreach (XmlNode n in frameNode.ChildNodes)
{
if (MatchNodeName(n, XmlTags.LeftIndentNode))
{
if (leftIndentFound)
{
this.ProcessDuplicateNode(n);
return null; // fatal
}
leftIndentFound = true;
// optional section
frame.frameInfoDefinition.leftIndentation = LoadPositiveOrZeroIntegerValue(n, out success);
if (!success)
return null;
}
else if (MatchNodeName(n, XmlTags.RightIndentNode))
{
if (rightIndentFound)
{
this.ProcessDuplicateNode(n);
return null; // fatal
}
rightIndentFound = true;
// optional section
frame.frameInfoDefinition.rightIndentation = LoadPositiveOrZeroIntegerValue(n, out success);
if (!success)
return null;
}
else if (MatchNodeName(n, XmlTags.FirstLineIndentNode))
{
if (firstLineIndentFound)
{
this.ProcessDuplicateAlternateNode(n, XmlTags.FirstLineIndentNode, XmlTags.FirstLineHangingNode);
return null;
}
firstLineIndentFound = true;
frame.frameInfoDefinition.firstLine = LoadPositiveOrZeroIntegerValue(n, out success);
if (!success)
return null;
}
else if (MatchNodeName(n, XmlTags.FirstLineHangingNode))
{
if (firstLineHangingFound)
{
this.ProcessDuplicateAlternateNode(n, XmlTags.FirstLineIndentNode, XmlTags.FirstLineHangingNode);
return null;
}
firstLineHangingFound = true;
frame.frameInfoDefinition.firstLine = LoadPositiveOrZeroIntegerValue(n, out success);
if (!success)
return null;
// hanging is codified as negative
frame.frameInfoDefinition.firstLine = -frame.frameInfoDefinition.firstLine;
}
else if (MatchNodeName(n, XmlTags.ComplexItemNode))
{
if (itemNodeFound)
{
this.ProcessDuplicateNode(n);
return null; // fatal
}
itemNodeFound = true;
frame.itemDefinition.formatTokenList = LoadComplexControlTokenListDefinitions(n);
}
else
{
this.ProcessUnknownNode(n);
}
}
if (firstLineHangingFound && firstLineIndentFound)
{
this.ProcessDuplicateAlternateNode(XmlTags.FirstLineIndentNode, XmlTags.FirstLineHangingNode);
return null; // fatal error
}
if (frame.itemDefinition.formatTokenList == null)
{
// MissingNode=Error at XPath {0} in file {1}: Missing Node {2}.
this.ReportError(StringUtil.Format(FormatAndOutXmlLoadingStrings.MissingNode, ComputeCurrentXPath(), FilePath, XmlTags.ComplexItemNode));
return null;
}
return frame;
}
}
private bool ReadBooleanNode(XmlNode collectionElement, out bool val)
{
val = false;
if (!VerifyNodeHasNoChildren(collectionElement))
{
return false;
}
string s = collectionElement.InnerText;
if (string.IsNullOrEmpty(s))
{
val = true;
return true;
}
if (string.Equals(s, XMLStringValues.False, StringComparison.OrdinalIgnoreCase))
{
val = false;
return true;
}
else if (string.Equals(s, XMLStringValues.True, StringComparison.OrdinalIgnoreCase))
{
val = true;
return true;
}
// Error at XPath {0} in file {1}: A Boolean value is expected.
this.ReportError(StringUtil.Format(FormatAndOutXmlLoadingStrings.ExpectBoolean, ComputeCurrentXPath(), FilePath));
return false;
}
}
}
| |
#region License
// Copyright (c) 2010-2019, Mark Final
// 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 BuildAMation 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.
#endregion // License
namespace Installer
{
/// <summary>
/// Module representing input to InnoSetup
/// </summary>
class InnoSetupScript :
Bam.Core.Module
{
private readonly System.Collections.Generic.Dictionary<Bam.Core.Module, string> Files = new System.Collections.Generic.Dictionary<Bam.Core.Module, string>();
private readonly System.Collections.Generic.Dictionary<Bam.Core.Module, string> Paths = new System.Collections.Generic.Dictionary<Bam.Core.Module, string>();
/// <summary>
/// Path key to the InnoSetup script
/// </summary>
public const string ScriptKey = "InnoSetup script";
protected override void
Init()
{
base.Init();
var parentModule = Bam.Core.Graph.Instance.ModuleStack.Peek();
this.RegisterGeneratedFile(
ScriptKey,
this.CreateTokenizedString(
"$(buildroot)/$(0)/$(config)/script.iss",
new[] { parentModule.Macros[Bam.Core.ModuleMacroNames.ModuleName] }
)
);
}
/// <summary>
/// Add a file to the InnoSetup script
/// </summary>
/// <param name="module">Module to add</param>
/// <param name="key">Path key from this module</param>
public void
AddFile(
Bam.Core.Module module,
string key)
{
this.DependsOn(module);
this.Files.Add(module, key);
}
/// <summary>
/// Add a path (a directory) to the InnoSetup script
/// </summary>
/// <param name="module">Module to add</param>
/// <param name="key">Path key from this module</param>
public void
AddPath(
Bam.Core.Module module,
string key)
{
this.DependsOn(module);
this.Paths.Add(module, key);
}
protected override void
EvaluateInternal()
{
// do nothing
}
protected override void
ExecuteInternal(
Bam.Core.ExecutionContext context)
{
var path = this.GeneratedPaths[ScriptKey].ToString();
var dir = System.IO.Path.GetDirectoryName(path);
Bam.Core.IOWrapper.CreateDirectoryIfNotExists(dir);
var outputName = this.EncapsulatingModule.Macros[Bam.Core.ModuleMacroNames.OutputName];
using (var scriptWriter = new System.IO.StreamWriter(path))
{
scriptWriter.WriteLine("[Setup]");
scriptWriter.WriteLine($"OutputBaseFilename={outputName.ToStringQuoteIfNecessary()}");
var installedExePath = this.CreateTokenizedString("@dir($(buildroot)/$(config)/$(0).exe)", outputName);
installedExePath.Parse();
scriptWriter.WriteLine($"OutputDir={installedExePath.ToStringQuoteIfNecessary()}");
// create the output directory in-advance, so that multiple InnoSetup processes, writing to the same folder
// do not hit a race condition in creating this folder
Bam.Core.IOWrapper.CreateDirectoryIfNotExists(installedExePath.ToStringQuoteIfNecessary());
scriptWriter.WriteLine($"AppName={outputName.ToString()}");
var productDef = Bam.Core.Graph.Instance.ProductDefinition;
if (null != productDef)
{
scriptWriter.WriteLine(
$"AppVersion={productDef.MajorVersion ?? 1}.{productDef.MinorVersion ?? 0}.{productDef.PatchVersion ?? 0}"
);
}
else
{
scriptWriter.WriteLine("AppVersion=1.0.0");
}
scriptWriter.WriteLine($"DefaultDirName={{userappdata}}\\{outputName.ToString()}");
scriptWriter.WriteLine("ArchitecturesAllowed=x64");
scriptWriter.WriteLine("ArchitecturesInstallIn64BitMode=x64");
scriptWriter.WriteLine("Uninstallable=No");
scriptWriter.WriteLine("[Files]");
foreach (var dep in this.Files)
{
scriptWriter.Write($"Source: \"{dep.Key.GeneratedPaths[dep.Value]}\"; ");
scriptWriter.Write("DestDir: \"{app}\"; ");
scriptWriter.Write("DestName: \"Test\"");
}
foreach (var dep in this.Paths)
{
scriptWriter.Write($"Source: \"{dep.Key.GeneratedPaths[dep.Value]}\\*.*\"; ");
scriptWriter.Write("DestDir: \"{app}\"; ");
scriptWriter.Write("Flags: recursesubdirs");
}
}
}
}
/// <summary>
/// Settings for InnoSetup
/// </summary>
[CommandLineProcessor.InputPaths(InnoSetupScript.ScriptKey, "")]
sealed class InnoSetupCompilerSettings :
Bam.Core.Settings
{
/// <summary>
/// Default constructor
/// </summary>
public InnoSetupCompilerSettings()
:
base(ELayout.Inputs_Outputs_Cmds)
{}
}
/// <summary>
/// Compiler tool for InnoSetup
/// </summary>
sealed class InnoSetupCompiler :
Bam.Core.PreBuiltTool
{
protected override void
Init()
{
#if D_NUGET_INNOSETUP
this.Macros.AddVerbatim(
"toolPath",
Bam.Core.NuGetUtilities.GetToolExecutablePath("innosetup", this.GetType().Namespace, "ISCC.exe")
);
#endif
// since the toolPath macro is needed to evaluate the Executable property
// in the check for existence
base.Init();
}
/// <summary>
/// \copydoc Bam.Core.ITool.SettingsType
/// </summary>
public override System.Type SettingsType => typeof(InnoSetupCompilerSettings);
/// <summary>
/// Executable path to the tool
/// </summary>
public override Bam.Core.TokenizedString Executable => this.Macros["toolPath"];
}
/// <summary>
/// Derive from this module to create an InnoSetup installer of the specified files.
/// </summary>
[Bam.Core.PlatformFilter(Bam.Core.EPlatform.Windows)]
abstract class InnoSetupInstaller :
Bam.Core.Module
{
private InnoSetupScript ScriptModule;
protected override void
Init()
{
base.Init();
this.ScriptModule = Bam.Core.Module.Create<InnoSetupScript>();
this.DependsOn(this.ScriptModule);
this.Tool = Bam.Core.Graph.Instance.FindReferencedModule<InnoSetupCompiler>();
this.Requires(this.Tool);
}
/// <summary>
/// Include an individual file in the installer.
/// </summary>
/// <param name="key">Key.</param>
/// <typeparam name="DependentModule">The 1st type parameter.</typeparam>
public void
Include<DependentModule>(
string key
) where DependentModule : Bam.Core.Module, new()
{
var dependent = Bam.Core.Graph.Instance.FindReferencedModule<DependentModule>();
if (null == dependent)
{
return;
}
this.ScriptModule.AddFile(dependent, key);
}
/// <summary>
/// Include a folder in the installer, such as the output from one of the Publisher collation steps.
/// </summary>
/// <param name="key">Key.</param>
/// <typeparam name="DependentModule">The 1st type parameter.</typeparam>
public void
SourceFolder<DependentModule>(
string key
) where DependentModule : Bam.Core.Module, new()
{
var dependent = Bam.Core.Graph.Instance.FindReferencedModule<DependentModule>();
this.ScriptModule.AddPath(dependent, key);
}
protected sealed override void
EvaluateInternal()
{
// do nothing
}
protected sealed override void
ExecuteInternal(
Bam.Core.ExecutionContext context)
{
switch (Bam.Core.Graph.Instance.Mode)
{
#if D_PACKAGE_MAKEFILEBUILDER
case "MakeFile":
MakeFileBuilder.Support.Add(this);
break;
#endif
#if D_PACKAGE_NATIVEBUILDER
case "Native":
NativeBuilder.Support.RunCommandLineTool(this, context);
break;
#endif
#if D_PACKAGE_VSSOLUTIONBUILDER
case "VSSolution":
Bam.Core.Log.DebugMessage("InnoSetup not supported on VisualStudio builds");
break;
#endif
default:
throw new System.NotSupportedException();
}
}
/// <summary>
/// /copydoc Bam.Core.Module.InputModulePaths
/// </summary>
public override System.Collections.Generic.IEnumerable<(Bam.Core.Module module, string pathKey)> InputModulePaths
{
get
{
yield return (this.ScriptModule, InnoSetupScript.ScriptKey);
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.IO;
using System.Security.Cryptography;
using Test.Cryptography;
using Xunit;
namespace System.Security.Cryptography.Encryption.Aes.Tests
{
using Aes = System.Security.Cryptography.Aes;
public static class AesCornerTests
{
[Fact]
public static void EncryptorReusability()
{
byte[] key = "1ed2f625c187b993256a8b3ccf9dcbfa5b44b4795c731012f70e4e64732efd5d".HexToByteArray();
byte[] iv = "47d1e060ba3c8643f9f8b65feeda4b30".HexToByteArray();
byte[] plainText = "f238882f6530ae9191c294868feed0b0df4058b322377dec14690c3b6bbf6ad1dd5b7c063a28e2cca2a6dce8cc2e668ea6ce80cee4c1a1a955ff46c530f3801b".HexToByteArray();
// CBC, Padding.None
byte[] expectedCipher = "7c6e1bcd3c30d2fb2d92e3346048307dc6719a6b96a945b4d987af09469ec68f5ca535fab7f596fffa80f7cfaeb26eefaf8d4ca8be190393b2569249d673f042".HexToByteArray();
using (Aes a = Aes.Create())
{
a.Key = key;
a.IV = iv;
a.Mode = CipherMode.CBC;
a.Padding = PaddingMode.None;
ICryptoTransform encryptor = a.CreateEncryptor();
Assert.True(encryptor.CanReuseTransform);
for (int i = 0; i < 4; i++)
{
byte[] cipher = encryptor.Transform(plainText, 1);
Assert.Equal<byte>(expectedCipher, cipher);
}
}
}
[Fact]
public static void TransformStateSeparation()
{
byte[] key = "1ed2f625c187b993256a8b3ccf9dcbfa5b44b4795c731012f70e4e64732efd5d".HexToByteArray();
byte[] iv = "47d1e060ba3c8643f9f8b65feeda4b30".HexToByteArray();
byte[] plainText = "f238882f6530ae9191c294868feed0b0df4058b322377dec14690c3b6bbf6ad1dd5b7c063a28e2cca2a6dce8cc2e668ea6ce80cee4c1a1a955ff46c530f3801b".HexToByteArray();
// CBC, Padding.None
byte[] cipher = "7c6e1bcd3c30d2fb2d92e3346048307dc6719a6b96a945b4d987af09469ec68f5ca535fab7f596fffa80f7cfaeb26eefaf8d4ca8be190393b2569249d673f042".HexToByteArray();
using (Aes a = Aes.Create())
{
a.Key = key;
a.IV = iv;
a.Mode = CipherMode.CBC;
a.Padding = PaddingMode.None;
// To ensure that each ICryptoTransform maintains an independent encryption state, we'll create two encryptors and two decryptors.
// Then we'll feed them one block each in an interleaved fashion. At the end, they'd better still come up with the correct result.
MemoryStream plain1 = new MemoryStream(plainText);
MemoryStream plain2 = new MemoryStream(plainText);
MemoryStream cipher1 = new MemoryStream(cipher);
MemoryStream cipher2 = new MemoryStream(cipher);
ICryptoTransform encryptor1 = a.CreateEncryptor();
ICryptoTransform encryptor2 = a.CreateEncryptor();
ICryptoTransform decryptor1 = a.CreateDecryptor();
ICryptoTransform decryptor2 = a.CreateDecryptor();
List<byte> encryptionCollector1 = new List<byte>();
List<byte> encryptionCollector2 = new List<byte>();
List<byte> decryptionCollector1 = new List<byte>();
List<byte> decryptionCollector2 = new List<byte>();
int blockSize = a.BlockSize / 8;
encryptionCollector1.Collect(encryptor1, plain1, 1 * blockSize);
encryptionCollector2.Collect(encryptor2, plain2, 1 * blockSize);
encryptionCollector1.Collect(encryptor1, plain1, 1 * blockSize);
decryptionCollector1.Collect(decryptor1, cipher1, 1 * blockSize);
decryptionCollector2.Collect(decryptor2, cipher2, 1 * blockSize);
decryptionCollector2.Collect(decryptor2, cipher2, 1 * blockSize);
encryptionCollector1.Collect(encryptor1, plain1, 1 * blockSize);
decryptionCollector1.Collect(decryptor1, cipher1, 1 * blockSize);
decryptionCollector2.Collect(decryptor2, cipher2, 1 * blockSize);
decryptionCollector2.Collect(decryptor2, cipher2, 1 * blockSize);
encryptionCollector2.Collect(encryptor2, plain2, 1 * blockSize);
decryptionCollector1.Collect(decryptor1, cipher1, 1 * blockSize);
decryptionCollector2.AddRange(decryptor2.TransformFinalBlock(new byte[0], 0, 0));
decryptionCollector1.Collect(decryptor1, cipher1, 1 * blockSize);
encryptionCollector2.Collect(encryptor2, plain2, 1 * blockSize);
decryptionCollector1.AddRange(decryptor1.TransformFinalBlock(new byte[0], 0, 0));
encryptionCollector1.Collect(encryptor1, plain1, 1 * blockSize);
encryptionCollector1.AddRange(encryptor1.TransformFinalBlock(new byte[0], 0, 0));
encryptionCollector2.Collect(encryptor2, plain2, 1 * blockSize);
encryptionCollector2.AddRange(encryptor2.TransformFinalBlock(new byte[0], 0, 0));
Assert.Equal<byte>(cipher, encryptionCollector1.ToArray());
Assert.Equal<byte>(cipher, encryptionCollector2.ToArray());
Assert.Equal<byte>(plainText, decryptionCollector1.ToArray());
Assert.Equal<byte>(plainText, decryptionCollector2.ToArray());
}
}
private static void Collect(this List<byte> l, ICryptoTransform transform, Stream input, int count)
{
byte[] buffer = new byte[count];
int numRead = input.Read(buffer, 0, count);
Assert.Equal(count, numRead);
byte[] buffer2 = new byte[count];
int numBytesWritten = transform.TransformBlock(buffer, 0, count, buffer2, 0);
Array.Resize(ref buffer2, numBytesWritten);
l.AddRange(buffer2);
}
[Fact]
public static void MultipleBlockTransformNoPad()
{
// Ensure that multiple blocks can be transformed with one call (the no padding code path)
byte[] key = "1ed2f625c187b993256a8b3ccf9dcbfa5b44b4795c731012f70e4e64732efd5d".HexToByteArray();
byte[] iv = "47d1e060ba3c8643f9f8b65feeda4b30".HexToByteArray();
byte[] plainText = "f238882f6530ae9191c294868feed0b0df4058b322377dec14690c3b6bbf6ad1dd5b7c063a28e2cca2a6dce8cc2e668ea6ce80cee4c1a1a955ff46c530f3801b".HexToByteArray();
// CBC, Padding.None
byte[] expectedCipher = "7c6e1bcd3c30d2fb2d92e3346048307dc6719a6b96a945b4d987af09469ec68f5ca535fab7f596fffa80f7cfaeb26eefaf8d4ca8be190393b2569249d673f042".HexToByteArray();
using (Aes a = Aes.Create())
{
a.Key = key;
a.IV = iv;
a.Mode = CipherMode.CBC;
a.Padding = PaddingMode.None;
using (ICryptoTransform encryptor = a.CreateEncryptor())
{
Assert.True(encryptor.CanTransformMultipleBlocks);
byte[] cipher = encryptor.Transform(plainText, blockSizeMultipler: 2);
Assert.Equal<byte>(expectedCipher, cipher);
}
using (ICryptoTransform decryptor = a.CreateDecryptor())
{
Assert.True(decryptor.CanTransformMultipleBlocks);
byte[] decrypted = decryptor.Transform(expectedCipher, blockSizeMultipler: 2);
Assert.Equal<byte>(plainText, decrypted);
}
}
}
[Fact]
public static void MultipleBlockTransformPKCS7()
{
// Ensure that multiple blocks can be transformed with one call. (the PKCS7 code path)
byte[] key = "1ed2f625c187b993256a8b3ccf9dcbfa5b44b4795c731012f70e4e64732efd5d".HexToByteArray();
byte[] iv = "47d1e060ba3c8643f9f8b65feeda4b30".HexToByteArray();
byte[] plainText = "f238882f6530ae9191c294868feed0b0df4058b322377dec14690c3b6bbf6ad1dd5b7c063a28e2cca2a6dce8cc2e668ea6ce80cee4c1a1a955ff46c530f3801b".HexToByteArray();
// CBC, Padding.PKCS7
byte[] expectedCipher = "7c6e1bcd3c30d2fb2d92e3346048307dc6719a6b96a945b4d987af09469ec68f5ca535fab7f596fffa80f7cfaeb26eefaf8d4ca8be190393b2569249d673f042a6a223f1c1069aa1d3c19d6bc454c205".HexToByteArray();
using (Aes a = Aes.Create())
{
a.Key = key;
a.IV = iv;
a.Mode = CipherMode.CBC;
a.Padding = PaddingMode.PKCS7;
using (ICryptoTransform encryptor = a.CreateEncryptor())
{
Assert.True(encryptor.CanTransformMultipleBlocks);
byte[] cipher = encryptor.Transform(plainText, blockSizeMultipler: 2);
Assert.Equal<byte>(expectedCipher, cipher);
}
using (ICryptoTransform decryptor = a.CreateDecryptor())
{
Assert.True(decryptor.CanTransformMultipleBlocks);
byte[] decrypted = decryptor.Transform(expectedCipher, blockSizeMultipler: 2);
Assert.Equal<byte>(plainText, decrypted);
}
}
}
[Fact]
public static void FinalOnlyTransformNoPad()
{
// Use no TransformBlock calls() - do the entire transform using only TransformFinalBlock().
byte[] key = "1ed2f625c187b993256a8b3ccf9dcbfa5b44b4795c731012f70e4e64732efd5d".HexToByteArray();
byte[] iv = "47d1e060ba3c8643f9f8b65feeda4b30".HexToByteArray();
byte[] plainText = "f238882f6530ae9191c294868feed0b0df4058b322377dec14690c3b6bbf6ad1dd5b7c063a28e2cca2a6dce8cc2e668ea6ce80cee4c1a1a955ff46c530f3801b".HexToByteArray();
// CBC, Padding.None
byte[] expectedCipher = "7c6e1bcd3c30d2fb2d92e3346048307dc6719a6b96a945b4d987af09469ec68f5ca535fab7f596fffa80f7cfaeb26eefaf8d4ca8be190393b2569249d673f042".HexToByteArray();
using (Aes a = Aes.Create())
{
a.Key = key;
a.IV = iv;
a.Mode = CipherMode.CBC;
a.Padding = PaddingMode.None;
using (ICryptoTransform encryptor = a.CreateEncryptor())
{
Assert.True(encryptor.CanTransformMultipleBlocks);
byte[] cipher = encryptor.TransformFinalBlock(plainText, 0, plainText.Length);
Assert.Equal<byte>(expectedCipher, cipher);
}
using (ICryptoTransform decryptor = a.CreateDecryptor())
{
Assert.True(decryptor.CanTransformMultipleBlocks);
byte[] decrypted = decryptor.TransformFinalBlock(expectedCipher, 0, expectedCipher.Length);
Assert.Equal<byte>(plainText, decrypted);
}
}
}
[Fact]
public static void FinalOnlyTransformPKCS7()
{
// Use no TransformBlock calls() - do the entire transform using only TransformFinalBlock().
byte[] key = "1ed2f625c187b993256a8b3ccf9dcbfa5b44b4795c731012f70e4e64732efd5d".HexToByteArray();
byte[] iv = "47d1e060ba3c8643f9f8b65feeda4b30".HexToByteArray();
byte[] plainText = "f238882f6530ae9191c294868feed0b0df4058b322377dec14690c3b6bbf6ad1dd5b7c063a28e2cca2a6dce8cc2e668ea6ce80cee4c1a1a955ff46c530f3801b".HexToByteArray();
// CBC, Padding.PKCS7
byte[] expectedCipher = "7c6e1bcd3c30d2fb2d92e3346048307dc6719a6b96a945b4d987af09469ec68f5ca535fab7f596fffa80f7cfaeb26eefaf8d4ca8be190393b2569249d673f042a6a223f1c1069aa1d3c19d6bc454c205".HexToByteArray();
using (Aes a = Aes.Create())
{
a.Key = key;
a.IV = iv;
a.Mode = CipherMode.CBC;
a.Padding = PaddingMode.PKCS7;
using (ICryptoTransform encryptor = a.CreateEncryptor())
{
Assert.True(encryptor.CanTransformMultipleBlocks);
byte[] cipher = encryptor.TransformFinalBlock(plainText, 0, plainText.Length);
Assert.Equal<byte>(expectedCipher, cipher);
}
using (ICryptoTransform decryptor = a.CreateDecryptor())
{
Assert.True(decryptor.CanTransformMultipleBlocks);
byte[] decrypted = decryptor.TransformFinalBlock(expectedCipher, 0, expectedCipher.Length);
Assert.Equal<byte>(plainText, decrypted);
}
}
}
[Fact]
public static void ZeroLengthTransformNoPad()
{
// Use no TransformBlock calls() - do the entire transform using only TransformFinalBlock().
byte[] key = "1ed2f625c187b993256a8b3ccf9dcbfa5b44b4795c731012f70e4e64732efd5d".HexToByteArray();
byte[] iv = "47d1e060ba3c8643f9f8b65feeda4b30".HexToByteArray();
byte[] plainText = "".HexToByteArray();
// CBC, Padding.None
byte[] expectedCipher = "".HexToByteArray();
using (Aes a = Aes.Create())
{
a.Key = key;
a.IV = iv;
a.Mode = CipherMode.CBC;
a.Padding = PaddingMode.None;
using (ICryptoTransform encryptor = a.CreateEncryptor())
{
Assert.True(encryptor.CanTransformMultipleBlocks);
byte[] cipher = encryptor.TransformFinalBlock(plainText, 0, plainText.Length);
Assert.Equal<byte>(expectedCipher, cipher);
}
using (ICryptoTransform decryptor = a.CreateDecryptor())
{
Assert.True(decryptor.CanTransformMultipleBlocks);
byte[] decrypted = decryptor.TransformFinalBlock(expectedCipher, 0, expectedCipher.Length);
Assert.Equal<byte>(plainText, decrypted);
}
}
}
[Fact]
public static void ZeroLengthTransformPKCS7()
{
// Use no TransformBlock calls() - do the entire transform using only TransformFinalBlock().
byte[] key = "1ed2f625c187b993256a8b3ccf9dcbfa5b44b4795c731012f70e4e64732efd5d".HexToByteArray();
byte[] iv = "47d1e060ba3c8643f9f8b65feeda4b30".HexToByteArray();
byte[] plainText = "".HexToByteArray();
// CBC, Padding.PKCS7
byte[] expectedCipher = "d5450767bcc31793fe5065251b96b715".HexToByteArray();
using (Aes a = Aes.Create())
{
a.Key = key;
a.IV = iv;
a.Mode = CipherMode.CBC;
a.Padding = PaddingMode.PKCS7;
using (ICryptoTransform encryptor = a.CreateEncryptor())
{
Assert.True(encryptor.CanTransformMultipleBlocks);
byte[] cipher = encryptor.TransformFinalBlock(plainText, 0, plainText.Length);
Assert.Equal<byte>(expectedCipher, cipher);
}
using (ICryptoTransform decryptor = a.CreateDecryptor())
{
Assert.True(decryptor.CanTransformMultipleBlocks);
byte[] decrypted = decryptor.TransformFinalBlock(expectedCipher, 0, expectedCipher.Length);
Assert.Equal<byte>(plainText, decrypted);
}
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using System.Linq;
using System.Threading.Tasks;
using System.Web.Security;
using AutoMapper;
using Microsoft.AspNet.Identity;
using Microsoft.Owin;
using Umbraco.Core.Models.Identity;
using Umbraco.Core.Models.Membership;
using Umbraco.Core.Services;
namespace Umbraco.Core.Security
{
public class BackOfficeUserStore : DisposableObject,
IUserStore<BackOfficeIdentityUser, int>,
IUserPasswordStore<BackOfficeIdentityUser, int>,
IUserEmailStore<BackOfficeIdentityUser, int>,
IUserLoginStore<BackOfficeIdentityUser, int>,
IUserRoleStore<BackOfficeIdentityUser, int>,
IUserSecurityStampStore<BackOfficeIdentityUser, int>,
IUserLockoutStore<BackOfficeIdentityUser, int>,
IUserTwoFactorStore<BackOfficeIdentityUser, int>
//TODO: This would require additional columns/tables for now people will need to implement this on their own
//IUserPhoneNumberStore<BackOfficeIdentityUser, int>,
//TODO: To do this we need to implement IQueryable - we'll have an IQuerable implementation soon with the UmbracoLinqPadDriver implementation
//IQueryableUserStore<BackOfficeIdentityUser, int>
{
private readonly IUserService _userService;
private readonly IExternalLoginService _externalLoginService;
private bool _disposed = false;
public BackOfficeUserStore(IUserService userService, IExternalLoginService externalLoginService, MembershipProviderBase usersMembershipProvider)
{
_userService = userService;
_externalLoginService = externalLoginService;
if (userService == null) throw new ArgumentNullException("userService");
if (usersMembershipProvider == null) throw new ArgumentNullException("usersMembershipProvider");
if (externalLoginService == null) throw new ArgumentNullException("externalLoginService");
_userService = userService;
_externalLoginService = externalLoginService;
if (usersMembershipProvider.PasswordFormat != MembershipPasswordFormat.Hashed)
{
throw new InvalidOperationException("Cannot use ASP.Net Identity with UmbracoMembersUserStore when the password format is not Hashed");
}
}
/// <summary>
/// Handles the disposal of resources. Derived from abstract class <see cref="DisposableObject"/> which handles common required locking logic.
/// </summary>
protected override void DisposeResources()
{
_disposed = true;
}
/// <summary>
/// Insert a new user
/// </summary>
/// <param name="user"/>
/// <returns/>
public Task CreateAsync(BackOfficeIdentityUser user)
{
ThrowIfDisposed();
if (user == null) throw new ArgumentNullException("user");
var userType = _userService.GetUserTypeByAlias(
user.UserTypeAlias.IsNullOrWhiteSpace() ? _userService.GetDefaultMemberType() : user.UserTypeAlias);
var member = new User(userType)
{
DefaultToLiveEditing = false,
Email = user.Email,
Language = user.Culture ?? Configuration.GlobalSettings.DefaultUILanguage,
Name = user.Name,
Username = user.UserName,
StartContentId = user.StartContentId == 0 ? -1 : user.StartContentId,
StartMediaId = user.StartMediaId == 0 ? -1 : user.StartMediaId,
IsLockedOut = user.IsLockedOut,
IsApproved = true
};
UpdateMemberProperties(member, user);
//the password must be 'something' it could be empty if authenticating
// with an external provider so we'll just generate one and prefix it, the
// prefix will help us determine if the password hasn't actually been specified yet.
if (member.RawPasswordValue.IsNullOrWhiteSpace())
{
//this will hash the guid with a salt so should be nicely random
var aspHasher = new PasswordHasher();
member.RawPasswordValue = "___UIDEMPTYPWORD__" +
aspHasher.HashPassword(Guid.NewGuid().ToString("N"));
}
_userService.Save(member);
if (member.Id == 0) throw new DataException("Could not create the user, check logs for details");
//re-assign id
user.Id = member.Id;
return Task.FromResult(0);
}
/// <summary>
/// Update a user
/// </summary>
/// <param name="user"/>
/// <returns/>
public async Task UpdateAsync(BackOfficeIdentityUser user)
{
ThrowIfDisposed();
if (user == null) throw new ArgumentNullException("user");
var asInt = user.Id.TryConvertTo<int>();
if (asInt == false)
{
throw new InvalidOperationException("The user id must be an integer to work with the Umbraco");
}
var found = _userService.GetUserById(asInt.Result);
if (found != null)
{
if (UpdateMemberProperties(found, user))
{
_userService.Save(found);
}
if (user.LoginsChanged)
{
var logins = await GetLoginsAsync(user);
_externalLoginService.SaveUserLogins(found.Id, logins);
}
}
}
/// <summary>
/// Delete a user
/// </summary>
/// <param name="user"/>
/// <returns/>
public Task DeleteAsync(BackOfficeIdentityUser user)
{
ThrowIfDisposed();
if (user == null) throw new ArgumentNullException("user");
var asInt = user.Id.TryConvertTo<int>();
if (asInt == false)
{
throw new InvalidOperationException("The user id must be an integer to work with the Umbraco");
}
var found = _userService.GetUserById(asInt.Result);
if (found != null)
{
_userService.Delete(found);
}
_externalLoginService.DeleteUserLogins(asInt.Result);
return Task.FromResult(0);
}
/// <summary>
/// Finds a user
/// </summary>
/// <param name="userId"/>
/// <returns/>
public async Task<BackOfficeIdentityUser> FindByIdAsync(int userId)
{
ThrowIfDisposed();
var user = _userService.GetUserById(userId);
if (user == null)
{
return null;
}
return await Task.FromResult(AssignLoginsCallback(Mapper.Map<BackOfficeIdentityUser>(user)));
}
/// <summary>
/// Find a user by name
/// </summary>
/// <param name="userName"/>
/// <returns/>
public async Task<BackOfficeIdentityUser> FindByNameAsync(string userName)
{
ThrowIfDisposed();
var user = _userService.GetByUsername(userName);
if (user == null)
{
return null;
}
var result = AssignLoginsCallback(Mapper.Map<BackOfficeIdentityUser>(user));
return await Task.FromResult(result);
}
/// <summary>
/// Set the user password hash
/// </summary>
/// <param name="user"/><param name="passwordHash"/>
/// <returns/>
public Task SetPasswordHashAsync(BackOfficeIdentityUser user, string passwordHash)
{
ThrowIfDisposed();
if (user == null) throw new ArgumentNullException("user");
if (passwordHash.IsNullOrWhiteSpace()) throw new ArgumentNullException("passwordHash");
user.PasswordHash = passwordHash;
return Task.FromResult(0);
}
/// <summary>
/// Get the user password hash
/// </summary>
/// <param name="user"/>
/// <returns/>
public Task<string> GetPasswordHashAsync(BackOfficeIdentityUser user)
{
ThrowIfDisposed();
if (user == null) throw new ArgumentNullException("user");
return Task.FromResult(user.PasswordHash);
}
/// <summary>
/// Returns true if a user has a password set
/// </summary>
/// <param name="user"/>
/// <returns/>
public Task<bool> HasPasswordAsync(BackOfficeIdentityUser user)
{
ThrowIfDisposed();
if (user == null) throw new ArgumentNullException("user");
return Task.FromResult(user.PasswordHash.IsNullOrWhiteSpace() == false);
}
/// <summary>
/// Set the user email
/// </summary>
/// <param name="user"/><param name="email"/>
/// <returns/>
public Task SetEmailAsync(BackOfficeIdentityUser user, string email)
{
ThrowIfDisposed();
if (user == null) throw new ArgumentNullException("user");
if (email.IsNullOrWhiteSpace()) throw new ArgumentNullException("email");
user.Email = email;
return Task.FromResult(0);
}
/// <summary>
/// Get the user email
/// </summary>
/// <param name="user"/>
/// <returns/>
public Task<string> GetEmailAsync(BackOfficeIdentityUser user)
{
ThrowIfDisposed();
if (user == null) throw new ArgumentNullException("user");
return Task.FromResult(user.Email);
}
/// <summary>
/// Returns true if the user email is confirmed
/// </summary>
/// <param name="user"/>
/// <returns/>
public Task<bool> GetEmailConfirmedAsync(BackOfficeIdentityUser user)
{
ThrowIfDisposed();
throw new NotImplementedException();
}
/// <summary>
/// Sets whether the user email is confirmed
/// </summary>
/// <param name="user"/><param name="confirmed"/>
/// <returns/>
public Task SetEmailConfirmedAsync(BackOfficeIdentityUser user, bool confirmed)
{
ThrowIfDisposed();
throw new NotImplementedException();
}
/// <summary>
/// Returns the user associated with this email
/// </summary>
/// <param name="email"/>
/// <returns/>
public Task<BackOfficeIdentityUser> FindByEmailAsync(string email)
{
ThrowIfDisposed();
var user = _userService.GetByEmail(email);
var result = user == null
? null
: Mapper.Map<BackOfficeIdentityUser>(user);
return Task.FromResult(AssignLoginsCallback(result));
}
/// <summary>
/// Adds a user login with the specified provider and key
/// </summary>
/// <param name="user"/><param name="login"/>
/// <returns/>
public Task AddLoginAsync(BackOfficeIdentityUser user, UserLoginInfo login)
{
ThrowIfDisposed();
if (user == null) throw new ArgumentNullException("user");
if (login == null) throw new ArgumentNullException("login");
var logins = user.Logins;
var instance = new IdentityUserLogin(login.LoginProvider, login.ProviderKey, user.Id);
var userLogin = instance;
logins.Add(userLogin);
return Task.FromResult(0);
}
/// <summary>
/// Removes the user login with the specified combination if it exists
/// </summary>
/// <param name="user"/><param name="login"/>
/// <returns/>
public Task RemoveLoginAsync(BackOfficeIdentityUser user, UserLoginInfo login)
{
ThrowIfDisposed();
if (user == null) throw new ArgumentNullException("user");
if (login == null) throw new ArgumentNullException("login");
var provider = login.LoginProvider;
var key = login.ProviderKey;
var userLogin = user.Logins.SingleOrDefault((l => l.LoginProvider == provider && l.ProviderKey == key));
if (userLogin != null)
user.Logins.Remove(userLogin);
return Task.FromResult(0);
}
/// <summary>
/// Returns the linked accounts for this user
/// </summary>
/// <param name="user"/>
/// <returns/>
public Task<IList<UserLoginInfo>> GetLoginsAsync(BackOfficeIdentityUser user)
{
ThrowIfDisposed();
if (user == null) throw new ArgumentNullException("user");
return Task.FromResult((IList<UserLoginInfo>)
user.Logins.Select(l => new UserLoginInfo(l.LoginProvider, l.ProviderKey)).ToList());
}
/// <summary>
/// Returns the user associated with this login
/// </summary>
/// <returns/>
public Task<BackOfficeIdentityUser> FindAsync(UserLoginInfo login)
{
ThrowIfDisposed();
if (login == null) throw new ArgumentNullException("login");
//get all logins associated with the login id
var result = _externalLoginService.Find(login).ToArray();
if (result.Any())
{
//return the first member that matches the result
var output = (from l in result
select _userService.GetUserById(l.UserId)
into user
where user != null
select Mapper.Map<BackOfficeIdentityUser>(user)).FirstOrDefault();
return Task.FromResult(AssignLoginsCallback(output));
}
return Task.FromResult<BackOfficeIdentityUser>(null);
}
/// <summary>
/// Adds a user to a role (section)
/// </summary>
/// <param name="user"/><param name="roleName"/>
/// <returns/>
public Task AddToRoleAsync(BackOfficeIdentityUser user, string roleName)
{
ThrowIfDisposed();
if (user == null) throw new ArgumentNullException("user");
if (user.AllowedSections.InvariantContains(roleName)) return Task.FromResult(0);
var asInt = user.Id.TryConvertTo<int>();
if (asInt == false)
{
throw new InvalidOperationException("The user id must be an integer to work with the Umbraco");
}
var found = _userService.GetUserById(asInt.Result);
if (found != null)
{
found.AddAllowedSection(roleName);
}
return Task.FromResult(0);
}
/// <summary>
/// Removes the role (allowed section) for the user
/// </summary>
/// <param name="user"/><param name="roleName"/>
/// <returns/>
public Task RemoveFromRoleAsync(BackOfficeIdentityUser user, string roleName)
{
ThrowIfDisposed();
if (user == null) throw new ArgumentNullException("user");
if (user.AllowedSections.InvariantContains(roleName) == false) return Task.FromResult(0);
var asInt = user.Id.TryConvertTo<int>();
if (asInt == false)
{
throw new InvalidOperationException("The user id must be an integer to work with the Umbraco");
}
var found = _userService.GetUserById(asInt.Result);
if (found != null)
{
found.RemoveAllowedSection(roleName);
}
return Task.FromResult(0);
}
/// <summary>
/// Returns the roles for this user
/// </summary>
/// <param name="user"/>
/// <returns/>
public Task<IList<string>> GetRolesAsync(BackOfficeIdentityUser user)
{
ThrowIfDisposed();
if (user == null) throw new ArgumentNullException("user");
return Task.FromResult((IList<string>)user.AllowedSections.ToList());
}
/// <summary>
/// Returns true if a user is in the role
/// </summary>
/// <param name="user"/><param name="roleName"/>
/// <returns/>
public Task<bool> IsInRoleAsync(BackOfficeIdentityUser user, string roleName)
{
ThrowIfDisposed();
if (user == null) throw new ArgumentNullException("user");
return Task.FromResult(user.AllowedSections.InvariantContains(roleName));
}
/// <summary>
/// Set the security stamp for the user
/// </summary>
/// <param name="user"/><param name="stamp"/>
/// <returns/>
public Task SetSecurityStampAsync(BackOfficeIdentityUser user, string stamp)
{
ThrowIfDisposed();
if (user == null) throw new ArgumentNullException("user");
user.SecurityStamp = stamp;
return Task.FromResult(0);
}
/// <summary>
/// Get the user security stamp
/// </summary>
/// <param name="user"/>
/// <returns/>
public Task<string> GetSecurityStampAsync(BackOfficeIdentityUser user)
{
ThrowIfDisposed();
if (user == null) throw new ArgumentNullException("user");
//the stamp cannot be null, so if it is currently null then we'll just return a hash of the password
return Task.FromResult(user.SecurityStamp.IsNullOrWhiteSpace()
? user.PasswordHash.ToMd5()
: user.SecurityStamp);
}
private BackOfficeIdentityUser AssignLoginsCallback(BackOfficeIdentityUser user)
{
if (user != null)
{
user.SetLoginsCallback(new Lazy<IEnumerable<IIdentityUserLogin>>(() =>
_externalLoginService.GetAll(user.Id)));
}
return user;
}
/// <summary>
/// Sets whether two factor authentication is enabled for the user
/// </summary>
/// <param name="user"/><param name="enabled"/>
/// <returns/>
public virtual Task SetTwoFactorEnabledAsync(BackOfficeIdentityUser user, bool enabled)
{
user.TwoFactorEnabled = false;
return Task.FromResult(0);
}
/// <summary>
/// Returns whether two factor authentication is enabled for the user
/// </summary>
/// <param name="user"/>
/// <returns/>
public virtual Task<bool> GetTwoFactorEnabledAsync(BackOfficeIdentityUser user)
{
return Task.FromResult(false);
}
#region IUserLockoutStore
/// <summary>
/// Returns the DateTimeOffset that represents the end of a user's lockout, any time in the past should be considered not locked out.
/// </summary>
/// <param name="user"/>
/// <returns/>
/// <remarks>
/// Currently we do not suport a timed lock out, when they are locked out, an admin will have to reset the status
/// </remarks>
public Task<DateTimeOffset> GetLockoutEndDateAsync(BackOfficeIdentityUser user)
{
if (user == null) throw new ArgumentNullException("user");
return user.LockoutEndDateUtc.HasValue
? Task.FromResult(DateTimeOffset.MaxValue)
: Task.FromResult(DateTimeOffset.MinValue);
}
/// <summary>
/// Locks a user out until the specified end date (set to a past date, to unlock a user)
/// </summary>
/// <param name="user"/><param name="lockoutEnd"/>
/// <returns/>
public Task SetLockoutEndDateAsync(BackOfficeIdentityUser user, DateTimeOffset lockoutEnd)
{
if (user == null) throw new ArgumentNullException("user");
user.LockoutEndDateUtc = lockoutEnd.UtcDateTime;
return Task.FromResult(0);
}
/// <summary>
/// Used to record when an attempt to access the user has failed
/// </summary>
/// <param name="user"/>
/// <returns/>
public Task<int> IncrementAccessFailedCountAsync(BackOfficeIdentityUser user)
{
if (user == null) throw new ArgumentNullException("user");
user.AccessFailedCount++;
return Task.FromResult(user.AccessFailedCount);
}
/// <summary>
/// Used to reset the access failed count, typically after the account is successfully accessed
/// </summary>
/// <param name="user"/>
/// <returns/>
public Task ResetAccessFailedCountAsync(BackOfficeIdentityUser user)
{
if (user == null) throw new ArgumentNullException("user");
user.AccessFailedCount = 0;
return Task.FromResult(0);
}
/// <summary>
/// Returns the current number of failed access attempts. This number usually will be reset whenever the password is
/// verified or the account is locked out.
/// </summary>
/// <param name="user"/>
/// <returns/>
public Task<int> GetAccessFailedCountAsync(BackOfficeIdentityUser user)
{
if (user == null) throw new ArgumentNullException("user");
return Task.FromResult(user.AccessFailedCount);
}
/// <summary>
/// Returns true
/// </summary>
/// <param name="user"/>
/// <returns/>
public Task<bool> GetLockoutEnabledAsync(BackOfficeIdentityUser user)
{
if (user == null) throw new ArgumentNullException("user");
return Task.FromResult(user.LockoutEnabled);
}
/// <summary>
/// Doesn't actually perform any function, users can always be locked out
/// </summary>
/// <param name="user"/><param name="enabled"/>
/// <returns/>
public Task SetLockoutEnabledAsync(BackOfficeIdentityUser user, bool enabled)
{
if (user == null) throw new ArgumentNullException("user");
user.LockoutEnabled = enabled;
return Task.FromResult(0);
}
#endregion
private bool UpdateMemberProperties(Models.Membership.IUser user, BackOfficeIdentityUser identityUser)
{
var anythingChanged = false;
//don't assign anything if nothing has changed as this will trigger
//the track changes of the model
if (user.Name != identityUser.Name && identityUser.Name.IsNullOrWhiteSpace() == false)
{
anythingChanged = true;
user.Name = identityUser.Name;
}
if (user.Email != identityUser.Email && identityUser.Email.IsNullOrWhiteSpace() == false)
{
anythingChanged = true;
user.Email = identityUser.Email;
}
if (user.FailedPasswordAttempts != identityUser.AccessFailedCount)
{
anythingChanged = true;
user.FailedPasswordAttempts = identityUser.AccessFailedCount;
}
if (user.IsLockedOut != identityUser.IsLockedOut)
{
anythingChanged = true;
user.IsLockedOut = identityUser.IsLockedOut;
}
if (user.Username != identityUser.UserName && identityUser.UserName.IsNullOrWhiteSpace() == false)
{
anythingChanged = true;
user.Username = identityUser.UserName;
}
if (user.RawPasswordValue != identityUser.PasswordHash && identityUser.PasswordHash.IsNullOrWhiteSpace() == false)
{
anythingChanged = true;
user.RawPasswordValue = identityUser.PasswordHash;
}
if (user.Language != identityUser.Culture && identityUser.Culture.IsNullOrWhiteSpace() == false)
{
anythingChanged = true;
user.Language = identityUser.Culture;
}
if (user.StartMediaId != identityUser.StartMediaId)
{
anythingChanged = true;
user.StartMediaId = identityUser.StartMediaId;
}
if (user.StartContentId != identityUser.StartContentId)
{
anythingChanged = true;
user.StartContentId = identityUser.StartContentId;
}
if (user.SecurityStamp != identityUser.SecurityStamp)
{
anythingChanged = true;
user.SecurityStamp = identityUser.SecurityStamp;
}
if (user.AllowedSections.ContainsAll(identityUser.AllowedSections) == false
|| identityUser.AllowedSections.ContainsAll(user.AllowedSections) == false)
{
anythingChanged = true;
foreach (var allowedSection in user.AllowedSections)
{
user.RemoveAllowedSection(allowedSection);
}
foreach (var allowedApplication in identityUser.AllowedSections)
{
user.AddAllowedSection(allowedApplication);
}
}
return anythingChanged;
}
private void ThrowIfDisposed()
{
if (_disposed)
throw new ObjectDisposedException(GetType().Name);
}
}
}
| |
/*
* OANDA v20 REST API
*
* The full OANDA v20 REST API Specification. This specification defines how to interact with v20 Accounts, Trades, Orders, Pricing and more.
*
* OpenAPI spec version: 3.0.15
* Contact: [email protected]
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*/
using System;
using System.Linq;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System.ComponentModel.DataAnnotations;
namespace Oanda.RestV20.Model
{
/// <summary>
/// A TakeProfitOrder is an order that is linked to an open Trade and created with a price threshold. The Order will be filled (closing the Trade) by the first price that is equal to or better than the threshold. A TakeProfitOrder cannot be used to open a new Position.
/// </summary>
[DataContract]
public partial class TakeProfitOrder : IEquatable<TakeProfitOrder>, IValidatableObject
{
/// <summary>
/// The current state of the Order.
/// </summary>
/// <value>The current state of the Order.</value>
[JsonConverter(typeof(StringEnumConverter))]
public enum StateEnum
{
/// <summary>
/// Enum PENDING for "PENDING"
/// </summary>
[EnumMember(Value = "PENDING")]
PENDING,
/// <summary>
/// Enum FILLED for "FILLED"
/// </summary>
[EnumMember(Value = "FILLED")]
FILLED,
/// <summary>
/// Enum TRIGGERED for "TRIGGERED"
/// </summary>
[EnumMember(Value = "TRIGGERED")]
TRIGGERED,
/// <summary>
/// Enum CANCELLED for "CANCELLED"
/// </summary>
[EnumMember(Value = "CANCELLED")]
CANCELLED
}
/// <summary>
/// The type of the Order. Always set to \"TAKE_PROFIT\" for Take Profit Orders.
/// </summary>
/// <value>The type of the Order. Always set to \"TAKE_PROFIT\" for Take Profit Orders.</value>
[JsonConverter(typeof(StringEnumConverter))]
public enum TypeEnum
{
/// <summary>
/// Enum MARKET for "MARKET"
/// </summary>
[EnumMember(Value = "MARKET")]
MARKET,
/// <summary>
/// Enum LIMIT for "LIMIT"
/// </summary>
[EnumMember(Value = "LIMIT")]
LIMIT,
/// <summary>
/// Enum STOP for "STOP"
/// </summary>
[EnumMember(Value = "STOP")]
STOP,
/// <summary>
/// Enum MARKETIFTOUCHED for "MARKET_IF_TOUCHED"
/// </summary>
[EnumMember(Value = "MARKET_IF_TOUCHED")]
MARKETIFTOUCHED,
/// <summary>
/// Enum TAKEPROFIT for "TAKE_PROFIT"
/// </summary>
[EnumMember(Value = "TAKE_PROFIT")]
TAKEPROFIT,
/// <summary>
/// Enum STOPLOSS for "STOP_LOSS"
/// </summary>
[EnumMember(Value = "STOP_LOSS")]
STOPLOSS,
/// <summary>
/// Enum TRAILINGSTOPLOSS for "TRAILING_STOP_LOSS"
/// </summary>
[EnumMember(Value = "TRAILING_STOP_LOSS")]
TRAILINGSTOPLOSS
}
/// <summary>
/// The time-in-force requested for the TakeProfit Order. Restricted to \"GTC\", \"GFD\" and \"GTD\" for TakeProfit Orders.
/// </summary>
/// <value>The time-in-force requested for the TakeProfit Order. Restricted to \"GTC\", \"GFD\" and \"GTD\" for TakeProfit Orders.</value>
[JsonConverter(typeof(StringEnumConverter))]
public enum TimeInForceEnum
{
/// <summary>
/// Enum GTC for "GTC"
/// </summary>
[EnumMember(Value = "GTC")]
GTC,
/// <summary>
/// Enum GTD for "GTD"
/// </summary>
[EnumMember(Value = "GTD")]
GTD,
/// <summary>
/// Enum GFD for "GFD"
/// </summary>
[EnumMember(Value = "GFD")]
GFD,
/// <summary>
/// Enum FOK for "FOK"
/// </summary>
[EnumMember(Value = "FOK")]
FOK,
/// <summary>
/// Enum IOC for "IOC"
/// </summary>
[EnumMember(Value = "IOC")]
IOC
}
/// <summary>
/// Specification of what component of a price should be used for comparison when determining if the Order should be filled.
/// </summary>
/// <value>Specification of what component of a price should be used for comparison when determining if the Order should be filled.</value>
[JsonConverter(typeof(StringEnumConverter))]
public enum TriggerConditionEnum
{
/// <summary>
/// Enum DEFAULT for "DEFAULT"
/// </summary>
[EnumMember(Value = "DEFAULT")]
DEFAULT,
/// <summary>
/// Enum TRIGGERDEFAULT for "TRIGGER_DEFAULT"
/// </summary>
[EnumMember(Value = "TRIGGER_DEFAULT")]
TRIGGERDEFAULT,
/// <summary>
/// Enum INVERSE for "INVERSE"
/// </summary>
[EnumMember(Value = "INVERSE")]
INVERSE,
/// <summary>
/// Enum BID for "BID"
/// </summary>
[EnumMember(Value = "BID")]
BID,
/// <summary>
/// Enum ASK for "ASK"
/// </summary>
[EnumMember(Value = "ASK")]
ASK,
/// <summary>
/// Enum MID for "MID"
/// </summary>
[EnumMember(Value = "MID")]
MID
}
/// <summary>
/// The current state of the Order.
/// </summary>
/// <value>The current state of the Order.</value>
[DataMember(Name="state", EmitDefaultValue=false)]
public StateEnum? State { get; set; }
/// <summary>
/// The type of the Order. Always set to \"TAKE_PROFIT\" for Take Profit Orders.
/// </summary>
/// <value>The type of the Order. Always set to \"TAKE_PROFIT\" for Take Profit Orders.</value>
[DataMember(Name="type", EmitDefaultValue=false)]
public TypeEnum? Type { get; set; }
/// <summary>
/// The time-in-force requested for the TakeProfit Order. Restricted to \"GTC\", \"GFD\" and \"GTD\" for TakeProfit Orders.
/// </summary>
/// <value>The time-in-force requested for the TakeProfit Order. Restricted to \"GTC\", \"GFD\" and \"GTD\" for TakeProfit Orders.</value>
[DataMember(Name="timeInForce", EmitDefaultValue=false)]
public TimeInForceEnum? TimeInForce { get; set; }
/// <summary>
/// Specification of what component of a price should be used for comparison when determining if the Order should be filled.
/// </summary>
/// <value>Specification of what component of a price should be used for comparison when determining if the Order should be filled.</value>
[DataMember(Name="triggerCondition", EmitDefaultValue=false)]
public TriggerConditionEnum? TriggerCondition { get; set; }
/// <summary>
/// Initializes a new instance of the <see cref="TakeProfitOrder" /> class.
/// </summary>
/// <param name="Id">The Order's identifier, unique within the Order's Account..</param>
/// <param name="CreateTime">The time when the Order was created..</param>
/// <param name="State">The current state of the Order..</param>
/// <param name="ClientExtensions">ClientExtensions.</param>
/// <param name="Type">The type of the Order. Always set to \"TAKE_PROFIT\" for Take Profit Orders..</param>
/// <param name="TradeID">The ID of the Trade to close when the price threshold is breached..</param>
/// <param name="ClientTradeID">The client ID of the Trade to be closed when the price threshold is breached..</param>
/// <param name="Price">The price threshold specified for the TakeProfit Order. The associated Trade will be closed by a market price that is equal to or better than this threshold..</param>
/// <param name="TimeInForce">The time-in-force requested for the TakeProfit Order. Restricted to \"GTC\", \"GFD\" and \"GTD\" for TakeProfit Orders..</param>
/// <param name="GtdTime">The date/time when the TakeProfit Order will be cancelled if its timeInForce is \"GTD\"..</param>
/// <param name="TriggerCondition">Specification of what component of a price should be used for comparison when determining if the Order should be filled..</param>
/// <param name="FillingTransactionID">ID of the Transaction that filled this Order (only provided when the Order's state is FILLED).</param>
/// <param name="FilledTime">Date/time when the Order was filled (only provided when the Order's state is FILLED).</param>
/// <param name="TradeOpenedID">Trade ID of Trade opened when the Order was filled (only provided when the Order's state is FILLED and a Trade was opened as a result of the fill).</param>
/// <param name="TradeReducedID">Trade ID of Trade reduced when the Order was filled (only provided when the Order's state is FILLED and a Trade was reduced as a result of the fill).</param>
/// <param name="TradeClosedIDs">Trade IDs of Trades closed when the Order was filled (only provided when the Order's state is FILLED and one or more Trades were closed as a result of the fill).</param>
/// <param name="CancellingTransactionID">ID of the Transaction that cancelled the Order (only provided when the Order's state is CANCELLED).</param>
/// <param name="CancelledTime">Date/time when the Order was cancelled (only provided when the state of the Order is CANCELLED).</param>
/// <param name="ReplacesOrderID">The ID of the Order that was replaced by this Order (only provided if this Order was created as part of a cancel/replace)..</param>
/// <param name="ReplacedByOrderID">The ID of the Order that replaced this Order (only provided if this Order was cancelled as part of a cancel/replace)..</param>
public TakeProfitOrder(string Id = default(string), string CreateTime = default(string), StateEnum? State = default(StateEnum?), ClientExtensions ClientExtensions = default(ClientExtensions), TypeEnum? Type = default(TypeEnum?), string TradeID = default(string), string ClientTradeID = default(string), string Price = default(string), TimeInForceEnum? TimeInForce = default(TimeInForceEnum?), string GtdTime = default(string), TriggerConditionEnum? TriggerCondition = default(TriggerConditionEnum?), string FillingTransactionID = default(string), string FilledTime = default(string), string TradeOpenedID = default(string), string TradeReducedID = default(string), List<string> TradeClosedIDs = default(List<string>), string CancellingTransactionID = default(string), string CancelledTime = default(string), string ReplacesOrderID = default(string), string ReplacedByOrderID = default(string))
{
this.Id = Id;
this.CreateTime = CreateTime;
this.State = State;
this.ClientExtensions = ClientExtensions;
this.Type = Type;
this.TradeID = TradeID;
this.ClientTradeID = ClientTradeID;
this.Price = Price;
this.TimeInForce = TimeInForce;
this.GtdTime = GtdTime;
this.TriggerCondition = TriggerCondition;
this.FillingTransactionID = FillingTransactionID;
this.FilledTime = FilledTime;
this.TradeOpenedID = TradeOpenedID;
this.TradeReducedID = TradeReducedID;
this.TradeClosedIDs = TradeClosedIDs;
this.CancellingTransactionID = CancellingTransactionID;
this.CancelledTime = CancelledTime;
this.ReplacesOrderID = ReplacesOrderID;
this.ReplacedByOrderID = ReplacedByOrderID;
}
/// <summary>
/// The Order's identifier, unique within the Order's Account.
/// </summary>
/// <value>The Order's identifier, unique within the Order's Account.</value>
[DataMember(Name="id", EmitDefaultValue=false)]
public string Id { get; set; }
/// <summary>
/// The time when the Order was created.
/// </summary>
/// <value>The time when the Order was created.</value>
[DataMember(Name="createTime", EmitDefaultValue=false)]
public string CreateTime { get; set; }
/// <summary>
/// Gets or Sets ClientExtensions
/// </summary>
[DataMember(Name="clientExtensions", EmitDefaultValue=false)]
public ClientExtensions ClientExtensions { get; set; }
/// <summary>
/// The ID of the Trade to close when the price threshold is breached.
/// </summary>
/// <value>The ID of the Trade to close when the price threshold is breached.</value>
[DataMember(Name="tradeID", EmitDefaultValue=false)]
public string TradeID { get; set; }
/// <summary>
/// The client ID of the Trade to be closed when the price threshold is breached.
/// </summary>
/// <value>The client ID of the Trade to be closed when the price threshold is breached.</value>
[DataMember(Name="clientTradeID", EmitDefaultValue=false)]
public string ClientTradeID { get; set; }
/// <summary>
/// The price threshold specified for the TakeProfit Order. The associated Trade will be closed by a market price that is equal to or better than this threshold.
/// </summary>
/// <value>The price threshold specified for the TakeProfit Order. The associated Trade will be closed by a market price that is equal to or better than this threshold.</value>
[DataMember(Name="price", EmitDefaultValue=false)]
public string Price { get; set; }
/// <summary>
/// The date/time when the TakeProfit Order will be cancelled if its timeInForce is \"GTD\".
/// </summary>
/// <value>The date/time when the TakeProfit Order will be cancelled if its timeInForce is \"GTD\".</value>
[DataMember(Name="gtdTime", EmitDefaultValue=false)]
public string GtdTime { get; set; }
/// <summary>
/// ID of the Transaction that filled this Order (only provided when the Order's state is FILLED)
/// </summary>
/// <value>ID of the Transaction that filled this Order (only provided when the Order's state is FILLED)</value>
[DataMember(Name="fillingTransactionID", EmitDefaultValue=false)]
public string FillingTransactionID { get; set; }
/// <summary>
/// Date/time when the Order was filled (only provided when the Order's state is FILLED)
/// </summary>
/// <value>Date/time when the Order was filled (only provided when the Order's state is FILLED)</value>
[DataMember(Name="filledTime", EmitDefaultValue=false)]
public string FilledTime { get; set; }
/// <summary>
/// Trade ID of Trade opened when the Order was filled (only provided when the Order's state is FILLED and a Trade was opened as a result of the fill)
/// </summary>
/// <value>Trade ID of Trade opened when the Order was filled (only provided when the Order's state is FILLED and a Trade was opened as a result of the fill)</value>
[DataMember(Name="tradeOpenedID", EmitDefaultValue=false)]
public string TradeOpenedID { get; set; }
/// <summary>
/// Trade ID of Trade reduced when the Order was filled (only provided when the Order's state is FILLED and a Trade was reduced as a result of the fill)
/// </summary>
/// <value>Trade ID of Trade reduced when the Order was filled (only provided when the Order's state is FILLED and a Trade was reduced as a result of the fill)</value>
[DataMember(Name="tradeReducedID", EmitDefaultValue=false)]
public string TradeReducedID { get; set; }
/// <summary>
/// Trade IDs of Trades closed when the Order was filled (only provided when the Order's state is FILLED and one or more Trades were closed as a result of the fill)
/// </summary>
/// <value>Trade IDs of Trades closed when the Order was filled (only provided when the Order's state is FILLED and one or more Trades were closed as a result of the fill)</value>
[DataMember(Name="tradeClosedIDs", EmitDefaultValue=false)]
public List<string> TradeClosedIDs { get; set; }
/// <summary>
/// ID of the Transaction that cancelled the Order (only provided when the Order's state is CANCELLED)
/// </summary>
/// <value>ID of the Transaction that cancelled the Order (only provided when the Order's state is CANCELLED)</value>
[DataMember(Name="cancellingTransactionID", EmitDefaultValue=false)]
public string CancellingTransactionID { get; set; }
/// <summary>
/// Date/time when the Order was cancelled (only provided when the state of the Order is CANCELLED)
/// </summary>
/// <value>Date/time when the Order was cancelled (only provided when the state of the Order is CANCELLED)</value>
[DataMember(Name="cancelledTime", EmitDefaultValue=false)]
public string CancelledTime { get; set; }
/// <summary>
/// The ID of the Order that was replaced by this Order (only provided if this Order was created as part of a cancel/replace).
/// </summary>
/// <value>The ID of the Order that was replaced by this Order (only provided if this Order was created as part of a cancel/replace).</value>
[DataMember(Name="replacesOrderID", EmitDefaultValue=false)]
public string ReplacesOrderID { get; set; }
/// <summary>
/// The ID of the Order that replaced this Order (only provided if this Order was cancelled as part of a cancel/replace).
/// </summary>
/// <value>The ID of the Order that replaced this Order (only provided if this Order was cancelled as part of a cancel/replace).</value>
[DataMember(Name="replacedByOrderID", EmitDefaultValue=false)]
public string ReplacedByOrderID { get; set; }
/// <summary>
/// Returns the string presentation of the object
/// </summary>
/// <returns>String presentation of the object</returns>
public override string ToString()
{
var sb = new StringBuilder();
sb.Append("class TakeProfitOrder {\n");
sb.Append(" Id: ").Append(Id).Append("\n");
sb.Append(" CreateTime: ").Append(CreateTime).Append("\n");
sb.Append(" State: ").Append(State).Append("\n");
sb.Append(" ClientExtensions: ").Append(ClientExtensions).Append("\n");
sb.Append(" Type: ").Append(Type).Append("\n");
sb.Append(" TradeID: ").Append(TradeID).Append("\n");
sb.Append(" ClientTradeID: ").Append(ClientTradeID).Append("\n");
sb.Append(" Price: ").Append(Price).Append("\n");
sb.Append(" TimeInForce: ").Append(TimeInForce).Append("\n");
sb.Append(" GtdTime: ").Append(GtdTime).Append("\n");
sb.Append(" TriggerCondition: ").Append(TriggerCondition).Append("\n");
sb.Append(" FillingTransactionID: ").Append(FillingTransactionID).Append("\n");
sb.Append(" FilledTime: ").Append(FilledTime).Append("\n");
sb.Append(" TradeOpenedID: ").Append(TradeOpenedID).Append("\n");
sb.Append(" TradeReducedID: ").Append(TradeReducedID).Append("\n");
sb.Append(" TradeClosedIDs: ").Append(TradeClosedIDs).Append("\n");
sb.Append(" CancellingTransactionID: ").Append(CancellingTransactionID).Append("\n");
sb.Append(" CancelledTime: ").Append(CancelledTime).Append("\n");
sb.Append(" ReplacesOrderID: ").Append(ReplacesOrderID).Append("\n");
sb.Append(" ReplacedByOrderID: ").Append(ReplacedByOrderID).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
/// <summary>
/// Returns the JSON string presentation of the object
/// </summary>
/// <returns>JSON string presentation of the object</returns>
public string ToJson()
{
return JsonConvert.SerializeObject(this, Formatting.Indented);
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
/// <param name="obj">Object to be compared</param>
/// <returns>Boolean</returns>
public override bool Equals(object obj)
{
// credit: http://stackoverflow.com/a/10454552/677735
return this.Equals(obj as TakeProfitOrder);
}
/// <summary>
/// Returns true if TakeProfitOrder instances are equal
/// </summary>
/// <param name="other">Instance of TakeProfitOrder to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(TakeProfitOrder other)
{
// credit: http://stackoverflow.com/a/10454552/677735
if (other == null)
return false;
return
(
this.Id == other.Id ||
this.Id != null &&
this.Id.Equals(other.Id)
) &&
(
this.CreateTime == other.CreateTime ||
this.CreateTime != null &&
this.CreateTime.Equals(other.CreateTime)
) &&
(
this.State == other.State ||
this.State != null &&
this.State.Equals(other.State)
) &&
(
this.ClientExtensions == other.ClientExtensions ||
this.ClientExtensions != null &&
this.ClientExtensions.Equals(other.ClientExtensions)
) &&
(
this.Type == other.Type ||
this.Type != null &&
this.Type.Equals(other.Type)
) &&
(
this.TradeID == other.TradeID ||
this.TradeID != null &&
this.TradeID.Equals(other.TradeID)
) &&
(
this.ClientTradeID == other.ClientTradeID ||
this.ClientTradeID != null &&
this.ClientTradeID.Equals(other.ClientTradeID)
) &&
(
this.Price == other.Price ||
this.Price != null &&
this.Price.Equals(other.Price)
) &&
(
this.TimeInForce == other.TimeInForce ||
this.TimeInForce != null &&
this.TimeInForce.Equals(other.TimeInForce)
) &&
(
this.GtdTime == other.GtdTime ||
this.GtdTime != null &&
this.GtdTime.Equals(other.GtdTime)
) &&
(
this.TriggerCondition == other.TriggerCondition ||
this.TriggerCondition != null &&
this.TriggerCondition.Equals(other.TriggerCondition)
) &&
(
this.FillingTransactionID == other.FillingTransactionID ||
this.FillingTransactionID != null &&
this.FillingTransactionID.Equals(other.FillingTransactionID)
) &&
(
this.FilledTime == other.FilledTime ||
this.FilledTime != null &&
this.FilledTime.Equals(other.FilledTime)
) &&
(
this.TradeOpenedID == other.TradeOpenedID ||
this.TradeOpenedID != null &&
this.TradeOpenedID.Equals(other.TradeOpenedID)
) &&
(
this.TradeReducedID == other.TradeReducedID ||
this.TradeReducedID != null &&
this.TradeReducedID.Equals(other.TradeReducedID)
) &&
(
this.TradeClosedIDs == other.TradeClosedIDs ||
this.TradeClosedIDs != null &&
this.TradeClosedIDs.SequenceEqual(other.TradeClosedIDs)
) &&
(
this.CancellingTransactionID == other.CancellingTransactionID ||
this.CancellingTransactionID != null &&
this.CancellingTransactionID.Equals(other.CancellingTransactionID)
) &&
(
this.CancelledTime == other.CancelledTime ||
this.CancelledTime != null &&
this.CancelledTime.Equals(other.CancelledTime)
) &&
(
this.ReplacesOrderID == other.ReplacesOrderID ||
this.ReplacesOrderID != null &&
this.ReplacesOrderID.Equals(other.ReplacesOrderID)
) &&
(
this.ReplacedByOrderID == other.ReplacedByOrderID ||
this.ReplacedByOrderID != null &&
this.ReplacedByOrderID.Equals(other.ReplacedByOrderID)
);
}
/// <summary>
/// Gets the hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
// credit: http://stackoverflow.com/a/263416/677735
unchecked // Overflow is fine, just wrap
{
int hash = 41;
// Suitable nullity checks etc, of course :)
if (this.Id != null)
hash = hash * 59 + this.Id.GetHashCode();
if (this.CreateTime != null)
hash = hash * 59 + this.CreateTime.GetHashCode();
if (this.State != null)
hash = hash * 59 + this.State.GetHashCode();
if (this.ClientExtensions != null)
hash = hash * 59 + this.ClientExtensions.GetHashCode();
if (this.Type != null)
hash = hash * 59 + this.Type.GetHashCode();
if (this.TradeID != null)
hash = hash * 59 + this.TradeID.GetHashCode();
if (this.ClientTradeID != null)
hash = hash * 59 + this.ClientTradeID.GetHashCode();
if (this.Price != null)
hash = hash * 59 + this.Price.GetHashCode();
if (this.TimeInForce != null)
hash = hash * 59 + this.TimeInForce.GetHashCode();
if (this.GtdTime != null)
hash = hash * 59 + this.GtdTime.GetHashCode();
if (this.TriggerCondition != null)
hash = hash * 59 + this.TriggerCondition.GetHashCode();
if (this.FillingTransactionID != null)
hash = hash * 59 + this.FillingTransactionID.GetHashCode();
if (this.FilledTime != null)
hash = hash * 59 + this.FilledTime.GetHashCode();
if (this.TradeOpenedID != null)
hash = hash * 59 + this.TradeOpenedID.GetHashCode();
if (this.TradeReducedID != null)
hash = hash * 59 + this.TradeReducedID.GetHashCode();
if (this.TradeClosedIDs != null)
hash = hash * 59 + this.TradeClosedIDs.GetHashCode();
if (this.CancellingTransactionID != null)
hash = hash * 59 + this.CancellingTransactionID.GetHashCode();
if (this.CancelledTime != null)
hash = hash * 59 + this.CancelledTime.GetHashCode();
if (this.ReplacesOrderID != null)
hash = hash * 59 + this.ReplacesOrderID.GetHashCode();
if (this.ReplacedByOrderID != null)
hash = hash * 59 + this.ReplacedByOrderID.GetHashCode();
return hash;
}
}
/// <summary>
/// To validate all properties of the instance
/// </summary>
/// <param name="validationContext">Validation context</param>
/// <returns>Validation Result</returns>
IEnumerable<System.ComponentModel.DataAnnotations.ValidationResult> IValidatableObject.Validate(ValidationContext validationContext)
{
yield break;
}
}
}
| |
/* ****************************************************************************
*
* Copyright (c) Microsoft Corporation.
*
* This source code is subject to terms and conditions of the Apache License, Version 2.0. A
* copy of the license can be found in the License.html file at the root of this distribution. If
* you cannot locate the Apache License, Version 2.0, please send an email to
* [email protected]. By using this source code in any fashion, you are agreeing to be bound
* by the terms of the Apache License, Version 2.0.
*
* You must not remove this notice, or any other, from this software.
*
* ***************************************************************************/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.InteropServices;
using System.Security.Permissions;
using Microsoft.VisualStudio;
using Microsoft.VisualStudio.OLE.Interop;
using Microsoft.VisualStudio.Shell;
namespace Microsoft.VisualStudio.Project
{
internal enum tagDVASPECT
{
DVASPECT_CONTENT = 1,
DVASPECT_THUMBNAIL = 2,
DVASPECT_ICON = 4,
DVASPECT_DOCPRINT = 8
}
internal enum tagTYMED
{
TYMED_HGLOBAL = 1,
TYMED_FILE = 2,
TYMED_ISTREAM = 4,
TYMED_ISTORAGE = 8,
TYMED_GDI = 16,
TYMED_MFPICT = 32,
TYMED_ENHMF = 64,
TYMED_NULL = 0
}
internal sealed class DataCacheEntry : IDisposable
{
#region fields
/// <summary>
/// Defines an object that will be a mutex for this object for synchronizing thread calls.
/// </summary>
private static volatile object Mutex = new object();
private FORMATETC format;
private long data;
private DATADIR dataDir;
private bool isDisposed;
#endregion
#region properties
internal FORMATETC Format
{
get
{
return this.format;
}
}
internal long Data
{
get
{
return this.data;
}
}
[SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal DATADIR DataDir
{
get
{
return this.dataDir;
}
}
#endregion
/// <summary>
/// The IntPtr is data allocated that should be removed. It is allocated by the ProcessSelectionData method.
/// </summary>
internal DataCacheEntry(FORMATETC fmt, IntPtr data, DATADIR dir)
{
this.format = fmt;
this.data = (long)data;
this.dataDir = dir;
}
#region Dispose
~DataCacheEntry()
{
Dispose(false);
}
/// <summary>
/// The IDispose interface Dispose method for disposing the object determinastically.
/// </summary>
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
/// <summary>
/// The method that does the cleanup.
/// </summary>
/// <param name="disposing"></param>
private void Dispose(bool disposing)
{
// Everybody can go here.
if(!this.isDisposed)
{
// Synchronize calls to the Dispose simulteniously.
lock(Mutex)
{
if(disposing && this.data != 0)
{
Marshal.FreeHGlobal((IntPtr)this.data);
this.data = 0;
}
this.isDisposed = true;
}
}
}
#endregion
}
/// <summary>
/// Unfortunately System.Windows.Forms.IDataObject and
/// Microsoft.VisualStudio.OLE.Interop.IDataObject are different...
/// </summary>
internal sealed class DataObject : IDataObject
{
#region fields
internal const int DATA_S_SAMEFORMATETC = 0x00040130;
EventSinkCollection map;
ArrayList entries;
#endregion
internal DataObject()
{
this.map = new EventSinkCollection();
this.entries = new ArrayList();
}
internal void SetData(FORMATETC format, IntPtr data)
{
this.entries.Add(new DataCacheEntry(format, data, DATADIR.DATADIR_SET));
}
#region IDataObject methods
int IDataObject.DAdvise(FORMATETC[] e, uint adv, IAdviseSink sink, out uint cookie)
{
if (e == null)
{
throw new ArgumentNullException("e");
}
STATDATA sdata = new STATDATA();
sdata.ADVF = adv;
sdata.FORMATETC = e[0];
sdata.pAdvSink = sink;
cookie = this.map.Add(sdata);
sdata.dwConnection = cookie;
return 0;
}
void IDataObject.DUnadvise(uint cookie)
{
this.map.RemoveAt(cookie);
}
int IDataObject.EnumDAdvise(out IEnumSTATDATA e)
{
e = new EnumSTATDATA((IEnumerable)this.map);
return 0; //??
}
int IDataObject.EnumFormatEtc(uint direction, out IEnumFORMATETC penum)
{
penum = new EnumFORMATETC((DATADIR)direction, (IEnumerable)this.entries);
return 0;
}
int IDataObject.GetCanonicalFormatEtc(FORMATETC[] format, FORMATETC[] fmt)
{
throw new System.Runtime.InteropServices.COMException("", DATA_S_SAMEFORMATETC);
}
void IDataObject.GetData(FORMATETC[] fmt, STGMEDIUM[] m)
{
STGMEDIUM retMedium = new STGMEDIUM();
if(fmt == null || fmt.Length < 1)
return;
foreach(DataCacheEntry e in this.entries)
{
if(e.Format.cfFormat == fmt[0].cfFormat /*|| fmt[0].cfFormat == InternalNativeMethods.CF_HDROP*/)
{
retMedium.tymed = e.Format.tymed;
// Caller must delete the memory.
retMedium.unionmember = DragDropHelper.CopyHGlobal(new IntPtr(e.Data));
break;
}
}
if(m != null && m.Length > 0)
m[0] = retMedium;
}
void IDataObject.GetDataHere(FORMATETC[] fmt, STGMEDIUM[] m)
{
}
int IDataObject.QueryGetData(FORMATETC[] fmt)
{
if(fmt == null || fmt.Length < 1)
return VSConstants.S_FALSE;
foreach(DataCacheEntry e in this.entries)
{
if(e.Format.cfFormat == fmt[0].cfFormat /*|| fmt[0].cfFormat == InternalNativeMethods.CF_HDROP*/)
return VSConstants.S_OK;
}
return VSConstants.S_FALSE;
}
void IDataObject.SetData(FORMATETC[] fmt, STGMEDIUM[] m, int fRelease)
{
}
#endregion
}
[SecurityPermissionAttribute(SecurityAction.Demand, Flags = SecurityPermissionFlag.UnmanagedCode)]
internal static class DragDropHelper
{
#pragma warning disable 414
internal static readonly ushort CF_VSREFPROJECTITEMS;
internal static readonly ushort CF_VSSTGPROJECTITEMS;
internal static readonly ushort CF_VSPROJECTCLIPDESCRIPTOR;
#pragma warning restore 414
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1810:InitializeReferenceTypeStaticFieldsInline")]
static DragDropHelper()
{
CF_VSREFPROJECTITEMS = UnsafeNativeMethods.RegisterClipboardFormat("CF_VSREFPROJECTITEMS");
CF_VSSTGPROJECTITEMS = UnsafeNativeMethods.RegisterClipboardFormat("CF_VSSTGPROJECTITEMS");
CF_VSPROJECTCLIPDESCRIPTOR = UnsafeNativeMethods.RegisterClipboardFormat("CF_PROJECTCLIPBOARDDESCRIPTOR");
}
public static FORMATETC CreateFormatEtc(ushort iFormat)
{
FORMATETC fmt = new FORMATETC();
fmt.cfFormat = iFormat;
fmt.ptd = IntPtr.Zero;
fmt.dwAspect = (uint)DVASPECT.DVASPECT_CONTENT;
fmt.lindex = -1;
fmt.tymed = (uint)TYMED.TYMED_HGLOBAL;
return fmt;
}
public static int QueryGetData(Microsoft.VisualStudio.OLE.Interop.IDataObject pDataObject, ref FORMATETC fmtetc)
{
int returnValue = VSConstants.E_FAIL;
FORMATETC[] af = new FORMATETC[1];
af[0] = fmtetc;
try
{
int result = ErrorHandler.ThrowOnFailure(pDataObject.QueryGetData(af));
if(result == VSConstants.S_OK)
{
fmtetc = af[0];
returnValue = VSConstants.S_OK;
}
}
catch(COMException e)
{
Trace.WriteLine("COMException : " + e.Message);
returnValue = e.ErrorCode;
}
return returnValue;
}
public static STGMEDIUM GetData(Microsoft.VisualStudio.OLE.Interop.IDataObject pDataObject, ref FORMATETC fmtetc)
{
FORMATETC[] af = new FORMATETC[1];
af[0] = fmtetc;
STGMEDIUM[] sm = new STGMEDIUM[1];
pDataObject.GetData(af, sm);
fmtetc = af[0];
return sm[0];
}
/// <summary>
/// Retrives data from a VS format.
/// </summary>
public static List<string> GetDroppedFiles(ushort format, Microsoft.VisualStudio.OLE.Interop.IDataObject dataObject, out DropDataType ddt)
{
ddt = DropDataType.None;
List<string> droppedFiles = new List<string>();
// try HDROP
FORMATETC fmtetc = CreateFormatEtc(format);
if(QueryGetData(dataObject, ref fmtetc) == VSConstants.S_OK)
{
STGMEDIUM stgmedium = DragDropHelper.GetData(dataObject, ref fmtetc);
if(stgmedium.tymed == (uint)TYMED.TYMED_HGLOBAL)
{
// We are releasing the cloned hglobal here.
IntPtr dropInfoHandle = stgmedium.unionmember;
if(dropInfoHandle != IntPtr.Zero)
{
ddt = DropDataType.Shell;
try
{
uint numFiles = UnsafeNativeMethods.DragQueryFile(dropInfoHandle, 0xFFFFFFFF, null, 0);
// We are a directory based project thus a projref string is placed on the clipboard.
// We assign the maximum length of a projref string.
// The format of a projref is : <Proj Guid>|<project rel path>|<file path>
uint lenght = (uint)Guid.Empty.ToString().Length + 2 * NativeMethods.MAX_PATH + 2;
char[] moniker = new char[lenght + 1];
for(uint fileIndex = 0; fileIndex < numFiles; fileIndex++)
{
uint queryFileLength = UnsafeNativeMethods.DragQueryFile(dropInfoHandle, fileIndex, moniker, lenght);
string filename = new String(moniker, 0, (int)queryFileLength);
droppedFiles.Add(filename);
}
}
finally
{
Marshal.FreeHGlobal(dropInfoHandle);
}
}
}
}
return droppedFiles;
}
public static string GetSourceProjectPath(Microsoft.VisualStudio.OLE.Interop.IDataObject dataObject)
{
string projectPath = null;
FORMATETC fmtetc = CreateFormatEtc(CF_VSPROJECTCLIPDESCRIPTOR);
if(QueryGetData(dataObject, ref fmtetc) == VSConstants.S_OK)
{
STGMEDIUM stgmedium = DragDropHelper.GetData(dataObject, ref fmtetc);
if(stgmedium.tymed == (uint)TYMED.TYMED_HGLOBAL)
{
// We are releasing the cloned hglobal here.
IntPtr dropInfoHandle = stgmedium.unionmember;
if(dropInfoHandle != IntPtr.Zero)
{
try
{
string path = GetData(dropInfoHandle);
// Clone the path that we can release our memory.
if(!String.IsNullOrEmpty(path))
{
projectPath = String.Copy(path);
}
}
finally
{
Marshal.FreeHGlobal(dropInfoHandle);
}
}
}
}
return projectPath;
}
/// <summary>
/// Returns the data packed after the DROPFILES structure.
/// </summary>
/// <param name="dropHandle"></param>
/// <returns></returns>
internal static string GetData(IntPtr dropHandle)
{
IntPtr data = UnsafeNativeMethods.GlobalLock(dropHandle);
try
{
_DROPFILES df = (_DROPFILES)Marshal.PtrToStructure(data, typeof(_DROPFILES));
if(df.fWide != 0)
{
IntPtr pdata = new IntPtr((long)data + df.pFiles);
return Marshal.PtrToStringUni(pdata);
}
}
finally
{
if(data != null)
{
UnsafeNativeMethods.GlobalUnLock(data);
}
}
return null;
}
internal static IntPtr CopyHGlobal(IntPtr data)
{
IntPtr src = UnsafeNativeMethods.GlobalLock(data);
int size = UnsafeNativeMethods.GlobalSize(data);
IntPtr ptr = Marshal.AllocHGlobal(size);
IntPtr buffer = UnsafeNativeMethods.GlobalLock(ptr);
try
{
for(int i = 0; i < size; i++)
{
byte val = Marshal.ReadByte(new IntPtr((long)src + i));
Marshal.WriteByte(new IntPtr((long)buffer + i), val);
}
}
finally
{
if(buffer != IntPtr.Zero)
{
UnsafeNativeMethods.GlobalUnLock(buffer);
}
if(src != IntPtr.Zero)
{
UnsafeNativeMethods.GlobalUnLock(src);
}
}
return ptr;
}
internal static void CopyStringToHGlobal(string s, IntPtr data, int bufferSize)
{
Int16 nullTerminator = 0;
int dwSize = Marshal.SizeOf(nullTerminator);
if((s.Length + 1) * Marshal.SizeOf(s[0]) > bufferSize)
throw new System.IO.InternalBufferOverflowException();
// IntPtr memory already locked...
for(int i = 0, len = s.Length; i < len; i++)
{
Marshal.WriteInt16(data, i * dwSize, s[i]);
}
// NULL terminate it
Marshal.WriteInt16(new IntPtr((long)data + (s.Length * dwSize)), nullTerminator);
}
} // end of dragdrophelper
internal class EnumSTATDATA : IEnumSTATDATA
{
IEnumerable i;
IEnumerator e;
public EnumSTATDATA(IEnumerable i)
{
this.i = i;
this.e = i.GetEnumerator();
}
void IEnumSTATDATA.Clone(out IEnumSTATDATA clone)
{
clone = new EnumSTATDATA(i);
}
int IEnumSTATDATA.Next(uint celt, STATDATA[] d, out uint fetched)
{
uint rc = 0;
//uint size = (fetched != null) ? fetched[0] : 0;
for(uint i = 0; i < celt; i++)
{
if(e.MoveNext())
{
STATDATA sdata = (STATDATA)e.Current;
rc++;
if(d != null && d.Length > i)
{
d[i] = sdata;
}
}
}
fetched = rc;
return 0;
}
int IEnumSTATDATA.Reset()
{
e.Reset();
return 0;
}
int IEnumSTATDATA.Skip(uint celt)
{
for(uint i = 0; i < celt; i++)
{
e.MoveNext();
}
return 0;
}
}
internal class EnumFORMATETC : IEnumFORMATETC
{
IEnumerable cache; // of DataCacheEntrys.
DATADIR dir;
IEnumerator e;
public EnumFORMATETC(DATADIR dir, IEnumerable cache)
{
this.cache = cache;
this.dir = dir;
e = cache.GetEnumerator();
}
void IEnumFORMATETC.Clone(out IEnumFORMATETC clone)
{
clone = new EnumFORMATETC(dir, cache);
}
int IEnumFORMATETC.Next(uint celt, FORMATETC[] d, uint[] fetched)
{
uint rc = 0;
//uint size = (fetched != null) ? fetched[0] : 0;
for(uint i = 0; i < celt; i++)
{
if(e.MoveNext())
{
DataCacheEntry entry = (DataCacheEntry)e.Current;
rc++;
if(d != null && d.Length > i)
{
d[i] = entry.Format;
}
}
else
{
return VSConstants.S_FALSE;
}
}
if(fetched != null && fetched.Length > 0)
fetched[0] = rc;
return VSConstants.S_OK;
}
int IEnumFORMATETC.Reset()
{
e.Reset();
return 0;
}
int IEnumFORMATETC.Skip(uint celt)
{
for(uint i = 0; i < celt; i++)
{
e.MoveNext();
}
return 0;
}
}
}
| |
#pragma warning disable 162,108,618
using Casanova.Prelude;
using System.Linq;
using System;
using System.Collections.Generic;
using UnityEngine;
namespace Game {public class World : MonoBehaviour{
public static int frame;
void Update () { Update(Time.deltaTime, this);
frame++; }
public bool JustEntered = true;
public void Start()
{
List<Planet> ___planets00;
___planets00 = (
(Enumerable.Range(1,(1) + ((50) - (1))).ToList<System.Int32>()).Select(__ContextSymbol0 => new { ___i00 = __ContextSymbol0 })
.Select(__ContextSymbol1 => new {___pos00 = new UnityEngine.Vector3(UnityEngine.Random.Range(-140f,140f),0f,UnityEngine.Random.Range(-140f,140f)), prev = __ContextSymbol1 })
.Select(__ContextSymbol2 => new {___mass01 = UnityEngine.Random.Range(3f,350f), prev = __ContextSymbol2 })
.Select(__ContextSymbol3 => new {___rotv01 = new UnityEngine.Vector3(UnityEngine.Random.Range(-50f,50f),UnityEngine.Random.Range(-50f,50f),UnityEngine.Random.Range(-50f,50f)), prev = __ContextSymbol3 })
.Select(__ContextSymbol4 => new Planet(__ContextSymbol4.prev.prev.___pos00,__ContextSymbol4.prev.___mass01,Vector3.zero,__ContextSymbol4.___rotv01))
.ToList<Planet>()).ToList<Planet>();
Planets = ___planets00;
MainCamera = new GameCamera();
}
public GameCamera MainCamera;
public List<Planet> __Planets;
public List<Planet> Planets{ get { return __Planets; }
set{ __Planets = value;
foreach(var e in value){if(e.JustEntered){ e.JustEntered = false;
}
} }
}
public System.Single count_down1;
public System.Single ___posx10;
public System.Single ___posz10;
public System.Single ___posx11;
public System.Single ___posz11;
public System.Single ___mass10;
public UnityEngine.Vector3 ___position10;
public UnityEngine.Vector3 ___velocity10;
public UnityEngine.Vector3 ___rotv10;
public Planet ___newPlanet10;
System.DateTime init_time = System.DateTime.Now;
public void Update(float dt, World world) {
var t = System.DateTime.Now; this.Rule0(dt, world);
MainCamera.Update(dt, world);
for(int x0 = 0; x0 < Planets.Count; x0++) {
Planets[x0].Update(dt, world);
}
this.Rule1(dt, world);
}
public void Rule0(float dt, World world)
{
Planets = (
(Planets).Select(__ContextSymbol5 => new { ___p00 = __ContextSymbol5 })
.Where(__ContextSymbol6 => !(__ContextSymbol6.___p00.OutOfBounds))
.Select(__ContextSymbol7 => __ContextSymbol7.___p00)
.ToList<Planet>()).ToList<Planet>();
}
int s1=-1;
public void Rule1(float dt, World world){
switch (s1)
{
case -1:
count_down1 = 1f;
goto case 11;
case 11:
if(((count_down1) > (0f)))
{
count_down1 = ((count_down1) - (dt));
s1 = 11;
return; }else
{
goto case 9; }
case 9:
___posx10 = UnityEngine.Random.Range(175f,200f);
___posz10 = UnityEngine.Random.Range(175f,200f);
if(((UnityEngine.Random.value) > (0.5f)))
{
___posx11 = ___posx10; }else
{
___posx11 = ((___posx10) * (-1f)); }
if(((UnityEngine.Random.value) > (0.5f)))
{
___posz11 = ___posz10; }else
{
___posz11 = ((___posz10) * (-1f)); }
___mass10 = UnityEngine.Random.Range(3f,350f);
___position10 = new UnityEngine.Vector3(___posx11,0f,___posz11);
___velocity10 = ((UnityEngine.Vector3.Normalize((___position10) * (-1f))) * (UnityEngine.Random.Range(1f,6f)));
___rotv10 = new UnityEngine.Vector3(UnityEngine.Random.Range(-50f,50f),UnityEngine.Random.Range(-50f,50f),UnityEngine.Random.Range(-50f,50f));
___newPlanet10 = new Planet(___position10,___mass10,___velocity10,___rotv10);
Planets = new Cons<Planet>(___newPlanet10, (Planets)).ToList<Planet>();
s1 = -1;
return;
default: return;}}
}
public class GameCamera{
public int frame;
public bool JustEntered = true;
public int ID;
public GameCamera()
{JustEntered = false;
frame = World.frame;
UnityCamera = UnityCamera.CreateMainCamera();
}
public UnityEngine.Vector3 CameraPosition{ get { return UnityCamera.CameraPosition; }
set{UnityCamera.CameraPosition = value; }
}
public System.Single CameraSize{ get { return UnityCamera.CameraSize; }
set{UnityCamera.CameraSize = value; }
}
public System.Boolean Quit{ set{UnityCamera.Quit = value; }
}
public UnityCamera UnityCamera;
public System.Boolean enabled{ get { return UnityCamera.enabled; }
set{UnityCamera.enabled = value; }
}
public UnityEngine.GameObject gameObject{ get { return UnityCamera.gameObject; }
}
public UnityEngine.HideFlags hideFlags{ get { return UnityCamera.hideFlags; }
set{UnityCamera.hideFlags = value; }
}
public System.Boolean isActiveAndEnabled{ get { return UnityCamera.isActiveAndEnabled; }
}
public System.String name{ get { return UnityCamera.name; }
set{UnityCamera.name = value; }
}
public System.String tag{ get { return UnityCamera.tag; }
set{UnityCamera.tag = value; }
}
public UnityEngine.Transform transform{ get { return UnityCamera.transform; }
}
public System.Boolean useGUILayout{ get { return UnityCamera.useGUILayout; }
set{UnityCamera.useGUILayout = value; }
}
public System.Single ___adjustment10;
public System.Single ___adjustment11;
public System.Single ___adjustment12;
public System.Single ___adjustment13;
public System.Single ___sensitivity00;
public System.Single ___sensitivity11;
public void Update(float dt, World world) {
frame = World.frame;
this.Rule0(dt, world);
this.Rule1(dt, world);
this.Rule2(dt, world);
}
int s000=-1;
public void parallelMethod000(float dt, World world){
switch (s000)
{
case -1:
if(!(((UnityEngine.Input.GetKey(KeyCode.DownArrow)) && (!(((CameraSize) > (75f)))))))
{
s000 = -1;
return; }else
{
goto case 0; }
case 0:
CameraSize = System.Math.Min(75f,(CameraSize) + (___sensitivity00));
s000 = -1;
return;
default: return;}}
int s001=-1;
public void parallelMethod001(float dt, World world){
switch (s001)
{
case -1:
if(!(((UnityEngine.Input.GetKey(KeyCode.UpArrow)) && (((((CameraSize) > (5f))) || (((CameraSize) == (5f))))))))
{
s001 = -1;
return; }else
{
goto case 0; }
case 0:
CameraSize = System.Math.Max(5f,(CameraSize) - (___sensitivity00));
s001 = -1;
return;
default: return;}}
int s110=-1;
public void parallelMethod110(float dt, World world){
switch (s110)
{
case -1:
if(!(((UnityEngine.Input.GetKey(KeyCode.A)) && (((CameraPosition.x) > (-100f))))))
{
s110 = -1;
return; }else
{
goto case 1; }
case 1:
___adjustment10 = System.Math.Max(-100f,(___sensitivity11) * (-1f));
CameraPosition = ((CameraPosition) + (new UnityEngine.Vector3(___adjustment10,0f,0f)));
s110 = -1;
return;
default: return;}}
int s111=-1;
public void parallelMethod111(float dt, World world){
switch (s111)
{
case -1:
if(!(((UnityEngine.Input.GetKey(KeyCode.D)) && (((100f) > (CameraPosition.x))))))
{
s111 = -1;
return; }else
{
goto case 1; }
case 1:
___adjustment11 = System.Math.Min(100f,___sensitivity11);
CameraPosition = ((CameraPosition) + (new UnityEngine.Vector3(___sensitivity11,0f,0f)));
s111 = -1;
return;
default: return;}}
int s112=-1;
public void parallelMethod112(float dt, World world){
switch (s112)
{
case -1:
if(!(((UnityEngine.Input.GetKey(KeyCode.S)) && (((CameraPosition.z) > (-100f))))))
{
s112 = -1;
return; }else
{
goto case 1; }
case 1:
___adjustment12 = System.Math.Max(-100f,(___sensitivity11) * (-1f));
CameraPosition = ((CameraPosition) + (new UnityEngine.Vector3(0f,0f,___adjustment12)));
s112 = -1;
return;
default: return;}}
int s113=-1;
public void parallelMethod113(float dt, World world){
switch (s113)
{
case -1:
if(!(((UnityEngine.Input.GetKey(KeyCode.W)) && (((100f) > (CameraPosition.z))))))
{
s113 = -1;
return; }else
{
goto case 1; }
case 1:
___adjustment13 = System.Math.Min(100f,___sensitivity11);
CameraPosition = ((CameraPosition) + (new UnityEngine.Vector3(0f,0f,___adjustment13)));
s113 = -1;
return;
default: return;}}
int s0=-1;
public void Rule0(float dt, World world){
switch (s0)
{
case -1:
___sensitivity00 = 0.5f;
goto case 0;
case 0:
this.parallelMethod000(dt,world);
this.parallelMethod001(dt,world);
s0 = 0;
return;
default: return;}}
int s1=-1;
public void Rule1(float dt, World world){
switch (s1)
{
case -1:
___sensitivity11 = 1f;
goto case 0;
case 0:
this.parallelMethod110(dt,world);
this.parallelMethod111(dt,world);
this.parallelMethod112(dt,world);
this.parallelMethod113(dt,world);
s1 = 0;
return;
default: return;}}
int s2=-1;
public void Rule2(float dt, World world){
switch (s2)
{
case -1:
if(!(UnityEngine.Input.GetKey(KeyCode.Escape)))
{
s2 = -1;
return; }else
{
goto case 0; }
case 0:
Quit = true;
s2 = -1;
return;
default: return;}}
}
public class Planet{
public int frame;
public bool JustEntered = true;
private UnityEngine.Vector3 pos;
private System.Single m;
private UnityEngine.Vector3 velocity;
private UnityEngine.Vector3 rotationVelocity;
public int ID;
public Planet(UnityEngine.Vector3 pos, System.Single m, UnityEngine.Vector3 velocity, UnityEngine.Vector3 rotationVelocity)
{JustEntered = false;
frame = World.frame;
Velocity = velocity;
UnityPlanet = UnityPlanet.Instantiate(pos,m);
RotationVelocity = rotationVelocity;
OutOfBounds = false;
Mass = m;
Acceleration = Vector3.zero;
}
public UnityEngine.Vector3 Acceleration;
public System.Boolean Destroyed{ get { return UnityPlanet.Destroyed; }
set{UnityPlanet.Destroyed = value; }
}
public System.Single Mass;
public System.Boolean OutOfBounds;
public UnityEngine.Vector3 Position{ get { return UnityPlanet.Position; }
set{UnityPlanet.Position = value; }
}
public UnityEngine.Quaternion Rotation{ get { return UnityPlanet.Rotation; }
set{UnityPlanet.Rotation = value; }
}
public UnityEngine.Vector3 RotationVelocity;
public UnityPlanet UnityPlanet;
public UnityEngine.Vector3 Velocity;
public System.Boolean enabled{ get { return UnityPlanet.enabled; }
set{UnityPlanet.enabled = value; }
}
public UnityEngine.GameObject gameObject{ get { return UnityPlanet.gameObject; }
}
public UnityEngine.HideFlags hideFlags{ get { return UnityPlanet.hideFlags; }
set{UnityPlanet.hideFlags = value; }
}
public System.Boolean isActiveAndEnabled{ get { return UnityPlanet.isActiveAndEnabled; }
}
public System.String name{ get { return UnityPlanet.name; }
set{UnityPlanet.name = value; }
}
public System.String tag{ get { return UnityPlanet.tag; }
set{UnityPlanet.tag = value; }
}
public UnityEngine.Transform transform{ get { return UnityPlanet.transform; }
}
public System.Boolean useGUILayout{ get { return UnityPlanet.useGUILayout; }
set{UnityPlanet.useGUILayout = value; }
}
public void Update(float dt, World world) {
frame = World.frame; this.Rule0(dt, world);
this.Rule2(dt, world);
this.Rule3(dt, world);
this.Rule4(dt, world);
this.Rule5(dt, world);
this.Rule1(dt, world);
}
public void Rule0(float dt, World world)
{
System.Single ___g00;
___g00 = (6.673f) * (UnityEngine.Mathf.Pow(10f,-3f));
List<UnityEngine.Vector3> ___accelerations00;
___accelerations00 = (
(world.Planets).Select(__ContextSymbol8 => new { ___planet00 = __ContextSymbol8 })
.Where(__ContextSymbol9 => !(((__ContextSymbol9.___planet00) == (this))))
.Select(__ContextSymbol10 => new {___r00 = UnityEngine.Vector3.Distance(this.Position,__ContextSymbol10.___planet00.Position), prev = __ContextSymbol10 })
.Select(__ContextSymbol11 => new {___acc00 = ((___g00) * (__ContextSymbol11.prev.___planet00.Mass)) / ((__ContextSymbol11.___r00) * (__ContextSymbol11.___r00)), prev = __ContextSymbol11 })
.Select(__ContextSymbol12 => (UnityEngine.Vector3.Normalize((__ContextSymbol12.prev.prev.___planet00.Position) - (this.Position))) * (__ContextSymbol12.___acc00))
.ToList<UnityEngine.Vector3>()).ToList<UnityEngine.Vector3>();
if(((___accelerations00.Count) > (0)))
{
Acceleration = (
(___accelerations00).Select(__ContextSymbol13 => new { ___a00 = __ContextSymbol13 })
.Select(__ContextSymbol14 => __ContextSymbol14.___a00)
.Aggregate(default(UnityEngine.Vector3), (acc, __x) => acc + __x));
}else
{
Acceleration = Vector3.zero;
}
}
public void Rule2(float dt, World world)
{
OutOfBounds = ((((((((Position.x) > (250f))) || (((Position.z) > (250f))))) || (((-250f) > (Position.x))))) || (((-250f) > (Position.z))));
}
public void Rule3(float dt, World world)
{
Rotation = (UnityEngine.Quaternion.Euler((RotationVelocity) * (dt))) * (Rotation);
}
public void Rule4(float dt, World world)
{
Velocity = (Velocity) + ((Acceleration) * (dt));
}
public void Rule5(float dt, World world)
{
Position = (Position) + ((Velocity) * (dt));
}
int s1=-1;
public void Rule1(float dt, World world){
switch (s1)
{
case -1:
if(!(OutOfBounds))
{
s1 = -1;
return; }else
{
goto case 0; }
case 0:
Destroyed = true;
s1 = -1;
return;
default: return;}}
}
}
| |
// 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.Runtime.CompilerServices;
using Xunit;
namespace System.Threading.Tasks.Tests
{
public class TaskAwaiterTests
{
[Theory]
[InlineData(false, false)]
[InlineData(false, true)]
[InlineData(false, null)]
[InlineData(true, false)]
[InlineData(true, true)]
[InlineData(true, null)]
public static void OnCompleted_CompletesInAnotherSynchronizationContext(bool generic, bool? continueOnCapturedContext)
{
SynchronizationContext origCtx = SynchronizationContext.Current;
try
{
// Create a context that tracks operations, and set it as current
var validateCtx = new ValidateCorrectContextSynchronizationContext();
Assert.Equal(0, validateCtx.PostCount);
SynchronizationContext.SetSynchronizationContext(validateCtx);
// Create a not-completed task and get an awaiter for it
var mres = new ManualResetEventSlim();
var tcs = new TaskCompletionSource<object>();
// Hook up a callback
bool postedInContext = false;
Action callback = () =>
{
postedInContext = ValidateCorrectContextSynchronizationContext.t_isPostedInContext;
mres.Set();
};
if (generic)
{
if (continueOnCapturedContext.HasValue) tcs.Task.ConfigureAwait(continueOnCapturedContext.Value).GetAwaiter().OnCompleted(callback);
else tcs.Task.GetAwaiter().OnCompleted(callback);
}
else
{
if (continueOnCapturedContext.HasValue) ((Task)tcs.Task).ConfigureAwait(continueOnCapturedContext.Value).GetAwaiter().OnCompleted(callback);
else ((Task)tcs.Task).GetAwaiter().OnCompleted(callback);
}
Assert.False(mres.IsSet, "Callback should not yet have run.");
// Complete the task in another context and wait for the callback to run
Task.Run(() => tcs.SetResult(null));
mres.Wait();
// Validate the callback ran and in the correct context
bool shouldHavePosted = !continueOnCapturedContext.HasValue || continueOnCapturedContext.Value;
Assert.Equal(shouldHavePosted ? 1 : 0, validateCtx.PostCount);
Assert.Equal(shouldHavePosted, postedInContext);
}
finally
{
// Reset back to the original context
SynchronizationContext.SetSynchronizationContext(origCtx);
}
}
[Theory]
[InlineData(false, false)]
[InlineData(false, true)]
[InlineData(false, null)]
[InlineData(true, false)]
[InlineData(true, true)]
[InlineData(true, null)]
public static void OnCompleted_CompletesInAnotherTaskScheduler(bool generic, bool? continueOnCapturedContext)
{
SynchronizationContext origCtx = SynchronizationContext.Current;
try
{
SynchronizationContext.SetSynchronizationContext(null); // get off xunit's SynchronizationContext to avoid interactions with await
var quwi = new QUWITaskScheduler();
RunWithSchedulerAsCurrent(quwi, delegate
{
Assert.True(TaskScheduler.Current == quwi, "Expected to be on target scheduler");
// Create the not completed task and get its awaiter
var mres = new ManualResetEventSlim();
var tcs = new TaskCompletionSource<object>();
// Hook up the callback
bool ranOnScheduler = false;
Action callback = () =>
{
ranOnScheduler = (TaskScheduler.Current == quwi);
mres.Set();
};
if (generic)
{
if (continueOnCapturedContext.HasValue) tcs.Task.ConfigureAwait(continueOnCapturedContext.Value).GetAwaiter().OnCompleted(callback);
else tcs.Task.GetAwaiter().OnCompleted(callback);
}
else
{
if (continueOnCapturedContext.HasValue) ((Task)tcs.Task).ConfigureAwait(continueOnCapturedContext.Value).GetAwaiter().OnCompleted(callback);
else ((Task)tcs.Task).GetAwaiter().OnCompleted(callback);
}
Assert.False(mres.IsSet, "Callback should not yet have run.");
// Complete the task in another scheduler and wait for the callback to run
Task.Run(delegate { tcs.SetResult(null); });
mres.Wait();
// Validate the callback ran on the right scheduler
bool shouldHaveRunOnScheduler = !continueOnCapturedContext.HasValue || continueOnCapturedContext.Value;
Assert.Equal(shouldHaveRunOnScheduler, ranOnScheduler);
});
}
finally
{
SynchronizationContext.SetSynchronizationContext(origCtx);
}
}
[Fact]
public static void GetResult_Completed_Success()
{
Task task = Task.CompletedTask;
task.GetAwaiter().GetResult();
task.ConfigureAwait(false).GetAwaiter().GetResult();
task.ConfigureAwait(true).GetAwaiter().GetResult();
const string expectedResult = "42";
Task<string> taskOfString = Task.FromResult(expectedResult);
Assert.Equal(expectedResult, taskOfString.GetAwaiter().GetResult());
Assert.Equal(expectedResult, taskOfString.ConfigureAwait(false).GetAwaiter().GetResult());
Assert.Equal(expectedResult, taskOfString.ConfigureAwait(true).GetAwaiter().GetResult());
}
[OuterLoop]
[Fact]
public static void GetResult_NotCompleted_BlocksUntilCompletion()
{
var tcs = new TaskCompletionSource<bool>();
// Kick off tasks that should all block
var tasks = new[] {
Task.Run(() => tcs.Task.GetAwaiter().GetResult()),
Task.Run(() => ((Task)tcs.Task).GetAwaiter().GetResult()),
Task.Run(() => tcs.Task.ConfigureAwait(false).GetAwaiter().GetResult()),
Task.Run(() => ((Task)tcs.Task).ConfigureAwait(false).GetAwaiter().GetResult())
};
Assert.Equal(-1, Task.WaitAny(tasks, 100)); // "Tasks should not have completed"
// Now complete the tasks, after which all the tasks should complete successfully.
tcs.SetResult(true);
Task.WaitAll(tasks);
}
[Fact]
public static void GetResult_CanceledTask_ThrowsCancellationException()
{
// Validate cancellation
Task<string> canceled = Task.FromCanceled<string>(new CancellationToken(true));
// Task.GetAwaiter and Task<T>.GetAwaiter
Assert.Throws<TaskCanceledException>(() => ((Task)canceled).GetAwaiter().GetResult());
Assert.Throws<TaskCanceledException>(() => canceled.GetAwaiter().GetResult());
// w/ ConfigureAwait false and true
Assert.Throws<TaskCanceledException>(() => ((Task)canceled).ConfigureAwait(false).GetAwaiter().GetResult());
Assert.Throws<TaskCanceledException>(() => ((Task)canceled).ConfigureAwait(true).GetAwaiter().GetResult());
Assert.Throws<TaskCanceledException>(() => canceled.ConfigureAwait(false).GetAwaiter().GetResult());
Assert.Throws<TaskCanceledException>(() => canceled.ConfigureAwait(true).GetAwaiter().GetResult());
}
[Fact]
public static void GetResult_FaultedTask_OneException_ThrowsOriginalException()
{
var exception = new ArgumentException("uh oh");
Task<string> task = Task.FromException<string>(exception);
// Task.GetAwaiter and Task<T>.GetAwaiter
Assert.Same(exception, Assert.Throws<ArgumentException>(() => ((Task)task).GetAwaiter().GetResult()));
Assert.Same(exception, Assert.Throws<ArgumentException>(() => task.GetAwaiter().GetResult()));
// w/ ConfigureAwait false and true
Assert.Same(exception, Assert.Throws<ArgumentException>(() => ((Task)task).ConfigureAwait(false).GetAwaiter().GetResult()));
Assert.Same(exception, Assert.Throws<ArgumentException>(() => ((Task)task).ConfigureAwait(true).GetAwaiter().GetResult()));
Assert.Same(exception, Assert.Throws<ArgumentException>(() => task.ConfigureAwait(false).GetAwaiter().GetResult()));
Assert.Same(exception, Assert.Throws<ArgumentException>(() => task.ConfigureAwait(true).GetAwaiter().GetResult()));
}
[Fact]
public static void GetResult_FaultedTask_MultipleExceptions_ThrowsFirstException()
{
var exception = new ArgumentException("uh oh");
var tcs = new TaskCompletionSource<string>();
tcs.SetException(new Exception[] { exception, new InvalidOperationException("uh oh") });
Task<string> task = tcs.Task;
// Task.GetAwaiter and Task<T>.GetAwaiter
Assert.Same(exception, Assert.Throws<ArgumentException>(() => ((Task)task).GetAwaiter().GetResult()));
Assert.Same(exception, Assert.Throws<ArgumentException>(() => task.GetAwaiter().GetResult()));
// w/ ConfigureAwait false and true
Assert.Same(exception, Assert.Throws<ArgumentException>(() => ((Task)task).ConfigureAwait(false).GetAwaiter().GetResult()));
Assert.Same(exception, Assert.Throws<ArgumentException>(() => ((Task)task).ConfigureAwait(true).GetAwaiter().GetResult()));
Assert.Same(exception, Assert.Throws<ArgumentException>(() => task.ConfigureAwait(false).GetAwaiter().GetResult()));
Assert.Same(exception, Assert.Throws<ArgumentException>(() => task.ConfigureAwait(true).GetAwaiter().GetResult()));
}
[Fact]
public static void AwaiterAndAwaitableEquality()
{
var completed = new TaskCompletionSource<string>();
Task task = completed.Task;
// TaskAwaiter
task.GetAwaiter().Equals(task.GetAwaiter());
// ConfiguredTaskAwaitable
Assert.Equal(task.ConfigureAwait(false), task.ConfigureAwait(false));
Assert.NotEqual(task.ConfigureAwait(false), task.ConfigureAwait(true));
Assert.NotEqual(task.ConfigureAwait(true), task.ConfigureAwait(false));
// ConfiguredTaskAwaitable<T>
Assert.Equal(task.ConfigureAwait(false), task.ConfigureAwait(false));
Assert.NotEqual(task.ConfigureAwait(false), task.ConfigureAwait(true));
Assert.NotEqual(task.ConfigureAwait(true), task.ConfigureAwait(false));
// ConfiguredTaskAwaitable.ConfiguredTaskAwaiter
Assert.Equal(task.ConfigureAwait(false).GetAwaiter(), task.ConfigureAwait(false).GetAwaiter());
Assert.NotEqual(task.ConfigureAwait(false).GetAwaiter(), task.ConfigureAwait(true).GetAwaiter());
Assert.NotEqual(task.ConfigureAwait(true).GetAwaiter(), task.ConfigureAwait(false).GetAwaiter());
// ConfiguredTaskAwaitable<T>.ConfiguredTaskAwaiter
Assert.Equal(task.ConfigureAwait(false).GetAwaiter(), task.ConfigureAwait(false).GetAwaiter());
Assert.NotEqual(task.ConfigureAwait(false).GetAwaiter(), task.ConfigureAwait(true).GetAwaiter());
Assert.NotEqual(task.ConfigureAwait(true).GetAwaiter(), task.ConfigureAwait(false).GetAwaiter());
}
[Fact]
public static void BaseSynchronizationContext_SameAsNoSynchronizationContext()
{
var quwi = new QUWITaskScheduler();
SynchronizationContext origCtx = SynchronizationContext.Current;
try
{
SynchronizationContext.SetSynchronizationContext(new SynchronizationContext());
RunWithSchedulerAsCurrent(quwi, delegate
{
ManualResetEventSlim mres = new ManualResetEventSlim();
var tcs = new TaskCompletionSource<object>();
var awaiter = ((Task)tcs.Task).GetAwaiter();
bool ranOnScheduler = false;
bool ranWithoutSyncCtx = false;
awaiter.OnCompleted(() =>
{
ranOnScheduler = (TaskScheduler.Current == quwi);
ranWithoutSyncCtx = SynchronizationContext.Current == null;
mres.Set();
});
Assert.False(mres.IsSet, "Callback should not yet have run.");
Task.Run(delegate { tcs.SetResult(null); });
mres.Wait();
Assert.True(ranOnScheduler, "Should have run on scheduler");
Assert.True(ranWithoutSyncCtx, "Should have run with a null sync ctx");
});
}
finally
{
SynchronizationContext.SetSynchronizationContext(origCtx);
}
}
[Theory]
[MemberData(nameof(CanceledTasksAndExpectedCancellationExceptions))]
public static void OperationCanceledException_PropagatesThroughCanceledTask(int lineNumber, Task task, OperationCanceledException expected)
{
var caught = Assert.ThrowsAny<OperationCanceledException>(() => task.GetAwaiter().GetResult());
Assert.Same(expected, caught);
}
public static IEnumerable<object[]> CanceledTasksAndExpectedCancellationExceptions()
{
var cts = new CancellationTokenSource();
var oce = new OperationCanceledException(cts.Token);
// Scheduled Task
Task<int> generic = Task.Run<int>(new Func<int>(() =>
{
cts.Cancel();
throw oce;
}), cts.Token);
yield return new object[] { LineNumber(), generic, oce };
Task nonGeneric = generic;
// WhenAll Task and Task<int>
yield return new object[] { LineNumber(), Task.WhenAll(generic), oce };
yield return new object[] { LineNumber(), Task.WhenAll(generic, Task.FromResult(42)), oce };
yield return new object[] { LineNumber(), Task.WhenAll(Task.FromResult(42), generic), oce };
yield return new object[] { LineNumber(), Task.WhenAll(generic, generic, generic), oce };
yield return new object[] { LineNumber(), Task.WhenAll(nonGeneric), oce };
yield return new object[] { LineNumber(), Task.WhenAll(nonGeneric, Task.FromResult(42)), oce };
yield return new object[] { LineNumber(), Task.WhenAll(Task.FromResult(42), nonGeneric), oce };
yield return new object[] { LineNumber(), Task.WhenAll(nonGeneric, nonGeneric, nonGeneric), oce };
// Task.Run Task and Task<int> with unwrapping
yield return new object[] { LineNumber(), Task.Run(() => generic), oce };
yield return new object[] { LineNumber(), Task.Run(() => nonGeneric), oce };
// A FromAsync Task and Task<int>
yield return new object[] { LineNumber(), Task.Factory.FromAsync(generic, new Action<IAsyncResult>(ar => { throw oce; })), oce };
yield return new object[] { LineNumber(), Task<int>.Factory.FromAsync(nonGeneric, new Func<IAsyncResult, int>(ar => { throw oce; })), oce };
// AsyncTaskMethodBuilder
var atmb = new AsyncTaskMethodBuilder();
atmb.SetException(oce);
yield return new object[] { LineNumber(), atmb.Task, oce };
}
private static int LineNumber([CallerLineNumber]int lineNumber = 0) => lineNumber;
private class ValidateCorrectContextSynchronizationContext : SynchronizationContext
{
[ThreadStatic]
internal static bool t_isPostedInContext;
internal int PostCount;
internal int SendCount;
public override void Post(SendOrPostCallback d, object state)
{
Interlocked.Increment(ref PostCount);
Task.Run(() =>
{
try
{
t_isPostedInContext = true;
d(state);
}
finally
{
t_isPostedInContext = false;
}
});
}
public override void Send(SendOrPostCallback d, object state)
{
Interlocked.Increment(ref SendCount);
d(state);
}
}
/// <summary>A scheduler that queues to the TP and tracks the number of times QueueTask and TryExecuteTaskInline are invoked.</summary>
private class QUWITaskScheduler : TaskScheduler
{
private int _queueTaskCount;
private int _tryExecuteTaskInlineCount;
public int QueueTaskCount { get { return _queueTaskCount; } }
public int TryExecuteTaskInlineCount { get { return _tryExecuteTaskInlineCount; } }
protected override IEnumerable<Task> GetScheduledTasks() { return null; }
protected override void QueueTask(Task task)
{
Interlocked.Increment(ref _queueTaskCount);
Task.Run(() => TryExecuteTask(task));
}
protected override bool TryExecuteTaskInline(Task task, bool taskWasPreviouslyQueued)
{
Interlocked.Increment(ref _tryExecuteTaskInlineCount);
return TryExecuteTask(task);
}
}
/// <summary>Runs the action with TaskScheduler.Current equal to the specified scheduler.</summary>
private static void RunWithSchedulerAsCurrent(TaskScheduler scheduler, Action action)
{
var t = new Task(action);
t.RunSynchronously(scheduler);
t.GetAwaiter().GetResult();
}
}
}
| |
//
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using System.Xml.Linq;
using Microsoft.WindowsAzure;
using Microsoft.WindowsAzure.Common;
using Microsoft.WindowsAzure.Common.Internals;
using Microsoft.WindowsAzure.Management.Scheduler;
using Microsoft.WindowsAzure.Management.Scheduler.Models;
namespace Microsoft.WindowsAzure.Management.Scheduler
{
public partial class SchedulerManagementClient : ServiceClient<SchedulerManagementClient>, Microsoft.WindowsAzure.Management.Scheduler.ISchedulerManagementClient
{
private string _apiVersion;
/// <summary>
/// Gets the API version.
/// </summary>
public string ApiVersion
{
get { return this._apiVersion; }
}
private Uri _baseUri;
/// <summary>
/// Gets the URI used as the base for all cloud service requests.
/// </summary>
public Uri BaseUri
{
get { return this._baseUri; }
}
private SubscriptionCloudCredentials _credentials;
/// <summary>
/// Gets subscription credentials which uniquely identify Microsoft
/// Azure subscription. The subscription ID forms part of the URI for
/// every service call.
/// </summary>
public SubscriptionCloudCredentials Credentials
{
get { return this._credentials; }
}
private int _longRunningOperationInitialTimeout;
/// <summary>
/// Gets or sets the initial timeout for Long Running Operations.
/// </summary>
public int LongRunningOperationInitialTimeout
{
get { return this._longRunningOperationInitialTimeout; }
set { this._longRunningOperationInitialTimeout = value; }
}
private int _longRunningOperationRetryTimeout;
/// <summary>
/// Gets or sets the retry timeout for Long Running Operations.
/// </summary>
public int LongRunningOperationRetryTimeout
{
get { return this._longRunningOperationRetryTimeout; }
set { this._longRunningOperationRetryTimeout = value; }
}
private IJobCollectionOperations _jobCollections;
public virtual IJobCollectionOperations JobCollections
{
get { return this._jobCollections; }
}
/// <summary>
/// Initializes a new instance of the SchedulerManagementClient class.
/// </summary>
private SchedulerManagementClient()
: base()
{
this._jobCollections = new JobCollectionOperations(this);
this._apiVersion = "2013-03-01";
this._longRunningOperationInitialTimeout = -1;
this._longRunningOperationRetryTimeout = -1;
this.HttpClient.Timeout = TimeSpan.FromSeconds(300);
}
/// <summary>
/// Initializes a new instance of the SchedulerManagementClient class.
/// </summary>
/// <param name='credentials'>
/// Required. Gets subscription credentials which uniquely identify
/// Microsoft Azure subscription. The subscription ID forms part of
/// the URI for every service call.
/// </param>
/// <param name='baseUri'>
/// Required. Gets the URI used as the base for all cloud service
/// requests.
/// </param>
public SchedulerManagementClient(SubscriptionCloudCredentials credentials, Uri baseUri)
: this()
{
if (credentials == null)
{
throw new ArgumentNullException("credentials");
}
if (baseUri == null)
{
throw new ArgumentNullException("baseUri");
}
this._credentials = credentials;
this._baseUri = baseUri;
this.Credentials.InitializeServiceClient(this);
}
/// <summary>
/// Initializes a new instance of the SchedulerManagementClient class.
/// </summary>
/// <param name='credentials'>
/// Required. Gets subscription credentials which uniquely identify
/// Microsoft Azure subscription. The subscription ID forms part of
/// the URI for every service call.
/// </param>
public SchedulerManagementClient(SubscriptionCloudCredentials credentials)
: this()
{
if (credentials == null)
{
throw new ArgumentNullException("credentials");
}
this._credentials = credentials;
this._baseUri = new Uri("https://management.core.windows.net/");
this.Credentials.InitializeServiceClient(this);
}
/// <summary>
/// Initializes a new instance of the SchedulerManagementClient class.
/// </summary>
/// <param name='httpClient'>
/// The Http client
/// </param>
private SchedulerManagementClient(HttpClient httpClient)
: base(httpClient)
{
this._jobCollections = new JobCollectionOperations(this);
this._apiVersion = "2013-03-01";
this._longRunningOperationInitialTimeout = -1;
this._longRunningOperationRetryTimeout = -1;
this.HttpClient.Timeout = TimeSpan.FromSeconds(300);
}
/// <summary>
/// Initializes a new instance of the SchedulerManagementClient class.
/// </summary>
/// <param name='credentials'>
/// Required. Gets subscription credentials which uniquely identify
/// Microsoft Azure subscription. The subscription ID forms part of
/// the URI for every service call.
/// </param>
/// <param name='baseUri'>
/// Required. Gets the URI used as the base for all cloud service
/// requests.
/// </param>
/// <param name='httpClient'>
/// The Http client
/// </param>
public SchedulerManagementClient(SubscriptionCloudCredentials credentials, Uri baseUri, HttpClient httpClient)
: this(httpClient)
{
if (credentials == null)
{
throw new ArgumentNullException("credentials");
}
if (baseUri == null)
{
throw new ArgumentNullException("baseUri");
}
this._credentials = credentials;
this._baseUri = baseUri;
this.Credentials.InitializeServiceClient(this);
}
/// <summary>
/// Initializes a new instance of the SchedulerManagementClient class.
/// </summary>
/// <param name='credentials'>
/// Required. Gets subscription credentials which uniquely identify
/// Microsoft Azure subscription. The subscription ID forms part of
/// the URI for every service call.
/// </param>
/// <param name='httpClient'>
/// The Http client
/// </param>
public SchedulerManagementClient(SubscriptionCloudCredentials credentials, HttpClient httpClient)
: this(httpClient)
{
if (credentials == null)
{
throw new ArgumentNullException("credentials");
}
this._credentials = credentials;
this._baseUri = new Uri("https://management.core.windows.net/");
this.Credentials.InitializeServiceClient(this);
}
/// <summary>
/// Clones properties from current instance to another
/// SchedulerManagementClient instance
/// </summary>
/// <param name='client'>
/// Instance of SchedulerManagementClient to clone to
/// </param>
protected override void Clone(ServiceClient<SchedulerManagementClient> client)
{
base.Clone(client);
if (client is SchedulerManagementClient)
{
SchedulerManagementClient clonedClient = ((SchedulerManagementClient)client);
clonedClient._credentials = this._credentials;
clonedClient._baseUri = this._baseUri;
clonedClient._apiVersion = this._apiVersion;
clonedClient._longRunningOperationInitialTimeout = this._longRunningOperationInitialTimeout;
clonedClient._longRunningOperationRetryTimeout = this._longRunningOperationRetryTimeout;
clonedClient.Credentials.InitializeServiceClient(clonedClient);
}
}
/// <summary>
/// The Get Operation Status operation returns the status of
/// thespecified operation. After calling an asynchronous operation,
/// you can call Get Operation Status to determine whether the
/// operation has succeeded, failed, or is still in progress. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/ee460783.aspx
/// for more information)
/// </summary>
/// <param name='requestId'>
/// Required. The request ID for the request you wish to track. The
/// request ID is returned in the x-ms-request-id response header for
/// every request.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The response body contains the status of the specified asynchronous
/// operation, indicating whether it has succeeded, is inprogress, or
/// has failed. Note that this status is distinct from the HTTP status
/// code returned for the Get Operation Status operation itself. If
/// the asynchronous operation succeeded, the response body includes
/// the HTTP status code for the successful request. If the
/// asynchronous operation failed, the response body includes the HTTP
/// status code for the failed request, and also includes error
/// information regarding the failure.
/// </returns>
public async System.Threading.Tasks.Task<Microsoft.WindowsAzure.Management.Scheduler.Models.SchedulerOperationStatusResponse> GetOperationStatusAsync(string requestId, CancellationToken cancellationToken)
{
// Validate
if (requestId == null)
{
throw new ArgumentNullException("requestId");
}
// Tracing
bool shouldTrace = CloudContext.Configuration.Tracing.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = Tracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("requestId", requestId);
Tracing.Enter(invocationId, this, "GetOperationStatusAsync", tracingParameters);
}
// Construct URL
string url = (this.Credentials.SubscriptionId != null ? this.Credentials.SubscriptionId.Trim() : "") + "/operations/" + requestId.Trim();
string baseUrl = this.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("x-ms-version", "2013-03-01");
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
Tracing.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
Tracing.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
Tracing.Error(invocationId, ex);
}
throw ex;
}
// Create Result
SchedulerOperationStatusResponse result = null;
// Deserialize Response
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new SchedulerOperationStatusResponse();
XDocument responseDoc = XDocument.Parse(responseContent);
XElement operationElement = responseDoc.Element(XName.Get("Operation", "http://schemas.microsoft.com/windowsazure"));
if (operationElement != null)
{
XElement idElement = operationElement.Element(XName.Get("ID", "http://schemas.microsoft.com/windowsazure"));
if (idElement != null)
{
string idInstance = idElement.Value;
result.Id = idInstance;
}
XElement statusElement = operationElement.Element(XName.Get("Status", "http://schemas.microsoft.com/windowsazure"));
if (statusElement != null)
{
SchedulerOperationStatus statusInstance = ((SchedulerOperationStatus)Enum.Parse(typeof(SchedulerOperationStatus), statusElement.Value, true));
result.Status = statusInstance;
}
XElement httpStatusCodeElement = operationElement.Element(XName.Get("HttpStatusCode", "http://schemas.microsoft.com/windowsazure"));
if (httpStatusCodeElement != null)
{
HttpStatusCode httpStatusCodeInstance = ((HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), httpStatusCodeElement.Value, true));
result.HttpStatusCode = httpStatusCodeInstance;
}
XElement errorElement = operationElement.Element(XName.Get("Error", "http://schemas.microsoft.com/windowsazure"));
if (errorElement != null)
{
SchedulerOperationStatusResponse.ErrorDetails errorInstance = new SchedulerOperationStatusResponse.ErrorDetails();
result.Error = errorInstance;
XElement codeElement = errorElement.Element(XName.Get("Code", "http://schemas.microsoft.com/windowsazure"));
if (codeElement != null)
{
string codeInstance = codeElement.Value;
errorInstance.Code = codeInstance;
}
XElement messageElement = errorElement.Element(XName.Get("Message", "http://schemas.microsoft.com/windowsazure"));
if (messageElement != null)
{
string messageInstance = messageElement.Value;
errorInstance.Message = messageInstance;
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
Tracing.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Gets a list of properties for the resource provider, including
/// supported regions and plans.
/// </summary>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The Resource Provider Get Properties operation response.
/// </returns>
public async System.Threading.Tasks.Task<Microsoft.WindowsAzure.Management.Scheduler.Models.ResourceProviderGetPropertiesResponse> GetResourceProviderPropertiesAsync(CancellationToken cancellationToken)
{
// Validate
// Tracing
bool shouldTrace = CloudContext.Configuration.Tracing.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = Tracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
Tracing.Enter(invocationId, this, "GetResourceProviderPropertiesAsync", tracingParameters);
}
// Construct URL
string url = (this.Credentials.SubscriptionId != null ? this.Credentials.SubscriptionId.Trim() : "") + "/resourceproviders/scheduler/Properties?";
url = url + "resourceType=JobCollections";
string baseUrl = this.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("x-ms-version", "2013-03-01");
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
Tracing.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
Tracing.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
Tracing.Error(invocationId, ex);
}
throw ex;
}
// Create Result
ResourceProviderGetPropertiesResponse result = null;
// Deserialize Response
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new ResourceProviderGetPropertiesResponse();
XDocument responseDoc = XDocument.Parse(responseContent);
XElement resourceProviderPropertiesSequenceElement = responseDoc.Element(XName.Get("ResourceProviderProperties", "http://schemas.microsoft.com/windowsazure"));
if (resourceProviderPropertiesSequenceElement != null)
{
foreach (XElement resourceProviderPropertiesElement in resourceProviderPropertiesSequenceElement.Elements(XName.Get("ResourceProviderProperty", "http://schemas.microsoft.com/windowsazure")))
{
string resourceProviderPropertiesKey = resourceProviderPropertiesElement.Element(XName.Get("Key", "http://schemas.microsoft.com/windowsazure")).Value;
string resourceProviderPropertiesValue = resourceProviderPropertiesElement.Element(XName.Get("Value", "http://schemas.microsoft.com/windowsazure")).Value;
result.Properties.Add(resourceProviderPropertiesKey, resourceProviderPropertiesValue);
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
Tracing.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Register the Scheduler resource provider with your subscription.
/// </summary>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public async System.Threading.Tasks.Task<OperationResponse> RegisterResourceProviderAsync(CancellationToken cancellationToken)
{
// Validate
// Tracing
bool shouldTrace = CloudContext.Configuration.Tracing.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = Tracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
Tracing.Enter(invocationId, this, "RegisterResourceProviderAsync", tracingParameters);
}
// Construct URL
string url = (this.Credentials.SubscriptionId != null ? this.Credentials.SubscriptionId.Trim() : "") + "/services?";
url = url + "service=scheduler.JobCollections";
url = url + "&action=register";
string baseUrl = this.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Put;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("x-ms-version", "2013-03-01");
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
Tracing.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
Tracing.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
Tracing.Error(invocationId, ex);
}
throw ex;
}
// Create Result
OperationResponse result = null;
result = new OperationResponse();
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
Tracing.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Unregister the Scheduler resource provider with your subscription.
/// </summary>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public async System.Threading.Tasks.Task<OperationResponse> UnregisterResourceProviderAsync(CancellationToken cancellationToken)
{
// Validate
// Tracing
bool shouldTrace = CloudContext.Configuration.Tracing.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = Tracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
Tracing.Enter(invocationId, this, "UnregisterResourceProviderAsync", tracingParameters);
}
// Construct URL
string url = (this.Credentials.SubscriptionId != null ? this.Credentials.SubscriptionId.Trim() : "") + "/services?";
url = url + "service=scheduler.JobCollections";
url = url + "&action=unregister";
string baseUrl = this.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Put;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("x-ms-version", "2013-03-01");
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
Tracing.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
Tracing.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
Tracing.Error(invocationId, ex);
}
throw ex;
}
// Create Result
OperationResponse result = null;
result = new OperationResponse();
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
Tracing.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
}
}
| |
using Lucene.Net.Support;
using System;
namespace Lucene.Net.Util
{
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/// <summary>
/// Some useful constants.
///
/// </summary>
public sealed class Constants
{
private Constants() // can't construct
{
}
/// <summary>
/// The value of <tt>System.getProperty("java.version")</tt>. * </summary>
public static readonly string JAVA_VERSION = AppSettings.Get("java.version", "");
public static readonly string JAVA_VENDOR = AppSettings.Get("java.vendor", "");
public static readonly string JVM_VENDOR = AppSettings.Get("java.vm.vendor", "");
public static readonly string JVM_VERSION = AppSettings.Get("java.vm.version", "");
public static readonly string JVM_NAME = AppSettings.Get("java.vm.name", "");
/// <summary>
/// The value of <tt>System.getProperty("os.name")</tt>. * </summary>
public static readonly string OS_NAME = GetEnvironmentVariable("OS", "Windows_NT") ?? "Linux";
/// <summary>
/// True iff running on Linux. </summary>
public static readonly bool LINUX = OS_NAME.StartsWith("Linux");
/// <summary>
/// True iff running on Windows. </summary>
public static readonly bool WINDOWS = OS_NAME.StartsWith("Windows");
/// <summary>
/// True iff running on SunOS. </summary>
public static readonly bool SUN_OS = OS_NAME.StartsWith("SunOS");
/// <summary>
/// True iff running on Mac OS X </summary>
public static readonly bool MAC_OS_X = OS_NAME.StartsWith("Mac OS X");
/// <summary>
/// True iff running on FreeBSD </summary>
public static readonly bool FREE_BSD = OS_NAME.StartsWith("FreeBSD");
public static readonly string OS_ARCH = GetEnvironmentVariable("PROCESSOR_ARCHITECTURE", "x86");
public static readonly string OS_VERSION = GetEnvironmentVariable("OS_VERSION", "?");
[Obsolete("We are not running on Java for heavens sake")]
public static readonly bool JRE_IS_MINIMUM_JAVA6 = (bool)new bool?(true); // prevent inlining in foreign class files
[Obsolete("We are not running on Java for heavens sake")]
public static readonly bool JRE_IS_MINIMUM_JAVA7 = (bool)new bool?(true); // prevent inlining in foreign class files
[Obsolete("We are not running on Java for heavens sake")]
public static readonly bool JRE_IS_MINIMUM_JAVA8;
[Obsolete("We are not running on Java for heavens sake")]
public static readonly bool JRE_IS_64BIT;
static Constants()
{
if (IntPtr.Size == 8)
{
JRE_IS_64BIT = true;// 64 bit machine
}
else if (IntPtr.Size == 4)
{
JRE_IS_64BIT = false;// 32 bit machine
}
try
{
LUCENE_VERSION = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString();
}
catch (System.Security.SecurityException) //Ignore in medium trust.
{
}
/* LUCENE TO-DO Well that was all over the top to check architechture
bool is64Bit = false;
try
{
Type unsafeClass = Type.GetType("sun.misc.Unsafe");
Field unsafeField = unsafeClass.getDeclaredField("theUnsafe");
unsafeField.Accessible = true;
object @unsafe = unsafeField.get(null);
int addressSize = (int)((Number) unsafeClass.GetMethod("addressSize").invoke(@unsafe));
is64Bit = addressSize >= 8;
}
catch (Exception e)
{
string x = System.getProperty("sun.arch.data.model");
if (x != null)
{
is64Bit = x.IndexOf("64") != -1;
}
else
{
if (OS_ARCH != null && OS_ARCH.IndexOf("64") != -1)
{
is64Bit = true;
}
else
{
is64Bit = false;
}
}
}
JRE_IS_64BIT = is64Bit;
// this method only exists in Java 8:
bool v8 = true;
try
{
typeof(Collections).getMethod("emptySortedSet");
}
catch (NoSuchMethodException nsme)
{
v8 = false;
}
JRE_IS_MINIMUM_JAVA8 = v8;
Package pkg = LucenePackage.Get();
string v = (pkg == null) ? null : pkg.ImplementationVersion;
if (v == null)
{
v = MainVersionWithoutAlphaBeta() + "-SNAPSHOT";
}
LUCENE_VERSION = Ident(v);*/
}
// this method prevents inlining the final version constant in compiled classes,
// see: http://www.javaworld.com/community/node/3400
private static string Ident(string s)
{
return s.ToString();
}
// We should never change index format with minor versions, so it should always be x.y or x.y.0.z for alpha/beta versions!
/// <summary>
/// this is the internal Lucene version, recorded into each segment.
/// NOTE: we track per-segment version as a String with the {@code "X.Y"} format
/// (no minor version), e.g. {@code "4.0", "3.1", "3.0"}.
/// <p>Alpha and Beta versions will have numbers like {@code "X.Y.0.Z"},
/// anything else is not allowed. this is done to prevent people from
/// using indexes created with ALPHA/BETA versions with the released version.
/// </summary>
public static readonly string LUCENE_MAIN_VERSION = Ident("4.8");
/// <summary>
/// this is the Lucene version for display purposes.
/// </summary>
public static readonly string LUCENE_VERSION;
/// <summary>
/// Returns a LUCENE_MAIN_VERSION without any ALPHA/BETA qualifier
/// Used by test only!
/// </summary>
public static string MainVersionWithoutAlphaBeta()
{
string[] parts = LUCENE_MAIN_VERSION.Split("\\.", true);
if (parts.Length == 4 && "0".Equals(parts[2]))
{
return parts[0] + "." + parts[1];
}
return LUCENE_MAIN_VERSION;
}
#region MEDIUM-TRUST Support
private static string GetEnvironmentVariable(string variable, string defaultValueOnSecurityException)
{
try
{
if (variable == "OS_VERSION") return System.Environment.OSVersion.ToString();
return System.Environment.GetEnvironmentVariable(variable);
}
catch (System.Security.SecurityException)
{
return defaultValueOnSecurityException;
}
}
#endregion MEDIUM-TRUST Support
}
}
| |
/********************************************************************
The Multiverse Platform is made available under the MIT License.
Copyright (c) 2012 The Multiverse Foundation
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.
*********************************************************************/
#region Using directives
using System;
using System.Collections.Generic;
using System.Text;
using System.Diagnostics;
using System.Net;
#endregion
namespace Multiverse.Network.Rdp
{
public class RdpPacket
{
public class Offset
{
public const int HeaderLength = 1;
public const int DataLength = 2;
public const int SeqNumber = 4;
public const int AckNumber = 8;
public const int VariableHeaderArea = 12;
public const int MaxSegments = 12;
public const int MaxSegmentSize = 14;
public const int OptionFlags = 16;
}
// 0 0 0 1 1
// 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5
// +-+-+-+-+-+-+---+---------------+
// |S|A|E|R|N| |Ver| Header |
// 0 |Y|C|A|S|U|0|No.| Length |
// |N|K|K|T|L| | | |
// +-+-+-+-+-+-+---+---------------+
// 1 | Data Length |
// +---------------+---------------+
// 2 | |
// +--- Sequence Number ---+
// 3 | |
// +---------------+---------------+
// 4 | |
// +--- Acknowledgement Number ---+
// 5 | |
// +---------------+---------------+
// 6 | Variable Header Area |
// . .
// . .
// | |
// +---------------+---------------+
const byte SynMask = 1 << 7;
const byte AckMask = 1 << 6;
const byte EakMask = 1 << 5;
const byte RstMask = 1 << 4;
const byte NulMask = 1 << 3;
const byte VerMask = 3;
const byte SequencedMask = 1 << 7;
public const int MaxEaks = ((255 * 2) - Offset.VariableHeaderArea) / 4;
/// <summary>
/// The length of the variable headers on an open packet
/// </summary>
public const int OpenLength = 6;
byte[] data;
static private byte[] ConvertInt(int val) {
return BitConverter.GetBytes(IPAddress.HostToNetworkOrder(val));
}
static private int ConvertInt(byte[] val, int offset) {
return IPAddress.HostToNetworkOrder(BitConverter.ToInt32(val, offset));
}
static private byte[] ConvertShort(short val) {
return BitConverter.GetBytes(IPAddress.HostToNetworkOrder(val));
}
static private short ConvertShort(byte[] val, int offset) {
return IPAddress.HostToNetworkOrder(BitConverter.ToInt16(val, offset));
}
public RdpPacket(byte[] data) {
this.data = data;
}
public RdpPacket(int dataLength) : this(dataLength, 0) {
}
/// <summary>
/// Create a packet with optionLength bytes set aside for the
/// variable header section
/// </summary>
/// <param name="dataLength"></param>
/// <param name="optionLength"></param>
public RdpPacket(int dataLength, int optionLength) {
int hdrLen = optionLength + Offset.VariableHeaderArea;
data = new byte[dataLength + hdrLen];
HeaderLength = hdrLen / 2;
DataLength = (short)dataLength;
}
public override string ToString() {
string rv = string.Format("{0}:{1}:{2}:{3}:{4} - {5}\tdatalen: {6} seq: {7} ack: {8}",
Syn, Ack, Eak, Rst, Nul, HeaderLength,
DataLength, SeqNumber, AckNumber);
if (Syn)
rv = rv + string.Format("\t{0}:{1}:{2}", MaxSegments, MaxSegmentSize, Sequenced);
else if (Eak) {
int[] eakEntries = EakEntries;
rv = rv + "\teack:";
foreach (int i in eakEntries)
rv = rv + string.Format(" {0}", i);
}
return rv;
}
#region Properties
public bool Syn {
get {
return (data[0] & SynMask) != 0;
}
set {
if (value)
data[0] |= SynMask;
else if (Syn)
data[0] -= SynMask;
}
}
public bool Ack {
get {
return (data[0] & AckMask) != 0;
}
set {
if (value)
data[0] |= AckMask;
else if (Ack)
data[0] -= AckMask;
}
}
public bool Eak {
get {
return (data[0] & EakMask) != 0;
}
set {
if (value)
data[0] |= EakMask;
else if (Eak)
data[0] -= EakMask;
}
}
public bool Rst {
get {
return (data[0] & RstMask) != 0;
}
set {
if (value)
data[0] |= RstMask;
else if (Rst)
data[0] -= RstMask;
}
}
public bool Nul {
get {
return (data[0] & NulMask) != 0;
}
set {
if (value)
data[0] |= NulMask;
else if (Nul)
data[0] -= NulMask;
}
}
public bool HasData {
get {
return DataLength != 0;
}
}
public short DataLength {
get {
return ConvertShort(data, Offset.DataLength);
}
set {
byte[] val = ConvertShort(value);
Array.Copy(val, 0, data, Offset.DataLength, 2);
}
}
public int HeaderLength {
get {
return (int)data[Offset.HeaderLength];
}
set {
data[Offset.HeaderLength] = (byte)value;
}
}
public int SeqNumber {
get {
return ConvertInt(data, Offset.SeqNumber);
}
set {
byte[] val = ConvertInt(value);
Array.Copy(val, 0, data, Offset.SeqNumber, 4);
}
}
public int AckNumber {
get {
return ConvertInt(data, Offset.AckNumber);
}
set {
byte[] val = ConvertInt(value);
Array.Copy(val, 0, data, Offset.AckNumber, 4);
}
}
public short MaxSegments {
get {
return ConvertShort(data, Offset.MaxSegments);
}
set {
byte[] val = ConvertShort(value);
Array.Copy(val, 0, data, Offset.MaxSegments, 2);
}
}
public short MaxSegmentSize {
get {
return ConvertShort(data, Offset.MaxSegmentSize);
}
set {
byte[] val = ConvertShort(value);
Array.Copy(val, 0, data, Offset.MaxSegmentSize, 2);
}
}
public bool Sequenced {
get {
byte[] val = new byte[2];
Array.Copy(data, Offset.OptionFlags, val, 0, 2);
return (val[0] & SequencedMask) != 0;
}
set {
byte[] val = new byte[2];
Array.Copy(data, Offset.OptionFlags, val, 0, 2);
if (value)
val[0] |= SequencedMask;
else if ((val[0] & SequencedMask) != 0)
val[0] -= SequencedMask;
Array.Copy(val, 0, data, Offset.OptionFlags, 2);
}
}
public int[] EakEntries {
get {
if (!Eak)
return null;
int eakLen = HeaderLength * 2 - Offset.VariableHeaderArea;
int[] rv = new int[eakLen / 4];
for (int i = 0; i < rv.Length; ++i) {
int offset = Offset.VariableHeaderArea + i * 4;
rv[i] = ConvertInt(data, offset);
}
return rv;
}
set {
Debug.Assert(4 * value.Length + Offset.VariableHeaderArea == HeaderLength * 2,
"Mismatched header length");
int eakCount = value.Length;
if (eakCount > MaxEaks)
eakCount = MaxEaks;
// this will lead to >500 bytes of eak data, which means
// that including the other headers, we have more than
// 512 bytes of header, but the header length field is
// limited to 256 shorts or 512 bytes.
for (int i = 0; i < eakCount; ++i) {
int offset = Offset.VariableHeaderArea + i * 4;
byte[] val = ConvertInt(value[i]);
Array.Copy(val, 0, data, offset, 4);
}
}
}
public byte[] PacketData {
get {
return data;
}
}
public int DataOffset {
get {
return HeaderLength * 2;
}
}
public byte[] Data {
get {
byte[] rv = new byte[DataLength];
Array.Copy(data, DataOffset, rv, 0, DataLength);
return rv;
}
}
public int PacketLength {
get {
return HeaderLength * 2 + DataLength;
}
}
#endregion
}
}
| |
#region S# License
/******************************************************************************************
NOTICE!!! This program and source code is owned and licensed by
StockSharp, LLC, www.stocksharp.com
Viewing or use of this code requires your acceptance of the license
agreement found at https://github.com/StockSharp/StockSharp/blob/master/LICENSE
Removal of this comment is a violation of the license agreement.
Project: StockSharp.Algo.Risk.Algo
File: RiskRule.cs
Created: 2015, 11, 11, 2:32 PM
Copyright 2010 by StockSharp, LLC
*******************************************************************************************/
#endregion S# License
namespace StockSharp.Algo.Risk
{
using System;
using System.Collections.Generic;
using System.ComponentModel;
using Ecng.Common;
using Ecng.ComponentModel;
using Ecng.Serialization;
using Ecng.Collections;
using StockSharp.Messages;
using StockSharp.Localization;
/// <summary>
/// Base risk-rule.
/// </summary>
public abstract class RiskRule : NotifiableObject, IRiskRule
{
/// <summary>
/// Initialize <see cref="RiskRule"/>.
/// </summary>
protected RiskRule()
{
}
private string _title;
/// <summary>
/// Header.
/// </summary>
[Browsable(false)]
public string Title
{
get { return _title; }
protected set
{
_title = value;
NotifyChanged(nameof(Title));
}
}
/// <summary>
/// Action that needs to be taken in case of rule activation.
/// </summary>
[DisplayNameLoc(LocalizedStrings.Str722Key)]
[DescriptionLoc(LocalizedStrings.Str859Key)]
[CategoryLoc(LocalizedStrings.GeneralKey)]
public RiskActions Action { get; set; }
/// <summary>
/// To reset the state.
/// </summary>
public virtual void Reset()
{
}
/// <summary>
/// To process the trade message.
/// </summary>
/// <param name="message">The trade message.</param>
/// <returns><see langword="true" />, if the rule is activated, otherwise, <see langword="false" />.</returns>
public abstract bool ProcessMessage(Message message);
/// <summary>
/// Load settings.
/// </summary>
/// <param name="storage">Storage.</param>
public virtual void Load(SettingsStorage storage)
{
Action = storage.GetValue<RiskActions>(nameof(Action));
}
/// <summary>
/// Save settings.
/// </summary>
/// <param name="storage">Storage.</param>
public virtual void Save(SettingsStorage storage)
{
storage.SetValue(nameof(Action), Action.To<string>());
}
}
/// <summary>
/// Risk-rule, tracking profit-loss.
/// </summary>
[DisplayNameLoc(LocalizedStrings.PnLKey)]
[DescriptionLoc(LocalizedStrings.Str860Key)]
public class RiskPnLRule : RiskRule
{
private decimal _pnL;
/// <summary>
/// Profit-loss.
/// </summary>
[DisplayNameLoc(LocalizedStrings.PnLKey)]
[DescriptionLoc(LocalizedStrings.Str861Key)]
[CategoryLoc(LocalizedStrings.GeneralKey)]
public decimal PnL
{
get { return _pnL; }
set
{
_pnL = value;
Title = value.To<string>();
}
}
/// <summary>
/// To process the trade message.
/// </summary>
/// <param name="message">The trade message.</param>
/// <returns><see langword="true" />, if the rule is activated, otherwise, <see langword="false" />.</returns>
public override bool ProcessMessage(Message message)
{
if (message.Type != MessageTypes.PortfolioChange)
return false;
var pfMsg = (PortfolioChangeMessage)message;
var currValue = (decimal?)pfMsg.Changes.TryGetValue(PositionChangeTypes.CurrentValue);
if (currValue == null)
return false;
if (PnL > 0)
return currValue >= PnL;
else
return currValue <= PnL;
}
/// <summary>
/// Save settings.
/// </summary>
/// <param name="storage">Storage.</param>
public override void Save(SettingsStorage storage)
{
base.Save(storage);
storage.SetValue(nameof(PnL), PnL);
}
/// <summary>
/// Load settings.
/// </summary>
/// <param name="storage">Storage.</param>
public override void Load(SettingsStorage storage)
{
base.Load(storage);
PnL = storage.GetValue<decimal>(nameof(PnL));
}
}
/// <summary>
/// Risk-rule, tracking position size.
/// </summary>
[DisplayNameLoc(LocalizedStrings.Str862Key)]
[DescriptionLoc(LocalizedStrings.Str863Key)]
public class RiskPositionSizeRule : RiskRule
{
private decimal _position;
/// <summary>
/// Position size.
/// </summary>
[DisplayNameLoc(LocalizedStrings.Str862Key)]
[DescriptionLoc(LocalizedStrings.Str864Key)]
[CategoryLoc(LocalizedStrings.GeneralKey)]
public decimal Position
{
get { return _position; }
set
{
_position = value;
Title = value.To<string>();
}
}
/// <summary>
/// To process the trade message.
/// </summary>
/// <param name="message">The trade message.</param>
/// <returns><see langword="true" />, if the rule is activated, otherwise, <see langword="false" />.</returns>
public override bool ProcessMessage(Message message)
{
if (message.Type != MessageTypes.PositionChange)
return false;
var posMsg = (PositionChangeMessage)message;
var currValue = (decimal?)posMsg.Changes.TryGetValue(PositionChangeTypes.CurrentValue);
if (currValue == null)
return false;
if (Position > 0)
return currValue >= Position;
else
return currValue <= Position;
}
/// <summary>
/// Save settings.
/// </summary>
/// <param name="storage">Storage.</param>
public override void Save(SettingsStorage storage)
{
base.Save(storage);
storage.SetValue(nameof(Position), Position);
}
/// <summary>
/// Load settings.
/// </summary>
/// <param name="storage">Storage.</param>
public override void Load(SettingsStorage storage)
{
base.Load(storage);
Position = storage.GetValue<decimal>(nameof(Position));
}
}
/// <summary>
/// Risk-rule, tracking position lifetime.
/// </summary>
[DisplayNameLoc(LocalizedStrings.Str865Key)]
[DescriptionLoc(LocalizedStrings.Str866Key)]
public class RiskPositionTimeRule : RiskRule
{
private readonly Dictionary<Tuple<SecurityId, string>, DateTimeOffset> _posOpenTime = new Dictionary<Tuple<SecurityId, string>, DateTimeOffset>();
private TimeSpan _time;
/// <summary>
/// Position lifetime.
/// </summary>
[DisplayNameLoc(LocalizedStrings.TimeKey)]
[DescriptionLoc(LocalizedStrings.Str867Key)]
[CategoryLoc(LocalizedStrings.GeneralKey)]
public TimeSpan Time
{
get { return _time; }
set
{
_time = value;
Title = value.To<string>();
}
}
/// <summary>
/// To reset the state.
/// </summary>
public override void Reset()
{
base.Reset();
_posOpenTime.Clear();
}
/// <summary>
/// To process the trade message.
/// </summary>
/// <param name="message">The trade message.</param>
/// <returns><see langword="true" />, if the rule is activated, otherwise, <see langword="false" />.</returns>
public override bool ProcessMessage(Message message)
{
switch (message.Type)
{
case MessageTypes.PositionChange:
{
var posMsg = (PositionChangeMessage)message;
var currValue = (decimal?)posMsg.Changes.TryGetValue(PositionChangeTypes.CurrentValue);
if (currValue == null)
return false;
var key = Tuple.Create(posMsg.SecurityId, posMsg.PortfolioName);
if (currValue == 0)
{
_posOpenTime.Remove(key);
return false;
}
var openTime = _posOpenTime.TryGetValue2(key);
if (openTime == null)
{
_posOpenTime.Add(key, posMsg.LocalTime);
return false;
}
var diff = posMsg.LocalTime - openTime;
if (diff < Time)
return false;
_posOpenTime.Remove(key);
return true;
}
case MessageTypes.Time:
{
List<Tuple<SecurityId, string>> removingPos = null;
foreach (var pair in _posOpenTime)
{
var diff = message.LocalTime - pair.Value;
if (diff < Time)
continue;
if (removingPos == null)
removingPos = new List<Tuple<SecurityId, string>>();
removingPos.Add(pair.Key);
}
removingPos?.ForEach(t => _posOpenTime.Remove(t));
return removingPos != null;
}
}
return false;
}
/// <summary>
/// Save settings.
/// </summary>
/// <param name="storage">Storage.</param>
public override void Save(SettingsStorage storage)
{
base.Save(storage);
storage.SetValue(nameof(Time), Time);
}
/// <summary>
/// Load settings.
/// </summary>
/// <param name="storage">Storage.</param>
public override void Load(SettingsStorage storage)
{
base.Load(storage);
Time = storage.GetValue<TimeSpan>(nameof(Time));
}
}
/// <summary>
/// Risk-rule, tracking commission size.
/// </summary>
[DisplayNameLoc(LocalizedStrings.Str159Key)]
[DescriptionLoc(LocalizedStrings.Str868Key)]
public class RiskCommissionRule : RiskRule
{
private decimal _commission;
/// <summary>
/// Commission size.
/// </summary>
[DisplayNameLoc(LocalizedStrings.Str159Key)]
[DescriptionLoc(LocalizedStrings.Str869Key)]
[CategoryLoc(LocalizedStrings.GeneralKey)]
public decimal Commission
{
get { return _commission; }
set
{
_commission = value;
Title = value.To<string>();
}
}
/// <summary>
/// To process the trade message.
/// </summary>
/// <param name="message">The trade message.</param>
/// <returns><see langword="true" />, if the rule is activated, otherwise, <see langword="false" />.</returns>
public override bool ProcessMessage(Message message)
{
if (message.Type != MessageTypes.PortfolioChange)
return false;
var pfMsg = (PortfolioChangeMessage)message;
var currValue = (decimal?)pfMsg.Changes.TryGetValue(PositionChangeTypes.Commission);
if (currValue == null)
return false;
return currValue >= Commission;
}
/// <summary>
/// Save settings.
/// </summary>
/// <param name="storage">Storage.</param>
public override void Save(SettingsStorage storage)
{
base.Save(storage);
storage.SetValue(nameof(Commission), Commission);
}
/// <summary>
/// Load settings.
/// </summary>
/// <param name="storage">Storage.</param>
public override void Load(SettingsStorage storage)
{
base.Load(storage);
Commission = storage.GetValue<decimal>(nameof(Commission));
}
}
/// <summary>
/// Risk-rule, tracking slippage size.
/// </summary>
[DisplayNameLoc(LocalizedStrings.Str163Key)]
[DescriptionLoc(LocalizedStrings.Str870Key)]
public class RiskSlippageRule : RiskRule
{
private decimal _slippage;
/// <summary>
/// Sllippage size.
/// </summary>
[DisplayNameLoc(LocalizedStrings.Str163Key)]
[DescriptionLoc(LocalizedStrings.Str871Key)]
[CategoryLoc(LocalizedStrings.GeneralKey)]
public decimal Slippage
{
get { return _slippage; }
set
{
_slippage = value;
Title = value.To<string>();
}
}
/// <summary>
/// To process the trade message.
/// </summary>
/// <param name="message">The trade message.</param>
/// <returns><see langword="true" />, if the rule is activated, otherwise, <see langword="false" />.</returns>
public override bool ProcessMessage(Message message)
{
if (message.Type != MessageTypes.Execution)
return false;
var execMsg = (ExecutionMessage)message;
var currValue = execMsg.Slippage;
if (currValue == null)
return false;
if (Slippage > 0)
return currValue > Slippage;
else
return currValue < Slippage;
}
/// <summary>
/// Save settings.
/// </summary>
/// <param name="storage">Storage.</param>
public override void Save(SettingsStorage storage)
{
base.Save(storage);
storage.SetValue(nameof(Slippage), Slippage);
}
/// <summary>
/// Load settings.
/// </summary>
/// <param name="storage">Storage.</param>
public override void Load(SettingsStorage storage)
{
base.Load(storage);
Slippage = storage.GetValue<decimal>(nameof(Slippage));
}
}
/// <summary>
/// Risk-rule, tracking order price.
/// </summary>
[DisplayNameLoc(LocalizedStrings.Str872Key)]
[DescriptionLoc(LocalizedStrings.Str873Key)]
public class RiskOrderPriceRule : RiskRule
{
private decimal _price;
/// <summary>
/// Order price.
/// </summary>
[DisplayNameLoc(LocalizedStrings.PriceKey)]
[DescriptionLoc(LocalizedStrings.OrderPriceKey)]
[CategoryLoc(LocalizedStrings.GeneralKey)]
public decimal Price
{
get { return _price; }
set
{
_price = value;
Title = value.To<string>();
}
}
/// <summary>
/// To process the trade message.
/// </summary>
/// <param name="message">The trade message.</param>
/// <returns><see langword="true" />, if the rule is activated, otherwise, <see langword="false" />.</returns>
public override bool ProcessMessage(Message message)
{
switch (message.Type)
{
case MessageTypes.OrderRegister:
{
var orderReg = (OrderRegisterMessage)message;
return orderReg.Price >= Price;
}
case MessageTypes.OrderReplace:
{
var orderReplace = (OrderReplaceMessage)message;
return orderReplace.Price > 0 && orderReplace.Price >= Price;
}
default:
return false;
}
}
/// <summary>
/// Save settings.
/// </summary>
/// <param name="storage">Storage.</param>
public override void Save(SettingsStorage storage)
{
base.Save(storage);
storage.SetValue(nameof(Price), Price);
}
/// <summary>
/// Load settings.
/// </summary>
/// <param name="storage">Storage.</param>
public override void Load(SettingsStorage storage)
{
base.Load(storage);
Price = storage.GetValue<decimal>(nameof(Price));
}
}
/// <summary>
/// Risk-rule, tracking order volume.
/// </summary>
[DisplayNameLoc(LocalizedStrings.Str662Key)]
[DescriptionLoc(LocalizedStrings.Str874Key)]
public class RiskOrderVolumeRule : RiskRule
{
private decimal _volume;
/// <summary>
/// Order volume.
/// </summary>
[DisplayNameLoc(LocalizedStrings.VolumeKey)]
[DescriptionLoc(LocalizedStrings.Str875Key)]
[CategoryLoc(LocalizedStrings.GeneralKey)]
public decimal Volume
{
get { return _volume; }
set
{
_volume = value;
Title = value.To<string>();
}
}
/// <summary>
/// To process the trade message.
/// </summary>
/// <param name="message">The trade message.</param>
/// <returns><see langword="true" />, if the rule is activated, otherwise, <see langword="false" />.</returns>
public override bool ProcessMessage(Message message)
{
switch (message.Type)
{
case MessageTypes.OrderRegister:
{
var orderReg = (OrderRegisterMessage)message;
return orderReg.Volume >= Volume;
}
case MessageTypes.OrderReplace:
{
var orderReplace = (OrderReplaceMessage)message;
return orderReplace.Volume > 0 && orderReplace.Volume >= Volume;
}
default:
return false;
}
}
/// <summary>
/// Save settings.
/// </summary>
/// <param name="storage">Storage.</param>
public override void Save(SettingsStorage storage)
{
base.Save(storage);
storage.SetValue(nameof(Volume), Volume);
}
/// <summary>
/// Load settings.
/// </summary>
/// <param name="storage">Storage.</param>
public override void Load(SettingsStorage storage)
{
base.Load(storage);
Volume = storage.GetValue<decimal>(nameof(Volume));
}
}
/// <summary>
/// Risk-rule, tracking orders placing frequency.
/// </summary>
[DisplayNameLoc(LocalizedStrings.Str876Key)]
[DescriptionLoc(LocalizedStrings.Str877Key)]
public class RiskOrderFreqRule : RiskRule
{
private DateTimeOffset? _endTime;
private int _current;
private int _count;
/// <summary>
/// Order count.
/// </summary>
[DisplayNameLoc(LocalizedStrings.Str878Key)]
[DescriptionLoc(LocalizedStrings.Str957Key)]
[CategoryLoc(LocalizedStrings.GeneralKey)]
public int Count
{
get { return _count; }
set
{
_count = value;
Title = value.To<string>();
}
}
private TimeSpan _interval;
/// <summary>
/// Interval, during which orders quantity will be monitored.
/// </summary>
[DisplayNameLoc(LocalizedStrings.Str175Key)]
[DescriptionLoc(LocalizedStrings.Str879Key)]
[CategoryLoc(LocalizedStrings.GeneralKey)]
public TimeSpan Interval
{
get { return _interval; }
set
{
_interval = value;
Title = value.To<string>();
}
}
/// <summary>
/// To reset the state.
/// </summary>
public override void Reset()
{
base.Reset();
_current = 0;
_endTime = null;
}
/// <summary>
/// To process the trade message.
/// </summary>
/// <param name="message">The trade message.</param>
/// <returns><see langword="true" />, if the rule is activated, otherwise, <see langword="false" />.</returns>
public override bool ProcessMessage(Message message)
{
switch (message.Type)
{
case MessageTypes.OrderRegister:
case MessageTypes.OrderReplace:
case MessageTypes.OrderPairReplace:
{
if (_endTime == null)
{
_endTime = message.LocalTime + Interval;
_current = 1;
return false;
}
if (message.LocalTime < _endTime)
{
_current++;
if (_current >= Count)
{
_endTime = message.LocalTime + Interval;
_current = 0;
return true;
}
return false;
}
_endTime = message.LocalTime + Interval;
_current = 0;
return false;
}
}
return false;
}
/// <summary>
/// Save settings.
/// </summary>
/// <param name="storage">Storage.</param>
public override void Save(SettingsStorage storage)
{
base.Save(storage);
storage.SetValue(nameof(Count), Count);
storage.SetValue(nameof(Interval), Interval);
}
/// <summary>
/// Load settings.
/// </summary>
/// <param name="storage">Storage.</param>
public override void Load(SettingsStorage storage)
{
base.Load(storage);
Count = storage.GetValue<int>(nameof(Count));
Interval = storage.GetValue<TimeSpan>(nameof(Interval));
}
}
/// <summary>
/// Risk-rule, tracking trade price.
/// </summary>
[DisplayNameLoc(LocalizedStrings.Str672Key)]
[DescriptionLoc(LocalizedStrings.Str880Key)]
public class RiskTradePriceRule : RiskRule
{
private decimal _price;
/// <summary>
/// Trade price.
/// </summary>
[DisplayNameLoc(LocalizedStrings.PriceKey)]
[DescriptionLoc(LocalizedStrings.Str147Key)]
[CategoryLoc(LocalizedStrings.GeneralKey)]
public decimal Price
{
get { return _price; }
set
{
_price = value;
Title = value.To<string>();
}
}
/// <summary>
/// To process the trade message.
/// </summary>
/// <param name="message">The trade message.</param>
/// <returns><see langword="true" />, if the rule is activated, otherwise, <see langword="false" />.</returns>
public override bool ProcessMessage(Message message)
{
if (message.Type != MessageTypes.Execution)
return false;
var execMsg = (ExecutionMessage)message;
if (!execMsg.HasTradeInfo())
return false;
return execMsg.TradePrice >= Price;
}
/// <summary>
/// Save settings.
/// </summary>
/// <param name="storage">Storage.</param>
public override void Save(SettingsStorage storage)
{
base.Save(storage);
storage.SetValue(nameof(Price), Price);
}
/// <summary>
/// Load settings.
/// </summary>
/// <param name="storage">Storage.</param>
public override void Load(SettingsStorage storage)
{
base.Load(storage);
Price = storage.GetValue<decimal>(nameof(Price));
}
}
/// <summary>
/// Risk-rule, tracking trade volume.
/// </summary>
[DisplayNameLoc(LocalizedStrings.Str664Key)]
[DescriptionLoc(LocalizedStrings.Str881Key)]
public class RiskTradeVolumeRule : RiskRule
{
private decimal _volume;
/// <summary>
/// Trade volume.
/// </summary>
[DisplayNameLoc(LocalizedStrings.VolumeKey)]
[DescriptionLoc(LocalizedStrings.Str882Key)]
[CategoryLoc(LocalizedStrings.GeneralKey)]
public decimal Volume
{
get { return _volume; }
set
{
_volume = value;
Title = value.To<string>();
}
}
/// <summary>
/// To process the trade message.
/// </summary>
/// <param name="message">The trade message.</param>
/// <returns><see langword="true" />, if the rule is activated, otherwise, <see langword="false" />.</returns>
public override bool ProcessMessage(Message message)
{
if (message.Type != MessageTypes.Execution)
return false;
var execMsg = (ExecutionMessage)message;
if (!execMsg.HasTradeInfo())
return false;
return execMsg.TradeVolume >= Volume;
}
/// <summary>
/// Save settings.
/// </summary>
/// <param name="storage">Storage.</param>
public override void Save(SettingsStorage storage)
{
base.Save(storage);
storage.SetValue(nameof(Volume), Volume);
}
/// <summary>
/// Load settings.
/// </summary>
/// <param name="storage">Storage.</param>
public override void Load(SettingsStorage storage)
{
base.Load(storage);
Volume = storage.GetValue<decimal>(nameof(Volume));
}
}
/// <summary>
/// Risk-rule, tracking orders execution frequency.
/// </summary>
[DisplayNameLoc(LocalizedStrings.Str883Key)]
[DescriptionLoc(LocalizedStrings.Str884Key)]
public class RiskTradeFreqRule : RiskRule
{
private DateTimeOffset? _endTime;
private int _current;
private int _count;
/// <summary>
/// Number of trades.
/// </summary>
[DisplayNameLoc(LocalizedStrings.Str878Key)]
[DescriptionLoc(LocalizedStrings.Str232Key, true)]
[CategoryLoc(LocalizedStrings.GeneralKey)]
public int Count
{
get { return _count; }
set
{
_count = value;
Title = value.To<string>();
}
}
private TimeSpan _interval;
/// <summary>
/// Interval, during which trades quantity will be monitored.
/// </summary>
[DisplayNameLoc(LocalizedStrings.Str175Key)]
[DescriptionLoc(LocalizedStrings.Str885Key)]
[CategoryLoc(LocalizedStrings.GeneralKey)]
public TimeSpan Interval
{
get { return _interval; }
set
{
_interval = value;
Title = value.To<string>();
}
}
/// <summary>
/// To reset the state.
/// </summary>
public override void Reset()
{
base.Reset();
_current = 0;
_endTime = null;
}
/// <summary>
/// To process the trade message.
/// </summary>
/// <param name="message">The trade message.</param>
/// <returns><see langword="true" />, if the rule is activated, otherwise, <see langword="false" />.</returns>
public override bool ProcessMessage(Message message)
{
if (message.Type != MessageTypes.Execution)
return false;
var execMsg = (ExecutionMessage)message;
if (!execMsg.HasTradeInfo())
return false;
if (_endTime == null)
{
_endTime = message.LocalTime + Interval;
_current = 1;
return false;
}
if (message.LocalTime < _endTime)
{
_current++;
if (_current >= Count)
{
_endTime = message.LocalTime + Interval;
_current = 0;
return true;
}
return false;
}
_endTime = message.LocalTime + Interval;
_current = 0;
return false;
}
/// <summary>
/// Save settings.
/// </summary>
/// <param name="storage">Storage.</param>
public override void Save(SettingsStorage storage)
{
base.Save(storage);
storage.SetValue(nameof(Count), Count);
storage.SetValue(nameof(Interval), Interval);
}
/// <summary>
/// Load settings.
/// </summary>
/// <param name="storage">Storage.</param>
public override void Load(SettingsStorage storage)
{
base.Load(storage);
Count = storage.GetValue<int>(nameof(Count));
Interval = storage.GetValue<TimeSpan>(nameof(Interval));
}
}
}
| |
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using SimpleContainer.Helpers;
namespace SimpleContainer.Implementation
{
internal class GenericsAutoCloser
{
private readonly TypesList typesList;
private readonly Func<AssemblyName, bool> assemblyFilter;
private readonly ConcurrentDictionary<Type, Type[]> cache = new ConcurrentDictionary<Type, Type[]>();
public GenericsAutoCloser(TypesList typesList, Func<AssemblyName, bool> assemblyFilter)
{
this.typesList = typesList;
this.assemblyFilter = assemblyFilter;
}
public Type[] AutoCloseDefinition(Type type)
{
Type[] result;
return cache.TryGetValue(type, out result) ? result : InferGenerics(type);
}
private Type[] InferGenerics(Type type)
{
var context = new Dictionary<Type, GenericDefinition>();
Mark(type, context);
Deduce(context);
Publish(context);
return context[type].closures.ToArray();
}
private void Publish(Dictionary<Type, GenericDefinition> context)
{
foreach (var p in context)
cache.TryAdd(p.Key, p.Value.closures.ToArray());
}
private static void Deduce(Dictionary<Type, GenericDefinition> context)
{
var targets = new Queue<GenericDefinition>();
foreach (var p in context)
if (p.Value.closures.Count > 0)
targets.Enqueue(p.Value);
while (targets.Count > 0)
{
var target = targets.Dequeue();
foreach (var referer in target.referers)
{
var anyRefererClosed = false;
foreach (var closure in target.closures)
{
if (referer.isInterface)
{
var closedReferers = closure.ImplementationsOf(referer.definition.type);
foreach (var closedReferer in closedReferers)
anyRefererClosed |= referer.definition.closures.Add(closedReferer);
}
else
{
var closedReferer = referer.definition.type.TryCloseByPattern(referer.pattern, closure);
if (closedReferer != null)
anyRefererClosed |= referer.definition.closures.Add(closedReferer);
}
}
if (anyRefererClosed)
targets.Enqueue(referer.definition);
}
}
}
private GenericDefinition Mark(Type definition, Dictionary<Type, GenericDefinition> context)
{
GenericDefinition result;
if (context.TryGetValue(definition, out result))
return result;
result = new GenericDefinition {type = definition};
context.Add(definition, result);
Type[] types;
if (cache.TryGetValue(definition, out types))
foreach (var type in types)
result.closures.Add(type);
else if (definition.IsAbstract)
MarkInterface(result, context);
else
MarkImplementation(result, context);
return result;
}
private void MarkImplementation(GenericDefinition definition, Dictionary<Type, GenericDefinition> context)
{
var ctor = definition.type.GetConstructor();
if (!ctor.isOk)
return;
var parameters = ctor.value.GetParameters();
var hasAnyGenericDependencies = false;
foreach (var parameter in parameters)
{
var parameterType = parameter.ParameterType;
if (parameterType.IsGenericType && (parameterType.GetGenericTypeDefinition() == typeof (IEnumerable<>)
|| parameterType.GetGenericTypeDefinition() == typeof (Func<>)))
parameterType = parameterType.GetGenericArguments()[0];
if (parameterType.IsSimpleType())
continue;
if (!assemblyFilter(parameterType.Assembly.GetName()))
continue;
if (!parameterType.IsGenericType)
continue;
if (!parameterType.ContainsGenericParameters)
continue;
if (parameterType.GenericParameters().Count != definition.type.GetGenericArguments().Length)
continue;
hasAnyGenericDependencies = true;
Mark(parameterType.GetGenericTypeDefinition(), context).referers.Add(new GenericReferer
{
definition = definition,
pattern = parameterType
});
}
if (!hasAnyGenericDependencies)
MarkImplementationConstraints(definition);
}
private void MarkInterface(GenericDefinition definition, Dictionary<Type, GenericDefinition> context)
{
foreach (var implType in typesList.InheritorsOf(definition.type))
{
var interfaceImpls = implType.ImplementationsOf(definition.type);
if (implType.IsGenericType)
{
var markedImpl = Mark(implType, context);
foreach (var interfaceImpl in interfaceImpls)
markedImpl.referers.Add(new GenericReferer
{
definition = definition,
pattern = interfaceImpl,
isInterface = true
});
}
else
foreach (var interfaceImpl in interfaceImpls)
{
var closure = definition.type.TryCloseByPattern(definition.type, interfaceImpl);
if (closure != null)
definition.closures.Add(closure);
}
}
}
private void MarkImplementationConstraints(GenericDefinition definition)
{
var genericArguments = definition.type.GetGenericArguments();
if (genericArguments.Length != 1)
return;
var constraints = genericArguments[0].GetGenericParameterConstraints();
if (constraints.Length == 0)
return;
foreach (var c in constraints)
if (!assemblyFilter(c.Assembly.GetName()))
return;
var impls = typesList.InheritorsOf(constraints[0]);
for (var i = 1; i < constraints.Length; i++)
{
if (impls.Count == 0)
return;
var current = typesList.InheritorsOf(constraints[i]);
for (var j = impls.Count - 1; j >= 0; j--)
if (current.IndexOf(impls[j]) < 0)
impls.RemoveAt(j);
}
if (impls.Count == 0)
return;
var nonGenericOverrides = typesList.InheritorsOf(definition.type)
.Where(x => !x.IsGenericType)
.ToArray();
foreach (var impl in impls)
{
if (genericArguments[0].GenericParameterAttributes.HasFlag(GenericParameterAttributes.DefaultConstructorConstraint))
if (impl.GetConstructor(Type.EmptyTypes) == null)
continue;
var closedItem = definition.type.MakeGenericType(impl);
var overriden = false;
foreach (var nonGenericOverride in nonGenericOverrides)
if (closedItem.IsAssignableFrom(nonGenericOverride))
{
overriden = true;
break;
}
if (!overriden)
definition.closures.Add(closedItem);
}
}
private class GenericDefinition
{
public readonly List<GenericReferer> referers = new List<GenericReferer>();
public readonly HashSet<Type> closures = new HashSet<Type>();
public Type type;
}
private class GenericReferer
{
public GenericDefinition definition;
public Type pattern;
public bool isInterface;
}
}
}
| |
//-----------------------------------------------------------------------
// <copyright file="PrefabModification.cs" company="Sirenix IVS">
// Copyright (c) 2018 Sirenix IVS
//
// 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.
// </copyright>
//-----------------------------------------------------------------------
namespace Stratus.OdinSerializer
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using Utilities;
/// <summary>
/// An Odin-serialized prefab modification, containing all the information necessary to apply the modification.
/// </summary>
public sealed class PrefabModification
{
/// <summary>
/// The type of modification to be made.
/// </summary>
public PrefabModificationType ModificationType;
/// <summary>
/// The deep reflection path at which to make the modification.
/// </summary>
public string Path;
/// <summary>
/// A list of all deep reflection paths in the target object where the value referenced by this modification was also located.
/// </summary>
public List<string> ReferencePaths;
/// <summary>
/// The modified value to set.
/// </summary>
public object ModifiedValue;
/// <summary>
/// The new list length to set.
/// </summary>
public int NewLength;
/// <summary>
/// The dictionary keys to add.
/// </summary>
public object[] DictionaryKeysAdded;
/// <summary>
/// The dictionary keys to remove.
/// </summary>
public object[] DictionaryKeysRemoved;
/// <summary>
/// Applies the modification to the given Object.
/// </summary>
public void Apply(UnityEngine.Object unityObject)
{
if (this.ModificationType == PrefabModificationType.Value)
{
this.ApplyValue(unityObject);
}
else if (this.ModificationType == PrefabModificationType.ListLength)
{
this.ApplyListLength(unityObject);
}
else if (this.ModificationType == PrefabModificationType.Dictionary)
{
this.ApplyDictionaryModifications(unityObject);
}
else
{
throw new NotImplementedException(this.ModificationType.ToString());
}
}
private void ApplyValue(UnityEngine.Object unityObject)
{
Type valueType = null;
if (!object.ReferenceEquals(this.ModifiedValue, null))
{
valueType = this.ModifiedValue.GetType();
}
if (valueType != null && this.ReferencePaths != null && this.ReferencePaths.Count > 0)
{
for (int i = 0; i < this.ReferencePaths.Count; i++)
{
var path = this.ReferencePaths[i];
try
{
var refValue = GetInstanceFromPath(path, unityObject);
if (!object.ReferenceEquals(refValue, null) && refValue.GetType() == valueType)
{
this.ModifiedValue = refValue;
break;
}
}
catch (Exception) { }
}
}
SetInstanceToPath(this.Path, unityObject, this.ModifiedValue);
}
private void ApplyListLength(UnityEngine.Object unityObject)
{
object listObj = GetInstanceFromPath(this.Path, unityObject);
if (listObj == null)
{
// The list has been deleted on the prefab;
// that supersedes our length change.
return;
}
Type listType = listObj.GetType();
if (listType.IsArray)
{
Array array = (Array)listObj;
if (this.NewLength == array.Length)
{
// If this happens, for some weird reason, then we can actually just not do anything
return;
}
// We actually need to replace all references to this array in the entire object graph!
// Ridiculous, we know - but there's no choice...
// Let's create a new, modified array
Array newArray = Array.CreateInstance(listType.GetElementType(), this.NewLength);
if (this.NewLength > array.Length)
{
Array.Copy(array, 0, newArray, 0, array.Length);
ReplaceAllReferencesInGraph(unityObject, array, newArray);
}
else
{
Array.Copy(array, 0, newArray, 0, newArray.Length);
ReplaceAllReferencesInGraph(unityObject, array, newArray);
}
}
else if (typeof(IList).IsAssignableFrom(listType))
{
IList list = (IList)listObj;
Type listElementType = listType.ImplementsOpenGenericInterface(typeof(IList<>)) ? listType.GetArgumentsOfInheritedOpenGenericInterface(typeof(IList<>))[0] : null;
bool elementIsValueType = listElementType != null ? listElementType.IsValueType : false;
int count = 0;
while (list.Count < this.NewLength)
{
if (elementIsValueType)
{
list.Add(Activator.CreateInstance(listElementType));
}
else
{
list.Add(null);
}
count++;
}
while (list.Count > this.NewLength)
{
list.RemoveAt(list.Count - 1);
}
}
else if (listType.ImplementsOpenGenericInterface(typeof(IList<>)))
{
Type elementType = listType.GetArgumentsOfInheritedOpenGenericInterface(typeof(IList<>))[0];
Type collectionType = typeof(ICollection<>).MakeGenericType(elementType);
bool elementIsValueType = elementType.IsValueType;
PropertyInfo countProp = collectionType.GetProperty("Count");
int count = (int)countProp.GetValue(listObj, null);
if (count < this.NewLength)
{
int add = this.NewLength - count;
MethodInfo addMethod = collectionType.GetMethod("Add");
for (int i = 0; i < add; i++)
{
if (elementIsValueType)
{
addMethod.Invoke(listObj, new object[] { Activator.CreateInstance(elementType) });
}
else
{
addMethod.Invoke(listObj, new object[] { null });
}
count++;
}
}
else if (count > this.NewLength)
{
int remove = count - this.NewLength;
Type listInterfaceType = typeof(IList<>).MakeGenericType(elementType);
MethodInfo removeAtMethod = listInterfaceType.GetMethod("RemoveAt");
for (int i = 0; i < remove; i++)
{
removeAtMethod.Invoke(listObj, new object[] { count - (remove + 1) });
}
}
}
}
private void ApplyDictionaryModifications(UnityEngine.Object unityObject)
{
object dictionaryObj = GetInstanceFromPath(this.Path, unityObject);
if (dictionaryObj == null)
{
// The dictionary has been deleted on the prefab;
// that supersedes our dictionary modifications.
return;
}
var type = dictionaryObj.GetType();
if (!type.ImplementsOpenGenericInterface(typeof(IDictionary<,>)))
{
// A value change has changed the target modified value to
// not be a dictionary - that also supersedes this modification.
return;
}
var typeArgs = type.GetArgumentsOfInheritedOpenGenericInterface(typeof(IDictionary<,>));
var iType = typeof(IDictionary<,>).MakeGenericType(typeArgs);
//
// First, remove keys
//
if (this.DictionaryKeysRemoved != null && this.DictionaryKeysRemoved.Length > 0)
{
MethodInfo method = iType.GetMethod("Remove", new Type[] { typeArgs[0] });
object[] parameters = new object[1];
for (int i = 0; i < this.DictionaryKeysRemoved.Length; i++)
{
parameters[0] = this.DictionaryKeysRemoved[i];
// Ensure the key value is safe to add
if (object.ReferenceEquals(parameters[0], null) || !typeArgs[0].IsAssignableFrom(parameters[0].GetType()))
continue;
method.Invoke(dictionaryObj, parameters);
}
}
//
// Then, add keys
//
if (this.DictionaryKeysAdded != null && this.DictionaryKeysAdded.Length > 0)
{
MethodInfo method = iType.GetMethod("set_Item", typeArgs);
object[] parameters = new object[2];
// Get default value to set key to
parameters[1] = typeArgs[1].IsValueType ? Activator.CreateInstance(typeArgs[1]) : null;
for (int i = 0; i < this.DictionaryKeysAdded.Length; i++)
{
parameters[0] = this.DictionaryKeysAdded[i];
// Ensure the key value is safe to add
if (object.ReferenceEquals(parameters[0], null) || !typeArgs[0].IsAssignableFrom(parameters[0].GetType()))
continue;
method.Invoke(dictionaryObj, parameters);
}
}
}
private static void ReplaceAllReferencesInGraph(object graph, object oldReference, object newReference, HashSet<object> processedReferences = null)
{
if (processedReferences == null)
{
processedReferences = new HashSet<object>(ReferenceEqualityComparer<object>.Default);
}
processedReferences.Add(graph);
if (graph.GetType().IsArray)
{
Array array = (Array)graph;
for (int i = 0; i < array.Length; i++)
{
var value = array.GetValue(i);
if (object.ReferenceEquals(value, null))
{
continue;
}
if (object.ReferenceEquals(value, oldReference))
{
array.SetValue(newReference, i);
value = newReference;
}
if (!processedReferences.Contains(value))
{
ReplaceAllReferencesInGraph(value, oldReference, newReference, processedReferences);
}
}
}
else
{
var members = FormatterUtilities.GetSerializableMembers(graph.GetType(), SerializationPolicies.Everything);
for (int i = 0; i < members.Length; i++)
{
FieldInfo field = (FieldInfo)members[i];
if (field.FieldType.IsPrimitive || field.FieldType == typeof(SerializationData) || field.FieldType == typeof(string))
continue;
object value = field.GetValue(graph);
if (object.ReferenceEquals(value, null))
{
continue;
}
Type valueType = value.GetType();
if (valueType.IsPrimitive || valueType == typeof(SerializationData) || valueType == typeof(string))
continue;
if (object.ReferenceEquals(value, oldReference))
{
field.SetValue(graph, newReference);
value = newReference;
}
if (!processedReferences.Contains(value))
{
ReplaceAllReferencesInGraph(value, oldReference, newReference, processedReferences);
}
}
}
}
private static object GetInstanceFromPath(string path, object instance)
{
string[] steps = path.Split('.');
object currentInstance = instance;
for (int i = 0; i < steps.Length; i++)
{
currentInstance = GetInstanceOfStep(steps[i], currentInstance);
if (object.ReferenceEquals(currentInstance, null))
{
//Debug.LogWarning("Failed to resolve modification path '" + path + "' at step '" + steps[i] + "'.");
return null;
}
}
return currentInstance;
}
private static object GetInstanceOfStep(string step, object instance)
{
Type type = instance.GetType();
if (step.StartsWith("[", StringComparison.InvariantCulture) && step.EndsWith("]", StringComparison.InvariantCulture))
{
int index;
string indexStr = step.Substring(1, step.Length - 2);
if (!int.TryParse(indexStr, out index))
{
throw new ArgumentException("Couldn't parse an index from the path step '" + step + "'.");
}
// We need to check the current type to see if we can treat it as a list
if (type.IsArray)
{
Array array = (Array)instance;
if (index < 0 || index >= array.Length)
{
return null;
}
return array.GetValue(index);
}
else if (typeof(IList).IsAssignableFrom(type))
{
IList list = (IList)instance;
if (index < 0 || index >= list.Count)
{
return null;
}
return list[index];
}
else if (type.ImplementsOpenGenericInterface(typeof(IList<>)))
{
Type elementType = type.GetArgumentsOfInheritedOpenGenericInterface(typeof(IList<>))[0];
Type listType = typeof(IList<>).MakeGenericType(elementType);
MethodInfo getItemMethod = listType.GetMethod("get_Item", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
try
{
return getItemMethod.Invoke(instance, new object[] { index });
}
catch (Exception)
{
return null;
}
}
}
else if (step.StartsWith("{", StringComparison.InvariantCultureIgnoreCase) && step.EndsWith("}", StringComparison.InvariantCultureIgnoreCase))
{
if (type.ImplementsOpenGenericInterface(typeof(IDictionary<,>)))
{
var dictArgs = type.GetArgumentsOfInheritedOpenGenericInterface(typeof(IDictionary<,>));
object key = DictionaryKeyUtility.GetDictionaryKeyValue(step, dictArgs[0]);
Type dictType = typeof(IDictionary<,>).MakeGenericType(dictArgs);
MethodInfo getItemMethod = dictType.GetMethod("get_Item", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
try
{
return getItemMethod.Invoke(instance, new object[] { key });
}
catch (Exception)
{
return null;
}
}
}
else
{
string privateTypeName = null;
int plusIndex = step.IndexOf('+');
if (plusIndex >= 0)
{
privateTypeName = step.Substring(0, plusIndex);
step = step.Substring(plusIndex + 1);
}
var possibleMembers = type.GetAllMembers(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance).Where(n => n is FieldInfo || n is PropertyInfo);
foreach (var member in possibleMembers)
{
if (member.Name == step)
{
if (privateTypeName != null && member.DeclaringType.Name != privateTypeName)
{
continue;
}
return member.GetMemberValue(instance);
}
}
}
return null;
}
private static void SetInstanceToPath(string path, object instance, object value)
{
bool setParentInstance;
string[] steps = path.Split('.');
SetInstanceToPath(path, steps, 0, instance, value, out setParentInstance);
}
private static void SetInstanceToPath(string path, string[] steps, int index, object instance, object value, out bool setParentInstance)
{
setParentInstance = false;
if (index < steps.Length - 1)
{
object currentInstance = GetInstanceOfStep(steps[index], instance);
if (object.ReferenceEquals(currentInstance, null))
{
//Debug.LogWarning("Failed to resolve prefab modification path '" + path + "' at step '" + steps[index] + "'.");
return;
}
SetInstanceToPath(path, steps, index + 1, currentInstance, value, out setParentInstance);
if (setParentInstance)
{
// We need to set the current instance to the parent instance member,
// because the current instance is a value type, and thus it may have
// been boxed. If we don't do this, the value set might be lost.
TrySetInstanceOfStep(steps[index], instance, currentInstance, out setParentInstance);
}
}
else
{
TrySetInstanceOfStep(steps[index], instance, value, out setParentInstance);
}
}
private static bool TrySetInstanceOfStep(string step, object instance, object value, out bool setParentInstance)
{
setParentInstance = false;
try
{
Type type = instance.GetType();
if (step.StartsWith("[", StringComparison.InvariantCulture) && step.EndsWith("]", StringComparison.InvariantCulture))
{
int index;
string indexStr = step.Substring(1, step.Length - 2);
if (!int.TryParse(indexStr, out index))
{
throw new ArgumentException("Couldn't parse an index from the path step '" + step + "'.");
}
// We need to check the current type to see if we can treat it as a list
if (type.IsArray)
{
Array array = (Array)instance;
if (index < 0 || index >= array.Length)
{
return false;
}
array.SetValue(value, index);
return true;
}
else if (typeof(IList).IsAssignableFrom(type))
{
IList list = (IList)instance;
if (index < 0 || index >= list.Count)
{
return false;
}
list[index] = value;
return true;
}
else if (type.ImplementsOpenGenericInterface(typeof(IList<>)))
{
Type elementType = type.GetArgumentsOfInheritedOpenGenericInterface(typeof(IList<>))[0];
Type listType = typeof(IList<>).MakeGenericType(elementType);
MethodInfo setItemMethod = listType.GetMethod("set_Item", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
setItemMethod.Invoke(instance, new object[] { index, value });
return true;
}
}
else if (step.StartsWith("{", StringComparison.InvariantCulture) && step.EndsWith("}", StringComparison.InvariantCulture))
{
if (type.ImplementsOpenGenericInterface(typeof(IDictionary<,>)))
{
var dictArgs = type.GetArgumentsOfInheritedOpenGenericInterface(typeof(IDictionary<,>));
object key = DictionaryKeyUtility.GetDictionaryKeyValue(step, dictArgs[0]);
Type dictType = typeof(IDictionary<,>).MakeGenericType(dictArgs);
MethodInfo containsKeyMethod = dictType.GetMethod("ContainsKey", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
MethodInfo setItemMethod = dictType.GetMethod("set_Item", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
bool containsKey = (bool)containsKeyMethod.Invoke(instance, new object[] { key });
if (!containsKey)
{
// We are *not* allowed to add new keys during this step
return false;
}
setItemMethod.Invoke(instance, new object[] { key, value });
}
}
else
{
string privateTypeName = null;
int plusIndex = step.IndexOf('+');
if (plusIndex >= 0)
{
privateTypeName = step.Substring(0, plusIndex);
step = step.Substring(plusIndex + 1);
}
var possibleMembers = type.GetAllMembers(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance).Where(n => n is FieldInfo || n is PropertyInfo);
foreach (var member in possibleMembers)
{
if (member.Name == step)
{
if (privateTypeName != null && member.DeclaringType.Name != privateTypeName)
{
continue;
}
member.SetMemberValue(instance, value);
if (instance.GetType().IsValueType)
{
setParentInstance = true;
}
return true;
}
}
}
return false;
}
catch (Exception)
{
return false;
}
}
}
}
| |
// 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 (c) 2007 Novell, Inc. (http://www.novell.com)
//
// Authors:
// Andreia Gaita ([email protected])
// Olivier Dufour [email protected]
// Gary Barnett [email protected]
using System;
using System.ComponentModel.Design;
using System.Drawing;
using System.IO;
using System.Reflection;
using System.Resources;
using System.Runtime.Serialization;
using System.Text;
namespace simpleresgen.mono
{
[Serializable]
#if INSIDE_SYSTEM_WEB
internal
#else
public
#endif
sealed class ResXDataNode : ISerializable
{
private string name;
private ResXFileRef fileRef;
private string comment;
private Point pos;
internal ResXDataNodeHandler handler;
public string Comment {
get { return comment ?? String.Empty; }
set { this.comment = value; }
}
public ResXFileRef FileRef {
get { return this.fileRef; }
}
public string Name {
get { return name ?? String.Empty; }
set {
if (value == null)
throw new ArgumentNullException ("name");
if (value == String.Empty)
throw new ArgumentException ("name");
this.name = value;
}
}
internal bool IsWritable {
get {
return (handler is IWritableHandler);
}
}
internal string MimeType { get; set; }
internal string Type { get;set;}
internal string DataString {
get {
if (IsWritable)
return ((IWritableHandler) handler).DataString;
else
throw new NotSupportedException ("Node Not Writable");
}
}
public ResXDataNode (string name, object value) : this (name, value, Point.Empty)
{
}
public ResXDataNode (string name, ResXFileRef fileRef)
{
if (name == null)
throw new ArgumentNullException ("name");
if (fileRef == null)
throw new ArgumentNullException ("fileRef");
if (name.Length == 0)
throw new ArgumentException ("name");
this.name = name;
this.fileRef = fileRef;
pos = Point.Empty;
handler = new FileRefHandler (fileRef);
}
internal ResXDataNode (string name, object value, Point position)
{
if (name == null)
throw new ArgumentNullException ("name");
if (name.Length == 0)
throw new ArgumentException ("name");
Type type = (value == null) ? typeof (object) : value.GetType ();
if ((value != null) && !type.IsSerializable) {
throw new InvalidOperationException (String.Format ("'{0}' of type '{1}' cannot be added"
+ " because it is not serializable",
name, type));
}
this.name = name;
this.pos = position;
handler = new InMemoryHandler (value);
}
internal ResXDataNode (string nameAtt, string mimeTypeAtt, string typeAtt,
string dataString, string commentString, Point position,
string basePath)
{
name = nameAtt;
comment = commentString;
pos = position;
MimeType = mimeTypeAtt;
Type = typeAtt;
if (!String.IsNullOrEmpty (mimeTypeAtt)) {
if (!String.IsNullOrEmpty(typeAtt)) {
handler = new TypeConverterFromResXHandler (dataString, mimeTypeAtt, typeAtt);
} else {
handler = new SerializedFromResXHandler (dataString, mimeTypeAtt);
}
} else if (!String.IsNullOrEmpty (typeAtt)) { //using hard coded types to avoid version mismatches
if (typeAtt.StartsWith ("System.Resources.ResXNullRef, System.Windows.Forms")) {
handler = new NullRefHandler (typeAtt);
} else if (typeAtt.StartsWith ("System.Byte[], mscorlib")) {
handler = new ByteArrayFromResXHandler (dataString);
} else if (typeAtt.StartsWith ("System.Resources.ResXFileRef, System.Windows.Forms")) {
ResXFileRef newFileRef = BuildFileRef (dataString, basePath);
handler = new FileRefHandler (newFileRef);
this.fileRef = newFileRef;
} else {
handler = new TypeConverterFromResXHandler (dataString, mimeTypeAtt, typeAtt);
}
} else {
handler = new InMemoryHandler (dataString);
}
if (handler == null)
throw new Exception ("handler is null");
}
public Point GetNodePosition ()
{
return pos;
}
public string GetValueTypeName (AssemblyName[] names)
{
return handler.GetValueTypeName (names);
}
public string GetValueTypeName (ITypeResolutionService typeResolver)
{
return handler.GetValueTypeName (typeResolver);
}
public Object GetValue (AssemblyName[] names)
{
return handler.GetValue (names);
}
public Object GetValue (ITypeResolutionService typeResolver)
{
return handler.GetValue (typeResolver);
}
//FIXME: .net doesnt instantiate encoding at this stage
ResXFileRef BuildFileRef (string dataString, string basePath)
{
ResXFileRef fr;
string[] parts = ResXFileRef.Parse (dataString);
if (parts.Length < 2)
throw new ArgumentException ("ResXFileRef cannot be generated");
string fileName = parts[0];
if (basePath != null)
fileName = Path.Combine (basePath, parts[0]);
string typeName = parts[1];
if (parts.Length == 3) {
Encoding encoding = Encoding.GetEncoding(parts[2]);
fr = new ResXFileRef (fileName, typeName, encoding);
} else
fr = new ResXFileRef (fileName, typeName);
return fr;
}
#region ISerializable Members
void ISerializable.GetObjectData (SerializationInfo si, StreamingContext context)
{
si.AddValue ("Name", this.Name);
si.AddValue ("Comment", this.Comment);
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using NDesk.Options;
using GitTfs.Core;
using GitTfs.Util;
using StructureMap;
namespace GitTfs.Commands
{
[Pluggable("rcheckin")]
[RequiresValidGitRepository]
public class Rcheckin : GitTfsCommand
{
private readonly CheckinOptions _checkinOptions;
private readonly CheckinOptionsFactory _checkinOptionsFactory;
private readonly TfsWriter _writer;
private readonly Globals _globals;
private readonly AuthorsFile _authors;
private bool AutoRebase { get; set; }
private bool ForceCheckin { get; set; }
public Rcheckin(CheckinOptions checkinOptions, TfsWriter writer, Globals globals, AuthorsFile authors)
{
_checkinOptions = checkinOptions;
_checkinOptionsFactory = new CheckinOptionsFactory(globals);
_writer = writer;
_globals = globals;
_authors = authors;
}
public OptionSet OptionSet
{
get
{
return new OptionSet
{
{"a|autorebase", "Continue and rebase if new TFS changesets found", v => AutoRebase = v != null},
{"ignore-merge", "Force check in ignoring parent tfs branches in merge commits", v => ForceCheckin = v != null},
}.Merge(_checkinOptions.OptionSet);
}
}
// uses rebase and works only with HEAD
public int Run()
{
_globals.WarnOnGitVersion();
if (_globals.Repository.IsBare)
throw new GitTfsException("error: you should specify the local branch to checkin for a bare repository.");
return _writer.Write("HEAD", PerformRCheckin);
}
// uses rebase and works only with HEAD in a none bare repository
public int Run(string localBranch)
{
_globals.WarnOnGitVersion();
if (!_globals.Repository.IsBare)
throw new GitTfsException("error: This syntax with one parameter is only allowed in bare repository.");
_authors.LoadAuthorsFromSavedFile(_globals.GitDir);
return _writer.Write(GitRepository.ShortToLocalName(localBranch), PerformRCheckin);
}
private int PerformRCheckin(TfsChangesetInfo parentChangeset, string refToCheckin)
{
if (_globals.Repository.IsBare)
AutoRebase = false;
if (_globals.Repository.WorkingCopyHasUnstagedOrUncommitedChanges)
{
throw new GitTfsException("error: You have local changes; rebase-workflow checkin only possible with clean working directory.")
.WithRecommendation("Try 'git stash' to stash your local changes and checkin again.");
}
// get latest changes from TFS to minimize possibility of late conflict
Trace.TraceInformation("Fetching changes from TFS to minimize possibility of late conflict...");
parentChangeset.Remote.Fetch();
if (parentChangeset.ChangesetId != parentChangeset.Remote.MaxChangesetId)
{
if (AutoRebase)
{
_globals.Repository.CommandNoisy("rebase", "--preserve-merges", parentChangeset.Remote.RemoteRef);
parentChangeset = _globals.Repository.GetTfsCommit(parentChangeset.Remote.MaxCommitHash);
}
else
{
if (_globals.Repository.IsBare)
_globals.Repository.UpdateRef(refToCheckin, parentChangeset.Remote.MaxCommitHash);
throw new GitTfsException("error: New TFS changesets were found.")
.WithRecommendation("Try to rebase HEAD onto latest TFS checkin and repeat rcheckin or alternatively checkins");
}
}
IEnumerable<GitCommit> commitsToCheckin = _globals.Repository.FindParentCommits(refToCheckin, parentChangeset.Remote.MaxCommitHash);
Trace.WriteLine("Commit to checkin count:" + commitsToCheckin.Count());
if (!commitsToCheckin.Any())
throw new GitTfsException("error: latest TFS commit should be parent of commits being checked in");
SetupMetadataExport(parentChangeset.Remote);
return _PerformRCheckinQuick(parentChangeset, refToCheckin, commitsToCheckin);
}
private void SetupMetadataExport(IGitTfsRemote remote)
{
var exportInitializer = new ExportMetadatasInitializer(_globals);
var shouldExport = _globals.Repository.GetConfig(GitTfsConstants.ExportMetadatasConfigKey) == "true";
exportInitializer.InitializeRemote(remote, shouldExport);
}
private int _PerformRCheckinQuick(TfsChangesetInfo parentChangeset, string refToCheckin, IEnumerable<GitCommit> commitsToCheckin)
{
var tfsRemote = parentChangeset.Remote;
string currentParent = parentChangeset.Remote.MaxCommitHash;
int newChangesetId = 0;
foreach (var commit in commitsToCheckin)
{
var message = BuildCommitMessage(commit, !_checkinOptions.NoGenerateCheckinComment, currentParent);
string target = commit.Sha;
var parents = commit.Parents.Where(c => c.Sha != currentParent).ToArray();
string tfsRepositoryPathOfMergedBranch = _checkinOptions.NoMerge
? null
: FindTfsRepositoryPathOfMergedBranch(tfsRemote, parents, target);
var commitSpecificCheckinOptions = _checkinOptionsFactory.BuildCommitSpecificCheckinOptions(_checkinOptions, message, commit, _authors);
Trace.TraceInformation("Starting checkin of {0} '{1}'", target.Substring(0, 8), commitSpecificCheckinOptions.CheckinComment);
try
{
newChangesetId = tfsRemote.Checkin(target, currentParent, parentChangeset, commitSpecificCheckinOptions, tfsRepositoryPathOfMergedBranch);
var fetchResult = tfsRemote.FetchWithMerge(newChangesetId, false, parents.Select(c => c.Sha).ToArray());
if (fetchResult.NewChangesetCount != 1)
{
var lastCommit = _globals.Repository.FindCommitHashByChangesetId(newChangesetId);
RebaseOnto(lastCommit, target);
if (AutoRebase)
tfsRemote.Repository.CommandNoisy("rebase", "--preserve-merges", tfsRemote.RemoteRef);
else
throw new GitTfsException("error: New TFS changesets were found. Rcheckin was not finished.");
}
currentParent = target;
parentChangeset = new TfsChangesetInfo { ChangesetId = newChangesetId, GitCommit = tfsRemote.MaxCommitHash, Remote = tfsRemote };
Trace.TraceInformation("Done with {0}.", target);
}
catch (Exception)
{
if (newChangesetId != 0)
{
var lastCommit = _globals.Repository.FindCommitHashByChangesetId(newChangesetId);
RebaseOnto(lastCommit, currentParent);
}
throw;
}
}
if (_globals.Repository.IsBare)
_globals.Repository.UpdateRef(refToCheckin, tfsRemote.MaxCommitHash);
else
_globals.Repository.ResetHard(tfsRemote.MaxCommitHash);
Trace.TraceInformation("No more to rcheckin.");
Trace.WriteLine("Cleaning...");
tfsRemote.CleanupWorkspaceDirectory();
return GitTfsExitCodes.OK;
}
public string BuildCommitMessage(GitCommit commit, bool generateCheckinComment, string latest)
{
return generateCheckinComment
? _globals.Repository.GetCommitMessage(commit.Sha, latest)
: _globals.Repository.GetCommit(commit.Sha).Message;
}
private string FindTfsRepositoryPathOfMergedBranch(IGitTfsRemote remoteToCheckin, GitCommit[] gitParents, string target)
{
if (gitParents.Length != 0)
{
Trace.TraceInformation("Working on the merge commit: " + target);
if (gitParents.Length > 1)
Trace.TraceWarning("warning: only 1 parent is supported by TFS for a merge changeset. The other parents won't be materialized in the TFS merge!");
foreach (var gitParent in gitParents)
{
var tfsCommit = _globals.Repository.GetTfsCommit(gitParent);
if (tfsCommit != null)
return tfsCommit.Remote.TfsRepositoryPath;
var lastCheckinCommit = _globals.Repository.GetLastParentTfsCommits(gitParent.Sha).FirstOrDefault();
if (lastCheckinCommit != null)
{
if (!ForceCheckin && lastCheckinCommit.Remote.Id != remoteToCheckin.Id)
throw new GitTfsException("error: the merged branch '" + lastCheckinCommit.Remote.Id
+ "' is a TFS tracked branch (" + lastCheckinCommit.Remote.TfsRepositoryPath
+ ") with some commits not checked in.\nIn this case, the local merge won't be materialized as a merge in tfs...")
.WithRecommendation("check in all the commits of the tfs merged branch in TFS before trying to check in a merge commit",
"use --ignore-merge option to ignore merged TFS branch and check in commit as a normal changeset (not a merge).");
}
else
{
Trace.TraceWarning("warning: the parent " + gitParent + " does not belong to a TFS tracked branch (not checked in TFS) and will be ignored!");
}
}
}
return null;
}
public void RebaseOnto(string newBaseCommit, string oldBaseCommit)
{
_globals.Repository.CommandNoisy("rebase", "--preserve-merges", "--onto", newBaseCommit, oldBaseCommit);
}
}
}
| |
// Copyright (c) Umbraco.
// See LICENSE for more details.
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using NUnit.Framework;
using Umbraco.Cms.Core.Models;
using Umbraco.Cms.Core.Models.Email;
using Umbraco.Cms.Infrastructure.Extensions;
namespace Umbraco.Cms.Tests.UnitTests.Umbraco.Infrastructure.Extensions
{
[TestFixture]
public class EmailMessageExtensionsTests
{
private const string ConfiguredSender = "[email protected]";
[Test]
public void Can_Construct_MimeMessage_From_Simple_EmailMessage()
{
const string from = "[email protected]";
const string to = "[email protected]";
const string subject = "Subject";
const string body = "<p>Message</p>";
const bool isBodyHtml = true;
var emailMessage = new EmailMessage(from, to, subject, body, isBodyHtml);
var result = emailMessage.ToMimeMessage(ConfiguredSender);
Assert.AreEqual(1, result.From.Count());
Assert.AreEqual(from, result.From.First().ToString());
Assert.AreEqual(1, result.To.Count());
Assert.AreEqual(to, result.To.First().ToString());
Assert.AreEqual(subject, result.Subject);
Assert.IsNull(result.TextBody);
Assert.AreEqual(body, result.HtmlBody.ToString());
}
[Test]
public void Can_Construct_MimeMessage_From_Full_EmailMessage()
{
const string from = "[email protected]";
string[] to = new[] { "[email protected]", "[email protected]" };
string[] cc = new[] { "[email protected]", "[email protected]" };
string[] bcc = new[] { "[email protected]", "[email protected]", "[email protected]", "invalid@email@address" };
string[] replyTo = new[] { "[email protected]" };
const string subject = "Subject";
const string body = "Message";
const bool isBodyHtml = false;
using var attachmentStream = new MemoryStream(Encoding.UTF8.GetBytes("test"));
var attachments = new List<EmailMessageAttachment>
{
new EmailMessageAttachment(attachmentStream, "test.txt"),
};
var emailMessage = new EmailMessage(from, to, cc, bcc, replyTo, subject, body, isBodyHtml, attachments);
var result = emailMessage.ToMimeMessage(ConfiguredSender);
Assert.AreEqual(1, result.From.Count());
Assert.AreEqual(from, result.From.First().ToString());
Assert.AreEqual(2, result.To.Count());
Assert.AreEqual(to[0], result.To.First().ToString());
Assert.AreEqual(to[1], result.To.Skip(1).First().ToString());
Assert.AreEqual(2, result.Cc.Count());
Assert.AreEqual(cc[0], result.Cc.First().ToString());
Assert.AreEqual(cc[1], result.Cc.Skip(1).First().ToString());
Assert.AreEqual(3, result.Bcc.Count());
Assert.AreEqual(bcc[0], result.Bcc.First().ToString());
Assert.AreEqual(bcc[1], result.Bcc.Skip(1).First().ToString());
Assert.AreEqual(bcc[2], result.Bcc.Skip(2).First().ToString());
Assert.AreEqual(1, result.ReplyTo.Count());
Assert.AreEqual(replyTo[0], result.ReplyTo.First().ToString());
Assert.AreEqual(subject, result.Subject);
Assert.IsNull(result.HtmlBody);
Assert.AreEqual(body, result.TextBody.ToString());
Assert.AreEqual(1, result.Attachments.Count());
}
[Test]
public void Can_Construct_MimeMessage_With_ConfiguredSender()
{
const string to = "[email protected]";
const string subject = "Subject";
const string body = "<p>Message</p>";
const bool isBodyHtml = true;
var emailMessage = new EmailMessage(null, to, subject, body, isBodyHtml);
var result = emailMessage.ToMimeMessage(ConfiguredSender);
Assert.AreEqual(1, result.From.Count());
Assert.AreEqual(ConfiguredSender, result.From.First().ToString());
Assert.AreEqual(1, result.To.Count());
Assert.AreEqual(to, result.To.First().ToString());
Assert.AreEqual(subject, result.Subject);
Assert.IsNull(result.TextBody);
Assert.AreEqual(body, result.HtmlBody.ToString());
}
[Test]
public void Can_Construct_NotificationEmailModel_From_Simple_MailMessage()
{
const string from = "[email protected]";
const string to = "[email protected]";
const string subject = "Subject";
const string body = "<p>Message</p>";
const bool isBodyHtml = true;
var emailMessage = new EmailMessage(from, to, subject, body, isBodyHtml);
NotificationEmailModel result = emailMessage.ToNotificationEmail(ConfiguredSender);
Assert.AreEqual(from, result.From.Address);
Assert.AreEqual("", result.From.DisplayName);
Assert.AreEqual(1, result.To.Count());
Assert.AreEqual(to, result.To.First().Address);
Assert.AreEqual("", result.To.First().DisplayName);
Assert.AreEqual(subject, result.Subject);
Assert.AreEqual(body, result.Body);
Assert.IsTrue(result.IsBodyHtml);
Assert.IsFalse(result.HasAttachments);
}
[Test]
public void Can_Construct_NotificationEmailModel_From_Simple_MailMessage_With_Configured_Sender()
{
const string to = "[email protected]";
const string subject = "Subject";
const string body = "<p>Message</p>";
const bool isBodyHtml = true;
var emailMessage = new EmailMessage(null, to, subject, body, isBodyHtml);
NotificationEmailModel result = emailMessage.ToNotificationEmail(ConfiguredSender);
Assert.AreEqual(ConfiguredSender, result.From.Address);
Assert.AreEqual("", result.From.DisplayName);
Assert.AreEqual(1, result.To.Count());
Assert.AreEqual(to, result.To.First().Address);
Assert.AreEqual("", result.To.First().DisplayName);
Assert.AreEqual(subject, result.Subject);
Assert.AreEqual(body, result.Body);
Assert.IsTrue(result.IsBodyHtml);
Assert.IsFalse(result.HasAttachments);
}
[Test]
public void Can_Construct_NotificationEmailModel_From_Simple_MailMessage_With_DisplayName()
{
const string from = "\"From Email\" <[email protected]>";
const string to = "\"To Email\" <[email protected]>";
const string subject = "Subject";
const string body = "<p>Message</p>";
const bool isBodyHtml = true;
var emailMessage = new EmailMessage(from, to, subject, body, isBodyHtml);
NotificationEmailModel result = emailMessage.ToNotificationEmail(ConfiguredSender);
Assert.AreEqual("[email protected]", result.From.Address);
Assert.AreEqual("From Email", result.From.DisplayName);
Assert.AreEqual(1, result.To.Count());
Assert.AreEqual("[email protected]", result.To.First().Address);
Assert.AreEqual("To Email", result.To.First().DisplayName);
Assert.AreEqual(subject, result.Subject);
Assert.AreEqual(body, result.Body);
Assert.IsTrue(result.IsBodyHtml);
Assert.IsFalse(result.HasAttachments);
}
[Test]
public void Can_Construct_NotificationEmailModel_From_Full_EmailMessage()
{
const string from = "\"From Email\" <[email protected]>";
string[] to = { "[email protected]", "\"Second Email\" <[email protected]>", "invalid@invalid@invalid" };
string[] cc = { "\"First CC\" <[email protected]>", "[email protected]", "invalid@invalid@invalid" };
string[] bcc = { "[email protected]", "[email protected]", "\"Third BCC\" <[email protected]>", "invalid@email@address" };
string[] replyTo = { "[email protected]", "invalid@invalid@invalid" };
const string subject = "Subject";
const string body = "Message";
const bool isBodyHtml = false;
using var attachmentStream = new MemoryStream(Encoding.UTF8.GetBytes("test"));
var attachments = new List<EmailMessageAttachment>
{
new EmailMessageAttachment(attachmentStream, "test.txt"),
};
var emailMessage = new EmailMessage(from, to, cc, bcc, replyTo, subject, body, isBodyHtml, attachments);
var result = emailMessage.ToNotificationEmail(ConfiguredSender);
Assert.AreEqual("[email protected]", result.From.Address);
Assert.AreEqual("From Email", result.From.DisplayName);
Assert.AreEqual(2, result.To.Count());
Assert.AreEqual("[email protected]", result.To.First().Address);
Assert.AreEqual("", result.To.First().DisplayName);
Assert.AreEqual("[email protected]", result.To.Skip(1).First().Address);
Assert.AreEqual("Second Email", result.To.Skip(1).First().DisplayName);
Assert.AreEqual(2, result.Cc.Count());
Assert.AreEqual("[email protected]", result.Cc.First().Address);
Assert.AreEqual("First CC", result.Cc.First().DisplayName);
Assert.AreEqual("[email protected]", result.Cc.Skip(1).First().Address);
Assert.AreEqual("", result.Cc.Skip(1).First().DisplayName);
Assert.AreEqual(3, result.Bcc.Count());
Assert.AreEqual("[email protected]", result.Bcc.First().Address);
Assert.AreEqual("", result.Bcc.First().DisplayName);
Assert.AreEqual("[email protected]", result.Bcc.Skip(1).First().Address);
Assert.AreEqual("", result.Bcc.Skip(1).First().DisplayName);
Assert.AreEqual("[email protected]", result.Bcc.Skip(2).First().Address);
Assert.AreEqual("Third BCC", result.Bcc.Skip(2).First().DisplayName);
Assert.AreEqual(1, result.ReplyTo.Count());
Assert.AreEqual("[email protected]", result.ReplyTo.First().Address);
Assert.AreEqual("", result.ReplyTo.First().DisplayName);
Assert.AreEqual(subject, result.Subject);
Assert.AreEqual(body, result.Body);
Assert.AreEqual(1, result.Attachments.Count());
}
}
}
| |
//
// FolderGallery.cs
//
// Author:
// Lorenzo Milesi <[email protected]>
// Stephane Delcroix <[email protected]>
// Stephen Shaw <[email protected]>
//
// Copyright (C) 2008-2009 Novell, Inc.
// Copyright (C) 2008 Lorenzo Milesi
// Copyright (C) 2008-2009 Stephane Delcroix
//
// 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 (C) 2005 Alessandro Gervaso <[email protected]>
*
* 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., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301
*/
//This should be used to export the selected pics to an original gallery
//located on a GIO location.
using System;
using System.IO;
using Hyena;
using FSpot;
using FSpot.Core;
using FSpot.Database;
using FSpot.Filters;
using FSpot.Settings;
using FSpot.Utils;
namespace FSpot.Exporters.Folder
{
internal class FolderGallery
{
protected struct ScaleRequest
{
public string Name;
public int Width;
public int Height;
public bool Skip;
public bool CopyExif;
public static ScaleRequest Default = new ScaleRequest (string.Empty, 0, 0, false);
public ScaleRequest (string name, int width, int height, bool skip, bool exif = false)
{
this.Name = name != null ? name : string.Empty;
this.Width = width;
this.Height = height;
this.Skip = skip;
this.CopyExif = exif;
}
public bool AvoidScale (int size)
{
return (size < this.Width && size < this.Height && this.Skip);
}
}
#region Variables
protected bool scale;
protected ScaleRequest[] requests;
#endregion
#region Constructor
internal FolderGallery (IBrowsableCollection selection, string path, string gallery_name)
{
if (null == selection)
throw new ArgumentNullException ("selection");
if (0 == selection.Count)
throw new ArgumentException ("selection can't be empty");
if (null == path)
throw new ArgumentNullException ("path");
if (null == gallery_name)
throw new ArgumentNullException ("gallery_name");
Collection = selection;
GalleryName = gallery_name;
GalleryPath = Path.Combine (path, GalleryName);
this.requests = new ScaleRequest [] { ScaleRequest.Default };
}
#endregion
#region Properties
public string GalleryName { get; protected set; }
public string GalleryPath { get; protected set; }
protected IBrowsableCollection Collection { get; set; }
public string Description { get; set; }
public Uri Destination { get; set; }
protected int Size { get; set; }
public bool ExportTags { get; set; }
public bool ExportTagIcons { get; set; }
string language = string.Empty;
public string Language {
get {
if (language == null) {
if ((language = Environment.GetEnvironmentVariable ("LC_ALL")) == null)
if ((language = Environment.GetEnvironmentVariable ("LC_MESSAGES")) == null)
if ((language = Environment.GetEnvironmentVariable ("LANG")) == null)
language = "en";
if (language.IndexOf ('.') >= 0)
language = language.Substring (0, language.IndexOf ('.'));
if (language.IndexOf ('@') >= 0)
language = language.Substring (0, language.IndexOf ('@'));
language = language.Replace ('_', '-');
}
return language;
}
}
#endregion
#region method
public virtual void GenerateLayout ()
{
MakeDir (GalleryPath);
}
protected virtual string ImageName (int image_num)
{
var uri = Collection [image_num].DefaultVersion.Uri;
var dest_uri = new SafeUri (GalleryPath);
// Find an unused name
int i = 1;
var dest = dest_uri.Append (uri.GetFilename ());
var file = GLib.FileFactory.NewForUri (dest);
while (file.Exists) {
var filename = uri.GetFilenameWithoutExtension ();
var extension = uri.GetExtension ();
dest = dest_uri.Append (string.Format ("{0}-{1}{2}", filename, i++, extension));
file = GLib.FileFactory.NewForUri (dest);
}
return dest.GetFilename ();
}
public void ProcessImage (int image_num, FilterSet filter_set)
{
IPhoto photo = Collection [image_num];
string path;
ScaleRequest req;
req = requests [0];
MakeDir (SubdirPath (req.Name));
path = SubdirPath (req.Name, ImageName (image_num));
using (FilterRequest request = new FilterRequest (photo.DefaultVersion.Uri)) {
filter_set.Convert (request);
if (request.Current.LocalPath == path)
request.Preserve (request.Current);
else
System.IO.File.Copy (request.Current.LocalPath, path, true);
if (photo != null && photo is Photo && App.Instance.Database != null)
App.Instance.Database.Exports.Create ((photo as Photo).Id, (photo as Photo).DefaultVersionId,
ExportStore.FolderExportType,
// FIXME this is wrong, the final path is the one
// after the Xfer.
new SafeUri (path).ToString ());
for (int i = 1; i < requests.Length; i++) {
req = requests [i];
if (scale && req.AvoidScale (Size))
continue;
FilterSet req_set = new FilterSet ();
req_set.Add (new ResizeFilter ((uint)Math.Max (req.Width, req.Height)));
bool sharpen;
try {
sharpen = Preferences.Get<bool> (FolderExport.SHARPEN_KEY);
} catch (NullReferenceException) {
sharpen = true;
Preferences.Set (FolderExport.SHARPEN_KEY, true);
}
if (sharpen) {
if (req.Name == "lq")
req_set.Add (new SharpFilter (0.1, 2, 4));
if (req.Name == "thumbs")
req_set.Add (new SharpFilter (0.1, 2, 5));
}
using (FilterRequest tmp_req = new FilterRequest (photo.DefaultVersion.Uri)) {
req_set.Convert (tmp_req);
MakeDir (SubdirPath (req.Name));
path = SubdirPath (req.Name, ImageName (image_num));
System.IO.File.Copy (tmp_req.Current.LocalPath, path, true);
}
}
}
}
protected string MakeDir (string path)
{
try {
Directory.CreateDirectory (path);
} catch {
Log.ErrorFormat ("Error in creating directory \"{0}\"", path);
}
return path;
}
protected string SubdirPath (string subdir, string file = null)
{
string path = Path.Combine (GalleryPath, subdir);
if (file != null)
path = Path.Combine (path, file);
return path;
}
public void SetScale (int size)
{
this.scale = true;
Size = size;
requests [0].Width = size;
requests [0].Height = size;
}
#endregion
}
}
| |
#region using
using System.Collections.Generic;
using System.Linq;
using Irony.Compiler;
using ScriptNET.Runtime;
using System;
#endregion
namespace ScriptNET.Ast
{
/// <summary>
/// Qualified Name
/// </summary>
internal class ScriptQualifiedName : ScriptExpr
{
#region Members
private string Identifier;
private List<ScriptAst> Modifiers;
private ScriptQualifiedName NamePart;
private delegate void EvaluateFunction(IScriptContext context);
private delegate void AssignFunction(object value, IScriptContext context);
private EvaluateFunction evaluation;
private AssignFunction assignment;
#endregion
#region Constructor
public ScriptQualifiedName(AstNodeArgs args)
: base(args)
{
if (ChildNodes.Count == 2 && ChildNodes[1].ChildNodes.Count == 0)
{
Identifier = ((Token)ChildNodes[0]).Text;
evaluation = EvaluateIdentifier;
assignment = AssignIdentifier;
}
else
if (ChildNodes[0] is Token && ChildNodes[1].ChildNodes.Count != 0)
{
Identifier = (ChildNodes[0] as Token).Text;
//NOTE: There might be two cases:
// 1) a()[]...()
// 2) a<>.(NamePart)
Modifiers = new List<ScriptAst>();
foreach (ScriptAst node in ChildNodes[1].ChildNodes)
Modifiers.Add(node);
ScriptGenericsPostfix generic = Modifiers.FirstOrDefault() as ScriptGenericsPostfix;
if (generic != null && Modifiers.Count == 1)
{
//Case 2
evaluation = EvaluateGenericType;
assignment = null;
}
else
{
//Case 1
evaluation = EvaluateFunctionCall;
assignment = AssignArray;
}
}
else
{
NamePart = ChildNodes[0] as ScriptQualifiedName;
Identifier = ((Token)ChildNodes[2]).Text;
if (ChildNodes.Count == 4 && ChildNodes[3].ChildNodes.Count != 0)
{
Modifiers = new List<ScriptAst>();
foreach (ScriptAst node in ChildNodes[3].ChildNodes)
{
Modifiers.Add(node);
}
}
evaluation = EvaluateNamePart;
assignment = AssignNamePart;
}
}
#endregion
#region Public Methods
public override void Evaluate(IScriptContext context)
{
evaluation(context);
}
public void Assign(object value, IScriptContext context)
{
assignment(value, context);
}
#endregion
#region Identifier
private void EvaluateIdentifier(IScriptContext context)
{
object result = GetIndentifierValue(context, Identifier);
context.Result = result;
}
private static object GetIndentifierValue(IScriptContext context, string identifier)
{
object result = context.GetItem(identifier, false);
if (result != RuntimeHost.NoVariable) return result;
if (RuntimeHost.HasType(identifier))
return RuntimeHost.GetType(identifier);
else
return NameSpaceResolver.Get(identifier);
}
private void AssignIdentifier(object value, IScriptContext context)
{
context.SetItem(Identifier, value);
}
#endregion
#region Single Call
private void EvaluateGenericType(IScriptContext context)
{
ScriptGenericsPostfix genericPostfix = (ScriptGenericsPostfix)Modifiers.First();
Type genericType = GetIndentifierValue(context, genericPostfix.GetGenericTypeName(Identifier)) as Type;
if (genericType == null || !genericType.IsGenericType)
{
throw new ScriptException("Given type is not generic");
}
genericPostfix.Evaluate(context);
context.Result = genericType.MakeGenericType((Type[])context.Result);
}
private void EvaluateFunctionCall(IScriptContext context)
{
EvaluateIdentifier(context);
foreach (ScriptAst node in Modifiers)
{
ScriptFunctionCall funcCall = node as ScriptFunctionCall;
if (funcCall != null)
{
IInvokable function = context.Result as IInvokable;
if (function == null)
throw new ScriptException("Is not a function type");
context.Result = CallFunction(function, funcCall, context);
continue;
}
ScriptArrayResolution arrayResolution = node as ScriptArrayResolution;
if (arrayResolution != null)
{
GetArrayValue(context.Result, arrayResolution, context);
continue;
}
ScriptGenericsPostfix genericPostfix = node as ScriptGenericsPostfix;
if (genericPostfix != null)
{
throw new NotSupportedException();
//genericPostfix.Evaluate(Context);
//continue;
}
}
}
private void AssignArray(object value, IScriptContext context)
{
object obj = context.GetItem(Identifier, true);
foreach (ScriptAst node in Modifiers)
{
ScriptFunctionCall functionCall = node as ScriptFunctionCall;
if (functionCall != null)
{
obj = CallFunction(context.GetFunctionDefinition(Identifier), functionCall, context);
continue;
}
ScriptArrayResolution arrayResolution = node as ScriptArrayResolution;
if (arrayResolution != null)
{
SetArrayValue(obj, arrayResolution, context, value);
continue;
}
ScriptGenericsPostfix genericPostfix = node as ScriptGenericsPostfix;
if (genericPostfix != null)
{
throw new NotSupportedException();
}
}
}
private static void SetArrayValue(object obj, ScriptArrayResolution scriptArrayResolution, IScriptContext context, object value)
{
scriptArrayResolution.Evaluate(context);
object[] indexParameters = (object[])context.Result;
object[] setterParameters = new object[indexParameters.Length + 1];
indexParameters.CopyTo(setterParameters, 0);
setterParameters[indexParameters.Length] = value;
IObjectBind setter = RuntimeHost.Binder.BindToIndex(obj, setterParameters, true);
if (setter != null)
{
setter.Invoke(context, null);
return;
}
throw MethodNotFoundException("setter", indexParameters);
}
private static void GetArrayValue(object obj, ScriptArrayResolution scriptArrayResolution, IScriptContext context)
{
scriptArrayResolution.Evaluate(context);
object[] param = (object[])context.Result;
IObjectBind indexBind = RuntimeHost.Binder.BindToIndex(obj, param, false);
if (indexBind != null)
{
context.Result = indexBind.Invoke(context, null);
}
else
{
throw MethodNotFoundException("indexer[]", param);
}
}
#endregion
#region Name Part
private void EvaluateNamePart(IScriptContext context)
{
NamePart.Evaluate(context);
object obj = context.Result;
if (Modifiers == null)
{
context.Result = GetMemberValue(obj, Identifier);
return;
}
Type[] genericArguments = null;
foreach (ScriptAst node in Modifiers)
{
//NOTE: Generic modifier should be the first among other modifiers in the list
ScriptGenericsPostfix generic = node as ScriptGenericsPostfix;
if (generic != null)
{
if (genericArguments != null)
{
throw new ScriptException("Wrong modifiers sequence");
}
generic.Execute(context);
genericArguments = (Type[])context.Result;
continue;
}
ScriptFunctionCall functionCall = node as ScriptFunctionCall;
if (functionCall != null)
{
CallClassMethod(obj, Identifier, functionCall, genericArguments, context);
continue;
}
ScriptArrayResolution arrayResolution = node as ScriptArrayResolution;
if (arrayResolution != null)
{
GetArrayValue(GetMemberValue(obj, Identifier), arrayResolution, context);
continue;
}
}
}
private void AssignNamePart(object value, IScriptContext context)
{
NamePart.Evaluate(context);
object obj = context.Result;
if (Modifiers == null)
{
SetMember(context, obj, value);
return;
}
//TODO: Bug, first evaluate get member, see unit test AssignmentToArrayObject
string localIdentifier = Identifier;
foreach (ScriptAst node in Modifiers)
{
ScriptFunctionCall scriptFunctionCall = node as ScriptFunctionCall;
if (scriptFunctionCall != null)
{
if (localIdentifier != null)
{
CallClassMethod(obj, localIdentifier, scriptFunctionCall, null, context);
obj = context.Result;
localIdentifier = null;
}
else
{
IInvokable funcDef = obj as IInvokable;
if (funcDef == null) throw new ScriptException("Attempt to invoke non IInvokable object.");
obj = CallFunction(funcDef, scriptFunctionCall, context);
}
continue;
}
ScriptArrayResolution scriptArrayResolution = node as ScriptArrayResolution;
if (scriptArrayResolution != null)
{
if (localIdentifier != null)
{
obj = GetMemberValue(obj, localIdentifier);
localIdentifier = null;
}
SetArrayValue(obj, scriptArrayResolution, context, value);
continue;
}
}
}
#endregion
#region Call Function
private static object CallFunction(IInvokable functionDefinition, ScriptFunctionCall scriptFunctionCall, IScriptContext context)
{
scriptFunctionCall.Evaluate(context);
return functionDefinition.Invoke(context, (object[])context.Result);
}
private void CallClassMethod(object obj, string memeberInfo, ScriptFunctionCall scriptFunctionCall, Type[] genericArguments, IScriptContext context)
{
scriptFunctionCall.Evaluate(context);
context.Result = CallAppropriateMethod(context, obj, memeberInfo, genericArguments, (object[])context.Result);
}
private static object CallAppropriateMethod(IScriptContext context, object obj, string Name, Type[] genericArguments, object[] param)
{
IObjectBind methodBind = methodBind = RuntimeHost.Binder.BindToMethod(obj, Name, genericArguments, param);
if (methodBind != null)
return methodBind.Invoke(context, null);
throw MethodNotFoundException(Name, param);
}
#endregion
#region Helpers
private void SetMember(IScriptContext context, object obj, object value)
{
IMemberBind bind = RuntimeHost.Binder.BindToMember(obj, Identifier, true);
if (bind == null)
throw new ScriptIdNotFoundException(Identifier);
bind.SetValue(value);
context.Result = value;
//Context.Result = RuntimeHost.Binder.Set(Identifier, obj, value);
}
private static object GetMemberValue(object obj, string memberInfo)
{
IMemberBind bind = RuntimeHost.Binder.BindToMember(obj, memberInfo, true);
if (bind == null)
throw new ScriptIdNotFoundException(memberInfo);
return bind.GetValue();
//return RuntimeHost.Binder.Get(memberInfo, obj);
}
private static ScriptMethodNotFoundException MethodNotFoundException(string Name, object[] param)
{
string message = "";
foreach (object t in param)
{
if (t != null)
{
if (string.IsNullOrEmpty(message)) message += t.GetType().Name;
else message += ", " + t.GetType().Name;
}
}
return new ScriptMethodNotFoundException("Semantic: There is no method with such signature: " + Name + "(" + message + ")");
}
#endregion
}
}
|