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;
using System.Linq;
using System.Net;
using System.Net.Security;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace System.Data.SqlClient.SNI
{
/// <summary>
/// Managed SNI proxy implementation. Contains many SNI entry points used by SqlClient.
/// </summary>
internal class SNIProxy
{
private const int DefaultSqlServerPort = 1433;
private const int DefaultSqlServerDacPort = 1434;
private const string SqlServerSpnHeader = "MSSQLSvc";
internal class SspiClientContextResult
{
internal const uint OK = 0;
internal const uint Failed = 1;
internal const uint KerberosTicketMissing = 2;
}
public static readonly SNIProxy Singleton = new SNIProxy();
/// <summary>
/// Terminate SNI
/// </summary>
public void Terminate()
{
}
/// <summary>
/// Enable SSL on a connection
/// </summary>
/// <param name="handle">Connection handle</param>
/// <returns>SNI error code</returns>
public uint EnableSsl(SNIHandle handle, uint options)
{
try
{
return handle.EnableSsl(options);
}
catch (Exception e)
{
return SNICommon.ReportSNIError(SNIProviders.SSL_PROV, SNICommon.HandshakeFailureError, e);
}
}
/// <summary>
/// Disable SSL on a connection
/// </summary>
/// <param name="handle">Connection handle</param>
/// <returns>SNI error code</returns>
public uint DisableSsl(SNIHandle handle)
{
handle.DisableSsl();
return TdsEnums.SNI_SUCCESS;
}
/// <summary>
/// Generate SSPI context
/// </summary>
/// <param name="handle">SNI connection handle</param>
/// <param name="receivedBuff">Receive buffer</param>
/// <param name="receivedLength">Received length</param>
/// <param name="sendBuff">Send buffer</param>
/// <param name="sendLength">Send length</param>
/// <param name="serverName">Service Principal Name buffer</param>
/// <param name="serverNameLength">Length of Service Principal Name</param>
/// <returns>SNI error code</returns>
public void GenSspiClientContext(SspiClientContextStatus sspiClientContextStatus, byte[] receivedBuff, ref byte[] sendBuff, byte[] serverName)
{
SafeDeleteContext securityContext = sspiClientContextStatus.SecurityContext;
ContextFlagsPal contextFlags = sspiClientContextStatus.ContextFlags;
SafeFreeCredentials credentialsHandle = sspiClientContextStatus.CredentialsHandle;
string securityPackage = NegotiationInfoClass.Negotiate;
if (securityContext == null)
{
credentialsHandle = NegotiateStreamPal.AcquireDefaultCredential(securityPackage, false);
}
SecurityBuffer[] inSecurityBufferArray = null;
if (receivedBuff != null)
{
inSecurityBufferArray = new SecurityBuffer[] { new SecurityBuffer(receivedBuff, SecurityBufferType.SECBUFFER_TOKEN) };
}
else
{
inSecurityBufferArray = new SecurityBuffer[] { };
}
int tokenSize = NegotiateStreamPal.QueryMaxTokenSize(securityPackage);
SecurityBuffer outSecurityBuffer = new SecurityBuffer(tokenSize, SecurityBufferType.SECBUFFER_TOKEN);
ContextFlagsPal requestedContextFlags = ContextFlagsPal.Connection
| ContextFlagsPal.Confidentiality
| ContextFlagsPal.MutualAuth;
string serverSPN = System.Text.Encoding.UTF8.GetString(serverName);
SecurityStatusPal statusCode = NegotiateStreamPal.InitializeSecurityContext(
credentialsHandle,
ref securityContext,
serverSPN,
requestedContextFlags,
inSecurityBufferArray,
outSecurityBuffer,
ref contextFlags);
if (statusCode.ErrorCode == SecurityStatusPalErrorCode.CompleteNeeded ||
statusCode.ErrorCode == SecurityStatusPalErrorCode.CompAndContinue)
{
inSecurityBufferArray = new SecurityBuffer[] { outSecurityBuffer };
statusCode = NegotiateStreamPal.CompleteAuthToken(ref securityContext, inSecurityBufferArray);
outSecurityBuffer.token = null;
}
sendBuff = outSecurityBuffer.token;
if (sendBuff == null)
{
sendBuff = Array.Empty<byte>();
}
sspiClientContextStatus.SecurityContext = securityContext;
sspiClientContextStatus.ContextFlags = contextFlags;
sspiClientContextStatus.CredentialsHandle = credentialsHandle;
if (IsErrorStatus(statusCode.ErrorCode))
{
// Could not access Kerberos Ticket.
//
// SecurityStatusPalErrorCode.InternalError only occurs in Unix and always comes with a GssApiException,
// so we don't need to check for a GssApiException here.
if (statusCode.ErrorCode == SecurityStatusPalErrorCode.InternalError)
{
throw new Exception(SQLMessage.KerberosTicketMissingError() + "\n" + statusCode);
}
else
{
throw new Exception(SQLMessage.SSPIGenerateError() + "\n" + statusCode);
}
}
}
private static bool IsErrorStatus(SecurityStatusPalErrorCode errorCode)
{
return errorCode != SecurityStatusPalErrorCode.NotSet &&
errorCode != SecurityStatusPalErrorCode.OK &&
errorCode != SecurityStatusPalErrorCode.ContinueNeeded &&
errorCode != SecurityStatusPalErrorCode.CompleteNeeded &&
errorCode != SecurityStatusPalErrorCode.CompAndContinue &&
errorCode != SecurityStatusPalErrorCode.ContextExpired &&
errorCode != SecurityStatusPalErrorCode.CredentialsNeeded &&
errorCode != SecurityStatusPalErrorCode.Renegotiate;
}
/// <summary>
/// Initialize SSPI
/// </summary>
/// <param name="maxLength">Max length of SSPI packet</param>
/// <returns>SNI error code</returns>
public uint InitializeSspiPackage(ref uint maxLength)
{
throw new PlatformNotSupportedException();
}
/// <summary>
/// Set connection buffer size
/// </summary>
/// <param name="handle">SNI handle</param>
/// <param name="bufferSize">Buffer size</param>
/// <returns>SNI error code</returns>
public uint SetConnectionBufferSize(SNIHandle handle, uint bufferSize)
{
handle.SetBufferSize((int)bufferSize);
return TdsEnums.SNI_SUCCESS;
}
/// <summary>
/// Get packet data
/// </summary>
/// <param name="packet">SNI packet</param>
/// <param name="inBuff">Buffer</param>
/// <param name="dataSize">Data size</param>
/// <returns>SNI error status</returns>
public uint PacketGetData(SNIPacket packet, byte[] inBuff, ref uint dataSize)
{
int dataSizeInt = 0;
packet.GetData(inBuff, ref dataSizeInt);
dataSize = (uint)dataSizeInt;
return TdsEnums.SNI_SUCCESS;
}
/// <summary>
/// Read synchronously
/// </summary>
/// <param name="handle">SNI handle</param>
/// <param name="packet">SNI packet</param>
/// <param name="timeout">Timeout</param>
/// <returns>SNI error status</returns>
public uint ReadSyncOverAsync(SNIHandle handle, out SNIPacket packet, int timeout)
{
return handle.Receive(out packet, timeout);
}
/// <summary>
/// Get SNI connection ID
/// </summary>
/// <param name="handle">SNI handle</param>
/// <param name="clientConnectionId">Client connection ID</param>
/// <returns>SNI error status</returns>
public uint GetConnectionId(SNIHandle handle, ref Guid clientConnectionId)
{
clientConnectionId = handle.ConnectionId;
return TdsEnums.SNI_SUCCESS;
}
/// <summary>
/// Send a packet
/// </summary>
/// <param name="handle">SNI handle</param>
/// <param name="packet">SNI packet</param>
/// <param name="sync">true if synchronous, false if asynchronous</param>
/// <returns>SNI error status</returns>
public uint WritePacket(SNIHandle handle, SNIPacket packet, bool sync)
{
if (sync)
{
return handle.Send(packet.Clone());
}
else
{
return handle.SendAsync(packet.Clone());
}
}
/// <summary>
/// Create a SNI connection handle
/// </summary>
/// <param name="callbackObject">Asynchronous I/O callback object</param>
/// <param name="fullServerName">Full server name from connection string</param>
/// <param name="ignoreSniOpenTimeout">Ignore open timeout</param>
/// <param name="timerExpire">Timer expiration</param>
/// <param name="instanceName">Instance name</param>
/// <param name="spnBuffer">SPN</param>
/// <param name="flushCache">Flush packet cache</param>
/// <param name="async">Asynchronous connection</param>
/// <param name="parallel">Attempt parallel connects</param>
/// <returns>SNI handle</returns>
public SNIHandle CreateConnectionHandle(object callbackObject, string fullServerName, bool ignoreSniOpenTimeout, long timerExpire, out byte[] instanceName, ref byte[] spnBuffer, bool flushCache, bool async, bool parallel, bool isIntegratedSecurity)
{
instanceName = new byte[1];
bool errorWithLocalDBProcessing;
string localDBDataSource = GetLocalDBDataSource(fullServerName, out errorWithLocalDBProcessing);
if (errorWithLocalDBProcessing)
{
return null;
}
// If a localDB Data source is available, we need to use it.
fullServerName = localDBDataSource ?? fullServerName;
DataSource details = DataSource.ParseServerName(fullServerName);
if (details == null)
{
return null;
}
SNIHandle sniHandle = null;
switch (details.ConnectionProtocol)
{
case DataSource.Protocol.Admin:
case DataSource.Protocol.None: // default to using tcp if no protocol is provided
case DataSource.Protocol.TCP:
sniHandle = CreateTcpHandle(details, timerExpire, callbackObject, parallel);
break;
case DataSource.Protocol.NP:
sniHandle = CreateNpHandle(details, timerExpire, callbackObject, parallel);
break;
default:
Debug.Fail($"Unexpected connection protocol: {details.ConnectionProtocol}");
break;
}
if (isIntegratedSecurity)
{
try
{
spnBuffer = GetSqlServerSPN(details);
}
catch (Exception e)
{
SNILoadHandle.SingletonInstance.LastError = new SNIError(SNIProviders.INVALID_PROV, SNICommon.ErrorSpnLookup, e);
}
}
return sniHandle;
}
private static byte[] GetSqlServerSPN(DataSource dataSource)
{
Debug.Assert(!string.IsNullOrWhiteSpace(dataSource.ServerName));
string hostName = dataSource.ServerName;
string postfix = null;
if (dataSource.Port != -1)
{
postfix = dataSource.Port.ToString();
}
else if (!string.IsNullOrWhiteSpace(dataSource.InstanceName))
{
postfix = dataSource.InstanceName;
}
// For handling tcp:<hostname> format
else if (dataSource.ConnectionProtocol == DataSource.Protocol.TCP)
{
postfix = DefaultSqlServerPort.ToString();
}
return GetSqlServerSPN(hostName, postfix);
}
private static byte[] GetSqlServerSPN(string hostNameOrAddress, string portOrInstanceName)
{
Debug.Assert(!string.IsNullOrWhiteSpace(hostNameOrAddress));
IPHostEntry hostEntry = Dns.GetHostEntry(hostNameOrAddress);
string fullyQualifiedDomainName = hostEntry.HostName;
string serverSpn = SqlServerSpnHeader + "/" + fullyQualifiedDomainName;
if (!string.IsNullOrWhiteSpace(portOrInstanceName))
{
serverSpn += ":" + portOrInstanceName;
}
return Encoding.UTF8.GetBytes(serverSpn);
}
/// <summary>
/// Creates an SNITCPHandle object
/// </summary>
/// <param name="fullServerName">Server string. May contain a comma delimited port number.</param>
/// <param name="timerExpire">Timer expiration</param>
/// <param name="callbackObject">Asynchronous I/O callback object</param>
/// <param name="parallel">Should MultiSubnetFailover be used</param>
/// <returns>SNITCPHandle</returns>
private SNITCPHandle CreateTcpHandle(DataSource details, long timerExpire, object callbackObject, bool parallel)
{
// TCP Format:
// tcp:<host name>\<instance name>
// tcp:<host name>,<TCP/IP port number>
string hostName = details.ServerName;
if (string.IsNullOrWhiteSpace(hostName))
{
SNILoadHandle.SingletonInstance.LastError = new SNIError(SNIProviders.TCP_PROV, 0, SNICommon.InvalidConnStringError, string.Empty);
return null;
}
int port = -1;
bool isAdminConnection = details.ConnectionProtocol == DataSource.Protocol.Admin;
if (details.IsSsrpRequired)
{
try
{
port = isAdminConnection ?
SSRP.GetDacPortByInstanceName(hostName, details.InstanceName) :
SSRP.GetPortByInstanceName(hostName, details.InstanceName);
}
catch (SocketException se)
{
SNILoadHandle.SingletonInstance.LastError = new SNIError(SNIProviders.TCP_PROV, SNICommon.InvalidConnStringError, se);
return null;
}
}
else if (details.Port != -1)
{
port = details.Port;
}
else
{
port = isAdminConnection ? DefaultSqlServerDacPort : DefaultSqlServerPort;
}
return new SNITCPHandle(hostName, port, timerExpire, callbackObject, parallel);
}
/// <summary>
/// Creates an SNINpHandle object
/// </summary>
/// <param name="fullServerName">Server string representing a UNC pipe path.</param>
/// <param name="timerExpire">Timer expiration</param>
/// <param name="callbackObject">Asynchronous I/O callback object</param>
/// <param name="parallel">Should MultiSubnetFailover be used. Only returns an error for named pipes.</param>
/// <returns>SNINpHandle</returns>
private SNINpHandle CreateNpHandle(DataSource details, long timerExpire, object callbackObject, bool parallel)
{
if (parallel)
{
SNICommon.ReportSNIError(SNIProviders.NP_PROV, 0, SNICommon.MultiSubnetFailoverWithNonTcpProtocol, string.Empty);
return null;
}
return new SNINpHandle(details.PipeHostName, details.PipeName, timerExpire, callbackObject);
}
/// <summary>
/// Read packet asynchronously
/// </summary>
/// <param name="handle">SNI handle</param>
/// <param name="packet">Packet</param>
/// <returns>SNI error status</returns>
public uint ReadAsync(SNIHandle handle, out SNIPacket packet)
{
packet = new SNIPacket(null);
return handle.ReceiveAsync(ref packet);
}
/// <summary>
/// Set packet data
/// </summary>
/// <param name="packet">SNI packet</param>
/// <param name="data">Data</param>
/// <param name="length">Length</param>
public void PacketSetData(SNIPacket packet, byte[] data, int length)
{
packet.SetData(data, length);
}
/// <summary>
/// Release packet
/// </summary>
/// <param name="packet">SNI packet</param>
public void PacketRelease(SNIPacket packet)
{
packet.Release();
}
/// <summary>
/// Check SNI handle connection
/// </summary>
/// <param name="handle"></param>
/// <returns>SNI error status</returns>
public uint CheckConnection(SNIHandle handle)
{
return handle.CheckConnection();
}
/// <summary>
/// Get last SNI error on this thread
/// </summary>
/// <returns></returns>
public SNIError GetLastError()
{
return SNILoadHandle.SingletonInstance.LastError;
}
/// <summary>
/// Gets the Local db Named pipe data source if the input is a localDB server.
/// </summary>
/// <param name="fullServerName">The data source</param>
/// <param name="error">Set true when an error occurred while getting LocalDB up</param>
/// <returns></returns>
private string GetLocalDBDataSource(string fullServerName, out bool error)
{
string localDBConnectionString = null;
bool isBadLocalDBDataSource;
string localDBInstance = DataSource.GetLocalDBInstance(fullServerName, out isBadLocalDBDataSource);
if (isBadLocalDBDataSource)
{
error = true;
return null;
}
else if (!string.IsNullOrEmpty(localDBInstance))
{
// We have successfully received a localDBInstance which is valid.
Debug.Assert(!string.IsNullOrWhiteSpace(localDBInstance), "Local DB Instance name cannot be empty.");
localDBConnectionString = LocalDB.GetLocalDBConnectionString(localDBInstance);
if (fullServerName == null)
{
// The Last error is set in LocalDB.GetLocalDBConnectionString. We don't need to set Last here.
error = true;
return null;
}
}
error = false;
return localDBConnectionString;
}
}
internal class DataSource
{
private const char CommaSeparator = ',';
private const char BackSlashSeparator = '\\';
private const string DefaultHostName = "localhost";
private const string DefaultSqlServerInstanceName = "mssqlserver";
private const string PipeBeginning = @"\\";
private const string PipeToken = "pipe";
private const string LocalDbHost = "(localdb)";
private const string NamedPipeInstanceNameHeader = "mssql$";
private const string DefaultPipeName = "sql\\query";
internal enum Protocol { TCP, NP, None, Admin };
internal Protocol ConnectionProtocol = Protocol.None;
/// <summary>
/// Provides the HostName of the server to connect to for TCP protocol.
/// This information is also used for finding the SPN of SqlServer
/// </summary>
internal string ServerName { get; private set; }
/// <summary>
/// Provides the port on which the TCP connection should be made if one was specified in Data Source
/// </summary>
internal int Port { get; private set; } = -1;
/// <summary>
/// Provides the inferred Instance Name from Server Data Source
/// </summary>
public string InstanceName { get; internal set; }
/// <summary>
/// Provides the pipe name in case of Named Pipes
/// </summary>
public string PipeName { get; internal set; }
/// <summary>
/// Provides the HostName to connect to in case of Named pipes Data Source
/// </summary>
public string PipeHostName { get; internal set; }
private string _workingDataSource;
private string _dataSourceAfterTrimmingProtocol;
internal bool IsBadDataSource { get; private set; } = false;
internal bool IsSsrpRequired { get; private set; } = false;
private DataSource(string dataSource)
{
// Remove all whitespaces from the datasource and all operations will happen on lower case.
_workingDataSource = dataSource.Trim().ToLowerInvariant();
int firstIndexOfColon = _workingDataSource.IndexOf(':');
PopulateProtocol();
_dataSourceAfterTrimmingProtocol = (firstIndexOfColon > -1) && ConnectionProtocol != DataSource.Protocol.None
? _workingDataSource.Substring(firstIndexOfColon + 1).Trim() : _workingDataSource;
if (_dataSourceAfterTrimmingProtocol.Contains("/")) // Pipe paths only allow back slashes
{
if (ConnectionProtocol == DataSource.Protocol.None)
ReportSNIError(SNIProviders.INVALID_PROV);
else if (ConnectionProtocol == DataSource.Protocol.NP)
ReportSNIError(SNIProviders.NP_PROV);
else if (ConnectionProtocol == DataSource.Protocol.TCP)
ReportSNIError(SNIProviders.TCP_PROV);
}
}
private void PopulateProtocol()
{
string[] splitByColon = _workingDataSource.Split(':');
if (splitByColon.Length <= 1)
{
ConnectionProtocol = DataSource.Protocol.None;
}
else
{
// We trim before switching because " tcp : server , 1433 " is a valid data source
switch (splitByColon[0].Trim())
{
case TdsEnums.TCP:
ConnectionProtocol = DataSource.Protocol.TCP;
break;
case TdsEnums.NP:
ConnectionProtocol = DataSource.Protocol.NP;
break;
case TdsEnums.ADMIN:
ConnectionProtocol = DataSource.Protocol.Admin;
break;
default:
// None of the supported protocols were found. This may be a IPv6 address
ConnectionProtocol = DataSource.Protocol.None;
break;
}
}
}
public static string GetLocalDBInstance(string dataSource, out bool error)
{
string instanceName = null;
string workingDataSource = dataSource.ToLowerInvariant();
string[] tokensByBackSlash = workingDataSource.Split(BackSlashSeparator);
error = false;
// All LocalDb endpoints are of the format host\instancename where host is always (LocalDb) (case-insensitive)
if (tokensByBackSlash.Length == 2 && LocalDbHost.Equals(tokensByBackSlash[0].TrimStart()))
{
if (!string.IsNullOrWhiteSpace(tokensByBackSlash[1]))
{
instanceName = tokensByBackSlash[1].Trim();
}
else
{
SNILoadHandle.SingletonInstance.LastError = new SNIError(SNIProviders.INVALID_PROV, 0, SNICommon.LocalDBNoInstanceName, string.Empty);
error = true;
return null;
}
}
return instanceName;
}
public static DataSource ParseServerName(string dataSource)
{
DataSource details = new DataSource(dataSource);
if (details.IsBadDataSource)
{
return null;
}
if (details.InferNamedPipesInformation())
{
return details;
}
if (details.IsBadDataSource)
{
return null;
}
if (details.InferConnectionDetails())
{
return details;
}
return null;
}
private void InferLocalServerName()
{
// If Server name is empty or localhost, then use "localhost"
if (string.IsNullOrEmpty(ServerName) || IsLocalHost(ServerName))
{
ServerName = ConnectionProtocol == DataSource.Protocol.Admin ?
Environment.MachineName : DefaultHostName;
}
}
private bool InferConnectionDetails()
{
string[] tokensByCommaAndSlash = _dataSourceAfterTrimmingProtocol.Split(BackSlashSeparator, ',');
ServerName = tokensByCommaAndSlash[0].Trim();
int commaIndex = _dataSourceAfterTrimmingProtocol.IndexOf(',');
int backSlashIndex = _dataSourceAfterTrimmingProtocol.IndexOf(BackSlashSeparator);
// Check the parameters. The parameters are Comma separated in the Data Source. The parameter we really care about is the port
// If Comma exists, the try to get the port number
if (commaIndex > -1)
{
string parameter = backSlashIndex > -1
? ((commaIndex > backSlashIndex) ? tokensByCommaAndSlash[2].Trim() : tokensByCommaAndSlash[1].Trim())
: tokensByCommaAndSlash[1].Trim();
// Bad Data Source like "server, "
if (string.IsNullOrEmpty(parameter))
{
ReportSNIError(SNIProviders.INVALID_PROV);
return false;
}
// For Tcp and Only Tcp are parameters allowed.
if (ConnectionProtocol == DataSource.Protocol.None)
{
ConnectionProtocol = DataSource.Protocol.TCP;
}
else if (ConnectionProtocol != DataSource.Protocol.TCP)
{
// Parameter has been specified for non-TCP protocol. This is not allowed.
ReportSNIError(SNIProviders.INVALID_PROV);
return false;
}
int port;
if (!int.TryParse(parameter, out port))
{
ReportSNIError(SNIProviders.TCP_PROV);
return false;
}
// If the user explicitly specified a invalid port in the connection string.
if (port < 1)
{
ReportSNIError(SNIProviders.TCP_PROV);
return false;
}
Port = port;
}
// Instance Name Handling. Only if we found a '\' and we did not find a port in the Data Source
else if (backSlashIndex > -1)
{
// This means that there will not be any part separated by comma.
InstanceName = tokensByCommaAndSlash[1].Trim();
if (string.IsNullOrWhiteSpace(InstanceName))
{
ReportSNIError(SNIProviders.INVALID_PROV);
return false;
}
if (DefaultSqlServerInstanceName.Equals(InstanceName))
{
ReportSNIError(SNIProviders.INVALID_PROV);
return false;
}
IsSsrpRequired = true;
}
InferLocalServerName();
return true;
}
private void ReportSNIError(SNIProviders provider)
{
SNILoadHandle.SingletonInstance.LastError = new SNIError(provider, 0, SNICommon.InvalidConnStringError, string.Empty);
IsBadDataSource = true;
}
private bool InferNamedPipesInformation()
{
// If we have a datasource beginning with a pipe or we have already determined that the protocol is Named Pipe
if (_dataSourceAfterTrimmingProtocol.StartsWith(PipeBeginning) || ConnectionProtocol == Protocol.NP)
{
// If the data source is "np:servername"
if (!_dataSourceAfterTrimmingProtocol.Contains(BackSlashSeparator))
{
PipeHostName = ServerName = _dataSourceAfterTrimmingProtocol;
InferLocalServerName();
PipeName = SNINpHandle.DefaultPipePath;
return true;
}
try
{
string[] tokensByBackSlash = _dataSourceAfterTrimmingProtocol.Split(BackSlashSeparator);
// The datasource is of the format \\host\pipe\sql\query [0]\[1]\[2]\[3]\[4]\[5]
// It would at least have 6 parts.
// Another valid Sql named pipe for an named instance is \\.\pipe\MSSQL$MYINSTANCE\sql\query
if (tokensByBackSlash.Length < 6)
{
ReportSNIError(SNIProviders.NP_PROV);
return false;
}
string host = tokensByBackSlash[2];
if (string.IsNullOrEmpty(host))
{
ReportSNIError(SNIProviders.NP_PROV);
return false;
}
//Check if the "pipe" keyword is the first part of path
if (!PipeToken.Equals(tokensByBackSlash[3]))
{
ReportSNIError(SNIProviders.NP_PROV);
return false;
}
if (tokensByBackSlash[4].StartsWith(NamedPipeInstanceNameHeader))
{
InstanceName = tokensByBackSlash[4].Substring(NamedPipeInstanceNameHeader.Length);
}
StringBuilder pipeNameBuilder = new StringBuilder();
for (int i = 4; i < tokensByBackSlash.Length - 1; i++)
{
pipeNameBuilder.Append(tokensByBackSlash[i]);
pipeNameBuilder.Append(Path.DirectorySeparatorChar);
}
// Append the last part without a "/"
pipeNameBuilder.Append(tokensByBackSlash[tokensByBackSlash.Length - 1]);
PipeName = pipeNameBuilder.ToString();
if (string.IsNullOrWhiteSpace(InstanceName) && !DefaultPipeName.Equals(PipeName))
{
InstanceName = PipeToken + PipeName;
}
ServerName = IsLocalHost(host) ? Environment.MachineName : host;
// Pipe hostname is the hostname after leading \\ which should be passed down as is to open Named Pipe.
// For Named Pipes the ServerName makes sense for SPN creation only.
PipeHostName = host;
}
catch (UriFormatException)
{
ReportSNIError(SNIProviders.NP_PROV);
return false;
}
// DataSource is something like "\\pipename"
if (ConnectionProtocol == DataSource.Protocol.None)
{
ConnectionProtocol = DataSource.Protocol.NP;
}
else if (ConnectionProtocol != DataSource.Protocol.NP)
{
// In case the path began with a "\\" and protocol was not Named Pipes
ReportSNIError(SNIProviders.NP_PROV);
return false;
}
return true;
}
return false;
}
private static bool IsLocalHost(string serverName)
=> ".".Equals(serverName) || "(local)".Equals(serverName) || "localhost".Equals(serverName);
}
}
| |
// ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
/*============================================================
**
** Class: CriticalHandle
**
**
** A specially designed handle wrapper to ensure we never leak
** an OS handle. The runtime treats this class specially during
** P/Invoke marshaling and finalization. Users should write
** subclasses of CriticalHandle for each distinct handle type.
** This class is similar to SafeHandle, but lacks the ref counting
** behavior on marshaling that prevents handle recycling errors
** or security holes. This lowers the overhead of using the handle
** considerably, but leaves the onus on the caller to protect
** themselves from any recycling effects.
**
** **** NOTE ****
**
** Since there are no ref counts tracking handle usage there is
** no thread safety either. Your application must ensure that
** usages of the handle do not cross with attempts to close the
** handle (or tolerate such crossings). Normal GC mechanics will
** prevent finalization until the handle class isn't used any more,
** but explicit Close or Dispose operations may be initiated at any
** time.
**
** Similarly, multiple calls to Close or Dispose on different
** threads at the same time may cause the ReleaseHandle method to be
** called more than once.
**
** In general (and as might be inferred from the lack of handle
** recycle protection) you should be very cautious about exposing
** CriticalHandle instances directly or indirectly to untrusted users.
** At a minimum you should restrict their ability to queue multiple
** operations against a single handle at the same time or block their
** access to Close and Dispose unless you are very comfortable with the
** semantics of passing an invalid (or possibly invalidated and
** reallocated) to the unamanged routines you marshal your handle to
** (and the effects of closing such a handle while those calls are in
** progress). The runtime cannot protect you from undefined program
** behvior that might result from such scenarios. You have been warned.
**
**
===========================================================*/
using System;
using System.Reflection;
using System.Threading;
using System.Security.Permissions;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Runtime.ConstrainedExecution;
using System.IO;
/*
Problems addressed by the CriticalHandle class:
1) Critical finalization - ensure we never leak OS resources in SQL. Done
without running truly arbitrary & unbounded amounts of managed code.
2) Reduced graph promotion - during finalization, keep object graph small
3) GC.KeepAlive behavior - P/Invoke vs. finalizer thread ---- (HandleRef)
4) Enforcement of the above via the type system - Don't use IntPtr anymore.
Subclasses of CriticalHandle will implement the ReleaseHandle
abstract method used to execute any code required to free the
handle. This method will be prepared as a constrained execution
region at instance construction time (along with all the methods in
its statically determinable call graph). This implies that we won't
get any inconvenient jit allocation errors or rude thread abort
interrupts while releasing the handle but the user must still write
careful code to avoid injecting fault paths of their own (see the
CER spec for more details). In particular, any sub-methods you call
should be decorated with a reliability contract of the appropriate
level. In most cases this should be:
ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)
Also, any P/Invoke methods should use the
SuppressUnmanagedCodeSecurity attribute to avoid a runtime security
check that can also inject failures (even if the check is guaranteed
to pass).
Subclasses must also implement the IsInvalid property so that the
infrastructure can tell when critical finalization is actually required.
Again, this method is prepared ahead of time. It's envisioned that direct
subclasses of CriticalHandle will provide an IsInvalid implementation that suits
the general type of handle they support (null is invalid, -1 is invalid etc.)
and then these classes will be further derived for specific handle types.
Most classes using CriticalHandle should not provide a finalizer. If they do
need to do so (ie, for flushing out file buffers, needing to write some data
back into memory, etc), then they can provide a finalizer that will be
guaranteed to run before the CriticalHandle's critical finalizer.
Subclasses are expected to be written as follows (note that
SuppressUnmanagedCodeSecurity should always be used on any P/Invoke methods
invoked as part of ReleaseHandle, in order to switch the security check from
runtime to jit time and thus remove a possible failure path from the
invocation of the method):
internal sealed MyCriticalHandleSubclass : CriticalHandle {
// Called by P/Invoke when returning CriticalHandles
private MyCriticalHandleSubclass() : base(IntPtr.Zero)
{
}
// Do not provide a finalizer - CriticalHandle's critical finalizer will
// call ReleaseHandle for you.
public override bool IsInvalid {
get { return handle == IntPtr.Zero; }
}
[DllImport(Win32Native.KERNEL32), SuppressUnmanagedCodeSecurity, ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
private static extern bool CloseHandle(IntPtr handle);
override protected bool ReleaseHandle()
{
return CloseHandle(handle);
}
}
Then elsewhere to create one of these CriticalHandles, define a method
with the following type of signature (CreateFile follows this model).
Note that when returning a CriticalHandle like this, P/Invoke will call your
classes default constructor.
[DllImport(Win32Native.KERNEL32)]
private static extern MyCriticalHandleSubclass CreateHandle(int someState);
*/
namespace System.Runtime.InteropServices
{
// This class should not be serializable - it's a handle. We require unmanaged
// code permission to subclass CriticalHandle to prevent people from writing a
// subclass and suddenly being able to run arbitrary native code with the
// same signature as CloseHandle. This is technically a little redundant, but
// we'll do this to ensure we've cut off all attack vectors. Similarly, all
// methods have a link demand to ensure untrusted code cannot directly edit
// or alter a handle.
[System.Security.SecurityCritical] // auto-generated_required
#if !FEATURE_CORECLR
[SecurityPermission(SecurityAction.InheritanceDemand, UnmanagedCode=true)]
#endif
public abstract class CriticalHandle : CriticalFinalizerObject, IDisposable
{
// ! Do not add or rearrange fields as the EE depends on this layout.
//------------------------------------------------------------------
#if DEBUG
private String _stackTrace; // Where we allocated this CriticalHandle.
#endif
#if !FEATURE_CORECLR
[System.Runtime.ForceTokenStabilization]
#endif //!FEATURE_CORECLR
protected IntPtr handle; // This must be protected so derived classes can use out params.
private bool _isClosed; // Set by SetHandleAsInvalid or Close/Dispose/finalization.
// Creates a CriticalHandle class. Users must then set the Handle property or allow P/Invoke marshaling to set it implicitly.
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
protected CriticalHandle(IntPtr invalidHandleValue)
{
handle = invalidHandleValue;
_isClosed = false;
#if DEBUG
if (BCLDebug.SafeHandleStackTracesEnabled)
_stackTrace = Environment.GetStackTrace(null, false);
else
_stackTrace = "For a stack trace showing who allocated this CriticalHandle, set SafeHandleStackTraces to 1 and rerun your app.";
#endif
}
#if FEATURE_CORECLR
// Adding an empty default constructor for annotation purposes
private CriticalHandle(){}
#endif
[System.Security.SecuritySafeCritical] // auto-generated
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
~CriticalHandle()
{
Dispose(false);
}
[System.Security.SecurityCritical] // auto-generated
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
private void Cleanup()
{
if (IsClosed)
return;
_isClosed = true;
if (IsInvalid)
return;
// Save last error from P/Invoke in case the implementation of
// ReleaseHandle trashes it (important because this ReleaseHandle could
// occur implicitly as part of unmarshaling another P/Invoke).
int lastError = Marshal.GetLastWin32Error();
if (!ReleaseHandle())
FireCustomerDebugProbe();
Marshal.SetLastWin32Error(lastError);
GC.SuppressFinalize(this);
}
[ResourceExposure(ResourceScope.None)]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
private extern void FireCustomerDebugProbe();
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
protected void SetHandle(IntPtr handle) {
this.handle = handle;
}
// Returns whether the handle has been explicitly marked as closed
// (Close/Dispose) or invalid (SetHandleAsInvalid).
public bool IsClosed {
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
get { return _isClosed; }
}
// Returns whether the handle looks like an invalid value (i.e. matches one
// of the handle's designated illegal values). CriticalHandle itself doesn't
// know what an invalid handle looks like, so this method is abstract and
// must be provided by a derived type.
public abstract bool IsInvalid {
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
get;
}
[System.Security.SecurityCritical] // auto-generated
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
public void Close() {
Dispose(true);
}
[System.Security.SecuritySafeCritical] // auto-generated
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
public void Dispose()
{
Dispose(true);
}
[System.Security.SecurityCritical] // auto-generated
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
protected virtual void Dispose(bool disposing)
{
Cleanup();
}
// This should only be called for cases when you know for a fact that
// your handle is invalid and you want to record that information.
// An example is calling a syscall and getting back ERROR_INVALID_HANDLE.
// This method will normally leak handles!
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
public void SetHandleAsInvalid()
{
_isClosed = true;
GC.SuppressFinalize(this);
}
// Implement this abstract method in your derived class to specify how to
// free the handle. Be careful not write any code that's subject to faults
// in this method (the runtime will prepare the infrastructure for you so
// that no jit allocations etc. will occur, but don't allocate memory unless
// you can deal with the failure and still free the handle).
// The boolean returned should be true for success and false if a
// catastrophic error occured and you wish to trigger a diagnostic for
// debugging purposes (the SafeHandleCriticalFailure MDA).
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
protected abstract bool ReleaseHandle();
}
}
| |
namespace Nancy.Tests.Unit.ModelBinding
{
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Globalization;
using System.Xml.Serialization;
using FakeItEasy;
using Fakes;
using Nancy.IO;
using Nancy.Json;
using Nancy.ModelBinding;
using Nancy.ModelBinding.DefaultBodyDeserializers;
using Nancy.ModelBinding.DefaultConverters;
using Nancy.Tests.Unit.ModelBinding.DefaultBodyDeserializers;
using Xunit.Extensions;
using Xunit;
public class DefaultBinderFixture
{
private readonly IFieldNameConverter passthroughNameConverter;
private readonly BindingDefaults emptyDefaults;
private readonly JavaScriptSerializer serializer;
private readonly BindingContext defaultBindingContext;
public DefaultBinderFixture()
{
this.defaultBindingContext = new BindingContext();
this.passthroughNameConverter = A.Fake<IFieldNameConverter>();
A.CallTo(() => this.passthroughNameConverter.Convert(null)).WithAnyArguments()
.ReturnsLazily(f => (string)f.Arguments[0]);
this.emptyDefaults = A.Fake<BindingDefaults>();
A.CallTo(() => this.emptyDefaults.DefaultBodyDeserializers).Returns(new IBodyDeserializer[] { });
A.CallTo(() => this.emptyDefaults.DefaultTypeConverters).Returns(new ITypeConverter[] { });
this.serializer = new JavaScriptSerializer();
this.serializer.RegisterConverters(JsonSettings.Converters);
}
[Fact]
public void Should_throw_if_type_converters_is_null()
{
// Given, When
var result = Record.Exception(() => new DefaultBinder(null, new IBodyDeserializer[] { }, A.Fake<IFieldNameConverter>(), new BindingDefaults()));
// Then
result.ShouldBeOfType(typeof(ArgumentNullException));
}
[Fact]
public void Should_throw_if_body_deserializers_is_null()
{
// Given, When
var result = Record.Exception(() => new DefaultBinder(new ITypeConverter[] { }, null, A.Fake<IFieldNameConverter>(), new BindingDefaults()));
// Then
result.ShouldBeOfType(typeof(ArgumentNullException));
}
[Fact]
public void Should_throw_if_body_deserializer_fails_and_IgnoreErrors_is_false()
{
// Given
var deserializer = new ThrowingBodyDeserializer<FormatException>();
var binder = this.GetBinder(bodyDeserializers: new[] { deserializer });
var context = CreateContextWithHeader("Content-Type", new[] { "application/xml" });
var config = new BindingConfig { IgnoreErrors = false };
// When
var result = Record.Exception(() => binder.Bind(context, this.GetType(), null, config));
// Then
result.ShouldBeOfType<ModelBindingException>();
result.InnerException.ShouldBeOfType<FormatException>();
}
[Fact]
public void Should_not_throw_if_body_deserializer_fails_and_IgnoreErrors_is_true()
{
// Given
var deserializer = new ThrowingBodyDeserializer<FormatException>();
var binder = this.GetBinder(bodyDeserializers: new[] { deserializer });
var context = CreateContextWithHeader("Content-Type", new[] { "application/xml" });
var config = new BindingConfig { IgnoreErrors = true };
// When, Then
Assert.DoesNotThrow(() => binder.Bind(context, this.GetType(), null, config));
}
[Fact]
public void Should_throw_if_field_name_converter_is_null()
{
// Given, When
var result = Record.Exception(() => new DefaultBinder(new ITypeConverter[] { }, new IBodyDeserializer[] { }, null, new BindingDefaults()));
// Then
result.ShouldBeOfType(typeof(ArgumentNullException));
}
[Fact]
public void Should_throw_if_defaults_is_null()
{
// Given, When
var result = Record.Exception(() => new DefaultBinder(new ITypeConverter[] { }, new IBodyDeserializer[] { }, A.Fake<IFieldNameConverter>(), null));
// Then
result.ShouldBeOfType(typeof(ArgumentNullException));
}
[Fact]
public void Should_call_body_deserializer_if_one_matches()
{
// Given
var deserializer = A.Fake<IBodyDeserializer>();
A.CallTo(() => deserializer.CanDeserialize(null, A<BindingContext>._)).WithAnyArguments().Returns(true);
var binder = this.GetBinder(bodyDeserializers: new[] { deserializer });
var context = CreateContextWithHeader("Content-Type", new[] { "application/xml" });
// When
binder.Bind(context, this.GetType(), null, BindingConfig.Default);
// Then
A.CallTo(() => deserializer.Deserialize(null, null, null)).WithAnyArguments()
.MustHaveHappened(Repeated.Exactly.Once);
}
[Fact]
public void Should_not_call_body_deserializer_if_doesnt_match()
{
// Given
var deserializer = A.Fake<IBodyDeserializer>();
A.CallTo(() => deserializer.CanDeserialize(null, A<BindingContext>._)).WithAnyArguments().Returns(false);
var binder = this.GetBinder(bodyDeserializers: new[] { deserializer });
var context = CreateContextWithHeader("Content-Type", new[] { "application/xml" });
// When
binder.Bind(context, this.GetType(), null, BindingConfig.Default);
// Then
A.CallTo(() => deserializer.Deserialize(null, null, null)).WithAnyArguments()
.MustNotHaveHappened();
}
[Fact]
public void Should_pass_request_content_type_to_can_deserialize()
{
// Then
var deserializer = A.Fake<IBodyDeserializer>();
var binder = this.GetBinder(bodyDeserializers: new[] { deserializer });
var context = CreateContextWithHeader("Content-Type", new[] { "application/xml" });
// When
binder.Bind(context, this.GetType(), null, BindingConfig.Default);
// Then
A.CallTo(() => deserializer.CanDeserialize("application/xml", A<BindingContext>._))
.MustHaveHappened(Repeated.Exactly.Once);
}
[Fact]
public void Should_pass_binding_context_to_can_deserialize()
{
// Then
var deserializer = A.Fake<IBodyDeserializer>();
var binder = this.GetBinder(bodyDeserializers: new[] { deserializer });
var context = CreateContextWithHeader("Content-Type", new[] { "application/xml" });
// When
binder.Bind(context, this.GetType(), null, BindingConfig.Default);
// Then
A.CallTo(() => deserializer.CanDeserialize("application/xml", A<BindingContext>.That.Not.IsNull()))
.MustHaveHappened(Repeated.Exactly.Once);
}
[Fact]
public void Should_use_object_from_deserializer_if_one_returned()
{
// Given
var modelObject = new TestModel { StringProperty = "Hello!" };
var deserializer = A.Fake<IBodyDeserializer>();
A.CallTo(() => deserializer.CanDeserialize(null, A<BindingContext>._)).WithAnyArguments().Returns(true);
A.CallTo(() => deserializer.Deserialize(null, null, null)).WithAnyArguments().Returns(modelObject);
var binder = this.GetBinder(bodyDeserializers: new[] { deserializer });
var context = CreateContextWithHeader("Content-Type", new[] { "application/xml" });
// When
var result = binder.Bind(context, typeof(TestModel), null, BindingConfig.Default);
// Then
result.ShouldBeOfType<TestModel>();
((TestModel)result).StringProperty.ShouldEqual("Hello!");
}
[Fact]
public void Should_use_object_from_deserializer_if_one_returned_and_overwrite_when_allowed()
{
// Given
var modelObject = new TestModel { StringPropertyWithDefaultValue = "Hello!" };
var deserializer = A.Fake<IBodyDeserializer>();
A.CallTo(() => deserializer.CanDeserialize(null, A<BindingContext>._)).WithAnyArguments().Returns(true);
A.CallTo(() => deserializer.Deserialize(null, null, null)).WithAnyArguments().Returns(modelObject);
var binder = this.GetBinder(bodyDeserializers: new[] { deserializer });
var context = CreateContextWithHeader("Content-Type", new[] { "application/xml" });
// When
var result = binder.Bind(context, typeof(TestModel), null, BindingConfig.Default);
// Then
result.ShouldBeOfType<TestModel>();
((TestModel)result).StringPropertyWithDefaultValue.ShouldEqual("Hello!");
}
[Fact]
public void Should_use_object_from_deserializer_if_one_returned_and_not_overwrite_when_not_allowed()
{
// Given
var modelObject =
new TestModel()
{
StringPropertyWithDefaultValue = "Hello!",
StringFieldWithDefaultValue = "World!",
};
var deserializer = A.Fake<IBodyDeserializer>();
A.CallTo(() => deserializer.CanDeserialize(null, A<BindingContext>._)).WithAnyArguments().Returns(true);
A.CallTo(() => deserializer.Deserialize(null, null, null)).WithAnyArguments().Returns(modelObject);
var binder = this.GetBinder(bodyDeserializers: new[] { deserializer });
var context = CreateContextWithHeader("Content-Type", new[] { "application/xml" });
// When
var result = binder.Bind(context, typeof(TestModel), null, BindingConfig.NoOverwrite);
// Then
result.ShouldBeOfType<TestModel>();
((TestModel)result).StringPropertyWithDefaultValue.ShouldEqual("Default Property Value");
((TestModel)result).StringFieldWithDefaultValue.ShouldEqual("Default Field Value");
}
[Fact]
public void Should_see_if_a_type_converter_is_available_for_each_property_on_the_model_where_incoming_value_exists()
{
// Given
var typeConverter = A.Fake<ITypeConverter>();
A.CallTo(() => typeConverter.CanConvertTo(null, null)).WithAnyArguments().Returns(false);
var binder = this.GetBinder(typeConverters: new[] { typeConverter });
var context = new NancyContext { Request = new FakeRequest("GET", "/") };
context.Request.Form["StringProperty"] = "Test";
context.Request.Form["IntProperty"] = "12";
// When
binder.Bind(context, typeof(TestModel), null, BindingConfig.Default);
// Then
A.CallTo(() => typeConverter.CanConvertTo(null, null)).WithAnyArguments()
.MustHaveHappened(Repeated.Exactly.Times(2));
}
[Fact]
public void Should_call_convert_on_type_converter_if_available()
{
// Given
var typeConverter = A.Fake<ITypeConverter>();
A.CallTo(() => typeConverter.CanConvertTo(typeof(string), null)).WithAnyArguments().Returns(true);
A.CallTo(() => typeConverter.Convert(null, null, null)).WithAnyArguments().Returns(null);
var binder = this.GetBinder(typeConverters: new[] { typeConverter });
var context = new NancyContext { Request = new FakeRequest("GET", "/") };
context.Request.Form["StringProperty"] = "Test";
// When
binder.Bind(context, typeof(TestModel), null, BindingConfig.Default);
// Then
A.CallTo(() => typeConverter.Convert(null, null, null)).WithAnyArguments()
.MustHaveHappened(Repeated.Exactly.Once);
}
[Fact]
public void Should_ignore_properties_that_cannot_be_converted()
{
// Given
var binder = this.GetBinder(typeConverters: new[] { new FallbackConverter() });
var context = new NancyContext { Request = new FakeRequest("GET", "/") };
context.Request.Form["StringProperty"] = "Test";
context.Request.Form["IntProperty"] = "12";
context.Request.Form["DateProperty"] = "Broken";
// When
var result = (TestModel)binder.Bind(context, typeof(TestModel), null, BindingConfig.Default);
// Then
result.StringProperty.ShouldEqual("Test");
result.IntProperty.ShouldEqual(12);
result.DateProperty.ShouldEqual(default(DateTime));
}
[Fact]
public void Should_throw_ModelBindingException_if_convertion_of_a_property_fails()
{
// Given
var binder = this.GetBinder(typeConverters: new[] { new FallbackConverter() });
var context = new NancyContext { Request = new FakeRequest("GET", "/") };
context.Request.Form["IntProperty"] = "badint";
context.Request.Form["AnotherIntProperty"] = "morebad";
// Then
Type modelType = typeof(TestModel);
Assert.Throws<ModelBindingException>(() => binder.Bind(context, modelType, null, BindingConfig.Default))
.ShouldMatch(exception =>
exception.BoundType == modelType
&& exception.PropertyBindingExceptions.Any(pe =>
pe.PropertyName == "IntProperty"
&& pe.AttemptedValue == "badint")
&& exception.PropertyBindingExceptions.Any(pe =>
pe.PropertyName == "AnotherIntProperty"
&& pe.AttemptedValue == "morebad")
&& exception.PropertyBindingExceptions.All(pe =>
pe.InnerException.Message.Contains(pe.AttemptedValue)
&& pe.InnerException.Message.Contains(modelType.GetProperty(pe.PropertyName).PropertyType.Name)));
}
[Fact]
public void Should_not_throw_ModelBindingException_if_convertion_of_property_fails_and_ignore_error_is_true()
{
// Given
var binder = this.GetBinder(typeConverters: new[] { new FallbackConverter() });
var context = new NancyContext { Request = new FakeRequest("GET", "/") };
context.Request.Form["IntProperty"] = "badint";
context.Request.Form["AnotherIntProperty"] = "morebad";
var config = new BindingConfig {IgnoreErrors = true};
// When
// Then
Assert.DoesNotThrow(() => binder.Bind(context, typeof(TestModel), null, config));
}
[Fact]
public void Should_set_remaining_properties_when_one_fails_and_ignore_error_is_enabled()
{
// Given
var binder = this.GetBinder(typeConverters: new[] { new FallbackConverter() });
var context = new NancyContext { Request = new FakeRequest("GET", "/") };
context.Request.Form["IntProperty"] = "badint";
context.Request.Form["AnotherIntProperty"] = 10;
var config = new BindingConfig { IgnoreErrors = true };
// When
var model = binder.Bind(context, typeof(TestModel), null, config) as TestModel;
// Then
model.AnotherIntProperty.ShouldEqual(10);
}
[Fact]
public void Should_ignore_indexer_properties()
{
// Given
var binder = this.GetBinder(typeConverters: new[] { new FallbackConverter() });
var context = CreateContextWithHeader("Content-Type", new[] { "application/xml" });
var validProperties = 0;
var deserializer = A.Fake<IBodyDeserializer>();
A.CallTo(() => deserializer.CanDeserialize(A<string>.Ignored, A<BindingContext>._)).Returns(true);
A.CallTo(() => deserializer.Deserialize(A<string>.Ignored, A<Stream>.Ignored, A<BindingContext>.Ignored))
.Invokes(f =>
{
validProperties = f.Arguments.Get<BindingContext>(2).ValidModelBindingMembers.Count();
})
.Returns(new TestModel());
A.CallTo(() => this.emptyDefaults.DefaultBodyDeserializers).Returns(new[] { deserializer });
// When
binder.Bind(context, typeof(TestModel), null, BindingConfig.Default);
// Then
validProperties.ShouldEqual(22);
}
[Fact]
public void Should_pass_binding_context_to_default_deserializer()
{
// Given
var deserializer = A.Fake<IBodyDeserializer>();
var binder = this.GetBinder();
var context = CreateContextWithHeader("Content-Type", new[] { "application/xml" });
A.CallTo(() => this.emptyDefaults.DefaultBodyDeserializers).Returns(new[] { deserializer });
// When
binder.Bind(context, this.GetType(), null, BindingConfig.Default);
// Then
A.CallTo(() => deserializer.CanDeserialize("application/xml", A<BindingContext>.That.Not.IsNull()))
.MustHaveHappened(Repeated.Exactly.Once);
}
[Fact]
public void Should_use_field_name_converter_for_each_field()
{
// Given
var binder = this.GetBinder();
var context = new NancyContext { Request = new FakeRequest("GET", "/") };
context.Request.Form["StringProperty"] = "Test";
context.Request.Form["IntProperty"] = "12";
// When
binder.Bind(context, typeof(TestModel), null, BindingConfig.Default);
// Then
A.CallTo(() => this.passthroughNameConverter.Convert(null)).WithAnyArguments()
.MustHaveHappened(Repeated.Exactly.Times(2));
}
[Fact]
public void Should_not_bind_anything_on_blacklist()
{
// Given
var binder = this.GetBinder(typeConverters: new[] { new FallbackConverter() });
var context = new NancyContext { Request = new FakeRequest("GET", "/") };
context.Request.Form["StringProperty"] = "Test";
context.Request.Form["IntProperty"] = "12";
// When
var result = (TestModel)binder.Bind(context, typeof(TestModel), null, BindingConfig.Default, "IntProperty");
// Then
result.StringProperty.ShouldEqual("Test");
result.IntProperty.ShouldEqual(0);
}
[Fact]
public void Should_not_bind_anything_on_blacklist_when_the_blacklist_is_specified_by_expressions()
{
// Given
var binder = this.GetBinder(typeConverters: new[] { new FallbackConverter() });
var context = new NancyContext { Request = new FakeRequest("GET", "/") };
context.Request.Form["StringProperty"] = "Test";
context.Request.Form["IntProperty"] = "12";
var fakeModule = A.Fake<INancyModule>();
var fakeModelBinderLocator = A.Fake<IModelBinderLocator>();
A.CallTo(() => fakeModule.Context).Returns(context);
A.CallTo(() => fakeModule.ModelBinderLocator).Returns(fakeModelBinderLocator);
A.CallTo(() => fakeModelBinderLocator.GetBinderForType(typeof (TestModel), context)).Returns(binder);
// When
var result = fakeModule.Bind<TestModel>(tm => tm.IntProperty);
// Then
result.StringProperty.ShouldEqual("Test");
result.IntProperty.ShouldEqual(0);
}
[Fact]
public void Should_use_default_body_deserializer_if_one_found()
{
// Given
var deserializer = A.Fake<IBodyDeserializer>();
A.CallTo(() => deserializer.CanDeserialize(null, A<BindingContext>._)).WithAnyArguments().Returns(true);
A.CallTo(() => this.emptyDefaults.DefaultBodyDeserializers).Returns(new[] { deserializer });
var binder = this.GetBinder();
var context = CreateContextWithHeader("Content-Type", new[] { "application/xml" });
// When
binder.Bind(context, this.GetType(), null, BindingConfig.Default);
// Then
A.CallTo(() => deserializer.Deserialize(null, null, null)).WithAnyArguments()
.MustHaveHappened(Repeated.Exactly.Once);
}
[Fact]
public void Should_use_default_type_converter_if_one_found()
{
// Given
var typeConverter = A.Fake<ITypeConverter>();
A.CallTo(() => typeConverter.CanConvertTo(typeof(string), null)).WithAnyArguments().Returns(true);
A.CallTo(() => typeConverter.Convert(null, null, null)).WithAnyArguments().Returns(null);
A.CallTo(() => this.emptyDefaults.DefaultTypeConverters).Returns(new[] { typeConverter });
var binder = this.GetBinder(new ITypeConverter[] { });
var context = new NancyContext { Request = new FakeRequest("GET", "/") };
context.Request.Form["StringProperty"] = "Test";
// When
binder.Bind(context, typeof(TestModel), null, BindingConfig.Default);
// Then
A.CallTo(() => typeConverter.Convert(null, null, null)).WithAnyArguments()
.MustHaveHappened(Repeated.Exactly.Once);
}
[Fact]
public void User_body_serializer_should_take_precedence_over_default_one()
{
// Given
var userDeserializer = A.Fake<IBodyDeserializer>();
A.CallTo(() => userDeserializer.CanDeserialize(null, A<BindingContext>._)).WithAnyArguments().Returns(true);
var defaultDeserializer = A.Fake<IBodyDeserializer>();
A.CallTo(() => defaultDeserializer.CanDeserialize(null, A<BindingContext>._)).WithAnyArguments().Returns(true);
A.CallTo(() => this.emptyDefaults.DefaultBodyDeserializers).Returns(new[] { defaultDeserializer });
var binder = this.GetBinder(bodyDeserializers: new[] { userDeserializer });
var context = CreateContextWithHeader("Content-Type", new[] { "application/xml" });
// When
binder.Bind(context, this.GetType(), null, BindingConfig.Default);
// Then
A.CallTo(() => userDeserializer.Deserialize(null, null, null)).WithAnyArguments()
.MustHaveHappened(Repeated.Exactly.Once);
A.CallTo(() => defaultDeserializer.Deserialize(null, null, null)).WithAnyArguments()
.MustNotHaveHappened();
}
[Fact]
public void User_type_converter_should_take_precedence_over_default_one()
{
// Given
var userTypeConverter = A.Fake<ITypeConverter>();
A.CallTo(() => userTypeConverter.CanConvertTo(typeof(string), null)).WithAnyArguments().Returns(true);
A.CallTo(() => userTypeConverter.Convert(null, null, null)).WithAnyArguments().Returns(null);
var defaultTypeConverter = A.Fake<ITypeConverter>();
A.CallTo(() => defaultTypeConverter.CanConvertTo(typeof(string), null)).WithAnyArguments().Returns(true);
A.CallTo(() => defaultTypeConverter.Convert(null, null, null)).WithAnyArguments().Returns(null);
A.CallTo(() => this.emptyDefaults.DefaultTypeConverters).Returns(new[] { defaultTypeConverter });
var binder = this.GetBinder(new[] { userTypeConverter });
var context = new NancyContext { Request = new FakeRequest("GET", "/") };
context.Request.Form["StringProperty"] = "Test";
// When
binder.Bind(context, typeof(TestModel), null, BindingConfig.Default);
// Then
A.CallTo(() => userTypeConverter.Convert(null, null, null)).WithAnyArguments()
.MustHaveHappened(Repeated.Exactly.Once);
A.CallTo(() => defaultTypeConverter.Convert(null, null, null)).WithAnyArguments()
.MustNotHaveHappened();
}
[Fact]
public void Should_bind_model_from_request()
{
// Given
var binder = this.GetBinder();
var context = CreateContextWithHeader("Content-Type", new[] { "application/xml" });
context.Request.Query["StringProperty"] = "Test";
context.Request.Query["IntProperty"] = "3";
// When
var result = (TestModel)binder.Bind(context, typeof(TestModel), null, BindingConfig.Default);
// Then
result.StringProperty.ShouldEqual("Test");
result.IntProperty.ShouldEqual(3);
}
[Fact]
public void Should_bind_model_from_context_parameters()
{
// Given
var binder = this.GetBinder();
var context = CreateContextWithHeader("Content-Type", new[] { "application/xml" });
context.Parameters["StringProperty"] = "Test";
context.Parameters["IntProperty"] = "3";
// When
var result = (TestModel)binder.Bind(context, typeof(TestModel), null, BindingConfig.Default);
// Then
result.StringProperty.ShouldEqual("Test");
result.IntProperty.ShouldEqual(3);
}
[Fact]
public void Form_properties_should_take_precendence_over_request_properties()
{
// Given
var binder = this.GetBinder();
var context = CreateContextWithHeader("Content-Type", new[] { "application/xml" });
context.Request.Form["StringProperty"] = "Test";
context.Request.Form["IntProperty"] = "3";
context.Request.Query["StringProperty"] = "Test2";
context.Request.Query["IntProperty"] = "1";
// When
var result = (TestModel)binder.Bind(context, typeof(TestModel), null, BindingConfig.Default);
// Then
result.StringProperty.ShouldEqual("Test");
result.IntProperty.ShouldEqual(3);
}
[Fact]
public void Should_bind_multiple_Form_properties_to_list()
{
//Given
var typeConverters = new ITypeConverter[] { new CollectionConverter(), new FallbackConverter() };
var binder = this.GetBinder(typeConverters);
var context = CreateContextWithHeader("Content-Type", new[] { "application/x-www-form-urlencoded" });
context.Request.Form["StringProperty_0"] = "Test";
context.Request.Form["IntProperty_0"] = "1";
context.Request.Form["StringProperty_1"] = "Test2";
context.Request.Form["IntProperty_1"] = "2";
// When
var result = (List<TestModel>)binder.Bind(context, typeof(List<TestModel>), null, BindingConfig.Default);
// Then
result.First().StringProperty.ShouldEqual("Test");
result.First().IntProperty.ShouldEqual(1);
result.Last().StringProperty.ShouldEqual("Test2");
result.Last().IntProperty.ShouldEqual(2);
}
[Fact]
public void Should_bind_more_than_10_multiple_Form_properties_to_list()
{
//Given
var typeConverters = new ITypeConverter[] { new CollectionConverter(), new FallbackConverter() };
var binder = this.GetBinder(typeConverters);
var context = CreateContextWithHeader("Content-Type", new[] { "application/x-www-form-urlencoded" });
context.Request.Form["IntProperty_0"] = "1";
context.Request.Form["IntProperty_01"] = "2";
context.Request.Form["IntProperty_02"] = "3";
context.Request.Form["IntProperty_03"] = "4";
context.Request.Form["IntProperty_04"] = "5";
context.Request.Form["IntProperty_05"] = "6";
context.Request.Form["IntProperty_06"] = "7";
context.Request.Form["IntProperty_07"] = "8";
context.Request.Form["IntProperty_08"] = "9";
context.Request.Form["IntProperty_09"] = "10";
context.Request.Form["IntProperty_10"] = "11";
context.Request.Form["IntProperty_11"] = "12";
context.Request.Form["IntProperty_12"] = "13";
// When
var result = (List<TestModel>)binder.Bind(context, typeof(List<TestModel>), null, BindingConfig.Default);
// Then
result.First().IntProperty.ShouldEqual(1);
result.ElementAt(1).IntProperty.ShouldEqual(2);
result.Last().IntProperty.ShouldEqual(13);
}
[Fact]
public void Should_bind_more_than_10_multiple_Form_properties_to_list_should_work_with_padded_zeros()
{
//Given
var typeConverters = new ITypeConverter[] { new CollectionConverter(), new FallbackConverter() };
var binder = this.GetBinder(typeConverters);
var context = CreateContextWithHeader("Content-Type", new[] { "application/x-www-form-urlencoded" });
context.Request.Form["IntProperty_00"] = "1";
context.Request.Form["IntProperty_01"] = "2";
context.Request.Form["IntProperty_02"] = "3";
context.Request.Form["IntProperty_03"] = "4";
context.Request.Form["IntProperty_04"] = "5";
context.Request.Form["IntProperty_05"] = "6";
context.Request.Form["IntProperty_06"] = "7";
context.Request.Form["IntProperty_07"] = "8";
context.Request.Form["IntProperty_08"] = "9";
context.Request.Form["IntProperty_09"] = "10";
context.Request.Form["IntProperty_10"] = "11";
context.Request.Form["IntProperty_11"] = "12";
context.Request.Form["IntProperty_12"] = "13";
// When
var result = (List<TestModel>)binder.Bind(context, typeof(List<TestModel>), null, BindingConfig.Default);
// Then
result.First().IntProperty.ShouldEqual(1);
result.Last().IntProperty.ShouldEqual(13);
}
[Fact]
public void Should_bind_more_than_10_multiple_Form_properties_to_list_starting_counting_from_1()
{
//Given
var typeConverters = new ITypeConverter[] { new CollectionConverter(), new FallbackConverter() };
var binder = this.GetBinder(typeConverters);
var context = CreateContextWithHeader("Content-Type", new[] { "application/x-www-form-urlencoded" });
context.Request.Form["IntProperty_01"] = "1";
context.Request.Form["IntProperty_02"] = "2";
context.Request.Form["IntProperty_03"] = "3";
context.Request.Form["IntProperty_04"] = "4";
context.Request.Form["IntProperty_05"] = "5";
context.Request.Form["IntProperty_06"] = "6";
context.Request.Form["IntProperty_07"] = "7";
context.Request.Form["IntProperty_08"] = "8";
context.Request.Form["IntProperty_09"] = "9";
context.Request.Form["IntProperty_10"] = "10";
context.Request.Form["IntProperty_11"] = "11";
context.Request.Form["IntProperty_12"] = "12";
// When
var result = (List<TestModel>)binder.Bind(context, typeof(List<TestModel>), null, BindingConfig.Default);
// Then
result.First().IntProperty.ShouldEqual(1);
result.Last().IntProperty.ShouldEqual(12);
}
[Fact]
public void Should_be_able_to_bind_more_than_once_should_ignore_non_list_properties_when_binding_to_a_list()
{
// Given
var typeConverters = new ITypeConverter[] { new CollectionConverter(), new FallbackConverter() };
var binder = this.GetBinder(typeConverters);
var context = CreateContextWithHeader("Content-Type", new[] { "application/x-www-form-urlencoded" });
context.Request.Form["StringProperty"] = "Test";
context.Request.Form["IntProperty"] = "3";
context.Request.Form["NestedIntProperty[0]"] = "1";
context.Request.Form["NestedIntField[0]"] = "2";
context.Request.Form["NestedStringProperty[0]"] = "one";
context.Request.Form["NestedStringField[0]"] = "two";
context.Request.Form["NestedIntProperty[1]"] = "3";
context.Request.Form["NestedIntField[1]"] = "4";
context.Request.Form["NestedStringProperty[1]"] = "three";
context.Request.Form["NestedStringField[1]"] = "four";
// When
var result = (TestModel)binder.Bind(context, typeof(TestModel), null, BindingConfig.Default);
var result2 = (List<AnotherTestModel>)binder.Bind(context, typeof(List<AnotherTestModel>), null, BindingConfig.Default);
// Then
result.StringProperty.ShouldEqual("Test");
result.IntProperty.ShouldEqual(3);
result2.ShouldHaveCount(2);
result2.First().NestedIntProperty.ShouldEqual(1);
result2.First().NestedIntField.ShouldEqual(2);
result2.First().NestedStringProperty.ShouldEqual("one");
result2.First().NestedStringField.ShouldEqual("two");
result2.Last().NestedIntProperty.ShouldEqual(3);
result2.Last().NestedIntField.ShouldEqual(4);
result2.Last().NestedStringProperty.ShouldEqual("three");
result2.Last().NestedStringField.ShouldEqual("four");
}
[Fact]
public void Should_bind_more_than_10_multiple_Form_properties_to_list_starting_with_jagged_ids()
{
//Given
var typeConverters = new ITypeConverter[] { new CollectionConverter(), new FallbackConverter() };
var binder = this.GetBinder(typeConverters);
var context = CreateContextWithHeader("Content-Type", new[] { "application/x-www-form-urlencoded" });
context.Request.Form["IntProperty_01"] = "1";
context.Request.Form["IntProperty_04"] = "2";
context.Request.Form["IntProperty_05"] = "3";
context.Request.Form["IntProperty_06"] = "4";
context.Request.Form["IntProperty_09"] = "5";
context.Request.Form["IntProperty_11"] = "6";
context.Request.Form["IntProperty_57"] = "7";
context.Request.Form["IntProperty_199"] = "8";
context.Request.Form["IntProperty_1599"] = "9";
context.Request.Form["StringProperty_1599"] = "nine";
context.Request.Form["IntProperty_233"] = "10";
context.Request.Form["IntProperty_14"] = "11";
context.Request.Form["IntProperty_12"] = "12";
// When
var result = (List<TestModel>)binder.Bind(context, typeof(List<TestModel>), null, BindingConfig.Default);
// Then
result.First().IntProperty.ShouldEqual(1);
result.Last().IntProperty.ShouldEqual(9);
result.Last().StringProperty.ShouldEqual("nine");
}
[Fact]
public void Should_bind_to_IEnumerable_from_Form()
{
//Given
var typeConverters = new ITypeConverter[] { new CollectionConverter(), new FallbackConverter() };
var binder = this.GetBinder(typeConverters);
var context = CreateContextWithHeader("Content-Type", new[] { "application/x-www-form-urlencoded" });
context.Request.Form["IntValuesProperty"] = "1,2,3,4";
context.Request.Form["IntValuesField"] = "5,6,7,8";
// When
var result = (TestModel)binder.Bind(context, typeof(TestModel), null, BindingConfig.Default);
// Then
result.IntValuesProperty.ShouldHaveCount(4);
result.IntValuesProperty.ShouldEqualSequence(new[] { 1, 2, 3, 4 });
result.IntValuesField.ShouldHaveCount(4);
result.IntValuesField.ShouldEqualSequence(new[] { 5, 6, 7, 8 });
}
[Fact]
public void Should_bind_to_IEnumerable_from_Form_with_multiple_inputs()
{
// Given
var typeConverters = new ITypeConverter[] { new CollectionConverter(), new FallbackConverter() };
var binder = this.GetBinder(typeConverters);
var context = CreateContextWithHeader("Content-Type", new[] { "application/x-www-form-urlencoded" });
context.Request.Form["IntValuesProperty_0"] = "1,2,3,4";
context.Request.Form["IntValuesField_0"] = "5,6,7,8";
context.Request.Form["IntValuesProperty_1"] = "9,10,11,12";
context.Request.Form["IntValuesField_1"] = "13,14,15,16";
// When
var result = (List<TestModel>)binder.Bind(context, typeof(List<TestModel>), null, BindingConfig.Default);
// Then
result.ShouldHaveCount(2);
result.First().IntValuesProperty.ShouldHaveCount(4);
result.First().IntValuesProperty.ShouldEqualSequence(new[] { 1, 2, 3, 4 });
result.First().IntValuesField.ShouldHaveCount(4);
result.First().IntValuesField.ShouldEqualSequence(new[] { 5, 6, 7, 8 });
result.Last().IntValuesProperty.ShouldHaveCount(4);
result.Last().IntValuesProperty.ShouldEqualSequence(new[] { 9, 10, 11, 12 });
result.Last().IntValuesField.ShouldHaveCount(4);
result.Last().IntValuesField.ShouldEqualSequence(new[] { 13, 14, 15, 16 });
}
[Fact]
public void Should_bind_to_IEnumerable_from_Form_with_multiple_inputs_using_brackets_and_specifying_an_instance()
{
// Given
var typeConverters = new ITypeConverter[] { new CollectionConverter(), new FallbackConverter() };
var binder = this.GetBinder(typeConverters);
var context = CreateContextWithHeader("Content-Type", new[] { "application/x-www-form-urlencoded" });
context.Request.Form["IntValuesProperty[0]"] = "1,2,3,4";
context.Request.Form["IntValuesField[0]"] = "5,6,7,8";
context.Request.Form["IntValuesProperty[1]"] = "9,10,11,12";
context.Request.Form["IntValuesField[1]"] = "13,14,15,16";
// When
var result = (List<TestModel>)binder.Bind(context, typeof(List<TestModel>), new List<TestModel> { new TestModel {AnotherStringProperty = "Test"} }, new BindingConfig { Overwrite = false});
// Then
result.ShouldHaveCount(2);
result.First().AnotherStringProperty.ShouldEqual("Test");
result.First().IntValuesProperty.ShouldHaveCount(4);
result.First().IntValuesProperty.ShouldEqualSequence(new[] { 1, 2, 3, 4 });
result.First().IntValuesField.ShouldHaveCount(4);
result.First().IntValuesField.ShouldEqualSequence(new[] { 5, 6, 7, 8 });
result.Last().AnotherStringProperty.ShouldBeNull();
result.Last().IntValuesProperty.ShouldHaveCount(4);
result.Last().IntValuesProperty.ShouldEqualSequence(new[] { 9, 10, 11, 12 });
result.Last().IntValuesField.ShouldHaveCount(4);
result.Last().IntValuesField.ShouldEqualSequence(new[] { 13, 14, 15, 16 });
}
[Fact]
public void Should_bind_to_IEnumerable_from_Form_with_multiple_inputs_using_brackets()
{
// Given
var typeConverters = new ITypeConverter[] { new CollectionConverter(), new FallbackConverter() };
var binder = this.GetBinder(typeConverters);
var context = CreateContextWithHeader("Content-Type", new[] { "application/x-www-form-urlencoded" });
context.Request.Form["IntValuesProperty[0]"] = "1,2,3,4";
context.Request.Form["IntValuesField[0]"] = "5,6,7,8";
context.Request.Form["IntValuesProperty[1]"] = "9,10,11,12";
context.Request.Form["IntValuesField[1]"] = "13,14,15,16";
// When
var result = (List<TestModel>)binder.Bind(context, typeof(List<TestModel>), null, BindingConfig.Default);
// Then
result.ShouldHaveCount(2);
result.First().IntValuesProperty.ShouldHaveCount(4);
result.First().IntValuesProperty.ShouldEqualSequence(new[] { 1, 2, 3, 4 });
result.First().IntValuesField.ShouldHaveCount(4);
result.First().IntValuesField.ShouldEqualSequence(new[] { 5, 6, 7, 8 });
result.Last().IntValuesProperty.ShouldHaveCount(4);
result.Last().IntValuesProperty.ShouldEqualSequence(new[] { 9, 10, 11, 12 });
result.Last().IntValuesField.ShouldHaveCount(4);
result.Last().IntValuesField.ShouldEqualSequence(new[] { 13, 14, 15, 16 });
}
[Fact]
public void Should_bind_collections_regardless_of_case()
{
// Given
var typeConverters = new ITypeConverter[] { new CollectionConverter(), new FallbackConverter() };
var binder = this.GetBinder(typeConverters);
var context = CreateContextWithHeader("Content-Type", new[] { "application/x-www-form-urlencoded" });
context.Request.Form["lowercaseintproperty[0]"] = "1";
context.Request.Form["lowercaseintproperty[1]"] = "2";
context.Request.Form["lowercaseIntproperty[2]"] = "3";
context.Request.Form["lowercaseIntproperty[3]"] = "4";
context.Request.Form["Lowercaseintproperty[4]"] = "5";
context.Request.Form["Lowercaseintproperty[5]"] = "6";
context.Request.Form["LowercaseIntproperty[6]"] = "7";
context.Request.Form["LowercaseIntproperty[7]"] = "8";
context.Request.Form["lowercaseintfield[0]"] = "9";
context.Request.Form["lowercaseintfield[1]"] = "10";
context.Request.Form["lowercaseIntfield[2]"] = "11";
context.Request.Form["lowercaseIntfield[3]"] = "12";
context.Request.Form["Lowercaseintfield[4]"] = "13";
context.Request.Form["Lowercaseintfield[5]"] = "14";
context.Request.Form["LowercaseIntfield[6]"] = "15";
context.Request.Form["LowercaseIntfield[7]"] = "16";
// When
var result = (List<TestModel>)binder.Bind(context, typeof(List<TestModel>), null, BindingConfig.Default);
// Then
result.ShouldHaveCount(8);
result.First().lowercaseintproperty.ShouldEqual(1);
result.Last().lowercaseintproperty.ShouldEqual(8);
result.First().lowercaseintfield.ShouldEqual(9);
result.Last().lowercaseintfield.ShouldEqual(16);
}
[Fact]
public void Form_properties_should_take_precendence_over_request_properties_and_context_properties()
{
// Given
var binder = this.GetBinder();
var context = CreateContextWithHeader("Content-Type", new[] { "application/xml" });
context.Request.Form["StringProperty"] = "Test";
context.Request.Form["IntProperty"] = "3";
context.Request.Query["StringProperty"] = "Test2";
context.Request.Query["IntProperty"] = "1";
context.Parameters["StringProperty"] = "Test3";
context.Parameters["IntProperty"] = "2";
// When
var result = (TestModel)binder.Bind(context, typeof(TestModel), null, BindingConfig.Default);
// Then
result.StringProperty.ShouldEqual("Test");
result.IntProperty.ShouldEqual(3);
}
[Fact]
public void Request_properties_should_take_precendence_over_context_properties()
{
// Given
var binder = this.GetBinder();
var context = CreateContextWithHeader("Content-Type", new[] { "application/xml" });
context.Request.Query["StringProperty"] = "Test";
context.Request.Query["IntProperty"] = "12";
context.Parameters["StringProperty"] = "Test2";
context.Parameters["IntProperty"] = "13";
// When
var result = (TestModel)binder.Bind(context, typeof(TestModel), null, BindingConfig.Default);
// Then
result.StringProperty.ShouldEqual("Test");
result.IntProperty.ShouldEqual(12);
}
[Fact]
public void Should_be_able_to_bind_from_form_and_request_simultaneously()
{
// Given
var binder = this.GetBinder();
var context = CreateContextWithHeader("Content-Type", new[] { "application/xml" });
context.Request.Form["StringProperty"] = "Test";
context.Request.Query["IntProperty"] = "12";
// When
var result = (TestModel)binder.Bind(context, typeof(TestModel), null, BindingConfig.Default);
// Then
result.StringProperty.ShouldEqual("Test");
result.IntProperty.ShouldEqual(12);
}
[Theory]
[InlineData("de-DE", 4.50)]
[InlineData("en-GB", 450)]
[InlineData("en-US", 450)]
[InlineData("sv-SE", 4.50)]
[InlineData("ru-RU", 4.50)]
[InlineData("zh-TW", 450)]
public void Should_be_able_to_bind_culturally_aware_form_properties_if_numeric(string culture, double expected)
{
// Given
var binder = this.GetBinder();
var context = CreateContextWithHeader("Content-Type", new[] { "application/xml" });
context.Culture = new CultureInfo(culture);
context.Request.Form["DoubleProperty"] = "4,50";
// When
var result = (TestModel)binder.Bind(context, typeof(TestModel), null, BindingConfig.Default);
// Then
result.DoubleProperty.ShouldEqual(expected);
}
[Theory]
[InlineData("12/25/2012", 12, 25, 2012, "en-US")]
[InlineData("12/12/2012", 12, 12, 2012, "en-US")]
[InlineData("25/12/2012", 12, 25, 2012, "en-GB")]
[InlineData("12/12/2012", 12, 12, 2012, "en-GB")]
[InlineData("12/12/2012", 12, 12, 2012, "ru-RU")]
[InlineData("25/12/2012", 12, 25, 2012, "ru-RU")]
[InlineData("2012-12-25", 12, 25, 2012, "zh-TW")]
[InlineData("2012-12-12", 12, 12, 2012, "zh-TW")]
public void Should_be_able_to_bind_culturally_aware_form_properties_if_datetime(string date, int month, int day, int year, string culture)
{
// Given
var binder = this.GetBinder();
var context = CreateContextWithHeader("Content-Type", new[] { "application/xml" });
context.Culture = new CultureInfo(culture);
context.Request.Form["DateProperty"] = date;
// When
var result = (TestModel)binder.Bind(context, typeof(TestModel), null, BindingConfig.Default);
// Then
result.DateProperty.Date.Month.ShouldEqual(month);
result.DateProperty.Date.Day.ShouldEqual(day);
result.DateProperty.Date.Year.ShouldEqual(year);
}
[Fact]
public void Should_be_able_to_bind_from_request_and_context_simultaneously()
{
// Given
var binder = this.GetBinder();
var context = CreateContextWithHeader("Content-Type", new[] { "application/xml" });
context.Request.Query["StringProperty"] = "Test";
context.Parameters["IntProperty"] = "12";
// When
var result = (TestModel)binder.Bind(context, typeof(TestModel), null, BindingConfig.Default);
// Then
result.StringProperty.ShouldEqual("Test");
result.IntProperty.ShouldEqual(12);
}
[Fact]
public void Should_not_overwrite_nullable_property_if_already_set_and_overwriting_is_not_allowed()
{
// Given
var binder = this.GetBinder();
var existing = new TestModel { StringProperty = "Existing Value" };
var context = CreateContextWithHeader("Content-Type", new[] { "application/xml" });
context.Request.Query["StringProperty"] = "Test";
context.Request.Query["IntProperty"] = "12";
context.Parameters["StringProperty"] = "Test2";
context.Parameters["IntProperty"] = "1";
// When
var result = (TestModel)binder.Bind(context, typeof(TestModel), existing, BindingConfig.NoOverwrite);
// Then
result.StringProperty.ShouldEqual("Existing Value");
result.IntProperty.ShouldEqual(12);
}
[Fact]
public void Should_not_overwrite_non_nullable_property_if_already_set_and_overwriting_is_not_allowed()
{
// Given
var binder = this.GetBinder();
var existing = new TestModel { IntProperty = 27 };
var context = CreateContextWithHeader("Content-Type", new[] { "application/xml" });
context.Request.Query["StringProperty"] = "Test";
context.Request.Query["IntProperty"] = "12";
context.Parameters["StringProperty"] = "Test2";
context.Parameters["IntProperty"] = "1";
// When
var result = (TestModel)binder.Bind(context, typeof(TestModel), existing, BindingConfig.NoOverwrite);
// Then
result.StringProperty.ShouldEqual("Test");
result.IntProperty.ShouldEqual(27);
}
[Fact]
public void Should_overwrite_nullable_property_if_already_set_and_overwriting_is_allowed()
{
// Given
var binder = this.GetBinder();
var existing = new TestModel { StringProperty = "Existing Value" };
var context = CreateContextWithHeader("Content-Type", new[] { "application/xml" });
context.Parameters["StringProperty"] = "Test2";
context.Parameters["IntProperty"] = "1";
// When
var result = (TestModel)binder.Bind(context, typeof(TestModel), existing, BindingConfig.Default);
// Then
result.StringProperty.ShouldEqual("Test2");
result.IntProperty.ShouldEqual(1);
}
[Fact]
public void Should_overwrite_non_nullable_property_if_already_set_and_overwriting_is_allowed()
{
// Given
var binder = this.GetBinder();
var existing = new TestModel { IntProperty = 27 };
var context = CreateContextWithHeader("Content-Type", new[] { "application/xml" });
context.Parameters["StringProperty"] = "Test2";
context.Parameters["IntProperty"] = "1";
// When
var result = (TestModel)binder.Bind(context, typeof(TestModel), existing, BindingConfig.Default);
// Then
result.StringProperty.ShouldEqual("Test2");
result.IntProperty.ShouldEqual(1);
}
[Fact]
public void Should_bind_list_model_from_body()
{
//Given
var binder = this.GetBinder(null, new List<IBodyDeserializer> { new XmlBodyDeserializer() });
var body = XmlBodyDeserializerFixture.ToXmlString(new List<TestModel>(new[] { new TestModel { StringProperty = "Test" }, new TestModel { StringProperty = "AnotherTest" } }));
var context = CreateContextWithHeaderAndBody("Content-Type", new[] { "application/xml" }, body);
// When
var result = (List<TestModel>)binder.Bind(context, typeof(List<TestModel>), null, BindingConfig.Default);
// Then
result.First().StringProperty.ShouldEqual("Test");
result.Last().StringProperty.ShouldEqual("AnotherTest");
}
[Fact]
public void Should_bind_array_model_from_body()
{
//Given
var binder = this.GetBinder(null, new List<IBodyDeserializer> { new XmlBodyDeserializer() });
var body = XmlBodyDeserializerFixture.ToXmlString(new List<TestModel>(new[] { new TestModel { StringProperty = "Test" }, new TestModel { StringProperty = "AnotherTest" } }));
var context = CreateContextWithHeaderAndBody("Content-Type", new[] { "application/xml" }, body);
// When
var result = (TestModel[])binder.Bind(context, typeof(TestModel[]), null, BindingConfig.Default);
// Then
result.First().StringProperty.ShouldEqual("Test");
result.Last().StringProperty.ShouldEqual("AnotherTest");
}
[Fact]
public void Should_bind_string_array_model_from_body()
{
//Given
var binder = this.GetBinder(null, new List<IBodyDeserializer> { new JsonBodyDeserializer() });
var body = serializer.Serialize(new[] { "Test","AnotherTest"});
var context = CreateContextWithHeaderAndBody("Content-Type", new[] { "application/json" }, body);
// When
var result = (string[])binder.Bind(context, typeof(string[]), null, BindingConfig.Default);
// Then
result.First().ShouldEqual("Test");
result.Last().ShouldEqual("AnotherTest");
}
[Fact]
public void Should_bind_ienumerable_model_from_body()
{
//Given
var binder = this.GetBinder(null, new List<IBodyDeserializer> { new JsonBodyDeserializer() });
var body = serializer.Serialize(new List<TestModel>(new[] { new TestModel { StringProperty = "Test" }, new TestModel { StringProperty = "AnotherTest" } }));
var context = CreateContextWithHeaderAndBody("Content-Type", new[] { "application/json" }, body);
// When
var result = (IEnumerable<TestModel>)binder.Bind(context, typeof(IEnumerable<TestModel>), null, BindingConfig.Default);
// Then
result.First().StringProperty.ShouldEqual("Test");
result.Last().StringProperty.ShouldEqual("AnotherTest");
}
[Fact]
public void Should_bind_ienumerable_model_with_instance_from_body()
{
//Given
var binder = this.GetBinder(null, new List<IBodyDeserializer> { new JsonBodyDeserializer() });
var body = serializer.Serialize(new List<TestModel>(new[] { new TestModel { StringProperty = "Test" }, new TestModel { StringProperty = "AnotherTest" } }));
var context = CreateContextWithHeaderAndBody("Content-Type", new[] { "application/json" }, body);
var then = DateTime.Now;
var instance = new List<TestModel> { new TestModel{ DateProperty = then }, new TestModel { IntProperty = 9, AnotherStringProperty = "Bananas" } };
// When
var result = (IEnumerable<TestModel>)binder.Bind(context, typeof(IEnumerable<TestModel>), instance, new BindingConfig{Overwrite = false});
// Then
result.First().StringProperty.ShouldEqual("Test");
result.First().DateProperty.ShouldEqual(then);
result.Last().StringProperty.ShouldEqual("AnotherTest");
result.Last().IntProperty.ShouldEqual(9);
result.Last().AnotherStringProperty.ShouldEqual("Bananas");
}
[Fact]
public void Should_bind_model_with_instance_from_body()
{
//Given
var binder = this.GetBinder(null, new List<IBodyDeserializer> { new XmlBodyDeserializer() });
var body = XmlBodyDeserializerFixture.ToXmlString(new TestModel { StringProperty = "Test" });
var context = CreateContextWithHeaderAndBody("Content-Type", new[] { "application/xml" }, body);
var then = DateTime.Now;
var instance = new TestModel { DateProperty = then, IntProperty = 6, AnotherStringProperty = "Beers" };
// Wham
var result = (TestModel)binder.Bind(context, typeof(TestModel), instance, new BindingConfig { Overwrite = false });
// Then
result.StringProperty.ShouldEqual("Test");
result.DateProperty.ShouldEqual(then);
result.IntProperty.ShouldEqual(6);
result.AnotherStringProperty.ShouldEqual("Beers");
}
[Fact]
public void Should_bind_model_from_body_that_contains_an_array()
{
//Given
var typeConverters = new ITypeConverter[] { new CollectionConverter(), new FallbackConverter() };
var binder = this.GetBinder(typeConverters, new List<IBodyDeserializer> { new JsonBodyDeserializer() });
var body = serializer.Serialize(
new TestModel
{
StringProperty = "Test",
SomeStringsProperty = new[] { "E", "A", "D", "G", "B", "E" },
SomeStringsField = new[] { "G", "D", "A", "E" },
});
var context = CreateContextWithHeaderAndBody("Content-Type", new[] { "application/json" }, body);
// When
var result = (TestModel)binder.Bind(context, typeof(TestModel), null, BindingConfig.Default);
// Then
result.SomeStringsProperty.ShouldHaveCount(6);
result.SomeStringsProperty.ShouldEqualSequence(new[] { "E", "A", "D", "G", "B", "E" });
result.SomeStringsField.ShouldHaveCount(4);
result.SomeStringsField.ShouldEqualSequence(new[] { "G", "D", "A", "E" });
}
[Fact]
public void Should_bind_array_model_from_body_that_contains_an_array()
{
//Given
var binder = this.GetBinder(null, new List<IBodyDeserializer> { new JsonBodyDeserializer() });
var body =
serializer.Serialize(new[]
{
new TestModel()
{
StringProperty = "Test",
SomeStringsProperty = new[] {"E", "A", "D", "G", "B", "E"},
SomeStringsField = new[] { "G", "D", "A", "E" },
},
new TestModel()
{
StringProperty = "AnotherTest",
SomeStringsProperty = new[] {"E", "A", "D", "G", "B", "E"},
SomeStringsField = new[] { "G", "D", "A", "E" },
}
});
var context = CreateContextWithHeaderAndBody("Content-Type", new[] { "application/json" }, body);
// When
var result = (TestModel[])binder.Bind(context, typeof(TestModel[]), null, BindingConfig.Default, "SomeStringsProperty", "SomeStringsField");
// Then
result.ShouldHaveCount(2);
result.First().SomeStringsProperty.ShouldBeNull();
result.First().SomeStringsField.ShouldBeNull();
result.Last().SomeStringsProperty.ShouldBeNull();
result.Last().SomeStringsField.ShouldBeNull();
}
[Fact]
public void Form_request_and_context_properties_should_take_precedence_over_body_properties()
{
// Given
var typeConverters = new ITypeConverter[] { new CollectionConverter(), new FallbackConverter() };
var bodyDeserializers = new IBodyDeserializer[] { new XmlBodyDeserializer() };
var binder = this.GetBinder(typeConverters, bodyDeserializers);
var body = XmlBodyDeserializerFixture.ToXmlString(new TestModel { IntProperty = 0, StringProperty = "From body" });
var context = CreateContextWithHeaderAndBody("Content-Type", new[] { "application/xml" }, body);
context.Request.Form["StringProperty"] = "From form";
context.Request.Query["IntProperty"] = "1";
context.Parameters["AnotherStringProperty"] = "From context";
// When
var result = (TestModel)binder.Bind(context, typeof(TestModel), null, BindingConfig.Default);
// Then
result.StringProperty.ShouldEqual("From form");
result.AnotherStringProperty.ShouldEqual("From context");
result.IntProperty.ShouldEqual(1);
}
[Fact]
public void Form_request_and_context_properties_should_be_ignored_in_body_only_mode_when_there_is_a_body()
{
// Given
var typeConverters = new ITypeConverter[] { new CollectionConverter(), new FallbackConverter() };
var bodyDeserializers = new IBodyDeserializer[] { new XmlBodyDeserializer() };
var binder = GetBinder(typeConverters, bodyDeserializers);
var body = XmlBodyDeserializerFixture.ToXmlString(new TestModel { IntProperty = 2, StringProperty = "From body" });
var context = CreateContextWithHeaderAndBody("Content-Type", new[] { "application/xml" }, body);
context.Request.Form["StringProperty"] = "From form";
context.Request.Query["IntProperty"] = "1";
context.Parameters["AnotherStringProperty"] = "From context";
// When
var result = (TestModel)binder.Bind(context, typeof(TestModel), null, new BindingConfig { BodyOnly = true });
// Then
result.StringProperty.ShouldEqual("From body");
result.AnotherStringProperty.ShouldBeNull(); // not in body, so default value
result.IntProperty.ShouldEqual(2);
}
[Fact]
public void Form_request_and_context_properties_should_NOT_be_used_in_body_only_mode_if_there_is_no_body()
{
// Given
var typeConverters = new ITypeConverter[] { new CollectionConverter(), new FallbackConverter() };
var binder = GetBinder(typeConverters);
var context = CreateContextWithHeader("Content-Type", new[] { "application/xml" });
context.Request.Form["StringProperty"] = "From form";
context.Request.Query["IntProperty"] = "1";
context.Parameters["AnotherStringProperty"] = "From context";
// When
var result = (TestModel)binder.Bind(context, typeof(TestModel), null, new BindingConfig { BodyOnly = true });
// Then
result.StringProperty.ShouldEqual(null);
result.AnotherStringProperty.ShouldEqual(null);
result.IntProperty.ShouldEqual(0);
}
[Fact]
public void Should_be_able_to_bind_body_request_form_and_context_properties()
{
//Given
var binder = this.GetBinder(null, new List<IBodyDeserializer> { new XmlBodyDeserializer() });
var body = XmlBodyDeserializerFixture.ToXmlString(new TestModel { DateProperty = new DateTime(2012, 8, 16) });
var context = CreateContextWithHeaderAndBody("Content-Type", new[] { "application/xml" }, body);
context.Request.Form["IntProperty"] = "0";
context.Request.Query["StringProperty"] = "From Query";
context.Parameters["AnotherStringProperty"] = "From Context";
// When
var result = (TestModel)binder.Bind(context, typeof(TestModel), null, BindingConfig.Default);
// Then
result.StringProperty.ShouldEqual("From Query");
result.IntProperty.ShouldEqual(0);
result.DateProperty.ShouldEqual(new DateTime(2012, 8, 16));
result.AnotherStringProperty.ShouldEqual("From Context");
}
[Fact]
public void Should_ignore_existing_instance_if_type_doesnt_match()
{
//Given
var binder = this.GetBinder();
var existing = new object();
var context = CreateContextWithHeader("Content-Type", new[] { "application/xml" });
// When
var result = (TestModel)binder.Bind(context, typeof(TestModel), existing, BindingConfig.Default);
// Then
result.ShouldNotBeSameAs(existing);
}
[Fact]
public void Should_bind_to_valuetype_from_body()
{
//Given
var binder = this.GetBinder(null, new List<IBodyDeserializer> { new JsonBodyDeserializer() });
var body = serializer.Serialize(1);
var context = CreateContextWithHeaderAndBody("Content-Type", new[] { "application/json" }, body);
// When
var result = (int)binder.Bind(context, typeof(int), null, BindingConfig.Default);
// Then
result.ShouldEqual(1);
}
[Fact]
public void Should_bind_ienumerable_model__of_valuetype_from_body()
{
//Given
var binder = this.GetBinder(null, new List<IBodyDeserializer> { new JsonBodyDeserializer() });
var body = serializer.Serialize(new[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 });
var context = CreateContextWithHeaderAndBody("Content-Type", new[] { "application/json" }, body);
// When
var result = (IEnumerable<int>)binder.Bind(context, typeof(IEnumerable<int>), null, BindingConfig.Default);
// Then
result.ShouldEqualSequence(new[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 });
}
[Fact]
public void Should_bind_to_model_with_non_public_default_constructor()
{
var binder = this.GetBinder();
var context = CreateContextWithHeader("Content-Type", new[] { "application/json" });
context.Request.Form["IntProperty"] = "10";
var result = (TestModelWithHiddenDefaultConstructor)binder.Bind(context, typeof (TestModelWithHiddenDefaultConstructor), null, BindingConfig.Default);
result.ShouldNotBeNull();
result.IntProperty.ShouldEqual(10);
}
private IBinder GetBinder(IEnumerable<ITypeConverter> typeConverters = null, IEnumerable<IBodyDeserializer> bodyDeserializers = null, IFieldNameConverter nameConverter = null, BindingDefaults bindingDefaults = null)
{
var converters = typeConverters ?? new ITypeConverter[] { new DateTimeConverter(), new NumericConverter(), new FallbackConverter() };
var deserializers = bodyDeserializers ?? new IBodyDeserializer[] { };
var converter = nameConverter ?? this.passthroughNameConverter;
var defaults = bindingDefaults ?? this.emptyDefaults;
return new DefaultBinder(converters, deserializers, converter, defaults);
}
private static NancyContext CreateContextWithHeader(string name, IEnumerable<string> values)
{
var header = new Dictionary<string, IEnumerable<string>>
{
{ name, values }
};
return new NancyContext
{
Request = new FakeRequest("GET", "/", header),
Parameters = DynamicDictionary.Empty
};
}
private static NancyContext CreateContextWithHeaderAndBody(string name, IEnumerable<string> values, string body)
{
var header = new Dictionary<string, IEnumerable<string>>
{
{ name, values }
};
byte[] byteArray = Encoding.UTF8.GetBytes(body);
var bodyStream = RequestStream.FromStream(new MemoryStream(byteArray));
return new NancyContext
{
Request = new FakeRequest("GET", "/", header, bodyStream, "http", string.Empty),
Parameters = DynamicDictionary.Empty
};
}
public class TestModel
{
public TestModel()
{
this.StringPropertyWithDefaultValue = "Default Property Value";
this.StringFieldWithDefaultValue = "Default Field Value";
}
public string StringProperty { get; set; }
public string AnotherStringProperty { get; set; }
public string StringField;
public string AnotherStringField;
public int IntProperty { get; set; }
public int AnotherIntProperty { get; set; }
public int IntField;
public int AnotherIntField;
public int lowercaseintproperty { get; set; }
public int lowercaseintfield;
public DateTime DateProperty { get; set; }
public DateTime DateField;
public string StringPropertyWithDefaultValue { get; set; }
public string StringFieldWithDefaultValue;
public double DoubleProperty { get; set; }
public double DoubleField;
[XmlIgnore]
public IEnumerable<int> IntValuesProperty { get; set; }
[XmlIgnore]
public IEnumerable<int> IntValuesField;
public string[] SomeStringsProperty { get; set; }
public string[] SomeStringsField;
public int this[int index]
{
get { return 0; }
set { }
}
public List<AnotherTestModel> ModelsProperty { get; set; }
public List<AnotherTestModel> ModelsField;
}
public class AnotherTestModel
{
public string NestedStringProperty { get; set; }
public int NestedIntProperty { get; set; }
public double NestedDoubleProperty { get; set; }
public string NestedStringField;
public int NestedIntField;
public double NestedDoubleField;
}
private class ThrowingBodyDeserializer<T> : IBodyDeserializer where T : Exception, new()
{
public bool CanDeserialize(string contentType, BindingContext context)
{
return true;
}
public object Deserialize(string contentType, Stream bodyStream, BindingContext context)
{
throw new T();
}
}
public class TestModelWithHiddenDefaultConstructor
{
public int IntProperty { get; private set; }
private TestModelWithHiddenDefaultConstructor() { }
}
}
public class BindingConfigFixture
{
[Fact]
public void Should_allow_overwrite_on_new_instance()
{
// Given
// When
var instance = new BindingConfig();
// Then
instance.Overwrite.ShouldBeTrue();
}
}
}
| |
//
// Copyright (c) 2004-2020 Jaroslaw Kowalski <jaak@jkowalski.net>, Kim Christensen, Julian Verdurmen
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of Jaroslaw Kowalski nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
namespace NLog.UnitTests.Config
{
using System;
using NLog.Config;
using NLog.LayoutRenderers;
using NLog.Layouts;
using NLog.Targets;
using Xunit;
public class VariableTests : NLogTestBase
{
[Fact]
public void VariablesTest1()
{
var configuration = XmlLoggingConfiguration.CreateFromXmlString(@"
<nlog throwExceptions='true'>
<variable name='prefix' value='[[' />
<variable name='suffix' value=']]' />
<targets>
<target name='d1' type='Debug' layout='${prefix}${message}${suffix}' />
</targets>
</nlog>");
var d1 = configuration.FindTargetByName("d1") as DebugTarget;
Assert.NotNull(d1);
var layout = d1.Layout as SimpleLayout;
Assert.NotNull(layout);
Assert.Equal(3, layout.Renderers.Count);
var lr1 = layout.Renderers[0] as LiteralLayoutRenderer;
var lr2 = layout.Renderers[1] as MessageLayoutRenderer;
var lr3 = layout.Renderers[2] as LiteralLayoutRenderer;
Assert.NotNull(lr1);
Assert.NotNull(lr2);
Assert.NotNull(lr3);
Assert.Equal("[[", lr1.Text);
Assert.Equal("]]", lr3.Text);
}
/// <summary>
/// Expand of property which are not layoutable <see cref="Layout"/>, but still get expanded.
/// </summary>
[Fact]
public void VariablesTest_string_expanding()
{
var configuration = XmlLoggingConfiguration.CreateFromXmlString(@"
<nlog throwExceptions='true'>
<variable name='test' value='hello'/>
<targets>
<target type='DataBase' name='test' DBProvider='${test}'/>
</targets>
</nlog>");
var target = configuration.FindTargetByName("test") as DatabaseTarget;
Assert.NotNull(target);
//dont change the ${test} as it isn't a Layout
Assert.NotEqual(typeof(Layout), target.DBProvider.GetType());
Assert.Equal("hello", target.DBProvider);
}
[Fact]
public void VariablesTest_minLevel_expanding()
{
var configuration = XmlLoggingConfiguration.CreateFromXmlString(@"
<nlog throwExceptions='true'>
<variable name='test' value='debug'/>
<rules>
<logger minLevel='${test}' final='true' />
</rules>
</nlog>");
var rule = configuration.LoggingRules[0];
Assert.NotNull(rule);
Assert.False(rule.IsLoggingEnabledForLevel(LogLevel.Trace));
Assert.True(rule.IsLoggingEnabledForLevel(LogLevel.Debug));
Assert.True(rule.IsLoggingEnabledForLevel(LogLevel.Info));
Assert.True(rule.IsLoggingEnabledForLevel(LogLevel.Warn));
Assert.True(rule.IsLoggingEnabledForLevel(LogLevel.Error));
Assert.True(rule.IsLoggingEnabledForLevel(LogLevel.Fatal));
}
/// <summary>
/// Expand of level attributes
/// </summary>
[Fact]
public void VariablesTest_Level_expanding()
{
var configuration = XmlLoggingConfiguration.CreateFromXmlString(@"
<nlog throwExceptions='true'>
<variable name='test' value='debug'/>
<rules>
<logger level='${test}' final='true' />
</rules>
</nlog>");
var rule = configuration.LoggingRules[0];
Assert.NotNull(rule);
Assert.False(rule.IsLoggingEnabledForLevel(LogLevel.Trace));
Assert.True(rule.IsLoggingEnabledForLevel(LogLevel.Debug));
Assert.False(rule.IsLoggingEnabledForLevel(LogLevel.Info));
Assert.False(rule.IsLoggingEnabledForLevel(LogLevel.Warn));
Assert.False(rule.IsLoggingEnabledForLevel(LogLevel.Error));
Assert.False(rule.IsLoggingEnabledForLevel(LogLevel.Fatal));
}
[Fact]
public void Xml_configuration_returns_defined_variables()
{
var configuration = XmlLoggingConfiguration.CreateFromXmlString(@"
<nlog throwExceptions='true'>
<variable name='prefix' value='[[' />
<variable name='suffix' value=']]' />
<targets>
<target name='d1' type='Debug' layout='${prefix}${message}${suffix}' />
</targets>
</nlog>");
LogManager.Configuration = configuration;
Assert.Equal("[[", LogManager.Configuration.Variables["prefix"].OriginalText);
Assert.Equal("]]", LogManager.Configuration.Variables["suffix"].OriginalText);
}
[Fact]
public void Xml_configuration_with_inner_returns_defined_variables_withValueElement()
{
var configuration = XmlLoggingConfiguration.CreateFromXmlString(@"
<nlog throwExceptions='true'>
<variable name='prefix'>
<value><![CDATA[
newline
]]></value>
</variable>
<variable name='suffix'><value>]]</value></variable>
</nlog>");
var nullEvent = LogEventInfo.CreateNullEvent();
// Act & Assert
Assert.Equal("\nnewline\n", configuration.Variables["prefix"].Render(nullEvent).Replace("\r", ""));
Assert.Equal("]]", configuration.Variables["suffix"].Render(nullEvent));
}
[Fact]
public void Xml_configuration_variableWithInnerAndAttribute_attributeHasPrecedence()
{
var configuration = XmlLoggingConfiguration.CreateFromXmlString(@"
<nlog throwExceptions='true'>
<variable name='var1' value='1'><value>2</value></variable>
</nlog>");
var nullEvent = LogEventInfo.CreateNullEvent();
// Act & Assert
Assert.Equal("1", configuration.Variables["var1"].FixedText);
}
[Fact]
public void NLogConfigurationExceptionShouldThrown_WhenVariableNodeIsWrittenToWrongPlace()
{
LogManager.ThrowConfigExceptions = true;
const string configurationString_VariableNodeIsInnerTargets =
@"<nlog>
<targets>
<variable name='variableOne' value='${longdate:universalTime=True}Z | ${message}'/>
<target name='d1' type='Debug' layout='${variableOne}' />
</targets>
<rules>
<logger name='*' minlevel='Debug' writeTo='d1'/>
</rules>
</nlog>";
const string configurationString_VariableNodeIsAfterTargets =
@"<nlog>
<targets>
<target name='d1' type='Debug' layout='${variableOne}' />
</targets>
<variable name='variableOne' value='${longdate:universalTime=True}Z | ${message}'/>
<rules>
<logger name='*' minlevel='Debug' writeTo='d1'/>
</rules>
</nlog>";
NLogConfigurationException nlogConfEx_ForInnerTargets = Assert.Throws<NLogConfigurationException>(
() => XmlLoggingConfiguration.CreateFromXmlString(configurationString_VariableNodeIsInnerTargets)
);
NLogConfigurationException nlogConfExForAfterTargets = Assert.Throws<NLogConfigurationException>(
() => XmlLoggingConfiguration.CreateFromXmlString(configurationString_VariableNodeIsAfterTargets)
);
}
}
}
| |
//
// SchedulerTests.cs
//
// Author:
// Gabriel Burt <gburt@novell.com>
//
// Copyright (C) 2009 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.Linq;
using System.Threading;
using NUnit.Framework;
using Hyena;
namespace Hyena.Jobs
{
[TestFixture]
public class SchedulerTests
{
private Scheduler scheduler;
[SetUp]
public void Setup ()
{
//Log.Debugging = true;
TestJob.job_count = 0;
Log.Debug ("New job scheduler test");
}
[TearDown]
public void TearDown ()
{
if (scheduler != null) {
// Ensure the scheduler's jobs are all finished, otherwise
// their job threads will be killed, throwing an exception
while (scheduler.JobCount > 0);
}
//Log.Debugging = false;
}
[Test]
public void TestSimultaneousSpeedJobs ()
{
scheduler = new Scheduler ();
scheduler.Add (new TestJob (200, PriorityHints.SpeedSensitive, Resource.Cpu, Resource.Disk));
scheduler.Add (new TestJob (200, PriorityHints.SpeedSensitive, Resource.Cpu, Resource.Disk));
scheduler.Add (new TestJob (200, PriorityHints.None, Resource.Cpu, Resource.Disk));
// Test that two SpeedSensitive jobs with the same Resources will run simultaneously
AssertJobsRunning (2);
// but that the third that isn't SpeedSensitive won't run until they are both done
while (scheduler.JobCount > 1);
Assert.AreEqual (PriorityHints.None, scheduler.Jobs.First ().PriorityHints);
}
[Test]
public void TestOneNonSpeedJobPerResource ()
{
// Test that two SpeedSensitive jobs with the same Resources will run simultaneously
scheduler = new Scheduler ();
scheduler.Add (new TestJob (200, PriorityHints.None, Resource.Cpu, Resource.Disk));
scheduler.Add (new TestJob (200, PriorityHints.None, Resource.Cpu, Resource.Disk));
AssertJobsRunning (1);
}
[Test]
public void TestSpeedJobPreemptsNonSpeedJobs ()
{
scheduler = new Scheduler ();
TestJob a = new TestJob (200, PriorityHints.None, Resource.Cpu);
TestJob b = new TestJob (200, PriorityHints.None, Resource.Disk);
TestJob c = new TestJob (200, PriorityHints.LongRunning, Resource.Database);
scheduler.Add (a);
scheduler.Add (b);
scheduler.Add (c);
// Test that three jobs got started
AssertJobsRunning (3);
scheduler.Add (new TestJob (200, PriorityHints.SpeedSensitive, Resource.Cpu, Resource.Disk));
// Make sure the SpeedSensitive jobs has caused the Cpu and Disk jobs to be paused
AssertJobsRunning (2);
Assert.AreEqual (true, a.IsScheduled);
Assert.AreEqual (true, b.IsScheduled);
Assert.AreEqual (true, c.IsRunning);
}
/*[Test]
public void TestManyJobs ()
{
var timer = System.Diagnostics.Stopwatch.StartNew ();
scheduler = new Scheduler ("TestManyJobs");
// First add some long running jobs
for (int i = 0; i < 100; i++) {
scheduler.Add (new TestJob (20, PriorityHints.LongRunning, Resource.Cpu));
}
// Then add some normal jobs that will prempt them
for (int i = 0; i < 100; i++) {
scheduler.Add (new TestJob (10, PriorityHints.None, Resource.Cpu));
}
// Then add some SpeedSensitive jobs that will prempt all of them
for (int i = 0; i < 100; i++) {
scheduler.Add (new TestJob (5, PriorityHints.SpeedSensitive, Resource.Cpu));
}
while (scheduler.Jobs.Count > 0);
Log.DebugFormat ("Took {0} to schedule and process all jobs", timer.Elapsed);
//scheduler.StopAll ();
}*/
/*[Test]
public void TestCannotDisposeWhileDatalossJobsScheduled ()
{
scheduler = new Scheduler ();
TestJob loss_job;
scheduler.Add (new TestJob (200, PriorityHints.SpeedSensitive, Resource.Cpu));
scheduler.Add (loss_job = new TestJob (200, PriorityHints.DataLossIfStopped, Resource.Cpu));
AssertJobsRunning (1);
Assert.AreEqual (false, scheduler.JobInfo[loss_job].IsRunning);
try {
//scheduler.StopAll ();
Assert.Fail ("Cannot stop with dataloss job scheduled");
} catch {
}
}
public void TestCannotDisposeWhileDatalossJobsRunning ()
{
scheduler = new Scheduler ();
scheduler.Add (new TestJob (200, PriorityHints.DataLossIfStopped, Resource.Cpu));
AssertJobsRunning (1);
try {
//scheduler.StopAll ();
Assert.Fail ("Cannot stop with dataloss job running");
} catch {
}
}*/
private void AssertJobsRunning (int count)
{
Assert.AreEqual (count, scheduler.Jobs.Count (j => j.IsRunning));
}
private class TestJob : SimpleAsyncJob
{
internal static int job_count;
int iteration;
int sleep_time;
public TestJob (int sleep_time, PriorityHints hints, params Resource [] resources)
: base (String.Format ("{0} ( {1}, {2})", job_count++, hints, resources.Aggregate ("", (a, b) => a += b.Id + " ")),
hints,
resources)
{
this.sleep_time = sleep_time;
}
protected override void Run ()
{
for (int i = 0; !IsCancelRequested && i < 2; i++) {
YieldToScheduler ();
Hyena.Log.DebugFormat ("{0} iteration {1}", Title, iteration++);
System.Threading.Thread.Sleep (sleep_time);
}
OnFinished ();
}
}
}
}
| |
using System;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Data.Common;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Xml;
using System.Xml.Serialization;
using SubSonic;
using SubSonic.Utilities;
namespace DalSic
{
/// <summary>
/// Strongly-typed collection for the AprZScorePesoEdad class.
/// </summary>
[Serializable]
public partial class AprZScorePesoEdadCollection : ActiveList<AprZScorePesoEdad, AprZScorePesoEdadCollection>
{
public AprZScorePesoEdadCollection() {}
/// <summary>
/// Filters an existing collection based on the set criteria. This is an in-memory filter
/// Thanks to developingchris for this!
/// </summary>
/// <returns>AprZScorePesoEdadCollection</returns>
public AprZScorePesoEdadCollection Filter()
{
for (int i = this.Count - 1; i > -1; i--)
{
AprZScorePesoEdad o = this[i];
foreach (SubSonic.Where w in this.wheres)
{
bool remove = false;
System.Reflection.PropertyInfo pi = o.GetType().GetProperty(w.ColumnName);
if (pi.CanRead)
{
object val = pi.GetValue(o, null);
switch (w.Comparison)
{
case SubSonic.Comparison.Equals:
if (!val.Equals(w.ParameterValue))
{
remove = true;
}
break;
}
}
if (remove)
{
this.Remove(o);
break;
}
}
}
return this;
}
}
/// <summary>
/// This is an ActiveRecord class which wraps the APR_ZScorePesoEdad table.
/// </summary>
[Serializable]
public partial class AprZScorePesoEdad : ActiveRecord<AprZScorePesoEdad>, IActiveRecord
{
#region .ctors and Default Settings
public AprZScorePesoEdad()
{
SetSQLProps();
InitSetDefaults();
MarkNew();
}
private void InitSetDefaults() { SetDefaults(); }
public AprZScorePesoEdad(bool useDatabaseDefaults)
{
SetSQLProps();
if(useDatabaseDefaults)
ForceDefaults();
MarkNew();
}
public AprZScorePesoEdad(object keyID)
{
SetSQLProps();
InitSetDefaults();
LoadByKey(keyID);
}
public AprZScorePesoEdad(string columnName, object columnValue)
{
SetSQLProps();
InitSetDefaults();
LoadByParam(columnName,columnValue);
}
protected static void SetSQLProps() { GetTableSchema(); }
#endregion
#region Schema and Query Accessor
public static Query CreateQuery() { return new Query(Schema); }
public static TableSchema.Table Schema
{
get
{
if (BaseSchema == null)
SetSQLProps();
return BaseSchema;
}
}
private static void GetTableSchema()
{
if(!IsSchemaInitialized)
{
//Schema declaration
TableSchema.Table schema = new TableSchema.Table("APR_ZScorePesoEdad", TableType.Table, DataService.GetInstance("sicProvider"));
schema.Columns = new TableSchema.TableColumnCollection();
schema.SchemaName = @"dbo";
//columns
TableSchema.TableColumn colvarId = new TableSchema.TableColumn(schema);
colvarId.ColumnName = "id";
colvarId.DataType = DbType.Int32;
colvarId.MaxLength = 0;
colvarId.AutoIncrement = true;
colvarId.IsNullable = false;
colvarId.IsPrimaryKey = true;
colvarId.IsForeignKey = false;
colvarId.IsReadOnly = false;
colvarId.DefaultSetting = @"";
colvarId.ForeignKeyTableName = "";
schema.Columns.Add(colvarId);
TableSchema.TableColumn colvarSexo = new TableSchema.TableColumn(schema);
colvarSexo.ColumnName = "Sexo";
colvarSexo.DataType = DbType.Int32;
colvarSexo.MaxLength = 0;
colvarSexo.AutoIncrement = false;
colvarSexo.IsNullable = true;
colvarSexo.IsPrimaryKey = false;
colvarSexo.IsForeignKey = false;
colvarSexo.IsReadOnly = false;
colvarSexo.DefaultSetting = @"";
colvarSexo.ForeignKeyTableName = "";
schema.Columns.Add(colvarSexo);
TableSchema.TableColumn colvarEdad = new TableSchema.TableColumn(schema);
colvarEdad.ColumnName = "Edad";
colvarEdad.DataType = DbType.Int32;
colvarEdad.MaxLength = 0;
colvarEdad.AutoIncrement = false;
colvarEdad.IsNullable = true;
colvarEdad.IsPrimaryKey = false;
colvarEdad.IsForeignKey = false;
colvarEdad.IsReadOnly = false;
colvarEdad.DefaultSetting = @"";
colvarEdad.ForeignKeyTableName = "";
schema.Columns.Add(colvarEdad);
TableSchema.TableColumn colvarSD4neg = new TableSchema.TableColumn(schema);
colvarSD4neg.ColumnName = "SD4neg";
colvarSD4neg.DataType = DbType.Decimal;
colvarSD4neg.MaxLength = 0;
colvarSD4neg.AutoIncrement = false;
colvarSD4neg.IsNullable = true;
colvarSD4neg.IsPrimaryKey = false;
colvarSD4neg.IsForeignKey = false;
colvarSD4neg.IsReadOnly = false;
colvarSD4neg.DefaultSetting = @"";
colvarSD4neg.ForeignKeyTableName = "";
schema.Columns.Add(colvarSD4neg);
TableSchema.TableColumn colvarSD3neg = new TableSchema.TableColumn(schema);
colvarSD3neg.ColumnName = "SD3neg";
colvarSD3neg.DataType = DbType.Decimal;
colvarSD3neg.MaxLength = 0;
colvarSD3neg.AutoIncrement = false;
colvarSD3neg.IsNullable = true;
colvarSD3neg.IsPrimaryKey = false;
colvarSD3neg.IsForeignKey = false;
colvarSD3neg.IsReadOnly = false;
colvarSD3neg.DefaultSetting = @"";
colvarSD3neg.ForeignKeyTableName = "";
schema.Columns.Add(colvarSD3neg);
TableSchema.TableColumn colvarSD2neg = new TableSchema.TableColumn(schema);
colvarSD2neg.ColumnName = "SD2neg";
colvarSD2neg.DataType = DbType.Decimal;
colvarSD2neg.MaxLength = 0;
colvarSD2neg.AutoIncrement = false;
colvarSD2neg.IsNullable = true;
colvarSD2neg.IsPrimaryKey = false;
colvarSD2neg.IsForeignKey = false;
colvarSD2neg.IsReadOnly = false;
colvarSD2neg.DefaultSetting = @"";
colvarSD2neg.ForeignKeyTableName = "";
schema.Columns.Add(colvarSD2neg);
TableSchema.TableColumn colvarSD1neg = new TableSchema.TableColumn(schema);
colvarSD1neg.ColumnName = "SD1neg";
colvarSD1neg.DataType = DbType.Decimal;
colvarSD1neg.MaxLength = 0;
colvarSD1neg.AutoIncrement = false;
colvarSD1neg.IsNullable = true;
colvarSD1neg.IsPrimaryKey = false;
colvarSD1neg.IsForeignKey = false;
colvarSD1neg.IsReadOnly = false;
colvarSD1neg.DefaultSetting = @"";
colvarSD1neg.ForeignKeyTableName = "";
schema.Columns.Add(colvarSD1neg);
TableSchema.TableColumn colvarSD0 = new TableSchema.TableColumn(schema);
colvarSD0.ColumnName = "SD0";
colvarSD0.DataType = DbType.Decimal;
colvarSD0.MaxLength = 0;
colvarSD0.AutoIncrement = false;
colvarSD0.IsNullable = true;
colvarSD0.IsPrimaryKey = false;
colvarSD0.IsForeignKey = false;
colvarSD0.IsReadOnly = false;
colvarSD0.DefaultSetting = @"";
colvarSD0.ForeignKeyTableName = "";
schema.Columns.Add(colvarSD0);
TableSchema.TableColumn colvarSD1 = new TableSchema.TableColumn(schema);
colvarSD1.ColumnName = "SD1";
colvarSD1.DataType = DbType.Decimal;
colvarSD1.MaxLength = 0;
colvarSD1.AutoIncrement = false;
colvarSD1.IsNullable = true;
colvarSD1.IsPrimaryKey = false;
colvarSD1.IsForeignKey = false;
colvarSD1.IsReadOnly = false;
colvarSD1.DefaultSetting = @"";
colvarSD1.ForeignKeyTableName = "";
schema.Columns.Add(colvarSD1);
TableSchema.TableColumn colvarSD2 = new TableSchema.TableColumn(schema);
colvarSD2.ColumnName = "SD2";
colvarSD2.DataType = DbType.Decimal;
colvarSD2.MaxLength = 0;
colvarSD2.AutoIncrement = false;
colvarSD2.IsNullable = true;
colvarSD2.IsPrimaryKey = false;
colvarSD2.IsForeignKey = false;
colvarSD2.IsReadOnly = false;
colvarSD2.DefaultSetting = @"";
colvarSD2.ForeignKeyTableName = "";
schema.Columns.Add(colvarSD2);
TableSchema.TableColumn colvarSD3 = new TableSchema.TableColumn(schema);
colvarSD3.ColumnName = "SD3";
colvarSD3.DataType = DbType.Decimal;
colvarSD3.MaxLength = 0;
colvarSD3.AutoIncrement = false;
colvarSD3.IsNullable = true;
colvarSD3.IsPrimaryKey = false;
colvarSD3.IsForeignKey = false;
colvarSD3.IsReadOnly = false;
colvarSD3.DefaultSetting = @"";
colvarSD3.ForeignKeyTableName = "";
schema.Columns.Add(colvarSD3);
TableSchema.TableColumn colvarSD4 = new TableSchema.TableColumn(schema);
colvarSD4.ColumnName = "SD4";
colvarSD4.DataType = DbType.Decimal;
colvarSD4.MaxLength = 0;
colvarSD4.AutoIncrement = false;
colvarSD4.IsNullable = true;
colvarSD4.IsPrimaryKey = false;
colvarSD4.IsForeignKey = false;
colvarSD4.IsReadOnly = false;
colvarSD4.DefaultSetting = @"";
colvarSD4.ForeignKeyTableName = "";
schema.Columns.Add(colvarSD4);
BaseSchema = schema;
//add this schema to the provider
//so we can query it later
DataService.Providers["sicProvider"].AddSchema("APR_ZScorePesoEdad",schema);
}
}
#endregion
#region Props
[XmlAttribute("Id")]
[Bindable(true)]
public int Id
{
get { return GetColumnValue<int>(Columns.Id); }
set { SetColumnValue(Columns.Id, value); }
}
[XmlAttribute("Sexo")]
[Bindable(true)]
public int? Sexo
{
get { return GetColumnValue<int?>(Columns.Sexo); }
set { SetColumnValue(Columns.Sexo, value); }
}
[XmlAttribute("Edad")]
[Bindable(true)]
public int? Edad
{
get { return GetColumnValue<int?>(Columns.Edad); }
set { SetColumnValue(Columns.Edad, value); }
}
[XmlAttribute("SD4neg")]
[Bindable(true)]
public decimal? SD4neg
{
get { return GetColumnValue<decimal?>(Columns.SD4neg); }
set { SetColumnValue(Columns.SD4neg, value); }
}
[XmlAttribute("SD3neg")]
[Bindable(true)]
public decimal? SD3neg
{
get { return GetColumnValue<decimal?>(Columns.SD3neg); }
set { SetColumnValue(Columns.SD3neg, value); }
}
[XmlAttribute("SD2neg")]
[Bindable(true)]
public decimal? SD2neg
{
get { return GetColumnValue<decimal?>(Columns.SD2neg); }
set { SetColumnValue(Columns.SD2neg, value); }
}
[XmlAttribute("SD1neg")]
[Bindable(true)]
public decimal? SD1neg
{
get { return GetColumnValue<decimal?>(Columns.SD1neg); }
set { SetColumnValue(Columns.SD1neg, value); }
}
[XmlAttribute("SD0")]
[Bindable(true)]
public decimal? SD0
{
get { return GetColumnValue<decimal?>(Columns.SD0); }
set { SetColumnValue(Columns.SD0, value); }
}
[XmlAttribute("SD1")]
[Bindable(true)]
public decimal? SD1
{
get { return GetColumnValue<decimal?>(Columns.SD1); }
set { SetColumnValue(Columns.SD1, value); }
}
[XmlAttribute("SD2")]
[Bindable(true)]
public decimal? SD2
{
get { return GetColumnValue<decimal?>(Columns.SD2); }
set { SetColumnValue(Columns.SD2, value); }
}
[XmlAttribute("SD3")]
[Bindable(true)]
public decimal? SD3
{
get { return GetColumnValue<decimal?>(Columns.SD3); }
set { SetColumnValue(Columns.SD3, value); }
}
[XmlAttribute("SD4")]
[Bindable(true)]
public decimal? SD4
{
get { return GetColumnValue<decimal?>(Columns.SD4); }
set { SetColumnValue(Columns.SD4, value); }
}
#endregion
//no foreign key tables defined (0)
//no ManyToMany tables defined (0)
#region ObjectDataSource support
/// <summary>
/// Inserts a record, can be used with the Object Data Source
/// </summary>
public static void Insert(int? varSexo,int? varEdad,decimal? varSD4neg,decimal? varSD3neg,decimal? varSD2neg,decimal? varSD1neg,decimal? varSD0,decimal? varSD1,decimal? varSD2,decimal? varSD3,decimal? varSD4)
{
AprZScorePesoEdad item = new AprZScorePesoEdad();
item.Sexo = varSexo;
item.Edad = varEdad;
item.SD4neg = varSD4neg;
item.SD3neg = varSD3neg;
item.SD2neg = varSD2neg;
item.SD1neg = varSD1neg;
item.SD0 = varSD0;
item.SD1 = varSD1;
item.SD2 = varSD2;
item.SD3 = varSD3;
item.SD4 = varSD4;
if (System.Web.HttpContext.Current != null)
item.Save(System.Web.HttpContext.Current.User.Identity.Name);
else
item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name);
}
/// <summary>
/// Updates a record, can be used with the Object Data Source
/// </summary>
public static void Update(int varId,int? varSexo,int? varEdad,decimal? varSD4neg,decimal? varSD3neg,decimal? varSD2neg,decimal? varSD1neg,decimal? varSD0,decimal? varSD1,decimal? varSD2,decimal? varSD3,decimal? varSD4)
{
AprZScorePesoEdad item = new AprZScorePesoEdad();
item.Id = varId;
item.Sexo = varSexo;
item.Edad = varEdad;
item.SD4neg = varSD4neg;
item.SD3neg = varSD3neg;
item.SD2neg = varSD2neg;
item.SD1neg = varSD1neg;
item.SD0 = varSD0;
item.SD1 = varSD1;
item.SD2 = varSD2;
item.SD3 = varSD3;
item.SD4 = varSD4;
item.IsNew = false;
if (System.Web.HttpContext.Current != null)
item.Save(System.Web.HttpContext.Current.User.Identity.Name);
else
item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name);
}
#endregion
#region Typed Columns
public static TableSchema.TableColumn IdColumn
{
get { return Schema.Columns[0]; }
}
public static TableSchema.TableColumn SexoColumn
{
get { return Schema.Columns[1]; }
}
public static TableSchema.TableColumn EdadColumn
{
get { return Schema.Columns[2]; }
}
public static TableSchema.TableColumn SD4negColumn
{
get { return Schema.Columns[3]; }
}
public static TableSchema.TableColumn SD3negColumn
{
get { return Schema.Columns[4]; }
}
public static TableSchema.TableColumn SD2negColumn
{
get { return Schema.Columns[5]; }
}
public static TableSchema.TableColumn SD1negColumn
{
get { return Schema.Columns[6]; }
}
public static TableSchema.TableColumn SD0Column
{
get { return Schema.Columns[7]; }
}
public static TableSchema.TableColumn SD1Column
{
get { return Schema.Columns[8]; }
}
public static TableSchema.TableColumn SD2Column
{
get { return Schema.Columns[9]; }
}
public static TableSchema.TableColumn SD3Column
{
get { return Schema.Columns[10]; }
}
public static TableSchema.TableColumn SD4Column
{
get { return Schema.Columns[11]; }
}
#endregion
#region Columns Struct
public struct Columns
{
public static string Id = @"id";
public static string Sexo = @"Sexo";
public static string Edad = @"Edad";
public static string SD4neg = @"SD4neg";
public static string SD3neg = @"SD3neg";
public static string SD2neg = @"SD2neg";
public static string SD1neg = @"SD1neg";
public static string SD0 = @"SD0";
public static string SD1 = @"SD1";
public static string SD2 = @"SD2";
public static string SD3 = @"SD3";
public static string SD4 = @"SD4";
}
#endregion
#region Update PK Collections
#endregion
#region Deep Save
#endregion
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using Xunit;
using SortedDictionaryTests.SortedDictionary_SortedDictionary_CtorTests;
using SortedDictionary_SortedDictionaryUtils;
namespace SortedDictionaryTests
{
internal class MyOwnIKeyImplementation<KeyType> : IComparer<KeyType>
{
public int GetHashCode(KeyType key)
{
//We cannot get the hascode that is culture aware here since TextInfo doesn't expose this functionality publicly
return key.GetHashCode();
}
public int Compare(KeyType key1, KeyType key2)
{
//We cannot get the hascode that is culture aware here since TextInfo doesn't expose this functionality publicly
return key1.GetHashCode();
}
public bool Equals(KeyType key1, KeyType key2)
{
return key1.Equals(key2);
}
}
namespace SortedDictionary_SortedDictionary_CtorTests
{
public class SortedDictionary_CtorTests
{
[Fact]
public static void SortedDictionary_DefaultCtorTest()
{
Driver<SimpleRef<int>, SimpleRef<String>> driver1 = new Driver<SimpleRef<int>, SimpleRef<String>>();
Driver<SimpleRef<String>, SimpleRef<int>> driver2 = new Driver<SimpleRef<String>, SimpleRef<int>>();
Driver<SimpleRef<int>, SimpleRef<int>> driver3 = new Driver<SimpleRef<int>, SimpleRef<int>>();
Driver<SimpleRef<String>, SimpleRef<String>> driver4 = new Driver<SimpleRef<String>, SimpleRef<String>>();
SimpleRef<int>[] ints = new SimpleRef<int>[] { new SimpleRef<int>(1), new SimpleRef<int>(2), new SimpleRef<int>(3) };
SimpleRef<String>[] strings = new SimpleRef<String>[] { new SimpleRef<String>("1"), new SimpleRef<String>("2"), new SimpleRef<String>("3") };
//Scenario 1: Vanilla - Create a SortedDictionary and check that default properties are set
driver1.TestVanilla();
driver2.TestVanilla();
driver3.TestVanilla();
driver4.TestVanilla();
//Scenario 2: Vanilla - Make sure that we can add key-value pairs to this
driver1.TestCanAdd(ints, strings);
driver2.TestCanAdd(strings, ints);
driver3.TestCanAdd(ints, ints);
driver4.TestCanAdd(strings, strings);
}
[Fact]
public static void SortedDictionary_IDictionaryCtorTest()
{
Driver<SimpleRef<int>, SimpleRef<String>> driver1 = new Driver<SimpleRef<int>, SimpleRef<String>>();
Driver<SimpleRef<String>, SimpleRef<int>> driver2 = new Driver<SimpleRef<String>, SimpleRef<int>>();
Driver<SimpleRef<int>, SimpleRef<int>> driver3 = new Driver<SimpleRef<int>, SimpleRef<int>>();
Driver<SimpleRef<String>, SimpleRef<String>> driver4 = new Driver<SimpleRef<String>, SimpleRef<String>>();
int count;
SimpleRef<int>[] ints;
SimpleRef<String>[] strings;
SortedDictionary<SimpleRef<int>, SimpleRef<String>> dic1;
SortedDictionary<SimpleRef<String>, SimpleRef<int>> dic2;
SortedDictionary<SimpleRef<int>, SimpleRef<int>> dic3;
SortedDictionary<SimpleRef<String>, SimpleRef<String>> dic4;
//Scenario 1: Vanilla - Create SortedDictionary using another SortedDictionary with 10 key-values and check
count = 10;
ints = GetSimpleInts(count);
strings = GetSimpleStrings(count);
dic1 = FillValues(ints, strings);
dic2 = FillValues(strings, ints);
dic3 = FillValues(ints, ints);
dic4 = FillValues(strings, strings);
driver1.TestVanillaIDictionary(dic1);
driver2.TestVanillaIDictionary(dic2);
driver3.TestVanillaIDictionary(dic3);
driver4.TestVanillaIDictionary(dic4);
//Scenario 2: SortedDictionary with 100 entries
count = 100;
ints = GetSimpleInts(count);
strings = GetSimpleStrings(count);
dic1 = FillValues(ints, strings);
dic2 = FillValues(strings, ints);
dic3 = FillValues(ints, ints);
dic4 = FillValues(strings, strings);
driver1.TestVanillaIDictionary(dic1);
driver2.TestVanillaIDictionary(dic2);
driver3.TestVanillaIDictionary(dic3);
driver4.TestVanillaIDictionary(dic4);
//Scenario 3: Implement our own type that implements IDictionary<KeyType, ValueType> and test
TestSortedDictionary<SimpleRef<int>, SimpleRef<String>> myDic1 = new TestSortedDictionary<SimpleRef<int>, SimpleRef<String>>(ints, strings);
TestSortedDictionary<SimpleRef<String>, SimpleRef<int>> myDic2 = new TestSortedDictionary<SimpleRef<String>, SimpleRef<int>>(strings, ints);
TestSortedDictionary<SimpleRef<int>, SimpleRef<int>> myDic3 = new TestSortedDictionary<SimpleRef<int>, SimpleRef<int>>(ints, ints);
TestSortedDictionary<SimpleRef<String>, SimpleRef<String>> myDic4 = new TestSortedDictionary<SimpleRef<String>, SimpleRef<String>>(strings, strings);
driver1.TestVanillaIDictionary(myDic1);
driver2.TestVanillaIDictionary(myDic2);
driver3.TestVanillaIDictionary(myDic3);
driver4.TestVanillaIDictionary(myDic4);
driver1.TestVanillaIDictionary(new SortedDictionary<SimpleRef<int>, SimpleRef<String>>());
driver2.TestVanillaIDictionary(new SortedDictionary<SimpleRef<String>, SimpleRef<int>>());
driver3.TestVanillaIDictionary(new SortedDictionary<SimpleRef<int>, SimpleRef<int>>());
driver4.TestVanillaIDictionary(new SortedDictionary<SimpleRef<String>, SimpleRef<String>>());
}
[Fact]
public static void SortedDictionary_IDictionaryIKeyComparerCtorTest()
{
Driver<String, String> driver = new Driver<String, String>();
int count;
SimpleRef<int>[] simpleInts;
SimpleRef<String>[] simpleStrings;
String[] strings;
SortedDictionary<String, String> dic1;
count = 10;
strings = new String[count];
for (int i = 0; i < count; i++)
strings[i] = i.ToString();
simpleInts = GetSimpleInts(count);
simpleStrings = GetSimpleStrings(count);
dic1 = FillValues(strings, strings);
// Scenario 1: Pass all the enum values and ensure that the behavior is correct
driver.TestEnumIDictionary_IKeyComparer(dic1);
// Scenario 2: Implement our own IKeyComparer and check
driver.IkeyComparerOwnImplementation(dic1);
//Scenario 3: ensure that SortedDictionary items from the passed IDictionary object use the interface IKeyComparer's Equals and GetHashCode APIs.
//Ex. Pass the case invariant IKeyComparer and check
//@TODO!!!
//Scenario 4: Contradictory values and check: ex. IDictionary is case insensitive but IKeyComparer is not
}
[Fact]
public static void SortedDictionary_IKeyComparerCtorTest()
{
Driver<String, String> driver1 = new Driver<String, String>();
//Scenario 1: Pass all the enum values and ensure that the behavior is correct
driver1.TestEnumIKeyComparer();
//Scenario 2: Parm validation: null
// If comparer is null, this constructor uses the default generic equality comparer, Comparer<T>.Default.
driver1.TestParmIKeyComparer();
//Scenario 3: Implement our own IKeyComparer and check
driver1.IkeyComparerOwnImplementation(null);
}
[Fact]
public static void SortedDictionary_IDictionaryIKeyComparerCtorTest_Negative()
{
Driver<String, String> driver = new Driver<String, String>();
//Param validation: null
driver.TestParmIDictionaryIKeyComparer();
}
[Fact]
public static void SortedDictionary_IDictionaryCtorTest_Negative()
{
Driver<SimpleRef<int>, SimpleRef<String>> driver1 = new Driver<SimpleRef<int>, SimpleRef<String>>();
Driver<SimpleRef<String>, SimpleRef<int>> driver2 = new Driver<SimpleRef<String>, SimpleRef<int>>();
Driver<SimpleRef<int>, SimpleRef<int>> driver3 = new Driver<SimpleRef<int>, SimpleRef<int>>();
Driver<SimpleRef<String>, SimpleRef<String>> driver4 = new Driver<SimpleRef<String>, SimpleRef<String>>();
//Scenario 4: Parm validation: null, empty SortedDictionary
driver1.TestParmIDictionary(null);
driver2.TestParmIDictionary(null);
driver3.TestParmIDictionary(null);
driver4.TestParmIDictionary(null);
}
private static SortedDictionary<KeyType, ValueType> FillValues<KeyType, ValueType>(KeyType[] keys, ValueType[] values)
{
SortedDictionary<KeyType, ValueType> _dic = new SortedDictionary<KeyType, ValueType>();
for (int i = 0; i < keys.Length; i++)
_dic.Add(keys[i], values[i]);
return _dic;
}
private static SimpleRef<int>[] GetSimpleInts(int count)
{
SimpleRef<int>[] ints = new SimpleRef<int>[count];
for (int i = 0; i < count; i++)
ints[i] = new SimpleRef<int>(i);
return ints;
}
private static SimpleRef<String>[] GetSimpleStrings(int count)
{
SimpleRef<String>[] strings = new SimpleRef<String>[count];
for (int i = 0; i < count; i++)
strings[i] = new SimpleRef<String>(i.ToString());
return strings;
}
}
/// Helper class
public class Driver<KeyType, ValueType>
{
private CultureInfo _english = new CultureInfo("en");
private CultureInfo _german = new CultureInfo("de");
private CultureInfo _danish = new CultureInfo("da");
private CultureInfo _turkish = new CultureInfo("tr");
private const String strAE = "AE";
private const String strUC4 = "\u00C4";
private const String straA = "aA";
private const String strAa = "Aa";
private const String strI = "I";
private const String strTurkishUpperI = "\u0131";
private const String strBB = "BB";
private const String strbb = "bb";
private const String value = "Default_Value";
public void TestVanilla()
{
SortedDictionary<KeyType, ValueType> _dic = new SortedDictionary<KeyType, ValueType>();
Assert.Equal(_dic.Comparer, Comparer<KeyType>.Default); //"Err_001! Comparer differ"
Assert.Equal(_dic.Count, 0); //"Err_002! Count is different"
Assert.False(((IDictionary<KeyType, ValueType>)_dic).IsReadOnly); //"Err_003! Dictionary is not readonly"
Assert.Equal(_dic.Keys.Count, 0); //"Err_004! Key count is different"
Assert.Equal(_dic.Values.Count, 0); //"Err_005! Values count is different"
}
public void TestVanillaIDictionary(IDictionary<KeyType, ValueType> SortedDictionary)
{
SortedDictionary<KeyType, ValueType> _dic = new SortedDictionary<KeyType, ValueType>(SortedDictionary);
Assert.Equal(_dic.Comparer, Comparer<KeyType>.Default); //"Err_006! Comparer differ"
Assert.Equal(_dic.Count, SortedDictionary.Count); //"Err_007! Count is different"
Assert.False(((IDictionary<KeyType, ValueType>)_dic).IsReadOnly); //"Err_008! Dictionary is not readonly"
Assert.Equal(_dic.Keys.Count, SortedDictionary.Count); //"Err_009! Key count is different"
Assert.Equal(_dic.Values.Count, SortedDictionary.Count); //"Err_010! Values count is different"
}
public void TestParmIDictionary(IDictionary<KeyType, ValueType> SortedDictionary)
{
Assert.Throws<ArgumentNullException>(() => new SortedDictionary<KeyType, ValueType>(SortedDictionary)); //"Err_011! wrong exception thrown."
}
public void TestCanAdd(KeyType[] keys, ValueType[] values)
{
SortedDictionary<KeyType, ValueType> _dic = new SortedDictionary<KeyType, ValueType>();
for (int i = 0; i < keys.Length; i++)
_dic.Add(keys[i], values[i]);
Assert.Equal(_dic.Count, keys.Length); //"Err_012! Count is different"
Assert.False(((IDictionary<KeyType, ValueType>)_dic).IsReadOnly); //"Err_013! Dictionary is not readonly"
Assert.Equal(_dic.Keys.Count, keys.Length); //"Err_014! Keys count is different"
Assert.Equal(_dic.Values.Count, values.Length); //"Err_015! values count is different"
}
public void TestEnumIDictionary_IKeyComparer(IDictionary<String, String> idic)
{
SortedDictionary<String, String> _dic;
IComparer<String> comparer;
IComparer<String>[] predefinedComparers = new IComparer<String>[] {
StringComparer.CurrentCulture,
StringComparer.CurrentCultureIgnoreCase,
StringComparer.Ordinal};
foreach (IComparer<String> predefinedComparer in predefinedComparers)
{
_dic = new SortedDictionary<String, String>(predefinedComparer);
Assert.Equal(_dic.Comparer, predefinedComparer); //"Err_016! Comparers differ"
Assert.Equal(_dic.Count, 0); //"Err_017! Count is different"
Assert.False(((IDictionary<KeyType, ValueType>)_dic).IsReadOnly); //"Err_018! Dictionary is not readonly"
Assert.Equal(_dic.Keys.Count, 0); //"Err_019! Count is different"
Assert.Equal(_dic.Values.Count, 0); //"Err_020! Count is different"
}
//Current culture
CultureInfo.DefaultThreadCurrentCulture = _english;
comparer = StringComparer.CurrentCulture;
_dic = new SortedDictionary<String, String>(comparer);
Assert.Equal(_dic.Comparer, comparer); //"Err_021! Comparer is different"
_dic.Add(strAE, value);
Assert.False(_dic.ContainsKey(strUC4)); //"Err_022! Expected that _dic.ContainsKey(strUC4) would return false"
//CurrentCultureIgnoreCase
CultureInfo.DefaultThreadCurrentCulture = _english;
comparer = StringComparer.CurrentCultureIgnoreCase;
_dic = new SortedDictionary<String, String>(comparer);
Assert.Equal(_dic.Comparer, comparer); //"Err_025! Comparer is different"
_dic.Add(straA, value);
Assert.True(_dic.ContainsKey(strAa)); //"Err_026! Expected that _dic.ContainsKey(strAa) would return true"
CultureInfo.DefaultThreadCurrentCulture = _danish;
comparer = StringComparer.CurrentCultureIgnoreCase;
_dic = new SortedDictionary<String, String>(comparer);
Assert.Equal(_dic.Comparer, comparer); //"Err_027! Comparer is different"
_dic.Add(straA, value);
Assert.False(_dic.ContainsKey(strAa)); //"Err_028! Expected that _dic.ContainsKey(strAa) would return false"
//Ordinal
CultureInfo.DefaultThreadCurrentCulture = _english;
comparer = StringComparer.Ordinal;
_dic = new SortedDictionary<String, String>(comparer);
Assert.Equal(_dic.Comparer, comparer); //"Err_029! Comparer is different"
_dic.Add(strBB, value);
Assert.False(_dic.ContainsKey(strbb)); //"Err_030! Expected that _dic.ContainsKey(strbb) would return false"
CultureInfo.DefaultThreadCurrentCulture = _danish;
comparer = StringComparer.Ordinal;
_dic = new SortedDictionary<String, String>(comparer);
Assert.Equal(_dic.Comparer, comparer); //"Err_031! Comparer is different"
_dic.Add(strBB, value);
Assert.False(_dic.ContainsKey(strbb)); //"Err_032! Expected that _dic.ContainsKey(strbb) would return false"
}
public void TestEnumIKeyComparer()
{
SortedDictionary<String, String> _dic;
IComparer<String> comparer;
IComparer<String>[] predefinedComparers = new IComparer<String>[] {
StringComparer.CurrentCulture,
StringComparer.CurrentCultureIgnoreCase,
StringComparer.Ordinal};
foreach (IComparer<String> predefinedComparer in predefinedComparers)
{
_dic = new SortedDictionary<String, String>(predefinedComparer);
Assert.Equal(_dic.Comparer, predefinedComparer); //"Err_033! Comparer is different"
Assert.Equal(_dic.Count, 0); //"Err_034! Count is different"
Assert.False(((IDictionary<KeyType, ValueType>)_dic).IsReadOnly); //"Err_035! Dictionary is not readonly"
Assert.Equal(_dic.Keys.Count, 0); //"Err_036! Count is different"
Assert.Equal(_dic.Values.Count, 0); //"Err_037! Count is different"
}
//Current culture
CultureInfo.DefaultThreadCurrentCulture = _english;
comparer = StringComparer.CurrentCulture;
_dic = new SortedDictionary<String, String>(comparer);
Assert.Equal(_dic.Comparer, comparer); //"Err_038! Comparer is different"
_dic.Add(strAE, value);
Assert.False(_dic.ContainsKey(strUC4)); //"Err_039! Expected that _dic.ContainsKey(strUC4) would return false"
//CurrentCultureIgnoreCase
CultureInfo.DefaultThreadCurrentCulture = _english;
comparer = StringComparer.CurrentCultureIgnoreCase;
_dic = new SortedDictionary<String, String>(comparer);
Assert.Equal(_dic.Comparer, comparer); //"Err_040! Comparer is different"
_dic.Add(straA, value);
Assert.True(_dic.ContainsKey(strAa)); //"Err_041! Expected that _dic.ContainsKey(strAa) would return true"
CultureInfo.DefaultThreadCurrentCulture = _danish;
comparer = StringComparer.CurrentCultureIgnoreCase;
_dic = new SortedDictionary<String, String>(comparer);
Assert.Equal(_dic.Comparer, comparer); //"Err_042! Comparer is different"
_dic.Add(straA, value);
Assert.False(_dic.ContainsKey(strAa)); //"Err_043! Expected that _dic.ContainsKey(strAa) would return false"
//Ordinal
CultureInfo.DefaultThreadCurrentCulture = _english;
comparer = StringComparer.Ordinal;
_dic = new SortedDictionary<String, String>(comparer);
Assert.Equal(_dic.Comparer, comparer); //"Err_044! Comparer is different"
_dic.Add(strBB, value);
Assert.False(_dic.ContainsKey(strbb)); //"Err_045! Expected that _dic.ContainsKey(strbb) would return false"
CultureInfo.DefaultThreadCurrentCulture = _danish;
comparer = StringComparer.Ordinal;
_dic = new SortedDictionary<String, String>(comparer);
Assert.Equal(_dic.Comparer, comparer); //"Err_046! Comparer is different"
_dic.Add(strBB, value);
Assert.False(_dic.ContainsKey(strbb)); //"Err_047! Expected that _dic.ContainsKey(strbb) would return false"
}
public void TestParmIDictionaryIKeyComparer()
{
//passing null will revert to the default comparison mechanism
SortedDictionary<String, String> _dic;
IComparer<String> comparer = null;
SortedDictionary<String, String> dic1 = new SortedDictionary<String, String>();
CultureInfo.DefaultThreadCurrentCulture = _english;
_dic = new SortedDictionary<String, String>(dic1, comparer);
_dic.Add(straA, value);
Assert.False(_dic.ContainsKey(strAa)); //"Err_048! Expected that _dic.ContainsKey(strAa) would return false"
CultureInfo.DefaultThreadCurrentCulture = _danish;
_dic = new SortedDictionary<String, String>(dic1, comparer);
_dic.Add(straA, value);
Assert.False(_dic.ContainsKey(strAa)); //"Err_049! Expected that _dic.ContainsKey(strAa) would return false"
comparer = StringComparer.CurrentCulture;
dic1 = null;
CultureInfo.DefaultThreadCurrentCulture = _english;
Assert.Throws<ArgumentNullException>(() => new SortedDictionary<String, String>(dic1, comparer)); //"Err_050! wrong exception thrown."
}
public void TestParmIKeyComparer()
{
IComparer<KeyType> comparer = null;
SortedDictionary<KeyType, ValueType> _dic = new SortedDictionary<KeyType, ValueType>(comparer);
Assert.Equal(_dic.Comparer, Comparer<KeyType>.Default); //"Err_051! Comparer differ"
Assert.Equal(_dic.Count, 0); //"Err_052! Count is different"
Assert.False(((IDictionary<KeyType, ValueType>)_dic).IsReadOnly); //"Err_053! Dictionary is not readonly"
Assert.Equal(_dic.Keys.Count, 0); //"Err_054! Key count is different"
Assert.Equal(_dic.Values.Count, 0); //"Err_055! Values count is different"
}
public void IkeyComparerOwnImplementation(IDictionary<String, String> idic)
{
//This just ensures that we can call our own implementation
SortedDictionary<String, String> _dic;
IComparer<String> comparer = new MyOwnIKeyImplementation<String>();
CultureInfo.DefaultThreadCurrentCulture = _english;
if (idic == null)
{
_dic = new SortedDictionary<String, String>(comparer);
}
else
{
_dic = new SortedDictionary<String, String>(idic, comparer);
}
_dic.Add(straA, value);
Assert.False(_dic.ContainsKey(strAa)); //"Err_056! Expected that _dic.ContainsKey(strAa) would return false"
CultureInfo.DefaultThreadCurrentCulture = _danish;
if (idic == null)
{
_dic = new SortedDictionary<String, String>(comparer);
}
else
{
_dic = new SortedDictionary<String, String>(idic, comparer);
}
_dic.Add(straA, value);
Assert.False(_dic.ContainsKey(strAa)); //"Err_057! Expected that _dic.ContainsKey(strAa) would return false"
}
}
}
}
| |
/*
* Copyright (c) Citrix Systems, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1) Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2) Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Globalization;
using Newtonsoft.Json;
namespace XenAPI
{
/// <summary>
/// Pool-wide patches
/// First published in XenServer 4.1.
/// </summary>
public partial class Pool_patch : XenObject<Pool_patch>
{
#region Constructors
public Pool_patch()
{
}
public Pool_patch(string uuid,
string name_label,
string name_description,
string version,
long size,
bool pool_applied,
List<XenRef<Host_patch>> host_patches,
List<after_apply_guidance> after_apply_guidance,
XenRef<Pool_update> pool_update,
Dictionary<string, string> other_config)
{
this.uuid = uuid;
this.name_label = name_label;
this.name_description = name_description;
this.version = version;
this.size = size;
this.pool_applied = pool_applied;
this.host_patches = host_patches;
this.after_apply_guidance = after_apply_guidance;
this.pool_update = pool_update;
this.other_config = other_config;
}
/// <summary>
/// Creates a new Pool_patch from a Hashtable.
/// Note that the fields not contained in the Hashtable
/// will be created with their default values.
/// </summary>
/// <param name="table"></param>
public Pool_patch(Hashtable table)
: this()
{
UpdateFrom(table);
}
/// <summary>
/// Creates a new Pool_patch from a Proxy_Pool_patch.
/// </summary>
/// <param name="proxy"></param>
public Pool_patch(Proxy_Pool_patch proxy)
{
UpdateFrom(proxy);
}
#endregion
/// <summary>
/// Updates each field of this instance with the value of
/// the corresponding field of a given Pool_patch.
/// </summary>
public override void UpdateFrom(Pool_patch update)
{
uuid = update.uuid;
name_label = update.name_label;
name_description = update.name_description;
version = update.version;
size = update.size;
pool_applied = update.pool_applied;
host_patches = update.host_patches;
after_apply_guidance = update.after_apply_guidance;
pool_update = update.pool_update;
other_config = update.other_config;
}
internal void UpdateFrom(Proxy_Pool_patch proxy)
{
uuid = proxy.uuid == null ? null : proxy.uuid;
name_label = proxy.name_label == null ? null : proxy.name_label;
name_description = proxy.name_description == null ? null : proxy.name_description;
version = proxy.version == null ? null : proxy.version;
size = proxy.size == null ? 0 : long.Parse(proxy.size);
pool_applied = (bool)proxy.pool_applied;
host_patches = proxy.host_patches == null ? null : XenRef<Host_patch>.Create(proxy.host_patches);
after_apply_guidance = proxy.after_apply_guidance == null ? null : Helper.StringArrayToEnumList<after_apply_guidance>(proxy.after_apply_guidance);
pool_update = proxy.pool_update == null ? null : XenRef<Pool_update>.Create(proxy.pool_update);
other_config = proxy.other_config == null ? null : Maps.convert_from_proxy_string_string(proxy.other_config);
}
public Proxy_Pool_patch ToProxy()
{
Proxy_Pool_patch result_ = new Proxy_Pool_patch();
result_.uuid = uuid ?? "";
result_.name_label = name_label ?? "";
result_.name_description = name_description ?? "";
result_.version = version ?? "";
result_.size = size.ToString();
result_.pool_applied = pool_applied;
result_.host_patches = host_patches == null ? new string[] {} : Helper.RefListToStringArray(host_patches);
result_.after_apply_guidance = after_apply_guidance == null ? new string[] {} : Helper.ObjectListToStringArray(after_apply_guidance);
result_.pool_update = pool_update ?? "";
result_.other_config = Maps.convert_to_proxy_string_string(other_config);
return result_;
}
/// <summary>
/// Given a Hashtable with field-value pairs, it updates the fields of this Pool_patch
/// with the values listed in the Hashtable. Note that only the fields contained
/// in the Hashtable will be updated and the rest will remain the same.
/// </summary>
/// <param name="table"></param>
public void UpdateFrom(Hashtable table)
{
if (table.ContainsKey("uuid"))
uuid = Marshalling.ParseString(table, "uuid");
if (table.ContainsKey("name_label"))
name_label = Marshalling.ParseString(table, "name_label");
if (table.ContainsKey("name_description"))
name_description = Marshalling.ParseString(table, "name_description");
if (table.ContainsKey("version"))
version = Marshalling.ParseString(table, "version");
if (table.ContainsKey("size"))
size = Marshalling.ParseLong(table, "size");
if (table.ContainsKey("pool_applied"))
pool_applied = Marshalling.ParseBool(table, "pool_applied");
if (table.ContainsKey("host_patches"))
host_patches = Marshalling.ParseSetRef<Host_patch>(table, "host_patches");
if (table.ContainsKey("after_apply_guidance"))
after_apply_guidance = Helper.StringArrayToEnumList<after_apply_guidance>(Marshalling.ParseStringArray(table, "after_apply_guidance"));
if (table.ContainsKey("pool_update"))
pool_update = Marshalling.ParseRef<Pool_update>(table, "pool_update");
if (table.ContainsKey("other_config"))
other_config = Maps.convert_from_proxy_string_string(Marshalling.ParseHashTable(table, "other_config"));
}
public bool DeepEquals(Pool_patch other)
{
if (ReferenceEquals(null, other))
return false;
if (ReferenceEquals(this, other))
return true;
return Helper.AreEqual2(this._uuid, other._uuid) &&
Helper.AreEqual2(this._name_label, other._name_label) &&
Helper.AreEqual2(this._name_description, other._name_description) &&
Helper.AreEqual2(this._version, other._version) &&
Helper.AreEqual2(this._size, other._size) &&
Helper.AreEqual2(this._pool_applied, other._pool_applied) &&
Helper.AreEqual2(this._host_patches, other._host_patches) &&
Helper.AreEqual2(this._after_apply_guidance, other._after_apply_guidance) &&
Helper.AreEqual2(this._pool_update, other._pool_update) &&
Helper.AreEqual2(this._other_config, other._other_config);
}
internal static List<Pool_patch> ProxyArrayToObjectList(Proxy_Pool_patch[] input)
{
var result = new List<Pool_patch>();
foreach (var item in input)
result.Add(new Pool_patch(item));
return result;
}
public override string SaveChanges(Session session, string opaqueRef, Pool_patch server)
{
if (opaqueRef == null)
{
System.Diagnostics.Debug.Assert(false, "Cannot create instances of this type on the server");
return "";
}
else
{
if (!Helper.AreEqual2(_other_config, server._other_config))
{
Pool_patch.set_other_config(session, opaqueRef, _other_config);
}
return null;
}
}
/// <summary>
/// Get a record containing the current state of the given pool_patch.
/// First published in XenServer 4.1.
/// Deprecated since XenServer 7.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pool_patch">The opaque_ref of the given pool_patch</param>
[Deprecated("XenServer 7.1")]
public static Pool_patch get_record(Session session, string _pool_patch)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.pool_patch_get_record(session.opaque_ref, _pool_patch);
else
return new Pool_patch(session.XmlRpcProxy.pool_patch_get_record(session.opaque_ref, _pool_patch ?? "").parse());
}
/// <summary>
/// Get a reference to the pool_patch instance with the specified UUID.
/// First published in XenServer 4.1.
/// Deprecated since XenServer 7.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_uuid">UUID of object to return</param>
[Deprecated("XenServer 7.1")]
public static XenRef<Pool_patch> get_by_uuid(Session session, string _uuid)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.pool_patch_get_by_uuid(session.opaque_ref, _uuid);
else
return XenRef<Pool_patch>.Create(session.XmlRpcProxy.pool_patch_get_by_uuid(session.opaque_ref, _uuid ?? "").parse());
}
/// <summary>
/// Get all the pool_patch instances with the given label.
/// First published in XenServer 4.1.
/// Deprecated since XenServer 7.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_label">label of object to return</param>
[Deprecated("XenServer 7.1")]
public static List<XenRef<Pool_patch>> get_by_name_label(Session session, string _label)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.pool_patch_get_by_name_label(session.opaque_ref, _label);
else
return XenRef<Pool_patch>.Create(session.XmlRpcProxy.pool_patch_get_by_name_label(session.opaque_ref, _label ?? "").parse());
}
/// <summary>
/// Get the uuid field of the given pool_patch.
/// First published in XenServer 4.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pool_patch">The opaque_ref of the given pool_patch</param>
public static string get_uuid(Session session, string _pool_patch)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.pool_patch_get_uuid(session.opaque_ref, _pool_patch);
else
return session.XmlRpcProxy.pool_patch_get_uuid(session.opaque_ref, _pool_patch ?? "").parse();
}
/// <summary>
/// Get the name/label field of the given pool_patch.
/// First published in XenServer 4.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pool_patch">The opaque_ref of the given pool_patch</param>
public static string get_name_label(Session session, string _pool_patch)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.pool_patch_get_name_label(session.opaque_ref, _pool_patch);
else
return session.XmlRpcProxy.pool_patch_get_name_label(session.opaque_ref, _pool_patch ?? "").parse();
}
/// <summary>
/// Get the name/description field of the given pool_patch.
/// First published in XenServer 4.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pool_patch">The opaque_ref of the given pool_patch</param>
public static string get_name_description(Session session, string _pool_patch)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.pool_patch_get_name_description(session.opaque_ref, _pool_patch);
else
return session.XmlRpcProxy.pool_patch_get_name_description(session.opaque_ref, _pool_patch ?? "").parse();
}
/// <summary>
/// Get the version field of the given pool_patch.
/// First published in XenServer 4.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pool_patch">The opaque_ref of the given pool_patch</param>
public static string get_version(Session session, string _pool_patch)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.pool_patch_get_version(session.opaque_ref, _pool_patch);
else
return session.XmlRpcProxy.pool_patch_get_version(session.opaque_ref, _pool_patch ?? "").parse();
}
/// <summary>
/// Get the size field of the given pool_patch.
/// First published in XenServer 4.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pool_patch">The opaque_ref of the given pool_patch</param>
public static long get_size(Session session, string _pool_patch)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.pool_patch_get_size(session.opaque_ref, _pool_patch);
else
return long.Parse(session.XmlRpcProxy.pool_patch_get_size(session.opaque_ref, _pool_patch ?? "").parse());
}
/// <summary>
/// Get the pool_applied field of the given pool_patch.
/// First published in XenServer 4.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pool_patch">The opaque_ref of the given pool_patch</param>
public static bool get_pool_applied(Session session, string _pool_patch)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.pool_patch_get_pool_applied(session.opaque_ref, _pool_patch);
else
return (bool)session.XmlRpcProxy.pool_patch_get_pool_applied(session.opaque_ref, _pool_patch ?? "").parse();
}
/// <summary>
/// Get the host_patches field of the given pool_patch.
/// First published in XenServer 4.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pool_patch">The opaque_ref of the given pool_patch</param>
public static List<XenRef<Host_patch>> get_host_patches(Session session, string _pool_patch)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.pool_patch_get_host_patches(session.opaque_ref, _pool_patch);
else
return XenRef<Host_patch>.Create(session.XmlRpcProxy.pool_patch_get_host_patches(session.opaque_ref, _pool_patch ?? "").parse());
}
/// <summary>
/// Get the after_apply_guidance field of the given pool_patch.
/// First published in XenServer 4.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pool_patch">The opaque_ref of the given pool_patch</param>
public static List<after_apply_guidance> get_after_apply_guidance(Session session, string _pool_patch)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.pool_patch_get_after_apply_guidance(session.opaque_ref, _pool_patch);
else
return Helper.StringArrayToEnumList<after_apply_guidance>(session.XmlRpcProxy.pool_patch_get_after_apply_guidance(session.opaque_ref, _pool_patch ?? "").parse());
}
/// <summary>
/// Get the pool_update field of the given pool_patch.
/// First published in XenServer 7.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pool_patch">The opaque_ref of the given pool_patch</param>
public static XenRef<Pool_update> get_pool_update(Session session, string _pool_patch)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.pool_patch_get_pool_update(session.opaque_ref, _pool_patch);
else
return XenRef<Pool_update>.Create(session.XmlRpcProxy.pool_patch_get_pool_update(session.opaque_ref, _pool_patch ?? "").parse());
}
/// <summary>
/// Get the other_config field of the given pool_patch.
/// First published in XenServer 4.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pool_patch">The opaque_ref of the given pool_patch</param>
public static Dictionary<string, string> get_other_config(Session session, string _pool_patch)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.pool_patch_get_other_config(session.opaque_ref, _pool_patch);
else
return Maps.convert_from_proxy_string_string(session.XmlRpcProxy.pool_patch_get_other_config(session.opaque_ref, _pool_patch ?? "").parse());
}
/// <summary>
/// Set the other_config field of the given pool_patch.
/// First published in XenServer 4.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pool_patch">The opaque_ref of the given pool_patch</param>
/// <param name="_other_config">New value to set</param>
public static void set_other_config(Session session, string _pool_patch, Dictionary<string, string> _other_config)
{
if (session.JsonRpcClient != null)
session.JsonRpcClient.pool_patch_set_other_config(session.opaque_ref, _pool_patch, _other_config);
else
session.XmlRpcProxy.pool_patch_set_other_config(session.opaque_ref, _pool_patch ?? "", Maps.convert_to_proxy_string_string(_other_config)).parse();
}
/// <summary>
/// Add the given key-value pair to the other_config field of the given pool_patch.
/// First published in XenServer 4.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pool_patch">The opaque_ref of the given pool_patch</param>
/// <param name="_key">Key to add</param>
/// <param name="_value">Value to add</param>
public static void add_to_other_config(Session session, string _pool_patch, string _key, string _value)
{
if (session.JsonRpcClient != null)
session.JsonRpcClient.pool_patch_add_to_other_config(session.opaque_ref, _pool_patch, _key, _value);
else
session.XmlRpcProxy.pool_patch_add_to_other_config(session.opaque_ref, _pool_patch ?? "", _key ?? "", _value ?? "").parse();
}
/// <summary>
/// Remove the given key and its corresponding value from the other_config field of the given pool_patch. If the key is not in that Map, then do nothing.
/// First published in XenServer 4.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pool_patch">The opaque_ref of the given pool_patch</param>
/// <param name="_key">Key to remove</param>
public static void remove_from_other_config(Session session, string _pool_patch, string _key)
{
if (session.JsonRpcClient != null)
session.JsonRpcClient.pool_patch_remove_from_other_config(session.opaque_ref, _pool_patch, _key);
else
session.XmlRpcProxy.pool_patch_remove_from_other_config(session.opaque_ref, _pool_patch ?? "", _key ?? "").parse();
}
/// <summary>
/// Apply the selected patch to a host and return its output
/// First published in XenServer 4.1.
/// Deprecated since XenServer 7.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pool_patch">The opaque_ref of the given pool_patch</param>
/// <param name="_host">The host to apply the patch too</param>
[Deprecated("XenServer 7.1")]
public static string apply(Session session, string _pool_patch, string _host)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.pool_patch_apply(session.opaque_ref, _pool_patch, _host);
else
return session.XmlRpcProxy.pool_patch_apply(session.opaque_ref, _pool_patch ?? "", _host ?? "").parse();
}
/// <summary>
/// Apply the selected patch to a host and return its output
/// First published in XenServer 4.1.
/// Deprecated since XenServer 7.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pool_patch">The opaque_ref of the given pool_patch</param>
/// <param name="_host">The host to apply the patch too</param>
[Deprecated("XenServer 7.1")]
public static XenRef<Task> async_apply(Session session, string _pool_patch, string _host)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.async_pool_patch_apply(session.opaque_ref, _pool_patch, _host);
else
return XenRef<Task>.Create(session.XmlRpcProxy.async_pool_patch_apply(session.opaque_ref, _pool_patch ?? "", _host ?? "").parse());
}
/// <summary>
/// Apply the selected patch to all hosts in the pool and return a map of host_ref -> patch output
/// First published in XenServer 4.1.
/// Deprecated since XenServer 7.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pool_patch">The opaque_ref of the given pool_patch</param>
[Deprecated("XenServer 7.1")]
public static void pool_apply(Session session, string _pool_patch)
{
if (session.JsonRpcClient != null)
session.JsonRpcClient.pool_patch_pool_apply(session.opaque_ref, _pool_patch);
else
session.XmlRpcProxy.pool_patch_pool_apply(session.opaque_ref, _pool_patch ?? "").parse();
}
/// <summary>
/// Apply the selected patch to all hosts in the pool and return a map of host_ref -> patch output
/// First published in XenServer 4.1.
/// Deprecated since XenServer 7.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pool_patch">The opaque_ref of the given pool_patch</param>
[Deprecated("XenServer 7.1")]
public static XenRef<Task> async_pool_apply(Session session, string _pool_patch)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.async_pool_patch_pool_apply(session.opaque_ref, _pool_patch);
else
return XenRef<Task>.Create(session.XmlRpcProxy.async_pool_patch_pool_apply(session.opaque_ref, _pool_patch ?? "").parse());
}
/// <summary>
/// Execute the precheck stage of the selected patch on a host and return its output
/// First published in XenServer 4.1.
/// Deprecated since XenServer 7.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pool_patch">The opaque_ref of the given pool_patch</param>
/// <param name="_host">The host to run the prechecks on</param>
[Deprecated("XenServer 7.1")]
public static string precheck(Session session, string _pool_patch, string _host)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.pool_patch_precheck(session.opaque_ref, _pool_patch, _host);
else
return session.XmlRpcProxy.pool_patch_precheck(session.opaque_ref, _pool_patch ?? "", _host ?? "").parse();
}
/// <summary>
/// Execute the precheck stage of the selected patch on a host and return its output
/// First published in XenServer 4.1.
/// Deprecated since XenServer 7.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pool_patch">The opaque_ref of the given pool_patch</param>
/// <param name="_host">The host to run the prechecks on</param>
[Deprecated("XenServer 7.1")]
public static XenRef<Task> async_precheck(Session session, string _pool_patch, string _host)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.async_pool_patch_precheck(session.opaque_ref, _pool_patch, _host);
else
return XenRef<Task>.Create(session.XmlRpcProxy.async_pool_patch_precheck(session.opaque_ref, _pool_patch ?? "", _host ?? "").parse());
}
/// <summary>
/// Removes the patch's files from the server
/// First published in XenServer 4.1.
/// Deprecated since XenServer 7.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pool_patch">The opaque_ref of the given pool_patch</param>
[Deprecated("XenServer 7.1")]
public static void clean(Session session, string _pool_patch)
{
if (session.JsonRpcClient != null)
session.JsonRpcClient.pool_patch_clean(session.opaque_ref, _pool_patch);
else
session.XmlRpcProxy.pool_patch_clean(session.opaque_ref, _pool_patch ?? "").parse();
}
/// <summary>
/// Removes the patch's files from the server
/// First published in XenServer 4.1.
/// Deprecated since XenServer 7.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pool_patch">The opaque_ref of the given pool_patch</param>
[Deprecated("XenServer 7.1")]
public static XenRef<Task> async_clean(Session session, string _pool_patch)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.async_pool_patch_clean(session.opaque_ref, _pool_patch);
else
return XenRef<Task>.Create(session.XmlRpcProxy.async_pool_patch_clean(session.opaque_ref, _pool_patch ?? "").parse());
}
/// <summary>
/// Removes the patch's files from all hosts in the pool, but does not remove the database entries
/// First published in XenServer 6.1.
/// Deprecated since XenServer 7.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pool_patch">The opaque_ref of the given pool_patch</param>
[Deprecated("XenServer 7.1")]
public static void pool_clean(Session session, string _pool_patch)
{
if (session.JsonRpcClient != null)
session.JsonRpcClient.pool_patch_pool_clean(session.opaque_ref, _pool_patch);
else
session.XmlRpcProxy.pool_patch_pool_clean(session.opaque_ref, _pool_patch ?? "").parse();
}
/// <summary>
/// Removes the patch's files from all hosts in the pool, but does not remove the database entries
/// First published in XenServer 6.1.
/// Deprecated since XenServer 7.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pool_patch">The opaque_ref of the given pool_patch</param>
[Deprecated("XenServer 7.1")]
public static XenRef<Task> async_pool_clean(Session session, string _pool_patch)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.async_pool_patch_pool_clean(session.opaque_ref, _pool_patch);
else
return XenRef<Task>.Create(session.XmlRpcProxy.async_pool_patch_pool_clean(session.opaque_ref, _pool_patch ?? "").parse());
}
/// <summary>
/// Removes the patch's files from all hosts in the pool, and removes the database entries. Only works on unapplied patches.
/// First published in XenServer 4.1.
/// Deprecated since XenServer 7.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pool_patch">The opaque_ref of the given pool_patch</param>
[Deprecated("XenServer 7.1")]
public static void destroy(Session session, string _pool_patch)
{
if (session.JsonRpcClient != null)
session.JsonRpcClient.pool_patch_destroy(session.opaque_ref, _pool_patch);
else
session.XmlRpcProxy.pool_patch_destroy(session.opaque_ref, _pool_patch ?? "").parse();
}
/// <summary>
/// Removes the patch's files from all hosts in the pool, and removes the database entries. Only works on unapplied patches.
/// First published in XenServer 4.1.
/// Deprecated since XenServer 7.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pool_patch">The opaque_ref of the given pool_patch</param>
[Deprecated("XenServer 7.1")]
public static XenRef<Task> async_destroy(Session session, string _pool_patch)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.async_pool_patch_destroy(session.opaque_ref, _pool_patch);
else
return XenRef<Task>.Create(session.XmlRpcProxy.async_pool_patch_destroy(session.opaque_ref, _pool_patch ?? "").parse());
}
/// <summary>
/// Removes the patch's files from the specified host
/// First published in XenServer 6.1.
/// Deprecated since XenServer 7.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pool_patch">The opaque_ref of the given pool_patch</param>
/// <param name="_host">The host on which to clean the patch</param>
[Deprecated("XenServer 7.1")]
public static void clean_on_host(Session session, string _pool_patch, string _host)
{
if (session.JsonRpcClient != null)
session.JsonRpcClient.pool_patch_clean_on_host(session.opaque_ref, _pool_patch, _host);
else
session.XmlRpcProxy.pool_patch_clean_on_host(session.opaque_ref, _pool_patch ?? "", _host ?? "").parse();
}
/// <summary>
/// Removes the patch's files from the specified host
/// First published in XenServer 6.1.
/// Deprecated since XenServer 7.1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_pool_patch">The opaque_ref of the given pool_patch</param>
/// <param name="_host">The host on which to clean the patch</param>
[Deprecated("XenServer 7.1")]
public static XenRef<Task> async_clean_on_host(Session session, string _pool_patch, string _host)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.async_pool_patch_clean_on_host(session.opaque_ref, _pool_patch, _host);
else
return XenRef<Task>.Create(session.XmlRpcProxy.async_pool_patch_clean_on_host(session.opaque_ref, _pool_patch ?? "", _host ?? "").parse());
}
/// <summary>
/// Return a list of all the pool_patchs known to the system.
/// First published in XenServer 4.1.
/// Deprecated since XenServer 7.1.
/// </summary>
/// <param name="session">The session</param>
[Deprecated("XenServer 7.1")]
public static List<XenRef<Pool_patch>> get_all(Session session)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.pool_patch_get_all(session.opaque_ref);
else
return XenRef<Pool_patch>.Create(session.XmlRpcProxy.pool_patch_get_all(session.opaque_ref).parse());
}
/// <summary>
/// Get all the pool_patch Records at once, in a single XML RPC call
/// First published in XenServer 4.1.
/// </summary>
/// <param name="session">The session</param>
public static Dictionary<XenRef<Pool_patch>, Pool_patch> get_all_records(Session session)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.pool_patch_get_all_records(session.opaque_ref);
else
return XenRef<Pool_patch>.Create<Proxy_Pool_patch>(session.XmlRpcProxy.pool_patch_get_all_records(session.opaque_ref).parse());
}
/// <summary>
/// Unique identifier/object reference
/// </summary>
public virtual string uuid
{
get { return _uuid; }
set
{
if (!Helper.AreEqual(value, _uuid))
{
_uuid = value;
NotifyPropertyChanged("uuid");
}
}
}
private string _uuid = "";
/// <summary>
/// a human-readable name
/// </summary>
public virtual string name_label
{
get { return _name_label; }
set
{
if (!Helper.AreEqual(value, _name_label))
{
_name_label = value;
NotifyPropertyChanged("name_label");
}
}
}
private string _name_label = "";
/// <summary>
/// a notes field containing human-readable description
/// </summary>
public virtual string name_description
{
get { return _name_description; }
set
{
if (!Helper.AreEqual(value, _name_description))
{
_name_description = value;
NotifyPropertyChanged("name_description");
}
}
}
private string _name_description = "";
/// <summary>
/// Patch version number
/// </summary>
public virtual string version
{
get { return _version; }
set
{
if (!Helper.AreEqual(value, _version))
{
_version = value;
NotifyPropertyChanged("version");
}
}
}
private string _version = "";
/// <summary>
/// Size of the patch
/// </summary>
public virtual long size
{
get { return _size; }
set
{
if (!Helper.AreEqual(value, _size))
{
_size = value;
NotifyPropertyChanged("size");
}
}
}
private long _size = 0;
/// <summary>
/// This patch should be applied across the entire pool
/// </summary>
public virtual bool pool_applied
{
get { return _pool_applied; }
set
{
if (!Helper.AreEqual(value, _pool_applied))
{
_pool_applied = value;
NotifyPropertyChanged("pool_applied");
}
}
}
private bool _pool_applied = false;
/// <summary>
/// This hosts this patch is applied to.
/// </summary>
[JsonConverter(typeof(XenRefListConverter<Host_patch>))]
public virtual List<XenRef<Host_patch>> host_patches
{
get { return _host_patches; }
set
{
if (!Helper.AreEqual(value, _host_patches))
{
_host_patches = value;
NotifyPropertyChanged("host_patches");
}
}
}
private List<XenRef<Host_patch>> _host_patches = new List<XenRef<Host_patch>>() {};
/// <summary>
/// What the client should do after this patch has been applied.
/// </summary>
public virtual List<after_apply_guidance> after_apply_guidance
{
get { return _after_apply_guidance; }
set
{
if (!Helper.AreEqual(value, _after_apply_guidance))
{
_after_apply_guidance = value;
NotifyPropertyChanged("after_apply_guidance");
}
}
}
private List<after_apply_guidance> _after_apply_guidance = new List<after_apply_guidance>() {};
/// <summary>
/// A reference to the associated pool_update object
/// First published in XenServer 7.1.
/// </summary>
[JsonConverter(typeof(XenRefConverter<Pool_update>))]
public virtual XenRef<Pool_update> pool_update
{
get { return _pool_update; }
set
{
if (!Helper.AreEqual(value, _pool_update))
{
_pool_update = value;
NotifyPropertyChanged("pool_update");
}
}
}
private XenRef<Pool_update> _pool_update = new XenRef<Pool_update>("OpaqueRef:NULL");
/// <summary>
/// additional configuration
/// </summary>
[JsonConverter(typeof(StringStringMapConverter))]
public virtual Dictionary<string, string> other_config
{
get { return _other_config; }
set
{
if (!Helper.AreEqual(value, _other_config))
{
_other_config = value;
NotifyPropertyChanged("other_config");
}
}
}
private Dictionary<string, string> _other_config = new Dictionary<string, string>() {};
}
}
| |
using System;
using System.Collections.Generic;
using CoreAnimation;
using CoreGraphics;
using Foundation;
using ObjCRuntime;
using UIKit;
namespace Toggl.Ross.Views.Charting
{
public interface IAnimationDelegate
{
void AnimationDidStart (CABasicAnimation anim);
void AnimationDidStop (CABasicAnimation anim, bool finished);
}
public interface IXYDonutChartDataSource
{
nint NumberOfSlicesInPieChart (XYDonutChart pieChart);
nfloat ValueForSliceAtIndex (XYDonutChart pieChart, nint index);
UIColor ColorForSliceAtIndex (XYDonutChart pieChart, nint index);
string TextForSliceAtIndex (XYDonutChart pieChart, nint index);
}
public class XYDonutChart : UIView, IAnimationDelegate
{
#region Event handlers
public event EventHandler<SelectedSliceEventArgs> WillSelectSliceAtIndex;
public event EventHandler<SelectedSliceEventArgs> DidSelectSliceAtIndex;
public event EventHandler<SelectedSliceEventArgs> WillDeselectSliceAtIndex;
public event EventHandler<SelectedSliceEventArgs> DidDeselectSliceAtIndex;
public event EventHandler<SelectedSliceEventArgs> DidDeselectAllSlices;
#endregion
#region Properties
public IXYDonutChartDataSource DataSource { get; set; }
public nfloat StartPieAngle { get; set; }
public nfloat AnimationSpeed { get; set; }
public UIFont LabelFont { get; set; }
public UIColor LabelColor { get; set; }
public UIColor LabelShadowColor { get; set; }
public nfloat LabelRadius { get; set; }
public nfloat SelectedSliceStroke { get; set; }
public nfloat SelectedSliceOffsetRadius { get; set; }
public bool IsDonut { get; set; }
public nfloat DonutLineStroke { get; set; }
private bool _showPercentage;
public bool ShowPercentage
{
get {
return _showPercentage;
} set {
_showPercentage = value;
var sliceLayers = _pieView.Layer.Sublayers ?? new CALayer[0];
foreach (SliceLayer layer in sliceLayers) {
var textLayer = layer.Sublayers [0];
textLayer.Hidden = !_showPercentage;
updateLabelForLayer (layer, layer.Value);
}
}
}
public bool ShowLabel { get; set; }
private CGPoint _pieCenter;
public CGPoint PieCenter
{
get {
return _pieCenter;
} set {
_pieView.Center = value;
_pieCenter = new CGPoint (_pieView.Frame.Width / 2, _pieView.Frame.Height / 2);
}
}
public nfloat PieRadius
{
get;
set;
}
public UIColor PieBackgroundColor
{
get {
return _pieView.BackgroundColor;
} set {
_pieView.BackgroundColor = value;
}
}
#endregion
int _selectedSliceIndex;
UIView _pieView;
NSTimer _animationTimer;
const int defaultSliceZOrder = 100;
List<CABasicAnimation> _animations;
AnimationDelegate _animationDelegate;
public XYDonutChart (CGRect frame) : base (frame)
{
}
public XYDonutChart ()
{
_pieView = new UIView ();
PieBackgroundColor = UIColor.Clear;
Add (_pieView);
_selectedSliceIndex = -1;
_animations = new List<CABasicAnimation> ();
_animationDelegate = new AnimationDelegate (this);
AnimationSpeed = 0.5f;
StartPieAngle = (nfloat)Math.PI * 3;
SelectedSliceStroke = 2.0f;
LabelColor = UIColor.White;
IsDonut = true;
ShowLabel = true;
ShowPercentage = true;
PieRadius = (nfloat)Math.Min (Bounds.Width / 2, Bounds.Height / 2) - 10;
LabelFont = UIFont.BoldSystemFontOfSize ( (nfloat)Math.Max (PieRadius / 10, 5));
PieCenter = new CGPoint (Bounds.Width / 2, Bounds.Height / 2);
LabelRadius = PieRadius / 2;
DonutLineStroke = PieRadius / 4;
}
public override void LayoutSubviews ()
{
base.LayoutSubviews ();
_pieView.Frame = Bounds;
PieCenter = new CGPoint (Bounds.Width / 2, Bounds.Height / 2);
}
protected override void Dispose (bool disposing)
{
layerPool.Clear ();
base.Dispose (disposing);
CALayer parentLayer = _pieView.Layer;
var pieLayers = parentLayer.Sublayers ?? new CALayer[0];
foreach (SliceLayer layer in pieLayers) {
var shapeLayer = (CAShapeLayer)layer.Sublayers [0];
layerPool.Remove (layer);
shapeLayer.FillColor = PieBackgroundColor.CGColor;
shapeLayer.Path.Dispose ();
layer.Delegate = null;
layer.ZPosition = 0;
layer.Sublayers [1].Hidden = true;
layer.RemoveFromSuperLayer ();
}
}
#region Touch Handing (Selection Notification)
public override void TouchesBegan (NSSet touches, UIEvent evt)
{
TouchesMoved (touches, evt);
}
public override void TouchesMoved (NSSet touches, UIEvent evt)
{
var touch = (UITouch)touches.AnyObject;
CGPoint point = touch.LocationInView (_pieView);
getCurrentSelectedOnTouch (point);
}
public override void TouchesEnded (NSSet touches, UIEvent evt)
{
var touch = (UITouch)touches.AnyObject;
CGPoint point = touch.LocationInView (_pieView);
var selectedIndex = getCurrentSelectedOnTouch (point);
notifyDelegateOfSelectionChangeFrom (_selectedSliceIndex, selectedIndex);
TouchesCancelled (touches, evt);
}
public override void TouchesCancelled (NSSet touches, UIEvent evt)
{
CALayer parentLayer = _pieView.Layer;
var pieLayers = parentLayer.Sublayers;
if (pieLayers == null) {
return;
}
}
private int getCurrentSelectedOnTouch (CGPoint point)
{
int selectedIndex = -1;
CGAffineTransform transform = CGAffineTransform.MakeIdentity ();
CALayer parentLayer = _pieView.Layer;
var pieLayers = parentLayer.Sublayers ?? new CALayer[0];
int idx = 0;
foreach (SliceLayer item in pieLayers) {
var shapeLayer = (CAShapeLayer)item.Sublayers [0];
CGPath path = shapeLayer.Path;
if (path.ContainsPoint (transform, point, false)) {
shapeLayer.LineWidth = SelectedSliceStroke;
shapeLayer.StrokeColor = UIColor.White.CGColor;
shapeLayer.LineJoin = CAShapeLayer.JoinBevel;
item.ZPosition = nfloat.MaxValue;
selectedIndex = idx;
} else {
item.ZPosition = defaultSliceZOrder;
shapeLayer.LineWidth = 0.0f;
}
idx++;
}
return selectedIndex;
}
#endregion
private List<SliceLayer> layerPool = new List<SliceLayer>();
public void ReloadData ()
{
if (DataSource == null) {
return;
}
CALayer parentLayer = _pieView.Layer;
var sliceLayers = parentLayer.Sublayers ?? new CALayer[0];
_selectedSliceIndex = -1;
for (int i = 0; i < sliceLayers.Length; i++) {
var layer = (SliceLayer)sliceLayers [i];
if (layer.IsSelected) {
SetSliceDeselectedAtIndex (i);
layer.Opacity = 1;
}
}
double startToAngle = 0.0f;
double endToAngle = startToAngle;
nint sliceCount = DataSource.NumberOfSlicesInPieChart (this);
nfloat sum = 0.0f;
var values = new nfloat[sliceCount];
for (nint index = 0; index < sliceCount; index++) {
values [index] = DataSource.ValueForSliceAtIndex (this, index);
sum += values [index];
}
var angles = new nfloat[sliceCount];
for (nint index = 0; index < sliceCount; index++) {
nfloat div;
if ( sum == 0.0f) {
div = 0;
} else {
div = values [index] / sum;
}
angles [index] = (nfloat)Math.PI * 2 * div;
}
_pieView.UserInteractionEnabled = false;
var layersToRemove = new List<SliceLayer> ();
bool isOnStart = (sliceLayers.Length == 0 && sliceCount > 0);
nint diff = sliceCount - sliceLayers.Length;
for (int i = 0; i < sliceLayers.Length; i++) {
layersToRemove.Add ((SliceLayer)sliceLayers [i]);
}
bool isOnEnd = (sliceLayers.Length > 0) && (sliceCount == 0 || sum <= 0);
if (isOnEnd) {
foreach (var item in sliceLayers) {
var layer = (SliceLayer)item;
updateLabelForLayer (layer, 0.0f);
layer.CreateArcAnimationForKey ("startAngle", StartPieAngle, StartPieAngle, _animationDelegate);
layer.CreateArcAnimationForKey ("endAngle", StartPieAngle, StartPieAngle, _animationDelegate);
}
return;
}
for (int index = 0; index < sliceCount; index++) {
SliceLayer layer = null;
double angle = angles [index];
endToAngle += angle;
double startFromAngle = StartPieAngle + startToAngle;
double endFromAngle = StartPieAngle + endToAngle;
if (index >= sliceLayers.Length) {
layer = createSliceLayer ();
if (isOnStart) {
startFromAngle = endFromAngle = StartPieAngle;
}
parentLayer.AddSublayer (layer);
diff--;
} else {
var onelayer = (SliceLayer)sliceLayers [index];
if (diff == 0 || onelayer.Value == values [index]) {
layer = onelayer;
layersToRemove.Remove (layer);
} else if (diff > 0) {
layer = createSliceLayer ();
parentLayer.InsertSublayer (layer, index);
diff--;
} else if (diff < 0) {
while (diff < 0) {
onelayer.RemoveFromSuperLayer ();
parentLayer.AddSublayer (onelayer); // TODO: check removing this code with the new Xamarin compiler
diff++;
onelayer = (SliceLayer)sliceLayers [index];
if ( onelayer.Value == values [index] || diff == 0) {
layer = onelayer;
layersToRemove.Remove (layer);
break;
}
}
}
}
layer.Value = values [index];
layer.Percentage = (sum > 0) ? layer.Value / sum : 0;
UIColor color;
if (DataSource.ColorForSliceAtIndex (this, index) != null) {
color = DataSource.ColorForSliceAtIndex (this, index);
} else {
color = UIColor.FromHSBA ((nfloat) (index / 8f % 20.0f / 20.0 + 0.02f), (nfloat) ((index % 8 + 3) / 10.0), (nfloat) (91 / 100.0), 1);
}
layer.ChangeToColor (color);
if (!String.IsNullOrEmpty (DataSource.TextForSliceAtIndex (this, index))) {
layer.Text = DataSource.TextForSliceAtIndex (this, index);
}
updateLabelForLayer (layer, values [index]);
layer.CreateArcAnimationForKey ("startAngle", startFromAngle, startToAngle + StartPieAngle, _animationDelegate);
layer.CreateArcAnimationForKey ("endAngle", endFromAngle, endToAngle + StartPieAngle, _animationDelegate);
startToAngle = endToAngle;
}
foreach (var layer in layersToRemove) {
var shapeLayer = (CAShapeLayer)layer.Sublayers [0];
layerPool.Remove (layer);
shapeLayer.FillColor = PieBackgroundColor.CGColor;
shapeLayer.Path.Dispose ();
layer.Delegate = null;
layer.ZPosition = 0;
layer.Sublayers [1].Hidden = true;
layer.RemoveFromSuperLayer ();
}
layersToRemove.Clear ();
foreach (var layer in sliceLayers) {
layer.ZPosition = defaultSliceZOrder;
}
_pieView.UserInteractionEnabled = true;
}
public void SetSliceSelectedAtIndex (int index)
{
if (SelectedSliceOffsetRadius <= 0) {
return;
}
var layer = (SliceLayer)_pieView.Layer.Sublayers [index];
if (layer != null && !layer.IsSelected) {
layer.CreateAnimationForKeyPath ( layer, "transform.scale", 1.08f);
layer.IsSelected = true;
_selectedSliceIndex = index;
}
foreach (var item in layerPool) {
item.Opacity = (item.IsSelected) ? 1.0f : 0.5f;
}
}
public void SetSliceDeselectedAtIndex (int index)
{
if (SelectedSliceOffsetRadius <= 0) {
return;
}
var layer = (SliceLayer)_pieView.Layer.Sublayers [index];
if (layer != null && layer.IsSelected) {
layer.CreateAnimationForKeyPath ( layer, "transform.scale", 1.0f);
layer.IsSelected = false;
_selectedSliceIndex = -1;
}
}
public void DeselectAllSlices()
{
for (int i = 0; i < layerPool.Count; i++) {
SetSliceDeselectedAtIndex (i);
layerPool[i].Opacity = 1;
}
}
private void notifyDelegateOfSelectionChangeFrom (int previousSelection, int newSelection)
{
if (previousSelection != newSelection) {
if (previousSelection != -1) {
int tempPre = previousSelection;
if (WillDeselectSliceAtIndex != null)
WillDeselectSliceAtIndex.Invoke (this, new SelectedSliceEventArgs () { Index = tempPre });
SetSliceDeselectedAtIndex (tempPre);
if (DidDeselectSliceAtIndex != null)
DidDeselectSliceAtIndex.Invoke (this, new SelectedSliceEventArgs () { Index = tempPre });
}
if (newSelection != -1) {
if (WillSelectSliceAtIndex != null)
WillSelectSliceAtIndex.Invoke (this, new SelectedSliceEventArgs () { Index = newSelection });
SetSliceSelectedAtIndex (newSelection);
_selectedSliceIndex = newSelection;
if (DidSelectSliceAtIndex != null)
DidSelectSliceAtIndex.Invoke (this, new SelectedSliceEventArgs () { Index = newSelection });
}
} else if (newSelection != -1) {
var layer = (SliceLayer)_pieView.Layer.Sublayers [newSelection];
if (SelectedSliceOffsetRadius > 0 && layer != null) {
if (layer.IsSelected) {
if (WillDeselectSliceAtIndex != null)
WillDeselectSliceAtIndex.Invoke (this, new SelectedSliceEventArgs () { Index = newSelection });
SetSliceDeselectedAtIndex (newSelection);
if (newSelection != -1 && DidDeselectSliceAtIndex != null)
DidDeselectSliceAtIndex.Invoke (this, new SelectedSliceEventArgs () { Index = newSelection });
} else {
if (WillSelectSliceAtIndex != null)
WillSelectSliceAtIndex.Invoke (this, new SelectedSliceEventArgs () { Index = newSelection });
SetSliceSelectedAtIndex (newSelection);
if (newSelection != -1 && DidSelectSliceAtIndex != null)
DidSelectSliceAtIndex.Invoke (this, new SelectedSliceEventArgs () { Index = newSelection });
}
}
}
if (newSelection == -1 || newSelection == previousSelection) {
if ( DidDeselectAllSlices != null) {
DidDeselectAllSlices.Invoke (this, new SelectedSliceEventArgs ());
}
foreach (var item in layerPool) {
item.Opacity = 1.0f;
}
}
}
private int containsLayer ( List<SliceLayer> list, SliceLayer layer)
{
int result = -1;
for (int i = 0; i < list.Count; i++) {
var item = list [i];
if (layer.StartAngle.CompareTo ( item.StartAngle) == 0 &&
layer.EndAngle.CompareTo ( item.EndAngle) == 0) {
result = i;
}
}
return result;
}
private bool equals ( nfloat a, nfloat b)
{
return (Math.Abs (a - b) < nfloat.Epsilon);
}
#region Animation Delegate + Run Loop Timer
[Export ("updateTimerFired:")]
private void UpdateTimerFired (NSTimer timer)
{
if (_pieView.Layer.Sublayers == null) {
return;
}
foreach (var layer in _pieView.Layer.Sublayers) {
if (layer.PresentationLayer != null) {
var shapeLayer = (CAShapeLayer)layer.Sublayers [0];
var currentStartAngle = (NSNumber)layer.PresentationLayer.ValueForKey (new NSString ("startAngle"));
var interpolatedStartAngle = currentStartAngle.NFloatValue;
var currentEndAngle = (NSNumber)layer.PresentationLayer.ValueForKey (new NSString ("endAngle"));
var interpolatedEndAngle = currentEndAngle.NFloatValue;
var path = CGPathCreateArc (_pieCenter, PieRadius, interpolatedStartAngle, interpolatedEndAngle);
shapeLayer.Path = path;
path.Dispose ();
CALayer labelLayer = layer.Sublayers [1];
nfloat interpolatedMidAngle = (interpolatedEndAngle + interpolatedStartAngle) / 2;
labelLayer.Position = new CGPoint (_pieCenter.X + LabelRadius * (nfloat)Math.Cos (interpolatedMidAngle), _pieCenter.Y + LabelRadius * (nfloat)Math.Sin (interpolatedMidAngle));
}
}
}
public void AnimationDidStart (CABasicAnimation anim)
{
if (_animationTimer == null) {
const double timeInterval = 1.0f / 60.0f;
_animationTimer = NSTimer.CreateTimer (timeInterval, this, new Selector ("updateTimerFired:"),null, true);
NSRunLoop.Main.AddTimer (_animationTimer, NSRunLoopMode.Common);
}
_animations.Add (anim);
}
public void AnimationDidStop (CABasicAnimation anim, bool isFinished)
{
_animations.Remove (anim);
if (_animations.Count == 0) {
_animationTimer.Invalidate ();
_animationTimer = null;
}
}
#endregion
#region Pie Layer Creation Method
private CGPath CGPathCreateArc (CGPoint center, nfloat radius, nfloat startAngle, nfloat endAngle)
{
var path = new CGPath ();
CGPath resultPath;
if (IsDonut) {
path.AddArc (center.X, center.Y, radius, startAngle, endAngle, false);
resultPath = path.CopyByStrokingPath (DonutLineStroke, CGLineCap.Butt, CGLineJoin.Miter, 10);
path.Dispose ();
} else {
path.MoveToPoint (center.X, center.Y);
path.AddArc (center.X, center.Y, radius, startAngle, endAngle, false);
path.CloseSubpath ();
resultPath = path;
}
return resultPath;
}
private SliceLayer createSliceLayer ()
{
var pieLayer = new SliceLayer ();
pieLayer.Frame = _pieView.Frame;
var arcLayer = new CAShapeLayer ();
arcLayer.ZPosition = 0;
arcLayer.StrokeColor = null;
pieLayer.AddSublayer (arcLayer);
var textLayer = new CATextLayer ();
textLayer.ContentsScale = UIScreen.MainScreen.Scale;
CGFont font = CGFont.CreateWithFontName (LabelFont.Name);
if (font != null) {
textLayer.SetFont (font);
font.Dispose ();
}
textLayer.FontSize = LabelFont.PointSize;
textLayer.AnchorPoint = new CGPoint (0.5f, 0.5f);
textLayer.AlignmentMode = CATextLayer.AlignmentCenter;
textLayer.BackgroundColor = UIColor.Clear.CGColor;
textLayer.ForegroundColor = LabelColor.CGColor;
if (LabelShadowColor != null) {
textLayer.ShadowColor = LabelShadowColor.CGColor;
textLayer.ShadowOffset = CGSize.Empty;
textLayer.ShadowOpacity = 1.0f;
textLayer.ShadowRadius = 2.0f;
}
CGSize size = ((NSString)"0").StringSize (LabelFont);
textLayer.Frame = new CGRect (new CGPoint (0, 0), size);
textLayer.Position = new CGPoint (_pieCenter.X + LabelRadius * (nfloat)Math.Cos (0), _pieCenter.Y + LabelRadius * (nfloat)Math.Sin (0));
pieLayer.AddSublayer (textLayer);
layerPool.Add (pieLayer);
return pieLayer;
}
#endregion
private void updateLabelForLayer (SliceLayer sliceLayer, nfloat value)
{
var textLayer = (CATextLayer)sliceLayer.Sublayers [1];
textLayer.Hidden = !ShowLabel;
if (!ShowLabel) {
return;
}
String label = ShowPercentage ? sliceLayer.Percentage.ToString ("P1") : sliceLayer.Value.ToString ("0.00");
var nsString = new NSString (label);
CGSize size = nsString.GetSizeUsingAttributes (new UIStringAttributes () { Font = LabelFont });
if (Math.PI * 2 * LabelRadius * sliceLayer.Percentage < Math.Max (size.Width, size.Height) || value <= 0) {
textLayer.String = "";
} else {
textLayer.String = label;
textLayer.Bounds = new CGRect (0, 0, size.Width, size.Height);
}
}
}
sealed class AnimationDelegate : CAAnimationDelegate
{
private readonly IAnimationDelegate _owner;
public AnimationDelegate (IAnimationDelegate owner)
{
_owner = owner;
}
public override void AnimationStarted (CAAnimation anim)
{
_owner.AnimationDidStart ((CABasicAnimation)anim);
}
public override void AnimationStopped (CAAnimation anim, bool finished)
{
_owner.AnimationDidStop ((CABasicAnimation)anim, finished);
}
}
class SliceLayer : CALayer
{
[Export ("startAngle")]
public nfloat StartAngle { get; set; }
[Export ("endAngle")]
public nfloat EndAngle { get; set; }
public nfloat Value { get; set; }
public nfloat Percentage { get; set; }
public bool IsSelected { get; set; }
public string Text { get; set; }
public SliceLayer ()
{
}
public SliceLayer (IntPtr ptr) : base (ptr)
{
}
[Export ("initWithLayer:")]
public SliceLayer (CALayer other) : base (other)
{
}
public override void Clone (CALayer other)
{
base.Clone ( other);
var sliceLayer = other as SliceLayer;
if (sliceLayer != null) {
StartAngle = sliceLayer.StartAngle;
EndAngle = sliceLayer.EndAngle;
Value = sliceLayer.Value;
Percentage = sliceLayer.Percentage;
IsSelected = sliceLayer.IsSelected;
Text = sliceLayer.Text;
}
}
[Export ("needsDisplayForKey:")]
static bool NeedsDisplayForKey (NSString key)
{
switch (key.ToString ()) {
case "startAngle":
return true;
case "endAngle":
return true;
default:
return CALayer.NeedsDisplayForKey (key);
}
}
public override NSObject ActionForKey (string eventKey)
{
// disable implicit animations and use explicit animations with MoveToPosition function
// More control and implicit animations don't works good
// need more tests!
if (eventKey == "position" || eventKey == "fillColor") {
return null;
}
return base.ActionForKey (eventKey);
}
public void CreateArcAnimationForKey (string key, double fromValue, double toValue, CAAnimationDelegate @delegate)
{
var _fromValue = new NSNumber (fromValue);
var _toValue = new NSNumber (toValue);
var _key = new NSString (key);
var arcAnimation = CABasicAnimation.FromKeyPath (key);
var currentAngle = _fromValue;
if (PresentationLayer != null) {
currentAngle = (NSNumber)PresentationLayer.ValueForKey (_key);
}
arcAnimation.Duration = 1.0f;
arcAnimation.From = currentAngle;
arcAnimation.To = _toValue;
arcAnimation.Delegate = @delegate;
arcAnimation.TimingFunction = CAMediaTimingFunction.FromName (CAMediaTimingFunction.Default);
AddAnimation (arcAnimation, key);
SetValueForKey (_toValue, _key);
}
public void MoveToPosition (CGPoint newPos)
{
var posAnim = CABasicAnimation.FromKeyPath ("position");
posAnim.From = NSValue.FromCGPoint (Position);
posAnim.To = NSValue.FromCGPoint (newPos);
posAnim.Duration = ( newPos.IsEmpty ) ? 0.2f : 0.4f;
posAnim.TimingFunction = CAMediaTimingFunction.FromName (CAMediaTimingFunction.Default);
AddAnimation (posAnim, "position");
Position = newPos;
}
public void ChangeToColor (UIColor color)
{
var shapeLayer = (CAShapeLayer)Sublayers [0];
var colorAnim = CABasicAnimation.FromKeyPath ("fillColor");
colorAnim.From = NSObject.FromObject (shapeLayer.FillColor);
colorAnim.To = NSObject.FromObject (color.CGColor);
colorAnim.Duration = 1.0f;
colorAnim.TimingFunction = CAMediaTimingFunction.FromName (CAMediaTimingFunction.Default);
shapeLayer.AddAnimation (colorAnim, "fillColor");
shapeLayer.FillColor = color.CGColor;
}
public void CreateAnimationForKeyPath ( CALayer layer, string key, float toValue )
{
var _fromValue = layer.ValueForKeyPath ( new NSString ( key));
var _toValue = new NSNumber (toValue);
var _key = new NSString (key);
var barAnimation = CABasicAnimation.FromKeyPath (key);
var currentValue = _fromValue;
if (layer.PresentationLayer != null) {
currentValue = layer.PresentationLayer.ValueForKeyPath (_key);
}
barAnimation.From = currentValue;
barAnimation.To = _toValue;
barAnimation.TimingFunction = CAMediaTimingFunction.FromName (CAMediaTimingFunction.Default);
layer.AddAnimation (barAnimation, key);
layer.SetValueForKeyPath (_toValue, _key);
}
}
public sealed class SelectedSliceEventArgs : EventArgs
{
public int Index { get; set; }
}
}
| |
//-----------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
namespace System.Activities
{
using System.Activities.DynamicUpdate;
using System.Activities.Runtime;
using System.Activities.Validation;
using System.Collections.Generic;
using System.Runtime;
using System.Runtime.Serialization;
public abstract class CodeActivity : Activity
{
protected CodeActivity()
{
}
protected internal sealed override Version ImplementationVersion
{
get
{
return null;
}
set
{
if (value != null)
{
throw FxTrace.Exception.AsError(new NotSupportedException());
}
}
}
[IgnoreDataMember]
[Fx.Tag.KnownXamlExternal]
protected sealed override Func<Activity> Implementation
{
get
{
return null;
}
set
{
if (value != null)
{
throw FxTrace.Exception.AsError(new NotSupportedException());
}
}
}
protected abstract void Execute(CodeActivityContext context);
sealed internal override void InternalExecute(ActivityInstance instance, ActivityExecutor executor, BookmarkManager bookmarkManager)
{
CodeActivityContext context = executor.CodeActivityContextPool.Acquire();
try
{
context.Initialize(instance, executor);
Execute(context);
}
finally
{
context.Dispose();
executor.CodeActivityContextPool.Release(context);
}
}
sealed internal override void InternalCancel(ActivityInstance instance, ActivityExecutor executor, BookmarkManager bookmarkManager)
{
Fx.Assert("Cancel should never be called on CodeActivity since it's synchronous");
}
sealed internal override void InternalAbort(ActivityInstance instance, ActivityExecutor executor, Exception terminationReason)
{
// no-op, this is only called if an exception is thrown out of execute
}
sealed internal override void OnInternalCacheMetadata(bool createEmptyBindings)
{
CodeActivityMetadata metadata = new CodeActivityMetadata(this, this.GetParentEnvironment(), createEmptyBindings);
CacheMetadata(metadata);
metadata.Dispose();
if (this.RuntimeArguments == null || this.RuntimeArguments.Count == 0)
{
this.SkipArgumentResolution = true;
}
}
internal sealed override void OnInternalCreateDynamicUpdateMap(DynamicUpdateMapBuilder.Finalizer finalizer,
DynamicUpdateMapBuilder.IDefinitionMatcher matcher, Activity originalActivity)
{
}
protected sealed override void OnCreateDynamicUpdateMap(UpdateMapMetadata metadata, Activity originalActivity)
{
// NO OP
}
protected sealed override void CacheMetadata(ActivityMetadata metadata)
{
throw FxTrace.Exception.AsError(new InvalidOperationException(SR.WrongCacheMetadataForCodeActivity));
}
protected virtual void CacheMetadata(CodeActivityMetadata metadata)
{
// We bypass the metadata call to avoid the null checks
SetArgumentsCollection(ReflectedInformation.GetArguments(this), metadata.CreateEmptyBindings);
}
}
public abstract class CodeActivity<TResult> : Activity<TResult>
{
protected CodeActivity()
{
}
protected internal sealed override Version ImplementationVersion
{
get
{
return null;
}
set
{
if (value != null)
{
throw FxTrace.Exception.AsError(new NotSupportedException());
}
}
}
[IgnoreDataMember]
[Fx.Tag.KnownXamlExternal]
protected sealed override Func<Activity> Implementation
{
get
{
return null;
}
set
{
if (value != null)
{
throw FxTrace.Exception.AsError(new NotSupportedException());
}
}
}
protected abstract TResult Execute(CodeActivityContext context);
sealed internal override void InternalExecute(ActivityInstance instance, ActivityExecutor executor, BookmarkManager bookmarkManager)
{
CodeActivityContext context = executor.CodeActivityContextPool.Acquire();
try
{
context.Initialize(instance, executor);
TResult executeResult = Execute(context);
this.Result.Set(context, executeResult);
}
finally
{
context.Dispose();
executor.CodeActivityContextPool.Release(context);
}
}
sealed internal override void InternalCancel(ActivityInstance instance, ActivityExecutor executor, BookmarkManager bookmarkManager)
{
Fx.Assert("Cancel should never be called on CodeActivity<T> since it's synchronous");
}
sealed internal override void InternalAbort(ActivityInstance instance, ActivityExecutor executor, Exception terminationReason)
{
// no-op, this is only called if an exception is thrown out of execute
}
sealed internal override void OnInternalCacheMetadataExceptResult(bool createEmptyBindings)
{
CodeActivityMetadata metadata = new CodeActivityMetadata(this, this.GetParentEnvironment(), createEmptyBindings);
CacheMetadata(metadata);
metadata.Dispose();
if (this.RuntimeArguments == null || this.RuntimeArguments.Count == 0 ||
// If there's an argument named "Result", we can safely assume it's the actual result
// argument, because Activity<T> will raise a validation error if it's not.
(this.RuntimeArguments.Count == 1 && this.RuntimeArguments[0].Name == Argument.ResultValue))
{
this.SkipArgumentResolution = true;
}
}
sealed internal override TResult InternalExecuteInResolutionContext(CodeActivityContext context)
{
Fx.Assert(this.SkipArgumentResolution, "This method should only be called if SkipArgumentResolution is true");
return Execute(context);
}
internal sealed override void OnInternalCreateDynamicUpdateMap(DynamicUpdateMapBuilder.Finalizer finalizer,
DynamicUpdateMapBuilder.IDefinitionMatcher matcher, Activity originalActivity)
{
}
protected sealed override void OnCreateDynamicUpdateMap(UpdateMapMetadata metadata, Activity originalActivity)
{
// NO OP
}
protected sealed override void CacheMetadata(ActivityMetadata metadata)
{
throw FxTrace.Exception.AsError(new InvalidOperationException(SR.WrongCacheMetadataForCodeActivity));
}
protected virtual void CacheMetadata(CodeActivityMetadata metadata)
{
// We bypass the metadata call to avoid the null checks
SetArgumentsCollection(ReflectedInformation.GetArguments(this), metadata.CreateEmptyBindings);
}
}
}
| |
// Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gax = Google.Api.Gax;
using gaxgrpc = Google.Api.Gax.Grpc;
using gaxgrpccore = Google.Api.Gax.Grpc.GrpcCore;
using gciv = Google.Cloud.Iam.V1;
using gcl = Google.Cloud.Location;
using proto = Google.Protobuf;
using grpccore = Grpc.Core;
using grpcinter = Grpc.Core.Interceptors;
using sys = System;
using scg = System.Collections.Generic;
using sco = System.Collections.ObjectModel;
using st = System.Threading;
using stt = System.Threading.Tasks;
namespace Testing.Mixins
{
/// <summary>Settings for <see cref="MixinServiceClient"/> instances.</summary>
public sealed partial class MixinServiceSettings : gaxgrpc::ServiceSettingsBase
{
/// <summary>Get a new instance of the default <see cref="MixinServiceSettings"/>.</summary>
/// <returns>A new instance of the default <see cref="MixinServiceSettings"/>.</returns>
public static MixinServiceSettings GetDefault() => new MixinServiceSettings();
/// <summary>Constructs a new <see cref="MixinServiceSettings"/> object with default settings.</summary>
public MixinServiceSettings()
{
}
// TEST_START
private MixinServiceSettings(MixinServiceSettings existing) : base(existing)
{
gax::GaxPreconditions.CheckNotNull(existing, nameof(existing));
MethodSettings = existing.MethodSettings;
LocationsSettings = existing.LocationsSettings;
IAMPolicySettings = existing.IAMPolicySettings;
OnCopy(existing);
}
// TEST_END
partial void OnCopy(MixinServiceSettings existing);
/// <summary>
/// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to <c>MixinServiceClient.Method</c>
/// and <c>MixinServiceClient.MethodAsync</c>.
/// </summary>
/// <remarks>
/// <list type="bullet">
/// <item><description>This call will not be retried.</description></item>
/// <item><description>No timeout is applied.</description></item>
/// </list>
/// </remarks>
public gaxgrpc::CallSettings MethodSettings { get; set; } = gaxgrpc::CallSettings.FromExpiration(gax::Expiration.None);
// TEST_START
/// <summary>
/// The settings to use for the <see cref="gcl::LocationsClient"/> associated with the client.
/// </summary>
public gcl::LocationsSettings LocationsSettings { get; set; } = gcl::LocationsSettings.GetDefault();
/// <summary>
/// The settings to use for the <see cref="gciv::IAMPolicyClient"/> associated with the client.
/// </summary>
public gciv::IAMPolicySettings IAMPolicySettings { get; set; } = gciv::IAMPolicySettings.GetDefault();
// TEST_END
/// <summary>Creates a deep clone of this object, with all the same property values.</summary>
/// <returns>A deep clone of this <see cref="MixinServiceSettings"/> object.</returns>
public MixinServiceSettings Clone() => new MixinServiceSettings(this);
}
/// <summary>
/// Builder class for <see cref="MixinServiceClient"/> to provide simple configuration of credentials, endpoint etc.
/// </summary>
public sealed partial class MixinServiceClientBuilder : gaxgrpc::ClientBuilderBase<MixinServiceClient>
{
/// <summary>The settings to use for RPCs, or <c>null</c> for the default settings.</summary>
public MixinServiceSettings Settings { get; set; }
/// <summary>Creates a new builder with default settings.</summary>
public MixinServiceClientBuilder()
{
UseJwtAccessWithScopes = MixinServiceClient.UseJwtAccessWithScopes;
}
partial void InterceptBuild(ref MixinServiceClient client);
partial void InterceptBuildAsync(st::CancellationToken cancellationToken, ref stt::Task<MixinServiceClient> task);
/// <summary>Builds the resulting client.</summary>
public override MixinServiceClient Build()
{
MixinServiceClient client = null;
InterceptBuild(ref client);
return client ?? BuildImpl();
}
/// <summary>Builds the resulting client asynchronously.</summary>
public override stt::Task<MixinServiceClient> BuildAsync(st::CancellationToken cancellationToken = default)
{
stt::Task<MixinServiceClient> task = null;
InterceptBuildAsync(cancellationToken, ref task);
return task ?? BuildAsyncImpl(cancellationToken);
}
private MixinServiceClient BuildImpl()
{
Validate();
grpccore::CallInvoker callInvoker = CreateCallInvoker();
return MixinServiceClient.Create(callInvoker, Settings);
}
private async stt::Task<MixinServiceClient> BuildAsyncImpl(st::CancellationToken cancellationToken)
{
Validate();
grpccore::CallInvoker callInvoker = await CreateCallInvokerAsync(cancellationToken).ConfigureAwait(false);
return MixinServiceClient.Create(callInvoker, Settings);
}
/// <summary>Returns the endpoint for this builder type, used if no endpoint is otherwise specified.</summary>
protected override string GetDefaultEndpoint() => MixinServiceClient.DefaultEndpoint;
/// <summary>
/// Returns the default scopes for this builder type, used if no scopes are otherwise specified.
/// </summary>
protected override scg::IReadOnlyList<string> GetDefaultScopes() => MixinServiceClient.DefaultScopes;
/// <summary>Returns the channel pool to use when no other options are specified.</summary>
protected override gaxgrpc::ChannelPool GetChannelPool() => MixinServiceClient.ChannelPool;
/// <summary>Returns the default <see cref="gaxgrpc::GrpcAdapter"/>to use if not otherwise specified.</summary>
protected override gaxgrpc::GrpcAdapter DefaultGrpcAdapter => gaxgrpccore::GrpcCoreAdapter.Instance;
}
/// <summary>MixinService client wrapper, for convenient use.</summary>
/// <remarks>
/// </remarks>
public abstract partial class MixinServiceClient
{
/// <summary>
/// The default endpoint for the MixinService service, which is a host of "mixins.example.com" and a port of
/// 443.
/// </summary>
public static string DefaultEndpoint { get; } = "mixins.example.com:443";
/// <summary>The default MixinService scopes.</summary>
/// <remarks>
/// The default MixinService scopes are:
/// <list type="bullet">
/// <item><description>scope1</description></item>
/// <item><description>scope2</description></item>
/// </list>
/// </remarks>
public static scg::IReadOnlyList<string> DefaultScopes { get; } = new sco::ReadOnlyCollection<string>(new string[] { "scope1", "scope2", });
internal static gaxgrpc::ChannelPool ChannelPool { get; } = new gaxgrpc::ChannelPool(DefaultScopes, UseJwtAccessWithScopes);
internal static bool UseJwtAccessWithScopes
{
get
{
bool useJwtAccessWithScopes = true;
MaybeUseJwtAccessWithScopes(ref useJwtAccessWithScopes);
return useJwtAccessWithScopes;
}
}
static partial void MaybeUseJwtAccessWithScopes(ref bool useJwtAccessWithScopes);
/// <summary>
/// Asynchronously creates a <see cref="MixinServiceClient"/> using the default credentials, endpoint and
/// settings. To specify custom credentials or other settings, use <see cref="MixinServiceClientBuilder"/>.
/// </summary>
/// <param name="cancellationToken">
/// The <see cref="st::CancellationToken"/> to use while creating the client.
/// </param>
/// <returns>The task representing the created <see cref="MixinServiceClient"/>.</returns>
public static stt::Task<MixinServiceClient> CreateAsync(st::CancellationToken cancellationToken = default) =>
new MixinServiceClientBuilder().BuildAsync(cancellationToken);
/// <summary>
/// Synchronously creates a <see cref="MixinServiceClient"/> using the default credentials, endpoint and
/// settings. To specify custom credentials or other settings, use <see cref="MixinServiceClientBuilder"/>.
/// </summary>
/// <returns>The created <see cref="MixinServiceClient"/>.</returns>
public static MixinServiceClient Create() => new MixinServiceClientBuilder().Build();
/// <summary>
/// Creates a <see cref="MixinServiceClient"/> which uses the specified call invoker for remote operations.
/// </summary>
/// <param name="callInvoker">
/// The <see cref="grpccore::CallInvoker"/> for remote operations. Must not be null.
/// </param>
/// <param name="settings">Optional <see cref="MixinServiceSettings"/>.</param>
/// <returns>The created <see cref="MixinServiceClient"/>.</returns>
internal static MixinServiceClient Create(grpccore::CallInvoker callInvoker, MixinServiceSettings settings = null)
{
gax::GaxPreconditions.CheckNotNull(callInvoker, nameof(callInvoker));
grpcinter::Interceptor interceptor = settings?.Interceptor;
if (interceptor != null)
{
callInvoker = grpcinter::CallInvokerExtensions.Intercept(callInvoker, interceptor);
}
MixinService.MixinServiceClient grpcClient = new MixinService.MixinServiceClient(callInvoker);
return new MixinServiceClientImpl(grpcClient, settings);
}
/// <summary>
/// Shuts down any channels automatically created by <see cref="Create()"/> and
/// <see cref="CreateAsync(st::CancellationToken)"/>. Channels which weren't automatically created are not
/// affected.
/// </summary>
/// <remarks>
/// After calling this method, further calls to <see cref="Create()"/> and
/// <see cref="CreateAsync(st::CancellationToken)"/> will create new channels, which could in turn be shut down
/// by another call to this method.
/// </remarks>
/// <returns>A task representing the asynchronous shutdown operation.</returns>
public static stt::Task ShutdownDefaultChannelsAsync() => ChannelPool.ShutdownChannelsAsync();
/// <summary>The underlying gRPC MixinService client</summary>
public virtual MixinService.MixinServiceClient GrpcClient => throw new sys::NotImplementedException();
// TEST_START
/// <summary>The <see cref="gcl::LocationsClient"/> associated with this client.</summary>
public virtual gcl::LocationsClient LocationsClient => throw new sys::NotImplementedException();
/// <summary>The <see cref="gciv::IAMPolicyClient"/> associated with this client.</summary>
public virtual gciv::IAMPolicyClient IAMPolicyClient => throw new sys::NotImplementedException();
// TEST_END
/// <summary>
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual Response Method(Request request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<Response> MethodAsync(Request request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<Response> MethodAsync(Request request, st::CancellationToken cancellationToken) =>
MethodAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
}
/// <summary>MixinService client wrapper implementation, for convenient use.</summary>
/// <remarks>
/// </remarks>
public sealed partial class MixinServiceClientImpl : MixinServiceClient
{
private readonly gaxgrpc::ApiCall<Request, Response> _callMethod;
// TEST_START
/// <summary>
/// Constructs a client wrapper for the MixinService service, with the specified gRPC client and settings.
/// </summary>
/// <param name="grpcClient">The underlying gRPC client.</param>
/// <param name="settings">The base <see cref="MixinServiceSettings"/> used within this client.</param>
public MixinServiceClientImpl(MixinService.MixinServiceClient grpcClient, MixinServiceSettings settings)
{
GrpcClient = grpcClient;
MixinServiceSettings effectiveSettings = settings ?? MixinServiceSettings.GetDefault();
gaxgrpc::ClientHelper clientHelper = new gaxgrpc::ClientHelper(effectiveSettings);
LocationsClient = new gcl::LocationsClientImpl(grpcClient.CreateLocationsClient(), effectiveSettings.LocationsSettings);
IAMPolicyClient = new gciv::IAMPolicyClientImpl(grpcClient.CreateIAMPolicyClient(), effectiveSettings.IAMPolicySettings);
_callMethod = clientHelper.BuildApiCall<Request, Response>(grpcClient.MethodAsync, grpcClient.Method, effectiveSettings.MethodSettings);
Modify_ApiCall(ref _callMethod);
Modify_MethodApiCall(ref _callMethod);
OnConstruction(grpcClient, effectiveSettings, clientHelper);
}
// TEST_END
partial void Modify_ApiCall<TRequest, TResponse>(ref gaxgrpc::ApiCall<TRequest, TResponse> call) where TRequest : class, proto::IMessage<TRequest> where TResponse : class, proto::IMessage<TResponse>;
partial void Modify_MethodApiCall(ref gaxgrpc::ApiCall<Request, Response> call);
partial void OnConstruction(MixinService.MixinServiceClient grpcClient, MixinServiceSettings effectiveSettings, gaxgrpc::ClientHelper clientHelper);
/// <summary>The underlying gRPC MixinService client</summary>
public override MixinService.MixinServiceClient GrpcClient { get; }
/// <summary>The <see cref="gcl::LocationsClient"/> associated with this client.</summary>
public override gcl::LocationsClient LocationsClient { get; }
/// <summary>The <see cref="gciv::IAMPolicyClient"/> associated with this client.</summary>
public override gciv::IAMPolicyClient IAMPolicyClient { get; }
partial void Modify_Request(ref Request request, ref gaxgrpc::CallSettings settings);
/// <summary>
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public override Response Method(Request request, gaxgrpc::CallSettings callSettings = null)
{
Modify_Request(ref request, ref callSettings);
return _callMethod.Sync(request, callSettings);
}
/// <summary>
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public override stt::Task<Response> MethodAsync(Request request, gaxgrpc::CallSettings callSettings = null)
{
Modify_Request(ref request, ref callSettings);
return _callMethod.Async(request, callSettings);
}
}
// TEST_START
public static partial class MixinService
{
public partial class MixinServiceClient
{
/// <summary>
/// Creates a new instance of <see cref="gcl::Locations.LocationsClient"/> using the same call invoker as
/// this client.
/// </summary>
/// <returns>
/// A new <see cref="gcl::Locations.LocationsClient"/> for the same target as this client.
/// </returns>
public virtual gcl::Locations.LocationsClient CreateLocationsClient() =>
new gcl::Locations.LocationsClient(CallInvoker);
/// <summary>
/// Creates a new instance of <see cref="gciv::IAMPolicy.IAMPolicyClient"/> using the same call invoker as
/// this client.
/// </summary>
/// <returns>
/// A new <see cref="gciv::IAMPolicy.IAMPolicyClient"/> for the same target as this client.
/// </returns>
public virtual gciv::IAMPolicy.IAMPolicyClient CreateIAMPolicyClient() =>
new gciv::IAMPolicy.IAMPolicyClient(CallInvoker);
}
}
// TEST_END
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Moq;
using NuGet.Test.Mocks;
using Xunit;
using NuGet.Test.Utility;
namespace NuGet.Test
{
public class LocalPackageRepositoryTest
{
[Fact]
public void GetPackageFilesOnlyDetectsFilesWithPackageExtension()
{
// Arrange
var mockFileSystem = new MockProjectSystem();
mockFileSystem.AddFile("foo.nupkg");
mockFileSystem.AddFile("bar.zip");
var repository = new LocalPackageRepository(new DefaultPackagePathResolver(mockFileSystem),
mockFileSystem);
// Act
var files = repository.GetPackageFiles().ToList();
// Assert
Assert.Equal(1, files.Count);
Assert.Equal("foo.nupkg", files[0]);
}
[Fact]
public void GetPackageFilesDetectsFilesInRootOrFirstLevelOfFolders()
{
// Arrange
var mockFileSystem = new MockProjectSystem();
mockFileSystem.AddFile("P1.nupkg");
mockFileSystem.AddFile("bar.zip");
mockFileSystem.AddFile(PathFixUtility.FixPath(@"baz\P2.nupkg"));
mockFileSystem.AddFile(PathFixUtility.FixPath(@"A\B\P3.nupkg"));
mockFileSystem.AddFile(PathFixUtility.FixPath(@"A\P4.nupkg"));
var repository = new LocalPackageRepository(new DefaultPackagePathResolver(mockFileSystem),
mockFileSystem);
// Act
var files = repository.GetPackageFiles().ToList();
// Assert
Assert.Equal(3, files.Count);
Assert.Equal(PathFixUtility.FixPath(@"baz\P2.nupkg"), files[0]);
Assert.Equal(PathFixUtility.FixPath(@"A\P4.nupkg"), files[1]);
Assert.Equal("P1.nupkg", files[2]);
}
[Fact]
public void GetPackagesOnlyRetrievesPackageFilesWhereLastModifiedIsOutOfDate()
{
// Arrange
var mockFileSystem = new Mock<MockProjectSystem>() { CallBase = true };
var lastModified = new Dictionary<string, DateTimeOffset>();
mockFileSystem.Setup(m => m.GetLastModified("P1.nupkg")).Returns(() => lastModified["P1.nupkg"]);
mockFileSystem.Setup(m => m.GetLastModified("P2.nupkg")).Returns(() => lastModified["P2.nupkg"]);
mockFileSystem.Object.AddFile("P1.nupkg");
mockFileSystem.Object.AddFile("P2.nupkg");
var repository = new LocalPackageRepository(new DefaultPackagePathResolver(mockFileSystem.Object),
mockFileSystem.Object);
var results = new List<string>();
Func<string, IPackage> openPackage = p =>
{
results.Add(p);
string id = Path.GetFileNameWithoutExtension(p);
return PackageUtility.CreatePackage(id, "1.0");
};
// Populate cache
lastModified["P1.nupkg"] = GetDateTimeOffset(seconds: 30);
lastModified["P2.nupkg"] = GetDateTimeOffset(seconds: 30);
repository.GetPackages(openPackage).ToList();
// Verify that both packages have been created from the file system
Assert.Equal(2, results.Count);
results.Clear();
// Act
lastModified["P1.nupkg"] = GetDateTimeOffset(seconds: 35);
lastModified["P2.nupkg"] = GetDateTimeOffset(seconds: 30);
repository.GetPackages(openPackage).ToList();
// Assert
Assert.Equal(results.Count, 1);
Assert.Equal(results[0], "P1.nupkg");
}
[Fact]
public void FindPackageMatchesExactVersionIfSideBySideIsDisabled()
{
// Arrange
var fileSystem = new MockFileSystem();
fileSystem.AddFile(PathFixUtility.FixPath(@"A\A.nupkg"));
var repository = new LocalPackageRepository(new DefaultPackagePathResolver(fileSystem, useSideBySidePaths: false), fileSystem, enableCaching: false);
var searchedPaths = new List<string>();
Func<string, IPackage> openPackage = p =>
{
searchedPaths.Add(p);
return PackageUtility.CreatePackage("A", "1.1");
};
// Act and Assert
IPackage result = repository.FindPackage(openPackage, "A", new SemanticVersion("1.0"));
Assert.Null(result);
Assert.Equal(PathFixUtility.FixPath(@"A\A.nupkg"), searchedPaths.Single());
searchedPaths.Clear();
result = repository.FindPackage(openPackage, "A", new SemanticVersion("0.8"));
Assert.Null(result);
Assert.Equal(PathFixUtility.FixPath(@"A\A.nupkg"), searchedPaths.Single());
searchedPaths.Clear();
result = repository.FindPackage(openPackage, "A", new SemanticVersion("1.1"));
Assert.Equal("A", result.Id);
Assert.Equal(new SemanticVersion("1.1"), result.Version);
}
[Fact]
public void FindPackageMatchesExactVersionIfSideBySideIsEnabled()
{
// Arrange
var fileSystem = new MockFileSystem();
fileSystem.AddFile(PathFixUtility.FixPath(@"A.1.1\A.1.1.nupkg"));
var repository = new LocalPackageRepository(new DefaultPackagePathResolver(fileSystem, useSideBySidePaths: true), fileSystem, enableCaching: false);
var searchedPaths = new List<string>();
Func<string, IPackage> openPackage = p =>
{
searchedPaths.Add(p);
return PackageUtility.CreatePackage("A", "1.1");
};
// Act and Assert
IPackage result = repository.FindPackage(openPackage, "A", new SemanticVersion("1.0"));
Assert.Null(result);
Assert.False(searchedPaths.Any());
result = repository.FindPackage(openPackage, "A", new SemanticVersion("0.8"));
Assert.Null(result);
Assert.False(searchedPaths.Any());
result = repository.FindPackage(openPackage, "A", new SemanticVersion("1.1"));
Assert.Equal(PathFixUtility.FixPath(@"A.1.1\A.1.1.nupkg"), searchedPaths.Single());
Assert.Equal("A", result.Id);
Assert.Equal(new SemanticVersion("1.1"), result.Version);
}
[Fact]
public void FindPackageVerifiesPackageFileExistsOnFileSystemWhenCaching()
{
// Arrange
var fileSystem = new MockFileSystem();
fileSystem.AddFile(@"A.1.0.0.nupkg");
var repository = new LocalPackageRepository(new DefaultPackagePathResolver(fileSystem, useSideBySidePaths: true), fileSystem, enableCaching: true);
var searchedPaths = new List<string>();
Func<string, IPackage> openPackage = p =>
{
searchedPaths.Add(p);
return PackageUtility.CreatePackage("A", "1.0");
};
// Act - 1
IPackage result = repository.FindPackage(openPackage, "A", new SemanticVersion("1.0"));
// Assert - 1
Assert.NotNull(result);
Assert.Equal("A", result.Id);
Assert.Equal(new SemanticVersion("1.0"), result.Version);
// Act - 2
fileSystem.DeleteFile("A.1.0.0.nupkg");
result = repository.FindPackage(openPackage, "A", new SemanticVersion("1.0"));
// Assert - 2
Assert.Null(result);
}
[Fact]
public void AddPackageAddsFileToFileSystem()
{
// Arrange
var mockFileSystem = new MockProjectSystem();
var repository = new LocalPackageRepository(new DefaultPackagePathResolver(mockFileSystem),
mockFileSystem);
IPackage package = PackageUtility.CreatePackage("A", "1.0");
// Act
repository.AddPackage(package);
// Assert
Assert.True(mockFileSystem.FileExists(PathFixUtility.FixPath(@"A.1.0\A.1.0.nupkg")));
}
[Fact]
public void RemovePackageRemovesPackageFileAndDirectoryAndRoot()
{
// Arrange
var mockFileSystem = new MockProjectSystem();
mockFileSystem.AddFile(PathFixUtility.FixPath(@"A.1.0\A.1.0.nupkg"));
var repository = new LocalPackageRepository(new DefaultPackagePathResolver(mockFileSystem),
mockFileSystem);
IPackage package = PackageUtility.CreatePackage("A", "1.0");
// Act
repository.RemovePackage(package);
// Assert
Assert.Equal(3, mockFileSystem.Deleted.Count);
Assert.True(mockFileSystem.Deleted.Contains(mockFileSystem.Root));
Assert.True(mockFileSystem.Deleted.Contains(Path.Combine(mockFileSystem.Root, "A.1.0")));
Assert.True(mockFileSystem.Deleted.Contains(Path.Combine(mockFileSystem.Root, PathFixUtility.FixPath(@"A.1.0\A.1.0.nupkg"))));
}
[Fact]
public void RemovePackageDoesNotRemovesRootIfNotEmpty()
{
// Arrange
var mockFileSystem = new MockProjectSystem();
mockFileSystem.AddFile(PathFixUtility.FixPath(@"A.1.0\A.1.0.nupkg"));
mockFileSystem.AddFile(PathFixUtility.FixPath(@"B.1.0\B.1.0.nupkg"));
var repository = new LocalPackageRepository(new DefaultPackagePathResolver(mockFileSystem),
mockFileSystem);
IPackage package = PackageUtility.CreatePackage("A", "1.0");
// Act
repository.RemovePackage(package);
// Assert
Assert.Equal(2, mockFileSystem.Deleted.Count);
Assert.True(mockFileSystem.Deleted.Contains(Path.Combine(mockFileSystem.Root, @"A.1.0")));
Assert.True(mockFileSystem.Deleted.Contains(Path.Combine(mockFileSystem.Root, PathFixUtility.FixPath(@"A.1.0\A.1.0.nupkg"))));
}
[Fact]
public void FindPackagesByIdReturnsEmptySequenceIfNoPackagesWithSpecifiedIdAreFound()
{
// Arramge
var fileSystem = new MockFileSystem();
var pathResolver = new DefaultPackagePathResolver(fileSystem);
var localPackageRepository = new LocalPackageRepository(pathResolver, fileSystem);
// Act
var packages = localPackageRepository.FindPackagesById("Foo");
// Assert
Assert.Empty(packages);
}
[Fact]
public void FindPackagesByIdFindsPackagesWithSpecifiedId()
{
// Arramge
var fileSystem = new MockFileSystem();
fileSystem.AddFile(PathFixUtility.FixPath(@"Foo.1.0\Foo.1.0.nupkg"));
fileSystem.AddFile(PathFixUtility.FixPath(@"Foo.2.0.0\Foo.2.0.0.nupkg"));
var foo_10 = PackageUtility.CreatePackage("Foo", "1.0");
var foo_20 = PackageUtility.CreatePackage("Foo", "2.0.0");
var package_dictionary = new Dictionary<String, IPackage>
{
{ PathFixUtility.FixPath(@"Foo.1.0\Foo.1.0.nupkg"), foo_10},
{ PathFixUtility.FixPath(@"Foo.2.0.0\Foo.2.0.0.nupkg"), foo_20}
};
var localPackageRepository = new MockLocalRepository(fileSystem, path =>
{
IPackage retval;
package_dictionary.TryGetValue(path, out retval);
return retval;
});
// Act
var packages = localPackageRepository.FindPackagesById("Foo").ToList();
// Assert
Assert.Equal(new[] { foo_10, foo_20 }, packages);
}
[Fact]
public void FindPackagesByIdIgnoresPartialIdMatches()
{
// Arramge
var fileSystem = new MockFileSystem();
fileSystem.AddFile(PathFixUtility.FixPath(@"Foo.1.0\Foo.1.0.nupkg"));
fileSystem.AddFile(PathFixUtility.FixPath(@"Foo.2.0.0\Foo.2.0.0.nupkg"));
fileSystem.AddFile(PathFixUtility.FixPath(@"Foo.Baz.2.0.0\Foo.Baz.2.0.0.nupkg"));
var foo_10 = PackageUtility.CreatePackage("Foo", "1.0");
var foo_20 = PackageUtility.CreatePackage("Foo", "2.0.0");
var fooBaz_20 = PackageUtility.CreatePackage("Foo.Baz", "2.0.0");
var package_dictionary = new Dictionary<string, IPackage>(){
{ PathFixUtility.FixPath(@"Foo.1.0\Foo.1.0.nupkg"),foo_10},
{ PathFixUtility.FixPath(@"Foo.2.0.0\Foo.2.0.0.nupkg"), foo_20},
{ PathFixUtility.FixPath(@"Foo.Baz.2.0.0\Foo.Baz.2.0.0.nupkg"), fooBaz_20}
};
var localPackageRepository = new MockLocalRepository(fileSystem, path =>
{
IPackage retval;
package_dictionary.TryGetValue(path, out retval);
return retval;
});
// Act
var packages = localPackageRepository.FindPackagesById("Foo").ToList();
// Assert
Assert.Equal(new[] { foo_10, foo_20 }, packages);
}
private static DateTimeOffset GetDateTimeOffset(int seconds)
{
return new DateTimeOffset(1000, 10, 1, 0, 0, seconds, TimeSpan.Zero);
}
private class MockLocalRepository : LocalPackageRepository
{
private readonly Func<string, IPackage> _openPackage;
public MockLocalRepository(IFileSystem fileSystem, Func<string, IPackage> openPackage = null)
: base(new DefaultPackagePathResolver(fileSystem), fileSystem)
{
_openPackage = openPackage;
}
protected override IPackage OpenPackage(string path)
{
return _openPackage(path);
}
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Editor.CSharp.Outlining;
using Microsoft.CodeAnalysis.Editor.Implementation.Outlining;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Test.Utilities;
using Roslyn.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Outlining
{
public class TypeDeclarationOutlinerTests :
AbstractOutlinerTests<TypeDeclarationSyntax>
{
internal override IEnumerable<OutliningSpan> GetRegions(TypeDeclarationSyntax typeDecl)
{
var outliner = new TypeDeclarationOutliner();
return outliner.GetOutliningSpans(typeDecl, CancellationToken.None).WhereNotNull();
}
[Fact, Trait(Traits.Feature, Traits.Features.Outlining)]
public void TestClass()
{
var tree = ParseLines("class C",
"{",
"}");
var typeDecl = tree.DigToFirstTypeDeclaration();
var actualRegion = GetRegion(typeDecl);
var expectedRegion = new OutliningSpan(
TextSpan.FromBounds(7, 13),
TextSpan.FromBounds(0, 13),
CSharpOutliningHelpers.Ellipsis,
autoCollapse: false);
AssertRegion(expectedRegion, actualRegion);
}
[Fact, Trait(Traits.Feature, Traits.Features.Outlining)]
public void TestClassWithLeadingComments()
{
var tree = ParseLines("// Foo",
"// Bar",
"class C",
"{",
"}");
var typeDecl = tree.DigToFirstTypeDeclaration();
var actualRegions = GetRegions(typeDecl).ToList();
Assert.Equal(2, actualRegions.Count);
var expectedRegion1 = new OutliningSpan(
TextSpan.FromBounds(0, 14),
"// Foo ...",
autoCollapse: true);
AssertRegion(expectedRegion1, actualRegions[0]);
var expectedRegion2 = new OutliningSpan(
TextSpan.FromBounds(23, 29),
TextSpan.FromBounds(16, 29),
CSharpOutliningHelpers.Ellipsis,
autoCollapse: false);
AssertRegion(expectedRegion2, actualRegions[1]);
}
[Fact, Trait(Traits.Feature, Traits.Features.Outlining)]
public void TestClassWithNestedComments()
{
var tree = ParseLines("class C",
"{",
" // Foo",
" // Bar",
"}");
var typeDecl = tree.DigToFirstTypeDeclaration();
var actualRegions = GetRegions(typeDecl).ToList();
Assert.Equal(2, actualRegions.Count);
var expectedRegion1 = new OutliningSpan(
TextSpan.FromBounds(7, 33),
TextSpan.FromBounds(0, 33),
CSharpOutliningHelpers.Ellipsis,
autoCollapse: false);
AssertRegion(expectedRegion1, actualRegions[0]);
var expectedRegion2 = new OutliningSpan(
TextSpan.FromBounds(14, 30),
"// Foo ...",
autoCollapse: true);
AssertRegion(expectedRegion2, actualRegions[1]);
}
[Fact, Trait(Traits.Feature, Traits.Features.Outlining)]
public void TestInterface()
{
var tree = ParseLines("interface I",
"{",
"}");
var typeDecl = tree.DigToFirstTypeDeclaration();
var actualRegion = GetRegion(typeDecl);
var expectedRegion = new OutliningSpan(
TextSpan.FromBounds(11, 17),
TextSpan.FromBounds(0, 17),
CSharpOutliningHelpers.Ellipsis,
autoCollapse: false);
AssertRegion(expectedRegion, actualRegion);
}
[Fact, Trait(Traits.Feature, Traits.Features.Outlining)]
public void TestInterfaceWithLeadingComments()
{
var tree = ParseLines("// Foo",
"// Bar",
"interface I",
"{",
"}");
var typeDecl = tree.DigToFirstTypeDeclaration();
var actualRegions = GetRegions(typeDecl).ToList();
Assert.Equal(2, actualRegions.Count);
var expectedRegion1 = new OutliningSpan(
TextSpan.FromBounds(0, 14),
"// Foo ...",
autoCollapse: true);
AssertRegion(expectedRegion1, actualRegions[0]);
var expectedRegion2 = new OutliningSpan(
TextSpan.FromBounds(27, 33),
TextSpan.FromBounds(16, 33),
CSharpOutliningHelpers.Ellipsis,
autoCollapse: false);
AssertRegion(expectedRegion2, actualRegions[1]);
}
[Fact, Trait(Traits.Feature, Traits.Features.Outlining)]
public void TestInterfaceWithNestedComments()
{
var tree = ParseLines("interface I",
"{",
" // Foo",
" // Bar",
"}");
var typeDecl = tree.DigToFirstTypeDeclaration();
var actualRegions = GetRegions(typeDecl).ToList();
Assert.Equal(2, actualRegions.Count);
var expectedRegion1 = new OutliningSpan(
TextSpan.FromBounds(11, 37),
TextSpan.FromBounds(0, 37),
CSharpOutliningHelpers.Ellipsis,
autoCollapse: false);
AssertRegion(expectedRegion1, actualRegions[0]);
var expectedRegion2 = new OutliningSpan(
TextSpan.FromBounds(18, 34),
"// Foo ...",
autoCollapse: true);
AssertRegion(expectedRegion2, actualRegions[1]);
}
[Fact, Trait(Traits.Feature, Traits.Features.Outlining)]
public void TestStruct()
{
var tree = ParseLines("struct S",
"{",
"}");
var typeDecl = tree.DigToFirstTypeDeclaration();
var actualRegion = GetRegion(typeDecl);
var expectedRegion = new OutliningSpan(
TextSpan.FromBounds(8, 14),
TextSpan.FromBounds(0, 14),
CSharpOutliningHelpers.Ellipsis,
autoCollapse: false);
AssertRegion(expectedRegion, actualRegion);
}
[Fact, Trait(Traits.Feature, Traits.Features.Outlining)]
public void TestStructWithLeadingComments()
{
var tree = ParseLines("// Foo",
"// Bar",
"struct S",
"{",
"}");
var typeDecl = tree.DigToFirstTypeDeclaration();
var actualRegions = GetRegions(typeDecl).ToList();
Assert.Equal(2, actualRegions.Count);
var expectedRegion1 = new OutliningSpan(
TextSpan.FromBounds(0, 14),
"// Foo ...",
autoCollapse: true);
AssertRegion(expectedRegion1, actualRegions[0]);
var expectedRegion2 = new OutliningSpan(
TextSpan.FromBounds(24, 30),
TextSpan.FromBounds(16, 30),
CSharpOutliningHelpers.Ellipsis,
autoCollapse: false);
AssertRegion(expectedRegion2, actualRegions[1]);
}
[Fact, Trait(Traits.Feature, Traits.Features.Outlining)]
public void TestStructWithNestedComments()
{
var tree = ParseLines("struct S",
"{",
" // Foo",
" // Bar",
"}");
var typeDecl = tree.DigToFirstTypeDeclaration();
var actualRegions = GetRegions(typeDecl).ToList();
Assert.Equal(2, actualRegions.Count);
var expectedRegion1 = new OutliningSpan(
TextSpan.FromBounds(8, 34),
TextSpan.FromBounds(0, 34),
CSharpOutliningHelpers.Ellipsis,
autoCollapse: false);
AssertRegion(expectedRegion1, actualRegions[0]);
var expectedRegion2 = new OutliningSpan(
TextSpan.FromBounds(15, 31),
"// Foo ...",
autoCollapse: true);
AssertRegion(expectedRegion2, actualRegions[1]);
}
}
}
| |
// 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;
public struct VT
{
public int[,] int2darr;
public int[, ,] int3darr;
public int[,] int2darr_b;
public int[, ,] int3darr_b;
public int[,] int2darr_c;
public int[, ,] int3darr_c;
}
public class CL
{
public int[,] int2darr = { { 0, -1 }, { 0, 0 } };
public int[, ,] int3darr = { { { 0, 0 } }, { { 0, -1 } }, { { 0, 0 } } };
public int[,] int2darr_b = { { 0, 1 }, { 0, 0 } };
public int[, ,] int3darr_b = { { { 0, 0 } }, { { 0, 1 } }, { { 0, 0 } } };
public int[,] int2darr_c = { { 0, 49 }, { 0, 0 } };
public int[, ,] int3darr_c = { { { 0, 0 } }, { { 0, 49 } }, { { 0, 0 } } };
}
public class intMDArrTest
{
static int[,] int2darr = { { 0, -1 }, { 0, 0 } };
static int[, ,] int3darr = { { { 0, 0 } }, { { 0, -1 } }, { { 0, 0 } } };
static int[][,] ja1 = new int[2][,];
static int[][, ,] ja2 = new int[2][, ,];
static int[,] int2darr_b = { { 0, 1 }, { 0, 0 } };
static int[, ,] int3darr_b = { { { 0, 0 } }, { { 0, 1 } }, { { 0, 0 } } };
static int[][,] ja1_b = new int[2][,];
static int[][, ,] ja2_b = new int[2][, ,];
static int[,] int2darr_c = { { 0, 49 }, { 0, 0 } };
static int[, ,] int3darr_c = { { { 0, 0 } }, { { 0, 49 } }, { { 0, 0 } } };
static int[][,] ja1_c = new int[2][,];
static int[][, ,] ja2_c = new int[2][, ,];
public static int Main()
{
bool pass = true;
VT vt1;
vt1.int2darr = new int[,] { { 0, -1 }, { 0, 0 } };
vt1.int3darr = new int[,,] { { { 0, 0 } }, { { 0, -1 } }, { { 0, 0 } } };
vt1.int2darr_b = new int[,] { { 0, 1 }, { 0, 0 } };
vt1.int3darr_b = new int[,,] { { { 0, 0 } }, { { 0, 1 } }, { { 0, 0 } } };
vt1.int2darr_c = new int[,] { { 0, 49 }, { 0, 0 } };
vt1.int3darr_c = new int[,,] { { { 0, 0 } }, { { 0, 49 } }, { { 0, 0 } } };
CL cl1 = new CL();
ja1[0] = new int[,] { { 0, -1 }, { 0, 0 } };
ja2[1] = new int[,,] { { { 0, 0 } }, { { 0, -1 } }, { { 0, 0 } } };
ja1_b[0] = new int[,] { { 0, 1 }, { 0, 0 } };
ja2_b[1] = new int[,,] { { { 0, 0 } }, { { 0, 1 } }, { { 0, 0 } } };
ja1_c[0] = new int[,] { { 0, 49 }, { 0, 0 } };
ja2_c[1] = new int[,,] { { { 0, 0 } }, { { 0, 49 } }, { { 0, 0 } } };
int result = -1;
// 2D
if (result != int2darr[0, 1])
{
Console.WriteLine("ERROR:");
Console.WriteLine("result is: {0}", result);
Console.WriteLine("2darr[0, 1] is: {0}", int2darr[0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (result != vt1.int2darr[0, 1])
{
Console.WriteLine("ERROR:");
Console.WriteLine("result is: {0}", result);
Console.WriteLine("vt1.int2darr[0, 1] is: {0}", vt1.int2darr[0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (result != cl1.int2darr[0, 1])
{
Console.WriteLine("ERROR:");
Console.WriteLine("result is: {0}", result);
Console.WriteLine("cl1.int2darr[0, 1] is: {0}", cl1.int2darr[0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (result != ja1[0][0, 1])
{
Console.WriteLine("ERROR:");
Console.WriteLine("result is: {0}", result);
Console.WriteLine("ja1[0][0, 1] is: {0}", ja1[0][0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
// 3D
if (result != int3darr[1, 0, 1])
{
Console.WriteLine("ERROR:");
Console.WriteLine("result is: {0}", result);
Console.WriteLine("int3darr[1,0,1] is: {0}", int3darr[1, 0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (result != vt1.int3darr[1, 0, 1])
{
Console.WriteLine("ERROR:");
Console.WriteLine("result is: {0}", result);
Console.WriteLine("vt1.int3darr[1,0,1] is: {0}", vt1.int3darr[1, 0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (result != cl1.int3darr[1, 0, 1])
{
Console.WriteLine("ERROR:");
Console.WriteLine("result is: {0}", result);
Console.WriteLine("cl1.int3darr[1,0,1] is: {0}", cl1.int3darr[1, 0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (result != ja2[1][1, 0, 1])
{
Console.WriteLine("ERROR:");
Console.WriteLine("result is: {0}", result);
Console.WriteLine("ja2[1][1,0,1] is: {0}", ja2[1][1, 0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
//Int32ToBool tests
bool Bool_result = true;
// 2D
if (Bool_result != Convert.ToBoolean(int2darr[0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Bool_result is: {0}", Bool_result);
Console.WriteLine("2darr[0, 1] is: {0}", int2darr[0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (Bool_result != Convert.ToBoolean(vt1.int2darr[0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Bool_result is: {0}", Bool_result);
Console.WriteLine("vt1.int2darr[0, 1] is: {0}", vt1.int2darr[0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (Bool_result != Convert.ToBoolean(cl1.int2darr[0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Bool_result is: {0}", Bool_result);
Console.WriteLine("cl1.int2darr[0, 1] is: {0}", cl1.int2darr[0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (Bool_result != Convert.ToBoolean(ja1[0][0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Bool_result is: {0}", Bool_result);
Console.WriteLine("ja1[0][0, 1] is: {0}", ja1[0][0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
// 3D
if (Bool_result != Convert.ToBoolean(int3darr[1, 0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Bool_result is: {0}", Bool_result);
Console.WriteLine("int3darr[1,0,1] is: {0}", int3darr[1, 0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (Bool_result != Convert.ToBoolean(vt1.int3darr[1, 0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Bool_result is: {0}", Bool_result);
Console.WriteLine("vt1.int3darr[1,0,1] is: {0}", vt1.int3darr[1, 0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (Bool_result != Convert.ToBoolean(cl1.int3darr[1, 0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Bool_result is: {0}", Bool_result);
Console.WriteLine("cl1.int3darr[1,0,1] is: {0}", cl1.int3darr[1, 0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (Bool_result != Convert.ToBoolean(ja2[1][1, 0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Bool_result is: {0}", Bool_result);
Console.WriteLine("ja2[1][1,0,1] is: {0}", ja2[1][1, 0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
//Int32ToByte tests
byte Byte_result = 1;
// 2D
if (Byte_result != Convert.ToByte(int2darr_b[0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Byte_result is: {0}", Byte_result);
Console.WriteLine("2darr[0, 1] is: {0}", int2darr_b[0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (Byte_result != Convert.ToByte(vt1.int2darr_b[0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Byte_result is: {0}", Byte_result);
Console.WriteLine("vt1.int2darr_b[0, 1] is: {0}", vt1.int2darr_b[0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (Byte_result != Convert.ToByte(cl1.int2darr_b[0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Byte_result is: {0}", Byte_result);
Console.WriteLine("cl1.int2darr_b[0, 1] is: {0}", cl1.int2darr_b[0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (Byte_result != Convert.ToByte(ja1_b[0][0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Byte_result is: {0}", Byte_result);
Console.WriteLine("ja1_b[0][0, 1] is: {0}", ja1_b[0][0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
// 3D
if (Byte_result != Convert.ToByte(int3darr_b[1, 0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Byte_result is: {0}", Byte_result);
Console.WriteLine("int3darr_b[1,0,1] is: {0}", int3darr_b[1, 0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (Byte_result != Convert.ToByte(vt1.int3darr_b[1, 0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Byte_result is: {0}", Byte_result);
Console.WriteLine("vt1.int3darr_b[1,0,1] is: {0}", vt1.int3darr_b[1, 0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (Byte_result != Convert.ToByte(cl1.int3darr_b[1, 0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Byte_result is: {0}", Byte_result);
Console.WriteLine("cl1.int3darr_b[1,0,1] is: {0}", cl1.int3darr_b[1, 0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (Byte_result != Convert.ToByte(ja2_b[1][1, 0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Byte_result is: {0}", Byte_result);
Console.WriteLine("ja2_b[1][1,0,1] is: {0}", ja2_b[1][1, 0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
//Int32ToDecimal tests
decimal Decimal_result = -1;
// 2D
if (Decimal_result != Convert.ToDecimal(int2darr[0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Decimal_result is: {0}", Decimal_result);
Console.WriteLine("2darr[0, 1] is: {0}", int2darr[0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (Decimal_result != Convert.ToDecimal(vt1.int2darr[0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Decimal_result is: {0}", Decimal_result);
Console.WriteLine("vt1.int2darr[0, 1] is: {0}", vt1.int2darr[0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (Decimal_result != Convert.ToDecimal(cl1.int2darr[0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Decimal_result is: {0}", Decimal_result);
Console.WriteLine("cl1.int2darr[0, 1] is: {0}", cl1.int2darr[0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (Decimal_result != Convert.ToDecimal(ja1[0][0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Decimal_result is: {0}", Decimal_result);
Console.WriteLine("ja1[0][0, 1] is: {0}", ja1[0][0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
// 3D
if (Decimal_result != Convert.ToDecimal(int3darr[1, 0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Decimal_result is: {0}", Decimal_result);
Console.WriteLine("int3darr[1,0,1] is: {0}", int3darr[1, 0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (Decimal_result != Convert.ToDecimal(vt1.int3darr[1, 0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Decimal_result is: {0}", Decimal_result);
Console.WriteLine("vt1.int3darr[1,0,1] is: {0}", vt1.int3darr[1, 0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (Decimal_result != Convert.ToDecimal(cl1.int3darr[1, 0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Decimal_result is: {0}", Decimal_result);
Console.WriteLine("cl1.int3darr[1,0,1] is: {0}", cl1.int3darr[1, 0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (Decimal_result != Convert.ToDecimal(ja2[1][1, 0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Decimal_result is: {0}", Decimal_result);
Console.WriteLine("ja2[1][1,0,1] is: {0}", ja2[1][1, 0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
//Int32ToDouble
double Double_result = -1;
// 2D
if (Double_result != Convert.ToDouble(int2darr[0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Double_result is: {0}", Double_result);
Console.WriteLine("2darr[0, 1] is: {0}", int2darr[0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (Double_result != Convert.ToDouble(vt1.int2darr[0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Double_result is: {0}", Double_result);
Console.WriteLine("vt1.int2darr[0, 1] is: {0}", vt1.int2darr[0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (Double_result != Convert.ToDouble(cl1.int2darr[0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Double_result is: {0}", Double_result);
Console.WriteLine("cl1.int2darr[0, 1] is: {0}", cl1.int2darr[0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (Double_result != Convert.ToDouble(ja1[0][0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Double_result is: {0}", Double_result);
Console.WriteLine("ja1[0][0, 1] is: {0}", ja1[0][0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
// 3D
if (Double_result != Convert.ToDouble(int3darr[1, 0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Double_result is: {0}", Double_result);
Console.WriteLine("int3darr[1,0,1] is: {0}", int3darr[1, 0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (Double_result != Convert.ToDouble(vt1.int3darr[1, 0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Double_result is: {0}", Double_result);
Console.WriteLine("vt1.int3darr[1,0,1] is: {0}", vt1.int3darr[1, 0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (Double_result != Convert.ToDouble(cl1.int3darr[1, 0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Double_result is: {0}", Double_result);
Console.WriteLine("cl1.int3darr[1,0,1] is: {0}", cl1.int3darr[1, 0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (Double_result != Convert.ToDouble(ja2[1][1, 0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Double_result is: {0}", Double_result);
Console.WriteLine("ja2[1][1,0,1] is: {0}", ja2[1][1, 0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
//Int32ToSingle
float Single_result = -1;
// 2D
if (Single_result != Convert.ToSingle(int2darr[0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Single_result is: {0}", Single_result);
Console.WriteLine("2darr[0, 1] is: {0}", int2darr[0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (Single_result != Convert.ToSingle(vt1.int2darr[0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Single_result is: {0}", Single_result);
Console.WriteLine("vt1.int2darr[0, 1] is: {0}", vt1.int2darr[0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (Single_result != Convert.ToSingle(cl1.int2darr[0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Single_result is: {0}", Single_result);
Console.WriteLine("cl1.int2darr[0, 1] is: {0}", cl1.int2darr[0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (Single_result != Convert.ToSingle(ja1[0][0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Single_result is: {0}", Single_result);
Console.WriteLine("ja1[0][0, 1] is: {0}", ja1[0][0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
// 3D
if (Single_result != Convert.ToSingle(int3darr[1, 0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Single_result is: {0}", Single_result);
Console.WriteLine("int3darr[1,0,1] is: {0}", int3darr[1, 0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (Single_result != Convert.ToSingle(vt1.int3darr[1, 0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Single_result is: {0}", Single_result);
Console.WriteLine("vt1.int3darr[1,0,1] is: {0}", vt1.int3darr[1, 0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (Single_result != Convert.ToSingle(cl1.int3darr[1, 0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Single_result is: {0}", Single_result);
Console.WriteLine("cl1.int3darr[1,0,1] is: {0}", cl1.int3darr[1, 0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (Single_result != Convert.ToSingle(ja2[1][1, 0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Single_result is: {0}", Single_result);
Console.WriteLine("ja2[1][1,0,1] is: {0}", ja2[1][1, 0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
//Int32ToInt64 tests
long Int64_result = -1;
// 2D
if (Int64_result != Convert.ToInt64(int2darr[0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Int64_result is: {0}", Int64_result);
Console.WriteLine("2darr[0, 1] is: {0}", int2darr[0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (Int64_result != Convert.ToInt64(vt1.int2darr[0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Int64_result is: {0}", Int64_result);
Console.WriteLine("vt1.int2darr[0, 1] is: {0}", vt1.int2darr[0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (Int64_result != Convert.ToInt64(cl1.int2darr[0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Int64_result is: {0}", Int64_result);
Console.WriteLine("cl1.int2darr[0, 1] is: {0}", cl1.int2darr[0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (Int64_result != Convert.ToInt64(ja1[0][0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Int64_result is: {0}", Int64_result);
Console.WriteLine("ja1[0][0, 1] is: {0}", ja1[0][0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
// 3D
if (Int64_result != Convert.ToInt64(int3darr[1, 0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Int64_result is: {0}", Int64_result);
Console.WriteLine("int3darr[1,0,1] is: {0}", int3darr[1, 0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (Int64_result != Convert.ToInt64(vt1.int3darr[1, 0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Int64_result is: {0}", Int64_result);
Console.WriteLine("vt1.int3darr[1,0,1] is: {0}", vt1.int3darr[1, 0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (Int64_result != Convert.ToInt64(cl1.int3darr[1, 0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Int64_result is: {0}", Int64_result);
Console.WriteLine("cl1.int3darr[1,0,1] is: {0}", cl1.int3darr[1, 0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (Int64_result != Convert.ToInt64(ja2[1][1, 0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Int64_result is: {0}", Int64_result);
Console.WriteLine("ja2[1][1,0,1] is: {0}", ja2[1][1, 0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
//Int32ToSByte tests
sbyte SByte_result = -1;
// 2D
if (SByte_result != Convert.ToSByte(int2darr[0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("SByte_result is: {0}", SByte_result);
Console.WriteLine("2darr[0, 1] is: {0}", int2darr[0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (SByte_result != Convert.ToSByte(vt1.int2darr[0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("SByte_result is: {0}", SByte_result);
Console.WriteLine("vt1.int2darr[0, 1] is: {0}", vt1.int2darr[0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (SByte_result != Convert.ToSByte(cl1.int2darr[0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("SByte_result is: {0}", SByte_result);
Console.WriteLine("cl1.int2darr[0, 1] is: {0}", cl1.int2darr[0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (SByte_result != Convert.ToSByte(ja1[0][0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("SByte_result is: {0}", SByte_result);
Console.WriteLine("ja1[0][0, 1] is: {0}", ja1[0][0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
// 3D
if (SByte_result != Convert.ToSByte(int3darr[1, 0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("SByte_result is: {0}", SByte_result);
Console.WriteLine("int3darr[1,0,1] is: {0}", int3darr[1, 0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (SByte_result != Convert.ToSByte(vt1.int3darr[1, 0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("SByte_result is: {0}", SByte_result);
Console.WriteLine("vt1.int3darr[1,0,1] is: {0}", vt1.int3darr[1, 0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (SByte_result != Convert.ToSByte(cl1.int3darr[1, 0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("SByte_result is: {0}", SByte_result);
Console.WriteLine("cl1.int3darr[1,0,1] is: {0}", cl1.int3darr[1, 0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (SByte_result != Convert.ToSByte(ja2[1][1, 0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("SByte_result is: {0}", SByte_result);
Console.WriteLine("ja2[1][1,0,1] is: {0}", ja2[1][1, 0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
//Int32ToInt16 tests
short Int16_result = -1;
// 2D
if (Int16_result != Convert.ToInt32(int2darr[0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Int16_result is: {0}", Int16_result);
Console.WriteLine("2darr[0, 1] is: {0}", int2darr[0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (Int16_result != Convert.ToInt32(vt1.int2darr[0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Int16_result is: {0}", Int16_result);
Console.WriteLine("vt1.int2darr[0, 1] is: {0}", vt1.int2darr[0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (Int16_result != Convert.ToInt32(cl1.int2darr[0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Int16_result is: {0}", Int16_result);
Console.WriteLine("cl1.int2darr[0, 1] is: {0}", cl1.int2darr[0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (Int16_result != Convert.ToInt32(ja1[0][0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Int16_result is: {0}", Int16_result);
Console.WriteLine("ja1[0][0, 1] is: {0}", ja1[0][0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
// 3D
if (Int16_result != Convert.ToInt32(int3darr[1, 0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Int16_result is: {0}", Int16_result);
Console.WriteLine("int3darr[1,0,1] is: {0}", int3darr[1, 0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (Int16_result != Convert.ToInt32(vt1.int3darr[1, 0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Int16_result is: {0}", Int16_result);
Console.WriteLine("vt1.int3darr[1,0,1] is: {0}", vt1.int3darr[1, 0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (Int16_result != Convert.ToInt32(cl1.int3darr[1, 0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Int16_result is: {0}", Int16_result);
Console.WriteLine("cl1.int3darr[1,0,1] is: {0}", cl1.int3darr[1, 0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (Int16_result != Convert.ToInt32(ja2[1][1, 0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Int16_result is: {0}", Int16_result);
Console.WriteLine("ja2[1][1,0,1] is: {0}", ja2[1][1, 0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
//Int32ToUInt32 tests
uint UInt32_result = 1;
// 2D
if (UInt32_result != Convert.ToUInt32(int2darr_b[0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("UInt32_result is: {0}", UInt32_result);
Console.WriteLine("2darr[0, 1] is: {0}", int2darr_b[0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (UInt32_result != Convert.ToUInt32(vt1.int2darr_b[0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("UInt32_result is: {0}", UInt32_result);
Console.WriteLine("vt1.int2darr_b[0, 1] is: {0}", vt1.int2darr_b[0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (UInt32_result != Convert.ToUInt32(cl1.int2darr_b[0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("UInt32_result is: {0}", UInt32_result);
Console.WriteLine("cl1.int2darr_b[0, 1] is: {0}", cl1.int2darr_b[0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (UInt32_result != Convert.ToUInt32(ja1_b[0][0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("UInt32_result is: {0}", UInt32_result);
Console.WriteLine("ja1_b[0][0, 1] is: {0}", ja1_b[0][0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
// 3D
if (UInt32_result != Convert.ToUInt32(int3darr_b[1, 0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("UInt32_result is: {0}", UInt32_result);
Console.WriteLine("int3darr_b[1,0,1] is: {0}", int3darr_b[1, 0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (UInt32_result != Convert.ToUInt32(vt1.int3darr_b[1, 0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("UInt32_result is: {0}", UInt32_result);
Console.WriteLine("vt1.int3darr_b[1,0,1] is: {0}", vt1.int3darr_b[1, 0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (UInt32_result != Convert.ToUInt32(cl1.int3darr_b[1, 0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("UInt32_result is: {0}", UInt32_result);
Console.WriteLine("cl1.int3darr_b[1,0,1] is: {0}", cl1.int3darr_b[1, 0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (UInt32_result != Convert.ToUInt32(ja2_b[1][1, 0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("UInt32_result is: {0}", UInt32_result);
Console.WriteLine("ja2_b[1][1,0,1] is: {0}", ja2_b[1][1, 0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
//Int32ToUInt64 tests
ulong UInt64_result = 1;
// 2D
if (UInt64_result != Convert.ToUInt64(int2darr_b[0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("UInt64_result is: {0}", UInt64_result);
Console.WriteLine("2darr[0, 1] is: {0}", int2darr_b[0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (UInt64_result != Convert.ToUInt64(vt1.int2darr_b[0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("UInt64_result is: {0}", UInt64_result);
Console.WriteLine("vt1.int2darr_b[0, 1] is: {0}", vt1.int2darr_b[0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (UInt64_result != Convert.ToUInt64(cl1.int2darr_b[0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("UInt64_result is: {0}", UInt64_result);
Console.WriteLine("cl1.int2darr_b[0, 1] is: {0}", cl1.int2darr_b[0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (UInt64_result != Convert.ToUInt64(ja1_b[0][0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("UInt64_result is: {0}", UInt64_result);
Console.WriteLine("ja1_b[0][0, 1] is: {0}", ja1_b[0][0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
// 3D
if (UInt64_result != Convert.ToUInt64(int3darr_b[1, 0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("UInt64_result is: {0}", UInt64_result);
Console.WriteLine("int3darr_b[1,0,1] is: {0}", int3darr_b[1, 0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (UInt64_result != Convert.ToUInt64(vt1.int3darr_b[1, 0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("UInt64_result is: {0}", UInt64_result);
Console.WriteLine("vt1.int3darr_b[1,0,1] is: {0}", vt1.int3darr_b[1, 0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (UInt64_result != Convert.ToUInt64(cl1.int3darr_b[1, 0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("UInt64_result is: {0}", UInt64_result);
Console.WriteLine("cl1.int3darr_b[1,0,1] is: {0}", cl1.int3darr_b[1, 0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (UInt64_result != Convert.ToUInt64(ja2_b[1][1, 0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("UInt64_result is: {0}", UInt64_result);
Console.WriteLine("ja2_b[1][1,0,1] is: {0}", ja2_b[1][1, 0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
//Int32ToUInt16 tests
ushort UInt16_result = 1;
// 2D
if (UInt16_result != Convert.ToUInt16(int2darr_b[0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("UInt16_result is: {0}", UInt16_result);
Console.WriteLine("2darr[0, 1] is: {0}", int2darr_b[0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (UInt16_result != Convert.ToUInt16(vt1.int2darr_b[0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("UInt16_result is: {0}", UInt16_result);
Console.WriteLine("vt1.int2darr_b[0, 1] is: {0}", vt1.int2darr_b[0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (UInt16_result != Convert.ToUInt16(cl1.int2darr_b[0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("UInt16_result is: {0}", UInt16_result);
Console.WriteLine("cl1.int2darr_b[0, 1] is: {0}", cl1.int2darr_b[0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (UInt16_result != Convert.ToUInt16(ja1_b[0][0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("UInt16_result is: {0}", UInt16_result);
Console.WriteLine("ja1_b[0][0, 1] is: {0}", ja1_b[0][0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
// 3D
if (UInt16_result != Convert.ToUInt16(int3darr_b[1, 0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("UInt16_result is: {0}", UInt16_result);
Console.WriteLine("int3darr_b[1,0,1] is: {0}", int3darr_b[1, 0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (UInt16_result != Convert.ToUInt16(vt1.int3darr_b[1, 0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("UInt16_result is: {0}", UInt16_result);
Console.WriteLine("vt1.int3darr_b[1,0,1] is: {0}", vt1.int3darr_b[1, 0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (UInt16_result != Convert.ToUInt16(cl1.int3darr_b[1, 0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("UInt16_result is: {0}", UInt16_result);
Console.WriteLine("cl1.int3darr_b[1,0,1] is: {0}", cl1.int3darr_b[1, 0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (UInt16_result != Convert.ToUInt16(ja2_b[1][1, 0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("UInt16_result is: {0}", UInt16_result);
Console.WriteLine("ja2_b[1][1,0,1] is: {0}", ja2_b[1][1, 0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
//Int32ToChar tests
char Char_result = '1';
// 2D
if (Char_result != Convert.ToChar(int2darr_c[0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Char_result is: {0}", Char_result);
Console.WriteLine("2darr[0, 1] is: {0}", int2darr_c[0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (Char_result != Convert.ToChar(vt1.int2darr_c[0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Char_result is: {0}", Char_result);
Console.WriteLine("vt1.int2darr_c[0, 1] is: {0}", vt1.int2darr_c[0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (Char_result != Convert.ToChar(cl1.int2darr_c[0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Char_result is: {0}", Char_result);
Console.WriteLine("cl1.int2darr_c[0, 1] is: {0}", cl1.int2darr_c[0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (Char_result != Convert.ToChar(ja1_c[0][0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Char_result is: {0}", Char_result);
Console.WriteLine("ja1_c[0][0, 1] is: {0}", ja1_c[0][0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
// 3D
if (Char_result != Convert.ToChar(int3darr_c[1, 0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Char_result is: {0}", Char_result);
Console.WriteLine("int3darr_c[1,0,1] is: {0}", int3darr_c[1, 0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (Char_result != Convert.ToChar(vt1.int3darr_c[1, 0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Char_result is: {0}", Char_result);
Console.WriteLine("vt1.int3darr_c[1,0,1] is: {0}", vt1.int3darr_c[1, 0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (Char_result != Convert.ToChar(cl1.int3darr_c[1, 0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Char_result is: {0}", Char_result);
Console.WriteLine("cl1.int3darr_c[1,0,1] is: {0}", cl1.int3darr_c[1, 0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (Char_result != Convert.ToChar(ja2_c[1][1, 0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Char_result is: {0}", Char_result);
Console.WriteLine("ja2_c[1][1,0,1] is: {0}", ja2_c[1][1, 0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (!pass)
{
Console.WriteLine("FAILED");
return 1;
}
else
{
Console.WriteLine("PASSED");
return 100;
}
}
};
| |
using System;
using Skybrud.Social.Json;
using Skybrud.Social.Twitter.Entities;
namespace Skybrud.Social.Twitter.Objects {
/// <see cref="https://dev.twitter.com/docs/platform-objects/users"/>
public class TwitterUser : SocialJsonObject {
#region Properties
/// <summary>
/// The integer representation of the unique identifier for this User. This number is greater
/// than 53 bits and some programming languages may have difficulty/silent defects in
/// interpreting it. Using a signed 64 bit integer for storing this identifier is safe.
/// Use <var>id_str</var> for fetching the identifier to stay on the safe side.
/// </summary>
public long Id { get; private set; }
/// <summary>
/// The string representation of the unique identifier for this Tweet.
/// Implementations should use this rather than the large integer in id.
/// <a href="http://groups.google.com/group/twitter-development-talk/browse_thread/thread/6a16efa375532182/">Discussion</a>.
/// </summary>
public string IdStr { get; private set; }
/// <summary>
/// The screen name, handle, or alias that this user identifies themselves with. <var>screen_names</var>
/// are unique but subject to change. Use <var>id_str</var> as a user identifier whenever possible.
/// Typically a maximum of 15 characters long, but some historical accounts may exist with longer names.
/// </summary>
public string ScreenName { get; private set; }
/// <summary>
/// The name of the user, as they've defined it. Not necessarily a person's name. Typically
/// capped at 20 characters, but subject to change.
/// </summary>
public string Name { get; private set; }
/// <summary>
/// <em>Nullable</em>. The user-defined location for this account's profile. Not necessarily a location
/// nor parseable. This field will occasionally be fuzzily interpreted by the Search service.
/// </summary>
public string Location { get; private set; }
/// <summary>
/// <em>Nullable</em>. A URL provided by the user in association with their profile.
/// </summary>
public string Url { get; private set; }
/// <summary>
/// <em>Nullable</em>. The user-defined UTF-8 string describing their account.
/// </summary>
public string Description { get; private set; }
/// <summary>
/// When true, indicates that this user has chosen to protect their Tweets.
/// See <a href="https://support.twitter.com/articles/14016">About Public and Protected Tweets</a>.
/// </summary>
public bool IsProtected { get; private set; }
/// <summary>
/// The number of followers this account currently has. Under certain conditions of duress,
/// this field will temporarily indicate "0".
/// </summary>
public int FollowersCount { get; private set; }
/// <summary>
/// The number of users this account is following (AKA their "followings"). Under certain
/// conditions of duress, this field will temporarily indicate "0".
/// </summary>
public int FriendsCount { get; private set; }
/// <summary>
/// The number of public lists that this user is a member of.
/// </summary>
public int ListedCount { get; private set; }
/// <summary>
/// The UTC datetime that the user account was created on Twitter.
/// </summary>
public DateTime CreatedAt { get; private set; }
/// <summary>
/// The number of tweets this user has favorited in the account's lifetime. British spelling used
/// in the field name for historical reasons.
/// </summary>
public int FavouritesCount { get; private set; }
/// <summary>
/// The number of tweets this user has favorited in the account's lifetime.
/// </summary>
public int FavoritesCount {
get { return FavouritesCount; }
}
/// <summary>
/// <em>Nullable</em>. The offset from GMT/UTC in seconds.
/// </summary>
public int? UtcOffset { get; private set; }
/// <summary>
/// <em>Nullable</em>. A string describing the Time Zone this user declares themselves within.
/// </summary>
public string TimeZone { get; private set; }
/// <summary>
/// When true, indicates that the user has enabled the possibility of geotagging their Tweets.
/// This field must be true for the current user to attach geographic data when using
/// POST statuses/update.
/// </summary>
public bool IsGeoEnabled { get; private set; }
/// <summary>
/// When true, indicates that the user has a verified account.
/// See <a href="https://support.twitter.com/articles/119135">Verified Accounts</a>.
/// </summary>
public bool IsVerified { get; private set; }
/// <summary>
/// The number of tweets (including retweets) issued by the user.
/// </summary>
public int StatusesCount { get; private set; }
/// <summary>
/// The <var>BCP 47</var> code for the user's self-declared user interface language.
/// May or may not have anything to do with the content of their Tweets.
/// </summary>
/// <see cref="http://tools.ietf.org/html/bcp47" />
public string Language { get; private set; }
/// <summary>
/// Indicates that the user has an account with "contributor mode" enabled, allowing for
/// Tweets issued by the user to be co-authored by another account. Rarely <var>true</var>.
/// </summary>
public bool ContributorsEnabled { get; private set; }
/// <summary>
/// When true, indicates that the user is a participant in Twitter's translator community.
/// </summary>
public bool IsTranslator { get; private set; }
/// <summary>
/// <em>Nullable</em>. <em>Perspectival</em>. When true, indicates that the authenticating user has issued a
/// follow request to this protected user account.
/// </summary>
public bool? FollowRequestSent { get; private set; }
/// <summary>
/// The hexadecimal color chosen by the user for their background.
/// </summary>
public string ProfileBackgroundColor { get; private set; }
/// <summary>
/// A HTTP-based URL pointing to the background image the user has uploaded for their
/// profile.
/// </summary>
public string ProfileBackgroundImageUrl { get; private set; }
/// <summary>
/// A HTTPS-based URL pointing to the background image the user has uploaded for their
/// profile.
/// </summary>
public string ProfileBackgroundImageUrlHttps { get; private set; }
/// <summary>
/// When true, indicates that the user's <var>profile_background_image_url</var> should be tiled
/// when displayed.
/// </summary>
public bool ProfileBackgroundTile { get; private set; }
/// <summary>
/// The HTTPS-based URL pointing to the standard web representation of the user's uploaded
/// profile banner. By adding a final path element of the URL, you can obtain different
/// image sizes optimized for specific displays. In the future, an API method will be
/// provided to serve these URLs so that you need not modify the original URL. For size
/// variations, please see <a href="https://dev.twitter.com/docs/user-profile-images-and-banners">User Profile Images and Banners</a>.
/// </summary>
public string ProfileBannerUrl { get; private set; }
/// <summary>
/// A HTTP-based URL pointing to the user's avatar image. See <a href="https://dev.twitter.com/docs/user-profile-images-and-banners">User Profile Images and Banners</a>.
/// </summary>
public string ProfileImageUrl { get; private set; }
/// <summary>
/// A HTTPS-based URL pointing to the user's avatar image.
/// </summary>
public string ProfileImageUrlHttps { get; private set; }
/// <summary>
/// The hexadecimal color the user has chosen to display links with in their Twitter UI.
/// </summary>
public string ProfileLinkColor { get; private set; }
/// <summary>
/// The hexadecimal color the user has chosen to display sidebar borders with in their Twitter UI.
/// </summary>
public string ProfileSidebarBorderColor { get; private set; }
/// <summary>
/// The hexadecimal color the user has chosen to display sidebar backgrounds with in their Twitter UI.
/// </summary>
public string ProfileSidebarFillColor { get; private set; }
/// <summary>
/// The hexadecimal color the user has chosen to display text with in their Twitter UI.
/// </summary>
public string ProfileTextColor { get; private set; }
/// <summary>
/// When true, indicates the user wants their uploaded background image to be used.
/// </summary>
public bool ProfileUseBackgroundImage { get; private set; }
/// <summary>
/// Indicates that the user would like to see media inline. Somewhat disused.
/// </summary>
public bool ShowAllInlineMedia { get; private set; }
/// <summary>
/// Boolean When true, indicates that the user has not altered the theme or background of their user profile.
/// </summary>
public bool HasDefaultProfile { get; private set; }
/// <summary>
/// When true, indicates that the user has not uploaded their own avatar and a default egg avatar is used instead.
/// </summary>
public bool HasDefaultProfileImage { get; private set; }
/// <summary>
/// <em>Nullable</em>. If possible, the user's most recent tweet or retweet. In some circumstances,
/// this data cannot be provided and this field will be omitted, null, or empty. Perspectival
/// attributes within tweets embedded within users cannot always be relied upon.
/// See <a href="https://dev.twitter.com/docs/faq/#6981">Why are embedded objects stale or inaccurate?</a>.
/// </summary>
public object Status { get; private set; }
/// <summary>
/// Entities which have been parsed out of the url or description fields defined by the user.
/// Read more about <a href="https://dev.twitter.com/docs/entities#users">Entities for Users</a>.
/// </summary>
public TwitterUserEntities Entities { get; private set; }
#endregion
#region Constructor(s)
private TwitterUser(JsonObject obj) : base(obj) {
// Hide default constructor
}
#endregion
#region Static methods
/// <summary>
/// Loads a user from the JSON file at the specified <var>path</var>.
/// </summary>
/// <param name="path">The path to the file.</param>
public static TwitterUser LoadJson(string path) {
return JsonObject.LoadJson(path, Parse);
}
/// <summary>
/// Gets a user from the specified JSON string.
/// </summary>
/// <param name="json">The JSON string representation of the object.</param>
public static TwitterUser ParseJson(string json) {
return JsonObject.ParseJson(json, Parse);
}
/// <summary>
/// Gets a user from the specified <var>JsonObject</var>.
/// </summary>
/// <param name="obj">The instance of <var>JsonObject</var> to parse.</param>
public static TwitterUser Parse(JsonObject obj) {
// Error checking
if (obj == null) return null;
if (obj.HasValue("error")) throw TwitterException.Parse(obj.GetArray("error"));
TwitterUser user = new TwitterUser(obj);
#region Basic properties
user.Id = obj.GetInt64("id");
user.IdStr = obj.GetString("id_str");
user.Name = obj.GetString("name");
user.ScreenName = obj.GetString("screen_name");
user.Location = obj.GetString("location");
user.Url = obj.GetString("url");
user.Description = obj.GetString("description");
user.IsProtected = obj.GetBoolean("protected");
user.FollowersCount = obj.GetInt32("followers_count");
user.FriendsCount = obj.GetInt32("friends_count");
user.ListedCount = obj.GetInt32("listed_count");
user.CreatedAt = TwitterUtils.ParseDateTime(obj.GetString("created_at"));
user.FavouritesCount = obj.GetInt32("favourites_count");
if (obj.HasValue("utc_offset")) user.UtcOffset = obj.GetInt32("utc_offset");
user.TimeZone = obj.GetString("time_zone");
user.IsGeoEnabled = obj.GetBoolean("geo_enabled");
user.IsVerified = obj.GetBoolean("verified");
user.StatusesCount = obj.GetInt32("statuses_count");
user.Language = obj.GetString("lang");
user.ContributorsEnabled = obj.GetBoolean("contributors_enabled");
user.IsTranslator = obj.GetBoolean("is_translator");
user.FollowRequestSent = obj.HasValue("follow_request_sent") && obj.GetBoolean("follow_request_sent");
user.Status = obj.GetObject("status", TwitterStatusMessage.Parse);
user.Entities = obj.GetObject("entities", TwitterUserEntities.Parse);
#endregion
#region Profile properties
user.HasDefaultProfile = obj.GetBoolean("default_profile");
user.HasDefaultProfileImage = obj.GetBoolean("default_profile_image");
user.ProfileBackgroundColor = obj.GetString("profile_background_color");
user.ProfileBackgroundImageUrl = obj.GetString("profile_background_image_url");
user.ProfileBackgroundImageUrlHttps = obj.GetString("profile_background_image_url_https");
user.ProfileBackgroundTile = obj.GetBoolean("profile_background_tile");
user.ProfileBannerUrl = obj.GetString("profile_banner_url");
user.ProfileImageUrl = obj.GetString("profile_image_url");
user.ProfileImageUrlHttps = obj.GetString("profile_image_url_https");
user.ProfileLinkColor = obj.GetString("profile_link_color");
user.ProfileSidebarBorderColor = obj.GetString("profile_sidebar_border_color");
user.ProfileSidebarFillColor = obj.GetString("profile_sidebar_fill_color");
user.ProfileTextColor = obj.GetString("profile_text_color");
user.ProfileUseBackgroundImage = obj.GetBoolean("profile_use_background_image");
#endregion
return user;
}
#endregion
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Text;
using log4net;
using Nini.Config;
using NUnit.Framework;
using OpenMetaverse;
using OpenMetaverse.Assets;
using OpenMetaverse.StructuredData;
using OpenSim.Framework;
using OpenSim.Region.CoreModules.Avatar.AvatarFactory;
using OpenSim.Region.OptionalModules.World.NPC;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Region.ScriptEngine.Shared;
using OpenSim.Region.ScriptEngine.Shared.Api;
using OpenSim.Region.ScriptEngine.Shared.Instance;
using OpenSim.Region.ScriptEngine.Shared.ScriptBase;
using OpenSim.Services.Interfaces;
using OpenSim.Tests.Common;
using LSL_Integer = OpenSim.Region.ScriptEngine.Shared.LSL_Types.LSLInteger;
using LSL_List = OpenSim.Region.ScriptEngine.Shared.LSL_Types.list;
namespace OpenSim.Region.ScriptEngine.Shared.Tests
{
[TestFixture]
public class LSL_ApiObjectTests : OpenSimTestCase
{
private const double VECTOR_COMPONENT_ACCURACY = 0.0000005d;
private const float FLOAT_ACCURACY = 0.00005f;
protected Scene m_scene;
protected XEngine.XEngine m_engine;
[SetUp]
public override void SetUp()
{
base.SetUp();
IConfigSource initConfigSource = new IniConfigSource();
IConfig config = initConfigSource.AddConfig("XEngine");
config.Set("Enabled", "true");
m_scene = new SceneHelpers().SetupScene();
SceneHelpers.SetupSceneModules(m_scene, initConfigSource);
m_engine = new XEngine.XEngine();
m_engine.Initialise(initConfigSource);
m_engine.AddRegion(m_scene);
}
[Test]
public void TestllGetLinkPrimitiveParams()
{
TestHelpers.InMethod();
TestHelpers.EnableLogging();
UUID ownerId = TestHelpers.ParseTail(0x1);
SceneObjectGroup grp1 = SceneHelpers.CreateSceneObject(2, ownerId, "grp1-", 0x10);
grp1.AbsolutePosition = new Vector3(10, 11, 12);
m_scene.AddSceneObject(grp1);
LSL_Api apiGrp1 = new LSL_Api();
apiGrp1.Initialize(m_engine, grp1.RootPart, null, null);
// Check simple 1 prim case
{
LSL_List resList
= apiGrp1.llGetLinkPrimitiveParams(1, new LSL_List(new LSL_Integer(ScriptBaseClass.PRIM_ROTATION)));
Assert.That(resList.Length, Is.EqualTo(1));
}
// Check 2 prim case
{
LSL_List resList
= apiGrp1.llGetLinkPrimitiveParams(
1,
new LSL_List(
new LSL_Integer(ScriptBaseClass.PRIM_ROTATION),
new LSL_Integer(ScriptBaseClass.PRIM_LINK_TARGET),
new LSL_Integer(2),
new LSL_Integer(ScriptBaseClass.PRIM_ROTATION)));
Assert.That(resList.Length, Is.EqualTo(2));
}
// Check invalid parameters are ignored
{
LSL_List resList
= apiGrp1.llGetLinkPrimitiveParams(3, new LSL_List(new LSL_Integer(ScriptBaseClass.PRIM_ROTATION)));
Assert.That(resList.Length, Is.EqualTo(0));
}
// Check all parameters are ignored if an initial bad link is given
{
LSL_List resList
= apiGrp1.llGetLinkPrimitiveParams(
3,
new LSL_List(
new LSL_Integer(ScriptBaseClass.PRIM_ROTATION),
new LSL_Integer(ScriptBaseClass.PRIM_LINK_TARGET),
new LSL_Integer(1),
new LSL_Integer(ScriptBaseClass.PRIM_ROTATION)));
Assert.That(resList.Length, Is.EqualTo(0));
}
// Check only subsequent parameters are ignored when we hit the first bad link number
{
LSL_List resList
= apiGrp1.llGetLinkPrimitiveParams(
1,
new LSL_List(
new LSL_Integer(ScriptBaseClass.PRIM_ROTATION),
new LSL_Integer(ScriptBaseClass.PRIM_LINK_TARGET),
new LSL_Integer(3),
new LSL_Integer(ScriptBaseClass.PRIM_ROTATION)));
Assert.That(resList.Length, Is.EqualTo(1));
}
}
[Test]
// llSetPrimitiveParams and llGetPrimitiveParams test.
public void TestllSetPrimitiveParams()
{
TestHelpers.InMethod();
// Create Prim1.
Scene scene = new SceneHelpers().SetupScene();
string obj1Name = "Prim1";
UUID objUuid = new UUID("00000000-0000-0000-0000-000000000001");
SceneObjectPart part1 =
new SceneObjectPart(UUID.Zero, PrimitiveBaseShape.Default,
Vector3.Zero, Quaternion.Identity,
Vector3.Zero) { Name = obj1Name, UUID = objUuid };
Assert.That(scene.AddNewSceneObject(new SceneObjectGroup(part1), false), Is.True);
LSL_Api apiGrp1 = new LSL_Api();
apiGrp1.Initialize(m_engine, part1, null, null);
// Note that prim hollow check is passed with the other prim params in order to allow the
// specification of a different check value from the prim param. A cylinder, prism, sphere,
// torus or ring, with a hole shape of square, is limited to a hollow of 70%. Test 5 below
// specifies a value of 95% and checks to see if 70% was properly returned.
// Test a sphere.
CheckllSetPrimitiveParams(
apiGrp1,
"test 1", // Prim test identification string
new LSL_Types.Vector3(6.0d, 9.9d, 9.9d), // Prim size
ScriptBaseClass.PRIM_TYPE_SPHERE, // Prim type
ScriptBaseClass.PRIM_HOLE_DEFAULT, // Prim hole type
new LSL_Types.Vector3(0.0d, 0.075d, 0.0d), // Prim cut
0.80f, // Prim hollow
new LSL_Types.Vector3(0.0d, 0.0d, 0.0d), // Prim twist
new LSL_Types.Vector3(0.32d, 0.76d, 0.0d), // Prim dimple
0.80f); // Prim hollow check
// Test a prism.
CheckllSetPrimitiveParams(
apiGrp1,
"test 2", // Prim test identification string
new LSL_Types.Vector3(3.5d, 3.5d, 3.5d), // Prim size
ScriptBaseClass.PRIM_TYPE_PRISM, // Prim type
ScriptBaseClass.PRIM_HOLE_CIRCLE, // Prim hole type
new LSL_Types.Vector3(0.0d, 1.0d, 0.0d), // Prim cut
0.90f, // Prim hollow
new LSL_Types.Vector3(0.0d, 0.0d, 0.0d), // Prim twist
new LSL_Types.Vector3(2.0d, 1.0d, 0.0d), // Prim taper
new LSL_Types.Vector3(0.0d, 0.0d, 0.0d), // Prim shear
0.90f); // Prim hollow check
// Test a box.
CheckllSetPrimitiveParams(
apiGrp1,
"test 3", // Prim test identification string
new LSL_Types.Vector3(3.5d, 3.5d, 3.5d), // Prim size
ScriptBaseClass.PRIM_TYPE_BOX, // Prim type
ScriptBaseClass.PRIM_HOLE_TRIANGLE, // Prim hole type
new LSL_Types.Vector3(0.0d, 1.0d, 0.0d), // Prim cut
0.95f, // Prim hollow
new LSL_Types.Vector3(1.0d, 0.0d, 0.0d), // Prim twist
new LSL_Types.Vector3(1.0d, 1.0d, 0.0d), // Prim taper
new LSL_Types.Vector3(0.0d, 0.0d, 0.0d), // Prim shear
0.95f); // Prim hollow check
// Test a tube.
CheckllSetPrimitiveParams(
apiGrp1,
"test 4", // Prim test identification string
new LSL_Types.Vector3(4.2d, 4.2d, 4.2d), // Prim size
ScriptBaseClass.PRIM_TYPE_TUBE, // Prim type
ScriptBaseClass.PRIM_HOLE_SQUARE, // Prim hole type
new LSL_Types.Vector3(0.0d, 1.0d, 0.0d), // Prim cut
0.00f, // Prim hollow
new LSL_Types.Vector3(1.0d, -1.0d, 0.0d), // Prim twist
new LSL_Types.Vector3(1.0d, 0.05d, 0.0d), // Prim hole size
// Expression for y selected to test precision problems during byte
// cast in SetPrimitiveShapeParams.
new LSL_Types.Vector3(0.0d, 0.35d + 0.1d, 0.0d), // Prim shear
new LSL_Types.Vector3(0.0d, 1.0d, 0.0d), // Prim profile cut
// Expression for y selected to test precision problems during sbyte
// cast in SetPrimitiveShapeParams.
new LSL_Types.Vector3(-1.0d, 0.70d + 0.1d + 0.1d, 0.0d), // Prim taper
1.11f, // Prim revolutions
0.88f, // Prim radius
0.95f, // Prim skew
0.00f); // Prim hollow check
// Test a prism.
CheckllSetPrimitiveParams(
apiGrp1,
"test 5", // Prim test identification string
new LSL_Types.Vector3(3.5d, 3.5d, 3.5d), // Prim size
ScriptBaseClass.PRIM_TYPE_PRISM, // Prim type
ScriptBaseClass.PRIM_HOLE_SQUARE, // Prim hole type
new LSL_Types.Vector3(0.0d, 1.0d, 0.0d), // Prim cut
0.95f, // Prim hollow
// Expression for x selected to test precision problems during sbyte
// cast in SetPrimitiveShapeBlockParams.
new LSL_Types.Vector3(0.7d + 0.2d, 0.0d, 0.0d), // Prim twist
// Expression for y selected to test precision problems during sbyte
// cast in SetPrimitiveShapeParams.
new LSL_Types.Vector3(2.0d, (1.3d + 0.1d), 0.0d), // Prim taper
new LSL_Types.Vector3(0.0d, 0.0d, 0.0d), // Prim shear
0.70f); // Prim hollow check
// Test a sculpted prim.
CheckllSetPrimitiveParams(
apiGrp1,
"test 6", // Prim test identification string
new LSL_Types.Vector3(2.0d, 2.0d, 2.0d), // Prim size
ScriptBaseClass.PRIM_TYPE_SCULPT, // Prim type
"be293869-d0d9-0a69-5989-ad27f1946fd4", // Prim map
ScriptBaseClass.PRIM_SCULPT_TYPE_SPHERE); // Prim sculpt type
}
// Set prim params for a box, cylinder or prism and check results.
public void CheckllSetPrimitiveParams(LSL_Api api, string primTest,
LSL_Types.Vector3 primSize, int primType, int primHoleType, LSL_Types.Vector3 primCut,
float primHollow, LSL_Types.Vector3 primTwist, LSL_Types.Vector3 primTaper, LSL_Types.Vector3 primShear,
float primHollowCheck)
{
// Set the prim params.
api.llSetPrimitiveParams(new LSL_Types.list(ScriptBaseClass.PRIM_SIZE, primSize,
ScriptBaseClass.PRIM_TYPE, primType, primHoleType,
primCut, primHollow, primTwist, primTaper, primShear));
// Get params for prim to validate settings.
LSL_Types.list primParams =
api.llGetPrimitiveParams(new LSL_Types.list(ScriptBaseClass.PRIM_SIZE, ScriptBaseClass.PRIM_TYPE));
// Validate settings.
CheckllSetPrimitiveParamsVector(primSize, api.llList2Vector(primParams, 0), primTest + " prim size");
Assert.AreEqual(primType, api.llList2Integer(primParams, 1),
"TestllSetPrimitiveParams " + primTest + " prim type check fail");
Assert.AreEqual(primHoleType, api.llList2Integer(primParams, 2),
"TestllSetPrimitiveParams " + primTest + " prim hole default check fail");
CheckllSetPrimitiveParamsVector(primCut, api.llList2Vector(primParams, 3), primTest + " prim cut");
Assert.AreEqual(primHollowCheck, api.llList2Float(primParams, 4), FLOAT_ACCURACY,
"TestllSetPrimitiveParams " + primTest + " prim hollow check fail");
CheckllSetPrimitiveParamsVector(primTwist, api.llList2Vector(primParams, 5), primTest + " prim twist");
CheckllSetPrimitiveParamsVector(primTaper, api.llList2Vector(primParams, 6), primTest + " prim taper");
CheckllSetPrimitiveParamsVector(primShear, api.llList2Vector(primParams, 7), primTest + " prim shear");
}
// Set prim params for a sphere and check results.
public void CheckllSetPrimitiveParams(LSL_Api api, string primTest,
LSL_Types.Vector3 primSize, int primType, int primHoleType, LSL_Types.Vector3 primCut,
float primHollow, LSL_Types.Vector3 primTwist, LSL_Types.Vector3 primDimple, float primHollowCheck)
{
// Set the prim params.
api.llSetPrimitiveParams(new LSL_Types.list(ScriptBaseClass.PRIM_SIZE, primSize,
ScriptBaseClass.PRIM_TYPE, primType, primHoleType,
primCut, primHollow, primTwist, primDimple));
// Get params for prim to validate settings.
LSL_Types.list primParams =
api.llGetPrimitiveParams(new LSL_Types.list(ScriptBaseClass.PRIM_SIZE, ScriptBaseClass.PRIM_TYPE));
// Validate settings.
CheckllSetPrimitiveParamsVector(primSize, api.llList2Vector(primParams, 0), primTest + " prim size");
Assert.AreEqual(primType, api.llList2Integer(primParams, 1),
"TestllSetPrimitiveParams " + primTest + " prim type check fail");
Assert.AreEqual(primHoleType, api.llList2Integer(primParams, 2),
"TestllSetPrimitiveParams " + primTest + " prim hole default check fail");
CheckllSetPrimitiveParamsVector(primCut, api.llList2Vector(primParams, 3), primTest + " prim cut");
Assert.AreEqual(primHollowCheck, api.llList2Float(primParams, 4), FLOAT_ACCURACY,
"TestllSetPrimitiveParams " + primTest + " prim hollow check fail");
CheckllSetPrimitiveParamsVector(primTwist, api.llList2Vector(primParams, 5), primTest + " prim twist");
CheckllSetPrimitiveParamsVector(primDimple, api.llList2Vector(primParams, 6), primTest + " prim dimple");
}
// Set prim params for a torus, tube or ring and check results.
public void CheckllSetPrimitiveParams(LSL_Api api, string primTest,
LSL_Types.Vector3 primSize, int primType, int primHoleType, LSL_Types.Vector3 primCut,
float primHollow, LSL_Types.Vector3 primTwist, LSL_Types.Vector3 primHoleSize,
LSL_Types.Vector3 primShear, LSL_Types.Vector3 primProfCut, LSL_Types.Vector3 primTaper,
float primRev, float primRadius, float primSkew, float primHollowCheck)
{
// Set the prim params.
api.llSetPrimitiveParams(new LSL_Types.list(ScriptBaseClass.PRIM_SIZE, primSize,
ScriptBaseClass.PRIM_TYPE, primType, primHoleType,
primCut, primHollow, primTwist, primHoleSize, primShear, primProfCut,
primTaper, primRev, primRadius, primSkew));
// Get params for prim to validate settings.
LSL_Types.list primParams =
api.llGetPrimitiveParams(new LSL_Types.list(ScriptBaseClass.PRIM_SIZE, ScriptBaseClass.PRIM_TYPE));
// Valdate settings.
CheckllSetPrimitiveParamsVector(primSize, api.llList2Vector(primParams, 0), primTest + " prim size");
Assert.AreEqual(primType, api.llList2Integer(primParams, 1),
"TestllSetPrimitiveParams " + primTest + " prim type check fail");
Assert.AreEqual(primHoleType, api.llList2Integer(primParams, 2),
"TestllSetPrimitiveParams " + primTest + " prim hole default check fail");
CheckllSetPrimitiveParamsVector(primCut, api.llList2Vector(primParams, 3), primTest + " prim cut");
Assert.AreEqual(primHollowCheck, api.llList2Float(primParams, 4), FLOAT_ACCURACY,
"TestllSetPrimitiveParams " + primTest + " prim hollow check fail");
CheckllSetPrimitiveParamsVector(primTwist, api.llList2Vector(primParams, 5), primTest + " prim twist");
CheckllSetPrimitiveParamsVector(primHoleSize, api.llList2Vector(primParams, 6), primTest + " prim hole size");
CheckllSetPrimitiveParamsVector(primShear, api.llList2Vector(primParams, 7), primTest + " prim shear");
CheckllSetPrimitiveParamsVector(primProfCut, api.llList2Vector(primParams, 8), primTest + " prim profile cut");
CheckllSetPrimitiveParamsVector(primTaper, api.llList2Vector(primParams, 9), primTest + " prim taper");
Assert.AreEqual(primRev, api.llList2Float(primParams, 10), FLOAT_ACCURACY,
"TestllSetPrimitiveParams " + primTest + " prim revolutions fail");
Assert.AreEqual(primRadius, api.llList2Float(primParams, 11), FLOAT_ACCURACY,
"TestllSetPrimitiveParams " + primTest + " prim radius fail");
Assert.AreEqual(primSkew, api.llList2Float(primParams, 12), FLOAT_ACCURACY,
"TestllSetPrimitiveParams " + primTest + " prim skew fail");
}
// Set prim params for a sculpted prim and check results.
public void CheckllSetPrimitiveParams(LSL_Api api, string primTest,
LSL_Types.Vector3 primSize, int primType, string primMap, int primSculptType)
{
// Set the prim params.
api.llSetPrimitiveParams(new LSL_Types.list(ScriptBaseClass.PRIM_SIZE, primSize,
ScriptBaseClass.PRIM_TYPE, primType, primMap, primSculptType));
// Get params for prim to validate settings.
LSL_Types.list primParams =
api.llGetPrimitiveParams(new LSL_Types.list(ScriptBaseClass.PRIM_SIZE, ScriptBaseClass.PRIM_TYPE));
// Validate settings.
CheckllSetPrimitiveParamsVector(primSize, api.llList2Vector(primParams, 0), primTest + " prim size");
Assert.AreEqual(primType, api.llList2Integer(primParams, 1),
"TestllSetPrimitiveParams " + primTest + " prim type check fail");
Assert.AreEqual(primMap, (string)api.llList2String(primParams, 2),
"TestllSetPrimitiveParams " + primTest + " prim map check fail");
Assert.AreEqual(primSculptType, api.llList2Integer(primParams, 3),
"TestllSetPrimitiveParams " + primTest + " prim type scuplt check fail");
}
public void CheckllSetPrimitiveParamsVector(LSL_Types.Vector3 vecCheck, LSL_Types.Vector3 vecReturned, string msg)
{
// Check each vector component against expected result.
Assert.AreEqual(vecCheck.x, vecReturned.x, VECTOR_COMPONENT_ACCURACY,
"TestllSetPrimitiveParams " + msg + " vector check fail on x component");
Assert.AreEqual(vecCheck.y, vecReturned.y, VECTOR_COMPONENT_ACCURACY,
"TestllSetPrimitiveParams " + msg + " vector check fail on y component");
Assert.AreEqual(vecCheck.z, vecReturned.z, VECTOR_COMPONENT_ACCURACY,
"TestllSetPrimitiveParams " + msg + " vector check fail on z component");
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Reflection.Internal;
using System.Text;
namespace System.Reflection.Metadata.Ecma335
{
public sealed partial class MetadataBuilder
{
// #US heap
private const int UserStringHeapSizeLimit = 0x01000000;
private readonly Dictionary<string, int> _userStrings = new Dictionary<string, int>();
private readonly BlobBuilder _userStringWriter = new BlobBuilder(1024);
private readonly int _userStringHeapStartOffset;
// #String heap
private Dictionary<string, StringHandle> _strings = new Dictionary<string, StringHandle>(128);
private int[] _stringIndexToResolvedOffsetMap;
private BlobBuilder _stringWriter;
private readonly int _stringHeapStartOffset;
// #Blob heap
private readonly Dictionary<ImmutableArray<byte>, BlobHandle> _blobs = new Dictionary<ImmutableArray<byte>, BlobHandle>(ByteSequenceComparer.Instance);
private readonly int _blobHeapStartOffset;
private int _blobHeapSize;
// #GUID heap
private readonly Dictionary<Guid, GuidHandle> _guids = new Dictionary<Guid, GuidHandle>();
private readonly BlobBuilder _guidWriter = new BlobBuilder(16); // full metadata has just a single guid
private bool _streamsAreComplete;
public MetadataBuilder(
int userStringHeapStartOffset = 0,
int stringHeapStartOffset = 0,
int blobHeapStartOffset = 0,
int guidHeapStartOffset = 0)
{
// -1 for the 0 we always write at the beginning of the heap:
if (userStringHeapStartOffset >= UserStringHeapSizeLimit - 1)
{
throw ImageFormatLimitationException.HeapSizeLimitExceeded(HeapIndex.UserString);
}
// Add zero-th entry to all heaps, even in EnC delta.
// We don't want generation-relative handles to ever be IsNil.
// In both full and delta metadata all nil heap handles should have zero value.
// There should be no blob handle that references the 0 byte added at the
// beginning of the delta blob.
_userStringWriter.WriteByte(0);
_blobs.Add(ImmutableArray<byte>.Empty, default(BlobHandle));
_blobHeapSize = 1;
// When EnC delta is applied #US, #String and #Blob heaps are appended.
// Thus indices of strings and blobs added to this generation are offset
// by the sum of respective heap sizes of all previous generations.
_userStringHeapStartOffset = userStringHeapStartOffset;
_stringHeapStartOffset = stringHeapStartOffset;
_blobHeapStartOffset = blobHeapStartOffset;
// Unlike other heaps, #Guid heap in EnC delta is zero-padded.
_guidWriter.WriteBytes(0, guidHeapStartOffset);
}
public BlobHandle GetOrAddBlob(BlobBuilder builder)
{
// TODO: avoid making a copy if the blob exists in the index
return GetOrAddBlob(builder.ToImmutableArray());
}
public BlobHandle GetOrAddBlob(ImmutableArray<byte> blob)
{
BlobHandle index;
if (!_blobs.TryGetValue(blob, out index))
{
Debug.Assert(!_streamsAreComplete);
index = MetadataTokens.BlobHandle(_blobHeapSize);
_blobs.Add(blob, index);
_blobHeapSize += BlobWriterImpl.GetCompressedIntegerSize(blob.Length) + blob.Length;
}
return index;
}
public BlobHandle GetOrAddConstantBlob(object value)
{
string str = value as string;
if (str != null)
{
return GetOrAddBlob(str);
}
var builder = PooledBlobBuilder.GetInstance();
builder.WriteConstant(value);
var result = GetOrAddBlob(builder);
builder.Free();
return result;
}
public BlobHandle GetOrAddBlob(string str)
{
byte[] byteArray = new byte[str.Length * 2];
int i = 0;
foreach (char ch in str)
{
byteArray[i++] = (byte)(ch & 0xFF);
byteArray[i++] = (byte)(ch >> 8);
}
return GetOrAddBlob(ImmutableArray.Create(byteArray));
}
public BlobHandle GetOrAddBlobUtf8(string str)
{
return GetOrAddBlob(ImmutableArray.Create(Encoding.UTF8.GetBytes(str)));
}
public GuidHandle GetOrAddGuid(Guid guid)
{
if (guid == Guid.Empty)
{
return default(GuidHandle);
}
GuidHandle result;
if (_guids.TryGetValue(guid, out result))
{
return result;
}
result = GetNextGuid();
_guids.Add(guid, result);
_guidWriter.WriteBytes(guid.ToByteArray());
return result;
}
public GuidHandle ReserveGuid(out Blob reservedBlob)
{
var handle = GetNextGuid();
reservedBlob = _guidWriter.ReserveBytes(16);
return handle;
}
private GuidHandle GetNextGuid()
{
Debug.Assert(!_streamsAreComplete);
// The only GUIDs that are serialized are MVID, EncId, and EncBaseId in the
// Module table. Each of those GUID offsets are relative to the local heap,
// even for deltas, so there's no need for a GetGuidStreamPosition() method
// to offset the positions by the size of the original heap in delta metadata.
// Unlike #Blob, #String and #US streams delta #GUID stream is padded to the
// size of the previous generation #GUID stream before new GUIDs are added.
// Metadata Spec:
// The Guid heap is an array of GUIDs, each 16 bytes wide.
// Its first element is numbered 1, its second 2, and so on.
return MetadataTokens.GuidHandle((_guidWriter.Count >> 4) + 1);
}
public StringHandle GetOrAddString(string str)
{
StringHandle index;
if (str.Length == 0)
{
index = default(StringHandle);
}
else if (!_strings.TryGetValue(str, out index))
{
Debug.Assert(!_streamsAreComplete);
index = MetadataTokens.StringHandle(_strings.Count + 1); // idx 0 is reserved for empty string
_strings.Add(str, index);
}
return index;
}
public int GetHeapOffset(StringHandle handle)
{
return _stringIndexToResolvedOffsetMap[MetadataTokens.GetHeapOffset(handle)];
}
public int GetHeapOffset(BlobHandle handle)
{
int offset = MetadataTokens.GetHeapOffset(handle);
return (offset == 0) ? 0 : _blobHeapStartOffset + offset;
}
public int GetHeapOffset(GuidHandle handle)
{
return MetadataTokens.GetHeapOffset(handle);
}
public int GetHeapOffset(UserStringHandle handle)
{
return MetadataTokens.GetHeapOffset(handle);
}
/// <exception cref="ImageFormatLimitationException">The remaining space on the heap is too small to fit the string.</exception>
public UserStringHandle GetOrAddUserString(string str)
{
int index;
if (!_userStrings.TryGetValue(str, out index))
{
Debug.Assert(!_streamsAreComplete);
int startPosition = _userStringWriter.Count;
int encodedLength = str.Length * 2 + 1;
index = startPosition + _userStringHeapStartOffset;
// Native metadata emitter allows strings to exceed the heap size limit as long
// as the index is within the limits (see https://github.com/dotnet/roslyn/issues/9852)
if (index >= UserStringHeapSizeLimit)
{
throw ImageFormatLimitationException.HeapSizeLimitExceeded(HeapIndex.UserString);
}
_userStrings.Add(str, index);
_userStringWriter.WriteCompressedInteger(encodedLength);
_userStringWriter.WriteUTF16(str);
// Write out a trailing byte indicating if the string is really quite simple
byte stringKind = 0;
foreach (char ch in str)
{
if (ch >= 0x7F)
{
stringKind = 1;
}
else
{
switch ((int)ch)
{
case 0x1:
case 0x2:
case 0x3:
case 0x4:
case 0x5:
case 0x6:
case 0x7:
case 0x8:
case 0xE:
case 0xF:
case 0x10:
case 0x11:
case 0x12:
case 0x13:
case 0x14:
case 0x15:
case 0x16:
case 0x17:
case 0x18:
case 0x19:
case 0x1A:
case 0x1B:
case 0x1C:
case 0x1D:
case 0x1E:
case 0x1F:
case 0x27:
case 0x2D:
stringKind = 1;
break;
default:
continue;
}
}
break;
}
_userStringWriter.WriteByte(stringKind);
}
return MetadataTokens.UserStringHandle(index);
}
internal void CompleteHeaps()
{
Debug.Assert(!_streamsAreComplete);
_streamsAreComplete = true;
SerializeStringHeap();
}
public ImmutableArray<int> GetHeapSizes()
{
var heapSizes = new int[MetadataTokens.HeapCount];
heapSizes[(int)HeapIndex.UserString] = _userStringWriter.Count;
heapSizes[(int)HeapIndex.String] = _stringWriter.Count;
heapSizes[(int)HeapIndex.Blob] = _blobHeapSize;
heapSizes[(int)HeapIndex.Guid] = _guidWriter.Count;
return ImmutableArray.CreateRange(heapSizes);
}
/// <summary>
/// Fills in stringIndexMap with data from stringIndex and write to stringWriter.
/// Releases stringIndex as the stringTable is sealed after this point.
/// </summary>
private void SerializeStringHeap()
{
// Sort by suffix and remove stringIndex
var sorted = new List<KeyValuePair<string, StringHandle>>(_strings);
sorted.Sort(new SuffixSort());
_strings = null;
_stringWriter = new BlobBuilder(1024);
// Create VirtIdx to Idx map and add entry for empty string
_stringIndexToResolvedOffsetMap = new int[sorted.Count + 1];
_stringIndexToResolvedOffsetMap[0] = 0;
_stringWriter.WriteByte(0);
// Find strings that can be folded
string prev = string.Empty;
foreach (KeyValuePair<string, StringHandle> entry in sorted)
{
int position = _stringHeapStartOffset + _stringWriter.Count;
// It is important to use ordinal comparison otherwise we'll use the current culture!
if (prev.EndsWith(entry.Key, StringComparison.Ordinal) && !BlobUtilities.IsLowSurrogateChar(entry.Key[0]))
{
// Map over the tail of prev string. Watch for null-terminator of prev string.
_stringIndexToResolvedOffsetMap[MetadataTokens.GetHeapOffset(entry.Value)] = position - (BlobUtilities.GetUTF8ByteCount(entry.Key) + 1);
}
else
{
_stringIndexToResolvedOffsetMap[MetadataTokens.GetHeapOffset(entry.Value)] = position;
_stringWriter.WriteUTF8(entry.Key, allowUnpairedSurrogates: false);
_stringWriter.WriteByte(0);
}
prev = entry.Key;
}
}
/// <summary>
/// Sorts strings such that a string is followed immediately by all strings
/// that are a suffix of it.
/// </summary>
private class SuffixSort : IComparer<KeyValuePair<string, StringHandle>>
{
public int Compare(KeyValuePair<string, StringHandle> xPair, KeyValuePair<string, StringHandle> yPair)
{
string x = xPair.Key;
string y = yPair.Key;
for (int i = x.Length - 1, j = y.Length - 1; i >= 0 & j >= 0; i--, j--)
{
if (x[i] < y[j])
{
return -1;
}
if (x[i] > y[j])
{
return +1;
}
}
return y.Length.CompareTo(x.Length);
}
}
public void WriteHeapsTo(BlobBuilder writer)
{
WriteAligned(_stringWriter, writer);
WriteAligned(_userStringWriter, writer);
WriteAligned(_guidWriter, writer);
WriteAlignedBlobHeap(writer);
}
private void WriteAlignedBlobHeap(BlobBuilder builder)
{
int alignment = BitArithmetic.Align(_blobHeapSize, 4) - _blobHeapSize;
var writer = new BlobWriter(builder.ReserveBytes(_blobHeapSize + alignment));
// Perf consideration: With large heap the following loop may cause a lot of cache misses
// since the order of entries in _blobs dictionary depends on the hash of the array values,
// which is not correlated to the heap index. If we observe such issue we should order
// the entries by heap position before running this loop.
foreach (var entry in _blobs)
{
int heapOffset = MetadataTokens.GetHeapOffset(entry.Value);
var blob = entry.Key;
writer.Offset = heapOffset;
writer.WriteCompressedInteger(blob.Length);
writer.WriteBytes(blob);
}
writer.Offset = _blobHeapSize;
writer.WriteBytes(0, alignment);
}
private static void WriteAligned(BlobBuilder source, BlobBuilder target)
{
int length = source.Count;
target.LinkSuffix(source);
target.WriteBytes(0, BitArithmetic.Align(length, 4) - length);
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator 0.16.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.DevTestLabs
{
using System;
using System.Linq;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Rest;
using Microsoft.Rest.Serialization;
using Newtonsoft.Json;
using Microsoft.Rest.Azure.OData;
using Microsoft.Rest.Azure;
using Models;
/// <summary>
/// FormulaOperations operations.
/// </summary>
internal partial class FormulaOperations : IServiceOperations<DevTestLabsClient>, IFormulaOperations
{
/// <summary>
/// Initializes a new instance of the FormulaOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
internal FormulaOperations(DevTestLabsClient client)
{
if (client == null)
{
throw new ArgumentNullException("client");
}
this.Client = client;
}
/// <summary>
/// Gets a reference to the DevTestLabsClient
/// </summary>
public DevTestLabsClient Client { get; private set; }
/// <summary>
/// List formulas in a given lab.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='labName'>
/// The name of the lab.
/// </param>
/// <param name='odataQuery'>
/// OData parameters to apply to the operation.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IPage<Formula>>> ListWithHttpMessagesAsync(string resourceGroupName, string labName, ODataQuery<Formula> odataQuery = default(ODataQuery<Formula>), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (this.Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (labName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "labName");
}
if (this.Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("odataQuery", odataQuery);
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("labName", labName);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "List", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DevTestLab/labs/{labName}/formulas").ToString();
_url = _url.Replace("{subscriptionId}", Uri.EscapeDataString(this.Client.SubscriptionId));
_url = _url.Replace("{resourceGroupName}", Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{labName}", Uri.EscapeDataString(labName));
List<string> _queryParameters = new List<string>();
if (odataQuery != null)
{
var _odataFilter = odataQuery.ToString();
if (!string.IsNullOrEmpty(_odataFilter))
{
_queryParameters.Add(_odataFilter);
}
}
if (this.Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IPage<Formula>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = SafeJsonConvert.DeserializeObject<Page<Formula>>(_responseContent, this.Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Get formula.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='labName'>
/// The name of the lab.
/// </param>
/// <param name='name'>
/// The name of the formula.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<Formula>> GetResourceWithHttpMessagesAsync(string resourceGroupName, string labName, string name, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (this.Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (labName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "labName");
}
if (name == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "name");
}
if (this.Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("labName", labName);
tracingParameters.Add("name", name);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "GetResource", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DevTestLab/labs/{labName}/formulas/{name}").ToString();
_url = _url.Replace("{subscriptionId}", Uri.EscapeDataString(this.Client.SubscriptionId));
_url = _url.Replace("{resourceGroupName}", Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{labName}", Uri.EscapeDataString(labName));
_url = _url.Replace("{name}", Uri.EscapeDataString(name));
List<string> _queryParameters = new List<string>();
if (this.Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<Formula>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = SafeJsonConvert.DeserializeObject<Formula>(_responseContent, this.Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Create or replace an existing Formula. This operation can take a while to
/// complete.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='labName'>
/// The name of the lab.
/// </param>
/// <param name='name'>
/// The name of the formula.
/// </param>
/// <param name='formula'>
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<AzureOperationResponse<Formula>> CreateOrUpdateResourceWithHttpMessagesAsync(string resourceGroupName, string labName, string name, Formula formula, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Send Request
AzureOperationResponse<Formula> _response = await BeginCreateOrUpdateResourceWithHttpMessagesAsync(
resourceGroupName, labName, name, formula, customHeaders, cancellationToken);
return await this.Client.GetPutOrPatchOperationResultAsync(_response,
customHeaders,
cancellationToken);
}
/// <summary>
/// Create or replace an existing Formula. This operation can take a while to
/// complete.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='labName'>
/// The name of the lab.
/// </param>
/// <param name='name'>
/// The name of the formula.
/// </param>
/// <param name='formula'>
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<Formula>> BeginCreateOrUpdateResourceWithHttpMessagesAsync(string resourceGroupName, string labName, string name, Formula formula, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (this.Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (labName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "labName");
}
if (name == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "name");
}
if (formula == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "formula");
}
if (this.Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("labName", labName);
tracingParameters.Add("name", name);
tracingParameters.Add("formula", formula);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "BeginCreateOrUpdateResource", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DevTestLab/labs/{labName}/formulas/{name}").ToString();
_url = _url.Replace("{subscriptionId}", Uri.EscapeDataString(this.Client.SubscriptionId));
_url = _url.Replace("{resourceGroupName}", Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{labName}", Uri.EscapeDataString(labName));
_url = _url.Replace("{name}", Uri.EscapeDataString(name));
List<string> _queryParameters = new List<string>();
if (this.Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("PUT");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
if(formula != null)
{
_requestContent = SafeJsonConvert.SerializeObject(formula, this.Client.SerializationSettings);
_httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8);
_httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
}
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200 && (int)_statusCode != 201)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<Formula>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = SafeJsonConvert.DeserializeObject<Formula>(_responseContent, this.Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
// Deserialize Response
if ((int)_statusCode == 201)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = SafeJsonConvert.DeserializeObject<Formula>(_responseContent, this.Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Delete formula.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='labName'>
/// The name of the lab.
/// </param>
/// <param name='name'>
/// The name of the formula.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse> DeleteResourceWithHttpMessagesAsync(string resourceGroupName, string labName, string name, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (this.Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (labName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "labName");
}
if (name == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "name");
}
if (this.Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("labName", labName);
tracingParameters.Add("name", name);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "DeleteResource", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DevTestLab/labs/{labName}/formulas/{name}").ToString();
_url = _url.Replace("{subscriptionId}", Uri.EscapeDataString(this.Client.SubscriptionId));
_url = _url.Replace("{resourceGroupName}", Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{labName}", Uri.EscapeDataString(labName));
_url = _url.Replace("{name}", Uri.EscapeDataString(name));
List<string> _queryParameters = new List<string>();
if (this.Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("DELETE");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200 && (int)_statusCode != 204)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// List formulas in a given lab.
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IPage<Formula>>> ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (nextPageLink == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("nextPageLink", nextPageLink);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "ListNext", tracingParameters);
}
// Construct URL
string _url = "{nextLink}";
_url = _url.Replace("{nextLink}", nextPageLink);
List<string> _queryParameters = new List<string>();
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IPage<Formula>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = SafeJsonConvert.DeserializeObject<Page<Formula>>(_responseContent, this.Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
| |
using UnityEngine;
using System.Collections.Generic;
using Pathfinding.Serialization;
namespace Pathfinding {
/** Basic point graph.
* \ingroup graphs
* The point graph is the most basic graph structure, it consists of a number of interconnected points in space called nodes or waypoints.\n
* The point graph takes a Transform object as "root", this Transform will be searched for child objects, every child object will be treated as a node.
* If #recursive is enabled, it will also search the child objects of the children recursively.
* It will then check if any connections between the nodes can be made, first it will check if the distance between the nodes isn't too large (#maxDistance)
* and then it will check if the axis aligned distance isn't too high. The axis aligned distance, named #limits,
* is useful because usually an AI cannot climb very high, but linking nodes far away from each other,
* but on the same Y level should still be possible. #limits and #maxDistance are treated as being set to infinity if they are set to 0 (zero). \n
* Lastly it will check if there are any obstructions between the nodes using
* <a href="http://unity3d.com/support/documentation/ScriptReference/Physics.Raycast.html">raycasting</a> which can optionally be thick.\n
* One thing to think about when using raycasting is to either place the nodes a small
* distance above the ground in your scene or to make sure that the ground is not in the raycast \a mask to avoid the raycast from hitting the ground.\n
*
* Alternatively, a tag can be used to search for nodes.
* \see http://docs.unity3d.com/Manual/Tags.html
*
* For larger graphs, it can take quite some time to scan the graph with the default settings.
* If you have the pro version you can enable 'optimizeForSparseGraph' which will in most cases reduce the calculation times
* drastically.
*
* \note Does not support linecast because of obvious reasons.
*
* \shadowimage{pointgraph_graph.png}
* \shadowimage{pointgraph_inspector.png}
*
*/
[JsonOptIn]
public class PointGraph : NavGraph
, IUpdatableGraph {
/** Childs of this transform are treated as nodes */
[JsonMember]
public Transform root;
/** If no #root is set, all nodes with the tag is used as nodes */
[JsonMember]
public string searchTag;
/** Max distance for a connection to be valid.
* The value 0 (zero) will be read as infinity and thus all nodes not restricted by
* other constraints will be added as connections.
*
* A negative value will disable any neighbours to be added.
* It will completely stop the connection processing to be done, so it can save you processing
* power if you don't these connections.
*/
[JsonMember]
public float maxDistance;
/** Max distance along the axis for a connection to be valid. 0 = infinity */
[JsonMember]
public Vector3 limits;
/** Use raycasts to check connections */
[JsonMember]
public bool raycast = true;
/** Use the 2D Physics API */
[JsonMember]
public bool use2DPhysics;
/** Use thick raycast */
[JsonMember]
public bool thickRaycast;
/** Thick raycast radius */
[JsonMember]
public float thickRaycastRadius = 1;
/** Recursively search for child nodes to the #root */
[JsonMember]
public bool recursive = true;
/** Layer mask to use for raycast */
[JsonMember]
public LayerMask mask;
/** Optimizes the graph for sparse graphs.
*
* This can reduce calculation times for both scanning and for normal path requests by huge amounts.
* It reduces the number of node-node checks that need to be done during scan, and can also optimize getting the nearest node from the graph (such as when querying for a path).
*
* Try enabling and disabling this option, check the scan times logged when you scan the graph to see if your graph is suited for this optimization
* or if it makes it slower.
*
* The gain of using this optimization increases with larger graphs, the default scan algorithm is brute force and requires O(n^2) checks, this optimization
* along with a graph suited for it, requires only O(n) checks during scan (assuming the connection distance limits are reasonable).
*
* \warning
* When you have this enabled, you will not be able to move nodes around using scripting unless you recalculate the lookup structure at the same time.
* \see #RebuildNodeLookup
*
* If you enable this during runtime, you will need to call #RebuildNodeLookup to make sure any existing nodes are added to the lookup structure.
* If the graph doesn't have any nodes yet or if you are going to scan the graph afterwards then you do not need to do this.
*
* \astarpro
*/
[JsonMember]
public bool optimizeForSparseGraph;
PointKDTree lookupTree = new PointKDTree();
/** All nodes in this graph.
* Note that only the first #nodeCount will be non-null.
*
* You can also use the GetNodes method to get all nodes.
*/
public PointNode[] nodes;
/** Number of nodes in this graph */
public int nodeCount { get; protected set; }
public override int CountNodes () {
return nodeCount;
}
public override void GetNodes (System.Action<GraphNode> action) {
if (nodes == null) return;
var count = nodeCount;
for (int i = 0; i < count; i++) action(nodes[i]);
}
public override NNInfoInternal GetNearest (Vector3 position, NNConstraint constraint, GraphNode hint) {
return GetNearestInternal(position, constraint, true);
}
public override NNInfoInternal GetNearestForce (Vector3 position, NNConstraint constraint) {
return GetNearestInternal(position, constraint, false);
}
NNInfoInternal GetNearestInternal (Vector3 position, NNConstraint constraint, bool fastCheck) {
if (nodes == null) return new NNInfoInternal();
if (optimizeForSparseGraph) {
return new NNInfoInternal(lookupTree.GetNearest((Int3)position, fastCheck ? null : constraint));
}
float maxDistSqr = constraint == null || constraint.constrainDistance ? AstarPath.active.maxNearestNodeDistanceSqr : float.PositiveInfinity;
var nnInfo = new NNInfoInternal(null);
float minDist = float.PositiveInfinity;
float minConstDist = float.PositiveInfinity;
for (int i = 0; i < nodeCount; i++) {
PointNode node = nodes[i];
float dist = (position-(Vector3)node.position).sqrMagnitude;
if (dist < minDist) {
minDist = dist;
nnInfo.node = node;
}
if (dist < minConstDist && dist < maxDistSqr && (constraint == null || constraint.Suitable(node))) {
minConstDist = dist;
nnInfo.constrainedNode = node;
}
}
if (!fastCheck) nnInfo.node = nnInfo.constrainedNode;
nnInfo.UpdateInfo();
return nnInfo;
}
/** Add a node to the graph at the specified position.
* \note Vector3 can be casted to Int3 using (Int3)myVector.
*
* \note This needs to be called when it is safe to update nodes, which is
* - when scanning
* - during a graph update
* - inside a callback registered using AstarPath.AddWorkItem
*
* \snippet MiscSnippets.cs PointGraph.AddNode
*/
public PointNode AddNode (Int3 position) {
return AddNode(new PointNode(active), position);
}
/** Add a node with the specified type to the graph at the specified position.
*
* \param node This must be a node created using T(AstarPath.active) right before the call to this method.
* The node parameter is only there because there is no new(AstarPath) constraint on
* generic type parameters.
* \param position The node will be set to this position.
* \note Vector3 can be casted to Int3 using (Int3)myVector.
*
* \note This needs to be called when it is safe to update nodes, which is
* - when scanning
* - during a graph update
* - inside a callback registered using AstarPath.AddWorkItem
*
* \see AstarPath.AddWorkItem
*/
public T AddNode<T>(T node, Int3 position) where T : PointNode {
if (nodes == null || nodeCount == nodes.Length) {
var newNodes = new PointNode[nodes != null ? System.Math.Max(nodes.Length+4, nodes.Length*2) : 4];
if (nodes != null) nodes.CopyTo(newNodes, 0);
nodes = newNodes;
}
node.SetPosition(position);
node.GraphIndex = graphIndex;
node.Walkable = true;
nodes[nodeCount] = node;
nodeCount++;
if (optimizeForSparseGraph) AddToLookup(node);
return node;
}
/** Recursively counds children of a transform */
protected static int CountChildren (Transform tr) {
int c = 0;
foreach (Transform child in tr) {
c++;
c += CountChildren(child);
}
return c;
}
/** Recursively adds childrens of a transform as nodes */
protected void AddChildren (ref int c, Transform tr) {
foreach (Transform child in tr) {
nodes[c].position = (Int3)child.position;
nodes[c].Walkable = true;
nodes[c].gameObject = child.gameObject;
c++;
AddChildren(ref c, child);
}
}
/** Rebuilds the lookup structure for nodes.
*
* This is used when #optimizeForSparseGraph is enabled.
*
* You should call this method every time you move a node in the graph manually and
* you are using #optimizeForSparseGraph, otherwise pathfinding might not work correctly.
*
* You may also call this after you have added many nodes using the
* #AddNode method. When adding nodes using the #AddNode method they
* will be added to the lookup structure. The lookup structure will
* rebalance itself when it gets too unbalanced however if you are
* sure you won't be adding any more nodes in the short term, you can
* make sure it is perfectly balanced and thus squeeze out the last
* bit of performance by calling this method. This can improve the
* performance of the #GetNearest method slightly. The improvements
* are on the order of 10-20%.
*
* \astarpro
*/
public void RebuildNodeLookup () {
if (!optimizeForSparseGraph || nodes == null) {
lookupTree = new PointKDTree();
} else {
lookupTree.Rebuild(nodes, 0, nodeCount);
}
}
void AddToLookup (PointNode node) {
lookupTree.Add(node);
}
protected virtual PointNode[] CreateNodes (int count) {
var nodes = new PointNode[count];
for (int i = 0; i < nodeCount; i++) nodes[i] = new PointNode(active);
return nodes;
}
protected override IEnumerable<Progress> ScanInternal () {
yield return new Progress(0, "Searching for GameObjects");
if (root == null) {
// If there is no root object, try to find nodes with the specified tag instead
GameObject[] gos = searchTag != null ? GameObject.FindGameObjectsWithTag(searchTag) : null;
if (gos == null) {
nodes = new PointNode[0];
nodeCount = 0;
yield break;
}
yield return new Progress(0.1f, "Creating nodes");
// Create all the nodes
nodeCount = gos.Length;
nodes = CreateNodes(nodeCount);
for (int i = 0; i < gos.Length; i++) {
nodes[i].position = (Int3)gos[i].transform.position;
nodes[i].Walkable = true;
nodes[i].gameObject = gos[i].gameObject;
}
} else {
// Search the root for children and create nodes for them
if (!recursive) {
nodeCount = root.childCount;
nodes = CreateNodes(nodeCount);
int c = 0;
foreach (Transform child in root) {
nodes[c].position = (Int3)child.position;
nodes[c].Walkable = true;
nodes[c].gameObject = child.gameObject;
c++;
}
} else {
nodeCount = CountChildren(root);
nodes = CreateNodes(nodeCount);
int startID = 0;
AddChildren(ref startID, root);
}
}
if (optimizeForSparseGraph) {
yield return new Progress(0.15f, "Building node lookup");
RebuildNodeLookup();
}
foreach (var progress in ConnectNodesAsync()) yield return progress.MapTo(0.16f, 1.0f);
}
/** Recalculates connections for all nodes in the graph.
* This is useful if you have created nodes manually using #AddNode and then want to connect them in the same way as the point graph normally connects nodes.
*/
public void ConnectNodes () {
foreach (var progress in ConnectNodesAsync()) {}
}
/** Calculates connections for all nodes in the graph.
* This is an IEnumerable, you can iterate through it using e.g foreach to get progress information.
*/
IEnumerable<Progress> ConnectNodesAsync () {
if (maxDistance >= 0) {
// To avoid too many allocations, these lists are reused for each node
var connections = new List<Connection>();
var candidateConnections = new List<GraphNode>();
long maxSquaredRange;
// Max possible squared length of a connection between two nodes
// This is used to speed up the calculations by skipping a lot of nodes that do not need to be checked
if (maxDistance == 0 && (limits.x == 0 || limits.y == 0 || limits.z == 0)) {
maxSquaredRange = long.MaxValue;
} else {
maxSquaredRange = (long)(Mathf.Max(limits.x, Mathf.Max(limits.y, Mathf.Max(limits.z, maxDistance))) * Int3.Precision) + 1;
maxSquaredRange *= maxSquaredRange;
}
// Report progress every N nodes
const int YieldEveryNNodes = 512;
// Loop through all nodes and add connections to other nodes
for (int i = 0; i < nodeCount; i++) {
if (i % YieldEveryNNodes == 0) {
yield return new Progress(i/(float)nodes.Length, "Connecting nodes");
}
connections.Clear();
var node = nodes[i];
if (optimizeForSparseGraph) {
candidateConnections.Clear();
lookupTree.GetInRange(node.position, maxSquaredRange, candidateConnections);
for (int j = 0; j < candidateConnections.Count; j++) {
var other = candidateConnections[j] as PointNode;
float dist;
if (other != node && IsValidConnection(node, other, out dist)) {
connections.Add(new Connection(
other,
/** \todo Is this equal to .costMagnitude */
(uint)Mathf.RoundToInt(dist*Int3.FloatPrecision)
));
}
}
} else {
// Only brute force is available in the free version
for (int j = 0; j < nodeCount; j++) {
if (i == j) continue;
PointNode other = nodes[j];
float dist;
if (IsValidConnection(node, other, out dist)) {
connections.Add(new Connection(
other,
/** \todo Is this equal to .costMagnitude */
(uint)Mathf.RoundToInt(dist*Int3.FloatPrecision)
));
}
}
}
node.connections = connections.ToArray();
}
}
}
/** Returns if the connection between \a a and \a b is valid.
* Checks for obstructions using raycasts (if enabled) and checks for height differences.\n
* As a bonus, it outputs the distance between the nodes too if the connection is valid.
*
* \note This is not the same as checking if node a is connected to node b.
* That should be done using a.ContainsConnection(b)
*/
public virtual bool IsValidConnection (GraphNode a, GraphNode b, out float dist) {
dist = 0;
if (!a.Walkable || !b.Walkable) return false;
var dir = (Vector3)(b.position-a.position);
if (
(!Mathf.Approximately(limits.x, 0) && Mathf.Abs(dir.x) > limits.x) ||
(!Mathf.Approximately(limits.y, 0) && Mathf.Abs(dir.y) > limits.y) ||
(!Mathf.Approximately(limits.z, 0) && Mathf.Abs(dir.z) > limits.z)) {
return false;
}
dist = dir.magnitude;
if (maxDistance == 0 || dist < maxDistance) {
if (raycast) {
var ray = new Ray((Vector3)a.position, dir);
var invertRay = new Ray((Vector3)b.position, -dir);
if (use2DPhysics) {
if (thickRaycast) {
return !Physics2D.CircleCast(ray.origin, thickRaycastRadius, ray.direction, dist, mask) && !Physics2D.CircleCast(invertRay.origin, thickRaycastRadius, invertRay.direction, dist, mask);
} else {
return !Physics2D.Linecast((Vector2)(Vector3)a.position, (Vector2)(Vector3)b.position, mask) && !Physics2D.Linecast((Vector2)(Vector3)b.position, (Vector2)(Vector3)a.position, mask);
}
} else {
if (thickRaycast) {
return !Physics.SphereCast(ray, thickRaycastRadius, dist, mask) && !Physics.SphereCast(invertRay, thickRaycastRadius, dist, mask);
} else {
return !Physics.Linecast((Vector3)a.position, (Vector3)b.position, mask) && !Physics.Linecast((Vector3)b.position, (Vector3)a.position, mask);
}
}
} else {
return true;
}
}
return false;
}
GraphUpdateThreading IUpdatableGraph.CanUpdateAsync (GraphUpdateObject o) {
return GraphUpdateThreading.UnityThread;
}
void IUpdatableGraph.UpdateAreaInit (GraphUpdateObject o) {}
void IUpdatableGraph.UpdateAreaPost (GraphUpdateObject o) {}
/** Updates an area in the list graph.
* Recalculates possibly affected connections, i.e all connectionlines passing trough the bounds of the \a guo will be recalculated
* \astarpro */
void IUpdatableGraph.UpdateArea (GraphUpdateObject guo) {
if (nodes == null) return;
for (int i = 0; i < nodeCount; i++) {
var node = nodes[i];
if (guo.bounds.Contains((Vector3)node.position)) {
guo.WillUpdateNode(node);
guo.Apply(node);
}
}
if (guo.updatePhysics) {
// Use a copy of the bounding box, we should not change the GUO's bounding box since it might be used for other graph updates
Bounds bounds = guo.bounds;
if (thickRaycast) {
// Expand the bounding box to account for the thick raycast
bounds.Expand(thickRaycastRadius*2);
}
// Create a temporary list used for holding connection data
List<Connection> tmpList = Pathfinding.Util.ListPool<Connection>.Claim();
for (int i = 0; i < nodeCount; i++) {
PointNode node = nodes[i];
var nodePos = (Vector3)node.position;
List<Connection> conn = null;
for (int j = 0; j < nodeCount; j++) {
if (j == i) continue;
var otherNodePos = (Vector3)nodes[j].position;
// Check if this connection intersects the bounding box.
// If it does we need to recalculate that connection.
if (VectorMath.SegmentIntersectsBounds(bounds, nodePos, otherNodePos)) {
float dist;
PointNode other = nodes[j];
bool contains = node.ContainsConnection(other);
bool validConnection = IsValidConnection(node, other, out dist);
// Fill the 'conn' list when we need to change a connection
if (conn == null && (contains != validConnection)) {
tmpList.Clear();
conn = tmpList;
conn.AddRange(node.connections);
}
if (!contains && validConnection) {
// A new connection should be added
uint cost = (uint)Mathf.RoundToInt(dist*Int3.FloatPrecision);
conn.Add(new Connection(other, cost));
} else if (contains && !validConnection) {
// A connection should be removed
for (int q = 0; q < conn.Count; q++) {
if (conn[q].node == other) {
conn.RemoveAt(q);
break;
}
}
}
}
}
// Save the new connections if any were changed
if (conn != null) {
node.connections = conn.ToArray();
}
}
// Release buffers back to the pool
Pathfinding.Util.ListPool<Connection>.Release(ref tmpList);
}
}
#if UNITY_EDITOR
public override void OnDrawGizmos (Pathfinding.Util.RetainedGizmos gizmos, bool drawNodes) {
base.OnDrawGizmos(gizmos, drawNodes);
if (!drawNodes) return;
Gizmos.color = new Color(0.161f, 0.341f, 1f, 0.5f);
if (root != null) {
DrawChildren(this, root);
} else if (!string.IsNullOrEmpty(searchTag)) {
GameObject[] gos = GameObject.FindGameObjectsWithTag(searchTag);
for (int i = 0; i < gos.Length; i++) {
Gizmos.DrawCube(gos[i].transform.position, Vector3.one*UnityEditor.HandleUtility.GetHandleSize(gos[i].transform.position)*0.1F);
}
}
}
static void DrawChildren (PointGraph graph, Transform tr) {
foreach (Transform child in tr) {
Gizmos.DrawCube(child.position, Vector3.one*UnityEditor.HandleUtility.GetHandleSize(child.position)*0.1F);
if (graph.recursive) DrawChildren(graph, child);
}
}
#endif
protected override void PostDeserialization (GraphSerializationContext ctx) {
RebuildNodeLookup();
}
public override void RelocateNodes (Matrix4x4 deltaMatrix) {
base.RelocateNodes(deltaMatrix);
RebuildNodeLookup();
}
protected override void DeserializeSettingsCompatibility (GraphSerializationContext ctx) {
base.DeserializeSettingsCompatibility(ctx);
root = ctx.DeserializeUnityObject() as Transform;
searchTag = ctx.reader.ReadString();
maxDistance = ctx.reader.ReadSingle();
limits = ctx.DeserializeVector3();
raycast = ctx.reader.ReadBoolean();
use2DPhysics = ctx.reader.ReadBoolean();
thickRaycast = ctx.reader.ReadBoolean();
thickRaycastRadius = ctx.reader.ReadSingle();
recursive = ctx.reader.ReadBoolean();
ctx.reader.ReadBoolean(); // Deprecated field
mask = (LayerMask)ctx.reader.ReadInt32();
optimizeForSparseGraph = ctx.reader.ReadBoolean();
ctx.reader.ReadBoolean(); // Deprecated field
}
protected override void SerializeExtraInfo (GraphSerializationContext ctx) {
// Serialize node data
if (nodes == null) ctx.writer.Write(-1);
// Length prefixed array of nodes
ctx.writer.Write(nodeCount);
for (int i = 0; i < nodeCount; i++) {
// -1 indicates a null field
if (nodes[i] == null) ctx.writer.Write(-1);
else {
ctx.writer.Write(0);
nodes[i].SerializeNode(ctx);
}
}
}
protected override void DeserializeExtraInfo (GraphSerializationContext ctx) {
int count = ctx.reader.ReadInt32();
if (count == -1) {
nodes = null;
return;
}
nodes = new PointNode[count];
nodeCount = count;
for (int i = 0; i < nodes.Length; i++) {
if (ctx.reader.ReadInt32() == -1) continue;
nodes[i] = new PointNode(active);
nodes[i].DeserializeNode(ctx);
}
}
}
}
| |
using Lucene.Net.Diagnostics;
using System;
using System.Collections.Generic;
using System.Diagnostics;
namespace Lucene.Net.Index
{
/*
* 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 ByteRunAutomaton = Lucene.Net.Util.Automaton.ByteRunAutomaton;
using BytesRef = Lucene.Net.Util.BytesRef;
using CompiledAutomaton = Lucene.Net.Util.Automaton.CompiledAutomaton;
using Int32sRef = Lucene.Net.Util.Int32sRef;
using StringHelper = Lucene.Net.Util.StringHelper;
using Transition = Lucene.Net.Util.Automaton.Transition;
/// <summary>
/// A <see cref="FilteredTermsEnum"/> that enumerates terms based upon what is accepted by a
/// DFA.
/// <para/>
/// The algorithm is such:
/// <list type="number">
/// <item><description>As long as matches are successful, keep reading sequentially.</description></item>
/// <item><description>When a match fails, skip to the next string in lexicographic order that
/// does not enter a reject state.</description></item>
/// </list>
/// <para>
/// The algorithm does not attempt to actually skip to the next string that is
/// completely accepted. this is not possible when the language accepted by the
/// FSM is not finite (i.e. * operator).
/// </para>
/// @lucene.experimental
/// </summary>
internal class AutomatonTermsEnum : FilteredTermsEnum
{
// a tableized array-based form of the DFA
private readonly ByteRunAutomaton runAutomaton;
// common suffix of the automaton
private readonly BytesRef commonSuffixRef;
// true if the automaton accepts a finite language
private readonly bool? finite;
// array of sorted transitions for each state, indexed by state number
private readonly Transition[][] allTransitions;
// for path tracking: each long records gen when we last
// visited the state; we use gens to avoid having to clear
private readonly long[] visited;
private long curGen;
// the reference used for seeking forwards through the term dictionary
private readonly BytesRef seekBytesRef = new BytesRef(10);
// true if we are enumerating an infinite portion of the DFA.
// in this case it is faster to drive the query based on the terms dictionary.
// when this is true, linearUpperBound indicate the end of range
// of terms where we should simply do sequential reads instead.
private bool linear = false;
private readonly BytesRef linearUpperBound = new BytesRef(10);
private readonly IComparer<BytesRef> termComp;
/// <summary>
/// Construct an enumerator based upon an automaton, enumerating the specified
/// field, working on a supplied <see cref="TermsEnum"/>
/// <para/>
/// @lucene.experimental
/// </summary>
/// <param name="tenum"> TermsEnum </param>
/// <param name="compiled"> CompiledAutomaton </param>
public AutomatonTermsEnum(TermsEnum tenum, CompiledAutomaton compiled)
: base(tenum)
{
this.finite = compiled.Finite;
this.runAutomaton = compiled.RunAutomaton;
if (Debugging.AssertsEnabled) Debugging.Assert(this.runAutomaton != null);
this.commonSuffixRef = compiled.CommonSuffixRef;
this.allTransitions = compiled.SortedTransitions;
// used for path tracking, where each bit is a numbered state.
visited = new long[runAutomaton.Count];
termComp = Comparer;
}
/// <summary>
/// Returns <c>true</c> if the term matches the automaton. Also stashes away the term
/// to assist with smart enumeration.
/// </summary>
protected override AcceptStatus Accept(BytesRef term)
{
if (commonSuffixRef is null || StringHelper.EndsWith(term, commonSuffixRef))
{
if (runAutomaton.Run(term.Bytes, term.Offset, term.Length))
{
return linear ? AcceptStatus.YES : AcceptStatus.YES_AND_SEEK;
}
else
{
return (linear && termComp.Compare(term, linearUpperBound) < 0) ? AcceptStatus.NO : AcceptStatus.NO_AND_SEEK;
}
}
else
{
return (linear && termComp.Compare(term, linearUpperBound) < 0) ? AcceptStatus.NO : AcceptStatus.NO_AND_SEEK;
}
}
protected override BytesRef NextSeekTerm(BytesRef term)
{
//System.out.println("ATE.nextSeekTerm term=" + term);
if (term is null)
{
if (Debugging.AssertsEnabled) Debugging.Assert(seekBytesRef.Length == 0);
// return the empty term, as its valid
if (runAutomaton.IsAccept(runAutomaton.InitialState))
{
return seekBytesRef;
}
}
else
{
seekBytesRef.CopyBytes(term);
}
// seek to the next possible string;
if (NextString())
{
return seekBytesRef; // reposition
}
else
{
return null; // no more possible strings can match
}
}
/// <summary>
/// Sets the enum to operate in linear fashion, as we have found
/// a looping transition at position: we set an upper bound and
/// act like a <see cref="Search.TermRangeQuery"/> for this portion of the term space.
/// </summary>
private void SetLinear(int position)
{
if (Debugging.AssertsEnabled) Debugging.Assert(linear == false);
int state = runAutomaton.InitialState;
int maxInterval = 0xff;
for (int i = 0; i < position; i++)
{
state = runAutomaton.Step(state, seekBytesRef.Bytes[i] & 0xff);
if (Debugging.AssertsEnabled) Debugging.Assert(state >= 0,"state={0}", state);
}
for (int i = 0; i < allTransitions[state].Length; i++)
{
Transition t = allTransitions[state][i];
if (t.Min <= (seekBytesRef.Bytes[position] & 0xff) && (seekBytesRef.Bytes[position] & 0xff) <= t.Max)
{
maxInterval = t.Max;
break;
}
}
// 0xff terms don't get the optimization... not worth the trouble.
if (maxInterval != 0xff)
{
maxInterval++;
}
int length = position + 1; // value + maxTransition
if (linearUpperBound.Bytes.Length < length)
{
linearUpperBound.Bytes = new byte[length];
}
Array.Copy(seekBytesRef.Bytes, 0, linearUpperBound.Bytes, 0, position);
linearUpperBound.Bytes[position] = (byte)maxInterval;
linearUpperBound.Length = length;
linear = true;
}
private readonly Int32sRef savedStates = new Int32sRef(10);
/// <summary>
/// Increments the byte buffer to the next string in binary order after s that will not put
/// the machine into a reject state. If such a string does not exist, returns
/// <c>false</c>.
/// <para/>
/// The correctness of this method depends upon the automaton being deterministic,
/// and having no transitions to dead states.
/// </summary>
/// <returns> <c>true</c> if more possible solutions exist for the DFA </returns>
private bool NextString()
{
int state;
int pos = 0;
savedStates.Grow(seekBytesRef.Length + 1);
int[] states = savedStates.Int32s;
states[0] = runAutomaton.InitialState;
while (true)
{
curGen++;
linear = false;
// walk the automaton until a character is rejected.
for (state = states[pos]; pos < seekBytesRef.Length; pos++)
{
visited[state] = curGen;
int nextState = runAutomaton.Step(state, seekBytesRef.Bytes[pos] & 0xff);
if (nextState == -1)
{
break;
}
states[pos + 1] = nextState;
// we found a loop, record it for faster enumeration
if ((finite == false) && !linear && visited[nextState] == curGen)
{
SetLinear(pos);
}
state = nextState;
}
// take the useful portion, and the last non-reject state, and attempt to
// append characters that will match.
if (NextString(state, pos))
{
return true;
} // no more solutions exist from this useful portion, backtrack
else
{
if ((pos = Backtrack(pos)) < 0) // no more solutions at all
{
return false;
}
int newState = runAutomaton.Step(states[pos], seekBytesRef.Bytes[pos] & 0xff);
if (newState >= 0 && runAutomaton.IsAccept(newState))
/* String is good to go as-is */
{
return true;
}
/* else advance further */
// TODO: paranoia? if we backtrack thru an infinite DFA, the loop detection is important!
// for now, restart from scratch for all infinite DFAs
if (finite == false)
{
pos = 0;
}
}
}
}
/// <summary>
/// Returns the next string in lexicographic order that will not put
/// the machine into a reject state.
/// <para/>
/// This method traverses the DFA from the given position in the string,
/// starting at the given state.
/// <para/>
/// If this cannot satisfy the machine, returns <c>false</c>. This method will
/// walk the minimal path, in lexicographic order, as long as possible.
/// <para/>
/// If this method returns <c>false</c>, then there might still be more solutions,
/// it is necessary to backtrack to find out.
/// </summary>
/// <param name="state"> current non-reject state </param>
/// <param name="position"> useful portion of the string </param>
/// <returns> <c>true</c> if more possible solutions exist for the DFA from this
/// position </returns>
private bool NextString(int state, int position)
{
/*
* the next lexicographic character must be greater than the existing
* character, if it exists.
*/
int c = 0;
if (position < seekBytesRef.Length)
{
c = seekBytesRef.Bytes[position] & 0xff;
// if the next byte is 0xff and is not part of the useful portion,
// then by definition it puts us in a reject state, and therefore this
// path is dead. there cannot be any higher transitions. backtrack.
if (c++ == 0xff)
{
return false;
}
}
seekBytesRef.Length = position;
visited[state] = curGen;
Transition[] transitions = allTransitions[state];
// find the minimal path (lexicographic order) that is >= c
for (int i = 0; i < transitions.Length; i++)
{
Transition transition = transitions[i];
if (transition.Max >= c)
{
int nextChar = Math.Max(c, transition.Min);
// append either the next sequential char, or the minimum transition
seekBytesRef.Grow(seekBytesRef.Length + 1);
seekBytesRef.Length++;
seekBytesRef.Bytes[seekBytesRef.Length - 1] = (byte)nextChar;
state = transition.Dest.Number;
/*
* as long as is possible, continue down the minimal path in
* lexicographic order. if a loop or accept state is encountered, stop.
*/
while (visited[state] != curGen && !runAutomaton.IsAccept(state))
{
visited[state] = curGen;
/*
* Note: we work with a DFA with no transitions to dead states.
* so the below is ok, if it is not an accept state,
* then there MUST be at least one transition.
*/
transition = allTransitions[state][0];
state = transition.Dest.Number;
// append the minimum transition
seekBytesRef.Grow(seekBytesRef.Length + 1);
seekBytesRef.Length++;
seekBytesRef.Bytes[seekBytesRef.Length - 1] = (byte)transition.Min;
// we found a loop, record it for faster enumeration
if ((finite == false) && !linear && visited[state] == curGen)
{
SetLinear(seekBytesRef.Length - 1);
}
}
return true;
}
}
return false;
}
/// <summary>
/// Attempts to backtrack thru the string after encountering a dead end
/// at some given position. Returns <c>false</c> if no more possible strings
/// can match.
/// </summary>
/// <param name="position"> current position in the input string </param>
/// <returns> position >=0 if more possible solutions exist for the DFA </returns>
private int Backtrack(int position)
{
while (position-- > 0)
{
int nextChar = seekBytesRef.Bytes[position] & 0xff;
// if a character is 0xff its a dead-end too,
// because there is no higher character in binary sort order.
if (nextChar++ != 0xff)
{
seekBytesRef.Bytes[position] = (byte)nextChar;
seekBytesRef.Length = position + 1;
return position;
}
}
return -1; // all solutions exhausted
}
}
}
| |
/*
Copyright (c) 2004-2006 Tomas Matousek.
The use and distribution terms for this software are contained in the file named License.txt,
which can be found in the root of the Phalanger distribution. By using this software
in any fashion, you are agreeing to be bound by the terms of this license.
You must not remove this notice from this software.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using PHP.Core;
using Convert = PHP.Core.Convert;
using System.Diagnostics;
namespace PHP.Library
{
public delegate object GetSetRestoreDelegate(LocalConfiguration config, string option, object value, IniAction action);
/// <summary>
/// An action which can be performed on option.
/// </summary>
public enum IniAction
{
Restore, Set, Get
}
[Flags]
public enum IniFlags : byte
{
Unsupported = 0,
Global = 0,
Supported = 1,
Local = 2,
Http = 4,
}
[Flags]
public enum IniAccessability
{
User = 1,
PerDirectory = 2,
System = 4,
All = 7,
Global = PerDirectory | System,
Local = All
}
public static class IniOptions
{
#region Options Table
/// <summary>
/// Holds information about the option.
/// </summary>
public class OptionDefinition // GENERICS: struct
{
public readonly IniFlags Flags;
public readonly GetSetRestoreDelegate Gsr;
public readonly string Extension;
internal OptionDefinition(IniFlags flags, GetSetRestoreDelegate gsr, string extension)
{
this.Flags = flags;
this.Gsr = gsr;
this.Extension = extension;
}
}
private static Dictionary<string, OptionDefinition> options;
private static GetSetRestoreDelegate GsrCoreOption = new GetSetRestoreDelegate(PhpIni.GetSetRestoreCoreOption);
/// <summary>
/// Gets a number of currently registered options.
/// </summary>
public static int Count { get { return options.Count; } }
/// <summary>
/// Gets an option by name.
/// </summary>
/// <param name="name">The name of the option.</param>
/// <returns>Information about the option or a <B>null</B> reference if it has not been registered yet.</returns>
/// <exception cref="ArgumentNullException"><paramref name="name"/> is a <B>null</B> reference.</exception>
/// <remarks>Shouldn't be called before or during option registration (not thread safe for writes).</remarks>
public static OptionDefinition GetOption(string name)
{
if (name == null)
throw new ArgumentNullException("name");
OptionDefinition value;
return options.TryGetValue(name, out value) ? value : null;
}
/// <summary>
/// Registeres a legacy configuration option. Not thread safe.
/// </summary>
/// <param name="name">A case-sensitive unique option name.</param>
/// <param name="flags">Flags.</param>
/// <param name="gsr">A delegate pointing to a method which will perform option's value getting, setting, and restoring.</param>
/// <param name="extension">A case-sensitive name of the extension which the option belongs to. Can be a <B>null</B> reference.</param>
/// <remarks>
/// Registered options are known to <c>ini_get</c>, <c>ini_set</c>, and <c>ini_restore</c> PHP functions.
/// </remarks>
/// <exception cref="ArgumentNullException"><paramref name="name"/> is a <B>null</B> reference.</exception>
/// <exception cref="ArgumentNullException"><paramref name="gsr"/> is a <B>null</B> reference.</exception>
/// <exception cref="ArgumentException">An option with specified name has already been registered.</exception>
public static void Register(string name, IniFlags flags, GetSetRestoreDelegate gsr, string extension)
{
if (name == null)
throw new ArgumentNullException("name");
if (gsr == null)
throw new ArgumentNullException("gsr");
if (options.ContainsKey(name))
throw new ArgumentException(LibResources.GetString("option_already_registered", name));
options.Add(name, new OptionDefinition(flags, gsr, extension));
}
/// <summary>
/// Registeres a Core option.
/// </summary>
private static void RegisterCoreOption(string name, IniFlags flags)
{
options.Add(name, new OptionDefinition(flags, GsrCoreOption, null));
}
#endregion
#region Initialization
static IniOptions()
{
options = new Dictionary<string, OptionDefinition>(150);
RegisterCoreOption("allow_call_time_pass_reference", IniFlags.Unsupported | IniFlags.Global);
RegisterCoreOption("allow_url_fopen", IniFlags.Supported | IniFlags.Local);
RegisterCoreOption("allow_webdav_methods", IniFlags.Unsupported | IniFlags.Global);
RegisterCoreOption("always_populate_raw_post_data", IniFlags.Supported | IniFlags.Local);
RegisterCoreOption("arg_separator.input", IniFlags.Unsupported | IniFlags.Global);
RegisterCoreOption("arg_separator.output", IniFlags.Unsupported | IniFlags.Local);
RegisterCoreOption("asp_tags", IniFlags.Supported | IniFlags.Global);
RegisterCoreOption("assert.active", IniFlags.Supported | IniFlags.Local);
RegisterCoreOption("assert.bail", IniFlags.Supported | IniFlags.Local);
RegisterCoreOption("assert.callback", IniFlags.Supported | IniFlags.Local);
RegisterCoreOption("assert.quiet_eval", IniFlags.Supported | IniFlags.Local);
RegisterCoreOption("assert.warning", IniFlags.Supported | IniFlags.Local);
RegisterCoreOption("async_send", IniFlags.Unsupported | IniFlags.Local);
RegisterCoreOption("auto_append_file", IniFlags.Unsupported | IniFlags.Global);
RegisterCoreOption("auto_detect_line_endings", IniFlags.Unsupported | IniFlags.Local);
RegisterCoreOption("auto_prepend_file", IniFlags.Unsupported | IniFlags.Global);
RegisterCoreOption("browscap", IniFlags.Unsupported | IniFlags.Global);
RegisterCoreOption("cgi.force_redirect", IniFlags.Unsupported | IniFlags.Global);
RegisterCoreOption("cgi.redirect_status_env", IniFlags.Unsupported | IniFlags.Global);
RegisterCoreOption("cgi.rfc2616_headers", IniFlags.Unsupported | IniFlags.Global);
RegisterCoreOption("child_terminate", IniFlags.Unsupported | IniFlags.Local);
RegisterCoreOption("debugger.enabled", IniFlags.Unsupported | IniFlags.Global);
RegisterCoreOption("debugger.host", IniFlags.Unsupported | IniFlags.Global);
RegisterCoreOption("debugger.port", IniFlags.Unsupported | IniFlags.Global);
RegisterCoreOption("default_charset", IniFlags.Supported | IniFlags.Local | IniFlags.Http);
RegisterCoreOption("default_mimetype", IniFlags.Supported | IniFlags.Local | IniFlags.Http);
RegisterCoreOption("default_socket_timeout", IniFlags.Supported | IniFlags.Local);
RegisterCoreOption("define_syslog_variables", IniFlags.Unsupported | IniFlags.Local);
RegisterCoreOption("disable_classes", IniFlags.Unsupported | IniFlags.Global);
RegisterCoreOption("disable_functions", IniFlags.Supported | IniFlags.Global);
RegisterCoreOption("display_errors", IniFlags.Supported | IniFlags.Local);
RegisterCoreOption("display_startup_errors", IniFlags.Unsupported | IniFlags.Local);
RegisterCoreOption("doc_root", IniFlags.Unsupported | IniFlags.Global);
RegisterCoreOption("enable_dl", IniFlags.Unsupported | IniFlags.Global);
RegisterCoreOption("engine", IniFlags.Unsupported | IniFlags.Local);
RegisterCoreOption("error_append_string", IniFlags.Supported | IniFlags.Local);
RegisterCoreOption("error_log", IniFlags.Supported | IniFlags.Local);
RegisterCoreOption("error_prepend_string", IniFlags.Supported | IniFlags.Local);
RegisterCoreOption("error_reporting", IniFlags.Supported | IniFlags.Local);
RegisterCoreOption("expose_php", IniFlags.Unsupported | IniFlags.Global);
RegisterCoreOption("extension_dir", IniFlags.Supported | IniFlags.Global);
RegisterCoreOption("fastcgi.impersonate", IniFlags.Unsupported | IniFlags.Global);
RegisterCoreOption("file_uploads", IniFlags.Supported | IniFlags.Global);
RegisterCoreOption("from", IniFlags.Supported | IniFlags.Local);
RegisterCoreOption("gpc_order", IniFlags.Unsupported | IniFlags.Local);
RegisterCoreOption("html_errors", IniFlags.Supported | IniFlags.Local);
RegisterCoreOption("ignore_repeated_errors", IniFlags.Unsupported | IniFlags.Local);
RegisterCoreOption("ignore_repeated_source", IniFlags.Unsupported | IniFlags.Local);
RegisterCoreOption("ignore_user_abort", IniFlags.Supported | IniFlags.Local | IniFlags.Http);
RegisterCoreOption("implicit_flush", IniFlags.Supported | IniFlags.Global);
RegisterCoreOption("include_path", IniFlags.Supported | IniFlags.Local);
RegisterCoreOption("last_modified", IniFlags.Unsupported | IniFlags.Local);
RegisterCoreOption("log_errors", IniFlags.Supported | IniFlags.Local);
RegisterCoreOption("log_errors_max_len", IniFlags.Unsupported | IniFlags.Local);
RegisterCoreOption("magic_quotes_gpc", IniFlags.Supported | IniFlags.Global);
RegisterCoreOption("magic_quotes_runtime", IniFlags.Supported | IniFlags.Local);
RegisterCoreOption("magic_quotes_sybase", IniFlags.Supported | IniFlags.Local);
RegisterCoreOption("max_execution_time", IniFlags.Supported | IniFlags.Local);
RegisterCoreOption("max_input_time", IniFlags.Unsupported | IniFlags.Global);
RegisterCoreOption("memory_limit", IniFlags.Supported | IniFlags.Local);
RegisterCoreOption("mime_magic.magicfile", IniFlags.Unsupported | IniFlags.Global);
RegisterCoreOption("open_basedir", IniFlags.Supported | IniFlags.Global);
RegisterCoreOption("output_buffering", IniFlags.Supported | IniFlags.Global);
RegisterCoreOption("output_handler", IniFlags.Supported | IniFlags.Global);
RegisterCoreOption("post_max_size", IniFlags.Supported | IniFlags.Global);
RegisterCoreOption("precision", IniFlags.Unsupported | IniFlags.Local);
RegisterCoreOption("register_argc_argv", IniFlags.Supported | IniFlags.Global);
RegisterCoreOption("register_globals", IniFlags.Supported | IniFlags.Global);
RegisterCoreOption("register_long_arrays", IniFlags.Supported | IniFlags.Global);
RegisterCoreOption("report_memleaks", IniFlags.Unsupported | IniFlags.Global);
RegisterCoreOption("safe_mode", IniFlags.Supported | IniFlags.Global);
RegisterCoreOption("safe_mode_allowed_env_vars", IniFlags.Unsupported | IniFlags.Global);
RegisterCoreOption("safe_mode_exec_dir", IniFlags.Supported | IniFlags.Global);
RegisterCoreOption("safe_mode_gid", IniFlags.Unsupported | IniFlags.Global);
RegisterCoreOption("safe_mode_include_dir", IniFlags.Unsupported | IniFlags.Global);
RegisterCoreOption("safe_mode_protected_env_vars", IniFlags.Unsupported | IniFlags.Global);
RegisterCoreOption("session.auto_start", IniFlags.Supported | IniFlags.Global | IniFlags.Http);
RegisterCoreOption("session.save_handler", IniFlags.Supported | IniFlags.Local | IniFlags.Http);
RegisterCoreOption("session.name", IniFlags.Supported | IniFlags.Global | IniFlags.Http);
RegisterCoreOption("short_open_tag", IniFlags.Supported | IniFlags.Global);
RegisterCoreOption("sql.safe_mode", IniFlags.Unsupported | IniFlags.Global);
RegisterCoreOption("track_errors", IniFlags.Unsupported | IniFlags.Local);
RegisterCoreOption("unserialize_callback_func", IniFlags.Supported | IniFlags.Local);
RegisterCoreOption("upload_max_filesize", IniFlags.Supported | IniFlags.Global);
RegisterCoreOption("upload_tmp_dir", IniFlags.Supported | IniFlags.Global);
RegisterCoreOption("url_rewriter.tags", IniFlags.Unsupported | IniFlags.Local);
RegisterCoreOption("user_agent", IniFlags.Supported | IniFlags.Local);
RegisterCoreOption("user_dir", IniFlags.Unsupported | IniFlags.Global);
RegisterCoreOption("variables_order", IniFlags.Supported | IniFlags.Local);
RegisterCoreOption("warn_plus_overloading", IniFlags.Unsupported | IniFlags.Global);
RegisterCoreOption("xbithack", IniFlags.Unsupported | IniFlags.Local);
RegisterCoreOption("y2k_compliance", IniFlags.Unsupported | IniFlags.Local);
RegisterCoreOption("zend.ze1_compatibility_mode", IniFlags.Supported | IniFlags.Local);
}
#endregion
/// <summary>
/// Tries to get, set, or restore an option given its PHP name and value.
/// </summary>
/// <param name="name">The option name.</param>
/// <param name="value">The option new value if applicable.</param>
/// <param name="action">The action to be taken.</param>
/// <param name="error"><B>true</B>, on failure.</param>
/// <returns>The option old value.</returns>
/// <exception cref="PhpException">The option not supported (Warning).</exception>
/// <exception cref="PhpException">The option is read only but action demands write access (Warning).</exception>
internal static object TryGetSetRestore(string name, object value, IniAction action, out bool error)
{
Debug.Assert(name != null);
error = true;
IniOptions.OptionDefinition option = GetOption(name);
// option not found:
if (option == null)
{
PhpException.Throw(PhpError.Warning, LibResources.GetString("unknown_option", name));
return null;
}
// the option is known but not supported:
if ((option.Flags & IniFlags.Supported) == 0)
{
PhpException.Throw(PhpError.Warning, LibResources.GetString("option_not_supported", name));
return null;
}
// the option is global thus cannot be changed:
if ((option.Flags & IniFlags.Local) == 0 && action != IniAction.Get)
{
PhpException.Throw(PhpError.Warning, LibResources.GetString("option_readonly", name));
return null;
}
error = false;
return option.Gsr(Configuration.Local, name, value, action);
}
/// <summary>
/// Formats a state of the specified option into <see cref="PhpArray"/>.
/// </summary>
/// <param name="flags">The option's flag.</param>
/// <param name="defaultValue">A default value of the option.</param>
/// <param name="localValue">A script local value of the option.</param>
/// <returns>An array containig keys <c>"global_value"</c>, <c>"local_value"</c>, <c>"access"</c>.</returns>
private static PhpArray FormatOptionState(IniFlags flags, object defaultValue, object localValue)
{
PhpArray result = new PhpArray(0, 3);
// default value:
result.Add("global_value", Convert.ObjectToString(defaultValue));
// local value:
result.Add("local_value", Convert.ObjectToString(localValue));
// accessibility:
result.Add("access", (int)((flags & IniFlags.Local) != 0 ? IniAccessability.Local : IniAccessability.Global));
return result;
}
/// <summary>
/// Gets an array of options states formatted by <see cref="FormatOptionState"/>.
/// </summary>
/// <param name="extension">An extension which options to retrieve.</param>
/// <param name="result">A dictionary where to add options.</param>
/// <returns>An array of option states.</returns>
/// <remarks>Options already contained in <paramref name="result"/> are overwritten.</remarks>
internal static IDictionary GetAllOptionStates(string extension, IDictionary result)
{
Debug.Assert(result != null);
LocalConfiguration local = Configuration.Local;
LocalConfiguration @default = Configuration.DefaultLocal;
foreach (KeyValuePair<string, OptionDefinition> entry in options)
{
string name = entry.Key;
OptionDefinition def = entry.Value;
// skips configuration which don't belong to the specified extension:
if ((extension == null || extension == def.Extension))
{
if ((def.Flags & IniFlags.Supported) == 0)
{
result[name] = FormatOptionState(
def.Flags,
"Not Supported",
"Not Supported");
}
else if ((def.Flags & IniFlags.Http) != 0 && System.Web.HttpContext.Current == null)
{
result[name] = FormatOptionState(
def.Flags,
"Http Context Required",
"Http Context Required");
}
else
{
result[name] = FormatOptionState(
def.Flags,
def.Gsr(@default, name, null, IniAction.Get),
def.Gsr(local, name, null, IniAction.Get));
}
}
}
return result;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using Appccelerate.EventBroker;
using Eto.Forms;
using Ninject.Extensions.Logging;
namespace SharpFlame.Settings
{
public sealed class InvalidKeyException : Exception
{
public InvalidKeyException()
{
}
public InvalidKeyException(string message)
: base(message)
{
}
public InvalidKeyException(string message,
Exception innerException): base(message, innerException)
{
}
}
public class KeyboardEventArgs : EventArgs
{
public KeyboardCommand Key;
}
public class KeyboardCommand {
public string Name { get; set; }
public Keys? Key { get; private set; }
public bool Repeat { get; set; }
public bool Active { get; set; }
public KeyboardCommand(string name, Keys? key = null, bool repeat = false)
{
Name = name;
if( key != null )
{
Key = key;
}
Active = false;
Repeat = repeat;
}
public override string ToString()
{
if( Key != null )
return Key.ToString();
else
{
return $"{Name} has no key!";
}
}
}
public class KeyboardManager
{
public event EventHandler<KeyboardEventArgs> KeyUp = delegate {};
public event EventHandler<KeyboardEventArgs> KeyDown = delegate {};
public readonly Dictionary<string, KeyboardCommand> Commands = new Dictionary<string, KeyboardCommand>();
public readonly Dictionary<string, KeyboardCommand> ActiveCommands = new Dictionary<string, KeyboardCommand>();
private readonly Dictionary<Keys, KeyboardCommand> hookTable = new Dictionary<Keys, KeyboardCommand>();
private readonly ILogger logger;
private UITimer watchModifier = new UITimer();
public KeyboardManager(ILoggerFactory logFactory)
{
logger = logFactory.GetCurrentClassLogger();
watchModifier.Interval = 0.100;
watchModifier.Elapsed += WatchModifier_Elapsed;
}
public void RegisterClearAll()
{
this.Commands.Clear();
this.hookTable.Clear();
this.ActiveCommands.Clear();
}
public bool Register(string name, Eto.Forms.Keys key = Eto.Forms.Keys.None, bool repeat = false)
{
if( this.Commands.ContainsKey(name) )
{
throw new Exception($"The key '{name}' already exist.");
}
var command = new KeyboardCommand(name, key, repeat);
this.Commands.Add(name, command);
if( key != Keys.None )
{
hookTable.Add(key, command);
}
return true;
}
/// <summary>
/// Updates the specified Key.
/// </summary>
/// <param name="name">Name.</param>
/// <param name="etoKey">Key.</param>
public void RegisterUpdate(string name, Keys etoKey = Keys.None, bool repeat = false)
{
if( !this.Commands.ContainsKey(name) )
{
throw new Exception($"The key '{name}' does not exist.");
}
Commands.Remove(name);
KeyboardCommand cmd;
if( hookTable.TryGetValue(etoKey, out cmd) )
{
hookTable.Remove(etoKey);
}
Register(name, etoKey, repeat);
}
public void HandleKeyDown(object sender, KeyEventArgs e)
{
var kd = e.KeyData;
KeyboardCommand cmd = null;
if( !hookTable.TryGetValue(kd, out cmd) )
{
return;
}
if( cmd.Active )
{
if( cmd.Repeat )
{
KeyDown(sender, new KeyboardEventArgs { Key = cmd });
}
}
else
{
Activate(cmd);
KeyDown(sender, new KeyboardEventArgs { Key = cmd });
}
e.Handled = true;
logger.Debug($"KeyDown: {kd}, Char: {( e.IsChar ? e.KeyChar.ToString() : "no char" )}, Handled: {e.Handled}");
}
public void HandleKeyUp(object sender, KeyEventArgs e)
{
var kd = e.KeyData;
KeyboardCommand cmd = null;
if( !hookTable.TryGetValue(kd, out cmd) )
{
return;
}
Deactivate(cmd);
KeyUp(sender, new KeyboardEventArgs { Key = cmd });
e.Handled = true;
logger.Debug($"KeyUp: {kd}, Char: { ( e.IsChar ? e.KeyChar.ToString() : "no char" ) }, Handled: {e.Handled}");
}
private void Activate(KeyboardCommand cmd)
{
cmd.Active = true;
this.ActiveCommands.Add(cmd.Name, cmd);
}
private void Deactivate(KeyboardCommand cmd)
{
cmd.Active = false;
if( ActiveCommands.ContainsKey(cmd.Name) )
{
ActiveCommands.Remove(cmd.Name);
}
}
private void ActivateModifier(object sender)
{
var current = Keyboard.Modifiers;
var keyeve = new KeyEventArgs(current, KeyEventType.KeyDown);
HandleKeyDown(sender, keyeve);
}
private Keys lastModifier;
public void HandleMouseDown(object sender, MouseEventArgs e)
{
if( e.Modifiers != Keys.None )
{
//we have modifer keys.
lastModifier = e.Modifiers;
ActivateModifier(sender);
watchModifier.Start();
}
}
private void WatchModifier_Elapsed(object sender, EventArgs e)
{
//reset modifier
if( Keyboard.Modifiers != Keys.None )
return;//still going.
var active = this.ActiveCommands.Values.ToArray()
.Where( cmd => cmd.Key == lastModifier);
if( active.Any() )
{
active.ForEach(Deactivate);
}
watchModifier.Stop();
}
}
}
| |
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using System.Collections.Generic;
using System.Management.Automation.Help;
namespace System.Management.Automation
{
/// <summary>
/// The MamlUtil class.
/// </summary>
internal static class MamlUtil
{
/// <summary>
/// Takes Name value from maml2 and overrides it in maml1.
/// </summary>
/// <param name="maml1"></param>
/// <param name="maml2"></param>
internal static void OverrideName(PSObject maml1, PSObject maml2)
{
PrependPropertyValue(maml1, maml2, new string[] { "Name" }, true);
PrependPropertyValue(maml1, maml2, new string[] { "Details", "Name" }, true);
}
/// <summary>
/// Takes Name value from maml2 and overrides it in maml1.
/// </summary>
/// <param name="maml1"></param>
/// <param name="maml2"></param>
internal static void OverridePSTypeNames(PSObject maml1, PSObject maml2)
{
foreach (var typename in maml2.TypeNames)
{
if (typename.StartsWith(DefaultCommandHelpObjectBuilder.TypeNameForDefaultHelp, StringComparison.OrdinalIgnoreCase))
{
// Win8: 638494 if the original help is auto-generated, let the Provider help decide the format.
return;
}
}
maml1.TypeNames.Clear();
// User request at the top..
foreach (string typeName in maml2.TypeNames)
{
maml1.TypeNames.Add(typeName);
}
}
/// <summary>
/// Adds common properties like PSSnapIn,ModuleName from maml2 to maml1.
/// </summary>
/// <param name="maml1"></param>
/// <param name="maml2"></param>
internal static void AddCommonProperties(PSObject maml1, PSObject maml2)
{
if (maml1.Properties["PSSnapIn"] == null)
{
PSPropertyInfo snapInProperty = maml2.Properties["PSSnapIn"];
if (snapInProperty != null)
{
maml1.Properties.Add(new PSNoteProperty("PSSnapIn", snapInProperty.Value));
}
}
if (maml1.Properties["ModuleName"] == null)
{
PSPropertyInfo moduleNameProperty = maml2.Properties["ModuleName"];
if (moduleNameProperty != null)
{
maml1.Properties.Add(new PSNoteProperty("ModuleName", moduleNameProperty.Value));
}
}
}
/// <summary>
/// Prepend - Modify Syntax element in maml1 using the Syntax element from maml2.
/// </summary>
internal static void PrependSyntax(PSObject maml1, PSObject maml2)
{
PrependPropertyValue(maml1, maml2, new string[] { "Syntax", "SyntaxItem" }, false);
}
/// <summary>
/// Prepend - Modify DetailedDescription element in maml1 using the DetailedDescription element from maml2.
/// </summary>
internal static void PrependDetailedDescription(PSObject maml1, PSObject maml2)
{
PrependPropertyValue(maml1, maml2, new string[] { "Description" }, false);
}
/// <summary>
/// Override - Modify Parameters element in maml1 using the Parameters element from maml2.
/// This will copy parameters from maml2 that are not present in maml1.
/// </summary>
internal static void OverrideParameters(PSObject maml1, PSObject maml2)
{
string[] parametersPath = new string[] { "Parameters", "Parameter" };
// Final collection of PSObjects.
List<object> maml2items = new List<object>();
// Add maml2 first since we are prepending.
// For maml2: Add as collection or single item. No-op if
PSPropertyInfo propertyInfo2 = GetPropertyInfo(maml2, parametersPath);
var array = propertyInfo2.Value as Array;
if (array != null)
{
maml2items.AddRange(array as IEnumerable<object>);
}
else
{
maml2items.Add(PSObject.AsPSObject(propertyInfo2.Value));
}
// Extend maml1 to make sure the property-path exists - since we'll be modifying it soon.
EnsurePropertyInfoPathExists(maml1, parametersPath);
// For maml1: Add as collection or single item. Do nothing if null or some other type.
PSPropertyInfo propertyInfo1 = GetPropertyInfo(maml1, parametersPath);
List<object> maml1items = new List<object>();
array = propertyInfo1.Value as Array;
if (array != null)
{
maml1items.AddRange(array as IEnumerable<object>);
}
else
{
maml1items.Add(PSObject.AsPSObject(propertyInfo1.Value));
}
// copy parameters from maml2 that are not present in maml1
for (int index = 0; index < maml2items.Count; index++)
{
PSObject m2paramObj = PSObject.AsPSObject(maml2items[index]);
string param2Name = string.Empty;
PSPropertyInfo m2propertyInfo = m2paramObj.Properties["Name"];
if (m2propertyInfo != null)
{
if (!LanguagePrimitives.TryConvertTo<string>(m2propertyInfo.Value, out param2Name))
{
continue;
}
}
bool isParamFoundInMaml1 = false;
foreach (PSObject m1ParamObj in maml1items)
{
string param1Name = string.Empty;
PSPropertyInfo m1PropertyInfo = m1ParamObj.Properties["Name"];
if (m1PropertyInfo != null)
{
if (!LanguagePrimitives.TryConvertTo<string>(m1PropertyInfo.Value, out param1Name))
{
continue;
}
}
if (param1Name.Equals(param2Name, StringComparison.OrdinalIgnoreCase))
{
isParamFoundInMaml1 = true;
}
}
if (!isParamFoundInMaml1)
{
maml1items.Add(maml2items[index]);
}
}
// Now replace in maml1. If items.Count == 0 do nothing since Value is already null.
if (maml1items.Count == 1)
{
propertyInfo1.Value = maml1items[0];
}
else if (maml1items.Count >= 2)
{
propertyInfo1.Value = maml1items.ToArray();
}
}
/// <summary>
/// Prepend - Modify Notes element in maml1 using the Notes element from maml2.
/// </summary>
internal static void PrependNotes(PSObject maml1, PSObject maml2)
{
PrependPropertyValue(maml1, maml2, new string[] { "AlertSet", "Alert" }, false);
}
/// <summary>
/// Get property info.
/// </summary>
internal static PSPropertyInfo GetPropertyInfo(PSObject psObject, string[] path)
{
if (path.Length == 0)
{
return null;
}
for (int i = 0; i < path.Length; ++i)
{
string propertyName = path[i];
PSPropertyInfo propertyInfo = psObject.Properties[propertyName];
if (i == path.Length - 1)
{
return propertyInfo;
}
if (propertyInfo == null || propertyInfo.Value is not PSObject)
{
return null;
}
psObject = (PSObject)propertyInfo.Value;
}
// We will never reach this line but the compiler needs some reassurance.
return null;
}
/// <summary>
/// Prepend property value.
/// </summary>
/// <param name="maml1">
/// </param>
/// <param name="maml2">
/// </param>
/// <param name="path">
/// </param>
/// <param name="shouldOverride">
/// Should Override the maml1 value from maml2 instead of prepend.
/// </param>
internal static void PrependPropertyValue(PSObject maml1, PSObject maml2, string[] path, bool shouldOverride)
{
// Final collection of PSObjects.
List<object> items = new List<object>();
// Add maml2 first since we are prepending.
// For maml2: Add as collection or single item. No-op if
PSPropertyInfo propertyInfo2 = GetPropertyInfo(maml2, path);
if (propertyInfo2 != null)
{
var array = propertyInfo2.Value as Array;
if (array != null)
{
items.AddRange(propertyInfo2.Value as IEnumerable<object>);
}
else
{
items.Add(propertyInfo2.Value);
}
}
// Extend maml1 to make sure the property-path exists - since we'll be modifying it soon.
EnsurePropertyInfoPathExists(maml1, path);
// For maml1: Add as collection or single item. Do nothing if null or some other type.
PSPropertyInfo propertyInfo1 = GetPropertyInfo(maml1, path);
if (propertyInfo1 != null)
{
if (!shouldOverride)
{
var array = propertyInfo1.Value as Array;
if (array != null)
{
items.AddRange(propertyInfo1.Value as IEnumerable<object>);
}
else
{
items.Add(propertyInfo1.Value);
}
}
// Now replace in maml1. If items.Count == 0 do nothing since Value is already null.
if (items.Count == 1)
{
propertyInfo1.Value = items[0];
}
else if (items.Count >= 2)
{
propertyInfo1.Value = items.ToArray();
}
}
}
/// <summary>
/// Ensure property info path exists.
/// </summary>
internal static void EnsurePropertyInfoPathExists(PSObject psObject, string[] path)
{
if (path.Length == 0)
{
return;
}
// Walk the path and extend it if necessary.
for (int i = 0; i < path.Length; ++i)
{
string propertyName = path[i];
PSPropertyInfo propertyInfo = psObject.Properties[propertyName];
// Add a property info here if none was found.
if (propertyInfo == null)
{
// Add null on the last one, since we don't need to extend path further.
object propertyValue = (i < path.Length - 1) ? new PSObject() : null;
propertyInfo = new PSNoteProperty(propertyName, propertyValue);
psObject.Properties.Add(propertyInfo);
}
// If we are on the last path element, we are done. Let's not mess with modifying Value.
if (i == path.Length - 1)
{
return;
}
// If we are not on the last path element, let's make sure we can extend the path.
if (propertyInfo.Value == null || propertyInfo.Value is not PSObject)
{
propertyInfo.Value = new PSObject();
}
// Now move one step further along the path.
psObject = (PSObject)propertyInfo.Value;
}
}
}
}
| |
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using osu.Framework.Audio;
using osu.Framework.Audio.Track;
using osu.Framework.Extensions;
using osu.Framework.Graphics.Textures;
using osu.Framework.Graphics.Video;
using osu.Framework.Lists;
using osu.Framework.Logging;
using osu.Framework.Platform;
using osu.Framework.Threading;
using osu.Game.Beatmaps.Formats;
using osu.Game.Database;
using osu.Game.IO;
using osu.Game.IO.Archives;
using osu.Game.Online.API;
using osu.Game.Online.API.Requests;
using osu.Game.Rulesets;
using osu.Game.Rulesets.Objects;
using Decoder = osu.Game.Beatmaps.Formats.Decoder;
using ZipArchive = SharpCompress.Archives.Zip.ZipArchive;
namespace osu.Game.Beatmaps
{
/// <summary>
/// Handles the storage and retrieval of Beatmaps/WorkingBeatmaps.
/// </summary>
public partial class BeatmapManager : DownloadableArchiveModelManager<BeatmapSetInfo, BeatmapSetFileInfo>
{
/// <summary>
/// Fired when a single difficulty has been hidden.
/// </summary>
public event Action<BeatmapInfo> BeatmapHidden;
/// <summary>
/// Fired when a single difficulty has been restored.
/// </summary>
public event Action<BeatmapInfo> BeatmapRestored;
/// <summary>
/// A default representation of a WorkingBeatmap to use when no beatmap is available.
/// </summary>
public readonly WorkingBeatmap DefaultBeatmap;
public override string[] HandledExtensions => new[] { ".osz" };
protected override string[] HashableFileTypes => new[] { ".osu" };
protected override string ImportFromStablePath => "Songs";
private readonly RulesetStore rulesets;
private readonly BeatmapStore beatmaps;
private readonly AudioManager audioManager;
private readonly GameHost host;
private readonly BeatmapUpdateQueue updateQueue;
private readonly Storage exportStorage;
public BeatmapManager(Storage storage, IDatabaseContextFactory contextFactory, RulesetStore rulesets, IAPIProvider api, AudioManager audioManager, GameHost host = null,
WorkingBeatmap defaultBeatmap = null)
: base(storage, contextFactory, api, new BeatmapStore(contextFactory), host)
{
this.rulesets = rulesets;
this.audioManager = audioManager;
this.host = host;
DefaultBeatmap = defaultBeatmap;
beatmaps = (BeatmapStore)ModelStore;
beatmaps.BeatmapHidden += b => BeatmapHidden?.Invoke(b);
beatmaps.BeatmapRestored += b => BeatmapRestored?.Invoke(b);
updateQueue = new BeatmapUpdateQueue(api);
exportStorage = storage.GetStorageForDirectory("exports");
}
protected override ArchiveDownloadRequest<BeatmapSetInfo> CreateDownloadRequest(BeatmapSetInfo set, bool minimiseDownloadSize) =>
new DownloadBeatmapSetRequest(set, minimiseDownloadSize);
protected override bool ShouldDeleteArchive(string path) => Path.GetExtension(path)?.ToLowerInvariant() == ".osz";
protected override Task Populate(BeatmapSetInfo beatmapSet, ArchiveReader archive, CancellationToken cancellationToken = default)
{
if (archive != null)
beatmapSet.Beatmaps = createBeatmapDifficulties(beatmapSet.Files);
foreach (BeatmapInfo b in beatmapSet.Beatmaps)
{
// remove metadata from difficulties where it matches the set
if (beatmapSet.Metadata.Equals(b.Metadata))
b.Metadata = null;
b.BeatmapSet = beatmapSet;
}
validateOnlineIds(beatmapSet);
return updateQueue.UpdateAsync(beatmapSet, cancellationToken);
}
protected override void PreImport(BeatmapSetInfo beatmapSet)
{
if (beatmapSet.Beatmaps.Any(b => b.BaseDifficulty == null))
throw new InvalidOperationException($"Cannot import {nameof(BeatmapInfo)} with null {nameof(BeatmapInfo.BaseDifficulty)}.");
// check if a set already exists with the same online id, delete if it does.
if (beatmapSet.OnlineBeatmapSetID != null)
{
var existingOnlineId = beatmaps.ConsumableItems.FirstOrDefault(b => b.OnlineBeatmapSetID == beatmapSet.OnlineBeatmapSetID);
if (existingOnlineId != null)
{
Delete(existingOnlineId);
beatmaps.PurgeDeletable(s => s.ID == existingOnlineId.ID);
LogForModel(beatmapSet, $"Found existing beatmap set with same OnlineBeatmapSetID ({beatmapSet.OnlineBeatmapSetID}). It has been purged.");
}
}
}
private void validateOnlineIds(BeatmapSetInfo beatmapSet)
{
var beatmapIds = beatmapSet.Beatmaps.Where(b => b.OnlineBeatmapID.HasValue).Select(b => b.OnlineBeatmapID).ToList();
LogForModel(beatmapSet, "Validating online IDs...");
// ensure all IDs are unique
if (beatmapIds.GroupBy(b => b).Any(g => g.Count() > 1))
{
LogForModel(beatmapSet, "Found non-unique IDs, resetting...");
resetIds();
return;
}
// find any existing beatmaps in the database that have matching online ids
var existingBeatmaps = QueryBeatmaps(b => beatmapIds.Contains(b.OnlineBeatmapID)).ToList();
if (existingBeatmaps.Count > 0)
{
// reset the import ids (to force a re-fetch) *unless* they match the candidate CheckForExisting set.
// we can ignore the case where the new ids are contained by the CheckForExisting set as it will either be used (import skipped) or deleted.
var existing = CheckForExisting(beatmapSet);
if (existing == null || existingBeatmaps.Any(b => !existing.Beatmaps.Contains(b)))
{
LogForModel(beatmapSet, "Found existing import with IDs already, resetting...");
resetIds();
}
}
void resetIds() => beatmapSet.Beatmaps.ForEach(b => b.OnlineBeatmapID = null);
}
protected override bool CheckLocalAvailability(BeatmapSetInfo model, IQueryable<BeatmapSetInfo> items)
=> base.CheckLocalAvailability(model, items)
|| (model.OnlineBeatmapSetID != null && items.Any(b => b.OnlineBeatmapSetID == model.OnlineBeatmapSetID));
/// <summary>
/// Delete a beatmap difficulty.
/// </summary>
/// <param name="beatmap">The beatmap difficulty to hide.</param>
public void Hide(BeatmapInfo beatmap) => beatmaps.Hide(beatmap);
/// <summary>
/// Restore a beatmap difficulty.
/// </summary>
/// <param name="beatmap">The beatmap difficulty to restore.</param>
public void Restore(BeatmapInfo beatmap) => beatmaps.Restore(beatmap);
/// <summary>
/// Saves an <see cref="IBeatmap"/> file against a given <see cref="BeatmapInfo"/>.
/// </summary>
/// <param name="info">The <see cref="BeatmapInfo"/> to save the content against. The file referenced by <see cref="BeatmapInfo.Path"/> will be replaced.</param>
/// <param name="beatmapContent">The <see cref="IBeatmap"/> content to write.</param>
public void Save(BeatmapInfo info, IBeatmap beatmapContent)
{
var setInfo = QueryBeatmapSet(s => s.Beatmaps.Any(b => b.ID == info.ID));
using (var stream = new MemoryStream())
{
using (var sw = new StreamWriter(stream, Encoding.UTF8, 1024, true))
new LegacyBeatmapEncoder(beatmapContent).Encode(sw);
stream.Seek(0, SeekOrigin.Begin);
UpdateFile(setInfo, setInfo.Files.Single(f => string.Equals(f.Filename, info.Path, StringComparison.OrdinalIgnoreCase)), stream);
}
var working = workingCache.FirstOrDefault(w => w.BeatmapInfo?.ID == info.ID);
if (working != null)
workingCache.Remove(working);
}
/// <summary>
/// Exports a <see cref="BeatmapSetInfo"/> to an .osz package.
/// </summary>
/// <param name="set">The <see cref="BeatmapSetInfo"/> to export.</param>
public void Export(BeatmapSetInfo set)
{
var localSet = QueryBeatmapSet(s => s.ID == set.ID);
using (var archive = ZipArchive.Create())
{
foreach (var file in localSet.Files)
archive.AddEntry(file.Filename, Files.Storage.GetStream(file.FileInfo.StoragePath));
using (var outputStream = exportStorage.GetStream($"{set}.osz", FileAccess.Write, FileMode.Create))
archive.SaveTo(outputStream);
exportStorage.OpenInNativeExplorer();
}
}
private readonly WeakList<WorkingBeatmap> workingCache = new WeakList<WorkingBeatmap>();
/// <summary>
/// Retrieve a <see cref="WorkingBeatmap"/> instance for the provided <see cref="BeatmapInfo"/>
/// </summary>
/// <param name="beatmapInfo">The beatmap to lookup.</param>
/// <param name="previous">The currently loaded <see cref="WorkingBeatmap"/>. Allows for optimisation where elements are shared with the new beatmap. May be returned if beatmapInfo requested matches</param>
/// <returns>A <see cref="WorkingBeatmap"/> instance correlating to the provided <see cref="BeatmapInfo"/>.</returns>
public WorkingBeatmap GetWorkingBeatmap(BeatmapInfo beatmapInfo, WorkingBeatmap previous = null)
{
if (beatmapInfo?.ID > 0 && previous != null && previous.BeatmapInfo?.ID == beatmapInfo.ID)
return previous;
if (beatmapInfo?.BeatmapSet == null || beatmapInfo == DefaultBeatmap?.BeatmapInfo)
return DefaultBeatmap;
lock (workingCache)
{
var working = workingCache.FirstOrDefault(w => w.BeatmapInfo?.ID == beatmapInfo.ID);
if (working == null)
{
if (beatmapInfo.Metadata == null)
beatmapInfo.Metadata = beatmapInfo.BeatmapSet.Metadata;
workingCache.Add(working = new BeatmapManagerWorkingBeatmap(Files.Store,
new LargeTextureStore(host?.CreateTextureLoaderStore(Files.Store)), beatmapInfo, audioManager));
}
previous?.TransferTo(working);
return working;
}
}
/// <summary>
/// Perform a lookup query on available <see cref="BeatmapSetInfo"/>s.
/// </summary>
/// <param name="query">The query.</param>
/// <returns>The first result for the provided query, or null if no results were found.</returns>
public BeatmapSetInfo QueryBeatmapSet(Expression<Func<BeatmapSetInfo, bool>> query) => beatmaps.ConsumableItems.AsNoTracking().FirstOrDefault(query);
protected override bool CanUndelete(BeatmapSetInfo existing, BeatmapSetInfo import)
{
if (!base.CanUndelete(existing, import))
return false;
var existingIds = existing.Beatmaps.Select(b => b.OnlineBeatmapID).OrderBy(i => i);
var importIds = import.Beatmaps.Select(b => b.OnlineBeatmapID).OrderBy(i => i);
// force re-import if we are not in a sane state.
return existing.OnlineBeatmapSetID == import.OnlineBeatmapSetID && existingIds.SequenceEqual(importIds);
}
/// <summary>
/// Returns a list of all usable <see cref="BeatmapSetInfo"/>s.
/// </summary>
/// <returns>A list of available <see cref="BeatmapSetInfo"/>.</returns>
public List<BeatmapSetInfo> GetAllUsableBeatmapSets() => GetAllUsableBeatmapSetsEnumerable().ToList();
/// <summary>
/// Returns a list of all usable <see cref="BeatmapSetInfo"/>s.
/// </summary>
/// <returns>A list of available <see cref="BeatmapSetInfo"/>.</returns>
public IQueryable<BeatmapSetInfo> GetAllUsableBeatmapSetsEnumerable() => beatmaps.ConsumableItems.Where(s => !s.DeletePending && !s.Protected);
/// <summary>
/// Perform a lookup query on available <see cref="BeatmapSetInfo"/>s.
/// </summary>
/// <param name="query">The query.</param>
/// <returns>Results from the provided query.</returns>
public IEnumerable<BeatmapSetInfo> QueryBeatmapSets(Expression<Func<BeatmapSetInfo, bool>> query) => beatmaps.ConsumableItems.AsNoTracking().Where(query);
/// <summary>
/// Perform a lookup query on available <see cref="BeatmapInfo"/>s.
/// </summary>
/// <param name="query">The query.</param>
/// <returns>The first result for the provided query, or null if no results were found.</returns>
public BeatmapInfo QueryBeatmap(Expression<Func<BeatmapInfo, bool>> query) => beatmaps.Beatmaps.AsNoTracking().FirstOrDefault(query);
/// <summary>
/// Perform a lookup query on available <see cref="BeatmapInfo"/>s.
/// </summary>
/// <param name="query">The query.</param>
/// <returns>Results from the provided query.</returns>
public IQueryable<BeatmapInfo> QueryBeatmaps(Expression<Func<BeatmapInfo, bool>> query) => beatmaps.Beatmaps.AsNoTracking().Where(query);
protected override string HumanisedModelName => "beatmap";
protected override BeatmapSetInfo CreateModel(ArchiveReader reader)
{
// let's make sure there are actually .osu files to import.
string mapName = reader.Filenames.FirstOrDefault(f => f.EndsWith(".osu"));
if (string.IsNullOrEmpty(mapName))
{
Logger.Log($"No beatmap files found in the beatmap archive ({reader.Name}).", LoggingTarget.Database);
return null;
}
Beatmap beatmap;
using (var stream = new LineBufferedReader(reader.GetStream(mapName)))
beatmap = Decoder.GetDecoder<Beatmap>(stream).Decode(stream);
return new BeatmapSetInfo
{
OnlineBeatmapSetID = beatmap.BeatmapInfo.BeatmapSet?.OnlineBeatmapSetID,
Beatmaps = new List<BeatmapInfo>(),
Metadata = beatmap.Metadata,
DateAdded = DateTimeOffset.UtcNow
};
}
/// <summary>
/// Create all required <see cref="BeatmapInfo"/>s for the provided archive.
/// </summary>
private List<BeatmapInfo> createBeatmapDifficulties(List<BeatmapSetFileInfo> files)
{
var beatmapInfos = new List<BeatmapInfo>();
foreach (var file in files.Where(f => f.Filename.EndsWith(".osu")))
{
using (var raw = Files.Store.GetStream(file.FileInfo.StoragePath))
using (var ms = new MemoryStream()) //we need a memory stream so we can seek
using (var sr = new LineBufferedReader(ms))
{
raw.CopyTo(ms);
ms.Position = 0;
var decoder = Decoder.GetDecoder<Beatmap>(sr);
IBeatmap beatmap = decoder.Decode(sr);
string hash = ms.ComputeSHA2Hash();
if (beatmapInfos.Any(b => b.Hash == hash))
continue;
beatmap.BeatmapInfo.Path = file.Filename;
beatmap.BeatmapInfo.Hash = hash;
beatmap.BeatmapInfo.MD5Hash = ms.ComputeMD5Hash();
var ruleset = rulesets.GetRuleset(beatmap.BeatmapInfo.RulesetID);
beatmap.BeatmapInfo.Ruleset = ruleset;
// TODO: this should be done in a better place once we actually need to dynamically update it.
beatmap.BeatmapInfo.StarDifficulty = ruleset?.CreateInstance().CreateDifficultyCalculator(new DummyConversionBeatmap(beatmap)).Calculate().StarRating ?? 0;
beatmap.BeatmapInfo.Length = calculateLength(beatmap);
beatmap.BeatmapInfo.BPM = beatmap.ControlPointInfo.BPMMode;
beatmapInfos.Add(beatmap.BeatmapInfo);
}
}
return beatmapInfos;
}
private double calculateLength(IBeatmap b)
{
if (!b.HitObjects.Any())
return 0;
var lastObject = b.HitObjects.Last();
//TODO: this isn't always correct (consider mania where a non-last object may last for longer than the last in the list).
double endTime = lastObject.GetEndTime();
double startTime = b.HitObjects.First().StartTime;
return endTime - startTime;
}
/// <summary>
/// A dummy WorkingBeatmap for the purpose of retrieving a beatmap for star difficulty calculation.
/// </summary>
private class DummyConversionBeatmap : WorkingBeatmap
{
private readonly IBeatmap beatmap;
public DummyConversionBeatmap(IBeatmap beatmap)
: base(beatmap.BeatmapInfo, null)
{
this.beatmap = beatmap;
}
protected override IBeatmap GetBeatmap() => beatmap;
protected override Texture GetBackground() => null;
protected override VideoSprite GetVideo() => null;
protected override Track GetTrack() => null;
}
private class BeatmapUpdateQueue
{
private readonly IAPIProvider api;
private const int update_queue_request_concurrency = 4;
private readonly ThreadedTaskScheduler updateScheduler = new ThreadedTaskScheduler(update_queue_request_concurrency, nameof(BeatmapUpdateQueue));
public BeatmapUpdateQueue(IAPIProvider api)
{
this.api = api;
}
public Task UpdateAsync(BeatmapSetInfo beatmapSet, CancellationToken cancellationToken)
{
if (api?.State != APIState.Online)
return Task.CompletedTask;
LogForModel(beatmapSet, "Performing online lookups...");
return Task.WhenAll(beatmapSet.Beatmaps.Select(b => UpdateAsync(beatmapSet, b, cancellationToken)).ToArray());
}
// todo: expose this when we need to do individual difficulty lookups.
protected Task UpdateAsync(BeatmapSetInfo beatmapSet, BeatmapInfo beatmap, CancellationToken cancellationToken)
=> Task.Factory.StartNew(() => update(beatmapSet, beatmap), cancellationToken, TaskCreationOptions.HideScheduler, updateScheduler);
private void update(BeatmapSetInfo set, BeatmapInfo beatmap)
{
if (api?.State != APIState.Online)
return;
var req = new GetBeatmapRequest(beatmap);
req.Failure += fail;
try
{
// intentionally blocking to limit web request concurrency
api.Perform(req);
var res = req.Result;
beatmap.Status = res.Status;
beatmap.BeatmapSet.Status = res.BeatmapSet.Status;
beatmap.BeatmapSet.OnlineBeatmapSetID = res.OnlineBeatmapSetID;
beatmap.OnlineBeatmapID = res.OnlineBeatmapID;
LogForModel(set, $"Online retrieval mapped {beatmap} to {res.OnlineBeatmapSetID} / {res.OnlineBeatmapID}.");
}
catch (Exception e)
{
fail(e);
}
void fail(Exception e)
{
beatmap.OnlineBeatmapID = null;
LogForModel(set, $"Online retrieval failed for {beatmap} ({e.Message})");
}
}
}
}
}
| |
using System;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Data.Common;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Xml;
using System.Xml.Serialization;
using SubSonic;
using SubSonic.Utilities;
namespace DalSic
{
/// <summary>
/// Strongly-typed collection for the PnBorrar class.
/// </summary>
[Serializable]
public partial class PnBorrarCollection : ActiveList<PnBorrar, PnBorrarCollection>
{
public PnBorrarCollection() {}
/// <summary>
/// Filters an existing collection based on the set criteria. This is an in-memory filter
/// Thanks to developingchris for this!
/// </summary>
/// <returns>PnBorrarCollection</returns>
public PnBorrarCollection Filter()
{
for (int i = this.Count - 1; i > -1; i--)
{
PnBorrar o = this[i];
foreach (SubSonic.Where w in this.wheres)
{
bool remove = false;
System.Reflection.PropertyInfo pi = o.GetType().GetProperty(w.ColumnName);
if (pi.CanRead)
{
object val = pi.GetValue(o, null);
switch (w.Comparison)
{
case SubSonic.Comparison.Equals:
if (!val.Equals(w.ParameterValue))
{
remove = true;
}
break;
}
}
if (remove)
{
this.Remove(o);
break;
}
}
}
return this;
}
}
/// <summary>
/// This is an ActiveRecord class which wraps the PN_Borrar table.
/// </summary>
[Serializable]
public partial class PnBorrar : ActiveRecord<PnBorrar>, IActiveRecord
{
#region .ctors and Default Settings
public PnBorrar()
{
SetSQLProps();
InitSetDefaults();
MarkNew();
}
private void InitSetDefaults() { SetDefaults(); }
public PnBorrar(bool useDatabaseDefaults)
{
SetSQLProps();
if(useDatabaseDefaults)
ForceDefaults();
MarkNew();
}
public PnBorrar(object keyID)
{
SetSQLProps();
InitSetDefaults();
LoadByKey(keyID);
}
public PnBorrar(string columnName, object columnValue)
{
SetSQLProps();
InitSetDefaults();
LoadByParam(columnName,columnValue);
}
protected static void SetSQLProps() { GetTableSchema(); }
#endregion
#region Schema and Query Accessor
public static Query CreateQuery() { return new Query(Schema); }
public static TableSchema.Table Schema
{
get
{
if (BaseSchema == null)
SetSQLProps();
return BaseSchema;
}
}
private static void GetTableSchema()
{
if(!IsSchemaInitialized)
{
//Schema declaration
TableSchema.Table schema = new TableSchema.Table("PN_Borrar", TableType.Table, DataService.GetInstance("sicProvider"));
schema.Columns = new TableSchema.TableColumnCollection();
schema.SchemaName = @"dbo";
//columns
TableSchema.TableColumn colvarIdNomenclador = new TableSchema.TableColumn(schema);
colvarIdNomenclador.ColumnName = "id_nomenclador";
colvarIdNomenclador.DataType = DbType.Int32;
colvarIdNomenclador.MaxLength = 0;
colvarIdNomenclador.AutoIncrement = true;
colvarIdNomenclador.IsNullable = false;
colvarIdNomenclador.IsPrimaryKey = true;
colvarIdNomenclador.IsForeignKey = false;
colvarIdNomenclador.IsReadOnly = false;
colvarIdNomenclador.DefaultSetting = @"";
colvarIdNomenclador.ForeignKeyTableName = "";
schema.Columns.Add(colvarIdNomenclador);
TableSchema.TableColumn colvarCodigo = new TableSchema.TableColumn(schema);
colvarCodigo.ColumnName = "codigo";
colvarCodigo.DataType = DbType.AnsiString;
colvarCodigo.MaxLength = -1;
colvarCodigo.AutoIncrement = false;
colvarCodigo.IsNullable = true;
colvarCodigo.IsPrimaryKey = false;
colvarCodigo.IsForeignKey = false;
colvarCodigo.IsReadOnly = false;
colvarCodigo.DefaultSetting = @"";
colvarCodigo.ForeignKeyTableName = "";
schema.Columns.Add(colvarCodigo);
TableSchema.TableColumn colvarGrupo = new TableSchema.TableColumn(schema);
colvarGrupo.ColumnName = "grupo";
colvarGrupo.DataType = DbType.AnsiString;
colvarGrupo.MaxLength = -1;
colvarGrupo.AutoIncrement = false;
colvarGrupo.IsNullable = true;
colvarGrupo.IsPrimaryKey = false;
colvarGrupo.IsForeignKey = false;
colvarGrupo.IsReadOnly = false;
colvarGrupo.DefaultSetting = @"";
colvarGrupo.ForeignKeyTableName = "";
schema.Columns.Add(colvarGrupo);
TableSchema.TableColumn colvarSubgrupo = new TableSchema.TableColumn(schema);
colvarSubgrupo.ColumnName = "subgrupo";
colvarSubgrupo.DataType = DbType.AnsiString;
colvarSubgrupo.MaxLength = -1;
colvarSubgrupo.AutoIncrement = false;
colvarSubgrupo.IsNullable = true;
colvarSubgrupo.IsPrimaryKey = false;
colvarSubgrupo.IsForeignKey = false;
colvarSubgrupo.IsReadOnly = false;
colvarSubgrupo.DefaultSetting = @"";
colvarSubgrupo.ForeignKeyTableName = "";
schema.Columns.Add(colvarSubgrupo);
TableSchema.TableColumn colvarDescripcion = new TableSchema.TableColumn(schema);
colvarDescripcion.ColumnName = "descripcion";
colvarDescripcion.DataType = DbType.AnsiString;
colvarDescripcion.MaxLength = -1;
colvarDescripcion.AutoIncrement = false;
colvarDescripcion.IsNullable = true;
colvarDescripcion.IsPrimaryKey = false;
colvarDescripcion.IsForeignKey = false;
colvarDescripcion.IsReadOnly = false;
colvarDescripcion.DefaultSetting = @"";
colvarDescripcion.ForeignKeyTableName = "";
schema.Columns.Add(colvarDescripcion);
TableSchema.TableColumn colvarPrecio = new TableSchema.TableColumn(schema);
colvarPrecio.ColumnName = "precio";
colvarPrecio.DataType = DbType.Decimal;
colvarPrecio.MaxLength = 0;
colvarPrecio.AutoIncrement = false;
colvarPrecio.IsNullable = true;
colvarPrecio.IsPrimaryKey = false;
colvarPrecio.IsForeignKey = false;
colvarPrecio.IsReadOnly = false;
colvarPrecio.DefaultSetting = @"";
colvarPrecio.ForeignKeyTableName = "";
schema.Columns.Add(colvarPrecio);
TableSchema.TableColumn colvarTipoNomenclador = new TableSchema.TableColumn(schema);
colvarTipoNomenclador.ColumnName = "tipo_nomenclador";
colvarTipoNomenclador.DataType = DbType.AnsiString;
colvarTipoNomenclador.MaxLength = -1;
colvarTipoNomenclador.AutoIncrement = false;
colvarTipoNomenclador.IsNullable = true;
colvarTipoNomenclador.IsPrimaryKey = false;
colvarTipoNomenclador.IsForeignKey = false;
colvarTipoNomenclador.IsReadOnly = false;
colvarTipoNomenclador.DefaultSetting = @"";
colvarTipoNomenclador.ForeignKeyTableName = "";
schema.Columns.Add(colvarTipoNomenclador);
TableSchema.TableColumn colvarIdNomencladorDetalle = new TableSchema.TableColumn(schema);
colvarIdNomencladorDetalle.ColumnName = "id_nomenclador_detalle";
colvarIdNomencladorDetalle.DataType = DbType.Int32;
colvarIdNomencladorDetalle.MaxLength = 0;
colvarIdNomencladorDetalle.AutoIncrement = false;
colvarIdNomencladorDetalle.IsNullable = true;
colvarIdNomencladorDetalle.IsPrimaryKey = false;
colvarIdNomencladorDetalle.IsForeignKey = false;
colvarIdNomencladorDetalle.IsReadOnly = false;
colvarIdNomencladorDetalle.DefaultSetting = @"";
colvarIdNomencladorDetalle.ForeignKeyTableName = "";
schema.Columns.Add(colvarIdNomencladorDetalle);
TableSchema.TableColumn colvarBorrado = new TableSchema.TableColumn(schema);
colvarBorrado.ColumnName = "borrado";
colvarBorrado.DataType = DbType.AnsiString;
colvarBorrado.MaxLength = 5;
colvarBorrado.AutoIncrement = false;
colvarBorrado.IsNullable = true;
colvarBorrado.IsPrimaryKey = false;
colvarBorrado.IsForeignKey = false;
colvarBorrado.IsReadOnly = false;
colvarBorrado.DefaultSetting = @"";
colvarBorrado.ForeignKeyTableName = "";
schema.Columns.Add(colvarBorrado);
TableSchema.TableColumn colvarDefinicion = new TableSchema.TableColumn(schema);
colvarDefinicion.ColumnName = "definicion";
colvarDefinicion.DataType = DbType.AnsiString;
colvarDefinicion.MaxLength = -1;
colvarDefinicion.AutoIncrement = false;
colvarDefinicion.IsNullable = true;
colvarDefinicion.IsPrimaryKey = false;
colvarDefinicion.IsForeignKey = false;
colvarDefinicion.IsReadOnly = false;
colvarDefinicion.DefaultSetting = @"";
colvarDefinicion.ForeignKeyTableName = "";
schema.Columns.Add(colvarDefinicion);
TableSchema.TableColumn colvarDiasUti = new TableSchema.TableColumn(schema);
colvarDiasUti.ColumnName = "dias_uti";
colvarDiasUti.DataType = DbType.Int32;
colvarDiasUti.MaxLength = 0;
colvarDiasUti.AutoIncrement = false;
colvarDiasUti.IsNullable = true;
colvarDiasUti.IsPrimaryKey = false;
colvarDiasUti.IsForeignKey = false;
colvarDiasUti.IsReadOnly = false;
colvarDiasUti.DefaultSetting = @"";
colvarDiasUti.ForeignKeyTableName = "";
schema.Columns.Add(colvarDiasUti);
TableSchema.TableColumn colvarDiasSala = new TableSchema.TableColumn(schema);
colvarDiasSala.ColumnName = "dias_sala";
colvarDiasSala.DataType = DbType.Int32;
colvarDiasSala.MaxLength = 0;
colvarDiasSala.AutoIncrement = false;
colvarDiasSala.IsNullable = true;
colvarDiasSala.IsPrimaryKey = false;
colvarDiasSala.IsForeignKey = false;
colvarDiasSala.IsReadOnly = false;
colvarDiasSala.DefaultSetting = @"";
colvarDiasSala.ForeignKeyTableName = "";
schema.Columns.Add(colvarDiasSala);
TableSchema.TableColumn colvarDiasTotal = new TableSchema.TableColumn(schema);
colvarDiasTotal.ColumnName = "dias_total";
colvarDiasTotal.DataType = DbType.Int32;
colvarDiasTotal.MaxLength = 0;
colvarDiasTotal.AutoIncrement = false;
colvarDiasTotal.IsNullable = true;
colvarDiasTotal.IsPrimaryKey = false;
colvarDiasTotal.IsForeignKey = false;
colvarDiasTotal.IsReadOnly = false;
colvarDiasTotal.DefaultSetting = @"";
colvarDiasTotal.ForeignKeyTableName = "";
schema.Columns.Add(colvarDiasTotal);
TableSchema.TableColumn colvarDiasMax = new TableSchema.TableColumn(schema);
colvarDiasMax.ColumnName = "dias_max";
colvarDiasMax.DataType = DbType.Int32;
colvarDiasMax.MaxLength = 0;
colvarDiasMax.AutoIncrement = false;
colvarDiasMax.IsNullable = true;
colvarDiasMax.IsPrimaryKey = false;
colvarDiasMax.IsForeignKey = false;
colvarDiasMax.IsReadOnly = false;
colvarDiasMax.DefaultSetting = @"";
colvarDiasMax.ForeignKeyTableName = "";
schema.Columns.Add(colvarDiasMax);
TableSchema.TableColumn colvarNeo = new TableSchema.TableColumn(schema);
colvarNeo.ColumnName = "neo";
colvarNeo.DataType = DbType.AnsiString;
colvarNeo.MaxLength = 1;
colvarNeo.AutoIncrement = false;
colvarNeo.IsNullable = true;
colvarNeo.IsPrimaryKey = false;
colvarNeo.IsForeignKey = false;
colvarNeo.IsReadOnly = false;
colvarNeo.DefaultSetting = @"";
colvarNeo.ForeignKeyTableName = "";
schema.Columns.Add(colvarNeo);
TableSchema.TableColumn colvarCeroacinco = new TableSchema.TableColumn(schema);
colvarCeroacinco.ColumnName = "ceroacinco";
colvarCeroacinco.DataType = DbType.AnsiString;
colvarCeroacinco.MaxLength = 1;
colvarCeroacinco.AutoIncrement = false;
colvarCeroacinco.IsNullable = true;
colvarCeroacinco.IsPrimaryKey = false;
colvarCeroacinco.IsForeignKey = false;
colvarCeroacinco.IsReadOnly = false;
colvarCeroacinco.DefaultSetting = @"";
colvarCeroacinco.ForeignKeyTableName = "";
schema.Columns.Add(colvarCeroacinco);
TableSchema.TableColumn colvarSeisanueve = new TableSchema.TableColumn(schema);
colvarSeisanueve.ColumnName = "seisanueve";
colvarSeisanueve.DataType = DbType.AnsiString;
colvarSeisanueve.MaxLength = 1;
colvarSeisanueve.AutoIncrement = false;
colvarSeisanueve.IsNullable = true;
colvarSeisanueve.IsPrimaryKey = false;
colvarSeisanueve.IsForeignKey = false;
colvarSeisanueve.IsReadOnly = false;
colvarSeisanueve.DefaultSetting = @"";
colvarSeisanueve.ForeignKeyTableName = "";
schema.Columns.Add(colvarSeisanueve);
TableSchema.TableColumn colvarAdol = new TableSchema.TableColumn(schema);
colvarAdol.ColumnName = "adol";
colvarAdol.DataType = DbType.AnsiString;
colvarAdol.MaxLength = 1;
colvarAdol.AutoIncrement = false;
colvarAdol.IsNullable = true;
colvarAdol.IsPrimaryKey = false;
colvarAdol.IsForeignKey = false;
colvarAdol.IsReadOnly = false;
colvarAdol.DefaultSetting = @"";
colvarAdol.ForeignKeyTableName = "";
schema.Columns.Add(colvarAdol);
TableSchema.TableColumn colvarAdulto = new TableSchema.TableColumn(schema);
colvarAdulto.ColumnName = "adulto";
colvarAdulto.DataType = DbType.AnsiString;
colvarAdulto.MaxLength = 1;
colvarAdulto.AutoIncrement = false;
colvarAdulto.IsNullable = true;
colvarAdulto.IsPrimaryKey = false;
colvarAdulto.IsForeignKey = false;
colvarAdulto.IsReadOnly = false;
colvarAdulto.DefaultSetting = @"";
colvarAdulto.ForeignKeyTableName = "";
schema.Columns.Add(colvarAdulto);
TableSchema.TableColumn colvarF = new TableSchema.TableColumn(schema);
colvarF.ColumnName = "f";
colvarF.DataType = DbType.AnsiString;
colvarF.MaxLength = 1;
colvarF.AutoIncrement = false;
colvarF.IsNullable = true;
colvarF.IsPrimaryKey = false;
colvarF.IsForeignKey = false;
colvarF.IsReadOnly = false;
colvarF.DefaultSetting = @"";
colvarF.ForeignKeyTableName = "";
schema.Columns.Add(colvarF);
TableSchema.TableColumn colvarM = new TableSchema.TableColumn(schema);
colvarM.ColumnName = "m";
colvarM.DataType = DbType.AnsiString;
colvarM.MaxLength = 1;
colvarM.AutoIncrement = false;
colvarM.IsNullable = true;
colvarM.IsPrimaryKey = false;
colvarM.IsForeignKey = false;
colvarM.IsReadOnly = false;
colvarM.DefaultSetting = @"";
colvarM.ForeignKeyTableName = "";
schema.Columns.Add(colvarM);
TableSchema.TableColumn colvarLineaCuidado = new TableSchema.TableColumn(schema);
colvarLineaCuidado.ColumnName = "linea_cuidado";
colvarLineaCuidado.DataType = DbType.AnsiString;
colvarLineaCuidado.MaxLength = 30;
colvarLineaCuidado.AutoIncrement = false;
colvarLineaCuidado.IsNullable = true;
colvarLineaCuidado.IsPrimaryKey = false;
colvarLineaCuidado.IsForeignKey = false;
colvarLineaCuidado.IsReadOnly = false;
colvarLineaCuidado.DefaultSetting = @"";
colvarLineaCuidado.ForeignKeyTableName = "";
schema.Columns.Add(colvarLineaCuidado);
BaseSchema = schema;
//add this schema to the provider
//so we can query it later
DataService.Providers["sicProvider"].AddSchema("PN_Borrar",schema);
}
}
#endregion
#region Props
[XmlAttribute("IdNomenclador")]
[Bindable(true)]
public int IdNomenclador
{
get { return GetColumnValue<int>(Columns.IdNomenclador); }
set { SetColumnValue(Columns.IdNomenclador, value); }
}
[XmlAttribute("Codigo")]
[Bindable(true)]
public string Codigo
{
get { return GetColumnValue<string>(Columns.Codigo); }
set { SetColumnValue(Columns.Codigo, value); }
}
[XmlAttribute("Grupo")]
[Bindable(true)]
public string Grupo
{
get { return GetColumnValue<string>(Columns.Grupo); }
set { SetColumnValue(Columns.Grupo, value); }
}
[XmlAttribute("Subgrupo")]
[Bindable(true)]
public string Subgrupo
{
get { return GetColumnValue<string>(Columns.Subgrupo); }
set { SetColumnValue(Columns.Subgrupo, value); }
}
[XmlAttribute("Descripcion")]
[Bindable(true)]
public string Descripcion
{
get { return GetColumnValue<string>(Columns.Descripcion); }
set { SetColumnValue(Columns.Descripcion, value); }
}
[XmlAttribute("Precio")]
[Bindable(true)]
public decimal? Precio
{
get { return GetColumnValue<decimal?>(Columns.Precio); }
set { SetColumnValue(Columns.Precio, value); }
}
[XmlAttribute("TipoNomenclador")]
[Bindable(true)]
public string TipoNomenclador
{
get { return GetColumnValue<string>(Columns.TipoNomenclador); }
set { SetColumnValue(Columns.TipoNomenclador, value); }
}
[XmlAttribute("IdNomencladorDetalle")]
[Bindable(true)]
public int? IdNomencladorDetalle
{
get { return GetColumnValue<int?>(Columns.IdNomencladorDetalle); }
set { SetColumnValue(Columns.IdNomencladorDetalle, value); }
}
[XmlAttribute("Borrado")]
[Bindable(true)]
public string Borrado
{
get { return GetColumnValue<string>(Columns.Borrado); }
set { SetColumnValue(Columns.Borrado, value); }
}
[XmlAttribute("Definicion")]
[Bindable(true)]
public string Definicion
{
get { return GetColumnValue<string>(Columns.Definicion); }
set { SetColumnValue(Columns.Definicion, value); }
}
[XmlAttribute("DiasUti")]
[Bindable(true)]
public int? DiasUti
{
get { return GetColumnValue<int?>(Columns.DiasUti); }
set { SetColumnValue(Columns.DiasUti, value); }
}
[XmlAttribute("DiasSala")]
[Bindable(true)]
public int? DiasSala
{
get { return GetColumnValue<int?>(Columns.DiasSala); }
set { SetColumnValue(Columns.DiasSala, value); }
}
[XmlAttribute("DiasTotal")]
[Bindable(true)]
public int? DiasTotal
{
get { return GetColumnValue<int?>(Columns.DiasTotal); }
set { SetColumnValue(Columns.DiasTotal, value); }
}
[XmlAttribute("DiasMax")]
[Bindable(true)]
public int? DiasMax
{
get { return GetColumnValue<int?>(Columns.DiasMax); }
set { SetColumnValue(Columns.DiasMax, value); }
}
[XmlAttribute("Neo")]
[Bindable(true)]
public string Neo
{
get { return GetColumnValue<string>(Columns.Neo); }
set { SetColumnValue(Columns.Neo, value); }
}
[XmlAttribute("Ceroacinco")]
[Bindable(true)]
public string Ceroacinco
{
get { return GetColumnValue<string>(Columns.Ceroacinco); }
set { SetColumnValue(Columns.Ceroacinco, value); }
}
[XmlAttribute("Seisanueve")]
[Bindable(true)]
public string Seisanueve
{
get { return GetColumnValue<string>(Columns.Seisanueve); }
set { SetColumnValue(Columns.Seisanueve, value); }
}
[XmlAttribute("Adol")]
[Bindable(true)]
public string Adol
{
get { return GetColumnValue<string>(Columns.Adol); }
set { SetColumnValue(Columns.Adol, value); }
}
[XmlAttribute("Adulto")]
[Bindable(true)]
public string Adulto
{
get { return GetColumnValue<string>(Columns.Adulto); }
set { SetColumnValue(Columns.Adulto, value); }
}
[XmlAttribute("F")]
[Bindable(true)]
public string F
{
get { return GetColumnValue<string>(Columns.F); }
set { SetColumnValue(Columns.F, value); }
}
[XmlAttribute("M")]
[Bindable(true)]
public string M
{
get { return GetColumnValue<string>(Columns.M); }
set { SetColumnValue(Columns.M, value); }
}
[XmlAttribute("LineaCuidado")]
[Bindable(true)]
public string LineaCuidado
{
get { return GetColumnValue<string>(Columns.LineaCuidado); }
set { SetColumnValue(Columns.LineaCuidado, value); }
}
#endregion
//no foreign key tables defined (0)
//no ManyToMany tables defined (0)
#region ObjectDataSource support
/// <summary>
/// Inserts a record, can be used with the Object Data Source
/// </summary>
public static void Insert(string varCodigo,string varGrupo,string varSubgrupo,string varDescripcion,decimal? varPrecio,string varTipoNomenclador,int? varIdNomencladorDetalle,string varBorrado,string varDefinicion,int? varDiasUti,int? varDiasSala,int? varDiasTotal,int? varDiasMax,string varNeo,string varCeroacinco,string varSeisanueve,string varAdol,string varAdulto,string varF,string varM,string varLineaCuidado)
{
PnBorrar item = new PnBorrar();
item.Codigo = varCodigo;
item.Grupo = varGrupo;
item.Subgrupo = varSubgrupo;
item.Descripcion = varDescripcion;
item.Precio = varPrecio;
item.TipoNomenclador = varTipoNomenclador;
item.IdNomencladorDetalle = varIdNomencladorDetalle;
item.Borrado = varBorrado;
item.Definicion = varDefinicion;
item.DiasUti = varDiasUti;
item.DiasSala = varDiasSala;
item.DiasTotal = varDiasTotal;
item.DiasMax = varDiasMax;
item.Neo = varNeo;
item.Ceroacinco = varCeroacinco;
item.Seisanueve = varSeisanueve;
item.Adol = varAdol;
item.Adulto = varAdulto;
item.F = varF;
item.M = varM;
item.LineaCuidado = varLineaCuidado;
if (System.Web.HttpContext.Current != null)
item.Save(System.Web.HttpContext.Current.User.Identity.Name);
else
item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name);
}
/// <summary>
/// Updates a record, can be used with the Object Data Source
/// </summary>
public static void Update(int varIdNomenclador,string varCodigo,string varGrupo,string varSubgrupo,string varDescripcion,decimal? varPrecio,string varTipoNomenclador,int? varIdNomencladorDetalle,string varBorrado,string varDefinicion,int? varDiasUti,int? varDiasSala,int? varDiasTotal,int? varDiasMax,string varNeo,string varCeroacinco,string varSeisanueve,string varAdol,string varAdulto,string varF,string varM,string varLineaCuidado)
{
PnBorrar item = new PnBorrar();
item.IdNomenclador = varIdNomenclador;
item.Codigo = varCodigo;
item.Grupo = varGrupo;
item.Subgrupo = varSubgrupo;
item.Descripcion = varDescripcion;
item.Precio = varPrecio;
item.TipoNomenclador = varTipoNomenclador;
item.IdNomencladorDetalle = varIdNomencladorDetalle;
item.Borrado = varBorrado;
item.Definicion = varDefinicion;
item.DiasUti = varDiasUti;
item.DiasSala = varDiasSala;
item.DiasTotal = varDiasTotal;
item.DiasMax = varDiasMax;
item.Neo = varNeo;
item.Ceroacinco = varCeroacinco;
item.Seisanueve = varSeisanueve;
item.Adol = varAdol;
item.Adulto = varAdulto;
item.F = varF;
item.M = varM;
item.LineaCuidado = varLineaCuidado;
item.IsNew = false;
if (System.Web.HttpContext.Current != null)
item.Save(System.Web.HttpContext.Current.User.Identity.Name);
else
item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name);
}
#endregion
#region Typed Columns
public static TableSchema.TableColumn IdNomencladorColumn
{
get { return Schema.Columns[0]; }
}
public static TableSchema.TableColumn CodigoColumn
{
get { return Schema.Columns[1]; }
}
public static TableSchema.TableColumn GrupoColumn
{
get { return Schema.Columns[2]; }
}
public static TableSchema.TableColumn SubgrupoColumn
{
get { return Schema.Columns[3]; }
}
public static TableSchema.TableColumn DescripcionColumn
{
get { return Schema.Columns[4]; }
}
public static TableSchema.TableColumn PrecioColumn
{
get { return Schema.Columns[5]; }
}
public static TableSchema.TableColumn TipoNomencladorColumn
{
get { return Schema.Columns[6]; }
}
public static TableSchema.TableColumn IdNomencladorDetalleColumn
{
get { return Schema.Columns[7]; }
}
public static TableSchema.TableColumn BorradoColumn
{
get { return Schema.Columns[8]; }
}
public static TableSchema.TableColumn DefinicionColumn
{
get { return Schema.Columns[9]; }
}
public static TableSchema.TableColumn DiasUtiColumn
{
get { return Schema.Columns[10]; }
}
public static TableSchema.TableColumn DiasSalaColumn
{
get { return Schema.Columns[11]; }
}
public static TableSchema.TableColumn DiasTotalColumn
{
get { return Schema.Columns[12]; }
}
public static TableSchema.TableColumn DiasMaxColumn
{
get { return Schema.Columns[13]; }
}
public static TableSchema.TableColumn NeoColumn
{
get { return Schema.Columns[14]; }
}
public static TableSchema.TableColumn CeroacincoColumn
{
get { return Schema.Columns[15]; }
}
public static TableSchema.TableColumn SeisanueveColumn
{
get { return Schema.Columns[16]; }
}
public static TableSchema.TableColumn AdolColumn
{
get { return Schema.Columns[17]; }
}
public static TableSchema.TableColumn AdultoColumn
{
get { return Schema.Columns[18]; }
}
public static TableSchema.TableColumn FColumn
{
get { return Schema.Columns[19]; }
}
public static TableSchema.TableColumn MColumn
{
get { return Schema.Columns[20]; }
}
public static TableSchema.TableColumn LineaCuidadoColumn
{
get { return Schema.Columns[21]; }
}
#endregion
#region Columns Struct
public struct Columns
{
public static string IdNomenclador = @"id_nomenclador";
public static string Codigo = @"codigo";
public static string Grupo = @"grupo";
public static string Subgrupo = @"subgrupo";
public static string Descripcion = @"descripcion";
public static string Precio = @"precio";
public static string TipoNomenclador = @"tipo_nomenclador";
public static string IdNomencladorDetalle = @"id_nomenclador_detalle";
public static string Borrado = @"borrado";
public static string Definicion = @"definicion";
public static string DiasUti = @"dias_uti";
public static string DiasSala = @"dias_sala";
public static string DiasTotal = @"dias_total";
public static string DiasMax = @"dias_max";
public static string Neo = @"neo";
public static string Ceroacinco = @"ceroacinco";
public static string Seisanueve = @"seisanueve";
public static string Adol = @"adol";
public static string Adulto = @"adulto";
public static string F = @"f";
public static string M = @"m";
public static string LineaCuidado = @"linea_cuidado";
}
#endregion
#region Update PK Collections
#endregion
#region Deep Save
#endregion
}
}
| |
//
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using Hyak.Common;
using Microsoft.Azure;
using Microsoft.Azure.Management.Automation;
using Microsoft.Azure.Management.Automation.Models;
using Newtonsoft.Json.Linq;
namespace Microsoft.Azure.Management.Automation
{
/// <summary>
/// Service operation for dsc nodes. (see
/// http://aka.ms/azureautomationsdk/dscnodeoperations for more
/// information)
/// </summary>
internal partial class DscNodeOperations : IServiceOperations<AutomationManagementClient>, IDscNodeOperations
{
/// <summary>
/// Initializes a new instance of the DscNodeOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
internal DscNodeOperations(AutomationManagementClient client)
{
this._client = client;
}
private AutomationManagementClient _client;
/// <summary>
/// Gets a reference to the
/// Microsoft.Azure.Management.Automation.AutomationManagementClient.
/// </summary>
public AutomationManagementClient Client
{
get { return this._client; }
}
/// <summary>
/// Delete the dsc node identified by node id. (see
/// http://aka.ms/azureautomationsdk/dscnodeoperations for more
/// information)
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group
/// </param>
/// <param name='automationAccount'>
/// Required. Automation account name.
/// </param>
/// <param name='nodeId'>
/// Required. The node id.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public async Task<AzureOperationResponse> DeleteAsync(string resourceGroupName, string automationAccount, Guid nodeId, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (automationAccount == null)
{
throw new ArgumentNullException("automationAccount");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("automationAccount", automationAccount);
tracingParameters.Add("nodeId", nodeId);
TracingAdapter.Enter(invocationId, this, "DeleteAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/resourceGroups/";
url = url + Uri.EscapeDataString(resourceGroupName);
url = url + "/providers/";
if (this.Client.ResourceNamespace != null)
{
url = url + Uri.EscapeDataString(this.Client.ResourceNamespace);
}
url = url + "/automationAccounts/";
url = url + Uri.EscapeDataString(automationAccount);
url = url + "/nodes/";
url = url + Uri.EscapeDataString(nodeId.ToString());
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2017-05-15-preview");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Delete;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("x-ms-version", "2014-06-01");
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
AzureOperationResponse result = null;
// Deserialize Response
result = new AzureOperationResponse();
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Retrieve the dsc node identified by node id. (see
/// http://aka.ms/azureautomationsdk/dscnodeoperations for more
/// information)
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group
/// </param>
/// <param name='automationAccount'>
/// Required. The automation account name.
/// </param>
/// <param name='nodeId'>
/// Required. The node id.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The response model for the get dsc node operation.
/// </returns>
public async Task<DscNodeGetResponse> GetAsync(string resourceGroupName, string automationAccount, Guid nodeId, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (automationAccount == null)
{
throw new ArgumentNullException("automationAccount");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("automationAccount", automationAccount);
tracingParameters.Add("nodeId", nodeId);
TracingAdapter.Enter(invocationId, this, "GetAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/resourceGroups/";
url = url + Uri.EscapeDataString(resourceGroupName);
url = url + "/providers/";
if (this.Client.ResourceNamespace != null)
{
url = url + Uri.EscapeDataString(this.Client.ResourceNamespace);
}
url = url + "/automationAccounts/";
url = url + Uri.EscapeDataString(automationAccount);
url = url + "/nodes/";
url = url + Uri.EscapeDataString(nodeId.ToString());
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2017-05-15-preview");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("Accept", "application/json");
httpRequest.Headers.Add("x-ms-version", "2014-06-01");
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
DscNodeGetResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new DscNodeGetResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
DscNode nodeInstance = new DscNode();
result.Node = nodeInstance;
JToken lastSeenValue = responseDoc["lastSeen"];
if (lastSeenValue != null && lastSeenValue.Type != JTokenType.Null)
{
DateTimeOffset lastSeenInstance = ((DateTimeOffset)lastSeenValue);
nodeInstance.LastSeen = lastSeenInstance;
}
JToken registrationTimeValue = responseDoc["registrationTime"];
if (registrationTimeValue != null && registrationTimeValue.Type != JTokenType.Null)
{
DateTimeOffset registrationTimeInstance = ((DateTimeOffset)registrationTimeValue);
nodeInstance.RegistrationTime = registrationTimeInstance;
}
JToken ipValue = responseDoc["ip"];
if (ipValue != null && ipValue.Type != JTokenType.Null)
{
string ipInstance = ((string)ipValue);
nodeInstance.Ip = ipInstance;
}
JToken accountIdValue = responseDoc["accountId"];
if (accountIdValue != null && accountIdValue.Type != JTokenType.Null)
{
Guid accountIdInstance = Guid.Parse(((string)accountIdValue));
nodeInstance.AccountId = accountIdInstance;
}
JToken nodeConfigurationValue = responseDoc["nodeConfiguration"];
if (nodeConfigurationValue != null && nodeConfigurationValue.Type != JTokenType.Null)
{
DscNodeConfigurationAssociationProperty nodeConfigurationInstance = new DscNodeConfigurationAssociationProperty();
nodeInstance.NodeConfiguration = nodeConfigurationInstance;
JToken nameValue = nodeConfigurationValue["name"];
if (nameValue != null && nameValue.Type != JTokenType.Null)
{
string nameInstance = ((string)nameValue);
nodeConfigurationInstance.Name = nameInstance;
}
}
JToken extensionHandlerArray = responseDoc["extensionHandler"];
if (extensionHandlerArray != null && extensionHandlerArray.Type != JTokenType.Null)
{
foreach (JToken extensionHandlerValue in ((JArray)extensionHandlerArray))
{
DscNodeExtensionHandlerAssociationProperty dscNodeExtensionHandlerAssociationPropertyInstance = new DscNodeExtensionHandlerAssociationProperty();
nodeInstance.ExtensionHandler.Add(dscNodeExtensionHandlerAssociationPropertyInstance);
JToken nameValue2 = extensionHandlerValue["name"];
if (nameValue2 != null && nameValue2.Type != JTokenType.Null)
{
string nameInstance2 = ((string)nameValue2);
dscNodeExtensionHandlerAssociationPropertyInstance.Name = nameInstance2;
}
JToken versionValue = extensionHandlerValue["version"];
if (versionValue != null && versionValue.Type != JTokenType.Null)
{
string versionInstance = ((string)versionValue);
dscNodeExtensionHandlerAssociationPropertyInstance.Version = versionInstance;
}
}
}
JToken statusValue = responseDoc["status"];
if (statusValue != null && statusValue.Type != JTokenType.Null)
{
string statusInstance = ((string)statusValue);
nodeInstance.Status = statusInstance;
}
JToken nodeIdValue = responseDoc["nodeId"];
if (nodeIdValue != null && nodeIdValue.Type != JTokenType.Null)
{
Guid nodeIdInstance = Guid.Parse(((string)nodeIdValue));
nodeInstance.NodeId = nodeIdInstance;
}
JToken idValue = responseDoc["id"];
if (idValue != null && idValue.Type != JTokenType.Null)
{
string idInstance = ((string)idValue);
nodeInstance.Id = idInstance;
}
JToken nameValue3 = responseDoc["name"];
if (nameValue3 != null && nameValue3.Type != JTokenType.Null)
{
string nameInstance3 = ((string)nameValue3);
nodeInstance.Name = nameInstance3;
}
JToken locationValue = responseDoc["location"];
if (locationValue != null && locationValue.Type != JTokenType.Null)
{
string locationInstance = ((string)locationValue);
nodeInstance.Location = locationInstance;
}
JToken tagsSequenceElement = ((JToken)responseDoc["tags"]);
if (tagsSequenceElement != null && tagsSequenceElement.Type != JTokenType.Null)
{
foreach (JProperty property in tagsSequenceElement)
{
string tagsKey = ((string)property.Name);
string tagsValue = ((string)property.Value);
nodeInstance.Tags.Add(tagsKey, tagsValue);
}
}
JToken typeValue = responseDoc["type"];
if (typeValue != null && typeValue.Type != JTokenType.Null)
{
string typeInstance = ((string)typeValue);
nodeInstance.Type = typeInstance;
}
JToken etagValue = responseDoc["etag"];
if (etagValue != null && etagValue.Type != JTokenType.Null)
{
string etagInstance = ((string)etagValue);
nodeInstance.Etag = etagInstance;
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Retrieve a list of dsc nodes. (see
/// http://aka.ms/azureautomationsdk/dscnodeoperations for more
/// information)
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group
/// </param>
/// <param name='automationAccount'>
/// Required. The automation account name.
/// </param>
/// <param name='parameters'>
/// Optional. The parameters supplied to the list operation.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The response model for the list dsc nodes operation.
/// </returns>
public async Task<DscNodeListResponse> ListAsync(string resourceGroupName, string automationAccount, DscNodeListParameters parameters, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (automationAccount == null)
{
throw new ArgumentNullException("automationAccount");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("automationAccount", automationAccount);
tracingParameters.Add("parameters", parameters);
TracingAdapter.Enter(invocationId, this, "ListAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/resourceGroups/";
url = url + Uri.EscapeDataString(resourceGroupName);
url = url + "/providers/";
if (this.Client.ResourceNamespace != null)
{
url = url + Uri.EscapeDataString(this.Client.ResourceNamespace);
}
url = url + "/automationAccounts/";
url = url + Uri.EscapeDataString(automationAccount);
url = url + "/nodes";
List<string> queryParameters = new List<string>();
List<string> odataFilter = new List<string>();
if (parameters != null && parameters.Status != null)
{
odataFilter.Add("status eq '" + Uri.EscapeDataString(parameters.Status) + "'");
}
if (parameters != null && parameters.NodeConfigurationName != null)
{
odataFilter.Add("nodeConfiguration/name eq '" + Uri.EscapeDataString(parameters.NodeConfigurationName) + "'");
}
if (parameters != null && parameters.Name != null)
{
odataFilter.Add("name eq '" + Uri.EscapeDataString(parameters.Name) + "'");
}
if (odataFilter.Count > 0)
{
queryParameters.Add("$filter=" + string.Join(" and ", odataFilter));
}
queryParameters.Add("api-version=2017-05-15-preview");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("Accept", "application/json");
httpRequest.Headers.Add("ocp-referer", url);
httpRequest.Headers.Add("x-ms-version", "2014-06-01");
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
DscNodeListResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new DscNodeListResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
JToken valueArray = responseDoc["value"];
if (valueArray != null && valueArray.Type != JTokenType.Null)
{
foreach (JToken valueValue in ((JArray)valueArray))
{
DscNode dscNodeInstance = new DscNode();
result.Nodes.Add(dscNodeInstance);
JToken lastSeenValue = valueValue["lastSeen"];
if (lastSeenValue != null && lastSeenValue.Type != JTokenType.Null)
{
DateTimeOffset lastSeenInstance = ((DateTimeOffset)lastSeenValue);
dscNodeInstance.LastSeen = lastSeenInstance;
}
JToken registrationTimeValue = valueValue["registrationTime"];
if (registrationTimeValue != null && registrationTimeValue.Type != JTokenType.Null)
{
DateTimeOffset registrationTimeInstance = ((DateTimeOffset)registrationTimeValue);
dscNodeInstance.RegistrationTime = registrationTimeInstance;
}
JToken ipValue = valueValue["ip"];
if (ipValue != null && ipValue.Type != JTokenType.Null)
{
string ipInstance = ((string)ipValue);
dscNodeInstance.Ip = ipInstance;
}
JToken accountIdValue = valueValue["accountId"];
if (accountIdValue != null && accountIdValue.Type != JTokenType.Null)
{
Guid accountIdInstance = Guid.Parse(((string)accountIdValue));
dscNodeInstance.AccountId = accountIdInstance;
}
JToken nodeConfigurationValue = valueValue["nodeConfiguration"];
if (nodeConfigurationValue != null && nodeConfigurationValue.Type != JTokenType.Null)
{
DscNodeConfigurationAssociationProperty nodeConfigurationInstance = new DscNodeConfigurationAssociationProperty();
dscNodeInstance.NodeConfiguration = nodeConfigurationInstance;
JToken nameValue = nodeConfigurationValue["name"];
if (nameValue != null && nameValue.Type != JTokenType.Null)
{
string nameInstance = ((string)nameValue);
nodeConfigurationInstance.Name = nameInstance;
}
}
JToken extensionHandlerArray = valueValue["extensionHandler"];
if (extensionHandlerArray != null && extensionHandlerArray.Type != JTokenType.Null)
{
foreach (JToken extensionHandlerValue in ((JArray)extensionHandlerArray))
{
DscNodeExtensionHandlerAssociationProperty dscNodeExtensionHandlerAssociationPropertyInstance = new DscNodeExtensionHandlerAssociationProperty();
dscNodeInstance.ExtensionHandler.Add(dscNodeExtensionHandlerAssociationPropertyInstance);
JToken nameValue2 = extensionHandlerValue["name"];
if (nameValue2 != null && nameValue2.Type != JTokenType.Null)
{
string nameInstance2 = ((string)nameValue2);
dscNodeExtensionHandlerAssociationPropertyInstance.Name = nameInstance2;
}
JToken versionValue = extensionHandlerValue["version"];
if (versionValue != null && versionValue.Type != JTokenType.Null)
{
string versionInstance = ((string)versionValue);
dscNodeExtensionHandlerAssociationPropertyInstance.Version = versionInstance;
}
}
}
JToken statusValue = valueValue["status"];
if (statusValue != null && statusValue.Type != JTokenType.Null)
{
string statusInstance = ((string)statusValue);
dscNodeInstance.Status = statusInstance;
}
JToken nodeIdValue = valueValue["nodeId"];
if (nodeIdValue != null && nodeIdValue.Type != JTokenType.Null)
{
Guid nodeIdInstance = Guid.Parse(((string)nodeIdValue));
dscNodeInstance.NodeId = nodeIdInstance;
}
JToken idValue = valueValue["id"];
if (idValue != null && idValue.Type != JTokenType.Null)
{
string idInstance = ((string)idValue);
dscNodeInstance.Id = idInstance;
}
JToken nameValue3 = valueValue["name"];
if (nameValue3 != null && nameValue3.Type != JTokenType.Null)
{
string nameInstance3 = ((string)nameValue3);
dscNodeInstance.Name = nameInstance3;
}
JToken locationValue = valueValue["location"];
if (locationValue != null && locationValue.Type != JTokenType.Null)
{
string locationInstance = ((string)locationValue);
dscNodeInstance.Location = locationInstance;
}
JToken tagsSequenceElement = ((JToken)valueValue["tags"]);
if (tagsSequenceElement != null && tagsSequenceElement.Type != JTokenType.Null)
{
foreach (JProperty property in tagsSequenceElement)
{
string tagsKey = ((string)property.Name);
string tagsValue = ((string)property.Value);
dscNodeInstance.Tags.Add(tagsKey, tagsValue);
}
}
JToken typeValue = valueValue["type"];
if (typeValue != null && typeValue.Type != JTokenType.Null)
{
string typeInstance = ((string)typeValue);
dscNodeInstance.Type = typeInstance;
}
JToken etagValue = valueValue["etag"];
if (etagValue != null && etagValue.Type != JTokenType.Null)
{
string etagInstance = ((string)etagValue);
dscNodeInstance.Etag = etagInstance;
}
}
}
JToken odatanextLinkValue = responseDoc["odata.nextLink"];
if (odatanextLinkValue != null && odatanextLinkValue.Type != JTokenType.Null)
{
string odatanextLinkInstance = Regex.Match(((string)odatanextLinkValue), "^.*[&\\?]\\$skiptoken=([^&]*)(&.*)?").Groups[1].Value;
result.SkipToken = odatanextLinkInstance;
}
JToken nextLinkValue = responseDoc["nextLink"];
if (nextLinkValue != null && nextLinkValue.Type != JTokenType.Null)
{
string nextLinkInstance = ((string)nextLinkValue);
result.NextLink = nextLinkInstance;
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Retrieve next list of configurations. (see
/// http://aka.ms/azureautomationsdk/dscnodeoperations for more
/// information)
/// </summary>
/// <param name='nextLink'>
/// Required. The link to retrieve next set of items.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The response model for the list dsc nodes operation.
/// </returns>
public async Task<DscNodeListResponse> ListNextAsync(string nextLink, CancellationToken cancellationToken)
{
// Validate
if (nextLink == null)
{
throw new ArgumentNullException("nextLink");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("nextLink", nextLink);
TracingAdapter.Enter(invocationId, this, "ListNextAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + nextLink;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("Accept", "application/json");
httpRequest.Headers.Add("ocp-referer", url);
httpRequest.Headers.Add("x-ms-version", "2014-06-01");
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
DscNodeListResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new DscNodeListResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
JToken valueArray = responseDoc["value"];
if (valueArray != null && valueArray.Type != JTokenType.Null)
{
foreach (JToken valueValue in ((JArray)valueArray))
{
DscNode dscNodeInstance = new DscNode();
result.Nodes.Add(dscNodeInstance);
JToken lastSeenValue = valueValue["lastSeen"];
if (lastSeenValue != null && lastSeenValue.Type != JTokenType.Null)
{
DateTimeOffset lastSeenInstance = ((DateTimeOffset)lastSeenValue);
dscNodeInstance.LastSeen = lastSeenInstance;
}
JToken registrationTimeValue = valueValue["registrationTime"];
if (registrationTimeValue != null && registrationTimeValue.Type != JTokenType.Null)
{
DateTimeOffset registrationTimeInstance = ((DateTimeOffset)registrationTimeValue);
dscNodeInstance.RegistrationTime = registrationTimeInstance;
}
JToken ipValue = valueValue["ip"];
if (ipValue != null && ipValue.Type != JTokenType.Null)
{
string ipInstance = ((string)ipValue);
dscNodeInstance.Ip = ipInstance;
}
JToken accountIdValue = valueValue["accountId"];
if (accountIdValue != null && accountIdValue.Type != JTokenType.Null)
{
Guid accountIdInstance = Guid.Parse(((string)accountIdValue));
dscNodeInstance.AccountId = accountIdInstance;
}
JToken nodeConfigurationValue = valueValue["nodeConfiguration"];
if (nodeConfigurationValue != null && nodeConfigurationValue.Type != JTokenType.Null)
{
DscNodeConfigurationAssociationProperty nodeConfigurationInstance = new DscNodeConfigurationAssociationProperty();
dscNodeInstance.NodeConfiguration = nodeConfigurationInstance;
JToken nameValue = nodeConfigurationValue["name"];
if (nameValue != null && nameValue.Type != JTokenType.Null)
{
string nameInstance = ((string)nameValue);
nodeConfigurationInstance.Name = nameInstance;
}
}
JToken extensionHandlerArray = valueValue["extensionHandler"];
if (extensionHandlerArray != null && extensionHandlerArray.Type != JTokenType.Null)
{
foreach (JToken extensionHandlerValue in ((JArray)extensionHandlerArray))
{
DscNodeExtensionHandlerAssociationProperty dscNodeExtensionHandlerAssociationPropertyInstance = new DscNodeExtensionHandlerAssociationProperty();
dscNodeInstance.ExtensionHandler.Add(dscNodeExtensionHandlerAssociationPropertyInstance);
JToken nameValue2 = extensionHandlerValue["name"];
if (nameValue2 != null && nameValue2.Type != JTokenType.Null)
{
string nameInstance2 = ((string)nameValue2);
dscNodeExtensionHandlerAssociationPropertyInstance.Name = nameInstance2;
}
JToken versionValue = extensionHandlerValue["version"];
if (versionValue != null && versionValue.Type != JTokenType.Null)
{
string versionInstance = ((string)versionValue);
dscNodeExtensionHandlerAssociationPropertyInstance.Version = versionInstance;
}
}
}
JToken statusValue = valueValue["status"];
if (statusValue != null && statusValue.Type != JTokenType.Null)
{
string statusInstance = ((string)statusValue);
dscNodeInstance.Status = statusInstance;
}
JToken nodeIdValue = valueValue["nodeId"];
if (nodeIdValue != null && nodeIdValue.Type != JTokenType.Null)
{
Guid nodeIdInstance = Guid.Parse(((string)nodeIdValue));
dscNodeInstance.NodeId = nodeIdInstance;
}
JToken idValue = valueValue["id"];
if (idValue != null && idValue.Type != JTokenType.Null)
{
string idInstance = ((string)idValue);
dscNodeInstance.Id = idInstance;
}
JToken nameValue3 = valueValue["name"];
if (nameValue3 != null && nameValue3.Type != JTokenType.Null)
{
string nameInstance3 = ((string)nameValue3);
dscNodeInstance.Name = nameInstance3;
}
JToken locationValue = valueValue["location"];
if (locationValue != null && locationValue.Type != JTokenType.Null)
{
string locationInstance = ((string)locationValue);
dscNodeInstance.Location = locationInstance;
}
JToken tagsSequenceElement = ((JToken)valueValue["tags"]);
if (tagsSequenceElement != null && tagsSequenceElement.Type != JTokenType.Null)
{
foreach (JProperty property in tagsSequenceElement)
{
string tagsKey = ((string)property.Name);
string tagsValue = ((string)property.Value);
dscNodeInstance.Tags.Add(tagsKey, tagsValue);
}
}
JToken typeValue = valueValue["type"];
if (typeValue != null && typeValue.Type != JTokenType.Null)
{
string typeInstance = ((string)typeValue);
dscNodeInstance.Type = typeInstance;
}
JToken etagValue = valueValue["etag"];
if (etagValue != null && etagValue.Type != JTokenType.Null)
{
string etagInstance = ((string)etagValue);
dscNodeInstance.Etag = etagInstance;
}
}
}
JToken odatanextLinkValue = responseDoc["odata.nextLink"];
if (odatanextLinkValue != null && odatanextLinkValue.Type != JTokenType.Null)
{
string odatanextLinkInstance = Regex.Match(((string)odatanextLinkValue), "^.*[&\\?]\\$skiptoken=([^&]*)(&.*)?").Groups[1].Value;
result.SkipToken = odatanextLinkInstance;
}
JToken nextLinkValue = responseDoc["nextLink"];
if (nextLinkValue != null && nextLinkValue.Type != JTokenType.Null)
{
string nextLinkInstance = ((string)nextLinkValue);
result.NextLink = nextLinkInstance;
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Update the dsc node. (see
/// http://aka.ms/azureautomationsdk/dscnodeoperations for more
/// information)
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group
/// </param>
/// <param name='automationAccount'>
/// Required. The automation account name.
/// </param>
/// <param name='parameters'>
/// Required. Parameters supplied to the patch dsc node.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The response model for the patch dsc node operation.
/// </returns>
public async Task<DscNodePatchResponse> PatchAsync(string resourceGroupName, string automationAccount, DscNodePatchParameters parameters, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (automationAccount == null)
{
throw new ArgumentNullException("automationAccount");
}
if (parameters == null)
{
throw new ArgumentNullException("parameters");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("automationAccount", automationAccount);
tracingParameters.Add("parameters", parameters);
TracingAdapter.Enter(invocationId, this, "PatchAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/resourceGroups/";
url = url + Uri.EscapeDataString(resourceGroupName);
url = url + "/providers/";
if (this.Client.ResourceNamespace != null)
{
url = url + Uri.EscapeDataString(this.Client.ResourceNamespace);
}
url = url + "/automationAccounts/";
url = url + Uri.EscapeDataString(automationAccount);
url = url + "/nodes/";
if (parameters.NodeId != null)
{
url = url + Uri.EscapeDataString(parameters.NodeId.ToString());
}
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2017-05-15-preview");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = new HttpMethod("PATCH");
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("x-ms-version", "2014-06-01");
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Serialize Request
string requestContent = null;
JToken requestDoc = null;
JObject dscNodePatchParametersValue = new JObject();
requestDoc = dscNodePatchParametersValue;
dscNodePatchParametersValue["nodeId"] = parameters.NodeId.ToString();
if (parameters.NodeConfiguration != null)
{
JObject nodeConfigurationValue = new JObject();
dscNodePatchParametersValue["nodeConfiguration"] = nodeConfigurationValue;
if (parameters.NodeConfiguration.Name != null)
{
nodeConfigurationValue["name"] = parameters.NodeConfiguration.Name;
}
}
requestContent = requestDoc.ToString(Newtonsoft.Json.Formatting.Indented);
httpRequest.Content = new StringContent(requestContent, Encoding.UTF8);
httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json");
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, requestContent, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
DscNodePatchResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new DscNodePatchResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
DscNode nodeInstance = new DscNode();
result.Node = nodeInstance;
JToken lastSeenValue = responseDoc["lastSeen"];
if (lastSeenValue != null && lastSeenValue.Type != JTokenType.Null)
{
DateTimeOffset lastSeenInstance = ((DateTimeOffset)lastSeenValue);
nodeInstance.LastSeen = lastSeenInstance;
}
JToken registrationTimeValue = responseDoc["registrationTime"];
if (registrationTimeValue != null && registrationTimeValue.Type != JTokenType.Null)
{
DateTimeOffset registrationTimeInstance = ((DateTimeOffset)registrationTimeValue);
nodeInstance.RegistrationTime = registrationTimeInstance;
}
JToken ipValue = responseDoc["ip"];
if (ipValue != null && ipValue.Type != JTokenType.Null)
{
string ipInstance = ((string)ipValue);
nodeInstance.Ip = ipInstance;
}
JToken accountIdValue = responseDoc["accountId"];
if (accountIdValue != null && accountIdValue.Type != JTokenType.Null)
{
Guid accountIdInstance = Guid.Parse(((string)accountIdValue));
nodeInstance.AccountId = accountIdInstance;
}
JToken nodeConfigurationValue2 = responseDoc["nodeConfiguration"];
if (nodeConfigurationValue2 != null && nodeConfigurationValue2.Type != JTokenType.Null)
{
DscNodeConfigurationAssociationProperty nodeConfigurationInstance = new DscNodeConfigurationAssociationProperty();
nodeInstance.NodeConfiguration = nodeConfigurationInstance;
JToken nameValue = nodeConfigurationValue2["name"];
if (nameValue != null && nameValue.Type != JTokenType.Null)
{
string nameInstance = ((string)nameValue);
nodeConfigurationInstance.Name = nameInstance;
}
}
JToken extensionHandlerArray = responseDoc["extensionHandler"];
if (extensionHandlerArray != null && extensionHandlerArray.Type != JTokenType.Null)
{
foreach (JToken extensionHandlerValue in ((JArray)extensionHandlerArray))
{
DscNodeExtensionHandlerAssociationProperty dscNodeExtensionHandlerAssociationPropertyInstance = new DscNodeExtensionHandlerAssociationProperty();
nodeInstance.ExtensionHandler.Add(dscNodeExtensionHandlerAssociationPropertyInstance);
JToken nameValue2 = extensionHandlerValue["name"];
if (nameValue2 != null && nameValue2.Type != JTokenType.Null)
{
string nameInstance2 = ((string)nameValue2);
dscNodeExtensionHandlerAssociationPropertyInstance.Name = nameInstance2;
}
JToken versionValue = extensionHandlerValue["version"];
if (versionValue != null && versionValue.Type != JTokenType.Null)
{
string versionInstance = ((string)versionValue);
dscNodeExtensionHandlerAssociationPropertyInstance.Version = versionInstance;
}
}
}
JToken statusValue = responseDoc["status"];
if (statusValue != null && statusValue.Type != JTokenType.Null)
{
string statusInstance = ((string)statusValue);
nodeInstance.Status = statusInstance;
}
JToken nodeIdValue = responseDoc["nodeId"];
if (nodeIdValue != null && nodeIdValue.Type != JTokenType.Null)
{
Guid nodeIdInstance = Guid.Parse(((string)nodeIdValue));
nodeInstance.NodeId = nodeIdInstance;
}
JToken idValue = responseDoc["id"];
if (idValue != null && idValue.Type != JTokenType.Null)
{
string idInstance = ((string)idValue);
nodeInstance.Id = idInstance;
}
JToken nameValue3 = responseDoc["name"];
if (nameValue3 != null && nameValue3.Type != JTokenType.Null)
{
string nameInstance3 = ((string)nameValue3);
nodeInstance.Name = nameInstance3;
}
JToken locationValue = responseDoc["location"];
if (locationValue != null && locationValue.Type != JTokenType.Null)
{
string locationInstance = ((string)locationValue);
nodeInstance.Location = locationInstance;
}
JToken tagsSequenceElement = ((JToken)responseDoc["tags"]);
if (tagsSequenceElement != null && tagsSequenceElement.Type != JTokenType.Null)
{
foreach (JProperty property in tagsSequenceElement)
{
string tagsKey = ((string)property.Name);
string tagsValue = ((string)property.Value);
nodeInstance.Tags.Add(tagsKey, tagsValue);
}
}
JToken typeValue = responseDoc["type"];
if (typeValue != null && typeValue.Type != JTokenType.Null)
{
string typeInstance = ((string)typeValue);
nodeInstance.Type = typeInstance;
}
JToken etagValue = responseDoc["etag"];
if (etagValue != null && etagValue.Type != JTokenType.Null)
{
string etagInstance = ((string)etagValue);
nodeInstance.Etag = etagInstance;
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using System.Timers;
using Nimbus.ConcurrentCollections;
using Nimbus.Configuration.Settings;
using Nimbus.Extensions;
using Nimbus.Infrastructure.Events;
using Nimbus.Infrastructure.Heartbeat.PerformanceCounters;
using Nimbus.MessageContracts.ControlMessages;
namespace Nimbus.Infrastructure.Heartbeat
{
internal class Heartbeat : IHeartbeat, IDisposable
{
private readonly HeartbeatIntervalSetting _heartbeatInterval;
private readonly IEventSender _eventSender;
private readonly ILogger _logger;
private readonly IClock _clock;
private readonly List<PerformanceCounterBase> _performanceCounters = new List<PerformanceCounterBase>();
private readonly List<PerformanceCounterDto> _performanceCounterHistory = new List<PerformanceCounterDto>();
private readonly object _mutex = new object();
private static readonly ThreadSafeLazy<Type[]> _performanceCounterTypes = new ThreadSafeLazy<Type[]>(() => typeof (Heartbeat).Assembly
.DefinedTypes
.Select(ti => ti.AsType())
.Where(
t =>
typeof (PerformanceCounterBase)
.IsAssignableFrom(t))
.Where(t => !t.IsAbstract)
.ToArray());
private Timer _heartbeatTimer;
private Timer _collectTimer;
private bool _isRunning;
private int _heartbeatExecuting;
public Heartbeat(HeartbeatIntervalSetting heartbeatInterval, IClock clock, IEventSender eventSender, ILogger logger)
{
_heartbeatInterval = heartbeatInterval;
_eventSender = eventSender;
_logger = logger;
_clock = clock;
}
private void OnCollectTimerElapsed(object sender, ElapsedEventArgs e)
{
Task.Run(() => Collect());
}
private async Task Collect()
{
lock (_mutex)
{
var dtos = _performanceCounters
.AsParallel()
.Select(c => new PerformanceCounterDto(_clock.UtcNow, c.CounterName, c.CategoryName, c.InstanceName, c.GetNextTransformedValue()))
.ToArray();
_performanceCounterHistory.AddRange(dtos);
}
}
private async void OnHeartbeatTimerElapsed(object sender, ElapsedEventArgs e)
{
// Prevent overlapping execution of heartbeats
if (System.Threading.Interlocked.CompareExchange(ref _heartbeatExecuting, 1, 0) == 0)
{
try
{
// The timer elapsed handler is already executing on the threadpool, so
// there is no reason to use Task.Run() to invoke the Beat method. Await the
// beat so the heartbeatExecuting flag can be set to zero (reset) when complete.
await Beat();
}
catch (Exception exc)
{
_logger.Warn("Error publishing heartbeat: {Message}.", exc.ToString());
}
finally
{
_heartbeatExecuting = 0; // indicates completion
}
}
}
private async Task Beat()
{
var heartbeatEvent = CreateHeartbeatEvent();
await _eventSender.Publish(heartbeatEvent);
}
public async Task Start()
{
if (_heartbeatInterval.Value == TimeSpan.MaxValue) return;
if (_isRunning) return;
foreach (var counterType in _performanceCounterTypes.Value)
{
try
{
var counter = (PerformanceCounterBase) Activator.CreateInstance(counterType);
_performanceCounters.Add(counter);
}
catch (Exception exc)
{
_logger.Warn(
"Could not create performance counter {PerformanceCounter}: {Message}. This might occur because the current process is not running with suffucient privileges.",
counterType.FullName,
exc.ToString());
}
}
_collectTimer = new Timer(TimeSpan.FromSeconds(5).TotalMilliseconds)
{
AutoReset = true
};
_collectTimer.Elapsed += OnCollectTimerElapsed;
_collectTimer.Start();
_heartbeatTimer = new Timer(_heartbeatInterval.Value.TotalMilliseconds)
{
AutoReset = true
};
_heartbeatTimer.Elapsed += OnHeartbeatTimerElapsed;
_heartbeatTimer.Start();
_isRunning = true;
}
public async Task Stop()
{
if (_heartbeatInterval.Value == TimeSpan.MaxValue) return;
if (!_isRunning) return;
var collectTimer = _collectTimer;
_collectTimer = null;
if (collectTimer != null)
{
collectTimer.Stop();
collectTimer.Dispose();
}
var heartbeatTimer = _heartbeatTimer;
_heartbeatTimer = null;
if (heartbeatTimer != null)
{
heartbeatTimer.Stop();
heartbeatTimer.Dispose();
}
_performanceCounters
.AsParallel()
.OfType<IDisposable>()
.Do(c => c.Dispose())
.Done();
_performanceCounters.Clear();
}
private HeartbeatEvent CreateHeartbeatEvent()
{
var process = Process.GetCurrentProcess();
PerformanceCounterDto[] performanceCounterHistory;
lock (_mutex)
{
performanceCounterHistory = _performanceCounterHistory.ToArray();
_performanceCounterHistory.Clear();
}
var heartbeatEvent = new HeartbeatEvent
{
Timestamp = _clock.UtcNow,
ProcessId = process.Id,
ProcessName = process.ProcessName,
MachineName = Environment.MachineName,
OSVersion = Environment.OSVersion.VersionString,
ProcessorCount = Environment.ProcessorCount,
StartTime = new DateTimeOffset(process.StartTime),
UserProcessorTime = process.UserProcessorTime,
TotalProcessorTime = process.TotalProcessorTime,
WorkingSet64 = process.WorkingSet64,
PeakWorkingSet64 = process.PeakWorkingSet64,
VirtualMemorySize64 = process.VirtualMemorySize64,
PerformanceCounters = performanceCounterHistory
};
return heartbeatEvent;
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (!disposing) return;
Stop().Wait();
}
}
}
| |
using System;
using Xunit;
using FluentAssertions;
using EmsApi.Dto.V2;
namespace EmsApi.Tests
{
public class DatabaseTests : TestBase
{
[Fact( DisplayName = "Get field should return discrete values" )]
public void Get_field_should_return_discrete_values()
{
using var api = NewService();
string flightRecordField = "[-hub-][field][[[ems-core][entity-type][foqa-flights]][[ems-core][base-field][flight.uid]]]";
Field noDiscrete = api.Databases.GetField( "[ems-core][entity-type][foqa-flights]", flightRecordField );
noDiscrete.DiscreteValues.Should().BeNull();
string eventStatusField = "[-hub-][field][[[ems-apm][entity-type][events:profile-a7483c449db94a449eb5f67681ee52b0]][[ems-apm][event-field][event-status:profile-a7483c449db94a449eb5f67681ee52b0]]]";
Field withDiscrete = api.Databases.GetField( "[ems-apm][entity-type][events:profile-a7483c449db94a449eb5f67681ee52b0]", eventStatusField );
withDiscrete.DiscreteValues.Should().NotBeNull();
}
[Fact( DisplayName = "A simple query with ordered results should return rows" )]
public void Simple_query_with_ordered_results_should_return_rows()
{
TestSimple( orderResults: true );
}
[Fact( DisplayName = "A simple query should return rows" )]
public void Simple_query_should_return_rows()
{
TestSimple( orderResults: false );
}
[Fact( DisplayName = "A simple query should fire callbacks" )]
public void Simple_query_should_fire_callbacks()
{
using var api = NewService();
var query = CreateQuery( orderResults: true );
// Limit the result set to 10 items and make sure we get 10 callbacks.
const int numItems = 10;
query.Top = numItems;
int numCallbacks = 0;
void callback( DatabaseQueryResult.Row row )
{
TestRow( row );
numCallbacks++;
}
api.Databases.SimpleQuery( Monikers.FlightDatabase, query, callback );
numCallbacks.Should().Be( numItems );
}
[Fact( DisplayName = "An advanced query should return rows" )]
public void Advanced_query_should_return_rows()
{
TestAdvanced( orderResults: false );
}
[Fact( DisplayName = "An advanced query with ordered results should return rows" )]
public void Advanced_query_with_ordered_results_should_return_rows()
{
TestAdvanced( orderResults: true );
}
[Fact( DisplayName = "An advanced query should fire callbacks" )]
public void Advanced_query_should_fire_callbacks()
{
using var api = NewService();
var query = CreateQuery( orderResults: true );
// Limit the result set to 20 items and make sure we get 20 callbacks.
const int numItems = 20;
query.Top = numItems;
int numCallbacks = 0;
void callback( DatabaseQueryResult.Row row )
{
TestRow( row );
numCallbacks++;
}
api.Databases.Query( Monikers.FlightDatabase, query, callback );
numCallbacks.Should().Be( numItems );
}
[Fact( DisplayName = "An advanced query should handle pagination" )]
public void Advanced_query_should_handle_pagination()
{
using var api = NewService();
// Note: To be deterministic, we have to use ordered results so the
// callbacks fire in order.
var query = CreateQuery( orderResults: true );
const int numItems = 30;
query.Top = numItems;
int numCallbacks = 0;
void callback( DatabaseQueryResult.Row row )
{
TestRow( row );
numCallbacks++;
}
api.Databases.Query( Monikers.FlightDatabase, query, callback, rowsPerCall: 10 );
numCallbacks.Should().Be( numItems );
}
#pragma warning disable xUnit1004 // Test methods should not be skipped
[Fact( DisplayName = "A create comment query should add a new comment", Skip = "We don't want to add a new comment every time the tests are run." )]
#pragma warning restore xUnit1004 // Test methods should not be skipped
public void Create_Comment_should_add_comment()
{
using var api = NewService();
var newComment = new NewComment
{
Comment = "look at that data quality",
// This value will depend on the EMS system. It should be a flight record number.
EntityIdentifier = { 3135409 }
};
api.Databases.CreateComment( Monikers.FlightDatabase, Monikers.FlightDataQualityField, newComment );
}
private static void TestSimple( bool orderResults )
{
using var api = NewService();
var query = CreateQuery( orderResults );
// Limit the number of flights returned for the simple query test.
const int numRows = 10;
query.Top = numRows;
// The simple query uses the non-async database route.
DatabaseQueryResult result = api.Databases.SimpleQuery( Monikers.FlightDatabase, query );
result.Rows.Count.Should().Be( numRows );
foreach( DatabaseQueryResult.Row row in result.Rows )
TestRow( row );
}
private static void TestAdvanced( bool orderResults )
{
using var api = NewService();
var query = CreateQuery( orderResults );
// Limit to 100 rows to save bandwidth.
query.Top = 100;
// The regular query uses async-query under the covers and handles pagination.
DatabaseQueryResult result = api.Databases.Query( Monikers.FlightDatabase, query );
foreach( DatabaseQueryResult.Row row in result.Rows )
TestRow( row );
}
private static void TestRow( DatabaseQueryResult.Row row )
{
int flightId = Convert.ToInt32( row[Monikers.FlightId] );
string tail = row[Monikers.TailNumber].ToString();
string cityPair = row[Monikers.CityPair].ToString();
string takeoffAirport = row[Monikers.TakeoffAirportName].ToString();
string landingAirport = row[Monikers.LandingAirportName].ToString();
flightId.Should().BeGreaterThan( 0 );
tail.Should().NotBeNullOrEmpty();
cityPair.Should().NotBeNullOrEmpty();
takeoffAirport.Should().NotBeNullOrEmpty();
landingAirport.Should().NotBeNullOrEmpty();
}
private static DatabaseQuery CreateQuery( bool orderResults )
{
var query = new DatabaseQuery();
// Select a few columns.
query.SelectField( Monikers.FlightId );
query.SelectField( Monikers.TailNumber );
query.SelectField( Monikers.CityPair );
query.SelectField( Monikers.TakeoffAirportName );
query.SelectField( Monikers.LandingAirportName );
// Filter for takeoff and landing valid.
query.AddBooleanFilter( Monikers.TakeoffValid, true );
query.AddBooleanFilter( Monikers.LandingValid, true );
// Order by flight id.
if( orderResults )
query.OrderByField( Monikers.FlightId );
// Use display formatting.
query.ValueFormat = DbQueryFormat.Display;
return query;
}
private static class Monikers
{
public static string FlightDatabase = "[ems-core][entity-type][foqa-flights]";
public static string FlightId = "[-hub-][field][[[ems-core][entity-type][foqa-flights]][[ems-core][base-field][flight.uid]]]";
public static string TailNumber = "[-hub-][field][[[ems-core][entity-type][foqa-flights]][[ems-core][base-field][flight.aircraft]]]";
public static string CityPair = "[-hub-][field][[[ems-core][entity-type][foqa-flights]][[ems-core][base-field][city-pair.pair]]]";
public static string TakeoffAirportName = "[-hub-][field][[[ems-core][entity-type][foqa-flights]][[[nav][type-link][airport-takeoff * foqa-flights]]][[nav][base-field][nav-airport.name]]]";
public static string LandingAirportName = "[-hub-][field][[[ems-core][entity-type][foqa-flights]][[[nav][type-link][airport-landing * foqa-flights]]][[nav][base-field][nav-airport.name]]]";
public static string TakeoffValid = "[-hub-][field][[[ems-core][entity-type][foqa-flights]][[ems-core][base-field][flight.exist-takeoff]]]";
public static string LandingValid = "[-hub-][field][[[ems-core][entity-type][foqa-flights]][[ems-core][base-field][flight.exist-landing]]]";
public static string FlightDataQualityField = "[-hub-][field][[[ems-core][entity-type][foqa-flights]][[data-quality][base-field][data-quality-comments]]]";
}
}
}
| |
using System.Collections.Generic;
#if CLUSTERING_ADONET
namespace Orleans.Clustering.AdoNet.Storage
#elif PERSISTENCE_ADONET
namespace Orleans.Persistence.AdoNet.Storage
#elif REMINDERS_ADONET
namespace Orleans.Reminders.AdoNet.Storage
#elif TESTER_SQLUTILS
namespace Orleans.Tests.SqlUtils
#else
// No default namespace intentionally to cause compile errors if something is not defined
#endif
{
internal static class DbConstantsStore
{
private static readonly Dictionary<string, DbConstants> invariantNameToConsts =
new Dictionary<string, DbConstants>
{
{
AdoNetInvariants.InvariantNameSqlServer,
new DbConstants(startEscapeIndicator: '[',
endEscapeIndicator: ']',
unionAllSelectTemplate: " UNION ALL SELECT ",
isSynchronousAdoNetImplementation: false,
supportsStreamNatively: true,
supportsCommandCancellation: true,
commandInterceptor: NoOpCommandInterceptor.Instance)
},
{AdoNetInvariants.InvariantNameMySql, new DbConstants(
startEscapeIndicator: '`',
endEscapeIndicator: '`',
unionAllSelectTemplate: " UNION ALL SELECT ",
isSynchronousAdoNetImplementation: true,
supportsStreamNatively: false,
supportsCommandCancellation: false,
commandInterceptor: NoOpCommandInterceptor.Instance)
},
{AdoNetInvariants.InvariantNamePostgreSql, new DbConstants(
startEscapeIndicator: '"',
endEscapeIndicator: '"',
unionAllSelectTemplate: " UNION ALL SELECT ",
isSynchronousAdoNetImplementation: true, //there are some intermittent PostgreSQL problems too, see more discussion at https://github.com/dotnet/orleans/pull/2949.
supportsStreamNatively: true,
supportsCommandCancellation: true, // See https://dev.mysql.com/doc/connector-net/en/connector-net-ref-mysqlclient-mysqlcommandmembers.html.
commandInterceptor: NoOpCommandInterceptor.Instance)
},
{AdoNetInvariants.InvariantNameOracleDatabase, new DbConstants(
startEscapeIndicator: '\"',
endEscapeIndicator: '\"',
unionAllSelectTemplate: " FROM DUAL UNION ALL SELECT ",
isSynchronousAdoNetImplementation: true,
supportsStreamNatively: false,
supportsCommandCancellation: false, // Is supported but the remarks sound scary: https://docs.oracle.com/cd/E11882_01/win.112/e23174/OracleCommandClass.htm#DAFIEHHG.
commandInterceptor: OracleCommandInterceptor.Instance)
},
{
AdoNetInvariants.InvariantNameSqlServerDotnetCore,
new DbConstants(startEscapeIndicator: '[',
endEscapeIndicator: ']',
unionAllSelectTemplate: " UNION ALL SELECT ",
isSynchronousAdoNetImplementation: false,
supportsStreamNatively: true,
supportsCommandCancellation: true,
commandInterceptor: NoOpCommandInterceptor.Instance)
},
{
AdoNetInvariants.InvariantNameMySqlConnector,
new DbConstants(startEscapeIndicator: '[',
endEscapeIndicator: ']',
unionAllSelectTemplate: " UNION ALL SELECT ",
isSynchronousAdoNetImplementation: false,
supportsStreamNatively: true,
supportsCommandCancellation: true,
commandInterceptor: NoOpCommandInterceptor.Instance)
}
};
public static DbConstants GetDbConstants(string invariantName)
{
return invariantNameToConsts[invariantName];
}
/// <summary>
/// If the underlying storage supports cancellation or not.
/// </summary>
/// <param name="storage">The storage used.</param>
/// <returns><em>TRUE</em> if cancellation is supported. <em>FALSE</em> otherwise.</returns>
public static bool SupportsCommandCancellation(this IRelationalStorage storage)
{
return SupportsCommandCancellation(storage.InvariantName);
}
/// <summary>
/// If the provider supports cancellation or not.
/// </summary>
/// <param name="adoNetProvider">The ADO.NET provider invariant string.</param>
/// <returns><em>TRUE</em> if cancellation is supported. <em>FALSE</em> otherwise.</returns>
public static bool SupportsCommandCancellation(string adoNetProvider)
{
return GetDbConstants(adoNetProvider).SupportsCommandCancellation;
}
/// <summary>
/// If the underlying storage supports streaming natively.
/// </summary>
/// <param name="storage">The storage used.</param>
/// <returns><em>TRUE</em> if streaming is supported natively. <em>FALSE</em> otherwise.</returns>
public static bool SupportsStreamNatively(this IRelationalStorage storage)
{
return SupportsStreamNatively(storage.InvariantName);
}
/// <summary>
/// If the provider supports streaming natively.
/// </summary>
/// <param name="adoNetProvider">The ADO.NET provider invariant string.</param>
/// <returns><em>TRUE</em> if streaming is supported natively. <em>FALSE</em> otherwise.</returns>
public static bool SupportsStreamNatively(string adoNetProvider)
{
return GetDbConstants(adoNetProvider).SupportsStreamNatively;
}
/// <summary>
/// If the underlying ADO.NET implementation is known to be synchronous.
/// </summary>
/// <param name="storage">The storage used.</param>
/// <returns></returns>
public static bool IsSynchronousAdoNetImplementation(this IRelationalStorage storage)
{
//Currently the assumption is all but MySQL are asynchronous.
return IsSynchronousAdoNetImplementation(storage.InvariantName);
}
/// <summary>
/// If the provider supports cancellation or not.
/// </summary>
/// <param name="adoNetProvider">The ADO.NET provider invariant string.</param>
/// <returns></returns>
public static bool IsSynchronousAdoNetImplementation(string adoNetProvider)
{
return GetDbConstants(adoNetProvider).IsSynchronousAdoNetImplementation;
}
public static ICommandInterceptor GetDatabaseCommandInterceptor(string invariantName)
{
return GetDbConstants(invariantName).DatabaseCommandInterceptor;
}
}
internal class DbConstants
{
/// <summary>
/// A query template for union all select
/// </summary>
public readonly string UnionAllSelectTemplate;
/// <summary>
/// Indicates whether the ADO.net provider does only support synchronous operations.
/// </summary>
public readonly bool IsSynchronousAdoNetImplementation;
/// <summary>
/// Indicates whether the ADO.net provider does streaming operations natively.
/// </summary>
public readonly bool SupportsStreamNatively;
/// <summary>
/// Indicates whether the ADO.net provider supports cancellation of commands.
/// </summary>
public readonly bool SupportsCommandCancellation;
/// <summary>
/// The character that indicates a start escape key for columns and tables that are reserved words.
/// </summary>
public readonly char StartEscapeIndicator;
/// <summary>
/// The character that indicates an end escape key for columns and tables that are reserved words.
/// </summary>
public readonly char EndEscapeIndicator;
public readonly ICommandInterceptor DatabaseCommandInterceptor;
public DbConstants(char startEscapeIndicator, char endEscapeIndicator, string unionAllSelectTemplate,
bool isSynchronousAdoNetImplementation, bool supportsStreamNatively, bool supportsCommandCancellation, ICommandInterceptor commandInterceptor)
{
StartEscapeIndicator = startEscapeIndicator;
EndEscapeIndicator = endEscapeIndicator;
UnionAllSelectTemplate = unionAllSelectTemplate;
IsSynchronousAdoNetImplementation = isSynchronousAdoNetImplementation;
SupportsStreamNatively = supportsStreamNatively;
SupportsCommandCancellation = supportsCommandCancellation;
DatabaseCommandInterceptor = commandInterceptor;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Internal;
using Microsoft.Extensions.Primitives;
using Microsoft.Net.Http.Headers;
namespace Microsoft.AspNetCore.Routing.Matching
{
/// <summary>
/// An <see cref="MatcherPolicy"/> that implements filtering and selection by
/// the HTTP method of a request.
/// </summary>
public sealed class HttpMethodMatcherPolicy : MatcherPolicy, IEndpointComparerPolicy, INodeBuilderPolicy, IEndpointSelectorPolicy
{
// Used in tests
internal static readonly string PreflightHttpMethod = HttpMethods.Options;
// Used in tests
internal const string Http405EndpointDisplayName = "405 HTTP Method Not Supported";
// Used in tests
internal const string AnyMethod = "*";
/// <summary>
/// For framework use only.
/// </summary>
public IComparer<Endpoint> Comparer => new HttpMethodMetadataEndpointComparer();
// The order value is chosen to be less than 0, so that it comes before naively
// written policies.
/// <summary>
/// For framework use only.
/// </summary>
public override int Order => -1000;
bool INodeBuilderPolicy.AppliesToEndpoints(IReadOnlyList<Endpoint> endpoints)
{
if (endpoints == null)
{
throw new ArgumentNullException(nameof(endpoints));
}
if (ContainsDynamicEndpoints(endpoints))
{
return false;
}
return AppliesToEndpointsCore(endpoints);
}
bool IEndpointSelectorPolicy.AppliesToEndpoints(IReadOnlyList<Endpoint> endpoints)
{
if (endpoints == null)
{
throw new ArgumentNullException(nameof(endpoints));
}
// When the node contains dynamic endpoints we can't make any assumptions.
return ContainsDynamicEndpoints(endpoints);
}
private static bool AppliesToEndpointsCore(IReadOnlyList<Endpoint> endpoints)
{
for (var i = 0; i < endpoints.Count; i++)
{
if (endpoints[i].Metadata.GetMetadata<IHttpMethodMetadata>()?.HttpMethods.Count > 0)
{
return true;
}
}
return false;
}
/// <summary>
/// For framework use only.
/// </summary>
/// <param name="httpContext"></param>
/// <param name="candidates"></param>
/// <returns></returns>
public Task ApplyAsync(HttpContext httpContext, CandidateSet candidates)
{
if (httpContext == null)
{
throw new ArgumentNullException(nameof(httpContext));
}
if (candidates == null)
{
throw new ArgumentNullException(nameof(candidates));
}
// Returning a 405 here requires us to return keep track of all 'seen' HTTP methods. We allocate to
// keep track of this because we either need to keep track of the HTTP methods or keep track of the
// endpoints - both allocate.
//
// Those code only runs in the presence of dynamic endpoints anyway.
//
// We want to return a 405 iff we eliminated ALL of the currently valid endpoints due to HTTP method
// mismatch.
bool? needs405Endpoint = null;
HashSet<string>? methods = null;
for (var i = 0; i < candidates.Count; i++)
{
// We do this check first for consistency with how 405 is implemented for the graph version
// of this code. We still want to know if any endpoints in this set require an HTTP method
// even if those endpoints are already invalid - hence the null-check.
var metadata = candidates[i].Endpoint?.Metadata.GetMetadata<IHttpMethodMetadata>();
if (metadata == null || metadata.HttpMethods.Count == 0)
{
// Can match any method.
needs405Endpoint = false;
continue;
}
// Saw a valid endpoint.
needs405Endpoint = needs405Endpoint ?? true;
if (!candidates.IsValidCandidate(i))
{
continue;
}
var httpMethod = httpContext.Request.Method;
var headers = httpContext.Request.Headers;
if (metadata.AcceptCorsPreflight &&
HttpMethods.Equals(httpMethod, PreflightHttpMethod) &&
headers.ContainsKey(HeaderNames.Origin) &&
headers.TryGetValue(HeaderNames.AccessControlRequestMethod, out var accessControlRequestMethod) &&
!StringValues.IsNullOrEmpty(accessControlRequestMethod))
{
needs405Endpoint = false; // We don't return a 405 for a CORS preflight request when the endpoints accept CORS preflight.
httpMethod = accessControlRequestMethod.ToString();
}
var matched = false;
for (var j = 0; j < metadata.HttpMethods.Count; j++)
{
var candidateMethod = metadata.HttpMethods[j];
if (!HttpMethods.Equals(httpMethod, candidateMethod))
{
methods = methods ?? new HashSet<string>(StringComparer.OrdinalIgnoreCase);
methods.Add(candidateMethod);
continue;
}
matched = true;
needs405Endpoint = false;
break;
}
if (!matched)
{
candidates.SetValidity(i, false);
}
}
if (needs405Endpoint == true)
{
// We saw some endpoints coming in, and we eliminated them all.
httpContext.SetEndpoint(CreateRejectionEndpoint(methods!.OrderBy(m => m, StringComparer.OrdinalIgnoreCase)));
httpContext.Request.RouteValues = null!;
}
return Task.CompletedTask;
}
/// <summary>
/// For framework use only.
/// </summary>
/// <param name="endpoints"></param>
/// <returns></returns>
public IReadOnlyList<PolicyNodeEdge> GetEdges(IReadOnlyList<Endpoint> endpoints)
{
// The algorithm here is designed to be preserve the order of the endpoints
// while also being relatively simple. Preserving order is important.
// First, build a dictionary of all possible HTTP method/CORS combinations
// that exist in this list of endpoints.
//
// For now we're just building up the set of keys. We don't add any endpoints
// to lists now because we don't want ordering problems.
var allHttpMethods = new List<string>();
var edges = new Dictionary<EdgeKey, List<Endpoint>>();
for (var i = 0; i < endpoints.Count; i++)
{
var endpoint = endpoints[i];
var (httpMethods, acceptCorsPreFlight) = GetHttpMethods(endpoint);
// If the action doesn't list HTTP methods then it supports all methods.
// In this phase we use a sentinel value to represent the *other* HTTP method
// a state that represents any HTTP method that doesn't have a match.
if (httpMethods.Count == 0)
{
httpMethods = new[] { AnyMethod, };
}
for (var j = 0; j < httpMethods.Count; j++)
{
// An endpoint that allows CORS reqests will match both CORS and non-CORS
// so we model it as both.
var httpMethod = httpMethods[j];
var key = new EdgeKey(httpMethod, acceptCorsPreFlight);
if (!edges.ContainsKey(key))
{
edges.Add(key, new List<Endpoint>());
}
// An endpoint that allows CORS reqests will match both CORS and non-CORS
// so we model it as both.
if (acceptCorsPreFlight)
{
key = new EdgeKey(httpMethod, false);
if (!edges.ContainsKey(key))
{
edges.Add(key, new List<Endpoint>());
}
}
// Also if it's not the *any* method key, then track it.
if (!string.Equals(AnyMethod, httpMethod, StringComparison.OrdinalIgnoreCase))
{
if (!ContainsHttpMethod(allHttpMethods, httpMethod))
{
allHttpMethods.Add(httpMethod);
}
}
}
}
allHttpMethods.Sort(StringComparer.OrdinalIgnoreCase);
// Now in a second loop, add endpoints to these lists. We've enumerated all of
// the states, so we want to see which states this endpoint matches.
for (var i = 0; i < endpoints.Count; i++)
{
var endpoint = endpoints[i];
var (httpMethods, acceptCorsPreFlight) = GetHttpMethods(endpoint);
if (httpMethods.Count == 0)
{
// OK this means that this endpoint matches *all* HTTP methods.
// So, loop and add it to all states.
foreach (var kvp in edges)
{
if (acceptCorsPreFlight || !kvp.Key.IsCorsPreflightRequest)
{
kvp.Value.Add(endpoint);
}
}
}
else
{
// OK this endpoint matches specific methods.
for (var j = 0; j < httpMethods.Count; j++)
{
var httpMethod = httpMethods[j];
var key = new EdgeKey(httpMethod, acceptCorsPreFlight);
edges[key].Add(endpoint);
// An endpoint that allows CORS reqests will match both CORS and non-CORS
// so we model it as both.
if (acceptCorsPreFlight)
{
key = new EdgeKey(httpMethod, false);
edges[key].Add(endpoint);
}
}
}
}
// Adds a very low priority endpoint that will reject the request with
// a 405 if nothing else can handle this verb. This is only done if
// no other actions exist that handle the 'all verbs'.
//
// The rationale for this is that we want to report a 405 if none of
// the supported methods match, but we don't want to report a 405 in a
// case where an application defines an endpoint that handles all verbs, but
// a constraint rejects the request, or a complex segment fails to parse. We
// consider a case like that a 'user input validation' failure rather than
// a semantic violation of HTTP.
//
// This will make 405 much more likely in API-focused applications, and somewhat
// unlikely in a traditional MVC application. That's good.
//
// We don't bother returning a 405 when the CORS preflight method doesn't exist.
// The developer calling the API will see it as a CORS error, which is fine because
// there isn't an endpoint to check for a CORS policy.
if (!edges.TryGetValue(new EdgeKey(AnyMethod, false), out var matches))
{
// Methods sorted for testability.
var endpoint = CreateRejectionEndpoint(allHttpMethods);
matches = new List<Endpoint>() { endpoint, };
edges[new EdgeKey(AnyMethod, false)] = matches;
}
var policyNodeEdges = new PolicyNodeEdge[edges.Count];
var index = 0;
foreach (var kvp in edges)
{
policyNodeEdges[index++] = new PolicyNodeEdge(kvp.Key, kvp.Value);
}
return policyNodeEdges;
(IReadOnlyList<string> httpMethods, bool acceptCorsPreflight) GetHttpMethods(Endpoint e)
{
var metadata = e.Metadata.GetMetadata<IHttpMethodMetadata>();
return metadata == null ? (Array.Empty<string>(), false) : (metadata.HttpMethods, metadata.AcceptCorsPreflight);
}
}
/// <summary>
/// For framework use only.
/// </summary>
/// <param name="exitDestination"></param>
/// <param name="edges"></param>
/// <returns></returns>
public PolicyJumpTable BuildJumpTable(int exitDestination, IReadOnlyList<PolicyJumpTableEdge> edges)
{
Dictionary<string, int>? destinations = null;
Dictionary<string, int>? corsPreflightDestinations = null;
for (var i = 0; i < edges.Count; i++)
{
// We create this data, so it's safe to cast it.
var key = (EdgeKey)edges[i].State;
if (key.IsCorsPreflightRequest)
{
if (corsPreflightDestinations == null)
{
corsPreflightDestinations = new Dictionary<string, int>(StringComparer.OrdinalIgnoreCase);
}
corsPreflightDestinations.Add(key.HttpMethod, edges[i].Destination);
}
else
{
if (destinations == null)
{
destinations = new Dictionary<string, int>(StringComparer.OrdinalIgnoreCase);
}
destinations.Add(key.HttpMethod, edges[i].Destination);
}
}
int corsPreflightExitDestination = exitDestination;
if (corsPreflightDestinations != null && corsPreflightDestinations.TryGetValue(AnyMethod, out var matchesAnyVerb))
{
// If we have endpoints that match any HTTP method, use that as the exit.
corsPreflightExitDestination = matchesAnyVerb;
corsPreflightDestinations.Remove(AnyMethod);
}
if (destinations != null && destinations.TryGetValue(AnyMethod, out matchesAnyVerb))
{
// If we have endpoints that match any HTTP method, use that as the exit.
exitDestination = matchesAnyVerb;
destinations.Remove(AnyMethod);
}
if (destinations?.Count == 1)
{
// If there is only a single valid HTTP method then use an optimized jump table.
// It avoids unnecessary dictionary lookups with the method name.
var httpMethodDestination = destinations.Single();
var method = httpMethodDestination.Key;
var destination = httpMethodDestination.Value;
var supportsCorsPreflight = false;
var corsPreflightDestination = 0;
if (corsPreflightDestinations?.Count > 0)
{
supportsCorsPreflight = true;
corsPreflightDestination = corsPreflightDestinations.Single().Value;
}
return new HttpMethodSingleEntryPolicyJumpTable(
exitDestination,
method,
destination,
supportsCorsPreflight,
corsPreflightExitDestination,
corsPreflightDestination);
}
else
{
return new HttpMethodDictionaryPolicyJumpTable(
exitDestination,
destinations,
corsPreflightExitDestination,
corsPreflightDestinations);
}
}
private static Endpoint CreateRejectionEndpoint(IEnumerable<string> httpMethods)
{
var allow = string.Join(", ", httpMethods);
return new Endpoint(
(context) =>
{
context.Response.StatusCode = 405;
// Prevent ArgumentException from duplicate key if header already added, such as when the
// request is re-executed by an error handler (see https://github.com/dotnet/aspnetcore/issues/6415)
context.Response.Headers.Allow = allow;
return Task.CompletedTask;
},
EndpointMetadataCollection.Empty,
Http405EndpointDisplayName);
}
private static bool ContainsHttpMethod(List<string> httpMethods, string httpMethod)
{
var methods = CollectionsMarshal.AsSpan(httpMethods);
for (var i = 0; i < methods.Length; i++)
{
// This is a fast path for when everything is using static HttpMethods instances.
if (object.ReferenceEquals(methods[i], httpMethod))
{
return true;
}
}
for (var i = 0; i < methods.Length; i++)
{
if (HttpMethods.Equals(methods[i], httpMethod))
{
return true;
}
}
return false;
}
internal static bool IsCorsPreflightRequest(HttpContext httpContext, string httpMethod, out StringValues accessControlRequestMethod)
{
accessControlRequestMethod = default;
var headers = httpContext.Request.Headers;
return HttpMethods.Equals(httpMethod, PreflightHttpMethod) &&
headers.ContainsKey(HeaderNames.Origin) &&
headers.TryGetValue(HeaderNames.AccessControlRequestMethod, out accessControlRequestMethod) &&
!StringValues.IsNullOrEmpty(accessControlRequestMethod);
}
private class HttpMethodMetadataEndpointComparer : EndpointMetadataComparer<IHttpMethodMetadata>
{
protected override int CompareMetadata(IHttpMethodMetadata? x, IHttpMethodMetadata? y)
{
// Ignore the metadata if it has an empty list of HTTP methods.
return base.CompareMetadata(
x?.HttpMethods.Count > 0 ? x : null,
y?.HttpMethods.Count > 0 ? y : null);
}
}
internal readonly struct EdgeKey : IEquatable<EdgeKey>, IComparable<EdgeKey>, IComparable
{
// Note that in contrast with the metadata, the edge represents a possible state change
// rather than a list of what's allowed. We represent CORS and non-CORS requests as separate
// states.
public readonly bool IsCorsPreflightRequest;
public readonly string HttpMethod;
public EdgeKey(string httpMethod, bool isCorsPreflightRequest)
{
HttpMethod = httpMethod;
IsCorsPreflightRequest = isCorsPreflightRequest;
}
// These are comparable so they can be sorted in tests.
public int CompareTo(EdgeKey other)
{
var compare = string.Compare(HttpMethod, other.HttpMethod, StringComparison.Ordinal);
if (compare != 0)
{
return compare;
}
return IsCorsPreflightRequest.CompareTo(other.IsCorsPreflightRequest);
}
public int CompareTo(object? obj)
{
return CompareTo((EdgeKey)obj!);
}
public bool Equals(EdgeKey other)
{
return
IsCorsPreflightRequest == other.IsCorsPreflightRequest &&
HttpMethods.Equals(HttpMethod, other.HttpMethod);
}
public override bool Equals(object? obj)
{
var other = obj as EdgeKey?;
return other == null ? false : Equals(other.Value);
}
public override int GetHashCode()
{
var hash = new HashCode();
hash.Add(IsCorsPreflightRequest ? 1 : 0);
hash.Add(HttpMethod, StringComparer.Ordinal);
return hash.ToHashCode();
}
// Used in GraphViz output.
public override string ToString()
{
return IsCorsPreflightRequest ? $"CORS: {HttpMethod}" : $"HTTP: {HttpMethod}";
}
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.RecoveryServices.SiteRecovery
{
using Microsoft.Azure;
using Microsoft.Azure.Management;
using Microsoft.Azure.Management.RecoveryServices;
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// ReplicationAlertSettingsOperations operations.
/// </summary>
internal partial class ReplicationAlertSettingsOperations : IServiceOperations<SiteRecoveryManagementClient>, IReplicationAlertSettingsOperations
{
/// <summary>
/// Initializes a new instance of the ReplicationAlertSettingsOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
internal ReplicationAlertSettingsOperations(SiteRecoveryManagementClient client)
{
if (client == null)
{
throw new System.ArgumentNullException("client");
}
Client = client;
}
/// <summary>
/// Gets a reference to the SiteRecoveryManagementClient
/// </summary>
public SiteRecoveryManagementClient Client { get; private set; }
/// <summary>
/// Gets an email notification(alert) configuration.
/// </summary>
/// <remarks>
/// Gets the details of the specified email notification(alert) configuration.
/// </remarks>
/// <param name='alertSettingName'>
/// The name of the email notification configuration.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<Alert>> GetWithHttpMessagesAsync(string alertSettingName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
if (Client.ResourceName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ResourceName");
}
if (Client.ResourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ResourceGroupName");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
if (alertSettingName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "alertSettingName");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("alertSettingName", alertSettingName);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{resourceName}/replicationAlertSettings/{alertSettingName}").ToString();
_url = _url.Replace("{resourceName}", System.Uri.EscapeDataString(Client.ResourceName));
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(Client.ResourceGroupName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
_url = _url.Replace("{alertSettingName}", System.Uri.EscapeDataString(alertSettingName));
List<string> _queryParameters = new List<string>();
if (Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<Alert>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Alert>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Configures email notifications for this vault.
/// </summary>
/// <remarks>
/// Create or update an email notification(alert) configuration.
/// </remarks>
/// <param name='alertSettingName'>
/// The name of the email notification(alert) configuration.
/// </param>
/// <param name='request'>
/// The input to configure the email notification(alert).
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<Alert>> CreateWithHttpMessagesAsync(string alertSettingName, ConfigureAlertRequest request, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
if (Client.ResourceName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ResourceName");
}
if (Client.ResourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ResourceGroupName");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
if (alertSettingName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "alertSettingName");
}
if (request == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "request");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("alertSettingName", alertSettingName);
tracingParameters.Add("request", request);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "Create", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{resourceName}/replicationAlertSettings/{alertSettingName}").ToString();
_url = _url.Replace("{resourceName}", System.Uri.EscapeDataString(Client.ResourceName));
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(Client.ResourceGroupName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
_url = _url.Replace("{alertSettingName}", System.Uri.EscapeDataString(alertSettingName));
List<string> _queryParameters = new List<string>();
if (Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("PUT");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
if(request != null)
{
_requestContent = Rest.Serialization.SafeJsonConvert.SerializeObject(request, Client.SerializationSettings);
_httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8);
_httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
}
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<Alert>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Alert>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Gets the list of configured email notification(alert) configurations.
/// </summary>
/// <remarks>
/// Gets the list of email notification(alert) configurations for the vault.
/// </remarks>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IPage<Alert>>> ListWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
if (Client.ResourceName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ResourceName");
}
if (Client.ResourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ResourceGroupName");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "List", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{resourceName}/replicationAlertSettings").ToString();
_url = _url.Replace("{resourceName}", System.Uri.EscapeDataString(Client.ResourceName));
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(Client.ResourceGroupName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IPage<Alert>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<Alert>>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Gets the list of configured email notification(alert) configurations.
/// </summary>
/// <remarks>
/// Gets the list of email notification(alert) configurations for the vault.
/// </remarks>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IPage<Alert>>> ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (nextPageLink == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("nextPageLink", nextPageLink);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "ListNext", tracingParameters);
}
// Construct URL
string _url = "{nextLink}";
_url = _url.Replace("{nextLink}", nextPageLink);
List<string> _queryParameters = new List<string>();
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IPage<Alert>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<Alert>>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
| |
/*
* Copyright (c) 2015, InWorldz Halcyon Developers
* 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 halcyon nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using net.openstack.Providers.Rackspace;
using net.openstack.Core.Domain;
using System.IO;
using OpenMetaverse;
using JSIStudios.SimpleRESTServices.Client;
using net.openstack.Core.Exceptions.Response;
using OpenSim.Framework;
using log4net;
using System.Reflection;
namespace InWorldz.Data.Assets.Stratus
{
/// <summary>
/// This class does the actual setup work for the cloudfiles client. These objects are pooled
/// and used by the worker threads.
/// </summary>
internal class CloudFilesAssetWorker
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
/// <summary>
/// How many hex characters to use for the CF container prefix
/// </summary>
const int CONTAINER_UUID_PREFIX_LEN = 4;
private CoreExt.ExtendedCloudFilesProvider _provider;
public const int DEFAULT_READ_TIMEOUT = 45 * 1000;
public const int DEFAULT_WRITE_TIMEOUT = 10 * 1000;
public CloudFilesAssetWorker() : this(DEFAULT_READ_TIMEOUT, DEFAULT_WRITE_TIMEOUT)
{
}
public CloudFilesAssetWorker(int readTimeout, int writeTimeout)
{
CloudIdentity identity = new CloudIdentity { Username = Config.Settings.Instance.CFUsername, APIKey = Config.Settings.Instance.CFApiKey };
IRestService restService = new CoreExt.ExtendedJsonRestServices(readTimeout, writeTimeout);
_provider = new CoreExt.ExtendedCloudFilesProvider(identity, Config.Settings.Instance.CFDefaultRegion, null, restService);
//warm up
_provider.GetAccountHeaders(useInternalUrl: Config.Settings.Instance.CFUseInternalURL, region: Config.Settings.Instance.CFDefaultRegion);
}
/// <summary>
/// Calls into the cloud files provider to grab an object and returns a memory stream containing
/// </summary>
/// <param name="assetId"></param>
/// <returns></returns>
public MemoryStream GetAsset(UUID assetId)
{
string assetIdStr = assetId.ToString();
MemoryStream memStream = new MemoryStream();
try
{
this.WarnIfLongOperation("GetObject",
() => _provider.GetObject(GenerateContainerName(assetIdStr), GenerateAssetObjectName(assetIdStr),
memStream, useInternalUrl: Config.Settings.Instance.CFUseInternalURL, region: Config.Settings.Instance.CFDefaultRegion));
return memStream;
}
catch
{
memStream.Dispose();
throw;
}
}
/// <summary>
/// CF containers are PREFIX_#### where we use the first N chars of the hex representation
/// of the asset ID to partition the space. The hex alpha chars in the container name are uppercase
/// </summary>
/// <param name="assetId"></param>
/// <returns></returns>
private static string GenerateContainerName(string assetId)
{
return Config.Settings.Instance.CFContainerPrefix + assetId.Substring(0, CONTAINER_UUID_PREFIX_LEN).ToUpper();
}
/// <summary>
/// The object name is defined by the assetId, dashes stripped, with the .asset prefix
/// </summary>
/// <param name="assetId"></param>
/// <returns></returns>
private static string GenerateAssetObjectName(string assetId)
{
return assetId.Replace("-", String.Empty).ToLower() + ".asset";
}
private void WarnIfLongOperation(string opName, Action operation)
{
const ulong WARNING_TIME = 5000;
ulong startTime = Util.GetLongTickCount();
operation();
ulong time = Util.GetLongTickCount() - startTime;
if (time >= WARNING_TIME)
{
m_log.WarnFormat("[InWorldz.Stratus]: Slow CF operation {0} took {1} ms", opName, time);
}
}
internal MemoryStream StoreAsset(StratusAsset asset)
{
MemoryStream stream = new MemoryStream();
try
{
ProtoBuf.Serializer.Serialize<StratusAsset>(stream, asset);
stream.Position = 0;
string assetIdStr = asset.Id.ToString();
Dictionary<string, string> mheaders = this.GenerateStorageHeaders(asset, stream);
this.WarnIfLongOperation("CreateObject",
() => _provider.CreateObject(GenerateContainerName(assetIdStr), stream, GenerateAssetObjectName(assetIdStr),
"application/octet-stream", headers: mheaders, useInternalUrl: Config.Settings.Instance.CFUseInternalURL,
region: Config.Settings.Instance.CFDefaultRegion)
);
stream.Position = 0;
return stream;
}
catch (ResponseException e)
{
stream.Dispose();
if (e.Response.StatusCode == System.Net.HttpStatusCode.PreconditionFailed)
{
throw new AssetAlreadyExistsException(String.Format("Asset {0} already exists and can not be overwritten", asset.Id));
}
else
{
throw;
}
}
catch
{
stream.Dispose();
throw;
}
}
private Dictionary<string, string> GenerateStorageHeaders(StratusAsset asset, MemoryStream stream)
{
//the HTTP headers only accept letters and digits
StringBuilder fixedName = new StringBuilder();
bool appended = false;
foreach (char letter in asset.Name)
{
char c = (char) (0x000000ff & (uint) letter);
if (c == 127 || (c < ' ' && c != '\t'))
{
continue;
}
else
{
fixedName.Append(letter);
appended = true;
}
}
if (!appended) fixedName.Append("empty");
Dictionary<string, string> headers = new Dictionary<string, string>
{
{"ETag", OpenSim.Framework.Util.Md5Hash(stream)},
{"X-Object-Meta-Temp", asset.Temporary ? "1" : "0"},
{"X-Object-Meta-Local", asset.Local ? "1" : "0"},
{"X-Object-Meta-Type", asset.Type.ToString()},
{"X-Object-Meta-Name", fixedName.ToString()}
};
if (!Config.Settings.Instance.EnableCFOverwrite)
{
headers.Add("If-None-Match", "*");
}
stream.Position = 0;
return headers;
}
internal Dictionary<string, string> GetAssetMetadata(UUID assetId)
{
string assetIdStr = assetId.ToString();
return _provider.GetObjectMetaData(GenerateContainerName(assetIdStr), GenerateAssetObjectName(assetIdStr),
useInternalUrl: Config.Settings.Instance.CFUseInternalURL, region: Config.Settings.Instance.CFDefaultRegion);
}
internal void PurgeAsset(UUID assetID)
{
string assetIdStr = assetID.ToString();
this.WarnIfLongOperation("DeleteObject",
()=> _provider.DeleteObject(GenerateContainerName(assetIdStr), GenerateAssetObjectName(assetIdStr),
useInternalUrl: Config.Settings.Instance.CFUseInternalURL, region: Config.Settings.Instance.CFDefaultRegion));
}
}
}
| |
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gax = Google.Api.Gax;
using gctv = Google.Cloud.Talent.V4Beta1;
using sys = System;
namespace Google.Cloud.Talent.V4Beta1
{
/// <summary>Resource name for the <c>Application</c> resource.</summary>
public sealed partial class ApplicationName : gax::IResourceName, sys::IEquatable<ApplicationName>
{
/// <summary>The possible contents of <see cref="ApplicationName"/>.</summary>
public enum ResourceNameType
{
/// <summary>An unparsed resource name.</summary>
Unparsed = 0,
/// <summary>
/// A resource name with pattern
/// <c>projects/{project}/tenants/{tenant}/profiles/{profile}/applications/{application}</c>.
/// </summary>
ProjectTenantProfileApplication = 1,
}
private static gax::PathTemplate s_projectTenantProfileApplication = new gax::PathTemplate("projects/{project}/tenants/{tenant}/profiles/{profile}/applications/{application}");
/// <summary>Creates a <see cref="ApplicationName"/> containing an unparsed resource name.</summary>
/// <param name="unparsedResourceName">The unparsed resource name. Must not be <c>null</c>.</param>
/// <returns>
/// A new instance of <see cref="ApplicationName"/> containing the provided
/// <paramref name="unparsedResourceName"/>.
/// </returns>
public static ApplicationName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) =>
new ApplicationName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName)));
/// <summary>
/// Creates a <see cref="ApplicationName"/> with the pattern
/// <c>projects/{project}/tenants/{tenant}/profiles/{profile}/applications/{application}</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="tenantId">The <c>Tenant</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="profileId">The <c>Profile</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="applicationId">The <c>Application</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>A new instance of <see cref="ApplicationName"/> constructed from the provided ids.</returns>
public static ApplicationName FromProjectTenantProfileApplication(string projectId, string tenantId, string profileId, string applicationId) =>
new ApplicationName(ResourceNameType.ProjectTenantProfileApplication, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), tenantId: gax::GaxPreconditions.CheckNotNullOrEmpty(tenantId, nameof(tenantId)), profileId: gax::GaxPreconditions.CheckNotNullOrEmpty(profileId, nameof(profileId)), applicationId: gax::GaxPreconditions.CheckNotNullOrEmpty(applicationId, nameof(applicationId)));
/// <summary>
/// Formats the IDs into the string representation of this <see cref="ApplicationName"/> with pattern
/// <c>projects/{project}/tenants/{tenant}/profiles/{profile}/applications/{application}</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="tenantId">The <c>Tenant</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="profileId">The <c>Profile</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="applicationId">The <c>Application</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="ApplicationName"/> with pattern
/// <c>projects/{project}/tenants/{tenant}/profiles/{profile}/applications/{application}</c>.
/// </returns>
public static string Format(string projectId, string tenantId, string profileId, string applicationId) =>
FormatProjectTenantProfileApplication(projectId, tenantId, profileId, applicationId);
/// <summary>
/// Formats the IDs into the string representation of this <see cref="ApplicationName"/> with pattern
/// <c>projects/{project}/tenants/{tenant}/profiles/{profile}/applications/{application}</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="tenantId">The <c>Tenant</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="profileId">The <c>Profile</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="applicationId">The <c>Application</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="ApplicationName"/> with pattern
/// <c>projects/{project}/tenants/{tenant}/profiles/{profile}/applications/{application}</c>.
/// </returns>
public static string FormatProjectTenantProfileApplication(string projectId, string tenantId, string profileId, string applicationId) =>
s_projectTenantProfileApplication.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), gax::GaxPreconditions.CheckNotNullOrEmpty(tenantId, nameof(tenantId)), gax::GaxPreconditions.CheckNotNullOrEmpty(profileId, nameof(profileId)), gax::GaxPreconditions.CheckNotNullOrEmpty(applicationId, nameof(applicationId)));
/// <summary>Parses the given resource name string into a new <see cref="ApplicationName"/> instance.</summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description>
/// <c>projects/{project}/tenants/{tenant}/profiles/{profile}/applications/{application}</c>
/// </description>
/// </item>
/// </list>
/// </remarks>
/// <param name="applicationName">The resource name in string form. Must not be <c>null</c>.</param>
/// <returns>The parsed <see cref="ApplicationName"/> if successful.</returns>
public static ApplicationName Parse(string applicationName) => Parse(applicationName, false);
/// <summary>
/// Parses the given resource name string into a new <see cref="ApplicationName"/> instance; optionally allowing
/// an unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description>
/// <c>projects/{project}/tenants/{tenant}/profiles/{profile}/applications/{application}</c>
/// </description>
/// </item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="applicationName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <returns>The parsed <see cref="ApplicationName"/> if successful.</returns>
public static ApplicationName Parse(string applicationName, bool allowUnparsed) =>
TryParse(applicationName, allowUnparsed, out ApplicationName result) ? result : throw new sys::ArgumentException("The given resource-name matches no pattern.");
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="ApplicationName"/> instance.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description>
/// <c>projects/{project}/tenants/{tenant}/profiles/{profile}/applications/{application}</c>
/// </description>
/// </item>
/// </list>
/// </remarks>
/// <param name="applicationName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="result">
/// When this method returns, the parsed <see cref="ApplicationName"/>, or <c>null</c> if parsing failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string applicationName, out ApplicationName result) =>
TryParse(applicationName, false, out result);
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="ApplicationName"/> instance; optionally
/// allowing an unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description>
/// <c>projects/{project}/tenants/{tenant}/profiles/{profile}/applications/{application}</c>
/// </description>
/// </item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="applicationName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <param name="result">
/// When this method returns, the parsed <see cref="ApplicationName"/>, or <c>null</c> if parsing failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string applicationName, bool allowUnparsed, out ApplicationName result)
{
gax::GaxPreconditions.CheckNotNull(applicationName, nameof(applicationName));
gax::TemplatedResourceName resourceName;
if (s_projectTenantProfileApplication.TryParseName(applicationName, out resourceName))
{
result = FromProjectTenantProfileApplication(resourceName[0], resourceName[1], resourceName[2], resourceName[3]);
return true;
}
if (allowUnparsed)
{
if (gax::UnparsedResourceName.TryParse(applicationName, out gax::UnparsedResourceName unparsedResourceName))
{
result = FromUnparsed(unparsedResourceName);
return true;
}
}
result = null;
return false;
}
private ApplicationName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string applicationId = null, string profileId = null, string projectId = null, string tenantId = null)
{
Type = type;
UnparsedResource = unparsedResourceName;
ApplicationId = applicationId;
ProfileId = profileId;
ProjectId = projectId;
TenantId = tenantId;
}
/// <summary>
/// Constructs a new instance of a <see cref="ApplicationName"/> class from the component parts of pattern
/// <c>projects/{project}/tenants/{tenant}/profiles/{profile}/applications/{application}</c>
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="tenantId">The <c>Tenant</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="profileId">The <c>Profile</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="applicationId">The <c>Application</c> ID. Must not be <c>null</c> or empty.</param>
public ApplicationName(string projectId, string tenantId, string profileId, string applicationId) : this(ResourceNameType.ProjectTenantProfileApplication, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), tenantId: gax::GaxPreconditions.CheckNotNullOrEmpty(tenantId, nameof(tenantId)), profileId: gax::GaxPreconditions.CheckNotNullOrEmpty(profileId, nameof(profileId)), applicationId: gax::GaxPreconditions.CheckNotNullOrEmpty(applicationId, nameof(applicationId)))
{
}
/// <summary>The <see cref="ResourceNameType"/> of the contained resource name.</summary>
public ResourceNameType Type { get; }
/// <summary>
/// The contained <see cref="gax::UnparsedResourceName"/>. Only non-<c>null</c> if this instance contains an
/// unparsed resource name.
/// </summary>
public gax::UnparsedResourceName UnparsedResource { get; }
/// <summary>
/// The <c>Application</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string ApplicationId { get; }
/// <summary>
/// The <c>Profile</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string ProfileId { get; }
/// <summary>
/// The <c>Project</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string ProjectId { get; }
/// <summary>
/// The <c>Tenant</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string TenantId { get; }
/// <summary>Whether this instance contains a resource name with a known pattern.</summary>
public bool IsKnownPattern => Type != ResourceNameType.Unparsed;
/// <summary>The string representation of the resource name.</summary>
/// <returns>The string representation of the resource name.</returns>
public override string ToString()
{
switch (Type)
{
case ResourceNameType.Unparsed: return UnparsedResource.ToString();
case ResourceNameType.ProjectTenantProfileApplication: return s_projectTenantProfileApplication.Expand(ProjectId, TenantId, ProfileId, ApplicationId);
default: throw new sys::InvalidOperationException("Unrecognized resource-type.");
}
}
/// <summary>Returns a hash code for this resource name.</summary>
public override int GetHashCode() => ToString().GetHashCode();
/// <inheritdoc/>
public override bool Equals(object obj) => Equals(obj as ApplicationName);
/// <inheritdoc/>
public bool Equals(ApplicationName other) => ToString() == other?.ToString();
/// <inheritdoc/>
public static bool operator ==(ApplicationName a, ApplicationName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false);
/// <inheritdoc/>
public static bool operator !=(ApplicationName a, ApplicationName b) => !(a == b);
}
public partial class Application
{
/// <summary>
/// <see cref="gctv::ApplicationName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gctv::ApplicationName ApplicationName
{
get => string.IsNullOrEmpty(Name) ? null : gctv::ApplicationName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
/// <summary><see cref="JobName"/>-typed view over the <see cref="Job"/> resource name property.</summary>
public JobName JobAsJobName
{
get => string.IsNullOrEmpty(Job) ? null : JobName.Parse(Job, allowUnparsed: true);
set => Job = value?.ToString() ?? "";
}
/// <summary>
/// <see cref="CompanyName"/>-typed view over the <see cref="Company"/> resource name property.
/// </summary>
public CompanyName CompanyAsCompanyName
{
get => string.IsNullOrEmpty(Company) ? null : CompanyName.Parse(Company, allowUnparsed: true);
set => Company = value?.ToString() ?? "";
}
}
}
| |
/*
* Copyright (c) Citrix Systems, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1) Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2) Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Globalization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
namespace XenAPI
{
/// <summary>
/// LVHD SR specific operations
/// First published in XenServer 7.0.
/// </summary>
public partial class LVHD : XenObject<LVHD>
{
public LVHD()
{
}
public LVHD(string uuid)
{
this.uuid = uuid;
}
/// <summary>
/// Creates a new LVHD from a Proxy_LVHD.
/// </summary>
/// <param name="proxy"></param>
public LVHD(Proxy_LVHD proxy)
{
this.UpdateFromProxy(proxy);
}
/// <summary>
/// Updates each field of this instance with the value of
/// the corresponding field of a given LVHD.
/// </summary>
public override void UpdateFrom(LVHD update)
{
uuid = update.uuid;
}
internal void UpdateFromProxy(Proxy_LVHD proxy)
{
uuid = proxy.uuid == null ? null : (string)proxy.uuid;
}
public Proxy_LVHD ToProxy()
{
Proxy_LVHD result_ = new Proxy_LVHD();
result_.uuid = uuid ?? "";
return result_;
}
/// <summary>
/// Creates a new LVHD from a Hashtable.
/// Note that the fields not contained in the Hashtable
/// will be created with their default values.
/// </summary>
/// <param name="table"></param>
public LVHD(Hashtable table) : this()
{
UpdateFrom(table);
}
/// <summary>
/// Given a Hashtable with field-value pairs, it updates the fields of this LVHD
/// with the values listed in the Hashtable. Note that only the fields contained
/// in the Hashtable will be updated and the rest will remain the same.
/// </summary>
/// <param name="table"></param>
public void UpdateFrom(Hashtable table)
{
if (table.ContainsKey("uuid"))
uuid = Marshalling.ParseString(table, "uuid");
}
public bool DeepEquals(LVHD other)
{
if (ReferenceEquals(null, other))
return false;
if (ReferenceEquals(this, other))
return true;
return Helper.AreEqual2(this._uuid, other._uuid);
}
internal static List<LVHD> ProxyArrayToObjectList(Proxy_LVHD[] input)
{
var result = new List<LVHD>();
foreach (var item in input)
result.Add(new LVHD(item));
return result;
}
public override string SaveChanges(Session session, string opaqueRef, LVHD server)
{
if (opaqueRef == null)
{
System.Diagnostics.Debug.Assert(false, "Cannot create instances of this type on the server");
return "";
}
else
{
throw new InvalidOperationException("This type has no read/write properties");
}
}
/// <summary>
/// Get a record containing the current state of the given LVHD.
/// First published in XenServer 7.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_lvhd">The opaque_ref of the given lvhd</param>
public static LVHD get_record(Session session, string _lvhd)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.lvhd_get_record(session.opaque_ref, _lvhd);
else
return new LVHD((Proxy_LVHD)session.proxy.lvhd_get_record(session.opaque_ref, _lvhd ?? "").parse());
}
/// <summary>
/// Get a reference to the LVHD instance with the specified UUID.
/// First published in XenServer 7.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_uuid">UUID of object to return</param>
public static XenRef<LVHD> get_by_uuid(Session session, string _uuid)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.lvhd_get_by_uuid(session.opaque_ref, _uuid);
else
return XenRef<LVHD>.Create(session.proxy.lvhd_get_by_uuid(session.opaque_ref, _uuid ?? "").parse());
}
/// <summary>
/// Get the uuid field of the given LVHD.
/// First published in XenServer 7.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_lvhd">The opaque_ref of the given lvhd</param>
public static string get_uuid(Session session, string _lvhd)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.lvhd_get_uuid(session.opaque_ref, _lvhd);
else
return (string)session.proxy.lvhd_get_uuid(session.opaque_ref, _lvhd ?? "").parse();
}
/// <summary>
/// Upgrades an LVHD SR to enable thin-provisioning. Future VDIs created in this SR will be thinly-provisioned, although existing VDIs will be left alone. Note that the SR must be attached to the SRmaster for upgrade to work.
/// First published in XenServer 7.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host">The LVHD Host to upgrade to being thin-provisioned.</param>
/// <param name="_sr">The LVHD SR to upgrade to being thin-provisioned.</param>
/// <param name="_initial_allocation">The initial amount of space to allocate to a newly-created VDI in bytes</param>
/// <param name="_allocation_quantum">The amount of space to allocate to a VDI when it needs to be enlarged in bytes</param>
public static string enable_thin_provisioning(Session session, string _host, string _sr, long _initial_allocation, long _allocation_quantum)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.lvhd_enable_thin_provisioning(session.opaque_ref, _host, _sr, _initial_allocation, _allocation_quantum);
else
return (string)session.proxy.lvhd_enable_thin_provisioning(session.opaque_ref, _host ?? "", _sr ?? "", _initial_allocation.ToString(), _allocation_quantum.ToString()).parse();
}
/// <summary>
/// Upgrades an LVHD SR to enable thin-provisioning. Future VDIs created in this SR will be thinly-provisioned, although existing VDIs will be left alone. Note that the SR must be attached to the SRmaster for upgrade to work.
/// First published in XenServer 7.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_host">The LVHD Host to upgrade to being thin-provisioned.</param>
/// <param name="_sr">The LVHD SR to upgrade to being thin-provisioned.</param>
/// <param name="_initial_allocation">The initial amount of space to allocate to a newly-created VDI in bytes</param>
/// <param name="_allocation_quantum">The amount of space to allocate to a VDI when it needs to be enlarged in bytes</param>
public static XenRef<Task> async_enable_thin_provisioning(Session session, string _host, string _sr, long _initial_allocation, long _allocation_quantum)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.async_lvhd_enable_thin_provisioning(session.opaque_ref, _host, _sr, _initial_allocation, _allocation_quantum);
else
return XenRef<Task>.Create(session.proxy.async_lvhd_enable_thin_provisioning(session.opaque_ref, _host ?? "", _sr ?? "", _initial_allocation.ToString(), _allocation_quantum.ToString()).parse());
}
/// <summary>
/// Unique identifier/object reference
/// </summary>
public virtual string uuid
{
get { return _uuid; }
set
{
if (!Helper.AreEqual(value, _uuid))
{
_uuid = value;
Changed = true;
NotifyPropertyChanged("uuid");
}
}
}
private string _uuid = "";
}
}
| |
/*
* 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.Runtime.Remoting.Lifetime;
using System.Threading;
using System.Reflection;
using System.Collections;
using System.Collections.Generic;
using OpenSim.Region.ScriptEngine.Interfaces;
using OpenSim.Region.ScriptEngine.Shared.Api.Interfaces;
using LSL_Float = OpenSim.Region.ScriptEngine.Shared.LSL_Types.LSLFloat;
using LSL_Integer = OpenSim.Region.ScriptEngine.Shared.LSL_Types.LSLInteger;
using LSL_Key = OpenSim.Region.ScriptEngine.Shared.LSL_Types.LSLString;
using LSL_List = OpenSim.Region.ScriptEngine.Shared.LSL_Types.list;
using LSL_Rotation = OpenSim.Region.ScriptEngine.Shared.LSL_Types.Quaternion;
using LSL_String = OpenSim.Region.ScriptEngine.Shared.LSL_Types.LSLString;
using LSL_Vector = OpenSim.Region.ScriptEngine.Shared.LSL_Types.Vector3;
namespace OpenSim.Region.ScriptEngine.Shared.ScriptBase
{
public partial class ScriptBaseClass : MarshalByRefObject
{
public ILSL_Api m_LSL_Functions;
public void ApiTypeLSL(IScriptApi api)
{
if (!(api is ILSL_Api))
return;
m_LSL_Functions = (ILSL_Api)api;
}
public void state(string newState)
{
m_LSL_Functions.state(newState);
}
//
// Script functions
//
public LSL_Integer llAbs(int i)
{
return m_LSL_Functions.llAbs(i);
}
public LSL_Float llAcos(double val)
{
return m_LSL_Functions.llAcos(val);
}
public void llAddToLandBanList(string avatar, double hours)
{
m_LSL_Functions.llAddToLandBanList(avatar, hours);
}
public void llAddToLandPassList(string avatar, double hours)
{
m_LSL_Functions.llAddToLandPassList(avatar, hours);
}
public void llAdjustSoundVolume(double volume)
{
m_LSL_Functions.llAdjustSoundVolume(volume);
}
public void llAllowInventoryDrop(int add)
{
m_LSL_Functions.llAllowInventoryDrop(add);
}
public LSL_Float llAngleBetween(LSL_Rotation a, LSL_Rotation b)
{
return m_LSL_Functions.llAngleBetween(a, b);
}
public void llApplyImpulse(LSL_Vector force, int local)
{
m_LSL_Functions.llApplyImpulse(force, local);
}
public void llApplyRotationalImpulse(LSL_Vector force, int local)
{
m_LSL_Functions.llApplyRotationalImpulse(force, local);
}
public LSL_Float llAsin(double val)
{
return m_LSL_Functions.llAsin(val);
}
public LSL_Float llAtan2(double x, double y)
{
return m_LSL_Functions.llAtan2(x, y);
}
public void llAttachToAvatar(int attachment)
{
m_LSL_Functions.llAttachToAvatar(attachment);
}
public LSL_Key llAvatarOnSitTarget()
{
return m_LSL_Functions.llAvatarOnSitTarget();
}
public LSL_Rotation llAxes2Rot(LSL_Vector fwd, LSL_Vector left, LSL_Vector up)
{
return m_LSL_Functions.llAxes2Rot(fwd, left, up);
}
public LSL_Rotation llAxisAngle2Rot(LSL_Vector axis, double angle)
{
return m_LSL_Functions.llAxisAngle2Rot(axis, angle);
}
public LSL_Integer llBase64ToInteger(string str)
{
return m_LSL_Functions.llBase64ToInteger(str);
}
public LSL_String llBase64ToString(string str)
{
return m_LSL_Functions.llBase64ToString(str);
}
public void llBreakAllLinks()
{
m_LSL_Functions.llBreakAllLinks();
}
public void llBreakLink(int linknum)
{
m_LSL_Functions.llBreakLink(linknum);
}
public LSL_Integer llCeil(double f)
{
return m_LSL_Functions.llCeil(f);
}
public void llClearCameraParams()
{
m_LSL_Functions.llClearCameraParams();
}
public void llCloseRemoteDataChannel(string channel)
{
m_LSL_Functions.llCloseRemoteDataChannel(channel);
}
public LSL_Float llCloud(LSL_Vector offset)
{
return m_LSL_Functions.llCloud(offset);
}
public void llCollisionFilter(string name, string id, int accept)
{
m_LSL_Functions.llCollisionFilter(name, id, accept);
}
public void llCollisionSound(string impact_sound, double impact_volume)
{
m_LSL_Functions.llCollisionSound(impact_sound, impact_volume);
}
public void llCollisionSprite(string impact_sprite)
{
m_LSL_Functions.llCollisionSprite(impact_sprite);
}
public LSL_Float llCos(double f)
{
return m_LSL_Functions.llCos(f);
}
public void llCreateLink(string target, int parent)
{
m_LSL_Functions.llCreateLink(target, parent);
}
public LSL_List llCSV2List(string src)
{
return m_LSL_Functions.llCSV2List(src);
}
public LSL_List llDeleteSubList(LSL_List src, int start, int end)
{
return m_LSL_Functions.llDeleteSubList(src, start, end);
}
public LSL_String llDeleteSubString(string src, int start, int end)
{
return m_LSL_Functions.llDeleteSubString(src, start, end);
}
public void llDetachFromAvatar()
{
m_LSL_Functions.llDetachFromAvatar();
}
public LSL_Vector llDetectedGrab(int number)
{
return m_LSL_Functions.llDetectedGrab(number);
}
public LSL_Integer llDetectedGroup(int number)
{
return m_LSL_Functions.llDetectedGroup(number);
}
public LSL_Key llDetectedKey(int number)
{
return m_LSL_Functions.llDetectedKey(number);
}
public LSL_Integer llDetectedLinkNumber(int number)
{
return m_LSL_Functions.llDetectedLinkNumber(number);
}
public LSL_String llDetectedName(int number)
{
return m_LSL_Functions.llDetectedName(number);
}
public LSL_Key llDetectedOwner(int number)
{
return m_LSL_Functions.llDetectedOwner(number);
}
public LSL_Vector llDetectedPos(int number)
{
return m_LSL_Functions.llDetectedPos(number);
}
public LSL_Rotation llDetectedRot(int number)
{
return m_LSL_Functions.llDetectedRot(number);
}
public LSL_Integer llDetectedType(int number)
{
return m_LSL_Functions.llDetectedType(number);
}
public LSL_Vector llDetectedTouchBinormal(int index)
{
return m_LSL_Functions.llDetectedTouchBinormal(index);
}
public LSL_Integer llDetectedTouchFace(int index)
{
return m_LSL_Functions.llDetectedTouchFace(index);
}
public LSL_Vector llDetectedTouchNormal(int index)
{
return m_LSL_Functions.llDetectedTouchNormal(index);
}
public LSL_Vector llDetectedTouchPos(int index)
{
return m_LSL_Functions.llDetectedTouchPos(index);
}
public LSL_Vector llDetectedTouchST(int index)
{
return m_LSL_Functions.llDetectedTouchST(index);
}
public LSL_Vector llDetectedTouchUV(int index)
{
return m_LSL_Functions.llDetectedTouchUV(index);
}
public LSL_Vector llDetectedVel(int number)
{
return m_LSL_Functions.llDetectedVel(number);
}
public void llDialog(string avatar, string message, LSL_List buttons, int chat_channel)
{
m_LSL_Functions.llDialog(avatar, message, buttons, chat_channel);
}
public void llDie()
{
m_LSL_Functions.llDie();
}
public LSL_String llDumpList2String(LSL_List src, string seperator)
{
return m_LSL_Functions.llDumpList2String(src, seperator);
}
public LSL_Integer llEdgeOfWorld(LSL_Vector pos, LSL_Vector dir)
{
return m_LSL_Functions.llEdgeOfWorld(pos, dir);
}
public void llEjectFromLand(string pest)
{
m_LSL_Functions.llEjectFromLand(pest);
}
public void llEmail(string address, string subject, string message)
{
m_LSL_Functions.llEmail(address, subject, message);
}
public LSL_String llEscapeURL(string url)
{
return m_LSL_Functions.llEscapeURL(url);
}
public LSL_Rotation llEuler2Rot(LSL_Vector v)
{
return m_LSL_Functions.llEuler2Rot(v);
}
public LSL_Float llFabs(double f)
{
return m_LSL_Functions.llFabs(f);
}
public LSL_Integer llFloor(double f)
{
return m_LSL_Functions.llFloor(f);
}
public void llForceMouselook(int mouselook)
{
m_LSL_Functions.llForceMouselook(mouselook);
}
public LSL_Float llFrand(double mag)
{
return m_LSL_Functions.llFrand(mag);
}
public LSL_Vector llGetAccel()
{
return m_LSL_Functions.llGetAccel();
}
public LSL_Integer llGetAgentInfo(string id)
{
return m_LSL_Functions.llGetAgentInfo(id);
}
public LSL_String llGetAgentLanguage(string id)
{
return m_LSL_Functions.llGetAgentLanguage(id);
}
public LSL_Vector llGetAgentSize(string id)
{
return m_LSL_Functions.llGetAgentSize(id);
}
public LSL_Float llGetAlpha(int face)
{
return m_LSL_Functions.llGetAlpha(face);
}
public LSL_Float llGetAndResetTime()
{
return m_LSL_Functions.llGetAndResetTime();
}
public LSL_String llGetAnimation(string id)
{
return m_LSL_Functions.llGetAnimation(id);
}
public LSL_List llGetAnimationList(string id)
{
return m_LSL_Functions.llGetAnimationList(id);
}
public LSL_Integer llGetAttached()
{
return m_LSL_Functions.llGetAttached();
}
public LSL_List llGetBoundingBox(string obj)
{
return m_LSL_Functions.llGetBoundingBox(obj);
}
public LSL_Vector llGetCameraPos()
{
return m_LSL_Functions.llGetCameraPos();
}
public LSL_Rotation llGetCameraRot()
{
return m_LSL_Functions.llGetCameraRot();
}
public LSL_Vector llGetCenterOfMass()
{
return m_LSL_Functions.llGetCenterOfMass();
}
public LSL_Vector llGetColor(int face)
{
return m_LSL_Functions.llGetColor(face);
}
public LSL_String llGetCreator()
{
return m_LSL_Functions.llGetCreator();
}
public LSL_String llGetDate()
{
return m_LSL_Functions.llGetDate();
}
public LSL_Float llGetEnergy()
{
return m_LSL_Functions.llGetEnergy();
}
public LSL_Vector llGetForce()
{
return m_LSL_Functions.llGetForce();
}
public LSL_Integer llGetFreeMemory()
{
return m_LSL_Functions.llGetFreeMemory();
}
public LSL_Integer llGetFreeURLs()
{
return m_LSL_Functions.llGetFreeURLs();
}
public LSL_Vector llGetGeometricCenter()
{
return m_LSL_Functions.llGetGeometricCenter();
}
public LSL_Float llGetGMTclock()
{
return m_LSL_Functions.llGetGMTclock();
}
public LSL_String llGetHTTPHeader(LSL_Key request_id, string header)
{
return m_LSL_Functions.llGetHTTPHeader(request_id, header);
}
public LSL_Key llGetInventoryCreator(string item)
{
return m_LSL_Functions.llGetInventoryCreator(item);
}
public LSL_Key llGetInventoryKey(string name)
{
return m_LSL_Functions.llGetInventoryKey(name);
}
public LSL_String llGetInventoryName(int type, int number)
{
return m_LSL_Functions.llGetInventoryName(type, number);
}
public LSL_Integer llGetInventoryNumber(int type)
{
return m_LSL_Functions.llGetInventoryNumber(type);
}
public LSL_Integer llGetInventoryPermMask(string item, int mask)
{
return m_LSL_Functions.llGetInventoryPermMask(item, mask);
}
public LSL_Integer llGetInventoryType(string name)
{
return m_LSL_Functions.llGetInventoryType(name);
}
public LSL_Key llGetKey()
{
return m_LSL_Functions.llGetKey();
}
public LSL_Key llGetLandOwnerAt(LSL_Vector pos)
{
return m_LSL_Functions.llGetLandOwnerAt(pos);
}
public LSL_Key llGetLinkKey(int linknum)
{
return m_LSL_Functions.llGetLinkKey(linknum);
}
public LSL_String llGetLinkName(int linknum)
{
return m_LSL_Functions.llGetLinkName(linknum);
}
public LSL_Integer llGetLinkNumber()
{
return m_LSL_Functions.llGetLinkNumber();
}
public LSL_Integer llGetListEntryType(LSL_List src, int index)
{
return m_LSL_Functions.llGetListEntryType(src, index);
}
public LSL_Integer llGetListLength(LSL_List src)
{
return m_LSL_Functions.llGetListLength(src);
}
public LSL_Vector llGetLocalPos()
{
return m_LSL_Functions.llGetLocalPos();
}
public LSL_Rotation llGetLocalRot()
{
return m_LSL_Functions.llGetLocalRot();
}
public LSL_Float llGetMass()
{
return m_LSL_Functions.llGetMass();
}
public void llGetNextEmail(string address, string subject)
{
m_LSL_Functions.llGetNextEmail(address, subject);
}
public LSL_String llGetNotecardLine(string name, int line)
{
return m_LSL_Functions.llGetNotecardLine(name, line);
}
public LSL_Key llGetNumberOfNotecardLines(string name)
{
return m_LSL_Functions.llGetNumberOfNotecardLines(name);
}
public LSL_Integer llGetNumberOfPrims()
{
return m_LSL_Functions.llGetNumberOfPrims();
}
public LSL_Integer llGetNumberOfSides()
{
return m_LSL_Functions.llGetNumberOfSides();
}
public LSL_String llGetObjectDesc()
{
return m_LSL_Functions.llGetObjectDesc();
}
public LSL_List llGetObjectDetails(string id, LSL_List args)
{
return m_LSL_Functions.llGetObjectDetails(id, args);
}
public LSL_Float llGetObjectMass(string id)
{
return m_LSL_Functions.llGetObjectMass(id);
}
public LSL_String llGetObjectName()
{
return m_LSL_Functions.llGetObjectName();
}
public LSL_Integer llGetObjectPermMask(int mask)
{
return m_LSL_Functions.llGetObjectPermMask(mask);
}
public LSL_Integer llGetObjectPrimCount(string object_id)
{
return m_LSL_Functions.llGetObjectPrimCount(object_id);
}
public LSL_Vector llGetOmega()
{
return m_LSL_Functions.llGetOmega();
}
public LSL_Key llGetOwner()
{
return m_LSL_Functions.llGetOwner();
}
public LSL_Key llGetOwnerKey(string id)
{
return m_LSL_Functions.llGetOwnerKey(id);
}
public LSL_List llGetParcelDetails(LSL_Vector pos, LSL_List param)
{
return m_LSL_Functions.llGetParcelDetails(pos, param);
}
public LSL_Integer llGetParcelFlags(LSL_Vector pos)
{
return m_LSL_Functions.llGetParcelFlags(pos);
}
public LSL_Integer llGetParcelMaxPrims(LSL_Vector pos, int sim_wide)
{
return m_LSL_Functions.llGetParcelMaxPrims(pos, sim_wide);
}
public LSL_Integer llGetParcelPrimCount(LSL_Vector pos, int category, int sim_wide)
{
return m_LSL_Functions.llGetParcelPrimCount(pos, category, sim_wide);
}
public LSL_List llGetParcelPrimOwners(LSL_Vector pos)
{
return m_LSL_Functions.llGetParcelPrimOwners(pos);
}
public LSL_Integer llGetPermissions()
{
return m_LSL_Functions.llGetPermissions();
}
public LSL_Key llGetPermissionsKey()
{
return m_LSL_Functions.llGetPermissionsKey();
}
public LSL_Vector llGetPos()
{
return m_LSL_Functions.llGetPos();
}
public LSL_List llGetPrimitiveParams(LSL_List rules)
{
return m_LSL_Functions.llGetPrimitiveParams(rules);
}
public LSL_Integer llGetRegionAgentCount()
{
return m_LSL_Functions.llGetRegionAgentCount();
}
public LSL_Vector llGetRegionCorner()
{
return m_LSL_Functions.llGetRegionCorner();
}
public LSL_Integer llGetRegionFlags()
{
return m_LSL_Functions.llGetRegionFlags();
}
public LSL_Float llGetRegionFPS()
{
return m_LSL_Functions.llGetRegionFPS();
}
public LSL_String llGetRegionName()
{
return m_LSL_Functions.llGetRegionName();
}
public LSL_Float llGetRegionTimeDilation()
{
return m_LSL_Functions.llGetRegionTimeDilation();
}
public LSL_Vector llGetRootPosition()
{
return m_LSL_Functions.llGetRootPosition();
}
public LSL_Rotation llGetRootRotation()
{
return m_LSL_Functions.llGetRootRotation();
}
public LSL_Rotation llGetRot()
{
return m_LSL_Functions.llGetRot();
}
public LSL_Vector llGetScale()
{
return m_LSL_Functions.llGetScale();
}
public LSL_String llGetScriptName()
{
return m_LSL_Functions.llGetScriptName();
}
public LSL_Integer llGetScriptState(string name)
{
return m_LSL_Functions.llGetScriptState(name);
}
public LSL_String llGetSimulatorHostname()
{
return m_LSL_Functions.llGetSimulatorHostname();
}
public LSL_Integer llGetStartParameter()
{
return m_LSL_Functions.llGetStartParameter();
}
public LSL_Integer llGetStatus(int status)
{
return m_LSL_Functions.llGetStatus(status);
}
public LSL_String llGetSubString(string src, int start, int end)
{
return m_LSL_Functions.llGetSubString(src, start, end);
}
public LSL_Vector llGetSunDirection()
{
return m_LSL_Functions.llGetSunDirection();
}
public LSL_String llGetTexture(int face)
{
return m_LSL_Functions.llGetTexture(face);
}
public LSL_Vector llGetTextureOffset(int face)
{
return m_LSL_Functions.llGetTextureOffset(face);
}
public LSL_Float llGetTextureRot(int side)
{
return m_LSL_Functions.llGetTextureRot(side);
}
public LSL_Vector llGetTextureScale(int side)
{
return m_LSL_Functions.llGetTextureScale(side);
}
public LSL_Float llGetTime()
{
return m_LSL_Functions.llGetTime();
}
public LSL_Float llGetTimeOfDay()
{
return m_LSL_Functions.llGetTimeOfDay();
}
public LSL_String llGetTimestamp()
{
return m_LSL_Functions.llGetTimestamp();
}
public LSL_Vector llGetTorque()
{
return m_LSL_Functions.llGetTorque();
}
public LSL_Integer llGetUnixTime()
{
return m_LSL_Functions.llGetUnixTime();
}
public LSL_Vector llGetVel()
{
return m_LSL_Functions.llGetVel();
}
public LSL_Float llGetWallclock()
{
return m_LSL_Functions.llGetWallclock();
}
public void llGiveInventory(string destination, string inventory)
{
m_LSL_Functions.llGiveInventory(destination, inventory);
}
public void llGiveInventoryList(string destination, string category, LSL_List inventory)
{
m_LSL_Functions.llGiveInventoryList(destination, category, inventory);
}
public LSL_Integer llGiveMoney(string destination, int amount)
{
return m_LSL_Functions.llGiveMoney(destination, amount);
}
public void llGodLikeRezObject(string inventory, LSL_Vector pos)
{
m_LSL_Functions.llGodLikeRezObject(inventory, pos);
}
public LSL_Float llGround(LSL_Vector offset)
{
return m_LSL_Functions.llGround(offset);
}
public LSL_Vector llGroundContour(LSL_Vector offset)
{
return m_LSL_Functions.llGroundContour(offset);
}
public LSL_Vector llGroundNormal(LSL_Vector offset)
{
return m_LSL_Functions.llGroundNormal(offset);
}
public void llGroundRepel(double height, int water, double tau)
{
m_LSL_Functions.llGroundRepel(height, water, tau);
}
public LSL_Vector llGroundSlope(LSL_Vector offset)
{
return m_LSL_Functions.llGroundSlope(offset);
}
public LSL_String llHTTPRequest(string url, LSL_List parameters, string body)
{
return m_LSL_Functions.llHTTPRequest(url, parameters, body);
}
public void llHTTPResponse(LSL_Key id, int status, string body)
{
m_LSL_Functions.llHTTPResponse(id, status, body);
}
public LSL_String llInsertString(string dst, int position, string src)
{
return m_LSL_Functions.llInsertString(dst, position, src);
}
public void llInstantMessage(string user, string message)
{
m_LSL_Functions.llInstantMessage(user, message);
}
public LSL_String llIntegerToBase64(int number)
{
return m_LSL_Functions.llIntegerToBase64(number);
}
public LSL_String llKey2Name(string id)
{
return m_LSL_Functions.llKey2Name(id);
}
public LSL_String llList2CSV(LSL_List src)
{
return m_LSL_Functions.llList2CSV(src);
}
public LSL_Float llList2Float(LSL_List src, int index)
{
return m_LSL_Functions.llList2Float(src, index);
}
public LSL_Integer llList2Integer(LSL_List src, int index)
{
return m_LSL_Functions.llList2Integer(src, index);
}
public LSL_Key llList2Key(LSL_List src, int index)
{
return m_LSL_Functions.llList2Key(src, index);
}
public LSL_List llList2List(LSL_List src, int start, int end)
{
return m_LSL_Functions.llList2List(src, start, end);
}
public LSL_List llList2ListStrided(LSL_List src, int start, int end, int stride)
{
return m_LSL_Functions.llList2ListStrided(src, start, end, stride);
}
public LSL_Rotation llList2Rot(LSL_List src, int index)
{
return m_LSL_Functions.llList2Rot(src, index);
}
public LSL_String llList2String(LSL_List src, int index)
{
return m_LSL_Functions.llList2String(src, index);
}
public LSL_Vector llList2Vector(LSL_List src, int index)
{
return m_LSL_Functions.llList2Vector(src, index);
}
public LSL_Integer llListen(int channelID, string name, string ID, string msg)
{
return m_LSL_Functions.llListen(channelID, name, ID, msg);
}
public void llListenControl(int number, int active)
{
m_LSL_Functions.llListenControl(number, active);
}
public void llListenRemove(int number)
{
m_LSL_Functions.llListenRemove(number);
}
public LSL_Integer llListFindList(LSL_List src, LSL_List test)
{
return m_LSL_Functions.llListFindList(src, test);
}
public LSL_List llListInsertList(LSL_List dest, LSL_List src, int start)
{
return m_LSL_Functions.llListInsertList(dest, src, start);
}
public LSL_List llListRandomize(LSL_List src, int stride)
{
return m_LSL_Functions.llListRandomize(src, stride);
}
public LSL_List llListReplaceList(LSL_List dest, LSL_List src, int start, int end)
{
return m_LSL_Functions.llListReplaceList(dest, src, start, end);
}
public LSL_List llListSort(LSL_List src, int stride, int ascending)
{
return m_LSL_Functions.llListSort(src, stride, ascending);
}
public LSL_Float llListStatistics(int operation, LSL_List src)
{
return m_LSL_Functions.llListStatistics(operation, src);
}
public void llLoadURL(string avatar_id, string message, string url)
{
m_LSL_Functions.llLoadURL(avatar_id, message, url);
}
public LSL_Float llLog(double val)
{
return m_LSL_Functions.llLog(val);
}
public LSL_Float llLog10(double val)
{
return m_LSL_Functions.llLog10(val);
}
public void llLookAt(LSL_Vector target, double strength, double damping)
{
m_LSL_Functions.llLookAt(target, strength, damping);
}
public void llLoopSound(string sound, double volume)
{
m_LSL_Functions.llLoopSound(sound, volume);
}
public void llLoopSoundMaster(string sound, double volume)
{
m_LSL_Functions.llLoopSoundMaster(sound, volume);
}
public void llLoopSoundSlave(string sound, double volume)
{
m_LSL_Functions.llLoopSoundSlave(sound, volume);
}
public void llMakeExplosion(int particles, double scale, double vel, double lifetime, double arc, string texture, LSL_Vector offset)
{
m_LSL_Functions.llMakeExplosion(particles, scale, vel, lifetime, arc, texture, offset);
}
public void llMakeFire(int particles, double scale, double vel, double lifetime, double arc, string texture, LSL_Vector offset)
{
m_LSL_Functions.llMakeFire(particles, scale, vel, lifetime, arc, texture, offset);
}
public void llMakeFountain(int particles, double scale, double vel, double lifetime, double arc, int bounce, string texture, LSL_Vector offset, double bounce_offset)
{
m_LSL_Functions.llMakeFountain(particles, scale, vel, lifetime, arc, bounce, texture, offset, bounce_offset);
}
public void llMakeSmoke(int particles, double scale, double vel, double lifetime, double arc, string texture, LSL_Vector offset)
{
m_LSL_Functions.llMakeSmoke(particles, scale, vel, lifetime, arc, texture, offset);
}
public void llMapDestination(string simname, LSL_Vector pos, LSL_Vector look_at)
{
m_LSL_Functions.llMapDestination(simname, pos, look_at);
}
public LSL_String llMD5String(string src, int nonce)
{
return m_LSL_Functions.llMD5String(src, nonce);
}
public LSL_String llSHA1String(string src)
{
return m_LSL_Functions.llSHA1String(src);
}
public void llMessageLinked(int linknum, int num, string str, string id)
{
m_LSL_Functions.llMessageLinked(linknum, num, str, id);
}
public void llMinEventDelay(double delay)
{
m_LSL_Functions.llMinEventDelay(delay);
}
public void llModifyLand(int action, int brush)
{
m_LSL_Functions.llModifyLand(action, brush);
}
public LSL_Integer llModPow(int a, int b, int c)
{
return m_LSL_Functions.llModPow(a, b, c);
}
public void llMoveToTarget(LSL_Vector target, double tau)
{
m_LSL_Functions.llMoveToTarget(target, tau);
}
public void llOffsetTexture(double u, double v, int face)
{
m_LSL_Functions.llOffsetTexture(u, v, face);
}
public void llOpenRemoteDataChannel()
{
m_LSL_Functions.llOpenRemoteDataChannel();
}
public LSL_Integer llOverMyLand(string id)
{
return m_LSL_Functions.llOverMyLand(id);
}
public void llOwnerSay(string msg)
{
m_LSL_Functions.llOwnerSay(msg);
}
public void llParcelMediaCommandList(LSL_List commandList)
{
m_LSL_Functions.llParcelMediaCommandList(commandList);
}
public LSL_List llParcelMediaQuery(LSL_List aList)
{
return m_LSL_Functions.llParcelMediaQuery(aList);
}
public LSL_List llParseString2List(string str, LSL_List separators, LSL_List spacers)
{
return m_LSL_Functions.llParseString2List(str, separators, spacers);
}
public LSL_List llParseStringKeepNulls(string src, LSL_List seperators, LSL_List spacers)
{
return m_LSL_Functions.llParseStringKeepNulls(src, seperators, spacers);
}
public void llParticleSystem(LSL_List rules)
{
m_LSL_Functions.llParticleSystem(rules);
}
public void llPassCollisions(int pass)
{
m_LSL_Functions.llPassCollisions(pass);
}
public void llPassTouches(int pass)
{
m_LSL_Functions.llPassTouches(pass);
}
public void llPlaySound(string sound, double volume)
{
m_LSL_Functions.llPlaySound(sound, volume);
}
public void llPlaySoundSlave(string sound, double volume)
{
m_LSL_Functions.llPlaySoundSlave(sound, volume);
}
public void llPointAt(LSL_Vector pos)
{
m_LSL_Functions.llPointAt(pos);
}
public LSL_Float llPow(double fbase, double fexponent)
{
return m_LSL_Functions.llPow(fbase, fexponent);
}
public void llPreloadSound(string sound)
{
m_LSL_Functions.llPreloadSound(sound);
}
public void llPushObject(string target, LSL_Vector impulse, LSL_Vector ang_impulse, int local)
{
m_LSL_Functions.llPushObject(target, impulse, ang_impulse, local);
}
public void llRefreshPrimURL()
{
m_LSL_Functions.llRefreshPrimURL();
}
public void llRegionSay(int channelID, string text)
{
m_LSL_Functions.llRegionSay(channelID, text);
}
public void llReleaseCamera(string avatar)
{
m_LSL_Functions.llReleaseCamera(avatar);
}
public void llReleaseURL(string url)
{
m_LSL_Functions.llReleaseURL(url);
}
public void llReleaseControls()
{
m_LSL_Functions.llReleaseControls();
}
public void llRemoteDataReply(string channel, string message_id, string sdata, int idata)
{
m_LSL_Functions.llRemoteDataReply(channel, message_id, sdata, idata);
}
public void llRemoteDataSetRegion()
{
m_LSL_Functions.llRemoteDataSetRegion();
}
public void llRemoteLoadScript(string target, string name, int running, int start_param)
{
m_LSL_Functions.llRemoteLoadScript(target, name, running, start_param);
}
public void llRemoteLoadScriptPin(string target, string name, int pin, int running, int start_param)
{
m_LSL_Functions.llRemoteLoadScriptPin(target, name, pin, running, start_param);
}
public void llRemoveFromLandBanList(string avatar)
{
m_LSL_Functions.llRemoveFromLandBanList(avatar);
}
public void llRemoveFromLandPassList(string avatar)
{
m_LSL_Functions.llRemoveFromLandPassList(avatar);
}
public void llRemoveInventory(string item)
{
m_LSL_Functions.llRemoveInventory(item);
}
public void llRemoveVehicleFlags(int flags)
{
m_LSL_Functions.llRemoveVehicleFlags(flags);
}
public LSL_Key llRequestAgentData(string id, int data)
{
return m_LSL_Functions.llRequestAgentData(id, data);
}
public LSL_Key llRequestInventoryData(string name)
{
return m_LSL_Functions.llRequestInventoryData(name);
}
public void llRequestPermissions(string agent, int perm)
{
m_LSL_Functions.llRequestPermissions(agent, perm);
}
public LSL_String llRequestSecureURL()
{
return m_LSL_Functions.llRequestSecureURL();
}
public LSL_Key llRequestSimulatorData(string simulator, int data)
{
return m_LSL_Functions.llRequestSimulatorData(simulator, data);
}
public LSL_Key llRequestURL()
{
return m_LSL_Functions.llRequestURL();
}
public void llResetLandBanList()
{
m_LSL_Functions.llResetLandBanList();
}
public void llResetLandPassList()
{
m_LSL_Functions.llResetLandPassList();
}
public void llResetOtherScript(string name)
{
m_LSL_Functions.llResetOtherScript(name);
}
public void llResetScript()
{
m_LSL_Functions.llResetScript();
}
public void llResetTime()
{
m_LSL_Functions.llResetTime();
}
public void llRezAtRoot(string inventory, LSL_Vector position, LSL_Vector velocity, LSL_Rotation rot, int param)
{
m_LSL_Functions.llRezAtRoot(inventory, position, velocity, rot, param);
}
public void llRezObject(string inventory, LSL_Vector pos, LSL_Vector vel, LSL_Rotation rot, int param)
{
m_LSL_Functions.llRezObject(inventory, pos, vel, rot, param);
}
public LSL_Float llRot2Angle(LSL_Rotation rot)
{
return m_LSL_Functions.llRot2Angle(rot);
}
public LSL_Vector llRot2Axis(LSL_Rotation rot)
{
return m_LSL_Functions.llRot2Axis(rot);
}
public LSL_Vector llRot2Euler(LSL_Rotation r)
{
return m_LSL_Functions.llRot2Euler(r);
}
public LSL_Vector llRot2Fwd(LSL_Rotation r)
{
return m_LSL_Functions.llRot2Fwd(r);
}
public LSL_Vector llRot2Left(LSL_Rotation r)
{
return m_LSL_Functions.llRot2Left(r);
}
public LSL_Vector llRot2Up(LSL_Rotation r)
{
return m_LSL_Functions.llRot2Up(r);
}
public void llRotateTexture(double rotation, int face)
{
m_LSL_Functions.llRotateTexture(rotation, face);
}
public LSL_Rotation llRotBetween(LSL_Vector start, LSL_Vector end)
{
return m_LSL_Functions.llRotBetween(start, end);
}
public void llRotLookAt(LSL_Rotation target, double strength, double damping)
{
m_LSL_Functions.llRotLookAt(target, strength, damping);
}
public LSL_Integer llRotTarget(LSL_Rotation rot, double error)
{
return m_LSL_Functions.llRotTarget(rot, error);
}
public void llRotTargetRemove(int number)
{
m_LSL_Functions.llRotTargetRemove(number);
}
public LSL_Integer llRound(double f)
{
return m_LSL_Functions.llRound(f);
}
public LSL_Integer llSameGroup(string agent)
{
return m_LSL_Functions.llSameGroup(agent);
}
public void llSay(int channelID, string text)
{
m_LSL_Functions.llSay(channelID, text);
}
public void llScaleTexture(double u, double v, int face)
{
m_LSL_Functions.llScaleTexture(u, v, face);
}
public LSL_Integer llScriptDanger(LSL_Vector pos)
{
return m_LSL_Functions.llScriptDanger(pos);
}
public LSL_Key llSendRemoteData(string channel, string dest, int idata, string sdata)
{
return m_LSL_Functions.llSendRemoteData(channel, dest, idata, sdata);
}
public void llSensor(string name, string id, int type, double range, double arc)
{
m_LSL_Functions.llSensor(name, id, type, range, arc);
}
public void llSensorRemove()
{
m_LSL_Functions.llSensorRemove();
}
public void llSensorRepeat(string name, string id, int type, double range, double arc, double rate)
{
m_LSL_Functions.llSensorRepeat(name, id, type, range, arc, rate);
}
public void llSetAlpha(double alpha, int face)
{
m_LSL_Functions.llSetAlpha(alpha, face);
}
public void llSetBuoyancy(double buoyancy)
{
m_LSL_Functions.llSetBuoyancy(buoyancy);
}
public void llSetCameraAtOffset(LSL_Vector offset)
{
m_LSL_Functions.llSetCameraAtOffset(offset);
}
public void llSetCameraEyeOffset(LSL_Vector offset)
{
m_LSL_Functions.llSetCameraEyeOffset(offset);
}
public void llSetCameraParams(LSL_List rules)
{
m_LSL_Functions.llSetCameraParams(rules);
}
public void llSetClickAction(int action)
{
m_LSL_Functions.llSetClickAction(action);
}
public void llSetColor(LSL_Vector color, int face)
{
m_LSL_Functions.llSetColor(color, face);
}
public void llSetDamage(double damage)
{
m_LSL_Functions.llSetDamage(damage);
}
public void llSetForce(LSL_Vector force, int local)
{
m_LSL_Functions.llSetForce(force, local);
}
public void llSetForceAndTorque(LSL_Vector force, LSL_Vector torque, int local)
{
m_LSL_Functions.llSetForceAndTorque(force, torque, local);
}
public void llSetHoverHeight(double height, int water, double tau)
{
m_LSL_Functions.llSetHoverHeight(height, water, tau);
}
public void llSetInventoryPermMask(string item, int mask, int value)
{
m_LSL_Functions.llSetInventoryPermMask(item, mask, value);
}
public void llSetLinkAlpha(int linknumber, double alpha, int face)
{
m_LSL_Functions.llSetLinkAlpha(linknumber, alpha, face);
}
public void llSetLinkColor(int linknumber, LSL_Vector color, int face)
{
m_LSL_Functions.llSetLinkColor(linknumber, color, face);
}
public void llSetLinkPrimitiveParams(int linknumber, LSL_List rules)
{
m_LSL_Functions.llSetLinkPrimitiveParams(linknumber, rules);
}
public void llSetLinkTexture(int linknumber, string texture, int face)
{
m_LSL_Functions.llSetLinkTexture(linknumber, texture, face);
}
public void llSetLocalRot(LSL_Rotation rot)
{
m_LSL_Functions.llSetLocalRot(rot);
}
public void llSetObjectDesc(string desc)
{
m_LSL_Functions.llSetObjectDesc(desc);
}
public void llSetObjectName(string name)
{
m_LSL_Functions.llSetObjectName(name);
}
public void llSetObjectPermMask(int mask, int value)
{
m_LSL_Functions.llSetObjectPermMask(mask, value);
}
public void llSetParcelMusicURL(string url)
{
m_LSL_Functions.llSetParcelMusicURL(url);
}
public void llSetPayPrice(int price, LSL_List quick_pay_buttons)
{
m_LSL_Functions.llSetPayPrice(price, quick_pay_buttons);
}
public void llSetPos(LSL_Vector pos)
{
m_LSL_Functions.llSetPos(pos);
}
public void llSetPrimitiveParams(LSL_List rules)
{
m_LSL_Functions.llSetPrimitiveParams(rules);
}
public void llSetPrimURL(string url)
{
m_LSL_Functions.llSetPrimURL(url);
}
public void llSetRemoteScriptAccessPin(int pin)
{
m_LSL_Functions.llSetRemoteScriptAccessPin(pin);
}
public void llSetRot(LSL_Rotation rot)
{
m_LSL_Functions.llSetRot(rot);
}
public void llSetScale(LSL_Vector scale)
{
m_LSL_Functions.llSetScale(scale);
}
public void llSetScriptState(string name, int run)
{
m_LSL_Functions.llSetScriptState(name, run);
}
public void llSetSitText(string text)
{
m_LSL_Functions.llSetSitText(text);
}
public void llSetSoundQueueing(int queue)
{
m_LSL_Functions.llSetSoundQueueing(queue);
}
public void llSetSoundRadius(double radius)
{
m_LSL_Functions.llSetSoundRadius(radius);
}
public void llSetStatus(int status, int value)
{
m_LSL_Functions.llSetStatus(status, value);
}
public void llSetText(string text, LSL_Vector color, double alpha)
{
m_LSL_Functions.llSetText(text, color, alpha);
}
public void llSetTexture(string texture, int face)
{
m_LSL_Functions.llSetTexture(texture, face);
}
public void llSetTextureAnim(int mode, int face, int sizex, int sizey, double start, double length, double rate)
{
m_LSL_Functions.llSetTextureAnim(mode, face, sizex, sizey, start, length, rate);
}
public void llSetTimerEvent(double sec)
{
m_LSL_Functions.llSetTimerEvent(sec);
}
public void llSetTorque(LSL_Vector torque, int local)
{
m_LSL_Functions.llSetTorque(torque, local);
}
public void llSetTouchText(string text)
{
m_LSL_Functions.llSetTouchText(text);
}
public void llSetVehicleFlags(int flags)
{
m_LSL_Functions.llSetVehicleFlags(flags);
}
public void llSetVehicleFloatParam(int param, LSL_Float value)
{
m_LSL_Functions.llSetVehicleFloatParam(param, value);
}
public void llSetVehicleRotationParam(int param, LSL_Rotation rot)
{
m_LSL_Functions.llSetVehicleRotationParam(param, rot);
}
public void llSetVehicleType(int type)
{
m_LSL_Functions.llSetVehicleType(type);
}
public void llSetVehicleVectorParam(int param, LSL_Vector vec)
{
m_LSL_Functions.llSetVehicleVectorParam(param, vec);
}
public void llShout(int channelID, string text)
{
m_LSL_Functions.llShout(channelID, text);
}
public LSL_Float llSin(double f)
{
return m_LSL_Functions.llSin(f);
}
public void llSitTarget(LSL_Vector offset, LSL_Rotation rot)
{
m_LSL_Functions.llSitTarget(offset, rot);
}
public void llSleep(double sec)
{
m_LSL_Functions.llSleep(sec);
}
public void llSound(string sound, double volume, int queue, int loop)
{
m_LSL_Functions.llSound(sound, volume, queue, loop);
}
public void llSoundPreload(string sound)
{
m_LSL_Functions.llSoundPreload(sound);
}
public LSL_Float llSqrt(double f)
{
return m_LSL_Functions.llSqrt(f);
}
public void llStartAnimation(string anim)
{
m_LSL_Functions.llStartAnimation(anim);
}
public void llStopAnimation(string anim)
{
m_LSL_Functions.llStopAnimation(anim);
}
public void llStopHover()
{
m_LSL_Functions.llStopHover();
}
public void llStopLookAt()
{
m_LSL_Functions.llStopLookAt();
}
public void llStopMoveToTarget()
{
m_LSL_Functions.llStopMoveToTarget();
}
public void llStopPointAt()
{
m_LSL_Functions.llStopPointAt();
}
public void llStopSound()
{
m_LSL_Functions.llStopSound();
}
public LSL_Integer llStringLength(string str)
{
return m_LSL_Functions.llStringLength(str);
}
public LSL_String llStringToBase64(string str)
{
return m_LSL_Functions.llStringToBase64(str);
}
public LSL_String llStringTrim(string src, int type)
{
return m_LSL_Functions.llStringTrim(src, type);
}
public LSL_Integer llSubStringIndex(string source, string pattern)
{
return m_LSL_Functions.llSubStringIndex(source, pattern);
}
public void llTakeCamera(string avatar)
{
m_LSL_Functions.llTakeCamera(avatar);
}
public void llTakeControls(int controls, int accept, int pass_on)
{
m_LSL_Functions.llTakeControls(controls, accept, pass_on);
}
public LSL_Float llTan(double f)
{
return m_LSL_Functions.llTan(f);
}
public LSL_Integer llTarget(LSL_Vector position, double range)
{
return m_LSL_Functions.llTarget(position, range);
}
public void llTargetOmega(LSL_Vector axis, double spinrate, double gain)
{
m_LSL_Functions.llTargetOmega(axis, spinrate, gain);
}
public void llTargetRemove(int number)
{
m_LSL_Functions.llTargetRemove(number);
}
public void llTeleportAgentHome(string agent)
{
m_LSL_Functions.llTeleportAgentHome(agent);
}
public void llTextBox(string avatar, string message, int chat_channel)
{
m_LSL_Functions.llTextBox(avatar, message, chat_channel);
}
public LSL_String llToLower(string source)
{
return m_LSL_Functions.llToLower(source);
}
public LSL_String llToUpper(string source)
{
return m_LSL_Functions.llToUpper(source);
}
public void llTriggerSound(string sound, double volume)
{
m_LSL_Functions.llTriggerSound(sound, volume);
}
public void llTriggerSoundLimited(string sound, double volume, LSL_Vector top_north_east, LSL_Vector bottom_south_west)
{
m_LSL_Functions.llTriggerSoundLimited(sound, volume, top_north_east, bottom_south_west);
}
public LSL_String llUnescapeURL(string url)
{
return m_LSL_Functions.llUnescapeURL(url);
}
public void llUnSit(string id)
{
m_LSL_Functions.llUnSit(id);
}
public LSL_Float llVecDist(LSL_Vector a, LSL_Vector b)
{
return m_LSL_Functions.llVecDist(a, b);
}
public LSL_Float llVecMag(LSL_Vector v)
{
return m_LSL_Functions.llVecMag(v);
}
public LSL_Vector llVecNorm(LSL_Vector v)
{
return m_LSL_Functions.llVecNorm(v);
}
public void llVolumeDetect(int detect)
{
m_LSL_Functions.llVolumeDetect(detect);
}
public LSL_Float llWater(LSL_Vector offset)
{
return m_LSL_Functions.llWater(offset);
}
public void llWhisper(int channelID, string text)
{
m_LSL_Functions.llWhisper(channelID, text);
}
public LSL_Vector llWind(LSL_Vector offset)
{
return m_LSL_Functions.llWind(offset);
}
public LSL_String llXorBase64Strings(string str1, string str2)
{
return m_LSL_Functions.llXorBase64Strings(str1, str2);
}
public LSL_String llXorBase64StringsCorrect(string str1, string str2)
{
return m_LSL_Functions.llXorBase64StringsCorrect(str1, str2);
}
}
}
| |
namespace OpenQA.Selenium.DevTools
{
using System;
using System.Collections.Concurrent;
using System.Diagnostics;
using System.IO;
using System.Net.WebSockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
/// <summary>
/// Represents a WebSocket connection to a running DevTools instance that can be used to send
/// commands and recieve events.
///</summary>
public partial class DevToolsSession : IDisposable
{
private readonly string m_endpointAddress;
private readonly TimeSpan m_closeConnectionWaitTimeSpan = TimeSpan.FromSeconds(2);
private ClientWebSocket m_sessionSocket;
private ConcurrentDictionary<long, DevToolsCommandData> m_pendingCommands = new ConcurrentDictionary<long, DevToolsCommandData>();
private long m_currentCommandId = 0;
private Task m_receiveTask;
/// <summary>
/// Initializes a new instance of the DevToolsSession class, using the specified WebSocket endpoint.
/// </summary>
/// <param name="endpointAddress"></param>
public DevToolsSession(string endpointAddress)
: this()
{
if (String.IsNullOrWhiteSpace(endpointAddress))
throw new ArgumentNullException(nameof(endpointAddress));
CommandTimeout = 5000;
m_endpointAddress = endpointAddress;
m_sessionSocket = new ClientWebSocket();
}
/// <summary>
/// Event raised when the DevToolsSession logs informational messages.
/// </summary>
public event EventHandler<DevToolsSessionLogMessageEventArgs> LogMessage;
/// <summary>
/// Event raised an event notification is received from the DevTools session.
/// </summary>
internal event EventHandler<DevToolsEventReceivedEventArgs> DevToolsEventReceived;
/// <summary>
/// Gets or sets the number of milliseconds to wait for a command to complete. Default is 5 seconds.
/// </summary>
public int CommandTimeout
{
get;
set;
}
/// <summary>
/// Gets or sets the active session ID of the connection.
/// </summary>
public string ActiveSessionId
{
get;
set;
}
/// <summary>
/// Gets the endpoint address of the session.
/// </summary>
public string EndpointAddress
{
get { return m_endpointAddress; }
}
/// <summary>
/// Sends the specified command and returns the associated command response.
/// </summary>
/// <typeparam name="TCommand"></typeparam>
/// <param name="command"></param>
/// <param name="cancellationToken"></param>
/// <param name="millisecondsTimeout"></param>
/// <param name="throwExceptionIfResponseNotReceived"></param>
/// <returns></returns>
public async Task<ICommandResponse<TCommand>> SendCommand<TCommand>(TCommand command, CancellationToken cancellationToken = default(CancellationToken), int? millisecondsTimeout = null, bool throwExceptionIfResponseNotReceived = true)
where TCommand : ICommand
{
if (command == null)
throw new ArgumentNullException(nameof(command));
var result = await SendCommand(command.CommandName, JToken.FromObject(command), cancellationToken, millisecondsTimeout, throwExceptionIfResponseNotReceived);
if (result == null)
return null;
if (!CommandResponseTypeMap.TryGetCommandResponseType<TCommand>(out Type commandResponseType))
throw new InvalidOperationException($"Type {typeof(TCommand)} does not correspond to a known command response type.");
return result.ToObject(commandResponseType) as ICommandResponse<TCommand>;
}
/// <summary>
/// Sends the specified command and returns the associated command response.
/// </summary>
/// <typeparam name="TCommand"></typeparam>
/// <typeparam name="TCommandResponse"></typeparam>
/// <param name="command"></param>
/// <param name="cancellationToken"></param>
/// <param name="millisecondsTimeout"></param>
/// <param name="throwExceptionIfResponseNotReceived"></param>
/// <returns></returns>
public async Task<TCommandResponse> SendCommand<TCommand, TCommandResponse>(TCommand command, CancellationToken cancellationToken = default(CancellationToken), int? millisecondsTimeout = null, bool throwExceptionIfResponseNotReceived = true)
where TCommand : ICommand
where TCommandResponse : ICommandResponse<TCommand>
{
if (command == null)
throw new ArgumentNullException(nameof(command));
var result = await SendCommand(command.CommandName, JToken.FromObject(command), cancellationToken, millisecondsTimeout, throwExceptionIfResponseNotReceived);
if (result == null)
return default(TCommandResponse);
return result.ToObject<TCommandResponse>();
}
/// <summary>
/// Returns a JToken based on a command created with the specified command name and params.
/// </summary>
/// <param name="commandName"></param>
/// <param name="params"></param>
/// <param name="cancellationToken"></param>
/// <param name="millisecondsTimeout"></param>
/// <param name="throwExceptionIfResponseNotReceived"></param>
/// <returns></returns>
//[DebuggerStepThrough]
public async Task<JToken> SendCommand(string commandName, JToken @params, CancellationToken cancellationToken = default(CancellationToken), int? millisecondsTimeout = null, bool throwExceptionIfResponseNotReceived = true)
{
var message = new DevToolsCommandData(Interlocked.Increment(ref m_currentCommandId), ActiveSessionId, commandName, @params);
if (millisecondsTimeout.HasValue == false)
millisecondsTimeout = CommandTimeout;
await OpenSessionConnection(cancellationToken);
LogTrace("Sending {id} {method}: {params}", message.CommandId, message.CommandName, @params.ToString());
var contents = JsonConvert.SerializeObject(message);
var contentBuffer = Encoding.UTF8.GetBytes(contents);
m_pendingCommands.TryAdd(message.CommandId, message);
await m_sessionSocket.SendAsync(new ArraySegment<byte>(contentBuffer), WebSocketMessageType.Text, true, cancellationToken);
var responseWasReceived = await Task.Run(() => message.SyncEvent.Wait(millisecondsTimeout.Value, cancellationToken));
if (!responseWasReceived && throwExceptionIfResponseNotReceived)
throw new InvalidOperationException($"A command response was not received: {commandName}");
DevToolsCommandData modified;
m_pendingCommands.TryRemove(message.CommandId, out modified);
if (modified.IsError)
{
var errorMessage = modified.Result.Value<string>("message");
var errorData = modified.Result.Value<string>("data");
var exceptionMessage = $"{commandName}: {errorMessage}";
if (!String.IsNullOrWhiteSpace(errorData))
exceptionMessage = $"{exceptionMessage} - {errorData}";
LogTrace("Recieved Error Response {id}: {message} {data}", modified.CommandId, message, errorData);
throw new CommandResponseException(exceptionMessage)
{
Code = modified.Result.Value<long>("code")
};
}
return modified.Result;
}
private async Task OpenSessionConnection(CancellationToken cancellationToken)
{
if (m_sessionSocket.State != WebSocketState.Open)
{
await m_sessionSocket.ConnectAsync(new Uri(m_endpointAddress), cancellationToken);
m_receiveTask = Task.Run(async () => await ReceiveMessage(cancellationToken));
}
}
private async Task ReceiveMessage(CancellationToken cancellationToken)
{
while (m_sessionSocket.State == WebSocketState.Open)
{
WebSocketReceiveResult result = null;
var buffer = WebSocket.CreateClientBuffer(1024, 1024);
try
{
result = await m_sessionSocket.ReceiveAsync(buffer, cancellationToken);
}
catch (OperationCanceledException)
{
}
catch (WebSocketException)
{
// If we receive a WebSocketException, there's not much we can do
// so we'll just terminate our listener.
break;
}
if (cancellationToken.IsCancellationRequested)
{
break;
}
if (result.MessageType == WebSocketMessageType.Close)
{
break;
}
else
{
using (var stream = new MemoryStream())
{
stream.Write(buffer.Array, 0, result.Count);
while (!result.EndOfMessage)
{
result = await m_sessionSocket.ReceiveAsync(buffer, cancellationToken);
stream.Write(buffer.Array, 0, result.Count);
}
stream.Seek(0, SeekOrigin.Begin);
using (var reader = new StreamReader(stream, Encoding.UTF8))
{
string message = reader.ReadToEnd();
ProcessIncomingMessage(message);
}
}
}
}
}
private void ProcessIncomingMessage(string message)
{
var messageObject = JObject.Parse(message);
long commandId;
if (messageObject.TryGetValue("id", out JToken idProperty) && (commandId = idProperty.Value<long>()) == m_currentCommandId)
{
DevToolsCommandData commandInfo;
m_pendingCommands.TryGetValue(commandId, out commandInfo);
if (messageObject.TryGetValue("error", out JToken errorProperty))
{
commandInfo.IsError = true;
commandInfo.Result = errorProperty;
commandInfo.SyncEvent.Set();
return;
}
commandInfo.Result = messageObject["result"];
LogTrace("Recieved Response {id}: {message}", commandId, commandInfo.Result.ToString());
commandInfo.SyncEvent.Set();
return;
}
if (messageObject.TryGetValue("method", out JToken methodProperty))
{
var method = methodProperty.Value<string>();
var methodParts = method.Split(new char[] { '.' }, 2);
var eventData = messageObject["params"];
LogTrace("Recieved Event {method}: {params}", method, eventData.ToString());
OnDevToolsEventReceived(new DevToolsEventReceivedEventArgs(methodParts[0], methodParts[1], eventData));
return;
}
LogTrace("Recieved Other: {message}", message);
}
private void OnDevToolsEventReceived(DevToolsEventReceivedEventArgs e)
{
if (DevToolsEventReceived != null)
{
DevToolsEventReceived(this, e);
}
}
private void LogTrace(string message, params object[] args)
{
if (LogMessage != null)
{
LogMessage(this, new DevToolsSessionLogMessageEventArgs(DevToolsSessionLogLevel.Trace, message, args));
}
}
private void LogError(string message, params object[] args)
{
if (LogMessage != null)
{
LogMessage(this, new DevToolsSessionLogMessageEventArgs(DevToolsSessionLogLevel.Error, message, args));
}
}
#region IDisposable Support
private bool m_isDisposed = false;
protected void Dispose(bool disposing)
{
if (!m_isDisposed)
{
if (disposing)
{
if (m_sessionSocket != null)
{
if (m_receiveTask != null)
{
if (m_sessionSocket.State == WebSocketState.Open)
{
try
{
// Since Chromium-based DevTools does not respond to the close
// request with a correctly echoed WebSocket close packet, but
// rather just terminates the socket connection, so we have to
// catch the exception thrown when the socket is terminated
// unexpectedly. Also, because we are using async, waiting for
// the task to complete might throw a TaskCanceledException,
// which we should also catch. Additiionally, there are times
// when mulitple failure modes can be seen, which will throw an
// AggregateException, consolidating several exceptions into one,
// and this too must be caught. Finally, the call to CloseAsync
// will hang even though the connection is already severed.
// Wait for the task to complete for a short time (since we're
// restricted to localhost, the default of 2 seconds should be
// plenty; if not, change the initialization of the timout),
// and if the task is still running, then we assume the connection
// is properly closed.
Task closeTask = Task.Run(() => m_sessionSocket.CloseAsync(WebSocketCloseStatus.NormalClosure, string.Empty, CancellationToken.None));
closeTask.Wait(m_closeConnectionWaitTimeSpan);
}
catch (WebSocketException)
{
}
catch (TaskCanceledException)
{
}
catch (AggregateException)
{
}
}
// Wait for the recieve task to be completely exited (for
// whatever reason) before attempting to dispose it.
m_receiveTask.Wait();
m_receiveTask.Dispose();
m_receiveTask = null;
}
m_sessionSocket.Dispose();
m_sessionSocket = null;
}
m_pendingCommands.Clear();
}
m_isDisposed = true;
}
}
/// <summary>
/// Disposes of the DevToolsSession and frees all resources.
///</summary>
public void Dispose()
{
Dispose(true);
}
#endregion
}
}
| |
/*
* DocuSign REST API
*
* The DocuSign REST API provides you with a powerful, convenient, and simple Web services API for interacting with DocuSign.
*
* OpenAPI spec version: v2.1
* Contact: devcenter@docusign.com
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*/
using System;
using System.Linq;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System.ComponentModel.DataAnnotations;
namespace DocuSign.eSign.Model
{
/// <summary>
/// DisplayApplianceDocumentPage
/// </summary>
[DataContract]
public partial class DisplayApplianceDocumentPage : IEquatable<DisplayApplianceDocumentPage>, IValidatableObject
{
public DisplayApplianceDocumentPage()
{
// Empty Constructor
}
/// <summary>
/// Initializes a new instance of the <see cref="DisplayApplianceDocumentPage" /> class.
/// </summary>
/// <param name="DocPageCountTotal">.</param>
/// <param name="DocumentId">Specifies the document ID number that the tab is placed on. This must refer to an existing Document's ID attribute..</param>
/// <param name="DocumentName">.</param>
/// <param name="Extension">.</param>
/// <param name="Height72DPI">.</param>
/// <param name="IsAttachmentType">.</param>
/// <param name="Page">.</param>
/// <param name="PageId">.</param>
/// <param name="Type">.</param>
/// <param name="Width72DPI">.</param>
public DisplayApplianceDocumentPage(int? DocPageCountTotal = default(int?), string DocumentId = default(string), string DocumentName = default(string), string Extension = default(string), int? Height72DPI = default(int?), bool? IsAttachmentType = default(bool?), int? Page = default(int?), string PageId = default(string), string Type = default(string), int? Width72DPI = default(int?))
{
this.DocPageCountTotal = DocPageCountTotal;
this.DocumentId = DocumentId;
this.DocumentName = DocumentName;
this.Extension = Extension;
this.Height72DPI = Height72DPI;
this.IsAttachmentType = IsAttachmentType;
this.Page = Page;
this.PageId = PageId;
this.Type = Type;
this.Width72DPI = Width72DPI;
}
/// <summary>
///
/// </summary>
/// <value></value>
[DataMember(Name="docPageCountTotal", EmitDefaultValue=false)]
public int? DocPageCountTotal { get; set; }
/// <summary>
/// Specifies the document ID number that the tab is placed on. This must refer to an existing Document's ID attribute.
/// </summary>
/// <value>Specifies the document ID number that the tab is placed on. This must refer to an existing Document's ID attribute.</value>
[DataMember(Name="documentId", EmitDefaultValue=false)]
public string DocumentId { get; set; }
/// <summary>
///
/// </summary>
/// <value></value>
[DataMember(Name="documentName", EmitDefaultValue=false)]
public string DocumentName { get; set; }
/// <summary>
///
/// </summary>
/// <value></value>
[DataMember(Name="extension", EmitDefaultValue=false)]
public string Extension { get; set; }
/// <summary>
///
/// </summary>
/// <value></value>
[DataMember(Name="height72DPI", EmitDefaultValue=false)]
public int? Height72DPI { get; set; }
/// <summary>
///
/// </summary>
/// <value></value>
[DataMember(Name="isAttachmentType", EmitDefaultValue=false)]
public bool? IsAttachmentType { get; set; }
/// <summary>
///
/// </summary>
/// <value></value>
[DataMember(Name="page", EmitDefaultValue=false)]
public int? Page { get; set; }
/// <summary>
///
/// </summary>
/// <value></value>
[DataMember(Name="pageId", EmitDefaultValue=false)]
public string PageId { get; set; }
/// <summary>
///
/// </summary>
/// <value></value>
[DataMember(Name="type", EmitDefaultValue=false)]
public string Type { get; set; }
/// <summary>
///
/// </summary>
/// <value></value>
[DataMember(Name="width72DPI", EmitDefaultValue=false)]
public int? Width72DPI { 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 DisplayApplianceDocumentPage {\n");
sb.Append(" DocPageCountTotal: ").Append(DocPageCountTotal).Append("\n");
sb.Append(" DocumentId: ").Append(DocumentId).Append("\n");
sb.Append(" DocumentName: ").Append(DocumentName).Append("\n");
sb.Append(" Extension: ").Append(Extension).Append("\n");
sb.Append(" Height72DPI: ").Append(Height72DPI).Append("\n");
sb.Append(" IsAttachmentType: ").Append(IsAttachmentType).Append("\n");
sb.Append(" Page: ").Append(Page).Append("\n");
sb.Append(" PageId: ").Append(PageId).Append("\n");
sb.Append(" Type: ").Append(Type).Append("\n");
sb.Append(" Width72DPI: ").Append(Width72DPI).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 DisplayApplianceDocumentPage);
}
/// <summary>
/// Returns true if DisplayApplianceDocumentPage instances are equal
/// </summary>
/// <param name="other">Instance of DisplayApplianceDocumentPage to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(DisplayApplianceDocumentPage other)
{
// credit: http://stackoverflow.com/a/10454552/677735
if (other == null)
return false;
return
(
this.DocPageCountTotal == other.DocPageCountTotal ||
this.DocPageCountTotal != null &&
this.DocPageCountTotal.Equals(other.DocPageCountTotal)
) &&
(
this.DocumentId == other.DocumentId ||
this.DocumentId != null &&
this.DocumentId.Equals(other.DocumentId)
) &&
(
this.DocumentName == other.DocumentName ||
this.DocumentName != null &&
this.DocumentName.Equals(other.DocumentName)
) &&
(
this.Extension == other.Extension ||
this.Extension != null &&
this.Extension.Equals(other.Extension)
) &&
(
this.Height72DPI == other.Height72DPI ||
this.Height72DPI != null &&
this.Height72DPI.Equals(other.Height72DPI)
) &&
(
this.IsAttachmentType == other.IsAttachmentType ||
this.IsAttachmentType != null &&
this.IsAttachmentType.Equals(other.IsAttachmentType)
) &&
(
this.Page == other.Page ||
this.Page != null &&
this.Page.Equals(other.Page)
) &&
(
this.PageId == other.PageId ||
this.PageId != null &&
this.PageId.Equals(other.PageId)
) &&
(
this.Type == other.Type ||
this.Type != null &&
this.Type.Equals(other.Type)
) &&
(
this.Width72DPI == other.Width72DPI ||
this.Width72DPI != null &&
this.Width72DPI.Equals(other.Width72DPI)
);
}
/// <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.DocPageCountTotal != null)
hash = hash * 59 + this.DocPageCountTotal.GetHashCode();
if (this.DocumentId != null)
hash = hash * 59 + this.DocumentId.GetHashCode();
if (this.DocumentName != null)
hash = hash * 59 + this.DocumentName.GetHashCode();
if (this.Extension != null)
hash = hash * 59 + this.Extension.GetHashCode();
if (this.Height72DPI != null)
hash = hash * 59 + this.Height72DPI.GetHashCode();
if (this.IsAttachmentType != null)
hash = hash * 59 + this.IsAttachmentType.GetHashCode();
if (this.Page != null)
hash = hash * 59 + this.Page.GetHashCode();
if (this.PageId != null)
hash = hash * 59 + this.PageId.GetHashCode();
if (this.Type != null)
hash = hash * 59 + this.Type.GetHashCode();
if (this.Width72DPI != null)
hash = hash * 59 + this.Width72DPI.GetHashCode();
return hash;
}
}
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
yield break;
}
}
}
| |
//-----------------------------------------------------------------------
// <copyright file="BindingSourceRefresh.cs" company="Marimer LLC">
// Copyright (c) Marimer LLC. All rights reserved.
// Website: http://www.lhotka.net/cslanet/
// </copyright>
// <summary>BindingSourceRefresh contains functionality for refreshing the data bound to controls on Host as well as a mechinism for catching data</summary>
//-----------------------------------------------------------------------
using System;
using System.ComponentModel;
using System.Collections.Generic;
using System.Diagnostics;
using System.Windows.Forms;
// code from Bill McCarthy
// http://msmvps.com/bill/archive/2005/10/05/69012.aspx
// used with permission
namespace Csla.Windows
{
/// <summary>
/// BindingSourceRefresh contains functionality for refreshing the data bound to controls on Host as well as a mechinism for catching data
/// binding errors that occur in Host.
/// </summary>
/// <remarks>Windows Forms extender control that resolves the
/// data refresh issue with data bound detail controls
/// as discussed in Chapter 5.</remarks>
[DesignerCategory("")]
[ProvideProperty("ReadValuesOnChange", typeof(BindingSource))]
public class BindingSourceRefresh : Component, IExtenderProvider, ISupportInitialize
{
#region Fields
private readonly Dictionary<BindingSource, bool> _sources = new Dictionary<BindingSource, bool>();
#endregion
#region Events
/// <summary>
/// BindingError event is raised when a data binding error occurs due to a exception.
/// </summary>
public event BindingErrorEventHandler BindingError = null;
#endregion
#region Constructors
/// <summary>
/// Constructor creates a new BindingSourceRefresh component then initialises all the different sub components.
/// </summary>
public BindingSourceRefresh()
{
InitializeComponent();
}
/// <summary>
/// Constructor creates a new BindingSourceRefresh component, adds the component to the container supplied before initialising all the different sub components.
/// </summary>
/// <param name="container">The container the component is to be added to.</param>
public BindingSourceRefresh(IContainer container)
{
container.Add(this);
InitializeComponent();
}
#endregion
#region Designer Functionality
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Component Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
components = new System.ComponentModel.Container();
}
#endregion
#endregion
#region Public Methods
/// <summary>
/// CanExtend() returns true if extendee is a binding source.
/// </summary>
/// <param name="extendee">The control to be extended.</param>
/// <returns>True if the control is a binding source, else false.</returns>
public bool CanExtend(object extendee)
{
return (extendee is BindingSource);
}
/// <summary>
/// GetReadValuesOnChange() gets the value of the custom ReadValuesOnChange extender property added to extended controls.
/// property added to extended controls.
/// </summary>
/// <param name="source">Control being extended.</param>
[Category("Csla")]
public bool GetReadValuesOnChange(BindingSource source)
{
bool result;
if (_sources.TryGetValue(source, out result))
return result;
else
return false;
}
/// <summary>
/// SetReadValuesOnChange() sets the value of the custom ReadValuesOnChange extender
/// property added to extended controls.
/// </summary>
/// <param name="source">Control being extended.</param>
/// <param name="value">New value of property.</param>
/// <remarks></remarks>
[Category("Csla")]
public void SetReadValuesOnChange(
BindingSource source, bool value)
{
_sources[source] = value;
if (!_isInitialising)
{
RegisterControlEvents(source, value);
}
}
#endregion
#region Properties
/// <summary>
/// Not in use - kept for backward compatibility
/// </summary>
[Browsable(false)]
[DefaultValue(null)]
#if NETSTANDARD2_0
[System.ComponentModel.DataAnnotations.ScaffoldColumn(false)]
#endif
public ContainerControl Host { get; set; }
/// <summary>
/// Forces the binding to re-read after an exception is thrown when changing the binding value
/// </summary>
[Browsable(true)]
[DefaultValue(false)]
public bool RefreshOnException { get; set; }
#endregion
#region Private Methods
/// <summary>
/// RegisterControlEvents() registers all the relevant events for the container control supplied and also to all child controls
/// in the oontainer control.
/// </summary>
/// <param name="container">The control (including child controls) to have the refresh events registered.</param>
/// <param name="register">True to register the events, false to unregister them.</param>
private void RegisterControlEvents(ICurrencyManagerProvider container, bool register)
{
var currencyManager = container.CurrencyManager;
// If we are to register the events the do so.
if (register)
{
currencyManager.Bindings.CollectionChanged += Bindings_CollectionChanged;
currencyManager.Bindings.CollectionChanging += Bindings_CollectionChanging;
}
// Else unregister them.
else
{
currencyManager.Bindings.CollectionChanged -= Bindings_CollectionChanged;
currencyManager.Bindings.CollectionChanging -= Bindings_CollectionChanging;
}
// Reigster the binding complete events for the currencymanagers bindings.
RegisterBindingEvents(currencyManager.Bindings, register);
}
/// <summary>
/// Registers the control events.
/// </summary>
/// <param name="source">The source.</param>
/// <param name="register">if set to <c>true</c> [register].</param>
private void RegisterBindingEvents(BindingsCollection source, bool register)
{
foreach (Binding binding in source)
{
RegisterBindingEvent(binding, register);
}
}
/// <summary>
/// Registers the binding event.
/// </summary>
/// <param name="register">if set to <c>true</c> [register].</param>
/// <param name="binding">The binding.</param>
private void RegisterBindingEvent(Binding binding, bool register)
{
if (register)
{
binding.BindingComplete += Control_BindingComplete;
}
else
{
binding.BindingComplete -= Control_BindingComplete;
}
}
#endregion
#region Event Methods
/// <summary>
/// Handles the CollectionChanging event of the Bindings control.
///
/// Remove event hooks for element or entire list depending on CollectionChangeAction.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="System.ComponentModel.CollectionChangeEventArgs"/> instance containing the event data.</param>
private void Bindings_CollectionChanging(object sender, CollectionChangeEventArgs e)
{
switch (e.Action)
{
case CollectionChangeAction.Refresh:
// remove events for entire list
RegisterBindingEvents((BindingsCollection)sender, false);
break;
case CollectionChangeAction.Add:
// adding new element - remove events for element
RegisterBindingEvent((Binding)e.Element, false);
break;
case CollectionChangeAction.Remove:
// removing element - remove events for element
RegisterBindingEvent((Binding)e.Element, false);
break;
}
}
/// <summary>
/// Handles the CollectionChanged event of the Bindings control.
///
/// Add event hooks for element or entire list depending on CollectionChangeAction.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="System.ComponentModel.CollectionChangeEventArgs"/> instance containing the event data.</param>
private void Bindings_CollectionChanged(object sender, CollectionChangeEventArgs e)
{
switch (e.Action)
{
case CollectionChangeAction.Refresh:
// refresh entire list - add event to all items
RegisterBindingEvents((BindingsCollection)sender, true);
break;
case CollectionChangeAction.Add:
// new element added - add event to element
RegisterBindingEvent((Binding)e.Element, true);
break;
case CollectionChangeAction.Remove:
// element has been removed - do nothing
break;
}
}
/// <summary>
/// Control_BindingComplete() is a event driven routine triggered when one of the control's bindings has been completed.
/// Control_BindingComplete() simply validates the result where if the result was a exception then the BindingError
/// event is raised, else if the binding was a successful data source update and we are to re-read the value on changed then
/// the binding value is reread into the control.
/// </summary>
/// <param name="sender">The object that triggered the event.</param>
/// <param name="e">The event arguments.</param>
private void Control_BindingComplete(object sender, BindingCompleteEventArgs e)
{
switch (e.BindingCompleteState)
{
case BindingCompleteState.Exception:
if ((RefreshOnException)
&& e.Binding.DataSource is BindingSource
&& GetReadValuesOnChange((BindingSource)e.Binding.DataSource))
{
e.Binding.ReadValue();
}
if (BindingError != null)
{
BindingError(this, new BindingErrorEventArgs(e.Binding, e.Exception));
}
break;
default:
if ((e.BindingCompleteContext == BindingCompleteContext.DataSourceUpdate)
&& e.Binding.DataSource is BindingSource
&& GetReadValuesOnChange((BindingSource)e.Binding.DataSource))
{
e.Binding.ReadValue();
}
break;
}
}
#endregion
#region ISupportInitialize Interface
private bool _isInitialising = false;
/// <summary>
/// BeginInit() is called when the component is starting to be initialised. BeginInit() simply sets the initialisation flag to true.
/// </summary>
void ISupportInitialize.BeginInit()
{
_isInitialising = true;
}
/// <summary>
/// EndInit() is called when the component has finished being initialised. EndInt() sets the initialise flag to false then runs
/// through registering all the different events that the component needs to hook into in Host.
/// </summary>
void ISupportInitialize.EndInit()
{
_isInitialising = false;
foreach (var source in _sources)
{
if (source.Value)
RegisterControlEvents(source.Key, true);
}
}
#endregion
}
#region Delegates
/// <summary>
/// BindingErrorEventHandler delegates is the event handling definition for handling data binding errors that occurred due to exceptions.
/// </summary>
/// <param name="sender">The object that triggered the event.</param>
/// <param name="e">The event arguments.</param>
public delegate void BindingErrorEventHandler(object sender, BindingErrorEventArgs e);
#endregion
#region BindingErrorEventArgs Class
/// <summary>
/// BindingErrorEventArgs defines the event arguments for reporting a data binding error due to a exception.
/// </summary>
public class BindingErrorEventArgs : EventArgs
{
#region Property Fields
private Exception _exception = null;
private Binding _binding = null;
#endregion
#region Properties
/// <summary>
/// Exception gets the exception that caused the binding error.
/// </summary>
public Exception Exception
{
get { return (_exception); }
}
/// <summary>
/// Binding gets the binding that caused the exception.
/// </summary>
public Binding Binding
{
get { return (_binding); }
}
#endregion
#region Constructors
/// <summary>
/// Constructor creates a new BindingErrorEventArgs object instance using the information specified.
/// </summary>
/// <param name="binding">The binding that caused th exception.</param>
/// <param name="exception">The exception that caused the error.</param>
public BindingErrorEventArgs(Binding binding, Exception exception)
{
_binding = binding;
_exception = exception;
}
#endregion
}
#endregion
}
| |
using System;
using System.Diagnostics;
using System.Collections.Generic;
using Chainey;
using IvionSoft;
using MeidoCommon.Parsing;
// Using directives for plugin use.
using MeidoCommon;
using System.ComponentModel.Composition;
[Export(typeof(IMeidoHook))]
public class IrcChainey : IMeidoHook, IPluginTriggers, IPluginIrcHandlers
{
public string Name
{
get { return "Chainey"; }
}
public string Version
{
get { return "9999"; } // ENDLESS NINE
}
public IEnumerable<Trigger> Triggers { get; private set; }
public IEnumerable<IIrcHandler> IrcHandlers { get; private set; }
readonly IIrcComm irc;
readonly IMeidoComm meido;
readonly ILog log;
// Keep Sqlite backend around because we need to dispose of it.
readonly SqliteBrain backend;
readonly BrainFrontend chainey;
readonly Random rnd = new Random();
readonly Config conf = new Config();
const string nickPlaceholder = "||NICK||";
public void Stop()
{
backend.Dispose();
}
[ImportingConstructor]
public IrcChainey(IIrcComm ircComm, IMeidoComm meidoComm)
{
meido = meidoComm;
log = meido.CreateLogger(this);
conf.Location = meidoComm.DataPathTo("chainey.sqlite");
backend = new SqliteBrain(conf.Location, conf.Order);
chainey = new BrainFrontend(backend);
chainey.Filter = false;
irc = ircComm;
var t = TriggerThreading.Queue;
Triggers = Trigger.Group(
new Trigger("markov", Markov, t) {
Help = new TriggerHelp(
"<seeds>",
"Builds reply with markov chains using the specified seeds.")
},
new Trigger(MarkovNick, t, "markov-nick", "nicksay") {
Help = new TriggerHelp(
"<nick> [seeds]",
"Builds reply with markov chains based on `seeds`, with the contraint that the words " +
"of the reply have been said by `nick` at some point.")
},
new Trigger(Remove, t, "markov-remove", "remove") {
Help = new TriggerHelp(
"<sentence>",
"Remove sentence and its constituent words from the markov chains database. " +
"(Admin only)")
}
);
IrcHandlers = new IIrcHandler[] {
new IrcHandler<IChannelMsg>(MessageHandler, t)
};
}
// -----------------
// Chainey triggers.
// -----------------
// remove <sentence>
void Remove(ITriggerMsg e)
{
if (meido.AuthLevel(e.Nick) >= 2)
{
chainey.Remove(e.ArgString());
e.Reply("Removed sentence.");
}
}
// markov <seeds>
void Markov(ITriggerMsg e)
{
var msg = e.Message.Split((char[])null, StringSplitOptions.RemoveEmptyEntries);
msg = msg.Slice(1, 0);
EmitSentence(e.ReturnTo, msg, e.Nick);
}
// markov-nick <nick> [seeds]
void MarkovNick(ITriggerMsg e)
{
var msg = e.Message.Split((char[])null, StringSplitOptions.RemoveEmptyEntries);
if (msg.Length > 1)
{
var source = msg[1].ToUpperInvariant();
List<Sentence> sentences;
// When we have seeds.
if (msg.Length > 2)
{
msg = msg.Slice(2, 0);
sentences = chainey.Build(msg, source, false);
}
// When we don't have seeds.
else
sentences = chainey.BuildRandom(1, source);
if (sentences.Count > 0)
SendSentence(e.ReturnTo, sentences[0], e.Nick);
}
}
// ---------------------------------------------
// Handling of messages (learning and replying).
// ---------------------------------------------
void MessageHandler(IChannelMsg e)
{
var msg = e.Message.Split((char[])null, StringSplitOptions.RemoveEmptyEntries);
// Don't process if it's empty or a probable trigger call.
if (msg.Length == 0 || e.StartsWithTriggerPrefix())
return;
string first = msg[0];
string last = msg[msg.Length - 1];
// If directly addressed. (nick: message || message, nick)
if (first.StartsWith(irc.Nickname, StringComparison.OrdinalIgnoreCase) ||
last.Contains(irc.Nickname, StringComparison.OrdinalIgnoreCase))
{
HandleAddressed(e.Channel, e.Nick, msg);
}
else
HandleUnaddressed(e.Channel, e.Nick, msg);
}
void HandleAddressed(string channel, string nick, string[] message)
{
if ( !MarkovTools.FoulPlay(message, conf.MaxConsecutive, conf.MaxTotal) )
{
EmitSentence(channel, message, nick);
AbsorbSentence(channel, nick, message);
}
else
irc.SendMessage(channel, "Foul play detected! Stop trying to teach me stupid things, {0}", nick);
}
void HandleUnaddressed(string channel, string nick, string[] message)
{
if ( RandomRespond(channel) )
EmitSentence(channel, message, nick);
if ( Learning(channel) && !MarkovTools.FoulPlay(message, conf.MaxConsecutive, conf.MaxTotal) )
{
AbsorbSentence(channel, nick, message);
}
}
bool Learning(string channel)
{
return conf.LearningChannels.Contains(channel);
}
bool RandomRespond(string channel)
{
if (conf.RandomResponseChannels.Contains(channel))
{
int chance;
lock (rnd)
chance = rnd.Next(conf.ResponseChance);
if (chance == 0)
return true;
}
return false;
}
void AbsorbSentence(string channel, string nick, string[] sentence)
{
if (Absorb(sentence))
{
int nickCount = 0;
for (int i = 0; i < sentence.Length; i++)
{
// Each word is a possible nick.
string possibleNick = sentence[i].TrimPunctuation();
// If the word is actually a nick, replace it with the placeholder.
if ( irc.IsJoined(channel, possibleNick) )
{
sentence[i] = sentence[i].Replace(possibleNick, nickPlaceholder);
nickCount++;
}
// Abort if someone is trying sabotage.
else if (possibleNick == nickPlaceholder)
return;
}
// If a sentence contains more than 2 mentions of a nick, don't add it. It's probably spam anyway.
if (nickCount < 3)
chainey.Add(sentence, nick.ToUpperInvariant());
}
}
// Don't absorb a sentence if its length is 0 or when someone is quoting someone verbatim.
static bool Absorb(string[] sentence)
{
if (sentence.Length > 0)
{
if (!sentence[0].StartsWith("<", StringComparison.OrdinalIgnoreCase) &&
!sentence[0].StartsWith("[", StringComparison.OrdinalIgnoreCase))
{
return true;
}
}
return false;
}
void EmitSentence(string target, string[] respondTo, string fromNick)
{
var sw = Stopwatch.StartNew();
var sentence = chainey.BuildResponse(respondTo);
sw.Stop();
log.Verbose("BuildResponse time: {0}", sw.Elapsed);
SendSentence(target, sentence, fromNick);
}
void SendSentence(string target, Sentence sentence, string fromNick)
{
if (sentence.Content != string.Empty)
{
string senReplaceNicks = sentence.Content.Replace(nickPlaceholder, fromNick);
irc.SendMessage(target, senReplaceNicks);
log.Message("{0} <> {1}", target, sentence);
}
}
}
| |
/*
* Velcro Physics:
* Copyright (c) 2017 Ian Qvist
*
* Original source Box2D:
* Copyright (c) 2006-2011 Erin Catto http://www.box2d.org
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*/
using System;
using Microsoft.Xna.Framework;
using QEngine.Physics.Dynamics.Solver;
using QEngine.Physics.Shared;
using QEngine.Physics.Utilities;
namespace QEngine.Physics.Dynamics.Joints
{
// Linear constraint (point-to-line)
// d = pB - pA = xB + rB - xA - rA
// C = dot(ay, d)
// Cdot = dot(d, cross(wA, ay)) + dot(ay, vB + cross(wB, rB) - vA - cross(wA, rA))
// = -dot(ay, vA) - dot(cross(d + rA, ay), wA) + dot(ay, vB) + dot(cross(rB, ay), vB)
// J = [-ay, -cross(d + rA, ay), ay, cross(rB, ay)]
// Spring linear constraint
// C = dot(ax, d)
// Cdot = = -dot(ax, vA) - dot(cross(d + rA, ax), wA) + dot(ax, vB) + dot(cross(rB, ax), vB)
// J = [-ax -cross(d+rA, ax) ax cross(rB, ax)]
// Motor rotational constraint
// Cdot = wB - wA
// J = [0 0 -1 0 0 1]
/// <summary>
/// A wheel joint. This joint provides two degrees of freedom: translation
/// along an axis fixed in bodyA and rotation in the plane. You can use a
/// joint limit to restrict the range of motion and a joint motor to drive
/// the rotation or to model rotational friction.
/// This joint is designed for vehicle suspensions.
/// </summary>
public class WheelJoint : Joint
{
private Vector2 _ax, _ay;
private Vector2 _axis;
private float _bias;
private bool _enableMotor;
private float _gamma;
private float _impulse;
// Solver temp
private int _indexA;
private int _indexB;
private float _invIA;
private float _invIB;
private float _invMassA;
private float _invMassB;
private Vector2 _localCenterA;
private Vector2 _localCenterB;
// Solver shared
private Vector2 _localYAxis;
private float _mass;
private float _maxMotorTorque;
private float _motorImpulse;
private float _motorMass;
private float _motorSpeed;
private float _sAx, _sBx;
private float _sAy, _sBy;
private float _springImpulse;
private float _springMass;
internal WheelJoint()
{
JointType = JointType.Wheel;
}
/// <summary>
/// Constructor for WheelJoint
/// </summary>
/// <param name="bodyA">The first body</param>
/// <param name="bodyB">The second body</param>
/// <param name="anchor">The anchor point</param>
/// <param name="axis">The axis</param>
/// <param name="useWorldCoordinates">Set to true if you are using world coordinates as anchors.</param>
public WheelJoint(Body bodyA, Body bodyB, Vector2 anchor, Vector2 axis, bool useWorldCoordinates = false)
: base(bodyA, bodyB)
{
JointType = JointType.Wheel;
if (useWorldCoordinates)
{
LocalAnchorA = bodyA.GetLocalPoint(anchor);
LocalAnchorB = bodyB.GetLocalPoint(anchor);
}
else
{
LocalAnchorA = bodyA.GetLocalPoint(bodyB.GetWorldPoint(anchor));
LocalAnchorB = anchor;
}
Axis = axis; //Velcro only: We maintain the original value as it is supposed to.
}
/// <summary>
/// The local anchor point on BodyA
/// </summary>
public Vector2 LocalAnchorA { get; set; }
/// <summary>
/// The local anchor point on BodyB
/// </summary>
public Vector2 LocalAnchorB { get; set; }
public override Vector2 WorldAnchorA
{
get { return BodyA.GetWorldPoint(LocalAnchorA); }
set { LocalAnchorA = BodyA.GetLocalPoint(value); }
}
public override Vector2 WorldAnchorB
{
get { return BodyB.GetWorldPoint(LocalAnchorB); }
set { LocalAnchorB = BodyB.GetLocalPoint(value); }
}
/// <summary>
/// The axis at which the suspension moves.
/// </summary>
public Vector2 Axis
{
get { return _axis; }
set
{
_axis = value;
LocalXAxis = BodyA.GetLocalVector(_axis);
_localYAxis = MathUtils.Cross(1.0f, LocalXAxis);
}
}
/// <summary>
/// The axis in local coordinates relative to BodyA
/// </summary>
public Vector2 LocalXAxis { get; private set; }
/// <summary>
/// The desired motor speed in radians per second.
/// </summary>
public float MotorSpeed
{
get { return _motorSpeed; }
set
{
if (value == _motorSpeed)
return;
WakeBodies();
_motorSpeed = value;
}
}
/// <summary>
/// The maximum motor torque, usually in N-m.
/// </summary>
public float MaxMotorTorque
{
get { return _maxMotorTorque; }
set
{
if (value == _maxMotorTorque)
return;
WakeBodies();
_maxMotorTorque = value;
}
}
/// <summary>
/// Suspension frequency, zero indicates no suspension
/// </summary>
public float Frequency { get; set; }
/// <summary>
/// Suspension damping ratio, one indicates critical damping
/// </summary>
public float DampingRatio { get; set; }
/// <summary>
/// Gets the translation along the axis
/// </summary>
public float JointTranslation
{
get
{
Body bA = BodyA;
Body bB = BodyB;
Vector2 pA = bA.GetWorldPoint(LocalAnchorA);
Vector2 pB = bB.GetWorldPoint(LocalAnchorB);
Vector2 d = pB - pA;
Vector2 axis = bA.GetWorldVector(LocalXAxis);
float translation = Vector2.Dot(d, axis);
return translation;
}
}
public float JointLinearSpeed
{
get
{
Body bA = BodyA;
Body bB = BodyB;
Transform xfA;
bA.GetTransform(out xfA);
Transform xfB;
bB.GetTransform(out xfB);
Vector2 rA = MathUtils.Mul(xfA.q, LocalAnchorA - bA._sweep.LocalCenter);
Vector2 rB = MathUtils.Mul(xfB.q, LocalAnchorB - bB._sweep.LocalCenter);
Vector2 p1 = bA._sweep.C + rA;
Vector2 p2 = bB._sweep.C + rB;
Vector2 d = p2 - p1;
Vector2 axis = MathUtils.Mul(xfA.q, LocalXAxis);
Vector2 vA = bA.LinearVelocity;
Vector2 vB = bB.LinearVelocity;
float wA = bA.AngularVelocity;
float wB = bB.AngularVelocity;
float speed = Vector2.Dot(d, MathUtils.Cross(wA, axis)) + Vector2.Dot(axis, vB + MathUtils.Cross(wB, rB) - vA - MathUtils.Cross(wA, rA));
return speed;
}
}
public float JointAngle
{
get
{
Body bA = BodyA;
Body bB = BodyB;
return bB._sweep.A - bA._sweep.A;
}
}
/// <summary>
/// Gets the angular velocity of the joint
/// </summary>
public float JointAngularSpeed
{
get
{
float wA = BodyA.AngularVelocity;
float wB = BodyB.AngularVelocity;
return wB - wA;
}
}
/// <summary>
/// Enable/disable the joint motor.
/// </summary>
public bool MotorEnabled
{
get { return _enableMotor; }
set
{
if (value == _enableMotor)
return;
WakeBodies();
_enableMotor = value;
}
}
/// <summary>
/// Gets the torque of the motor
/// </summary>
/// <param name="invDt">inverse delta time</param>
public float GetMotorTorque(float invDt)
{
return invDt * _motorImpulse;
}
public override Vector2 GetReactionForce(float invDt)
{
return invDt * (_impulse * _ay + _springImpulse * _ax);
}
public override float GetReactionTorque(float invDt)
{
return invDt * _motorImpulse;
}
internal override void InitVelocityConstraints(ref SolverData data)
{
_indexA = BodyA.IslandIndex;
_indexB = BodyB.IslandIndex;
_localCenterA = BodyA._sweep.LocalCenter;
_localCenterB = BodyB._sweep.LocalCenter;
_invMassA = BodyA._invMass;
_invMassB = BodyB._invMass;
_invIA = BodyA._invI;
_invIB = BodyB._invI;
float mA = _invMassA, mB = _invMassB;
float iA = _invIA, iB = _invIB;
Vector2 cA = data.Positions[_indexA].C;
float aA = data.Positions[_indexA].A;
Vector2 vA = data.Velocities[_indexA].V;
float wA = data.Velocities[_indexA].W;
Vector2 cB = data.Positions[_indexB].C;
float aB = data.Positions[_indexB].A;
Vector2 vB = data.Velocities[_indexB].V;
float wB = data.Velocities[_indexB].W;
Rot qA = new Rot(aA), qB = new Rot(aB);
// Compute the effective masses.
Vector2 rA = MathUtils.Mul(qA, LocalAnchorA - _localCenterA);
Vector2 rB = MathUtils.Mul(qB, LocalAnchorB - _localCenterB);
Vector2 d1 = cB + rB - cA - rA;
// Point to line constraint
{
_ay = MathUtils.Mul(qA, _localYAxis);
_sAy = MathUtils.Cross(d1 + rA, _ay);
_sBy = MathUtils.Cross(rB, _ay);
_mass = mA + mB + iA * _sAy * _sAy + iB * _sBy * _sBy;
if (_mass > 0.0f)
{
_mass = 1.0f / _mass;
}
}
// Spring constraint
_springMass = 0.0f;
_bias = 0.0f;
_gamma = 0.0f;
if (Frequency > 0.0f)
{
_ax = MathUtils.Mul(qA, LocalXAxis);
_sAx = MathUtils.Cross(d1 + rA, _ax);
_sBx = MathUtils.Cross(rB, _ax);
float invMass = mA + mB + iA * _sAx * _sAx + iB * _sBx * _sBx;
if (invMass > 0.0f)
{
_springMass = 1.0f / invMass;
float C = Vector2.Dot(d1, _ax);
// Frequency
float omega = 2.0f * Settings.Pi * Frequency;
// Damping coefficient
float d = 2.0f * _springMass * DampingRatio * omega;
// Spring stiffness
float k = _springMass * omega * omega;
// magic formulas
float h = data.Step.dt;
_gamma = h * (d + h * k);
if (_gamma > 0.0f)
{
_gamma = 1.0f / _gamma;
}
_bias = C * h * k * _gamma;
_springMass = invMass + _gamma;
if (_springMass > 0.0f)
{
_springMass = 1.0f / _springMass;
}
}
}
else
{
_springImpulse = 0.0f;
}
// Rotational motor
if (_enableMotor)
{
_motorMass = iA + iB;
if (_motorMass > 0.0f)
{
_motorMass = 1.0f / _motorMass;
}
}
else
{
_motorMass = 0.0f;
_motorImpulse = 0.0f;
}
if (Settings.EnableWarmstarting)
{
// Account for variable time step.
_impulse *= data.Step.dtRatio;
_springImpulse *= data.Step.dtRatio;
_motorImpulse *= data.Step.dtRatio;
Vector2 P = _impulse * _ay + _springImpulse * _ax;
float LA = _impulse * _sAy + _springImpulse * _sAx + _motorImpulse;
float LB = _impulse * _sBy + _springImpulse * _sBx + _motorImpulse;
vA -= _invMassA * P;
wA -= _invIA * LA;
vB += _invMassB * P;
wB += _invIB * LB;
}
else
{
_impulse = 0.0f;
_springImpulse = 0.0f;
_motorImpulse = 0.0f;
}
data.Velocities[_indexA].V = vA;
data.Velocities[_indexA].W = wA;
data.Velocities[_indexB].V = vB;
data.Velocities[_indexB].W = wB;
}
internal override void SolveVelocityConstraints(ref SolverData data)
{
float mA = _invMassA, mB = _invMassB;
float iA = _invIA, iB = _invIB;
Vector2 vA = data.Velocities[_indexA].V;
float wA = data.Velocities[_indexA].W;
Vector2 vB = data.Velocities[_indexB].V;
float wB = data.Velocities[_indexB].W;
// Solve spring constraint
{
float Cdot = Vector2.Dot(_ax, vB - vA) + _sBx * wB - _sAx * wA;
float impulse = -_springMass * (Cdot + _bias + _gamma * _springImpulse);
_springImpulse += impulse;
Vector2 P = impulse * _ax;
float LA = impulse * _sAx;
float LB = impulse * _sBx;
vA -= mA * P;
wA -= iA * LA;
vB += mB * P;
wB += iB * LB;
}
// Solve rotational motor constraint
{
float Cdot = wB - wA - _motorSpeed;
float impulse = -_motorMass * Cdot;
float oldImpulse = _motorImpulse;
float maxImpulse = data.Step.dt * _maxMotorTorque;
_motorImpulse = MathUtils.Clamp(_motorImpulse + impulse, -maxImpulse, maxImpulse);
impulse = _motorImpulse - oldImpulse;
wA -= iA * impulse;
wB += iB * impulse;
}
// Solve point to line constraint
{
float Cdot = Vector2.Dot(_ay, vB - vA) + _sBy * wB - _sAy * wA;
float impulse = -_mass * Cdot;
_impulse += impulse;
Vector2 P = impulse * _ay;
float LA = impulse * _sAy;
float LB = impulse * _sBy;
vA -= mA * P;
wA -= iA * LA;
vB += mB * P;
wB += iB * LB;
}
data.Velocities[_indexA].V = vA;
data.Velocities[_indexA].W = wA;
data.Velocities[_indexB].V = vB;
data.Velocities[_indexB].W = wB;
}
internal override bool SolvePositionConstraints(ref SolverData data)
{
Vector2 cA = data.Positions[_indexA].C;
float aA = data.Positions[_indexA].A;
Vector2 cB = data.Positions[_indexB].C;
float aB = data.Positions[_indexB].A;
Rot qA = new Rot(aA), qB = new Rot(aB);
Vector2 rA = MathUtils.Mul(qA, LocalAnchorA - _localCenterA);
Vector2 rB = MathUtils.Mul(qB, LocalAnchorB - _localCenterB);
Vector2 d = (cB - cA) + rB - rA;
Vector2 ay = MathUtils.Mul(qA, _localYAxis);
float sAy = MathUtils.Cross(d + rA, ay);
float sBy = MathUtils.Cross(rB, ay);
float C = Vector2.Dot(d, ay);
float k = _invMassA + _invMassB + _invIA * _sAy * _sAy + _invIB * _sBy * _sBy;
float impulse;
if (k != 0.0f)
{
impulse = -C / k;
}
else
{
impulse = 0.0f;
}
Vector2 P = impulse * ay;
float LA = impulse * sAy;
float LB = impulse * sBy;
cA -= _invMassA * P;
aA -= _invIA * LA;
cB += _invMassB * P;
aB += _invIB * LB;
data.Positions[_indexA].C = cA;
data.Positions[_indexA].A = aA;
data.Positions[_indexB].C = cB;
data.Positions[_indexB].A = aB;
return Math.Abs(C) <= Settings.LinearSlop;
}
}
}
| |
using System;
using System.Threading;
using System.Threading.Tasks;
namespace Orleans.Runtime
{
/// <summary>
/// SafeTimerBase - an internal base class for implementing sync and async timers in Orleans.
///
/// </summary>
internal class SafeTimerBase : IDisposable
{
private Timer timer;
private Func<object, Task> asynTaskCallback;
private TimerCallback syncCallbackFunc;
private TimeSpan dueTime;
private TimeSpan timerFrequency;
private bool timerStarted;
private DateTime previousTickTime;
private int totalNumTicks;
private Logger logger;
internal SafeTimerBase(Func<object, Task> asynTaskCallback, object state)
{
Init(asynTaskCallback, null, state, Constants.INFINITE_TIMESPAN, Constants.INFINITE_TIMESPAN);
}
internal SafeTimerBase(Func<object, Task> asynTaskCallback, object state, TimeSpan dueTime, TimeSpan period)
{
Init(asynTaskCallback, null, state, dueTime, period);
Start(dueTime, period);
}
internal SafeTimerBase(TimerCallback syncCallback, object state)
{
Init(null, syncCallback, state, Constants.INFINITE_TIMESPAN, Constants.INFINITE_TIMESPAN);
}
internal SafeTimerBase(TimerCallback syncCallback, object state, TimeSpan dueTime, TimeSpan period)
{
Init(null, syncCallback, state, dueTime, period);
Start(dueTime, period);
}
public void Start(TimeSpan due, TimeSpan period)
{
if (timerStarted) throw new InvalidOperationException(String.Format("Calling start on timer {0} is not allowed, since it was already created in a started mode with specified due.", GetFullName()));
if (period == TimeSpan.Zero) throw new ArgumentOutOfRangeException("period", period, "Cannot use TimeSpan.Zero for timer period");
timerFrequency = period;
dueTime = due;
timerStarted = true;
previousTickTime = DateTime.UtcNow;
timer.Change(due, Constants.INFINITE_TIMESPAN);
}
private void Init(Func<object, Task> asynCallback, TimerCallback synCallback, object state, TimeSpan due, TimeSpan period)
{
if (synCallback == null && asynCallback == null) throw new ArgumentNullException("synCallback", "Cannot use null for both sync and asyncTask timer callbacks.");
int numNonNulls = (asynCallback != null ? 1 : 0) + (synCallback != null ? 1 : 0);
if (numNonNulls > 1) throw new ArgumentNullException("synCallback", "Cannot define more than one timer callbacks. Pick one.");
if (period == TimeSpan.Zero) throw new ArgumentOutOfRangeException("period", period, "Cannot use TimeSpan.Zero for timer period");
this.asynTaskCallback = asynCallback;
syncCallbackFunc = synCallback;
timerFrequency = period;
this.dueTime = due;
totalNumTicks = 0;
logger = LogManager.GetLogger(GetFullName(), LoggerType.Runtime);
if (logger.IsVerbose) logger.Verbose(ErrorCode.TimerChanging, "Creating timer {0} with dueTime={1} period={2}", GetFullName(), due, period);
timer = new Timer(HandleTimerCallback, state, Constants.INFINITE_TIMESPAN, Constants.INFINITE_TIMESPAN);
}
#region IDisposable Members
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
// Maybe called by finalizer thread with disposing=false. As per guidelines, in such a case do not touch other objects.
// Dispose() may be called multiple times
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
DisposeTimer();
}
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
internal void DisposeTimer()
{
if (timer != null)
{
try
{
var t = timer;
timer = null;
if (logger.IsVerbose) logger.Verbose(ErrorCode.TimerDisposing, "Disposing timer {0}", GetFullName());
t.Dispose();
}
catch (Exception exc)
{
logger.Warn(ErrorCode.TimerDisposeError,
string.Format("Ignored error disposing timer {0}", GetFullName()), exc);
}
}
}
#endregion
private string GetFullName()
{
// the type information is really useless and just too long.
string name;
if (syncCallbackFunc != null)
name = "sync";
else if (asynTaskCallback != null)
name = "asynTask";
else
throw new InvalidOperationException("invalid SafeTimerBase state");
return String.Format("{0}.SafeTimerBase", name);
}
public bool CheckTimerFreeze(DateTime lastCheckTime, Func<string> callerName)
{
return CheckTimerDelay(previousTickTime, totalNumTicks,
dueTime, timerFrequency, logger, () => String.Format("{0}.{1}", GetFullName(), callerName()), ErrorCode.Timer_SafeTimerIsNotTicking, true);
}
public static bool CheckTimerDelay(DateTime previousTickTime, int totalNumTicks,
TimeSpan dueTime, TimeSpan timerFrequency, Logger logger, Func<string> getName, ErrorCode errorCode, bool freezeCheck)
{
TimeSpan timeSinceLastTick = DateTime.UtcNow - previousTickTime;
TimeSpan exceptedTimeToNexTick = totalNumTicks == 0 ? dueTime : timerFrequency;
TimeSpan exceptedTimeWithSlack;
if (exceptedTimeToNexTick >= TimeSpan.FromSeconds(6))
{
exceptedTimeWithSlack = exceptedTimeToNexTick + TimeSpan.FromSeconds(3);
}
else
{
exceptedTimeWithSlack = exceptedTimeToNexTick.Multiply(1.5);
}
if (timeSinceLastTick <= exceptedTimeWithSlack) return true;
// did not tick in the last period.
var errMsg = String.Format("{0}{1} did not fire on time. Last fired at {2}, {3} since previous fire, should have fired after {4}.",
freezeCheck ? "Watchdog Freeze Alert: " : "-", // 0
getName == null ? "" : getName(), // 1
LogFormatter.PrintDate(previousTickTime), // 2
timeSinceLastTick, // 3
exceptedTimeToNexTick); // 4
if(freezeCheck)
{
logger.Error(errorCode, errMsg);
}else
{
logger.Warn(errorCode, errMsg);
}
return false;
}
/// <summary>
/// Changes the start time and the interval between method invocations for a timer, using TimeSpan values to measure time intervals.
/// </summary>
/// <param name="newDueTime">A TimeSpan representing the amount of time to delay before invoking the callback method specified when the Timer was constructed. Specify negative one (-1) milliseconds to prevent the timer from restarting. Specify zero (0) to restart the timer immediately.</param>
/// <param name="period">The time interval between invocations of the callback method specified when the Timer was constructed. Specify negative one (-1) milliseconds to disable periodic signaling.</param>
/// <returns><c>true</c> if the timer was successfully updated; otherwise, <c>false</c>.</returns>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
private bool Change(TimeSpan newDueTime, TimeSpan period)
{
if (period == TimeSpan.Zero) throw new ArgumentOutOfRangeException("period", period, string.Format("Cannot use TimeSpan.Zero for timer {0} period", GetFullName()));
if (timer == null) return false;
timerFrequency = period;
if (logger.IsVerbose) logger.Verbose(ErrorCode.TimerChanging, "Changing timer {0} to dueTime={1} period={2}", GetFullName(), newDueTime, period);
try
{
// Queue first new timer tick
return timer.Change(newDueTime, Constants.INFINITE_TIMESPAN);
}
catch (Exception exc)
{
logger.Warn(ErrorCode.TimerChangeError,
string.Format("Error changing timer period - timer {0} not changed", GetFullName()), exc);
return false;
}
}
private void HandleTimerCallback(object state)
{
if (timer == null) return;
if (asynTaskCallback != null)
{
HandleAsyncTaskTimerCallback(state);
}
else
{
HandleSyncTimerCallback(state);
}
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
private void HandleSyncTimerCallback(object state)
{
try
{
if (logger.IsVerbose3) logger.Verbose3(ErrorCode.TimerBeforeCallback, "About to make sync timer callback for timer {0}", GetFullName());
syncCallbackFunc(state);
if (logger.IsVerbose3) logger.Verbose3(ErrorCode.TimerAfterCallback, "Completed sync timer callback for timer {0}", GetFullName());
}
catch (Exception exc)
{
logger.Warn(ErrorCode.TimerCallbackError, string.Format("Ignored exception {0} during sync timer callback {1}", exc.Message, GetFullName()), exc);
}
finally
{
previousTickTime = DateTime.UtcNow;
// Queue next timer callback
QueueNextTimerTick();
}
}
private async void HandleAsyncTaskTimerCallback(object state)
{
if (timer == null) return;
// There is a subtle race/issue here w.r.t unobserved promises.
// It may happen than the asyncCallbackFunc will resolve some promises on which the higher level application code is depends upon
// and this promise's await or CW will fire before the below code (after await or Finally) even runs.
// In the unit test case this may lead to the situation where unit test has finished, but p1 or p2 or p3 have not been observed yet.
// To properly fix this we may use a mutex/monitor to delay execution of asyncCallbackFunc until all CWs and Finally in the code below were scheduled
// (not until CW lambda was run, but just until CW function itself executed).
// This however will relay on scheduler executing these in separate threads to prevent deadlock, so needs to be done carefully.
// In particular, need to make sure we execute asyncCallbackFunc in another thread (so use StartNew instead of ExecuteWithSafeTryCatch).
try
{
if (logger.IsVerbose3) logger.Verbose3(ErrorCode.TimerBeforeCallback, "About to make async task timer callback for timer {0}", GetFullName());
await asynTaskCallback(state);
if (logger.IsVerbose3) logger.Verbose3(ErrorCode.TimerAfterCallback, "Completed async task timer callback for timer {0}", GetFullName());
}
catch (Exception exc)
{
logger.Warn(ErrorCode.TimerCallbackError, string.Format("Ignored exception {0} during async task timer callback {1}", exc.Message, GetFullName()), exc);
}
finally
{
previousTickTime = DateTime.UtcNow;
// Queue next timer callback
QueueNextTimerTick();
}
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
private void QueueNextTimerTick()
{
try
{
if (timer == null) return;
totalNumTicks++;
if (logger.IsVerbose3) logger.Verbose3(ErrorCode.TimerChanging, "About to QueueNextTimerTick for timer {0}", GetFullName());
if (timerFrequency == Constants.INFINITE_TIMESPAN)
{
//timer.Change(Constants.INFINITE_TIMESPAN, Constants.INFINITE_TIMESPAN);
DisposeTimer();
if (logger.IsVerbose) logger.Verbose(ErrorCode.TimerStopped, "Timer {0} is now stopped and disposed", GetFullName());
}
else
{
timer.Change(timerFrequency, Constants.INFINITE_TIMESPAN);
if (logger.IsVerbose3) logger.Verbose3(ErrorCode.TimerNextTick, "Queued next tick for timer {0} in {1}", GetFullName(), timerFrequency);
}
}
catch (ObjectDisposedException ode)
{
logger.Warn(ErrorCode.TimerDisposeError,
string.Format("Timer {0} already disposed - will not queue next timer tick", GetFullName()), ode);
}
catch (Exception exc)
{
logger.Error(ErrorCode.TimerQueueTickError,
string.Format("Error queueing next timer tick - WARNING: timer {0} is now stopped", GetFullName()), exc);
}
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Collections.Generic;
using Xunit;
namespace System.Numerics.Matrices.Tests
{
/// <summary>
/// Tests for the Matrix2x1 structure.
/// </summary>
public class Test2x1
{
const int Epsilon = 10;
[Fact]
public void ConstructorValuesAreAccessibleByIndexer()
{
Matrix2x1 matrix2x1;
matrix2x1 = new Matrix2x1();
for (int x = 0; x < matrix2x1.Columns; x++)
{
for (int y = 0; y < matrix2x1.Rows; y++)
{
Assert.Equal(0, matrix2x1[x, y], Epsilon);
}
}
double value = 33.33;
matrix2x1 = new Matrix2x1(value);
for (int x = 0; x < matrix2x1.Columns; x++)
{
for (int y = 0; y < matrix2x1.Rows; y++)
{
Assert.Equal(value, matrix2x1[x, y], Epsilon);
}
}
GenerateFilledMatrixWithValues(out matrix2x1);
for (int y = 0; y < matrix2x1.Rows; y++)
{
for (int x = 0; x < matrix2x1.Columns; x++)
{
Assert.Equal(y * matrix2x1.Columns + x, matrix2x1[x, y], Epsilon);
}
}
}
[Fact]
public void IndexerGetAndSetValuesCorrectly()
{
Matrix2x1 matrix2x1 = new Matrix2x1();
for (int x = 0; x < matrix2x1.Columns; x++)
{
for (int y = 0; y < matrix2x1.Rows; y++)
{
matrix2x1[x, y] = y * matrix2x1.Columns + x;
}
}
for (int y = 0; y < matrix2x1.Rows; y++)
{
for (int x = 0; x < matrix2x1.Columns; x++)
{
Assert.Equal(y * matrix2x1.Columns + x, matrix2x1[x, y], Epsilon);
}
}
}
[Fact]
public void ConstantValuesAreCorrect()
{
Matrix2x1 matrix2x1 = new Matrix2x1();
Assert.Equal(2, matrix2x1.Columns);
Assert.Equal(1, matrix2x1.Rows);
Assert.Equal(Matrix2x1.ColumnCount, matrix2x1.Columns);
Assert.Equal(Matrix2x1.RowCount, matrix2x1.Rows);
}
[Fact]
public void ScalarMultiplicationIsCorrect()
{
Matrix2x1 matrix2x1;
GenerateFilledMatrixWithValues(out matrix2x1);
for (double c = -10; c <= 10; c += 0.5)
{
Matrix2x1 result = matrix2x1 * c;
for (int y = 0; y < matrix2x1.Rows; y++)
{
for (int x = 0; x < matrix2x1.Columns; x++)
{
Assert.Equal(matrix2x1[x, y] * c, result[x, y], Epsilon);
}
}
}
}
[Fact]
public void MemberGetAndSetValuesCorrectly()
{
Matrix2x1 matrix2x1 = new Matrix2x1();
matrix2x1.M11 = 0;
matrix2x1.M21 = 1;
Assert.Equal(0, matrix2x1.M11, Epsilon);
Assert.Equal(1, matrix2x1.M21, Epsilon);
Assert.Equal(matrix2x1[0, 0], matrix2x1.M11, Epsilon);
Assert.Equal(matrix2x1[1, 0], matrix2x1.M21, Epsilon);
}
[Fact]
public void HashCodeGenerationWorksCorrectly()
{
HashSet<int> hashCodes = new HashSet<int>();
Matrix2x1 value = new Matrix2x1(1);
for (int i = 2; i <= 100; i++)
{
Assert.True(hashCodes.Add(value.GetHashCode()), "Unique hash code generation failure.");
value *= i;
}
}
[Fact]
public void SimpleAdditionGeneratesCorrectValues()
{
Matrix2x1 value1 = new Matrix2x1(1);
Matrix2x1 value2 = new Matrix2x1(99);
Matrix2x1 result = value1 + value2;
for (int y = 0; y < Matrix2x1.RowCount; y++)
{
for (int x = 0; x < Matrix2x1.ColumnCount; x++)
{
Assert.Equal(1 + 99, result[x, y], Epsilon);
}
}
}
[Fact]
public void SimpleSubtractionGeneratesCorrectValues()
{
Matrix2x1 value1 = new Matrix2x1(100);
Matrix2x1 value2 = new Matrix2x1(1);
Matrix2x1 result = value1 - value2;
for (int y = 0; y < Matrix2x1.RowCount; y++)
{
for (int x = 0; x < Matrix2x1.ColumnCount; x++)
{
Assert.Equal(100 - 1, result[x, y], Epsilon);
}
}
}
[Fact]
public void EqualityOperatorWorksCorrectly()
{
Matrix2x1 value1 = new Matrix2x1(100);
Matrix2x1 value2 = new Matrix2x1(50) * 2;
Assert.Equal(value1, value2);
Assert.True(value1 == value2, "Equality operator failed.");
}
[Fact]
public void AccessorThrowsWhenOutOfBounds()
{
Matrix2x1 matrix2x1 = new Matrix2x1();
Assert.Throws<ArgumentOutOfRangeException>(() => { matrix2x1[-1, 0] = 0; });
Assert.Throws<ArgumentOutOfRangeException>(() => { matrix2x1[0, -1] = 0; });
Assert.Throws<ArgumentOutOfRangeException>(() => { matrix2x1[2, 0] = 0; });
Assert.Throws<ArgumentOutOfRangeException>(() => { matrix2x1[0, 1] = 0; });
}
[Fact]
public void MuliplyByMatrix2x2ProducesMatrix2x1()
{
Matrix2x1 matrix1 = new Matrix2x1(3);
Matrix2x2 matrix2 = new Matrix2x2(2);
Matrix2x1 result = matrix1 * matrix2;
Matrix2x1 expected = new Matrix2x1(12, 12);
Assert.Equal(expected, result);
}
[Fact]
public void MuliplyByMatrix3x2ProducesMatrix3x1()
{
Matrix2x1 matrix1 = new Matrix2x1(3);
Matrix3x2 matrix2 = new Matrix3x2(2);
Matrix3x1 result = matrix1 * matrix2;
Matrix3x1 expected = new Matrix3x1(12, 12, 12);
Assert.Equal(expected, result);
}
[Fact]
public void MuliplyByMatrix4x2ProducesMatrix4x1()
{
Matrix2x1 matrix1 = new Matrix2x1(3);
Matrix4x2 matrix2 = new Matrix4x2(2);
Matrix4x1 result = matrix1 * matrix2;
Matrix4x1 expected = new Matrix4x1(12, 12, 12, 12);
Assert.Equal(expected, result);
}
private void GenerateFilledMatrixWithValues(out Matrix2x1 matrix)
{
matrix = new Matrix2x1(0, 1);
}
}
}
| |
using UnityEngine;
using UnityEditor;
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Diagnostics;
using Debug = UnityEngine.Debug;
using Ink.Runtime;
/// <summary>
/// Holds a reference to an InkFile object for every .ink file detected in the Assets folder.
/// Provides helper functions to easily obtain these files.
/// </summary>
namespace Ink.UnityIntegration {
public class InkLibrary : ScriptableObject {
public static bool created {
get {
return _Instance != null || FindLibrary() != null;
}
}
private static InkLibrary _Instance;
public static InkLibrary Instance {
get {
if(_Instance == null)
_Instance = FindOrCreateLibrary();
return _Instance;
}
}
public const string defaultPath = "Assets/InkLibrary.asset";
public const string pathPlayerPrefsKey = "InkLibraryAssetPath";
public List<InkFile> inkLibrary = new List<InkFile>();
public List<InkCompiler.CompilationStackItem> compilationStack = new List<InkCompiler.CompilationStackItem>();
/// <summary>
/// Removes and null references in the library
/// </summary>
public static void Clean () {
for (int i = InkLibrary.Instance.inkLibrary.Count - 1; i >= 0; i--) {
InkFile inkFile = InkLibrary.Instance.inkLibrary[i];
if (inkFile.inkAsset == null)
InkLibrary.Instance.inkLibrary.RemoveAt(i);
}
}
private static InkLibrary FindLibrary () {
if(EditorPrefs.HasKey(pathPlayerPrefsKey)) {
InkLibrary library = AssetDatabase.LoadAssetAtPath<InkLibrary>(EditorPrefs.GetString(pathPlayerPrefsKey));
if(library != null) return library;
else EditorPrefs.DeleteKey(pathPlayerPrefsKey);
}
string[] GUIDs = AssetDatabase.FindAssets("t:"+typeof(InkLibrary).Name);
if(GUIDs.Length > 0) {
if(GUIDs.Length > 1) {
for(int i = 1; i < GUIDs.Length; i++) {
AssetDatabase.DeleteAsset(AssetDatabase.GUIDToAssetPath(GUIDs[i]));
}
Debug.LogWarning("More than one InkLibrary was found. Deleted excess asset instances.");
}
string path = AssetDatabase.GUIDToAssetPath(GUIDs[0]);
EditorPrefs.SetString(pathPlayerPrefsKey, path);
return AssetDatabase.LoadAssetAtPath<InkLibrary>(path);
}
return null;
}
private static InkLibrary FindOrCreateLibrary () {
InkLibrary tmpSettings = FindLibrary();
// If we couldn't find the asset in the project, create a new one.
if(tmpSettings == null) {
tmpSettings = CreateInkLibrary ();
Debug.Log("Created a new InkLibrary file at "+defaultPath+" because one was not found.");
InkLibrary.Rebuild();
}
return tmpSettings;
}
private static InkLibrary CreateInkLibrary () {
var asset = ScriptableObject.CreateInstance<InkLibrary>();
AssetDatabase.CreateAsset (asset, defaultPath);
AssetDatabase.SaveAssets ();
AssetDatabase.ImportAsset(AssetDatabase.GetAssetPath(asset));
EditorPrefs.SetString(pathPlayerPrefsKey, defaultPath);
return asset;
}
/// <summary>
/// Updates the ink library. Executed whenever an ink file is changed by InkToJSONPostProcessor
/// Can be called manually, but incurs a performance cost.
/// </summary>
public static void Rebuild () {
Debug.Log("Rebuilding Ink Library...");
string[] inkFilePaths = GetAllInkFilePaths();
List<InkFile> newInkLibrary = new List<InkFile>(inkFilePaths.Length);
for (int i = 0; i < inkFilePaths.Length; i++) {
InkFile inkFile = GetInkFileWithAbsolutePath(inkFilePaths [i]);
if(inkFile == null) {
string localAssetPath = InkEditorUtils.AbsoluteToUnityRelativePath(inkFilePaths [i]);
DefaultAsset inkFileAsset = AssetDatabase.LoadAssetAtPath<DefaultAsset>(localAssetPath);
// If the ink file can't be found, it might not yet have been imported. We try to manually import it to fix this.
if(inkFileAsset == null) {
AssetDatabase.ImportAsset(localAssetPath);
inkFileAsset = AssetDatabase.LoadAssetAtPath<DefaultAsset>(localAssetPath);
if(inkFileAsset == null) {
Debug.LogWarning("Ink File Asset not found at "+localAssetPath+". This can occur if the .meta file has not yet been created. This issue should resolve itself, but if unexpected errors occur, rebuild Ink Library using Assets > Recompile Ink");
continue;
}
}
inkFile = new InkFile(inkFileAsset);
}
newInkLibrary.Add(inkFile);
}
Instance.inkLibrary = newInkLibrary;
InkMetaLibrary.Instance.metaLibrary.Clear();
foreach (InkFile inkFile in Instance.inkLibrary) {
InkMetaLibrary.Instance.metaLibrary.Add(inkFile.metaInfo);
}
InkMetaLibrary.RebuildInkFileConnections();
foreach (InkFile inkFile in Instance.inkLibrary) {
inkFile.FindCompiledJSONAsset();
}
Save();
}
private static string[] GetAllInkFilePaths () {
string[] inkFilePaths = Directory.GetFiles(Application.dataPath, "*.ink", SearchOption.AllDirectories);
for (int i = 0; i < inkFilePaths.Length; i++) {
inkFilePaths [i] = InkEditorUtils.SanitizePathString(inkFilePaths [i]);
}
return inkFilePaths;
}
public static void Save () {
EditorUtility.SetDirty(Instance);
AssetDatabase.SaveAssets();
EditorApplication.RepaintProjectWindow();
}
public static List<InkFile> GetMasterInkFiles () {
List<InkFile> masterInkFiles = new List<InkFile>();
if(Instance.inkLibrary == null) return masterInkFiles;
foreach (InkFile inkFile in Instance.inkLibrary) {
if(inkFile.metaInfo.isMaster) {
masterInkFiles.Add(inkFile);
}
}
return masterInkFiles;
}
/// <summary>
/// Gets the ink file from the .ink file reference.
/// </summary>
/// <returns>The ink file with path.</returns>
/// <param name="path">Path.</param>
public static InkFile GetInkFileWithFile (DefaultAsset file) {
if(InkLibrary.Instance.inkLibrary == null) return null;
foreach(InkFile inkFile in InkLibrary.Instance.inkLibrary) {
if(inkFile.inkAsset == file) {
return inkFile;
}
}
return null;
}
/// <summary>
/// Gets the ink file with path relative to Assets folder, for example: "Assets/Ink/myStory.ink".
/// </summary>
/// <returns>The ink file with path.</returns>
/// <param name="path">Path.</param>
public static InkFile GetInkFileWithPath (string path) {
if(Instance.inkLibrary == null) return null;
foreach(InkFile inkFile in Instance.inkLibrary) {
if(inkFile.filePath == path) {
return inkFile;
}
}
return null;
}
/// <summary>
/// Gets the ink file with absolute path.
/// </summary>
/// <returns>The ink file with path.</returns>
/// <param name="path">Path.</param>
public static InkFile GetInkFileWithAbsolutePath (string absolutePath) {
if(InkLibrary.Instance.inkLibrary == null) return null;
foreach(InkFile inkFile in InkLibrary.Instance.inkLibrary) {
if(inkFile.absoluteFilePath == absolutePath) {
return inkFile;
}
}
return null;
}
public static List<InkCompiler.CompilationStackItem> FilesInCompilingStackInState (InkCompiler.CompilationStackItem.State state) {
List<InkCompiler.CompilationStackItem> items = new List<InkCompiler.CompilationStackItem>();
foreach(var x in Instance.compilationStack) {
if(x.state == state)
items.Add(x);
}
return items;
}
public static InkCompiler.CompilationStackItem GetCompilationStackItem (Process process) {
foreach(var x in Instance.compilationStack) {
if(x.process == process)
return x;
}
Debug.LogError("Fatal Error compiling Ink! No file found! Please report this as a bug. "+process);
return null;
}
public static InkCompiler.CompilationStackItem GetCompilationStackItem (InkFile inkFile) {
foreach(var x in Instance.compilationStack) {
if(x.inkFile == inkFile)
return x;
}
return null;
}
}
}
| |
/*
* 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.IO;
using System.Net;
using System.Text;
using HttpServer;
namespace OpenSim.Framework.Servers.HttpServer
{
/// <summary>
/// OSHttpResponse is the OpenSim representation of an HTTP
/// response.
/// </summary>
public class OSHttpResponse : IOSHttpResponse
{
/// <summary>
/// Content type property.
/// </summary>
/// <remarks>
/// Setting this property will also set IsContentTypeSet to
/// true.
/// </remarks>
public virtual string ContentType
{
get
{
return _httpResponse.ContentType;
}
set
{
_httpResponse.ContentType = value;
}
}
/// <summary>
/// Boolean property indicating whether the content type
/// property actively has been set.
/// </summary>
/// <remarks>
/// IsContentTypeSet will go away together with .NET base.
/// </remarks>
// public bool IsContentTypeSet
// {
// get { return _contentTypeSet; }
// }
// private bool _contentTypeSet;
/// <summary>
/// Length of the body content; 0 if there is no body.
/// </summary>
public long ContentLength
{
get
{
return _httpResponse.ContentLength;
}
set
{
_httpResponse.ContentLength = value;
}
}
/// <summary>
/// Alias for ContentLength.
/// </summary>
public long ContentLength64
{
get { return ContentLength; }
set { ContentLength = value; }
}
/// <summary>
/// Encoding of the body content.
/// </summary>
public Encoding ContentEncoding
{
get
{
return _httpResponse.Encoding;
}
set
{
_httpResponse.Encoding = value;
}
}
public bool KeepAlive
{
get
{
return _httpResponse.Connection == ConnectionType.KeepAlive;
}
set
{
if (value)
_httpResponse.Connection = ConnectionType.KeepAlive;
else
_httpResponse.Connection = ConnectionType.Close;
}
}
/// <summary>
/// Get or set the keep alive timeout property (default is
/// 20). Setting this to 0 also disables KeepAlive. Setting
/// this to something else but 0 also enable KeepAlive.
/// </summary>
public int KeepAliveTimeout
{
get
{
return _httpResponse.KeepAlive;
}
set
{
if (value == 0)
{
_httpResponse.Connection = ConnectionType.Close;
_httpResponse.KeepAlive = 0;
}
else
{
_httpResponse.Connection = ConnectionType.KeepAlive;
_httpResponse.KeepAlive = value;
}
}
}
/// <summary>
/// Return the output stream feeding the body.
/// </summary>
/// <remarks>
/// On its way out...
/// </remarks>
public Stream OutputStream
{
get
{
return _httpResponse.Body;
}
}
public string ProtocolVersion
{
get
{
return _httpResponse.ProtocolVersion;
}
set
{
_httpResponse.ProtocolVersion = value;
}
}
/// <summary>
/// Return the output stream feeding the body.
/// </summary>
public Stream Body
{
get
{
return _httpResponse.Body;
}
}
/// <summary>
/// Set a redirct location.
/// </summary>
public string RedirectLocation
{
// get { return _redirectLocation; }
set
{
_httpResponse.Redirect(value);
}
}
/// <summary>
/// Chunk transfers.
/// </summary>
public bool SendChunked
{
get
{
return _httpResponse.Chunked;
}
set
{
_httpResponse.Chunked = value;
}
}
/// <summary>
/// HTTP status code.
/// </summary>
public virtual int StatusCode
{
get
{
return (int)_httpResponse.Status;
}
set
{
_httpResponse.Status = (HttpStatusCode)value;
}
}
/// <summary>
/// HTTP status description.
/// </summary>
public string StatusDescription
{
get
{
return _httpResponse.Reason;
}
set
{
_httpResponse.Reason = value;
}
}
public bool ReuseContext
{
get
{
if (_httpClientContext != null)
{
return !_httpClientContext.EndWhenDone;
}
return true;
}
set
{
if (_httpClientContext != null)
{
_httpClientContext.EndWhenDone = !value;
}
}
}
protected IHttpResponse _httpResponse;
private IHttpClientContext _httpClientContext;
public OSHttpResponse() {}
public OSHttpResponse(IHttpResponse resp)
{
_httpResponse = resp;
}
/// <summary>
/// Instantiate an OSHttpResponse object from an OSHttpRequest
/// object.
/// </summary
/// <param name="req">Incoming OSHttpRequest to which we are
/// replying</param>
public OSHttpResponse(OSHttpRequest req)
{
_httpResponse = new HttpResponse(req.IHttpClientContext, req.IHttpRequest);
_httpClientContext = req.IHttpClientContext;
}
public OSHttpResponse(HttpResponse resp, IHttpClientContext clientContext)
{
_httpResponse = resp;
_httpClientContext = clientContext;
}
/// <summary>
/// Add a header field and content to the response.
/// </summary>
/// <param name="key">string containing the header field
/// name</param>
/// <param name="value">string containing the header field
/// value</param>
public void AddHeader(string key, string value)
{
_httpResponse.AddHeader(key, value);
}
/// <summary>
/// Send the response back to the remote client
/// </summary>
public void Send()
{
_httpResponse.Body.Flush();
_httpResponse.Send();
}
public void FreeContext()
{
if (_httpClientContext != null)
_httpClientContext.Close();
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeStyle;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.CodeFixes.SimplifyTypeNames;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Options;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics.SimplifyTypeNames
{
public partial class SimplifyTypeNamesTests : AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest
{
#region "Fix all occurrences tests"
[Fact]
[Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)]
[Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)]
public async Task TestFixAllInDocument()
{
var fixAllActionId = SimplifyTypeNamesCodeFixProvider.GetCodeActionId(IDEDiagnosticIds.SimplifyNamesDiagnosticId, "System.Int32");
var input = @"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true"">
<Document>
using System;
class Program
{
static System.Int32 F(System.Int32 x, System.Int16 y)
{
{|FixAllInDocument:System.Int32|} i1 = 0;
System.Int16 s1 = 0;
System.Int32 i2 = 0;
return i1 + s1 + i2;
}
}
</Document>
<Document>
using System;
class Program2
{
static System.Int32 F(System.Int32 x, System.Int16 y)
{
System.Int32 i1 = 0;
System.Int16 s1 = 0;
System.Int32 i2 = 0;
return i1 + s1 + i2;
}
}
</Document>
</Project>
<Project Language=""C#"" AssemblyName=""Assembly2"" CommonReferences=""true"">
<Document>
using System;
class Program2
{
static System.Int32 F(System.Int32 x, System.Int16 y)
{
System.Int32 i1 = 0;
System.Int16 s1 = 0;
System.Int32 i2 = 0;
return i1 + s1 + i2;
}
}
</Document>
</Project>
</Workspace>";
var expected = @"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true"">
<Document>
using System;
class Program
{
static int F(int x, System.Int16 y)
{
int i1 = 0;
System.Int16 s1 = 0;
int i2 = 0;
return i1 + s1 + i2;
}
}
</Document>
<Document>
using System;
class Program2
{
static System.Int32 F(System.Int32 x, System.Int16 y)
{
System.Int32 i1 = 0;
System.Int16 s1 = 0;
System.Int32 i2 = 0;
return i1 + s1 + i2;
}
}
</Document>
</Project>
<Project Language=""C#"" AssemblyName=""Assembly2"" CommonReferences=""true"">
<Document>
using System;
class Program2
{
static System.Int32 F(System.Int32 x, System.Int16 y)
{
System.Int32 i1 = 0;
System.Int16 s1 = 0;
System.Int32 i2 = 0;
return i1 + s1 + i2;
}
}
</Document>
</Project>
</Workspace>";
await TestAsync(input, expected, compareTokens: false, options: PreferIntrinsicTypeEverywhere, fixAllActionEquivalenceKey: fixAllActionId);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)]
[Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)]
public async Task TestFixAllInProject()
{
var fixAllActionId = SimplifyTypeNamesCodeFixProvider.GetCodeActionId(IDEDiagnosticIds.SimplifyNamesDiagnosticId, "System.Int32");
var input = @"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true"">
<Document>
using System;
class Program
{
static System.Int32 F(System.Int32 x, System.Int16 y)
{
{|FixAllInProject:System.Int32|} i1 = 0;
System.Int16 s1 = 0;
System.Int32 i2 = 0;
return i1 + s1 + i2;
}
}
</Document>
<Document>
using System;
class Program2
{
static System.Int32 F(System.Int32 x, System.Int16 y)
{
System.Int32 i1 = 0;
System.Int16 s1 = 0;
System.Int32 i2 = 0;
return i1 + s1 + i2;
}
}
</Document>
</Project>
<Project Language=""C#"" AssemblyName=""Assembly2"" CommonReferences=""true"">
<Document>
using System;
class Program2
{
static System.Int32 F(System.Int32 x, System.Int16 y)
{
System.Int32 i1 = 0;
System.Int16 s1 = 0;
System.Int32 i2 = 0;
return i1 + s1 + i2;
}
}
</Document>
</Project>
</Workspace>";
var expected = @"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true"">
<Document>
using System;
class Program
{
static int F(int x, System.Int16 y)
{
int i1 = 0;
System.Int16 s1 = 0;
int i2 = 0;
return i1 + s1 + i2;
}
}
</Document>
<Document>
using System;
class Program2
{
static int F(int x, System.Int16 y)
{
int i1 = 0;
System.Int16 s1 = 0;
int i2 = 0;
return i1 + s1 + i2;
}
}
</Document>
</Project>
<Project Language=""C#"" AssemblyName=""Assembly2"" CommonReferences=""true"">
<Document>
using System;
class Program2
{
static System.Int32 F(System.Int32 x, System.Int16 y)
{
System.Int32 i1 = 0;
System.Int16 s1 = 0;
System.Int32 i2 = 0;
return i1 + s1 + i2;
}
}
</Document>
</Project>
</Workspace>";
await TestAsync(input, expected, compareTokens: false, options: PreferIntrinsicTypeEverywhere, fixAllActionEquivalenceKey: fixAllActionId);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)]
[Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)]
public async Task TestFixAllInSolution()
{
var fixAllActionId = SimplifyTypeNamesCodeFixProvider.GetCodeActionId(IDEDiagnosticIds.SimplifyNamesDiagnosticId, "System.Int32");
var input = @"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true"">
<Document>
using System;
class Program
{
static System.Int32 F(System.Int32 x, System.Int16 y)
{
{|FixAllInSolution:System.Int32|} i1 = 0;
System.Int16 s1 = 0;
System.Int32 i2 = 0;
return i1 + s1 + i2;
}
}
</Document>
<Document>
using System;
class Program2
{
static System.Int32 F(System.Int32 x, System.Int16 y)
{
System.Int32 i1 = 0;
System.Int16 s1 = 0;
System.Int32 i2 = 0;
return i1 + s1 + i2;
}
}
</Document>
</Project>
<Project Language=""C#"" AssemblyName=""Assembly2"" CommonReferences=""true"">
<Document>
using System;
class Program2
{
static System.Int32 F(System.Int32 x, System.Int16 y)
{
System.Int32 i1 = 0;
System.Int16 s1 = 0;
System.Int32 i2 = 0;
return i1 + s1 + i2;
}
}
</Document>
</Project>
</Workspace>";
var expected = @"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true"">
<Document>
using System;
class Program
{
static int F(int x, System.Int16 y)
{
int i1 = 0;
System.Int16 s1 = 0;
int i2 = 0;
return i1 + s1 + i2;
}
}
</Document>
<Document>
using System;
class Program2
{
static int F(int x, System.Int16 y)
{
int i1 = 0;
System.Int16 s1 = 0;
int i2 = 0;
return i1 + s1 + i2;
}
}
</Document>
</Project>
<Project Language=""C#"" AssemblyName=""Assembly2"" CommonReferences=""true"">
<Document>
using System;
class Program2
{
static int F(int x, System.Int16 y)
{
int i1 = 0;
System.Int16 s1 = 0;
int i2 = 0;
return i1 + s1 + i2;
}
}
</Document>
</Project>
</Workspace>";
await TestAsync(input, expected, compareTokens: false, options:PreferIntrinsicTypeEverywhere, fixAllActionEquivalenceKey: fixAllActionId);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)]
[Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)]
public async Task TestFixAllInSolution_RemoveThis()
{
var fixAllActionId = SimplifyTypeNamesCodeFixProvider.GetCodeActionId(IDEDiagnosticIds.RemoveQualificationDiagnosticId, null);
var input = @"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true"">
<Document>
using System;
class ProgramA
{
private int x = 0;
private int y = 0;
private int z = 0;
private System.Int32 F(System.Int32 p1, System.Int16 p2)
{
System.Int32 i1 = {|FixAllInSolution:this.x|};
System.Int16 s1 = this.y;
System.Int32 i2 = this.z;
System.Console.Write(i1 + s1 + i2);
System.Console.WriteLine(i1 + s1 + i2);
System.Exception ex = null;
return i1 + s1 + i2;
}
}
class ProgramB
{
private int x2 = 0;
private int y2 = 0;
private int z2 = 0;
private System.Int32 F(System.Int32 p1, System.Int16 p2)
{
System.Int32 i1 = this.x2;
System.Int16 s1 = this.y2;
System.Int32 i2 = this.z2;
System.Console.Write(i1 + s1 + i2);
System.Console.WriteLine(i1 + s1 + i2);
System.Exception ex = null;
return i1 + s1 + i2;
}
}
</Document>
<Document>
using System;
class ProgramA2
{
private int x = 0;
private int y = 0;
private int z = 0;
private System.Int32 F(System.Int32 p1, System.Int16 p2)
{
System.Int32 i1 = this.x;
System.Int16 s1 = this.y;
System.Int32 i2 = this.z;
System.Console.Write(i1 + s1 + i2);
System.Console.WriteLine(i1 + s1 + i2);
System.Exception ex = null;
return i1 + s1 + i2;
}
}
class ProgramB2
{
private int x2 = 0;
private int y2 = 0;
private int z2 = 0;
private System.Int32 F(System.Int32 p1, System.Int16 p2)
{
System.Int32 i1 = this.x2;
System.Int16 s1 = this.y2;
System.Int32 i2 = this.z2;
System.Console.Write(i1 + s1 + i2);
System.Console.WriteLine(i1 + s1 + i2);
System.Exception ex = null;
return i1 + s1 + i2;
}
}
</Document>
</Project>
<Project Language=""C#"" AssemblyName=""Assembly2"" CommonReferences=""true"">
<Document>
using System;
class ProgramA3
{
private int x = 0;
private int y = 0;
private int z = 0;
private System.Int32 F(System.Int32 p1, System.Int16 p2)
{
System.Int32 i1 = this.x;
System.Int16 s1 = this.y;
System.Int32 i2 = this.z;
System.Console.Write(i1 + s1 + i2);
System.Console.WriteLine(i1 + s1 + i2);
System.Exception ex = null;
return i1 + s1 + i2;
}
}
class ProgramB3
{
private int x2 = 0;
private int y2 = 0;
private int z2 = 0;
private System.Int32 F(System.Int32 p1, System.Int16 p2)
{
System.Int32 i1 = this.x2;
System.Int16 s1 = this.y2;
System.Int32 i2 = this.z2;
System.Console.Write(i1 + s1 + i2);
System.Console.WriteLine(i1 + s1 + i2);
System.Exception ex = null;
return i1 + s1 + i2;
}
}
</Document>
</Project>
</Workspace>";
var expected = @"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true"">
<Document>
using System;
class ProgramA
{
private int x = 0;
private int y = 0;
private int z = 0;
private System.Int32 F(System.Int32 p1, System.Int16 p2)
{
System.Int32 i1 = x;
System.Int16 s1 = y;
System.Int32 i2 = z;
System.Console.Write(i1 + s1 + i2);
System.Console.WriteLine(i1 + s1 + i2);
System.Exception ex = null;
return i1 + s1 + i2;
}
}
class ProgramB
{
private int x2 = 0;
private int y2 = 0;
private int z2 = 0;
private System.Int32 F(System.Int32 p1, System.Int16 p2)
{
System.Int32 i1 = x2;
System.Int16 s1 = y2;
System.Int32 i2 = z2;
System.Console.Write(i1 + s1 + i2);
System.Console.WriteLine(i1 + s1 + i2);
System.Exception ex = null;
return i1 + s1 + i2;
}
}
</Document>
<Document>
using System;
class ProgramA2
{
private int x = 0;
private int y = 0;
private int z = 0;
private System.Int32 F(System.Int32 p1, System.Int16 p2)
{
System.Int32 i1 = x;
System.Int16 s1 = y;
System.Int32 i2 = z;
System.Console.Write(i1 + s1 + i2);
System.Console.WriteLine(i1 + s1 + i2);
System.Exception ex = null;
return i1 + s1 + i2;
}
}
class ProgramB2
{
private int x2 = 0;
private int y2 = 0;
private int z2 = 0;
private System.Int32 F(System.Int32 p1, System.Int16 p2)
{
System.Int32 i1 = x2;
System.Int16 s1 = y2;
System.Int32 i2 = z2;
System.Console.Write(i1 + s1 + i2);
System.Console.WriteLine(i1 + s1 + i2);
System.Exception ex = null;
return i1 + s1 + i2;
}
}
</Document>
</Project>
<Project Language=""C#"" AssemblyName=""Assembly2"" CommonReferences=""true"">
<Document>
using System;
class ProgramA3
{
private int x = 0;
private int y = 0;
private int z = 0;
private System.Int32 F(System.Int32 p1, System.Int16 p2)
{
System.Int32 i1 = x;
System.Int16 s1 = y;
System.Int32 i2 = z;
System.Console.Write(i1 + s1 + i2);
System.Console.WriteLine(i1 + s1 + i2);
System.Exception ex = null;
return i1 + s1 + i2;
}
}
class ProgramB3
{
private int x2 = 0;
private int y2 = 0;
private int z2 = 0;
private System.Int32 F(System.Int32 p1, System.Int16 p2)
{
System.Int32 i1 = x2;
System.Int16 s1 = y2;
System.Int32 i2 = z2;
System.Console.Write(i1 + s1 + i2);
System.Console.WriteLine(i1 + s1 + i2);
System.Exception ex = null;
return i1 + s1 + i2;
}
}
</Document>
</Project>
</Workspace>";
await TestAsync(input, expected, compareTokens: false, fixAllActionEquivalenceKey: fixAllActionId);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.CodeActionsSimplifyTypeNames)]
[Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)]
public async Task TestFixAllInSolution_SimplifyMemberAccess()
{
var fixAllActionId = SimplifyTypeNamesCodeFixProvider.GetCodeActionId(IDEDiagnosticIds.SimplifyMemberAccessDiagnosticId, "System.Console");
var input = @"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true"">
<Document>
using System;
class ProgramA
{
private int x = 0;
private int y = 0;
private int z = 0;
private System.Int32 F(System.Int32 p1, System.Int16 p2)
{
System.Int32 i1 = this.x;
System.Int16 s1 = this.y;
System.Int32 i2 = this.z;
{|FixAllInSolution:System.Console.Write|}(i1 + s1 + i2);
System.Console.WriteLine(i1 + s1 + i2);
System.Exception ex = null;
return i1 + s1 + i2;
}
}
class ProgramB
{
private int x2 = 0;
private int y2 = 0;
private int z2 = 0;
private System.Int32 F(System.Int32 p1, System.Int16 p2)
{
System.Int32 i1 = this.x2;
System.Int16 s1 = this.y2;
System.Int32 i2 = this.z2;
System.Console.Write(i1 + s1 + i2);
System.Console.WriteLine(i1 + s1 + i2);
System.Exception ex = null;
return i1 + s1 + i2;
}
}
</Document>
<Document>
using System;
class ProgramA2
{
private int x = 0;
private int y = 0;
private int z = 0;
private System.Int32 F(System.Int32 p1, System.Int16 p2)
{
System.Int32 i1 = this.x;
System.Int16 s1 = this.y;
System.Int32 i2 = this.z;
System.Console.Write(i1 + s1 + i2);
System.Console.WriteLine(i1 + s1 + i2);
System.Exception ex = null;
return i1 + s1 + i2;
}
}
class ProgramB2
{
private int x2 = 0;
private int y2 = 0;
private int z2 = 0;
private System.Int32 F(System.Int32 p1, System.Int16 p2)
{
System.Int32 i1 = this.x2;
System.Int16 s1 = this.y2;
System.Int32 i2 = this.z2;
System.Console.Write(i1 + s1 + i2);
System.Console.WriteLine(i1 + s1 + i2);
System.Exception ex = null;
return i1 + s1 + i2;
}
}
</Document>
</Project>
<Project Language=""C#"" AssemblyName=""Assembly2"" CommonReferences=""true"">
<Document>
using System;
class ProgramA3
{
private int x = 0;
private int y = 0;
private int z = 0;
private System.Int32 F(System.Int32 p1, System.Int16 p2)
{
System.Int32 i1 = this.x;
System.Int16 s1 = this.y;
System.Int32 i2 = this.z;
System.Console.Write(i1 + s1 + i2);
System.Console.WriteLine(i1 + s1 + i2);
System.Exception ex = null;
return i1 + s1 + i2;
}
}
class ProgramB3
{
private int x2 = 0;
private int y2 = 0;
private int z2 = 0;
private System.Int32 F(System.Int32 p1, System.Int16 p2)
{
System.Int32 i1 = this.x2;
System.Int16 s1 = this.y2;
System.Int32 i2 = this.z2;
System.Console.Write(i1 + s1 + i2);
System.Console.WriteLine(i1 + s1 + i2);
System.Exception ex = null;
return i1 + s1 + i2;
}
}
</Document>
</Project>
</Workspace>";
var expected = @"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true"">
<Document>
using System;
class ProgramA
{
private int x = 0;
private int y = 0;
private int z = 0;
private System.Int32 F(System.Int32 p1, System.Int16 p2)
{
System.Int32 i1 = this.x;
System.Int16 s1 = this.y;
System.Int32 i2 = this.z;
Console.Write(i1 + s1 + i2);
Console.WriteLine(i1 + s1 + i2);
System.Exception ex = null;
return i1 + s1 + i2;
}
}
class ProgramB
{
private int x2 = 0;
private int y2 = 0;
private int z2 = 0;
private System.Int32 F(System.Int32 p1, System.Int16 p2)
{
System.Int32 i1 = this.x2;
System.Int16 s1 = this.y2;
System.Int32 i2 = this.z2;
Console.Write(i1 + s1 + i2);
Console.WriteLine(i1 + s1 + i2);
System.Exception ex = null;
return i1 + s1 + i2;
}
}
</Document>
<Document>
using System;
class ProgramA2
{
private int x = 0;
private int y = 0;
private int z = 0;
private System.Int32 F(System.Int32 p1, System.Int16 p2)
{
System.Int32 i1 = this.x;
System.Int16 s1 = this.y;
System.Int32 i2 = this.z;
Console.Write(i1 + s1 + i2);
Console.WriteLine(i1 + s1 + i2);
System.Exception ex = null;
return i1 + s1 + i2;
}
}
class ProgramB2
{
private int x2 = 0;
private int y2 = 0;
private int z2 = 0;
private System.Int32 F(System.Int32 p1, System.Int16 p2)
{
System.Int32 i1 = this.x2;
System.Int16 s1 = this.y2;
System.Int32 i2 = this.z2;
Console.Write(i1 + s1 + i2);
Console.WriteLine(i1 + s1 + i2);
System.Exception ex = null;
return i1 + s1 + i2;
}
}
</Document>
</Project>
<Project Language=""C#"" AssemblyName=""Assembly2"" CommonReferences=""true"">
<Document>
using System;
class ProgramA3
{
private int x = 0;
private int y = 0;
private int z = 0;
private System.Int32 F(System.Int32 p1, System.Int16 p2)
{
System.Int32 i1 = this.x;
System.Int16 s1 = this.y;
System.Int32 i2 = this.z;
Console.Write(i1 + s1 + i2);
Console.WriteLine(i1 + s1 + i2);
System.Exception ex = null;
return i1 + s1 + i2;
}
}
class ProgramB3
{
private int x2 = 0;
private int y2 = 0;
private int z2 = 0;
private System.Int32 F(System.Int32 p1, System.Int16 p2)
{
System.Int32 i1 = this.x2;
System.Int16 s1 = this.y2;
System.Int32 i2 = this.z2;
Console.Write(i1 + s1 + i2);
Console.WriteLine(i1 + s1 + i2);
System.Exception ex = null;
return i1 + s1 + i2;
}
}
</Document>
</Project>
</Workspace>";
await TestAsync(input, expected, compareTokens: false, fixAllActionEquivalenceKey: fixAllActionId);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.CodeActionsQualifyMemberAccess)]
[Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)]
public async Task TestFixAllInSolution_RemoveMemberAccessQualification()
{
var input = @"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true"">
<Document>
using System;
class C
{
int Property { get; set; }
int OtherProperty { get; set; }
void M()
{
{|FixAllInSolution:this.Property|} = 1;
var x = this.OtherProperty;
}
}
</Document>
<Document>
using System;
class D
{
string StringProperty { get; set; }
int field;
void N()
{
this.StringProperty = string.Empty;
this.field = 0; // ensure qualification isn't removed
}
}
</Document>
</Project>
</Workspace>";
var expected = @"
<Workspace>
<Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true"">
<Document>
using System;
class C
{
int Property { get; set; }
int OtherProperty { get; set; }
void M()
{
Property = 1;
var x = OtherProperty;
}
}
</Document>
<Document>
using System;
class D
{
string StringProperty { get; set; }
int field;
void N()
{
StringProperty = string.Empty;
this.field = 0; // ensure qualification isn't removed
}
}
</Document>
</Project>
</Workspace>";
var options = OptionsSet(
SingleOption(CodeStyleOptions.QualifyPropertyAccess, false, NotificationOption.Suggestion),
SingleOption(CodeStyleOptions.QualifyFieldAccess, true, NotificationOption.Suggestion));
await TestAsync(
initialMarkup: input,
expectedMarkup: expected,
options: options,
compareTokens: false,
fixAllActionEquivalenceKey: CSharpFeaturesResources.Remove_this_qualification);
}
#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.
/*============================================================
**
**
**
**
** Purpose: Provides a fast, AV free, cross-language way of
** accessing unmanaged memory in a random fashion.
**
**
===========================================================*/
using System;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
using System.Runtime.ConstrainedExecution;
using System.Runtime.Versioning;
using Microsoft.Win32.SafeHandles;
using System.Diagnostics;
namespace System.IO
{
/// Perf notes: ReadXXX, WriteXXX (for basic types) acquire and release the
/// SafeBuffer pointer rather than relying on generic Read(T) from SafeBuffer because
/// this gives better throughput; benchmarks showed about 12-15% better.
public class UnmanagedMemoryAccessor : IDisposable
{
private SafeBuffer _buffer;
private Int64 _offset;
private Int64 _capacity;
private FileAccess _access;
private bool _isOpen;
private bool _canRead;
private bool _canWrite;
protected UnmanagedMemoryAccessor()
{
_isOpen = false;
}
#region SafeBuffer ctors and initializers
// <SecurityKernel Critical="True" Ring="1">
// <ReferencesCritical Name="Method: Initialize(SafeBuffer, Int64, Int64, FileAccess):Void" Ring="1" />
// </SecurityKernel>
public UnmanagedMemoryAccessor(SafeBuffer buffer, Int64 offset, Int64 capacity)
{
Initialize(buffer, offset, capacity, FileAccess.Read);
}
public UnmanagedMemoryAccessor(SafeBuffer buffer, Int64 offset, Int64 capacity, FileAccess access)
{
Initialize(buffer, offset, capacity, access);
}
protected void Initialize(SafeBuffer buffer, Int64 offset, Int64 capacity, FileAccess access)
{
if (buffer == null)
{
throw new ArgumentNullException(nameof(buffer));
}
if (offset < 0)
{
throw new ArgumentOutOfRangeException(nameof(offset), SR.ArgumentOutOfRange_NeedNonNegNum);
}
if (capacity < 0)
{
throw new ArgumentOutOfRangeException(nameof(capacity), SR.ArgumentOutOfRange_NeedNonNegNum);
}
if (buffer.ByteLength < (UInt64)(offset + capacity))
{
throw new ArgumentException(SR.Argument_OffsetAndCapacityOutOfBounds);
}
if (access < FileAccess.Read || access > FileAccess.ReadWrite)
{
throw new ArgumentOutOfRangeException(nameof(access));
}
if (_isOpen)
{
throw new InvalidOperationException(SR.InvalidOperation_CalledTwice);
}
unsafe
{
byte* pointer = null;
RuntimeHelpers.PrepareConstrainedRegions();
try
{
buffer.AcquirePointer(ref pointer);
if (((byte*)((Int64)pointer + offset + capacity)) < pointer)
{
throw new ArgumentException(SR.Argument_UnmanagedMemAccessorWrapAround);
}
}
finally
{
if (pointer != null)
{
buffer.ReleasePointer();
}
}
}
_offset = offset;
_buffer = buffer;
_capacity = capacity;
_access = access;
_isOpen = true;
_canRead = (_access & FileAccess.Read) != 0;
_canWrite = (_access & FileAccess.Write) != 0;
}
#endregion
public Int64 Capacity
{
get
{
return _capacity;
}
}
public bool CanRead
{
get
{
return _isOpen && _canRead;
}
}
public bool CanWrite
{
get
{
return _isOpen && _canWrite;
}
}
protected virtual void Dispose(bool disposing)
{
_isOpen = false;
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected bool IsOpen
{
get { return _isOpen; }
}
public bool ReadBoolean(Int64 position)
{
int sizeOfType = sizeof(bool);
EnsureSafeToRead(position, sizeOfType);
byte b = InternalReadByte(position);
return b != 0;
}
public byte ReadByte(Int64 position)
{
int sizeOfType = sizeof(byte);
EnsureSafeToRead(position, sizeOfType);
return InternalReadByte(position);
}
public char ReadChar(Int64 position)
{
EnsureSafeToRead(position, sizeof(char));
char result;
unsafe
{
byte* pointer = null;
RuntimeHelpers.PrepareConstrainedRegions();
try
{
_buffer.AcquirePointer(ref pointer);
result = Unsafe.ReadUnaligned<char>(pointer + _offset + position);
}
finally
{
if (pointer != null)
{
_buffer.ReleasePointer();
}
}
}
return result;
}
// See comment above.
public Int16 ReadInt16(Int64 position)
{
EnsureSafeToRead(position, sizeof(Int16));
Int16 result;
unsafe
{
byte* pointer = null;
RuntimeHelpers.PrepareConstrainedRegions();
try
{
_buffer.AcquirePointer(ref pointer);
result = Unsafe.ReadUnaligned<Int16>(pointer + _offset + position);
}
finally
{
if (pointer != null)
{
_buffer.ReleasePointer();
}
}
}
return result;
}
public Int32 ReadInt32(Int64 position)
{
EnsureSafeToRead(position, sizeof(Int32));
Int32 result;
unsafe
{
byte* pointer = null;
RuntimeHelpers.PrepareConstrainedRegions();
try
{
_buffer.AcquirePointer(ref pointer);
result = Unsafe.ReadUnaligned<Int32>(pointer + _offset + position);
}
finally
{
if (pointer != null)
{
_buffer.ReleasePointer();
}
}
}
return result;
}
public Int64 ReadInt64(Int64 position)
{
EnsureSafeToRead(position, sizeof(Int64));
Int64 result;
unsafe
{
byte* pointer = null;
RuntimeHelpers.PrepareConstrainedRegions();
try
{
_buffer.AcquirePointer(ref pointer);
result = Unsafe.ReadUnaligned<Int64>(pointer + _offset + position);
}
finally
{
if (pointer != null)
{
_buffer.ReleasePointer();
}
}
}
return result;
}
public Decimal ReadDecimal(Int64 position)
{
const int ScaleMask = 0x00FF0000;
const int SignMask = unchecked((int)0x80000000);
EnsureSafeToRead(position, sizeof(Decimal));
int lo, mid, hi, flags;
unsafe
{
byte* pointer = null;
try
{
_buffer.AcquirePointer(ref pointer);
lo = Unsafe.ReadUnaligned<Int32>(pointer + _offset + position);
mid = Unsafe.ReadUnaligned<Int32>(pointer + _offset + position + 4);
hi = Unsafe.ReadUnaligned<Int32>(pointer + _offset + position + 8);
flags = Unsafe.ReadUnaligned<Int32>(pointer + _offset + position + 12);
}
finally
{
if (pointer != null)
{
_buffer.ReleasePointer();
}
}
}
// Check for invalid Decimal values
if (!((flags & ~(SignMask | ScaleMask)) == 0 && (flags & ScaleMask) <= (28 << 16)))
{
throw new ArgumentException(SR.Arg_BadDecimal); // Throw same Exception type as Decimal(int[]) ctor for compat
}
bool isNegative = (flags & SignMask) != 0;
byte scale = (byte)(flags >> 16);
return new decimal(lo, mid, hi, isNegative, scale);
}
public Single ReadSingle(Int64 position)
{
EnsureSafeToRead(position, sizeof(Single));
Single result;
unsafe
{
byte* pointer = null;
RuntimeHelpers.PrepareConstrainedRegions();
try
{
_buffer.AcquirePointer(ref pointer);
result = Unsafe.ReadUnaligned<Single>(pointer + _offset + position);
}
finally
{
if (pointer != null)
{
_buffer.ReleasePointer();
}
}
}
return result;
}
public Double ReadDouble(Int64 position)
{
EnsureSafeToRead(position, sizeof(Double));
Double result;
unsafe
{
byte* pointer = null;
RuntimeHelpers.PrepareConstrainedRegions();
try
{
_buffer.AcquirePointer(ref pointer);
result = Unsafe.ReadUnaligned<Double>(pointer + _offset + position);
}
finally
{
if (pointer != null)
{
_buffer.ReleasePointer();
}
}
}
return result;
}
[CLSCompliant(false)]
public SByte ReadSByte(Int64 position)
{
int sizeOfType = sizeof(SByte);
EnsureSafeToRead(position, sizeOfType);
SByte result;
unsafe
{
byte* pointer = null;
RuntimeHelpers.PrepareConstrainedRegions();
try
{
_buffer.AcquirePointer(ref pointer);
result = *((SByte*)(pointer + _offset + position));
}
finally
{
if (pointer != null)
{
_buffer.ReleasePointer();
}
}
}
return result;
}
[CLSCompliant(false)]
public UInt16 ReadUInt16(Int64 position)
{
EnsureSafeToRead(position, sizeof(UInt16));
UInt16 result;
unsafe
{
byte* pointer = null;
RuntimeHelpers.PrepareConstrainedRegions();
try
{
_buffer.AcquirePointer(ref pointer);
result = Unsafe.ReadUnaligned<UInt16>(pointer + _offset + position);
}
finally
{
if (pointer != null)
{
_buffer.ReleasePointer();
}
}
}
return result;
}
[CLSCompliant(false)]
public UInt32 ReadUInt32(Int64 position)
{
EnsureSafeToRead(position, sizeof(UInt32));
UInt32 result;
unsafe
{
byte* pointer = null;
RuntimeHelpers.PrepareConstrainedRegions();
try
{
_buffer.AcquirePointer(ref pointer);
result = Unsafe.ReadUnaligned<UInt32>(pointer + _offset + position);
}
finally
{
if (pointer != null)
{
_buffer.ReleasePointer();
}
}
}
return result;
}
[CLSCompliant(false)]
public UInt64 ReadUInt64(Int64 position)
{
EnsureSafeToRead(position, sizeof(UInt64));
UInt64 result;
unsafe
{
byte* pointer = null;
RuntimeHelpers.PrepareConstrainedRegions();
try
{
_buffer.AcquirePointer(ref pointer);
result = Unsafe.ReadUnaligned<UInt64>(pointer + _offset + position);
}
finally
{
if (pointer != null)
{
_buffer.ReleasePointer();
}
}
}
return result;
}
// Reads a struct of type T from unmanaged memory, into the reference pointed to by ref value.
// Note: this method is not safe, since it overwrites the contents of a structure, it can be
// used to modify the private members of a struct. Furthermore, using this with a struct that
// contains reference members will most likely cause the runtime to AV. Note, that despite
// various checks made by the C++ code used by Marshal.PtrToStructure, Marshal.PtrToStructure
// will still overwrite privates and will also crash the runtime when used with structs
// containing reference members. For this reason, I am sticking an UnmanagedCode requirement
// on this method to match Marshal.PtrToStructure.
// Alos note that this method is most performant when used with medium to large sized structs
// (larger than 8 bytes -- though this is number is JIT and architecture dependent). As
// such, it is best to use the ReadXXX methods for small standard types such as ints, longs,
// bools, etc.
public void Read<T>(Int64 position, out T structure) where T : struct
{
if (position < 0)
{
throw new ArgumentOutOfRangeException(nameof(position), SR.ArgumentOutOfRange_NeedNonNegNum);
}
if (!_isOpen)
{
throw new ObjectDisposedException("UnmanagedMemoryAccessor", SR.ObjectDisposed_ViewAccessorClosed);
}
if (!CanRead)
{
throw new NotSupportedException(SR.NotSupported_Reading);
}
UInt32 sizeOfT = Marshal.SizeOfType(typeof(T));
if (position > _capacity - sizeOfT)
{
if (position >= _capacity)
{
throw new ArgumentOutOfRangeException(nameof(position), SR.ArgumentOutOfRange_PositionLessThanCapacityRequired);
}
else
{
throw new ArgumentException(SR.Format(SR.Argument_NotEnoughBytesToRead, typeof (T).FullName), nameof(position));
}
}
structure = _buffer.Read<T>((UInt64)(_offset + position));
}
// Reads 'count' structs of type T from unmanaged memory, into 'array' starting at 'offset'.
// Note: this method is not safe, since it overwrites the contents of structures, it can
// be used to modify the private members of a struct. Furthermore, using this with a
// struct that contains reference members will most likely cause the runtime to AV. This
// is consistent with Marshal.PtrToStructure.
public int ReadArray<T>(Int64 position, T[] array, Int32 offset, Int32 count) where T : struct
{
if (array == null)
{
throw new ArgumentNullException(nameof(array), "Buffer cannot be null.");
}
if (offset < 0)
{
throw new ArgumentOutOfRangeException(nameof(offset), SR.ArgumentOutOfRange_NeedNonNegNum);
}
if (count < 0)
{
throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum);
}
if (array.Length - offset < count)
{
throw new ArgumentException(SR.Argument_OffsetAndLengthOutOfBounds);
}
if (!CanRead)
{
if (!_isOpen)
{
throw new ObjectDisposedException("UnmanagedMemoryAccessor", SR.ObjectDisposed_ViewAccessorClosed);
}
else
{
throw new NotSupportedException(SR.NotSupported_Reading);
}
}
if (position < 0)
{
throw new ArgumentOutOfRangeException(nameof(position), SR.ArgumentOutOfRange_NeedNonNegNum);
}
UInt32 sizeOfT = Marshal.AlignedSizeOf<T>();
// only check position and ask for fewer Ts if count is too big
if (position >= _capacity)
{
throw new ArgumentOutOfRangeException(nameof(position), SR.ArgumentOutOfRange_PositionLessThanCapacityRequired);
}
int n = count;
long spaceLeft = _capacity - position;
if (spaceLeft < 0)
{
n = 0;
}
else
{
ulong spaceNeeded = (ulong)(sizeOfT * count);
if ((ulong)spaceLeft < spaceNeeded)
{
n = (int)(spaceLeft / sizeOfT);
}
}
_buffer.ReadArray<T>((UInt64)(_offset + position), array, offset, n);
return n;
}
// ************** Write Methods ****************/
// The following 13 WriteXXX methods write a value of type XXX into unmanaged memory at 'positon'.
// The bounds of the unmanaged memory are checked against to ensure that there is enough
// space after 'position' to write a value of type XXX. XXX can be a bool, byte, char, decimal,
// double, short, int, long, sbyte, float, ushort, uint, or ulong.
public void Write(Int64 position, bool value)
{
int sizeOfType = sizeof(bool);
EnsureSafeToWrite(position, sizeOfType);
byte b = (byte)(value ? 1 : 0);
InternalWrite(position, b);
}
public void Write(Int64 position, byte value)
{
int sizeOfType = sizeof(byte);
EnsureSafeToWrite(position, sizeOfType);
InternalWrite(position, value);
}
public void Write(Int64 position, char value)
{
EnsureSafeToWrite(position, sizeof(char));
unsafe
{
byte* pointer = null;
RuntimeHelpers.PrepareConstrainedRegions();
try
{
_buffer.AcquirePointer(ref pointer);
Unsafe.WriteUnaligned<char>(pointer + _offset + position, value);
}
finally
{
if (pointer != null)
{
_buffer.ReleasePointer();
}
}
}
}
public void Write(Int64 position, Int16 value)
{
EnsureSafeToWrite(position, sizeof(Int16));
unsafe
{
byte* pointer = null;
RuntimeHelpers.PrepareConstrainedRegions();
try
{
_buffer.AcquirePointer(ref pointer);
Unsafe.WriteUnaligned<Int16>(pointer + _offset + position, value);
}
finally
{
if (pointer != null)
{
_buffer.ReleasePointer();
}
}
}
}
public void Write(Int64 position, Int32 value)
{
EnsureSafeToWrite(position, sizeof(Int32));
unsafe
{
byte* pointer = null;
RuntimeHelpers.PrepareConstrainedRegions();
try
{
_buffer.AcquirePointer(ref pointer);
Unsafe.WriteUnaligned<Int32>(pointer + _offset + position, value);
}
finally
{
if (pointer != null)
{
_buffer.ReleasePointer();
}
}
}
}
public void Write(Int64 position, Int64 value)
{
EnsureSafeToWrite(position, sizeof(Int64));
unsafe
{
byte* pointer = null;
RuntimeHelpers.PrepareConstrainedRegions();
try
{
_buffer.AcquirePointer(ref pointer);
Unsafe.WriteUnaligned<Int64>(pointer + _offset + position, value);
}
finally
{
if (pointer != null)
{
_buffer.ReleasePointer();
}
}
}
}
public void Write(Int64 position, Decimal value)
{
EnsureSafeToWrite(position, sizeof(Decimal));
unsafe
{
int* valuePtr = (int*)(&value);
int flags = *valuePtr;
int hi = *(valuePtr + 1);
int lo = *(valuePtr + 2);
int mid = *(valuePtr + 3);
byte* pointer = null;
try
{
_buffer.AcquirePointer(ref pointer);
Unsafe.WriteUnaligned<Int32>(pointer + _offset + position, lo);
Unsafe.WriteUnaligned<Int32>(pointer + _offset + position + 4, mid);
Unsafe.WriteUnaligned<Int32>(pointer + _offset + position + 8, hi);
Unsafe.WriteUnaligned<Int32>(pointer + _offset + position + 12, flags);
}
finally
{
if (pointer != null)
{
_buffer.ReleasePointer();
}
}
}
}
public void Write(Int64 position, Single value)
{
EnsureSafeToWrite(position, sizeof(Single));
unsafe
{
byte* pointer = null;
RuntimeHelpers.PrepareConstrainedRegions();
try
{
_buffer.AcquirePointer(ref pointer);
Unsafe.WriteUnaligned<Single>(pointer + _offset + position, value);
}
finally
{
if (pointer != null)
{
_buffer.ReleasePointer();
}
}
}
}
public void Write(Int64 position, Double value)
{
EnsureSafeToWrite(position, sizeof(Double));
unsafe
{
byte* pointer = null;
RuntimeHelpers.PrepareConstrainedRegions();
try
{
_buffer.AcquirePointer(ref pointer);
Unsafe.WriteUnaligned<Double>(pointer + _offset + position, value);
}
finally
{
if (pointer != null)
{
_buffer.ReleasePointer();
}
}
}
}
[CLSCompliant(false)]
public void Write(Int64 position, SByte value)
{
EnsureSafeToWrite(position, sizeof(SByte));
unsafe
{
byte* pointer = null;
RuntimeHelpers.PrepareConstrainedRegions();
try
{
_buffer.AcquirePointer(ref pointer);
*((SByte*)(pointer + _offset + position)) = value;
}
finally
{
if (pointer != null)
{
_buffer.ReleasePointer();
}
}
}
}
[CLSCompliant(false)]
public void Write(Int64 position, UInt16 value)
{
int sizeOfType = sizeof(UInt16);
EnsureSafeToWrite(position, sizeOfType);
unsafe
{
byte* pointer = null;
RuntimeHelpers.PrepareConstrainedRegions();
try
{
_buffer.AcquirePointer(ref pointer);
Unsafe.WriteUnaligned<UInt16>(pointer + _offset + position, value);
}
finally
{
if (pointer != null)
{
_buffer.ReleasePointer();
}
}
}
}
[CLSCompliant(false)]
public void Write(Int64 position, UInt32 value)
{
EnsureSafeToWrite(position, sizeof(UInt32));
unsafe
{
byte* pointer = null;
RuntimeHelpers.PrepareConstrainedRegions();
try
{
_buffer.AcquirePointer(ref pointer);
Unsafe.WriteUnaligned<UInt32>(pointer + _offset + position, value);
}
finally
{
if (pointer != null)
{
_buffer.ReleasePointer();
}
}
}
}
[CLSCompliant(false)]
public void Write(Int64 position, UInt64 value)
{
EnsureSafeToWrite(position, sizeof(UInt64));
unsafe
{
byte* pointer = null;
RuntimeHelpers.PrepareConstrainedRegions();
try
{
_buffer.AcquirePointer(ref pointer);
Unsafe.WriteUnaligned<UInt64>(pointer + _offset + position, value);
}
finally
{
if (pointer != null)
{
_buffer.ReleasePointer();
}
}
}
}
// Writes the struct pointed to by ref value into unmanaged memory. Note that this method
// is most performant when used with medium to large sized structs (larger than 8 bytes
// though this is number is JIT and architecture dependent). As such, it is best to use
// the WriteX methods for small standard types such as ints, longs, bools, etc.
public void Write<T>(Int64 position, ref T structure) where T : struct
{
if (position < 0)
{
throw new ArgumentOutOfRangeException(nameof(position), SR.ArgumentOutOfRange_NeedNonNegNum);
}
if (!_isOpen)
{
throw new ObjectDisposedException("UnmanagedMemoryAccessor", SR.ObjectDisposed_ViewAccessorClosed);
}
if (!CanWrite)
{
throw new NotSupportedException(SR.NotSupported_Writing);
}
UInt32 sizeOfT = Marshal.SizeOfType(typeof(T));
if (position > _capacity - sizeOfT)
{
if (position >= _capacity)
{
throw new ArgumentOutOfRangeException(nameof(position), SR.ArgumentOutOfRange_PositionLessThanCapacityRequired);
}
else
{
throw new ArgumentException(SR.Format(SR.Argument_NotEnoughBytesToWrite, typeof (T).FullName), nameof(position));
}
}
_buffer.Write<T>((UInt64)(_offset + position), structure);
}
// Writes 'count' structs of type T from 'array' (starting at 'offset') into unmanaged memory.
public void WriteArray<T>(Int64 position, T[] array, Int32 offset, Int32 count) where T : struct
{
if (array == null)
{
throw new ArgumentNullException(nameof(array), "Buffer cannot be null.");
}
if (offset < 0)
{
throw new ArgumentOutOfRangeException(nameof(offset), SR.ArgumentOutOfRange_NeedNonNegNum);
}
if (count < 0)
{
throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum);
}
if (array.Length - offset < count)
{
throw new ArgumentException(SR.Argument_OffsetAndLengthOutOfBounds);
}
if (position < 0)
{
throw new ArgumentOutOfRangeException(nameof(position), SR.ArgumentOutOfRange_NeedNonNegNum);
}
if (position >= Capacity)
{
throw new ArgumentOutOfRangeException(nameof(position), SR.ArgumentOutOfRange_PositionLessThanCapacityRequired);
}
if (!_isOpen)
{
throw new ObjectDisposedException("UnmanagedMemoryAccessor", SR.ObjectDisposed_ViewAccessorClosed);
}
if (!CanWrite)
{
throw new NotSupportedException(SR.NotSupported_Writing);
}
_buffer.WriteArray<T>((UInt64)(_offset + position), array, offset, count);
}
private byte InternalReadByte(Int64 position)
{
Debug.Assert(CanRead, "UMA not readable");
Debug.Assert(position >= 0, "position less than 0");
Debug.Assert(position <= _capacity - sizeof(byte), "position is greater than capacity - sizeof(byte)");
byte result;
unsafe
{
byte* pointer = null;
RuntimeHelpers.PrepareConstrainedRegions();
try
{
_buffer.AcquirePointer(ref pointer);
result = *(pointer + _offset + position);
}
finally
{
if (pointer != null)
{
_buffer.ReleasePointer();
}
}
}
return result;
}
private void InternalWrite(Int64 position, byte value)
{
Debug.Assert(CanWrite, "UMA not writable");
Debug.Assert(position >= 0, "position less than 0");
Debug.Assert(position <= _capacity - sizeof(byte), "position is greater than capacity - sizeof(byte)");
unsafe
{
byte* pointer = null;
RuntimeHelpers.PrepareConstrainedRegions();
try
{
_buffer.AcquirePointer(ref pointer);
*(pointer + _offset + position) = value;
}
finally
{
if (pointer != null)
{
_buffer.ReleasePointer();
}
}
}
}
private void EnsureSafeToRead(Int64 position, int sizeOfType)
{
if (!_isOpen)
{
throw new ObjectDisposedException("UnmanagedMemoryAccessor", SR.ObjectDisposed_ViewAccessorClosed);
}
if (!CanRead)
{
throw new NotSupportedException(SR.NotSupported_Reading);
}
if (position < 0)
{
throw new ArgumentOutOfRangeException(nameof(position), SR.ArgumentOutOfRange_NeedNonNegNum);
}
if (position > _capacity - sizeOfType)
{
if (position >= _capacity)
{
throw new ArgumentOutOfRangeException(nameof(position), SR.ArgumentOutOfRange_PositionLessThanCapacityRequired);
}
else
{
throw new ArgumentException(SR.Argument_NotEnoughBytesToRead, nameof(position));
}
}
}
private void EnsureSafeToWrite(Int64 position, int sizeOfType)
{
if (!_isOpen)
{
throw new ObjectDisposedException("UnmanagedMemoryAccessor", SR.ObjectDisposed_ViewAccessorClosed);
}
if (!CanWrite)
{
throw new NotSupportedException(SR.NotSupported_Writing);
}
if (position < 0)
{
throw new ArgumentOutOfRangeException(nameof(position), SR.ArgumentOutOfRange_NeedNonNegNum);
}
if (position > _capacity - sizeOfType)
{
if (position >= _capacity)
{
throw new ArgumentOutOfRangeException(nameof(position), SR.ArgumentOutOfRange_PositionLessThanCapacityRequired);
}
else
{
throw new ArgumentException(SR.Format(SR.Argument_NotEnoughBytesToWrite, nameof(Byte)), nameof(position));
}
}
}
}
}
| |
using System;
using System.Diagnostics;
using System.Threading;
namespace Community.CsharpSqlite
{
public partial class Sqlite3
{
/*
** 2008 October 07
**
** The author disclaims copyright to this source code. In place of
** a legal notice, here is a blessing:
**
** May you do good and not evil.
** May you find forgiveness for yourself and forgive others.
** May you share freely, never taking more than you give.
**
*************************************************************************
** This file contains the C functions that implement mutexes.
**
** This implementation in this file does not provide any mutual
** exclusion and is thus suitable for use only in applications
** that use SQLite in a single thread. The routines defined
** here are place-holders. Applications can substitute working
** mutex routines at start-time using the
**
** sqlite3_config(SQLITE_CONFIG_MUTEX,...)
**
** interface.
**
** If compiled with SQLITE_DEBUG, then additional logic is inserted
** that does error checking on mutexes to make sure they are being
** called correctly.
*************************************************************************
** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart
** C#-SQLite is an independent reimplementation of the SQLite software library
**
** SQLITE_SOURCE_ID: 2009-12-07 16:39:13 1ed88e9d01e9eda5cbc622e7614277f29bcc551c
**
*************************************************************************
*/
//#include "sqliteInt.h"
#if !SQLITE_DEBUG
/*
** Stub routines for all mutex methods.
**
** This routines provide no mutual exclusion or error checking.
*/
static int noopMutexHeld(sqlite3_mutex p){ return 1; }
static int noopMutexNotheld(sqlite3_mutex p){ return 1; }
static int noopMutexInit(){ return SQLITE_OK; }
static int noopMutexEnd(){ return SQLITE_OK; }
static sqlite3_mutex noopMutexAlloc(int id){ return new sqlite3_mutex(); }
static void noopMutexFree(sqlite3_mutex p){ }
static void noopMutexEnter(sqlite3_mutex p){ }
static int noopMutexTry(sqlite3_mutex p){ return SQLITE_OK; }
static void noopMutexLeave(sqlite3_mutex p){ }
sqlite3_mutex_methods sqlite3NoopMutex(){
sqlite3_mutex_methods sMutex = new sqlite3_mutex_methods(
(dxMutexInit)noopMutexInit,
(dxMutexEnd)noopMutexEnd,
(dxMutexAlloc)noopMutexAlloc,
(dxMutexFree)noopMutexFree,
(dxMutexEnter)noopMutexEnter,
(dxMutexTry)noopMutexTry,
(dxMutexLeave)noopMutexLeave,
#if SQLITE_DEBUG
(dxMutexHeld)noopMutexHeld,
(dxMutexNotheld)noopMutexNotheld
#else
null,
null
#endif
);
return sMutex;
}
#endif //* !SQLITE_DEBUG */
#if SQLITE_DEBUG && !SQLITE_MUTEX_OMIT
/*
** In this implementation, error checking is provided for testing
** and debugging purposes. The mutexes still do not provide any
** mutual exclusion.
*/
/*
** The mutex object
*/
public class sqlite3_debug_mutex : sqlite3_mutex
{
//public int id; /* The mutex type */
public int cnt; /* Number of entries without a matching leave */
};
/*
** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
** intended for use inside Debug.Assert() statements.
*/
static bool debugMutexHeld( sqlite3_mutex pX )
{
sqlite3_debug_mutex p = (sqlite3_debug_mutex)pX;
return p == null || p.cnt > 0;
}
static bool debugMutexNotheld( sqlite3_mutex pX )
{
sqlite3_debug_mutex p = (sqlite3_debug_mutex)pX;
return p == null || p.cnt == 0;
}
/*
** Initialize and deinitialize the mutex subsystem.
*/
static int debugMutexInit()
{
return SQLITE_OK;
}
static int debugMutexEnd()
{
return SQLITE_OK;
}
/*
** The sqlite3_mutex_alloc() routine allocates a new
** mutex and returns a pointer to it. If it returns NULL
** that means that a mutex could not be allocated.
*/
static sqlite3_mutex debugMutexAlloc( int id )
{
sqlite3_debug_mutex[] aStatic = new sqlite3_debug_mutex[6];
sqlite3_debug_mutex pNew = null;
switch ( id )
{
case SQLITE_MUTEX_FAST:
case SQLITE_MUTEX_RECURSIVE:
{
pNew = new sqlite3_debug_mutex();//sqlite3Malloc(sizeof(*pNew));
if ( pNew != null )
{
pNew.id = id;
pNew.cnt = 0;
}
break;
}
default:
{
Debug.Assert( id - 2 >= 0 );
Debug.Assert( id - 2 < aStatic.Length );//(int)(sizeof(aStatic)/sizeof(aStatic[0])) );
pNew = aStatic[id - 2];
pNew.id = id;
break;
}
}
return pNew;
}
/*
** This routine deallocates a previously allocated mutex.
*/
static void debugMutexFree( sqlite3_mutex pX )
{
sqlite3_debug_mutex p = (sqlite3_debug_mutex)pX;
Debug.Assert( p.cnt == 0 );
Debug.Assert( p.id == SQLITE_MUTEX_FAST || p.id == SQLITE_MUTEX_RECURSIVE );
//sqlite3_free(ref p);
}
/*
** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
** to enter a mutex. If another thread is already within the mutex,
** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
** SQLITE_BUSY. The sqlite3_mutex_try() interface returns SQLITE_OK
** upon successful entry. Mutexes created using SQLITE_MUTEX_RECURSIVE can
** be entered multiple times by the same thread. In such cases the,
** mutex must be exited an equal number of times before another thread
** can enter. If the same thread tries to enter any other kind of mutex
** more than once, the behavior is undefined.
*/
static void debugMutexEnter( sqlite3_mutex pX )
{
sqlite3_debug_mutex p = (sqlite3_debug_mutex)pX;
Debug.Assert( p.id == SQLITE_MUTEX_RECURSIVE || debugMutexNotheld( p ) );
p.cnt++;
}
static int debugMutexTry( sqlite3_mutex pX )
{
sqlite3_debug_mutex p = (sqlite3_debug_mutex)pX;
Debug.Assert( p.id == SQLITE_MUTEX_RECURSIVE || debugMutexNotheld( p ) );
p.cnt++;
return SQLITE_OK;
}
/*
** The sqlite3_mutex_leave() routine exits a mutex that was
** previously entered by the same thread. The behavior
** is undefined if the mutex is not currently entered or
** is not currently allocated. SQLite will never do either.
*/
static void debugMutexLeave( sqlite3_mutex pX )
{
sqlite3_debug_mutex p = (sqlite3_debug_mutex)pX;
Debug.Assert( debugMutexHeld( p ) );
p.cnt--;
Debug.Assert( p.id == SQLITE_MUTEX_RECURSIVE || debugMutexNotheld( p ) );
}
static sqlite3_mutex_methods sqlite3NoopMutex()
{
sqlite3_mutex_methods sMutex = new sqlite3_mutex_methods(
(dxMutexInit)debugMutexInit,
(dxMutexEnd)debugMutexEnd,
(dxMutexAlloc)debugMutexAlloc,
(dxMutexFree)debugMutexFree,
(dxMutexEnter)debugMutexEnter,
(dxMutexTry)debugMutexTry,
(dxMutexLeave)debugMutexLeave,
(dxMutexHeld)debugMutexHeld,
(dxMutexNotheld)debugMutexNotheld
);
return sMutex;
}
#endif //* SQLITE_DEBUG */
/*
** If compiled with SQLITE_MUTEX_NOOP, then the no-op mutex implementation
** is used regardless of the run-time threadsafety setting.
*/
#if SQLITE_MUTEX_NOOP
sqlite3_mutex_methods const sqlite3DefaultMutex(void){
return sqlite3NoopMutex();
}
#endif //* SQLITE_MUTEX_NOOP */
}
}
| |
#define TRANSITION_ENABLED
//#define TRANSITION_POSTEFFECTS_ENABLED
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine.Extensions;
using UnityEngine.UI.Windows.Plugins.Flow;
using UnityEngine.UI.Windows.Animations;
using UnityEngine.UI.Extensions;
using UnityEngine.EventSystems;
using UnityEngine.Serialization;
namespace UnityEngine.UI.Windows {
/*
* Events order: (Any of OnShowBegin, OnHideBegin, etc.)
* Layout
* Modules
* Audio
* Events
* Transitions
* Screen
*/
[ExecuteInEditMode()]
//[RequireComponent(typeof(Camera))]
public abstract class WindowBase :
WindowObject,
IWindowEventsAsync,
IWindowEventsController,
IFunctionIteration,
IWindow,
IBeginDragHandler,
IDragHandler,
IEndDragHandler,
IDraggableHandler,
IResourceReference,
ICanvasElement {
#if UNITY_EDITOR
[HideInInspector]
public bool editorInfoFold = false;
#endif
[SerializeField][Hidden("_workCamera", state: null, inverseCondition: true)]
private Camera _workCamera;
[HideInInspector]
public Camera workCamera { get { return this._workCamera; } protected set { this._workCamera = value; } }
[HideInInspector][FormerlySerializedAs("initialized")]
public bool isReady = false;
[Header("Window Preferences")]
public TargetPreferences targetPreferences = new TargetPreferences();
public Preferences preferences = new Preferences();
new public Audio.Window audio = new Audio.Window();
public ModulesList modules = new ModulesList();
public Events events = new Events();
#if !TRANSITION_ENABLED
[ReadOnly]
#endif
public Transition transition = new Transition();
[Header("Logger")]
public WindowComponentHistoryTracker eventsHistoryTracker = new WindowComponentHistoryTracker();
[SerializeField][HideInInspector]
private ActiveState activeState = ActiveState.None;
//[SerializeField][HideInInspector]
private int activeIteration = 0;
[SerializeField][HideInInspector]
private WindowObjectState _currentState = WindowObjectState.NotInitialized;
private WindowObjectState currentState {
set {
this.lastState = this._currentState;
this._currentState = value;
}
get {
return this._currentState;
}
}
[SerializeField][HideInInspector]
private WindowObjectState lastState = WindowObjectState.NotInitialized;
[SerializeField][HideInInspector]
private DragState dragState = DragState.None;
[SerializeField][HideInInspector]
private bool paused = false;
private int functionIterationIndex = 0;
[HideInInspector]
protected bool setup = false;
[HideInInspector]
private bool passParams = false;
[HideInInspector]
private object[] parameters;
private System.Action<WindowBase> onParametersPassCall;
[HideInInspector][System.NonSerialized]
public bool skipRecycle = false;
protected InitialParameters initialParameters;
private WindowBase source;
private GameObject firstSelectedGameObject;
private GameObject currentSelectedGameObject;
#region ICanvasElement
Transform ICanvasElement.transform {
get { return base.transform; }
}
void ICanvasElement.GraphicUpdateComplete() {
}
bool ICanvasElement.IsDestroyed() {
return this == null;
}
void ICanvasElement.LayoutComplete() {
ME.Coroutines.RunNextFrame(() => {
if (this.GetState() != WindowObjectState.Hiding &&
this.GetState() != WindowObjectState.Hidden &&
this.GetState() != WindowObjectState.Deinitializing &&
this.GetState() != WindowObjectState.NotInitialized) {
this.DoLayoutWindowLayoutComplete();
this.modules.DoWindowLayoutComplete();
this.audio.DoWindowLayoutComplete();
this.events.DoWindowLayoutComplete();
this.transition.DoWindowLayoutComplete();
(this as IWindowEventsController).DoWindowLayoutComplete();
}
});
}
void ICanvasElement.Rebuild(CanvasUpdate executing) {
}
#endregion
public override bool IsDestroyable() {
return false;
}
public bool SourceEquals(WindowBase y) {
if (y == null) return false;
if (this.source == null) return y.source == this;
if (y.source == null) return y == this.source;
return this.source == y.source;
}
public WindowBase GetSource() {
return this.source;
}
public void Setup(FlowData data) {
this.Setup(-1, data);
}
public void Setup(int id, FlowData data) {
#if UNITY_EDITOR
if (id >= 0) this.windowId = id;
if (this.audio == null) this.audio = new Audio.Window();
this.audio.flowData = data;
#endif
}
public virtual void OnCameraReset() {
}
public void SetAsPerspective() {
WindowSystem.ApplyToSettings(this.workCamera, mode: WindowSystemSettings.Camera.Mode.Perspective);
}
public void SetAsOrthoraphic() {
WindowSystem.ApplyToSettings(this.workCamera, mode: WindowSystemSettings.Camera.Mode.Orthographic);
}
public bool IsVisible() {
return (this.GetState() == WindowObjectState.Showing || this.GetState() == WindowObjectState.Shown);
}
public float GetDepth() {
return this.workCamera.depth;
}
public float GetZDepth() {
return this.transform.position.z;
}
public void SetDepth(float depth, float zDepth) {
var pos = this.transform.position;
pos.z = zDepth;
this.transform.position = pos;
this.workCamera.depth = depth;
}
internal void Init(WindowBase source, float depth, float zDepth, int raycastPriority, int orderInLayer, System.Action onInitialized, bool async) {
this.source = source;
this.Init(depth, zDepth, raycastPriority, orderInLayer, onInitialized, async);
}
internal void Init(float depth, float zDepth, int raycastPriority, int orderInLayer, System.Action onInitialized, bool async) {
this.Init(new InitialParameters() { depth = depth, zDepth = zDepth, raycastPriority = raycastPriority, orderInLayer = orderInLayer }, onInitialized, async);
}
internal void Init(InitialParameters parameters, System.Action onInitialized, bool async) {
this.initialParameters = parameters;
this.currentState = WindowObjectState.Initializing;
if (this.isReady == false) {
this.currentState = WindowObjectState.NotInitialized;
Debug.LogError("Can't initialize window instance because of some components were not installed properly.", this);
return;
}
this.SetOrientationChangedDirect();
this.SetDepth(this.initialParameters.depth, this.initialParameters.zDepth);
this.events.LateUpdate(this);
if (Application.isPlaying == true) {
if (this.preferences.IsDontDestroyOnSceneChange() == true) {
GameObject.DontDestroyOnLoad(this.gameObject);
}
}
if (this.passParams == true) {
if (this.parameters != null && this.parameters.Length > 0) {
System.Reflection.MethodInfo methodInfo;
if (WindowSystem.InvokeMethodWithParameters(out methodInfo, this, "OnParametersPass", this.parameters) == true) {
// Success
methodInfo.Invoke(this, this.parameters);
} else {
// Method not found
var prs = new string[this.parameters.Length];
for (int i = 0; i < prs.Length; ++i) prs[i] = this.parameters[i].ToString();
Debug.LogWarning(string.Format("Method `OnParametersPass` was not found with input parameters: {0}, Parameters: {1}", this.parameters.Length, string.Join(", ", prs)), this);
}
}
if (this.onParametersPassCall != null) {
this.onParametersPassCall.Invoke(this);
this.onParametersPassCall = null;
this.passParams = false;
}
} else {
this.OnEmptyPass();
}
System.Action callbackInner = () => {
this.setup = true;
//Debug.Log("INIT: " + this.activeIteration + " :: " + this);
this.currentState = WindowObjectState.Initialized;
this.eventsHistoryTracker.Add(this, HistoryTrackerEventType.Init);
if (onInitialized != null) onInitialized.Invoke();
};
if (this.setup == false) {
this.Setup(this);
#if DEBUGBUILD
Profiler.BeginSample("WindowBase::OnPreInit()");
#endif
this.OnPreInit();
#if DEBUGBUILD
Profiler.EndSample();
#endif
#if DEBUGBUILD
Profiler.BeginSample("WindowBase::OnInit()");
#endif
this.DoLayoutInit(this.initialParameters.depth, this.initialParameters.raycastPriority, this.initialParameters.orderInLayer, () => {
WindowSystem.ApplyToSettingsInstance(this.workCamera, this.GetCanvas(), this);
this.OnModulesInit();
this.OnAudioInit();
this.events.DoInit();
this.OnTransitionInit();
if (WindowSystem.IsCallEventsEnabled() == true) {
this.OnInit();
}
callbackInner.Invoke();
}, async);
#if DEBUGBUILD
Profiler.EndSample();
#endif
} else {
callbackInner.Invoke();
}
}
void IWindowEventsController.DoWindowUnload() {
//Debug.LogWarningFormat("Unloading window `{0}` with state `{1}`", this.name, this.GetState());
this.DoLayoutUnload();
this.modules.DoWindowUnload();
this.audio.DoWindowUnload();
this.events.DoWindowUnload();
this.transition.DoWindowUnload();
this.OnWindowUnload();
}
public void ApplyActiveState() {
this.activeIteration = -WindowSystem.GetWindowsInFrontCount(this) - 1;
this.SetActive();
if (this.preferences.sendActiveState == true) {
WindowSystem.SendInactiveStateByWindow(this);
}
}
public void SetFunctionIterationIndex(int iteration) {
this.functionIterationIndex = iteration;
}
public int GetFunctionIterationIndex() {
return this.functionIterationIndex;
}
internal void SetParameters(System.Action<WindowBase> onParametersPassCall, params object[] parameters) {
this.onParametersPassCall = onParametersPassCall;
if (parameters != null && parameters.Length > 0) {
this.parameters = parameters;
this.passParams = true;
} else {
this.passParams = (onParametersPassCall != null);
}
}
public virtual Canvas GetCanvas() {
return null;
}
public virtual CanvasScaler GetCanvasScaler() {
return null;
}
/// <summary>
/// Gets the state.
/// </summary>
/// <returns>The state.</returns>
public virtual WindowObjectState GetLastState() {
return this.lastState;
}
public virtual WindowObjectState GetState() {
return this.currentState;
}
public virtual Vector2 GetSize() {
return new Vector2(Screen.width, Screen.height);
}
public void ApplyInnerCameras(Camera[] cameras, bool front) {
var currentDepth = this.workCamera.depth;
var depthStep = WindowSystem.GetDepthStep() * 0.5f;
var camerasCount = cameras.Length;
var innerStep = depthStep / camerasCount;
for (int i = 0; i < camerasCount; ++i) {
cameras[i].orthographicSize = this.workCamera.orthographicSize;
cameras[i].depth = currentDepth + innerStep * (i + 1) * (front == true ? 1f : -1f);
}
}
#if TRANSITION_POSTEFFECTS_ENABLED
private void OnRenderImage(RenderTexture source, RenderTexture destination) {
this.transition.OnRenderImage(source, destination);
}
private void OnPostRender() {
this.transition.OnPostRender();
}
private void OnPreRender() {
this.transition.OnPreRender();
}
#endif
private void OnAudioInit() {
this.audio.Setup(this);
this.audio.DoInit();
}
private void OnTransitionInit() {
this.workCamera.clearFlags = CameraClearFlags.Depth;
this.transition.Setup(this);
this.transition.DoInit();
}
private void OnModulesInit() {
this.modules.Create(this, this.GetLayoutRoot());
this.modules.DoInit();
}
public ActiveState GetActiveState() {
return this.activeState;
}
public void TurnOnRender() {
this.workCamera.enabled = true;
//var canvas = this.GetCanvas();
//if (canvas != null) canvas.enabled = true;
var canvases = this.GetComponentsInChildren<Canvas>(includeInactive: true);
for (int i = 0; i < canvases.Length; ++i) canvases[i].enabled = true;
}
public void TurnOffRender() {
this.workCamera.enabled = false;
//var canvas = this.GetCanvas();
//if (canvas != null) canvas.enabled = false;
var canvases = this.GetComponentsInChildren<Canvas>(includeInactive: true);
for (int i = 0; i < canvases.Length; ++i) canvases[i].enabled = false;
}
public void SetActive() {
//Debug.Log("SetActive: " + this);
++this.activeIteration;
if (this.activeIteration == 0) {
if (this.activeState != ActiveState.Active) {
this.activeState = ActiveState.Active;
this.TurnOnRender();
this.eventsHistoryTracker.Add(this, HistoryTrackerEventType.WindowActive);
this.DoLayoutWindowActive();
this.modules.DoWindowActive();
this.audio.DoWindowActive();
this.events.DoWindowActive();
this.transition.DoWindowActive();
(this as IWindowEventsController).DoWindowActive();
}
} else {
if (WindowSystem.IsWindowsInFrontFullCoverage(this) == false) {
this.TurnOnRender();
}
}
}
public void SetInactive(WindowBase newWindow) {
//Debug.Log("SetInactive: " + this);
if (newWindow != null && newWindow.preferences.fullCoverage == true) {
this.TurnOffRender();
}
--this.activeIteration;
if (this.activeIteration == -1) {
if (this.activeState != ActiveState.Inactive) {
this.activeState = ActiveState.Inactive;
this.eventsHistoryTracker.Add(this, HistoryTrackerEventType.WindowInactive);
this.DoLayoutWindowInactive();
this.modules.DoWindowInactive();
this.audio.DoWindowInactive();
this.events.DoWindowInactive();
this.transition.DoWindowInactive();
(this as IWindowEventsController).DoWindowInactive();
}
}
}
void IWindowEventsController.DoWindowLayoutComplete() {
WindowSystem.RunSafe(this.OnWindowLayoutComplete);
}
public virtual void OnWindowLayoutComplete() {
}
void IWindowEventsController.DoWindowActive() {
WindowSystem.RunSafe(this.OnWindowActive);
if (WindowSystem.IsRestoreSelectedElement() == true && this.preferences.restoreSelectedElement == true && EventSystem.current != null) {
EventSystem.current.firstSelectedGameObject = this.firstSelectedGameObject;
EventSystem.current.SetSelectedGameObject(this.currentSelectedGameObject);
}
}
public virtual void OnWindowActive() {
}
void IWindowEventsController.DoWindowInactive() {
WindowSystem.RunSafe(this.OnWindowInactive);
if (WindowSystem.IsRestoreSelectedElement() == true && this.preferences.restoreSelectedElement == true && EventSystem.current != null) {
this.firstSelectedGameObject = EventSystem.current.firstSelectedGameObject;
this.currentSelectedGameObject = EventSystem.current.currentSelectedGameObject;
}
}
public virtual void OnWindowInactive() {
}
public virtual void OnVersionChanged() {
}
public virtual void OnLocalizationChanged() {
}
public virtual void OnManualEvent<T>(T data) where T : IManualEvent {
}
public virtual void OnBackButtonAction() {
}
#region Orientation
public virtual void SetOrientationChangedDirect() {
var orientation = WindowSystem.GetOrientation();
if (orientation == Orientation.Horizontal) {
this.ApplyOrientationIndexDirect(0);
} else if (orientation == Orientation.Vertical) {
this.ApplyOrientationIndexDirect(1);
}
}
public virtual void ApplyOrientationIndexDirect(int index) {
}
public virtual void SetOrientationChanged() {
var orientation = WindowSystem.GetOrientation();
if (orientation == Orientation.Horizontal) {
this.ApplyOrientationIndex(0);
} else if (orientation == Orientation.Vertical) {
this.ApplyOrientationIndex(1);
}
this.OnOrientationChanged();
}
public virtual void ApplyOrientationIndex(int index) {
}
public virtual void OnOrientationChanged() {
}
#endregion
#region DRAG'n'DROP
private List<WindowLayoutElement> dragTempParent = new List<WindowLayoutElement>();
public void OnBeginDrag(PointerEventData eventData) {
this.SetDragBegin(eventData);
}
public void OnDrag(PointerEventData eventData) {
this.SetDrag(eventData);
}
public void OnEndDrag(PointerEventData eventData) {
this.SetDragEnd(eventData);
}
public bool IsDraggable() {
return this.preferences.draggable;
}
private void SetDragBegin(PointerEventData eventData) {
if (this.preferences.draggable == false) return;
if (this.dragState != DragState.None) return;
if (eventData.pointerCurrentRaycast.gameObject == null) return;
this.dragTempParent.Clear();
eventData.pointerCurrentRaycast.gameObject.GetComponentsInParent<WindowLayoutElement>(includeInactive: true, results: this.dragTempParent);
if (this.dragTempParent.Count > 0) {
var layoutElement = this.dragTempParent[0];
if (this.preferences.dragTag == LayoutTag.None || this.preferences.dragTag == layoutElement.tag) {
this.dragState = DragState.Begin;
this.OnMoveBegin(eventData);
}
}
}
private void SetDrag(PointerEventData eventData) {
if (this.preferences.draggable == false) return;
if (this.dragState != DragState.Begin && this.dragState != DragState.Move) return;
this.dragState = DragState.Move;
var delta = eventData.delta;
this.SetDrag_INTERNAL(delta);
this.OnMove(eventData);
}
private void SetDrag_INTERNAL(Vector2 delta) {
var k = (this.GetLayoutRoot() as RectTransform).sizeDelta.x / Screen.width;
if (this.preferences.IsDragViewportRestricted() == true) {
var screenRect = WindowSystem.GetScreenRect();
var rect = this.GetRect();
rect.center += delta;
if (rect.xMin <= screenRect.xMin) {
delta.x += screenRect.xMin - rect.xMin;
}
if (rect.yMin - rect.height <= screenRect.yMin) {
delta.y += screenRect.yMin - (rect.yMin - rect.height);
}
if (rect.xMax >= screenRect.xMax) {
delta.x += screenRect.xMax - rect.xMax;
}
if (rect.yMax - rect.height >= screenRect.yMax) {
delta.y += screenRect.yMax - (rect.yMax - rect.height);
}
}
this.MoveLayout(delta * k);
}
private void SetDragEnd(PointerEventData eventData) {
if (this.preferences.draggable == false) return;
if (this.dragState != DragState.Begin && this.dragState != DragState.Move) return;
this.dragState = DragState.End;
this.OnMoveEnd(eventData);
this.dragState = DragState.None;
}
public virtual void OnMoveBegin(PointerEventData eventData) {
}
public virtual void OnMove(PointerEventData eventData) {
}
public virtual void OnMoveEnd(PointerEventData eventData) {
}
#endregion
public virtual Rect GetRect() {
var bounds = RectTransformUtility.CalculateRelativeRectTransformBounds(this.GetLayoutRoot());
return new Rect(new Vector2(bounds.center.x, bounds.center.y), new Vector2(bounds.size.x, bounds.size.y));
}
public bool TurnOff() {
if (this == null) return false;
#if DEBUGBUILD
Profiler.BeginSample("WindowBase::TurnOff()");
#endif
var result = false;
if (WindowSystem.IsCameraRenderDisableOnWindowTurnOff() == true) {
if (this.workCamera != null) this.workCamera.enabled = false;
var canvas = this.GetCanvas();
if (canvas != null) canvas.enabled = false;
var scaler = this.GetCanvasScaler();
if (scaler != null) scaler.enabled = false;
result = false;
} else {
if (this.gameObject != null) this.gameObject.SetActive(false);
result = true;
}
#if DEBUGBUILD
Profiler.EndSample();
#endif
return result;
}
public void TurnOn() {
if (this == null) return;
#if DEBUGBUILD
Profiler.BeginSample("WindowBase::TurnOn()");
#endif
if (WindowSystem.IsCameraRenderDisableOnWindowTurnOff() == true) {
if (this.workCamera != null) this.workCamera.enabled = true;
var canvas = this.GetCanvas();
if (canvas != null) canvas.enabled = true;
var scaler = this.GetCanvasScaler();
if (scaler != null) scaler.enabled = true;
} else {
if (this.gameObject != null) this.gameObject.SetActive(true);
}
#if DEBUGBUILD
Profiler.EndSample();
#endif
}
/// <summary>
/// Gets the name of the sorting layer.
/// </summary>
/// <returns>The sorting layer name.</returns>
public virtual string GetSortingLayerName() {
return WindowSystem.GetSortingLayerName();
}
/// <summary>
/// Gets the sorting order.
/// </summary>
/// <returns>The sorting order.</returns>
public virtual int GetSortingOrder() {
return 0;
}
/// <summary>
/// Gets the duration of the animation.
/// </summary>
/// <returns>The animation duration.</returns>
/// <param name="forward">If set to <c>true</c> forward.</param>
public float GetAnimationDuration(bool forward) {
var layoutDuration = this.GetLayoutAnimationDuration(forward);
var moduleDuration = this.GetModuleAnimationDuration(forward);
var transitionDuration = this.GetTransitionAnimationDuration(forward);
return Mathf.Max(layoutDuration, Mathf.Max(moduleDuration, transitionDuration));
}
/// <summary>
/// Gets the duration of the transition animation.
/// </summary>
/// <returns>The transition animation duration.</returns>
/// <param name="forward">If set to <c>true</c> forward.</param>
public virtual float GetTransitionAnimationDuration(bool forward) {
return this.transition.GetAnimationDuration(forward);
}
/// <summary>
/// Gets the duration of the module animation.
/// </summary>
/// <returns>The module animation duration.</returns>
/// <param name="forward">If set to <c>true</c> forward.</param>
public virtual float GetModuleAnimationDuration(bool forward) {
return this.modules.GetAnimationDuration(forward);
}
/// <summary>
/// Gets the module.
/// </summary>
/// <returns>The module.</returns>
/// <typeparam name="T">The 1st type parameter.</typeparam>
public T GetModule<T>() where T : WindowModule {
return this.modules.Get<T>();
}
/// <summary>
/// Show this instance.
/// </summary>
public bool Show() {
return this.Show_INTERNAL(null, null);
}
/// <summary>
/// Show the specified onShowEnd.
/// </summary>
/// <param name="onShowEnd">On show end.</param>
public bool Show(System.Action onShowEnd) {
return this.Show_INTERNAL(onShowEnd, null);
}
/// <summary>
/// Show window with specific transition.
/// </summary>
/// <param name="transition">Transition.</param>
/// <param name="transitionParameters">Transition parameters.</param>
public bool Show(AttachItem transitionItem) {
return this.Show_INTERNAL(null, transitionItem);
}
/// <summary>
/// Show the specified onShowEnd.
/// </summary>
/// <param name="onShowEnd">On show end.</param>
public bool Show(System.Action onShowEnd, AttachItem transitionItem) {
return this.Show_INTERNAL(onShowEnd, transitionItem);
}
private bool Show_INTERNAL(System.Action onShowEnd, AttachItem transitionItem) {
if (WindowSystem.IsCallEventsEnabled() == false) {
return false;
}
if (this.currentState == WindowObjectState.Showing || this.currentState == WindowObjectState.Shown) {
return false;
}
this.currentState = WindowObjectState.Showing;
this.eventsHistoryTracker.Add(this, HistoryTrackerEventType.ShowBegin);
WindowSystem.AddToHistory(this);
CanvasUpdateRegistry.RegisterCanvasElementForLayoutRebuild(this);
if (this.gameObject.activeSelf == false) this.gameObject.SetActive(true);
ME.Coroutines.Run(this.Show_INTERNAL_YIELD(onShowEnd, transitionItem));
return true;
}
private System.Collections.Generic.IEnumerator<byte> Show_INTERNAL_YIELD(System.Action onShowEnd, AttachItem transitionItem) {
while (this.paused == true) yield return 0;
this.ApplyActiveState();
this.TurnOn();
var parameters = AppearanceParameters.Default();
this.showWaitCounter = 0;
var counter = 0;
System.Action callback = () => {
if (this.currentState != WindowObjectState.Showing) return;
++counter;
if (counter < 6 + this.showWaitCounter) return;
#if DEBUGBUILD
Profiler.BeginSample("WindowBase::OnShowEnd()");
#endif
this.DoLayoutShowEnd(parameters);
this.modules.DoShowEnd(parameters);
this.audio.DoShowEnd(parameters);
this.events.DoShowEnd(parameters);
this.transition.DoShowEnd(parameters);
(this as IWindowEventsController).DoShowEnd(parameters);
if (onShowEnd != null) onShowEnd();
#if DEBUGBUILD
Profiler.EndSample();
#endif
this.currentState = WindowObjectState.Shown;
this.eventsHistoryTracker.Add(this, HistoryTrackerEventType.ShowEnd);
WindowSystem.RunSafe(this.OnShowEndLate);
};
parameters = parameters.ReplaceCallback(callback);
#if DEBUGBUILD
Profiler.BeginSample("WindowBase::OnShowBegin()");
#endif
(this as IWindowEventsController).DoWindowOpen();
this.DoLayoutShowBegin(parameters);
this.modules.DoShowBegin(parameters);
if (transitionItem != null && transitionItem.audioTransition != null) {
this.audio.DoShowBegin(transitionItem.audioTransition, transitionItem.audioTransitionParameters, parameters);
} else {
this.audio.DoShowBegin(parameters);
}
this.events.DoShowBegin(parameters);
if (transitionItem != null && transitionItem.transition != null) {
this.transition.DoShowBegin(transitionItem.transition, transitionItem.transitionParameters, parameters);
} else {
this.transition.DoShowBegin(parameters);
}
(this as IWindowEventsController).DoShowBegin(parameters);
#if DEBUGBUILD
Profiler.EndSample();
#endif
}
private int showWaitCounter = 0;
public void AddShowWaitCounter() {
++this.showWaitCounter;
}
private int hideWaitCounter = 0;
public void AddHideWaitCounter() {
++this.hideWaitCounter;
}
/// <summary>
/// Hide this instance.
/// </summary>
public bool Hide() {
return this.Hide_INTERNAL(onHideEnd: null, transitionItem: null);
}
public bool Hide(System.Action onHideEnd, bool immediately) {
return this.Hide_INTERNAL(onHideEnd: onHideEnd, transitionItem: null, immediately: immediately);
}
public bool Hide(bool immediately) {
return this.Hide_INTERNAL(onHideEnd: null, transitionItem: null, immediately: immediately);
}
public bool Hide(bool immediately, bool forced) {
return this.Hide_INTERNAL(onHideEnd: null, transitionItem: null, immediately: immediately, forced: forced);
}
public bool Hide(System.Action onHideEnd, bool immediately, bool forced) {
return this.Hide_INTERNAL(onHideEnd: onHideEnd, transitionItem: null, immediately: immediately, forced: forced);
}
/// <summary>
/// Hide window with specific transition.
/// </summary>
/// <param name="transition">Transition.</param>
/// <param name="transitionParameters">Transition parameters.</param>
public bool Hide(AttachItem transitionItem) {
return this.Hide_INTERNAL(null, transitionItem);
}
/// <summary>
/// Hide the specified onHideEnd.
/// Wait while all components, animations, events and modules return the callback.
/// </summary>
/// <param name="onHideEnd">On hide end.</param>
public bool Hide(System.Action onHideEnd) {
return this.Hide_INTERNAL(onHideEnd, null);
}
/// <summary>
/// Hide the specified onHideEnd with specific transition.
/// Wait while all components, animations, events and modules return the callback.
/// </summary>
/// <param name="onHideEnd">On hide end.</param>
/// <param name="transition">Transition.</param>
/// <param name="transitionParameters">Transition parameters.</param>
public bool Hide(System.Action onHideEnd, AttachItem transitionItem) {
return this.Hide_INTERNAL(onHideEnd, transitionItem);
}
private bool Hide_INTERNAL(System.Action onHideEnd, AttachItem transitionItem, bool immediately = false, bool forced = false) {
return this.Hide_INTERNAL(onHideEnd, transitionItem, AppearanceParameters.Default().ReplaceImmediately(immediately).ReplaceForced(forced));
}
private bool Hide_INTERNAL(System.Action onHideEnd, AttachItem transitionItem, AppearanceParameters parameters) {
if (this == null) {
return false;
}
var forced = parameters.GetForced(defaultValue: false);
if ((this.currentState == WindowObjectState.Hidden || this.currentState == WindowObjectState.Hiding) && forced == false) {
return false;
}
this.currentState = WindowObjectState.Hiding;
this.eventsHistoryTracker.Add(this, HistoryTrackerEventType.HideBegin);
//if (this.gameObject.activeSelf == false) this.gameObject.SetActive(true);
ME.Coroutines.Run(this.Hide_INTERNAL_YIELD(onHideEnd, transitionItem, parameters));
return true;
}
private System.Collections.Generic.IEnumerator<byte> Hide_INTERNAL_YIELD(System.Action onHideEnd, AttachItem transitionItem, AppearanceParameters parameters) {
if (parameters.GetForced(defaultValue: false) == false) {
while (this.paused == true) yield return 0;
}
this.activeIteration = 0;
this.SetInactive(null);
if (this.preferences.sendActiveState == true) {
WindowSystem.SendActiveStateByWindow(this);
}
//var parameters = AppearanceParameters.Default();
//parameters.ReplaceImmediately(immediately);
//parameters.ReplaceForced(forced);
this.hideWaitCounter = 0;
var counter = 0;
System.Action callback = () => {
if (this.currentState != WindowObjectState.Hiding) return;
++counter;
if (counter < 6 + this.hideWaitCounter) return;
WindowSystem.AddToHistory(this);
#if DEBUGBUILD
Profiler.BeginSample("WindowBase::OnHideEnd()");
#endif
this.DoLayoutHideEnd(parameters);
this.modules.DoHideEnd(parameters);
this.audio.DoHideEnd(parameters);
this.events.DoHideEnd(parameters);
this.transition.DoHideEnd(parameters);
(this as IWindowEventsController).DoHideEnd(parameters);
if (onHideEnd != null) onHideEnd();
#if DEBUGBUILD
Profiler.EndSample();
#endif
this.currentState = WindowObjectState.Hidden;
this.eventsHistoryTracker.Add(this, HistoryTrackerEventType.HideEnd);
WindowSystem.RunSafe(this.OnHideEndLate);
this.events.DoHideEndLate(parameters);
CanvasUpdateRegistry.UnRegisterCanvasElementForRebuild(this);
WindowSystem.Recycle(this, setInactive: this.TurnOff());
};
parameters = parameters.ReplaceCallback(callback);
#if DEBUGBUILD
Profiler.BeginSample("WindowBase::OnHideBegin()");
#endif
(this as IWindowEventsController).DoWindowClose();
this.DoLayoutHideBegin(parameters);
this.modules.DoHideBegin(parameters);
if (transitionItem != null && transitionItem.audioTransition != null) {
this.audio.DoHideBegin(transitionItem.audioTransition, transitionItem.audioTransitionParameters, parameters);
} else {
this.audio.DoHideBegin(parameters);
}
this.events.DoHideBegin(parameters);
if (transitionItem != null && transitionItem.transition != null) {
this.transition.DoHideBegin(transitionItem.transition, transitionItem.transitionParameters, parameters);
} else {
this.transition.DoHideBegin(parameters);
}
(this as IWindowEventsController).DoHideBegin(parameters);
#if DEBUGBUILD
Profiler.EndSample();
#endif
}
public void Pause() {
this.paused = true;
}
public void Resume() {
this.paused = false;
}
public void DoDestroy(System.Action callback) {
if (Application.isPlaying == false) return;
if (this.GetState() == WindowObjectState.Deinitializing ||
this.GetState() == WindowObjectState.NotInitialized) {
callback.Invoke();
return;
}
this.eventsHistoryTracker.Add(this, HistoryTrackerEventType.Deinit);
#if DEBUGBUILD
Profiler.BeginSample("WindowBase::OnDeinit()");
#endif
this.currentState = WindowObjectState.Deinitializing;
ME.Utilities.CallInSequence<System.Action<System.Action>>(() => {
this.currentState = WindowObjectState.NotInitialized;
if (callback != null) callback.Invoke();
}, /*waitPrevious:*/ true, (item, c) => {
item.Invoke(c);
},
this.DoLayoutDeinit,
this.modules.DoDeinit,
this.audio.DoDeinit,
this.events.DoDeinit,
this.transition.DoDeinit,
(this as IWindowEventsController).DoDeinit
);
#if DEBUGBUILD
Profiler.EndSample();
#endif
}
public virtual Transform GetLayoutRoot() { return null; }
protected virtual void MoveLayout(Vector2 delta) {}
/// <summary>
/// Gets the duration of the layout animation.
/// </summary>
/// <returns>The layout animation duration.</returns>
/// <param name="forward">If set to <c>true</c> forward.</param>
public virtual float GetLayoutAnimationDuration(bool forward) {
return 0f;
}
protected virtual void DoLayoutWindowActive() {}
protected virtual void DoLayoutWindowInactive() {}
protected virtual void DoLayoutWindowOpen() {}
protected virtual void DoLayoutWindowClose() {}
protected virtual void DoLayoutWindowLayoutComplete() {}
protected virtual void DoLayoutUnload() {}
/// <summary>
/// Raises the layout init event.
/// </summary>
/// <param name="depth">Depth.</param>
/// <param name="raycastPriority">Raycast priority.</param>
/// <param name="orderInLayer">Order in layer.</param>
protected virtual void DoLayoutInit(float depth, int raycastPriority, int orderInLayer, System.Action callback, bool async) {}
/// <summary>
/// Raises the layout deinit event.
/// </summary>
protected virtual void DoLayoutDeinit(System.Action callback) { callback.Invoke(); }
/// <summary>
/// Raises the layout show begin event.
/// </summary>
/// <param name="callback">Callback.</param>
protected virtual void DoLayoutShowBegin(AppearanceParameters parameters) { parameters.Call(); }
/// <summary>
/// Raises the layout show end event.
/// </summary>
protected virtual void DoLayoutShowEnd(AppearanceParameters parameters) {}
/// <summary>
/// Raises the layout hide begin event.
/// </summary>
/// <param name="callback">Callback.</param>
protected virtual void DoLayoutHideBegin(AppearanceParameters parameters) { parameters.Call(); }
/// <summary>
/// Raises the layout hide end event.
/// </summary>
protected virtual void DoLayoutHideEnd(AppearanceParameters parameters) {}
/// <summary>
/// Raises the parameters pass event.
/// Don't override this method - use your own.
/// Window will use reflection to determine your method.
/// Example: OnParametersPass(T1 param1, T2 param2, etc.)
/// You can use any types in any order and call window with them.
/// </summary>
[CompilerIgnore]
public virtual void OnParametersPass() {}
[CompilerIgnore]
public void OnParametersPass(params object[] objects) {
throw new UnityException(string.Format("OnParametersPass is not valid for screen `{0}`", this.name));
}
/// <summary>
/// Raises the empty pass event.
/// </summary>
public virtual void OnEmptyPass() {}
public virtual void OnPreInit() {}
void IWindowEventsController.DoWindowOpen() {
this.DoLayoutWindowOpen();
(this.modules as IWindowEventsController).DoWindowOpen();
(this.audio as IWindowEventsController).DoWindowOpen();
(this.events as IWindowEventsController).DoWindowOpen();
(this.transition as IWindowEventsController).DoWindowOpen();
WindowSystem.RunSafe(this.OnWindowOpen);
}
void IWindowEventsController.DoWindowClose() {
this.DoLayoutWindowClose();
(this.modules as IWindowEventsController).DoWindowClose();
(this.audio as IWindowEventsController).DoWindowClose();
(this.events as IWindowEventsController).DoWindowClose();
(this.transition as IWindowEventsController).DoWindowClose();
WindowSystem.RunSafe(this.OnWindowClose);
}
/// <summary>
/// Raises the init event.
/// </summary>
void IWindowEventsController.DoInit() {
WindowSystem.RunSafe(this.OnInit);
}
/// <summary>
/// Raises the deinit event.
/// </summary>
void IWindowEventsController.DoDeinit(System.Action callback) {
WindowSystem.RunSafe(this.OnDeinit, callback);
}
/// <summary>
/// Raises the show begin event.
/// </summary>
/// <param name="callback">Callback.</param>
void IWindowEventsController.DoShowBegin(AppearanceParameters parameters) {
WindowSystem.RunSafe(this.OnShowBegin);
WindowSystem.RunSafe(this.OnShowBegin, parameters);
parameters.Call();
}
/// <summary>
/// Raises the show end event.
/// </summary>
void IWindowEventsController.DoShowEnd(AppearanceParameters parameters) {
WindowSystem.RunSafe(this.OnShowEnd);
WindowSystem.RunSafe(this.OnShowEnd, parameters);
}
/// <summary>
/// Raises the hide begin event.
/// </summary>
/// <param name="callback">Callback.</param>
void IWindowEventsController.DoHideBegin(AppearanceParameters parameters) {
WindowSystem.RunSafe(this.OnHideBegin);
WindowSystem.RunSafe(this.OnHideBegin, parameters);
parameters.Call();
}
/// <summary>
/// Raises the hide end event.
/// </summary>
void IWindowEventsController.DoHideEnd(AppearanceParameters parameters) {
WindowSystem.RunSafe(this.OnHideEnd);
WindowSystem.RunSafe(this.OnHideEnd, parameters);
}
public virtual void OnWindowOpen() {}
public virtual void OnWindowClose() {}
public virtual void OnInit() {}
//public virtual void OnDeinit() {}
public virtual void OnShowEnd() {}
public virtual void OnShowEnd(AppearanceParameters parameters) {}
public virtual void OnHideEnd() {}
public virtual void OnHideEnd(AppearanceParameters parameters) {}
public virtual void OnShowBegin() {}
public virtual void OnShowBegin(AppearanceParameters parameters) {}
public virtual void OnHideBegin() {}
public virtual void OnHideBegin(AppearanceParameters parameters) {}
public virtual void OnWindowUnload() {}
/// <summary>
/// Fires after all states are Shown.
/// </summary>
public virtual void OnShowEndLate() {}
/// <summary>
/// Fires after all states are Hidden.
/// </summary>
public virtual void OnHideEndLate() {}
#if UNITY_EDITOR
public override void OnValidateEditor() {
base.OnValidateEditor();
this.preferences.OnValidate();
this.SetupCamera();
}
private void SetupCamera() {
this.workCamera = ME.Utilities.FindReferenceChildren<Camera>(this);
if (this.workCamera == null) {
this.workCamera = this.gameObject.AddComponent<Camera>();
}
if (this.workCamera != null) {
// Camera
if (this.preferences.overrideCameraSettings == true) {
this.preferences.cameraSettings.Apply(this.workCamera);
} else {
WindowSystem.ApplyToSettings(this.workCamera);
}
if ((this.workCamera.cullingMask & (1 << this.gameObject.layer)) == 0) {
this.workCamera.cullingMask = 0x0;
this.workCamera.cullingMask |= 1 << this.gameObject.layer;
}
this.workCamera.backgroundColor = new Color(0f, 0f, 0f, 0f);
}
this.isReady = (this.workCamera != null);
}
[ContextMenu("Create on Scene")]
public void CreateOnScene() {
this.CreateOnScene(callEvents: true);
}
public void CreateOnScene(bool callEvents) {
if (callEvents == false) {
WindowSystem.DisableCallEvents();
}
WindowBase window = null;
try {
window = WindowSystem.Show<WindowBase>(source: this);
} catch (UnityException) {
} finally {
if (window != null) {
var selection = new List<GameObject>();
var layoutWindow = window as UnityEngine.UI.Windows.Types.LayoutWindowType;
if (layoutWindow != null) {
var currentLayout = layoutWindow.layouts.layouts[0];
foreach (var component in currentLayout.components) {
var compInstance = currentLayout.Get<WindowComponent>(component.tag);
if (compInstance != null) selection.Add(compInstance.gameObject);
}
}
if (window != null) {
selection.Add(window.gameObject);
}
UnityEditor.Selection.objects = selection.ToArray();
if (selection.Count > 0) {
if (UnityEditor.SceneView.currentDrawingSceneView != null) {
UnityEditor.SceneView.currentDrawingSceneView.AlignViewToObject(selection[0].transform);
}
}
} else {
Debug.LogError("Create window on scene failed. May be WindowSystem is not exist on scene.");
}
}
if (callEvents == false) {
WindowSystem.RestoreCallEvents();
}
}
#endif
}
}
| |
using System;
using System.Collections.Generic;
using java.awt.image;
using java.io;
using java.lang;
using java.net;
using java.nio;
using java.text;
using java.util;
using OpenRSS.Extensions;
using RSUtilities;
using RSUtilities.Collections;
namespace OpenRSS.Cache.sprite
{
/// <summary>
/// Represents a <seealso cref="Sprite" /> which may contain one or more frames.
/// @author Graham
/// @author `Discardedx2
/// </summary>
public sealed class Sprite
{
/// <summary>
/// This flag indicates that the pixels should be read vertically instead of
/// horizontally.
/// </summary>
public const int FLAG_VERTICAL = 0x01;
/// <summary>
/// This flag indicates that every pixel has an alpha, as well as red, green
/// and blue, component.
/// </summary>
public const int FLAG_ALPHA = 0x02;
/// <summary>
/// The array of animation frames in this sprite.
/// </summary>
private readonly BufferedImage[] frames;
/// <summary>
/// The height of this sprite.
/// </summary>
private readonly int height;
/// <summary>
/// The width of this sprite.
/// </summary>
private readonly int width;
/// <summary>
/// Creates a new sprite with one frame.
/// </summary>
/// <param name="width"> The width of the sprite in pixels. </param>
/// <param name="height"> The height of the sprite in pixels. </param>
public Sprite(int width, int height)
: this(width, height, 1)
{ }
/// <summary>
/// Creates a new sprite with the specified number of frames.
/// </summary>
/// <param name="width"> The width of the sprite in pixels. </param>
/// <param name="height"> The height of the sprite in pixels. </param>
/// <param name="size"> The number of animation frames. </param>
public Sprite(int width, int height, int size)
{
if (size < 1)
{
throw new ArgumentException();
}
this.width = width;
this.height = height;
frames = new BufferedImage[size];
}
/// <summary>
/// Decodes the <seealso cref="Sprite" /> from the specified <seealso cref="ByteBuffer" />.
/// </summary>
/// <param name="buffer"> The buffer. </param>
/// <returns> The sprite. </returns>
public static Sprite Decode(ByteBuffer buffer)
{
/* find the size of this sprite set */
buffer.position(buffer.limit() - 2);
var size = buffer.getShort() & 0xFFFF;
/* allocate arrays to store info */
var offsetsX = new int[size];
var offsetsY = new int[size];
var subWidths = new int[size];
var subHeights = new int[size];
/* read the width, height and palette size */
buffer.position(buffer.limit() - size * 8 - 7);
var width = buffer.getShort() & 0xFFFF;
var height = buffer.getShort() & 0xFFFF;
var palette = new int[(buffer.get() & 0xFF) + 1];
/* and allocate an object for this sprite set */
var set = new Sprite(width, height, size);
/* read the offsets and dimensions of the individual sprites */
for (var i = 0; i < size; i++)
{
offsetsX[i] = buffer.getShort() & 0xFFFF;
}
for (var i = 0; i < size; i++)
{
offsetsY[i] = buffer.getShort() & 0xFFFF;
}
for (var i = 0; i < size; i++)
{
subWidths[i] = buffer.getShort() & 0xFFFF;
}
for (var i = 0; i < size; i++)
{
subHeights[i] = buffer.getShort() & 0xFFFF;
}
/* read the palette */
buffer.position(buffer.limit() - size * 8 - 7 - (palette.Length - 1) * 3);
palette[0] = 0; // transparent colour (black)
for (var index = 1; index < palette.Length; index++)
{
palette[index] = ByteBufferExtensions.GetTriByte(buffer);
if (palette[index] == 0)
{
palette[index] = 1;
}
}
/* read the pixels themselves */
buffer.position(0);
for (var id = 0; id < size; id++)
{
/* grab some frequently used values */
int subWidth = subWidths[id],
subHeight = subHeights[id];
int offsetX = offsetsX[id],
offsetY = offsetsY[id];
/* create a BufferedImage to store the resulting image */
var image = set.frames[id] = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
/* allocate an array for the palette indices */
//JAVA TO C# CONVERTER NOTE: The following call to the 'RectangularArrays' helper class reproduces the rectangular array initialization that is automatic in Java:
//ORIGINAL LINE: int[][] indices = new int[subWidth][subHeight];
var indices = ArrayUtil.ReturnRectangularArray<int>(subWidth, subHeight);
/* read the flags so we know whether to read horizontally or vertically */
var flags = buffer.get() & 0xFF;
/* read the palette indices */
if ((flags & FLAG_VERTICAL) != 0)
{
for (var x = 0; x < subWidth; x++)
{
for (var y = 0; y < subHeight; y++)
{
indices[x][y] = buffer.get() & 0xFF;
}
}
}
else
{
for (var y = 0; y < subHeight; y++)
{
for (var x = 0; x < subWidth; x++)
{
indices[x][y] = buffer.get() & 0xFF;
}
}
}
/* read the alpha (if there is alpha) and convert values to ARGB */
if ((flags & FLAG_ALPHA) != 0)
{
if ((flags & FLAG_VERTICAL) != 0)
{
for (var x = 0; x < subWidth; x++)
{
for (var y = 0; y < subHeight; y++)
{
var alpha = buffer.get() & 0xFF;
image.setRGB(x + offsetX, y + offsetY, alpha << 24 | palette[indices[x][y]]);
}
}
}
else
{
for (var y = 0; y < subHeight; y++)
{
for (var x = 0; x < subWidth; x++)
{
var alpha = buffer.get() & 0xFF;
image.setRGB(x + offsetX, y + offsetY, alpha << 24 | palette[indices[x][y]]);
}
}
}
}
else
{
for (var x = 0; x < subWidth; x++)
{
for (var y = 0; y < subHeight; y++)
{
var index = indices[x][y];
if (index == 0)
{
image.setRGB(x + offsetX, y + offsetY, 0);
}
else
{
image.setRGB(x + offsetX, y + offsetY, (int) (0xFF000000 | palette[index]));
}
}
}
}
}
return set;
}
/// <summary>
/// Gets the width of this sprite.
/// </summary>
/// <returns> The width of this sprite. </returns>
public int GetWidth()
{
return width;
}
/// <summary>
/// Gets the height of this sprite.
/// </summary>
/// <returns> The height of this sprite. </returns>
public int GetHeight()
{
return height;
}
/// <summary>
/// Gets the number of frames in this set.
/// </summary>
/// <returns> The number of frames. </returns>
public int Size()
{
return frames.Length;
}
/// <summary>
/// Gets the frame with the specified id.
/// </summary>
/// <param name="id"> The id. </param>
/// <returns> The frame. </returns>
public BufferedImage GetFrame(int id)
{
return frames[id];
}
/// <summary>
/// Sets the frame with the specified id.
/// </summary>
/// <param name="id"> The id. </param>
/// <param name="frame"> The frame. </param>
public void SetFrame(int id, BufferedImage frame)
{
if (frame.getWidth() != width || frame.getHeight() != height)
{
throw new ArgumentException("The frame's dimensions do not match with the sprite's dimensions.");
}
frames[id] = frame;
}
/// <summary>
/// Encodes this <seealso cref="Sprite" /> into a <seealso cref="ByteBuffer" />.
/// <p />
/// Please note that this is a fairly simple implementation which only
/// supports vertical encoding. It does not attempt to use the offsets
/// to save space.
/// </summary>
/// <returns> The buffer. </returns>
/// <exception cref="IOException"> if an I/O exception occurs. </exception>
public ByteBuffer Encode()
{
var bout = new ByteArrayOutputStream();
var os = new DataOutputStream(bout);
try
{
/* set up some variables */
IList<int?> palette = new List<int?>();
palette.Add(0); // transparent colour
/* write the sprites */
foreach (var image in frames)
{
/* check if we can encode this */
if (image.getWidth() != width || image.getHeight() != height)
{
throw new IOException("All frames must be the same size.");
}
/* loop through all the pixels constructing a palette */
var flags = FLAG_VERTICAL; // TODO: do we need to support horizontal encoding?
for (var x = 0; x < width; x++)
{
for (var y = 0; y < height; y++)
{
/* grab the colour of this pixel */
var argb = image.getRGB(x, y);
var alpha = (argb >> 24) & 0xFF;
var rgb = argb & 0xFFFFFF;
if (rgb == 0)
{
rgb = 1;
}
/* we need an alpha channel to encode this image */
if (alpha != 0 && alpha != 255)
{
flags |= FLAG_ALPHA;
}
/* add the colour to the palette if it isn't already in the palette */
if (!palette.Contains(rgb))
{
if (palette.Count >= 256)
{
throw new IOException("Too many colours in this sprite!");
}
palette.Add(rgb);
}
}
}
/* write this sprite */
os.write(flags);
for (var x = 0; x < width; x++)
{
for (var y = 0; y < height; y++)
{
var argb = image.getRGB(x, y);
var alpha = (argb >> 24) & 0xFF;
var rgb = argb & 0xFFFFFF;
if (rgb == 0)
{
rgb = 1;
}
if ((flags & FLAG_ALPHA) == 0 && alpha == 0)
{
os.write(0);
}
else
{
os.write(palette.IndexOf(rgb));
}
}
}
/* write the alpha channel if this sprite has one */
if ((flags & FLAG_ALPHA) != 0)
{
for (var x = 0; x < width; x++)
{
for (var y = 0; y < height; y++)
{
var argb = image.getRGB(x, y);
var alpha = (argb >> 24) & 0xFF;
os.write(alpha);
}
}
}
}
/* write the palette */
for (var i = 1; i < palette.Count; i++)
{
var rgb = (int) palette[i];
os.write((byte) (rgb >> 16));
os.write((byte) (rgb >> 8));
os.write((byte) rgb);
}
/* write the max width, height and palette size */
os.writeShort(width);
os.writeShort(height);
os.write(palette.Count - 1);
/* write the individual offsets and dimensions */
for (var i = 0; i < frames.Length; i++)
{
os.writeShort(0); // offset X
os.writeShort(0); // offset Y
os.writeShort(width);
os.writeShort(height);
}
/* write the number of frames */
os.writeShort(frames.Length);
/* convert the stream to a byte array and then wrap a buffer */
var bytes = bout.toByteArray();
return ByteBuffer.wrap(bytes);
}
finally
{
os.close();
}
}
}
}
| |
/*
* Copyright 2021 Google LLC All Rights Reserved.
* Use of this source code is governed by a BSD-style
* license that can be found in the LICENSE file or at
* https://developers.google.com/open-source/licenses/bsd
*/
// <auto-generated>
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/type/datetime.proto
// </auto-generated>
#pragma warning disable 1591, 0612, 3021
#region Designer generated code
using pb = global::Google.Protobuf;
using pbc = global::Google.Protobuf.Collections;
using pbr = global::Google.Protobuf.Reflection;
using scg = global::System.Collections.Generic;
namespace Google.Type {
/// <summary>Holder for reflection information generated from google/type/datetime.proto</summary>
public static partial class DatetimeReflection {
#region Descriptor
/// <summary>File descriptor for google/type/datetime.proto</summary>
public static pbr::FileDescriptor Descriptor {
get { return descriptor; }
}
private static pbr::FileDescriptor descriptor;
static DatetimeReflection() {
byte[] descriptorData = global::System.Convert.FromBase64String(
string.Concat(
"Chpnb29nbGUvdHlwZS9kYXRldGltZS5wcm90bxILZ29vZ2xlLnR5cGUaHmdv",
"b2dsZS9wcm90b2J1Zi9kdXJhdGlvbi5wcm90byLgAQoIRGF0ZVRpbWUSDAoE",
"eWVhchgBIAEoBRINCgVtb250aBgCIAEoBRILCgNkYXkYAyABKAUSDQoFaG91",
"cnMYBCABKAUSDwoHbWludXRlcxgFIAEoBRIPCgdzZWNvbmRzGAYgASgFEg0K",
"BW5hbm9zGAcgASgFEi8KCnV0Y19vZmZzZXQYCCABKAsyGS5nb29nbGUucHJv",
"dG9idWYuRHVyYXRpb25IABIqCgl0aW1lX3pvbmUYCSABKAsyFS5nb29nbGUu",
"dHlwZS5UaW1lWm9uZUgAQg0KC3RpbWVfb2Zmc2V0IicKCFRpbWVab25lEgoK",
"AmlkGAEgASgJEg8KB3ZlcnNpb24YAiABKAlCaQoPY29tLmdvb2dsZS50eXBl",
"Qg1EYXRlVGltZVByb3RvUAFaPGdvb2dsZS5nb2xhbmcub3JnL2dlbnByb3Rv",
"L2dvb2dsZWFwaXMvdHlwZS9kYXRldGltZTtkYXRldGltZfgBAaICA0dUUGIG",
"cHJvdG8z"));
descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData,
new pbr::FileDescriptor[] { global::Google.Protobuf.WellKnownTypes.DurationReflection.Descriptor, },
new pbr::GeneratedClrTypeInfo(null, null, new pbr::GeneratedClrTypeInfo[] {
new pbr::GeneratedClrTypeInfo(typeof(global::Google.Type.DateTime), global::Google.Type.DateTime.Parser, new[]{ "Year", "Month", "Day", "Hours", "Minutes", "Seconds", "Nanos", "UtcOffset", "TimeZone" }, new[]{ "TimeOffset" }, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::Google.Type.TimeZone), global::Google.Type.TimeZone.Parser, new[]{ "Id", "Version" }, null, null, null, null)
}));
}
#endregion
}
#region Messages
/// <summary>
/// Represents civil time (or occasionally physical time).
///
/// This type can represent a civil time in one of a few possible ways:
///
/// * When utc_offset is set and time_zone is unset: a civil time on a calendar
/// day with a particular offset from UTC.
/// * When time_zone is set and utc_offset is unset: a civil time on a calendar
/// day in a particular time zone.
/// * When neither time_zone nor utc_offset is set: a civil time on a calendar
/// day in local time.
///
/// The date is relative to the Proleptic Gregorian Calendar.
///
/// If year is 0, the DateTime is considered not to have a specific year. month
/// and day must have valid, non-zero values.
///
/// This type may also be used to represent a physical time if all the date and
/// time fields are set and either case of the `time_offset` oneof is set.
/// Consider using `Timestamp` message for physical time instead. If your use
/// case also would like to store the user's timezone, that can be done in
/// another field.
///
/// This type is more flexible than some applications may want. Make sure to
/// document and validate your application's limitations.
/// </summary>
public sealed partial class DateTime : pb::IMessage<DateTime>
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
, pb::IBufferMessage
#endif
{
private static readonly pb::MessageParser<DateTime> _parser = new pb::MessageParser<DateTime>(() => new DateTime());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public static pb::MessageParser<DateTime> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public static pbr::MessageDescriptor Descriptor {
get { return global::Google.Type.DatetimeReflection.Descriptor.MessageTypes[0]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public DateTime() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public DateTime(DateTime other) : this() {
year_ = other.year_;
month_ = other.month_;
day_ = other.day_;
hours_ = other.hours_;
minutes_ = other.minutes_;
seconds_ = other.seconds_;
nanos_ = other.nanos_;
switch (other.TimeOffsetCase) {
case TimeOffsetOneofCase.UtcOffset:
UtcOffset = other.UtcOffset.Clone();
break;
case TimeOffsetOneofCase.TimeZone:
TimeZone = other.TimeZone.Clone();
break;
}
_unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public DateTime Clone() {
return new DateTime(this);
}
/// <summary>Field number for the "year" field.</summary>
public const int YearFieldNumber = 1;
private int year_;
/// <summary>
/// Optional. Year of date. Must be from 1 to 9999, or 0 if specifying a
/// datetime without a year.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public int Year {
get { return year_; }
set {
year_ = value;
}
}
/// <summary>Field number for the "month" field.</summary>
public const int MonthFieldNumber = 2;
private int month_;
/// <summary>
/// Required. Month of year. Must be from 1 to 12.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public int Month {
get { return month_; }
set {
month_ = value;
}
}
/// <summary>Field number for the "day" field.</summary>
public const int DayFieldNumber = 3;
private int day_;
/// <summary>
/// Required. Day of month. Must be from 1 to 31 and valid for the year and
/// month.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public int Day {
get { return day_; }
set {
day_ = value;
}
}
/// <summary>Field number for the "hours" field.</summary>
public const int HoursFieldNumber = 4;
private int hours_;
/// <summary>
/// Required. Hours of day in 24 hour format. Should be from 0 to 23. An API
/// may choose to allow the value "24:00:00" for scenarios like business
/// closing time.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public int Hours {
get { return hours_; }
set {
hours_ = value;
}
}
/// <summary>Field number for the "minutes" field.</summary>
public const int MinutesFieldNumber = 5;
private int minutes_;
/// <summary>
/// Required. Minutes of hour of day. Must be from 0 to 59.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public int Minutes {
get { return minutes_; }
set {
minutes_ = value;
}
}
/// <summary>Field number for the "seconds" field.</summary>
public const int SecondsFieldNumber = 6;
private int seconds_;
/// <summary>
/// Required. Seconds of minutes of the time. Must normally be from 0 to 59. An
/// API may allow the value 60 if it allows leap-seconds.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public int Seconds {
get { return seconds_; }
set {
seconds_ = value;
}
}
/// <summary>Field number for the "nanos" field.</summary>
public const int NanosFieldNumber = 7;
private int nanos_;
/// <summary>
/// Required. Fractions of seconds in nanoseconds. Must be from 0 to
/// 999,999,999.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public int Nanos {
get { return nanos_; }
set {
nanos_ = value;
}
}
/// <summary>Field number for the "utc_offset" field.</summary>
public const int UtcOffsetFieldNumber = 8;
/// <summary>
/// UTC offset. Must be whole seconds, between -18 hours and +18 hours.
/// For example, a UTC offset of -4:00 would be represented as
/// { seconds: -14400 }.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public global::Google.Protobuf.WellKnownTypes.Duration UtcOffset {
get { return timeOffsetCase_ == TimeOffsetOneofCase.UtcOffset ? (global::Google.Protobuf.WellKnownTypes.Duration) timeOffset_ : null; }
set {
timeOffset_ = value;
timeOffsetCase_ = value == null ? TimeOffsetOneofCase.None : TimeOffsetOneofCase.UtcOffset;
}
}
/// <summary>Field number for the "time_zone" field.</summary>
public const int TimeZoneFieldNumber = 9;
/// <summary>
/// Time zone.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public global::Google.Type.TimeZone TimeZone {
get { return timeOffsetCase_ == TimeOffsetOneofCase.TimeZone ? (global::Google.Type.TimeZone) timeOffset_ : null; }
set {
timeOffset_ = value;
timeOffsetCase_ = value == null ? TimeOffsetOneofCase.None : TimeOffsetOneofCase.TimeZone;
}
}
private object timeOffset_;
/// <summary>Enum of possible cases for the "time_offset" oneof.</summary>
public enum TimeOffsetOneofCase {
None = 0,
UtcOffset = 8,
TimeZone = 9,
}
private TimeOffsetOneofCase timeOffsetCase_ = TimeOffsetOneofCase.None;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public TimeOffsetOneofCase TimeOffsetCase {
get { return timeOffsetCase_; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public void ClearTimeOffset() {
timeOffsetCase_ = TimeOffsetOneofCase.None;
timeOffset_ = null;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public override bool Equals(object other) {
return Equals(other as DateTime);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public bool Equals(DateTime other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (Year != other.Year) return false;
if (Month != other.Month) return false;
if (Day != other.Day) return false;
if (Hours != other.Hours) return false;
if (Minutes != other.Minutes) return false;
if (Seconds != other.Seconds) return false;
if (Nanos != other.Nanos) return false;
if (!object.Equals(UtcOffset, other.UtcOffset)) return false;
if (!object.Equals(TimeZone, other.TimeZone)) return false;
if (TimeOffsetCase != other.TimeOffsetCase) return false;
return Equals(_unknownFields, other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public override int GetHashCode() {
int hash = 1;
if (Year != 0) hash ^= Year.GetHashCode();
if (Month != 0) hash ^= Month.GetHashCode();
if (Day != 0) hash ^= Day.GetHashCode();
if (Hours != 0) hash ^= Hours.GetHashCode();
if (Minutes != 0) hash ^= Minutes.GetHashCode();
if (Seconds != 0) hash ^= Seconds.GetHashCode();
if (Nanos != 0) hash ^= Nanos.GetHashCode();
if (timeOffsetCase_ == TimeOffsetOneofCase.UtcOffset) hash ^= UtcOffset.GetHashCode();
if (timeOffsetCase_ == TimeOffsetOneofCase.TimeZone) hash ^= TimeZone.GetHashCode();
hash ^= (int) timeOffsetCase_;
if (_unknownFields != null) {
hash ^= _unknownFields.GetHashCode();
}
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public void WriteTo(pb::CodedOutputStream output) {
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
output.WriteRawMessage(this);
#else
if (Year != 0) {
output.WriteRawTag(8);
output.WriteInt32(Year);
}
if (Month != 0) {
output.WriteRawTag(16);
output.WriteInt32(Month);
}
if (Day != 0) {
output.WriteRawTag(24);
output.WriteInt32(Day);
}
if (Hours != 0) {
output.WriteRawTag(32);
output.WriteInt32(Hours);
}
if (Minutes != 0) {
output.WriteRawTag(40);
output.WriteInt32(Minutes);
}
if (Seconds != 0) {
output.WriteRawTag(48);
output.WriteInt32(Seconds);
}
if (Nanos != 0) {
output.WriteRawTag(56);
output.WriteInt32(Nanos);
}
if (timeOffsetCase_ == TimeOffsetOneofCase.UtcOffset) {
output.WriteRawTag(66);
output.WriteMessage(UtcOffset);
}
if (timeOffsetCase_ == TimeOffsetOneofCase.TimeZone) {
output.WriteRawTag(74);
output.WriteMessage(TimeZone);
}
if (_unknownFields != null) {
_unknownFields.WriteTo(output);
}
#endif
}
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) {
if (Year != 0) {
output.WriteRawTag(8);
output.WriteInt32(Year);
}
if (Month != 0) {
output.WriteRawTag(16);
output.WriteInt32(Month);
}
if (Day != 0) {
output.WriteRawTag(24);
output.WriteInt32(Day);
}
if (Hours != 0) {
output.WriteRawTag(32);
output.WriteInt32(Hours);
}
if (Minutes != 0) {
output.WriteRawTag(40);
output.WriteInt32(Minutes);
}
if (Seconds != 0) {
output.WriteRawTag(48);
output.WriteInt32(Seconds);
}
if (Nanos != 0) {
output.WriteRawTag(56);
output.WriteInt32(Nanos);
}
if (timeOffsetCase_ == TimeOffsetOneofCase.UtcOffset) {
output.WriteRawTag(66);
output.WriteMessage(UtcOffset);
}
if (timeOffsetCase_ == TimeOffsetOneofCase.TimeZone) {
output.WriteRawTag(74);
output.WriteMessage(TimeZone);
}
if (_unknownFields != null) {
_unknownFields.WriteTo(ref output);
}
}
#endif
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public int CalculateSize() {
int size = 0;
if (Year != 0) {
size += 1 + pb::CodedOutputStream.ComputeInt32Size(Year);
}
if (Month != 0) {
size += 1 + pb::CodedOutputStream.ComputeInt32Size(Month);
}
if (Day != 0) {
size += 1 + pb::CodedOutputStream.ComputeInt32Size(Day);
}
if (Hours != 0) {
size += 1 + pb::CodedOutputStream.ComputeInt32Size(Hours);
}
if (Minutes != 0) {
size += 1 + pb::CodedOutputStream.ComputeInt32Size(Minutes);
}
if (Seconds != 0) {
size += 1 + pb::CodedOutputStream.ComputeInt32Size(Seconds);
}
if (Nanos != 0) {
size += 1 + pb::CodedOutputStream.ComputeInt32Size(Nanos);
}
if (timeOffsetCase_ == TimeOffsetOneofCase.UtcOffset) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(UtcOffset);
}
if (timeOffsetCase_ == TimeOffsetOneofCase.TimeZone) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(TimeZone);
}
if (_unknownFields != null) {
size += _unknownFields.CalculateSize();
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public void MergeFrom(DateTime other) {
if (other == null) {
return;
}
if (other.Year != 0) {
Year = other.Year;
}
if (other.Month != 0) {
Month = other.Month;
}
if (other.Day != 0) {
Day = other.Day;
}
if (other.Hours != 0) {
Hours = other.Hours;
}
if (other.Minutes != 0) {
Minutes = other.Minutes;
}
if (other.Seconds != 0) {
Seconds = other.Seconds;
}
if (other.Nanos != 0) {
Nanos = other.Nanos;
}
switch (other.TimeOffsetCase) {
case TimeOffsetOneofCase.UtcOffset:
if (UtcOffset == null) {
UtcOffset = new global::Google.Protobuf.WellKnownTypes.Duration();
}
UtcOffset.MergeFrom(other.UtcOffset);
break;
case TimeOffsetOneofCase.TimeZone:
if (TimeZone == null) {
TimeZone = new global::Google.Type.TimeZone();
}
TimeZone.MergeFrom(other.TimeZone);
break;
}
_unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public void MergeFrom(pb::CodedInputStream input) {
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
input.ReadRawMessage(this);
#else
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
_unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
break;
case 8: {
Year = input.ReadInt32();
break;
}
case 16: {
Month = input.ReadInt32();
break;
}
case 24: {
Day = input.ReadInt32();
break;
}
case 32: {
Hours = input.ReadInt32();
break;
}
case 40: {
Minutes = input.ReadInt32();
break;
}
case 48: {
Seconds = input.ReadInt32();
break;
}
case 56: {
Nanos = input.ReadInt32();
break;
}
case 66: {
global::Google.Protobuf.WellKnownTypes.Duration subBuilder = new global::Google.Protobuf.WellKnownTypes.Duration();
if (timeOffsetCase_ == TimeOffsetOneofCase.UtcOffset) {
subBuilder.MergeFrom(UtcOffset);
}
input.ReadMessage(subBuilder);
UtcOffset = subBuilder;
break;
}
case 74: {
global::Google.Type.TimeZone subBuilder = new global::Google.Type.TimeZone();
if (timeOffsetCase_ == TimeOffsetOneofCase.TimeZone) {
subBuilder.MergeFrom(TimeZone);
}
input.ReadMessage(subBuilder);
TimeZone = subBuilder;
break;
}
}
}
#endif
}
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
_unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
case 8: {
Year = input.ReadInt32();
break;
}
case 16: {
Month = input.ReadInt32();
break;
}
case 24: {
Day = input.ReadInt32();
break;
}
case 32: {
Hours = input.ReadInt32();
break;
}
case 40: {
Minutes = input.ReadInt32();
break;
}
case 48: {
Seconds = input.ReadInt32();
break;
}
case 56: {
Nanos = input.ReadInt32();
break;
}
case 66: {
global::Google.Protobuf.WellKnownTypes.Duration subBuilder = new global::Google.Protobuf.WellKnownTypes.Duration();
if (timeOffsetCase_ == TimeOffsetOneofCase.UtcOffset) {
subBuilder.MergeFrom(UtcOffset);
}
input.ReadMessage(subBuilder);
UtcOffset = subBuilder;
break;
}
case 74: {
global::Google.Type.TimeZone subBuilder = new global::Google.Type.TimeZone();
if (timeOffsetCase_ == TimeOffsetOneofCase.TimeZone) {
subBuilder.MergeFrom(TimeZone);
}
input.ReadMessage(subBuilder);
TimeZone = subBuilder;
break;
}
}
}
}
#endif
}
/// <summary>
/// Represents a time zone from the
/// [IANA Time Zone Database](https://www.iana.org/time-zones).
/// </summary>
public sealed partial class TimeZone : pb::IMessage<TimeZone>
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
, pb::IBufferMessage
#endif
{
private static readonly pb::MessageParser<TimeZone> _parser = new pb::MessageParser<TimeZone>(() => new TimeZone());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public static pb::MessageParser<TimeZone> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public static pbr::MessageDescriptor Descriptor {
get { return global::Google.Type.DatetimeReflection.Descriptor.MessageTypes[1]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public TimeZone() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public TimeZone(TimeZone other) : this() {
id_ = other.id_;
version_ = other.version_;
_unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public TimeZone Clone() {
return new TimeZone(this);
}
/// <summary>Field number for the "id" field.</summary>
public const int IdFieldNumber = 1;
private string id_ = "";
/// <summary>
/// IANA Time Zone Database time zone, e.g. "America/New_York".
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public string Id {
get { return id_; }
set {
id_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "version" field.</summary>
public const int VersionFieldNumber = 2;
private string version_ = "";
/// <summary>
/// Optional. IANA Time Zone Database version number, e.g. "2019a".
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public string Version {
get { return version_; }
set {
version_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public override bool Equals(object other) {
return Equals(other as TimeZone);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public bool Equals(TimeZone other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (Id != other.Id) return false;
if (Version != other.Version) return false;
return Equals(_unknownFields, other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public override int GetHashCode() {
int hash = 1;
if (Id.Length != 0) hash ^= Id.GetHashCode();
if (Version.Length != 0) hash ^= Version.GetHashCode();
if (_unknownFields != null) {
hash ^= _unknownFields.GetHashCode();
}
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public void WriteTo(pb::CodedOutputStream output) {
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
output.WriteRawMessage(this);
#else
if (Id.Length != 0) {
output.WriteRawTag(10);
output.WriteString(Id);
}
if (Version.Length != 0) {
output.WriteRawTag(18);
output.WriteString(Version);
}
if (_unknownFields != null) {
_unknownFields.WriteTo(output);
}
#endif
}
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) {
if (Id.Length != 0) {
output.WriteRawTag(10);
output.WriteString(Id);
}
if (Version.Length != 0) {
output.WriteRawTag(18);
output.WriteString(Version);
}
if (_unknownFields != null) {
_unknownFields.WriteTo(ref output);
}
}
#endif
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public int CalculateSize() {
int size = 0;
if (Id.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(Id);
}
if (Version.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(Version);
}
if (_unknownFields != null) {
size += _unknownFields.CalculateSize();
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public void MergeFrom(TimeZone other) {
if (other == null) {
return;
}
if (other.Id.Length != 0) {
Id = other.Id;
}
if (other.Version.Length != 0) {
Version = other.Version;
}
_unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public void MergeFrom(pb::CodedInputStream input) {
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
input.ReadRawMessage(this);
#else
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
_unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
break;
case 10: {
Id = input.ReadString();
break;
}
case 18: {
Version = input.ReadString();
break;
}
}
}
#endif
}
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
_unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
case 10: {
Id = input.ReadString();
break;
}
case 18: {
Version = input.ReadString();
break;
}
}
}
}
#endif
}
#endregion
}
#endregion Designer generated code
| |
// can't use flipped right now - bug in monomac/xam.mac that causes crashing since FlippedView gets disposed incorrectly
// has something to do with using layers (background colors) at the same time
//#define USE_FLIPPED
using System;
using Eto.Drawing;
using Eto.Forms;
#if XAMMAC2
using AppKit;
using Foundation;
using CoreGraphics;
using ObjCRuntime;
using CoreAnimation;
#else
using MonoMac.AppKit;
using MonoMac.Foundation;
using MonoMac.CoreGraphics;
using MonoMac.ObjCRuntime;
using MonoMac.CoreAnimation;
#if Mac64
using CGSize = MonoMac.Foundation.NSSize;
using CGRect = MonoMac.Foundation.NSRect;
using CGPoint = MonoMac.Foundation.NSPoint;
using nfloat = System.Double;
using nint = System.Int64;
using nuint = System.UInt64;
#else
using CGSize = System.Drawing.SizeF;
using CGRect = System.Drawing.RectangleF;
using CGPoint = System.Drawing.PointF;
using nfloat = System.Single;
using nint = System.Int32;
using nuint = System.UInt32;
#endif
#endif
namespace Eto.Mac.Forms.Controls
{
public class ScrollableHandler : MacPanel<NSScrollView, Scrollable, Scrollable.ICallback>, Scrollable.IHandler
{
bool expandContentWidth = true;
bool expandContentHeight = true;
Point scrollPosition;
public override NSView ContainerControl { get { return Control; } }
class EtoScrollView : NSScrollView, IMacControl
{
public WeakReference WeakHandler { get; set; }
public ScrollableHandler Handler
{
get { return (ScrollableHandler)WeakHandler.Target; }
set { WeakHandler = new WeakReference(value); }
}
public override void ResetCursorRects()
{
var cursor = Handler.Cursor;
if (cursor != null)
AddCursorRect(new CGRect(CGPoint.Empty, Frame.Size), cursor.ControlObject as NSCursor);
}
}
class FlippedView : NSView
{
public WeakReference WeakHandler { get; set; }
public ScrollableHandler Handler
{
get { return (ScrollableHandler)WeakHandler.Target; }
set { WeakHandler = new WeakReference(value); }
}
#if USE_FLIPPED
public override bool IsFlipped
{
get { return true; }
}
#endif
#if !USE_FLIPPED
public override void SetFrameSize(CGSize newSize)
{
base.SetFrameSize(newSize);
Handler.SetPosition(Handler.scrollPosition, true);
}
#endif
}
public ScrollableHandler()
{
Enabled = true;
Control = new EtoScrollView
{
Handler = this,
BackgroundColor = NSColor.Control,
BorderType = NSBorderType.BezelBorder,
DrawsBackground = false,
HasVerticalScroller = true,
HasHorizontalScroller = true,
AutohidesScrollers = true,
DocumentView = new FlippedView { Handler = this }
};
// only draw dirty regions, instead of entire scroll area
Control.ContentView.CopiesOnScroll = true;
}
protected override void Initialize()
{
base.Initialize();
if (!ContentControl.IsFlipped)
// need to keep the scroll position as it scrolls instead of calculating
HandleEvent(Scrollable.ScrollEvent);
}
public override void AttachEvent(string id)
{
switch (id)
{
case Scrollable.ScrollEvent:
Control.ContentView.PostsBoundsChangedNotifications = true;
AddObserver(NSView.BoundsChangedNotification, e =>
{
var handler = e.Handler as ScrollableHandler;
if (handler != null)
{
var view = handler.ContentControl;
if (!view.IsFlipped)
{
var contentBounds = handler.Control.ContentView.Bounds;
if (contentBounds.Height > 0)
handler.scrollPosition = new Point((int)contentBounds.X, (int)Math.Max(0, (view.Frame.Height - contentBounds.Height - contentBounds.Y)));
}
handler.Callback.OnScroll(handler.Widget, new ScrollEventArgs(handler.ScrollPosition));
}
}, Control.ContentView);
break;
default:
base.AttachEvent(id);
break;
}
}
public BorderType Border
{
get
{
switch (Control.BorderType)
{
case NSBorderType.BezelBorder:
return BorderType.Bezel;
case NSBorderType.LineBorder:
return BorderType.Line;
case NSBorderType.NoBorder:
return BorderType.None;
default:
throw new NotSupportedException();
}
}
set
{
switch (value)
{
case BorderType.Bezel:
Control.BorderType = NSBorderType.BezelBorder;
break;
case BorderType.Line:
Control.BorderType = NSBorderType.LineBorder;
break;
case BorderType.None:
Control.BorderType = NSBorderType.NoBorder;
break;
default:
throw new NotSupportedException();
}
}
}
public override NSView ContentControl
{
get { return (NSView)Control.DocumentView; }
}
public override void LayoutChildren()
{
base.LayoutChildren();
UpdateScrollSizes();
}
public override void OnLoadComplete(EventArgs e)
{
base.OnLoadComplete(e);
UpdateScrollSizes();
}
Size GetBorderSize()
{
return Border == BorderType.None ? Size.Empty : new Size(2, 2);
}
protected override SizeF GetNaturalSize(SizeF availableSize)
{
return SizeF.Min(availableSize, base.GetNaturalSize(availableSize) + GetBorderSize());
}
protected override CGRect GetContentBounds()
{
var contentSize = Content.GetPreferredSize(SizeF.MaxValue);
if (ExpandContentWidth)
contentSize.Width = Math.Max(ClientSize.Width, contentSize.Width);
if (ExpandContentHeight)
contentSize.Height = Math.Max(ClientSize.Height, contentSize.Height);
return new RectangleF(contentSize).ToNS();
}
protected override NSViewResizingMask ContentResizingMask()
{
return ContentControl.IsFlipped ? base.ContentResizingMask() : (NSViewResizingMask)0;
}
void InternalSetFrameSize(CGSize size)
{
var view = ContentControl;
if (!view.IsFlipped)
{
var ctl = Content.GetContainerView();
if (ctl != null)
{
var clientHeight = Control.DocumentVisibleRect.Size.Height;
ctl.Frame = new CGRect(new CGPoint(0, (nfloat)Math.Max(0, clientHeight - size.Height)), size);
size.Height = (nfloat)Math.Max(clientHeight, size.Height);
}
}
if (size != view.Frame.Size)
{
view.SetFrameSize(size);
}
}
public void UpdateScrollSizes()
{
InternalSetFrameSize(GetContentBounds().Size);
}
public override Color BackgroundColor
{
get
{
return Control.BackgroundColor.ToEto();
}
set
{
Control.BackgroundColor = value.ToNSUI();
Control.DrawsBackground = value.A > 0;
}
}
public Point ScrollPosition
{
get
{
var view = ContentControl;
if (Widget.Loaded && view.IsFlipped)
{
return Control.ContentView.Bounds.Location.ToEtoPoint();
}
return scrollPosition;
}
set
{
SetPosition(value, false);
}
}
void SetPosition(Point value, bool force)
{
if (Widget.Loaded || force)
{
var view = ContentControl;
if (view.IsFlipped)
Control.ContentView.ScrollToPoint(value.ToNS());
else if (Control.ContentView.Frame.Height > 0)
Control.ContentView.ScrollToPoint(new CGPoint(value.X, (nfloat)Math.Max(0, view.Frame.Height - Control.ContentView.Frame.Height - value.Y)));
Control.ReflectScrolledClipView(Control.ContentView);
}
scrollPosition = value;
}
public Size ScrollSize
{
get { return ContentControl.Frame.Size.ToEtoSize(); }
set
{
InternalSetFrameSize(value.ToNS());
}
}
public override Size ClientSize
{
get
{
return Control.DocumentVisibleRect.Size.ToEtoSize();
}
set
{
}
}
public override bool Enabled { get; set; }
public override void SetContentSize(CGSize contentSize)
{
if (MinimumSize != Size.Empty)
{
contentSize.Width = (nfloat)Math.Max(contentSize.Width, MinimumSize.Width);
contentSize.Height = (nfloat)Math.Max(contentSize.Height, MinimumSize.Height);
}
if (ExpandContentWidth)
contentSize.Width = (nfloat)Math.Max(ClientSize.Width, contentSize.Width);
if (ExpandContentHeight)
contentSize.Height = (nfloat)Math.Max(ClientSize.Height, contentSize.Height);
InternalSetFrameSize(contentSize);
}
#if !USE_FLIPPED
public override void OnSizeChanged(EventArgs e)
{
base.OnSizeChanged(e);
UpdateScrollSizes();
SetPosition(scrollPosition, true);
}
#endif
public Rectangle VisibleRect
{
get { return new Rectangle(ScrollPosition, Size.Min(ScrollSize, ClientSize)); }
}
public bool ExpandContentWidth
{
get { return expandContentWidth; }
set
{
if (expandContentWidth != value)
{
expandContentWidth = value;
UpdateScrollSizes();
}
}
}
public bool ExpandContentHeight
{
get { return expandContentHeight; }
set
{
if (expandContentHeight != value)
{
expandContentHeight = value;
UpdateScrollSizes();
}
}
}
public float MinimumZoom { get { return 1f; } set { } }
public float MaximumZoom { get { return 1f; } set { } }
public float Zoom { get { return 1f; } set { } }
}
}
| |
// Python Tools for Visual Studio
// Copyright(c) Microsoft Corporation
// All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the License); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at http://www.apache.org/licenses/LICENSE-2.0
//
// THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS
// OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY
// IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
// MERCHANTABLITY OR NON-INFRINGEMENT.
//
// See the Apache Version 2.0 License for specific language governing
// permissions and limitations under the License.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Input;
using Microsoft.PythonTools.Infrastructure;
using Microsoft.PythonTools.Interpreter;
using Microsoft.PythonTools.Logging;
using Microsoft.PythonTools.Project;
using Microsoft.PythonTools.Project.Web;
using Microsoft.VisualStudioTools;
using Microsoft.VisualStudioTools.Project;
namespace Microsoft.PythonTools.Commands {
/// <summary>
/// Provides the command for starting a file or the start item of a project in the REPL window.
/// </summary>
internal sealed class DiagnosticsCommand : Command {
private readonly IServiceProvider _serviceProvider;
private static readonly IEnumerable<string> InterestingDteProperties = new[] {
"InterpreterId",
"InterpreterVersion",
"StartupFile",
"WorkingDirectory",
"PublishUrl",
"SearchPath",
"CommandLineArguments",
"InterpreterPath"
};
private static readonly IEnumerable<string> InterestingProjectProperties = new[] {
"ClusterRunEnvironment",
"ClusterPublishBeforeRun",
"ClusterWorkingDir",
"ClusterMpiExecCommand",
"ClusterAppCommand",
"ClusterAppArguments",
"ClusterDeploymentDir",
"ClusterTargetPlatform",
PythonWebLauncher.DebugWebServerTargetProperty,
PythonWebLauncher.DebugWebServerTargetTypeProperty,
PythonWebLauncher.DebugWebServerArgumentsProperty,
PythonWebLauncher.DebugWebServerEnvironmentProperty,
PythonWebLauncher.RunWebServerTargetProperty,
PythonWebLauncher.RunWebServerTargetTypeProperty,
PythonWebLauncher.RunWebServerArgumentsProperty,
PythonWebLauncher.RunWebServerEnvironmentProperty,
PythonWebPropertyPage.StaticUriPatternSetting,
PythonWebPropertyPage.StaticUriRewriteSetting,
PythonWebPropertyPage.WsgiHandlerSetting
};
private static readonly Regex InterestingApplicationLogEntries = new Regex(
@"^Application: (devenv\.exe|.+?Python.+?\.exe|ipy(64)?\.exe)",
RegexOptions.IgnoreCase | RegexOptions.CultureInvariant
);
public DiagnosticsCommand(IServiceProvider serviceProvider) {
_serviceProvider = serviceProvider;
}
public override void DoCommand(object sender, EventArgs args) {
var ui = _serviceProvider.GetUIThread();
var cts = new CancellationTokenSource();
bool skipAnalysisLog = Keyboard.IsKeyDown(Key.LeftShift) || Keyboard.IsKeyDown(Key.RightShift);
var dlg = new DiagnosticsWindow(_serviceProvider, Task.Run(() => GetData(ui, skipAnalysisLog, cts.Token), cts.Token));
dlg.ShowModal();
cts.Cancel();
}
private string GetData(UIThreadBase ui, bool skipAnalysisLog, CancellationToken cancel) {
StringBuilder res = new StringBuilder();
string pythonPathIsMasked = "";
EnvDTE.DTE dte = null;
IPythonInterpreterFactoryProvider[] knownProviders = null;
IPythonLauncherProvider[] launchProviders = null;
InMemoryLogger inMemLogger = null;
ui.Invoke((Action)(() => {
pythonPathIsMasked = _serviceProvider.GetPythonToolsService().GeneralOptions.ClearGlobalPythonPath
? " (masked)"
: "";
dte = (EnvDTE.DTE)_serviceProvider.GetService(typeof(EnvDTE.DTE));
var model = _serviceProvider.GetComponentModel();
knownProviders = model.GetExtensions<IPythonInterpreterFactoryProvider>().ToArray();
launchProviders = model.GetExtensions<IPythonLauncherProvider>().ToArray();
inMemLogger = model.GetService<InMemoryLogger>();
}));
res.AppendLine("Projects: ");
var projects = dte.Solution.Projects;
foreach (EnvDTE.Project project in projects) {
cancel.ThrowIfCancellationRequested();
string name;
try {
// Some projects will throw rather than give us a unique
// name. They are not ours, so we will ignore them.
name = project.UniqueName;
} catch (Exception ex) when (!ex.IsCriticalException()) {
bool isPythonProject = false;
try {
isPythonProject = Utilities.GuidEquals(PythonConstants.ProjectFactoryGuid, project.Kind);
} catch (Exception ex2) when (!ex2.IsCriticalException()) {
}
if (isPythonProject) {
// Actually, it was one of our projects, so we do care
// about the exception. We'll add it to the output,
// rather than crashing.
res.AppendLine(" Project: " + ex.Message);
res.AppendLine(" Kind: Python");
}
continue;
}
res.AppendLine(" Project: " + name);
if (Utilities.GuidEquals(PythonConstants.ProjectFactoryGuid, project.Kind)) {
res.AppendLine(" Kind: Python");
foreach (var prop in InterestingDteProperties) {
res.AppendLine(" " + prop + ": " + GetProjectProperty(project, prop));
}
var pyProj = project.GetPythonProject();
if (pyProj != null) {
ui.Invoke((Action)(() => {
foreach (var prop in InterestingProjectProperties) {
var propValue = pyProj.GetProjectProperty(prop);
if (propValue != null) {
res.AppendLine(" " + prop + ": " + propValue);
}
}
}));
foreach (var factory in pyProj.InterpreterFactories) {
res.AppendLine();
res.AppendLine(" Interpreter: " + factory.Configuration.Description);
res.AppendLine(" Id: " + factory.Configuration.Id);
res.AppendLine(" Version: " + factory.Configuration.Version);
res.AppendLine(" Arch: " + factory.Configuration.Architecture);
res.AppendLine(" Prefix Path: " + factory.Configuration.PrefixPath ?? "(null)");
res.AppendLine(" Path: " + factory.Configuration.InterpreterPath ?? "(null)");
res.AppendLine(" Windows Path: " + factory.Configuration.WindowsInterpreterPath ?? "(null)");
res.AppendLine(string.Format(" Path Env: {0}={1}{2}",
factory.Configuration.PathEnvironmentVariable ?? "(null)",
Environment.GetEnvironmentVariable(factory.Configuration.PathEnvironmentVariable ?? ""),
pythonPathIsMasked
));
}
}
} else {
res.AppendLine(" Kind: " + project.Kind);
}
res.AppendLine();
}
res.AppendLine("Environments: ");
foreach (var provider in knownProviders.MaybeEnumerate()) {
cancel.ThrowIfCancellationRequested();
res.AppendLine(" " + provider.GetType().FullName);
foreach (var config in provider.GetInterpreterConfigurations()) {
res.AppendLine(" Id: " + config.Id);
res.AppendLine(" Factory: " + config.Description);
res.AppendLine(" Version: " + config.Version);
res.AppendLine(" Arch: " + config.Architecture);
res.AppendLine(" Prefix Path: " + config.PrefixPath ?? "(null)");
res.AppendLine(" Path: " + config.InterpreterPath ?? "(null)");
res.AppendLine(" Windows Path: " + config.WindowsInterpreterPath ?? "(null)");
res.AppendLine(" Path Env: " + config.PathEnvironmentVariable ?? "(null)");
res.AppendLine();
}
}
res.AppendLine("Launchers:");
foreach (var launcher in launchProviders.MaybeEnumerate()) {
cancel.ThrowIfCancellationRequested();
res.AppendLine(" Launcher: " + launcher.GetType().FullName);
res.AppendLine(" " + launcher.Description);
res.AppendLine(" " + launcher.Name);
res.AppendLine();
}
try {
res.AppendLine("Logged events/stats:");
res.AppendLine(inMemLogger.ToString());
res.AppendLine();
} catch (Exception ex) when (!ex.IsCriticalException()) {
res.AppendLine(" Failed to access event log.");
res.AppendLine(ex.ToString());
res.AppendLine();
}
if (!skipAnalysisLog) {
try {
res.AppendLine("System events:");
var application = new EventLog("Application");
var lastWeek = DateTime.Now.Subtract(TimeSpan.FromDays(7));
foreach (var entry in application.Entries.Cast<EventLogEntry>()
.Where(e => e.InstanceId == 1026L) // .NET Runtime
.Where(e => e.TimeGenerated >= lastWeek)
.Where(e => InterestingApplicationLogEntries.IsMatch(e.Message))
.OrderByDescending(e => e.TimeGenerated)
) {
res.AppendLine(string.Format("Time: {0:s}", entry.TimeGenerated));
using (var reader = new StringReader(entry.Message.TrimEnd())) {
for (var line = reader.ReadLine(); line != null; line = reader.ReadLine()) {
res.AppendLine(line);
}
}
res.AppendLine();
}
} catch (Exception ex) when (!ex.IsCriticalException()) {
res.AppendLine(" Failed to access event log.");
res.AppendLine(ex.ToString());
res.AppendLine();
}
}
res.AppendLine("Loaded assemblies:");
foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies().OrderBy(assem => assem.FullName)) {
cancel.ThrowIfCancellationRequested();
AssemblyFileVersionAttribute assemFileVersion;
var error = "(null)";
try {
assemFileVersion = assembly.GetCustomAttributes(typeof(AssemblyFileVersionAttribute), false)
.OfType<AssemblyFileVersionAttribute>()
.FirstOrDefault();
} catch (Exception e) when (!e.IsCriticalException()) {
assemFileVersion = null;
error = string.Format("{0}: {1}", e.GetType().Name, e.Message);
}
res.AppendLine(string.Format(" {0}, FileVersion={1}",
assembly.FullName,
assemFileVersion?.Version ?? error
));
}
res.AppendLine();
string globalAnalysisLog = PythonTypeDatabase.GlobalLogFilename;
if (File.Exists(globalAnalysisLog)) {
res.AppendLine("Global Analysis:");
try {
res.AppendLine(File.ReadAllText(globalAnalysisLog));
} catch (Exception ex) when (!ex.IsCriticalException()) {
res.AppendLine("Error reading the global analysis log.");
res.AppendLine("Please wait for analysis to complete and try again.");
res.AppendLine(ex.ToString());
}
}
res.AppendLine();
if (!skipAnalysisLog) {
res.AppendLine("Environment Analysis Logs: ");
foreach (var provider in knownProviders) {
foreach (var factory in provider.GetInterpreterFactories().OfType<IPythonInterpreterFactoryWithDatabase>()) {
cancel.ThrowIfCancellationRequested();
res.AppendLine(factory.Configuration.Description);
string analysisLog = factory.GetAnalysisLogContent(CultureInfo.InvariantCulture);
if (!string.IsNullOrEmpty(analysisLog)) {
res.AppendLine(analysisLog);
}
res.AppendLine();
}
}
}
return res.ToString();
}
private static string GetProjectProperty(EnvDTE.Project project, string name) {
try {
return project.Properties.Item(name).Value.ToString();
} catch {
return "<undefined>";
}
}
public override int CommandId {
get { return (int)PkgCmdIDList.cmdidDiagnostics; }
}
}
}
| |
using System;
using System.Text;
using BigMath;
using NUnit.Framework;
using Raksha.Crypto;
using Raksha.Crypto.Digests;
using Raksha.Crypto.Generators;
using Raksha.Crypto.Parameters;
using Raksha.Crypto.Signers;
using Raksha.Math;
using Raksha.Math.EC;
using Raksha.Security;
using Raksha.Utilities.Encoders;
using Raksha.Tests.Utilities;
namespace Raksha.Tests.Crypto
{
/**
* ECGOST3410 tests are taken from GOST R 34.10-2001.
*/
[TestFixture]
public class ECGost3410Test
: SimpleTest
{
private static readonly byte[] hashmessage = Hex.Decode("3042453136414534424341374533364339313734453431443642453241453435");
/**
* ECGOST3410 over the field Fp<br/>
*/
BigInteger r = new BigInteger("29700980915817952874371204983938256990422752107994319651632687982059210933395");
BigInteger s = new BigInteger("574973400270084654178925310019147038455227042649098563933718999175515839552");
byte[] kData = new BigInteger("53854137677348463731403841147996619241504003434302020712960838528893196233395").ToByteArray();
private readonly SecureRandom k;
public ECGost3410Test()
{
k = FixedSecureRandom.From(kData);
}
private void ecGOST3410_TEST()
{
BigInteger mod_p = new BigInteger("57896044618658097711785492504343953926634992332820282019728792003956564821041"); //p
FpCurve curve = new FpCurve(
mod_p, // p
new BigInteger("7"), // a
new BigInteger("43308876546767276905765904595650931995942111794451039583252968842033849580414")); // b
ECDomainParameters parameters = new ECDomainParameters(
curve,
new FpPoint(curve,
new FpFieldElement(mod_p,new BigInteger("2")), // x
new FpFieldElement(mod_p,new BigInteger("4018974056539037503335449422937059775635739389905545080690979365213431566280"))), // y
new BigInteger("57896044618658097711785492504343953927082934583725450622380973592137631069619")); // q
ECPrivateKeyParameters priKey = new ECPrivateKeyParameters(
"ECGOST3410",
new BigInteger("55441196065363246126355624130324183196576709222340016572108097750006097525544"), // d
parameters);
ParametersWithRandom param = new ParametersWithRandom(priKey, k);
ECGost3410Signer ecgost3410 = new ECGost3410Signer();
ecgost3410.Init(true, param);
byte[] mVal = new BigInteger("20798893674476452017134061561508270130637142515379653289952617252661468872421").ToByteArray();
byte[] message = new byte[mVal.Length];
for (int i = 0; i != mVal.Length; i++)
{
message[i] = mVal[mVal.Length - 1 - i];
}
BigInteger[] sig = ecgost3410.GenerateSignature(message);
if (!r.Equals(sig[0]))
{
Fail("r component wrong.", r, sig[0]);
}
if (!s.Equals(sig[1]))
{
Fail("s component wrong.", s, sig[1]);
}
// Verify the signature
ECPublicKeyParameters pubKey = new ECPublicKeyParameters(
"ECGOST3410",
new FpPoint(curve,
new FpFieldElement(mod_p, new BigInteger("57520216126176808443631405023338071176630104906313632182896741342206604859403")), // x
new FpFieldElement(mod_p, new BigInteger("17614944419213781543809391949654080031942662045363639260709847859438286763994"))), // y
parameters);
ecgost3410.Init(false, pubKey);
if (!ecgost3410.VerifySignature(message, sig[0], sig[1]))
{
Fail("verification fails");
}
}
/**
* Test Sign and Verify with test parameters
* see: http://www.ietf.org/internet-drafts/draft-popov-cryptopro-cpalgs-01.txt
* gostR3410-2001-TestParamSet P.46
*/
private void ecGOST3410_TestParam()
{
SecureRandom random = new SecureRandom();
BigInteger mod_p = new BigInteger("57896044618658097711785492504343953926634992332820282019728792003956564821041"); //p
FpCurve curve = new FpCurve(
mod_p, // p
new BigInteger("7"), // a
new BigInteger("43308876546767276905765904595650931995942111794451039583252968842033849580414")); // b
ECDomainParameters parameters = new ECDomainParameters(
curve,
new FpPoint(curve,
new FpFieldElement(mod_p,new BigInteger("2")), // x
new FpFieldElement(mod_p,new BigInteger("4018974056539037503335449422937059775635739389905545080690979365213431566280"))), // y
new BigInteger("57896044618658097711785492504343953927082934583725450622380973592137631069619")); // q
ECKeyPairGenerator pGen = new ECKeyPairGenerator();
ECKeyGenerationParameters genParam = new ECKeyGenerationParameters(
parameters,
random);
pGen.Init(genParam);
AsymmetricCipherKeyPair pair = pGen.GenerateKeyPair();
ParametersWithRandom param = new ParametersWithRandom(pair.Private, random);
ECGost3410Signer ecgost3410 = new ECGost3410Signer();
ecgost3410.Init(true, param);
//get hash message using the digest GOST3411.
byte[] message = Encoding.ASCII.GetBytes("Message for sign");
Gost3411Digest gost3411 = new Gost3411Digest();
gost3411.BlockUpdate(message, 0, message.Length);
byte[] hashmessage = new byte[gost3411.GetDigestSize()];
gost3411.DoFinal(hashmessage, 0);
BigInteger[] sig = ecgost3410.GenerateSignature(hashmessage);
ecgost3410.Init(false, pair.Public);
if (!ecgost3410.VerifySignature(hashmessage, sig[0], sig[1]))
{
Fail("signature fails");
}
}
/**
* Test Sign and Verify with A parameters
* see: http://www.ietf.org/internet-drafts/draft-popov-cryptopro-cpalgs-01.txt
* gostR3410-2001-CryptoPro-A-ParamSet P.47
*/
public void ecGOST3410_AParam()
{
SecureRandom random = new SecureRandom();
BigInteger mod_p = new BigInteger("115792089237316195423570985008687907853269984665640564039457584007913129639319"); //p
FpCurve curve = new FpCurve(
mod_p, // p
new BigInteger("115792089237316195423570985008687907853269984665640564039457584007913129639316"), // a
new BigInteger("166")); // b
ECDomainParameters parameters = new ECDomainParameters(
curve,
new FpPoint(curve,
new FpFieldElement(mod_p, new BigInteger("1")), // x
new FpFieldElement(mod_p, new BigInteger("64033881142927202683649881450433473985931760268884941288852745803908878638612"))), // y
new BigInteger("115792089237316195423570985008687907853073762908499243225378155805079068850323")); // q
ECKeyPairGenerator pGen = new ECKeyPairGenerator("ECGOST3410");
ECKeyGenerationParameters genParam = new ECKeyGenerationParameters(
parameters,
random);
pGen.Init(genParam);
AsymmetricCipherKeyPair pair = pGen.GenerateKeyPair();
ParametersWithRandom param = new ParametersWithRandom(pair.Private, random);
ECGost3410Signer ecgost3410 = new ECGost3410Signer();
ecgost3410.Init(true, param);
BigInteger[] sig = ecgost3410.GenerateSignature(hashmessage);
ecgost3410.Init(false, pair.Public);
if (!ecgost3410.VerifySignature(hashmessage, sig[0], sig[1]))
{
Fail("signature fails");
}
}
/**
* Test Sign and Verify with B parameters
* see: http://www.ietf.org/internet-drafts/draft-popov-cryptopro-cpalgs-01.txt
* gostR3410-2001-CryptoPro-B-ParamSet P.47-48
*/
private void ecGOST3410_BParam()
{
SecureRandom random = new SecureRandom();
BigInteger mod_p = new BigInteger("57896044618658097711785492504343953926634992332820282019728792003956564823193"); //p
FpCurve curve = new FpCurve(
mod_p, // p
new BigInteger("57896044618658097711785492504343953926634992332820282019728792003956564823190"), // a
new BigInteger("28091019353058090096996979000309560759124368558014865957655842872397301267595")); // b
ECDomainParameters parameters = new ECDomainParameters(
curve,
new FpPoint(curve,
new FpFieldElement(mod_p,new BigInteger("1")), // x
new FpFieldElement(mod_p,new BigInteger("28792665814854611296992347458380284135028636778229113005756334730996303888124"))), // y
new BigInteger("57896044618658097711785492504343953927102133160255826820068844496087732066703")); // q
ECKeyPairGenerator pGen = new ECKeyPairGenerator("ECGOST3410");
ECKeyGenerationParameters genParam = new ECKeyGenerationParameters(
parameters,
random);
pGen.Init(genParam);
AsymmetricCipherKeyPair pair = pGen.GenerateKeyPair();
ParametersWithRandom param = new ParametersWithRandom(pair.Private, random);
ECGost3410Signer ecgost3410 = new ECGost3410Signer();
ecgost3410.Init(true, param);
BigInteger[] sig = ecgost3410.GenerateSignature(hashmessage);
ecgost3410.Init(false, pair.Public);
if (!ecgost3410.VerifySignature(hashmessage, sig[0], sig[1]))
{
Fail("signature fails");
}
}
/**
* Test Sign and Verify with C parameters
* see: http://www.ietf.org/internet-drafts/draft-popov-cryptopro-cpalgs-01.txt
* gostR3410-2001-CryptoPro-C-ParamSet P.48
*/
private void ecGOST3410_CParam()
{
SecureRandom random = new SecureRandom();
BigInteger mod_p = new BigInteger("70390085352083305199547718019018437841079516630045180471284346843705633502619"); //p
FpCurve curve = new FpCurve(
mod_p, // p
new BigInteger("70390085352083305199547718019018437841079516630045180471284346843705633502616"), // a
new BigInteger("32858")); // b
ECDomainParameters parameters = new ECDomainParameters(
curve,
new FpPoint(curve,
new FpFieldElement(mod_p,new BigInteger("0")), // x
new FpFieldElement(mod_p,new BigInteger("29818893917731240733471273240314769927240550812383695689146495261604565990247"))), // y
new BigInteger("70390085352083305199547718019018437840920882647164081035322601458352298396601")); // q
ECKeyPairGenerator pGen = new ECKeyPairGenerator("ECGOST3410");
ECKeyGenerationParameters genParam = new ECKeyGenerationParameters(
parameters,
random);
pGen.Init(genParam);
AsymmetricCipherKeyPair pair = pGen.GenerateKeyPair();
ParametersWithRandom param = new ParametersWithRandom(pair.Private, random);
ECGost3410Signer ecgost3410 = new ECGost3410Signer();
ecgost3410.Init(true, param);
BigInteger[] sig = ecgost3410.GenerateSignature(hashmessage);
ecgost3410.Init(false, pair.Public);
if (!ecgost3410.VerifySignature(hashmessage, sig[0], sig[1]))
{
Fail("signature fails");
}
}
public override string Name
{
get { return "ECGOST3410"; }
}
public override void PerformTest()
{
ecGOST3410_TEST();
ecGOST3410_TestParam();
ecGOST3410_AParam();
ecGOST3410_BParam();
ecGOST3410_CParam();
}
public static void Main(
string[] args)
{
ECGost3410Test test = new ECGost3410Test();
ITestResult result = test.Perform();
Console.WriteLine(result);
}
[Test]
public void TestFunction()
{
string resultText = Perform().ToString();
Assert.AreEqual(Name + ": Okay", resultText);
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
extern alias T1;
using System;
using System.Globalization;
using System.Linq;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
using Azure;
using Azure.Core.TestFramework;
using Azure.Data.Tables;
using Microsoft.Extensions.Hosting;
using Newtonsoft.Json.Linq;
using NUnit.Framework;
namespace Microsoft.Azure.WebJobs.Extensions.Tables.Tests
{
// Can't record V4
[LiveOnly]
public class CompatibilityTests: TablesLiveTestBase
{
private static DateTimeOffset DateTimeOffsetValue = DateTimeOffset.Parse("07-08-1997", null, DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal);
private static DateTime DateTimeValue = DateTime.Parse("07-08-1997", null, DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal);
public CompatibilityTests(bool isAsync, bool useCosmos) : base(isAsync, useCosmos)
{
}
[Test]
[TestCaseSource(nameof(SdkExtensionPermutations))]
public async Task CanSavePocoAndLoadITableEntityWithNullables(ITablesClient writer, ITablesClient reader)
{
var testEntity = new TestITableEntity()
{
PartitionKey = PartitionKey,
RowKey = RowKey,
// SDK can't handle overflow in longs
UInt64TypeProperty = long.MaxValue,
Int64TypeProperty = long.MaxValue,
};
await writer.Write(this, testEntity);
var output = await reader.Read<TestITableEntity>(this);
AssertAreEqual(testEntity, output);
}
[Test]
[TestCaseSource(nameof(SdkExtensionPermutations))]
public async Task CanSavePocoAndLoadITableEntityWithNullablesSet(ITablesClient writer, ITablesClient reader)
{
var testEntity = new TestITableEntity(true)
{
PartitionKey = PartitionKey,
RowKey = RowKey,
// SDK can't handle overflow in longs
UInt64TypeProperty = long.MaxValue,
Int64TypeProperty = long.MaxValue,
NullableUInt64TypeProperty = long.MaxValue,
NullableInt64TypeProperty = long.MaxValue,
};
await writer.Write(this, testEntity);
var output = await reader.Read<TestITableEntity>(this);
AssertAreEqual(testEntity, output);
}
[Test]
[TestCaseSource(nameof(T1T2ExtensionPermutations))]
public async Task CanSavePocoAndLoadPoco(ITablesClient writer, ITablesClient reader)
{
var testEntity = new TestEntity()
{
PartitionKey = PartitionKey,
RowKey = RowKey,
// SDK can't handle overflow in longs
UInt64TypeProperty = long.MaxValue,
Int64TypeProperty = long.MaxValue,
};
await writer.Write(this, testEntity);
var output = await reader.Read<TestEntity>(this);
AssertAreEqual(testEntity, output);
}
[Test]
[TestCaseSource(nameof(T1T2ExtensionPermutations))]
public async Task CanSavePocoAndLoadPocoWithNullablesSet(ITablesClient writer, ITablesClient reader)
{
var testEntity = new TestEntity(true)
{
PartitionKey = PartitionKey,
RowKey = RowKey
};
await writer.Write(this, testEntity);
var output = await reader.Read<TestEntity>(this);
AssertAreEqual(testEntity, output);
}
[Test]
[TestCaseSource(nameof(T1T2ExtensionPermutations))]
public async Task CanSavePocoAndLoadPocoWithInnerPoco(ITablesClient writer, ITablesClient reader)
{
var testEntity = new TestEntity(true)
{
PartitionKey = PartitionKey,
RowKey = RowKey,
NestedEntity = new TestEntity(true)
};
await writer.Write(this, testEntity);
var output = await reader.Read<TestEntity>(this);
AssertAreEqual(testEntity, output);
AssertAreEqual(testEntity.NestedEntity, output.NestedEntity);
}
[Test]
[TestCaseSource(nameof(T1T2ExtensionPermutations))]
public async Task CanSavePocoAndLoadJObject(ITablesClient writer, ITablesClient reader)
{
if (UseCosmos && writer is Extension && reader is ExtensionT1)
{
Assert.Ignore("https://github.com/Azure/azure-webjobs-sdk/issues/2813");
}
var testEntity = new TestEntity()
{
PartitionKey = PartitionKey,
RowKey = RowKey,
// V4 can't handle longs in JObject
UInt64TypeProperty = int.MaxValue,
Int64TypeProperty = int.MaxValue,
NullableUInt64TypeProperty = int.MaxValue,
NullableInt64TypeProperty = int.MaxValue,
};
await writer.Write(this, testEntity);
var outputA = await writer.Read<JObject>(this);
var outputB = await reader.Read<JObject>(this);
AssertAreEqual(outputA, outputB);
}
[Test]
[TestCaseSource(nameof(T1T2ExtensionPermutations))]
public async Task CanSavePocoAndLoadJObjectWithNullablesSet(ITablesClient writer, ITablesClient reader)
{
if (UseCosmos && writer is Extension && reader is ExtensionT1)
{
Assert.Ignore("https://github.com/Azure/azure-webjobs-sdk/issues/2813");
}
var testEntity = new TestEntity(true)
{
PartitionKey = PartitionKey,
RowKey = RowKey,
// V4 can't handle longs in JObject
UInt64TypeProperty = int.MaxValue,
Int64TypeProperty = int.MaxValue,
NullableUInt64TypeProperty = int.MaxValue,
NullableInt64TypeProperty = int.MaxValue,
};
await writer.Write(this, testEntity);
var outputA = await writer.Read<JObject>(this);
var outputB = await reader.Read<JObject>(this);
AssertAreEqual(outputA, outputB);
}
[Test]
[TestCaseSource(nameof(T1T2ExtensionPermutations))]
public async Task CanSavePocoAndLoadJObjectWithInnerPoco(ITablesClient writer, ITablesClient reader)
{
if (UseCosmos && writer is Extension && reader is ExtensionT1)
{
Assert.Ignore("https://github.com/Azure/azure-webjobs-sdk/issues/2813");
}
var testEntity = new TestEntity(true)
{
PartitionKey = PartitionKey,
RowKey = RowKey,
NestedEntity = new TestEntity(true),
// V4 can't handle longs in JObject
UInt64TypeProperty = int.MaxValue,
Int64TypeProperty = int.MaxValue,
NullableUInt64TypeProperty = int.MaxValue,
NullableInt64TypeProperty = int.MaxValue,
};
await writer.Write(this, testEntity);
var outputA = await writer.Read<JObject>(this);
var outputB = await reader.Read<JObject>(this);
AssertAreEqual(outputA, outputB);
}
[Test]
[TestCaseSource(nameof(T1T2ExtensionPermutations))]
public async Task CanSaveJObjectAndLoadJObject(ITablesClient writer, ITablesClient reader)
{
if (UseCosmos && writer is Extension && reader is ExtensionT1)
{
Assert.Ignore("https://github.com/Azure/azure-webjobs-sdk/issues/2813");
}
var testEntity = FormatJObject(new TestEntity()
{
PartitionKey = PartitionKey,
RowKey = RowKey,
// V4 can't handle longs in JObject
UInt64TypeProperty = int.MaxValue,
Int64TypeProperty = int.MaxValue,
NullableUInt64TypeProperty = int.MaxValue,
NullableInt64TypeProperty = int.MaxValue,
});
await writer.Write(this, testEntity);
var outputA = await writer.Read<JObject>(this);
var outputB = await reader.Read<JObject>(this);
AssertAreEqual(outputA, outputB);
}
[Test]
[TestCaseSource(nameof(T1T2ExtensionPermutations))]
public async Task CanSaveJObjectAndLoadJObjectWithNullablesSet(ITablesClient writer, ITablesClient reader)
{
if (UseCosmos && writer is Extension && reader is ExtensionT1)
{
Assert.Ignore("https://github.com/Azure/azure-webjobs-sdk/issues/2813");
}
var testEntity = FormatJObject(new TestEntity(true)
{
PartitionKey = PartitionKey,
RowKey = RowKey,
// V4 can't handle longs in JObject
UInt64TypeProperty = int.MaxValue,
Int64TypeProperty = int.MaxValue,
NullableUInt64TypeProperty = int.MaxValue,
NullableInt64TypeProperty = int.MaxValue,
});
await writer.Write(this, testEntity);
var outputA = await writer.Read<JObject>(this);
var outputB = await reader.Read<JObject>(this);
AssertAreEqual(outputA, outputB);
}
[Test]
[TestCaseSource(nameof(T1T2ExtensionPermutations))]
public async Task CanSaveJObjectAndLoadJObjectWithInnerPoco(ITablesClient writer, ITablesClient reader)
{
if (UseCosmos && writer is Extension && reader is ExtensionT1)
{
Assert.Ignore("https://github.com/Azure/azure-webjobs-sdk/issues/2813");
}
var testEntity = FormatJObject(new TestEntity(true)
{
PartitionKey = PartitionKey,
RowKey = RowKey,
NestedEntity = new TestEntity(true),
// V4 can't handle longs in JObject
UInt64TypeProperty = int.MaxValue,
Int64TypeProperty = int.MaxValue,
NullableUInt64TypeProperty = int.MaxValue,
NullableInt64TypeProperty = int.MaxValue,
});
await writer.Write(this, testEntity);
var outputA = await writer.Read<JObject>(this);
var outputB = await reader.Read<JObject>(this);
AssertAreEqual(outputA, outputB);
}
public static object[] SdkExtensionPermutations { get; } = {
new object[] { Sdk.Instance, Extension.Instance },
new object[] { Extension.Instance, Sdk.Instance },
new object[] { Sdk.Instance, Sdk.Instance },
new object[] { Extension.Instance, Extension.Instance }
};
public static object[] T1T2ExtensionPermutations { get; } = {
new object[] { ExtensionT1.Instance, Extension.Instance },
new object[] { Extension.Instance, ExtensionT1.Instance },
new object[] { ExtensionT1.Instance, ExtensionT1.Instance },
new object[] { Extension.Instance, Extension.Instance }
};
private JObject FormatJObject(object o)
{
var jo = JObject.FromObject(o);
// remove readonly properties
jo.Remove("Timestamp");
jo.Remove("ETag");
return jo;
}
private void AssertAreEqual(JObject a, JObject b)
{
JObject Sort(JObject o)
{
return new JObject(o.Properties().OrderByDescending(p => p.Name));
}
string NormalizeDates(string s)
{
return s.Replace("+00:00", "Z");
}
Assert.AreEqual(
NormalizeDates(Sort(a).ToString()),
NormalizeDates(Sort(b).ToString()));
}
private void AssertAreEqual(object a, object b)
{
Assert.AreEqual(a.GetType(), b.GetType());
foreach (var property in a.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance))
{
if (property.Name is nameof(ITableEntity.Timestamp) or nameof(ITableEntity.ETag) or nameof(TestEntity.NestedEntity)) continue;
var av = property.GetValue(a);
var bv = property.GetValue(b);
Assert.AreEqual(av, bv, property.Name);
}
}
public class TestITableEntity : ITableEntity
{
public TestITableEntity() : this(false)
{
}
public TestITableEntity(bool setNullables)
{
DatetimeOffsetTypeProperty = DateTimeOffsetValue;
DatetimeTypeProperty = DateTimeValue;
StringTypeProperty = "hello";
GuidTypeProperty = Guid.Parse("ca761232-ed42-11ce-bacd-00aa0057b223");
BinaryTypeProperty = new byte[] {1, 2, 3};
Int64TypeProperty = long.MaxValue;
UInt64TypeProperty = ulong.MaxValue;
DoubleTypeProperty = double.MaxValue;
IntTypeProperty = int.MaxValue;
EnumProperty = ConsoleColor.Blue;
if (setNullables)
{
NullableDatetimeTypeProperty = DateTimeValue;
NullableDatetimeOffsetTypeProperty = DateTimeOffsetValue;
NullableGuidTypeProperty = Guid.Parse("ca761232-ed42-11ce-bacd-00aa0057b223");
NullableInt64TypeProperty = long.MaxValue;
NullableUInt64TypeProperty = ulong.MaxValue;
NullableDoubleTypeProperty = double.MaxValue;
NullableIntTypeProperty = int.MaxValue;
NullableEnumProperty = ConsoleColor.Blue;
}
}
public string StringTypeProperty { get; set; }
public DateTime DatetimeTypeProperty { get; set; }
public DateTimeOffset DatetimeOffsetTypeProperty { get; set; }
public Guid GuidTypeProperty { get; set; }
public byte[] BinaryTypeProperty { get; set; }
public long Int64TypeProperty { get; set; }
public ulong UInt64TypeProperty { get; set; }
public double DoubleTypeProperty { get; set; }
public int IntTypeProperty { get; set; }
public ConsoleColor EnumProperty { get; set; }
public DateTime? NullableDatetimeTypeProperty { get; set; }
public DateTimeOffset? NullableDatetimeOffsetTypeProperty { get; set; }
public Guid? NullableGuidTypeProperty { get; set; }
public long? NullableInt64TypeProperty { get; set; }
public ulong? NullableUInt64TypeProperty { get; set; }
public double? NullableDoubleTypeProperty { get; set; }
public int? NullableIntTypeProperty { get; set; }
public ConsoleColor? NullableEnumProperty { get; set; }
public string PartitionKey { get; set; }
public string RowKey { get; set; }
public DateTimeOffset? Timestamp { get; set; }
public ETag ETag { get; set; }
}
public class TestEntity
{
public TestEntity() : this(false)
{
}
public TestEntity(bool setNullables)
{
DatetimeOffsetTypeProperty = DateTimeOffsetValue;
DatetimeTypeProperty = DateTimeValue;
StringTypeProperty = "hello";
GuidTypeProperty = Guid.Parse("ca761232-ed42-11ce-bacd-00aa0057b223");
BinaryTypeProperty = new byte[] {1, 2, 3};
Int64TypeProperty = long.MaxValue;
UInt64TypeProperty = ulong.MaxValue;
DoubleTypeProperty = double.MaxValue;
IntTypeProperty = int.MaxValue;
EnumProperty = ConsoleColor.Blue;
ArrayProperty = new[] { "this", "works" };
if (setNullables)
{
NullableDatetimeTypeProperty = DateTimeValue;
NullableDatetimeOffsetTypeProperty = DateTimeOffsetValue;
NullableGuidTypeProperty = Guid.Parse("ca761232-ed42-11ce-bacd-00aa0057b223");
NullableInt64TypeProperty = long.MaxValue;
NullableUInt64TypeProperty = ulong.MaxValue;
NullableDoubleTypeProperty = double.MaxValue;
NullableIntTypeProperty = int.MaxValue;
NullableEnumProperty = ConsoleColor.Blue;
}
}
public string StringTypeProperty { get; set; }
public DateTime DatetimeTypeProperty { get; set; }
public DateTimeOffset DatetimeOffsetTypeProperty { get; set; }
public Guid GuidTypeProperty { get; set; }
public byte[] BinaryTypeProperty { get; set; }
public long Int64TypeProperty { get; set; }
public ulong UInt64TypeProperty { get; set; }
public double DoubleTypeProperty { get; set; }
public int IntTypeProperty { get; set; }
public ConsoleColor EnumProperty { get; set; }
public string[] ArrayProperty { get; set; }
public DateTime? NullableDatetimeTypeProperty { get; set; }
public DateTimeOffset? NullableDatetimeOffsetTypeProperty { get; set; }
public Guid? NullableGuidTypeProperty { get; set; }
public long? NullableInt64TypeProperty { get; set; }
public ulong? NullableUInt64TypeProperty { get; set; }
public double? NullableDoubleTypeProperty { get; set; }
public int? NullableIntTypeProperty { get; set; }
public ConsoleColor NullableEnumProperty { get; set; }
public string PartitionKey { get; set; }
public string RowKey { get; set; }
public DateTimeOffset Timestamp { get; set; }
public string ETag { get; set; }
public TestEntity NestedEntity { get; set; }
}
public interface ITablesClient
{
ValueTask<T> Read<T>(CompatibilityTests test);
ValueTask Write<T>(CompatibilityTests test, T entity);
}
private class Sdk: ITablesClient
{
public static Sdk Instance = new();
public async ValueTask<T> Read<T>(CompatibilityTests test)
{
return await (Task<Response<T>>)typeof(TableClient)
.GetMethod("GetEntityAsync", BindingFlags.Public | BindingFlags.Instance)
.MakeGenericMethod(typeof(T))
.Invoke(test.TableClient, new object[] { PartitionKey, RowKey, null, default(CancellationToken) });
}
public async ValueTask Write<T>(CompatibilityTests test, T entity)
{
await (Task)typeof(TableClient)
.GetMethod("AddEntityAsync", BindingFlags.Public | BindingFlags.Instance)
.MakeGenericMethod(typeof(T))
.Invoke(test.TableClient, new object[] { entity, default(CancellationToken) });
}
public override string ToString() => "SDK";
}
private class Extension : ITablesClient
{
public static Extension Instance = new();
public async ValueTask<T> Read<T>(CompatibilityTests test)
{
var result = await test.CallAsync<GetEntityProgram<T>>();
return result.Entity;
}
public async ValueTask Write<T>(CompatibilityTests test, T entity)
{
await test.CallAsync<AddEntityProgram<T>>(arguments: new { entity });
}
public override string ToString() => "Extension";
private class AddEntityProgram<T>
{
[return: Table(TableNameExpression)]
public T Call(T entity) => entity;
}
private class GetEntityProgram<T>
{
public void Call([Table(TableNameExpression, PartitionKey, RowKey)] T entity)
{
Entity = entity;
}
public T Entity { get; set; }
}
}
private class ExtensionT1 : ITablesClient
{
public static ExtensionT1 Instance = new();
public async ValueTask<T> Read<T>(CompatibilityTests test)
{
var result = await test.CallAsync<GetEntityProgramT1<T>>(configure: builder => Configure(builder, test));
return result.Entity;
}
public async ValueTask Write<T>(CompatibilityTests test,T entity)
{
await test.CallAsync<AddEntityProgramT1<T>>(arguments: new { entity }, configure: builder => Configure(builder, test));
}
private void Configure(HostBuilder builder, CompatibilityTests test)
{
test.DefaultConfigure(builder);
builder.ConfigureWebJobs(jobsBuilder =>
{
T1::Microsoft.Extensions.Hosting.StorageWebJobsBuilderExtensions.AddAzureStorage(jobsBuilder);
});
}
public override string ToString() => "ExtensionT1";
private class AddEntityProgramT1<T>
{
[return: T1::Microsoft.Azure.WebJobs.Table(TableNameExpression)]
public T Call(T entity) => entity;
}
private class GetEntityProgramT1<T>
{
public void Call([T1::Microsoft.Azure.WebJobs.TableAttribute(TableNameExpression, PartitionKey, RowKey)] T entity)
{
Entity = entity;
}
public T Entity { get; set; }
}
}
}
}
| |
// Copyright (c) 2010-2014 SharpDX - Alexandre Mutel
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#if !WP8
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
namespace SharpDX.Win32
{
/// <summary>
/// Implementation of OLE IPropertyBag2.
/// </summary>
/// <unmanaged>IPropertyBag2</unmanaged>
public class PropertyBag : ComObject
{
private IPropertyBag2 nativePropertyBag;
/// <summary>
/// Initializes a new instance of the <see cref="PropertyBag"/> class.
/// </summary>
/// <param name="propertyBagPointer">The property bag pointer.</param>
public PropertyBag(IntPtr propertyBagPointer) : base(propertyBagPointer)
{
}
protected override void NativePointerUpdated(IntPtr oldNativePointer)
{
base.NativePointerUpdated(oldNativePointer);
if (NativePointer != IntPtr.Zero)
nativePropertyBag = (IPropertyBag2)Marshal.GetObjectForIUnknown(NativePointer);
else
nativePropertyBag = null;
}
private void CheckIfInitialized()
{
if (nativePropertyBag == null)
throw new InvalidOperationException("This instance is not bound to an unmanaged IPropertyBag2");
}
/// <summary>
/// Gets the number of properties.
/// </summary>
public int Count
{
get
{
CheckIfInitialized();
int propertyCount;
nativePropertyBag.CountProperties(out propertyCount);
return propertyCount;
}
}
/// <summary>
/// Gets the keys.
/// </summary>
public string[] Keys
{
get
{
CheckIfInitialized();
var keys = new List<string>();
for (int i = 0; i < Count; i++)
{
PROPBAG2 propbag2;
int temp;
nativePropertyBag.GetPropertyInfo(i, 1, out propbag2, out temp);
keys.Add(propbag2.Name);
}
return keys.ToArray();
}
}
/// <summary>
/// Gets the value of the property with this name.
/// </summary>
/// <param name="name">The name.</param>
/// <returns>Value of the property</returns>
public object Get(string name)
{
CheckIfInitialized();
object value;
var propbag2 = new PROPBAG2() {Name = name};
Result error;
// Gets the property
var result = nativePropertyBag.Read(1, ref propbag2, IntPtr.Zero, out value, out error);
if (result.Failure || error.Failure)
throw new InvalidOperationException(string.Format(System.Globalization.CultureInfo.InvariantCulture, "Property with name [{0}] is not valid for this instance", name));
propbag2.Dispose();
return value;
}
/// <summary>
/// Gets the value of the property by using a <see cref="PropertyBagKey{T1,T2}"/>
/// </summary>
/// <typeparam name="T1">The public type of this property.</typeparam>
/// <typeparam name="T2">The marshaling type of this property.</typeparam>
/// <param name="propertyKey">The property key.</param>
/// <returns>Value of the property</returns>
public T1 Get<T1, T2>(PropertyBagKey<T1, T2> propertyKey)
{
var value = Get(propertyKey.Name);
return (T1) Convert.ChangeType(value, typeof (T1));
}
/// <summary>
/// Sets the value of the property with this name
/// </summary>
/// <param name="name">The name.</param>
/// <param name="value">The value.</param>
public void Set(string name, object value)
{
CheckIfInitialized();
// In order to set a property in the property bag
// we need to convert the value to the destination type
var previousValue = Get(name);
value = Convert.ChangeType(value, previousValue==null?value.GetType() : previousValue.GetType());
// Set the property
var propbag2 = new PROPBAG2() { Name = name };
var result = nativePropertyBag.Write(1, ref propbag2, value);
result.CheckError();
propbag2.Dispose();
}
/// <summary>
/// Sets the value of the property by using a <see cref="PropertyBagKey{T1,T2}"/>
/// </summary>
/// <typeparam name="T1">The public type of this property.</typeparam>
/// <typeparam name="T2">The marshaling type of this property.</typeparam>
/// <param name="propertyKey">The property key.</param>
/// <param name="value">The value.</param>
public void Set<T1,T2>(PropertyBagKey<T1,T2> propertyKey, T1 value)
{
Set(propertyKey.Name, value);
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
private struct PROPBAG2 : IDisposable
{
internal uint type;
internal ushort vt;
internal ushort cfType;
internal IntPtr dwHint;
internal IntPtr pstrName;
internal Guid clsid;
public string Name
{
get
{
unsafe
{
return Marshal.PtrToStringUni(pstrName);
}
}
set
{
pstrName = Marshal.StringToCoTaskMemUni(value);
}
}
public void Dispose()
{
if (pstrName != IntPtr.Zero)
{
Marshal.FreeCoTaskMem(pstrName);
pstrName = IntPtr.Zero;
}
}
}
[ComImport, InterfaceType(ComInterfaceType.InterfaceIsIUnknown), Guid("22F55882-280B-11D0-A8A9-00A0C90C2004")]
private interface IPropertyBag2
{
[PreserveSig()]
Result Read([In] int cProperties, [In] ref PROPBAG2 pPropBag, IntPtr pErrLog, [Out] out object pvarValue, out Result phrError);
[PreserveSig()]
Result Write([In] int cProperties, [In] ref PROPBAG2 pPropBag, ref object value);
[PreserveSig()]
Result CountProperties(out int pcProperties);
[PreserveSig()]
Result GetPropertyInfo([In] int iProperty, [In] int cProperties, out PROPBAG2 pPropBag, out int pcProperties);
[PreserveSig()]
Result LoadObject([In, MarshalAs(UnmanagedType.LPWStr)] string pstrName, [In] uint dwHint, [In, MarshalAs(UnmanagedType.IUnknown)] object pUnkObject, IntPtr pErrLog);
}
}
}
#endif
| |
using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Data.SqlServerCe;
namespace Factotum
{
class DatabaseUpdater
{
int dbVersion;
SqlCeConnection cnn;
public DatabaseUpdater(int dbVersion, SqlCeConnection cnn)
{
this.dbVersion = dbVersion;
this.cnn = cnn;
}
public void UpdateToCurrent()
{
int appDbVersion = UserSettings.sets.DbVersion;
int curDbVersion = dbVersion;
while (curDbVersion < appDbVersion)
{
switch (curDbVersion)
{
case 1:
Upgrade1To2();
break;
case 2:
Upgrade2To3();
break;
case 3:
Upgrade3To4();
break;
case 4:
Upgrade4To5();
break;
case 5:
Upgrade5To6();
break;
case 6:
Upgrade6To7();
break;
case 7:
break;
default:
break;
}
curDbVersion++;
}
// Update the database version number in the Globals table.
SqlCeCommand cmd = cnn.CreateCommand();
cmd.Parameters.Add("@p0", curDbVersion);
cmd.CommandText = "Update Globals Set DatabaseVersion = @p0";
if (cnn.State != ConnectionState.Open) cnn.Open();
cmd.ExecuteNonQuery();
}
private void Upgrade1To2()
{
// Add the cmpAvgCrewDose column to the Components table.
SqlCeCommand cmd = cnn.CreateCommand();
cmd.CommandText = "Alter table Components Add [CmpAvgCrewDose] Float Default 0 NOT NULL";
if (cnn.State != ConnectionState.Open) cnn.Open();
cmd.ExecuteNonQuery();
}
private void Upgrade2To3()
{
// Add the TmpComponentListing and TmpStatusReport tables.
// This is an attempt to simplify the data source definitions for the reports which
// have been difficult to modify and inflexible with regard to subqueries, etc...
SqlCeCommand cmd = cnn.CreateCommand();
cmd.CommandText =
@"Create table [TmpComponentListing]
(
[CmpName] Nvarchar(50) NULL,
[CtpName] Nvarchar(25) NULL,
[CmtName] Nvarchar(25) NULL,
[LinName] Nvarchar(40) NULL,
[SysName] Nvarchar(40) NULL,
[PslSchedule] Nvarchar(20) NULL,
[PslNomDia] Numeric(5,3) NULL,
[CmpTimesInspected] Integer Default 0 NULL,
[CmpAvgInspectionTime] Float Default 0 NULL,
[CmpAvgCrewDose] Float Default 0 NULL,
[CmpHighRad] Bit Default 0 NULL,
[CmpHardToAccess] Bit Default 0 NULL,
[CmpNote] Nvarchar(256) NULL
)";
if (cnn.State != ConnectionState.Open) cnn.Open();
cmd.ExecuteNonQuery();
cmd = cnn.CreateCommand();
cmd.CommandText =
@"Create table [TmpStatusReport]
(
[IscName] Nvarchar(50) NULL,
[CmpName] Nvarchar(50) NULL,
[IscIsReadyToInspect] Bit Default 0 NULL,
[IscInsID] Uniqueidentifier NULL,
[IscOtgID] Uniqueidentifier NULL,
[IscMinCount] Smallint Default 0 NULL,
[IscIsFinal] Bit Default 0 NULL,
[IscIsUtFieldComplete] Bit Default 0 NULL,
[IscReportSubmittedOn] Datetime NULL,
[IscCompletionReportedOn] Datetime NULL,
[IscWorkOrder] Nvarchar(50) NULL,
[IscEdsNumber] Integer Default 0 NULL,
[TotalCrewDose] Float NULL,
[TotalPersonHours] Float NULL
) ";
if (cnn.State != ConnectionState.Open) cnn.Open();
cmd.ExecuteNonQuery();
}
private void Upgrade3To4()
{
// Add divider type columns to the Grids table.
SqlCeCommand cmd = cnn.CreateCommand();
cmd.CommandText =
@"Alter table Grids Add
[GrdUpMainPreDivider] Tinyint Default 0 NOT NULL,
[GrdDnMainPreDivider] Tinyint Default 0 NOT NULL,
[GrdUpExtPreDivider] Tinyint Default 0 NOT NULL,
[GrdDnExtPreDivider] Tinyint Default 0 NOT NULL,
[GrdBranchPreDivider] Tinyint Default 0 NOT NULL,
[GrdBranchExtPreDivider] Tinyint Default 0 NOT NULL,
[GrdPostDivider] Tinyint Default 0 NOT NULL";
if (cnn.State != ConnectionState.Open) cnn.Open();
cmd.ExecuteNonQuery();
cmd = cnn.CreateCommand();
cmd.CommandText =
@"Alter table Globals Add
[CompatibleDBVersion] Integer Default 0 NOT NULL";
if (cnn.State != ConnectionState.Open) cnn.Open();
cmd.ExecuteNonQuery();
// Back end updates may not always break older front ends
// The CompatibleDBVersion is used to determine whether or not an older front end version
// can work with a newer back end. If the db version specified in the front end's system properties
// is greater or equal the CompatibleDBVersion stored in the globals table of the DB, we'll let
// the front end use it.
// This will need to be considered for possible updating in all future upgrades as well
cmd = cnn.CreateCommand();
cmd.CommandText =
@"Update Globals Set [CompatibleDBVersion] = 4";
if (cnn.State != ConnectionState.Open) cnn.Open();
cmd.ExecuteNonQuery();
}
private void Upgrade4To5()
{
// Add divider type columns to the Grids table.
SqlCeCommand cmd = cnn.CreateCommand();
cmd.CommandText =
@"ALTER TABLE RadialLocations ALTER COLUMN RdlName nvarchar(50)";
if (cnn.State != ConnectionState.Open) cnn.Open();
cmd.ExecuteNonQuery();
cmd = cnn.CreateCommand();
cmd.CommandText =
@"ALTER TABLE Grids ALTER COLUMN GrdAxialLocOverride nvarchar(50)";
if (cnn.State != ConnectionState.Open) cnn.Open();
cmd.ExecuteNonQuery();
// This will need to be considered for possible updating in all future upgrades as well
cmd = cnn.CreateCommand();
cmd.CommandText =
@"Update Globals Set [CompatibleDBVersion] = 4";
if (cnn.State != ConnectionState.Open) cnn.Open();
cmd.ExecuteNonQuery();
}
private void Upgrade5To6()
{
// Add the GrdHideColumnLayoutGraphic column to the Grids table.
SqlCeCommand cmd = cnn.CreateCommand();
cmd.CommandText = "Alter table Grids Add [GrdHideColumnLayoutGraphic] Bit Default 0 NOT NULL";
if (cnn.State != ConnectionState.Open) cnn.Open();
cmd.ExecuteNonQuery();
cmd = cnn.CreateCommand();
cmd.CommandText =
@"ALTER TABLE GridSizes ALTER COLUMN GszAxialDistance numeric(6,3) NOT NULL";
if (cnn.State != ConnectionState.Open) cnn.Open();
cmd.ExecuteNonQuery();
cmd = cnn.CreateCommand();
cmd.CommandText =
@"ALTER TABLE GridSizes ALTER COLUMN GszRadialDistance numeric(6,3) NOT NULL";
if (cnn.State != ConnectionState.Open) cnn.Open();
cmd.ExecuteNonQuery();
cmd = cnn.CreateCommand();
cmd.CommandText =
@"ALTER TABLE Grids ALTER COLUMN GrdAxialDistance numeric(6,3) NULL";
if (cnn.State != ConnectionState.Open) cnn.Open();
cmd.ExecuteNonQuery();
cmd = cnn.CreateCommand();
cmd.CommandText =
@"ALTER TABLE Grids ALTER COLUMN GrdRadialDistance numeric(6,3) NULL";
if (cnn.State != ConnectionState.Open) cnn.Open();
cmd.ExecuteNonQuery();
// Any app that works with version 4 db will work with this version.
// the following would not have been necessary, except that I just
// fixed a mistake in the 4To5 updater where I had the compatible version as 5.
cmd = cnn.CreateCommand();
cmd.CommandText =
@"Update Globals Set [CompatibleDBVersion] = 4";
if (cnn.State != ConnectionState.Open) cnn.Open();
cmd.ExecuteNonQuery();
}
private void Upgrade6To7()
{
// Add an optional component section to additional measurements so we can compute Tscr.
SqlCeCommand cmd = cnn.CreateCommand();
cmd.CommandText = "Alter Table AdditionalMeasurements ADD AdmComponentSection smallint NULL";
if (cnn.State != ConnectionState.Open) cnn.Open();
cmd.ExecuteNonQuery();
cmd = cnn.CreateCommand();
cmd.CommandText =
@"ALTER TABLE Components ALTER COLUMN CmpMisc1 nvarchar(50) NULL;";
if (cnn.State != ConnectionState.Open) cnn.Open();
cmd.ExecuteNonQuery();
cmd = cnn.CreateCommand();
cmd.CommandText =
@"ALTER TABLE Components ALTER COLUMN CmpMisc2 nvarchar(50) NULL;";
if (cnn.State != ConnectionState.Open) cnn.Open();
cmd.ExecuteNonQuery();
}
}
}
| |
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using Agent.Sdk;
using Agent.Sdk.Knob;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading;
namespace Microsoft.VisualStudio.Services.Agent.Util
{
public static class IOUtil
{
private static UtilKnobValueContext _knobContext = UtilKnobValueContext.Instance();
public static string ExeExtension
{
get =>
PlatformUtil.RunningOnWindows
? ".exe"
: string.Empty;
}
public static StringComparison FilePathStringComparison
{
get =>
PlatformUtil.RunningOnLinux
? StringComparison.Ordinal
: StringComparison.OrdinalIgnoreCase;
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1720: Identifiers should not contain type")]
public static void SaveObject(object obj, string path)
{
File.WriteAllText(path, StringUtil.ConvertToJson(obj), Encoding.UTF8);
}
public static T LoadObject<T>(string path)
{
string json = File.ReadAllText(path, Encoding.UTF8);
return StringUtil.ConvertFromJson<T>(json);
}
public static string GetPathHash(string path)
{
ArgUtil.NotNull(path, nameof(path));
string hashString = path.ToLowerInvariant();
using (SHA256 sha256hash = SHA256.Create())
{
byte[] data = sha256hash.ComputeHash(Encoding.UTF8.GetBytes(hashString));
StringBuilder sBuilder = new StringBuilder();
for (int i = 0; i < data.Length; i++)
{
sBuilder.Append(data[i].ToString("x2"));
}
string hash = sBuilder.ToString();
return hash;
}
}
public static void Delete(string path, CancellationToken cancellationToken)
{
DeleteDirectory(path, cancellationToken);
DeleteFile(path);
}
public static void DeleteDirectory(string path, CancellationToken cancellationToken)
{
DeleteDirectory(path, contentsOnly: false, continueOnContentDeleteError: false, cancellationToken: cancellationToken);
}
public static void DeleteDirectory(string path, bool contentsOnly, bool continueOnContentDeleteError, CancellationToken cancellationToken)
{
ArgUtil.NotNullOrEmpty(path, nameof(path));
DirectoryInfo directory = new DirectoryInfo(path);
if (!directory.Exists)
{
return;
}
if (!contentsOnly)
{
// Remove the readonly flag.
RemoveReadOnly(directory);
// Check if the directory is a reparse point.
if (directory.Attributes.HasFlag(FileAttributes.ReparsePoint))
{
// Delete the reparse point directory and short-circuit.
directory.Delete();
return;
}
}
// Initialize a concurrent stack to store the directories. The directories
// cannot be deleted until the files are deleted.
var directories = new ConcurrentStack<DirectoryInfo>();
if (!contentsOnly)
{
directories.Push(directory);
}
// Create a new token source for the parallel query. The parallel query should be
// canceled after the first error is encountered. Otherwise the number of exceptions
// could get out of control for a large directory with access denied on every file.
using (var tokenSource = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken))
{
try
{
// Recursively delete all files and store all subdirectories.
Enumerate(directory, tokenSource)
.AsParallel()
.WithCancellation(tokenSource.Token)
.ForAll((FileSystemInfo item) =>
{
bool success = false;
try
{
// Remove the readonly attribute.
RemoveReadOnly(item);
// Check if the item is a file.
if (item is FileInfo)
{
// Delete the file.
item.Delete();
}
else
{
// Check if the item is a directory reparse point.
var subdirectory = item as DirectoryInfo;
ArgUtil.NotNull(subdirectory, nameof(subdirectory));
if (subdirectory.Attributes.HasFlag(FileAttributes.ReparsePoint))
{
try
{
// Delete the reparse point.
subdirectory.Delete();
}
catch (DirectoryNotFoundException)
{
// The target of the reparse point directory has been deleted.
// Therefore the item is no longer a directory and is now a file.
//
// Deletion of reparse point directories happens in parallel. This case can occur
// when reparse point directory FOO points to some other reparse point directory BAR,
// and BAR is deleted after the DirectoryInfo for FOO has already been initialized.
File.Delete(subdirectory.FullName);
}
}
else
{
// Store the directory.
directories.Push(subdirectory);
}
}
success = true;
}
catch (Exception) when (continueOnContentDeleteError)
{
// ignore any exception when continueOnContentDeleteError is true.
success = true;
}
finally
{
if (!success)
{
tokenSource.Cancel(); // Cancel is thread-safe.
}
}
});
}
catch (Exception)
{
tokenSource.Cancel();
throw;
}
}
// Delete the directories.
foreach (DirectoryInfo dir in directories.OrderByDescending(x => x.FullName.Length))
{
cancellationToken.ThrowIfCancellationRequested();
dir.Delete();
}
}
public static void DeleteFile(string path)
{
ArgUtil.NotNullOrEmpty(path, nameof(path));
var file = new FileInfo(path);
if (file.Exists)
{
RemoveReadOnly(file);
file.Delete();
}
}
public static void MoveDirectory(string sourceDir, string targetDir, string stagingDir, CancellationToken token)
{
ArgUtil.Directory(sourceDir, nameof(sourceDir));
ArgUtil.NotNullOrEmpty(targetDir, nameof(targetDir));
ArgUtil.NotNullOrEmpty(stagingDir, nameof(stagingDir));
// delete existing stagingDir
DeleteDirectory(stagingDir, token);
// make sure parent dir of stagingDir exist
Directory.CreateDirectory(Path.GetDirectoryName(stagingDir));
// move source to staging
Directory.Move(sourceDir, stagingDir);
// delete existing targetDir
DeleteDirectory(targetDir, token);
// make sure parent dir of targetDir exist
Directory.CreateDirectory(Path.GetDirectoryName(targetDir));
// move staging to target
Directory.Move(stagingDir, targetDir);
}
/// <summary>
/// Given a path and directory, return the path relative to the directory. If the path is not
/// under the directory the path is returned un modified. Examples:
/// MakeRelative(@"d:\src\project\foo.cpp", @"d:\src") -> @"project\foo.cpp"
/// MakeRelative(@"d:\src\project\foo.cpp", @"d:\specs") -> @"d:\src\project\foo.cpp"
/// MakeRelative(@"d:\src\project\foo.cpp", @"d:\src\proj") -> @"d:\src\project\foo.cpp"
/// </summary>
/// <remarks>Safe for remote paths. Does not access the local disk.</remarks>
/// <param name="path">Path to make relative.</param>
/// <param name="folder">Folder to make it relative to.</param>
/// <returns>Relative path.</returns>
public static string MakeRelative(string path, string folder)
{
ArgUtil.NotNullOrEmpty(path, nameof(path));
ArgUtil.NotNull(folder, nameof(folder));
// Replace all Path.AltDirectorySeparatorChar with Path.DirectorySeparatorChar from both inputs
path = path.Replace(Path.AltDirectorySeparatorChar, Path.DirectorySeparatorChar);
folder = folder.Replace(Path.AltDirectorySeparatorChar, Path.DirectorySeparatorChar);
// Check if the dir is a prefix of the path (if not, it isn't relative at all).
if (!path.StartsWith(folder, IOUtil.FilePathStringComparison))
{
return path;
}
// Dir is a prefix of the path, if they are the same length then the relative path is empty.
if (path.Length == folder.Length)
{
return string.Empty;
}
// If the dir ended in a '\\' (like d:\) or '/' (like user/bin/) then we have a relative path.
if (folder.Length > 0 && folder[folder.Length - 1] == Path.DirectorySeparatorChar)
{
return path.Substring(folder.Length);
}
// The next character needs to be a '\\' or they aren't really relative.
else if (path[folder.Length] == Path.DirectorySeparatorChar)
{
return path.Substring(folder.Length + 1);
}
else
{
return path;
}
}
public static string ResolvePath(String rootPath, String relativePath)
{
ArgUtil.NotNullOrEmpty(rootPath, nameof(rootPath));
ArgUtil.NotNullOrEmpty(relativePath, nameof(relativePath));
if (!Path.IsPathRooted(rootPath))
{
throw new ArgumentException($"{rootPath} should be a rooted path.");
}
if (relativePath.IndexOfAny(Path.GetInvalidPathChars()) > -1)
{
throw new InvalidOperationException($"{relativePath} contains invalid path characters.");
}
else if (Path.GetFileName(relativePath).IndexOfAny(Path.GetInvalidFileNameChars()) > -1)
{
throw new InvalidOperationException($"{relativePath} contains invalid folder name characters.");
}
else if (Path.IsPathRooted(relativePath))
{
throw new InvalidOperationException($"{relativePath} can not be a rooted path.");
}
else
{
rootPath = rootPath.Replace(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar);
relativePath = relativePath.Replace(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar);
// Root the path
relativePath = String.Concat(rootPath, Path.AltDirectorySeparatorChar, relativePath);
// Collapse ".." directories with their parent, and skip "." directories.
String[] split = relativePath.Split(new[] { Path.AltDirectorySeparatorChar }, StringSplitOptions.RemoveEmptyEntries);
var segments = new Stack<String>(split.Length);
Int32 skip = 0;
for (Int32 i = split.Length - 1; i >= 0; i--)
{
String segment = split[i];
if (String.Equals(segment, ".", StringComparison.Ordinal))
{
continue;
}
else if (String.Equals(segment, "..", StringComparison.Ordinal))
{
skip++;
}
else if (skip > 0)
{
skip--;
}
else
{
segments.Push(segment);
}
}
if (skip > 0)
{
throw new InvalidOperationException($"The file path {relativePath} is invalid");
}
if (PlatformUtil.RunningOnWindows)
{
if (segments.Count > 1)
{
return String.Join(Path.DirectorySeparatorChar, segments);
}
else
{
return segments.Pop() + Path.DirectorySeparatorChar;
}
}
else
{
return Path.DirectorySeparatorChar + String.Join(Path.DirectorySeparatorChar, segments);
}
}
}
public static void CopyDirectory(string source, string target, CancellationToken cancellationToken)
{
// Validate args.
ArgUtil.Directory(source, nameof(source));
ArgUtil.NotNullOrEmpty(target, nameof(target));
ArgUtil.NotNull(cancellationToken, nameof(cancellationToken));
cancellationToken.ThrowIfCancellationRequested();
// Create the target directory.
Directory.CreateDirectory(target);
// Get the file contents of the directory to copy.
DirectoryInfo sourceDir = new DirectoryInfo(source);
foreach (FileInfo sourceFile in sourceDir.GetFiles() ?? new FileInfo[0])
{
// Check if the file already exists.
cancellationToken.ThrowIfCancellationRequested();
FileInfo targetFile = new FileInfo(Path.Combine(target, sourceFile.Name));
if (!targetFile.Exists ||
sourceFile.Length != targetFile.Length ||
sourceFile.LastWriteTime != targetFile.LastWriteTime)
{
// Copy the file.
sourceFile.CopyTo(targetFile.FullName, true);
}
}
// Copy the subdirectories.
foreach (DirectoryInfo subDir in sourceDir.GetDirectories() ?? new DirectoryInfo[0])
{
CopyDirectory(
source: subDir.FullName,
target: Path.Combine(target, subDir.Name),
cancellationToken: cancellationToken);
}
}
public static void ValidateExecutePermission(string directory)
{
ArgUtil.Directory(directory, nameof(directory));
string dir = directory;
int failsafe = AgentKnobs.PermissionsCheckFailsafe.GetValue(_knobContext).AsInt();
for (int i = 0; i < failsafe; i++)
{
try
{
Directory.EnumerateFileSystemEntries(dir).FirstOrDefault();
}
catch (UnauthorizedAccessException ex)
{
// Permission to read the directory contents is required for '{0}' and each directory up the hierarchy. {1}
string message = StringUtil.Loc("DirectoryHierarchyUnauthorized", directory, ex.Message);
throw new UnauthorizedAccessException(message, ex);
}
dir = Path.GetDirectoryName(dir);
if (string.IsNullOrEmpty(dir))
{
return;
}
}
// This should never happen.
throw new NotSupportedException($"Unable to validate execute permissions for directory '{directory}'. Exceeded maximum iterations.");
}
/// <summary>
/// Recursively enumerates a directory without following directory reparse points.
/// </summary>
private static IEnumerable<FileSystemInfo> Enumerate(DirectoryInfo directory, CancellationTokenSource tokenSource)
{
ArgUtil.NotNull(directory, nameof(directory));
ArgUtil.Equal(false, directory.Attributes.HasFlag(FileAttributes.ReparsePoint), nameof(directory.Attributes.HasFlag));
// Push the directory onto the processing stack.
var directories = new Stack<DirectoryInfo>(new[] { directory });
while (directories.Count > 0)
{
// Pop the next directory.
directory = directories.Pop();
foreach (FileSystemInfo item in directory.GetFileSystemInfos())
{
// Push non-reparse-point directories onto the processing stack.
directory = item as DirectoryInfo;
if (directory != null &&
!item.Attributes.HasFlag(FileAttributes.ReparsePoint))
{
directories.Push(directory);
}
// Then yield the directory. Otherwise there is a race condition when this method attempts to initialize
// the Attributes and the caller is deleting the reparse point in parallel (FileNotFoundException).
yield return item;
}
}
}
private static void RemoveReadOnly(FileSystemInfo item)
{
ArgUtil.NotNull(item, nameof(item));
if (item.Attributes.HasFlag(FileAttributes.ReadOnly))
{
item.Attributes = item.Attributes & ~FileAttributes.ReadOnly;
}
}
public static string GetDirectoryName(string path, PlatformUtil.OS platform)
{
if (string.IsNullOrWhiteSpace(path))
{
return string.Empty;
}
if (platform == PlatformUtil.OS.Windows)
{
var paths = path.TrimEnd('\\', '/')
.Split(new char[] {'\\','/'}, StringSplitOptions.RemoveEmptyEntries);
Array.Resize(ref paths, paths.Length - 1);
return string.Join('\\', paths);
}
else
{
var paths = path.TrimEnd('/')
.Split('/', StringSplitOptions.RemoveEmptyEntries);
Array.Resize(ref paths, paths.Length - 1);
var prefix = "";
if (path.StartsWith('/'))
{
prefix = "/";
}
return prefix + string.Join('/', paths);
}
}
}
}
| |
/*
* 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 Nini.Config;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Region.Physics.Manager;
namespace OpenSim.Region.Physics.POSPlugin
{
public class POSPrim : PhysicsActor
{
private PhysicsVector _position;
private PhysicsVector _velocity;
private PhysicsVector _acceleration;
private PhysicsVector _size;
private PhysicsVector m_rotationalVelocity = PhysicsVector.Zero;
private Quaternion _orientation;
private bool iscolliding;
public POSPrim()
{
_velocity = new PhysicsVector();
_position = new PhysicsVector();
_acceleration = new PhysicsVector();
}
public override int PhysicsActorType
{
get { return (int) ActorTypes.Prim; }
set { return; }
}
public override PhysicsVector RotationalVelocity
{
get { return m_rotationalVelocity; }
set { m_rotationalVelocity = value; }
}
public override bool IsPhysical
{
get { return false; }
set { return; }
}
public override bool ThrottleUpdates
{
get { return false; }
set { return; }
}
public override bool IsColliding
{
get { return iscolliding; }
set { iscolliding = value; }
}
public override bool CollidingGround
{
get { return false; }
set { return; }
}
public override bool CollidingObj
{
get { return false; }
set { return; }
}
public override bool Stopped
{
get { return false; }
}
public override PhysicsVector Position
{
get { return _position; }
set { _position = value; }
}
public override PhysicsVector Size
{
get { return _size; }
set { _size = value; }
}
public override float Mass
{
get { return 0f; }
}
public override PhysicsVector Force
{
get { return PhysicsVector.Zero; }
set { return; }
}
public override int VehicleType
{
get { return 0; }
set { return; }
}
public override void VehicleFloatParam(int param, float value)
{
}
public override void VehicleVectorParam(int param, PhysicsVector value)
{
}
public override void VehicleRotationParam(int param, Quaternion rotation)
{
}
public override void SetVolumeDetect(int param)
{
}
public override PhysicsVector CenterOfMass
{
get { return PhysicsVector.Zero; }
}
public override PhysicsVector GeometricCenter
{
get { return PhysicsVector.Zero; }
}
public override PrimitiveBaseShape Shape
{
set { return; }
}
public override float Buoyancy
{
get { return 0f; }
set { return; }
}
public override bool FloatOnWater
{
set { return; }
}
public override PhysicsVector Velocity
{
get { return _velocity; }
set { _velocity = value; }
}
public override float CollisionScore
{
get { return 0f; }
set { }
}
public override Quaternion Orientation
{
get { return _orientation; }
set { _orientation = value; }
}
public override PhysicsVector Acceleration
{
get { return _acceleration; }
}
public override bool Kinematic
{
get { return true; }
set { }
}
public void SetAcceleration(PhysicsVector accel)
{
_acceleration = accel;
}
public override void AddForce(PhysicsVector force, bool pushforce)
{
}
public override void AddAngularForce(PhysicsVector force, bool pushforce)
{
}
public override PhysicsVector Torque
{
get { return PhysicsVector.Zero; }
set { return; }
}
public override void SetMomentum(PhysicsVector momentum)
{
}
public override bool Flying
{
get { return false; }
set { }
}
public override bool SetAlwaysRun
{
get { return false; }
set { return; }
}
public override uint LocalID
{
set { return; }
}
public override bool Grabbed
{
set { return; }
}
public override void link(PhysicsActor obj)
{
}
public override void delink()
{
}
public override void LockAngularMotion(PhysicsVector axis)
{
}
public override bool Selected
{
set { return; }
}
public override void CrossingFailure()
{
}
public override PhysicsVector PIDTarget
{
set { return; }
}
public override bool PIDActive
{
set { return; }
}
public override float PIDTau
{
set { return; }
}
public override float PIDHoverHeight
{
set { return; }
}
public override bool PIDHoverActive
{
set { return; }
}
public override PIDHoverType PIDHoverType
{
set { return; }
}
public override float PIDHoverTau
{
set { return; }
}
public override void SubscribeEvents(int ms)
{
}
public override void UnSubscribeEvents()
{
}
public override bool SubscribedEvents()
{
return false;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections;
using System.IO;
using System.Text;
namespace System.Net.Mail
{
//Streams created are read only and return 0 once a full server reply has been read
//To get the next server reply, call GetNextReplyReader
internal class SmtpReplyReaderFactory
{
private enum ReadState
{
Status0,
Status1,
Status2,
ContinueFlag,
ContinueCR,
ContinueLF,
LastCR,
LastLF,
Done
}
private BufferedReadStream _bufferedStream;
private byte[] _byteBuffer;
private SmtpReplyReader _currentReader;
private const int DefaultBufferSize = 256;
private ReadState _readState = ReadState.Status0;
private SmtpStatusCode _statusCode;
internal SmtpReplyReaderFactory(Stream stream)
{
_bufferedStream = new BufferedReadStream(stream);
}
internal SmtpReplyReader CurrentReader
{
get
{
return _currentReader;
}
}
internal SmtpStatusCode StatusCode
{
get
{
return _statusCode;
}
}
internal IAsyncResult BeginReadLines(SmtpReplyReader caller, AsyncCallback callback, object state)
{
ReadLinesAsyncResult result = new ReadLinesAsyncResult(this, callback, state);
result.Read(caller);
return result;
}
internal IAsyncResult BeginReadLine(SmtpReplyReader caller, AsyncCallback callback, object state)
{
ReadLinesAsyncResult result = new ReadLinesAsyncResult(this, callback, state, true);
result.Read(caller);
return result;
}
internal void Close(SmtpReplyReader caller)
{
if (_currentReader == caller)
{
if (_readState != ReadState.Done)
{
if (_byteBuffer == null)
{
_byteBuffer = new byte[SmtpReplyReaderFactory.DefaultBufferSize];
}
while (0 != Read(caller, _byteBuffer, 0, _byteBuffer.Length)) ;
}
_currentReader = null;
}
}
internal LineInfo[] EndReadLines(IAsyncResult result)
{
return ReadLinesAsyncResult.End(result);
}
internal LineInfo EndReadLine(IAsyncResult result)
{
LineInfo[] info = ReadLinesAsyncResult.End(result);
if (info != null && info.Length > 0)
{
return info[0];
}
return new LineInfo();
}
internal SmtpReplyReader GetNextReplyReader()
{
if (_currentReader != null)
{
_currentReader.Close();
}
_readState = ReadState.Status0;
_currentReader = new SmtpReplyReader(this);
return _currentReader;
}
private int ProcessRead(byte[] buffer, int offset, int read, bool readLine)
{
// if 0 bytes were read,there was a failure
if (read == 0)
{
throw new IOException(SR.Format(SR.net_io_readfailure, SR.net_io_connectionclosed));
}
unsafe
{
fixed (byte* pBuffer = buffer)
{
byte* start = pBuffer + offset;
byte* ptr = start;
byte* end = ptr + read;
switch (_readState)
{
case ReadState.Status0:
{
if (ptr < end)
{
byte b = *ptr++;
if (b < '0' && b > '9')
{
throw new FormatException(SR.SmtpInvalidResponse);
}
_statusCode = (SmtpStatusCode)(100 * (b - '0'));
goto case ReadState.Status1;
}
_readState = ReadState.Status0;
break;
}
case ReadState.Status1:
{
if (ptr < end)
{
byte b = *ptr++;
if (b < '0' && b > '9')
{
throw new FormatException(SR.SmtpInvalidResponse);
}
_statusCode += 10 * (b - '0');
goto case ReadState.Status2;
}
_readState = ReadState.Status1;
break;
}
case ReadState.Status2:
{
if (ptr < end)
{
byte b = *ptr++;
if (b < '0' && b > '9')
{
throw new FormatException(SR.SmtpInvalidResponse);
}
_statusCode += b - '0';
goto case ReadState.ContinueFlag;
}
_readState = ReadState.Status2;
break;
}
case ReadState.ContinueFlag:
{
if (ptr < end)
{
byte b = *ptr++;
if (b == ' ') // last line
{
goto case ReadState.LastCR;
}
else if (b == '-') // more lines coming
{
goto case ReadState.ContinueCR;
}
else // error
{
throw new FormatException(SR.SmtpInvalidResponse);
}
}
_readState = ReadState.ContinueFlag;
break;
}
case ReadState.ContinueCR:
{
while (ptr < end)
{
if (*ptr++ == '\r')
{
goto case ReadState.ContinueLF;
}
}
_readState = ReadState.ContinueCR;
break;
}
case ReadState.ContinueLF:
{
if (ptr < end)
{
if (*ptr++ != '\n')
{
throw new FormatException(SR.SmtpInvalidResponse);
}
if (readLine)
{
_readState = ReadState.Status0;
return (int)(ptr - start);
}
goto case ReadState.Status0;
}
_readState = ReadState.ContinueLF;
break;
}
case ReadState.LastCR:
{
while (ptr < end)
{
if (*ptr++ == '\r')
{
goto case ReadState.LastLF;
}
}
_readState = ReadState.LastCR;
break;
}
case ReadState.LastLF:
{
if (ptr < end)
{
if (*ptr++ != '\n')
{
throw new FormatException(SR.SmtpInvalidResponse);
}
goto case ReadState.Done;
}
_readState = ReadState.LastLF;
break;
}
case ReadState.Done:
{
int actual = (int)(ptr - start);
_readState = ReadState.Done;
return actual;
}
}
return (int)(ptr - start);
}
}
}
internal int Read(SmtpReplyReader caller, byte[] buffer, int offset, int count)
{
// if we've already found the delimitter, then return 0 indicating
// end of stream.
if (count == 0 || _currentReader != caller || _readState == ReadState.Done)
{
return 0;
}
int read = _bufferedStream.Read(buffer, offset, count);
int actual = ProcessRead(buffer, offset, read, false);
if (actual < read)
{
_bufferedStream.Push(buffer, offset + actual, read - actual);
}
return actual;
}
internal LineInfo ReadLine(SmtpReplyReader caller)
{
LineInfo[] info = ReadLines(caller, true);
if (info != null && info.Length > 0)
{
return info[0];
}
return new LineInfo();
}
internal LineInfo[] ReadLines(SmtpReplyReader caller)
{
return ReadLines(caller, false);
}
internal LineInfo[] ReadLines(SmtpReplyReader caller, bool oneLine)
{
if (caller != _currentReader || _readState == ReadState.Done)
{
return new LineInfo[0];
}
if (_byteBuffer == null)
{
_byteBuffer = new byte[SmtpReplyReaderFactory.DefaultBufferSize];
}
System.Diagnostics.Debug.Assert(_readState == ReadState.Status0);
StringBuilder builder = new StringBuilder();
ArrayList lines = new ArrayList();
int statusRead = 0;
for (int start = 0, read = 0; ;)
{
if (start == read)
{
read = _bufferedStream.Read(_byteBuffer, 0, _byteBuffer.Length);
start = 0;
}
int actual = ProcessRead(_byteBuffer, start, read - start, true);
if (statusRead < 4)
{
int left = Math.Min(4 - statusRead, actual);
statusRead += left;
start += left;
actual -= left;
if (actual == 0)
{
continue;
}
}
builder.Append(Encoding.UTF8.GetString(_byteBuffer, start, actual));
start += actual;
if (_readState == ReadState.Status0)
{
statusRead = 0;
lines.Add(new LineInfo(_statusCode, builder.ToString(0, builder.Length - 2))); // return everything except CRLF
if (oneLine)
{
_bufferedStream.Push(_byteBuffer, start, read - start);
return (LineInfo[])lines.ToArray(typeof(LineInfo));
}
builder = new StringBuilder();
}
else if (_readState == ReadState.Done)
{
lines.Add(new LineInfo(_statusCode, builder.ToString(0, builder.Length - 2))); // return everything except CRLF
_bufferedStream.Push(_byteBuffer, start, read - start);
return (LineInfo[])lines.ToArray(typeof(LineInfo));
}
}
}
private class ReadLinesAsyncResult : LazyAsyncResult
{
private StringBuilder _builder;
private ArrayList _lines;
private SmtpReplyReaderFactory _parent;
private static AsyncCallback s_readCallback = new AsyncCallback(ReadCallback);
private int _read;
private int _statusRead;
private bool _oneLine;
internal ReadLinesAsyncResult(SmtpReplyReaderFactory parent, AsyncCallback callback, object state) : base(null, state, callback)
{
_parent = parent;
}
internal ReadLinesAsyncResult(SmtpReplyReaderFactory parent, AsyncCallback callback, object state, bool oneLine) : base(null, state, callback)
{
_oneLine = oneLine;
_parent = parent;
}
internal void Read(SmtpReplyReader caller)
{
// if we've already found the delimitter, then return 0 indicating
// end of stream.
if (_parent._currentReader != caller || _parent._readState == ReadState.Done)
{
InvokeCallback();
return;
}
if (_parent._byteBuffer == null)
{
_parent._byteBuffer = new byte[SmtpReplyReaderFactory.DefaultBufferSize];
}
System.Diagnostics.Debug.Assert(_parent._readState == ReadState.Status0);
_builder = new StringBuilder();
_lines = new ArrayList();
Read();
}
internal static LineInfo[] End(IAsyncResult result)
{
ReadLinesAsyncResult thisPtr = (ReadLinesAsyncResult)result;
thisPtr.InternalWaitForCompletion();
return (LineInfo[])thisPtr._lines.ToArray(typeof(LineInfo));
}
private void Read()
{
do
{
IAsyncResult result = _parent._bufferedStream.BeginRead(_parent._byteBuffer, 0, _parent._byteBuffer.Length, s_readCallback, this);
if (!result.CompletedSynchronously)
{
return;
}
_read = _parent._bufferedStream.EndRead(result);
} while (ProcessRead());
}
private static void ReadCallback(IAsyncResult result)
{
if (!result.CompletedSynchronously)
{
Exception exception = null;
ReadLinesAsyncResult thisPtr = (ReadLinesAsyncResult)result.AsyncState;
try
{
thisPtr._read = thisPtr._parent._bufferedStream.EndRead(result);
if (thisPtr.ProcessRead())
{
thisPtr.Read();
}
}
catch (Exception e)
{
exception = e;
}
if (exception != null)
{
thisPtr.InvokeCallback(exception);
}
}
}
private bool ProcessRead()
{
if (_read == 0)
{
throw new IOException(SR.Format(SR.net_io_readfailure, SR.net_io_connectionclosed));
}
for (int start = 0; start != _read;)
{
int actual = _parent.ProcessRead(_parent._byteBuffer, start, _read - start, true);
if (_statusRead < 4)
{
int left = Math.Min(4 - _statusRead, actual);
_statusRead += left;
start += left;
actual -= left;
if (actual == 0)
{
continue;
}
}
_builder.Append(Encoding.UTF8.GetString(_parent._byteBuffer, start, actual));
start += actual;
if (_parent._readState == ReadState.Status0)
{
_lines.Add(new LineInfo(_parent._statusCode, _builder.ToString(0, _builder.Length - 2))); // return everything except CRLF
_builder = new StringBuilder();
_statusRead = 0;
if (_oneLine)
{
_parent._bufferedStream.Push(_parent._byteBuffer, start, _read - start);
InvokeCallback();
return false;
}
}
else if (_parent._readState == ReadState.Done)
{
_lines.Add(new LineInfo(_parent._statusCode, _builder.ToString(0, _builder.Length - 2))); // return everything except CRLF
_parent._bufferedStream.Push(_parent._byteBuffer, start, _read - start);
InvokeCallback();
return false;
}
}
return true;
}
}
}
}
| |
//
// https://github.com/ServiceStack/ServiceStack.Text
// ServiceStack.Text: .NET C# POCO JSON, JSV and CSV Text Serializers.
//
// Authors:
// Demis Bellot (demis.bellot@gmail.com)
//
// Copyright 2012 ServiceStack Ltd.
//
// Licensed under the same terms of ServiceStack: new BSD license.
//
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Text;
using System.Text.RegularExpressions;
using ServiceStack.Text.Common;
using ServiceStack.Text.Support;
#if NETFX_CORE
using System.Threading.Tasks;
#endif
#if WINDOWS_PHONE
using System.IO.IsolatedStorage;
#if !WP8
using ServiceStack.Text.WP;
#endif
#endif
namespace ServiceStack.Text
{
public static class StringExtensions
{
public static T To<T>(this string value)
{
return TypeSerializer.DeserializeFromString<T>(value);
}
public static T To<T>(this string value, T defaultValue)
{
return String.IsNullOrEmpty(value) ? defaultValue : TypeSerializer.DeserializeFromString<T>(value);
}
public static T ToOrDefaultValue<T>(this string value)
{
return String.IsNullOrEmpty(value) ? default(T) : TypeSerializer.DeserializeFromString<T>(value);
}
public static object To(this string value, Type type)
{
return TypeSerializer.DeserializeFromString(value, type);
}
/// <summary>
/// Converts from base: 0 - 62
/// </summary>
/// <param name="source">The source.</param>
/// <param name="from">From.</param>
/// <param name="to">To.</param>
/// <returns></returns>
public static string BaseConvert(this string source, int from, int to)
{
const string chars = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
var result = "";
var length = source.Length;
var number = new int[length];
for (var i = 0; i < length; i++)
{
number[i] = chars.IndexOf(source[i]);
}
int newlen;
do
{
var divide = 0;
newlen = 0;
for (var i = 0; i < length; i++)
{
divide = divide * @from + number[i];
if (divide >= to)
{
number[newlen++] = divide / to;
divide = divide % to;
}
else if (newlen > 0)
{
number[newlen++] = 0;
}
}
length = newlen;
result = chars[divide] + result;
}
while (newlen != 0);
return result;
}
public static string EncodeXml(this string value)
{
return value.Replace("<", "<").Replace(">", ">").Replace("&", "&");
}
public static string EncodeJson(this string value)
{
return String.Concat
("\"",
value.Replace("\\", "\\\\").Replace("\"", "\\\"").Replace("\r", "").Replace("\n", "\\n"),
"\""
);
}
public static string EncodeJsv(this string value)
{
if (JsState.QueryStringMode)
{
return UrlEncode(value);
}
return String.IsNullOrEmpty(value) || !JsWriter.HasAnyEscapeChars(value)
? value
: String.Concat
(
JsWriter.QuoteString,
value.Replace(JsWriter.QuoteString, TypeSerializer.DoubleQuoteString),
JsWriter.QuoteString
);
}
public static string DecodeJsv(this string value)
{
const int startingQuotePos = 1;
const int endingQuotePos = 2;
return String.IsNullOrEmpty(value) || value[0] != JsWriter.QuoteChar
? value
: value.Substring(startingQuotePos, value.Length - endingQuotePos)
.Replace(TypeSerializer.DoubleQuoteString, JsWriter.QuoteString);
}
public static string UrlEncode(this string text)
{
if (String.IsNullOrEmpty(text)) return text;
var sb = new StringBuilder();
foreach (var charCode in Encoding.UTF8.GetBytes(text))
{
if (
charCode >= 65 && charCode <= 90 // A-Z
|| charCode >= 97 && charCode <= 122 // a-z
|| charCode >= 48 && charCode <= 57 // 0-9
|| charCode >= 44 && charCode <= 46 // ,-.
)
{
sb.Append((char)charCode);
}
else
{
sb.Append('%' + charCode.ToString("x2"));
}
}
return sb.ToString();
}
public static string UrlDecode(this string text)
{
if (String.IsNullOrEmpty(text)) return null;
var bytes = new List<byte>();
var textLength = text.Length;
for (var i = 0; i < textLength; i++)
{
var c = text[i];
if (c == '+')
{
bytes.Add(32);
}
else if (c == '%')
{
var hexNo = Convert.ToByte(text.Substring(i + 1, 2), 16);
bytes.Add(hexNo);
i += 2;
}
else
{
bytes.Add((byte)c);
}
}
#if SILVERLIGHT
byte[] byteArray = bytes.ToArray();
return Encoding.UTF8.GetString(byteArray, 0, byteArray.Length);
#else
return Encoding.UTF8.GetString(bytes.ToArray());
#endif
}
#if !XBOX
public static string HexEscape(this string text, params char[] anyCharOf)
{
if (String.IsNullOrEmpty(text)) return text;
if (anyCharOf == null || anyCharOf.Length == 0) return text;
var encodeCharMap = new HashSet<char>(anyCharOf);
var sb = new StringBuilder();
var textLength = text.Length;
for (var i = 0; i < textLength; i++)
{
var c = text[i];
if (encodeCharMap.Contains(c))
{
sb.Append('%' + ((int)c).ToString("x"));
}
else
{
sb.Append(c);
}
}
return sb.ToString();
}
#endif
public static string HexUnescape(this string text, params char[] anyCharOf)
{
if (String.IsNullOrEmpty(text)) return null;
if (anyCharOf == null || anyCharOf.Length == 0) return text;
var sb = new StringBuilder();
var textLength = text.Length;
for (var i = 0; i < textLength; i++)
{
var c = text.Substring(i, 1);
if (c == "%")
{
var hexNo = Convert.ToInt32(text.Substring(i + 1, 2), 16);
sb.Append((char)hexNo);
i += 2;
}
else
{
sb.Append(c);
}
}
return sb.ToString();
}
public static string UrlFormat(this string url, params string[] urlComponents)
{
var encodedUrlComponents = new string[urlComponents.Length];
for (var i = 0; i < urlComponents.Length; i++)
{
var x = urlComponents[i];
encodedUrlComponents[i] = x.UrlEncode();
}
return String.Format(url, encodedUrlComponents);
}
public static string ToRot13(this string value)
{
var array = value.ToCharArray();
for (var i = 0; i < array.Length; i++)
{
var number = (int)array[i];
if (number >= 'a' && number <= 'z')
number += (number > 'm') ? -13 : 13;
else if (number >= 'A' && number <= 'Z')
number += (number > 'M') ? -13 : 13;
array[i] = (char)number;
}
return new string(array);
}
public static string WithTrailingSlash(this string path)
{
if (String.IsNullOrEmpty(path))
throw new ArgumentNullException("path");
if (path[path.Length - 1] != '/')
{
return path + "/";
}
return path;
}
public static string AppendPath(this string uri, params string[] uriComponents)
{
return AppendUrlPaths(uri, uriComponents);
}
public static string AppendUrlPaths(this string uri, params string[] uriComponents)
{
var sb = new StringBuilder(uri.WithTrailingSlash());
var i = 0;
foreach (var uriComponent in uriComponents)
{
if (i++ > 0) sb.Append('/');
sb.Append(uriComponent.UrlEncode());
}
return sb.ToString();
}
#if !SILVERLIGHT
public static string FromAsciiBytes(this byte[] bytes)
{
return bytes == null ? null
: Encoding.ASCII.GetString(bytes, 0, bytes.Length);
}
public static byte[] ToAsciiBytes(this string value)
{
return Encoding.ASCII.GetBytes(value);
}
#endif
public static string FromUtf8Bytes(this byte[] bytes)
{
return bytes == null ? null
: Encoding.UTF8.GetString(bytes, 0, bytes.Length);
}
public static byte[] ToUtf8Bytes(this string value)
{
return Encoding.UTF8.GetBytes(value);
}
public static byte[] ToUtf8Bytes(this int intVal)
{
return FastToUtf8Bytes(intVal.ToString());
}
public static byte[] ToUtf8Bytes(this long longVal)
{
return FastToUtf8Bytes(longVal.ToString());
}
public static byte[] ToUtf8Bytes(this double doubleVal)
{
var doubleStr = doubleVal.ToString(CultureInfo.InvariantCulture.NumberFormat);
if (doubleStr.IndexOf('E') != -1 || doubleStr.IndexOf('e') != -1)
doubleStr = DoubleConverter.ToExactString(doubleVal);
return FastToUtf8Bytes(doubleStr);
}
/// <summary>
/// Skip the encoding process for 'safe strings'
/// </summary>
/// <param name="strVal"></param>
/// <returns></returns>
private static byte[] FastToUtf8Bytes(string strVal)
{
var bytes = new byte[strVal.Length];
for (var i = 0; i < strVal.Length; i++)
bytes[i] = (byte)strVal[i];
return bytes;
}
public static string[] SplitOnFirst(this string strVal, char needle)
{
if (strVal == null) return new string[0];
var pos = strVal.IndexOf(needle);
return pos == -1
? new[] { strVal }
: new[] { strVal.Substring(0, pos), strVal.Substring(pos + 1) };
}
public static string[] SplitOnFirst(this string strVal, string needle)
{
if (strVal == null) return new string[0];
var pos = strVal.IndexOf(needle);
return pos == -1
? new[] { strVal }
: new[] { strVal.Substring(0, pos), strVal.Substring(pos + 1) };
}
public static string[] SplitOnLast(this string strVal, char needle)
{
if (strVal == null) return new string[0];
var pos = strVal.LastIndexOf(needle);
return pos == -1
? new[] { strVal }
: new[] { strVal.Substring(0, pos), strVal.Substring(pos + 1) };
}
public static string[] SplitOnLast(this string strVal, string needle)
{
if (strVal == null) return new string[0];
var pos = strVal.LastIndexOf(needle);
return pos == -1
? new[] { strVal }
: new[] { strVal.Substring(0, pos), strVal.Substring(pos + 1) };
}
public static string WithoutExtension(this string filePath)
{
if (String.IsNullOrEmpty(filePath)) return null;
var extPos = filePath.LastIndexOf('.');
if (extPos == -1) return filePath;
var dirPos = filePath.LastIndexOfAny(DirSeps);
return extPos > dirPos ? filePath.Substring(0, extPos) : filePath;
}
#if NETFX_CORE
private static readonly char DirSep = '\\';//Path.DirectorySeparatorChar;
private static readonly char AltDirSep = '/';//Path.DirectorySeparatorChar == '/' ? '\\' : '/';
#else
private static readonly char DirSep = Path.DirectorySeparatorChar;
private static readonly char AltDirSep = Path.DirectorySeparatorChar == '/' ? '\\' : '/';
#endif
static readonly char[] DirSeps = new[] { '\\', '/' };
public static string ParentDirectory(this string filePath)
{
if (String.IsNullOrEmpty(filePath)) return null;
var dirSep = filePath.IndexOf(DirSep) != -1
? DirSep
: filePath.IndexOf(AltDirSep) != -1 ? AltDirSep : (char)0;
return dirSep == 0 ? null : filePath.TrimEnd(dirSep).SplitOnLast(dirSep)[0];
}
public static string ToJsv<T>(this T obj)
{
return TypeSerializer.SerializeToString(obj);
}
public static T FromJsv<T>(this string jsv)
{
return TypeSerializer.DeserializeFromString<T>(jsv);
}
public static string ToJson<T>(this T obj) {
return JsConfig.PreferInterfaces
? JsonSerializer.SerializeToString(obj, AssemblyUtils.MainInterface<T>())
: JsonSerializer.SerializeToString(obj);
}
public static T FromJson<T>(this string json)
{
return JsonSerializer.DeserializeFromString<T>(json);
}
public static string ToCsv<T>(this T obj)
{
return CsvSerializer.SerializeToString(obj);
}
#if !XBOX && !SILVERLIGHT && !MONOTOUCH
public static string ToXml<T>(this T obj)
{
return XmlSerializer.SerializeToString(obj);
}
#endif
#if !XBOX && !SILVERLIGHT && !MONOTOUCH
public static T FromXml<T>(this string json)
{
return XmlSerializer.DeserializeFromString<T>(json);
}
#endif
public static string FormatWith(this string text, params object[] args)
{
return String.Format(text, args);
}
public static string Fmt(this string text, params object[] args)
{
return String.Format(text, args);
}
public static bool StartsWithIgnoreCase(this string text, string startsWith)
{
#if NETFX_CORE
return text != null
&& text.StartsWith(startsWith, StringComparison.CurrentCultureIgnoreCase);
#else
return text != null
&& text.StartsWith(startsWith, StringComparison.InvariantCultureIgnoreCase);
#endif
}
public static bool EndsWithIgnoreCase(this string text, string endsWith)
{
#if NETFX_CORE
return text != null
&& text.EndsWith(endsWith, StringComparison.CurrentCultureIgnoreCase);
#else
return text != null
&& text.EndsWith(endsWith, StringComparison.InvariantCultureIgnoreCase);
#endif
}
public static string ReadAllText(this string filePath)
{
#if XBOX && !SILVERLIGHT
using( var fileStream = new FileStream( filePath, FileMode.Open, FileAccess.Read ) )
{
return new StreamReader( fileStream ).ReadToEnd( ) ;
}
#elif NETFX_CORE
var task = Windows.Storage.StorageFile.GetFileFromPathAsync(filePath);
task.AsTask().Wait();
var file = task.GetResults();
var streamTask = file.OpenStreamForReadAsync();
streamTask.Wait();
var fileStream = streamTask.Result;
return new StreamReader( fileStream ).ReadToEnd( ) ;
#elif WINDOWS_PHONE
using (var isoStore = IsolatedStorageFile.GetUserStoreForApplication())
{
using (var fileStream = isoStore.OpenFile(filePath, FileMode.Open))
{
return new StreamReader(fileStream).ReadToEnd();
}
}
#else
return File.ReadAllText(filePath);
#endif
}
public static int IndexOfAny(this string text, params string[] needles)
{
return IndexOfAny(text, 0, needles);
}
public static int IndexOfAny(this string text, int startIndex, params string[] needles)
{
if (text == null) return -1;
var firstPos = -1;
foreach (var needle in needles)
{
var pos = text.IndexOf(needle);
if (firstPos == -1 || pos < firstPos) firstPos = pos;
}
return firstPos;
}
public static string ExtractContents(this string fromText, string startAfter, string endAt)
{
return ExtractContents(fromText, startAfter, startAfter, endAt);
}
public static string ExtractContents(this string fromText, string uniqueMarker, string startAfter, string endAt)
{
if (String.IsNullOrEmpty(uniqueMarker))
throw new ArgumentNullException("uniqueMarker");
if (String.IsNullOrEmpty(startAfter))
throw new ArgumentNullException("startAfter");
if (String.IsNullOrEmpty(endAt))
throw new ArgumentNullException("endAt");
if (String.IsNullOrEmpty(fromText)) return null;
var markerPos = fromText.IndexOf(uniqueMarker);
if (markerPos == -1) return null;
var startPos = fromText.IndexOf(startAfter, markerPos);
if (startPos == -1) return null;
startPos += startAfter.Length;
var endPos = fromText.IndexOf(endAt, startPos);
if (endPos == -1) endPos = fromText.Length;
return fromText.Substring(startPos, endPos - startPos);
}
#if XBOX && !SILVERLIGHT
static readonly Regex StripHtmlRegEx = new Regex(@"<(.|\n)*?>", RegexOptions.Compiled);
#else
static readonly Regex StripHtmlRegEx = new Regex(@"<(.|\n)*?>");
#endif
public static string StripHtml(this string html)
{
return String.IsNullOrEmpty(html) ? null : StripHtmlRegEx.Replace(html, "");
}
#if XBOX && !SILVERLIGHT
static readonly Regex StripBracketsRegEx = new Regex(@"\[(.|\n)*?\]", RegexOptions.Compiled);
static readonly Regex StripBracesRegEx = new Regex(@"\((.|\n)*?\)", RegexOptions.Compiled);
#else
static readonly Regex StripBracketsRegEx = new Regex(@"\[(.|\n)*?\]");
static readonly Regex StripBracesRegEx = new Regex(@"\((.|\n)*?\)");
#endif
public static string StripMarkdownMarkup(this string markdown)
{
if (String.IsNullOrEmpty(markdown)) return null;
markdown = StripBracketsRegEx.Replace(markdown, "");
markdown = StripBracesRegEx.Replace(markdown, "");
markdown = markdown
.Replace("*", "")
.Replace("!", "")
.Replace("\r", "")
.Replace("\n", "")
.Replace("#", "");
return markdown;
}
private const int LowerCaseOffset = 'a' - 'A';
public static string ToCamelCase(this string value)
{
if (String.IsNullOrEmpty(value)) return value;
var len = value.Length;
var newValue = new char[len];
var firstPart = true;
for (var i = 0; i < len; ++i) {
var c0 = value[i];
var c1 = i < len - 1 ? value[i + 1] : 'A';
var c0isUpper = c0 >= 'A' && c0 <= 'Z';
var c1isUpper = c1 >= 'A' && c1 <= 'Z';
if (firstPart && c0isUpper && (c1isUpper || i == 0))
c0 = (char)(c0 + LowerCaseOffset);
else
firstPart = false;
newValue[i] = c0;
}
return new string(newValue);
}
private static readonly TextInfo TextInfo = CultureInfo.InvariantCulture.TextInfo;
public static string ToTitleCase(this string value)
{
#if SILVERLIGHT || __MonoCS__
string[] words = value.Split('_');
for (int i = 0; i <= words.Length - 1; i++)
{
if ((!object.ReferenceEquals(words[i], string.Empty)))
{
string firstLetter = words[i].Substring(0, 1);
string rest = words[i].Substring(1);
string result = firstLetter.ToUpper() + rest.ToLower();
words[i] = result;
}
}
return String.Join("", words);
#else
return TextInfo.ToTitleCase(value).Replace("_", String.Empty);
#endif
}
public static string ToLowercaseUnderscore(this string value)
{
if (String.IsNullOrEmpty(value)) return value;
value = value.ToCamelCase();
var sb = new StringBuilder(value.Length);
foreach (var t in value)
{
if (Char.IsLower(t) || t == '_')
{
sb.Append(t);
}
else
{
sb.Append("_");
sb.Append(Char.ToLowerInvariant(t));
}
}
return sb.ToString();
}
public static string SafeSubstring(this string value, int length)
{
return String.IsNullOrEmpty(value)
? String.Empty
: value.Substring(Math.Min(length, value.Length));
}
public static string SafeSubstring(this string value, int startIndex, int length)
{
if (String.IsNullOrEmpty(value)) return String.Empty;
if (value.Length >= (startIndex + length))
return value.Substring(startIndex, length);
return value.Length > startIndex ? value.Substring(startIndex) : String.Empty;
}
public static bool IsAnonymousType(this Type type)
{
if (type == null)
throw new ArgumentNullException("type");
// HACK: The only way to detect anonymous types right now.
#if NETFX_CORE
return type.IsGeneric() && type.Name.Contains("AnonymousType")
&& (type.Name.StartsWith("<>", StringComparison.Ordinal) || type.Name.StartsWith("VB$", StringComparison.Ordinal));
#else
return Attribute.IsDefined(type, typeof(CompilerGeneratedAttribute), false)
&& type.IsGeneric() && type.Name.Contains("AnonymousType")
&& (type.Name.StartsWith("<>", StringComparison.Ordinal) || type.Name.StartsWith("VB$", StringComparison.Ordinal))
&& (type.Attributes & TypeAttributes.NotPublic) == TypeAttributes.NotPublic;
#endif
}
public static int CompareIgnoreCase(this string strA, string strB)
{
return String.Compare(strA, strB, InvariantComparisonIgnoreCase());
}
public static bool EndsWithInvariant(this string str, string endsWith)
{
return str.EndsWith(endsWith, InvariantComparison());
}
#if NETFX_CORE
public static char DirSeparatorChar = '\\';
public static StringComparison InvariantComparison()
{
return StringComparison.CurrentCulture;
}
public static StringComparison InvariantComparisonIgnoreCase()
{
return StringComparison.CurrentCultureIgnoreCase;
}
public static StringComparer InvariantComparer()
{
return StringComparer.CurrentCulture;
}
public static StringComparer InvariantComparerIgnoreCase()
{
return StringComparer.CurrentCultureIgnoreCase;
}
#else
public static char DirSeparatorChar = Path.DirectorySeparatorChar;
public static StringComparison InvariantComparison()
{
return StringComparison.InvariantCulture;
}
public static StringComparison InvariantComparisonIgnoreCase()
{
return StringComparison.InvariantCultureIgnoreCase;
}
public static StringComparer InvariantComparer()
{
return StringComparer.InvariantCulture;
}
public static StringComparer InvariantComparerIgnoreCase()
{
return StringComparer.InvariantCultureIgnoreCase;
}
#endif
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Xml.XPath;
using Examine;
using Examine.LuceneEngine.SearchCriteria;
using Examine.Providers;
using Lucene.Net.Documents;
using Umbraco.Core;
using Umbraco.Core.Configuration;
using Umbraco.Core.Dynamics;
using Umbraco.Core.Logging;
using Umbraco.Core.Models;
using Umbraco.Core.Models.PublishedContent;
using Umbraco.Core.Xml;
using Umbraco.Web.Models;
using UmbracoExamine;
using umbraco;
using Umbraco.Core.Cache;
using Umbraco.Core.Sync;
using Umbraco.Web.Cache;
namespace Umbraco.Web.PublishedCache.XmlPublishedCache
{
/// <summary>
/// An IPublishedMediaStore that first checks for the media in Examine, and then reverts to the database
/// </summary>
/// <remarks>
/// NOTE: In the future if we want to properly cache all media this class can be extended or replaced when these classes/interfaces are exposed publicly.
/// </remarks>
internal class PublishedMediaCache : IPublishedMediaCache
{
public PublishedMediaCache(ApplicationContext applicationContext)
{
if (applicationContext == null) throw new ArgumentNullException("applicationContext");
_applicationContext = applicationContext;
}
/// <summary>
/// Generally used for unit testing to use an explicit examine searcher
/// </summary>
/// <param name="applicationContext"></param>
/// <param name="searchProvider"></param>
/// <param name="indexProvider"></param>
internal PublishedMediaCache(ApplicationContext applicationContext, BaseSearchProvider searchProvider, BaseIndexProvider indexProvider)
{
if (applicationContext == null) throw new ArgumentNullException("applicationContext");
if (searchProvider == null) throw new ArgumentNullException("searchProvider");
if (indexProvider == null) throw new ArgumentNullException("indexProvider");
_applicationContext = applicationContext;
_searchProvider = searchProvider;
_indexProvider = indexProvider;
}
static PublishedMediaCache()
{
InitializeCacheConfig();
}
private readonly ApplicationContext _applicationContext;
private readonly BaseSearchProvider _searchProvider;
private readonly BaseIndexProvider _indexProvider;
public virtual IPublishedContent GetById(UmbracoContext umbracoContext, bool preview, int nodeId)
{
return GetUmbracoMedia(nodeId);
}
public virtual IEnumerable<IPublishedContent> GetAtRoot(UmbracoContext umbracoContext, bool preview)
{
//TODO: We should be able to look these ids first in Examine!
var rootMedia = _applicationContext.Services.MediaService.GetRootMedia();
return rootMedia.Select(m => GetUmbracoMedia(m.Id));
}
public virtual IPublishedContent GetSingleByXPath(UmbracoContext umbracoContext, bool preview, string xpath, XPathVariable[] vars)
{
throw new NotImplementedException("PublishedMediaCache does not support XPath.");
}
public virtual IPublishedContent GetSingleByXPath(UmbracoContext umbracoContext, bool preview, XPathExpression xpath, XPathVariable[] vars)
{
throw new NotImplementedException("PublishedMediaCache does not support XPath.");
}
public virtual IEnumerable<IPublishedContent> GetByXPath(UmbracoContext umbracoContext, bool preview, string xpath, XPathVariable[] vars)
{
throw new NotImplementedException("PublishedMediaCache does not support XPath.");
}
public virtual IEnumerable<IPublishedContent> GetByXPath(UmbracoContext umbracoContext, bool preview, XPathExpression xpath, XPathVariable[] vars)
{
throw new NotImplementedException("PublishedMediaCache does not support XPath.");
}
public virtual XPathNavigator GetXPathNavigator(UmbracoContext umbracoContext, bool preview)
{
throw new NotImplementedException("PublishedMediaCache does not support XPath.");
}
public bool XPathNavigatorIsNavigable { get { return false; } }
public virtual bool HasContent(UmbracoContext context, bool preview) { throw new NotImplementedException(); }
private ExamineManager GetExamineManagerSafe()
{
try
{
return ExamineManager.Instance;
}
catch (TypeInitializationException)
{
return null;
}
}
private BaseIndexProvider GetIndexProviderSafe()
{
if (_indexProvider != null)
return _indexProvider;
var eMgr = GetExamineManagerSafe();
if (eMgr != null)
{
try
{
//by default use the InternalSearcher
var indexer = eMgr.IndexProviderCollection["InternalIndexer"];
if (indexer.IndexerData.IncludeNodeTypes.Any() || indexer.IndexerData.ExcludeNodeTypes.Any())
{
LogHelper.Warn<PublishedMediaCache>("The InternalIndexer for examine is configured incorrectly, it should not list any include/exclude node types or field names, it should simply be configured as: " + "<IndexSet SetName=\"InternalIndexSet\" IndexPath=\"~/App_Data/TEMP/ExamineIndexes/Internal/\" />");
}
return indexer;
}
catch (Exception ex)
{
LogHelper.Error<PublishedMediaCache>("Could not retrieve the InternalIndexer", ex);
//something didn't work, continue returning null.
}
}
return null;
}
private BaseSearchProvider GetSearchProviderSafe()
{
if (_searchProvider != null)
return _searchProvider;
var eMgr = GetExamineManagerSafe();
if (eMgr != null)
{
try
{
//by default use the InternalSearcher
return eMgr.SearchProviderCollection["InternalSearcher"];
}
catch (FileNotFoundException)
{
//Currently examine is throwing FileNotFound exceptions when we have a loadbalanced filestore and a node is published in umbraco
//See this thread: http://examine.cdodeplex.com/discussions/264341
//Catch the exception here for the time being, and just fallback to GetMedia
//TODO: Need to fix examine in LB scenarios!
}
catch (NullReferenceException)
{
//This will occur when the search provider cannot be initialized. In newer examine versions the initialization is lazy and therefore
// the manager will return the singleton without throwing initialization errors, however if examine isn't configured correctly a null
// reference error will occur because the examine settings are null.
}
}
return null;
}
private IPublishedContent GetUmbracoMedia(int id)
{
// this recreates an IPublishedContent and model each time
// it is called, but at least it should NOT hit the database
// nor Lucene each time, relying on the memory cache instead
var cacheValues = GetCacheValues(id, GetUmbracoMediaCacheValues);
return cacheValues == null ? null : CreateFromCacheValues(cacheValues);
}
private CacheValues GetUmbracoMediaCacheValues(int id)
{
var searchProvider = GetSearchProviderSafe();
if (searchProvider != null)
{
try
{
//first check in Examine as this is WAY faster
var criteria = searchProvider.CreateSearchCriteria("media");
var filter = criteria.Id(id).Not().Field(UmbracoContentIndexer.IndexPathFieldName, "-1,-21,".MultipleCharacterWildcard());
//the above filter will create a query like this, NOTE: That since the use of the wildcard, it automatically escapes it in Lucene.
//+(+__NodeId:3113 -__Path:-1,-21,*) +__IndexType:media
var results = searchProvider.Search(filter.Compile());
if (results.Any())
{
return ConvertFromSearchResult(results.First());
}
}
catch (FileNotFoundException ex)
{
//Currently examine is throwing FileNotFound exceptions when we have a loadbalanced filestore and a node is published in umbraco
//See this thread: http://examine.cdodeplex.com/discussions/264341
//Catch the exception here for the time being, and just fallback to GetMedia
//TODO: Need to fix examine in LB scenarios!
LogHelper.Error<PublishedMediaCache>("Could not load data from Examine index for media", ex);
}
}
LogHelper.Warn<PublishedMediaCache>(
"Could not retrieve media {0} from Examine index, reverting to looking up media via legacy library.GetMedia method",
() => id);
var media = global::umbraco.library.GetMedia(id, false);
return ConvertFromXPathNodeIterator(media, id);
}
internal CacheValues ConvertFromXPathNodeIterator(XPathNodeIterator media, int id)
{
if (media != null && media.Current != null)
{
return media.Current.Name.InvariantEquals("error")
? null
: ConvertFromXPathNavigator(media.Current);
}
LogHelper.Warn<PublishedMediaCache>(
"Could not retrieve media {0} from Examine index or from legacy library.GetMedia method",
() => id);
return null;
}
internal CacheValues ConvertFromSearchResult(SearchResult searchResult)
{
//NOTE: Some fields will not be included if the config section for the internal index has been
//mucked around with. It should index everything and so the index definition should simply be:
// <IndexSet SetName="InternalIndexSet" IndexPath="~/App_Data/TEMP/ExamineIndexes/Internal/" />
var values = new Dictionary<string, string>(searchResult.Fields);
//we need to ensure some fields exist, because of the above issue
if (!new []{"template", "templateId"}.Any(values.ContainsKey))
values.Add("template", 0.ToString());
if (!new[] { "sortOrder" }.Any(values.ContainsKey))
values.Add("sortOrder", 0.ToString());
if (!new[] { "urlName" }.Any(values.ContainsKey))
values.Add("urlName", "");
if (!new[] { "nodeType" }.Any(values.ContainsKey))
values.Add("nodeType", 0.ToString());
if (!new[] { "creatorName" }.Any(values.ContainsKey))
values.Add("creatorName", "");
if (!new[] { "writerID" }.Any(values.ContainsKey))
values.Add("writerID", 0.ToString());
if (!new[] { "creatorID" }.Any(values.ContainsKey))
values.Add("creatorID", 0.ToString());
if (!new[] { "createDate" }.Any(values.ContainsKey))
values.Add("createDate", default(DateTime).ToString("yyyy-MM-dd HH:mm:ss"));
if (!new[] { "level" }.Any(values.ContainsKey))
{
values.Add("level", values["__Path"].Split(',').Length.ToString());
}
// because, migration
if (values.ContainsKey("key") == false)
values["key"] = Guid.Empty.ToString();
return new CacheValues
{
Values = values,
FromExamine = true
};
//var content = new DictionaryPublishedContent(values,
// d => d.ParentId != -1 //parent should be null if -1
// ? GetUmbracoMedia(d.ParentId)
// : null,
// //callback to return the children of the current node
// d => GetChildrenMedia(d.Id),
// GetProperty,
// true);
//return content.CreateModel();
}
internal CacheValues ConvertFromXPathNavigator(XPathNavigator xpath, bool forceNav = false)
{
if (xpath == null) throw new ArgumentNullException("xpath");
var values = new Dictionary<string, string> {{"nodeName", xpath.GetAttribute("nodeName", "")}};
if (!UmbracoConfig.For.UmbracoSettings().Content.UseLegacyXmlSchema)
{
values["nodeTypeAlias"] = xpath.Name;
}
var result = xpath.SelectChildren(XPathNodeType.Element);
//add the attributes e.g. id, parentId etc
if (result.Current != null && result.Current.HasAttributes)
{
if (result.Current.MoveToFirstAttribute())
{
//checking for duplicate keys because of the 'nodeTypeAlias' might already be added above.
if (!values.ContainsKey(result.Current.Name))
{
values[result.Current.Name] = result.Current.Value;
}
while (result.Current.MoveToNextAttribute())
{
if (!values.ContainsKey(result.Current.Name))
{
values[result.Current.Name] = result.Current.Value;
}
}
result.Current.MoveToParent();
}
}
// because, migration
if (values.ContainsKey("key") == false)
values["key"] = Guid.Empty.ToString();
//add the user props
while (result.MoveNext())
{
if (result.Current != null && !result.Current.HasAttributes)
{
string value = result.Current.Value;
if (string.IsNullOrEmpty(value))
{
if (result.Current.HasAttributes || result.Current.SelectChildren(XPathNodeType.Element).Count > 0)
{
value = result.Current.OuterXml;
}
}
values[result.Current.Name] = value;
}
}
return new CacheValues
{
Values = values,
XPath = forceNav ? xpath : null // outside of tests we do NOT want to cache the navigator!
};
//var content = new DictionaryPublishedContent(values,
// d => d.ParentId != -1 //parent should be null if -1
// ? GetUmbracoMedia(d.ParentId)
// : null,
// //callback to return the children of the current node based on the xml structure already found
// d => GetChildrenMedia(d.Id, xpath),
// GetProperty,
// false);
//return content.CreateModel();
}
/// <summary>
/// We will need to first check if the document was loaded by Examine, if so we'll need to check if this property exists
/// in the results, if it does not, then we'll have to revert to looking up in the db.
/// </summary>
/// <param name="dd"> </param>
/// <param name="alias"></param>
/// <returns></returns>
private IPublishedProperty GetProperty(DictionaryPublishedContent dd, string alias)
{
//lets check if the alias does not exist on the document.
//NOTE: Examine will not index empty values and we do not output empty XML Elements to the cache - either of these situations
// would mean that the property is missing from the collection whether we are getting the value from Examine or from the library media cache.
if (dd.Properties.All(x => x.PropertyTypeAlias.InvariantEquals(alias) == false))
{
return null;
}
if (dd.LoadedFromExamine)
{
//We are going to check for a special field however, that is because in some cases we store a 'Raw'
//value in the index such as for xml/html.
var rawValue = dd.Properties.FirstOrDefault(x => x.PropertyTypeAlias.InvariantEquals(UmbracoContentIndexer.RawFieldPrefix + alias));
return rawValue
?? dd.Properties.FirstOrDefault(x => x.PropertyTypeAlias.InvariantEquals(alias));
}
//if its not loaded from examine, then just return the property
return dd.Properties.FirstOrDefault(x => x.PropertyTypeAlias.InvariantEquals(alias));
}
/// <summary>
/// A Helper methods to return the children for media whther it is based on examine or xml
/// </summary>
/// <param name="parentId"></param>
/// <param name="xpath"></param>
/// <returns></returns>
private IEnumerable<IPublishedContent> GetChildrenMedia(int parentId, XPathNavigator xpath = null)
{
//if there is no navigator, try examine first, then re-look it up
if (xpath == null)
{
var searchProvider = GetSearchProviderSafe();
if (searchProvider != null)
{
try
{
//first check in Examine as this is WAY faster
var criteria = searchProvider.CreateSearchCriteria("media");
var filter = criteria.ParentId(parentId).Not().Field(UmbracoContentIndexer.IndexPathFieldName, "-1,-21,".MultipleCharacterWildcard());
//the above filter will create a query like this, NOTE: That since the use of the wildcard, it automatically escapes it in Lucene.
//+(+parentId:3113 -__Path:-1,-21,*) +__IndexType:media
ISearchResults results;
//we want to check if the indexer for this searcher has "sortOrder" flagged as sortable.
//if so, we'll use Lucene to do the sorting, if not we'll have to manually sort it (slower).
var indexer = GetIndexProviderSafe();
var useLuceneSort = indexer != null && indexer.IndexerData.StandardFields.Any(x => x.Name.InvariantEquals("sortOrder") && x.EnableSorting);
if (useLuceneSort)
{
//we have a sortOrder field declared to be sorted, so we'll use Examine
results = searchProvider.Search(
filter.And().OrderBy(new SortableField("sortOrder", SortType.Int)).Compile());
}
else
{
results = searchProvider.Search(filter.Compile());
}
if (results.Any())
{
// var medias = results.Select(ConvertFromSearchResult);
var medias = results.Select(x =>
{
int nid;
if (int.TryParse(x["__NodeId"], out nid) == false && int.TryParse(x["NodeId"], out nid) == false)
throw new Exception("Failed to extract NodeId from search result.");
var cacheValues = GetCacheValues(nid, id => ConvertFromSearchResult(x));
return CreateFromCacheValues(cacheValues);
});
return useLuceneSort ? medias : medias.OrderBy(x => x.SortOrder);
}
else
{
//if there's no result then return null. Previously we defaulted back to library.GetMedia below
//but this will always get called for when we are getting descendents since many items won't have
//children and then we are hitting the database again!
//So instead we're going to rely on Examine to have the correct results like it should.
return Enumerable.Empty<IPublishedContent>();
}
}
catch (FileNotFoundException)
{
//Currently examine is throwing FileNotFound exceptions when we have a loadbalanced filestore and a node is published in umbraco
//See this thread: http://examine.cdodeplex.com/discussions/264341
//Catch the exception here for the time being, and just fallback to GetMedia
}
}
//falling back to get media
var media = library.GetMedia(parentId, true);
if (media != null && media.Current != null)
{
xpath = media.Current;
}
else
{
return Enumerable.Empty<IPublishedContent>();
}
}
var mediaList = new List<IPublishedContent>();
// this is so bad, really
var item = xpath.Select("//*[@id='" + parentId + "']");
if (item.Current == null)
return Enumerable.Empty<IPublishedContent>();
var items = item.Current.SelectChildren(XPathNodeType.Element);
// and this does not work, because... meh
//var q = "//* [@id='" + parentId + "']/* [@id]";
//var items = xpath.Select(q);
foreach (XPathNavigator itemm in items)
{
int id;
if (int.TryParse(itemm.GetAttribute("id", ""), out id) == false)
continue; // wtf?
var captured = itemm;
var cacheValues = GetCacheValues(id, idd => ConvertFromXPathNavigator(captured));
mediaList.Add(CreateFromCacheValues(cacheValues));
}
////The xpath might be the whole xpath including the current ones ancestors so we need to select the current node
//var item = xpath.Select("//*[@id='" + parentId + "']");
//if (item.Current == null)
//{
// return Enumerable.Empty<IPublishedContent>();
//}
//var children = item.Current.SelectChildren(XPathNodeType.Element);
//foreach(XPathNavigator x in children)
//{
// //NOTE: I'm not sure why this is here, it is from legacy code of ExamineBackedMedia, but
// // will leave it here as it must have done something!
// if (x.Name != "contents")
// {
// //make sure it's actually a node, not a property
// if (!string.IsNullOrEmpty(x.GetAttribute("path", "")) &&
// !string.IsNullOrEmpty(x.GetAttribute("id", "")))
// {
// mediaList.Add(ConvertFromXPathNavigator(x));
// }
// }
//}
return mediaList;
}
/// <summary>
/// An IPublishedContent that is represented all by a dictionary.
/// </summary>
/// <remarks>
/// This is a helper class and definitely not intended for public use, it expects that all of the values required
/// to create an IPublishedContent exist in the dictionary by specific aliases.
/// </remarks>
internal class DictionaryPublishedContent : PublishedContentWithKeyBase
{
// note: I'm not sure this class fully complies with IPublishedContent rules especially
// I'm not sure that _properties contains all properties including those without a value,
// neither that GetProperty will return a property without a value vs. null... @zpqrtbnk
// List of properties that will appear in the XML and do not match
// anything in the ContentType, so they must be ignored.
private static readonly string[] IgnoredKeys = { "version", "isDoc" };
public DictionaryPublishedContent(
IDictionary<string, string> valueDictionary,
Func<int, IPublishedContent> getParent,
Func<int, XPathNavigator, IEnumerable<IPublishedContent>> getChildren,
Func<DictionaryPublishedContent, string, IPublishedProperty> getProperty,
XPathNavigator nav,
bool fromExamine)
{
if (valueDictionary == null) throw new ArgumentNullException("valueDictionary");
if (getParent == null) throw new ArgumentNullException("getParent");
if (getProperty == null) throw new ArgumentNullException("getProperty");
_getParent = new Lazy<IPublishedContent>(() => getParent(ParentId));
_getChildren = new Lazy<IEnumerable<IPublishedContent>>(() => getChildren(Id, nav));
_getProperty = getProperty;
LoadedFromExamine = fromExamine;
ValidateAndSetProperty(valueDictionary, val => _id = int.Parse(val), "id", "nodeId", "__NodeId"); //should validate the int!
ValidateAndSetProperty(valueDictionary, val => _key = Guid.Parse(val), "key");
// wtf are we dealing with templates for medias?!
ValidateAndSetProperty(valueDictionary, val => _templateId = int.Parse(val), "template", "templateId");
ValidateAndSetProperty(valueDictionary, val => _sortOrder = int.Parse(val), "sortOrder");
ValidateAndSetProperty(valueDictionary, val => _name = val, "nodeName", "__nodeName");
ValidateAndSetProperty(valueDictionary, val => _urlName = val, "urlName");
ValidateAndSetProperty(valueDictionary, val => _documentTypeAlias = val, "nodeTypeAlias", UmbracoContentIndexer.NodeTypeAliasFieldName);
ValidateAndSetProperty(valueDictionary, val => _documentTypeId = int.Parse(val), "nodeType");
ValidateAndSetProperty(valueDictionary, val => _writerName = val, "writerName");
ValidateAndSetProperty(valueDictionary, val => _creatorName = val, "creatorName", "writerName"); //this is a bit of a hack fix for: U4-1132
ValidateAndSetProperty(valueDictionary, val => _writerId = int.Parse(val), "writerID");
ValidateAndSetProperty(valueDictionary, val => _creatorId = int.Parse(val), "creatorID", "writerID"); //this is a bit of a hack fix for: U4-1132
ValidateAndSetProperty(valueDictionary, val => _path = val, "path", "__Path");
ValidateAndSetProperty(valueDictionary, val => _createDate = ParseDateTimeValue(val), "createDate");
ValidateAndSetProperty(valueDictionary, val => _updateDate = ParseDateTimeValue(val), "updateDate");
ValidateAndSetProperty(valueDictionary, val => _level = int.Parse(val), "level");
ValidateAndSetProperty(valueDictionary, val =>
{
int pId;
ParentId = -1;
if (int.TryParse(val, out pId))
{
ParentId = pId;
}
}, "parentID");
_contentType = PublishedContentType.Get(PublishedItemType.Media, _documentTypeAlias);
_properties = new Collection<IPublishedProperty>();
//handle content type properties
//make sure we create them even if there's no value
foreach (var propertyType in _contentType.PropertyTypes)
{
var alias = propertyType.PropertyTypeAlias;
_keysAdded.Add(alias);
string value;
const bool isPreviewing = false; // false :: never preview a media
var property = valueDictionary.TryGetValue(alias, out value) == false
? new XmlPublishedProperty(propertyType, isPreviewing)
: new XmlPublishedProperty(propertyType, isPreviewing, value);
_properties.Add(property);
}
//loop through remaining values that haven't been applied
foreach (var i in valueDictionary.Where(x =>
_keysAdded.Contains(x.Key) == false // not already processed
&& IgnoredKeys.Contains(x.Key) == false)) // not ignorable
{
if (i.Key.InvariantStartsWith("__"))
{
// no type for that one, dunno how to convert
IPublishedProperty property = new PropertyResult(i.Key, i.Value, PropertyResultType.CustomProperty);
_properties.Add(property);
}
else
{
// this is a property that does not correspond to anything, ignore and log
LogHelper.Warn<PublishedMediaCache>("Dropping property \"" + i.Key + "\" because it does not belong to the content type.");
}
}
}
private DateTime ParseDateTimeValue(string val)
{
if (LoadedFromExamine)
{
try
{
//we might need to parse the date time using Lucene converters
return DateTools.StringToDate(val);
}
catch (FormatException)
{
//swallow exception, its not formatted correctly so revert to just trying to parse
}
}
return DateTime.Parse(val);
}
/// <summary>
/// Flag to get/set if this was laoded from examine cache
/// </summary>
internal bool LoadedFromExamine { get; private set; }
//private readonly Func<DictionaryPublishedContent, IPublishedContent> _getParent;
private readonly Lazy<IPublishedContent> _getParent;
//private readonly Func<DictionaryPublishedContent, IEnumerable<IPublishedContent>> _getChildren;
private readonly Lazy<IEnumerable<IPublishedContent>> _getChildren;
private readonly Func<DictionaryPublishedContent, string, IPublishedProperty> _getProperty;
/// <summary>
/// Returns 'Media' as the item type
/// </summary>
public override PublishedItemType ItemType
{
get { return PublishedItemType.Media; }
}
public override IPublishedContent Parent
{
get { return _getParent.Value; }
}
public int ParentId { get; private set; }
public override int Id
{
get { return _id; }
}
public override Guid Key { get { return _key; } }
public override int TemplateId
{
get
{
//TODO: should probably throw a not supported exception since media doesn't actually support this.
return _templateId;
}
}
public override int SortOrder
{
get { return _sortOrder; }
}
public override string Name
{
get { return _name; }
}
public override string UrlName
{
get { return _urlName; }
}
public override string DocumentTypeAlias
{
get { return _documentTypeAlias; }
}
public override int DocumentTypeId
{
get { return _documentTypeId; }
}
public override string WriterName
{
get { return _writerName; }
}
public override string CreatorName
{
get { return _creatorName; }
}
public override int WriterId
{
get { return _writerId; }
}
public override int CreatorId
{
get { return _creatorId; }
}
public override string Path
{
get { return _path; }
}
public override DateTime CreateDate
{
get { return _createDate; }
}
public override DateTime UpdateDate
{
get { return _updateDate; }
}
public override Guid Version
{
get { return _version; }
}
public override int Level
{
get { return _level; }
}
public override bool IsDraft
{
get { return false; }
}
public override ICollection<IPublishedProperty> Properties
{
get { return _properties; }
}
public override IEnumerable<IPublishedContent> Children
{
get { return _getChildren.Value; }
}
public override IPublishedProperty GetProperty(string alias)
{
return _getProperty(this, alias);
}
public override PublishedContentType ContentType
{
get { return _contentType; }
}
// override to implement cache
// cache at context level, ie once for the whole request
// but cache is not shared by requests because we wouldn't know how to clear it
public override IPublishedProperty GetProperty(string alias, bool recurse)
{
if (recurse == false) return GetProperty(alias);
IPublishedProperty property;
string key = null;
var cache = UmbracoContextCache.Current;
if (cache != null)
{
key = string.Format("RECURSIVE_PROPERTY::{0}::{1}", Id, alias.ToLowerInvariant());
object o;
if (cache.TryGetValue(key, out o))
{
property = o as IPublishedProperty;
if (property == null)
throw new InvalidOperationException("Corrupted cache.");
return property;
}
}
// else get it for real, no cache
property = base.GetProperty(alias, true);
if (cache != null)
cache[key] = property;
return property;
}
private readonly List<string> _keysAdded = new List<string>();
private int _id;
private Guid _key;
private int _templateId;
private int _sortOrder;
private string _name;
private string _urlName;
private string _documentTypeAlias;
private int _documentTypeId;
private string _writerName;
private string _creatorName;
private int _writerId;
private int _creatorId;
private string _path;
private DateTime _createDate;
private DateTime _updateDate;
private Guid _version;
private int _level;
private readonly ICollection<IPublishedProperty> _properties;
private readonly PublishedContentType _contentType;
private void ValidateAndSetProperty(IDictionary<string, string> valueDictionary, Action<string> setProperty, params string[] potentialKeys)
{
var key = potentialKeys.FirstOrDefault(x => valueDictionary.ContainsKey(x) && valueDictionary[x] != null);
if (key == null)
{
throw new FormatException("The valueDictionary is not formatted correctly and is missing any of the '" + string.Join(",", potentialKeys) + "' elements");
}
setProperty(valueDictionary[key]);
_keysAdded.Add(key);
}
}
// REFACTORING
// caching the basic atomic values - and the parent id
// but NOT caching actual parent nor children and NOT even
// the list of children ids - BUT caching the path
internal class CacheValues
{
public IDictionary<string, string> Values { get; set; }
public XPathNavigator XPath { get; set; }
public bool FromExamine { get; set; }
}
public const string PublishedMediaCacheKey = "MediaCacheMeh.";
private const int PublishedMediaCacheTimespanSeconds = 4 * 60; // 4 mins
private static TimeSpan _publishedMediaCacheTimespan;
private static bool _publishedMediaCacheEnabled;
private static void InitializeCacheConfig()
{
var value = ConfigurationManager.AppSettings["Umbraco.PublishedMediaCache.Seconds"];
int seconds;
if (int.TryParse(value, out seconds) == false)
seconds = PublishedMediaCacheTimespanSeconds;
if (seconds > 0)
{
_publishedMediaCacheEnabled = true;
_publishedMediaCacheTimespan = TimeSpan.FromSeconds(seconds);
}
else
{
_publishedMediaCacheEnabled = false;
}
}
internal IPublishedContent CreateFromCacheValues(CacheValues cacheValues)
{
var content = new DictionaryPublishedContent(
cacheValues.Values,
parentId => parentId < 0 ? null : GetUmbracoMedia(parentId),
GetChildrenMedia,
GetProperty,
cacheValues.XPath, // though, outside of tests, that should be null
cacheValues.FromExamine
);
return content.CreateModel();
}
private static CacheValues GetCacheValues(int id, Func<int, CacheValues> func)
{
if (_publishedMediaCacheEnabled == false)
return func(id);
var cache = ApplicationContext.Current.ApplicationCache.RuntimeCache;
var key = PublishedMediaCacheKey + id;
return (CacheValues) cache.GetCacheItem(key, () => func(id), _publishedMediaCacheTimespan);
}
internal static void ClearCache(int id)
{
var cache = ApplicationContext.Current.ApplicationCache.RuntimeCache;
var sid = id.ToString();
var key = PublishedMediaCacheKey + sid;
// we do clear a lot of things... but the cache refresher is somewhat
// convoluted and it's hard to tell what to clear exactly ;-(
// clear the parent - NOT (why?)
//var exist = (CacheValues) cache.GetCacheItem(key);
//if (exist != null)
// cache.ClearCacheItem(PublishedMediaCacheKey + GetValuesValue(exist.Values, "parentID"));
// clear the item
cache.ClearCacheItem(key);
// clear all children - in case we moved and their path has changed
var fid = "/" + sid + "/";
cache.ClearCacheObjectTypes<CacheValues>((k, v) =>
GetValuesValue(v.Values, "path", "__Path").Contains(fid));
}
private static string GetValuesValue(IDictionary<string, string> d, params string[] keys)
{
string value = null;
var ignored = keys.Any(x => d.TryGetValue(x, out value));
return value ?? "";
}
}
}
| |
using System;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Web.Compilation;
using System.Web.Mvc;
using System.Web.Routing;
using Umbraco.Core;
using Umbraco.Web.Models;
using Umbraco.Web.Mvc;
using Umbraco.Web.Routing;
using umbraco;
using umbraco.cms.businesslogic.language;
using Umbraco.Core.Configuration;
namespace Umbraco.Web.Templates
{
/// <summary>
/// This is used purely for the RenderTemplate functionality in Umbraco
/// </summary>
/// <remarks>
/// This allows you to render either an MVC or Webforms template based purely off of a node id and an optional alttemplate id as string output.
/// </remarks>
internal class TemplateRenderer
{
private readonly UmbracoContext _umbracoContext;
private object _oldPageId;
private object _oldPageElements;
private PublishedContentRequest _oldPublishedContentRequest;
private object _oldAltTemplate;
public TemplateRenderer(UmbracoContext umbracoContext, int pageId, int? altTemplateId)
{
if (umbracoContext == null) throw new ArgumentNullException("umbracoContext");
PageId = pageId;
AltTemplate = altTemplateId;
_umbracoContext = umbracoContext;
}
/// <summary>
/// Gets/sets the page id for the template to render
/// </summary>
public int PageId { get; private set; }
/// <summary>
/// Gets/sets the alt template to render if there is one
/// </summary>
public int? AltTemplate { get; private set; }
public void Render(StringWriter writer)
{
if (writer == null) throw new ArgumentNullException("writer");
// instanciate a request a process
// important to use CleanedUmbracoUrl - lowercase path-only version of the current url, though this isn't going to matter
// terribly much for this implementation since we are just creating a doc content request to modify it's properties manually.
var contentRequest = new PublishedContentRequest(_umbracoContext.CleanedUmbracoUrl, _umbracoContext.RoutingContext);
var doc = contentRequest.RoutingContext.UmbracoContext.ContentCache.GetById(PageId);
if (doc == null)
{
writer.Write("<!-- Could not render template for Id {0}, the document was not found -->", PageId);
return;
}
//in some cases the UmbracoContext will not have a PublishedContentRequest assigned to it if we are not in the
//execution of a front-end rendered page. In this case set the culture to the default.
//set the culture to the same as is currently rendering
if (_umbracoContext.PublishedContentRequest == null)
{
var defaultLanguage = Language.GetAllAsList().FirstOrDefault();
contentRequest.Culture = defaultLanguage == null
? CultureInfo.CurrentUICulture
: new CultureInfo(defaultLanguage.CultureAlias);
}
else
{
contentRequest.Culture = _umbracoContext.PublishedContentRequest.Culture;
}
//set the doc that was found by id
contentRequest.PublishedContent = doc;
//set the template, either based on the AltTemplate found or the standard template of the doc
contentRequest.TemplateModel = UmbracoConfig.For.UmbracoSettings().WebRouting.DisableAlternativeTemplates || AltTemplate.HasValue == false
? _umbracoContext.Application.Services.FileService.GetTemplate(doc.TemplateId)
: _umbracoContext.Application.Services.FileService.GetTemplate(AltTemplate.Value);
//if there is not template then exit
if (!contentRequest.HasTemplate)
{
if (!AltTemplate.HasValue)
{
writer.Write("<!-- Could not render template for Id {0}, the document's template was not found with id {0}-->", doc.TemplateId);
}
else
{
writer.Write("<!-- Could not render template for Id {0}, the altTemplate was not found with id {0}-->", AltTemplate);
}
return;
}
//First, save all of the items locally that we know are used in the chain of execution, we'll need to restore these
//after this page has rendered.
SaveExistingItems();
try
{
//set the new items on context objects for this templates execution
SetNewItemsOnContextObjects(contentRequest);
//Render the template
ExecuteTemplateRendering(writer, contentRequest);
}
finally
{
//restore items on context objects to continuing rendering the parent template
RestoreItems();
}
}
private void ExecuteTemplateRendering(TextWriter sw, PublishedContentRequest contentRequest)
{
//NOTE: Before we used to build up the query strings here but this is not necessary because when we do a
// Server.Execute in the TemplateRenderer, we pass in a 'true' to 'preserveForm' which automatically preserves all current
// query strings so there's no need for this. HOWEVER, once we get MVC involved, we might have to do some fun things,
// though this will happen in the TemplateRenderer.
//var queryString = _umbracoContext.HttpContext.Request.QueryString.AllKeys
// .ToDictionary(key => key, key => context.Request.QueryString[key]);
switch (contentRequest.RenderingEngine)
{
case RenderingEngine.Mvc:
var requestContext = new RequestContext(_umbracoContext.HttpContext, new RouteData()
{
Route = RouteTable.Routes["Umbraco_default"]
});
var routeHandler = new RenderRouteHandler(ControllerBuilder.Current.GetControllerFactory(), _umbracoContext);
var routeDef = routeHandler.GetUmbracoRouteDefinition(requestContext, contentRequest);
var renderModel = new RenderModel(contentRequest.PublishedContent, contentRequest.Culture);
//manually add the action/controller, this is required by mvc
requestContext.RouteData.Values.Add("action", routeDef.ActionName);
requestContext.RouteData.Values.Add("controller", routeDef.ControllerName);
//add the rest of the required route data
routeHandler.SetupRouteDataForRequest(renderModel, requestContext, contentRequest);
var stringOutput = RenderUmbracoRequestToString(requestContext);
sw.Write(stringOutput);
break;
case RenderingEngine.WebForms:
default:
var webFormshandler = (global::umbraco.UmbracoDefault)BuildManager
.CreateInstanceFromVirtualPath("~/default.aspx", typeof(global::umbraco.UmbracoDefault));
//the 'true' parameter will ensure that the current query strings are carried through, we don't have
// to build up the url again, it will just work.
_umbracoContext.HttpContext.Server.Execute(webFormshandler, sw, true);
break;
}
}
/// <summary>
/// This will execute the UmbracoMvcHandler for the request specified and get the string output.
/// </summary>
/// <param name="requestContext">
/// Assumes the RequestContext is setup specifically to render an Umbraco view.
/// </param>
/// <returns></returns>
/// <remarks>
/// To acheive this we temporarily change the output text writer of the current HttpResponse, then
/// execute the controller via the handler which innevitably writes the result to the text writer
/// that has been assigned to the response. Then we change the response textwriter back to the original
/// before continuing .
/// </remarks>
private string RenderUmbracoRequestToString(RequestContext requestContext)
{
var currentWriter = requestContext.HttpContext.Response.Output;
var newWriter = new StringWriter();
requestContext.HttpContext.Response.Output = newWriter;
var handler = new UmbracoMvcHandler(requestContext);
handler.ExecuteUmbracoRequest();
//reset it
requestContext.HttpContext.Response.Output = currentWriter;
return newWriter.ToString();
}
private void SetNewItemsOnContextObjects(PublishedContentRequest contentRequest)
{
// handlers like default.aspx will want it and most macros currently need it
contentRequest.UmbracoPage = new page(contentRequest);
//now, set the new ones for this page execution
_umbracoContext.HttpContext.Items["pageID"] = contentRequest.PublishedContent.Id;
_umbracoContext.HttpContext.Items["pageElements"] = contentRequest.UmbracoPage.Elements;
_umbracoContext.HttpContext.Items[Umbraco.Core.Constants.Conventions.Url.AltTemplate] = null;
_umbracoContext.PublishedContentRequest = contentRequest;
}
/// <summary>
/// Save all items that we know are used for rendering execution to variables so we can restore after rendering
/// </summary>
private void SaveExistingItems()
{
//Many objects require that these legacy items are in the http context items... before we render this template we need to first
//save the values in them so that we can re-set them after we render so the rest of the execution works as per normal.
_oldPageId = _umbracoContext.HttpContext.Items["pageID"];
_oldPageElements = _umbracoContext.HttpContext.Items["pageElements"];
_oldPublishedContentRequest = _umbracoContext.PublishedContentRequest;
_oldAltTemplate = _umbracoContext.HttpContext.Items[Umbraco.Core.Constants.Conventions.Url.AltTemplate];
}
/// <summary>
/// Restores all items back to their context's to continue normal page rendering execution
/// </summary>
private void RestoreItems()
{
_umbracoContext.PublishedContentRequest = _oldPublishedContentRequest;
_umbracoContext.HttpContext.Items["pageID"] = _oldPageId;
_umbracoContext.HttpContext.Items["pageElements"] = _oldPageElements;
_umbracoContext.HttpContext.Items[Umbraco.Core.Constants.Conventions.Url.AltTemplate] = _oldAltTemplate;
}
}
}
| |
// ------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
// ------------------------------------------------------------------------------
// **NOTE** This file was generated by a tool and any changes will be overwritten.
// Template Source: Templates\CSharp\Requests\EntityRequest.cs.tt
namespace Microsoft.Graph
{
using System;
using System.Collections.Generic;
using System.IO;
using System.Net.Http;
using System.Threading;
using System.Linq.Expressions;
/// <summary>
/// The type WorkbookChartAxisTitleFormatRequest.
/// </summary>
public partial class WorkbookChartAxisTitleFormatRequest : BaseRequest, IWorkbookChartAxisTitleFormatRequest
{
/// <summary>
/// Constructs a new WorkbookChartAxisTitleFormatRequest.
/// </summary>
/// <param name="requestUrl">The URL for the built request.</param>
/// <param name="client">The <see cref="IBaseClient"/> for handling requests.</param>
/// <param name="options">Query and header option name value pairs for the request.</param>
public WorkbookChartAxisTitleFormatRequest(
string requestUrl,
IBaseClient client,
IEnumerable<Option> options)
: base(requestUrl, client, options)
{
}
/// <summary>
/// Creates the specified WorkbookChartAxisTitleFormat using POST.
/// </summary>
/// <param name="workbookChartAxisTitleFormatToCreate">The WorkbookChartAxisTitleFormat to create.</param>
/// <returns>The created WorkbookChartAxisTitleFormat.</returns>
public System.Threading.Tasks.Task<WorkbookChartAxisTitleFormat> CreateAsync(WorkbookChartAxisTitleFormat workbookChartAxisTitleFormatToCreate)
{
return this.CreateAsync(workbookChartAxisTitleFormatToCreate, CancellationToken.None);
}
/// <summary>
/// Creates the specified WorkbookChartAxisTitleFormat using POST.
/// </summary>
/// <param name="workbookChartAxisTitleFormatToCreate">The WorkbookChartAxisTitleFormat to create.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The created WorkbookChartAxisTitleFormat.</returns>
public async System.Threading.Tasks.Task<WorkbookChartAxisTitleFormat> CreateAsync(WorkbookChartAxisTitleFormat workbookChartAxisTitleFormatToCreate, CancellationToken cancellationToken)
{
this.ContentType = "application/json";
this.Method = "POST";
var newEntity = await this.SendAsync<WorkbookChartAxisTitleFormat>(workbookChartAxisTitleFormatToCreate, cancellationToken).ConfigureAwait(false);
this.InitializeCollectionProperties(newEntity);
return newEntity;
}
/// <summary>
/// Deletes the specified WorkbookChartAxisTitleFormat.
/// </summary>
/// <returns>The task to await.</returns>
public System.Threading.Tasks.Task DeleteAsync()
{
return this.DeleteAsync(CancellationToken.None);
}
/// <summary>
/// Deletes the specified WorkbookChartAxisTitleFormat.
/// </summary>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The task to await.</returns>
public async System.Threading.Tasks.Task DeleteAsync(CancellationToken cancellationToken)
{
this.Method = "DELETE";
await this.SendAsync<WorkbookChartAxisTitleFormat>(null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Gets the specified WorkbookChartAxisTitleFormat.
/// </summary>
/// <returns>The WorkbookChartAxisTitleFormat.</returns>
public System.Threading.Tasks.Task<WorkbookChartAxisTitleFormat> GetAsync()
{
return this.GetAsync(CancellationToken.None);
}
/// <summary>
/// Gets the specified WorkbookChartAxisTitleFormat.
/// </summary>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The WorkbookChartAxisTitleFormat.</returns>
public async System.Threading.Tasks.Task<WorkbookChartAxisTitleFormat> GetAsync(CancellationToken cancellationToken)
{
this.Method = "GET";
var retrievedEntity = await this.SendAsync<WorkbookChartAxisTitleFormat>(null, cancellationToken).ConfigureAwait(false);
this.InitializeCollectionProperties(retrievedEntity);
return retrievedEntity;
}
/// <summary>
/// Updates the specified WorkbookChartAxisTitleFormat using PATCH.
/// </summary>
/// <param name="workbookChartAxisTitleFormatToUpdate">The WorkbookChartAxisTitleFormat to update.</param>
/// <returns>The updated WorkbookChartAxisTitleFormat.</returns>
public System.Threading.Tasks.Task<WorkbookChartAxisTitleFormat> UpdateAsync(WorkbookChartAxisTitleFormat workbookChartAxisTitleFormatToUpdate)
{
return this.UpdateAsync(workbookChartAxisTitleFormatToUpdate, CancellationToken.None);
}
/// <summary>
/// Updates the specified WorkbookChartAxisTitleFormat using PATCH.
/// </summary>
/// <param name="workbookChartAxisTitleFormatToUpdate">The WorkbookChartAxisTitleFormat to update.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The updated WorkbookChartAxisTitleFormat.</returns>
public async System.Threading.Tasks.Task<WorkbookChartAxisTitleFormat> UpdateAsync(WorkbookChartAxisTitleFormat workbookChartAxisTitleFormatToUpdate, CancellationToken cancellationToken)
{
this.ContentType = "application/json";
this.Method = "PATCH";
var updatedEntity = await this.SendAsync<WorkbookChartAxisTitleFormat>(workbookChartAxisTitleFormatToUpdate, cancellationToken).ConfigureAwait(false);
this.InitializeCollectionProperties(updatedEntity);
return updatedEntity;
}
/// <summary>
/// Adds the specified expand value to the request.
/// </summary>
/// <param name="value">The expand value.</param>
/// <returns>The request object to send.</returns>
public IWorkbookChartAxisTitleFormatRequest Expand(string value)
{
this.QueryOptions.Add(new QueryOption("$expand", value));
return this;
}
/// <summary>
/// Adds the specified expand value to the request.
/// </summary>
/// <param name="expandExpression">The expression from which to calculate the expand value.</param>
/// <returns>The request object to send.</returns>
public IWorkbookChartAxisTitleFormatRequest Expand(Expression<Func<WorkbookChartAxisTitleFormat, object>> expandExpression)
{
if (expandExpression == null)
{
throw new ArgumentNullException(nameof(expandExpression));
}
string error;
string value = ExpressionExtractHelper.ExtractMembers(expandExpression, out error);
if (value == null)
{
throw new ArgumentException(error, nameof(expandExpression));
}
else
{
this.QueryOptions.Add(new QueryOption("$expand", value));
}
return this;
}
/// <summary>
/// Adds the specified select value to the request.
/// </summary>
/// <param name="value">The select value.</param>
/// <returns>The request object to send.</returns>
public IWorkbookChartAxisTitleFormatRequest Select(string value)
{
this.QueryOptions.Add(new QueryOption("$select", value));
return this;
}
/// <summary>
/// Adds the specified select value to the request.
/// </summary>
/// <param name="selectExpression">The expression from which to calculate the select value.</param>
/// <returns>The request object to send.</returns>
public IWorkbookChartAxisTitleFormatRequest Select(Expression<Func<WorkbookChartAxisTitleFormat, object>> selectExpression)
{
if (selectExpression == null)
{
throw new ArgumentNullException(nameof(selectExpression));
}
string error;
string value = ExpressionExtractHelper.ExtractMembers(selectExpression, out error);
if (value == null)
{
throw new ArgumentException(error, nameof(selectExpression));
}
else
{
this.QueryOptions.Add(new QueryOption("$select", value));
}
return this;
}
/// <summary>
/// Initializes any collection properties after deserialization, like next requests for paging.
/// </summary>
/// <param name="workbookChartAxisTitleFormatToInitialize">The <see cref="WorkbookChartAxisTitleFormat"/> with the collection properties to initialize.</param>
private void InitializeCollectionProperties(WorkbookChartAxisTitleFormat workbookChartAxisTitleFormatToInitialize)
{
}
}
}
| |
//
// HttpContent.cs
//
// Authors:
// Marek Safar <marek.safar@gmail.com>
//
// Copyright (C) 2011 Xamarin Inc (http://www.xamarin.com)
//
// 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.Net.Http.Headers;
using System.IO;
using System.Threading.Tasks;
using System.Text;
using Rackspace.Threading;
namespace System.Net.Http
{
public abstract class HttpContent : IDisposable
{
sealed class FixedMemoryStream : MemoryStream
{
readonly long maxSize;
public FixedMemoryStream (long maxSize)
: base ()
{
this.maxSize = maxSize;
}
void CheckOverflow (int count)
{
if (Length + count > maxSize)
throw new HttpRequestException (string.Format ("Cannot write more bytes to the buffer than the configured maximum buffer size: {0}", maxSize));
}
public override void WriteByte (byte value)
{
CheckOverflow (1);
base.WriteByte (value);
}
public override void Write (byte[] buffer, int offset, int count)
{
CheckOverflow (count);
base.Write (buffer, offset, count);
}
}
FixedMemoryStream buffer;
Stream stream;
bool disposed;
HttpContentHeaders headers;
public HttpContentHeaders Headers {
get {
return headers ?? (headers = new HttpContentHeaders (this));
}
}
internal long? LoadedBufferLength {
get {
return buffer == null ? (long?)null : buffer.Length;
}
}
public Task CopyToAsync (Stream stream)
{
return CopyToAsync (stream, null);
}
public Task CopyToAsync (Stream stream, TransportContext context)
{
if (stream == null)
throw new ArgumentNullException ("stream");
if (buffer != null)
return buffer.CopyToAsync (stream);
return SerializeToStreamAsync (stream, context);
}
protected virtual Task<Stream> CreateContentReadStreamAsync ()
{
return LoadIntoBufferAsync ().Select<Stream> (_ => buffer);
}
static FixedMemoryStream CreateFixedMemoryStream (long maxBufferSize)
{
return new FixedMemoryStream (maxBufferSize);
}
public void Dispose ()
{
Dispose (true);
}
protected virtual void Dispose (bool disposing)
{
if (disposing && !disposed) {
disposed = true;
if (buffer != null)
buffer.Dispose ();
}
}
public Task LoadIntoBufferAsync ()
{
return LoadIntoBufferAsync (int.MaxValue);
}
public Task LoadIntoBufferAsync (long maxBufferSize)
{
if (disposed)
throw new ObjectDisposedException (GetType ().ToString ());
if (buffer != null)
return CompletedTask.Default;
buffer = CreateFixedMemoryStream (maxBufferSize);
return SerializeToStreamAsync (buffer, null)
.Select (_ => buffer.Seek (0, SeekOrigin.Begin));
}
public Task<Stream> ReadAsStreamAsync ()
{
if (disposed)
throw new ObjectDisposedException (GetType ().ToString ());
if (buffer != null)
return CompletedTask.FromResult<Stream> (new MemoryStream (buffer.GetBuffer (), 0, (int)buffer.Length, false));
if (stream == null)
return CreateContentReadStreamAsync ().Select (task => stream = task.Result);
return CompletedTask.FromResult (stream);
}
public Task<byte[]> ReadAsByteArrayAsync ()
{
return LoadIntoBufferAsync ().Select (_ => buffer.ToArray ());
}
public Task<string> ReadAsStringAsync ()
{
return LoadIntoBufferAsync ().Select (
_ => {
if (buffer.Length == 0)
return string.Empty;
var buf = buffer.GetBuffer ();
var buf_length = (int) buffer.Length;
int preambleLength = 0;
Encoding encoding;
if (headers != null && headers.ContentType != null && headers.ContentType.CharSet != null) {
encoding = Encoding.GetEncoding (headers.ContentType.CharSet);
preambleLength = StartsWith (buf, buf_length, encoding.GetPreamble ());
} else {
encoding = GetEncodingFromBuffer (buf, buf_length, ref preambleLength) ?? Encoding.UTF8;
}
return encoding.GetString (buf, preambleLength, buf_length - preambleLength);
});
}
private static Encoding GetEncodingFromBuffer (byte[] buffer, int length, ref int preambleLength)
{
var encodings_with_preamble = new [] { Encoding.UTF8, Encoding.UTF32, Encoding.Unicode };
foreach (var enc in encodings_with_preamble) {
if ((preambleLength = StartsWith (buffer, length, enc.GetPreamble ())) > 0)
return enc;
}
return null;
}
static int StartsWith (byte[] array, int length, byte[] value)
{
if (length < value.Length)
return 0;
for (int i = 0; i < value.Length; ++i) {
if (array [i] != value [i])
return 0;
}
return value.Length;
}
protected internal abstract Task SerializeToStreamAsync (Stream stream, TransportContext context);
protected internal abstract bool TryComputeLength (out long length);
}
}
| |
/********************************************************************************************
Copyright (c) Microsoft Corporation
All rights reserved.
Microsoft Public License:
This license governs use of the accompanying software. If you use the software, you
accept this license. If you do not accept the license, do not use the software.
1. Definitions
The terms "reproduce," "reproduction," "derivative works," and "distribution" have the
same meaning here as under U.S. copyright law.
A "contribution" is the original software, or any additions or changes to the software.
A "contributor" is any person that distributes its contribution under this license.
"Licensed patents" are a contributor's patent claims that read directly on its contribution.
2. Grant of Rights
(A) Copyright Grant- Subject to the terms of this license, including the license conditions
and limitations in section 3, each contributor grants you a non-exclusive, worldwide,
royalty-free copyright license to reproduce its contribution, prepare derivative works of
its contribution, and distribute its contribution or any derivative works that you create.
(B) Patent Grant- Subject to the terms of this license, including the license conditions
and limitations in section 3, each contributor grants you a non-exclusive, worldwide,
royalty-free license under its licensed patents to make, have made, use, sell, offer for
sale, import, and/or otherwise dispose of its contribution in the software or derivative
works of the contribution in the software.
3. Conditions and Limitations
(A) No Trademark License- This license does not grant you rights to use any contributors'
name, logo, or trademarks.
(B) If you bring a patent claim against any contributor over patents that you claim are
infringed by the software, your patent license from such contributor to the software ends
automatically.
(C) If you distribute any portion of the software, you must retain all copyright, patent,
trademark, and attribution notices that are present in the software.
(D) If you distribute any portion of the software in source code form, you may do so only
under this license by including a complete copy of this license with your distribution.
If you distribute any portion of the software in compiled or object code form, you may only
do so under a license that complies with this license.
(E) The software is licensed "as-is." You bear the risk of using it. The contributors give
no express warranties, guarantees or conditions. You may have additional consumer rights
under your local laws which this license cannot change. To the extent permitted under your
local laws, the contributors exclude the implied warranties of merchantability, fitness for
a particular purpose and non-infringement.
********************************************************************************************/
using System;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Runtime.InteropServices;
using Microsoft.VisualStudio;
using Microsoft.VisualStudio.OLE.Interop;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.Interop;
using IOleServiceProvider = Microsoft.VisualStudio.OLE.Interop.IServiceProvider;
namespace Microsoft.VisualStudio.Project
{
/// <summary>
/// All public properties on Nodeproperties or derived classes are assumed to be used by Automation by default.
/// Set this attribute to false on Properties that should not be visible for Automation.
/// </summary>
[AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = true)]
public sealed class AutomationBrowsableAttribute : System.Attribute
{
public AutomationBrowsableAttribute(bool browsable)
{
this.browsable = browsable;
}
public bool Browsable
{
get
{
return this.browsable;
}
}
private bool browsable;
}
/// <summary>
/// To create your own localizable node properties, subclass this and add public properties
/// decorated with your own localized display name, category and description attributes.
/// </summary>
[CLSCompliant(false), ComVisible(true)]
public class NodeProperties : LocalizableProperties,
ISpecifyPropertyPages,
IVsGetCfgProvider,
IVsSpecifyProjectDesignerPages,
EnvDTE80.IInternalExtenderProvider,
IVsBrowseObject
{
#region fields
private HierarchyNode node;
#endregion
#region properties
[Browsable(false)]
[AutomationBrowsable(false)]
public HierarchyNode Node
{
get { return this.node; }
}
/// <summary>
/// Used by Property Pages Frame to set it's title bar. The Caption of the Hierarchy Node is returned.
/// </summary>
[Browsable(false)]
[AutomationBrowsable(false)]
public virtual string Name
{
get { return this.node.Caption; }
}
#endregion
#region ctors
public NodeProperties(HierarchyNode node)
{
if(node == null)
{
throw new ArgumentNullException("node");
}
this.node = node;
}
#endregion
#region ISpecifyPropertyPages methods
public virtual void GetPages(CAUUID[] pages)
{
this.GetCommonPropertyPages(pages);
}
#endregion
#region IVsSpecifyProjectDesignerPages
/// <summary>
/// Implementation of the IVsSpecifyProjectDesignerPages. It will retun the pages that are configuration independent.
/// </summary>
/// <param name="pages">The pages to return.</param>
/// <returns></returns>
public virtual int GetProjectDesignerPages(CAUUID[] pages)
{
this.GetCommonPropertyPages(pages);
return VSConstants.S_OK;
}
#endregion
#region IVsGetCfgProvider methods
public virtual int GetCfgProvider(out IVsCfgProvider p)
{
p = null;
return VSConstants.E_NOTIMPL;
}
#endregion
#region IVsBrowseObject methods
/// <summary>
/// Maps back to the hierarchy or project item object corresponding to the browse object.
/// </summary>
/// <param name="hier">Reference to the hierarchy object.</param>
/// <param name="itemid">Reference to the project item.</param>
/// <returns>If the method succeeds, it returns S_OK. If it fails, it returns an error code. </returns>
public virtual int GetProjectItem(out IVsHierarchy hier, out uint itemid)
{
if(this.node == null)
{
throw new InvalidOperationException();
}
hier = this.node.ProjectMgr.InteropSafeIVsHierarchy;
itemid = this.node.ID;
return VSConstants.S_OK;
}
#endregion
#region overridden methods
/// <summary>
/// Get the Caption of the Hierarchy Node instance. If Caption is null or empty we delegate to base
/// </summary>
/// <returns>Caption of Hierarchy node instance</returns>
public override string GetComponentName()
{
string caption = this.Node.Caption;
if(string.IsNullOrEmpty(caption))
{
return base.GetComponentName();
}
else
{
return caption;
}
}
#endregion
#region helper methods
protected string GetProperty(string name, string def)
{
string a = this.Node.ItemNode.GetMetadata(name);
return (a == null) ? def : a;
}
protected void SetProperty(string name, string value)
{
this.Node.ItemNode.SetMetadata(name, value);
}
/// <summary>
/// Retrieves the common property pages. The NodeProperties is the BrowseObject and that will be called to support
/// configuration independent properties.
/// </summary>
/// <param name="pages">The pages to return.</param>
private void GetCommonPropertyPages(CAUUID[] pages)
{
// We do not check whether the supportsProjectDesigner is set to false on the ProjectNode.
// We rely that the caller knows what to call on us.
if(pages == null)
{
throw new ArgumentNullException("pages");
}
if(pages.Length == 0)
{
throw new ArgumentException(SR.GetString(SR.InvalidParameter, CultureInfo.CurrentUICulture), "pages");
}
// Only the project should show the property page the rest should show the project properties.
if(this.node != null && (this.node is ProjectNode))
{
// Retrieve the list of guids from hierarchy properties.
// Because a flavor could modify that list we must make sure we are calling the outer most implementation of IVsHierarchy
string guidsList = String.Empty;
IVsHierarchy hierarchy = this.Node.ProjectMgr.InteropSafeIVsHierarchy;
object variant = null;
ErrorHandler.ThrowOnFailure(hierarchy.GetProperty(VSConstants.VSITEMID_ROOT, (int)__VSHPROPID2.VSHPROPID_PropertyPagesCLSIDList, out variant));
guidsList = (string)variant;
Guid[] guids = Utilities.GuidsArrayFromSemicolonDelimitedStringOfGuids(guidsList);
if(guids == null || guids.Length == 0)
{
pages[0] = new CAUUID();
pages[0].cElems = 0;
}
else
{
pages[0] = PackageUtilities.CreateCAUUIDFromGuidArray(guids);
}
}
else
{
pages[0] = new CAUUID();
pages[0].cElems = 0;
}
}
#endregion
#region IInternalExtenderProvider Members
bool EnvDTE80.IInternalExtenderProvider.CanExtend(string extenderCATID, string extenderName, object extendeeObject)
{
EnvDTE80.IInternalExtenderProvider outerHierarchy = this.Node.ProjectMgr.InteropSafeIVsHierarchy as EnvDTE80.IInternalExtenderProvider;
if(outerHierarchy != null)
{
return outerHierarchy.CanExtend(extenderCATID, extenderName, extendeeObject);
}
return false;
}
object EnvDTE80.IInternalExtenderProvider.GetExtender(string extenderCATID, string extenderName, object extendeeObject, EnvDTE.IExtenderSite extenderSite, int cookie)
{
EnvDTE80.IInternalExtenderProvider outerHierarchy = this.Node.ProjectMgr.InteropSafeIVsHierarchy as EnvDTE80.IInternalExtenderProvider;
if(outerHierarchy != null)
{
return outerHierarchy.GetExtender(extenderCATID, extenderName, extendeeObject, extenderSite, cookie);
}
return null;
}
object EnvDTE80.IInternalExtenderProvider.GetExtenderNames(string extenderCATID, object extendeeObject)
{
EnvDTE80.IInternalExtenderProvider outerHierarchy = this.Node.ProjectMgr.InteropSafeIVsHierarchy as EnvDTE80.IInternalExtenderProvider;
if(outerHierarchy != null)
{
return outerHierarchy.GetExtenderNames(extenderCATID, extendeeObject);
}
return null;
}
#endregion
#region ExtenderSupport
[Browsable(false)]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "CATID")]
public virtual string ExtenderCATID
{
get
{
Guid catid = this.Node.ProjectMgr.GetCATIDForType(this.GetType());
if(Guid.Empty.CompareTo(catid) == 0)
{
return null;
}
return catid.ToString("B");
}
}
[Browsable(false)]
public object ExtenderNames()
{
EnvDTE.ObjectExtenders extenderService = (EnvDTE.ObjectExtenders)this.Node.GetService(typeof(EnvDTE.ObjectExtenders));
Debug.Assert(extenderService != null, "Could not get the ObjectExtenders object from the services exposed by this property object");
if(extenderService == null)
{
throw new InvalidOperationException();
}
return extenderService.GetExtenderNames(this.ExtenderCATID, this);
}
public object Extender(string extenderName)
{
EnvDTE.ObjectExtenders extenderService = (EnvDTE.ObjectExtenders)this.Node.GetService(typeof(EnvDTE.ObjectExtenders));
Debug.Assert(extenderService != null, "Could not get the ObjectExtenders object from the services exposed by this property object");
if(extenderService == null)
{
throw new InvalidOperationException();
}
return extenderService.GetExtender(this.ExtenderCATID, extenderName, this);
}
#endregion
}
[CLSCompliant(false), ComVisible(true)]
public class FileNodeProperties : NodeProperties
{
#region properties
[SRCategoryAttribute(SR.Advanced)]
[LocDisplayName(SR.BuildAction)]
[SRDescriptionAttribute(SR.BuildActionDescription)]
public virtual BuildAction BuildAction
{
get
{
string value = this.Node.ItemNode.ItemName;
if(value == null || value.Length == 0)
{
return BuildAction.None;
}
return (BuildAction)Enum.Parse(typeof(BuildAction), value);
}
set
{
this.Node.ItemNode.ItemName = value.ToString();
}
}
[SRCategoryAttribute(SR.Misc)]
[LocDisplayName(SR.FileName)]
[SRDescriptionAttribute(SR.FileNameDescription)]
public string FileName
{
get
{
return this.Node.Caption;
}
set
{
this.Node.SetEditLabel(value);
}
}
[SRCategoryAttribute(SR.Misc)]
[LocDisplayName(SR.FullPath)]
[SRDescriptionAttribute(SR.FullPathDescription)]
public string FullPath
{
get
{
return this.Node.Url;
}
}
#region non-browsable properties - used for automation only
[Browsable(false)]
public string Extension
{
get
{
return Path.GetExtension(this.Node.Caption);
}
}
#endregion
#endregion
#region ctors
public FileNodeProperties(HierarchyNode node)
: base(node)
{
}
#endregion
#region overridden methods
public override string GetClassName()
{
return SR.GetString(SR.FileProperties, CultureInfo.CurrentUICulture);
}
#endregion
}
[CLSCompliant(false), ComVisible(true)]
public class DependentFileNodeProperties : NodeProperties
{
#region properties
[SRCategoryAttribute(SR.Advanced)]
[LocDisplayName(SR.BuildAction)]
[SRDescriptionAttribute(SR.BuildActionDescription)]
public virtual BuildAction BuildAction
{
get
{
string value = this.Node.ItemNode.ItemName;
if(value == null || value.Length == 0)
{
return BuildAction.None;
}
return (BuildAction)Enum.Parse(typeof(BuildAction), value);
}
set
{
this.Node.ItemNode.ItemName = value.ToString();
}
}
[SRCategoryAttribute(SR.Misc)]
[LocDisplayName(SR.FileName)]
[SRDescriptionAttribute(SR.FileNameDescription)]
public virtual string FileName
{
get
{
return this.Node.Caption;
}
}
[SRCategoryAttribute(SR.Misc)]
[LocDisplayName(SR.FullPath)]
[SRDescriptionAttribute(SR.FullPathDescription)]
public string FullPath
{
get
{
return this.Node.Url;
}
}
#endregion
#region ctors
public DependentFileNodeProperties(HierarchyNode node)
: base(node)
{
}
#endregion
#region overridden methods
public override string GetClassName()
{
return SR.GetString(SR.FileProperties, CultureInfo.CurrentUICulture);
}
#endregion
}
[CLSCompliant(false), ComVisible(true)]
public class SingleFileGeneratorNodeProperties : FileNodeProperties
{
#region fields
private EventHandler<HierarchyNodeEventArgs> onCustomToolChanged;
private EventHandler<HierarchyNodeEventArgs> onCustomToolNameSpaceChanged;
#endregion
#region custom tool events
internal event EventHandler<HierarchyNodeEventArgs> OnCustomToolChanged
{
add { onCustomToolChanged += value; }
remove { onCustomToolChanged -= value; }
}
internal event EventHandler<HierarchyNodeEventArgs> OnCustomToolNameSpaceChanged
{
add { onCustomToolNameSpaceChanged += value; }
remove { onCustomToolNameSpaceChanged -= value; }
}
#endregion
#region properties
[SRCategoryAttribute(SR.Advanced)]
[LocDisplayName(SR.CustomTool)]
[SRDescriptionAttribute(SR.CustomToolDescription)]
public virtual string CustomTool
{
get
{
return this.Node.ItemNode.GetMetadata(ProjectFileConstants.Generator);
}
set
{
if (CustomTool != value)
{
this.Node.ItemNode.SetMetadata(ProjectFileConstants.Generator, value != string.Empty ? value : null);
HierarchyNodeEventArgs args = new HierarchyNodeEventArgs(this.Node);
if (onCustomToolChanged != null)
{
onCustomToolChanged(this.Node, args);
}
}
}
}
[SRCategoryAttribute(VisualStudio.Project.SR.Advanced)]
[LocDisplayName(SR.CustomToolNamespace)]
[SRDescriptionAttribute(SR.CustomToolNamespaceDescription)]
public virtual string CustomToolNamespace
{
get
{
return this.Node.ItemNode.GetMetadata(ProjectFileConstants.CustomToolNamespace);
}
set
{
if (CustomToolNamespace != value)
{
this.Node.ItemNode.SetMetadata(ProjectFileConstants.CustomToolNamespace, value != String.Empty ? value : null);
HierarchyNodeEventArgs args = new HierarchyNodeEventArgs(this.Node);
if (onCustomToolNameSpaceChanged != null)
{
onCustomToolNameSpaceChanged(this.Node, args);
}
}
}
}
#endregion
#region ctors
public SingleFileGeneratorNodeProperties(HierarchyNode node)
: base(node)
{
}
#endregion
}
[CLSCompliant(false), ComVisible(true)]
public class ProjectNodeProperties : NodeProperties
{
#region properties
[SRCategoryAttribute(SR.Misc)]
[LocDisplayName(SR.ProjectFolder)]
[SRDescriptionAttribute(SR.ProjectFolderDescription)]
[AutomationBrowsable(false)]
public string ProjectFolder
{
get
{
return this.Node.ProjectMgr.ProjectFolder;
}
}
[SRCategoryAttribute(SR.Misc)]
[LocDisplayName(SR.ProjectFile)]
[SRDescriptionAttribute(SR.ProjectFileDescription)]
[AutomationBrowsable(false)]
public string ProjectFile
{
get
{
return this.Node.ProjectMgr.ProjectFile;
}
set
{
this.Node.ProjectMgr.ProjectFile = value;
}
}
#region non-browsable properties - used for automation only
[Browsable(false)]
public string FileName
{
get
{
return this.Node.ProjectMgr.ProjectFile;
}
set
{
this.Node.ProjectMgr.ProjectFile = value;
}
}
[Browsable(false)]
public string FullPath
{
get
{
string fullPath = this.Node.ProjectMgr.ProjectFolder;
if(!fullPath.EndsWith(Path.DirectorySeparatorChar.ToString(), StringComparison.Ordinal))
{
return fullPath + Path.DirectorySeparatorChar;
}
else
{
return fullPath;
}
}
}
#endregion
#endregion
#region ctors
public ProjectNodeProperties(ProjectNode node)
: base(node)
{
}
#endregion
#region overridden methods
public override string GetClassName()
{
return SR.GetString(SR.ProjectProperties, CultureInfo.CurrentUICulture);
}
/// <summary>
/// ICustomTypeDescriptor.GetEditor
/// To enable the "Property Pages" button on the properties browser
/// the browse object (project properties) need to be unmanaged
/// or it needs to provide an editor of type ComponentEditor.
/// </summary>
/// <param name="editorBaseType">Type of the editor</param>
/// <returns>Editor</returns>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope",
Justification="The service provider is used by the PropertiesEditorLauncher")]
public override object GetEditor(Type editorBaseType)
{
// Override the scenario where we are asked for a ComponentEditor
// as this is how the Properties Browser calls us
if(editorBaseType == typeof(ComponentEditor))
{
IOleServiceProvider sp;
ErrorHandler.ThrowOnFailure(this.Node.GetSite(out sp));
return new PropertiesEditorLauncher(new ServiceProvider(sp));
}
return base.GetEditor(editorBaseType);
}
public override int GetCfgProvider(out IVsCfgProvider p)
{
if(this.Node != null && this.Node.ProjectMgr != null)
{
return this.Node.ProjectMgr.GetCfgProvider(out p);
}
return base.GetCfgProvider(out p);
}
#endregion
}
[CLSCompliant(false), ComVisible(true)]
public class FolderNodeProperties : NodeProperties
{
#region properties
[SRCategoryAttribute(SR.Misc)]
[LocDisplayName(SR.FolderName)]
[SRDescriptionAttribute(SR.FolderNameDescription)]
[AutomationBrowsable(false)]
public string FolderName
{
get
{
return this.Node.Caption;
}
set
{
this.Node.SetEditLabel(value);
this.Node.ReDraw(UIHierarchyElement.Caption);
}
}
#region properties - used for automation only
[Browsable(false)]
[AutomationBrowsable(true)]
public string FileName
{
get
{
return this.Node.Caption;
}
set
{
this.Node.SetEditLabel(value);
}
}
[Browsable(false)]
[AutomationBrowsable(true)]
public string FullPath
{
get
{
string fullPath = this.Node.GetMkDocument();
if(!fullPath.EndsWith(Path.DirectorySeparatorChar.ToString(), StringComparison.Ordinal))
{
return fullPath + Path.DirectorySeparatorChar;
}
else
{
return fullPath;
}
}
}
#endregion
#endregion
#region ctors
public FolderNodeProperties(HierarchyNode node)
: base(node)
{
}
#endregion
#region overridden methods
public override string GetClassName()
{
return SR.GetString(SR.FolderProperties, CultureInfo.CurrentUICulture);
}
#endregion
}
[CLSCompliant(false), ComVisible(true)]
public class ReferenceNodeProperties : NodeProperties
{
#region properties
[SRCategoryAttribute(SR.Misc)]
[LocDisplayName(SR.RefName)]
[SRDescriptionAttribute(SR.RefNameDescription)]
[Browsable(true)]
[AutomationBrowsable(true)]
public override string Name
{
get
{
return this.Node.Caption;
}
}
[SRCategoryAttribute(SR.Misc)]
[LocDisplayName(SR.CopyToLocal)]
[SRDescriptionAttribute(SR.CopyToLocalDescription)]
public bool CopyToLocal
{
get
{
string copyLocal = this.GetProperty(ProjectFileConstants.Private, "False");
if(copyLocal == null || copyLocal.Length == 0)
return true;
return bool.Parse(copyLocal);
}
set
{
this.SetProperty(ProjectFileConstants.Private, value.ToString());
}
}
[SRCategoryAttribute(SR.Misc)]
[LocDisplayName(SR.FullPath)]
[SRDescriptionAttribute(SR.FullPathDescription)]
public virtual string FullPath
{
get
{
return this.Node.Url;
}
}
#endregion
#region ctors
public ReferenceNodeProperties(HierarchyNode node)
: base(node)
{
}
#endregion
#region overridden methods
public override string GetClassName()
{
return SR.GetString(SR.ReferenceProperties, CultureInfo.CurrentUICulture);
}
#endregion
}
[ComVisible(true)]
public class ProjectReferencesProperties : ReferenceNodeProperties
{
#region ctors
public ProjectReferencesProperties(ProjectReferenceNode node)
: base(node)
{
}
#endregion
#region overriden methods
public override string FullPath
{
get
{
return ((ProjectReferenceNode)Node).ReferencedProjectOutputPath;
}
}
#endregion
}
[ComVisible(true)]
public class ComReferenceProperties : ReferenceNodeProperties
{
public ComReferenceProperties(ComReferenceNode node)
: base(node)
{
}
[SRCategory(SR.Misc)]
[LocDisplayName(SR.EmbedInteropTypes)]
[SRDescription(SR.EmbedInteropTypesDescription)]
public virtual bool EmbedInteropTypes
{
get { return ((ComReferenceNode)this.Node).EmbedInteropTypes; }
set { ((ComReferenceNode)this.Node).EmbedInteropTypes = value; }
}
}
}
| |
/***************************************************************************
* VolumeButton.cs
*
* Copyright (C) 2005 Ronald S. Bultje; 2007 Novell, Inc.
*
* Ported to Gtk# by Aaron Bockover <abockover@novell.com>
* Based on r106 of libbacon/trunk/src/bacon-volume.c in GNOME SVN
*
* Original Authors (BaconVolumeButton/GTK+):
* Ronald S. Bultje <rbultje@ronald.bitfreak.net>
* Bastien Nocera <hadess@hadess.net>
* Contributions By (BaconVolumeButton/GTK+):
* Jan Arne Petersen <jpetersen@jpetersen.org>
* Christian Persch <chpe@gnome.org>
****************************************************************************/
/* THIS FILE IS LICENSED UNDER THE MIT LICENSE AS OUTLINED IMMEDIATELY BELOW:
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
#pragma warning disable 0612
using System;
using System.Runtime.InteropServices;
using Mono.Unix;
using GLib;
using Gtk;
namespace Bacon
{
public class VolumeButton : Button
{
public delegate void VolumeChangedHandler(int volume);
private const int SCALE_SIZE = 100;
private const int CLICK_TIMEOUT = 250;
private Tooltips tooltips = new Tooltips();
private Window dock;
private VolumeScale slider;
private Image image;
private Button plus;
private Button minus;
private IconSize size;
private uint click_id;
private int direction;
private int previous_volume;
private uint pop_time;
private bool timeout;
private bool classic;
private Gdk.Pixbuf [] pixbufs;
public event VolumeChangedHandler VolumeChanged;
public bool Classic {
get { return classic; }
set { classic = value; }
}
public bool Active {
get { return dock == null ? false : dock.Visible; }
}
public VolumeButton() : this(0.0, 100.0, 5.0, IconSize.SmallToolbar)
{
}
public VolumeButton(double min, double max, double step, IconSize size) : base()
{
this.size = size;
BuildButton();
BuildPopup(min, max, step);
Accessible.Name = Catalog.GetString ("Volume");
WidgetEventAfter += OnWidgetEventAfter;
}
public override void Dispose()
{
if(dock != null) {
dock.Destroy();
dock = null;
}
if(click_id != 0) {
GLib.Source.Remove(click_id);
click_id = 0;
}
base.Dispose();
}
private void BuildButton()
{
FocusOnClick = false;
Relief = ReliefStyle.None;
image = new Image();
image.Show();
Add(image);
}
private void BuildPopup(double min, double max, double step)
{
dock = new Window(WindowType.Popup);
dock.Screen = Screen;
dock.ButtonPressEvent += OnDockButtonPressEvent;
dock.KeyPressEvent += OnDockKeyPressEvent;
dock.KeyReleaseEvent += OnDockKeyReleaseEvent;
dock.ScrollEvent += OnPlusMinusScollEvent;
dock.Hidden += OnDockHidden;
Frame frame = new Frame();
frame.Shadow = ShadowType.Out;
frame.Show();
dock.Add(frame);
VBox box = new VBox(false, 0);
box.Show();
frame.Add(box);
Label label = new Label();
label.Markup = "<b><big>+</big></b>";
plus = new Button(label);
plus.Relief = ReliefStyle.None;
plus.ButtonPressEvent += OnPlusMinusButtonPressEvent;
plus.ButtonReleaseEvent += OnPlusMinusButtonReleaseEvent;
plus.ScrollEvent += OnPlusMinusScollEvent;
plus.ShowAll();
box.PackStart(plus, false, true, 0);
slider = new VolumeScale(this, min, max, step);
slider.SetSizeRequest(-1, SCALE_SIZE);
slider.DrawValue = false;
slider.Inverted = true;
slider.Show();
box.PackStart(slider, true, true, 0);
label = new Label();
label.Markup = "<b><big>\u2212</big></b>";
minus = new Button(label);
minus.Relief = ReliefStyle.None;
minus.ButtonPressEvent += OnPlusMinusButtonPressEvent;
minus.ButtonReleaseEvent += OnPlusMinusButtonReleaseEvent;
minus.ScrollEvent += OnPlusMinusScollEvent;
minus.ShowAll();
box.PackEnd(minus, false, true, 0);
Show();
}
protected virtual void OnVolumeChanged()
{
VolumeChangedHandler handler = VolumeChanged;
if(handler != null) {
handler(Volume);
}
}
private bool ShowDock(Gdk.Event evnt)
{
Adjustment adj = slider.Adjustment;
int x, y, m, dx, dy, sx, sy, ystartoff;
uint event_time;
double v;
if(previous_volume != (int)slider.Adjustment.Lower) {
previous_volume = Volume;
}
if(evnt is Gdk.EventKey) {
event_time = ((Gdk.EventKey)evnt).Time;
} else if(evnt is Gdk.EventButton) {
event_time = ((Gdk.EventButton)evnt).Time;
} else if(evnt is Gdk.EventScroll) {
event_time = ((Gdk.EventScroll)evnt).Time;
} else {
throw new ApplicationException("ShowDock expects EventKey, EventButton, or EventScroll");
}
if(classic) {
dock.Realize();
}
dock.Screen = Screen;
GdkWindow.GetOrigin(out x, out y);
x += Allocation.X;
v = Volume / (adj.Upper - adj.Lower);
if(classic) {
dock.Move(x + (Allocation.Width - dock.Allocation.Width) / 2, y - dock.Allocation.Height);
dock.ShowAll();
Relief = ReliefStyle.Normal;
State = StateType.Active;
} else {
y += Allocation.Y;
dock.Move(x, y - (SCALE_SIZE / 2));
dock.ShowAll();
dock.GdkWindow.GetOrigin(out dx, out dy);
dy += dock.Allocation.Y;
slider.GdkWindow.GetOrigin(out sx, out sy);
sy += slider.Allocation.Y;
ystartoff = sy - dy;
timeout = true;
x += (Allocation.Width - dock.Allocation.Width) / 2;
y -= ystartoff;
y -= slider.MinSliderSize / 2;
m = slider.Allocation.Height - slider.MinSliderSize;
y -= (int)(m * (1.0 - v));
if(evnt is Gdk.EventButton) {
y += (int)((Gdk.EventButton)evnt).Y;
} else if(evnt is Gdk.EventScroll) {
y += (int)((Gdk.EventScroll)evnt).Y;
}
dock.Move(x, y);
slider.GdkWindow.GetOrigin(out sx, out sy);
}
bool base_result = !classic && evnt is Gdk.EventButton
? base.OnButtonPressEvent((Gdk.EventButton)evnt)
: true;
Gtk.Grab.Add(dock);
if(Gdk.Pointer.Grab(dock.GdkWindow, true,
Gdk.EventMask.ButtonPressMask |
Gdk.EventMask.ButtonReleaseMask |
Gdk.EventMask.PointerMotionMask, null, null, event_time) != Gdk.GrabStatus.Success) {
Gtk.Grab.Remove(dock);
dock.Hide();
return false;
}
if(Gdk.Keyboard.Grab(dock.GdkWindow, true, event_time) != Gdk.GrabStatus.Success) {
Display.PointerUngrab(event_time);
Gtk.Grab.Remove(dock);
dock.Hide();
return false;
}
if(!classic && evnt is Gdk.EventButton) {
dock.GrabFocus();
Gdk.EventButton evnt_copy = (Gdk.EventButton)Gdk.EventHelper.Copy(evnt);
m = slider.Allocation.Height - slider.MinSliderSize;
UpdateEventButton(evnt_copy, slider.GdkWindow, slider.Allocation.Width / 2,
((1.0 - v) * m) + slider.MinSliderSize / 2);
slider.ProcessEvent(evnt_copy);
Gdk.EventHelper.Free(evnt_copy);
} else {
slider.GrabFocus();
}
pop_time = event_time;
return base_result;
}
protected override bool OnButtonPressEvent(Gdk.EventButton evnt)
{
return ShowDock(evnt);
}
protected override bool OnKeyReleaseEvent(Gdk.EventKey evnt)
{
switch(evnt.Key) {
case Gdk.Key.space:
case Gdk.Key.Return:
case Gdk.Key.KP_Enter:
return ShowDock(evnt);
default:
return false;
}
}
protected override bool OnKeyPressEvent(Gdk.EventKey evnt)
{
switch(evnt.Key) {
case Gdk.Key.Up:
case Gdk.Key.Down:
case Gdk.Key.KP_Add:
case Gdk.Key.KP_Subtract:
case Gdk.Key.plus:
case Gdk.Key.minus:
return ShowDock(evnt);
case Gdk.Key.Key_0:
case Gdk.Key.KP_0:
case Gdk.Key.m:
case Gdk.Key.M:
ToggleMute();
return false;
default:
break;
}
return false;
}
// FIXME: There's no g_signal_stop_emission* binding:
// http://bugzilla.novell.com/show_bug.cgi?id=319275
[DllImport("libgobject-2.0-0.dll")]
private static extern void g_signal_stop_emission_by_name(IntPtr o, string signal);
// In case there's no map provided by the assembly .config file
[DllImport("libgobject-2.0-0.dll", EntryPoint="g_signal_stop_emission_by_name")]
private static extern void g_signal_stop_emission_by_name_fallback(IntPtr o, string signal);
private void OnWidgetEventAfter(object o, WidgetEventAfterArgs args)
{
if(args.Event.Type != Gdk.EventType.Scroll) {
return;
}
try {
g_signal_stop_emission_by_name(Handle, "event-after");
} catch(DllNotFoundException) {
WarnGObjectMap();
g_signal_stop_emission_by_name_fallback(Handle, "event-after");
}
}
protected override bool OnScrollEvent(Gdk.EventScroll evnt)
{
if(evnt.Type != Gdk.EventType.Scroll) {
return false;
}
if(evnt.Direction == Gdk.ScrollDirection.Up) {
AdjustVolume(1);
} else if(evnt.Direction == Gdk.ScrollDirection.Down) {
AdjustVolume(-1);
}
return true;
}
protected override void OnStyleSet(Style previous)
{
base.OnStyleSet(previous);
LoadIcons();
}
private void OnDockKeyPressEvent(object o, KeyPressEventArgs args)
{
args.RetVal = args.Event.Key == Gdk.Key.Escape;
}
private void OnDockKeyReleaseEvent(object o, KeyReleaseEventArgs args)
{
if(args.Event.Key == Gdk.Key.Escape) {
Display.KeyboardUngrab(args.Event.Time);
Display.PointerUngrab(args.Event.Time);
Gtk.Grab.Remove(dock);
dock.Hide();
timeout = false;
args.RetVal = true;
return;
}
args.RetVal = false;
}
private void OnDockHidden(object o, EventArgs args)
{
State = StateType.Normal;
Relief = ReliefStyle.None;
}
private void OnDockButtonPressEvent(object o, ButtonPressEventArgs args)
{
if(args.Event.Type == Gdk.EventType.ButtonPress) {
ReleaseGrab(args.Event);
args.RetVal = true;
return;
}
args.RetVal = false;
}
private bool PlusMinusButtonTimeout()
{
if(click_id == 0) {
return false;
}
bool result = AdjustVolume(direction);
if(!result) {
GLib.Source.Remove(click_id);
click_id = 0;
}
return result;
}
[GLib.ConnectBefore]
private void OnPlusMinusButtonPressEvent(object o, ButtonPressEventArgs args)
{
if(click_id != 0) {
GLib.Source.Remove(click_id);
}
direction = o == minus ? -1 : 1;
click_id = GLib.Timeout.Add(CLICK_TIMEOUT / 2, PlusMinusButtonTimeout);
PlusMinusButtonTimeout();
args.RetVal = true;
}
[GLib.ConnectBefore]
private void OnPlusMinusButtonReleaseEvent(object o, ButtonReleaseEventArgs args)
{
if(click_id != 0) {
GLib.Source.Remove(click_id);
click_id = 0;
}
}
[GLib.ConnectBefore]
private void OnPlusMinusScollEvent(object o, ScrollEventArgs args)
{
if(args.Event.Direction == Gdk.ScrollDirection.Up) {
AdjustVolume(1);
} else if(args.Event.Direction == Gdk.ScrollDirection.Down) {
AdjustVolume(-1);
}
}
private void ReleaseGrab(Gdk.Event evnt)
{
uint event_time;
if(evnt is Gdk.EventKey) {
event_time = ((Gdk.EventKey)evnt).Time;
} else if(evnt is Gdk.EventButton) {
event_time = ((Gdk.EventButton)evnt).Time;
} else {
throw new ApplicationException("ShowDock expects EventKey or EventButton");
}
Display.KeyboardUngrab(event_time);
Display.PointerUngrab(event_time);
Gtk.Grab.Remove(dock);
dock.Hide();
timeout = false;
if(evnt is Gdk.EventButton) {
Gdk.EventButton evnt_copy = (Gdk.EventButton)Gdk.EventHelper.Copy(evnt);
UpdateEventButton(evnt_copy, GdkWindow, Gdk.EventType.ButtonRelease);
ProcessEvent(evnt_copy);
Gdk.EventHelper.Free(evnt_copy);
}
}
private void LoadIcons()
{
string [,] icon_names = {
{ "audio-volume-muted", "stock_volume-0" },
{ "audio-volume-low", "stock_volume-min" },
{ "audio-volume-medium", "stock_volume-med" },
{ "audio-volume-high", "stock_volume-max" }
};
int width, height;
Icon.SizeLookup(size, out width, out height);
IconTheme theme = IconTheme.GetForScreen(Screen);
if(pixbufs == null) {
pixbufs = new Gdk.Pixbuf[icon_names.Length / icon_names.Rank];
}
for(int i = 0; i < icon_names.Length / icon_names.Rank; i++) {
for(int j = 0; j < icon_names.Rank; j++) {
if(pixbufs[i] != null) {
pixbufs[i].Dispose();
pixbufs[i] = null;
}
try {
pixbufs[i] = theme.LoadIcon(icon_names[i, j], width, 0);
break;
} catch {
}
}
}
Update();
}
private void Update()
{
UpdateIcon();
UpdateTip();
}
private void UpdateIcon()
{
if(slider == null || pixbufs == null) {
return;
}
double step = (slider.Adjustment.Upper - slider.Adjustment.Lower - 1) / (pixbufs.Length - 1);
image.Pixbuf = pixbufs[(int)Math.Ceiling((Volume - 1) / step)];
}
private void UpdateTip()
{
string tip;
if(Volume == slider.Adjustment.Lower) {
tip = Catalog.GetString("Muted");
} else if(Volume == slider.Adjustment.Upper) {
tip = Catalog.GetString("Full Volume");
} else {
tip = String.Format("{0}%", (int)((Volume - slider.Adjustment.Lower) /
(slider.Adjustment.Upper - slider.Adjustment.Lower) * 100.0));
}
tooltips.SetTip(this, tip, null);
}
private bool AdjustVolume(int direction)
{
Adjustment adj = slider.Adjustment;
double temp_vol = Volume + direction * adj.StepIncrement;
temp_vol = Math.Min(adj.Upper, temp_vol);
temp_vol = Math.Max(adj.Lower, temp_vol);
Volume = (int)temp_vol;
return Volume > adj.Lower && Volume < adj.Upper;
}
public void ToggleMute()
{
if(Volume == (int)slider.Adjustment.Lower) {
Volume = previous_volume;
} else {
previous_volume = Volume;
Volume = (int)slider.Adjustment.Lower;
}
}
public int Volume {
get { return (int)slider.Value; }
set {
slider.Value = value;
Update();
}
}
// FIXME: This is seriously LAME. The Gtk# binding does not support mutating
// Gdk.Event* objects. All the properties are marked read only. Support for
// these objects is simply incomplete.
// http://bugzilla.novell.com/show_bug.cgi?id=323373
private void UpdateEventButton(Gdk.EventButton evnt, Gdk.Window window, Gdk.EventType type)
{
Marshal.WriteInt32(evnt.Handle, 0, (int)type);
UpdateEventButtonWindow(evnt, window);
}
private void UpdateEventButton(Gdk.EventButton evnt, Gdk.Window window, double x, double y)
{
int x_offset = IntPtr.Size * 2 + 8;
UpdateEventButtonWindow(evnt, window);
MarshalWriteDouble(evnt.Handle, x_offset, x);
MarshalWriteDouble(evnt.Handle, x_offset + 8, y);
}
private void UpdateEventButtonWindow(Gdk.EventButton evnt, Gdk.Window window)
{
// FIXME: GLib.Object.Ref is obsolete because it's low level and shouldn't
// be exposed, but it was in 1.x, and it's not going to go away, so this is OK.
#pragma warning disable 0612
window.Ref();
#pragma warning restore 0612
Marshal.WriteIntPtr(evnt.Handle, IntPtr.Size, window.Handle);
}
private void MarshalWriteDouble(IntPtr ptr, int offset, double value)
{
byte [] bytes = BitConverter.GetBytes(value);
for(int i = 0; i < bytes.Length; i++) {
Marshal.WriteByte(ptr, offset + i, bytes[i]);
}
}
private void WarnGObjectMap()
{
Console.Error.WriteLine("* WARNING *: Provide a DLL Map for libgobject-2.0-0.dll");
}
private class VolumeScale : VScale
{
private VolumeButton button;
public VolumeScale(VolumeButton button, double min, double max, double step)
: base(new Adjustment(min, min, max, step, 10 * step, 0))
{
this.button = button;
}
protected override void OnValueChanged()
{
base.OnValueChanged();
button.Update();
button.OnVolumeChanged();
}
protected override bool OnButtonPressEvent(Gdk.EventButton evnt)
{
Gtk.Grab.Remove(button.dock);
return base.OnButtonPressEvent(evnt);
}
protected override bool OnButtonReleaseEvent(Gdk.EventButton evnt)
{
if(button.timeout) {
if(evnt.Time > button.pop_time + CLICK_TIMEOUT) {
button.ReleaseGrab(evnt);
return base.OnButtonReleaseEvent(evnt);
}
button.timeout = false;
}
bool result = base.OnButtonReleaseEvent(evnt);
Gtk.Grab.Add(button.dock);
return result;
}
protected override bool OnKeyReleaseEvent(Gdk.EventKey evnt)
{
switch(evnt.Key) {
case Gdk.Key.space:
case Gdk.Key.Return:
case Gdk.Key.KP_Enter:
button.ReleaseGrab(evnt);
break;
}
return base.OnKeyReleaseEvent(evnt);
}
// FIXME: This is also seriously LAME. The MinSliderSize property is "protected"
// according to gtkrange.h, and thus should be exposed and accessible through
// this sub-class, but GAPI does not bind protected structure fields. LAME LAME.
// http://bugzilla.novell.com/show_bug.cgi?id=323372
[DllImport("libgobject-2.0-0.dll")]
private static extern void g_type_query(IntPtr type, IntPtr query);
// In case there's no map provided by the assembly .config file
[DllImport("libgobject-2.0-0.dll", EntryPoint="g_type_query")]
private static extern void g_type_query_fallback(IntPtr type, IntPtr query);
private int min_slider_size_offset = -1;
public int MinSliderSize {
get {
if(min_slider_size_offset < 0) {
IntPtr query = Marshal.AllocHGlobal(5 * IntPtr.Size);
try {
g_type_query(Gtk.Widget.GType.Val, query);
} catch(DllNotFoundException) {
button.WarnGObjectMap();
g_type_query_fallback(Gtk.Widget.GType.Val, query);
}
min_slider_size_offset = (int)Marshal.ReadIntPtr(query, 2 * IntPtr.Size + 4);
min_slider_size_offset += IntPtr.Size + 8;
Marshal.FreeHGlobal(query);
}
return (int)Marshal.ReadIntPtr(Handle, min_slider_size_offset);
}
}
}
}
}
#pragma warning restore 0612
| |
using SharpDX;
using SharpDX.Direct3D11;
using System;
using System.Threading;
#if !NETFX_CORE
namespace HelixToolkit.Wpf.SharpDX
#else
#if CORE
namespace HelixToolkit.SharpDX.Core
#else
namespace HelixToolkit.UWP
#endif
#endif
{
using System.Diagnostics;
using Model;
namespace Utilities
{
/// <summary>
/// A proxy container to handle view resources
/// </summary>
public class ShaderResourceViewProxy : ReferenceCountDisposeObject
{
public Guid Guid { internal set; get; } = Guid.NewGuid();
public static ShaderResourceViewProxy Empty { get; } = new ShaderResourceViewProxy();
/// <summary>
/// Gets the texture view.
/// </summary>
/// <value>
/// The texture view.
/// </value>
public ShaderResourceView TextureView { get { return textureView; } }
private ShaderResourceView textureView;
/// <summary>
/// Gets the depth stencil view.
/// </summary>
/// <value>
/// The depth stencil view.
/// </value>
public DepthStencilView DepthStencilView { get { return depthStencilView; } }
private DepthStencilView depthStencilView;
/// <summary>
/// Gets the render target view.
/// </summary>
/// <value>
/// The render target view.
/// </value>
public RenderTargetView RenderTargetView { get { return renderTargetView; } }
private RenderTargetView renderTargetView;
/// <summary>
/// Gets the resource.
/// </summary>
/// <value>
/// The resource.
/// </value>
public Resource Resource { get { return resource; } }
private Resource resource;
private readonly Device device;
public global::SharpDX.DXGI.Format TextureFormat { private set; get; }
private ShaderResourceViewProxy() { }
/// <summary>
/// Initializes a new instance of the <see cref="ShaderResourceViewProxy"/> class.
/// </summary>
/// <param name="device">The device.</param>
public ShaderResourceViewProxy(Device device) { this.device = device; }
/// <summary>
/// Initializes a new instance of the <see cref="ShaderResourceViewProxy"/> class.
/// </summary>
/// <param name="device">The device.</param>
/// <param name="textureDesc">The texture desc.</param>
public ShaderResourceViewProxy(Device device, Texture1DDescription textureDesc) : this(device)
{
resource = Collect(new Texture1D(device, textureDesc));
TextureFormat = textureDesc.Format;
}
/// <summary>
/// Initializes a new instance of the <see cref="ShaderResourceViewProxy"/> class.
/// </summary>
/// <param name="device">The device.</param>
/// <param name="textureDesc">The texture desc.</param>
public ShaderResourceViewProxy(Device device, Texture2DDescription textureDesc) : this(device)
{
resource = Collect(new Texture2D(device, textureDesc));
TextureFormat = textureDesc.Format;
}
/// <summary>
/// Initializes a new instance of the <see cref="ShaderResourceViewProxy"/> class.
/// </summary>
/// <param name="device">The device.</param>
/// <param name="textureDesc">The texture desc.</param>
public ShaderResourceViewProxy(Device device, Texture3DDescription textureDesc) : this(device)
{
resource = Collect(new Texture3D(device, textureDesc));
TextureFormat = textureDesc.Format;
}
/// <summary>
///
/// </summary>
/// <param name="device"></param>
/// <param name="resource"></param>
public ShaderResourceViewProxy(Device device, Resource resource) : this(device)
{
this.resource = Collect(resource);
}
/// <summary>
/// Initializes a new instance of the <see cref="ShaderResourceViewProxy"/> class.
/// </summary>
/// <param name="view">The view.</param>
public ShaderResourceViewProxy(ShaderResourceView view) : this(view.Device)
{
textureView = Collect(view);
TextureFormat = view.Description.Format;
}
/// <summary>
/// Creates the view from texture model.
/// </summary>
/// <param name="texture">The stream.</param>
/// <param name="createSRV">Create ShaderResourceView</param>
/// <param name="enableAutoGenMipMap">Enable auto mipmaps generation</param>
/// <exception cref="ArgumentOutOfRangeException"/>
public void CreateView(TextureModel texture, bool createSRV = true, bool enableAutoGenMipMap = true)
{
this.DisposeAndClear();
if (texture != null && device != null)
{
if (texture.IsCompressed)
{
var stream = texture.CompressedStream;
if (stream == null || !stream.CanRead)
{
Debug.WriteLine("Stream is null or unreadable.");
return;
}
resource = Collect(TextureLoader.FromMemoryAsShaderResource(device, stream, !enableAutoGenMipMap));
if (createSRV)
{
textureView = Collect(new ShaderResourceView(device, resource));
}
TextureFormat = textureView.Description.Format;
if (texture.CanAutoCloseStream)
{
Debug.WriteLine($"Auto closing stream for {texture.Guid}");
stream.Dispose();
}
}
else if (texture.NonCompressedData != null && texture.NonCompressedData.Length > 0)
{
if (texture.Width * texture.Height > texture.NonCompressedData.Length)
{
throw new ArgumentOutOfRangeException($"Texture width * height = {texture.Width * texture.Height} is larger than texture data length {texture.NonCompressedData.Length}.");
}
else if (texture.Height <= 1)
{
if (texture.Width == 0)
{
CreateView(texture.NonCompressedData, texture.UncompressedFormat, createSRV, enableAutoGenMipMap);
}
else
{
CreateView(texture.NonCompressedData, texture.Width, texture.UncompressedFormat, createSRV, enableAutoGenMipMap);
}
}
else
{
CreateView(texture.NonCompressedData, texture.Width, texture.Height, texture.UncompressedFormat, createSRV, enableAutoGenMipMap);
}
}
}
}
/// <summary>
/// Creates the view.
/// </summary>
/// <param name="desc">The desc.</param>
public void CreateView(ShaderResourceViewDescription desc)
{
RemoveAndDispose(ref textureView);
if (resource == null)
{
return;
}
textureView = Collect(new ShaderResourceView(device, resource, desc));
}
/// <summary>
/// Creates the view.
/// </summary>
/// <param name="desc">The desc.</param>
public void CreateView(DepthStencilViewDescription desc)
{
RemoveAndDispose(ref depthStencilView);
if (resource == null)
{
return;
}
depthStencilView = Collect(new DepthStencilView(device, resource, desc));
}
/// <summary>
/// Creates the view.
/// </summary>
/// <param name="desc">The desc.</param>
public void CreateView(RenderTargetViewDescription desc)
{
RemoveAndDispose(ref renderTargetView);
if (resource == null)
{
return;
}
renderTargetView = Collect(new RenderTargetView(device, resource, desc));
}
/// <summary>
/// Creates the view.
/// </summary>
public void CreateTextureView()
{
RemoveAndDispose(ref textureView);
if (resource == null)
{
return;
}
textureView = Collect(new ShaderResourceView(device, resource));
}
/// <summary>
/// Creates the render target.
/// </summary>
public void CreateRenderTargetView()
{
RemoveAndDispose(ref renderTargetView);
if (resource == null)
{
return;
}
renderTargetView = Collect(new RenderTargetView(device, resource));
}
public void CreateDepthStencilView()
{
RemoveAndDispose(ref depthStencilView);
if (resource == null)
{
return;
}
depthStencilView = Collect(new DepthStencilView(device, resource));
}
/// <summary>
/// Creates the 1D texture view from data array.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="array">The array.</param>
/// <param name="format">The format.</param>
/// <param name="createSRV">if set to <c>true</c> [create SRV].</param>
/// <param name="generateMipMaps">if set to <c>true</c> [generate mip maps].</param>
public void CreateView<T>(T[] array, global::SharpDX.DXGI.Format format,
bool createSRV = true, bool generateMipMaps = true) where T : struct
{
CreateView(array, array.Length, format, createSRV, generateMipMaps);
}
/// <summary>
/// Creates the 1D texture view from data array.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="array">The array.</param>
/// <param name="length">data length</param>
/// <param name="format">The pixel format.</param>
/// <param name="createSRV">if set to <c>true</c> [create SRV].</param>
/// <param name="generateMipMaps"></param>
public void CreateView<T>(T[] array, int length, global::SharpDX.DXGI.Format format,
bool createSRV = true, bool generateMipMaps = true) where T : struct
{
this.DisposeAndClear();
var texture = Collect(global::SharpDX.Toolkit.Graphics.Texture1D.New(device, Math.Min(array.Length, length), format, array));
TextureFormat = format;
if (texture.Description.MipLevels == 1 && generateMipMaps)
{
if(TextureLoader.GenerateMipMaps(device, texture, out var mipmapTexture))
{
resource = Collect(mipmapTexture);
RemoveAndDispose(ref texture);
}
else
{
resource = texture;
}
}
else
{
resource = texture;
}
if (createSRV)
{
textureView = Collect(new ShaderResourceView(device, resource));
}
}
/// <summary>
/// Creates the 2D texture view from data array.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="array">The array.</param>
/// <param name="width">The width.</param>
/// <param name="height">The height.</param>
/// <param name="format">The format.</param>
/// <param name="createSRV">if set to <c>true</c> [create SRV].</param>
/// <param name="generateMipMaps"></param>
/// <exception cref="ArgumentOutOfRangeException"/>
public void CreateView<T>(T[] array, int width, int height, global::SharpDX.DXGI.Format format,
bool createSRV = true, bool generateMipMaps = true) where T : struct
{
this.DisposeAndClear();
if(width * height > array.Length)
{
throw new ArgumentOutOfRangeException($"Width*Height = {width * height} is larger than array size {array.Length}.");
}
var texture = Collect(global::SharpDX.Toolkit.Graphics.Texture2D.New(device, width, height,
format, array));
TextureFormat = format;
if (texture.Description.MipLevels == 1 && generateMipMaps)
{
if (TextureLoader.GenerateMipMaps(device, texture, out var mipmapTexture))
{
resource = Collect(mipmapTexture);
RemoveAndDispose(ref texture);
}
else
{
resource = texture;
}
}
else
{
resource = texture;
}
if (createSRV)
{
textureView = Collect(new ShaderResourceView(device, resource));
}
}
/// <summary>
/// Creates the shader resource view from data ptr.
/// </summary>
/// <param name="dataPtr">The data PTR.</param>
/// <param name="width">The width.</param>
/// <param name="height">The height.</param>
/// <param name="format">The format.</param>
/// <param name="createSRV">if set to <c>true</c> [create SRV].</param>
/// <param name="generateMipMaps"></param>
public unsafe void CreateView(IntPtr dataPtr, int width, int height,
global::SharpDX.DXGI.Format format,
bool createSRV = true, bool generateMipMaps = true)
{
this.DisposeAndClear();
var ptr = (IntPtr)dataPtr;
global::SharpDX.Toolkit.Graphics.Image
.ComputePitch(format, width, height,
out var rowPitch, out var slicePitch, out var widthCount, out var heightCount);
var databox = new DataBox(ptr, rowPitch, slicePitch);
var texture = Collect(global::SharpDX.Toolkit.Graphics.Texture2D.New(device, width, height, 1, format,
new[] { databox }));
TextureFormat = format;
if (texture.Description.MipLevels == 1 && generateMipMaps)
{
if (TextureLoader.GenerateMipMaps(device, texture, out var mipmapTexture))
{
resource = Collect(mipmapTexture);
RemoveAndDispose(ref texture);
}
else
{
resource = texture;
}
}
else
{
resource = texture;
}
if (createSRV)
{
textureView = Collect(new ShaderResourceView(device, resource));
}
}
/// <summary>
/// Creates the view from 3D texture byte array.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="pixels">The pixels.</param>
/// <param name="width">The width.</param>
/// <param name="height">The height.</param>
/// <param name="depth">The depth.</param>
/// <param name="format">The format.</param>
/// <param name="createSRV">if set to <c>true</c> [create SRV].</param>
/// <param name="generateMipMaps"></param>
/// <exception cref="ArgumentOutOfRangeException"/>
public void CreateView<T>(T[] pixels, int width, int height, int depth,
global::SharpDX.DXGI.Format format, bool createSRV = true, bool generateMipMaps = true) where T : struct
{
this.DisposeAndClear();
if (width * height * depth > pixels.Length)
{
throw new ArgumentOutOfRangeException($"Width*Height*Depth = {width * height * depth} is larger than array size {pixels.Length}.");
}
var texture = Collect(global::SharpDX.Toolkit.Graphics.Texture3D.New(device, width, height, depth,
format, pixels));
TextureFormat = format;
if (texture.Description.MipLevels == 1 && generateMipMaps)
{
if (TextureLoader.GenerateMipMaps(device, texture, out var mipmapTexture))
{
resource = Collect(mipmapTexture);
RemoveAndDispose(ref texture);
}
else
{
resource = texture;
}
}
else
{
resource = texture;
}
if (createSRV)
{
textureView = Collect(new ShaderResourceView(device, resource));
}
}
/// <summary>
/// Creates the view.
/// </summary>
/// <param name="width">The width.</param>
/// <param name="height">The height.</param>
/// <param name="depth">The depth.</param>
/// <param name="format">The format.</param>
/// <param name="createSRV">if set to <c>true</c> [create SRV].</param>
/// <param name="dataPtr"></param>
/// <param name="generateMipMaps"></param>
public unsafe void CreateView(IntPtr dataPtr, int width, int height, int depth,
global::SharpDX.DXGI.Format format, bool createSRV = true, bool generateMipMaps = true)
{
this.DisposeAndClear();
var ptr = (IntPtr)dataPtr;
var img = global::SharpDX.Toolkit.Graphics.Image.New3D(width, height, depth, global::SharpDX.Toolkit.Graphics.MipMapCount.Auto, format, dataPtr);
var databox = img.ToDataBox();
var texture = Collect(global::SharpDX.Toolkit.Graphics.Texture3D.New(device, width, height, depth, format,
databox));
TextureFormat = format;
if (texture.Description.MipLevels == 1 && generateMipMaps)
{
if (TextureLoader.GenerateMipMaps(device, texture, out var mipmapTexture))
{
resource = Collect(mipmapTexture);
RemoveAndDispose(ref texture);
}
else
{
resource = texture;
}
}
else
{
resource = texture;
}
if (createSRV)
{
textureView = Collect(new ShaderResourceView(device, resource));
}
}
/// <summary>
/// Creates the 1D texture view from color array.
/// </summary>
/// <param name="array">The array.</param>
public void CreateViewFromColorArray(Color4[] array)
{
CreateView(array, global::SharpDX.DXGI.Format.R32G32B32A32_Float);
}
/// <summary>
/// Creates the 2D texture view from color array.
/// </summary>
/// <param name="array">The array.</param>
/// <param name="width">The width.</param>
/// <param name="height">The height.</param>
/// <param name="createSRV"></param>
/// <param name="generateMipMaps"></param>
public void CreateViewFromColorArray(Color4[] array, int width, int height,
bool createSRV = true, bool generateMipMaps = true)
{
CreateView(array, width, height, global::SharpDX.DXGI.Format.R32G32B32A32_Float, createSRV, generateMipMaps);
}
#region Static Creator
/// <summary>
/// Creates ShaderResourceViewProxy from 2D texture array
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="device">The device.</param>
/// <param name="array">The array.</param>
/// <param name="format">The format.</param>
/// <param name="createSRV">if set to <c>true</c> [create SRV].</param>
/// <param name="generateMipMaps"></param>
/// <returns></returns>
public static ShaderResourceViewProxy CreateView<T>(Device device, T[] array,
global::SharpDX.DXGI.Format format, bool createSRV = true, bool generateMipMaps = true) where T : struct
{
var proxy = new ShaderResourceViewProxy(device);
proxy.CreateView(array, format, createSRV, generateMipMaps);
return proxy;
}
/// <summary>
/// Creates ShaderResourceViewProxy from common file formats such as Jpg, Bmp, DDS, Png, etc
/// </summary>
/// <param name="device">The device.</param>
/// <param name="texture">The texture.</param>
/// <param name="createSRV">if set to <c>true</c> [create SRV].</param>
/// <param name="generateMipMaps"></param>
/// <returns></returns>
public static ShaderResourceViewProxy CreateView(Device device, System.IO.Stream texture, bool createSRV = true, bool generateMipMaps = true)
{
var proxy = new ShaderResourceViewProxy(device);
proxy.CreateView(texture, createSRV, generateMipMaps);
return proxy;
}
/// <summary>
/// Creates the 2D texture view from data array
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="device">The device.</param>
/// <param name="array">The array.</param>
/// <param name="width">The width.</param>
/// <param name="height">The height.</param>
/// <param name="format">The format.</param>
/// <param name="createSRV">if set to <c>true</c> [create SRV].</param>
/// <param name="generateMipMaps"></param>
/// <returns></returns>
public static ShaderResourceViewProxy CreateView<T>(Device device, T[] array, int width, int height,
global::SharpDX.DXGI.Format format, bool createSRV = true, bool generateMipMaps = true) where T : struct
{
var proxy = new ShaderResourceViewProxy(device);
proxy.CreateView(array, width, height, format, createSRV, generateMipMaps);
return proxy;
}
/// <summary>
/// Creates the 2D texture view from raw pixel byte array
/// </summary>
/// <param name="device">The device.</param>
/// <param name="dataPtr">The data PTR.</param>
/// <param name="width">The width.</param>
/// <param name="height">The height.</param>
/// <param name="format">The format.</param>
/// <param name="createSRV">if set to <c>true</c> [create SRV].</param>
/// <param name="generateMipMaps"></param>
/// <returns></returns>
public unsafe static ShaderResourceViewProxy CreateView(Device device, IntPtr dataPtr, int width, int height,
global::SharpDX.DXGI.Format format, bool createSRV = true, bool generateMipMaps = true)
{
var proxy = new ShaderResourceViewProxy(device);
proxy.CreateView(dataPtr, width, height, format, createSRV, generateMipMaps);
return proxy;
}
/// <summary>
/// Creates the 1D texture view from color array.
/// </summary>
/// <param name="device"></param>
/// <param name="array">The array.</param>
public static ShaderResourceViewProxy CreateViewFromColorArray(Device device, Color4[] array)
{
var proxy = new ShaderResourceViewProxy(device);
proxy.CreateViewFromColorArray(array);
return proxy;
}
/// <summary>
/// Creates the 2D texture view from color array.
/// </summary>
/// <param name="device"></param>
/// <param name="array">The array.</param>
/// <param name="width">The width.</param>
/// <param name="height">The height.</param>
/// <param name="createSRV"></param>
/// <param name="generateMipMaps"></param>
public static ShaderResourceViewProxy CreateViewFromColorArray(Device device, Color4[] array,
int width, int height, bool createSRV = true, bool generateMipMaps = true)
{
var proxy = new ShaderResourceViewProxy(device);
proxy.CreateViewFromColorArray(array, width, height, createSRV, generateMipMaps);
return proxy;
}
/// <summary>
/// Creates the 3D texture view from raw pixel array
/// </summary>
/// <param name="device">The device.</param>
/// <param name="pixels">The pixels.</param>
/// <param name="width">The width.</param>
/// <param name="height">The height.</param>
/// <param name="depth">The depth.</param>
/// <param name="format">The format.</param>
/// <param name="createSRV">if set to <c>true</c> [create SRV].</param>
/// <param name="generateMipMaps"></param>
/// <returns></returns>
public static ShaderResourceViewProxy CreateViewFromPixelData(Device device, byte[] pixels,
int width, int height, int depth,
global::SharpDX.DXGI.Format format, bool createSRV = true, bool generateMipMaps = true)
{
var proxy = new ShaderResourceViewProxy(device);
proxy.CreateView(pixels, width, height, depth, format, createSRV, generateMipMaps);
return proxy;
}
/// <summary>
/// Creates the view from pixel data.
/// </summary>
/// <param name="device">The device.</param>
/// <param name="pixels">The pixels.</param>
/// <param name="width">The width.</param>
/// <param name="height">The height.</param>
/// <param name="depth">The depth.</param>
/// <param name="format">The format.</param>
/// <param name="createSRV">if set to <c>true</c> [create SRV].</param>
/// <param name="generateMipMaps">if set to <c>true</c> [generate mip maps].</param>
/// <returns></returns>
public static ShaderResourceViewProxy CreateViewFromPixelData(Device device, Half4[] pixels,
int width, int height, int depth,
global::SharpDX.DXGI.Format format, bool createSRV = true, bool generateMipMaps = true)
{
var proxy = new ShaderResourceViewProxy(device);
proxy.CreateView(pixels, width, height, depth, format, createSRV, generateMipMaps);
return proxy;
}
/// <summary>
/// Creates the view from pixel data.
/// </summary>
/// <param name="device">The device.</param>
/// <param name="pixels">The pixels.</param>
/// <param name="width">The width.</param>
/// <param name="height">The height.</param>
/// <param name="depth">The depth.</param>
/// <param name="format">The format.</param>
/// <param name="createSRV">if set to <c>true</c> [create SRV].</param>
/// <param name="generateMipMaps"></param>
/// <returns></returns>
public unsafe static ShaderResourceViewProxy CreateViewFromPixelData(Device device, IntPtr pixels,
int width, int height, int depth,
global::SharpDX.DXGI.Format format, bool createSRV = true, bool generateMipMaps = true)
{
var proxy = new ShaderResourceViewProxy(device);
proxy.CreateView(pixels, width, height, depth, format, createSRV, generateMipMaps);
return proxy;
}
#endregion
/// <summary>
/// Performs an implicit conversion from <see cref="ShaderResourceViewProxy"/> to <see cref="ShaderResourceView"/>.
/// </summary>
/// <param name="proxy">The proxy.</param>
/// <returns>
/// The result of the conversion.
/// </returns>
public static implicit operator ShaderResourceView(ShaderResourceViewProxy proxy)
{
return proxy?.textureView;
}
/// <summary>
/// Performs an implicit conversion from <see cref="ShaderResourceViewProxy"/> to <see cref="DepthStencilView"/>.
/// </summary>
/// <param name="proxy">The proxy.</param>
/// <returns>
/// The result of the conversion.
/// </returns>
public static implicit operator DepthStencilView(ShaderResourceViewProxy proxy)
{
return proxy?.depthStencilView;
}
/// <summary>
/// Performs an implicit conversion from <see cref="ShaderResourceViewProxy"/> to <see cref="RenderTargetView"/>.
/// </summary>
/// <param name="proxy">The proxy.</param>
/// <returns>
/// The result of the conversion.
/// </returns>
public static implicit operator RenderTargetView(ShaderResourceViewProxy proxy)
{
return proxy?.renderTargetView;
}
}
}
}
| |
#region Using Statements
using System;
using System.Collections.Generic;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
#endregion
namespace NetworkStateManagement
{
/// <summary>
/// Base class for screens that contain a menu of options. The user can
/// move up and down to select an entry, or cancel to back out of the screen.
/// </summary>
abstract class MenuScreen : GameScreen
{
#region Fields
protected List<MenuEntry> menuEntries = new List<MenuEntry>();
protected int selectedEntry = 0;
protected string menuTitle;
#endregion
#region Properties
/// <summary>
/// Gets the list of menu entries, so derived classes can add
/// or change the menu contents.
/// </summary>
protected IList<MenuEntry> MenuEntries
{
get { return menuEntries; }
}
#endregion
#region Initialization
/// <summary>
/// Constructor.
/// </summary>
public MenuScreen(string menuTitle)
{
this.menuTitle = menuTitle;
TransitionOnTime = TimeSpan.FromSeconds(0.5);
TransitionOffTime = TimeSpan.FromSeconds(0.5);
}
#endregion
#region Handle Input
/// <summary>
/// Responds to user input, changing the selected entry and accepting
/// or cancelling the menu.
/// </summary>
public override void HandleInput(InputState input)
{
// Move to the previous menu entry?
if (input.IsMenuUp(ControllingPlayer))
{
selectedEntry--;
if (selectedEntry < 0)
selectedEntry = menuEntries.Count - 1;
}
// Move to the next menu entry?
if (input.IsMenuDown(ControllingPlayer))
{
selectedEntry++;
if (selectedEntry >= menuEntries.Count)
selectedEntry = 0;
}
// Accept or cancel the menu? We pass in our ControllingPlayer, which may
// either be null (to accept input from any player) or a specific index.
// If we pass a null controlling player, the InputState helper returns to
// us which player actually provided the input. We pass that through to
// OnSelectEntry and OnCancel, so they can tell which player triggered them.
PlayerIndex playerIndex;
if (input.IsMenuSelect(ControllingPlayer, out playerIndex))
{
OnSelectEntry(selectedEntry, playerIndex);
}
else if (input.IsMenuCancel(ControllingPlayer, out playerIndex))
{
OnCancel(playerIndex);
}
}
/// <summary>
/// Handler for when the user has chosen a menu entry.
/// </summary>
protected virtual void OnSelectEntry(int entryIndex, PlayerIndex playerIndex)
{
menuEntries[entryIndex].OnSelectEntry(playerIndex);
}
/// <summary>
/// Handler for when the user has cancelled the menu.
/// </summary>
protected virtual void OnCancel(PlayerIndex playerIndex)
{
ExitScreen();
}
/// <summary>
/// Helper overload makes it easy to use OnCancel as a MenuEntry event handler.
/// </summary>
protected void OnCancel(object sender, PlayerIndexEventArgs e)
{
OnCancel(e.PlayerIndex);
}
#endregion
#region Update and Draw
/// <summary>
/// Allows the screen the chance to position the menu entries. By default
/// all menu entries are lined up in a vertical list, centered on the screen.
/// </summary>
protected virtual void UpdateMenuEntryLocations()
{
// Make the menu slide into place during transitions, using a
// power curve to make things look more interesting (this makes
// the movement slow down as it nears the end).
float transitionOffset = (float)Math.Pow(TransitionPosition, 2);
// start at Y = 175; each X value is generated per entry
Vector2 position = new Vector2(0f, 175f);
// update each menu entry's location in turn
for (int i = 0; i < menuEntries.Count; i++)
{
MenuEntry menuEntry = menuEntries[i];
// each entry is to be centered horizontally
position.X = ScreenManager.GraphicsDevice.Viewport.Width / 2 - menuEntry.GetWidth(this) / 2;
if (ScreenState == ScreenState.TransitionOn)
position.X -= transitionOffset * 256;
else
position.X += transitionOffset * 512;
// set the entry's position
menuEntry.Position = position;
// move down for the next entry the size of this entry
position.Y += menuEntry.GetHeight(this);
}
}
/// <summary>
/// Updates the menu.
/// </summary>
public override void Update(GameTime gameTime, bool otherScreenHasFocus,
bool coveredByOtherScreen)
{
base.Update(gameTime, otherScreenHasFocus, coveredByOtherScreen);
// Update each nested MenuEntry object.
for (int i = 0; i < menuEntries.Count; i++)
{
bool isSelected = IsActive && (i == selectedEntry);
menuEntries[i].Update(this, isSelected, gameTime);
}
}
/// <summary>
/// Draws the menu.
/// </summary>
public override void Draw(GameTime gameTime)
{
// make sure our entries are in the right place before we draw them
UpdateMenuEntryLocations();
GraphicsDevice graphics = ScreenManager.GraphicsDevice;
SpriteBatch spriteBatch = ScreenManager.SpriteBatch;
SpriteFont font = ScreenManager.Font;
spriteBatch.Begin();
// Draw each menu entry in turn.
for (int i = 0; i < menuEntries.Count; i++)
{
MenuEntry menuEntry = menuEntries[i];
bool isSelected = IsActive && (i == selectedEntry);
menuEntry.Draw(this, isSelected, gameTime);
}
// Make the menu slide into place during transitions, using a
// power curve to make things look more interesting (this makes
// the movement slow down as it nears the end).
float transitionOffset = (float)Math.Pow(TransitionPosition, 2);
// Draw the menu title centered on the screen
Vector2 titlePosition = new Vector2(graphics.Viewport.Width / 2, 80);
Vector2 titleOrigin = font.MeasureString(menuTitle) / 2;
Color titleColor = new Color(192, 192, 192) * TransitionAlpha;
float titleScale = 1.25f;
titlePosition.Y -= transitionOffset * 100;
spriteBatch.DrawString(font, menuTitle, titlePosition, titleColor, 0,
titleOrigin, titleScale, SpriteEffects.None, 0);
spriteBatch.End();
}
#endregion
}
}
| |
using System;
namespace OTFontFile
{
/// <summary>
/// Summary description for Table_GDEF.
/// </summary>
public class Table_GDEF : OTTable
{
/************************
* constructors
*/
public Table_GDEF(OTTag tag, MBOBuffer buf) : base(tag, buf)
{
}
/************************
* field offset values
*/
public enum FieldOffsets
{
Version = 0,
GlyphClassDefOffset = 4,
AttachListOffset = 6,
LigCaretListOffset = 8,
MarkAttachClassDefOffset = 10
}
/************************
* classes
*/
public class AttachListTable
{
public AttachListTable(ushort offset, MBOBuffer bufTable)
{
m_offsetAttachListTable = offset;
m_bufTable = bufTable;
}
public enum FieldOffsets
{
CoverageOffset = 0,
GlyphCount = 2,
AttachPointOffsets = 4
}
public uint CalcLength()
{
return (uint)FieldOffsets.AttachPointOffsets + (uint)GlyphCount*2;
}
public ushort CoverageOffset
{
get {return m_bufTable.GetUshort(m_offsetAttachListTable + (uint)FieldOffsets.CoverageOffset);}
}
public ushort GlyphCount
{
get {return m_bufTable.GetUshort(m_offsetAttachListTable + (uint)FieldOffsets.GlyphCount);}
}
public ushort GetAttachPointOffset(uint i)
{
return m_bufTable.GetUshort(m_offsetAttachListTable + (uint)FieldOffsets.AttachPointOffsets + i*2);
}
public OTL.CoverageTable GetCoverageTable()
{
ushort offset = (ushort)(m_offsetAttachListTable + CoverageOffset);
return new OTL.CoverageTable(offset, m_bufTable);
}
public AttachPointTable GetAttachPointTable(uint i)
{
ushort offset = GetAttachPointOffset(i);
return new AttachPointTable(offset, m_bufTable);
}
protected ushort m_offsetAttachListTable;
protected MBOBuffer m_bufTable;
}
public class AttachPointTable
{
public AttachPointTable(ushort offset, MBOBuffer bufTable)
{
m_offsetAttachPointTable = offset;
m_bufTable = bufTable;
}
public enum FieldOffsets
{
PointCount = 0,
PointIndexArray = 2
}
public ushort PointCount
{
get {return m_bufTable.GetUshort(m_offsetAttachPointTable + (uint)FieldOffsets.PointCount);}
}
public ushort GetPointIndex(uint i)
{
return m_bufTable.GetUshort(m_offsetAttachPointTable + (uint)FieldOffsets.PointIndexArray + i*2);
}
protected ushort m_offsetAttachPointTable;
protected MBOBuffer m_bufTable;
}
public class LigCaretListTable
{
public LigCaretListTable(ushort offset, MBOBuffer bufTable)
{
m_offsetLigCaretListTable = offset;
m_bufTable = bufTable;
}
public enum FieldOffsets
{
CoverageOffset = 0,
LigGlyphCount = 2,
LigGlyphOffsets = 4
}
public uint CalcLength()
{
return (uint)FieldOffsets.LigGlyphOffsets + (uint)LigGlyphCount*2;
}
public ushort CoverageOffset
{
get {return m_bufTable.GetUshort(m_offsetLigCaretListTable + (uint)FieldOffsets.CoverageOffset);}
}
public ushort LigGlyphCount
{
get {return m_bufTable.GetUshort(m_offsetLigCaretListTable + (uint)FieldOffsets.LigGlyphCount);}
}
public ushort GetLigGlyphOffset(uint i)
{
return m_bufTable.GetUshort(m_offsetLigCaretListTable + (uint)FieldOffsets.LigGlyphOffsets + i*2);
}
public OTL.CoverageTable GetCoverageTable()
{
ushort offset = (ushort)(m_offsetLigCaretListTable + CoverageOffset);
return new OTL.CoverageTable(offset, m_bufTable);
}
public LigGlyphTable GetLigGlyphTable(uint i)
{
ushort offset = GetLigGlyphOffset(i);
return new LigGlyphTable((ushort)(m_offsetLigCaretListTable + offset), m_bufTable);
}
protected ushort m_offsetLigCaretListTable;
protected MBOBuffer m_bufTable;
}
public class LigGlyphTable
{
public LigGlyphTable(ushort offset, MBOBuffer bufTable)
{
m_offsetLigGlyphTable = offset;
m_bufTable = bufTable;
}
public enum FieldOffsets
{
CaretCount = 0,
CaretValueOffsets = 2
}
public uint CalcLength()
{
return (uint)FieldOffsets.CaretValueOffsets + (uint)CaretCount*2;
}
public ushort CaretCount
{
get {return m_bufTable.GetUshort(m_offsetLigGlyphTable + (uint)FieldOffsets.CaretCount);}
}
public ushort GetCaretValueOffset(uint i)
{
return m_bufTable.GetUshort(m_offsetLigGlyphTable + (uint)FieldOffsets.CaretValueOffsets + i*2);
}
public CaretValueTable GetCaretValueTable(uint i)
{
ushort offset = (ushort)(m_offsetLigGlyphTable + GetCaretValueOffset(i));
return new CaretValueTable(offset, m_bufTable);
}
protected ushort m_offsetLigGlyphTable;
protected MBOBuffer m_bufTable;
}
public class CaretValueTable
{
public CaretValueTable(ushort offset, MBOBuffer bufTable)
{
m_offsetCaretValueTable = offset;
m_bufTable = bufTable;
}
public enum FieldOffsets
{
CaretValueFormat = 0
}
public enum FieldOffsets1
{
Coordinate = 2
}
public enum FieldOffsets2
{
CaretValuePoint = 2
}
public enum FieldOffsets3
{
Coordinate = 2,
DeviceTableOffset = 3
}
public ushort CaretValueFormat
{
get {return m_bufTable.GetUshort(m_offsetCaretValueTable + (uint)FieldOffsets.CaretValueFormat);}
}
// format 1 only!
public ushort F1Coordinate
{
get
{
if (CaretValueFormat != 1)
{
throw new System.InvalidOperationException();
}
return m_bufTable.GetUshort(m_offsetCaretValueTable + (uint)FieldOffsets1.Coordinate);
}
}
// format 2 only!
public ushort F2CaretValuePoint
{
get
{
if (CaretValueFormat != 2)
{
throw new System.InvalidOperationException();
}
return m_bufTable.GetUshort(m_offsetCaretValueTable + (uint)FieldOffsets2.CaretValuePoint);
}
}
// format 3 only!
public ushort F3Coordinate
{
get
{
if (CaretValueFormat != 3)
{
throw new System.InvalidOperationException();
}
return m_bufTable.GetUshort(m_offsetCaretValueTable + (uint)FieldOffsets3.Coordinate);
}
}
public ushort F3DeviceTableOffset
{
get
{
if (CaretValueFormat != 3)
{
throw new System.InvalidOperationException();
}
return m_bufTable.GetUshort(m_offsetCaretValueTable + (uint)FieldOffsets3.DeviceTableOffset);
}
}
public OTL.DeviceTable F3GetDeviceTable()
{
if (CaretValueFormat != 3)
{
throw new System.InvalidOperationException();
}
ushort offset = (ushort)(m_offsetCaretValueTable + F3DeviceTableOffset);
return new OTL.DeviceTable(offset, m_bufTable);
}
protected ushort m_offsetCaretValueTable;
protected MBOBuffer m_bufTable;
}
/************************
* accessors
*/
public OTFixed Version
{
get {return m_bufTable.GetFixed((uint)FieldOffsets.Version);}
}
public ushort GlyphClassDefOffset
{
get {return m_bufTable.GetUshort((uint)FieldOffsets.GlyphClassDefOffset);}
}
public ushort AttachListOffset
{
get {return m_bufTable.GetUshort((uint)FieldOffsets.AttachListOffset);}
}
public ushort LigCaretListOffset
{
get {return m_bufTable.GetUshort((uint)FieldOffsets.LigCaretListOffset);}
}
public ushort MarkAttachClassDefOffset
{
get {return m_bufTable.GetUshort((uint)FieldOffsets.MarkAttachClassDefOffset);}
}
public OTL.ClassDefTable GetGlyphClassDefTable()
{
OTL.ClassDefTable cdt = null;
if (GlyphClassDefOffset != 0)
{
cdt = new OTL.ClassDefTable(GlyphClassDefOffset, m_bufTable);
}
return cdt;
}
public AttachListTable GetAttachListTable()
{
AttachListTable alt = null;
if (AttachListOffset != 0)
{
alt = new AttachListTable(AttachListOffset, m_bufTable);
}
return alt;
}
public LigCaretListTable GetLigCaretListTable()
{
LigCaretListTable lclt = null;
if (LigCaretListOffset != 0)
{
lclt = new LigCaretListTable(LigCaretListOffset, m_bufTable);
}
return lclt;
}
public OTL.ClassDefTable GetMarkAttachClassDefTable()
{
OTL.ClassDefTable cdt = null;
if (MarkAttachClassDefOffset != 0)
{
cdt = new OTL.ClassDefTable(MarkAttachClassDefOffset, m_bufTable);
}
return cdt;
}
/************************
* DataCache class
*/
public override DataCache GetCache()
{
if (m_cache == null)
{
m_cache = new GDEF_cache();
}
return m_cache;
}
public class GDEF_cache : DataCache
{
public override OTTable GenerateTable()
{
// not yet implemented!
return null;
}
}
}
}
| |
namespace AngleSharp.Css.Values
{
using AngleSharp.Css;
using AngleSharp.Text;
using System;
using System.Globalization;
using System.Runtime.InteropServices;
/// <summary>
/// Represents a color value.
/// </summary>
[StructLayout(LayoutKind.Explicit, Pack = 1, CharSet = CharSet.Unicode)]
public struct Color : IEquatable<Color>, IComparable<Color>, ICssPrimitiveValue
{
#region Basic colors
/// <summary>
/// The color #000000.
/// </summary>
public static readonly Color Black = new Color(0, 0, 0);
/// <summary>
/// The color #FFFFFF.
/// </summary>
public static readonly Color White = new Color(255, 255, 255);
/// <summary>
/// The color #FF0000.
/// </summary>
public static readonly Color Red = new Color(255, 0, 0);
/// <summary>
/// The color #FF00FF.
/// </summary>
public static readonly Color Magenta = new Color(255, 0, 255);
/// <summary>
/// The color #008000.
/// </summary>
public static readonly Color Green = new Color(0, 128, 0);
/// <summary>
/// The color #00FF00.
/// </summary>
public static readonly Color PureGreen = new Color(0, 255, 0);
/// <summary>
/// The color #0000FF.
/// </summary>
public static readonly Color Blue = new Color(0, 0, 255);
/// <summary>
/// The color #00000000.
/// </summary>
public static readonly Color Transparent = new Color(0, 0, 0, 0);
/// <summary>
/// The color #00010203.
/// </summary>
public static readonly Color CurrentColor = new Color(0, 1, 2, 3);
/// <summary>
/// The color #30201000.
/// </summary>
public static readonly Color InvertedColor = new Color(48, 32, 16, 0);
#endregion
#region Fields
[FieldOffset(0)]
private readonly Byte _alpha;
[FieldOffset(1)]
private readonly Byte _red;
[FieldOffset(2)]
private readonly Byte _green;
[FieldOffset(3)]
private readonly Byte _blue;
[FieldOffset(0)]
private readonly Int32 _hashcode;
#endregion
#region ctor
/// <summary>
/// Creates a CSS color type without any transparency (alpha = 100%).
/// </summary>
/// <param name="r">The red value.</param>
/// <param name="g">The green value.</param>
/// <param name="b">The blue value.</param>
public Color(Byte r, Byte g, Byte b)
{
_hashcode = 0;
_alpha = 255;
_red = r;
_blue = b;
_green = g;
}
/// <summary>
/// Creates a CSS color type.
/// </summary>
/// <param name="r">The red value.</param>
/// <param name="g">The green value.</param>
/// <param name="b">The blue value.</param>
/// <param name="a">The alpha value.</param>
public Color(Byte r, Byte g, Byte b, Byte a)
{
_hashcode = 0;
_alpha = a;
_red = r;
_blue = b;
_green = g;
}
#endregion
#region Static constructors
/// <summary>
/// Returns the color from the given primitives.
/// </summary>
/// <param name="r">The value for red [0,255].</param>
/// <param name="g">The value for green [0,255].</param>
/// <param name="b">The value for blue [0,255].</param>
/// <param name="a">The value for alpha [0,1].</param>
/// <returns>The CSS color value.</returns>
public static Color FromRgba(Byte r, Byte g, Byte b, Double a) =>
new Color(r, g, b, Normalize(a));
/// <summary>
/// Returns the color from the given primitives.
/// </summary>
/// <param name="r">The value for red [0,1].</param>
/// <param name="g">The value for green [0,1].</param>
/// <param name="b">The value for blue [0,1].</param>
/// <param name="a">The value for alpha [0,1].</param>
/// <returns>The CSS color value.</returns>
public static Color FromRgba(Double r, Double g, Double b, Double a) =>
new Color(Normalize(r), Normalize(g), Normalize(b), Normalize(a));
/// <summary>
/// Returns the gray color from the given value.
/// </summary>
/// <param name="number">The value for each component [0,255].</param>
/// <param name="alpha">The value for alpha [0,1].</param>
/// <returns>The CSS color value.</returns>
public static Color FromGray(Byte number, Double alpha = 1.0) =>
new Color(number, number, number, Normalize(alpha));
/// <summary>
/// Returns the gray color from the given value.
/// </summary>
/// <param name="value">The value for each component [0,1].</param>
/// <param name="alpha">The value for alpha [0,1].</param>
/// <returns>The CSS color value.</returns>
public static Color FromGray(Double value, Double alpha = 1.0) =>
FromGray(Normalize(value), alpha);
/// <summary>
/// Returns the color with the given name.
/// </summary>
/// <param name="name">The name of the color.</param>
/// <returns>The CSS color value.</returns>
public static Color? FromName(String name) => CssColors.GetColor(name);
/// <summary>
/// Returns the color from the given primitives without any alpha.
/// </summary>
/// <param name="r">The value for red [0,255].</param>
/// <param name="g">The value for green [0,255].</param>
/// <param name="b">The value for blue [0,255].</param>
/// <returns>The CSS color value.</returns>
public static Color FromRgb(Byte r, Byte g, Byte b) => new Color(r, g, b);
/// <summary>
/// Returns the color from the given hex string.
/// </summary>
/// <param name="color">The hex string like fff or abc123 or AA126B etc.</param>
/// <returns>The CSS color value.</returns>
public static Color FromHex(String color)
{
int r = 0, g = 0, b = 0, a = 255;
switch (color.Length)
{
case 4:
a = 17 * color[3].FromHex();
goto case 3;
case 3:
r = 17 * color[0].FromHex();
g = 17 * color[1].FromHex();
b = 17 * color[2].FromHex();
break;
case 8:
a = 16 * color[6].FromHex() + color[7].FromHex();
goto case 6;
case 6:
r = 16 * color[0].FromHex() + color[1].FromHex();
g = 16 * color[2].FromHex() + color[3].FromHex();
b = 16 * color[4].FromHex() + color[5].FromHex();
break;
}
return new Color((Byte)r, (Byte)g, (Byte)b, (Byte)a);
}
/// <summary>
/// Returns the color from the given hex string if it can be converted, otherwise
/// the color is not set.
/// </summary>
/// <param name="color">The hexadecimal representation of the color.</param>
/// <param name="value">The color value to be created.</param>
/// <returns>The status if the string can be converted.</returns>
public static Boolean TryFromHex(String color, out Color value)
{
if (color.Length == 6 || color.Length == 3 || color.Length == 8 || color.Length == 4)
{
for (var i = 0; i < color.Length; i++)
{
if (!color[i].IsHex())
goto fail;
}
value = FromHex(color);
return true;
}
fail:
value = new Color();
return false;
}
/// <summary>
/// Returns the color of non-CSS colors in a special IE notation known
/// as "flex hex". Computes the part without the hash and possible color
/// names. More information can be found at:
/// http://scrappy-do.blogspot.de/2004/08/little-rant-about-microsoft-internet.html
/// </summary>
/// <param name="color">The color string to evaluate.</param>
/// <returns>The color for the color string.</returns>
public static Color FromFlexHex(String color)
{
var length = Math.Max(color.Length, 3);
var remaining = length % 3;
if (remaining != 0)
{
length += 3 - remaining;
}
var n = length / 3;
var d = Math.Min(2, n);
var s = Math.Max(n - 8, 0);
var chars = new Char[length];
for (var i = 0; i < color.Length; i++)
{
chars[i] = color[i].IsHex() ? color[i] : '0';
}
for (var i = color.Length; i < length; i++)
{
chars[i] = '0';
}
if (d == 1)
{
var r = chars[0 * n + s].FromHex();
var g = chars[1 * n + s].FromHex();
var b = chars[2 * n + s].FromHex();
return new Color((Byte)r, (Byte)g, (Byte)b);
}
else
{
var r = 16 * chars[0 * n + s].FromHex() + chars[0 * n + s + 1].FromHex();
var g = 16 * chars[1 * n + s].FromHex() + chars[1 * n + s + 1].FromHex();
var b = 16 * chars[2 * n + s].FromHex() + chars[2 * n + s + 1].FromHex();
return new Color((Byte)r, (Byte)g, (Byte)b);
}
}
/// <summary>
/// Returns the color that represents the given HSL values.
/// </summary>
/// <param name="h">The color angle [0,1].</param>
/// <param name="s">The saturation [0,1].</param>
/// <param name="l">The light value [0,1].</param>
/// <returns>The CSS color.</returns>
public static Color FromHsl(Double h, Double s, Double l) => FromHsla(h, s, l, 1.0);
/// <summary>
/// Returns the color that represents the given HSL values.
/// </summary>
/// <param name="h">The color angle [0,1].</param>
/// <param name="s">The saturation [0,1].</param>
/// <param name="l">The light value [0,1].</param>
/// <param name="alpha">The alpha value [0,1].</param>
/// <returns>The CSS color.</returns>
public static Color FromHsla(Double h, Double s, Double l, Double alpha)
{
const Double third = 1.0 / 3.0;
var m2 = l < 0.5 ? (l * (s + 1.0)) : (l + s - l * s);
var m1 = 2.0 * l - m2;
var r = Normalize(HueToRgb(m1, m2, h + third));
var g = Normalize(HueToRgb(m1, m2, h));
var b = Normalize(HueToRgb(m1, m2, h - third));
return new Color(r, g, b, Normalize(alpha));
}
/// <summary>
/// Returns the color that represents Hue-Whiteness-Blackness.
/// </summary>
/// <param name="h">The color angle [0,1].</param>
/// <param name="w">The whiteness [0,1].</param>
/// <param name="b">The blackness [0,1].</param>
/// <returns>The CSS color.</returns>
public static Color FromHwb(Double h, Double w, Double b)
{
return FromHwba(h, w, b, 1f);
}
/// <summary>
/// Returns the color that represents Hue-Whiteness-Blackness.
/// </summary>
/// <param name="h">The color angle [0,1].</param>
/// <param name="w">The whiteness [0,1].</param>
/// <param name="b">The blackness [0,1].</param>
/// <param name="alpha">The alpha value [0,1].</param>
/// <returns>The CSS color.</returns>
public static Color FromHwba(Double h, Double w, Double b, Double alpha)
{
var ratio = 1.0 / (w + b);
var red = 0.0;
var green = 0.0;
var blue = 0.0;
if (ratio < 1.0)
{
w *= ratio;
b *= ratio;
}
var p = (Int32)(6.0 * h);
var f = 6.0 * h - p;
if ((p & 0x01) != 0)
{
f = 1.0 - f;
}
var v = 1.0 - b;
var n = w + f * (v - w);
switch (p)
{
default:
case 6:
case 0: red = v; green = n; blue = w; break;
case 1: red = n; green = v; blue = w; break;
case 2: red = w; green = v; blue = n; break;
case 3: red = w; green = n; blue = v; break;
case 4: red = n; green = w; blue = v; break;
case 5: red = v; green = w; blue = n; break;
}
return FromRgba(red, green, blue, alpha);
}
#endregion
#region Properties
/// <summary>
/// Gets or sets if hex codes should be used for serialization.
/// This will not be applied in case of transparent colors, i.e.,
/// when alpha is not 1.
/// </summary>
public static Boolean UseHex { get; set; }
/// <summary>
/// Gets the CSS text representation.
/// </summary>
public String CssText
{
get
{
if (Equals(Color.CurrentColor))
{
return CssKeywords.CurrentColor;
}
else if (Equals(Color.InvertedColor))
{
return CssKeywords.Invert;
}
else if (_alpha == 255 && UseHex)
{
return $"#{_red.ToString("X2", CultureInfo.InvariantCulture)}{_green.ToString("X2", CultureInfo.InvariantCulture)}{_blue.ToString("X2", CultureInfo.InvariantCulture)}";
}
else
{
var fn = FunctionNames.Rgba;
var args = String.Join(", ", new[]
{
R.ToString(CultureInfo.InvariantCulture),
G.ToString(CultureInfo.InvariantCulture),
B.ToString(CultureInfo.InvariantCulture),
Alpha.ToString(CultureInfo.InvariantCulture),
});
return fn.CssFunction(args);
}
}
}
/// <summary>
/// Gets the Int32 value of the color.
/// </summary>
public Int32 Value => _hashcode;
/// <summary>
/// Gets the alpha part of the color.
/// </summary>
public Byte A => _alpha;
/// <summary>
/// Gets the alpha part of the color in percent (0..1).
/// </summary>
public Double Alpha => Math.Round(_alpha / 255.0, 2);
/// <summary>
/// Gets the red part of the color.
/// </summary>
public Byte R => _red;
/// <summary>
/// Gets the green part of the color.
/// </summary>
public Byte G => _green;
/// <summary>
/// Gets the blue part of the color.
/// </summary>
public Byte B => _blue;
#endregion
#region Equality
/// <summary>
/// Compares two colors and returns a boolean indicating if the two do match.
/// </summary>
/// <param name="a">The first color to use.</param>
/// <param name="b">The second color to use.</param>
/// <returns>True if both colors are equal, otherwise false.</returns>
public static Boolean operator ==(Color a, Color b) => a._hashcode == b._hashcode;
/// <summary>
/// Compares two colors and returns a boolean indicating if the two do not match.
/// </summary>
/// <param name="a">The first color to use.</param>
/// <param name="b">The second color to use.</param>
/// <returns>True if both colors are not equal, otherwise false.</returns>
public static Boolean operator !=(Color a, Color b) => a._hashcode != b._hashcode;
/// <summary>
/// Checks two colors for equality.
/// </summary>
/// <param name="other">The other color.</param>
/// <returns>True if both colors or equal, otherwise false.</returns>
public Boolean Equals(Color other) => _hashcode == other._hashcode;
/// <summary>
/// Tests if another object is equal to this object.
/// </summary>
/// <param name="obj">The object to test with.</param>
/// <returns>True if the two objects are equal, otherwise false.</returns>
public override Boolean Equals(Object obj)
{
var other = obj as Color?;
if (other != null)
{
return Equals(other.Value);
}
return false;
}
Int32 IComparable<Color>.CompareTo(Color other) => _hashcode - other._hashcode;
/// <summary>
/// Returns a hash code that defines the current color.
/// </summary>
/// <returns>The integer value of the hashcode.</returns>
public override Int32 GetHashCode() => _hashcode;
#endregion
#region Methods
/// <summary>
/// Mixes two colors using alpha compositing as described here:
/// http://en.wikipedia.org/wiki/Alpha_compositing
/// </summary>
/// <param name="above">The first color (above) with transparency.</param>
/// <param name="below">The second color (below the first one) without transparency.</param>
/// <returns>The outcome in the crossing section.</returns>
public static Color Mix(Color above, Color below) => Mix(above.Alpha, above, below);
/// <summary>
/// Mixes two colors using alpha compositing as described here:
/// http://en.wikipedia.org/wiki/Alpha_compositing
/// </summary>
/// <param name="alpha">The mixing parameter.</param>
/// <param name="above">The first color (above) (no transparency).</param>
/// <param name="below">The second color (below the first one) (no transparency).</param>
/// <returns>The outcome in the crossing section.</returns>
public static Color Mix(Double alpha, Color above, Color below)
{
var gamma = 1.0 - alpha;
var r = gamma * below.R + alpha * above.R;
var g = gamma * below.G + alpha * above.G;
var b = gamma * below.B + alpha * above.B;
return new Color((Byte)r, (Byte)g, (Byte)b);
}
#endregion
#region Helpers
private static Byte Normalize(Double value) =>
(Byte)Math.Max(Math.Min(Math.Truncate(256.0 * value), 255.0), 0.0);
private static Double HueToRgb(Double m1, Double m2, Double h)
{
if (h < 0.0)
{
h += 1.0;
}
else if (h > 1.0)
{
h -= 1.0;
}
if (6.0 * h < 1.0)
{
return m1 + (m2 - m1) * h * 6.0;
}
else if (2.0 * h < 1.0)
{
return m2;
}
else if (3.0 * h < 2.0)
{
return m1 + (m2 - m1) * (4.0 - 6.0 * h);
}
return m1;
}
#endregion
}
}
| |
#region License
// Copyright (c) K2 Workflow (SourceCode Technology Holdings Inc.). All rights reserved.
// Licensed under the MIT License. See LICENSE file in the project root for full license information.
#endregion
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
namespace SourceCode.Chasm
{
[DebuggerDisplay("{ToString(),nq,ac}")]
#pragma warning disable CA1710 // Identifiers should have correct suffix
public struct TreeNodeMap : IReadOnlyDictionary<string, TreeNode>, IReadOnlyList<TreeNode>, IEquatable<TreeNodeMap>
#pragma warning restore CA1710 // Identifiers should have correct suffix
{
#region Constants
/// <summary>
/// A singleton representing an empty <see cref="TreeNodeMap"/> value.
/// </summary>
/// <value>
/// The empty.
/// </value>
public static TreeNodeMap Empty { get; }
#endregion
#region Fields
internal readonly ReadOnlyMemory<TreeNode> _nodes;
#endregion
#region Properties
public int Count => _nodes.Length;
public TreeNode this[int index]
{
get
{
if (_nodes.IsEmpty)
return Array.Empty<TreeNode>()[index]; // Throw underlying exception
var span = _nodes.Span;
return span[index];
}
}
public TreeNode this[string key]
{
get
{
if (!TryGetValue(key, out var node))
throw new KeyNotFoundException(nameof(key));
return node;
}
}
#endregion
#region Constructors
public TreeNodeMap(params TreeNode[] nodes)
{
// We choose to coerce empty & null, so de/serialization round-trips with fidelity
if (nodes == null || nodes.Length == 0)
{
_nodes = default; // ie, same as default struct ctor
return;
}
// Sort & de-duplicate
_nodes = DistinctSort(nodes, false);
}
public TreeNodeMap(IEnumerable<TreeNode> nodes)
{
// We choose to coerce empty & null, so de/serialization round-trips with fidelity
if (nodes == null)
{
_nodes = default; // ie, same as default struct ctor
return;
}
// Sort & de-duplicate
_nodes = DistinctSort(nodes);
}
public TreeNodeMap(ICollection<TreeNode> nodes)
{
// We choose to coerce empty & null, so de/serialization round-trips with fidelity
if (nodes == null || nodes.Count == 0)
{
_nodes = default; // ie, same as default struct ctor
return;
}
// Copy
var array = new TreeNode[nodes.Count];
nodes.CopyTo(array, 0);
// Sort & de-duplicate
_nodes = DistinctSort(array, true);
}
private TreeNodeMap(ReadOnlyMemory<TreeNode> nodes)
{
_nodes = nodes;
}
#endregion
#region Methods
private static ReadOnlyMemory<TreeNode> Merge(TreeNodeMap first, TreeNodeMap second)
{
var newArray = new TreeNode[first.Count + second.Count];
var i = 0;
var aIndex = 0;
var bIndex = 0;
for (; aIndex < first.Count || bIndex < second.Count; i++)
{
if (aIndex >= first.Count)
{
newArray[i] = second[bIndex++];
}
else if (bIndex >= second.Count)
{
newArray[i] = first[aIndex++];
}
else
{
var a = first[aIndex];
var b = second[bIndex];
var cmp = StringComparer.Ordinal.Compare(a.Name, b.Name);
if (cmp == 0)
{
newArray[i] = b;
++bIndex;
++aIndex;
}
else if (cmp < 0)
{
newArray[i] = a;
++aIndex;
}
else
{
newArray[i] = b;
++bIndex;
}
}
}
return new ReadOnlyMemory<TreeNode>(newArray, 0, i);
}
public TreeNodeMap Merge(TreeNode node)
{
if (_nodes.IsEmpty) return new TreeNodeMap(node);
var index = IndexOf(node.Name);
var span = _nodes.Span;
TreeNode[] array;
if (index >= 0)
{
array = new TreeNode[_nodes.Length];
span.CopyTo(array);
array[index] = node;
}
else
{
index = ~index;
array = new TreeNode[_nodes.Length + 1];
var j = 0;
for (var i = 0; i < array.Length; i++)
array[i] = i == index ? node : span[j++];
}
return new TreeNodeMap(array);
}
public TreeNodeMap Delete(Func<string, bool> predicate)
{
if (predicate == null) throw new ArgumentNullException(nameof(predicate));
if (_nodes.Length == 0) return this;
var copy = new TreeNode[_nodes.Length - 1];
var span = _nodes.Span;
var j = 0;
for (var i = 0; i < _nodes.Length; i++)
{
if (!predicate(span[i].Name))
copy[j++] = span[i];
}
if (j == _nodes.Length)
return this;
return new TreeNodeMap(new ReadOnlyMemory<TreeNode>(copy, 0, j));
}
public TreeNodeMap Delete(string key)
{
if (_nodes.Length == 0) return this;
var copy = new TreeNode[_nodes.Length - 1];
var span = _nodes.Span;
var found = false;
for (var i = 0; i < _nodes.Length; i++)
{
if (found)
{
copy[i - 1] = span[i];
}
else
{
if (i < _nodes.Length - 1)
copy[i] = span[i];
found = StringComparer.Ordinal.Equals(span[i].Name, key);
}
}
if (found)
return new TreeNodeMap(new ReadOnlyMemory<TreeNode>(copy));
return this;
}
public TreeNodeMap Merge(TreeNodeMap nodes)
{
if (nodes == default || nodes.Count == 0)
return this;
if (_nodes.IsEmpty || _nodes.Length == 0)
return nodes;
var set = Merge(this, nodes);
var tree = new TreeNodeMap(set);
return tree;
}
public TreeNodeMap Merge(ICollection<TreeNode> nodes)
{
if (nodes == null || nodes.Count == 0)
return this;
if (_nodes.IsEmpty)
return new TreeNodeMap(nodes);
var set = Merge(this, new TreeNodeMap(nodes));
var tree = new TreeNodeMap(set);
return tree;
}
public int IndexOf(string key)
{
if (_nodes.IsEmpty || key == null) return -1;
var l = 0;
var r = _nodes.Length - 1;
var i = r / 2;
var ks = key;
var span = _nodes.Span;
while (r >= l)
{
var cmp = StringComparer.Ordinal.Compare(span[i].Name, ks);
if (cmp == 0) return i;
else if (cmp > 0) r = i - 1;
else l = i + 1;
i = l + (r - l) / 2;
}
return ~i;
}
public bool ContainsKey(string key) => IndexOf(key) >= 0;
public bool TryGetValue(string key, out TreeNode value)
{
value = default;
if (_nodes.IsEmpty || key == null)
return false;
var l = 0;
var r = _nodes.Length - 1;
var i = r / 2;
var ks = key;
var span = _nodes.Span;
while (r >= l)
{
value = span[i];
var cmp = StringComparer.Ordinal.Compare(value.Name, ks);
if (cmp == 0) return true;
if (cmp > 0) r = i - 1;
else l = i + 1;
i = l + (r - l) / 2;
}
value = default;
return false;
}
public bool TryGetValue(string key, NodeKind kind, out TreeNode value)
{
value = default;
if (!TryGetValue(key, out var node))
return false;
if (node.Kind != kind)
return false;
value = node;
return true;
}
#endregion
#region Helpers
private static ReadOnlyMemory<TreeNode> DistinctSort(TreeNode[] array, bool alreadyCopied)
{
Debug.Assert(array != null); // Already checked at callsites
// Optimize for common cases 0, 1, 2, N
ReadOnlyMemory<TreeNode> result;
switch (array.Length)
{
case 0:
return default;
case 1:
// Always copy. The callsite may change the array after creating the TreeNodeMap.
result = new TreeNode[1] { array[0] };
return result;
case 2:
// If the Name (alone) is duplicated
if (StringComparer.Ordinal.Equals(array[0].Name, array[1].Name))
{
// If it's a complete duplicate, silently skip
if (TreeNodeComparer.Default.Equals(array[0], array[1]))
result = new TreeNode[1] { array[0] };
else
throw CreateDuplicateException(array[0]);
}
// In the wrong order
else if (TreeNodeComparer.Default.Compare(array[0], array[1]) > 0)
{
result = new TreeNode[2] { array[1], array[0] };
}
else if (alreadyCopied)
{
result = array;
}
else
{
result = new TreeNode[2] { array[0], array[1] };
}
return result;
default:
// If callsite did not already copy, do so before mutating
var nodes = array;
if (!alreadyCopied)
{
nodes = new TreeNode[array.Length];
array.CopyTo(nodes, 0);
}
// Sort: Delegate dispatch faster than interface (https://github.com/dotnet/coreclr/pull/8504)
Array.Sort(nodes, TreeNodeComparer.Default.Compare);
// Distinct
var j = 1;
for (var i = 1; i < nodes.Length; i++)
{
// If the Name (alone) is duplicated
if (StringComparer.Ordinal.Equals(nodes[i - 1].Name, nodes[i].Name))
{
// If it's a complete duplicate, silently skip
if (TreeNodeComparer.Default.Equals(nodes[i - 1], nodes[i]))
continue;
throw CreateDuplicateException(nodes[0]);
}
nodes[j++] = nodes[i]; // Increment target index if distinct
}
var span = new ReadOnlyMemory<TreeNode>(nodes, 0, j);
return span;
}
ArgumentException CreateDuplicateException(TreeNode node)
=> new ArgumentException($"Duplicate {nameof(TreeNode)} arguments passed to {nameof(TreeNodeMap)}: ({node})");
}
private static ReadOnlyMemory<TreeNode> DistinctSort(IEnumerable<TreeNode> nodes)
{
Debug.Assert(nodes != null); // Already checked at callsites
if (!System.Linq.Enumerable.Any(nodes)) return default;
// If callsite did not already copy, do so before mutating
var array = new List<TreeNode>(nodes).ToArray();
return DistinctSort(array, true);
}
#endregion
#region IEnumerable
public IEnumerable<string> Keys
{
get
{
if (_nodes.IsEmpty)
yield break;
// TODO: Is Span safe under yield?
var span = _nodes.Span;
for (var i = 0; i < _nodes.Length; i++)
yield return span[i].Name;
}
}
public IEnumerable<TreeNode> Values
{
get
{
if (_nodes.IsEmpty)
yield break;
// TODO: Is Span safe under yield?
var span = _nodes.Span;
for (var i = 0; i < _nodes.Length; i++)
yield return span[i];
}
}
public IEnumerator<TreeNode> GetEnumerator() => Values.GetEnumerator();
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
IEnumerator<KeyValuePair<string, TreeNode>> IEnumerable<KeyValuePair<string, TreeNode>>.GetEnumerator()
{
if (_nodes.IsEmpty)
yield break;
// TODO: Is Span safe under yield?
var span = _nodes.Span;
for (var i = 0; i < _nodes.Length; i++)
yield return new KeyValuePair<string, TreeNode>(span[i].Name, span[i]);
}
#endregion
#region IEquatable
public bool Equals(TreeNodeMap other) => TreeNodeMapComparer.Default.Equals(this, other);
public override bool Equals(object obj)
=> obj is TreeNodeMap tree
&& TreeNodeMapComparer.Default.Equals(this, tree);
public override int GetHashCode() => TreeNodeMapComparer.Default.GetHashCode(this);
#endregion
#region Operators
public static bool operator ==(TreeNodeMap x, TreeNodeMap y) => TreeNodeMapComparer.Default.Equals(x, y);
public static bool operator !=(TreeNodeMap x, TreeNodeMap y) => !(x == y);
public override string ToString() => $"{nameof(Count)}: {_nodes.Length}";
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Runtime.Tests.Common;
using Xunit;
public static class Int32Tests
{
[Fact]
public static void TestCtorEmpty()
{
int i = new int();
Assert.Equal(0, i);
}
[Fact]
public static void TestCtorValue()
{
int i = 41;
Assert.Equal(41, i);
}
[Fact]
public static void TestMaxValue()
{
Assert.Equal(0x7FFFFFFF, int.MaxValue);
}
[Fact]
public static void TestMinValue()
{
Assert.Equal(unchecked((int)0x80000000), int.MinValue);
}
[Theory]
[InlineData(234, 0)]
[InlineData(int.MinValue, 1)]
[InlineData(-123, 1)]
[InlineData(0, 1)]
[InlineData(45, 1)]
[InlineData(123, 1)]
[InlineData(456, -1)]
[InlineData(int.MaxValue, -1)]
public static void TestCompareTo(int value, int expected)
{
int i = 234;
int result = CompareHelper.NormalizeCompare(i.CompareTo(value));
Assert.Equal(expected, result);
}
[Theory]
[InlineData(null, 1)]
[InlineData(234, 0)]
[InlineData(int.MinValue, 1)]
[InlineData(-123, 1)]
[InlineData(0, 1)]
[InlineData(45, 1)]
[InlineData(123, 1)]
[InlineData(456, -1)]
[InlineData(int.MaxValue, -1)]
public static void TestCompareToObject(object obj, int expected)
{
IComparable comparable = 234;
int i = CompareHelper.NormalizeCompare(comparable.CompareTo(obj));
Assert.Equal(expected, i);
}
[Fact]
public static void TestCompareToObjectInvalid()
{
IComparable comparable = 234;
Assert.Throws<ArgumentException>(null, () => comparable.CompareTo("a")); //Obj is not a int
}
[Theory]
[InlineData(789, true)]
[InlineData(-789, false)]
[InlineData(0, false)]
public static void TestEqualsObject(object obj, bool expected)
{
int i = 789;
Assert.Equal(expected, i.Equals(obj));
}
[Theory]
[InlineData(789, true)]
[InlineData(-789, false)]
[InlineData(0, false)]
public static void TestEquals(int i2, bool expected)
{
int i = 789;
Assert.Equal(expected, i.Equals(i2));
}
[Fact]
public static void TestGetHashCode()
{
int i1 = 123;
int i2 = 654;
Assert.NotEqual(0, i1.GetHashCode());
Assert.NotEqual(i1.GetHashCode(), i2.GetHashCode());
}
[Fact]
public static void TestToString()
{
int i1 = 6310;
Assert.Equal("6310", i1.ToString());
int i2 = -8249;
Assert.Equal("-8249", i2.ToString());
}
[Fact]
public static void TestToStringFormatProvider()
{
var numberFormat = new NumberFormatInfo();
int i1 = 6310;
Assert.Equal("6310", i1.ToString(numberFormat));
int i2 = -8249;
Assert.Equal("-8249", i2.ToString(numberFormat));
int i3 = -2468;
// Changing the negative pattern doesn't do anything without also passing in a format string
numberFormat.NumberNegativePattern = 0;
Assert.Equal("-2468", i3.ToString(numberFormat));
}
[Fact]
public static void TestToStringFormat()
{
int i1 = 6310;
Assert.Equal("6310", i1.ToString("G"));
int i2 = -8249;
Assert.Equal("-8249", i2.ToString("g"));
int i3 = -2468;
Assert.Equal(string.Format("{0:N}", -2468.00), i3.ToString("N"));
int i4 = 0x248;
Assert.Equal("248", i4.ToString("x"));
}
[Fact]
public static void TestToStringFormatFormatProvider()
{
var numberFormat = new NumberFormatInfo();
int i1 = 6310;
Assert.Equal("6310", i1.ToString("G", numberFormat));
int i2 = -8249;
Assert.Equal("-8249", i2.ToString("g", numberFormat));
numberFormat.NegativeSign = "xx"; // setting it to trash to make sure it doesn't show up
numberFormat.NumberGroupSeparator = "*";
numberFormat.NumberNegativePattern = 0;
int i3 = -2468;
Assert.Equal("(2*468.00)", i3.ToString("N", numberFormat));
}
public static IEnumerable<object[]> ParseValidData()
{
NumberFormatInfo defaultFormat = null;
NumberStyles defaultStyle = NumberStyles.Integer;
var emptyNfi = new NumberFormatInfo();
var testNfi = new NumberFormatInfo();
testNfi.CurrencySymbol = "$";
yield return new object[] { "-2147483648", defaultStyle, defaultFormat, -2147483648 };
yield return new object[] { "0", defaultStyle, defaultFormat, 0 };
yield return new object[] { "123", defaultStyle, defaultFormat, 123 };
yield return new object[] { " 123 ", defaultStyle, defaultFormat, 123 };
yield return new object[] { "2147483647", defaultStyle, defaultFormat, 2147483647 };
yield return new object[] { "123", NumberStyles.HexNumber, defaultFormat, 0x123 };
yield return new object[] { "abc", NumberStyles.HexNumber, defaultFormat, 0xabc };
yield return new object[] { "1000", NumberStyles.AllowThousands, defaultFormat, 1000 };
yield return new object[] { "(123)", NumberStyles.AllowParentheses, defaultFormat, -123 }; // Parentheses = negative
yield return new object[] { "123", defaultStyle, emptyNfi, 123 };
yield return new object[] { "123", NumberStyles.Any, emptyNfi, 123 };
yield return new object[] { "12", NumberStyles.HexNumber, emptyNfi, 0x12 };
yield return new object[] { "$1,000", NumberStyles.Currency, testNfi, 1000 };
}
public static IEnumerable<object[]> ParseInvalidData()
{
NumberFormatInfo defaultFormat = null;
NumberStyles defaultStyle = NumberStyles.Integer;
var emptyNfi = new NumberFormatInfo();
var testNfi = new NumberFormatInfo();
testNfi.CurrencySymbol = "$";
testNfi.NumberDecimalSeparator = ".";
yield return new object[] { null, defaultStyle, defaultFormat, typeof(ArgumentNullException) };
yield return new object[] { "", defaultStyle, defaultFormat, typeof(FormatException) };
yield return new object[] { " ", defaultStyle, defaultFormat, typeof(FormatException) };
yield return new object[] { "Garbage", defaultStyle, defaultFormat, typeof(FormatException) };
yield return new object[] { "abc", defaultStyle, defaultFormat, typeof(FormatException) }; // Hex value
yield return new object[] { "1E23", defaultStyle, defaultFormat, typeof(FormatException) }; // Exponent
yield return new object[] { "(123)", defaultStyle, defaultFormat, typeof(FormatException) }; // Parentheses
yield return new object[] { 1000.ToString("C0"), defaultStyle, defaultFormat, typeof(FormatException) }; //Currency
yield return new object[] { 1000.ToString("N0"), defaultStyle, defaultFormat, typeof(FormatException) }; //Thousands
yield return new object[] { 678.90.ToString("F2"), defaultStyle, defaultFormat, typeof(FormatException) }; //Decimal
yield return new object[] { "abc", NumberStyles.None, defaultFormat, typeof(FormatException) }; // Negative hex value
yield return new object[] { " 123 ", NumberStyles.None, defaultFormat, typeof(FormatException) }; // Trailing and leading whitespace
yield return new object[] { "67.90", defaultStyle, testNfi, typeof(FormatException) }; // Decimal
yield return new object[] { "-2147483649", defaultStyle, defaultFormat, typeof(OverflowException) }; // > max value
yield return new object[] { "2147483648", defaultStyle, defaultFormat, typeof(OverflowException) }; // < min value
}
[Theory, MemberData("ParseValidData")]
public static void TestParse(string value, NumberStyles style, NumberFormatInfo nfi, int expected)
{
int i;
//If no style is specified, use the (String) or (String, IFormatProvider) overload
if (style == NumberStyles.Integer)
{
Assert.Equal(true, int.TryParse(value, out i));
Assert.Equal(expected, i);
Assert.Equal(expected, int.Parse(value));
//If a format provider is specified, but the style is the default, use the (String, IFormatProvider) overload
if (nfi != null)
{
Assert.Equal(expected, int.Parse(value, nfi));
}
}
// If a format provider isn't specified, test the default one, using a new instance of NumberFormatInfo
Assert.Equal(true, int.TryParse(value, style, nfi ?? new NumberFormatInfo(), out i));
Assert.Equal(expected, i);
//If a format provider isn't specified, test the default one, using the (String, NumberStyles) overload
if (nfi == null)
{
Assert.Equal(expected, int.Parse(value, style));
}
Assert.Equal(expected, int.Parse(value, style, nfi ?? new NumberFormatInfo()));
}
[Theory, MemberData("ParseInvalidData")]
public static void TestParseInvalid(string value, NumberStyles style, NumberFormatInfo nfi, Type exceptionType)
{
int i;
//If no style is specified, use the (String) or (String, IFormatProvider) overload
if (style == NumberStyles.Integer)
{
Assert.Equal(false, int.TryParse(value, out i));
Assert.Equal(default(int), i);
Assert.Throws(exceptionType, () => int.Parse(value));
//If a format provider is specified, but the style is the default, use the (String, IFormatProvider) overload
if (nfi != null)
{
Assert.Throws(exceptionType, () => int.Parse(value, nfi));
}
}
// If a format provider isn't specified, test the default one, using a new instance of NumberFormatInfo
Assert.Equal(false, int.TryParse(value, style, nfi ?? new NumberFormatInfo(), out i));
Assert.Equal(default(int), i);
//If a format provider isn't specified, test the default one, using the (String, NumberStyles) overload
if (nfi == null)
{
Assert.Throws(exceptionType, () => int.Parse(value, style));
}
Assert.Throws(exceptionType, () => int.Parse(value, style, nfi ?? new NumberFormatInfo()));
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.ObjectModel;
using System.Linq;
using System.Runtime.InteropServices;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.DotNet.XUnitExtensions;
using Xunit;
using Xunit.Abstractions;
namespace System.IO.Tests
{
public class FileSystemWatcherTests : FileSystemWatcherTest
{
private static void ValidateDefaults(FileSystemWatcher watcher, string path, string filter)
{
Assert.Equal(false, watcher.EnableRaisingEvents);
Assert.Equal(filter, watcher.Filter);
Assert.Equal(false, watcher.IncludeSubdirectories);
Assert.Equal(8192, watcher.InternalBufferSize);
Assert.Equal(NotifyFilters.LastWrite | NotifyFilters.FileName | NotifyFilters.DirectoryName, watcher.NotifyFilter);
Assert.Equal(path, watcher.Path);
}
[Fact]
public void FileSystemWatcher_NewFileInfoAction_TriggersNothing()
{
using (var testDirectory = new TempDirectory(GetTestFilePath()))
using (var file = new TempFile(Path.Combine(testDirectory.Path, "file")))
using (var watcher = new FileSystemWatcher(testDirectory.Path, Path.GetFileName(file.Path)))
{
Action action = () => new FileInfo(file.Path);
ExpectEvent(watcher, 0, action, expectedPath: file.Path);
}
}
[Fact]
public void FileSystemWatcher_FileInfoGetter_TriggersNothing()
{
using (var testDirectory = new TempDirectory(GetTestFilePath()))
using (var file = new TempFile(Path.Combine(testDirectory.Path, "file")))
using (var watcher = new FileSystemWatcher(testDirectory.Path, Path.GetFileName(file.Path)))
{
FileAttributes res;
Action action = () => res = new FileInfo(file.Path).Attributes;
ExpectEvent(watcher, 0, action, expectedPath: file.Path);
}
}
[Fact]
public void FileSystemWatcher_EmptyAction_TriggersNothing()
{
using (var testDirectory = new TempDirectory(GetTestFilePath()))
using (var file = new TempFile(Path.Combine(testDirectory.Path, "file")))
using (var watcher = new FileSystemWatcher(testDirectory.Path, Path.GetFileName(file.Path)))
{
Action action = () => { };
ExpectEvent(watcher, 0, action, expectedPath: file.Path);
}
}
[Fact]
public void FileSystemWatcher_ctor()
{
string path = string.Empty;
string pattern = "*";
using (FileSystemWatcher watcher = new FileSystemWatcher())
ValidateDefaults(watcher, path, pattern);
}
[Fact]
public void FileSystemWatcher_ctor_path()
{
string path = @".";
string pattern = "*";
using (FileSystemWatcher watcher = new FileSystemWatcher(path))
ValidateDefaults(watcher, path, pattern);
}
[Fact]
public void FileSystemWatcher_ctor_path_pattern()
{
string path = @".";
string pattern = "honey.jar";
using (FileSystemWatcher watcher = new FileSystemWatcher(path, pattern))
ValidateDefaults(watcher, path, pattern);
}
[Fact]
public void FileSystemWatcher_ctor_NullStrings()
{
using (var testDirectory = new TempDirectory(GetTestFilePath()))
{
// Null filter
Assert.Throws<ArgumentNullException>("filter", () => new FileSystemWatcher(testDirectory.Path, null));
// Null path
Assert.Throws<ArgumentNullException>("path", () => new FileSystemWatcher(null, null));
Assert.Throws<ArgumentNullException>("path", () => new FileSystemWatcher(null));
Assert.Throws<ArgumentNullException>("path", () => new FileSystemWatcher(null, "*"));
}
}
[Fact]
public void FileSystemWatcher_ctor_InvalidStrings()
{
using (var testDirectory = new TempDirectory(GetTestFilePath()))
{
// Empty path
AssertExtensions.Throws<ArgumentException>("path", () => new FileSystemWatcher(string.Empty));
AssertExtensions.Throws<ArgumentException>("path", () => new FileSystemWatcher(string.Empty, "*"));
// Invalid directory
AssertExtensions.Throws<ArgumentException>("path", () => new FileSystemWatcher(GetTestFilePath()));
AssertExtensions.Throws<ArgumentException>("path", () => new FileSystemWatcher(GetTestFilePath(), "*"));
}
}
[Fact]
public void FileSystemWatcher_Changed()
{
using (FileSystemWatcher watcher = new FileSystemWatcher())
{
var handler = new FileSystemEventHandler((o, e) => { });
// add / remove
watcher.Changed += handler;
watcher.Changed -= handler;
// shouldn't throw
watcher.Changed -= handler;
}
}
[Fact]
public void FileSystemWatcher_Created()
{
using (FileSystemWatcher watcher = new FileSystemWatcher())
{
var handler = new FileSystemEventHandler((o, e) => { });
// add / remove
watcher.Created += handler;
watcher.Created -= handler;
// shouldn't throw
watcher.Created -= handler;
}
}
[Fact]
public void FileSystemWatcher_Deleted()
{
using (FileSystemWatcher watcher = new FileSystemWatcher())
{
var handler = new FileSystemEventHandler((o, e) => { });
// add / remove
watcher.Deleted += handler;
watcher.Deleted -= handler;
// shouldn't throw
watcher.Deleted -= handler;
}
}
[Fact]
public void FileSystemWatcher_Disposed()
{
FileSystemWatcher watcher = new FileSystemWatcher();
watcher.Dispose();
watcher.Dispose(); // shouldn't throw
Assert.Throws<ObjectDisposedException>(() => watcher.EnableRaisingEvents = true);
}
[Fact]
public void FileSystemWatcher_EnableRaisingEvents()
{
using (var testDirectory = new TempDirectory(GetTestFilePath()))
{
FileSystemWatcher watcher = new FileSystemWatcher(testDirectory.Path);
Assert.Equal(false, watcher.EnableRaisingEvents);
watcher.EnableRaisingEvents = true;
Assert.Equal(true, watcher.EnableRaisingEvents);
watcher.EnableRaisingEvents = false;
Assert.Equal(false, watcher.EnableRaisingEvents);
}
}
[Fact]
public void FileSystemWatcher_Error()
{
using (FileSystemWatcher watcher = new FileSystemWatcher())
{
var handler = new ErrorEventHandler((o, e) => { });
// add / remove
watcher.Error += handler;
watcher.Error -= handler;
// shouldn't throw
watcher.Error -= handler;
}
}
[Fact]
public void FileSystemWatcher_Filter()
{
FileSystemWatcher watcher = new FileSystemWatcher();
Assert.Equal("*", watcher.Filter);
// Null and empty should be mapped to "*"
watcher.Filter = null;
Assert.Equal("*", watcher.Filter);
watcher.Filter = string.Empty;
Assert.Equal("*", watcher.Filter);
watcher.Filter = " ";
Assert.Equal(" ", watcher.Filter);
watcher.Filter = "\0";
Assert.Equal("\0", watcher.Filter);
watcher.Filter = "\n";
Assert.Equal("\n", watcher.Filter);
watcher.Filter = "abc.dll";
Assert.Equal("abc.dll", watcher.Filter);
if (!(PlatformDetection.IsOSX))
{
watcher.Filter = "ABC.DLL";
Assert.Equal("ABC.DLL", watcher.Filter);
}
// We can make this setting by first changing to another value then back.
watcher.Filter = null;
watcher.Filter = "ABC.DLL";
Assert.Equal("ABC.DLL", watcher.Filter);
}
[Fact]
public void FileSystemWatcher_IncludeSubdirectories()
{
FileSystemWatcher watcher = new FileSystemWatcher();
Assert.Equal(false, watcher.IncludeSubdirectories);
watcher.IncludeSubdirectories = true;
Assert.Equal(true, watcher.IncludeSubdirectories);
watcher.IncludeSubdirectories = false;
Assert.Equal(false, watcher.IncludeSubdirectories);
}
[Fact]
public void FileSystemWatcher_InternalBufferSize()
{
FileSystemWatcher watcher = new FileSystemWatcher();
Assert.Equal(8192, watcher.InternalBufferSize);
watcher.InternalBufferSize = 20000;
Assert.Equal(20000, watcher.InternalBufferSize);
watcher.InternalBufferSize = int.MaxValue;
Assert.Equal(int.MaxValue, watcher.InternalBufferSize);
// FSW enforces a minimum value of 4096
watcher.InternalBufferSize = 0;
Assert.Equal(4096, watcher.InternalBufferSize);
watcher.InternalBufferSize = -1;
Assert.Equal(4096, watcher.InternalBufferSize);
watcher.InternalBufferSize = int.MinValue;
Assert.Equal(4096, watcher.InternalBufferSize);
watcher.InternalBufferSize = 4095;
Assert.Equal(4096, watcher.InternalBufferSize);
}
[Fact]
public void FileSystemWatcher_NotifyFilter()
{
FileSystemWatcher watcher = new FileSystemWatcher();
Assert.Equal(NotifyFilters.LastWrite | NotifyFilters.FileName | NotifyFilters.DirectoryName, watcher.NotifyFilter);
var notifyFilters = Enum.GetValues(typeof(NotifyFilters)).Cast<NotifyFilters>();
foreach (NotifyFilters filterValue in notifyFilters)
{
watcher.NotifyFilter = filterValue;
Assert.Equal(filterValue, watcher.NotifyFilter);
}
var allFilters = notifyFilters.Aggregate((mask, flag) => mask | flag);
watcher.NotifyFilter = allFilters;
Assert.Equal(allFilters, watcher.NotifyFilter);
// This doesn't make sense, but it is permitted.
watcher.NotifyFilter = 0;
Assert.Equal((NotifyFilters)0, watcher.NotifyFilter);
// These throw InvalidEnumException on desktop, but ArgumentException on K
Assert.ThrowsAny<ArgumentException>(() => watcher.NotifyFilter = (NotifyFilters)(-1));
Assert.ThrowsAny<ArgumentException>(() => watcher.NotifyFilter = (NotifyFilters)int.MinValue);
Assert.ThrowsAny<ArgumentException>(() => watcher.NotifyFilter = (NotifyFilters)int.MaxValue);
Assert.ThrowsAny<ArgumentException>(() => watcher.NotifyFilter = allFilters + 1);
// Simulate a bit added to the flags
Assert.ThrowsAny<ArgumentException>(() => watcher.NotifyFilter = allFilters | (NotifyFilters)((int)notifyFilters.Max() << 1));
}
[Fact]
public void FileSystemWatcher_OnChanged()
{
using (TestFileSystemWatcher watcher = new TestFileSystemWatcher())
{
bool eventOccurred = false;
object obj = null;
FileSystemEventArgs actualArgs = null, expectedArgs = new FileSystemEventArgs(WatcherChangeTypes.Changed, "directory", "file");
watcher.Changed += (o, e) =>
{
eventOccurred = true;
obj = o;
actualArgs = e;
};
watcher.CallOnChanged(expectedArgs);
Assert.True(eventOccurred, "Event should be invoked");
Assert.Equal(watcher, obj);
Assert.Equal(expectedArgs, actualArgs);
}
}
[Fact]
public void FileSystemWatcher_OnCreated()
{
using (TestFileSystemWatcher watcher = new TestFileSystemWatcher())
{
bool eventOccurred = false;
object obj = null;
FileSystemEventArgs actualArgs = null, expectedArgs = new FileSystemEventArgs(WatcherChangeTypes.Created, "directory", "file");
watcher.Created += (o, e) =>
{
eventOccurred = true;
obj = o;
actualArgs = e;
};
watcher.CallOnCreated(expectedArgs);
Assert.True(eventOccurred, "Event should be invoked");
Assert.Equal(watcher, obj);
Assert.Equal(expectedArgs, actualArgs);
}
}
[Fact]
[PlatformSpecific(TestPlatforms.OSX | TestPlatforms.Windows)] // Casing matters on Linux
public void FileSystemWatcher_OnCreatedWithMismatchedCasingGivesExpectedFullPath()
{
using (var dir = new TempDirectory(GetTestFilePath()))
using (var fsw = new FileSystemWatcher(dir.Path))
{
AutoResetEvent are = new AutoResetEvent(false);
string fullPath = Path.Combine(dir.Path.ToUpper(), "Foo.txt");
fsw.Created += (o, e) =>
{
Assert.True(fullPath.Equals(e.FullPath, StringComparison.OrdinalIgnoreCase));
are.Set();
};
fsw.EnableRaisingEvents = true;
using (var file = new TempFile(fullPath))
{
ExpectEvent(are, "created");
}
}
}
[Fact]
public void FileSystemWatcher_OnDeleted()
{
using (TestFileSystemWatcher watcher = new TestFileSystemWatcher())
{
bool eventOccurred = false;
object obj = null;
FileSystemEventArgs actualArgs = null, expectedArgs = new FileSystemEventArgs(WatcherChangeTypes.Deleted, "directory", "file");
watcher.Deleted += (o, e) =>
{
eventOccurred = true;
obj = o;
actualArgs = e;
};
watcher.CallOnDeleted(expectedArgs);
Assert.True(eventOccurred, "Event should be invoked");
Assert.Equal(watcher, obj);
Assert.Equal(expectedArgs, actualArgs);
}
}
[Fact]
public void FileSystemWatcher_OnError()
{
using (TestFileSystemWatcher watcher = new TestFileSystemWatcher())
{
bool eventOccurred = false;
object obj = null;
ErrorEventArgs actualArgs = null, expectedArgs = new ErrorEventArgs(new Exception());
watcher.Error += (o, e) =>
{
eventOccurred = true;
obj = o;
actualArgs = e;
};
watcher.CallOnError(expectedArgs);
Assert.True(eventOccurred, "Event should be invoked");
Assert.Equal(watcher, obj);
Assert.Equal(expectedArgs, actualArgs);
}
}
[Fact]
public void FileSystemWatcher_OnRenamed()
{
using (TestFileSystemWatcher watcher = new TestFileSystemWatcher())
{
bool eventOccurred = false;
object obj = null;
RenamedEventArgs actualArgs = null, expectedArgs = new RenamedEventArgs(WatcherChangeTypes.Renamed, "directory", "file", "oldFile");
watcher.Renamed += (o, e) =>
{
eventOccurred = true;
obj = o;
actualArgs = e;
};
watcher.CallOnRenamed(expectedArgs);
Assert.True(eventOccurred, "Event should be invoked");
Assert.Equal(watcher, obj);
Assert.Equal(expectedArgs, actualArgs);
}
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)] // Unix FSW don't trigger on a file rename.
public void FileSystemWatcher_Windows_OnRenameGivesExpectedFullPath()
{
using (var dir = new TempDirectory(GetTestFilePath()))
using (var file = new TempFile(Path.Combine(dir.Path, "file")))
using (var fsw = new FileSystemWatcher(dir.Path))
{
AutoResetEvent eventOccurred = WatchRenamed(fsw).EventOccured;
string newPath = Path.Combine(dir.Path, "newPath");
fsw.Renamed += (o, e) =>
{
Assert.Equal(file.Path, e.OldFullPath);
Assert.Equal(newPath, e.FullPath);
};
fsw.EnableRaisingEvents = true;
File.Move(file.Path, newPath);
ExpectEvent(eventOccurred, "renamed");
}
}
[Fact]
public void FileSystemWatcher_Path()
{
FileSystemWatcher watcher = new FileSystemWatcher();
Assert.Equal(string.Empty, watcher.Path);
watcher.Path = null;
Assert.Equal(string.Empty, watcher.Path);
watcher.Path = ".";
Assert.Equal(".", watcher.Path);
if (!PlatformDetection.IsInAppContainer)
{
watcher.Path = "..";
Assert.Equal("..", watcher.Path);
}
string currentDir = Path.GetFullPath(".").TrimEnd('.', Path.DirectorySeparatorChar);
watcher.Path = currentDir;
Assert.Equal(currentDir, watcher.Path);
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows) || // expect no change for OrdinalIgnoreCase-equal strings
RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
{
watcher.Path = currentDir.ToUpperInvariant();
Assert.Equal(currentDir, watcher.Path);
watcher.Path = currentDir.ToLowerInvariant();
Assert.Equal(currentDir, watcher.Path);
}
// expect a change for same "full-path" but different string path, FSW does not normalize
string currentDirRelative = currentDir +
Path.DirectorySeparatorChar + "." +
Path.DirectorySeparatorChar + "." +
Path.DirectorySeparatorChar + "." +
Path.DirectorySeparatorChar + ".";
watcher.Path = currentDirRelative;
Assert.Equal(currentDirRelative, watcher.Path);
// FSW starts with String.Empty and will ignore setting this if it is already set,
// but if you set it after some other valid string has been set it will throw.
Assert.Throws<ArgumentException>(() => watcher.Path = string.Empty);
// Non-existent path
Assert.Throws<ArgumentException>(() => watcher.Path = GetTestFilePath());
// Web path
Assert.Throws<ArgumentException>(() => watcher.Path = "http://localhost");
// File protocol
Assert.Throws<ArgumentException>(() => watcher.Path = "file:///" + currentDir.Replace(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar));
}
[Fact]
public void FileSystemWatcher_Renamed()
{
using (FileSystemWatcher watcher = new FileSystemWatcher())
{
var handler = new RenamedEventHandler((o, e) => { });
// add / remove
watcher.Renamed += handler;
watcher.Renamed -= handler;
// shouldn't throw
watcher.Renamed -= handler;
}
}
[Fact]
public void FileSystemWatcher_StopCalledOnBackgroundThreadDoesNotDeadlock()
{
// Check the case where Stop or Dispose (they do the same thing) is called from
// a FSW event callback and make sure we don't Thread.Join to deadlock
using (var dir = new TempDirectory(GetTestFilePath()))
{
string filePath = Path.Combine(dir.Path, "testfile.txt");
File.Create(filePath).Dispose();
AutoResetEvent are = new AutoResetEvent(false);
FileSystemWatcher watcher = new FileSystemWatcher(Path.GetFullPath(dir.Path), "*");
FileSystemEventHandler callback = (sender, arg) =>
{
watcher.Dispose();
are.Set();
};
watcher.NotifyFilter = NotifyFilters.FileName | NotifyFilters.LastWrite;
watcher.Changed += callback;
watcher.EnableRaisingEvents = true;
File.SetLastWriteTime(filePath, File.GetLastWriteTime(filePath).AddDays(1));
Assert.True(are.WaitOne(10000));
Assert.Throws<ObjectDisposedException>(() => watcher.EnableRaisingEvents = true);
}
}
[Fact]
public void FileSystemWatcher_WatchingAliasedFolderResolvesToRealPathWhenWatching()
{
using (var testDirectory = new TempDirectory(GetTestFilePath()))
using (var dir = new TempDirectory(Path.Combine(testDirectory.Path, "dir")))
using (var fsw = new FileSystemWatcher(dir.Path))
{
AutoResetEvent are = WatchCreated(fsw).EventOccured;
fsw.Filter = "*";
fsw.EnableRaisingEvents = true;
using (var temp = new TempDirectory(Path.Combine(dir.Path, "foo")))
{
ExpectEvent(are, "created");
}
}
}
[Fact]
public void DefaultFiltersValue()
{
var watcher = new FileSystemWatcher();
Assert.Equal(0, watcher.Filters.Count);
Assert.Empty(watcher.Filters);
Assert.NotNull(watcher.Filters);
Assert.Equal(new string[] { }, watcher.Filters);
}
[Fact]
public void AddFilterToFilters()
{
var watcher = new FileSystemWatcher();
watcher.Filters.Add("*.pdb");
watcher.Filters.Add("*.dll");
Assert.Equal(2, watcher.Filters.Count);
Assert.Equal(new string[] { "*.pdb", "*.dll" }, watcher.Filters);
string[] copied = new string[2];
watcher.Filters.CopyTo(copied, 0);
Assert.Equal(new string[] { "*.pdb", "*.dll" }, copied);
}
[Fact]
public void FiltersCaseSensitive()
{
var watcher = new FileSystemWatcher();
watcher.Filters.Add("foo");
Assert.Equal("foo", watcher.Filters[0]);
watcher.Filters[0] = "Foo";
Assert.Equal("Foo", watcher.Filters[0]);
}
[Fact]
public void RemoveFilterFromFilters()
{
var watcher = new FileSystemWatcher();
watcher.Filters.Add("*.pdb");
watcher.Filters.Add("*.dll");
watcher.Filters.Remove("*.pdb");
Assert.DoesNotContain(watcher.Filters, t => t == "*.pdb");
Assert.Equal(new string[] { "*.dll" }, watcher.Filters);
// No Exception is thrown while removing an item which is not present in the list.
watcher.Filters.Remove("*.pdb");
}
[Fact]
public void AddEmptyStringToFilters()
{
var watcher = new FileSystemWatcher();
watcher.Filters.Add("*.pdb");
watcher.Filters.Add("*.dll");
watcher.Filters.Add(string.Empty);
Assert.Equal(3, watcher.Filters.Count);
Assert.Equal(new string[] { "*.pdb", "*.dll", "*" }, watcher.Filters);
}
[Fact]
public void AddNullToFilters()
{
var watcher = new FileSystemWatcher();
watcher.Filters.Add("*.pdb");
watcher.Filters.Add("*.dll");
watcher.Filters.Add(null);
Assert.Equal(3, watcher.Filters.Count);
Assert.Equal(new string[] { "*.pdb", "*.dll", "*" }, watcher.Filters);
}
[Fact]
public void SetEmptyStringToFilters()
{
var watcher = new FileSystemWatcher();
watcher.Filters.Add("*.pdb");
watcher.Filters.Add("*.dll");
watcher.Filters[0] = string.Empty;
Assert.Equal(2, watcher.Filters.Count);
Assert.Equal("*", watcher.Filters[0]);
Assert.Equal(new string[] { "*", "*.dll"}, watcher.Filters);
}
[Fact]
public void RemoveEmptyStringToFilters()
{
var watcher = new FileSystemWatcher();
watcher.Filters.Add("*.pdb");
watcher.Filters.Add("*.dll");
watcher.Filters.Add(string.Empty);
Assert.Equal(3, watcher.Filters.Count);
watcher.Filters.Remove(string.Empty);
Assert.Equal(3, watcher.Filters.Count);
Assert.Equal(new string[] { "*.pdb", "*.dll", "*" }, watcher.Filters);
}
[Fact]
public void RemoveAtFilters()
{
var watcher = new FileSystemWatcher();
watcher.Filters.Add("*.pdb");
watcher.Filters.Add("*.dll");
watcher.Filters.RemoveAt(0);
Assert.Equal(1, watcher.Filters.Count);
Assert.Equal("*.dll", watcher.Filter);
Assert.Equal(new string[] {"*.dll" }, watcher.Filters);
}
[Fact]
public void RemoveAtEmptyFilters()
{
var watcher = new FileSystemWatcher();
watcher.Filters.Add("*.pdb");
watcher.Filters.RemoveAt(0);
Assert.Equal(0, watcher.Filters.Count);
Assert.Equal("*", watcher.Filter);
Assert.Equal(new string[] { }, watcher.Filters);
}
[Fact]
public void SetNullToFilters()
{
var watcher = new FileSystemWatcher();
watcher.Filters.Add("*.pdb");
watcher.Filters.Add("*.dll");
watcher.Filters[0] = null;
Assert.Equal(2, watcher.Filters.Count);
Assert.Equal("*", watcher.Filters[0]);
Assert.Equal(new string[] { "*", "*.dll" }, watcher.Filters);
}
[Fact]
public void ContainsEmptyStringFilters()
{
var watcher = new FileSystemWatcher();
watcher.Filters.Add("*.pdb");
watcher.Filters.Add("*.dll");
watcher.Filters.Add(string.Empty);
Assert.False(watcher.Filters.Contains(string.Empty));
Assert.True(watcher.Filters.Contains("*"));
}
[Fact]
public void ContainsNullFilters()
{
var watcher = new FileSystemWatcher();
watcher.Filters.Add("*.pdb");
watcher.Filters.Add("*.dll");
watcher.Filters.Add(null);
Assert.False(watcher.Filters.Contains(null));
Assert.True(watcher.Filters.Contains("*"));
}
[Fact]
public void ContainsFilters()
{
var watcher = new FileSystemWatcher();
watcher.Filters.Add("*.pdb");
watcher.Filters.Add("*.dll");
Assert.True(watcher.Filters.Contains("*.pdb"));
}
[Fact]
public void InsertEmptyStringFilters()
{
var watcher = new FileSystemWatcher();
watcher.Filters.Add("*.pdb");
watcher.Filters.Add("*.dll");
watcher.Filters.Insert(1, string.Empty);
Assert.Equal("*", watcher.Filters[1]);
Assert.Equal(3, watcher.Filters.Count);
Assert.Equal(new string[] { "*.pdb", "*", "*.dll" }, watcher.Filters);
}
[Fact]
public void InsertNullFilters()
{
var watcher = new FileSystemWatcher();
watcher.Filters.Add("*.pdb");
watcher.Filters.Add("*.dll");
watcher.Filters.Insert(1, null);
Assert.Equal("*", watcher.Filters[1]);
Assert.Equal(3, watcher.Filters.Count);
Assert.Equal(new string[] { "*.pdb", "*", "*.dll" }, watcher.Filters);
}
[Fact]
public void InsertFilters()
{
var watcher = new FileSystemWatcher();
watcher.Filters.Add("*.pdb");
watcher.Filters.Add("*.dll");
watcher.Filters.Insert(1, "foo");
Assert.Equal("foo", watcher.Filters[1]);
Assert.Equal(3, watcher.Filters.Count);
Assert.Equal(new string[] { "*.pdb", "foo", "*.dll" }, watcher.Filters);
}
[Fact]
public void InsertAtZero()
{
var watcher = new FileSystemWatcher();
watcher.Filters.Add("*.pdb");
watcher.Filters.Add("*.dll");
watcher.Filters.Insert(0, "foo");
Assert.Equal("foo", watcher.Filters[0]);
Assert.Equal("foo", watcher.Filter);
Assert.Equal(3, watcher.Filters.Count);
Assert.Equal(new string[] { "foo", "*.pdb", "*.dll" }, watcher.Filters);
}
[Fact]
public void IndexOfEmptyStringFilters()
{
var watcher = new FileSystemWatcher();
watcher.Filters.Add("*.pdb");
watcher.Filters.Add("*.dll");
watcher.Filters.Add(string.Empty);
Assert.Equal(-1, watcher.Filters.IndexOf(string.Empty));
}
[Fact]
public void IndexOfNullFilters()
{
var watcher = new FileSystemWatcher();
watcher.Filters.Add("*.pdb");
watcher.Filters.Add("*.dll");
watcher.Filters.Add(null);
Assert.Equal(-1, watcher.Filters.IndexOf(null));
}
[Fact]
public void IndexOfFilters()
{
var watcher = new FileSystemWatcher();
watcher.Filters.Add("*.pdb");
watcher.Filters.Add("*.dll");
Assert.Equal(-1, watcher.Filters.IndexOf("foo"));
Assert.Equal(0, watcher.Filters.IndexOf("*.pdb"));
}
[Fact]
public void GetTypeFilters()
{
var watcher = new FileSystemWatcher();
Assert.IsAssignableFrom<Collection<string>>(watcher.Filters);
}
[Fact]
public void ClearFilters()
{
var watcher = new FileSystemWatcher();
watcher.Filters.Add("*.pdb");
watcher.Filters.Add("*.dll");
watcher.Filters.Clear();
Assert.Equal(0, watcher.Filters.Count);
Assert.Equal(new string[] { }, watcher.Filters) ;
}
[Fact]
public void GetFilterAfterFiltersClear()
{
using (var testDirectory = new TempDirectory(GetTestFilePath()))
{
var watcher = new FileSystemWatcher(testDirectory.Path);
watcher.Filters.Add("*.pdb");
watcher.Filters.Add("*.dll");
watcher.Filters.Clear();
Assert.Equal("*", watcher.Filter);
Assert.Equal(new string[] { }, watcher.Filters);
}
}
[Fact]
public void GetFiltersAfterFiltersClear()
{
using (var testDirectory = new TempDirectory(GetTestFilePath()))
{
var watcher = new FileSystemWatcher(testDirectory.Path);
watcher.Filters.Add("*.pdb");
watcher.Filters.Add("*.dll");
watcher.Filters.Clear();
Assert.Throws<ArgumentOutOfRangeException>(() => watcher.Filters[0]);
Assert.Equal(0, watcher.Filters.Count);
Assert.Empty(watcher.Filters);
Assert.NotNull(watcher.Filters);
}
}
[Fact]
public void InvalidOperationsOnFilters()
{
var watcher = new FileSystemWatcher();
watcher.Filters.Add("*.pdb");
watcher.Filters.Add("*.dll");
Assert.Throws<ArgumentOutOfRangeException>(() => watcher.Filters.Insert(4, "*"));
watcher.Filters.Clear();
Assert.Throws<ArgumentOutOfRangeException>(() => watcher.Filters[0]);
}
[Fact]
public void SetAndGetFilterProperty()
{
using (var testDirectory = new TempDirectory(GetTestFilePath()))
{
var watcher = new FileSystemWatcher(testDirectory.Path, "*.pdb");
watcher.Filters.Add("foo");
Assert.Equal(2, watcher.Filters.Count);
Assert.Equal(new string[] { "*.pdb", "foo" }, watcher.Filters);
watcher.Filter = "*.doc";
Assert.Equal(1, watcher.Filters.Count);
Assert.Equal("*.doc", watcher.Filter);
Assert.Equal("*.doc", watcher.Filters[0]);
Assert.Equal(new string[] { "*.doc" }, watcher.Filters);
watcher.Filters.Clear();
Assert.Equal("*", watcher.Filter);
}
}
[Fact]
public void SetAndGetFiltersProperty()
{
using (var testDirectory = new TempDirectory(GetTestFilePath()))
{
var watcher = new FileSystemWatcher(testDirectory.Path, "*.pdb");
watcher.Filters.Add("foo");
Assert.Equal(new string[] { "*.pdb", "foo" }, watcher.Filters);
}
}
[Fact]
public void FileSystemWatcher_File_Delete_MultipleFilters()
{
// Check delete events against multiple filters
DirectoryInfo directory = Directory.CreateDirectory(GetTestFilePath());
FileInfo fileOne = new FileInfo(Path.Combine(directory.FullName, GetTestFileName()));
FileInfo fileTwo = new FileInfo(Path.Combine(directory.FullName, GetTestFileName()));
FileInfo fileThree = new FileInfo(Path.Combine(directory.FullName, GetTestFileName()));
fileOne.Create().Dispose();
fileTwo.Create().Dispose();
fileThree.Create().Dispose();
using (var watcher = new FileSystemWatcher(directory.FullName))
{
watcher.Filters.Add(fileOne.Name);
watcher.Filters.Add(fileTwo.Name);
ExpectEvent(watcher, WatcherChangeTypes.Deleted, () => fileOne.Delete(), cleanup: null, expectedPath : fileOne.FullName);
ExpectEvent(watcher, WatcherChangeTypes.Deleted, () => fileTwo.Delete(), cleanup: null, expectedPath: fileTwo.FullName );
ExpectNoEvent(watcher, WatcherChangeTypes.Deleted, () => fileThree.Delete(), cleanup: null, expectedPath: fileThree.FullName);
}
}
[Fact]
public void FileSystemWatcher_Directory_Create_MultipleFilters()
{
// Check create events against multiple filters
DirectoryInfo directory = Directory.CreateDirectory(GetTestFilePath());
string directoryOne = Path.Combine(directory.FullName, GetTestFileName());
string directoryTwo = Path.Combine(directory.FullName, GetTestFileName());
string directoryThree = Path.Combine(directory.FullName, GetTestFileName());
using (var watcher = new FileSystemWatcher(directory.FullName))
{
watcher.Filters.Add(Path.GetFileName(directoryOne));
watcher.Filters.Add(Path.GetFileName(directoryTwo));
ExpectEvent(watcher, WatcherChangeTypes.Created, () => Directory.CreateDirectory(directoryOne), cleanup: null, expectedPath: directoryOne);
ExpectEvent(watcher, WatcherChangeTypes.Created, () => Directory.CreateDirectory(directoryTwo), cleanup: null, expectedPath: directoryTwo);
ExpectNoEvent(watcher, WatcherChangeTypes.Created, () => Directory.CreateDirectory(directoryThree), cleanup: null, expectedPath: directoryThree);
}
}
[Fact]
public void FileSystemWatcher_Directory_Create_Filter_Ctor()
{
// Check create events against multiple filters
DirectoryInfo directory = Directory.CreateDirectory(GetTestFilePath());
string directoryOne = Path.Combine(directory.FullName, GetTestFileName());
string directoryTwo = Path.Combine(directory.FullName, GetTestFileName());
string directoryThree = Path.Combine(directory.FullName, GetTestFileName());
using (var watcher = new FileSystemWatcher(directory.FullName, Path.GetFileName(directoryOne)))
{
watcher.Filters.Add(Path.GetFileName(directoryTwo));
ExpectEvent(watcher, WatcherChangeTypes.Created, () => Directory.CreateDirectory(directoryOne), cleanup: null, expectedPath: directoryOne);
ExpectEvent(watcher, WatcherChangeTypes.Created, () => Directory.CreateDirectory(directoryTwo), cleanup: null, expectedPath: directoryTwo);
ExpectNoEvent(watcher, WatcherChangeTypes.Created, () => Directory.CreateDirectory(directoryThree), cleanup: null, expectedPath: directoryThree);
}
}
[Fact]
public void FileSystemWatcher_Directory_Delete_MultipleFilters()
{
DirectoryInfo directory = Directory.CreateDirectory(GetTestFilePath());
DirectoryInfo directoryOne = Directory.CreateDirectory(Path.Combine(directory.FullName, GetTestFileName()));
DirectoryInfo directoryTwo = Directory.CreateDirectory(Path.Combine(directory.FullName, GetTestFileName()));
DirectoryInfo directoryThree = Directory.CreateDirectory(Path.Combine(directory.FullName, GetTestFileName()));
using (var watcher = new FileSystemWatcher(directory.FullName))
{
watcher.Filters.Add(Path.GetFileName(directoryOne.FullName));
watcher.Filters.Add(Path.GetFileName(directoryTwo.FullName));
ExpectEvent(watcher, WatcherChangeTypes.Deleted, () => directoryOne.Delete(), cleanup: null, expectedPath: directoryOne.FullName);
ExpectEvent(watcher, WatcherChangeTypes.Deleted, () => directoryTwo.Delete(), cleanup: null, expectedPath: directoryTwo.FullName);
ExpectNoEvent(watcher, WatcherChangeTypes.Deleted, () => directoryThree.Delete(), cleanup: null, expectedPath: directoryThree.FullName);
}
}
[Fact]
public void FileSystemWatcher_File_Create_MultipleFilters()
{
DirectoryInfo directory = Directory.CreateDirectory(GetTestFilePath());
FileInfo fileOne = new FileInfo(Path.Combine(directory.FullName, GetTestFileName()));
FileInfo fileTwo = new FileInfo(Path.Combine(directory.FullName, GetTestFileName()));
FileInfo fileThree = new FileInfo(Path.Combine(directory.FullName, GetTestFileName()));
using (var watcher = new FileSystemWatcher(directory.FullName))
{
watcher.Filters.Add(fileOne.Name);
watcher.Filters.Add(fileTwo.Name);
ExpectEvent(watcher, WatcherChangeTypes.Created, () => fileOne.Create().Dispose(), cleanup: null, expectedPath: fileOne.FullName);
ExpectEvent(watcher, WatcherChangeTypes.Created, () => fileTwo.Create().Dispose(), cleanup: null, expectedPath: fileTwo.FullName);
ExpectNoEvent(watcher, WatcherChangeTypes.Created, () => fileThree.Create().Dispose(), cleanup: null, expectedPath: fileThree.FullName);
}
}
[Fact]
public void FileSystemWatcher_ModifyFiltersConcurrentWithEvents()
{
DirectoryInfo directory = Directory.CreateDirectory(GetTestFilePath());
FileInfo fileOne = new FileInfo(Path.Combine(directory.FullName, GetTestFileName()));
FileInfo fileTwo = new FileInfo(Path.Combine(directory.FullName, GetTestFileName()));
FileInfo fileThree = new FileInfo(Path.Combine(directory.FullName, GetTestFileName()));
using (var watcher = new FileSystemWatcher(directory.FullName))
{
watcher.Filters.Add(fileOne.Name);
watcher.Filters.Add(fileTwo.Name);
var cts = new CancellationTokenSource();
Task modifier = Task.Run(() =>
{
string otherFilter = Guid.NewGuid().ToString("N");
while (!cts.IsCancellationRequested)
{
watcher.Filters.Add(otherFilter);
watcher.Filters.RemoveAt(2);
}
});
ExpectEvent(watcher, WatcherChangeTypes.Created, () => fileOne.Create().Dispose(), cleanup: null, expectedPath: fileOne.FullName);
ExpectEvent(watcher, WatcherChangeTypes.Created, () => fileTwo.Create().Dispose(), cleanup: null, expectedPath: fileTwo.FullName);
ExpectNoEvent(watcher, WatcherChangeTypes.Created, () => fileThree.Create().Dispose(), cleanup: null, expectedPath: fileThree.FullName);
cts.Cancel();
modifier.Wait();
}
}
}
[Collection("NoParallelTests")]
public class DangerousFileSystemWatcherTests : FileSystemWatcherTest
{
[PlatformSpecific(TestPlatforms.Linux)] // Reads MaxUsersWatches from Linux OS files
[OuterLoop("This test will use all available watchers and can cause failures in other concurrent tests or system processes.")]
[Fact]
public void FileSystemWatcher_CreateManyConcurrentWatches()
{
int maxUserWatches = int.Parse(File.ReadAllText("/proc/sys/fs/inotify/max_user_watches"));
using (var dir = new TempDirectory(GetTestFilePath()))
using (var watcher = new FileSystemWatcher(dir.Path) { IncludeSubdirectories = true, NotifyFilter = NotifyFilters.FileName })
{
Action action = () =>
{
// Create enough directories to exceed the number of allowed watches
for (int i = 0; i <= maxUserWatches; i++)
{
Directory.CreateDirectory(Path.Combine(dir.Path, i.ToString()));
}
};
Action cleanup = () =>
{
for (int i = 0; i <= maxUserWatches; i++)
{
Directory.Delete(Path.Combine(dir.Path, i.ToString()));
}
};
ExpectError(watcher, action, cleanup);
// Make sure existing watches still work even after we've had one or more failures
Action createAction = () => File.WriteAllText(Path.Combine(dir.Path, Path.GetRandomFileName()), "text");
Action createCleanup = () => File.Delete(Path.Combine(dir.Path, Path.GetRandomFileName()));
ExpectEvent(watcher, WatcherChangeTypes.Created, createAction, createCleanup);
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Linq;
using Csla;
using Invoices.DataAccess;
namespace Invoices.Business
{
/// <summary>
/// CustomerList (read only list).<br/>
/// This is a generated <see cref="CustomerList"/> business object.
/// This class is a root collection.
/// </summary>
/// <remarks>
/// The items of the collection are <see cref="CustomerInfo"/> objects.
/// </remarks>
[Serializable]
#if WINFORMS
public partial class CustomerList : ReadOnlyBindingListBase<CustomerList, CustomerInfo>
#else
public partial class CustomerList : ReadOnlyListBase<CustomerList, CustomerInfo>
#endif
{
#region Event handler properties
[NotUndoable]
private static bool _singleInstanceSavedHandler = true;
/// <summary>
/// Gets or sets a value indicating whether only a single instance should handle the Saved event.
/// </summary>
/// <value>
/// <c>true</c> if only a single instance should handle the Saved event; otherwise, <c>false</c>.
/// </value>
public static bool SingleInstanceSavedHandler
{
get { return _singleInstanceSavedHandler; }
set { _singleInstanceSavedHandler = value; }
}
#endregion
#region Factory Methods
/// <summary>
/// Factory method. Loads a <see cref="CustomerList"/> collection.
/// </summary>
/// <returns>A reference to the fetched <see cref="CustomerList"/> collection.</returns>
public static CustomerList GetCustomerList()
{
return DataPortal.Fetch<CustomerList>();
}
/// <summary>
/// Factory method. Loads a <see cref="CustomerList"/> collection, based on given parameters.
/// </summary>
/// <param name="name">The Name parameter of the CustomerList to fetch.</param>
/// <returns>A reference to the fetched <see cref="CustomerList"/> collection.</returns>
public static CustomerList GetCustomerList(string name)
{
return DataPortal.Fetch<CustomerList>(name);
}
/// <summary>
/// Factory method. Asynchronously loads a <see cref="CustomerList"/> collection.
/// </summary>
/// <param name="callback">The completion callback method.</param>
public static void GetCustomerList(EventHandler<DataPortalResult<CustomerList>> callback)
{
DataPortal.BeginFetch<CustomerList>(callback);
}
/// <summary>
/// Factory method. Asynchronously loads a <see cref="CustomerList"/> collection, based on given parameters.
/// </summary>
/// <param name="name">The Name parameter of the CustomerList to fetch.</param>
/// <param name="callback">The completion callback method.</param>
public static void GetCustomerList(string name, EventHandler<DataPortalResult<CustomerList>> callback)
{
DataPortal.BeginFetch<CustomerList>(name, callback);
}
#endregion
#region Constructor
/// <summary>
/// Initializes a new instance of the <see cref="CustomerList"/> class.
/// </summary>
/// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks>
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public CustomerList()
{
// Use factory methods and do not use direct creation.
CustomerEditSaved.Register(this);
var rlce = RaiseListChangedEvents;
RaiseListChangedEvents = false;
AllowNew = false;
AllowEdit = false;
AllowRemove = false;
RaiseListChangedEvents = rlce;
}
#endregion
#region Saved Event Handler
/// <summary>
/// Handle Saved events of <see cref="CustomerEdit"/> to update the list of <see cref="CustomerInfo"/> objects.
/// </summary>
/// <param name="sender">The sender of the event.</param>
/// <param name="e">The <see cref="Csla.Core.SavedEventArgs"/> instance containing the event data.</param>
internal void CustomerEditSavedHandler(object sender, Csla.Core.SavedEventArgs e)
{
var obj = (CustomerEdit)e.NewObject;
if (((CustomerEdit)sender).IsNew)
{
IsReadOnly = false;
var rlce = RaiseListChangedEvents;
RaiseListChangedEvents = true;
Add(CustomerInfo.LoadInfo(obj));
RaiseListChangedEvents = rlce;
IsReadOnly = true;
}
else if (((CustomerEdit)sender).IsDeleted)
{
for (int index = 0; index < this.Count; index++)
{
var child = this[index];
if (child.CustomerId == obj.CustomerId)
{
IsReadOnly = false;
var rlce = RaiseListChangedEvents;
RaiseListChangedEvents = true;
this.RemoveItem(index);
RaiseListChangedEvents = rlce;
IsReadOnly = true;
break;
}
}
}
else
{
for (int index = 0; index < this.Count; index++)
{
var child = this[index];
if (child.CustomerId == obj.CustomerId)
{
child.UpdatePropertiesOnSaved(obj);
#if !WINFORMS
var notifyCollectionChangedEventArgs =
new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Replace, child, child, index);
OnCollectionChanged(notifyCollectionChangedEventArgs);
#else
var listChangedEventArgs = new ListChangedEventArgs(ListChangedType.ItemChanged, index);
OnListChanged(listChangedEventArgs);
#endif
break;
}
}
}
}
#endregion
#region Data Access
/// <summary>
/// Loads a <see cref="CustomerList"/> collection from the database.
/// </summary>
protected void DataPortal_Fetch()
{
var args = new DataPortalHookArgs();
OnFetchPre(args);
using (var dalManager = DalFactoryInvoices.GetManager())
{
var dal = dalManager.GetProvider<ICustomerListDal>();
var data = dal.Fetch();
Fetch(data);
}
OnFetchPost(args);
}
/// <summary>
/// Loads a <see cref="CustomerList"/> collection from the database, based on given criteria.
/// </summary>
/// <param name="name">The Name.</param>
protected void DataPortal_Fetch(string name)
{
var args = new DataPortalHookArgs(name);
OnFetchPre(args);
using (var dalManager = DalFactoryInvoices.GetManager())
{
var dal = dalManager.GetProvider<ICustomerListDal>();
var data = dal.Fetch(name);
Fetch(data);
}
OnFetchPost(args);
}
/// <summary>
/// Loads all <see cref="CustomerList"/> collection items from the given list of CustomerInfoDto.
/// </summary>
/// <param name="data">The list of <see cref="CustomerInfoDto"/>.</param>
private void Fetch(List<CustomerInfoDto> data)
{
IsReadOnly = false;
var rlce = RaiseListChangedEvents;
RaiseListChangedEvents = false;
foreach (var dto in data)
{
Add(DataPortal.FetchChild<CustomerInfo>(dto));
}
RaiseListChangedEvents = rlce;
IsReadOnly = true;
}
#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
#region CustomerEditSaved nested class
// TODO: edit "CustomerList.cs", uncomment the "OnDeserialized" method and add the following line:
// TODO: CustomerEditSaved.Register(this);
/// <summary>
/// Nested class to manage the Saved events of <see cref="CustomerEdit"/>
/// to update the list of <see cref="CustomerInfo"/> objects.
/// </summary>
private static class CustomerEditSaved
{
private static List<WeakReference> _references;
private static bool Found(object obj)
{
return _references.Any(reference => Equals(reference.Target, obj));
}
/// <summary>
/// Registers a CustomerList instance to handle Saved events.
/// to update the list of <see cref="CustomerInfo"/> objects.
/// </summary>
/// <param name="obj">The CustomerList instance.</param>
public static void Register(CustomerList obj)
{
var mustRegister = _references == null;
if (mustRegister)
_references = new List<WeakReference>();
if (CustomerList.SingleInstanceSavedHandler)
_references.Clear();
if (!Found(obj))
_references.Add(new WeakReference(obj));
if (mustRegister)
CustomerEdit.CustomerEditSaved += CustomerEditSavedHandler;
}
/// <summary>
/// Handles Saved events of <see cref="CustomerEdit"/>.
/// </summary>
/// <param name="sender">The sender of the event.</param>
/// <param name="e">The <see cref="Csla.Core.SavedEventArgs"/> instance containing the event data.</param>
public static void CustomerEditSavedHandler(object sender, Csla.Core.SavedEventArgs e)
{
foreach (var reference in _references)
{
if (reference.IsAlive)
((CustomerList) reference.Target).CustomerEditSavedHandler(sender, e);
}
}
/// <summary>
/// Removes event handling and clears all registered CustomerList instances.
/// </summary>
public static void Unregister()
{
CustomerEdit.CustomerEditSaved -= CustomerEditSavedHandler;
_references = null;
}
}
#endregion
}
}
| |
using System;
using System.IO;
using System.Reflection.Emit;
namespace ClrTest.Reflection
{
public interface IILStringCollector
{
void Process(ILInstruction ilInstruction, string operandString);
}
public class ReadableILStringToTextWriter : IILStringCollector
{
protected TextWriter writer;
public ReadableILStringToTextWriter(TextWriter writer)
{
this.writer = writer;
}
public virtual void Process(ILInstruction ilInstruction, string operandString)
{
if (OpCodes.Nop.Equals(ilInstruction.OpCode))
{
return;
}
this.writer.WriteLine("IL_{0:x4}: {1,-10} {2}",
ilInstruction.Offset,
ilInstruction.OpCode.Name,
operandString);
}
}
public class RawILStringToTextWriter : ReadableILStringToTextWriter
{
public RawILStringToTextWriter(TextWriter writer)
: base(writer)
{
}
public override void Process(ILInstruction ilInstruction, string operandString)
{
this.writer.WriteLine("IL_{0:x4}: {1,-4}| {2, -8}",
ilInstruction.Offset,
ilInstruction.OpCode.Value.ToString("x2"),
operandString);
}
}
public abstract class ILInstructionVisitor
{
public virtual void VisitInlineBrTargetInstruction(InlineBrTargetInstruction inlineBrTargetInstruction) { }
public virtual void VisitInlineFieldInstruction(InlineFieldInstruction inlineFieldInstruction) { }
public virtual void VisitInlineIInstruction(InlineIInstruction inlineIInstruction) { }
public virtual void VisitInlineI8Instruction(InlineI8Instruction inlineI8Instruction) { }
public virtual void VisitInlineMethodInstruction(InlineMethodInstruction inlineMethodInstruction) { }
public virtual void VisitInlineNoneInstruction(InlineNoneInstruction inlineNoneInstruction) { }
public virtual void VisitInlineRInstruction(InlineRInstruction inlineRInstruction) { }
public virtual void VisitInlineSigInstruction(InlineSigInstruction inlineSigInstruction) { }
public virtual void VisitInlineStringInstruction(InlineStringInstruction inlineStringInstruction) { }
public virtual void VisitInlineSwitchInstruction(InlineSwitchInstruction inlineSwitchInstruction) { }
public virtual void VisitInlineTokInstruction(InlineTokInstruction inlineTokInstruction) { }
public virtual void VisitInlineTypeInstruction(InlineTypeInstruction inlineTypeInstruction) { }
public virtual void VisitInlineVarInstruction(InlineVarInstruction inlineVarInstruction) { }
public virtual void VisitShortInlineBrTargetInstruction(ShortInlineBrTargetInstruction shortInlineBrTargetInstruction) { }
public virtual void VisitShortInlineIInstruction(ShortInlineIInstruction shortInlineIInstruction) { }
public virtual void VisitShortInlineRInstruction(ShortInlineRInstruction shortInlineRInstruction) { }
public virtual void VisitShortInlineVarInstruction(ShortInlineVarInstruction shortInlineVarInstruction) { }
}
public class ReadableILStringVisitor : ILInstructionVisitor
{
protected IFormatProvider formatProvider;
protected IILStringCollector collector;
public ReadableILStringVisitor(IILStringCollector collector)
: this(collector, DefaultFormatProvider.Instance)
{
}
public ReadableILStringVisitor(IILStringCollector collector, IFormatProvider formatProvider)
{
this.formatProvider = formatProvider;
this.collector = collector;
}
public override void VisitInlineBrTargetInstruction(InlineBrTargetInstruction inlineBrTargetInstruction)
{
collector.Process(inlineBrTargetInstruction, formatProvider.Label(inlineBrTargetInstruction.TargetOffset));
}
public override void VisitInlineFieldInstruction(InlineFieldInstruction inlineFieldInstruction)
{
string field;
try
{
field = inlineFieldInstruction.Field + "/" + inlineFieldInstruction.Field.DeclaringType;
}
catch (Exception ex)
{
field = "!" + ex.Message + "!";
}
collector.Process(inlineFieldInstruction, field);
}
public override void VisitInlineIInstruction(InlineIInstruction inlineIInstruction)
{
collector.Process(inlineIInstruction, inlineIInstruction.Int32.ToString());
}
public override void VisitInlineI8Instruction(InlineI8Instruction inlineI8Instruction)
{
collector.Process(inlineI8Instruction, inlineI8Instruction.Int64.ToString());
}
public override void VisitInlineMethodInstruction(InlineMethodInstruction inlineMethodInstruction)
{
string method;
try
{
method = inlineMethodInstruction.Method + "/" + inlineMethodInstruction.Method.DeclaringType;
}
catch (Exception ex)
{
method = "!" + ex.Message + "!";
}
collector.Process(inlineMethodInstruction, method);
}
public override void VisitInlineNoneInstruction(InlineNoneInstruction inlineNoneInstruction)
{
collector.Process(inlineNoneInstruction, string.Empty);
}
public override void VisitInlineRInstruction(InlineRInstruction inlineRInstruction)
{
collector.Process(inlineRInstruction, inlineRInstruction.Double.ToString());
}
public override void VisitInlineSigInstruction(InlineSigInstruction inlineSigInstruction)
{
collector.Process(inlineSigInstruction, formatProvider.SigByteArrayToString(inlineSigInstruction.Signature));
}
public override void VisitInlineStringInstruction(InlineStringInstruction inlineStringInstruction)
{
collector.Process(inlineStringInstruction, formatProvider.EscapedString(inlineStringInstruction.String));
}
public override void VisitInlineSwitchInstruction(InlineSwitchInstruction inlineSwitchInstruction)
{
collector.Process(inlineSwitchInstruction, formatProvider.MultipleLabels(inlineSwitchInstruction.TargetOffsets));
}
public override void VisitInlineTokInstruction(InlineTokInstruction inlineTokInstruction)
{
string member;
try
{
member = inlineTokInstruction.Member + "/" + inlineTokInstruction.Member.DeclaringType;
}
catch (Exception ex)
{
member = "!" + ex.Message + "!";
}
collector.Process(inlineTokInstruction, member);
}
public override void VisitInlineTypeInstruction(InlineTypeInstruction inlineTypeInstruction)
{
string type;
try
{
type = inlineTypeInstruction.Type.Name;
}
catch (Exception ex)
{
type = "!" + ex.Message + "!";
}
collector.Process(inlineTypeInstruction, type);
}
public override void VisitInlineVarInstruction(InlineVarInstruction inlineVarInstruction)
{
collector.Process(inlineVarInstruction, formatProvider.Argument(inlineVarInstruction.Ordinal));
}
public override void VisitShortInlineBrTargetInstruction(ShortInlineBrTargetInstruction shortInlineBrTargetInstruction)
{
collector.Process(shortInlineBrTargetInstruction, formatProvider.Label(shortInlineBrTargetInstruction.TargetOffset));
}
public override void VisitShortInlineIInstruction(ShortInlineIInstruction shortInlineIInstruction)
{
collector.Process(shortInlineIInstruction, shortInlineIInstruction.Byte.ToString());
}
public override void VisitShortInlineRInstruction(ShortInlineRInstruction shortInlineRInstruction)
{
collector.Process(shortInlineRInstruction, shortInlineRInstruction.Single.ToString());
}
public override void VisitShortInlineVarInstruction(ShortInlineVarInstruction shortInlineVarInstruction)
{
collector.Process(shortInlineVarInstruction, formatProvider.Argument(shortInlineVarInstruction.Ordinal));
}
}
public class RawILStringVisitor : ReadableILStringVisitor
{
public RawILStringVisitor(IILStringCollector collector)
: this(collector, DefaultFormatProvider.Instance)
{
}
public RawILStringVisitor(IILStringCollector collector, IFormatProvider formatProvider)
: base(collector, formatProvider)
{
}
public override void VisitInlineBrTargetInstruction(InlineBrTargetInstruction inlineBrTargetInstruction)
{
collector.Process(inlineBrTargetInstruction, formatProvider.Int32ToHex(inlineBrTargetInstruction.Delta));
}
public override void VisitInlineFieldInstruction(InlineFieldInstruction inlineFieldInstruction)
{
collector.Process(inlineFieldInstruction, formatProvider.Int32ToHex(inlineFieldInstruction.Token));
}
public override void VisitInlineMethodInstruction(InlineMethodInstruction inlineMethodInstruction)
{
collector.Process(inlineMethodInstruction, formatProvider.Int32ToHex(inlineMethodInstruction.Token));
}
public override void VisitInlineSigInstruction(InlineSigInstruction inlineSigInstruction)
{
collector.Process(inlineSigInstruction, formatProvider.Int32ToHex(inlineSigInstruction.Token));
}
public override void VisitInlineStringInstruction(InlineStringInstruction inlineStringInstruction)
{
collector.Process(inlineStringInstruction, formatProvider.Int32ToHex(inlineStringInstruction.Token));
}
public override void VisitInlineSwitchInstruction(InlineSwitchInstruction inlineSwitchInstruction)
{
collector.Process(inlineSwitchInstruction, "...");
}
public override void VisitInlineTokInstruction(InlineTokInstruction inlineTokInstruction)
{
collector.Process(inlineTokInstruction, formatProvider.Int32ToHex(inlineTokInstruction.Token));
}
public override void VisitInlineTypeInstruction(InlineTypeInstruction inlineTypeInstruction)
{
collector.Process(inlineTypeInstruction, formatProvider.Int32ToHex(inlineTypeInstruction.Token));
}
public override void VisitInlineVarInstruction(InlineVarInstruction inlineVarInstruction)
{
collector.Process(inlineVarInstruction, formatProvider.Int16ToHex(inlineVarInstruction.Ordinal));
}
public override void VisitShortInlineBrTargetInstruction(ShortInlineBrTargetInstruction shortInlineBrTargetInstruction)
{
collector.Process(shortInlineBrTargetInstruction, formatProvider.Int8ToHex(shortInlineBrTargetInstruction.Delta));
}
public override void VisitShortInlineVarInstruction(ShortInlineVarInstruction shortInlineVarInstruction)
{
collector.Process(shortInlineVarInstruction, formatProvider.Int8ToHex(shortInlineVarInstruction.Ordinal));
}
}
}
| |
#region License
/* Copyright (c) 2003-2015 Llewellyn Pritchard
* All rights reserved.
* This source code is subject to terms and conditions of the BSD License.
* See license.txt. */
#endregion
#region Includes
using System;
using System.ComponentModel;
using System.Drawing;
using System.Windows.Forms;
#endregion
namespace IronScheme.Editor.Controls
{
class FindDialog : Form
{
AdvancedTextBox atb;
internal string lastfind = string.Empty;
Label label1;
ComboBox comboBox1;
CheckBox checkBox1;
CheckBox checkBox2;
CheckBox checkBox3;
CheckBox checkBox4;
GroupBox groupBox1;
RadioButton radioButton1;
RadioButton radioButton2;
Button button1;
Button button2;
Button button3;
ComboBox comboBox2;
Label label2;
Button button5;
RadioButton radioButton3;
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.Container components = null;
public FindDialog(AdvancedTextBox atb) : this()
{
this.atb = atb;
}
public FindDialog()
{
//
// Required for Windows Form Designer support
//
Font = new Font(SystemInformation.MenuFont.FontFamily, 8.25f);
InitializeComponent();
checkBox1.CheckedChanged +=new EventHandler(checkBox1_CheckedChanged);
checkBox2.CheckedChanged +=new EventHandler(checkBox1_CheckedChanged);
checkBox3.CheckedChanged +=new EventHandler(checkBox1_CheckedChanged);
checkBox4.CheckedChanged +=new EventHandler(checkBox4_CheckedChanged);
}
protected override void OnClosing(CancelEventArgs e)
{
e.Cancel = true;
Hide();
base.OnClosing (e);
}
protected override void OnVisibleChanged(EventArgs e)
{
if (Visible)
{
if (lastfind == string.Empty)
{
comboBox1.Text = atb.SelectionText;
}
button1.Enabled = comboBox1.Text != string.Empty;
button2.Enabled = false;
button5.Enabled = false;
}
base.OnVisibleChanged (e);
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if(components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.label1 = new System.Windows.Forms.Label();
this.comboBox1 = new System.Windows.Forms.ComboBox();
this.checkBox1 = new System.Windows.Forms.CheckBox();
this.checkBox2 = new System.Windows.Forms.CheckBox();
this.checkBox3 = new System.Windows.Forms.CheckBox();
this.checkBox4 = new System.Windows.Forms.CheckBox();
this.groupBox1 = new System.Windows.Forms.GroupBox();
this.radioButton3 = new System.Windows.Forms.RadioButton();
this.radioButton2 = new System.Windows.Forms.RadioButton();
this.radioButton1 = new System.Windows.Forms.RadioButton();
this.button1 = new System.Windows.Forms.Button();
this.button2 = new System.Windows.Forms.Button();
this.button3 = new System.Windows.Forms.Button();
this.comboBox2 = new System.Windows.Forms.ComboBox();
this.label2 = new System.Windows.Forms.Label();
this.button5 = new System.Windows.Forms.Button();
this.groupBox1.SuspendLayout();
this.SuspendLayout();
//
// label1
//
this.label1.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.label1.Location = new System.Drawing.Point(5, 5);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(72, 16);
this.label1.TabIndex = 11;
this.label1.Text = "Find what:";
//
// comboBox1
//
this.comboBox1.Items.AddRange(new object[] {
"public",
"get",
"Entity",
"ess"});
this.comboBox1.Location = new System.Drawing.Point(85, 2);
this.comboBox1.Name = "comboBox1";
this.comboBox1.Size = new System.Drawing.Size(211, 21);
this.comboBox1.TabIndex = 0;
this.comboBox1.Text = "public";
this.comboBox1.TextChanged += new System.EventHandler(this.comboBox1_TextChanged);
//
// checkBox1
//
this.checkBox1.Checked = true;
this.checkBox1.CheckState = System.Windows.Forms.CheckState.Checked;
this.checkBox1.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.checkBox1.Location = new System.Drawing.Point(6, 48);
this.checkBox1.Name = "checkBox1";
this.checkBox1.Size = new System.Drawing.Size(128, 22);
this.checkBox1.TabIndex = 2;
this.checkBox1.Text = "Match case";
//
// checkBox2
//
this.checkBox2.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.checkBox2.Location = new System.Drawing.Point(6, 67);
this.checkBox2.Name = "checkBox2";
this.checkBox2.Size = new System.Drawing.Size(128, 22);
this.checkBox2.TabIndex = 3;
this.checkBox2.Text = "Match token";
//
// checkBox3
//
this.checkBox3.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.checkBox3.Location = new System.Drawing.Point(6, 86);
this.checkBox3.Name = "checkBox3";
this.checkBox3.Size = new System.Drawing.Size(128, 22);
this.checkBox3.TabIndex = 4;
this.checkBox3.Text = "Search Up";
//
// checkBox4
//
this.checkBox4.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.checkBox4.Location = new System.Drawing.Point(6, 105);
this.checkBox4.Name = "checkBox4";
this.checkBox4.Size = new System.Drawing.Size(128, 22);
this.checkBox4.TabIndex = 5;
this.checkBox4.Text = "Regular Expression";
//
// groupBox1
//
this.groupBox1.Controls.Add(this.radioButton3);
this.groupBox1.Controls.Add(this.radioButton2);
this.groupBox1.Controls.Add(this.radioButton1);
this.groupBox1.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.groupBox1.Location = new System.Drawing.Point(131, 48);
this.groupBox1.Name = "groupBox1";
this.groupBox1.Size = new System.Drawing.Size(162, 76);
this.groupBox1.TabIndex = 6;
this.groupBox1.TabStop = false;
this.groupBox1.Text = "Search";
//
// radioButton3
//
this.radioButton3.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.radioButton3.Location = new System.Drawing.Point(4, 56);
this.radioButton3.Name = "radioButton3";
this.radioButton3.Size = new System.Drawing.Size(104, 16);
this.radioButton3.TabIndex = 2;
this.radioButton3.Text = "All Documents";
//
// radioButton2
//
this.radioButton2.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.radioButton2.Location = new System.Drawing.Point(4, 36);
this.radioButton2.Name = "radioButton2";
this.radioButton2.Size = new System.Drawing.Size(104, 16);
this.radioButton2.TabIndex = 1;
this.radioButton2.Text = "Selection";
//
// radioButton1
//
this.radioButton1.Checked = true;
this.radioButton1.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.radioButton1.Location = new System.Drawing.Point(4, 16);
this.radioButton1.Name = "radioButton1";
this.radioButton1.Size = new System.Drawing.Size(128, 16);
this.radioButton1.TabIndex = 0;
this.radioButton1.TabStop = true;
this.radioButton1.Text = "Current Document";
//
// button1
//
this.button1.BackColor = System.Drawing.SystemColors.Control;
this.button1.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.button1.Location = new System.Drawing.Point(301, 2);
this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size(75, 26);
this.button1.TabIndex = 7;
this.button1.Text = "Find next";
this.button1.UseVisualStyleBackColor = false;
this.button1.Click += new System.EventHandler(this.button1_Click);
//
// button2
//
this.button2.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.button2.Location = new System.Drawing.Point(301, 34);
this.button2.Name = "button2";
this.button2.Size = new System.Drawing.Size(75, 26);
this.button2.TabIndex = 8;
this.button2.Text = "Replace";
this.button2.Click += new System.EventHandler(this.button2_Click);
//
// button3
//
this.button3.DialogResult = System.Windows.Forms.DialogResult.Cancel;
this.button3.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.button3.Location = new System.Drawing.Point(301, 98);
this.button3.Name = "button3";
this.button3.Size = new System.Drawing.Size(75, 26);
this.button3.TabIndex = 10;
this.button3.Text = "Close";
this.button3.Click += new System.EventHandler(this.button3_Click);
//
// comboBox2
//
this.comboBox2.Location = new System.Drawing.Point(85, 26);
this.comboBox2.Name = "comboBox2";
this.comboBox2.Size = new System.Drawing.Size(211, 21);
this.comboBox2.TabIndex = 1;
this.comboBox2.TextChanged += new System.EventHandler(this.comboBox2_TextChanged);
//
// label2
//
this.label2.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.label2.Location = new System.Drawing.Point(5, 30);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(80, 16);
this.label2.TabIndex = 10;
this.label2.Text = "Replace with:";
//
// button5
//
this.button5.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.button5.Location = new System.Drawing.Point(301, 66);
this.button5.Name = "button5";
this.button5.Size = new System.Drawing.Size(75, 26);
this.button5.TabIndex = 9;
this.button5.Text = "Replace all";
//
// FindDialog
//
this.AcceptButton = this.button1;
this.CancelButton = this.button3;
this.ClientSize = new System.Drawing.Size(380, 127);
this.Controls.Add(this.button5);
this.Controls.Add(this.comboBox2);
this.Controls.Add(this.label2);
this.Controls.Add(this.button3);
this.Controls.Add(this.button2);
this.Controls.Add(this.button1);
this.Controls.Add(this.groupBox1);
this.Controls.Add(this.checkBox4);
this.Controls.Add(this.checkBox3);
this.Controls.Add(this.checkBox2);
this.Controls.Add(this.checkBox1);
this.Controls.Add(this.comboBox1);
this.Controls.Add(this.label1);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedToolWindow;
this.MaximizeBox = false;
this.MinimizeBox = false;
this.Name = "FindDialog";
this.ShowInTaskbar = false;
this.StartPosition = System.Windows.Forms.FormStartPosition.Manual;
this.Text = "Find";
this.TopMost = true;
this.groupBox1.ResumeLayout(false);
this.ResumeLayout(false);
}
#endregion
private void button3_Click(object sender, System.EventArgs e)
{
Hide();
}
private void button1_Click(object sender, System.EventArgs e)
{
button1.BackColor = SystemColors.Control;
RichTextBoxFinds options = 0;
int end = atb.TextLength - 1;
int start = atb.SelectionStart + atb.SelectionLength;
if (checkBox1.Checked)
{
options |= RichTextBoxFinds.MatchCase;
}
if(checkBox2.Checked)
{
options |= RichTextBoxFinds.WholeWord;
}
if(checkBox3.Checked)
{
options |= RichTextBoxFinds.Reverse;
end = start - 1;
start = 0;
}
if(checkBox4.Checked)
{
options |= RichTextBoxFinds.NoHighlight;
}
int pos;
string pat = lastfind = comboBox1.Text;
pos = atb.Find(pat, start, end, options);
if (pos != -1)
{
atb.Select(pos, pat.Length);
atb.ScrollToCaret();
}
else
{
button1.Enabled = false;
}
}
private void button2_Click(object sender, System.EventArgs e)
{
if (atb.SelectionLength > 0)
{
atb.SelectionText = comboBox2.Text;
atb.Invalidate();
}
}
private void comboBox1_TextChanged(object sender, EventArgs e)
{
button1.Enabled = comboBox1.Text != string.Empty;
}
private void comboBox2_TextChanged(object sender, EventArgs e)
{
button5.Enabled = button2.Enabled = comboBox2.Text != string.Empty;
}
private void checkBox1_CheckedChanged(object sender, EventArgs e)
{
button1.Enabled = comboBox1.Text != string.Empty;
}
private void checkBox4_CheckedChanged(object sender, EventArgs e)
{
button1.Enabled = comboBox1.Text != string.Empty;
if (checkBox4.Checked)
{
checkBox1.Enabled = false;
checkBox2.Enabled = false;
}
else
{
checkBox1.Enabled = true;
checkBox2.Enabled = true;
}
}
}
}
| |
#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;
using System.Linq;
using System.Globalization;
namespace Newtonsoft.Json.Utilities
{
internal static class CollectionUtils
{
public static IEnumerable<T> CastValid<T>(this IEnumerable enumerable)
{
ValidationUtils.ArgumentNotNull(enumerable, "enumerable");
return enumerable.Cast<object>().Where(o => o is T).Cast<T>();
}
public static List<T> CreateList<T>(params T[] values)
{
return new List<T>(values);
}
/// <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(ICollection collection)
{
if (collection != null)
{
return (collection.Count == 0);
}
return true;
}
/// <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>
/// Determines whether the collection is null, empty or its contents are uninitialized values.
/// </summary>
/// <param name="list">The list.</param>
/// <returns>
/// <c>true</c> if the collection is null or empty or its contents are uninitialized values; otherwise, <c>false</c>.
/// </returns>
public static bool IsNullOrEmptyOrDefault<T>(IList<T> list)
{
if (IsNullOrEmpty<T>(list))
return true;
return ReflectionUtils.ItemsUnitializedValue<T>(list);
}
/// <summary>
/// Makes a slice of the specified list in between the start and end indexes.
/// </summary>
/// <param name="list">The list.</param>
/// <param name="start">The start index.</param>
/// <param name="end">The end index.</param>
/// <returns>A slice of the list.</returns>
public static IList<T> Slice<T>(IList<T> list, int? start, int? end)
{
return Slice<T>(list, start, end, null);
}
/// <summary>
/// Makes a slice of the specified list in between the start and end indexes,
/// getting every so many items based upon the step.
/// </summary>
/// <param name="list">The list.</param>
/// <param name="start">The start index.</param>
/// <param name="end">The end index.</param>
/// <param name="step">The step.</param>
/// <returns>A slice of the list.</returns>
public static IList<T> Slice<T>(IList<T> list, int? start, int? end, int? step)
{
if (list == null)
throw new ArgumentNullException("list");
if (step == 0)
throw new ArgumentException("Step cannot be zero.", "step");
List<T> slicedList = new List<T>();
// nothing to slice
if (list.Count == 0)
return slicedList;
// set defaults for null arguments
int s = step ?? 1;
int startIndex = start ?? 0;
int endIndex = end ?? list.Count;
// start from the end of the list if start is negitive
startIndex = (startIndex < 0) ? list.Count + startIndex : startIndex;
// end from the start of the list if end is negitive
endIndex = (endIndex < 0) ? list.Count + endIndex : endIndex;
// ensure indexes keep within collection bounds
startIndex = Math.Max(startIndex, 0);
endIndex = Math.Min(endIndex, list.Count - 1);
// loop between start and end indexes, incrementing by the step
for (int i = startIndex; i < endIndex; i += s)
{
slicedList.Add(list[i]);
}
return slicedList;
}
/// <summary>
/// Group the collection using a function which returns the key.
/// </summary>
/// <param name="source">The source collection to group.</param>
/// <param name="keySelector">The key selector.</param>
/// <returns>A Dictionary with each key relating to a list of objects in a list grouped under it.</returns>
public static Dictionary<K, List<V>> GroupBy<K, V>(ICollection<V> source, Func<V, K> keySelector)
{
if (keySelector == null)
throw new ArgumentNullException("keySelector");
Dictionary<K, List<V>> groupedValues = new Dictionary<K, List<V>>();
foreach (V value in source)
{
// using delegate to get the value's key
K key = keySelector(value);
List<V> groupedValueList;
// add a list for grouped values if the key is not already in Dictionary
if (!groupedValues.TryGetValue(key, out groupedValueList))
{
groupedValueList = new List<V>();
groupedValues.Add(key, groupedValueList);
}
groupedValueList.Add(value);
}
return groupedValues;
}
/// <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);
}
}
public static void AddRange(this IList initial, IEnumerable collection)
{
ValidationUtils.ArgumentNotNull(initial, "initial");
ListWrapper<object> wrapper = new ListWrapper<object>(initial);
wrapper.AddRange(collection.Cast<object>());
}
public static List<T> Distinct<T>(List<T> collection)
{
List<T> distinctList = new List<T>();
foreach (T value in collection)
{
if (!distinctList.Contains(value))
distinctList.Add(value);
}
return distinctList;
}
public static List<List<T>> Flatten<T>(params IList<T>[] lists)
{
List<List<T>> flattened = new List<List<T>>();
Dictionary<int, T> currentList = new Dictionary<int, T>();
Recurse<T>(new List<IList<T>>(lists), 0, currentList, flattened);
return flattened;
}
private static void Recurse<T>(IList<IList<T>> global, int current, Dictionary<int, T> currentSet, List<List<T>> flattenedResult)
{
IList<T> currentArray = global[current];
for (int i = 0; i < currentArray.Count; i++)
{
currentSet[current] = currentArray[i];
if (current == global.Count - 1)
{
List<T> items = new List<T>();
for (int k = 0; k < currentSet.Count; k++)
{
items.Add(currentSet[k]);
}
flattenedResult.Add(items);
}
else
{
Recurse(global, current + 1, currentSet, flattenedResult);
}
}
}
public static List<T> CreateList<T>(ICollection collection)
{
if (collection == null)
throw new ArgumentNullException("collection");
T[] array = new T[collection.Count];
collection.CopyTo(array, 0);
return new List<T>(array);
}
public static bool ListEquals<T>(IList<T> a, IList<T> b)
{
if (a == null || b == null)
return (a == null && b == null);
if (a.Count != b.Count)
return false;
EqualityComparer<T> comparer = EqualityComparer<T>.Default;
for (int i = 0; i < a.Count; i++)
{
if (!comparer.Equals(a[i], b[i]))
return false;
}
return true;
}
#region GetSingleItem
public static bool TryGetSingleItem<T>(IList<T> list, out T value)
{
return TryGetSingleItem<T>(list, false, out value);
}
public static bool TryGetSingleItem<T>(IList<T> list, bool returnDefaultIfEmpty, out T value)
{
return MiscellaneousUtils.TryAction<T>(delegate { return GetSingleItem(list, returnDefaultIfEmpty); }, out value);
}
public static T GetSingleItem<T>(IList<T> list)
{
return GetSingleItem<T>(list, false);
}
public static T GetSingleItem<T>(IList<T> list, bool returnDefaultIfEmpty)
{
if (list.Count == 1)
return list[0];
else if (returnDefaultIfEmpty && list.Count == 0)
return default(T);
else
throw new Exception("Expected single {0} in list but got {1}.".FormatWith(CultureInfo.InvariantCulture, typeof(T), list.Count));
}
#endregion
public static IList<T> Minus<T>(IList<T> list, IList<T> minus)
{
ValidationUtils.ArgumentNotNull(list, "list");
List<T> result = new List<T>(list.Count);
foreach (T t in list)
{
if (minus == null || !minus.Contains(t))
result.Add(t);
}
return result;
}
public static IList CreateGenericList(Type listType)
{
ValidationUtils.ArgumentNotNull(listType, "listType");
return (IList)ReflectionUtils.CreateGeneric(typeof(List<>), listType);
}
public static IDictionary CreateGenericDictionary(Type keyType, Type valueType)
{
ValidationUtils.ArgumentNotNull(keyType, "keyType");
ValidationUtils.ArgumentNotNull(valueType, "valueType");
return (IDictionary)ReflectionUtils.CreateGeneric(typeof(Dictionary<,>), keyType, valueType);
}
public static bool IsListType(Type type)
{
ValidationUtils.ArgumentNotNull(type, "type");
if (type.IsArray)
return true;
if (typeof(IList).IsAssignableFrom(type))
return true;
if (ReflectionUtils.ImplementsGenericDefinition(type, typeof(IList<>)))
return true;
return false;
}
public static bool IsCollectionType(Type type)
{
ValidationUtils.ArgumentNotNull(type, "type");
if (type.IsArray)
return true;
if (typeof(ICollection).IsAssignableFrom(type))
return true;
if (ReflectionUtils.ImplementsGenericDefinition(type, typeof(ICollection<>)))
return true;
return false;
}
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 IWrappedCollection CreateCollectionWrapper(object list)
{
ValidationUtils.ArgumentNotNull(list, "list");
Type collectionDefinition;
if (ReflectionUtils.ImplementsGenericDefinition(list.GetType(), typeof(ICollection<>), out collectionDefinition))
{
Type collectionItemType = ReflectionUtils.GetCollectionItemType(collectionDefinition);
// Activator.CreateInstance throws AmbiguousMatchException. Manually invoke constructor
Func<Type, IList<object>, object> instanceCreator = (t, a) =>
{
ConstructorInfo c = t.GetConstructor(new[] { collectionDefinition });
return c.Invoke(new[] { list });
};
return (IWrappedCollection)ReflectionUtils.CreateGeneric(typeof(CollectionWrapper<>), new[] { collectionItemType }, instanceCreator, list);
}
else if (list is IList)
{
return new CollectionWrapper<object>((IList)list);
}
else
{
throw new Exception("Can not create ListWrapper for type {0}.".FormatWith(CultureInfo.InvariantCulture, list.GetType()));
}
}
public static IWrappedList CreateListWrapper(object list)
{
ValidationUtils.ArgumentNotNull(list, "list");
Type listDefinition;
if (ReflectionUtils.ImplementsGenericDefinition(list.GetType(), typeof(IList<>), out listDefinition))
{
Type collectionItemType = ReflectionUtils.GetCollectionItemType(listDefinition);
// Activator.CreateInstance throws AmbiguousMatchException. Manually invoke constructor
Func<Type, IList<object>, object> instanceCreator = (t, a) =>
{
ConstructorInfo c = t.GetConstructor(new[] {listDefinition});
return c.Invoke(new[] { list });
};
return (IWrappedList)ReflectionUtils.CreateGeneric(typeof(ListWrapper<>), new[] { collectionItemType }, instanceCreator, list);
}
else if (list is IList)
{
return new ListWrapper<object>((IList)list);
}
else
{
throw new Exception("Can not create ListWrapper for type {0}.".FormatWith(CultureInfo.InvariantCulture, list.GetType()));
}
}
public static IWrappedDictionary CreateDictionaryWrapper(object dictionary)
{
ValidationUtils.ArgumentNotNull(dictionary, "dictionary");
Type dictionaryDefinition;
if (ReflectionUtils.ImplementsGenericDefinition(dictionary.GetType(), typeof(IDictionary<,>), out dictionaryDefinition))
{
Type dictionaryKeyType = ReflectionUtils.GetDictionaryKeyType(dictionaryDefinition);
Type dictionaryValueType = ReflectionUtils.GetDictionaryValueType(dictionaryDefinition);
// Activator.CreateInstance throws AmbiguousMatchException. Manually invoke constructor
Func<Type, IList<object>, object> instanceCreator = (t, a) =>
{
ConstructorInfo c = t.GetConstructor(new[] { dictionaryDefinition });
return c.Invoke(new[] { dictionary });
};
return (IWrappedDictionary)ReflectionUtils.CreateGeneric(typeof(DictionaryWrapper<,>), new[] { dictionaryKeyType, dictionaryValueType }, instanceCreator, dictionary);
}
else if (dictionary is IDictionary)
{
return new DictionaryWrapper<object, object>((IDictionary)dictionary);
}
else
{
throw new Exception("Can not create DictionaryWrapper for type {0}.".FormatWith(CultureInfo.InvariantCulture, dictionary.GetType()));
}
}
public static object CreateAndPopulateList(Type listType, Action<IList, bool> populateList)
{
ValidationUtils.ArgumentNotNull(listType, "listType");
ValidationUtils.ArgumentNotNull(populateList, "populateList");
IList list;
Type collectionType;
bool isReadOnlyOrFixedSize = false;
if (listType.IsArray)
{
// have to use an arraylist when creating array
// there is no way to know the size until it is finised
list = new List<object>();
isReadOnlyOrFixedSize = true;
}
else if (ReflectionUtils.InheritsGenericDefinition(listType, typeof(ReadOnlyCollection<>), out collectionType))
{
Type readOnlyCollectionContentsType = collectionType.GetGenericArguments()[0];
Type genericEnumerable = ReflectionUtils.MakeGenericType(typeof(IEnumerable<>), readOnlyCollectionContentsType);
bool suitableConstructor = false;
foreach (ConstructorInfo constructor in listType.GetConstructors())
{
IList<ParameterInfo> parameters = constructor.GetParameters();
if (parameters.Count == 1)
{
if (genericEnumerable.IsAssignableFrom(parameters[0].ParameterType))
{
suitableConstructor = true;
break;
}
}
}
if (!suitableConstructor)
throw new Exception("Read-only type {0} does not have a public constructor that takes a type that implements {1}.".FormatWith(CultureInfo.InvariantCulture, listType, genericEnumerable));
// can't add or modify a readonly list
// use List<T> and convert once populated
list = CreateGenericList(readOnlyCollectionContentsType);
isReadOnlyOrFixedSize = true;
}
else if (typeof(IList).IsAssignableFrom(listType))
{
if (ReflectionUtils.IsInstantiatableType(listType))
list = (IList)Activator.CreateInstance(listType);
else if (listType == typeof(IList))
list = new List<object>();
else
list = null;
}
else if (ReflectionUtils.ImplementsGenericDefinition(listType, typeof(ICollection<>)))
{
if (ReflectionUtils.IsInstantiatableType(listType))
list = CreateCollectionWrapper(Activator.CreateInstance(listType));
else
list = null;
}
else
{
list = null;
}
if (list == null)
throw new Exception("Cannot create and populate list type {0}.".FormatWith(CultureInfo.InvariantCulture, listType));
populateList(list, isReadOnlyOrFixedSize);
// create readonly and fixed sized collections using the temporary list
if (isReadOnlyOrFixedSize)
{
if (listType.IsArray)
list = ToArray(((List<object>)list).ToArray(), ReflectionUtils.GetCollectionItemType(listType));
else if (ReflectionUtils.InheritsGenericDefinition(listType, typeof(ReadOnlyCollection<>)))
list = (IList)ReflectionUtils.CreateInstance(listType, list);
}
else if (list is IWrappedCollection)
{
return ((IWrappedCollection) list).UnderlyingCollection;
}
return list;
}
public static Array ToArray(Array initial, Type type)
{
if (type == null)
throw new ArgumentNullException("type");
Array destinationArray = Array.CreateInstance(type, initial.Length);
Array.Copy(initial, 0, destinationArray, 0, initial.Length);
return destinationArray;
}
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)
{
return list.AddRangeDistinct(values, EqualityComparer<T>.Default);
}
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;
}
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="ChtmlCalendarAdapter.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
using System;
using System.Globalization;
using System.IO;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.MobileControls;
using System.Web.UI.MobileControls.Adapters;
using System.Web.UI.WebControls;
using System.Diagnostics;
using System.Collections;
using System.Security.Permissions;
#if COMPILING_FOR_SHIPPED_SOURCE
namespace System.Web.UI.MobileControls.ShippedAdapterSource
#else
namespace System.Web.UI.MobileControls.Adapters
#endif
{
/*
* ChtmlCalendarAdapter provides the cHTML device functionality for Calendar
* control. It is using secondary UI support to provide internal screens
* to allow the user to pick or enter a date.
*
* Copyright (c) 2000 Microsoft Corporation
*/
/// <include file='doc\ChtmlCalendarAdapter.uex' path='docs/doc[@for="ChtmlCalendarAdapter"]/*' />
[AspNetHostingPermission(SecurityAction.LinkDemand, Level=AspNetHostingPermissionLevel.Minimal)]
[AspNetHostingPermission(SecurityAction.InheritanceDemand, Level=AspNetHostingPermissionLevel.Minimal)]
[Obsolete("The System.Web.Mobile.dll assembly has been deprecated and should no longer be used. For information about how to develop ASP.NET mobile applications, see http://go.microsoft.com/fwlink/?LinkId=157231.")]
public class ChtmlCalendarAdapter : HtmlControlAdapter
{
private SelectionList _selectList;
private TextBox _textBox;
private Command _command;
private List _optionList;
private List _monthList;
private List _weekList;
private List _dayList;
private int _chooseOption = FirstPrompt;
private int _monthsToDisplay;
private int _eraCount = 0;
private bool _requireFormTag = false;
/////////////////////////////////////////////////////////////////////
// Globalization of Calendar Information:
// Similar to the globalization support of the ASP.NET Calendar control,
// this support is done via COM+ thread culture info/object.
// Specific example can be found from ASP.NET Calendar spec.
/////////////////////////////////////////////////////////////////////
// This member variable is set each time when calendar info needs to
// be accessed and be shared for other helper functions.
private Globalization.Calendar _threadCalendar;
private String _textBoxErrorMessage;
// Since SecondaryUIMode is an int type, we use constant integers here
// instead of enum so the mode can be compared without casting.
private const int FirstPrompt = NotSecondaryUIInit;
private const int OptionPrompt = NotSecondaryUIInit + 1;
private const int TypeDate = NotSecondaryUIInit + 2;
private const int DateOption = NotSecondaryUIInit + 3;
private const int WeekOption = NotSecondaryUIInit + 4;
private const int MonthOption = NotSecondaryUIInit + 5;
private const int ChooseMonth = NotSecondaryUIInit + 6;
private const int ChooseWeek = NotSecondaryUIInit + 7;
private const int ChooseDay = NotSecondaryUIInit + 8;
private const int DefaultDateDone = NotSecondaryUIInit + 9;
private const int TypeDateDone = NotSecondaryUIInit + 10;
private const int Done = NotSecondaryUIInit + 11;
private const String DaySeparator = " - ";
private const String Space = " ";
/// <include file='doc\ChtmlCalendarAdapter.uex' path='docs/doc[@for="ChtmlCalendarAdapter.Control"]/*' />
protected new Calendar Control
{
get
{
return (Calendar)base.Control;
}
}
/// <include file='doc\ChtmlCalendarAdapter.uex' path='docs/doc[@for="ChtmlCalendarAdapter.RequiresFormTag"]/*' />
public override bool RequiresFormTag
{
get
{
return _requireFormTag;
}
}
/// <include file='doc\ChtmlCalendarAdapter.uex' path='docs/doc[@for="ChtmlCalendarAdapter.OnInit"]/*' />
public override void OnInit(EventArgs e)
{
ListCommandEventHandler listCommandEventHandler;
// Create secondary child controls for rendering secondary UI.
// Note that their ViewState is disabled because they are used
// for rendering only.
//---------------------------------------------------------------
_selectList = new SelectionList();
_selectList.Visible = false;
_selectList.EnableViewState = false;
Control.Controls.Add(_selectList);
_textBox = new TextBox();
_textBox.Visible = false;
_textBox.EnableViewState = false;
EventHandler eventHandler = new EventHandler(this.TextBoxEventHandler);
_textBox.TextChanged += eventHandler;
Control.Controls.Add(_textBox);
_command = new Command();
_command.Visible = false;
_command.EnableViewState = false;
Control.Controls.Add(_command);
// Below are initialization of several list controls. A note is
// that here the usage of DataMember is solely for remembering
// how many items a particular list control is bounded to. The
// property is not used as originally designed.
//---------------------------------------------------------------
_optionList = new List();
_optionList.DataMember = "5";
listCommandEventHandler = new ListCommandEventHandler(this.OptionListEventHandler);
InitList(_optionList, listCommandEventHandler);
// Use MobileCapabilities to check screen size and determine how
// many months should be displayed for different devices.
_monthsToDisplay = MonthsToDisplay(Device.ScreenCharactersHeight);
// Create the list of months, including [Next] and [Prev] links
_monthList = new List();
_monthList.DataMember = Convert.ToString(_monthsToDisplay + 2, CultureInfo.InvariantCulture);
listCommandEventHandler = new ListCommandEventHandler(this.MonthListEventHandler);
InitList(_monthList, listCommandEventHandler);
_weekList = new List();
_weekList.DataMember = "6";
listCommandEventHandler = new ListCommandEventHandler(this.WeekListEventHandler);
InitList(_weekList, listCommandEventHandler);
_dayList = new List();
_dayList.DataMember = "7";
listCommandEventHandler = new ListCommandEventHandler(this.DayListEventHandler);
InitList(_dayList, listCommandEventHandler);
// Initialize the VisibleDate which will be used to keep track
// the ongoing selection of year, month and day from multiple
// secondary UI screens. If the page is loaded for the first
// time, it doesn't need to be initialized (since it is not used
// yet) so no unnecessary viewstate value will be generated.
if (Page.IsPostBack && Control.VisibleDate == DateTime.MinValue)
{
Control.VisibleDate = DateTime.Today;
}
}
/// <include file='doc\ChtmlCalendarAdapter.uex' path='docs/doc[@for="ChtmlCalendarAdapter.OnLoad"]/*' />
public override void OnLoad(EventArgs e)
{
base.OnLoad(e);
// Here we check to see which list control should be initialized
// with items so postback event can be handled properly.
if (Page.IsPostBack)
{
String controlId = Page.Request[Constants.EventSourceID];
if (controlId != null && controlId.Length != 0)
{
List list = Page.FindControl(controlId) as List;
if (list != null &&
Control.Controls.Contains(list))
{
DataBindListWithEmptyValues(
list, Convert.ToInt32(list.DataMember, CultureInfo.InvariantCulture));
}
}
}
}
/// <include file='doc\ChtmlCalendarAdapter.uex' path='docs/doc[@for="ChtmlCalendarAdapter.LoadAdapterState"]/*' />
public override void LoadAdapterState(Object state)
{
if (state != null)
{
if (state is Pair)
{
Pair pair = (Pair)state;
base.LoadAdapterState(pair.First);
_chooseOption = (int)pair.Second;
}
else if (state is Triplet)
{
Triplet triplet = (Triplet)state;
base.LoadAdapterState(triplet.First);
_chooseOption = (int)triplet.Second;
Control.VisibleDate = new DateTime(Int64.Parse((String)triplet.Third, CultureInfo.InvariantCulture));
}
else if (state is Object[])
{
Object[] viewState = (Object[])state;
base.LoadAdapterState(viewState[0]);
_chooseOption = (int)viewState[1];
Control.VisibleDate = new DateTime(Int64.Parse((String)viewState[2], CultureInfo.InvariantCulture));
_eraCount = (int)viewState[3];
if (SecondaryUIMode == TypeDate)
{
// Create a placeholder list for capturing the selected era
// in postback data.
for (int i = 0; i < _eraCount; i++)
{
_selectList.Items.Add(String.Empty);
}
}
}
else
{
_chooseOption = (int)state;
}
}
}
/// <include file='doc\ChtmlCalendarAdapter.uex' path='docs/doc[@for="ChtmlCalendarAdapter.SaveAdapterState"]/*' />
public override Object SaveAdapterState()
{
DateTime visibleDate = Control.VisibleDate;
bool saveVisibleDate = visibleDate != DateTime.MinValue &&
DateTime.Compare(visibleDate, DateTime.Today) != 0 &&
!IsViewStateEnabled();
Object baseState = base.SaveAdapterState();
if (baseState == null && !saveVisibleDate && _eraCount == 0)
{
if (_chooseOption != FirstPrompt)
{
return _chooseOption;
}
else
{
return null;
}
}
else if (!saveVisibleDate && _eraCount == 0)
{
return new Pair(baseState, _chooseOption);
}
else if (_eraCount == 0)
{
return new Triplet(baseState, _chooseOption, visibleDate.Ticks.ToString(CultureInfo.InvariantCulture));
}
else
{
return new Object[] { baseState,
_chooseOption,
visibleDate.Ticks.ToString(CultureInfo.InvariantCulture),
_eraCount };
}
}
/// <include file='doc\ChtmlCalendarAdapter.uex' path='docs/doc[@for="ChtmlCalendarAdapter.OnPreRender"]/*' />
public override void OnPreRender(EventArgs e)
{
base.OnPreRender(e);
// We specially binding eras of the current calendar object here
// when the UI of typing date is display. We do it only if the
// calendar supports more than one era.
if (SecondaryUIMode == TypeDate)
{
DateTimeFormatInfo currentInfo = DateTimeFormatInfo.CurrentInfo;
int [] ints = currentInfo.Calendar.Eras;
if (ints.Length > 1)
{
// Save the value in private view state
_eraCount = ints.Length;
int currentEra;
if (_selectList.SelectedIndex != -1)
{
currentEra = ints[_selectList.SelectedIndex];
}
else
{
currentEra =
currentInfo.Calendar.GetEra(Control.VisibleDate);
}
// Clear the placeholder item list if created in LoadAdapterState
_selectList.Items.Clear();
for (int i = 0; i < ints.Length; i++)
{
int era = ints[i];
_selectList.Items.Add(currentInfo.GetEraName(era));
// There is no association between the era value and
// its index in the era array, so we need to check it
// explicitly for the default selected index.
if (currentEra == era)
{
_selectList.SelectedIndex = i;
}
}
_selectList.Visible = true;
}
else
{
// disable viewstate since no need to save any data for
// this control
_selectList.EnableViewState = false;
}
}
else
{
_selectList.EnableViewState = false;
}
}
/// <include file='doc\ChtmlCalendarAdapter.uex' path='docs/doc[@for="ChtmlCalendarAdapter.Render"]/*' />
public override void Render(HtmlMobileTextWriter writer)
{
ArrayList arr;
DateTime tempDate;
DateTimeFormatInfo currentDateTimeInfo = DateTimeFormatInfo.CurrentInfo;
String abbreviatedMonthDayPattern = AbbreviateMonthPattern(currentDateTimeInfo.MonthDayPattern);
_threadCalendar = currentDateTimeInfo.Calendar;
bool breakAfter = false;
writer.EnterStyle(Style);
Debug.Assert(NotSecondaryUI == NotSecondaryUIInit);
switch (SecondaryUIMode)
{
case FirstPrompt:
String promptText = Control.CalendarEntryText;
if (String.IsNullOrEmpty(promptText))
{
promptText = SR.GetString(SR.CalendarAdapterFirstPrompt);
}
// Link to input option selection screen
RenderPostBackEventAsAnchor(writer,
OptionPrompt.ToString(CultureInfo.InvariantCulture),
promptText);
// We should honor BreakAfter property here as the first
// UI is shown with other controls on the same form.
// For other secondary UI, it is not necessary.
if (Control.BreakAfter)
{
breakAfter = true;
}
break;
// Render the first secondary page that provides differnt
// options to select a date.
case OptionPrompt:
writer.Write(SR.GetString(SR.CalendarAdapterOptionPrompt));
writer.WriteBreak();
arr = new ArrayList();
// Option to select the default date
arr.Add(Control.VisibleDate.ToString(
currentDateTimeInfo.ShortDatePattern, CultureInfo.CurrentCulture));
// Option to another page that can enter a date by typing
arr.Add(SR.GetString(SR.CalendarAdapterOptionType));
// Options to a set of pages for selecting a date, a week
// or a month by picking month/year, week and day
// accordingly. Available options are determined by
// SelectionMode.
arr.Add(SR.GetString(SR.CalendarAdapterOptionChooseDate));
if (Control.SelectionMode == CalendarSelectionMode.DayWeek ||
Control.SelectionMode == CalendarSelectionMode.DayWeekMonth)
{
arr.Add(SR.GetString(SR.CalendarAdapterOptionChooseWeek));
if (Control.SelectionMode == CalendarSelectionMode.DayWeekMonth)
{
arr.Add(SR.GetString(SR.CalendarAdapterOptionChooseMonth));
}
}
DataBindAndRender(writer, _optionList, arr);
break;
// Render a title and textbox to capture a date entered by user
case TypeDate:
if (_textBoxErrorMessage != null)
{
writer.Write(_textBoxErrorMessage);
writer.WriteBreak();
}
if (_selectList.Visible)
{
writer.Write(SR.GetString(SR.CalendarAdapterOptionEra));
writer.WriteBreak();
_selectList.RenderControl(writer);
}
String numericDateFormat = GetNumericDateFormat();
writer.Write(SR.GetString(SR.CalendarAdapterOptionType));
writer.Write(":");
writer.WriteBreak();
writer.Write("(");
writer.Write(numericDateFormat.ToUpper(CultureInfo.InvariantCulture));
writer.Write(")");
if (!_selectList.Visible)
{
writer.Write(GetEra(Control.VisibleDate));
}
writer.WriteBreak();
_textBox.Numeric = true;
_textBox.Size = numericDateFormat.Length;
_textBox.MaxLength = numericDateFormat.Length;
_textBox.Text = Control.VisibleDate.ToString(numericDateFormat, CultureInfo.InvariantCulture);
_textBox.Visible = true;
_textBox.RenderControl(writer);
// Command button for sending the textbox value back to the server
_command.Text = GetDefaultLabel(OKLabel);
_command.Visible = true;
_command.RenderControl(writer);
break;
// Render a paged list for choosing a month
case ChooseMonth:
writer.Write(SR.GetString(SR.CalendarAdapterOptionChooseMonth));
writer.Write(":");
writer.WriteBreak();
tempDate = Control.VisibleDate;
String abbreviatedYearMonthPattern = AbbreviateMonthPattern(currentDateTimeInfo.YearMonthPattern);
// This is to be consistent with ASP.NET Calendar control
// on handling YearMonthPattern:
// Some cultures have a comma in their YearMonthPattern,
// which does not look right in a calendar. Here we
// strip the comma off.
int indexComma = abbreviatedYearMonthPattern.IndexOf(',');
if (indexComma >= 0)
{
abbreviatedYearMonthPattern =
abbreviatedYearMonthPattern.Remove(indexComma, 1);
}
arr = new ArrayList();
for (int i = 0; i < _monthsToDisplay; i++)
{
arr.Add(tempDate.ToString(abbreviatedYearMonthPattern, CultureInfo.CurrentCulture));
tempDate = _threadCalendar.AddMonths(tempDate, 1);
}
arr.Add(GetDefaultLabel(NextLabel));
arr.Add(GetDefaultLabel(PreviousLabel));
DataBindAndRender(writer, _monthList, arr);
break;
// Based on the month selected in case ChooseMonth above, render a list of
// availabe weeks of the month.
case ChooseWeek:
String monthFormat = (GetNumericDateFormat()[0] == 'y') ? "yyyy/M" : "M/yyyy";
writer.Write(SR.GetString(SR.CalendarAdapterOptionChooseWeek));
writer.Write(" (");
writer.Write(Control.VisibleDate.ToString(monthFormat, CultureInfo.CurrentCulture));
writer.Write("):");
writer.WriteBreak();
// List weeks of days of the selected month. May include
// days from the previous and the next month to fill out
// all six week choices. This is consistent with the
// ASP.NET Calendar control.
// Note that the event handling code of this list control
// should be implemented according to the index content
// generated here.
tempDate = FirstCalendarDay(Control.VisibleDate);
arr = new ArrayList();
String weekDisplay;
for (int i = 0; i < 6; i++)
{
weekDisplay = tempDate.ToString(abbreviatedMonthDayPattern, CultureInfo.CurrentCulture);
weekDisplay += DaySeparator;
tempDate = _threadCalendar.AddDays(tempDate, 6);
weekDisplay += tempDate.ToString(abbreviatedMonthDayPattern, CultureInfo.CurrentCulture);
arr.Add(weekDisplay);
tempDate = _threadCalendar.AddDays(tempDate, 1);
}
DataBindAndRender(writer, _weekList, arr);
break;
// Based on the month and week selected in case ChooseMonth and ChooseWeek above,
// render a list of the dates in the week.
case ChooseDay:
writer.Write(SR.GetString(SR.CalendarAdapterOptionChooseDate));
writer.Write(":");
writer.WriteBreak();
tempDate = Control.VisibleDate;
arr = new ArrayList();
String date;
String dayName;
StringBuilder dayDisplay = new StringBuilder();
bool dayNameFirst = (GetNumericDateFormat()[0] != 'y');
for (int i = 0; i < 7; i++)
{
date = tempDate.ToString(abbreviatedMonthDayPattern, CultureInfo.CurrentCulture);
if (Control.ShowDayHeader)
{
// Use the short format for displaying day name
dayName = GetAbbreviatedDayName(tempDate);
dayDisplay.Length = 0;
if (dayNameFirst)
{
dayDisplay.Append(dayName);
dayDisplay.Append(Space);
dayDisplay.Append(date);
}
else
{
dayDisplay.Append(date);
dayDisplay.Append(Space);
dayDisplay.Append(dayName);
}
arr.Add(dayDisplay.ToString());
}
else
{
arr.Add(date);
}
tempDate = _threadCalendar.AddDays(tempDate, 1);
}
DataBindAndRender(writer, _dayList, arr);
break;
default:
Debug.Assert(false, "Unexpected Secondary UI Mode");
break;
}
writer.ExitStyle(Style, breakAfter);
}
/// <include file='doc\ChtmlCalendarAdapter.uex' path='docs/doc[@for="ChtmlCalendarAdapter.HandlePostBackEvent"]/*' />
public override bool HandlePostBackEvent(String eventArgument)
{
// This is mainly to capture the option picked by the user on
// secondary pages and manipulate SecondaryUIMode accordingly so
// Render() can generate the appropriate UI.
// It also capture the state "Done" which can be set when a date,
// a week or a month is selected or entered in some secondary
// page.
SecondaryUIMode = Int32.Parse(eventArgument, CultureInfo.InvariantCulture);
Debug.Assert(NotSecondaryUI == NotSecondaryUIInit);
switch (SecondaryUIMode)
{
case DefaultDateDone:
SelectRange(Control.VisibleDate, Control.VisibleDate);
goto case Done;
case TypeDate:
_requireFormTag = true;
break;
case TypeDateDone:
try
{
String dateText = _textBox.Text;
String dateFormat = GetNumericDateFormat();
DateTimeFormatInfo currentInfo = DateTimeFormatInfo.CurrentInfo;
int eraIndex = _selectList.SelectedIndex;
if (eraIndex >= 0 &&
eraIndex < currentInfo.Calendar.Eras.Length)
{
dateText += currentInfo.GetEraName(currentInfo.Calendar.Eras[eraIndex]);
dateFormat += "gg";
}
DateTime dateTime = DateTime.ParseExact(dateText, dateFormat, null);
SelectRange(dateTime, dateTime);
Control.VisibleDate = dateTime;
}
catch
{
_textBoxErrorMessage = SR.GetString(SR.CalendarAdapterTextBoxErrorMessage);
SecondaryUIMode = TypeDate;
goto case TypeDate;
}
goto case Done;
case Done:
// Set the secondary exit code and raise the selection event for
// web page developer to manipulate the selected date.
ExitSecondaryUIMode();
_chooseOption = FirstPrompt;
break;
case DateOption:
case WeekOption:
case MonthOption:
_chooseOption = SecondaryUIMode; // save in the ViewState
// In all 3 cases, continue to the UI that chooses a month
SecondaryUIMode = ChooseMonth;
break;
}
return true;
}
/////////////////////////////////////////////////////////////////////
// Misc. helper and wrapper functions
/////////////////////////////////////////////////////////////////////
private int MonthsToDisplay(int screenCharactersHeight)
{
const int MinMonthsToDisplay = 4;
const int MaxMonthsToDisplay = 12;
if (screenCharactersHeight < MinMonthsToDisplay)
{
return MinMonthsToDisplay;
}
else if (screenCharactersHeight > MaxMonthsToDisplay)
{
return MaxMonthsToDisplay;
}
return screenCharactersHeight;
}
// A helper function to initialize and add a child list control
private void InitList(List list,
ListCommandEventHandler eventHandler)
{
list.Visible = false;
list.ItemCommand += eventHandler;
list.EnableViewState = false;
Control.Controls.Add(list);
}
private void DataBindListWithEmptyValues(List list, int arraySize)
{
ArrayList arr = new ArrayList();
for (int i = 0; i < arraySize; i++)
{
arr.Add("");
}
list.DataSource = arr;
list.DataBind();
}
// A helper function to do the common code for DataBind and
// RenderChildren.
private void DataBindAndRender(HtmlMobileTextWriter writer,
List list,
ArrayList arr)
{
list.DataSource = arr;
list.DataBind();
list.Visible = true;
list.RenderControl(writer);
}
// Abbreviate the Month format from "MMMM" (full
// month name) to "MMM" (three-character month abbreviation)
private String AbbreviateMonthPattern(String pattern)
{
const String FullMonthFormat = "MMMM";
int i = pattern.IndexOf(FullMonthFormat, StringComparison.Ordinal);
if (i != -1)
{
pattern = pattern.Remove(i, 1);
}
return pattern;
}
private String GetAbbreviatedDayName(DateTime dateTime)
{
return DateTimeFormatInfo.CurrentInfo.GetAbbreviatedDayName(
_threadCalendar.GetDayOfWeek(dateTime));
}
private String GetEra(DateTime dateTime)
{
// We shouldn't need to display the era for the common Gregorian
// Calendar
if (DateTimeFormatInfo.CurrentInfo.Calendar.GetType() ==
typeof(GregorianCalendar))
{
return String.Empty;
}
else
{
return dateTime.ToString("gg", CultureInfo.CurrentCulture);
}
}
private static readonly char[] formatChars =
new char[] { 'M', 'd', 'y' };
private String GetNumericDateFormat()
{
String shortDatePattern =
DateTimeFormatInfo.CurrentInfo.ShortDatePattern;
// Guess on what short date pattern should be used
int i = shortDatePattern.IndexOfAny(formatChars);
char firstFormatChar;
if (i == -1)
{
firstFormatChar = 'M';
}
else
{
firstFormatChar = shortDatePattern[i];
}
// We either use two or four digits for the year
String yearPattern;
if (shortDatePattern.IndexOf("yyyy", StringComparison.Ordinal) == -1)
{
yearPattern = "yy";
}
else
{
yearPattern = "yyyy";
}
switch (firstFormatChar)
{
case 'M':
default:
return "MMdd" + yearPattern;
case 'd':
return "ddMM" + yearPattern;
case 'y':
return yearPattern + "MMdd";
}
}
/////////////////////////////////////////////////////////////////////
// Helper functions
/////////////////////////////////////////////////////////////////////
// Return the first date of the input year and month
private DateTime EffectiveVisibleDate(DateTime visibleDate)
{
return _threadCalendar.AddDays(
visibleDate,
-(_threadCalendar.GetDayOfMonth(visibleDate) - 1));
}
// Return the beginning date of a calendar that includes the
// targeting month. The date can actually be in the previous month.
private DateTime FirstCalendarDay(DateTime visibleDate)
{
DateTime firstDayOfMonth = EffectiveVisibleDate(visibleDate);
int daysFromLastMonth =
((int)_threadCalendar.GetDayOfWeek(firstDayOfMonth)) -
NumericFirstDayOfWeek();
// Always display at least one day from the previous month
if (daysFromLastMonth <= 0)
{
daysFromLastMonth += 7;
}
return _threadCalendar.AddDays(firstDayOfMonth, -daysFromLastMonth);
}
private int NumericFirstDayOfWeek()
{
// Used globalized value by default
return(Control.FirstDayOfWeek == FirstDayOfWeek.Default)
? (int) DateTimeFormatInfo.CurrentInfo.FirstDayOfWeek
: (int) Control.FirstDayOfWeek;
}
/////////////////////////////////////////////////////////////////////
// The followings are event handlers to capture the selection from
// the corresponding list control in an secondary page. The index of
// the selection is used to determine which and how the next
// secondary page is rendered. Some event handlers below update
// Calendar.VisibleDate and set SecondaryUIMode with appropriate
// values.
////////////////////////////////////////////////////////////////////////
private void TextBoxEventHandler(Object source, EventArgs e)
{
HandlePostBackEvent(TypeDateDone.ToString(CultureInfo.InvariantCulture));
}
private static readonly int[] Options =
{DefaultDateDone, TypeDate, DateOption, WeekOption, MonthOption};
private void OptionListEventHandler(Object source, ListCommandEventArgs e)
{
SecondaryUIMode = Options[e.ListItem.Index];
HandlePostBackEvent(SecondaryUIMode.ToString(CultureInfo.InvariantCulture));
}
private void MonthListEventHandler(Object source, ListCommandEventArgs e)
{
_threadCalendar = DateTimeFormatInfo.CurrentInfo.Calendar;
if (e.ListItem.Index == _monthsToDisplay)
{
// Next was selected
Control.VisibleDate = _threadCalendar.AddMonths(
Control.VisibleDate, _monthsToDisplay);
SecondaryUIMode = ChooseMonth;
}
else if (e.ListItem.Index == _monthsToDisplay + 1)
{
// Prev was selected
Control.VisibleDate = _threadCalendar.AddMonths(
Control.VisibleDate, -_monthsToDisplay);
SecondaryUIMode = ChooseMonth;
}
else
{
// A month was selected
Control.VisibleDate = _threadCalendar.AddMonths(
Control.VisibleDate,
e.ListItem.Index);
if (_chooseOption == MonthOption)
{
// Add the whole month to the date list
DateTime beginDate = EffectiveVisibleDate(Control.VisibleDate);
Control.VisibleDate = beginDate;
DateTime endDate = _threadCalendar.AddMonths(beginDate, 1);
endDate = _threadCalendar.AddDays(endDate, -1);
SelectRange(beginDate, endDate);
HandlePostBackEvent(Done.ToString(CultureInfo.InvariantCulture));
}
else
{
SecondaryUIMode = ChooseWeek;
}
}
}
private void WeekListEventHandler(Object source, ListCommandEventArgs e)
{
// Get the first calendar day and adjust it to the week the user
// selected (to be consistent with the index setting in Render())
_threadCalendar = DateTimeFormatInfo.CurrentInfo.Calendar;
DateTime tempDate = FirstCalendarDay(Control.VisibleDate);
Control.VisibleDate = _threadCalendar.AddDays(tempDate, e.ListItem.Index * 7);
if (_chooseOption == WeekOption)
{
// Add the whole week to the date list
DateTime endDate = _threadCalendar.AddDays(Control.VisibleDate, 6);
SelectRange(Control.VisibleDate, endDate);
HandlePostBackEvent(Done.ToString(CultureInfo.InvariantCulture));
}
else
{
SecondaryUIMode = ChooseDay;
}
}
private void DayListEventHandler(Object source, ListCommandEventArgs e)
{
_threadCalendar = DateTimeFormatInfo.CurrentInfo.Calendar;
// VisibleDate should have been set with the first day of the week
// so the selected index can be used to adjust to the selected day.
Control.VisibleDate = _threadCalendar.AddDays(Control.VisibleDate, e.ListItem.Index);
SelectRange(Control.VisibleDate, Control.VisibleDate);
HandlePostBackEvent(Done.ToString(CultureInfo.InvariantCulture));
}
private void SelectRange(DateTime dateFrom, DateTime dateTo)
{
Debug.Assert(dateFrom <= dateTo, "Bad Date Range");
// see if this range differs in any way from the current range
// these checks will determine this because the colleciton is sorted
TimeSpan ts = dateTo - dateFrom;
SelectedDatesCollection selectedDates = Control.SelectedDates;
if (selectedDates.Count != ts.Days + 1
|| selectedDates[0] != dateFrom
|| selectedDates[selectedDates.Count - 1] != dateTo)
{
selectedDates.SelectRange(dateFrom, dateTo);
Control.RaiseSelectionChangedEvent();
}
}
private bool IsViewStateEnabled()
{
Control ctl = Control;
while (ctl != null)
{
if (!ctl.EnableViewState)
{
return false;
}
ctl = ctl.Parent;
}
return true;
}
}
}
| |
using System;
using System.Globalization;
using System.Collections.Generic;
using Sasoma.Utils;
using Sasoma.Microdata.Interfaces;
using Sasoma.Languages.Core;
using Sasoma.Microdata.Properties;
namespace Sasoma.Microdata.Types
{
/// <summary>
/// Event type: Literary event.
/// </summary>
public class LiteraryEvent_Core : TypeCore, IEvent
{
public LiteraryEvent_Core()
{
this._TypeId = 152;
this._Id = "LiteraryEvent";
this._Schema_Org_Url = "http://schema.org/LiteraryEvent";
string label = "";
GetLabel(out label, "LiteraryEvent", typeof(LiteraryEvent_Core));
this._Label = label;
this._Ancestors = new int[]{266,98};
this._SubTypes = new int[0];
this._SuperTypes = new int[]{98};
this._Properties = new int[]{67,108,143,229,19,71,82,130,151,158,214,216,218};
}
/// <summary>
/// A person attending the event.
/// </summary>
private Attendees_Core attendees;
public Attendees_Core Attendees
{
get
{
return attendees;
}
set
{
attendees = value;
SetPropertyInstance(attendees);
}
}
/// <summary>
/// A short description of the item.
/// </summary>
private Description_Core description;
public Description_Core Description
{
get
{
return description;
}
set
{
description = value;
SetPropertyInstance(description);
}
}
/// <summary>
/// The duration of the item (movie, audio recording, event, etc.) in <a href=\http://en.wikipedia.org/wiki/ISO_8601\ target=\new\>ISO 8601 date format</a>.
/// </summary>
private Properties.Duration_Core duration;
public Properties.Duration_Core Duration
{
get
{
return duration;
}
set
{
duration = value;
SetPropertyInstance(duration);
}
}
/// <summary>
/// The end date and time of the event (in <a href=\http://en.wikipedia.org/wiki/ISO_8601\ target=\new\>ISO 8601 date format</a>).
/// </summary>
private EndDate_Core endDate;
public EndDate_Core EndDate
{
get
{
return endDate;
}
set
{
endDate = value;
SetPropertyInstance(endDate);
}
}
/// <summary>
/// URL of an image of the item.
/// </summary>
private Image_Core image;
public Image_Core Image
{
get
{
return image;
}
set
{
image = value;
SetPropertyInstance(image);
}
}
/// <summary>
/// The location of the event or organization.
/// </summary>
private Location_Core location;
public Location_Core Location
{
get
{
return location;
}
set
{
location = value;
SetPropertyInstance(location);
}
}
/// <summary>
/// The name of the item.
/// </summary>
private Name_Core name;
public Name_Core Name
{
get
{
return name;
}
set
{
name = value;
SetPropertyInstance(name);
}
}
/// <summary>
/// An offer to sell this item\u2014for example, an offer to sell a product, the DVD of a movie, or tickets to an event.
/// </summary>
private Offers_Core offers;
public Offers_Core Offers
{
get
{
return offers;
}
set
{
offers = value;
SetPropertyInstance(offers);
}
}
/// <summary>
/// The main performer or performers of the event\u2014for example, a presenter, musician, or actor.
/// </summary>
private Performers_Core performers;
public Performers_Core Performers
{
get
{
return performers;
}
set
{
performers = value;
SetPropertyInstance(performers);
}
}
/// <summary>
/// The start date and time of the event (in <a href=\http://en.wikipedia.org/wiki/ISO_8601\ target=\new\>ISO 8601 date format</a>).
/// </summary>
private StartDate_Core startDate;
public StartDate_Core StartDate
{
get
{
return startDate;
}
set
{
startDate = value;
SetPropertyInstance(startDate);
}
}
/// <summary>
/// Events that are a part of this event. For example, a conference event includes many presentations, each are subEvents of the conference.
/// </summary>
private SubEvents_Core subEvents;
public SubEvents_Core SubEvents
{
get
{
return subEvents;
}
set
{
subEvents = value;
SetPropertyInstance(subEvents);
}
}
/// <summary>
/// An event that this event is a part of. For example, a collection of individual music performances might each have a music festival as their superEvent.
/// </summary>
private SuperEvent_Core superEvent;
public SuperEvent_Core SuperEvent
{
get
{
return superEvent;
}
set
{
superEvent = value;
SetPropertyInstance(superEvent);
}
}
/// <summary>
/// URL of the item.
/// </summary>
private Properties.URL_Core uRL;
public Properties.URL_Core URL
{
get
{
return uRL;
}
set
{
uRL = value;
SetPropertyInstance(uRL);
}
}
}
}
| |
using System;
using System.Collections.Generic;
namespace Manos.IO
{
/// <summary>
/// Base class for asynchronous streams. Other than synchronous streams,
/// asynchronous streams do not block calls to their Read or Write methods.
/// <para>Calls to Read replace the current set of reader callbacks (which need
/// not yet exist) with a new set of callbacks. These callbacks are invoked
/// whenever the corresponding event occured.</para>
/// <para>Calls to Write place the data to be written into a write queue.
/// Whenever the stream becomes writeable, data from the queue is written.</para>
/// <para>The reading and writing parts of the stream may be paused and resumed
/// individually. Pausing and resuming is a set-reset process, so multiple
/// calls to Pause methods can be undone by a single call to a Resume method.</para>
/// </summary>
public abstract class FragmentStream<TFragment> : IStream<TFragment>
where TFragment : class
{
private readonly Context context;
// write queue handling
private TFragment currentFragment;
private IDisposable currentReader;
private IEnumerator<TFragment> currentWriter;
private bool disposed;
private Action<TFragment> onData;
private Action onEndOfStream;
private Action<Exception> onError;
private Queue<IEnumerable<TFragment>> writeQueue;
/// <summary>
/// Initializes a new instance of the <see cref="Manos.IO.FragmentStream{TFragment}"/> class.
/// </summary>
/// <param name='context'>
/// The context this instance will be bound to.
/// </param>
protected FragmentStream(Context context)
{
if (context == null)
throw new ArgumentNullException("context");
this.context = context;
}
#region IStream<TFragment> Members
/// <summary>
/// Gets the context this stream is bound to.
/// </summary>
public virtual Context Context
{
get { return context; }
}
/// <summary>
/// Replaces the current set of reader callbacks with the given set of reader callbacks.
/// The returned value may be used to indicate that no further callback invocations should
/// occur.
/// </summary>
/// <exception cref='ArgumentNullException'>
/// Is thrown when any argument passed to the method is <see langword="null" /> .
/// </exception>
public virtual IDisposable Read(Action<TFragment> onData, Action<Exception> onError, Action onEndOfStream)
{
CheckDisposed();
if (onData == null)
throw new ArgumentNullException("onData");
if (onError == null)
throw new ArgumentNullException("onError");
if (onEndOfStream == null)
throw new ArgumentNullException("onClose");
this.onData = onData;
this.onError = onError;
this.onEndOfStream = onEndOfStream;
currentReader = new ReaderHandle(this);
return currentReader;
}
/// <summary>
/// Places a sequence of fragments into the write queue.
/// The sequence is not touched, only when the first piece of data in the
/// sequence may be written to the stream, the enumeration is started.
/// This allows for data generators that produce large amounts of data, but
/// have a very small memory footprint.
/// <para>The sequence may return an arbitrary number of fragments.</para>
/// <para><c>null</c> fragments pause writing.</para>
/// </summary>
/// <exception cref='ArgumentNullException'>
/// Is thrown when an argument passed to a method is invalid because it is <see langword="null" /> .
/// </exception>
public virtual void Write(IEnumerable<TFragment> data)
{
CheckDisposed();
if (data == null)
throw new ArgumentNullException("data");
if (writeQueue == null)
{
writeQueue = new Queue<IEnumerable<TFragment>>();
}
writeQueue.Enqueue(data);
}
/// <summary>
/// Places a single buffer into the write queue.
/// </summary>
public virtual void Write(TFragment data)
{
CheckDisposed();
Write(SingleFragment(data));
}
/// <summary>
/// Gets or sets the position of the stream.
/// </summary>
public abstract long Position { get; set; }
/// <summary>
/// Gets a value indicating whether this instance can read.
/// </summary>
/// <value>
/// <c>true</c> if this instance can read; otherwise, <c>false</c>.
/// </value>
public abstract bool CanRead { get; }
/// <summary>
/// Gets a value indicating whether this instance can write.
/// </summary>
/// <value>
/// <c>true</c> if this instance can write; otherwise, <c>false</c>.
/// </value>
public abstract bool CanWrite { get; }
/// <summary>
/// Gets a value indicating whether this instance can seek.
/// </summary>
/// <value>
/// <c>true</c> if this instance can seek; otherwise, <c>false</c>.
/// </value>
public virtual bool CanSeek
{
get { return false; }
}
/// <summary>
/// Gets a value indicating whether this instance can timeout.
/// </summary>
/// <value>
/// <c>true</c> if this instance can timeout; otherwise, <c>false</c>.
/// </value>
public virtual bool CanTimeout
{
get { return false; }
}
/// <summary>
/// Gets or sets the read timeout.
/// </summary>
public virtual TimeSpan ReadTimeout
{
get { throw new NotSupportedException(); }
set { throw new NotSupportedException(); }
}
/// <summary>
/// Gets or sets the write timeout.
/// </summary>
public virtual TimeSpan WriteTimeout
{
get { throw new NotSupportedException(); }
set { throw new NotSupportedException(); }
}
/// <summary>
/// Instructs the stream to resume reading when it is not reading yet.
/// </summary>
public abstract void ResumeReading();
/// <summary>
/// Resumes writing.
/// </summary>
public abstract void ResumeWriting();
/// <summary>
/// Pauses reading.
/// </summary>
public abstract void PauseReading();
/// <summary>
/// Pauses writing.
/// </summary>
public abstract void PauseWriting();
/// <summary>
/// Seeks by <paramref name="delta"/> fragments. A positive <paramref name="delta"/>
/// will seek forward, a negative <paramref name="delta"/> will seek backwards.
/// </summary>
public virtual void SeekBy(long delta)
{
throw new NotSupportedException();
}
/// <summary>
/// Seeks to absolute position <paramref name="position"/> in the stream.
/// </summary>
public virtual void SeekTo(long position)
{
throw new NotSupportedException();
}
/// <summary>
/// Flush all buffers held by this instance, if applicable. This need not
/// flush the write queue, it must however place equivalents for all
/// semantically written data into the write queue.
/// <para>For example, a block cipher stream might operate an 16 byte blocks.
/// A call to <see cref="Flush"/> on this stream would pad an incomplete block
/// to 16 bytes, encrypt it, and queue it for writing.</para>
/// </summary>
public abstract void Flush();
/// <summary>
/// Close this instance. The currently active reader is cancelled,
/// the write queue is cleared.
/// </summary>
public virtual void Close()
{
Dispose();
}
/// <summary>
/// Releases all resource used by the <see cref="Manos.IO.FragmentStream{TFragment}"/> object.
/// </summary>
/// <remarks>
/// Call <see cref="Dispose()"/> when you are finished using the <see cref="Manos.IO.FragmentStream{TFragment}"/>. The
/// <see cref="Dispose()"/> method leaves the <see cref="Manos.IO.FragmentStream{TFragment}"/> in an unusable state. After calling
/// <see cref="Dispose()"/>, you must release all references to the <see cref="Manos.IO.FragmentStream{TFragment}"/> so the garbage
/// collector can reclaim the memory that the <see cref="Manos.IO.FragmentStream{TFragment}"/> was occupying.
/// </remarks>
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
#endregion
/// <summary>
/// Cancels the current reader and clears the set of reader callbacks.
/// </summary>
protected virtual void CancelReader()
{
CheckDisposed();
onData = null;
onError = null;
onEndOfStream = null;
currentReader = null;
}
private static IEnumerable<TFragment> SingleFragment(TFragment fragment)
{
yield return fragment;
}
/// <summary>
/// Releases unmanaged resources and performs other cleanup operations before the
/// <see cref="Manos.IO.FragmentStream{TFragment}"/> is
/// reclaimed by garbage collection.
/// </summary>
~FragmentStream()
{
Dispose(false);
}
/// <summary>
/// Checks whether the object has been disposed.
/// </summary>
/// <exception cref='ObjectDisposedException'>
/// Is thrown when an operation is performed on a disposed object.
/// </exception>
protected virtual void CheckDisposed()
{
if (disposed)
throw new ObjectDisposedException(GetType().Name);
}
/// <summary>
/// Dispose the current instance.
/// </summary>
/// <param name='disposing'>
/// <c>true</c>, if the method was called by <see cref="Dispose()"/>,
/// <c>false</c> if it was called from a finalizer.
/// </param>
protected virtual void Dispose(bool disposing)
{
if (currentReader != null)
{
onData = null;
onEndOfStream = null;
onError = null;
currentReader = null;
}
if (writeQueue != null)
{
if (currentWriter != null)
{
currentWriter.Dispose();
currentWriter = null;
}
currentFragment = null;
writeQueue.Clear();
writeQueue = null;
}
disposed = true;
}
/// <summary>
/// Raises the data callback, if set.
/// </summary>
protected virtual void RaiseData(TFragment data)
{
if (onData != null)
{
onData(data);
}
}
/// <summary>
/// Raises the error callback, if set.
/// </summary>
protected virtual void RaiseError(Exception exception)
{
if (onError != null)
{
onError(exception);
}
}
/// <summary>
/// Raises the end of stream callback, if set.
/// </summary>
protected virtual void RaiseEndOfStream()
{
if (onEndOfStream != null)
{
onEndOfStream();
}
}
/// <summary>
/// Writes a single fragment.
/// </summary>
/// <returns>
/// See <seealso cref="WriteResult"/> for result values.
/// </returns>
/// <param name='fragment'>
/// The fragment to write.
/// </param>
protected abstract WriteResult WriteSingleFragment(TFragment fragment);
/// <summary>
/// Handles one write operation. If the write queue is empty, or the fragment
/// produced by the currently writing sequence is <c>null</c>, the writing
/// process is paused.
/// </summary>
protected virtual void HandleWrite()
{
if (writeQueue == null)
{
throw new InvalidOperationException();
}
if (!EnsureActiveFragment() || currentFragment == null)
{
PauseWriting();
}
else
{
WriteCurrentFragment();
}
}
/// <summary>
/// Writes the current fragment to the stream via <see cref="WriteSingleFragment"/>.
/// </summary>
protected virtual void WriteCurrentFragment()
{
WriteResult sent = WriteSingleFragment(currentFragment);
switch (sent)
{
case WriteResult.Consume:
currentFragment = null;
break;
case WriteResult.Error:
PauseWriting();
break;
case WriteResult.Continue:
// no error, continue
break;
}
}
/// <summary>
/// Ensures that a fragment to be written exists.
/// </summary>
/// <returns>
/// <c>true</c>, iff there is a fragment that can be written.
/// </returns>
protected virtual bool EnsureActiveFragment()
{
if (currentFragment == null && EnsureActiveWriter())
{
if (currentWriter.MoveNext())
{
currentFragment = currentWriter.Current;
return true;
}
else
{
currentWriter.Dispose();
currentWriter = null;
return EnsureActiveFragment();
}
}
return currentFragment != null;
}
/// <summary>
/// Ensures that a sequence to be written to the stream exists.
/// </summary>
/// <returns>
/// <c>true</c>, iff there is a sequence that can be written to the stream.
/// </returns>
protected virtual bool EnsureActiveWriter()
{
if (currentWriter == null && writeQueue.Count > 0)
{
currentWriter = writeQueue.Dequeue().GetEnumerator();
}
return currentWriter != null;
}
/// <summary>
/// Size of the fragment in fragment units.
/// </summary>
/// <returns>
/// The size.
/// </returns>
/// <param name='fragment'>
/// Fragment.
/// </param>
protected abstract long FragmentSize(TFragment fragment);
#region Nested type: ReaderHandle
/// <summary>
/// A <see cref="ReaderHandle"/> represents a stream users' handle on the
/// set of reader callbacks. If the user wishes to not receive further
/// callbacks, he must call <see cref="Dispose"/> on the handle to cancel
/// his set of callbacks.
/// </summary>
protected class ReaderHandle : IDisposable
{
private readonly FragmentStream<TFragment> parent;
/// <summary>
/// Initializes a new instance of the <see cref="Manos.IO.FragmentStream{TFragment}.ReaderHandle"/> class.
/// </summary>
public ReaderHandle(FragmentStream<TFragment> parent)
{
this.parent = parent;
}
#region IDisposable Members
/// <summary>
/// Cancels the set of reader callbacks in the parent.
/// </summary>
public void Dispose()
{
if (parent.currentReader == this)
parent.CancelReader();
}
#endregion
}
#endregion
#region Nested type: WriteResult
/// <summary>
/// Enumeration of results a write operation can produce.
/// </summary>
protected enum WriteResult
{
/// <summary>
/// The write failed in some way. Pause the writing process.
/// </summary>
Error,
/// <summary>
/// The write succeeded and has written the entire fragment.
/// Consume the fragment.
/// </summary>
Consume,
/// <summary>
/// The write succeeded and has not written the entire fragment.
/// Continue writing the fragment as soon as possible.
/// </summary>
Continue
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Alea.cuDNN;
namespace AleaTK.ML
{
public sealed class Data
{
private Tensor _tensor = null;
private Tensor _gradient = null;
public Data(Context context, Variable variable)
{
Context = context;
Variable = variable;
}
public Context Context { get; }
public Variable Variable { get; }
public int GradientAggregationCounter { get; set; } = 0;
public void Initialize()
{
if (Variable.HasInitializer)
{
Variable.Initialize(Context, ref _tensor);
}
}
public Tensor Tensor => _tensor;
public Tensor Gradient => _gradient;
public IValue TensorAsValue => Variable.TensorToValue(_tensor);
public IValue GradientAsValue => Variable.TensorToValue(_gradient);
public Expr TensorAsExpr => Variable.TensorToExpr(_tensor);
public Expr GradientAsExpr => Variable.TensorToExpr(_gradient);
public Tensor GetOrAllocateTensor(Layout layout, long length)
{
Variable.GetOrAllocate(Context.Device, layout, length, ref _tensor);
return _tensor;
}
public Tensor GetOrAllocateGradient(Layout layout, long length)
{
Variable.GetOrAllocate(Context.Device, layout, length, ref _gradient);
return _gradient;
}
public void SetTensor(Tensor tensor)
{
_tensor = tensor;
}
public void SetGradient(Tensor gradient)
{
_gradient = gradient;
}
}
public class Executor : Disposable
{
private readonly Dictionary<Variable, Data> _data = new Dictionary<Variable, Data>();
private readonly List<Differentiable> _forwardOrder = new List<Differentiable>();
private readonly List<Differentiable> _backwardOrder;
#region Native repo
public DisposableRepository<TensorDescriptor> TensorDescRepo { get; } =
new DisposableRepository<TensorDescriptor>(() => new TensorDescriptor());
public DisposableRepository<FilterDescriptor> FilterDescRepo { get; } =
new DisposableRepository<FilterDescriptor>(() => new FilterDescriptor());
public DisposableDictionary<Symbol, TensorDescriptor> TensorDescDict { get; } =
new DisposableDictionary<Symbol, TensorDescriptor>(_ => new TensorDescriptor());
public DisposableDictionary<Symbol, FilterDescriptor> FilterDescDict { get; } =
new DisposableDictionary<Symbol, FilterDescriptor>(_ => new FilterDescriptor());
public DisposableDictionary<Symbol, DropoutDescriptor> DropoutDescDict { get; } =
new DisposableDictionary<Symbol, DropoutDescriptor>(_ => new DropoutDescriptor());
public DisposableDictionary<Symbol, RNNDescriptor> RnnDescDict { get; } =
new DisposableDictionary<Symbol, RNNDescriptor>(_ => new RNNDescriptor());
#endregion
#region Storage
public Dictionary<Symbol, object> Objects { get; } = new Dictionary<Symbol, object>();
public Dictionary<Symbol, IDisposable> Disposables { get; } = new Dictionary<Symbol, IDisposable>();
#endregion
#region Properties
public Context Context { get; }
public Variable Output { get; }
public bool AssignAllGradient { get; set; } = false;
public IEnumerable<Differentiable> ForwardOrder => _forwardOrder;
public IEnumerable<Differentiable> BackwardOrder => _backwardOrder;
public IEnumerable<Data> Data => _data.Values;
public Data GetData(Variable var)
{
return _data[var];
}
#endregion
public Executor(Context ctx, Variable output)
{
Context = ctx;
Output = output;
AddData(output);
SetForwardOrder(output);
_backwardOrder = ((IEnumerable<Differentiable>)_forwardOrder).Reverse().ToList();
}
#region Set order
private void SetForwardOrder(Variable variable)
{
SetForwardOrder(variable, new HashSet<Differentiable>());
}
private void SetForwardOrder(Variable variable, HashSet<Differentiable> cache)
{
if (variable.HasOwner)
{
SetForwardOrder(variable.Owner, cache);
}
}
private void SetForwardOrder(Differentiable op, HashSet<Differentiable> cache)
{
if (cache.Contains(op)) return;
foreach (var input in op.Inputs)
{
SetForwardOrder(input, cache);
}
_forwardOrder.Add(op);
cache.Add(op);
}
#endregion
#region Add data
private void AddData(Variable variable)
{
AddData(variable, new HashSet<Differentiable>());
}
private void AddData(Variable variable, HashSet<Differentiable> cache)
{
if (_data.ContainsKey(variable)) return;
if (variable.HasOwner)
{
AddData(variable.Owner, cache);
}
else
{
_data.Add(variable, new Data(Context, variable));
}
}
private void AddData(Differentiable op, HashSet<Differentiable> cache)
{
if (cache.Contains(op)) return;
foreach (var input in op.Inputs)
{
AddData(input, cache);
}
foreach (var auxVar in op.AuxVars)
{
AddData(auxVar, cache);
}
foreach (var output in op.Outputs)
{
_data.Add(output, new Data(Context, output));
}
cache.Add(op);
}
#endregion
#region Get/Set variable tensor
/// <summary>
/// Get variable tensor. The variable tensor is assumed to be allocated already,
/// if not, an exception will be thrown. This is usually used for getting input
/// variable tensor.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="variable"></param>
/// <returns></returns>
public Tensor<T> GetTensor<T>(Variable<T> variable)
{
var data = _data[variable];
return data.Tensor.Cast<T>();
}
/// <summary>
/// Get variable tesnor. If the variable tensor is not allocated or it is
/// allocated but not large enough for holding the shape, then a new allocation
/// will be triggered. This is usually used for output variable tensor.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="variable"></param>
/// <param name="shape"></param>
/// <returns></returns>
public Tensor<T> GetTensor<T>(Variable<T> variable, Shape shape)
{
var layout = new Layout(shape);
var data = _data[variable];
return data.GetOrAllocateTensor(layout, shape.Length).Cast<T>();
}
/// <summary>
/// Set variable tensor to an exists tensor (referencing tensor). The tensor must
/// be allocated in the same device of this executor.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="variable"></param>
/// <param name="tensor"></param>
public void SetTensor<T>(Variable<T> variable, Tensor<T> tensor)
{
Util.EnsureTrue(tensor.Device == Context.Device, "Set gradient is reference, must be in same device.");
var data = _data[variable];
data.SetTensor(tensor.ToTensor());
}
/// <summary>
/// Assign variable tensor from another tensor (copy may happen if the src tensor
/// is not in the same device of this executor).
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="variable"></param>
/// <param name="srcTensor"></param>
/// <returns></returns>
public Task AssignTensor<T>(Variable<T> variable, Tensor<T> srcTensor)
{
var data = _data[variable];
var blob = data.GetOrAllocateTensor(srcTensor.Layout, srcTensor.Memory.Length);
var dstTensor = blob.Cast<T>();
return Context.Copy(dstTensor, srcTensor);
}
/// <summary>
/// Assign variable tensor from an expression.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="variable"></param>
/// <param name="expr"></param>
/// <returns></returns>
public Task AssignTensor<T>(Variable<T> variable, Expr<T> expr)
{
var shape = expr.Shape;
var layout = new Layout(shape);
var length = layout.Shape.Length;
var data = _data[variable];
var blob = data.GetOrAllocateTensor(layout, length);
var tensor = blob.Cast<T>();
return Context.Assign(tensor, expr);
}
#endregion
#region Get/Set variable gradient
/// <summary>
/// Get variable gradient. The variable gradient is assumed to be allocated already,
/// if not, an exception will be thrown. This is usually used for getting output
/// variable gradient.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="variable"></param>
/// <returns></returns>
public Tensor<T> GetGradient<T>(Variable<T> variable)
{
var data = _data[variable];
return data.Gradient.Cast<T>();
}
/// <summary>
/// Get variable gradient together with its aggregation counter. The variable gradient
/// is assumed to be allocated already, if not, an exception will be thrown. This is
/// usually used for getting output variable gradient.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="variable"></param>
/// <param name="aggregationCounter"></param>
/// <returns></returns>
public Tensor<T> GetGradient<T>(Variable<T> variable, out int aggregationCounter)
{
var data = _data[variable];
aggregationCounter = data.GradientAggregationCounter;
return data.Gradient.Cast<T>();
}
/// <summary>
/// Get variable gradient. If the variable gradient is not allocated or it is
/// allocated but not large enough for holding the shape, then a new allocation
/// will be triggered. This is usually used for input variable gradient.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="variable"></param>
/// <param name="shape"></param>
/// <returns></returns>
public Tensor<T> GetGradient<T>(Variable<T> variable, Shape shape)
{
var layout = new Layout(shape);
var data = _data[variable];
return data.GetOrAllocateGradient(layout, shape.Length).Cast<T>();
}
/// <summary>
/// Get variable gradient together with its aggregation counter. If the variable gradient
/// is not allocated or it is allocated but not large enough for holding the shape, then
/// a new allocation will be triggered. This is usually used for input variable gradient.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="variable"></param>
/// <param name="shape"></param>
/// <param name="aggregationCounter"></param>
/// <returns></returns>
public Tensor<T> GetGradient<T>(Variable<T> variable, Shape shape, out int aggregationCounter)
{
var layout = new Layout(shape);
var data = _data[variable];
aggregationCounter = data.GradientAggregationCounter;
return data.GetOrAllocateGradient(layout, shape.Length).Cast<T>();
}
/// <summary>
/// Set variable gradient to an exists tensor (referencing tensor).
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="variable"></param>
/// <param name="gradient"></param>
/// <param name="counter"></param>
public void SetGradient<T>(Variable<T> variable, Tensor<T> gradient, int counter = 1)
{
Util.EnsureTrue(gradient.Device == Context.Device, "Set gradient is reference, must be in same device.");
var data = _data[variable];
data.GradientAggregationCounter = counter;
data.SetGradient(gradient.ToTensor());
}
/// <summary>
/// Assign variable gradient from an expression. If replace is false, then the previouse
/// gradient will be add to current gradient.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="variable"></param>
/// <param name="expr"></param>
/// <param name="aggregateCounter"></param>
/// <param name="replace"></param>
/// <returns></returns>
public Task AssignGradient<T>(Variable<T> variable, Expr<T> expr, int aggregateCounter = 1, bool replace = false)
{
if (!replace && !AssignAllGradient && !variable.HasOwner && variable.Type != VariableType.Parameter) return Task.Run(() => { });
var data = _data[variable];
if (replace)
{
var shape = data.Tensor.Layout.Shape;
var layout = new Layout(shape);
var length = layout.Shape.Length;
var blob = data.GetOrAllocateGradient(layout, length);
var tensor = blob.Cast<T>();
data.GradientAggregationCounter = aggregateCounter;
return Context.Assign(tensor, expr);
}
else
{
var currentAggregationCounter = data.GradientAggregationCounter;
data.GradientAggregationCounter += aggregateCounter;
if (currentAggregationCounter <= 0)
{
var shape = data.Tensor.Layout.Shape;
var layout = new Layout(shape);
var length = layout.Shape.Length;
var blob = data.GetOrAllocateGradient(layout, length);
var tensor = blob.Cast<T>();
return Context.Assign(tensor, expr);
}
else
{
var grad = data.GradientAsExpr;
return Context.Assign(data.GradientAsValue, grad + expr);
}
}
}
/// <summary>
/// Assign variable gradient by a tensor.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="variable"></param>
/// <param name="tensor"></param>
/// <param name="aggregateCounter"></param>
/// <param name="replace"></param>
/// <returns></returns>
public Task AssignGradient<T>(Variable<T> variable, Tensor<T> tensor, int aggregateCounter = 1, bool replace = false)
{
if (!replace && !AssignAllGradient && !variable.HasOwner && variable.Type != VariableType.Parameter) return Task.Run(() => { });
if (Context.Device == tensor.Device)
{
return AssignGradient(variable, (Expr<T>) tensor, aggregateCounter, replace);
}
else if (replace)
{
var data = _data[variable];
var blob = data.GetOrAllocateGradient(tensor.Layout, tensor.Memory.Length);
var dstTensor = blob.Cast<T>();
data.GradientAggregationCounter = aggregateCounter;
return Context.Copy(dstTensor, tensor);
}
else
{
throw new NotImplementedException();
}
}
#endregion
public int GetGradientAggregationCounter(Variable var)
{
var data = _data[var];
return data.GradientAggregationCounter;
}
public void SetGradientAggregationCounter(Variable var, int aggregationCounter)
{
var data = _data[var];
data.GradientAggregationCounter = aggregationCounter;
}
public int IncreaseGradientAggregationCounter(Variable var, int increasing = 1)
{
var data = _data[var];
var oldCounter = data.GradientAggregationCounter;
data.GradientAggregationCounter += increasing;
return oldCounter;
}
public void ClearGradientAggregationCounters()
{
foreach (var data in Data)
{
data.GradientAggregationCounter = 0;
}
}
public virtual void Initalize()
{
// initialize variables which has inititlizers.
foreach (var data in Data)
{
data.Initialize();
}
// call operator's init.
foreach (var op in ForwardOrder)
{
op.Initialize(this);
}
}
public void Forward()
{
foreach (var op in ForwardOrder)
{
op.Forward(this);
}
}
public void Backward(bool clearGradientAggretionCounter = true)
{
if (clearGradientAggretionCounter)
{
foreach (var data in Data)
{
data.GradientAggregationCounter = 0;
}
}
foreach (var op in BackwardOrder)
{
op.Backward(this);
}
}
}
}
| |
//
// 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.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Azure;
using Microsoft.WindowsAzure.Management.Sql;
using Microsoft.WindowsAzure.Management.Sql.Models;
namespace Microsoft.WindowsAzure.Management.Sql
{
/// <summary>
/// This is the main client class for interacting with the Azure SQL
/// Database REST APIs.
/// </summary>
public static partial class ServerOperationsExtensions
{
/// <summary>
/// Changes the administrative password of an existing Azure SQL
/// Database Server for a given subscription.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.Sql.IServerOperations.
/// </param>
/// <param name='serverName'>
/// Required. The name of the Azure SQL Database Server that will have
/// the administrator password changed.
/// </param>
/// <param name='parameters'>
/// Required. The necessary parameters for modifying the adminstrator
/// password for a server.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public static AzureOperationResponse ChangeAdministratorPassword(this IServerOperations operations, string serverName, ServerChangeAdministratorPasswordParameters parameters)
{
return Task.Factory.StartNew((object s) =>
{
return ((IServerOperations)s).ChangeAdministratorPasswordAsync(serverName, parameters);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Changes the administrative password of an existing Azure SQL
/// Database Server for a given subscription.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.Sql.IServerOperations.
/// </param>
/// <param name='serverName'>
/// Required. The name of the Azure SQL Database Server that will have
/// the administrator password changed.
/// </param>
/// <param name='parameters'>
/// Required. The necessary parameters for modifying the adminstrator
/// password for a server.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public static Task<AzureOperationResponse> ChangeAdministratorPasswordAsync(this IServerOperations operations, string serverName, ServerChangeAdministratorPasswordParameters parameters)
{
return operations.ChangeAdministratorPasswordAsync(serverName, parameters, CancellationToken.None);
}
/// <summary>
/// Provisions a new SQL Database server in a subscription.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.Sql.IServerOperations.
/// </param>
/// <param name='parameters'>
/// Required. The parameters needed to provision a server.
/// </param>
/// <returns>
/// The response returned from the Create Server operation. This
/// contains all the information returned from the service when a
/// server is created.
/// </returns>
public static ServerCreateResponse Create(this IServerOperations operations, ServerCreateParameters parameters)
{
return Task.Factory.StartNew((object s) =>
{
return ((IServerOperations)s).CreateAsync(parameters);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Provisions a new SQL Database server in a subscription.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.Sql.IServerOperations.
/// </param>
/// <param name='parameters'>
/// Required. The parameters needed to provision a server.
/// </param>
/// <returns>
/// The response returned from the Create Server operation. This
/// contains all the information returned from the service when a
/// server is created.
/// </returns>
public static Task<ServerCreateResponse> CreateAsync(this IServerOperations operations, ServerCreateParameters parameters)
{
return operations.CreateAsync(parameters, CancellationToken.None);
}
/// <summary>
/// Deletes the specified Azure SQL Database Server from a subscription.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.Sql.IServerOperations.
/// </param>
/// <param name='serverName'>
/// Required. The name of the Azure SQL Database Server to be deleted.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public static AzureOperationResponse Delete(this IServerOperations operations, string serverName)
{
return Task.Factory.StartNew((object s) =>
{
return ((IServerOperations)s).DeleteAsync(serverName);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Deletes the specified Azure SQL Database Server from a subscription.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.Sql.IServerOperations.
/// </param>
/// <param name='serverName'>
/// Required. The name of the Azure SQL Database Server to be deleted.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public static Task<AzureOperationResponse> DeleteAsync(this IServerOperations operations, string serverName)
{
return operations.DeleteAsync(serverName, CancellationToken.None);
}
/// <summary>
/// Returns all SQL Database Servers that are provisioned for a
/// subscription.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.Sql.IServerOperations.
/// </param>
/// <returns>
/// The response structure for the Server List operation. Contains a
/// list of all the servers in a subscription.
/// </returns>
public static ServerListResponse List(this IServerOperations operations)
{
return Task.Factory.StartNew((object s) =>
{
return ((IServerOperations)s).ListAsync();
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Returns all SQL Database Servers that are provisioned for a
/// subscription.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.WindowsAzure.Management.Sql.IServerOperations.
/// </param>
/// <returns>
/// The response structure for the Server List operation. Contains a
/// list of all the servers in a subscription.
/// </returns>
public static Task<ServerListResponse> ListAsync(this IServerOperations operations)
{
return operations.ListAsync(CancellationToken.None);
}
}
}
| |
using System;
using System.ComponentModel;
using System.Linq;
using Umbraco.Core;
using Umbraco.Core.Sync;
using umbraco.interfaces;
namespace Umbraco.Web.Cache
{
/// <summary>
/// Represents the entry point into Umbraco's distributed cache infrastructure.
/// </summary>
/// <remarks>
/// <para>
/// The distributed cache infrastructure ensures that distributed caches are
/// invalidated properly in load balancing environments.
/// </para>
/// <para>
/// Distribute caches include static (in-memory) cache, runtime cache, front-end content cache, Examine/Lucene indexes
/// </para>
/// </remarks>
public sealed class DistributedCache
{
#region Public constants/Ids
public const string ApplicationTreeCacheRefresherId = "0AC6C028-9860-4EA4-958D-14D39F45886E";
public const string ApplicationCacheRefresherId = "B15F34A1-BC1D-4F8B-8369-3222728AB4C8";
public const string TemplateRefresherId = "DD12B6A0-14B9-46e8-8800-C154F74047C8";
public const string PageCacheRefresherId = "27AB3022-3DFA-47b6-9119-5945BC88FD66";
public const string UnpublishedPageCacheRefresherId = "55698352-DFC5-4DBE-96BD-A4A0F6F77145";
public const string MemberCacheRefresherId = "E285DF34-ACDC-4226-AE32-C0CB5CF388DA";
public const string MemberGroupCacheRefresherId = "187F236B-BD21-4C85-8A7C-29FBA3D6C00C";
public const string MediaCacheRefresherId = "B29286DD-2D40-4DDB-B325-681226589FEC";
public const string MacroCacheRefresherId = "7B1E683C-5F34-43dd-803D-9699EA1E98CA";
public const string UserCacheRefresherId = "E057AF6D-2EE6-41F4-8045-3694010F0AA6";
public const string UserPermissionsCacheRefresherId = "840AB9C5-5C0B-48DB-A77E-29FE4B80CD3A";
public const string UserTypeCacheRefresherId = "7E707E21-0195-4522-9A3C-658CC1761BD4";
public const string ContentTypeCacheRefresherId = "6902E22C-9C10-483C-91F3-66B7CAE9E2F5";
public const string LanguageCacheRefresherId = "3E0F95D8-0BE5-44B8-8394-2B8750B62654";
public const string DomainCacheRefresherId = "11290A79-4B57-4C99-AD72-7748A3CF38AF";
public const string StylesheetCacheRefresherId = "E0633648-0DEB-44AE-9A48-75C3A55CB670";
public const string StylesheetPropertyCacheRefresherId = "2BC7A3A4-6EB1-4FBC-BAA3-C9E7B6D36D38";
public const string DataTypeCacheRefresherId = "35B16C25-A17E-45D7-BC8F-EDAB1DCC28D2";
public const string DictionaryCacheRefresherId = "D1D7E227-F817-4816-BFE9-6C39B6152884";
public const string PublicAccessCacheRefresherId = "1DB08769-B104-4F8B-850E-169CAC1DF2EC";
public static readonly Guid ApplicationTreeCacheRefresherGuid = new Guid(ApplicationTreeCacheRefresherId);
public static readonly Guid ApplicationCacheRefresherGuid = new Guid(ApplicationCacheRefresherId);
public static readonly Guid TemplateRefresherGuid = new Guid(TemplateRefresherId);
public static readonly Guid PageCacheRefresherGuid = new Guid(PageCacheRefresherId);
public static readonly Guid UnpublishedPageCacheRefresherGuid = new Guid(UnpublishedPageCacheRefresherId);
public static readonly Guid MemberCacheRefresherGuid = new Guid(MemberCacheRefresherId);
public static readonly Guid MemberGroupCacheRefresherGuid = new Guid(MemberGroupCacheRefresherId);
public static readonly Guid MediaCacheRefresherGuid = new Guid(MediaCacheRefresherId);
public static readonly Guid MacroCacheRefresherGuid = new Guid(MacroCacheRefresherId);
public static readonly Guid UserCacheRefresherGuid = new Guid(UserCacheRefresherId);
public static readonly Guid UserPermissionsCacheRefresherGuid = new Guid(UserPermissionsCacheRefresherId);
public static readonly Guid UserTypeCacheRefresherGuid = new Guid(UserTypeCacheRefresherId);
public static readonly Guid ContentTypeCacheRefresherGuid = new Guid(ContentTypeCacheRefresherId);
public static readonly Guid LanguageCacheRefresherGuid = new Guid(LanguageCacheRefresherId);
public static readonly Guid DomainCacheRefresherGuid = new Guid(DomainCacheRefresherId);
public static readonly Guid StylesheetCacheRefresherGuid = new Guid(StylesheetCacheRefresherId);
public static readonly Guid StylesheetPropertyCacheRefresherGuid = new Guid(StylesheetPropertyCacheRefresherId);
public static readonly Guid DataTypeCacheRefresherGuid = new Guid(DataTypeCacheRefresherId);
public static readonly Guid DictionaryCacheRefresherGuid = new Guid(DictionaryCacheRefresherId);
public static readonly Guid PublicAccessCacheRefresherGuid = new Guid(PublicAccessCacheRefresherId);
#endregion
#region Constructor & Singleton
// note - should inject into the application instead of using a singleton
private static readonly DistributedCache InstanceObject = new DistributedCache();
/// <summary>
/// Initializes a new instance of the <see cref="DistributedCache"/> class.
/// </summary>
private DistributedCache()
{ }
/// <summary>
/// Gets the static unique instance of the <see cref="DistributedCache"/> class.
/// </summary>
/// <returns>The static unique instance of the <see cref="DistributedCache"/> class.</returns>
/// <remarks>Exists so that extension methods can be added to the distributed cache.</remarks>
public static DistributedCache Instance
{
get
{
return InstanceObject;
}
}
#endregion
#region Core notification methods
/// <summary>
/// Notifies the distributed cache of specifieds item invalidation, for a specified <see cref="ICacheRefresher"/>.
/// </summary>
/// <typeparam name="T">The type of the invalidated items.</typeparam>
/// <param name="factoryGuid">The unique identifier of the ICacheRefresher.</param>
/// <param name="getNumericId">A function returning the unique identifier of items.</param>
/// <param name="instances">The invalidated items.</param>
/// <remarks>
/// This method is much better for performance because it does not need to re-lookup object instances.
/// </remarks>
public void Refresh<T>(Guid factoryGuid, Func<T, int> getNumericId, params T[] instances)
{
if (factoryGuid == Guid.Empty || instances.Length == 0 || getNumericId == null) return;
ServerMessengerResolver.Current.Messenger.PerformRefresh(
ServerRegistrarResolver.Current.Registrar.Registrations,
GetRefresherById(factoryGuid),
getNumericId,
instances);
}
/// <summary>
/// Notifies the distributed cache of a specified item invalidation, for a specified <see cref="ICacheRefresher"/>.
/// </summary>
/// <param name="factoryGuid">The unique identifier of the ICacheRefresher.</param>
/// <param name="id">The unique identifier of the invalidated item.</param>
public void Refresh(Guid factoryGuid, int id)
{
if (factoryGuid == Guid.Empty || id == default(int)) return;
ServerMessengerResolver.Current.Messenger.PerformRefresh(
ServerRegistrarResolver.Current.Registrar.Registrations,
GetRefresherById(factoryGuid),
id);
}
/// <summary>
/// Notifies the distributed cache of a specified item invalidation, for a specified <see cref="ICacheRefresher"/>.
/// </summary>
/// <param name="factoryGuid">The unique identifier of the ICacheRefresher.</param>
/// <param name="id">The unique identifier of the invalidated item.</param>
public void Refresh(Guid factoryGuid, Guid id)
{
if (factoryGuid == Guid.Empty || id == Guid.Empty) return;
ServerMessengerResolver.Current.Messenger.PerformRefresh(
ServerRegistrarResolver.Current.Registrar.Registrations,
GetRefresherById(factoryGuid),
id);
}
public void RefreshByPayload(Guid factoryGuid, object payload)
{
if (factoryGuid == Guid.Empty || payload == null) return;
ServerMessengerResolver.Current.Messenger.PerformRefresh(
ServerRegistrarResolver.Current.Registrar.Registrations,
GetRefresherById(factoryGuid),
payload);
}
/// <summary>
/// Notifies the distributed cache, for a specified <see cref="ICacheRefresher"/>.
/// </summary>
/// <param name="factoryGuid">The unique identifier of the ICacheRefresher.</param>
/// <param name="jsonPayload">The notification content.</param>
public void RefreshByJson(Guid factoryGuid, string jsonPayload)
{
if (factoryGuid == Guid.Empty || jsonPayload.IsNullOrWhiteSpace()) return;
ServerMessengerResolver.Current.Messenger.PerformRefresh(
ServerRegistrarResolver.Current.Registrar.Registrations,
GetRefresherById(factoryGuid),
jsonPayload);
}
///// <summary>
///// Notifies the distributed cache, for a specified <see cref="ICacheRefresher"/>.
///// </summary>
///// <param name="refresherId">The unique identifier of the ICacheRefresher.</param>
///// <param name="payload">The notification content.</param>
//internal void Notify(Guid refresherId, object payload)
//{
// if (refresherId == Guid.Empty || payload == null) return;
// ServerMessengerResolver.Current.Messenger.Notify(
// ServerRegistrarResolver.Current.Registrar.Registrations,
// GetRefresherById(refresherId),
// json);
//}
/// <summary>
/// Notifies the distributed cache of a global invalidation for a specified <see cref="ICacheRefresher"/>.
/// </summary>
/// <param name="factoryGuid">The unique identifier of the ICacheRefresher.</param>
public void RefreshAll(Guid factoryGuid)
{
if (factoryGuid == Guid.Empty) return;
ServerMessengerResolver.Current.Messenger.PerformRefreshAll(
ServerRegistrarResolver.Current.Registrar.Registrations,
GetRefresherById(factoryGuid));
}
[EditorBrowsable(EditorBrowsableState.Never)]
[Obsolete("This method is no longer in use and does not work as advertised, the allServers parameter doesnt have any affect for database server messengers, do not use!")]
public void RefreshAll(Guid factoryGuid, bool allServers)
{
if (factoryGuid == Guid.Empty) return;
if (allServers)
{
RefreshAll(factoryGuid);
}
else
{
ServerMessengerResolver.Current.Messenger.PerformRefreshAll(
Enumerable.Empty<IServerAddress>(),
GetRefresherById(factoryGuid));
}
}
/// <summary>
/// Notifies the distributed cache of a specified item removal, for a specified <see cref="ICacheRefresher"/>.
/// </summary>
/// <param name="factoryGuid">The unique identifier of the ICacheRefresher.</param>
/// <param name="id">The unique identifier of the removed item.</param>
public void Remove(Guid factoryGuid, int id)
{
if (factoryGuid == Guid.Empty || id == default(int)) return;
ServerMessengerResolver.Current.Messenger.PerformRemove(
ServerRegistrarResolver.Current.Registrar.Registrations,
GetRefresherById(factoryGuid),
id);
}
/// <summary>
/// Notifies the distributed cache of specifieds item removal, for a specified <see cref="ICacheRefresher"/>.
/// </summary>
/// <typeparam name="T">The type of the removed items.</typeparam>
/// <param name="factoryGuid">The unique identifier of the ICacheRefresher.</param>
/// <param name="getNumericId">A function returning the unique identifier of items.</param>
/// <param name="instances">The removed items.</param>
/// <remarks>
/// This method is much better for performance because it does not need to re-lookup object instances.
/// </remarks>
public void Remove<T>(Guid factoryGuid, Func<T, int> getNumericId, params T[] instances)
{
ServerMessengerResolver.Current.Messenger.PerformRemove(
ServerRegistrarResolver.Current.Registrar.Registrations,
GetRefresherById(factoryGuid),
getNumericId,
instances);
}
#endregion
// helper method to get an ICacheRefresher by its unique identifier
private static ICacheRefresher GetRefresherById(Guid uniqueIdentifier)
{
return CacheRefreshersResolver.Current.GetById(uniqueIdentifier);
}
}
}
| |
// 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.Runtime.Versioning;
using System.Diagnostics.Contracts;
namespace System.Globalization
{
////////////////////////////////////////////////////////////////////////////
//
// Rules for the Hijri calendar:
// - The Hijri calendar is a strictly Lunar calendar.
// - Days begin at sunset.
// - Islamic Year 1 (Muharram 1, 1 A.H.) is equivalent to absolute date
// 227015 (Friday, July 16, 622 C.E. - Julian).
// - Leap Years occur in the 2, 5, 7, 10, 13, 16, 18, 21, 24, 26, & 29th
// years of a 30-year cycle. Year = leap iff ((11y+14) mod 30 < 11).
// - There are 12 months which contain alternately 30 and 29 days.
// - The 12th month, Dhu al-Hijjah, contains 30 days instead of 29 days
// in a leap year.
// - Common years have 354 days. Leap years have 355 days.
// - There are 10,631 days in a 30-year cycle.
// - The Islamic months are:
// 1. Muharram (30 days) 7. Rajab (30 days)
// 2. Safar (29 days) 8. Sha'ban (29 days)
// 3. Rabi I (30 days) 9. Ramadan (30 days)
// 4. Rabi II (29 days) 10. Shawwal (29 days)
// 5. Jumada I (30 days) 11. Dhu al-Qada (30 days)
// 6. Jumada II (29 days) 12. Dhu al-Hijjah (29 days) {30}
//
// NOTENOTE
// The calculation of the HijriCalendar is based on the absolute date. And the
// absolute date means the number of days from January 1st, 1 A.D.
// Therefore, we do not support the days before the January 1st, 1 A.D.
//
////////////////////////////////////////////////////////////////////////////
/*
** Calendar support range:
** Calendar Minimum Maximum
** ========== ========== ==========
** Gregorian 0622/07/18 9999/12/31
** Hijri 0001/01/01 9666/04/03
*/
[System.Runtime.InteropServices.ComVisible(true)]
public partial class HijriCalendar : Calendar
{
internal static readonly int HijriEra = 1;
internal const int DatePartYear = 0;
internal const int DatePartDayOfYear = 1;
internal const int DatePartMonth = 2;
internal const int DatePartDay = 3;
internal const int MinAdvancedHijri = -2;
internal const int MaxAdvancedHijri = 2;
internal static readonly int[] HijriMonthDays = { 0, 30, 59, 89, 118, 148, 177, 207, 236, 266, 295, 325, 355 };
//internal static Calendar m_defaultInstance;
private int _hijriAdvance = Int32.MinValue;
// DateTime.MaxValue = Hijri calendar (year:9666, month: 4, day: 3).
internal const int MaxCalendarYear = 9666;
internal const int MaxCalendarMonth = 4;
internal const int MaxCalendarDay = 3;
// Hijri calendar (year: 1, month: 1, day:1 ) = Gregorian (year: 622, month: 7, day: 18)
// This is the minimal Gregorian date that we support in the HijriCalendar.
internal static readonly DateTime calendarMinValue = new DateTime(622, 7, 18);
internal static readonly DateTime calendarMaxValue = DateTime.MaxValue;
[System.Runtime.InteropServices.ComVisible(false)]
public override DateTime MinSupportedDateTime
{
get
{
return (calendarMinValue);
}
}
[System.Runtime.InteropServices.ComVisible(false)]
public override DateTime MaxSupportedDateTime
{
get
{
return (calendarMaxValue);
}
}
/*=================================GetDefaultInstance==========================
**Action: Internal method to provide a default intance of HijriCalendar. Used by NLS+ implementation
** and other calendars.
**Returns:
**Arguments:
**Exceptions:
============================================================================*/
/*
internal static Calendar GetDefaultInstance() {
if (m_defaultInstance == null) {
m_defaultInstance = new HijriCalendar();
}
return (m_defaultInstance);
}
*/
// Construct an instance of Hijri calendar.
public HijriCalendar()
{
}
internal override CalendarId ID
{
get
{
return CalendarId.HIJRI;
}
}
protected override int DaysInYearBeforeMinSupportedYear
{
get
{
// the year before the 1st year of the cycle would have been the 30th year
// of the previous cycle which is not a leap year. Common years have 354 days.
return 354;
}
}
/*=================================GetAbsoluteDateHijri==========================
**Action: Gets the Absolute date for the given Hijri date. The absolute date means
** the number of days from January 1st, 1 A.D.
**Returns:
**Arguments:
**Exceptions:
============================================================================*/
private long GetAbsoluteDateHijri(int y, int m, int d)
{
return (long)(DaysUpToHijriYear(y) + HijriMonthDays[m - 1] + d - 1 - HijriAdjustment);
}
/*=================================DaysUpToHijriYear==========================
**Action: Gets the total number of days (absolute date) up to the given Hijri Year.
** The absolute date means the number of days from January 1st, 1 A.D.
**Returns: Gets the total number of days (absolute date) up to the given Hijri Year.
**Arguments: HijriYear year value in Hijri calendar.
**Exceptions: None
**Notes:
============================================================================*/
private long DaysUpToHijriYear(int HijriYear)
{
long NumDays; // number of absolute days
int NumYear30; // number of years up to current 30 year cycle
int NumYearsLeft; // number of years into 30 year cycle
//
// Compute the number of years up to the current 30 year cycle.
//
NumYear30 = ((HijriYear - 1) / 30) * 30;
//
// Compute the number of years left. This is the number of years
// into the 30 year cycle for the given year.
//
NumYearsLeft = HijriYear - NumYear30 - 1;
//
// Compute the number of absolute days up to the given year.
//
NumDays = ((NumYear30 * 10631L) / 30L) + 227013L;
while (NumYearsLeft > 0)
{
// Common year is 354 days, and leap year is 355 days.
NumDays += 354 + (IsLeapYear(NumYearsLeft, CurrentEra) ? 1 : 0);
NumYearsLeft--;
}
//
// Return the number of absolute days.
//
return (NumDays);
}
public int HijriAdjustment
{
[System.Security.SecuritySafeCritical] // auto-generated
get
{
if (_hijriAdvance == Int32.MinValue)
{
// Never been set before. Use the system value from registry.
_hijriAdvance = GetHijriDateAdjustment();
}
return (_hijriAdvance);
}
set
{
// NOTE: Check the value of Min/MaxAdavncedHijri with Arabic speakers to see if the assumption is good.
if (value < MinAdvancedHijri || value > MaxAdvancedHijri)
{
throw new ArgumentOutOfRangeException(
"HijriAdjustment",
String.Format(
CultureInfo.CurrentCulture,
SR.ArgumentOutOfRange_Bounds_Lower_Upper,
MinAdvancedHijri,
MaxAdvancedHijri));
}
Contract.EndContractBlock();
VerifyWritable();
_hijriAdvance = value;
}
}
static internal void CheckTicksRange(long ticks)
{
if (ticks < calendarMinValue.Ticks || ticks > calendarMaxValue.Ticks)
{
throw new ArgumentOutOfRangeException(
"time",
String.Format(
CultureInfo.InvariantCulture,
SR.ArgumentOutOfRange_CalendarRange,
calendarMinValue,
calendarMaxValue));
}
}
static internal void CheckEraRange(int era)
{
if (era != CurrentEra && era != HijriEra)
{
throw new ArgumentOutOfRangeException("era", SR.ArgumentOutOfRange_InvalidEraValue);
}
}
static internal void CheckYearRange(int year, int era)
{
CheckEraRange(era);
if (year < 1 || year > MaxCalendarYear)
{
throw new ArgumentOutOfRangeException(
"year",
String.Format(
CultureInfo.CurrentCulture,
SR.ArgumentOutOfRange_Range,
1,
MaxCalendarYear));
}
}
static internal void CheckYearMonthRange(int year, int month, int era)
{
CheckYearRange(year, era);
if (year == MaxCalendarYear)
{
if (month > MaxCalendarMonth)
{
throw new ArgumentOutOfRangeException(
"month",
String.Format(
CultureInfo.CurrentCulture,
SR.ArgumentOutOfRange_Range,
1,
MaxCalendarMonth));
}
}
if (month < 1 || month > 12)
{
throw new ArgumentOutOfRangeException("month", SR.ArgumentOutOfRange_Month);
}
}
/*=================================GetDatePart==========================
**Action: Returns a given date part of this <i>DateTime</i>. This method is used
** to compute the year, day-of-year, month, or day part.
**Returns:
**Arguments:
**Exceptions: ArgumentException if part is incorrect.
**Notes:
** First, we get the absolute date (the number of days from January 1st, 1 A.C) for the given ticks.
** Use the formula (((AbsoluteDate - 227013) * 30) / 10631) + 1, we can a rough value for the Hijri year.
** In order to get the exact Hijri year, we compare the exact absolute date for HijriYear and (HijriYear + 1).
** From here, we can get the correct Hijri year.
============================================================================*/
internal virtual int GetDatePart(long ticks, int part)
{
int HijriYear; // Hijri year
int HijriMonth; // Hijri month
int HijriDay; // Hijri day
long NumDays; // The calculation buffer in number of days.
CheckTicksRange(ticks);
//
// Get the absolute date. The absolute date is the number of days from January 1st, 1 A.D.
// 1/1/0001 is absolute date 1.
//
NumDays = ticks / GregorianCalendar.TicksPerDay + 1;
//
// See how much we need to backup or advance
//
NumDays += HijriAdjustment;
//
// Calculate the appromixate Hijri Year from this magic formula.
//
HijriYear = (int)(((NumDays - 227013) * 30) / 10631) + 1;
long daysToHijriYear = DaysUpToHijriYear(HijriYear); // The absoulte date for HijriYear
long daysOfHijriYear = GetDaysInYear(HijriYear, CurrentEra); // The number of days for (HijriYear+1) year.
if (NumDays < daysToHijriYear)
{
daysToHijriYear -= daysOfHijriYear;
HijriYear--;
}
else if (NumDays == daysToHijriYear)
{
HijriYear--;
daysToHijriYear -= GetDaysInYear(HijriYear, CurrentEra);
}
else
{
if (NumDays > daysToHijriYear + daysOfHijriYear)
{
daysToHijriYear += daysOfHijriYear;
HijriYear++;
}
}
if (part == DatePartYear)
{
return (HijriYear);
}
//
// Calculate the Hijri Month.
//
HijriMonth = 1;
NumDays -= daysToHijriYear;
if (part == DatePartDayOfYear)
{
return ((int)NumDays);
}
while ((HijriMonth <= 12) && (NumDays > HijriMonthDays[HijriMonth - 1]))
{
HijriMonth++;
}
HijriMonth--;
if (part == DatePartMonth)
{
return (HijriMonth);
}
//
// Calculate the Hijri Day.
//
HijriDay = (int)(NumDays - HijriMonthDays[HijriMonth - 1]);
if (part == DatePartDay)
{
return (HijriDay);
}
// Incorrect part value.
throw new InvalidOperationException(SR.InvalidOperation_DateTimeParsing);
}
// 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,
SR.ArgumentOutOfRange_Range,
-120000,
120000));
}
Contract.EndContractBlock();
// Get the date in Hijri calendar.
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 days = GetDaysInMonth(y, m);
if (d > days)
{
d = days;
}
long ticks = GetAbsoluteDateHijri(y, m, d) * TicksPerDay + (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.
//
[Pure]
public override int GetDaysInMonth(int year, int month, int era)
{
CheckYearMonthRange(year, month, era);
if (month == 12)
{
// For the 12th month, leap year has 30 days, and common year has 29 days.
return (IsLeapYear(year, CurrentEra) ? 30 : 29);
}
// Other months contain 30 and 29 days alternatively. The 1st month has 30 days.
return (((month % 2) == 1) ? 30 : 29);
}
// 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)
{
CheckYearRange(year, era);
// Common years have 354 days. Leap years have 355 days.
return (IsLeapYear(year, CurrentEra) ? 355 : 354);
}
// Returns the era for the specified DateTime value.
public override int GetEra(DateTime time)
{
CheckTicksRange(time.Ticks);
return (HijriEra);
}
public override int[] Eras
{
get
{
return (new int[] { HijriEra });
}
}
// 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)
{
CheckYearRange(year, era);
return (12);
}
// Returns the year part of the specified DateTime. The returned value is an
// integer between 1 and MaxCalendarYear.
//
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)
{
// The year/month/era value checking is done in GetDaysInMonth().
int daysInMonth = GetDaysInMonth(year, month, era);
if (day < 1 || day > daysInMonth)
{
throw new ArgumentOutOfRangeException(
"day",
String.Format(
CultureInfo.CurrentCulture,
SR.ArgumentOutOfRange_Day,
daysInMonth,
month));
}
return (IsLeapYear(year, era) && month == 12 && day == 30);
}
// 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)
{
CheckYearRange(year, era);
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)
{
CheckYearMonthRange(year, month, era);
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)
{
CheckYearRange(year, era);
return ((((year * 11) + 14) % 30) < 11);
}
// 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)
{
// The year/month/era checking is done in GetDaysInMonth().
int daysInMonth = GetDaysInMonth(year, month, era);
if (day < 1 || day > daysInMonth)
{
throw new ArgumentOutOfRangeException(
"day",
String.Format(
CultureInfo.CurrentCulture,
SR.ArgumentOutOfRange_Day,
daysInMonth,
month));
}
long lDate = GetAbsoluteDateHijri(year, month, day);
if (lDate >= 0)
{
return (new DateTime(lDate * GregorianCalendar.TicksPerDay + TimeToTicks(hour, minute, second, millisecond)));
}
else
{
throw new ArgumentOutOfRangeException(null, SR.ArgumentOutOfRange_BadYearMonthDay);
}
}
private const int DEFAULT_TWO_DIGIT_YEAR_MAX = 1451;
public override int TwoDigitYearMax
{
get
{
if (twoDigitYearMax == -1)
{
twoDigitYearMax = GetSystemTwoDigitYearSetting(ID, DEFAULT_TWO_DIGIT_YEAR_MAX);
}
return (twoDigitYearMax);
}
set
{
VerifyWritable();
if (value < 99 || value > MaxCalendarYear)
{
throw new ArgumentOutOfRangeException(
"value",
String.Format(
CultureInfo.CurrentCulture,
SR.ArgumentOutOfRange_Range,
99,
MaxCalendarYear));
}
twoDigitYearMax = value;
}
}
public override int ToFourDigitYear(int year)
{
if (year < 0)
{
throw new ArgumentOutOfRangeException("year",
SR.ArgumentOutOfRange_NeedNonNegNum);
}
Contract.EndContractBlock();
if (year < 100)
{
return (base.ToFourDigitYear(year));
}
if (year > MaxCalendarYear)
{
throw new ArgumentOutOfRangeException(
"year",
String.Format(
CultureInfo.CurrentCulture,
SR.ArgumentOutOfRange_Range,
1,
MaxCalendarYear));
}
return (year);
}
}
}
| |
// 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.Compute.V1.Snippets
{
using Google.Api.Gax;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using lro = Google.LongRunning;
/// <summary>Generated snippets.</summary>
public sealed class GeneratedRegionCommitmentsClientSnippets
{
/// <summary>Snippet for AggregatedList</summary>
public void AggregatedListRequestObject()
{
// Snippet: AggregatedList(AggregatedListRegionCommitmentsRequest, CallSettings)
// Create client
RegionCommitmentsClient regionCommitmentsClient = RegionCommitmentsClient.Create();
// Initialize request argument(s)
AggregatedListRegionCommitmentsRequest request = new AggregatedListRegionCommitmentsRequest
{
OrderBy = "",
Project = "",
Filter = "",
IncludeAllScopes = false,
ReturnPartialSuccess = false,
};
// Make the request
PagedEnumerable<CommitmentAggregatedList, KeyValuePair<string, CommitmentsScopedList>> response = regionCommitmentsClient.AggregatedList(request);
// Iterate over all response items, lazily performing RPCs as required
foreach (KeyValuePair<string, CommitmentsScopedList> 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 (CommitmentAggregatedList page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (KeyValuePair<string, CommitmentsScopedList> 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<KeyValuePair<string, CommitmentsScopedList>> 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 (KeyValuePair<string, CommitmentsScopedList> 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 AggregatedListAsync</summary>
public async Task AggregatedListRequestObjectAsync()
{
// Snippet: AggregatedListAsync(AggregatedListRegionCommitmentsRequest, CallSettings)
// Create client
RegionCommitmentsClient regionCommitmentsClient = await RegionCommitmentsClient.CreateAsync();
// Initialize request argument(s)
AggregatedListRegionCommitmentsRequest request = new AggregatedListRegionCommitmentsRequest
{
OrderBy = "",
Project = "",
Filter = "",
IncludeAllScopes = false,
ReturnPartialSuccess = false,
};
// Make the request
PagedAsyncEnumerable<CommitmentAggregatedList, KeyValuePair<string, CommitmentsScopedList>> response = regionCommitmentsClient.AggregatedListAsync(request);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((KeyValuePair<string, CommitmentsScopedList> 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((CommitmentAggregatedList page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (KeyValuePair<string, CommitmentsScopedList> 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<KeyValuePair<string, CommitmentsScopedList>> 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 (KeyValuePair<string, CommitmentsScopedList> 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 AggregatedList</summary>
public void AggregatedList()
{
// Snippet: AggregatedList(string, string, int?, CallSettings)
// Create client
RegionCommitmentsClient regionCommitmentsClient = RegionCommitmentsClient.Create();
// Initialize request argument(s)
string project = "";
// Make the request
PagedEnumerable<CommitmentAggregatedList, KeyValuePair<string, CommitmentsScopedList>> response = regionCommitmentsClient.AggregatedList(project);
// Iterate over all response items, lazily performing RPCs as required
foreach (KeyValuePair<string, CommitmentsScopedList> 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 (CommitmentAggregatedList page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (KeyValuePair<string, CommitmentsScopedList> 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<KeyValuePair<string, CommitmentsScopedList>> 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 (KeyValuePair<string, CommitmentsScopedList> 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 AggregatedListAsync</summary>
public async Task AggregatedListAsync()
{
// Snippet: AggregatedListAsync(string, string, int?, CallSettings)
// Create client
RegionCommitmentsClient regionCommitmentsClient = await RegionCommitmentsClient.CreateAsync();
// Initialize request argument(s)
string project = "";
// Make the request
PagedAsyncEnumerable<CommitmentAggregatedList, KeyValuePair<string, CommitmentsScopedList>> response = regionCommitmentsClient.AggregatedListAsync(project);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((KeyValuePair<string, CommitmentsScopedList> 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((CommitmentAggregatedList page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (KeyValuePair<string, CommitmentsScopedList> 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<KeyValuePair<string, CommitmentsScopedList>> 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 (KeyValuePair<string, CommitmentsScopedList> 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 Get</summary>
public void GetRequestObject()
{
// Snippet: Get(GetRegionCommitmentRequest, CallSettings)
// Create client
RegionCommitmentsClient regionCommitmentsClient = RegionCommitmentsClient.Create();
// Initialize request argument(s)
GetRegionCommitmentRequest request = new GetRegionCommitmentRequest
{
Region = "",
Project = "",
Commitment = "",
};
// Make the request
Commitment response = regionCommitmentsClient.Get(request);
// End snippet
}
/// <summary>Snippet for GetAsync</summary>
public async Task GetRequestObjectAsync()
{
// Snippet: GetAsync(GetRegionCommitmentRequest, CallSettings)
// Additional: GetAsync(GetRegionCommitmentRequest, CancellationToken)
// Create client
RegionCommitmentsClient regionCommitmentsClient = await RegionCommitmentsClient.CreateAsync();
// Initialize request argument(s)
GetRegionCommitmentRequest request = new GetRegionCommitmentRequest
{
Region = "",
Project = "",
Commitment = "",
};
// Make the request
Commitment response = await regionCommitmentsClient.GetAsync(request);
// End snippet
}
/// <summary>Snippet for Get</summary>
public void Get()
{
// Snippet: Get(string, string, string, CallSettings)
// Create client
RegionCommitmentsClient regionCommitmentsClient = RegionCommitmentsClient.Create();
// Initialize request argument(s)
string project = "";
string region = "";
string commitment = "";
// Make the request
Commitment response = regionCommitmentsClient.Get(project, region, commitment);
// End snippet
}
/// <summary>Snippet for GetAsync</summary>
public async Task GetAsync()
{
// Snippet: GetAsync(string, string, string, CallSettings)
// Additional: GetAsync(string, string, string, CancellationToken)
// Create client
RegionCommitmentsClient regionCommitmentsClient = await RegionCommitmentsClient.CreateAsync();
// Initialize request argument(s)
string project = "";
string region = "";
string commitment = "";
// Make the request
Commitment response = await regionCommitmentsClient.GetAsync(project, region, commitment);
// End snippet
}
/// <summary>Snippet for Insert</summary>
public void InsertRequestObject()
{
// Snippet: Insert(InsertRegionCommitmentRequest, CallSettings)
// Create client
RegionCommitmentsClient regionCommitmentsClient = RegionCommitmentsClient.Create();
// Initialize request argument(s)
InsertRegionCommitmentRequest request = new InsertRegionCommitmentRequest
{
RequestId = "",
Region = "",
Project = "",
CommitmentResource = new Commitment(),
};
// Make the request
lro::Operation<Operation, Operation> response = regionCommitmentsClient.Insert(request);
// Poll until the returned long-running operation is complete
lro::Operation<Operation, Operation> completedResponse = response.PollUntilCompleted();
// Retrieve the operation result
Operation result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
lro::Operation<Operation, Operation> retrievedResponse = regionCommitmentsClient.PollOnceInsert(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Operation retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for InsertAsync</summary>
public async Task InsertRequestObjectAsync()
{
// Snippet: InsertAsync(InsertRegionCommitmentRequest, CallSettings)
// Additional: InsertAsync(InsertRegionCommitmentRequest, CancellationToken)
// Create client
RegionCommitmentsClient regionCommitmentsClient = await RegionCommitmentsClient.CreateAsync();
// Initialize request argument(s)
InsertRegionCommitmentRequest request = new InsertRegionCommitmentRequest
{
RequestId = "",
Region = "",
Project = "",
CommitmentResource = new Commitment(),
};
// Make the request
lro::Operation<Operation, Operation> response = await regionCommitmentsClient.InsertAsync(request);
// Poll until the returned long-running operation is complete
lro::Operation<Operation, Operation> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
Operation result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
lro::Operation<Operation, Operation> retrievedResponse = await regionCommitmentsClient.PollOnceInsertAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Operation retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for Insert</summary>
public void Insert()
{
// Snippet: Insert(string, string, Commitment, CallSettings)
// Create client
RegionCommitmentsClient regionCommitmentsClient = RegionCommitmentsClient.Create();
// Initialize request argument(s)
string project = "";
string region = "";
Commitment commitmentResource = new Commitment();
// Make the request
lro::Operation<Operation, Operation> response = regionCommitmentsClient.Insert(project, region, commitmentResource);
// Poll until the returned long-running operation is complete
lro::Operation<Operation, Operation> completedResponse = response.PollUntilCompleted();
// Retrieve the operation result
Operation result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
lro::Operation<Operation, Operation> retrievedResponse = regionCommitmentsClient.PollOnceInsert(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Operation retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for InsertAsync</summary>
public async Task InsertAsync()
{
// Snippet: InsertAsync(string, string, Commitment, CallSettings)
// Additional: InsertAsync(string, string, Commitment, CancellationToken)
// Create client
RegionCommitmentsClient regionCommitmentsClient = await RegionCommitmentsClient.CreateAsync();
// Initialize request argument(s)
string project = "";
string region = "";
Commitment commitmentResource = new Commitment();
// Make the request
lro::Operation<Operation, Operation> response = await regionCommitmentsClient.InsertAsync(project, region, commitmentResource);
// Poll until the returned long-running operation is complete
lro::Operation<Operation, Operation> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
Operation result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
lro::Operation<Operation, Operation> retrievedResponse = await regionCommitmentsClient.PollOnceInsertAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Operation retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for List</summary>
public void ListRequestObject()
{
// Snippet: List(ListRegionCommitmentsRequest, CallSettings)
// Create client
RegionCommitmentsClient regionCommitmentsClient = RegionCommitmentsClient.Create();
// Initialize request argument(s)
ListRegionCommitmentsRequest request = new ListRegionCommitmentsRequest
{
Region = "",
OrderBy = "",
Project = "",
Filter = "",
ReturnPartialSuccess = false,
};
// Make the request
PagedEnumerable<CommitmentList, Commitment> response = regionCommitmentsClient.List(request);
// Iterate over all response items, lazily performing RPCs as required
foreach (Commitment 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 (CommitmentList page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (Commitment 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<Commitment> 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 (Commitment 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 ListAsync</summary>
public async Task ListRequestObjectAsync()
{
// Snippet: ListAsync(ListRegionCommitmentsRequest, CallSettings)
// Create client
RegionCommitmentsClient regionCommitmentsClient = await RegionCommitmentsClient.CreateAsync();
// Initialize request argument(s)
ListRegionCommitmentsRequest request = new ListRegionCommitmentsRequest
{
Region = "",
OrderBy = "",
Project = "",
Filter = "",
ReturnPartialSuccess = false,
};
// Make the request
PagedAsyncEnumerable<CommitmentList, Commitment> response = regionCommitmentsClient.ListAsync(request);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((Commitment 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((CommitmentList page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (Commitment 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<Commitment> 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 (Commitment 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 List</summary>
public void List()
{
// Snippet: List(string, string, string, int?, CallSettings)
// Create client
RegionCommitmentsClient regionCommitmentsClient = RegionCommitmentsClient.Create();
// Initialize request argument(s)
string project = "";
string region = "";
// Make the request
PagedEnumerable<CommitmentList, Commitment> response = regionCommitmentsClient.List(project, region);
// Iterate over all response items, lazily performing RPCs as required
foreach (Commitment 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 (CommitmentList page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (Commitment 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<Commitment> 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 (Commitment 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 ListAsync</summary>
public async Task ListAsync()
{
// Snippet: ListAsync(string, string, string, int?, CallSettings)
// Create client
RegionCommitmentsClient regionCommitmentsClient = await RegionCommitmentsClient.CreateAsync();
// Initialize request argument(s)
string project = "";
string region = "";
// Make the request
PagedAsyncEnumerable<CommitmentList, Commitment> response = regionCommitmentsClient.ListAsync(project, region);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((Commitment 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((CommitmentList page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (Commitment 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<Commitment> 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 (Commitment 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
}
}
}
| |
using System;
using System.Globalization;
using Orleans.Core;
using Orleans.Core.Abstractions.Internal;
namespace Orleans.Runtime
{
[Serializable]
internal class GrainId : UniqueIdentifier, IEquatable<GrainId>, IGrainIdentity
{
private static readonly object lockable = new object();
private const int INTERN_CACHE_INITIAL_SIZE = InternerConstants.SIZE_LARGE;
private static readonly TimeSpan internCacheCleanupInterval = InternerConstants.DefaultCacheCleanupFreq;
private static Interner<UniqueKey, GrainId> grainIdInternCache;
public UniqueKey.Category Category => Key.IdCategory;
public bool IsSystemTarget => Key.IsSystemTargetKey;
public bool IsGrain => Category == UniqueKey.Category.Grain || Category == UniqueKey.Category.KeyExtGrain;
public bool IsClient => Category == UniqueKey.Category.Client || Category == UniqueKey.Category.GeoClient;
internal GrainId(UniqueKey key)
: base(key)
{
}
public static GrainId NewId()
{
return FindOrCreateGrainId(UniqueKey.NewKey(Guid.NewGuid(), UniqueKey.Category.Grain));
}
public static GrainId NewClientId(string clusterId = null)
{
return NewClientId(Guid.NewGuid(), clusterId);
}
internal static GrainId NewClientId(Guid id, string clusterId = null)
{
return FindOrCreateGrainId(UniqueKey.NewKey(id,
clusterId == null ? UniqueKey.Category.Client : UniqueKey.Category.GeoClient, 0, clusterId));
}
internal static GrainId GetGrainId(UniqueKey key)
{
return FindOrCreateGrainId(key);
}
internal static GrainId GetSystemGrainId(Guid guid)
{
return FindOrCreateGrainId(UniqueKey.NewKey(guid, UniqueKey.Category.SystemGrain));
}
// For testing only.
internal static GrainId GetGrainIdForTesting(Guid guid)
{
return FindOrCreateGrainId(UniqueKey.NewKey(guid, UniqueKey.Category.None));
}
internal static GrainId NewSystemTargetGrainIdByTypeCode(int typeData)
{
return FindOrCreateGrainId(UniqueKey.NewSystemTargetKey(Guid.NewGuid(), typeData));
}
internal static GrainId GetSystemTargetGrainId(short systemGrainId)
{
return FindOrCreateGrainId(UniqueKey.NewSystemTargetKey(systemGrainId));
}
internal static GrainId GetGrainId(long typeCode, long primaryKey, string keyExt=null)
{
return FindOrCreateGrainId(UniqueKey.NewKey(primaryKey,
keyExt == null ? UniqueKey.Category.Grain : UniqueKey.Category.KeyExtGrain,
typeCode, keyExt));
}
internal static GrainId GetGrainId(long typeCode, Guid primaryKey, string keyExt=null)
{
return FindOrCreateGrainId(UniqueKey.NewKey(primaryKey,
keyExt == null ? UniqueKey.Category.Grain : UniqueKey.Category.KeyExtGrain,
typeCode, keyExt));
}
internal static GrainId GetGrainId(long typeCode, string primaryKey)
{
return FindOrCreateGrainId(UniqueKey.NewKey(0L,
UniqueKey.Category.KeyExtGrain,
typeCode, primaryKey));
}
internal static GrainId GetGrainServiceGrainId(short id, int typeData)
{
return FindOrCreateGrainId(UniqueKey.NewGrainServiceKey(id, typeData));
}
public Guid PrimaryKey
{
get { return GetPrimaryKey(); }
}
public long PrimaryKeyLong
{
get { return GetPrimaryKeyLong(); }
}
public string PrimaryKeyString
{
get { return GetPrimaryKeyString(); }
}
public string IdentityString
{
get { return ToDetailedString(); }
}
public bool IsLongKey
{
get { return Key.IsLongKey; }
}
public long GetPrimaryKeyLong(out string keyExt)
{
return Key.PrimaryKeyToLong(out keyExt);
}
internal long GetPrimaryKeyLong()
{
return Key.PrimaryKeyToLong();
}
public Guid GetPrimaryKey(out string keyExt)
{
return Key.PrimaryKeyToGuid(out keyExt);
}
internal Guid GetPrimaryKey()
{
return Key.PrimaryKeyToGuid();
}
internal string GetPrimaryKeyString()
{
string key;
var tmp = GetPrimaryKey(out key);
return key;
}
public int TypeCode => Key.BaseTypeCode;
private static GrainId FindOrCreateGrainId(UniqueKey key)
{
// Note: This is done here to avoid a wierd cyclic dependency / static initialization ordering problem involving the GrainId, Constants & Interner classes
if (grainIdInternCache != null) return grainIdInternCache.FindOrCreate(key, k => new GrainId(k));
lock (lockable)
{
if (grainIdInternCache == null)
{
grainIdInternCache = new Interner<UniqueKey, GrainId>(INTERN_CACHE_INITIAL_SIZE, internCacheCleanupInterval);
}
}
return grainIdInternCache.FindOrCreate(key, k => new GrainId(k));
}
public bool Equals(GrainId other)
{
return other != null && Key.Equals(other.Key);
}
public override bool Equals(UniqueIdentifier obj)
{
var o = obj as GrainId;
return o != null && Key.Equals(o.Key);
}
public override bool Equals(object obj)
{
var o = obj as GrainId;
return o != null && Key.Equals(o.Key);
}
// Keep compiler happy -- it does not like classes to have Equals(...) without GetHashCode() methods
public override int GetHashCode()
{
return Key.GetHashCode();
}
/// <summary>
/// Get a uniformly distributed hash code value for this grain, based on Jenkins Hash function.
/// NOTE: Hash code value may be positive or NEGATIVE.
/// </summary>
/// <returns>Hash code for this GrainId</returns>
public uint GetUniformHashCode()
{
return Key.GetUniformHashCode();
}
public override string ToString()
{
return ToStringImpl(false);
}
// same as ToString, just full primary key and type code
internal string ToDetailedString()
{
return ToStringImpl(true);
}
// same as ToString, just full primary key and type code
private string ToStringImpl(bool detailed)
{
// TODO Get name of system/target grain + name of the grain type
var keyString = Key.ToString();
// this should grab the least-significant half of n1, suffixing it with the key extension.
string idString = keyString;
if (!detailed)
{
if (keyString.Length >= 48)
idString = keyString.Substring(24, 8) + keyString.Substring(48);
else
idString = keyString.Substring(24, 8);
}
string fullString = null;
switch (Category)
{
case UniqueKey.Category.Grain:
case UniqueKey.Category.KeyExtGrain:
var typeString = TypeCode.ToString("X");
if (!detailed) typeString = typeString.Substring(Math.Max(0, typeString.Length - 8));
fullString = $"*grn/{typeString}/{idString}";
break;
case UniqueKey.Category.Client:
fullString = $"*cli/{idString}";
break;
case UniqueKey.Category.GeoClient:
fullString = $"*gcl/{Key.KeyExt}/{idString}";
break;
case UniqueKey.Category.SystemTarget:
fullString = $"*stg/{Key.N1}/{idString}";
break;
case UniqueKey.Category.SystemGrain:
fullString = $"*sgn/{Key.PrimaryKeyToGuid()}/{idString}";
break;
default:
fullString = "???/" + idString;
break;
}
return detailed ? String.Format("{0}-0x{1, 8:X8}", fullString, GetUniformHashCode()) : fullString;
}
internal string ToFullString()
{
string kx;
string pks =
Key.IsLongKey ?
GetPrimaryKeyLong(out kx).ToString(CultureInfo.InvariantCulture) :
GetPrimaryKey(out kx).ToString();
string pksHex =
Key.IsLongKey ?
GetPrimaryKeyLong(out kx).ToString("X") :
GetPrimaryKey(out kx).ToString("X");
return
String.Format(
"[GrainId: {0}, IdCategory: {1}, BaseTypeCode: {2} (x{3}), PrimaryKey: {4} (x{5}), UniformHashCode: {6} (0x{7, 8:X8}){8}]",
ToDetailedString(), // 0
Category, // 1
TypeCode, // 2
TypeCode.ToString("X"), // 3
pks, // 4
pksHex, // 5
GetUniformHashCode(), // 6
GetUniformHashCode(), // 7
Key.HasKeyExt ? String.Format(", KeyExtension: {0}", kx) : ""); // 8
}
internal string ToStringWithHashCode()
{
return String.Format("{0}-0x{1, 8:X8}", this.ToString(), this.GetUniformHashCode());
}
/// <summary>
/// Return this GrainId in a standard string form, suitable for later use with the <c>FromParsableString</c> method.
/// </summary>
/// <returns>GrainId in a standard string format.</returns>
internal string ToParsableString()
{
// NOTE: This function must be the "inverse" of FromParsableString, and data must round-trip reliably.
return Key.ToHexString();
}
/// <summary>
/// Create a new GrainId object by parsing string in a standard form returned from <c>ToParsableString</c> method.
/// </summary>
/// <param name="grainId">String containing the GrainId info to be parsed.</param>
/// <returns>New GrainId object created from the input data.</returns>
internal static GrainId FromParsableString(string grainId)
{
// NOTE: This function must be the "inverse" of ToParsableString, and data must round-trip reliably.
var key = UniqueKey.Parse(grainId);
return FindOrCreateGrainId(key);
}
}
}
| |
using System.Runtime.CompilerServices;
using Microsoft.Xna.Framework;
using Nez.PhysicsShapes;
namespace Nez.Verlet
{
/// <summary>
/// the root of the Verlet simulation. Create a World and call its update method each frame.
/// </summary>
public class VerletWorld
{
/// <summary>
/// gravity for the simulation
/// </summary>
public Vector2 Gravity = new Vector2(0, 980f);
/// <summary>
/// number of iterations that will be used for Constraint solving
/// </summary>
public int ConstraintIterations = 3;
/// <summary>
/// max number of iterations for the simulation as a whole
/// </summary>
public int MaximumStepIterations = 5;
/// <summary>
/// Bounds of the Verlet World. Particles will be confined to this space if set.
/// </summary>
public Rectangle? SimulationBounds;
/// <summary>
/// should Particles be allowed to be dragged?
/// </summary>
public bool AllowDragging = true;
/// <summary>
/// squared selection radius of the mouse pointer
/// </summary>
public float SelectionRadiusSquared = 20 * 20;
Particle _draggedParticle;
FastList<Composite> _composites = new FastList<Composite>();
// collision helpers
internal static Collider[] _colliders = new Collider[4];
Circle _tempCircle = new Circle(1);
// timing
float _leftOverTime;
float _fixedDeltaTime = 1f / 60;
int _iterationSteps;
float _fixedDeltaTimeSq;
public VerletWorld(Rectangle? simulationBounds = null)
{
SimulationBounds = simulationBounds;
_fixedDeltaTimeSq = Mathf.Pow(_fixedDeltaTime, 2);
}
#region verlet simulation
public void Update()
{
UpdateTiming();
if (AllowDragging)
HandleDragging();
for (var iteration = 1; iteration <= _iterationSteps; iteration++)
{
for (var i = _composites.Length - 1; i >= 0; i--)
{
var composite = _composites.Buffer[i];
// solve constraints
for (var s = 0; s < ConstraintIterations; s++)
composite.SolveConstraints();
// do the verlet integration
composite.UpdateParticles(_fixedDeltaTimeSq, Gravity);
// handle collisions with Nez Colliders
composite.HandleConstraintCollisions();
for (var j = 0; j < composite.Particles.Length; j++)
{
var p = composite.Particles.Buffer[j];
// optinally constrain to bounds
if (SimulationBounds.HasValue)
ConstrainParticleToBounds(p);
// optionally handle collisions with Nez Colliders
if (p.CollidesWithColliders)
HandleCollisions(p, composite.CollidesWithLayers);
}
}
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
void ConstrainParticleToBounds(Particle p)
{
var tempPos = p.Position;
var bounds = SimulationBounds.Value;
if (p.Radius == 0)
{
if (tempPos.Y > bounds.Height)
tempPos.Y = bounds.Height;
else if (tempPos.Y < bounds.Y)
tempPos.Y = bounds.Y;
if (tempPos.X < bounds.X)
tempPos.X = bounds.X;
else if (tempPos.X > bounds.Width)
tempPos.X = bounds.Width;
}
else
{
// special care for larger particles
if (tempPos.Y < bounds.Y + p.Radius)
tempPos.Y = 2f * (bounds.Y + p.Radius) - tempPos.Y;
if (tempPos.Y > bounds.Height - p.Radius)
tempPos.Y = 2f * (bounds.Height - p.Radius) - tempPos.Y;
if (tempPos.X > bounds.Width - p.Radius)
tempPos.X = 2f * (bounds.Width - p.Radius) - tempPos.X;
if (tempPos.X < bounds.X + p.Radius)
tempPos.X = 2f * (bounds.X + p.Radius) - tempPos.X;
}
p.Position = tempPos;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
void HandleCollisions(Particle p, int collidesWithLayers)
{
var collidedCount = Physics.OverlapCircleAll(p.Position, p.Radius, _colliders, collidesWithLayers);
for (var i = 0; i < collidedCount; i++)
{
var collider = _colliders[i];
if (collider.IsTrigger)
continue;
CollisionResult collisionResult;
// if we have a large enough Particle radius use a Circle for the collision check else fall back to a point
if (p.Radius < 2)
{
if (collider.Shape.PointCollidesWithShape(p.Position, out collisionResult))
{
// TODO: add a Dictionary of Collider,float that lets Colliders be setup as force volumes. The float can then be
// multiplied by the mtv here. It should be very small values, like 0.002f for example.
p.Position -= collisionResult.MinimumTranslationVector;
}
}
else
{
_tempCircle.Radius = p.Radius;
_tempCircle.position = p.Position;
if (_tempCircle.CollidesWithShape(collider.Shape, out collisionResult))
{
p.Position -= collisionResult.MinimumTranslationVector;
}
}
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
void UpdateTiming()
{
_leftOverTime += Time.DeltaTime;
_iterationSteps = Mathf.TruncateToInt(_leftOverTime / _fixedDeltaTime);
_leftOverTime -= (float) _iterationSteps * _fixedDeltaTime;
_iterationSteps = System.Math.Min(_iterationSteps, MaximumStepIterations);
}
#endregion
#region Composite management
/// <summary>
/// adds a Composite to the simulation
/// </summary>
/// <returns>The composite.</returns>
/// <param name="composite">Composite.</param>
/// <typeparam name="T">The 1st type parameter.</typeparam>
public T AddComposite<T>(T composite) where T : Composite
{
_composites.Add(composite);
return composite;
}
/// <summary>
/// removes a Composite from the simulation
/// </summary>
/// <param name="composite">Composite.</param>
public void RemoveComposite(Composite composite)
{
_composites.Remove(composite);
}
#endregion
[MethodImpl(MethodImplOptions.AggressiveInlining)]
void HandleDragging()
{
if (Input.LeftMouseButtonPressed)
{
_draggedParticle = GetNearestParticle(Input.MousePosition);
}
else if (Input.LeftMouseButtonDown)
{
if (_draggedParticle != null)
_draggedParticle.Position = Input.MousePosition;
}
else if (Input.LeftMouseButtonReleased)
{
if (_draggedParticle != null)
_draggedParticle.Position = Input.MousePosition;
_draggedParticle = null;
}
}
/// <summary>
/// gets the nearest Particle to the position. Uses the selectionRadiusSquared to determine if a Particle is near enough for consideration.
/// </summary>
/// <returns>The nearest particle.</returns>
/// <param name="position">Position.</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public Particle GetNearestParticle(Vector2 position)
{
// less than 64 and we count it
var nearestSquaredDistance = SelectionRadiusSquared;
Particle particle = null;
// find nearest point
for (var j = 0; j < _composites.Length; j++)
{
var particles = _composites.Buffer[j].Particles;
for (var i = 0; i < particles.Length; i++)
{
var p = particles.Buffer[i];
var squaredDistanceToParticle = Vector2.DistanceSquared(p.Position, position);
if (squaredDistanceToParticle <= SelectionRadiusSquared &&
(particle == null || squaredDistanceToParticle < nearestSquaredDistance))
{
particle = p;
nearestSquaredDistance = squaredDistanceToParticle;
}
}
}
return particle;
}
public void DebugRender(Batcher batcher)
{
for (var i = 0; i < _composites.Length; i++)
_composites.Buffer[i].DebugRender(batcher);
if (AllowDragging)
{
if (_draggedParticle != null)
{
batcher.DrawCircle(_draggedParticle.Position, 8, Color.White);
}
else
{
// Highlight the nearest particle within the selection radius
var particle = GetNearestParticle(Input.MousePosition);
if (particle != null)
batcher.DrawCircle(particle.Position, 8, Color.White * 0.4f);
}
}
}
}
}
| |
//
// File.cs: Provides tagging for Canon CR2 files
//
// Author:
// Mike Gemuende (mike@gemuende.be)
//
// Copyright (C) 2010 Mike Gemuende
//
// This library is free software; you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License version
// 2.1 as published by the Free Software Foundation.
//
// This library is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
// USA
//
using System;
using System.Collections.Generic;
using TagLib;
using TagLib.Image;
using TagLib.IFD;
using TagLib.IFD.Tags;
namespace TagLib.Tiff.Cr2
{
/// <summary>
/// This class extends <see cref="TagLib.Tiff.BaseTiffFile" /> to provide tagging
/// for CR2 image files.
/// </summary>
[SupportedMimeType("taglib/cr2", "cr2")]
[SupportedMimeType("image/cr2")]
[SupportedMimeType("image/x-canon-cr2")]
public class File : TagLib.Tiff.BaseTiffFile
{
#region private fields
/// <summary>
/// The Properties of the image
/// </summary>
private Properties properties;
#endregion
#region public Properties
/// <summary>
/// Gets the media properties of the file represented by the
/// current instance.
/// </summary>
/// <value>
/// A <see cref="TagLib.Properties" /> object containing the
/// media properties of the file represented by the current
/// instance.
/// </value>
public override TagLib.Properties Properties {
get { return properties; }
}
/// <summary>
/// Indicates if tags can be written back to the current file or not
/// </summary>
/// <value>
/// A <see cref="bool" /> which is true if tags can be written to the
/// current file, otherwise false.
/// </value>
public override bool Writeable {
get { return false; }
}
#endregion
#region constructors
/// <summary>
/// Constructs and initializes a new instance of <see
/// cref="File" /> for a specified path in the local file
/// system and specified read style.
/// </summary>
/// <param name="path">
/// A <see cref="string" /> object containing the path of the
/// file to use in the new instance.
/// </param>
/// <param name="propertiesStyle">
/// A <see cref="ReadStyle" /> value specifying at what level
/// of accuracy to read the media properties, or <see
/// cref="ReadStyle.None" /> to ignore the properties.
/// </param>
/// <exception cref="ArgumentNullException">
/// <paramref name="path" /> is <see langword="null" />.
/// </exception>
public File (string path, ReadStyle propertiesStyle)
: this (new File.LocalFileAbstraction (path),
propertiesStyle)
{
}
/// <summary>
/// Constructs and initializes a new instance of <see
/// cref="File" /> for a specified path in the local file
/// system.
/// </summary>
/// <param name="path">
/// A <see cref="string" /> object containing the path of the
/// file to use in the new instance.
/// </param>
/// <exception cref="ArgumentNullException">
/// <paramref name="path" /> is <see langword="null" />.
/// </exception>
public File (string path) : this (path, ReadStyle.Average)
{
}
/// <summary>
/// Constructs and initializes a new instance of <see
/// cref="File" /> for a specified file abstraction and
/// specified read style.
/// </summary>
/// <param name="abstraction">
/// A <see cref="IFileAbstraction" /> object to use when
/// reading from and writing to the file.
/// </param>
/// <param name="propertiesStyle">
/// A <see cref="ReadStyle" /> value specifying at what level
/// of accuracy to read the media properties, or <see
/// cref="ReadStyle.None" /> to ignore the properties.
/// </param>
/// <exception cref="ArgumentNullException">
/// <paramref name="abstraction" /> is <see langword="null"
/// />.
/// </exception>
public File (File.IFileAbstraction abstraction,
ReadStyle propertiesStyle) : base (abstraction)
{
Read (propertiesStyle);
}
/// <summary>
/// Constructs and initializes a new instance of <see
/// cref="File" /> for a specified file abstraction.
/// </summary>
/// <param name="abstraction">
/// A <see cref="IFileAbstraction" /> object to use when
/// reading from and writing to the file.
/// </param>
/// <exception cref="ArgumentNullException">
/// <paramref name="abstraction" /> is <see langword="null"
/// />.
/// </exception>
protected File (IFileAbstraction abstraction)
: this (abstraction, ReadStyle.Average)
{
}
#endregion
#region Public Methods
/// <summary>
/// Saves the changes made in the current instance to the
/// file it represents.
/// </summary>
public override void Save ()
{
throw new NotSupportedException ();
}
#endregion
#region private methods
/// <summary>
/// Reads the information from file with a specified read style.
/// </summary>
/// <param name="propertiesStyle">
/// A <see cref="ReadStyle" /> value specifying at what level
/// of accuracy to read the media properties, or <see
/// cref="ReadStyle.None" /> to ignore the properties.
/// </param>
private void Read (ReadStyle propertiesStyle)
{
Mode = AccessMode.Read;
try {
ImageTag = new CombinedImageTag (TagTypes.TiffIFD);
ReadFile ();
TagTypesOnDisk = TagTypes;
if (propertiesStyle != ReadStyle.None)
properties = ExtractProperties ();
} finally {
Mode = AccessMode.Closed;
}
}
/// <summary>
/// Parses the CR2 file
/// </summary>
private void ReadFile ()
{
// A CR2 file starts with a Tiff header followed by a CR2 header
uint first_ifd_offset = ReadHeader ();
uint raw_ifd_offset = ReadAdditionalCR2Header ();
ReadIFD (first_ifd_offset, 3);
ReadIFD (raw_ifd_offset, 1);
}
/// <summary>
/// Reads and validates the CR2 header started at the current position.
/// </summary>
/// <returns>
/// A <see cref="System.UInt32"/> with the offset to the IFD with the RAW data.
/// </returns>
private uint ReadAdditionalCR2Header ()
{
// CR2 Header
//
// CR2 Information:
//
// 2 bytes CR2 Magic word (CR)
// 1 byte CR2 major version (2)
// 1 byte CR2 minor version (0)
// 4 bytes Offset to RAW IFD
//
ByteVector header = ReadBlock (8);
if (header.Count != 8)
throw new CorruptFileException ("Unexpected end of CR2 header");
if (header.Mid (0, 2).ToString () != "CR")
throw new CorruptFileException("CR2 Magic (CR) expected");
byte major_version = header [2];
byte minor_version = header [3];
if (major_version != 2 || minor_version != 0)
throw new UnsupportedFormatException ("Only major version 2 and minor version 0 are supported");
uint raw_ifd_offset = header.Mid (4, 4).ToUInt (IsBigEndian);
return raw_ifd_offset;
}
/// <summary>
/// Attempts to extract the media properties of the main
/// photo.
/// </summary>
/// <returns>
/// A <see cref="Properties" /> object with a best effort guess
/// at the right values. When no guess at all can be made,
/// <see langword="null" /> is returned.
/// </returns>
private Properties ExtractProperties ()
{
int width = 0, height = 0;
IFDTag tag = GetTag (TagTypes.TiffIFD) as IFDTag;
width = (int) (tag.ExifIFD.GetLongValue (0, (ushort) ExifEntryTag.PixelXDimension) ?? 0);
height = (int) (tag.ExifIFD.GetLongValue (0, (ushort) ExifEntryTag.PixelYDimension) ?? 0);
if (width > 0 && height > 0) {
return new Properties (TimeSpan.Zero, new Codec (width, height, "Canon RAW File"));
}
return null;
}
#endregion
}
}
| |
using System;
using System.Configuration;
using System.Linq;
using System.Threading;
using FluentAssertions;
using MongoDB.Driver;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace NLog.MongoDB.Tests
{
[TestClass]
public class IntegrationTests
{
private MongoDatabase _db;
private MongoServer _server;
[TestInitialize]
public void Init()
{
var connectionString = ConfigurationManager.ConnectionStrings["MongoDB"].ConnectionString;
var connectionStringBuilder = new MongoUrlBuilder(connectionString);
var mongoClient = new MongoClient(connectionStringBuilder.ToMongoUrl());
_server = mongoClient.GetServer();
var dbName = connectionStringBuilder.DatabaseName;
_db = _server.GetDatabase(dbName);
}
[TestCleanup]
public void CleanUp()
{
_server.Disconnect();
}
[TestMethod]
public void Test_DynamicFields()
{
const string loggerName = "testDynamicFields";
var collection = _db.GetCollection(loggerName);
// Clear out test collection
collection.RemoveAll();
var logger = LogManager.GetLogger(loggerName);
logger.LogException(
LogLevel.Error,
"Test Log Message",
new Exception("Test Exception", new Exception("Inner Exception")));
Thread.Sleep(2000);
collection.FindAll().Count().Should().Be(1);
var logEntry = collection.FindAll().First();
Assert.IsTrue(logEntry.Contains("_id"));
logEntry["level"].Should().Be(LogLevel.Error.ToString());
logEntry["message"].Should().Be("Test Log Message");
logEntry["exception"].Should().Be("Test Exception");
// Clean-up
_db.DropCollection(loggerName);
}
[TestMethod]
public void Test_DynamicFields_Without_Exception()
{
const string loggerName = "testDynamicFields";
var collection = _db.GetCollection(loggerName);
// Clear out test collection
collection.RemoveAll();
var logger = LogManager.GetLogger(loggerName);
logger.Log(
LogLevel.Error,
"Test Log Message");
Thread.Sleep(2000);
collection.FindAll().Count().Should().Be(1);
var logEntry = collection.FindAll().First();
Assert.IsTrue(logEntry.Contains("_id"));
Assert.IsFalse(logEntry.Contains("exception"));
logEntry["level"].Should().Be(LogLevel.Error.ToString());
logEntry["message"].Should().Be("Test Log Message");
// Clean-up
_db.DropCollection(loggerName);
}
[TestMethod]
public void Test_DynamicTypedFields()
{
const string loggerName = "testDynamicTypedFields";
var collection = _db.GetCollection(loggerName);
collection.RemoveAll();
var logger = LogManager.GetLogger(loggerName);
var logEventTime = DateTime.UtcNow;
var logEvent = new LogEventInfo
{
TimeStamp = logEventTime,
LoggerName = loggerName,
Level = LogLevel.Error,
Message = "Test Log Message",
Exception = new Exception("Test Exception", new Exception("Inner Exception"))
};
logEvent.Properties.Add("transactionId", 1);
logger.Log(logEvent);
Thread.Sleep(2000);
collection.FindAll().Count().Should().Be(1);
var logEntry = collection.FindAll().First();
Assert.IsTrue(logEntry.Contains("_id"));
Assert.AreEqual(logEventTime.Date, logEntry["timestamp"].ToUniversalTime().Date);
logEntry["level"].Should().Be(LogLevel.Error.ToString());
logEntry["message"].Should().Be("Test Log Message");
var exception = logEntry["exception"].AsBsonDocument;
Assert.AreEqual("Test Exception", exception["message"].AsString);
var innerException = exception["innerException"].AsBsonDocument;
Assert.AreEqual("Inner Exception", innerException["message"].AsString);
Assert.AreEqual(1, logEntry["transactionId"].AsInt32);
_db.DropCollection(loggerName);
}
[TestMethod]
public void Test_Capped_Collection_With_Id()
{
const string loggerName = "cappedWithId";
_db.DropCollection(loggerName);
var collection = _db.GetCollection(loggerName);
var logger = LogManager.GetLogger(loggerName);
var logEventTime = DateTime.UtcNow;
var logEvent = new LogEventInfo
{
Level = LogLevel.Info,
TimeStamp = logEventTime,
LoggerName = loggerName
};
logger.Log(logEvent);
Thread.Sleep(2000);
collection.FindAll().Count().Should().Be(1);
var logEntry = collection.FindAll().First();
Assert.IsTrue(logEntry.Contains("_id"));
_db.DropCollection(loggerName);
}
[TestMethod, Ignore]// "Mongo driver is adding an ID regardless of the settings we set."
public void Test_Capped_Collection_Without_Id()
{
const string loggerName = "cappedWithoutId";
_db.DropCollection(loggerName);
var logger = LogManager.GetLogger(loggerName);
var logEventTime = DateTime.UtcNow;
var logEvent = new LogEventInfo
{
Level = LogLevel.Info,
TimeStamp = logEventTime,
LoggerName = loggerName
};
logger.Log(logEvent);
Thread.Sleep(2000);
var collection = _db.GetCollection(loggerName, new MongoCollectionSettings { AssignIdOnInsert = false });
collection.FindAll().Count().Should().Be(1);
var logEntry = collection.FindAll().First();
collection.IsCapped()
.Should().BeTrue("since we set it to be true in the configuration");
logEntry.Contains("_id")
.Should().BeFalse("since we set id-capture to false in the configuration");
collection.Settings.AssignIdOnInsert
.Should().BeFalse("since we set up the collection this way");
_db.DropCollection(loggerName);
}
[TestMethod]
public void Test_ConnectionName()
{
var connectionString = ConfigurationManager.ConnectionStrings["MongoDB"].ConnectionString;
var connectionStringBuilder = new MongoUrlBuilder(connectionString);
TestMongoConnection(
_server,
connectionStringBuilder.DatabaseName,
"testMongoConnectionName");
}
[TestMethod]
public void Test_ConnectionString()
{
var connectionString = ConfigurationManager.ConnectionStrings["MongoDB"].ConnectionString;
var connectionStringBuilder = new MongoUrlBuilder(connectionString);
TestMongoConnection(
_server,
connectionStringBuilder.DatabaseName,
"testMongoConnectionString");
}
#region Helpers
private void TestMongoConnection(MongoServer server, string database, string loggerName)
{
var db = server.GetDatabase(database);
var collection = db.GetCollection(loggerName);
// Clear out test collection
collection.RemoveAll();
var logger = LogManager.GetLogger(loggerName);
logger.LogException(
LogLevel.Error,
"Test Log Message",
new Exception("Test Exception", new Exception("Inner Exception")));
Thread.Sleep(2000);
collection.FindAll().Count().Should().Be(1);
var logEntry = collection.FindAll().First();
Assert.IsTrue(logEntry.Contains("_id"));
logEntry["level"].Should().Be(LogLevel.Error.ToString());
logEntry["message"].Should().Be("Test Log Message");
var exception = logEntry["exception"].AsBsonDocument;
exception["message"].Should().Be("Test Exception");
var innerException = exception["innerException"].AsBsonDocument;
innerException["message"].Should().Be("Inner Exception");
// Clean-up
db.DropCollection(loggerName);
server.Disconnect();
}
#endregion
}
}
| |
/********************************************************************
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.
*********************************************************************/
using System;
using System.Collections.Generic;
using System.Text;
using System.Diagnostics;
using System.IO;
using log4net;
using Axiom.Animating;
using Multiverse.Interface; // for UIScripting
using Multiverse.AssetRepository;
using Multiverse.Utility; // for TimeTool
using Multiverse.Lib.LogUtil;
namespace Multiverse.Base
{
public delegate void WorldInitializedHandler(object sender, EventArgs e);
public delegate void FrameStartedHandler(object sender, ScriptingFrameEventArgs e);
public delegate void FrameEndedHandler(object sender, ScriptingFrameEventArgs e);
public class ScriptingFrameEventArgs : EventArgs
{
protected float time;
public ScriptingFrameEventArgs(float time)
: base()
{
this.time = time;
}
public float TimeSinceLastFrame
{
get
{
return time;
}
}
}
public class ClientAPI
{
private static readonly log4net.ILog log = log4net.LogManager.GetLogger(typeof(ClientAPI));
private static readonly log4net.ILog deprecatedLog = log4net.LogManager.GetLogger("ScriptDeprecated");
protected static IGameWorld betaWorld;
protected static bool initialized;
protected static SortedList<long, List<object>> effectWorkQueue;
protected static YieldEffectHandler yieldHandler;
protected static Dictionary<AnimationState, AnimationStateInfo> playingAnimations;
public static event WorldInitializedHandler WorldInitialized;
public static event FrameStartedHandler FrameStarted;
public static event FrameEndedHandler FrameEnded;
public static event EventHandler WorldConnect;
public static event EventHandler WorldDisconnect;
static ClientAPI()
{
effectWorkQueue = new SortedList<long, List<object>>();
playingAnimations = new Dictionary<AnimationState, AnimationStateInfo>();
}
public static void OnWorldInitialized() {
WorldInitializedHandler handler = WorldInitialized;
if (handler != null) {
handler(null, new EventArgs());
}
}
public static void OnWorldConnect() {
if (WorldConnect != null)
WorldConnect(null, new EventArgs());
}
public static void OnWorldDisconnect() {
if (WorldDisconnect != null)
WorldDisconnect(null, new EventArgs());
}
public static void OnFrameStarted(float time)
{
FrameStartedHandler handler = FrameStarted;
if (handler != null)
{
handler(null, new ScriptingFrameEventArgs(time));
}
}
public static void OnFrameEnded(float time)
{
FrameEndedHandler handler = FrameEnded;
if (handler != null)
{
handler(null, new ScriptingFrameEventArgs(time));
}
//if (triggerWorldInitialized &&
//betaWorld.WorldManager.SceneManager.CurrentViewport != null)
if (triggerWorldInitialized) {
OnWorldInitialized();
triggerWorldInitialized = false;
}
}
public static void InitAPI(IGameWorld gameWorld)
{
string scriptPath = null;
// add to the path so that imports from ClientAPI will be found
if (System.IO.Directory.Exists("..\\Scripts"))
{
scriptPath = "../Scripts/";
}
else
{
scriptPath = "../../Scripts/";
}
UiScripting.AddPath(scriptPath);
log.InfoFormat("API Script Path: {0}", scriptPath);
foreach (string dir in RepositoryClass.Instance.RepositoryDirectoryList) {
string scriptRepository;
scriptRepository = string.Format("{0}/Scripts/", dir);
if (Directory.Exists(scriptRepository))
{
UiScripting.AddPath(scriptRepository);
log.InfoFormat("World Script Path: {0}", scriptRepository);
}
scriptRepository = string.Format("{0}/IPCE/", dir);
if (Directory.Exists(scriptRepository))
{
UiScripting.AddPath(scriptRepository);
log.InfoFormat("World Script Path: {0}", scriptRepository);
}
}
// Create a dictionary to initialize globals for the ClientAPI module
Dictionary<string, object> globals = new Dictionary<string, object>();
// Load the ClientAPI python code
UiScripting.RunModule(scriptPath, "ClientAPI.py", "ClientAPI", true, globals);
// Run world startup script
if (!UiScripting.RunFile("Startup.py"))
throw new PrettyClientException("bad_script.htm", "Unable to run startup scripts");
yieldHandler = UiScripting.SetupDelegate<YieldEffectHandler>("return generator.next()", null);
betaWorld = gameWorld;
initialized = true;
}
public delegate int YieldEffectHandler(object generator);
public static void QueueYieldEffect(object generator, int milliseconds)
{
long time = milliseconds + TimeTool.CurrentTime;
List<object> timeList;
if (effectWorkQueue.ContainsKey(time))
{
timeList = effectWorkQueue[time];
}
else
{
timeList = new List<object>();
effectWorkQueue[time] = timeList;
}
timeList.Add(generator);
}
public static void ProcessYieldEffectQueue()
{
long currentTime = TimeTool.CurrentTime;
// process any pending queue items
while ((effectWorkQueue.Count > 0) && (effectWorkQueue.Keys[0] < currentTime))
{
// fetch the generator object
List<object> generatorList = effectWorkQueue.Values[0];
// remove it from the queue
effectWorkQueue.RemoveAt(0);
foreach (object generator in generatorList)
{
int nextWait = 0;
bool done = false;
try
{
// call the python yield handler code with the generator object, which does
// the next slice of work on the effect.
nextWait = yieldHandler(generator);
}
catch (IronPython.Runtime.Exceptions.StopIterationException)
{
done = true;
}
catch (Exception ex)
{
string pystack = UiScripting.FormatException(ex);
LogUtil.ExceptionLog.ErrorFormat("Exception in yield effect handler. Python Stack Trace: {0}\n.Full Stack Trace: {1}", pystack, ex);
log.Error("Cancelling effect execution.");
done = true;
}
if (!done)
{
// add it back to the queue at the next scheduled time offset
QueueYieldEffect(generator, nextWait);
}
}
}
}
public static AnimationStateInfo PlaySceneAnimation(AnimationState state, float speed, bool looping)
{
if (playingAnimations.ContainsKey(state))
{
log.ErrorFormat("Attempted to play an already playing animation: {0}", state.Name);
return null;
}
AnimationStateInfo stateInfo = new AnimationStateInfo(state, speed, looping);
playingAnimations[state] = stateInfo;
state.Time = 0;
return stateInfo;
}
public static void StopSceneAnimation(AnimationState state)
{
if (!playingAnimations.ContainsKey(state))
{
log.InfoFormat("Attempted to stop an animation that is not playing: {0}", state.Name);
return;
}
playingAnimations.Remove(state);
return;
}
public static void ProcessSceneAnimations(float timeSinceLastFrame)
{
if (playingAnimations.Count > 0)
{
List<AnimationState> removals = new List<AnimationState>();
foreach (AnimationStateInfo info in playingAnimations.Values)
{
float overflow = 0f;
if (info.AddTime(timeSinceLastFrame, out overflow))
removals.Add(info.State);
}
// remove any animations that have finished
foreach (AnimationState state in removals)
{
playingAnimations.Remove(state);
}
}
}
protected static bool triggerWorldInitialized;
public static bool TriggerWorldInitialized
{
get
{
return triggerWorldInitialized;
}
set
{
triggerWorldInitialized = true;
}
}
public static log4net.ILog Log {
get { return log; }
}
protected static Dictionary<string, object> deprecatedCalls = new Dictionary<string, object>();
public static void ScriptDeprecated(string version, string oldMethod, string newMethod)
{
StackTrace t = new StackTrace(true);
StackFrame f = null;
int i = 0;
bool foundPython = false;
// look for the first stack frame that appears to be in a python script
for (; i < t.FrameCount; i++)
{
f = t.GetFrame(i);
string filename = f.GetFileName();
if ((filename != null) && filename.ToLowerInvariant().EndsWith(".py"))
{
foundPython = true;
break;
}
}
if (foundPython)
{
// generate a string that uniquely identifies a call to a deprecated interface
// from a particular line of script code. We will use this string to avoid
// printing the same deprecated message over and over for the same line of code.
string instanceID = oldMethod + f.GetFileName() + f.GetFileLineNumber().ToString();
if (!deprecatedCalls.ContainsKey(instanceID))
{
// mark the call instance ID in the
deprecatedCalls[instanceID] = null;
deprecatedLog.WarnFormat("DEPRECATED:{0}: {1} in the Client API should no longer be used. You should replace it with {2}", version, oldMethod, newMethod);
deprecatedLog.WarnFormat(" {0} is called:", oldMethod);
// continue from the index where the previous loop found a python file
for (; i < t.FrameCount; i++)
{
f = t.GetFrame(i);
string filename = f.GetFileName();
if ((filename != null) && filename.ToLowerInvariant().EndsWith(".py"))
{
deprecatedLog.WarnFormat(" at {0} in {1}: line {2}", f.GetMethod().Name, filename, f.GetFileLineNumber());
}
}
}
}
}
}
}
| |
/********************************************************************
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.
*********************************************************************/
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Windows.Forms;
namespace MVImportTool
{
/// <summary>
/// This class is used to install converted components into a repository.
/// The components installed include the direct results of the conversion
/// (e.g. '.mesh' files) as well as files the components depend on. In
/// particular, '.material' files depend on textures, but the paths to
/// image files are not mentioned in the '.material' file; hence, the
/// the installer will crawl the '.dae' file to find the texture sources.
///
/// TODO: The converted components are assumed to be in the same directory
/// as the '.dae' file. Currently the ConversionTool always builds into
/// the same directory as the source file, but conceivably that might
/// change in the future. Maybe the filename and working directory should
/// be specified separately....?
/// </summary>
internal class RepositoryInstaller
{
#region Properties
/// <summary>
/// Global settings for filtering files by component type. These
/// allow yo uto select the types of files to install.
/// </summary>
[Flags]
internal enum InstallFilterFlags
{
Mesh = 0x01,
Materials = 0x02,
Skeleton = 0x04,
Physics = 0x08,
Textures = 0x10,
All = (Mesh | Materials | Skeleton | Physics | Textures)
}
internal InstallFilterFlags FilterFlags
{
get { return m_FilterFlags; }
set { m_FilterFlags = value; }
}
InstallFilterFlags m_FilterFlags;
/// <summary>
/// The choices presented to the user regarding overwriting files.
/// </summary>
[Flags]
internal enum OverwritePolicyFlags
{
Always,
Never,
Ask
}
internal OverwritePolicyFlags OverwritePolicy
{
get { return m_OverwritePolicy; }
set
{
m_OverwritePolicy = value;
InstallationCandidate.OverwritePolicy = value;
}
}
OverwritePolicyFlags m_OverwritePolicy;
/// <summary>
/// If true, present the user with a dialog before actually copying
/// files to the repository. The dialog allows you to select which
/// files get installed on an individual basis.
/// </summary>
public bool ConfirmInstallation
{
get { return m_ConfirmInstallation; }
set { m_ConfirmInstallation = value; }
}
bool m_ConfirmInstallation;
#endregion Properties
/// <summary>
/// Construct an instance of this installer. The installer operates
/// on a single DAE file. If you want to install from another DAE
/// file, create another instance.
///
/// This only installs files with a creation date after the earliest
/// time specified by the argument.
/// </summary>
/// <param name="daeFile">the source DAE file</param>
/// <param name="earliestTime">time the </param>
/// <param name="log">log for reporting status; can be null</param>
public RepositoryInstaller( string daeFile, DateTime earliestTime, ILog log )
{
m_DAEFile = daeFile;
m_EarliestTime = earliestTime;
m_LogWriter = new LogWriter( log );
InstallationCandidate.Log = m_LogWriter;
// These are the file types that can be produced; a particular
// conversion run does not necessarilly produce all types.
// TODO: It would be nice if these came from a config file.
// TODO: Maybe make this a property that is set up by the client.
m_ProductFiles.Add( ".mesh", null );
m_ProductFiles.Add( ".material", null );
m_ProductFiles.Add( ".skeleton", null );
m_ProductFiles.Add( ".physics", null );
// This associates the file type with a repository subdir
// TODO: Same as above...
m_RepositorySubdirectories.Add( ".mesh", "Meshes" );
m_RepositorySubdirectories.Add( ".material", "Materials" );
m_RepositorySubdirectories.Add( ".skeleton", "Skeletons" );
m_RepositorySubdirectories.Add( ".physics", "Physics" );
m_Candidates.Add( "Meshes", new List<InstallationCandidate>() );
m_Candidates.Add( "Materials", new List<InstallationCandidate>() );
m_Candidates.Add( "Skeletons", new List<InstallationCandidate>() );
m_Candidates.Add( "Physics", new List<InstallationCandidate>() );
m_Candidates.Add( "Textures", new List<InstallationCandidate>() );
m_TypeToFilterFlagMap.Add( "Meshes", InstallFilterFlags.Mesh );
m_TypeToFilterFlagMap.Add( "Materials", InstallFilterFlags.Materials );
m_TypeToFilterFlagMap.Add( "Skeletons", InstallFilterFlags.Skeleton );
m_TypeToFilterFlagMap.Add( "Physics", InstallFilterFlags.Physics );
m_TypeToFilterFlagMap.Add( "Textures", InstallFilterFlags.Textures );
FindConversionProductFiles();
FilterFlags = InstallFilterFlags.All;
m_Finder = new TextureFinder( daeFile );
//if( FindConversionProductFiles() )
//{
// FilterFlags = InstallFilterFlags.All;
// m_Finder = new TextureFinder( daeFile );
//}
}
/// <summary>
/// Perform the installation to a single repository. This installs
/// all conversion products, and texture files referenced by the
/// source DAE file.
/// </summary>
/// <param name="targetRepository">repository path</param>
public void InstallTo( string targetRepository )
{
ClearState();
if( Directory.Exists( targetRepository ) )
{
ScheduleConversionFiles( targetRepository );
ScheduleTextureFiles( targetRepository );
WarnAboutMissingTextures();
if( GetApprovalForInstallation( targetRepository ) )
{
InstallApprovedFiles();
}
}
else
{
string msg = String.Format(
"Cannot find repository '{0}'",
targetRepository );
MessageBox.Show(
msg,
"Repository Installer",
MessageBoxButtons.OK,
MessageBoxIcon.Warning );
}
}
// Warn about texture files referenced in the DAE file that could
// not be found; this does not prevent the rest of the installation
// from proceding.
// TODO: Some people may not like the pop-up nag--especially if they
// are running this in a batch mode! :) Maybe add a control that
// switches the warning to the log stream.
void WarnAboutMissingTextures()
{
if( IsTypeEnabled( "Textures" ) )
{
if( 0 < m_Finder.MissingTextures.Count )
{
FileInfo daeInfo = new FileInfo( m_DAEFile );
StringBuilder msgText = new StringBuilder( String.Format(
"File <{0}> referenced image files that could \n" +
" not be found; they cannot be installed in the repository\n\n",
daeInfo.Name ) );
foreach( string imageId in m_Finder.MissingTextures.Keys )
{
msgText.Append( m_Finder.MissingTextures[ imageId ].FullName );
msgText.Append( "\n" );
}
MessageBox.Show(
msgText.ToString(),
"Repository Installer",
MessageBoxButtons.OK,
MessageBoxIcon.Warning );
}
}
}
#region Internal state
// Map the file extension to the repository subdirectory it gets installed to.
readonly Dictionary<string, string> m_RepositorySubdirectories = new Dictionary<string, string>();
readonly Dictionary<string, InstallFilterFlags> m_TypeToFilterFlagMap = new Dictionary<string, InstallFilterFlags>();
// Map the file extension to the actual file of that type produced by the conversion.
Dictionary<string, FileInfo> m_ProductFiles = new Dictionary<string, FileInfo>();
// Candidates categorized by their types
Dictionary<string, List<InstallationCandidate>> m_Candidates = new Dictionary<string, List<InstallationCandidate>>();
string m_DAEFile;
DateTime m_EarliestTime;
TextureFinder m_Finder;
LogWriter m_LogWriter;
// Since an instance of this class can install into more than one
// repository, we need to reset the state prior to each install.
void ClearState()
{
// We need a new copy of the keys because we are going to
// modify the collection as we iterate.
string[] types = new string[ m_Candidates.Keys.Count ];
m_Candidates.Keys.CopyTo( types, 0 );
foreach( string type in types )
{
if( m_ProductFiles.ContainsKey( type ) )
{
m_ProductFiles[ type ] = null;
}
if( m_Candidates.ContainsKey( type ) )
{
m_Candidates[ type ].Clear();
}
}
}
#endregion
// Checks the type against the type-filter flags
bool IsTypeEnabled( string type )
{
return Convert.ToBoolean( FilterFlags & m_TypeToFilterFlagMap[ type ] );
}
// Discover all the files produced from the source DAE file, e.g. .mesh file.
// Note that we do a time-check to make sure that the files we found are
// actually produced from the dae file, and not a relic from something earlier
// that just happened to have the same name.
//
// Return false if no files were found.
bool FindConversionProductFiles()
{
FileInfo daeInfo = new FileInfo( m_DAEFile );
bool productFound = false;
if( daeInfo.Exists )
{
List<string> types = new List<string>();
types.AddRange( m_ProductFiles.Keys );
foreach( string type in types )
{
string prodFile = Path.ChangeExtension( m_DAEFile, type );
FileInfo prodInfo = new FileInfo( prodFile );
if( prodInfo.Exists )
{
if( m_EarliestTime < prodInfo.LastWriteTime )
{
m_ProductFiles[ type ] = prodInfo;
productFound = true;
}
}
}
}
if( ! productFound )
{
MessageBox.Show(
"No installable files were found.\n" +
"Did you forget to convert the DAE file?",
"Repository Installer",
MessageBoxButtons.OK,
MessageBoxIcon.Warning );
}
return productFound;
}
#region Installation scheduling
// Schedule converted files for installation. They actually get installed
// after passing user filters that enable installation.
void ScheduleConversionFiles( string target )
{
DirectoryInfo dirInfo = new DirectoryInfo( target );
if( dirInfo.Exists )
{
foreach( string type in m_ProductFiles.Keys )
{
if( null != m_ProductFiles[ type ] )
{
string typeSubdirectory = target + "\\" + m_RepositorySubdirectories[ type ];
string newFile = typeSubdirectory + "\\" + m_ProductFiles[ type ].Name;
ScheduleForInstallation( m_RepositorySubdirectories[ type ], m_ProductFiles[ type ], newFile );
}
}
}
}
// Schedule texture files for installation. They actually get installed
// after passing user filters that enable installation.
void ScheduleTextureFiles( string target )
{
string textureDir = target + "\\Textures\\";
foreach( string imageId in m_Finder.Textures.Keys )
{
FileInfo textureFile = m_Finder.Textures[ imageId ];
string newFile = textureDir + textureFile.Name;
ScheduleForInstallation( "Textures", textureFile, newFile );
}
}
void ScheduleForInstallation( string type, FileInfo source, string destination )
{
if( m_Candidates.ContainsKey( type ) )
{
InstallationCandidate candidate = new InstallationCandidate( source, destination );
candidate.IsEnabled = IsTypeEnabled( type );
m_Candidates[ type ].Add( candidate );
}
}
#endregion Installation scheduling
#region Installation--confirmation and copying
// This is for fast lookup of the components approved by the user.
// The value for each key will always be 'null'.
Dictionary<string, object> m_ApprovedForInstallation;
// Present the user with a detailed list of installable components.
// The components marked if they are schedule for installation.
// The use can select/unselect individual files for installation.
bool GetApprovalForInstallation( string targetRepository )
{
InstallationPreviewDialog preview = new InstallationPreviewDialog();
preview.TargetRepository = targetRepository;
SortedList<string,object> candidateSources = new SortedList<string, object>();
// Build the set of available components, marked if they are
// scheduled for installation.
foreach( string type in m_Candidates.Keys )
{
List<InstallationCandidate> candidateList = m_Candidates[ type ];
foreach( InstallationCandidate candidate in candidateList )
{
if( ! candidateSources.ContainsKey( candidate.Source.Name ) )
{
candidateSources.Add( candidate.Source.Name, null );
preview.Add( candidate.Destination, IsTypeEnabled( type ) );
}
}
}
return BuildApprovedList( preview );
}
private bool BuildApprovedList( InstallationPreviewDialog preview )
{
m_ApprovedForInstallation = new Dictionary<string, object>();
if( ConfirmInstallation )
{
if( DialogResult.OK != preview.ShowDialog() )
{
return false;
}
}
foreach( string approvedItem in preview.CheckedItems )
{
m_ApprovedForInstallation.Add( approvedItem, null );
}
return true;
}
class UserCancelException : Exception
{
}
// Finally--Install the files the user approved.
void InstallApprovedFiles()
{
try
{
foreach( string type in m_Candidates.Keys )
{
List<InstallationCandidate> candidates = m_Candidates[ type ];
foreach( InstallationCandidate candidate in candidates )
{
if( m_ApprovedForInstallation.ContainsKey( candidate.Destination ) )
{
// User's selection overrides the global settings
candidate.IsEnabled = true;
candidate.Install();
}
}
}
}
catch( UserCancelException )
{
m_LogWriter.WriteLine( "User canceled installation" );
}
}
#endregion Installation--confirmation and copying
#region Internal class: Installation Candidate
// This represents a component that can be installed, but it must
// be enabled for the installation to proceed. The intent is to
// have an item that can be scheduled for installation, but then
// present it to the user for approval before carrying out the
// installation.
class InstallationCandidate
{
internal readonly FileInfo Source;
internal readonly string Destination;
internal static LogWriter Log;
internal static OverwritePolicyFlags OverwritePolicy;
internal bool IsEnabled
{
get { return m_IsEnabled; }
set { m_IsEnabled = value; }
}
bool m_IsEnabled;
internal InstallationCandidate( FileInfo source, string destination )
{
Source = source;
Destination = destination;
}
internal void Install()
{
if( IsEnabled )
{
FileInfo target = new FileInfo( Destination );
if( ! target.Directory.Exists )
{
target.Directory.Create();
}
if( IsOkayToOverwrite( target ) )
{
Log.WriteLine( " Installing " + Destination );
Source.CopyTo( Destination, true );
}
}
}
bool IsOkayToOverwrite( FileInfo fileInfo )
{
bool isOkay = true;
switch( OverwritePolicy )
{
case OverwritePolicyFlags.Never:
{
isOkay = ! fileInfo.Exists;
break;
}
case OverwritePolicyFlags.Ask:
{
isOkay = AskIsOkayToOverwrite( fileInfo );
break;
}
}
return isOkay;
}
bool AskIsOkayToOverwrite( FileInfo fileInfo )
{
string msg = String.Format(
"File already exists; do you want to overwrite it?\n" +
"(Click 'Cancel' to abort the installation.)\n" +
"\nFilename:\n" +
" " + fileInfo.FullName );
DialogResult result =
MessageBox.Show(
msg,
"Repository Installer",
MessageBoxButtons.YesNoCancel,
MessageBoxIcon.Question );
if( DialogResult.Cancel == result )
{
throw new UserCancelException();
}
return (DialogResult.Yes == result);
}
}
#endregion Internal class
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace System
{
using System;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime;
using System.Runtime.ConstrainedExecution;
using System.Diagnostics;
using System.Runtime.Serialization;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Threading;
using System.Runtime.Versioning;
using System.Text;
using System.Globalization;
using System.Security;
using Microsoft.Win32.SafeHandles;
using StackCrawlMark = System.Threading.StackCrawlMark;
public unsafe struct RuntimeTypeHandle : ISerializable
{
// Returns handle for interop with EE. The handle is guaranteed to be non-null.
internal RuntimeTypeHandle GetNativeHandle()
{
// Create local copy to avoid a race condition
RuntimeType type = m_type;
if (type == null)
throw new ArgumentNullException(null, SR.Arg_InvalidHandle);
return new RuntimeTypeHandle(type);
}
// Returns type for interop with EE. The type is guaranteed to be non-null.
internal RuntimeType GetTypeChecked()
{
// Create local copy to avoid a race condition
RuntimeType type = m_type;
if (type == null)
throw new ArgumentNullException(null, SR.Arg_InvalidHandle);
return type;
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern static bool IsInstanceOfType(RuntimeType type, Object o);
internal unsafe static Type GetTypeHelper(Type typeStart, Type[] genericArgs, IntPtr pModifiers, int cModifiers)
{
Type type = typeStart;
if (genericArgs != null)
{
type = type.MakeGenericType(genericArgs);
}
if (cModifiers > 0)
{
int* arModifiers = (int*)pModifiers.ToPointer();
for (int i = 0; i < cModifiers; i++)
{
if ((CorElementType)Marshal.ReadInt32((IntPtr)arModifiers, i * sizeof(int)) == CorElementType.Ptr)
type = type.MakePointerType();
else if ((CorElementType)Marshal.ReadInt32((IntPtr)arModifiers, i * sizeof(int)) == CorElementType.ByRef)
type = type.MakeByRefType();
else if ((CorElementType)Marshal.ReadInt32((IntPtr)arModifiers, i * sizeof(int)) == CorElementType.SzArray)
type = type.MakeArrayType();
else
type = type.MakeArrayType(Marshal.ReadInt32((IntPtr)arModifiers, ++i * sizeof(int)));
}
}
return type;
}
public static bool operator ==(RuntimeTypeHandle left, object right) { return left.Equals(right); }
public static bool operator ==(object left, RuntimeTypeHandle right) { return right.Equals(left); }
public static bool operator !=(RuntimeTypeHandle left, object right) { return !left.Equals(right); }
public static bool operator !=(object left, RuntimeTypeHandle right) { return !right.Equals(left); }
// This is the RuntimeType for the type
private RuntimeType m_type;
public override int GetHashCode()
{
return m_type != null ? m_type.GetHashCode() : 0;
}
public override bool Equals(object obj)
{
if (!(obj is RuntimeTypeHandle))
return false;
RuntimeTypeHandle handle = (RuntimeTypeHandle)obj;
return handle.m_type == m_type;
}
public bool Equals(RuntimeTypeHandle handle)
{
return handle.m_type == m_type;
}
public IntPtr Value
{
get
{
return m_type != null ? m_type.m_handle : IntPtr.Zero;
}
}
[MethodImpl(MethodImplOptions.InternalCall)]
internal static extern IntPtr GetValueInternal(RuntimeTypeHandle handle);
internal RuntimeTypeHandle(RuntimeType type)
{
m_type = type;
}
internal static bool IsTypeDefinition(RuntimeType type)
{
CorElementType corElemType = GetCorElementType(type);
if (!((corElemType >= CorElementType.Void && corElemType < CorElementType.Ptr) ||
corElemType == CorElementType.ValueType ||
corElemType == CorElementType.Class ||
corElemType == CorElementType.TypedByRef ||
corElemType == CorElementType.I ||
corElemType == CorElementType.U ||
corElemType == CorElementType.Object))
return false;
if (HasInstantiation(type) && !IsGenericTypeDefinition(type))
return false;
return true;
}
internal static bool IsPrimitive(RuntimeType type)
{
CorElementType corElemType = GetCorElementType(type);
return (corElemType >= CorElementType.Boolean && corElemType <= CorElementType.R8) ||
corElemType == CorElementType.I ||
corElemType == CorElementType.U;
}
internal static bool IsByRef(RuntimeType type)
{
CorElementType corElemType = GetCorElementType(type);
return (corElemType == CorElementType.ByRef);
}
internal static bool IsPointer(RuntimeType type)
{
CorElementType corElemType = GetCorElementType(type);
return (corElemType == CorElementType.Ptr);
}
internal static bool IsArray(RuntimeType type)
{
CorElementType corElemType = GetCorElementType(type);
return (corElemType == CorElementType.Array || corElemType == CorElementType.SzArray);
}
internal static bool IsSZArray(RuntimeType type)
{
CorElementType corElemType = GetCorElementType(type);
return (corElemType == CorElementType.SzArray);
}
internal static bool HasElementType(RuntimeType type)
{
CorElementType corElemType = GetCorElementType(type);
return ((corElemType == CorElementType.Array || corElemType == CorElementType.SzArray) // IsArray
|| (corElemType == CorElementType.Ptr) // IsPointer
|| (corElemType == CorElementType.ByRef)); // IsByRef
}
internal static IntPtr[] CopyRuntimeTypeHandles(RuntimeTypeHandle[] inHandles, out int length)
{
if (inHandles == null || inHandles.Length == 0)
{
length = 0;
return null;
}
IntPtr[] outHandles = new IntPtr[inHandles.Length];
for (int i = 0; i < inHandles.Length; i++)
{
outHandles[i] = inHandles[i].Value;
}
length = outHandles.Length;
return outHandles;
}
internal static IntPtr[] CopyRuntimeTypeHandles(Type[] inHandles, out int length)
{
if (inHandles == null || inHandles.Length == 0)
{
length = 0;
return null;
}
IntPtr[] outHandles = new IntPtr[inHandles.Length];
for (int i = 0; i < inHandles.Length; i++)
{
outHandles[i] = inHandles[i].GetTypeHandleInternal().Value;
}
length = outHandles.Length;
return outHandles;
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern Object CreateInstance(RuntimeType type, bool publicOnly, bool wrapExceptions, ref bool canBeCached, ref RuntimeMethodHandleInternal ctor);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern Object CreateCaInstance(RuntimeType type, IRuntimeMethodInfo ctor);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern Object Allocate(RuntimeType type);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern Object CreateInstanceForAnotherGenericParameter(RuntimeType type, RuntimeType genericParameter);
internal RuntimeType GetRuntimeType()
{
return m_type;
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern static CorElementType GetCorElementType(RuntimeType type);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern static RuntimeAssembly GetAssembly(RuntimeType type);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern static RuntimeModule GetModule(RuntimeType type);
public ModuleHandle GetModuleHandle()
{
return new ModuleHandle(RuntimeTypeHandle.GetModule(m_type));
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern static RuntimeType GetBaseType(RuntimeType type);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern static TypeAttributes GetAttributes(RuntimeType type);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern static RuntimeType GetElementType(RuntimeType type);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern static bool CompareCanonicalHandles(RuntimeType left, RuntimeType right);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern static int GetArrayRank(RuntimeType type);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern static int GetToken(RuntimeType type);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern static RuntimeMethodHandleInternal GetMethodAt(RuntimeType type, int slot);
// This is managed wrapper for MethodTable::IntroducedMethodIterator
internal struct IntroducedMethodEnumerator
{
private bool _firstCall;
private RuntimeMethodHandleInternal _handle;
internal IntroducedMethodEnumerator(RuntimeType type)
{
_handle = RuntimeTypeHandle.GetFirstIntroducedMethod(type);
_firstCall = true;
}
public bool MoveNext()
{
if (_firstCall)
{
_firstCall = false;
}
else if (_handle.Value != IntPtr.Zero)
{
RuntimeTypeHandle.GetNextIntroducedMethod(ref _handle);
}
return !(_handle.Value == IntPtr.Zero);
}
public RuntimeMethodHandleInternal Current
{
get
{
return _handle;
}
}
// Glue to make this work nicely with C# foreach statement
public IntroducedMethodEnumerator GetEnumerator()
{
return this;
}
}
internal static IntroducedMethodEnumerator GetIntroducedMethods(RuntimeType type)
{
return new IntroducedMethodEnumerator(type);
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern RuntimeMethodHandleInternal GetFirstIntroducedMethod(RuntimeType type);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern void GetNextIntroducedMethod(ref RuntimeMethodHandleInternal method);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern static bool GetFields(RuntimeType type, IntPtr* result, int* count);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern static Type[] GetInterfaces(RuntimeType type);
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
private extern static void GetConstraints(RuntimeTypeHandle handle, ObjectHandleOnStack types);
internal Type[] GetConstraints()
{
Type[] types = null;
GetConstraints(GetNativeHandle(), JitHelpers.GetObjectHandleOnStack(ref types));
return types;
}
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
private extern static IntPtr GetGCHandle(RuntimeTypeHandle handle, GCHandleType type);
internal IntPtr GetGCHandle(GCHandleType type)
{
return GetGCHandle(GetNativeHandle(), type);
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern static int GetNumVirtuals(RuntimeType type);
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
private extern static void VerifyInterfaceIsImplemented(RuntimeTypeHandle handle, RuntimeTypeHandle interfaceHandle);
internal void VerifyInterfaceIsImplemented(RuntimeTypeHandle interfaceHandle)
{
VerifyInterfaceIsImplemented(GetNativeHandle(), interfaceHandle.GetNativeHandle());
}
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
private extern static int GetInterfaceMethodImplementationSlot(RuntimeTypeHandle handle, RuntimeTypeHandle interfaceHandle, RuntimeMethodHandleInternal interfaceMethodHandle);
internal int GetInterfaceMethodImplementationSlot(RuntimeTypeHandle interfaceHandle, RuntimeMethodHandleInternal interfaceMethodHandle)
{
return GetInterfaceMethodImplementationSlot(GetNativeHandle(), interfaceHandle.GetNativeHandle(), interfaceMethodHandle);
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern static bool IsComObject(RuntimeType type, bool isGenericCOM);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern static bool IsInterface(RuntimeType type);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern static bool IsByRefLike(RuntimeType type);
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[return: MarshalAs(UnmanagedType.Bool)]
private extern static bool _IsVisible(RuntimeTypeHandle typeHandle);
internal static bool IsVisible(RuntimeType type)
{
return _IsVisible(new RuntimeTypeHandle(type));
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern static bool IsValueType(RuntimeType type);
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
private extern static void ConstructName(RuntimeTypeHandle handle, TypeNameFormatFlags formatFlags, StringHandleOnStack retString);
internal string ConstructName(TypeNameFormatFlags formatFlags)
{
string name = null;
ConstructName(GetNativeHandle(), formatFlags, JitHelpers.GetStringHandleOnStack(ref name));
return name;
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private extern static void* _GetUtf8Name(RuntimeType type);
internal static Utf8String GetUtf8Name(RuntimeType type)
{
return new Utf8String(_GetUtf8Name(type));
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern static bool CanCastTo(RuntimeType type, RuntimeType target);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern static RuntimeType GetDeclaringType(RuntimeType type);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern static IRuntimeMethodInfo GetDeclaringMethod(RuntimeType type);
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
private extern static void GetDefaultConstructor(RuntimeTypeHandle handle, ObjectHandleOnStack method);
internal IRuntimeMethodInfo GetDefaultConstructor()
{
IRuntimeMethodInfo ctor = null;
GetDefaultConstructor(GetNativeHandle(), JitHelpers.GetObjectHandleOnStack(ref ctor));
return ctor;
}
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
private extern static void GetTypeByName(string name, bool throwOnError, bool ignoreCase, bool reflectionOnly, StackCrawlMarkHandle stackMark,
IntPtr pPrivHostBinder,
bool loadTypeFromPartialName, ObjectHandleOnStack type, ObjectHandleOnStack keepalive);
// Wrapper function to reduce the need for ifdefs.
internal static RuntimeType GetTypeByName(string name, bool throwOnError, bool ignoreCase, bool reflectionOnly, ref StackCrawlMark stackMark, bool loadTypeFromPartialName)
{
return GetTypeByName(name, throwOnError, ignoreCase, reflectionOnly, ref stackMark, IntPtr.Zero, loadTypeFromPartialName);
}
internal static RuntimeType GetTypeByName(string name, bool throwOnError, bool ignoreCase, bool reflectionOnly, ref StackCrawlMark stackMark,
IntPtr pPrivHostBinder,
bool loadTypeFromPartialName)
{
if (name == null || name.Length == 0)
{
if (throwOnError)
throw new TypeLoadException(SR.Arg_TypeLoadNullStr);
return null;
}
RuntimeType type = null;
Object keepAlive = null;
GetTypeByName(name, throwOnError, ignoreCase, reflectionOnly,
JitHelpers.GetStackCrawlMarkHandle(ref stackMark),
pPrivHostBinder,
loadTypeFromPartialName, JitHelpers.GetObjectHandleOnStack(ref type), JitHelpers.GetObjectHandleOnStack(ref keepAlive));
GC.KeepAlive(keepAlive);
return type;
}
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
private extern static void GetTypeByNameUsingCARules(string name, RuntimeModule scope, ObjectHandleOnStack type);
internal static RuntimeType GetTypeByNameUsingCARules(string name, RuntimeModule scope)
{
if (name == null || name.Length == 0)
throw new ArgumentException(null, nameof(name));
RuntimeType type = null;
GetTypeByNameUsingCARules(name, scope.GetNativeHandle(), JitHelpers.GetObjectHandleOnStack(ref type));
return type;
}
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
internal extern static void GetInstantiation(RuntimeTypeHandle type, ObjectHandleOnStack types, bool fAsRuntimeTypeArray);
internal RuntimeType[] GetInstantiationInternal()
{
RuntimeType[] types = null;
GetInstantiation(GetNativeHandle(), JitHelpers.GetObjectHandleOnStack(ref types), true);
return types;
}
internal Type[] GetInstantiationPublic()
{
Type[] types = null;
GetInstantiation(GetNativeHandle(), JitHelpers.GetObjectHandleOnStack(ref types), false);
return types;
}
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
private extern static void Instantiate(RuntimeTypeHandle handle, IntPtr* pInst, int numGenericArgs, ObjectHandleOnStack type);
internal RuntimeType Instantiate(Type[] inst)
{
// defensive copy to be sure array is not mutated from the outside during processing
int instCount;
IntPtr[] instHandles = CopyRuntimeTypeHandles(inst, out instCount);
fixed (IntPtr* pInst = instHandles)
{
RuntimeType type = null;
Instantiate(GetNativeHandle(), pInst, instCount, JitHelpers.GetObjectHandleOnStack(ref type));
GC.KeepAlive(inst);
return type;
}
}
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
private extern static void MakeArray(RuntimeTypeHandle handle, int rank, ObjectHandleOnStack type);
internal RuntimeType MakeArray(int rank)
{
RuntimeType type = null;
MakeArray(GetNativeHandle(), rank, JitHelpers.GetObjectHandleOnStack(ref type));
return type;
}
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
private extern static void MakeSZArray(RuntimeTypeHandle handle, ObjectHandleOnStack type);
internal RuntimeType MakeSZArray()
{
RuntimeType type = null;
MakeSZArray(GetNativeHandle(), JitHelpers.GetObjectHandleOnStack(ref type));
return type;
}
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
private extern static void MakeByRef(RuntimeTypeHandle handle, ObjectHandleOnStack type);
internal RuntimeType MakeByRef()
{
RuntimeType type = null;
MakeByRef(GetNativeHandle(), JitHelpers.GetObjectHandleOnStack(ref type));
return type;
}
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
private extern static void MakePointer(RuntimeTypeHandle handle, ObjectHandleOnStack type);
internal RuntimeType MakePointer()
{
RuntimeType type = null;
MakePointer(GetNativeHandle(), JitHelpers.GetObjectHandleOnStack(ref type));
return type;
}
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
internal extern static bool IsCollectible(RuntimeTypeHandle handle);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern static bool HasInstantiation(RuntimeType type);
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
private extern static void GetGenericTypeDefinition(RuntimeTypeHandle type, ObjectHandleOnStack retType);
internal static RuntimeType GetGenericTypeDefinition(RuntimeType type)
{
RuntimeType retType = type;
if (HasInstantiation(retType) && !IsGenericTypeDefinition(retType))
GetGenericTypeDefinition(retType.GetTypeHandleInternal(), JitHelpers.GetObjectHandleOnStack(ref retType));
return retType;
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern static bool IsGenericTypeDefinition(RuntimeType type);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern static bool IsGenericVariable(RuntimeType type);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private extern static int GetGenericVariableIndex(RuntimeType type);
internal int GetGenericVariableIndex()
{
RuntimeType type = GetTypeChecked();
if (!IsGenericVariable(type))
throw new InvalidOperationException(SR.Arg_NotGenericParameter);
return GetGenericVariableIndex(type);
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern static bool ContainsGenericVariables(RuntimeType handle);
internal bool ContainsGenericVariables()
{
return ContainsGenericVariables(GetTypeChecked());
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private extern static bool SatisfiesConstraints(RuntimeType paramType, IntPtr* pTypeContext, int typeContextLength, IntPtr* pMethodContext, int methodContextLength, RuntimeType toType);
internal static bool SatisfiesConstraints(RuntimeType paramType, RuntimeType[] typeContext, RuntimeType[] methodContext, RuntimeType toType)
{
int typeContextLength;
int methodContextLength;
IntPtr[] typeContextHandles = CopyRuntimeTypeHandles(typeContext, out typeContextLength);
IntPtr[] methodContextHandles = CopyRuntimeTypeHandles(methodContext, out methodContextLength);
fixed (IntPtr* pTypeContextHandles = typeContextHandles, pMethodContextHandles = methodContextHandles)
{
bool result = SatisfiesConstraints(paramType, pTypeContextHandles, typeContextLength, pMethodContextHandles, methodContextLength, toType);
GC.KeepAlive(typeContext);
GC.KeepAlive(methodContext);
return result;
}
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private extern static IntPtr _GetMetadataImport(RuntimeType type);
internal static MetadataImport GetMetadataImport(RuntimeType type)
{
return new MetadataImport(_GetMetadataImport(type), type);
}
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
throw new PlatformNotSupportedException();
}
}
// This type is used to remove the expense of having a managed reference object that is dynamically
// created when we can prove that we don't need that object. Use of this type requires code to ensure
// that the underlying native resource is not freed.
// Cases in which this may be used:
// 1. When native code calls managed code passing one of these as a parameter
// 2. When managed code acquires one of these from an IRuntimeMethodInfo, and ensure that the IRuntimeMethodInfo is preserved
// across the lifetime of the RuntimeMethodHandleInternal instance
// 3. When another object is used to keep the RuntimeMethodHandleInternal alive. See delegates, CreateInstance cache, Signature structure
// When in doubt, do not use.
internal struct RuntimeMethodHandleInternal
{
internal static RuntimeMethodHandleInternal EmptyHandle
{
get
{
return new RuntimeMethodHandleInternal();
}
}
internal bool IsNullHandle()
{
return m_handle == IntPtr.Zero;
}
internal IntPtr Value
{
get
{
return m_handle;
}
}
internal RuntimeMethodHandleInternal(IntPtr value)
{
m_handle = value;
}
internal IntPtr m_handle;
}
internal class RuntimeMethodInfoStub : IRuntimeMethodInfo
{
public RuntimeMethodInfoStub(RuntimeMethodHandleInternal methodHandleValue, object keepalive)
{
m_keepalive = keepalive;
m_value = methodHandleValue;
}
public RuntimeMethodInfoStub(IntPtr methodHandleValue, object keepalive)
{
m_keepalive = keepalive;
m_value = new RuntimeMethodHandleInternal(methodHandleValue);
}
private object m_keepalive;
// These unused variables are used to ensure that this class has the same layout as RuntimeMethodInfo
#pragma warning disable 169
private object m_a;
private object m_b;
private object m_c;
private object m_d;
private object m_e;
private object m_f;
private object m_g;
#pragma warning restore 169
public RuntimeMethodHandleInternal m_value;
RuntimeMethodHandleInternal IRuntimeMethodInfo.Value
{
get
{
return m_value;
}
}
}
internal interface IRuntimeMethodInfo
{
RuntimeMethodHandleInternal Value
{
get;
}
}
public unsafe struct RuntimeMethodHandle : ISerializable
{
// Returns handle for interop with EE. The handle is guaranteed to be non-null.
internal static IRuntimeMethodInfo EnsureNonNullMethodInfo(IRuntimeMethodInfo method)
{
if (method == null)
throw new ArgumentNullException(null, SR.Arg_InvalidHandle);
return method;
}
private IRuntimeMethodInfo m_value;
internal RuntimeMethodHandle(IRuntimeMethodInfo method)
{
m_value = method;
}
internal IRuntimeMethodInfo GetMethodInfo()
{
return m_value;
}
// Used by EE
private static IntPtr GetValueInternal(RuntimeMethodHandle rmh)
{
return rmh.Value;
}
// ISerializable interface
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
throw new PlatformNotSupportedException();
}
public IntPtr Value
{
get
{
return m_value != null ? m_value.Value.Value : IntPtr.Zero;
}
}
public override int GetHashCode()
{
return ValueType.GetHashCodeOfPtr(Value);
}
public override bool Equals(object obj)
{
if (!(obj is RuntimeMethodHandle))
return false;
RuntimeMethodHandle handle = (RuntimeMethodHandle)obj;
return handle.Value == Value;
}
public static bool operator ==(RuntimeMethodHandle left, RuntimeMethodHandle right)
{
return left.Equals(right);
}
public static bool operator !=(RuntimeMethodHandle left, RuntimeMethodHandle right)
{
return !left.Equals(right);
}
public bool Equals(RuntimeMethodHandle handle)
{
return handle.Value == Value;
}
internal bool IsNullHandle()
{
return m_value == null;
}
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
internal extern static IntPtr GetFunctionPointer(RuntimeMethodHandleInternal handle);
public IntPtr GetFunctionPointer()
{
IntPtr ptr = GetFunctionPointer(EnsureNonNullMethodInfo(m_value).Value);
GC.KeepAlive(m_value);
return ptr;
}
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
internal extern static bool IsCAVisibleFromDecoratedType(
RuntimeTypeHandle attrTypeHandle,
IRuntimeMethodInfo attrCtor,
RuntimeTypeHandle sourceTypeHandle,
RuntimeModule sourceModule);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern IRuntimeMethodInfo _GetCurrentMethod(ref StackCrawlMark stackMark);
internal static IRuntimeMethodInfo GetCurrentMethod(ref StackCrawlMark stackMark)
{
return _GetCurrentMethod(ref stackMark);
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern MethodAttributes GetAttributes(RuntimeMethodHandleInternal method);
internal static MethodAttributes GetAttributes(IRuntimeMethodInfo method)
{
MethodAttributes retVal = RuntimeMethodHandle.GetAttributes(method.Value);
GC.KeepAlive(method);
return retVal;
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern MethodImplAttributes GetImplAttributes(IRuntimeMethodInfo method);
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
private extern static void ConstructInstantiation(IRuntimeMethodInfo method, TypeNameFormatFlags format, StringHandleOnStack retString);
internal static string ConstructInstantiation(IRuntimeMethodInfo method, TypeNameFormatFlags format)
{
string name = null;
ConstructInstantiation(EnsureNonNullMethodInfo(method), format, JitHelpers.GetStringHandleOnStack(ref name));
return name;
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern static RuntimeType GetDeclaringType(RuntimeMethodHandleInternal method);
internal static RuntimeType GetDeclaringType(IRuntimeMethodInfo method)
{
RuntimeType type = RuntimeMethodHandle.GetDeclaringType(method.Value);
GC.KeepAlive(method);
return type;
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern static int GetSlot(RuntimeMethodHandleInternal method);
internal static int GetSlot(IRuntimeMethodInfo method)
{
Debug.Assert(method != null);
int slot = RuntimeMethodHandle.GetSlot(method.Value);
GC.KeepAlive(method);
return slot;
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern static int GetMethodDef(IRuntimeMethodInfo method);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern static string GetName(RuntimeMethodHandleInternal method);
internal static string GetName(IRuntimeMethodInfo method)
{
string name = RuntimeMethodHandle.GetName(method.Value);
GC.KeepAlive(method);
return name;
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private extern static void* _GetUtf8Name(RuntimeMethodHandleInternal method);
internal static Utf8String GetUtf8Name(RuntimeMethodHandleInternal method)
{
return new Utf8String(_GetUtf8Name(method));
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern bool MatchesNameHash(RuntimeMethodHandleInternal method, uint hash);
[DebuggerStepThroughAttribute]
[Diagnostics.DebuggerHidden]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern static object InvokeMethod(object target, object[] arguments, Signature sig, bool constructor, bool wrapExceptions);
#region Private Invocation Helpers
internal static INVOCATION_FLAGS GetSecurityFlags(IRuntimeMethodInfo handle)
{
return (INVOCATION_FLAGS)RuntimeMethodHandle.GetSpecialSecurityFlags(handle);
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
static extern internal uint GetSpecialSecurityFlags(IRuntimeMethodInfo method);
#endregion
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
private extern static void GetMethodInstantiation(RuntimeMethodHandleInternal method, ObjectHandleOnStack types, bool fAsRuntimeTypeArray);
internal static RuntimeType[] GetMethodInstantiationInternal(IRuntimeMethodInfo method)
{
RuntimeType[] types = null;
GetMethodInstantiation(EnsureNonNullMethodInfo(method).Value, JitHelpers.GetObjectHandleOnStack(ref types), true);
GC.KeepAlive(method);
return types;
}
internal static RuntimeType[] GetMethodInstantiationInternal(RuntimeMethodHandleInternal method)
{
RuntimeType[] types = null;
GetMethodInstantiation(method, JitHelpers.GetObjectHandleOnStack(ref types), true);
return types;
}
internal static Type[] GetMethodInstantiationPublic(IRuntimeMethodInfo method)
{
RuntimeType[] types = null;
GetMethodInstantiation(EnsureNonNullMethodInfo(method).Value, JitHelpers.GetObjectHandleOnStack(ref types), false);
GC.KeepAlive(method);
return types;
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern static bool HasMethodInstantiation(RuntimeMethodHandleInternal method);
internal static bool HasMethodInstantiation(IRuntimeMethodInfo method)
{
bool fRet = RuntimeMethodHandle.HasMethodInstantiation(method.Value);
GC.KeepAlive(method);
return fRet;
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern static RuntimeMethodHandleInternal GetStubIfNeeded(RuntimeMethodHandleInternal method, RuntimeType declaringType, RuntimeType[] methodInstantiation);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern static RuntimeMethodHandleInternal GetMethodFromCanonical(RuntimeMethodHandleInternal method, RuntimeType declaringType);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern static bool IsGenericMethodDefinition(RuntimeMethodHandleInternal method);
internal static bool IsGenericMethodDefinition(IRuntimeMethodInfo method)
{
bool fRet = RuntimeMethodHandle.IsGenericMethodDefinition(method.Value);
GC.KeepAlive(method);
return fRet;
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern static bool IsTypicalMethodDefinition(IRuntimeMethodInfo method);
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
private extern static void GetTypicalMethodDefinition(IRuntimeMethodInfo method, ObjectHandleOnStack outMethod);
internal static IRuntimeMethodInfo GetTypicalMethodDefinition(IRuntimeMethodInfo method)
{
if (!IsTypicalMethodDefinition(method))
GetTypicalMethodDefinition(method, JitHelpers.GetObjectHandleOnStack(ref method));
return method;
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private extern static int GetGenericParameterCount(RuntimeMethodHandleInternal method);
internal static int GetGenericParameterCount(IRuntimeMethodInfo method) => GetGenericParameterCount(method.Value);
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
private extern static void StripMethodInstantiation(IRuntimeMethodInfo method, ObjectHandleOnStack outMethod);
internal static IRuntimeMethodInfo StripMethodInstantiation(IRuntimeMethodInfo method)
{
IRuntimeMethodInfo strippedMethod = method;
StripMethodInstantiation(method, JitHelpers.GetObjectHandleOnStack(ref strippedMethod));
return strippedMethod;
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern static bool IsDynamicMethod(RuntimeMethodHandleInternal method);
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
internal extern static void Destroy(RuntimeMethodHandleInternal method);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern static Resolver GetResolver(RuntimeMethodHandleInternal method);
[MethodImpl(MethodImplOptions.InternalCall)]
internal extern static MethodBody GetMethodBody(IRuntimeMethodInfo method, RuntimeType declaringType);
[MethodImpl(MethodImplOptions.InternalCall)]
internal extern static bool IsConstructor(RuntimeMethodHandleInternal method);
[MethodImpl(MethodImplOptions.InternalCall)]
internal extern static LoaderAllocator GetLoaderAllocator(RuntimeMethodHandleInternal method);
}
// This type is used to remove the expense of having a managed reference object that is dynamically
// created when we can prove that we don't need that object. Use of this type requires code to ensure
// that the underlying native resource is not freed.
// Cases in which this may be used:
// 1. When native code calls managed code passing one of these as a parameter
// 2. When managed code acquires one of these from an RtFieldInfo, and ensure that the RtFieldInfo is preserved
// across the lifetime of the RuntimeFieldHandleInternal instance
// 3. When another object is used to keep the RuntimeFieldHandleInternal alive.
// When in doubt, do not use.
internal struct RuntimeFieldHandleInternal
{
internal bool IsNullHandle()
{
return m_handle == IntPtr.Zero;
}
internal IntPtr Value
{
get
{
return m_handle;
}
}
internal RuntimeFieldHandleInternal(IntPtr value)
{
m_handle = value;
}
internal IntPtr m_handle;
}
internal interface IRuntimeFieldInfo
{
RuntimeFieldHandleInternal Value
{
get;
}
}
[StructLayout(LayoutKind.Sequential)]
internal class RuntimeFieldInfoStub : IRuntimeFieldInfo
{
// These unused variables are used to ensure that this class has the same layout as RuntimeFieldInfo
#pragma warning disable 169
private object m_keepalive;
private object m_c;
private object m_d;
private int m_b;
private object m_e;
private RuntimeFieldHandleInternal m_fieldHandle;
#pragma warning restore 169
RuntimeFieldHandleInternal IRuntimeFieldInfo.Value
{
get
{
return m_fieldHandle;
}
}
}
public unsafe struct RuntimeFieldHandle : ISerializable
{
// Returns handle for interop with EE. The handle is guaranteed to be non-null.
internal RuntimeFieldHandle GetNativeHandle()
{
// Create local copy to avoid a race condition
IRuntimeFieldInfo field = m_ptr;
if (field == null)
throw new ArgumentNullException(null, SR.Arg_InvalidHandle);
return new RuntimeFieldHandle(field);
}
private IRuntimeFieldInfo m_ptr;
internal RuntimeFieldHandle(IRuntimeFieldInfo fieldInfo)
{
m_ptr = fieldInfo;
}
internal IRuntimeFieldInfo GetRuntimeFieldInfo()
{
return m_ptr;
}
public IntPtr Value
{
get
{
return m_ptr != null ? m_ptr.Value.Value : IntPtr.Zero;
}
}
internal bool IsNullHandle()
{
return m_ptr == null;
}
public override int GetHashCode()
{
return ValueType.GetHashCodeOfPtr(Value);
}
public override bool Equals(object obj)
{
if (!(obj is RuntimeFieldHandle))
return false;
RuntimeFieldHandle handle = (RuntimeFieldHandle)obj;
return handle.Value == Value;
}
public unsafe bool Equals(RuntimeFieldHandle handle)
{
return handle.Value == Value;
}
public static bool operator ==(RuntimeFieldHandle left, RuntimeFieldHandle right)
{
return left.Equals(right);
}
public static bool operator !=(RuntimeFieldHandle left, RuntimeFieldHandle right)
{
return !left.Equals(right);
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern String GetName(RtFieldInfo field);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern unsafe void* _GetUtf8Name(RuntimeFieldHandleInternal field);
internal static unsafe Utf8String GetUtf8Name(RuntimeFieldHandleInternal field) { return new Utf8String(_GetUtf8Name(field)); }
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern bool MatchesNameHash(RuntimeFieldHandleInternal handle, uint hash);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern FieldAttributes GetAttributes(RuntimeFieldHandleInternal field);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern RuntimeType GetApproxDeclaringType(RuntimeFieldHandleInternal field);
internal static RuntimeType GetApproxDeclaringType(IRuntimeFieldInfo field)
{
RuntimeType type = GetApproxDeclaringType(field.Value);
GC.KeepAlive(field);
return type;
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern int GetToken(RtFieldInfo field);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern Object GetValue(RtFieldInfo field, Object instance, RuntimeType fieldType, RuntimeType declaringType, ref bool domainInitialized);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern Object GetValueDirect(RtFieldInfo field, RuntimeType fieldType, void* pTypedRef, RuntimeType contextType);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern void SetValue(RtFieldInfo field, Object obj, Object value, RuntimeType fieldType, FieldAttributes fieldAttr, RuntimeType declaringType, ref bool domainInitialized);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern void SetValueDirect(RtFieldInfo field, RuntimeType fieldType, void* pTypedRef, Object value, RuntimeType contextType);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern RuntimeFieldHandleInternal GetStaticFieldForGenericType(RuntimeFieldHandleInternal field, RuntimeType declaringType);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern bool AcquiresContextFromThis(RuntimeFieldHandleInternal field);
// ISerializable interface
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
throw new PlatformNotSupportedException();
}
}
public unsafe struct ModuleHandle
{
// Returns handle for interop with EE. The handle is guaranteed to be non-null.
#region Public Static Members
public static readonly ModuleHandle EmptyHandle = GetEmptyMH();
#endregion
unsafe static private ModuleHandle GetEmptyMH()
{
return new ModuleHandle();
}
#region Private Data Members
private RuntimeModule m_ptr;
#endregion
#region Constructor
internal ModuleHandle(RuntimeModule module)
{
m_ptr = module;
}
#endregion
#region Internal FCalls
internal RuntimeModule GetRuntimeModule()
{
return m_ptr;
}
public override int GetHashCode()
{
return m_ptr != null ? m_ptr.GetHashCode() : 0;
}
public override bool Equals(object obj)
{
if (!(obj is ModuleHandle))
return false;
ModuleHandle handle = (ModuleHandle)obj;
return handle.m_ptr == m_ptr;
}
public unsafe bool Equals(ModuleHandle handle)
{
return handle.m_ptr == m_ptr;
}
public static bool operator ==(ModuleHandle left, ModuleHandle right)
{
return left.Equals(right);
}
public static bool operator !=(ModuleHandle left, ModuleHandle right)
{
return !left.Equals(right);
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern IRuntimeMethodInfo GetDynamicMethod(DynamicMethod method, RuntimeModule module, string name, byte[] sig, Resolver resolver);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern int GetToken(RuntimeModule module);
private static void ValidateModulePointer(RuntimeModule module)
{
// Make sure we have a valid Module to resolve against.
if (module == null)
throw new InvalidOperationException(SR.InvalidOperation_NullModuleHandle);
}
// SQL-CLR LKG9 Compiler dependency
public RuntimeTypeHandle GetRuntimeTypeHandleFromMetadataToken(int typeToken) { return ResolveTypeHandle(typeToken); }
public RuntimeTypeHandle ResolveTypeHandle(int typeToken)
{
return new RuntimeTypeHandle(ResolveTypeHandleInternal(GetRuntimeModule(), typeToken, null, null));
}
public RuntimeTypeHandle ResolveTypeHandle(int typeToken, RuntimeTypeHandle[] typeInstantiationContext, RuntimeTypeHandle[] methodInstantiationContext)
{
return new RuntimeTypeHandle(ModuleHandle.ResolveTypeHandleInternal(GetRuntimeModule(), typeToken, typeInstantiationContext, methodInstantiationContext));
}
internal static RuntimeType ResolveTypeHandleInternal(RuntimeModule module, int typeToken, RuntimeTypeHandle[] typeInstantiationContext, RuntimeTypeHandle[] methodInstantiationContext)
{
ValidateModulePointer(module);
if (!ModuleHandle.GetMetadataImport(module).IsValidToken(typeToken))
throw new ArgumentOutOfRangeException(nameof(typeToken),
SR.Format(SR.Argument_InvalidToken, typeToken, new ModuleHandle(module)));
int typeInstCount, methodInstCount;
IntPtr[] typeInstantiationContextHandles = RuntimeTypeHandle.CopyRuntimeTypeHandles(typeInstantiationContext, out typeInstCount);
IntPtr[] methodInstantiationContextHandles = RuntimeTypeHandle.CopyRuntimeTypeHandles(methodInstantiationContext, out methodInstCount);
fixed (IntPtr* typeInstArgs = typeInstantiationContextHandles, methodInstArgs = methodInstantiationContextHandles)
{
RuntimeType type = null;
ResolveType(module, typeToken, typeInstArgs, typeInstCount, methodInstArgs, methodInstCount, JitHelpers.GetObjectHandleOnStack(ref type));
GC.KeepAlive(typeInstantiationContext);
GC.KeepAlive(methodInstantiationContext);
return type;
}
}
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
private extern static void ResolveType(RuntimeModule module,
int typeToken,
IntPtr* typeInstArgs,
int typeInstCount,
IntPtr* methodInstArgs,
int methodInstCount,
ObjectHandleOnStack type);
// SQL-CLR LKG9 Compiler dependency
public RuntimeMethodHandle GetRuntimeMethodHandleFromMetadataToken(int methodToken) { return ResolveMethodHandle(methodToken); }
public RuntimeMethodHandle ResolveMethodHandle(int methodToken) { return ResolveMethodHandle(methodToken, null, null); }
internal static IRuntimeMethodInfo ResolveMethodHandleInternal(RuntimeModule module, int methodToken) { return ModuleHandle.ResolveMethodHandleInternal(module, methodToken, null, null); }
public RuntimeMethodHandle ResolveMethodHandle(int methodToken, RuntimeTypeHandle[] typeInstantiationContext, RuntimeTypeHandle[] methodInstantiationContext)
{
return new RuntimeMethodHandle(ResolveMethodHandleInternal(GetRuntimeModule(), methodToken, typeInstantiationContext, methodInstantiationContext));
}
internal static IRuntimeMethodInfo ResolveMethodHandleInternal(RuntimeModule module, int methodToken, RuntimeTypeHandle[] typeInstantiationContext, RuntimeTypeHandle[] methodInstantiationContext)
{
int typeInstCount, methodInstCount;
IntPtr[] typeInstantiationContextHandles = RuntimeTypeHandle.CopyRuntimeTypeHandles(typeInstantiationContext, out typeInstCount);
IntPtr[] methodInstantiationContextHandles = RuntimeTypeHandle.CopyRuntimeTypeHandles(methodInstantiationContext, out methodInstCount);
RuntimeMethodHandleInternal handle = ResolveMethodHandleInternalCore(module, methodToken, typeInstantiationContextHandles, typeInstCount, methodInstantiationContextHandles, methodInstCount);
IRuntimeMethodInfo retVal = new RuntimeMethodInfoStub(handle, RuntimeMethodHandle.GetLoaderAllocator(handle));
GC.KeepAlive(typeInstantiationContext);
GC.KeepAlive(methodInstantiationContext);
return retVal;
}
internal static RuntimeMethodHandleInternal ResolveMethodHandleInternalCore(RuntimeModule module, int methodToken, IntPtr[] typeInstantiationContext, int typeInstCount, IntPtr[] methodInstantiationContext, int methodInstCount)
{
ValidateModulePointer(module);
if (!ModuleHandle.GetMetadataImport(module.GetNativeHandle()).IsValidToken(methodToken))
throw new ArgumentOutOfRangeException(nameof(methodToken),
SR.Format(SR.Argument_InvalidToken, methodToken, new ModuleHandle(module)));
fixed (IntPtr* typeInstArgs = typeInstantiationContext, methodInstArgs = methodInstantiationContext)
{
return ResolveMethod(module.GetNativeHandle(), methodToken, typeInstArgs, typeInstCount, methodInstArgs, methodInstCount);
}
}
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
private extern static RuntimeMethodHandleInternal ResolveMethod(RuntimeModule module,
int methodToken,
IntPtr* typeInstArgs,
int typeInstCount,
IntPtr* methodInstArgs,
int methodInstCount);
// SQL-CLR LKG9 Compiler dependency
public RuntimeFieldHandle GetRuntimeFieldHandleFromMetadataToken(int fieldToken) { return ResolveFieldHandle(fieldToken); }
public RuntimeFieldHandle ResolveFieldHandle(int fieldToken) { return new RuntimeFieldHandle(ResolveFieldHandleInternal(GetRuntimeModule(), fieldToken, null, null)); }
public RuntimeFieldHandle ResolveFieldHandle(int fieldToken, RuntimeTypeHandle[] typeInstantiationContext, RuntimeTypeHandle[] methodInstantiationContext)
{ return new RuntimeFieldHandle(ResolveFieldHandleInternal(GetRuntimeModule(), fieldToken, typeInstantiationContext, methodInstantiationContext)); }
internal static IRuntimeFieldInfo ResolveFieldHandleInternal(RuntimeModule module, int fieldToken, RuntimeTypeHandle[] typeInstantiationContext, RuntimeTypeHandle[] methodInstantiationContext)
{
ValidateModulePointer(module);
if (!ModuleHandle.GetMetadataImport(module.GetNativeHandle()).IsValidToken(fieldToken))
throw new ArgumentOutOfRangeException(nameof(fieldToken),
SR.Format(SR.Argument_InvalidToken, fieldToken, new ModuleHandle(module)));
// defensive copy to be sure array is not mutated from the outside during processing
int typeInstCount, methodInstCount;
IntPtr[] typeInstantiationContextHandles = RuntimeTypeHandle.CopyRuntimeTypeHandles(typeInstantiationContext, out typeInstCount);
IntPtr[] methodInstantiationContextHandles = RuntimeTypeHandle.CopyRuntimeTypeHandles(methodInstantiationContext, out methodInstCount);
fixed (IntPtr* typeInstArgs = typeInstantiationContextHandles, methodInstArgs = methodInstantiationContextHandles)
{
IRuntimeFieldInfo field = null;
ResolveField(module.GetNativeHandle(), fieldToken, typeInstArgs, typeInstCount, methodInstArgs, methodInstCount, JitHelpers.GetObjectHandleOnStack(ref field));
GC.KeepAlive(typeInstantiationContext);
GC.KeepAlive(methodInstantiationContext);
return field;
}
}
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
private extern static void ResolveField(RuntimeModule module,
int fieldToken,
IntPtr* typeInstArgs,
int typeInstCount,
IntPtr* methodInstArgs,
int methodInstCount,
ObjectHandleOnStack retField);
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
private extern static bool _ContainsPropertyMatchingHash(RuntimeModule module, int propertyToken, uint hash);
internal static bool ContainsPropertyMatchingHash(RuntimeModule module, int propertyToken, uint hash)
{
return _ContainsPropertyMatchingHash(module.GetNativeHandle(), propertyToken, hash);
}
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
internal extern static void GetModuleType(RuntimeModule handle, ObjectHandleOnStack type);
internal static RuntimeType GetModuleType(RuntimeModule module)
{
RuntimeType type = null;
GetModuleType(module.GetNativeHandle(), JitHelpers.GetObjectHandleOnStack(ref type));
return type;
}
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
private extern static void GetPEKind(RuntimeModule handle, out int peKind, out int machine);
// making this internal, used by Module.GetPEKind
internal static void GetPEKind(RuntimeModule module, out PortableExecutableKinds peKind, out ImageFileMachine machine)
{
int lKind, lMachine;
GetPEKind(module.GetNativeHandle(), out lKind, out lMachine);
peKind = (PortableExecutableKinds)lKind;
machine = (ImageFileMachine)lMachine;
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern static int GetMDStreamVersion(RuntimeModule module);
public int MDStreamVersion
{
get { return GetMDStreamVersion(GetRuntimeModule().GetNativeHandle()); }
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private extern static IntPtr _GetMetadataImport(RuntimeModule module);
internal static MetadataImport GetMetadataImport(RuntimeModule module)
{
return new MetadataImport(_GetMetadataImport(module.GetNativeHandle()), module);
}
#endregion
}
internal unsafe class Signature
{
#region Definitions
internal enum MdSigCallingConvention : byte
{
Generics = 0x10,
HasThis = 0x20,
ExplicitThis = 0x40,
CallConvMask = 0x0F,
Default = 0x00,
C = 0x01,
StdCall = 0x02,
ThisCall = 0x03,
FastCall = 0x04,
Vararg = 0x05,
Field = 0x06,
LocalSig = 0x07,
Property = 0x08,
Unmgd = 0x09,
GenericInst = 0x0A,
Max = 0x0B,
}
#endregion
#region FCalls
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private extern void GetSignature(
void* pCorSig, int cCorSig,
RuntimeFieldHandleInternal fieldHandle, IRuntimeMethodInfo methodHandle, RuntimeType declaringType);
#endregion
#region Private Data Members
//
// Keep the layout in sync with SignatureNative in the VM
//
internal RuntimeType[] m_arguments;
internal RuntimeType m_declaringType;
internal RuntimeType m_returnTypeORfieldType;
internal object m_keepalive;
internal void* m_sig;
internal int m_managedCallingConventionAndArgIteratorFlags; // lowest byte is CallingConvention, upper 3 bytes are ArgIterator flags
internal int m_nSizeOfArgStack;
internal int m_csig;
internal RuntimeMethodHandleInternal m_pMethod;
#endregion
#region Constructors
public Signature(
IRuntimeMethodInfo method,
RuntimeType[] arguments,
RuntimeType returnType,
CallingConventions callingConvention)
{
m_pMethod = method.Value;
m_arguments = arguments;
m_returnTypeORfieldType = returnType;
m_managedCallingConventionAndArgIteratorFlags = (byte)callingConvention;
GetSignature(null, 0, new RuntimeFieldHandleInternal(), method, null);
}
public Signature(IRuntimeMethodInfo methodHandle, RuntimeType declaringType)
{
GetSignature(null, 0, new RuntimeFieldHandleInternal(), methodHandle, declaringType);
}
public Signature(IRuntimeFieldInfo fieldHandle, RuntimeType declaringType)
{
GetSignature(null, 0, fieldHandle.Value, null, declaringType);
GC.KeepAlive(fieldHandle);
}
public Signature(void* pCorSig, int cCorSig, RuntimeType declaringType)
{
GetSignature(pCorSig, cCorSig, new RuntimeFieldHandleInternal(), null, declaringType);
}
#endregion
#region Internal Members
internal CallingConventions CallingConvention { get { return (CallingConventions)(byte)m_managedCallingConventionAndArgIteratorFlags; } }
internal RuntimeType[] Arguments { get { return m_arguments; } }
internal RuntimeType ReturnType { get { return m_returnTypeORfieldType; } }
internal RuntimeType FieldType { get { return m_returnTypeORfieldType; } }
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern bool CompareSig(Signature sig1, Signature sig2);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern Type[] GetCustomModifiers(int position, bool required);
#endregion
}
internal abstract class Resolver
{
internal struct CORINFO_EH_CLAUSE
{
internal int Flags;
internal int TryOffset;
internal int TryLength;
internal int HandlerOffset;
internal int HandlerLength;
internal int ClassTokenOrFilterOffset;
}
// ILHeader info
internal abstract RuntimeType GetJitContext(ref int securityControlFlags);
internal abstract byte[] GetCodeInfo(ref int stackSize, ref int initLocals, ref int EHCount);
internal abstract byte[] GetLocalsSignature();
internal abstract unsafe void GetEHInfo(int EHNumber, void* exception);
internal abstract unsafe byte[] GetRawEHInfo();
// token resolution
internal abstract String GetStringLiteral(int token);
internal abstract void ResolveToken(int token, out IntPtr typeHandle, out IntPtr methodHandle, out IntPtr fieldHandle);
internal abstract byte[] ResolveSignature(int token, int fromMethod);
//
internal abstract MethodInfo GetDynamicMethod();
}
}
| |
using System;
using System.Globalization;
// CoreCLR Port from Co7526TryParse_all.cs
// Tests UInt16.TryParse(String), UInt16.TryParse(String, NumberStyles, IFormatProvider, ref UInt16)
// 2003/04/01 KatyK
// 2007/06/28 adapted by MarielY
public class Co7526TryParse
{
static bool verbose = false;
public static int Main()
{
bool passed = true;
try
{
// Make the test culture independent
TestLibrary.Utilities.CurrentCulture = CultureInfo.InvariantCulture;
// Set up NFIs to use
NumberFormatInfo goodNFI = new NumberFormatInfo();
NumberFormatInfo corruptNFI = new NumberFormatInfo(); // DecimalSeparator == GroupSeparator
corruptNFI.NumberDecimalSeparator = ".";
corruptNFI.NumberGroupSeparator = ".";
corruptNFI.CurrencyDecimalSeparator = ".";
corruptNFI.CurrencyGroupSeparator = ".";
corruptNFI.CurrencySymbol = "$";
NumberFormatInfo swappedNFI = new NumberFormatInfo(); // DecimalSeparator & GroupSeparator swapped
swappedNFI.NumberDecimalSeparator = ".";
swappedNFI.NumberGroupSeparator = ",";
swappedNFI.CurrencyDecimalSeparator = ",";
swappedNFI.CurrencyGroupSeparator = ".";
swappedNFI.CurrencySymbol = "$";
NumberFormatInfo distinctNFI = new NumberFormatInfo(); // DecimalSeparator & GroupSeparator distinct
distinctNFI.NumberDecimalSeparator = ".";
distinctNFI.NumberGroupSeparator = ",";
distinctNFI.CurrencyDecimalSeparator = ":";
distinctNFI.CurrencyGroupSeparator = ";";
distinctNFI.CurrencySymbol = "$";
NumberFormatInfo customNFI = new NumberFormatInfo();
customNFI.NegativeSign = "^";
NumberFormatInfo ambigNFI = new NumberFormatInfo();
ambigNFI.NegativeSign = "^";
ambigNFI.CurrencySymbol = "^";
CultureInfo germanCulture = new CultureInfo("de-DE");
CultureInfo japaneseCulture;
try
{
japaneseCulture = new CultureInfo("ja-JP");
}
catch (Exception)
{
TestLibrary.Logging.WriteLine("East Asian Languages are not installed. Skiping Japanese culture tests.");
japaneseCulture = null;
}
// Parse tests included for comparison/regression
passed &= VerifyUInt16Parse("5", 5);
passed &= VerifyUInt16Parse("5 ", 5);
passed &= VerifyUInt16Parse("5\0", 5);
passed &= VerifyUInt16Parse("10000", 10000);
passed &= VerifyUInt16Parse("50000", 50000);
passed &= VerifyUInt16Parse("5", NumberStyles.Integer, CultureInfo.InvariantCulture, 5);
passed &= VerifyUInt16Parse("5 \0", NumberStyles.Integer, CultureInfo.InvariantCulture, 5);
passed &= VerifyUInt16Parse("5\0\0\0", NumberStyles.Integer, CultureInfo.InvariantCulture, 5);
passed &= VerifyUInt16Parse("12", NumberStyles.HexNumber, CultureInfo.InvariantCulture, 0x12);
passed &= VerifyUInt16Parse("fF", NumberStyles.HexNumber, CultureInfo.InvariantCulture, 0xFF);
passed &= VerifyUInt16Parse("fFFF", NumberStyles.HexNumber, CultureInfo.InvariantCulture, 0xFFFF);
passed &= VerifyUInt16Parse("5", NumberStyles.Integer, goodNFI, 5);
passed &= VerifyUInt16Parse("5.0", NumberStyles.AllowDecimalPoint, goodNFI, 5);
passed &= VerifyUInt16Parse("123", NumberStyles.Integer, germanCulture, 123);
passed &= VerifyUInt16Parse("123", NumberStyles.Integer, japaneseCulture, 123);
passed &= VerifyUInt16Parse("123,000", NumberStyles.AllowDecimalPoint, germanCulture, 123);
passed &= VerifyUInt16Parse("123.000", NumberStyles.AllowDecimalPoint, japaneseCulture, 123);
passed &= VerifyUInt16Parse("5,00 " + germanCulture.NumberFormat.CurrencySymbol, NumberStyles.Any, germanCulture, 5); // currency
//
passed &= VerifyUInt16Parse("5", NumberStyles.Integer, corruptNFI, 5);
passed &= VerifyUInt16Parse("5", NumberStyles.Number, corruptNFI, 5);
passed &= VerifyUInt16Parse("5.0", NumberStyles.Number, corruptNFI, 5);
passed &= VerifyUInt16ParseException("5,0", NumberStyles.Number, corruptNFI, typeof(FormatException));
passed &= VerifyUInt16ParseException("5.0.0", NumberStyles.Number, corruptNFI, typeof(FormatException));
passed &= VerifyUInt16Parse("$5.0", NumberStyles.Currency, corruptNFI, 5);
passed &= VerifyUInt16ParseException("$5,0", NumberStyles.Currency, corruptNFI, typeof(FormatException));
passed &= VerifyUInt16ParseException("$5.0.0", NumberStyles.Currency, corruptNFI, typeof(FormatException));
passed &= VerifyUInt16Parse("5.0", NumberStyles.Currency, corruptNFI, 5);
passed &= VerifyUInt16ParseException("5,0", NumberStyles.Currency, corruptNFI, typeof(FormatException));
passed &= VerifyUInt16ParseException("5.0.0", NumberStyles.Currency, corruptNFI, typeof(FormatException));
passed &= VerifyUInt16Parse("5.0", NumberStyles.Any, corruptNFI, 5);
passed &= VerifyUInt16ParseException("5,0", NumberStyles.Any, corruptNFI, typeof(FormatException));
passed &= VerifyUInt16ParseException("5.0.0", NumberStyles.Any, corruptNFI, typeof(FormatException));
//
passed &= VerifyUInt16Parse("5", NumberStyles.Integer, swappedNFI, 5);
passed &= VerifyUInt16ParseException("1,234", NumberStyles.Integer, swappedNFI, typeof(FormatException));
passed &= VerifyUInt16Parse("5", NumberStyles.Number, swappedNFI, 5);
passed &= VerifyUInt16Parse("5.0", NumberStyles.Number, swappedNFI, 5);
passed &= VerifyUInt16Parse("1,234", NumberStyles.Number, swappedNFI, 1234);
passed &= VerifyUInt16Parse("1,234.0", NumberStyles.Number, swappedNFI, 1234);
passed &= VerifyUInt16ParseException("5.000.000", NumberStyles.Number, swappedNFI, typeof(FormatException));
passed &= VerifyUInt16ParseException("5.000,00", NumberStyles.Number, swappedNFI, typeof(FormatException));
passed &= VerifyUInt16Parse("5.000", NumberStyles.Currency, swappedNFI, 5); //???
passed &= VerifyUInt16ParseException("5.000,00", NumberStyles.Currency, swappedNFI, typeof(FormatException)); //???
passed &= VerifyUInt16Parse("$5.000", NumberStyles.Currency, swappedNFI, 5000);
passed &= VerifyUInt16Parse("$5.000,00", NumberStyles.Currency, swappedNFI, 5000);
passed &= VerifyUInt16Parse("5.000", NumberStyles.Any, swappedNFI, 5); //?
passed &= VerifyUInt16ParseException("5.000,00", NumberStyles.Any, swappedNFI, typeof(FormatException)); //?
passed &= VerifyUInt16Parse("$5.000", NumberStyles.Any, swappedNFI, 5000);
passed &= VerifyUInt16Parse("$5.000,00", NumberStyles.Any, swappedNFI, 5000);
passed &= VerifyUInt16Parse("5,0", NumberStyles.Currency, swappedNFI, 5);
passed &= VerifyUInt16Parse("$5,0", NumberStyles.Currency, swappedNFI, 5);
passed &= VerifyUInt16Parse("5,000", NumberStyles.Currency, swappedNFI, 5);
passed &= VerifyUInt16Parse("$5,000", NumberStyles.Currency, swappedNFI, 5);
passed &= VerifyUInt16ParseException("5,000.0", NumberStyles.Currency, swappedNFI, typeof(FormatException));
passed &= VerifyUInt16ParseException("$5,000.0", NumberStyles.Currency, swappedNFI, typeof(FormatException));
passed &= VerifyUInt16Parse("5,000", NumberStyles.Any, swappedNFI, 5);
passed &= VerifyUInt16Parse("$5,000", NumberStyles.Any, swappedNFI, 5);
passed &= VerifyUInt16ParseException("5,000.0", NumberStyles.Any, swappedNFI, typeof(FormatException));
passed &= VerifyUInt16ParseException("$5,000.0", NumberStyles.Any, swappedNFI, typeof(FormatException));
//
passed &= VerifyUInt16Parse("5.0", NumberStyles.Number, distinctNFI, 5);
passed &= VerifyUInt16Parse("1,234.0", NumberStyles.Number, distinctNFI, 1234);
passed &= VerifyUInt16Parse("5.0", NumberStyles.Currency, distinctNFI, 5);
passed &= VerifyUInt16Parse("1,234.0", NumberStyles.Currency, distinctNFI, 1234);
passed &= VerifyUInt16Parse("5.0", NumberStyles.Any, distinctNFI, 5);
passed &= VerifyUInt16Parse("1,234.0", NumberStyles.Any, distinctNFI, 1234);
passed &= VerifyUInt16ParseException("$5.0", NumberStyles.Currency, distinctNFI, typeof(FormatException));
passed &= VerifyUInt16ParseException("$5.0", NumberStyles.Any, distinctNFI, typeof(FormatException));
passed &= VerifyUInt16ParseException("5:0", NumberStyles.Number, distinctNFI, typeof(FormatException));
passed &= VerifyUInt16ParseException("5;0", NumberStyles.Number, distinctNFI, typeof(FormatException));
passed &= VerifyUInt16ParseException("$5:0", NumberStyles.Number, distinctNFI, typeof(FormatException));
passed &= VerifyUInt16Parse("5:0", NumberStyles.Currency, distinctNFI, 5);
passed &= VerifyUInt16Parse("5:000", NumberStyles.Currency, distinctNFI, 5);
passed &= VerifyUInt16Parse("5;000", NumberStyles.Currency, distinctNFI, 5000);
passed &= VerifyUInt16Parse("$5:0", NumberStyles.Currency, distinctNFI, 5);
passed &= VerifyUInt16Parse("$5;0", NumberStyles.Currency, distinctNFI, 50);
passed &= VerifyUInt16Parse("5:0", NumberStyles.Any, distinctNFI, 5);
passed &= VerifyUInt16Parse("5;0", NumberStyles.Any, distinctNFI, 50);
passed &= VerifyUInt16Parse("$5:0", NumberStyles.Any, distinctNFI, 5);
passed &= VerifyUInt16Parse("$5;0", NumberStyles.Any, distinctNFI, 50);
passed &= VerifyUInt16ParseException("1,23;45.0", NumberStyles.Number, distinctNFI, typeof(FormatException));
passed &= VerifyUInt16Parse("1,23;45.0", NumberStyles.Currency, distinctNFI, 12345);
passed &= VerifyUInt16Parse("1,23;45.0", NumberStyles.Any, distinctNFI, 12345);
passed &= VerifyUInt16ParseException("$1,23;45.0", NumberStyles.Any, distinctNFI, typeof(FormatException));
//
passed &= VerifyUInt16ParseException("-5", typeof(OverflowException));
passed &= VerifyUInt16ParseException("100000", typeof(OverflowException));
passed &= VerifyUInt16ParseException("Garbage", typeof(FormatException));
passed &= VerifyUInt16ParseException("5\0Garbage", typeof(FormatException));
passed &= VerifyUInt16ParseException(null, typeof(ArgumentNullException));
passed &= VerifyUInt16ParseException("1FFFF", NumberStyles.HexNumber, CultureInfo.InvariantCulture, typeof(OverflowException));
passed &= VerifyUInt16ParseException("FFFFFFFF", NumberStyles.HexNumber, CultureInfo.InvariantCulture, typeof(OverflowException));
passed &= VerifyUInt16ParseException("5", NumberStyles.AllowHexSpecifier | NumberStyles.AllowParentheses, null, typeof(ArgumentException));
passed &= VerifyUInt16ParseException("4", (NumberStyles)(-1), typeof(ArgumentException));
passed &= VerifyUInt16ParseException("4", (NumberStyles)0x10000, typeof(ArgumentException));
passed &= VerifyUInt16ParseException("4", (NumberStyles)(-1), CultureInfo.InvariantCulture, typeof(ArgumentException));
passed &= VerifyUInt16ParseException("4", (NumberStyles)0x10000, CultureInfo.InvariantCulture, typeof(ArgumentException));
passed &= VerifyUInt16ParseException("123.000", NumberStyles.Any, germanCulture, typeof(OverflowException));
passed &= VerifyUInt16ParseException("123,000", NumberStyles.Any, japaneseCulture, typeof(OverflowException));
passed &= VerifyUInt16ParseException("123,000", NumberStyles.Integer, germanCulture, typeof(FormatException));
passed &= VerifyUInt16ParseException("123.000", NumberStyles.Integer, japaneseCulture, typeof(FormatException));
passed &= VerifyUInt16ParseException("5,00 " + germanCulture.NumberFormat.CurrencySymbol, NumberStyles.Integer, germanCulture, typeof(FormatException)); // currency
/////////// TryParse(String)
//// Pass cases
passed &= VerifyUInt16TryParse("5", 5, true);
passed &= VerifyUInt16TryParse(" 5 ", 5, true);
passed &= VerifyUInt16TryParse("5\0", 5, true);
passed &= VerifyUInt16TryParse("5 \0", 5, true);
passed &= VerifyUInt16TryParse("5\0\0\0", 5, true);
passed &= VerifyUInt16TryParse("10000", 10000, true);
passed &= VerifyUInt16TryParse("50000", 50000, true);
passed &= VerifyUInt16TryParse(UInt16.MaxValue.ToString(), UInt16.MaxValue, true);
passed &= VerifyUInt16TryParse(UInt16.MinValue.ToString(), UInt16.MinValue, true);
//// Fail cases
passed &= VerifyUInt16TryParse(null, 0, false);
passed &= VerifyUInt16TryParse("", 0, false);
passed &= VerifyUInt16TryParse("Garbage", 0, false);
passed &= VerifyUInt16TryParse("5\0Garbage", 0, false);
passed &= VerifyUInt16TryParse("-5", 0, false);
passed &= VerifyUInt16TryParse("100000", 0, false);
passed &= VerifyUInt16TryParse("-100000", 0, false);
passed &= VerifyUInt16TryParse("FF", 0, false);
passed &= VerifyUInt16TryParse("27.3", 0, false);
passed &= VerifyUInt16TryParse("23 5", 0, false);
/////////// TryParse(TryParse(String, NumberStyles, IFormatProvider, ref UInt16)
//// Pass cases
passed &= VerifyUInt16TryParse("5", NumberStyles.Integer, CultureInfo.InvariantCulture, 5, true);
// Variations on NumberStyles
passed &= VerifyUInt16TryParse("12", NumberStyles.HexNumber, CultureInfo.InvariantCulture, 0x12, true);
passed &= VerifyUInt16TryParse("FF", NumberStyles.HexNumber, CultureInfo.InvariantCulture, 0xFF, true);
passed &= VerifyUInt16TryParse("fF", NumberStyles.HexNumber, CultureInfo.InvariantCulture, 0xFF, true);
passed &= VerifyUInt16TryParse("fFFF", NumberStyles.HexNumber, CultureInfo.InvariantCulture, 0xFFFF, true);
passed &= VerifyUInt16TryParse(" 5", NumberStyles.AllowLeadingWhite, goodNFI, 5, true);
passed &= VerifyUInt16TryParse("5", NumberStyles.Number, goodNFI, 5, true);
passed &= VerifyUInt16TryParse("5.0", NumberStyles.AllowDecimalPoint, goodNFI, 5, true);
// Variations on IFP
passed &= VerifyUInt16TryParse("5", NumberStyles.Integer, goodNFI, 5, true);
passed &= VerifyUInt16TryParse("5", NumberStyles.Integer, null, 5, true);
passed &= VerifyUInt16TryParse("5", NumberStyles.Integer, new DateTimeFormatInfo(), 5, true);
passed &= VerifyUInt16TryParse("123", NumberStyles.Integer, germanCulture, 123, true);
passed &= VerifyUInt16TryParse("123", NumberStyles.Integer, japaneseCulture, 123, true);
passed &= VerifyUInt16TryParse("123,000", NumberStyles.AllowDecimalPoint, germanCulture, 123, true);
passed &= VerifyUInt16TryParse("123.000", NumberStyles.AllowDecimalPoint, japaneseCulture, 123, true);
passed &= VerifyUInt16TryParse("5,00 " + germanCulture.NumberFormat.CurrencySymbol, NumberStyles.Any, germanCulture, 5, true); // currency
//// Fail cases
passed &= VerifyUInt16TryParse("-5", NumberStyles.Integer, CultureInfo.InvariantCulture, 0, false);
passed &= VerifyUInt16TryParse("FF", NumberStyles.Integer, CultureInfo.InvariantCulture, 0, false);
passed &= VerifyUInt16TryParse("1FFFF", NumberStyles.HexNumber, CultureInfo.InvariantCulture, 0, false);
passed &= VerifyUInt16TryParse("FFFFFFFF", NumberStyles.HexNumber, CultureInfo.InvariantCulture, 0, false);
passed &= VerifyUInt16TryParse("^42", NumberStyles.Any, customNFI, 0, false);
passed &= VerifyUInt16TryParse("-42", NumberStyles.Any, customNFI, 0, false);
passed &= VerifyUInt16TryParse("5.3", NumberStyles.AllowDecimalPoint, goodNFI, 0, false);
passed &= VerifyUInt16TryParse("5 ", NumberStyles.AllowLeadingWhite, goodNFI, 0, false);
passed &= VerifyUInt16TryParse("123.000", NumberStyles.Any, germanCulture, 0, false);
passed &= VerifyUInt16TryParse("123,000", NumberStyles.Any, japaneseCulture, 0, false);
passed &= VerifyUInt16TryParse("123,000", NumberStyles.Integer, germanCulture, 0, false);
passed &= VerifyUInt16TryParse("123.000", NumberStyles.Integer, japaneseCulture, 0, false);
passed &= VerifyUInt16TryParse("5,00 " + germanCulture.NumberFormat.CurrencySymbol, NumberStyles.Integer, germanCulture, 0, false); // currency
//// Exception cases
passed &= VerifyUInt16TryParseException("5", NumberStyles.AllowHexSpecifier | NumberStyles.AllowParentheses, null, typeof(ArgumentException));
passed &= VerifyUInt16TryParseException("4", (NumberStyles)(-1), CultureInfo.InvariantCulture, typeof(ArgumentException));
passed &= VerifyUInt16TryParseException("4", (NumberStyles)0x10000, CultureInfo.InvariantCulture, typeof(ArgumentException));
// NumberStyles/NFI variations
//
passed &= VerifyUInt16TryParse("5", NumberStyles.Integer, corruptNFI, 5, true);
passed &= VerifyUInt16TryParse("5", NumberStyles.Number, corruptNFI, 5, true);
passed &= VerifyUInt16TryParse("5.0", NumberStyles.Number, corruptNFI, 5, true);
passed &= VerifyUInt16TryParse("5,0", NumberStyles.Number, corruptNFI, 0, false);
passed &= VerifyUInt16TryParse("5.0.0", NumberStyles.Number, corruptNFI, 0, false);
passed &= VerifyUInt16TryParse("$5.0", NumberStyles.Currency, corruptNFI, 5, true);
passed &= VerifyUInt16TryParse("$5,0", NumberStyles.Currency, corruptNFI, 0, false);
passed &= VerifyUInt16TryParse("$5.0.0", NumberStyles.Currency, corruptNFI, 0, false);
passed &= VerifyUInt16TryParse("5.0", NumberStyles.Currency, corruptNFI, 5, true);
passed &= VerifyUInt16TryParse("5,0", NumberStyles.Currency, corruptNFI, 0, false);
passed &= VerifyUInt16TryParse("5.0.0", NumberStyles.Currency, corruptNFI, 0, false);
passed &= VerifyUInt16TryParse("5.0", NumberStyles.Any, corruptNFI, 5, true);
passed &= VerifyUInt16TryParse("5,0", NumberStyles.Any, corruptNFI, 0, false);
passed &= VerifyUInt16TryParse("5.0.0", NumberStyles.Any, corruptNFI, 0, false);
//
passed &= VerifyUInt16TryParse("5", NumberStyles.Integer, swappedNFI, 5, true);
passed &= VerifyUInt16TryParse("1,234", NumberStyles.Integer, swappedNFI, 0, false);
passed &= VerifyUInt16TryParse("5", NumberStyles.Number, swappedNFI, 5, true);
passed &= VerifyUInt16TryParse("5.0", NumberStyles.Number, swappedNFI, 5, true);
passed &= VerifyUInt16TryParse("1,234", NumberStyles.Number, swappedNFI, 1234, true);
passed &= VerifyUInt16TryParse("1,234.0", NumberStyles.Number, swappedNFI, 1234, true);
passed &= VerifyUInt16TryParse("5.000.000", NumberStyles.Number, swappedNFI, 0, false);
passed &= VerifyUInt16TryParse("5.000,00", NumberStyles.Number, swappedNFI, 0, false);
passed &= VerifyUInt16TryParse("5.000", NumberStyles.Currency, swappedNFI, 5, true); //???
passed &= VerifyUInt16TryParse("5.000,00", NumberStyles.Currency, swappedNFI, 0, false); //???
passed &= VerifyUInt16TryParse("$5.000", NumberStyles.Currency, swappedNFI, 5000, true);
passed &= VerifyUInt16TryParse("$5.000,00", NumberStyles.Currency, swappedNFI, 5000, true);
passed &= VerifyUInt16TryParse("5.000", NumberStyles.Any, swappedNFI, 5, true); //?
passed &= VerifyUInt16TryParse("5.000,00", NumberStyles.Any, swappedNFI, 0, false); //?
passed &= VerifyUInt16TryParse("$5.000", NumberStyles.Any, swappedNFI, 5000, true);
passed &= VerifyUInt16TryParse("$5.000,00", NumberStyles.Any, swappedNFI, 5000, true);
passed &= VerifyUInt16TryParse("5,0", NumberStyles.Currency, swappedNFI, 5, true);
passed &= VerifyUInt16TryParse("$5,0", NumberStyles.Currency, swappedNFI, 5, true);
passed &= VerifyUInt16TryParse("5,000", NumberStyles.Currency, swappedNFI, 5, true);
passed &= VerifyUInt16TryParse("$5,000", NumberStyles.Currency, swappedNFI, 5, true);
passed &= VerifyUInt16TryParse("5,000.0", NumberStyles.Currency, swappedNFI, 0, false);
passed &= VerifyUInt16TryParse("$5,000.0", NumberStyles.Currency, swappedNFI, 0, false);
passed &= VerifyUInt16TryParse("5,000", NumberStyles.Any, swappedNFI, 5, true);
passed &= VerifyUInt16TryParse("$5,000", NumberStyles.Any, swappedNFI, 5, true);
passed &= VerifyUInt16TryParse("5,000.0", NumberStyles.Any, swappedNFI, 0, false);
passed &= VerifyUInt16TryParse("$5,000.0", NumberStyles.Any, swappedNFI, 0, false);
//
passed &= VerifyUInt16TryParse("5.0", NumberStyles.Number, distinctNFI, 5, true);
passed &= VerifyUInt16TryParse("1,234.0", NumberStyles.Number, distinctNFI, 1234, true);
passed &= VerifyUInt16TryParse("5.0", NumberStyles.Currency, distinctNFI, 5, true);
passed &= VerifyUInt16TryParse("1,234.0", NumberStyles.Currency, distinctNFI, 1234, true);
passed &= VerifyUInt16TryParse("5.0", NumberStyles.Any, distinctNFI, 5, true);
passed &= VerifyUInt16TryParse("1,234.0", NumberStyles.Any, distinctNFI, 1234, true);
passed &= VerifyUInt16TryParse("$5.0", NumberStyles.Currency, distinctNFI, 0, false);
passed &= VerifyUInt16TryParse("$5.0", NumberStyles.Any, distinctNFI, 0, false);
passed &= VerifyUInt16TryParse("5:0", NumberStyles.Number, distinctNFI, 0, false);
passed &= VerifyUInt16TryParse("5;0", NumberStyles.Number, distinctNFI, 0, false);
passed &= VerifyUInt16TryParse("$5:0", NumberStyles.Number, distinctNFI, 0, false);
passed &= VerifyUInt16TryParse("5:0", NumberStyles.Currency, distinctNFI, 5, true);
passed &= VerifyUInt16TryParse("5:000", NumberStyles.Currency, distinctNFI, 5, true);
passed &= VerifyUInt16TryParse("5;000", NumberStyles.Currency, distinctNFI, 5000, true);
passed &= VerifyUInt16TryParse("$5:0", NumberStyles.Currency, distinctNFI, 5, true);
passed &= VerifyUInt16TryParse("$5;0", NumberStyles.Currency, distinctNFI, 50, true);
passed &= VerifyUInt16TryParse("5:0", NumberStyles.Any, distinctNFI, 5, true);
passed &= VerifyUInt16TryParse("5;0", NumberStyles.Any, distinctNFI, 50, true);
passed &= VerifyUInt16TryParse("$5:0", NumberStyles.Any, distinctNFI, 5, true);
passed &= VerifyUInt16TryParse("$5;0", NumberStyles.Any, distinctNFI, 50, true);
passed &= VerifyUInt16TryParse("1,23;45.0", NumberStyles.Number, distinctNFI, 0, false);
passed &= VerifyUInt16TryParse("1,23;45.0", NumberStyles.Currency, distinctNFI, 12345, true);
passed &= VerifyUInt16TryParse("1,23;45.0", NumberStyles.Any, distinctNFI, 12345, true);
passed &= VerifyUInt16TryParse("$1,23;45.0", NumberStyles.Any, distinctNFI, 0, false);
// Should these pass or fail? Current parse behavior is to pass, so they might be
// parse bugs, but they're not tryparse bugs.
passed &= VerifyUInt16Parse("5", NumberStyles.Float, goodNFI, 5);
passed &= VerifyUInt16TryParse("5", NumberStyles.Float, goodNFI, 5, true);
passed &= VerifyUInt16Parse("5", NumberStyles.AllowDecimalPoint, goodNFI, 5);
passed &= VerifyUInt16TryParse("5", NumberStyles.AllowDecimalPoint, goodNFI, 5, true);
// I expect ArgumentException with an ambiguous NFI
passed &= VerifyUInt16ParseException("^42", NumberStyles.Any, ambigNFI, typeof(OverflowException));
passed &= VerifyUInt16TryParse("^42", NumberStyles.Any, ambigNFI, 0, false);
/// END TEST CASES
}
catch (Exception e)
{
TestLibrary.Logging.WriteLine("Unexpected exception!! " + e.ToString());
passed = false;
}
if (passed)
{
TestLibrary.Logging.WriteLine("paSs");
return 100;
}
else
{
TestLibrary.Logging.WriteLine("FAiL");
return 1;
}
}
public static bool VerifyUInt16TryParse(string value, UInt16 expectedResult, bool expectedReturn)
{
if (verbose)
{
TestLibrary.Logging.WriteLine("Test: UInt16.TryParse, Value = '{0}', Expected Result = {1}, Expected Return = {2}",
value, expectedResult, expectedReturn);
}
UInt16 result = 0;
try
{
bool returnValue = UInt16.TryParse(value, out result);
if (returnValue != expectedReturn)
{
TestLibrary.Logging.WriteLine("FAILURE: Value = '{0}', Expected Return: {1}, Actual Return: {2}", value, expectedReturn, returnValue);
return false;
}
if (result != expectedResult)
{
TestLibrary.Logging.WriteLine("FAILURE: Value = '{0}', Expected Return: {1}, Actual Return: {2}", value, expectedResult, result);
return false;
}
return true;
}
catch (Exception ex)
{
TestLibrary.Logging.WriteLine("FAILURE: Unexpected Exception, Value = '{0}', Exception: {1}", value, ex);
return false;
}
}
public static bool VerifyUInt16TryParse(string value, NumberStyles style, IFormatProvider provider, UInt16 expectedResult, bool expectedReturn)
{
if (provider == null) return true;
if (verbose)
{
TestLibrary.Logging.WriteLine("Test: UInt16.TryParse, Value = '{0}', Style = {1}, Provider = {2}, Expected Result = {3}, Expected Return = {4}",
value, style, provider, expectedResult, expectedReturn);
}
UInt16 result = 0;
try
{
bool returnValue = UInt16.TryParse(value, style, provider, out result);
if (returnValue != expectedReturn)
{
TestLibrary.Logging.WriteLine("FAILURE: Value = '{0}', Style = {1}, Provider = {2}, Expected Return = {3}, Actual Return = {4}",
value, style, provider, expectedReturn, returnValue);
return false;
}
if (result != expectedResult)
{
TestLibrary.Logging.WriteLine("FAILURE: Value = '{0}', Expected Return: {1}, Actual Return: {2}", value, expectedResult, result);
return false;
}
return true;
}
catch (Exception ex)
{
TestLibrary.Logging.WriteLine("FAILURE: Unexpected Exception, Value = '{0}', Exception: {1}", value, ex);
return false;
}
}
public static bool VerifyUInt16TryParseException(string value, NumberStyles style, IFormatProvider provider, Type exceptionType)
{
if (provider == null) return true;
if (verbose)
{
TestLibrary.Logging.WriteLine("Test: UInt16.TryParse, Value = '{0}', Style = {1}, Provider = {2}, Expected Exception = {3}",
value, style, provider, exceptionType);
}
try
{
UInt16 result = 0;
Boolean returnValue = UInt16.TryParse(value, style, provider, out result);
TestLibrary.Logging.WriteLine("FAILURE: Value = '{0}', Expected Exception: {1}", value, exceptionType);
return false;
}
catch (Exception ex)
{
if (!ex.GetType().IsAssignableFrom(exceptionType))
{
TestLibrary.Logging.WriteLine("FAILURE: Wrong Exception Type, Value = '{0}', Exception Type: {1} Expected Type: {2}", value, ex.GetType(), exceptionType);
return false;
}
return true;
}
}
public static bool VerifyUInt16Parse(string value, UInt16 expectedResult)
{
if (verbose)
{
TestLibrary.Logging.WriteLine("Test: UInt16.Parse, Value = '{0}', Expected Result, {1}",
value, expectedResult);
}
try
{
UInt16 returnValue = UInt16.Parse(value);
if (returnValue != expectedResult)
{
TestLibrary.Logging.WriteLine("FAILURE: Value = '{0}', Expected Return: {1}, Actual Return: {2}", value, expectedResult, returnValue);
return false;
}
return true;
}
catch (Exception ex)
{
TestLibrary.Logging.WriteLine("FAILURE: Unexpected Exception, Value = '{0}', Exception: {1}", value, ex);
return false;
}
}
public static bool VerifyUInt16Parse(string value, NumberStyles style, IFormatProvider provider, UInt16 expectedResult)
{
if (provider == null) return true;
if (verbose)
{
TestLibrary.Logging.WriteLine("Test: UInt16.Parse, Value = '{0}', Style = {1}, provider = {2}, Expected Result = {3}",
value, style, provider, expectedResult);
}
try
{
UInt16 returnValue = UInt16.Parse(value, style, provider);
if (returnValue != expectedResult)
{
TestLibrary.Logging.WriteLine("FAILURE: Value = '{0}', Expected Return: {1}, Actual Return: {2}", value, expectedResult, returnValue);
return false;
}
return true;
}
catch (Exception ex)
{
TestLibrary.Logging.WriteLine("FAILURE: Unexpected Exception, Value = '{0}', Exception: {1}", value, ex);
return false;
}
}
public static bool VerifyUInt16ParseException(string value, Type exceptionType)
{
if (verbose)
{
TestLibrary.Logging.WriteLine("Test: UInt16.Parse, Value = '{0}', Expected Exception, {1}",
value, exceptionType);
}
try
{
UInt16 returnValue = UInt16.Parse(value);
TestLibrary.Logging.WriteLine("FAILURE: Value = '{0}', Expected Exception: {1}", value, exceptionType);
return false;
}
catch (Exception ex)
{
if (!ex.GetType().IsAssignableFrom(exceptionType))
{
TestLibrary.Logging.WriteLine("FAILURE: Wrong Exception Type, Value = '{0}', Exception Type: {1} Expected Type: {2}", value, ex.GetType(), exceptionType);
return false;
}
return true;
}
}
public static bool VerifyUInt16ParseException(string value, NumberStyles style, Type exceptionType)
{
if (verbose)
{
TestLibrary.Logging.WriteLine("Test: UInt16.Parse, Value = '{0}', Style = {1}, Expected Exception = {3}",
value, style, exceptionType);
}
try
{
UInt16 returnValue = UInt16.Parse(value, style);
TestLibrary.Logging.WriteLine("FAILURE: Value = '{0}', Expected Exception: {1}", value, exceptionType);
return false;
}
catch (Exception ex)
{
if (!ex.GetType().IsAssignableFrom(exceptionType))
{
TestLibrary.Logging.WriteLine("FAILURE: Wrong Exception Type, Value = '{0}', Exception Type: {1} Expected Type: {2}", value, ex.GetType(), exceptionType);
return false;
}
return true;
}
}
public static bool VerifyUInt16ParseException(string value, NumberStyles style, IFormatProvider provider, Type exceptionType)
{
if (provider == null) return true;
if (verbose)
{
TestLibrary.Logging.WriteLine("Test: UInt16.Parse, Value = '{0}', Style = {1}, Provider = {2}, Expected Exception = {3}",
value, style, provider, exceptionType);
}
try
{
UInt16 returnValue = UInt16.Parse(value, style, provider);
TestLibrary.Logging.WriteLine("FAILURE: Value = '{0}', Expected Exception: {1}", value, exceptionType);
return false;
}
catch (Exception ex)
{
if (!ex.GetType().IsAssignableFrom(exceptionType))
{
TestLibrary.Logging.WriteLine("FAILURE: Wrong Exception Type, Value = '{0}', Exception Type: {1} Expected Type: {2}", value, ex.GetType(), exceptionType);
return false;
}
return true;
}
}
}
| |
// ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
/*============================================================
**
** Class: Int32
**
**
** Purpose: A representation of a 32 bit 2's complement
** integer.
**
**
===========================================================*/
namespace System {
using System;
using System.Globalization;
///#if GENERICS_WORK
/// using System.Numerics;
///#endif
using System.Runtime;
using System.Runtime.InteropServices;
using System.Diagnostics.Contracts;
[Serializable]
[System.Runtime.InteropServices.StructLayout(LayoutKind.Sequential)]
[System.Runtime.InteropServices.ComVisible(true)]
#if GENERICS_WORK
public struct Int32 : IComparable, IFormattable, IConvertible
, IComparable<Int32>, IEquatable<Int32>
/// , IArithmetic<Int32>
#else
public struct Int32 : IComparable, IFormattable, IConvertible
#endif
{
internal int m_value;
public const int MaxValue = 0x7fffffff;
public const int MinValue = unchecked((int)0x80000000);
// 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 Int32, this method throws an ArgumentException.
//
public int CompareTo(Object value) {
if (value == null) {
return 1;
}
if (value is Int32) {
// Need to use compare because subtraction will wrap
// to positive for very large neg numbers, etc.
int i = (int)value;
if (m_value < i) return -1;
if (m_value > i) return 1;
return 0;
}
throw new ArgumentException (Environment.GetResourceString("Arg_MustBeInt32"));
}
#if !FEATURE_CORECLR
[TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries")]
#endif
public int CompareTo(int value) {
// Need to use compare because subtraction will wrap
// to positive for very large neg numbers, etc.
if (m_value < value) return -1;
if (m_value > value) return 1;
return 0;
}
#if !FEATURE_CORECLR
[TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries")]
#endif
public override bool Equals(Object obj) {
if (!(obj is Int32)) {
return false;
}
return m_value == ((Int32)obj).m_value;
}
#if !FEATURE_CORECLR
[TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries")]
#endif
public bool Equals(Int32 obj)
{
return m_value == obj;
}
// The absolute value of the int contained.
#if !FEATURE_CORECLR
[TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries")]
#endif
public override int GetHashCode() {
return m_value;
}
[System.Security.SecuritySafeCritical] // auto-generated
#if !FEATURE_CORECLR
[TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries")]
#endif
[Pure]
public override String ToString() {
Contract.Ensures(Contract.Result<String>() != null);
return Number.FormatInt32(m_value, null, NumberFormatInfo.CurrentInfo);
}
[System.Security.SecuritySafeCritical] // auto-generated
#if !FEATURE_CORECLR
[TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries")]
#endif
[Pure]
public String ToString(String format) {
Contract.Ensures(Contract.Result<String>() != null);
return Number.FormatInt32(m_value, format, NumberFormatInfo.CurrentInfo);
}
[System.Security.SecuritySafeCritical] // auto-generated
#if !FEATURE_CORECLR
[TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries")]
#endif
[Pure]
public String ToString(IFormatProvider provider) {
Contract.Ensures(Contract.Result<String>() != null);
return Number.FormatInt32(m_value, null, NumberFormatInfo.GetInstance(provider));
}
[Pure]
[System.Security.SecuritySafeCritical] // auto-generated
public String ToString(String format, IFormatProvider provider) {
Contract.Ensures(Contract.Result<String>() != null);
return Number.FormatInt32(m_value, format, NumberFormatInfo.GetInstance(provider));
}
[Pure]
public static int Parse(String s) {
return Number.ParseInt32(s, NumberStyles.Integer, NumberFormatInfo.CurrentInfo);
}
[Pure]
public static int Parse(String s, NumberStyles style) {
NumberFormatInfo.ValidateParseStyleInteger(style);
return Number.ParseInt32(s, style, NumberFormatInfo.CurrentInfo);
}
// Parses an integer from a String in the given style. If
// a NumberFormatInfo isn't specified, the current culture's
// NumberFormatInfo is assumed.
//
#if !FEATURE_CORECLR
[TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries")]
#endif
[Pure]
public static int Parse(String s, IFormatProvider provider) {
return Number.ParseInt32(s, NumberStyles.Integer, NumberFormatInfo.GetInstance(provider));
}
// Parses an integer from a String in the given style. If
// a NumberFormatInfo isn't specified, the current culture's
// NumberFormatInfo is assumed.
//
#if !FEATURE_CORECLR
[TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries")]
#endif
[Pure]
public static int Parse(String s, NumberStyles style, IFormatProvider provider) {
NumberFormatInfo.ValidateParseStyleInteger(style);
return Number.ParseInt32(s, style, NumberFormatInfo.GetInstance(provider));
}
// Parses an integer from a String. Returns false rather
// than throwing exceptin if input is invalid
//
[Pure]
public static bool TryParse(String s, out Int32 result) {
return Number.TryParseInt32(s, NumberStyles.Integer, NumberFormatInfo.CurrentInfo, out result);
}
// Parses an integer from a String in the given style. Returns false rather
// than throwing exceptin if input is invalid
//
#if !FEATURE_CORECLR
[TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries")]
#endif
[Pure]
public static bool TryParse(String s, NumberStyles style, IFormatProvider provider, out Int32 result) {
NumberFormatInfo.ValidateParseStyleInteger(style);
return Number.TryParseInt32(s, style, NumberFormatInfo.GetInstance(provider), out result);
}
//
// IConvertible implementation
//
#if !FEATURE_CORECLR
[TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries")]
#endif
[Pure]
public TypeCode GetTypeCode() {
return TypeCode.Int32;
}
/// <internalonly/>
bool IConvertible.ToBoolean(IFormatProvider provider) {
return Convert.ToBoolean(m_value);
}
/// <internalonly/>
char IConvertible.ToChar(IFormatProvider provider) {
return Convert.ToChar(m_value);
}
/// <internalonly/>
sbyte IConvertible.ToSByte(IFormatProvider provider) {
return Convert.ToSByte(m_value);
}
/// <internalonly/>
byte IConvertible.ToByte(IFormatProvider provider) {
return Convert.ToByte(m_value);
}
/// <internalonly/>
short IConvertible.ToInt16(IFormatProvider provider) {
return Convert.ToInt16(m_value);
}
/// <internalonly/>
ushort IConvertible.ToUInt16(IFormatProvider provider) {
return Convert.ToUInt16(m_value);
}
/// <internalonly/>
#if !FEATURE_CORECLR
[TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries")]
#endif
int IConvertible.ToInt32(IFormatProvider provider) {
return m_value;
}
/// <internalonly/>
uint IConvertible.ToUInt32(IFormatProvider provider) {
return Convert.ToUInt32(m_value);
}
/// <internalonly/>
#if !FEATURE_CORECLR
[TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries")]
#endif
long IConvertible.ToInt64(IFormatProvider provider) {
return Convert.ToInt64(m_value);
}
/// <internalonly/>
ulong IConvertible.ToUInt64(IFormatProvider provider) {
return Convert.ToUInt64(m_value);
}
/// <internalonly/>
float IConvertible.ToSingle(IFormatProvider provider) {
return Convert.ToSingle(m_value);
}
/// <internalonly/>
double IConvertible.ToDouble(IFormatProvider provider) {
return Convert.ToDouble(m_value);
}
/// <internalonly/>
Decimal IConvertible.ToDecimal(IFormatProvider provider) {
return Convert.ToDecimal(m_value);
}
/// <internalonly/>
DateTime IConvertible.ToDateTime(IFormatProvider provider) {
throw new InvalidCastException(Environment.GetResourceString("InvalidCast_FromTo", "Int32", "DateTime"));
}
/// <internalonly/>
Object IConvertible.ToType(Type type, IFormatProvider provider) {
return Convert.DefaultToType((IConvertible)this, type, provider);
}
///#if GENERICS_WORK
/// //
/// // IArithmetic<Int32> implementation
/// //
///
/// /// <internalonly/>
/// Int32 IArithmetic<Int32>.AbsoluteValue(out bool overflowed) {
/// overflowed = (m_value == MinValue); // -m_value overflows
/// return (Int32) (m_value < 0 ? -m_value : m_value);
/// }
///
/// /// <internalonly/>
/// Int32 IArithmetic<Int32>.Negate(out bool overflowed) {
/// overflowed = (m_value == MinValue); // Negate(MinValue) overflows
/// return (Int32) (-m_value);
/// }
///
/// /// <internalonly/>
/// Int32 IArithmetic<Int32>.Sign(out bool overflowed) {
/// overflowed = false;
/// return (m_value >= 0 ? (m_value == 0 ? 0 : 1) : -1);
/// }
///
/// /// <internalonly/>
/// Int32 IArithmetic<Int32>.Add(Int32 addend, out bool overflowed) {
/// long l = ((long)m_value) + addend;
/// overflowed = (l > MaxValue || l < MinValue);
/// return (Int32) l;
/// }
///
/// /// <internalonly/>
/// Int32 IArithmetic<Int32>.Subtract(Int32 subtrahend, out bool overflowed) {
/// long l = ((long)m_value) - subtrahend;
/// overflowed = (l > MaxValue || l < MinValue);
/// return (Int32) l;
/// }
///
/// /// <internalonly/>
/// Int32 IArithmetic<Int32>.Multiply(Int32 multiplier, out bool overflowed) {
/// long l = ((long)m_value) * multiplier;
/// overflowed = (l > MaxValue || l < MinValue);
/// return (Int32) l;
/// }
///
///
/// /// <internalonly/>
/// Int32 IArithmetic<Int32>.Divide(Int32 divisor, out bool overflowed) {
/// // signed integer division can overflow. Consider the following
/// // 8-bit case: -128/-1 = 128.
/// // 128 won't fit into a signed 8-bit integer, instead you will end up
/// // with -128.
/// //
/// // Because of this corner case, we must check if the numerator
/// // is MinValue and if the denominator is -1.
///
/// overflowed = (divisor == -1 && m_value == MinValue);
///
/// if (overflowed) {
/// // we special case (MinValue / (-1)) for Int32 and Int64 as
/// // unchecked still throws OverflowException when variables
/// // are used instead of constants
/// return MinValue;
/// }
/// else {
/// return unchecked(m_value / divisor);
/// }
/// }
///
/// /// <internalonly/>
/// Int32 IArithmetic<Int32>.DivideRemainder(Int32 divisor, out Int32 remainder, out bool overflowed) {
/// overflowed = (divisor == -1 && m_value == MinValue);
///
/// if (overflowed) {
/// // we special case (MinValue / (-1)) for Int32 and Int64 as
/// // unchecked still throws OverflowException when variables
/// // are used instead of constants
/// remainder = 0;
/// return MinValue;
/// }
/// else {
/// remainder = (m_value % divisor);
/// return unchecked(m_value / divisor);
/// }
/// }
///
/// /// <internalonly/>
/// Int32 IArithmetic<Int32>.Remainder(Int32 divisor, out bool overflowed) {
/// overflowed = false;
///
/// if (divisor == -1 && m_value == MinValue) {
/// // we special case (MinValue % (-1)) for Int32 and Int64 as
/// // unchecked still throws OverflowException when variables
/// // are used instead of constants
/// return 0;
/// }
/// else {
/// return (m_value % divisor);
/// }
/// }
///
/// /// <internalonly/>
/// ArithmeticDescriptor<Int32> IArithmetic<Int32>.GetDescriptor() {
/// if (s_descriptor == null) {
/// s_descriptor = new Int32ArithmeticDescriptor( ArithmeticCapabilities.One
/// | ArithmeticCapabilities.Zero
/// | ArithmeticCapabilities.MaxValue
/// | ArithmeticCapabilities.MinValue);
/// }
/// return s_descriptor;
/// }
///
/// private static Int32ArithmeticDescriptor s_descriptor;
///
/// class Int32ArithmeticDescriptor : ArithmeticDescriptor<Int32> {
/// public Int32ArithmeticDescriptor(ArithmeticCapabilities capabilities) : base(capabilities) {}
///
/// public override Int32 One {
/// get {
/// return (Int32) 1;
/// }
/// }
///
/// public override Int32 Zero {
/// get {
/// return (Int32) 0;
/// }
/// }
///
/// public override Int32 MinValue {
/// get {
/// return Int32.MinValue;
/// }
/// }
///
/// public override Int32 MaxValue {
/// get {
/// return Int32.MaxValue;
/// }
/// }
/// }
///#endif // #if GENERICS_WORK
}
}
| |
/*
MIT License
Copyright (c) 2017 Saied Zarrinmehr
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SpatialAnalysis.Geometry;
namespace SpatialAnalysis.CellularEnvironment
{
/// <summary>
/// Represents the coordinates of a cell in a cellular floor
/// </summary>
public class Index
{
public static readonly Index Right = new Index(1, 0);
public static readonly Index Left = new Index(-1, 0);
public static readonly Index Up = new Index(0, 1);
public static readonly Index Down = new Index(0, -1);
public static readonly Index DownRight = new Index(-1, 1);
public static readonly Index DownLeft = new Index(-1, -1);
public static readonly Index UpRight = new Index(1, 1);
public static readonly Index UpLeft = new Index(1, -1);
/// <summary>
/// All surrounding neighbors relative indices
/// </summary>
public static readonly Index[] Neighbors = new Index[]
{
Index.Right,
Index.UpRight,
Index.Up,
Index.UpLeft,
Index.Left,
Index.DownLeft,
Index.Down,
Index.DownRight,
};
/// <summary>
/// All surrounding neighbors relative indices at top, buttom, right and left
/// </summary>
public static readonly HashSet<Index> CrossNeighbors = new HashSet<Index>
{
Index.Up,
Index.Down,
Index.Right,
Index.Left
};
/// <summary>
/// The width coordinate of a cell
/// </summary>
public int I { get; set; }
/// <summary>
/// the height coordinates of a cell
/// </summary>
public int J { get; set; }
/// <summary>
/// Creates a index based on its width and height coordinates
/// </summary>
/// <param name="i">Width coordinate</param>
/// <param name="j">Height coordinate</param>
public Index(int i, int j)
{
this.I = i;
this.J = j;
}
public override int GetHashCode()
{
int hash = 7;
hash = 71 * hash + this.I.GetHashCode();
hash = 71 * hash + this.J.GetHashCode();
return hash;
}
public override bool Equals(object obj)
{
Index index = obj as Index;
if (index == null)
{
return false;
}
else
{
return index.I == this.I && index.J == this.J;
}
}
public override string ToString()
{
//return string.Format("I: {0}; J: {1}", this.I.ToString(), this.J.ToString());
return string.Format("[{0}, {1}]", this.I.ToString(), this.J.ToString());
}
public static Index operator +(Index A, Index B)
{
return new Index(A.I + B.I, A.J + B.J);
}
public static Index operator -(Index A, Index B)
{
return new Index(A.I - B.I, A.J - B.J);
}
public static bool operator ==(Index A, Index B)
{
if (Object.ReferenceEquals(A, B))
{
return true;
}
if ((object)A == null || (object)B == null)
{
return false;
}
return A.I == B.I && A.J == B.J;
}
public static bool operator !=(Index A, Index B)
{
return !(A == B);
}
public static Index operator *(Index A, int Integer)
{
return new Index(Integer * A.I, Integer * A.J);
}
public static Index operator *(int Integer, Index A)
{
return new Index(Integer * A.I, Integer * A.J);
}
/// <summary>
/// Creates a deep copy of the index
/// </summary>
/// <returns>A new index</returns>
public Index Copy()
{
return new Index(this.I, this.J);
}
/// <summary>
/// Finds the collection of indices that are not aligned with the origin
/// </summary>
/// <param name="range">range of neighborhood</param>
/// <returns>a collection of indices</returns>
internal static HashSet<Index> GetPotentialFieldNeighborhood(int range)
{
HashSet<Index> set = new HashSet<Index>(new DirectionComparer());
for (int i = 0; i <= range; i++)
{
for (int j = 0; j <= range; j++)
{
if (!(i == 0 && j == 0))
{
set.Add(new Index(i, j));
}
}
}
HashSet<Index> indices = new HashSet<Index>(set);
foreach (Index index in set)
{
var second = index.Copy();
second.I *= -1;
indices.Add(second);
var third = index.Copy();
third.I *= -1;
third.J *= -1;
indices.Add(third);
var fourth = index.Copy();
fourth.J *= -1;
indices.Add(fourth);
}
return indices;
}
}
/// <summary>
/// Compares two indexes with each other for equality test.
/// </summary>
/// <seealso cref="System.Collections.Generic.IEqualityComparer{SpatialAnalysis.CellularEnvironment.Index}" />
class IndexComparer : IEqualityComparer<Index>
{
/// <summary>
/// Determines whether the specified objects are equal.
/// </summary>
/// <param name="x">The first object of type <paramref name="T" /> to compare.</param>
/// <param name="y">The second object of type <paramref name="T" /> to compare.</param>
/// <returns>true if the specified objects are equal; otherwise, false.</returns>
public bool Equals(Index x, Index y)
{
return x.I == y.I && x.J == y.J;
}
/// <summary>
/// Returns a hash code for this instance.
/// </summary>
/// <param name="obj">The <see cref="T:System.Object" /> for which a hash code is to be returned.</param>
/// <returns>A hash code for this instance, suitable for use in hashing algorithms and data structures like a hash table.</returns>
public int GetHashCode(Index obj)
{
return obj.GetHashCode();
}
}
/// <summary>
/// Includes a logic for index equality that uses the proportion of the I and J for equality test.
/// </summary>
/// <seealso cref="System.Collections.Generic.IEqualityComparer{SpatialAnalysis.CellularEnvironment.Index}" />
class DirectionComparer : IEqualityComparer<Index>
{
/// <summary>
/// Determines whether the specified objects are equal.
/// </summary>
/// <param name="x">The first object of type <paramref name="T" /> to compare.</param>
/// <param name="y">The second object of type <paramref name="T" /> to compare.</param>
/// <returns>true if the specified objects are equal; otherwise, false.</returns>
public bool Equals(Index x, Index y)
{
double direction1 = this.DirectionFactor(x);
double direction2 = this.DirectionFactor(y);
bool result = true;
if (direction1 != direction2)
{
result = false;
}
else
{
if (!(Math.Sign(x.I) == Math.Sign(y.I) && Math.Sign(x.J) == Math.Sign(y.J)))
{
return false;
}
}
return result;
}
/// <summary>
/// Returns a hash code for this instance.
/// </summary>
/// <param name="obj">The <see cref="T:System.Object" /> for which a hash code is to be returned.</param>
/// <returns>A hash code for this instance, suitable for use in hashing algorithms and data structures like a hash table.</returns>
public int GetHashCode(Index obj)
{
return this.DirectionFactor(obj).GetHashCode();
}
/// <summary>
/// Returns the direction factor
/// </summary>
/// <param name="index">The index.</param>
/// <returns>System.Double.</returns>
public double DirectionFactor(Index index)
{
double i = (double)index.I;
double sineSquared = i * i / (index.I * index.I + index.J * index.J);
return sineSquared;
}
}
}
| |
using System.Collections.Generic;
using Pathfinding.Serialization;
using UnityEngine;
namespace Pathfinding {
/** Base class for GridNode and LevelGridNode */
public abstract class GridNodeBase : GraphNode {
protected GridNodeBase (AstarPath astar) : base (astar) {
}
protected int nodeInGridIndex;
/** The index of the node in the grid.
* This is x + z*graph.width (+ y*graph.width*graph.depth if this is a LayerGridGraph)
* So you can get the X and Z indices using
* \code
* int index = node.NodeInGridIndex;
* int x = index % graph.width;
* int z = index / graph.width;
* // where graph is GridNode.GetGridGraph (node.graphIndex), i.e the graph the nodes are contained in.
* \endcode
*/
public int NodeInGridIndex { get { return nodeInGridIndex;} set { nodeInGridIndex = value; }}
}
public class GridNode : GridNodeBase {
public GridNode (AstarPath astar) : base (astar) {
}
private static GridGraph[] _gridGraphs = new GridGraph[0];
public static GridGraph GetGridGraph (uint graphIndex) { return _gridGraphs[(int)graphIndex]; }
public GraphNode[] connections;
public uint[] connectionCosts;
public static void SetGridGraph (int graphIndex, GridGraph graph) {
if (_gridGraphs.Length <= graphIndex) {
var gg = new GridGraph[graphIndex+1];
for (int i=0;i<_gridGraphs.Length;i++) gg[i] = _gridGraphs[i];
_gridGraphs = gg;
}
_gridGraphs[graphIndex] = graph;
}
protected ushort gridFlags;
/** Internal use only */
internal ushort InternalGridFlags {
get { return gridFlags; }
set { gridFlags = value; }
}
const int GridFlagsConnectionOffset = 0;
const int GridFlagsConnectionBit0 = 1 << GridFlagsConnectionOffset;
const int GridFlagsConnectionMask = 0xFF << GridFlagsConnectionOffset;
const int GridFlagsWalkableErosionOffset = 8;
const int GridFlagsWalkableErosionMask = 1 << GridFlagsWalkableErosionOffset;
const int GridFlagsWalkableTmpOffset = 9;
const int GridFlagsWalkableTmpMask = 1 << GridFlagsWalkableTmpOffset;
const int GridFlagsEdgeNodeOffset = 10;
const int GridFlagsEdgeNodeMask = 1 << GridFlagsEdgeNodeOffset;
/** Returns true if the node has a connection in the specified direction.
* The dir parameter corresponds to directions in the grid as:
\code
[0] = -Y
[1] = +X
[2] = +Y
[3] = -X
[4] = -Y+X
[5] = +Y+X
[6] = +Y-X
[7] = -Y-X
\endcode
* \see SetConnectionInternal
*/
public bool GetConnectionInternal (int dir) {
return (gridFlags >> dir & GridFlagsConnectionBit0) != 0;
}
/** Enables or disables a connection in a specified direction on the graph.
* \see GetConnectionInternal
*/
public void SetConnectionInternal (int dir, bool value) {
unchecked { gridFlags = (ushort)(gridFlags & ~((ushort)1 << GridFlagsConnectionOffset << dir) | (value ? (ushort)1 : (ushort)0) << GridFlagsConnectionOffset << dir); }
}
/** Sets the state of all grid connections.
* \param connections a bitmask of the connections (bit 0 is the first connection, etc.).
*
* \see SetConnectionInternal
*/
public void SetAllConnectionInternal (int connections) {
unchecked { gridFlags = (ushort)((gridFlags & ~GridFlagsConnectionMask) | (connections << GridFlagsConnectionOffset)); }
}
/** Disables all grid connections from this node.
* \note Other nodes might still be able to get to this node.
* Therefore it is recommended to also disable the relevant connections on adjacent nodes.
*/
public void ResetConnectionsInternal () {
unchecked {
gridFlags = (ushort)(gridFlags & ~GridFlagsConnectionMask);
}
}
public bool EdgeNode {
get {
return (gridFlags & GridFlagsEdgeNodeMask) != 0;
}
set {
unchecked { gridFlags = (ushort)(gridFlags & ~GridFlagsEdgeNodeMask | (value ? GridFlagsEdgeNodeMask : 0)); }
}
}
/** Stores walkability before erosion is applied.
* Used by graph updating.
*/
public bool WalkableErosion {
get {
return (gridFlags & GridFlagsWalkableErosionMask) != 0;
}
set {
unchecked { gridFlags = (ushort)(gridFlags & ~GridFlagsWalkableErosionMask | (value ? (ushort)GridFlagsWalkableErosionMask : (ushort)0)); }
}
}
/** Temporary variable used by graph updating */
public bool TmpWalkable {
get {
return (gridFlags & GridFlagsWalkableTmpMask) != 0;
}
set {
unchecked { gridFlags = (ushort)(gridFlags & ~GridFlagsWalkableTmpMask | (value ? (ushort)GridFlagsWalkableTmpMask : (ushort)0)); }
}
}
public override void ClearConnections (bool alsoReverse) {
if (alsoReverse) {
GridGraph gg = GetGridGraph (GraphIndex);
for (int i=0;i<8;i++) {
GridNode other = gg.GetNodeConnection (this,i);
if (other != null) {
//Remove reverse connection
other.SetConnectionInternal(i < 4 ? ((i + 2) % 4) : (((5-2) % 4) + 4),false);
}
}
}
ResetConnectionsInternal ();
if ( alsoReverse ) {
if ( connections != null ) for (int i=0;i<connections.Length;i++) connections[i].RemoveConnection ( this );
}
connections = null;
connectionCosts = null;
}
public override void GetConnections (GraphNodeDelegate del)
{
GridGraph gg = GetGridGraph (GraphIndex);
int[] neighbourOffsets = gg.neighbourOffsets;
GridNode[] nodes = gg.nodes;
for (int i=0;i<8;i++) {
if (GetConnectionInternal(i)) {
GridNode other = nodes[nodeInGridIndex + neighbourOffsets[i]];
if (other != null) del (other);
}
}
if ( connections != null ) for (int i=0;i<connections.Length;i++) del(connections[i]);
}
public Vector3 ClosestPointOnNode (Vector3 p) {
var gg = GetGridGraph(GraphIndex);
// Convert to graph space
p = gg.inverseMatrix.MultiplyPoint3x4(p);
// Nodes are offset 0.5 graph space nodes
float xf = position.x-0.5F;
float zf = position.z-0.5f;
// Calculate graph position of this node
int x = nodeInGridIndex % gg.width;
int z = nodeInGridIndex / gg.width;
// Handle the y coordinate separately
float y = gg.inverseMatrix.MultiplyPoint3x4((Vector3)p).y;
var closestInGraphSpace = new Vector3(Mathf.Clamp(xf,x-0.5f,x+0.5f)+0.5f, y, Mathf.Clamp(zf,z-0.5f,z+0.5f)+0.5f);
// Convert to world space
return gg.matrix.MultiplyPoint3x4 (closestInGraphSpace);
}
public override bool GetPortal (GraphNode other, List<Vector3> left, List<Vector3> right, bool backwards)
{
if (backwards) return true;
GridGraph gg = GetGridGraph (GraphIndex);
int[] neighbourOffsets = gg.neighbourOffsets;
GridNode[] nodes = gg.nodes;
for (int i=0;i<4;i++) {
if (GetConnectionInternal(i) && other == nodes[nodeInGridIndex + neighbourOffsets[i]]) {
Vector3 middle = ((Vector3)(position + other.position))*0.5f;
Vector3 cross = Vector3.Cross (gg.collision.up, (Vector3)(other.position-position));
cross.Normalize();
cross *= gg.nodeSize*0.5f;
left.Add (middle - cross);
right.Add (middle + cross);
return true;
}
}
for (int i=4;i<8;i++) {
if (GetConnectionInternal(i) && other == nodes[nodeInGridIndex + neighbourOffsets[i]]) {
bool rClear = false;
bool lClear = false;
if (GetConnectionInternal(i-4)) {
GridNode n2 = nodes[nodeInGridIndex + neighbourOffsets[i-4]];
if (n2.Walkable && n2.GetConnectionInternal((i-4+1)%4)) {
rClear = true;
}
}
if (GetConnectionInternal((i-4+1)%4)) {
GridNode n2 = nodes[nodeInGridIndex + neighbourOffsets[(i-4+1)%4]];
if (n2.Walkable && n2.GetConnectionInternal(i-4)) {
lClear = true;
}
}
Vector3 middle = ((Vector3)(position + other.position))*0.5f;
Vector3 cross = Vector3.Cross (gg.collision.up, (Vector3)(other.position-position));
cross.Normalize();
cross *= gg.nodeSize*1.4142f;
left.Add (middle - (lClear ? cross : Vector3.zero));
right.Add (middle + (rClear ? cross : Vector3.zero));
return true;
}
}
return false;
}
public override void FloodFill (Stack<GraphNode> stack, uint region) {
GridGraph gg = GetGridGraph (GraphIndex);
int[] neighbourOffsets = gg.neighbourOffsets;
GridNode[] nodes = gg.nodes;
for (int i=0;i<8;i++) {
if (GetConnectionInternal(i)) {
GridNode other = nodes[nodeInGridIndex + neighbourOffsets[i]];
if (other != null && other.Area != region) {
other.Area = region;
stack.Push (other);
}
}
}
if ( connections != null ) for (int i=0;i<connections.Length;i++) {
GraphNode other = connections[i];
if (other.Area != region) {
other.Area = region;
stack.Push (other);
}
}
}
/** Add a connection from this node to the specified node.
* If the connection already exists, the cost will simply be updated and
* no extra connection added.
*
* \note Only adds a one-way connection. Consider calling the same function on the other node
* to get a two-way connection.
*/
public override void AddConnection (GraphNode node, uint cost) {
if (connections != null) {
for (int i=0;i<connections.Length;i++) {
if (connections[i] == node) {
connectionCosts[i] = cost;
return;
}
}
}
int connLength = connections != null ? connections.Length : 0;
var newconns = new GraphNode[connLength+1];
var newconncosts = new uint[connLength+1];
for (int i=0;i<connLength;i++) {
newconns[i] = connections[i];
newconncosts[i] = connectionCosts[i];
}
newconns[connLength] = node;
newconncosts[connLength] = cost;
connections = newconns;
connectionCosts = newconncosts;
}
/** Removes any connection from this node to the specified node.
* If no such connection exists, nothing will be done.
*
* \note This only removes the connection from this node to the other node.
* You may want to call the same function on the other node to remove its eventual connection
* to this node.
*/
public override void RemoveConnection (GraphNode node) {
if (connections == null) return;
for (int i=0;i<connections.Length;i++) {
if (connections[i] == node) {
int connLength = connections.Length;
var newconns = new GraphNode[connLength-1];
var newconncosts = new uint[connLength-1];
for (int j=0;j<i;j++) {
newconns[j] = connections[j];
newconncosts[j] = connectionCosts[j];
}
for (int j=i+1;j<connLength;j++) {
newconns[j-1] = connections[j];
newconncosts[j-1] = connectionCosts[j];
}
connections = newconns;
connectionCosts = newconncosts;
return;
}
}
}
public override void UpdateRecursiveG (Path path, PathNode pathNode, PathHandler handler) {
GridGraph gg = GetGridGraph (GraphIndex);
int[] neighbourOffsets = gg.neighbourOffsets;
GridNode[] nodes = gg.nodes;
UpdateG (path,pathNode);
handler.PushNode (pathNode);
ushort pid = handler.PathID;
for (int i=0;i<8;i++) {
if (GetConnectionInternal(i)) {
GridNode other = nodes[nodeInGridIndex + neighbourOffsets[i]];
PathNode otherPN = handler.GetPathNode (other);
if (otherPN.parent == pathNode && otherPN.pathID == pid) other.UpdateRecursiveG (path, otherPN,handler);
}
}
if ( connections != null ) for (int i=0;i<connections.Length;i++) {
GraphNode other = connections[i];
PathNode otherPN = handler.GetPathNode (other);
if (otherPN.parent == pathNode && otherPN.pathID == pid) other.UpdateRecursiveG (path, otherPN,handler);
}
}
public override void Open (Path path, PathNode pathNode, PathHandler handler) {
GridGraph gg = GetGridGraph (GraphIndex);
ushort pid = handler.PathID;
{
int[] neighbourOffsets = gg.neighbourOffsets;
uint[] neighbourCosts = gg.neighbourCosts;
GridNode[] nodes = gg.nodes;
for (int i=0;i<8;i++) {
if (GetConnectionInternal(i)) {
GridNode other = nodes[nodeInGridIndex + neighbourOffsets[i]];
if (!path.CanTraverse (other)) continue;
PathNode otherPN = handler.GetPathNode (other);
uint tmpCost = neighbourCosts[i];
if (otherPN.pathID != pid) {
otherPN.parent = pathNode;
otherPN.pathID = pid;
otherPN.cost = tmpCost;
otherPN.H = path.CalculateHScore (other);
other.UpdateG (path, otherPN);
//Debug.Log ("G " + otherPN.G + " F " + otherPN.F);
handler.PushNode (otherPN);
//Debug.DrawRay ((Vector3)otherPN.node.Position, Vector3.up,Color.blue);
} else {
// Sorry for the huge number of #ifs
//If not we can test if the path from the current node to this one is a better one then the one already used
#if ASTAR_NO_TRAVERSAL_COST
if (pathNode.G+tmpCost < otherPN.G)
#else
if (pathNode.G+tmpCost+path.GetTraversalCost(other) < otherPN.G)
#endif
{
//Debug.Log ("Path better from " + NodeIndex + " to " + otherPN.node.NodeIndex + " " + (pathNode.G+tmpCost+path.GetTraversalCost(other)) + " < " + otherPN.G);
otherPN.cost = tmpCost;
otherPN.parent = pathNode;
other.UpdateRecursiveG (path,otherPN, handler);
//Or if the path from this node ("other") to the current ("current") is better
}
#if ASTAR_NO_TRAVERSAL_COST
else if (otherPN.G+tmpCost < pathNode.G)
#else
else if (otherPN.G+tmpCost+path.GetTraversalCost (this) < pathNode.G)
#endif
{
//Debug.Log ("Path better from " + otherPN.node.NodeIndex + " to " + NodeIndex + " " + (otherPN.G+tmpCost+path.GetTraversalCost (this)) + " < " + pathNode.G);
pathNode.parent = otherPN;
pathNode.cost = tmpCost;
UpdateRecursiveG(path, pathNode, handler);
}
}
}
}
}
if (connections != null) for (int i=0;i<connections.Length;i++) {
GraphNode other = connections[i];
if (!path.CanTraverse (other)) continue;
PathNode otherPN = handler.GetPathNode (other);
uint tmpCost = connectionCosts[i];
if (otherPN.pathID != pid) {
otherPN.parent = pathNode;
otherPN.pathID = pid;
otherPN.cost = tmpCost;
otherPN.H = path.CalculateHScore (other);
other.UpdateG (path, otherPN);
//Debug.Log ("G " + otherPN.G + " F " + otherPN.F);
handler.PushNode (otherPN);
//Debug.DrawRay ((Vector3)otherPN.node.Position, Vector3.up,Color.blue);
} else {
// Sorry for the huge number of #ifs
//If not we can test if the path from the current node to this one is a better one then the one already used
#if ASTAR_NO_TRAVERSAL_COST
if (pathNode.G+tmpCost < otherPN.G)
#else
if (pathNode.G+tmpCost+path.GetTraversalCost(other) < otherPN.G)
#endif
{
//Debug.Log ("Path better from " + NodeIndex + " to " + otherPN.node.NodeIndex + " " + (pathNode.G+tmpCost+path.GetTraversalCost(other)) + " < " + otherPN.G);
otherPN.cost = tmpCost;
otherPN.parent = pathNode;
other.UpdateRecursiveG (path,otherPN, handler);
//Or if the path from this node ("other") to the current ("current") is better
}
#if ASTAR_NO_TRAVERSAL_COST
else if (otherPN.G+tmpCost < pathNode.G && other.ContainsConnection (this))
#else
else if (otherPN.G+tmpCost+path.GetTraversalCost (this) < pathNode.G && other.ContainsConnection (this))
#endif
{
//Debug.Log ("Path better from " + otherPN.node.NodeIndex + " to " + NodeIndex + " " + (otherPN.G+tmpCost+path.GetTraversalCost (this)) + " < " + pathNode.G);
pathNode.parent = otherPN;
pathNode.cost = tmpCost;
UpdateRecursiveG(path, pathNode, handler);
}
}
}
}
public override void SerializeNode (GraphSerializationContext ctx) {
base.SerializeNode (ctx);
ctx.writer.Write (position.x);
ctx.writer.Write (position.y);
ctx.writer.Write (position.z);
ctx.writer.Write (gridFlags);
}
public override void DeserializeNode (GraphSerializationContext ctx)
{
base.DeserializeNode (ctx);
position = new Int3(ctx.reader.ReadInt32(), ctx.reader.ReadInt32(), ctx.reader.ReadInt32());
gridFlags = ctx.reader.ReadUInt16();
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using EncompassRest.Schema;
namespace EncompassRest.Loans
{
/// <summary>
/// Gfe2010Page
/// </summary>
public sealed partial class Gfe2010Page : DirtyExtensibleObject, IIdentifiable
{
private DirtyValue<int?>? _balloonPaymentDueInYears;
private DirtyValue<string?>? _brokerCompensationFwbc;
private DirtyValue<string?>? _brokerCompensationFwsc;
private DirtyValue<decimal?>? _curedGfeTotalTolerance;
private DirtyValue<DateTime?>? _firstArmChangeDate;
private DirtyList<Gfe2010FwbcFwsc>? _gfe2010FwbcFwscs;
private DirtyList<Gfe2010GfeCharge>? _gfe2010GfeCharges;
private DirtyValue<string?>? _gfeRecordingCharges;
private DirtyValue<decimal?>? _gfeTotalTolerance;
private DirtyValue<bool?>? _hasEscrowAccountIndicator;
private DirtyValue<bool?>? _hasEscrowCityPropertyTaxesIndicator;
private DirtyValue<bool?>? _hasEscrowFloodInsurancesIndicator;
private DirtyValue<bool?>? _hasEscrowHomeownerInsurancesIndicator;
private DirtyValue<bool?>? _hasEscrowPropertyTaxesIndicator;
private DirtyValue<bool?>? _hasEscrowUserDefinedIndicator1;
private DirtyValue<bool?>? _hasEscrowUserDefinedIndicator2;
private DirtyValue<bool?>? _hasEscrowUserDefinedIndicator3;
private DirtyValue<bool?>? _hasEscrowUserDefinedIndicator4;
private DirtyValue<decimal?>? _highestArmRate;
private DirtyValue<decimal?>? _hud1GovernmentRecordingCharge;
private DirtyValue<decimal?>? _hud1Pg1SellerPaidClosingCostsAmount;
private DirtyValue<decimal?>? _hud1Pg1TotalSettlementCharges;
private DirtyValue<decimal?>? _hud1Pg2SellerPaidClosingCostsAmount;
private DirtyValue<decimal?>? _hud1Pg2TotalSettlementCharges;
private DirtyValue<decimal?>? _hudTotalTolerance;
private DirtyValue<decimal?>? _hudTotalToleranceIncreasePercent;
private DirtyValue<string?>? _id;
private DirtyValue<decimal?>? _line1101SellerPaidTotal;
private DirtyValue<decimal?>? _line1201SellerPaidTotal;
private DirtyValue<decimal?>? _line1301SellerPaidTotal;
private DirtyValue<decimal?>? _line801BorrowerPaidTotal;
private DirtyValue<decimal?>? _line801SellerPaidTotal;
private DirtyValue<decimal?>? _line802BorrowerPaidTotal;
private DirtyValue<decimal?>? _line803BorrowerPaidTotal;
private DirtyValue<decimal?>? _line803SellerPaidTotal;
private DirtyValue<bool?>? _line818FwbcIndicator;
private DirtyValue<bool?>? _line818FwscIndicator;
private DirtyValue<bool?>? _line819FwbcIndicator;
private DirtyValue<bool?>? _line819FwscIndicator;
private DirtyValue<bool?>? _line820FwbcIndicator;
private DirtyValue<bool?>? _line820FwscIndicator;
private DirtyValue<bool?>? _line821FwbcIndicator;
private DirtyValue<bool?>? _line821FwscIndicator;
private DirtyValue<bool?>? _line822FwbcIndicator;
private DirtyValue<bool?>? _line822FwscIndicator;
private DirtyValue<bool?>? _line823FwbcIndicator;
private DirtyValue<bool?>? _line823FwscIndicator;
private DirtyValue<bool?>? _line824FwbcIndicator;
private DirtyValue<bool?>? _line824FwscIndicator;
private DirtyValue<bool?>? _line825FwbcIndicator;
private DirtyValue<bool?>? _line825FwscIndicator;
private DirtyValue<bool?>? _line826FwbcIndicator;
private DirtyValue<bool?>? _line826FwscIndicator;
private DirtyValue<bool?>? _line827FwbcIndicator;
private DirtyValue<bool?>? _line827FwscIndicator;
private DirtyValue<bool?>? _line828FwbcIndicator;
private DirtyValue<bool?>? _line828FwscIndicator;
private DirtyValue<bool?>? _line829FwbcIndicator;
private DirtyValue<bool?>? _line829FwscIndicator;
private DirtyValue<bool?>? _line830FwbcIndicator;
private DirtyValue<bool?>? _line830FwscIndicator;
private DirtyValue<bool?>? _line831FwbcIndicator;
private DirtyValue<bool?>? _line831FwscIndicator;
private DirtyValue<bool?>? _line832FwbcIndicator;
private DirtyValue<bool?>? _line832FwscIndicator;
private DirtyValue<bool?>? _line833FwbcIndicator;
private DirtyValue<bool?>? _line833FwscIndicator;
private DirtyValue<bool?>? _lineLFwbcIndicator;
private DirtyValue<bool?>? _lineLFwscIndicator;
private DirtyValue<bool?>? _lineMFwbcIndicator;
private DirtyValue<bool?>? _lineMFwscIndicator;
private DirtyValue<bool?>? _lineNFwbcIndicator;
private DirtyValue<bool?>? _lineNFwscIndicator;
private DirtyValue<bool?>? _lineOFwbcIndicator;
private DirtyValue<bool?>? _lineOFwscIndicator;
private DirtyValue<bool?>? _linePFwbcIndicator;
private DirtyValue<bool?>? _linePFwscIndicator;
private DirtyValue<bool?>? _lineQFwbcIndicator;
private DirtyValue<bool?>? _lineQFwscIndicator;
private DirtyValue<bool?>? _lineRFwbcIndicator;
private DirtyValue<bool?>? _lineRFwscIndicator;
private DirtyValue<decimal?>? _lowestArmRate;
private DirtyValue<bool?>? _monthlyAmountIncludeInterestIndicator;
private DirtyValue<bool?>? _monthlyAmountIncludeMiIndicator;
private DirtyValue<bool?>? _monthlyAmountIncludePrincipalIndicator;
private DirtyValue<decimal?>? _monthlyAmountWithEscrow;
private DirtyValue<decimal?>? _monthlyEscrowPayment;
private DirtyValue<decimal?>? _prepaidInterest;
private DirtyValue<decimal?>? _totalToleranceIncreaseAmount;
/// <summary>
/// Years/Months Until Balloon Pymt Due [NEWHUD.X348]
/// </summary>
public int? BalloonPaymentDueInYears { get => _balloonPaymentDueInYears; set => SetField(ref _balloonPaymentDueInYears, value); }
/// <summary>
/// Fees Line Fees Line 801 Broker Compensation Borrower Checked [NEWHUD.X672]
/// </summary>
public string? BrokerCompensationFwbc { get => _brokerCompensationFwbc; set => SetField(ref _brokerCompensationFwbc, value); }
/// <summary>
/// Fees Line Fees Line 801 Broker Compensation Seller Checked [NEWHUD.X673]
/// </summary>
public string? BrokerCompensationFwsc { get => _brokerCompensationFwsc; set => SetField(ref _brokerCompensationFwsc, value); }
/// <summary>
/// Cured Total GFE Tolerance [NEWHUD.CuredX312]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public decimal? CuredGfeTotalTolerance { get => _curedGfeTotalTolerance; set => SetField(ref _curedGfeTotalTolerance, value); }
/// <summary>
/// First ARM Change Date [NEWHUD.X332]
/// </summary>
public DateTime? FirstArmChangeDate { get => _firstArmChangeDate; set => SetField(ref _firstArmChangeDate, value); }
/// <summary>
/// Gfe2010Page Gfe2010FwbcFwscs
/// </summary>
[AllowNull]
public IList<Gfe2010FwbcFwsc> Gfe2010FwbcFwscs { get => GetField(ref _gfe2010FwbcFwscs); set => SetField(ref _gfe2010FwbcFwscs, value); }
/// <summary>
/// Gfe2010Page Gfe2010GfeCharges
/// </summary>
[AllowNull]
public IList<Gfe2010GfeCharge> Gfe2010GfeCharges { get => GetField(ref _gfe2010GfeCharges); set => SetField(ref _gfe2010GfeCharges, value); }
/// <summary>
/// GFE Gov Recording Chrgs [NEWHUD.X295]
/// </summary>
public string? GfeRecordingCharges { get => _gfeRecordingCharges; set => SetField(ref _gfeRecordingCharges, value); }
/// <summary>
/// Total GFE Tolerance [NEWHUD.X312]
/// </summary>
public decimal? GfeTotalTolerance { get => _gfeTotalTolerance; set => SetField(ref _gfeTotalTolerance, value); }
/// <summary>
/// Has Escrow Acct [NEWHUD.X335]
/// </summary>
public bool? HasEscrowAccountIndicator { get => _hasEscrowAccountIndicator; set => SetField(ref _hasEscrowAccountIndicator, value); }
/// <summary>
/// Incl Escrow-City Prop Taxes [NEWHUD.X1726]
/// </summary>
public bool? HasEscrowCityPropertyTaxesIndicator { get => _hasEscrowCityPropertyTaxesIndicator; set => SetField(ref _hasEscrowCityPropertyTaxesIndicator, value); }
/// <summary>
/// Incl Escrow-Flood Ins [NEWHUD.X338]
/// </summary>
public bool? HasEscrowFloodInsurancesIndicator { get => _hasEscrowFloodInsurancesIndicator; set => SetField(ref _hasEscrowFloodInsurancesIndicator, value); }
/// <summary>
/// Incl Escrow-Homeowners Ins [NEWHUD.X339]
/// </summary>
public bool? HasEscrowHomeownerInsurancesIndicator { get => _hasEscrowHomeownerInsurancesIndicator; set => SetField(ref _hasEscrowHomeownerInsurancesIndicator, value); }
/// <summary>
/// Incl Escrow-Prop Taxes [NEWHUD.X337]
/// </summary>
public bool? HasEscrowPropertyTaxesIndicator { get => _hasEscrowPropertyTaxesIndicator; set => SetField(ref _hasEscrowPropertyTaxesIndicator, value); }
/// <summary>
/// Incl Escrow-User Defined 1 [NEWHUD.X340]
/// </summary>
public bool? HasEscrowUserDefinedIndicator1 { get => _hasEscrowUserDefinedIndicator1; set => SetField(ref _hasEscrowUserDefinedIndicator1, value); }
/// <summary>
/// Incl Escrow-User Defined 2 [NEWHUD.X341]
/// </summary>
public bool? HasEscrowUserDefinedIndicator2 { get => _hasEscrowUserDefinedIndicator2; set => SetField(ref _hasEscrowUserDefinedIndicator2, value); }
/// <summary>
/// Incl Escrow-User Defined 3 [NEWHUD.X342]
/// </summary>
public bool? HasEscrowUserDefinedIndicator3 { get => _hasEscrowUserDefinedIndicator3; set => SetField(ref _hasEscrowUserDefinedIndicator3, value); }
/// <summary>
/// New HUD-1 Page 3 Include Escrow Annual Fee [NEWHUD.X343]
/// </summary>
public bool? HasEscrowUserDefinedIndicator4 { get => _hasEscrowUserDefinedIndicator4; set => SetField(ref _hasEscrowUserDefinedIndicator4, value); }
/// <summary>
/// Highest ARM Rate [NEWHUD.X334]
/// </summary>
[LoanFieldProperty(Format = LoanFieldFormat.DECIMAL_3)]
public decimal? HighestArmRate { get => _highestArmRate; set => SetField(ref _highestArmRate, value); }
/// <summary>
/// 10% Tolerance Comp Chart - HUD1 Government Recording Charge [NEWHUD.X336]
/// </summary>
public decimal? Hud1GovernmentRecordingCharge { get => _hud1GovernmentRecordingCharge; set => SetField(ref _hud1GovernmentRecordingCharge, value); }
/// <summary>
/// Seller Total Closing Cost for HUD-1 Pg1 [NEWHUD.X774]
/// </summary>
public decimal? Hud1Pg1SellerPaidClosingCostsAmount { get => _hud1Pg1SellerPaidClosingCostsAmount; set => SetField(ref _hud1Pg1SellerPaidClosingCostsAmount, value); }
/// <summary>
/// Borr Total Closing Cost for HUD-1 Pg1 [NEWHUD.X773]
/// </summary>
public decimal? Hud1Pg1TotalSettlementCharges { get => _hud1Pg1TotalSettlementCharges; set => SetField(ref _hud1Pg1TotalSettlementCharges, value); }
/// <summary>
/// Seller Total Closing Costs [NEWHUD.X278]
/// </summary>
public decimal? Hud1Pg2SellerPaidClosingCostsAmount { get => _hud1Pg2SellerPaidClosingCostsAmount; set => SetField(ref _hud1Pg2SellerPaidClosingCostsAmount, value); }
/// <summary>
/// Borr Total Closing Costs [NEWHUD.X277]
/// </summary>
public decimal? Hud1Pg2TotalSettlementCharges { get => _hud1Pg2TotalSettlementCharges; set => SetField(ref _hud1Pg2TotalSettlementCharges, value); }
/// <summary>
/// Total HUD Tolerance [NEWHUD.X313]
/// </summary>
public decimal? HudTotalTolerance { get => _hudTotalTolerance; set => SetField(ref _hudTotalTolerance, value); }
/// <summary>
/// Total GFE Tolerance Increase % [NEWHUD.X315]
/// </summary>
public decimal? HudTotalToleranceIncreasePercent { get => _hudTotalToleranceIncreasePercent; set => SetField(ref _hudTotalToleranceIncreasePercent, value); }
/// <summary>
/// Gfe2010Page Id
/// </summary>
public string? Id { get => _id; set => SetField(ref _id, value); }
/// <summary>
/// Fees Line 1101 Seller Paid Total [NEWHUD.X798]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public decimal? Line1101SellerPaidTotal { get => _line1101SellerPaidTotal; set => SetField(ref _line1101SellerPaidTotal, value); }
/// <summary>
/// Fees Line 1201 Seller Paid Total [NEWHUD.X799]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public decimal? Line1201SellerPaidTotal { get => _line1201SellerPaidTotal; set => SetField(ref _line1201SellerPaidTotal, value); }
/// <summary>
/// Fees Line 1301 Seller Paid Total [NEWHUD.X800]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public decimal? Line1301SellerPaidTotal { get => _line1301SellerPaidTotal; set => SetField(ref _line1301SellerPaidTotal, value); }
/// <summary>
/// Fees Line 801 Borrower Paid Total [NEWHUD.X795]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public decimal? Line801BorrowerPaidTotal { get => _line801BorrowerPaidTotal; set => SetField(ref _line801BorrowerPaidTotal, value); }
/// <summary>
/// Fees Line 801 Seller Paid Total [NEWHUD.X794]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public decimal? Line801SellerPaidTotal { get => _line801SellerPaidTotal; set => SetField(ref _line801SellerPaidTotal, value); }
/// <summary>
/// Fees Line 802 Borrower Paid Total [NEWHUD.X797]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public decimal? Line802BorrowerPaidTotal { get => _line802BorrowerPaidTotal; set => SetField(ref _line802BorrowerPaidTotal, value); }
/// <summary>
/// Fees Line 803 Borrower Paid Total [NEWHUD.X796]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public decimal? Line803BorrowerPaidTotal { get => _line803BorrowerPaidTotal; set => SetField(ref _line803BorrowerPaidTotal, value); }
/// <summary>
/// Fees Line 803 Seller Paid Total [NEWHUD.X801]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public decimal? Line803SellerPaidTotal { get => _line803SellerPaidTotal; set => SetField(ref _line803SellerPaidTotal, value); }
/// <summary>
/// Fees Line 820 Funding Worksheet Checkbox for Borrower [NEWHUD.X1486]
/// </summary>
public bool? Line818FwbcIndicator { get => _line818FwbcIndicator; set => SetField(ref _line818FwbcIndicator, value); }
/// <summary>
/// Fees Line 820 Funding Worksheet Checkbox for Seller [NEWHUD.X1509]
/// </summary>
public bool? Line818FwscIndicator { get => _line818FwscIndicator; set => SetField(ref _line818FwscIndicator, value); }
/// <summary>
/// Fees Line 821 Funding Worksheet Checkbox for Borrower [NEWHUD.X1487]
/// </summary>
public bool? Line819FwbcIndicator { get => _line819FwbcIndicator; set => SetField(ref _line819FwbcIndicator, value); }
/// <summary>
/// Fees Line 821 Funding Worksheet Checkbox for Seller [NEWHUD.X1510]
/// </summary>
public bool? Line819FwscIndicator { get => _line819FwscIndicator; set => SetField(ref _line819FwscIndicator, value); }
/// <summary>
/// Fees Line 822 Funding Worksheet Checkbox for Borrower [NEWHUD.X1488]
/// </summary>
public bool? Line820FwbcIndicator { get => _line820FwbcIndicator; set => SetField(ref _line820FwbcIndicator, value); }
/// <summary>
/// Fees Line 822 Funding Worksheet Checkbox for Seller [NEWHUD.X1511]
/// </summary>
public bool? Line820FwscIndicator { get => _line820FwscIndicator; set => SetField(ref _line820FwscIndicator, value); }
/// <summary>
/// Fees Line 823 Funding Worksheet Checkbox for Borrower [NEWHUD.X1489]
/// </summary>
public bool? Line821FwbcIndicator { get => _line821FwbcIndicator; set => SetField(ref _line821FwbcIndicator, value); }
/// <summary>
/// Fees Line 823 Funding Worksheet Checkbox for Seller [NEWHUD.X1512]
/// </summary>
public bool? Line821FwscIndicator { get => _line821FwscIndicator; set => SetField(ref _line821FwscIndicator, value); }
/// <summary>
/// Fees Line 824 Funding Worksheet Checkbox for Borrower [NEWHUD.X1490]
/// </summary>
public bool? Line822FwbcIndicator { get => _line822FwbcIndicator; set => SetField(ref _line822FwbcIndicator, value); }
/// <summary>
/// Fees Line 824 Funding Worksheet Checkbox for Seller [NEWHUD.X1513]
/// </summary>
public bool? Line822FwscIndicator { get => _line822FwscIndicator; set => SetField(ref _line822FwscIndicator, value); }
/// <summary>
/// Fees Line 825 Funding Worksheet Checkbox for Borrower [NEWHUD.X1491]
/// </summary>
public bool? Line823FwbcIndicator { get => _line823FwbcIndicator; set => SetField(ref _line823FwbcIndicator, value); }
/// <summary>
/// Fees Line 825 Funding Worksheet Checkbox for Seller [NEWHUD.X1514]
/// </summary>
public bool? Line823FwscIndicator { get => _line823FwscIndicator; set => SetField(ref _line823FwscIndicator, value); }
/// <summary>
/// Fees Line 826 Funding Worksheet Checkbox for Borrower [NEWHUD.X1492]
/// </summary>
public bool? Line824FwbcIndicator { get => _line824FwbcIndicator; set => SetField(ref _line824FwbcIndicator, value); }
/// <summary>
/// Fees Line 826 Funding Worksheet Checkbox for Seller [NEWHUD.X1515]
/// </summary>
public bool? Line824FwscIndicator { get => _line824FwscIndicator; set => SetField(ref _line824FwscIndicator, value); }
/// <summary>
/// Fees Line 827 Funding Worksheet Checkbox for Borrower [NEWHUD.X1493]
/// </summary>
public bool? Line825FwbcIndicator { get => _line825FwbcIndicator; set => SetField(ref _line825FwbcIndicator, value); }
/// <summary>
/// Fees Line 827 Funding Worksheet Checkbox for Seller [NEWHUD.X1516]
/// </summary>
public bool? Line825FwscIndicator { get => _line825FwscIndicator; set => SetField(ref _line825FwscIndicator, value); }
/// <summary>
/// Fees Line 828 Funding Worksheet Checkbox for Borrower [NEWHUD.X1494]
/// </summary>
public bool? Line826FwbcIndicator { get => _line826FwbcIndicator; set => SetField(ref _line826FwbcIndicator, value); }
/// <summary>
/// Fees Line 828 Funding Worksheet Checkbox for Seller [NEWHUD.X1517]
/// </summary>
public bool? Line826FwscIndicator { get => _line826FwscIndicator; set => SetField(ref _line826FwscIndicator, value); }
/// <summary>
/// Fees Line 829 Funding Worksheet Checkbox for Borrower [NEWHUD.X1495]
/// </summary>
public bool? Line827FwbcIndicator { get => _line827FwbcIndicator; set => SetField(ref _line827FwbcIndicator, value); }
/// <summary>
/// Fees Line 829 Funding Worksheet Checkbox for Seller [NEWHUD.X1518]
/// </summary>
public bool? Line827FwscIndicator { get => _line827FwscIndicator; set => SetField(ref _line827FwscIndicator, value); }
/// <summary>
/// Fees Line 830 Funding Worksheet Checkbox for Borrower [NEWHUD.X1496]
/// </summary>
public bool? Line828FwbcIndicator { get => _line828FwbcIndicator; set => SetField(ref _line828FwbcIndicator, value); }
/// <summary>
/// Fees Line 830 Funding Worksheet Checkbox for Seller [NEWHUD.X1519]
/// </summary>
public bool? Line828FwscIndicator { get => _line828FwscIndicator; set => SetField(ref _line828FwscIndicator, value); }
/// <summary>
/// Fees Line 831 Funding Worksheet Checkbox for Borrower [NEWHUD.X1497]
/// </summary>
public bool? Line829FwbcIndicator { get => _line829FwbcIndicator; set => SetField(ref _line829FwbcIndicator, value); }
/// <summary>
/// Fees Line 831 Funding Worksheet Checkbox for Seller [NEWHUD.X1520]
/// </summary>
public bool? Line829FwscIndicator { get => _line829FwscIndicator; set => SetField(ref _line829FwscIndicator, value); }
/// <summary>
/// Fees Line 832 Funding Worksheet Checkbox for Borrower [NEWHUD.X1498]
/// </summary>
public bool? Line830FwbcIndicator { get => _line830FwbcIndicator; set => SetField(ref _line830FwbcIndicator, value); }
/// <summary>
/// Fees Line 832 Funding Worksheet Checkbox for Seller [NEWHUD.X1521]
/// </summary>
public bool? Line830FwscIndicator { get => _line830FwscIndicator; set => SetField(ref _line830FwscIndicator, value); }
/// <summary>
/// Fees Line 833 Funding Worksheet Checkbox for Borrower [NEWHUD.X1499]
/// </summary>
public bool? Line831FwbcIndicator { get => _line831FwbcIndicator; set => SetField(ref _line831FwbcIndicator, value); }
/// <summary>
/// Fees Line 833 Funding Worksheet Checkbox for Seller [NEWHUD.X1522]
/// </summary>
public bool? Line831FwscIndicator { get => _line831FwscIndicator; set => SetField(ref _line831FwscIndicator, value); }
/// <summary>
/// Fees Line 834 Funding Worksheet Checkbox for Borrower [NEWHUD.X1500]
/// </summary>
public bool? Line832FwbcIndicator { get => _line832FwbcIndicator; set => SetField(ref _line832FwbcIndicator, value); }
/// <summary>
/// Fees Line 834 Funding Worksheet Checkbox for Seller [NEWHUD.X1523]
/// </summary>
public bool? Line832FwscIndicator { get => _line832FwscIndicator; set => SetField(ref _line832FwscIndicator, value); }
/// <summary>
/// Fees Line 835 Funding Worksheet Checkbox for Borrower [NEWHUD.X1501]
/// </summary>
public bool? Line833FwbcIndicator { get => _line833FwbcIndicator; set => SetField(ref _line833FwbcIndicator, value); }
/// <summary>
/// Fees Line 835 Funding Worksheet Checkbox for Seller [NEWHUD.X1524]
/// </summary>
public bool? Line833FwscIndicator { get => _line833FwscIndicator; set => SetField(ref _line833FwscIndicator, value); }
/// <summary>
/// Fees Line 801 L Funding Worksheet Checkbox for Borrower [NEWHUD.X1479]
/// </summary>
public bool? LineLFwbcIndicator { get => _lineLFwbcIndicator; set => SetField(ref _lineLFwbcIndicator, value); }
/// <summary>
/// Fees Line 801 L Funding Worksheet Checkbox for Seller [NEWHUD.X1502]
/// </summary>
public bool? LineLFwscIndicator { get => _lineLFwscIndicator; set => SetField(ref _lineLFwscIndicator, value); }
/// <summary>
/// Fees Line 801 M Funding Worksheet Checkbox for Borrower [NEWHUD.X1480]
/// </summary>
public bool? LineMFwbcIndicator { get => _lineMFwbcIndicator; set => SetField(ref _lineMFwbcIndicator, value); }
/// <summary>
/// Fees Line 801 M Funding Worksheet Checkbox for Seller [NEWHUD.X1503]
/// </summary>
public bool? LineMFwscIndicator { get => _lineMFwscIndicator; set => SetField(ref _lineMFwscIndicator, value); }
/// <summary>
/// Fees Line 801 N Funding Worksheet Checkbox for Borrower [NEWHUD.X1481]
/// </summary>
public bool? LineNFwbcIndicator { get => _lineNFwbcIndicator; set => SetField(ref _lineNFwbcIndicator, value); }
/// <summary>
/// Fees Line 801 N Funding Worksheet Checkbox for Seller [NEWHUD.X1504]
/// </summary>
public bool? LineNFwscIndicator { get => _lineNFwscIndicator; set => SetField(ref _lineNFwscIndicator, value); }
/// <summary>
/// Fees Line 801 O Funding Worksheet Checkbox for Borrower [NEWHUD.X1482]
/// </summary>
public bool? LineOFwbcIndicator { get => _lineOFwbcIndicator; set => SetField(ref _lineOFwbcIndicator, value); }
/// <summary>
/// Fees Line 801 O Funding Worksheet Checkbox for Seller [NEWHUD.X1505]
/// </summary>
public bool? LineOFwscIndicator { get => _lineOFwscIndicator; set => SetField(ref _lineOFwscIndicator, value); }
/// <summary>
/// Fees Line 801 P Funding Worksheet Checkbox for Borrower [NEWHUD.X1483]
/// </summary>
public bool? LinePFwbcIndicator { get => _linePFwbcIndicator; set => SetField(ref _linePFwbcIndicator, value); }
/// <summary>
/// Fees Line 801 P Funding Worksheet Checkbox for Seller [NEWHUD.X1506]
/// </summary>
public bool? LinePFwscIndicator { get => _linePFwscIndicator; set => SetField(ref _linePFwscIndicator, value); }
/// <summary>
/// Fees Line 801 Q Funding Worksheet Checkbox for Borrower [NEWHUD.X1484]
/// </summary>
public bool? LineQFwbcIndicator { get => _lineQFwbcIndicator; set => SetField(ref _lineQFwbcIndicator, value); }
/// <summary>
/// Fees Line 801 Q Funding Worksheet Checkbox for Seller [NEWHUD.X1507]
/// </summary>
public bool? LineQFwscIndicator { get => _lineQFwscIndicator; set => SetField(ref _lineQFwscIndicator, value); }
/// <summary>
/// Fees Line 801 R Funding Worksheet Checkbox for Borrower [NEWHUD.X1485]
/// </summary>
public bool? LineRFwbcIndicator { get => _lineRFwbcIndicator; set => SetField(ref _lineRFwbcIndicator, value); }
/// <summary>
/// Fees Line 801 R Funding Worksheet Checkbox for Seller [NEWHUD.X1508]
/// </summary>
public bool? LineRFwscIndicator { get => _lineRFwscIndicator; set => SetField(ref _lineRFwscIndicator, value); }
/// <summary>
/// Lowest ARM Rate [NEWHUD.X333]
/// </summary>
[LoanFieldProperty(Format = LoanFieldFormat.DECIMAL_3)]
public decimal? LowestArmRate { get => _lowestArmRate; set => SetField(ref _lowestArmRate, value); }
/// <summary>
/// Mnthly Amt Includes Interest [NEWHUD.X356]
/// </summary>
public bool? MonthlyAmountIncludeInterestIndicator { get => _monthlyAmountIncludeInterestIndicator; set => SetField(ref _monthlyAmountIncludeInterestIndicator, value); }
/// <summary>
/// Mnthly Amt Includes Mortg Ins [NEWHUD.X357]
/// </summary>
public bool? MonthlyAmountIncludeMiIndicator { get => _monthlyAmountIncludeMiIndicator; set => SetField(ref _monthlyAmountIncludeMiIndicator, value); }
/// <summary>
/// Mnthly Amt Includes Principal [NEWHUD.X355]
/// </summary>
public bool? MonthlyAmountIncludePrincipalIndicator { get => _monthlyAmountIncludePrincipalIndicator; set => SetField(ref _monthlyAmountIncludePrincipalIndicator, value); }
/// <summary>
/// HUD-1 Pg 3 Initial Mthly Amt w/Escrow [NEWHUD.X802]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public decimal? MonthlyAmountWithEscrow { get => _monthlyAmountWithEscrow; set => SetField(ref _monthlyAmountWithEscrow, value); }
/// <summary>
/// HUD-1 Pg 3 Mthly Escrow Pymt w/o Mrtg Ins [NEWHUD.X950]
/// </summary>
[LoanFieldProperty(ReadOnly = true)]
public decimal? MonthlyEscrowPayment { get => _monthlyEscrowPayment; set => SetField(ref _monthlyEscrowPayment, value); }
/// <summary>
/// New HUD HUD-1 Page 3 Prepaid Interest [NEWHUD.X949]
/// </summary>
public decimal? PrepaidInterest { get => _prepaidInterest; set => SetField(ref _prepaidInterest, value); }
/// <summary>
/// Total GFE Tolerance Increase Amt [NEWHUD.X314]
/// </summary>
public decimal? TotalToleranceIncreaseAmount { get => _totalToleranceIncreaseAmount; set => SetField(ref _totalToleranceIncreaseAmount, 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.
// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
//
// IntRangePartitionerTests.cs - Tests for range partitioner for integer range.
//
// PLEASE NOTE !! - For tests that need to iterate the elements inside the partitions more
// than once, we need to call GetPartitions for the second time. Iterating a second times
// over the first enumerable<tuples> / IList<IEnumerator<tuples> will yield no elements
//
// PLEASE NOTE!! - we use lazy evaluation wherever possible to allow for more than Int32.MaxValue
// elements. ToArray / toList will result in an OOM
//
// Taken from:
// \qa\clr\testsrc\pfx\Functional\Common\Partitioner\YetiTests\RangePartitioner\IntRangePartitionerTests.cs
// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
using System;
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using Xunit;
namespace System.Collections.Concurrent.Tests
{
public class IntRangePartitionerTests
{
/// <summary>
/// Ensure that the partitioner returned has properties set correctly
/// </summary>
[Fact]
public static void CheckKeyProperties()
{
var partitioner = Partitioner.Create(0, 1000);
Assert.True(partitioner.KeysOrderedInEachPartition, "Expected KeysOrderedInEachPartition to be set to true");
Assert.False(partitioner.KeysOrderedAcrossPartitions, "KeysOrderedAcrossPartitions to be set to false");
Assert.True(partitioner.KeysNormalized, "Expected KeysNormalized to be set to true");
partitioner = Partitioner.Create(0, 1000, 90);
Assert.True(partitioner.KeysOrderedInEachPartition, "Expected KeysOrderedInEachPartition to be set to true");
Assert.False(partitioner.KeysOrderedAcrossPartitions, "KeysOrderedAcrossPartitions to be set to false");
Assert.True(partitioner.KeysNormalized, "Expected KeysNormalized to be set to true");
}
/// <summary>
/// GetPartitions returns an IList<IEnumerator<Tuple<int, int>>
/// We unroll the tuples and flatten them to a single sequence
/// The single sequence is compared to the original range for verification
/// </summary>
[Fact]
public static void CheckGetPartitions()
{
CheckGetPartitions(0, 1, 1);
CheckGetPartitions(1, 1999, 3);
CheckGetPartitions(2147473647, 9999, 4);
CheckGetPartitions(-1999, 5000, 63);
CheckGetPartitions(-2147483648, 5000, 63);
}
public static void CheckGetPartitions(int from, int count, int dop)
{
int to = from + count;
var partitioner = Partitioner.Create(from, to);
//var elements = dopPartitions.SelectMany(enumerator => enumerator.UnRoll());
IList<int> elements = new List<int>();
foreach (var partition in partitioner.GetPartitions(dop))
{
foreach (var item in partition.UnRoll())
elements.Add(item);
}
Assert.True(elements.CompareSequences<int>(RangePartitionerHelpers.IntEnumerable(from, to)), "GetPartitions element mismatch");
}
/// <summary>
/// CheckGetDynamicPartitions returns an IEnumerable<Tuple<int, int>>
/// We unroll the tuples and flatten them to a single sequence
/// The single sequence is compared to the original range for verification
/// </summary>
/// <param name="from"></param>
/// <param name="count"></param>
[Fact]
public static void CheckGetDynamicPartitions()
{
CheckGetDynamicPartitions(0, 1);
CheckGetDynamicPartitions(1, 1999);
CheckGetDynamicPartitions(2147473647, 9999);
CheckGetDynamicPartitions(-1999, 5000);
CheckGetDynamicPartitions(-2147483648, 5000);
}
public static void CheckGetDynamicPartitions(int from, int count)
{
int to = from + count;
var partitioner = Partitioner.Create(from, to);
//var elements = partitioner.GetDynamicPartitions().SelectMany(tuple => tuple.UnRoll());
IList<int> elements = new List<int>();
foreach (var partition in partitioner.GetDynamicPartitions())
{
foreach (var item in partition.UnRoll())
elements.Add(item);
}
Assert.True(elements.CompareSequences<int>(RangePartitionerHelpers.IntEnumerable(from, to)), "GetDynamicPartitions Element mismatch");
}
/// <summary>
/// GetOrderablePartitions returns an IList<IEnumerator<KeyValuePair<long, Tuple<int, int>>>
/// We unroll the tuples and flatten them to a single sequence
/// The single sequence is compared to the original range for verification
/// Also the indices are extracted to ensure that they are ordered & normalized
/// </summary>
[Fact]
public static void CheckGetOrderablePartitions()
{
CheckGetOrderablePartitions(0, 1, 1);
CheckGetOrderablePartitions(1, 1999, 3);
CheckGetOrderablePartitions(2147473647, 9999, 4);
CheckGetOrderablePartitions(-1999, 5000, 63);
CheckGetOrderablePartitions(-2147483648, 5000, 63);
}
public static void CheckGetOrderablePartitions(int from, int count, int dop)
{
int to = from + count;
var partitioner = Partitioner.Create(from, to);
//var elements = partitioner.GetOrderablePartitions(dop).SelectMany(enumerator => enumerator.UnRoll());
IList<int> elements = new List<int>();
foreach (var partition in partitioner.GetPartitions(dop))
{
foreach (var item in partition.UnRoll())
elements.Add(item);
}
Assert.True(elements.CompareSequences<int>(RangePartitionerHelpers.IntEnumerable(from, to)), "GetOrderablePartitions Element mismatch");
//var keys = partitioner.GetOrderablePartitions(dop).SelectMany(enumerator => enumerator.UnRollIndices()).ToArray();
IList<long> keys = new List<long>();
foreach (var partition in partitioner.GetOrderablePartitions(dop))
{
foreach (var item in partition.UnRollIndices())
keys.Add(item);
}
Assert.True(keys.CompareSequences<long>(RangePartitionerHelpers.LongEnumerable(keys[0], keys.Count)), "GetOrderablePartitions key mismatch");
}
/// <summary>
/// GetOrderableDynamicPartitions returns an IEnumerable<KeyValuePair<long, Tuple<int, int>>
/// We unroll the tuples and flatten them to a single sequence
/// The single sequence is compared to the original range for verification
/// Also the indices are extracted to ensure that they are ordered & normalized
/// </summary>
[Fact]
public static void GetOrderableDynamicPartitions()
{
GetOrderableDynamicPartitions(0, 1);
GetOrderableDynamicPartitions(1, 1999);
GetOrderableDynamicPartitions(2147473647, 9999);
GetOrderableDynamicPartitions(-1999, 5000);
GetOrderableDynamicPartitions(-2147483648, 5000);
}
private static void GetOrderableDynamicPartitions(int from, int count)
{
int to = from + count;
var partitioner = Partitioner.Create(from, to);
//var elements = partitioner.GetOrderableDynamicPartitions().SelectMany(tuple => tuple.UnRoll());
IList<int> elements = new List<int>();
foreach (var partition in partitioner.GetOrderableDynamicPartitions())
{
foreach (var item in partition.UnRoll())
elements.Add(item);
}
Assert.True(elements.CompareSequences<int>(RangePartitionerHelpers.IntEnumerable(from, to)), "GetOrderableDynamicPartitions Element mismatch");
//var keys = partitioner.GetOrderableDynamicPartitions().Select(tuple => tuple.Key).ToArray();
IList<long> keys = new List<long>();
foreach (var tuple in partitioner.GetOrderableDynamicPartitions())
{
keys.Add(tuple.Key);
}
Assert.True(keys.CompareSequences<long>(RangePartitionerHelpers.LongEnumerable(keys[0], keys.Count)), "GetOrderableDynamicPartitions key mismatch");
}
/// <summary>
/// GetPartitions returns an IList<IEnumerator<Tuple<int, int>>
/// We unroll the tuples and flatten them to a single sequence
/// The single sequence is compared to the original range for verification
/// This method tests the partitioner created with user provided desiredRangeSize
/// The range sizes for individual ranges are checked to see if they are equal to
/// desiredRangeSize. The last range may have less than or equal to desiredRangeSize.
/// </summary>
[Fact]
public static void CheckGetPartitionsWithRange()
{
CheckGetPartitionsWithRange(1999, 1000, 20, 1);
CheckGetPartitionsWithRange(-1999, 1000, 100, 2);
CheckGetPartitionsWithRange(1999, 1, 2000, 3);
CheckGetPartitionsWithRange(2147482647, 999, 600, 4);
CheckGetPartitionsWithRange(-2147483648, 1000, 19, 63);
}
public static void CheckGetPartitionsWithRange(int from, int count, int desiredRangeSize, int dop)
{
int to = from + count;
var partitioner = Partitioner.Create(from, to, desiredRangeSize);
//var elements = partitioner.GetPartitions(dop).SelectMany(enumerator => enumerator.UnRoll());
IList<int> elements = new List<int>();
foreach (var partition in partitioner.GetPartitions(dop))
{
foreach (var item in partition.UnRoll())
elements.Add(item);
}
Assert.True(elements.CompareSequences<int>(RangePartitionerHelpers.IntEnumerable(from, to)), "GetPartitions element mismatch");
//var rangeSizes = partitioner.GetPartitions(dop).SelectMany(enumerator => enumerator.GetRangeSize()).ToArray();
IList<int> rangeSizes = new List<int>();
foreach (var partition in partitioner.GetPartitions(dop))
{
foreach (var item in partition.GetRangeSize())
rangeSizes.Add(item);
}
ValidateRangeSize(desiredRangeSize, rangeSizes);
}
/// <summary>
/// CheckGetDynamicPartitionsWithRange returns an IEnumerable<Tuple<int, int>>
/// We unroll the tuples and flatten them to a single sequence
/// The single sequence is compared to the original range for verification
/// This method tests the partitioner created with user provided desiredRangeSize
/// The range sizes for individual ranges are checked to see if they are equal to
/// desiredRangeSize. The last range may have less than or equal to desiredRangeSize.
/// </summary>
[Fact]
public static void CheckGetDynamicPartitionsWithRange()
{
CheckGetDynamicPartitionsWithRange(1999, 1000, 20);
CheckGetDynamicPartitionsWithRange(-1999, 1000, 100);
CheckGetDynamicPartitionsWithRange(1999, 1, 2000);
CheckGetDynamicPartitionsWithRange(2147482647, 999, 600);
CheckGetDynamicPartitionsWithRange(-2147483648, 1000, 19);
}
public static void CheckGetDynamicPartitionsWithRange(int from, int count, int desiredRangeSize)
{
int to = from + count;
var partitioner = Partitioner.Create(from, to, desiredRangeSize);
//var elements = partitioner.GetDynamicPartitions().SelectMany(tuple => tuple.UnRoll());
IList<int> elements = new List<int>();
foreach (var partition in partitioner.GetDynamicPartitions())
{
foreach (var item in partition.UnRoll())
elements.Add(item);
}
Assert.True(elements.CompareSequences<int>(RangePartitionerHelpers.IntEnumerable(from, to)), "GetDynamicPartitions Element mismatch");
//var rangeSizes = partitioner.GetDynamicPartitions().Select(tuple => tuple.GetRangeSize()).ToArray();
IList<int> rangeSizes = new List<int>();
foreach (var partition in partitioner.GetDynamicPartitions())
{
rangeSizes.Add(partition.GetRangeSize());
}
ValidateRangeSize(desiredRangeSize, rangeSizes);
}
/// <summary>
/// GetOrderablePartitions returns an IList<IEnumerator<KeyValuePair<long, Tuple<int, int>>>
/// We unroll the tuples and flatten them to a single sequence
/// The single sequence is compared to the original range for verification
/// Also the indices are extracted to ensure that they are ordered & normalized
/// This method tests the partitioner created with user provided desiredRangeSize
/// The range sizes for individual ranges are checked to see if they are equal to
/// desiredRangeSize. The last range may have less than or equal to desiredRangeSize.
/// </summary>
[Fact]
public static void CheckGetOrderablePartitionsWithRange()
{
CheckGetOrderablePartitionsWithRange(1999, 1000, 20, 1);
CheckGetOrderablePartitionsWithRange(-1999, 1000, 100, 2);
CheckGetOrderablePartitionsWithRange(1999, 1, 2000, 3);
CheckGetOrderablePartitionsWithRange(2147482647, 999, 600, 4);
CheckGetOrderablePartitionsWithRange(-2147483648, 1000, 19, 63);
}
private static void CheckGetOrderablePartitionsWithRange(int from, int count, int desiredRangeSize, int dop)
{
int to = from + count;
var partitioner = Partitioner.Create(from, to, desiredRangeSize);
//var elements = partitioner.GetOrderablePartitions(dop).SelectMany(enumerator => enumerator.UnRoll());
IList<int> elements = new List<int>();
foreach (var partition in partitioner.GetOrderablePartitions(dop))
{
foreach (var item in partition.UnRoll())
elements.Add(item);
}
Assert.True(elements.CompareSequences<int>(RangePartitionerHelpers.IntEnumerable(from, to)), "GetOrderablePartitions Element mismatch");
//var keys = partitioner.GetOrderablePartitions(dop).SelectMany(enumerator => enumerator.UnRollIndices()).ToArray();
IList<long> keys = new List<long>();
foreach (var partition in partitioner.GetOrderablePartitions(dop))
{
foreach (var item in partition.UnRollIndices())
keys.Add(item);
}
Assert.True(keys.CompareSequences<long>(RangePartitionerHelpers.LongEnumerable(keys[0], keys.Count)), "GetOrderablePartitions key mismatch");
//var rangeSizes = partitioner.GetOrderablePartitions(dop).SelectMany(enumerator => enumerator.GetRangeSize()).ToArray();
IList<int> rangeSizes = new List<int>();
foreach (var partition in partitioner.GetOrderablePartitions(dop))
{
foreach (var item in partition.GetRangeSize())
rangeSizes.Add(item);
}
ValidateRangeSize(desiredRangeSize, rangeSizes);
}
/// <summary>
/// GetOrderableDynamicPartitions returns an IEnumerable<KeyValuePair<long, Tuple<int, int>>
/// We unroll the tuples and flatten them to a single sequence
/// The single sequence is compared to the original range for verification
/// Also the indices are extracted to ensure that they are ordered & normalized
/// This method tests the partitioner created with user provided desiredRangeSize
/// The range sizes for individual ranges are checked to see if they are equal to
/// desiredRangeSize. The last range may have less than or equal to desiredRangeSize.
/// </summary>
[Fact]
public static void GetOrderableDynamicPartitionsWithRange()
{
GetOrderableDynamicPartitionsWithRange(1999, 1000, 20);
GetOrderableDynamicPartitionsWithRange(-1999, 1000, 100);
GetOrderableDynamicPartitionsWithRange(1999, 1, 2000);
GetOrderableDynamicPartitionsWithRange(2147482647, 999, 600);
GetOrderableDynamicPartitionsWithRange(-2147483648, 1000, 19);
}
private static void GetOrderableDynamicPartitionsWithRange(int from, int count, int desiredRangeSize)
{
int to = from + count;
var partitioner = Partitioner.Create(from, to, desiredRangeSize);
//var elements = partitioner.GetOrderableDynamicPartitions().SelectMany(tuple => tuple.UnRoll());
IList<int> elements = new List<int>();
foreach (var tuple in partitioner.GetOrderableDynamicPartitions())
{
foreach (var item in tuple.UnRoll())
elements.Add(item);
}
Assert.True(elements.CompareSequences<int>(RangePartitionerHelpers.IntEnumerable(from, to)), "GetOrderableDynamicPartitions Element mismatch");
//var keys = partitioner.GetOrderableDynamicPartitions().Select(tuple => tuple.Key).ToArray();
IList<long> keys = new List<long>();
foreach (var tuple in partitioner.GetOrderableDynamicPartitions())
{
keys.Add(tuple.Key);
}
Assert.True(keys.CompareSequences<long>(RangePartitionerHelpers.LongEnumerable(keys[0], keys.Count)), "GetOrderableDynamicPartitions key mismatch");
//var rangeSizes = partitioner.GetOrderableDynamicPartitions().Select(tuple => tuple.GetRangeSize()).ToArray();
IList<int> rangeSizes = new List<int>();
foreach (var partition in partitioner.GetOrderableDynamicPartitions())
{
rangeSizes.Add(partition.GetRangeSize());
}
ValidateRangeSize(desiredRangeSize, rangeSizes);
}
/// <summary>
/// Helper function to validate the the range size of the partitioners match what the user specified
/// (desiredRangeSize).
/// </summary>
/// <param name="desiredRangeSize"></param>
/// <param name="rangeSizes"></param>
public static void ValidateRangeSize(int desiredRangeSize, IList<int> rangeSizes)
{
//var rangesWithDifferentRangeSize = rangeSizes.Take(rangeSizes.Length - 1).Where(r => r != desiredRangeSize).ToArray();
IList<int> rangesWithDifferentRangeSize = new List<int>();
// ensuring that every range, size from the last one is the same.
int numToTake = rangeSizes.Count - 1;
for (int i = 0; i < numToTake; i++)
{
int range = rangeSizes[i];
if (range != desiredRangeSize)
rangesWithDifferentRangeSize.Add(range);
}
Assert.Equal(0, rangesWithDifferentRangeSize.Count);
Assert.InRange(rangeSizes[rangeSizes.Count - 1], 0, desiredRangeSize);
}
[Fact]
public static void RangePartitionerChunking()
{
RangePartitionerChunking(1999, 1000, 10);
RangePartitionerChunking(89, 17823, -1);
}
/// <summary>
/// Ensure that the range partitioner doesn't chunk up elements i.e. uses chunk size = 1
/// </summary>
/// <param name="from"></param>
/// <param name="count"></param>
/// <param name="rangeSize"></param>
public static void RangePartitionerChunking(int from, int count, int rangeSize)
{
int to = from + count;
var partitioner = (rangeSize == -1) ? Partitioner.Create(from, to) : Partitioner.Create(from, to, rangeSize);
// Check static partitions
var partitions = partitioner.GetPartitions(2);
// Initialize the from / to values from the first element
if (!partitions[0].MoveNext()) return;
Assert.Equal(from, partitions[0].Current.Item1);
if (rangeSize == -1)
{
rangeSize = partitions[0].Current.Item2 - partitions[0].Current.Item1;
}
int nextExpectedFrom = partitions[0].Current.Item2;
int nextExpectedTo = (nextExpectedFrom + rangeSize) > to ? to : (nextExpectedFrom + rangeSize);
// Ensure that each partition gets one range only
// we check this by alternating partitions asking for elements and make sure
// that we get ranges in a sequence. If chunking were to happen then we wouldn't see a sequence
int actualCount = partitions[0].Current.Item2 - partitions[0].Current.Item1;
while (true)
{
if (!partitions[0].MoveNext()) break;
Assert.Equal(nextExpectedFrom, partitions[0].Current.Item1);
Assert.Equal(nextExpectedTo, partitions[0].Current.Item2);
nextExpectedFrom = (nextExpectedFrom + rangeSize) > to ? to : (nextExpectedFrom + rangeSize);
nextExpectedTo = (nextExpectedTo + rangeSize) > to ? to : (nextExpectedTo + rangeSize);
actualCount += partitions[0].Current.Item2 - partitions[0].Current.Item1;
if (!partitions[1].MoveNext()) break;
Assert.Equal(nextExpectedFrom, partitions[1].Current.Item1);
Assert.Equal(nextExpectedTo, partitions[1].Current.Item2);
nextExpectedFrom = (nextExpectedFrom + rangeSize) > to ? to : (nextExpectedFrom + rangeSize);
nextExpectedTo = (nextExpectedTo + rangeSize) > to ? to : (nextExpectedTo + rangeSize);
actualCount += partitions[1].Current.Item2 - partitions[1].Current.Item1;
if (!partitions[1].MoveNext()) break;
Assert.Equal(nextExpectedFrom, partitions[1].Current.Item1);
Assert.Equal(nextExpectedTo, partitions[1].Current.Item2);
nextExpectedFrom = (nextExpectedFrom + rangeSize) > to ? to : (nextExpectedFrom + rangeSize);
nextExpectedTo = (nextExpectedTo + rangeSize) > to ? to : (nextExpectedTo + rangeSize);
actualCount += partitions[1].Current.Item2 - partitions[1].Current.Item1;
if (!partitions[0].MoveNext()) break;
Assert.Equal(nextExpectedFrom, partitions[0].Current.Item1);
Assert.Equal(nextExpectedTo, partitions[0].Current.Item2);
nextExpectedFrom = (nextExpectedFrom + rangeSize) > to ? to : (nextExpectedFrom + rangeSize);
nextExpectedTo = (nextExpectedTo + rangeSize) > to ? to : (nextExpectedTo + rangeSize);
actualCount += partitions[0].Current.Item2 - partitions[0].Current.Item1;
}
// Verifying that all items are there
Assert.Equal(count, actualCount);
}
[Fact]
public static void RangePartitionerDynamicChunking()
{
RangePartitionerDynamicChunking(1999, 1000, 10);
RangePartitionerDynamicChunking(1, 884354, -1);
}
/// <summary>
/// Ensure that the range partitioner doesn't chunk up elements i.e. uses chunk size = 1
/// </summary>
/// <param name="from"></param>
/// <param name="count"></param>
/// <param name="rangeSize"></param>
public static void RangePartitionerDynamicChunking(int from, int count, int rangeSize)
{
int to = from + count;
var partitioner = (rangeSize == -1) ? Partitioner.Create(from, to) : Partitioner.Create(from, to, rangeSize);
// Check static partitions
var partitions = partitioner.GetDynamicPartitions();
var partition1 = partitions.GetEnumerator();
var partition2 = partitions.GetEnumerator();
// Initialize the from / to values from the first element
if (!partition1.MoveNext()) return;
Assert.True(from == partition1.Current.Item1);
if (rangeSize == -1)
{
rangeSize = partition1.Current.Item2 - partition1.Current.Item1;
}
int nextExpectedFrom = partition1.Current.Item2;
int nextExpectedTo = (nextExpectedFrom + rangeSize) > to ? to : (nextExpectedFrom + rangeSize);
// Ensure that each partition gets one range only
// we check this by alternating partitions asking for elements and make sure
// that we get ranges in a sequence. If chunking were to happen then we wouldn't see a sequence
int actualCount = partition1.Current.Item2 - partition1.Current.Item1;
while (true)
{
if (!partition1.MoveNext()) break;
Assert.Equal(nextExpectedFrom, partition1.Current.Item1);
Assert.Equal(nextExpectedTo, partition1.Current.Item2);
nextExpectedFrom = (nextExpectedFrom + rangeSize) > to ? to : (nextExpectedFrom + rangeSize);
nextExpectedTo = (nextExpectedTo + rangeSize) > to ? to : (nextExpectedTo + rangeSize);
actualCount += partition1.Current.Item2 - partition1.Current.Item1;
if (!partition2.MoveNext()) break;
Assert.Equal(nextExpectedFrom, partition2.Current.Item1);
Assert.Equal(nextExpectedTo, partition2.Current.Item2);
nextExpectedFrom = (nextExpectedFrom + rangeSize) > to ? to : (nextExpectedFrom + rangeSize);
nextExpectedTo = (nextExpectedTo + rangeSize) > to ? to : (nextExpectedTo + rangeSize);
actualCount += partition2.Current.Item2 - partition2.Current.Item1;
if (!partition2.MoveNext()) break;
Assert.Equal(nextExpectedFrom, partition2.Current.Item1);
Assert.Equal(nextExpectedTo, partition2.Current.Item2);
nextExpectedFrom = (nextExpectedFrom + rangeSize) > to ? to : (nextExpectedFrom + rangeSize);
nextExpectedTo = (nextExpectedTo + rangeSize) > to ? to : (nextExpectedTo + rangeSize);
actualCount += partition2.Current.Item2 - partition2.Current.Item1;
if (!partition1.MoveNext()) break;
Assert.Equal(nextExpectedFrom, partition1.Current.Item1);
Assert.Equal(nextExpectedTo, partition1.Current.Item2);
nextExpectedFrom = (nextExpectedFrom + rangeSize) > to ? to : (nextExpectedFrom + rangeSize);
nextExpectedTo = (nextExpectedTo + rangeSize) > to ? to : (nextExpectedTo + rangeSize);
actualCount += partition1.Current.Item2 - partition1.Current.Item1;
}
// Verifying that all items are there
Assert.Equal(count, actualCount);
}
}
}
| |
// CodeContracts
//
// Copyright (c) Microsoft Corporation
//
// All rights reserved.
//
// MIT License
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// File System.Web.UI.TemplateControl.cs
// Automatically generated contract file.
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Diagnostics.Contracts;
using System;
// Disable the "this variable is not used" warning as every field would imply it.
#pragma warning disable 0414
// Disable the "this variable is never assigned to".
#pragma warning disable 0649
// Disable the "this variable is never used".
#pragma warning disable 0169
// Disable the "new keyword not required" warning.
#pragma warning disable 0109
// Disable the "extern without DllImport" warning.
#pragma warning disable 0626
// Disable the "could hide other member" warning, can happen on certain properties.
#pragma warning disable 0108
namespace System.Web.UI
{
abstract public partial class TemplateControl : Control, INamingContainer, IFilterResolutionService
{
#region Methods and constructors
protected virtual new void Construct ()
{
}
protected LiteralControl CreateResourceBasedLiteralControl (int offset, int size, bool fAsciiOnly)
{
Contract.Ensures (Contract.Result<System.Web.UI.LiteralControl>() != null);
return default(LiteralControl);
}
protected internal string Eval (string expression, string format)
{
return default(string);
}
protected internal Object Eval (string expression)
{
return default(Object);
}
protected virtual new void FrameworkInitialize ()
{
}
protected Object GetGlobalResourceObject (string className, string resourceKey)
{
return default(Object);
}
protected Object GetGlobalResourceObject (string className, string resourceKey, Type objType, string propName)
{
return default(Object);
}
protected Object GetLocalResourceObject (string resourceKey)
{
return default(Object);
}
protected Object GetLocalResourceObject (string resourceKey, Type objType, string propName)
{
return default(Object);
}
public Control LoadControl (Type t, Object[] parameters)
{
return default(Control);
}
public Control LoadControl (string virtualPath)
{
return default(Control);
}
public ITemplate LoadTemplate (string virtualPath)
{
Contract.Ensures (Contract.Result<System.Web.UI.ITemplate>() != null);
return default(ITemplate);
}
protected virtual new void OnAbortTransaction (EventArgs e)
{
}
protected virtual new void OnCommitTransaction (EventArgs e)
{
}
protected virtual new void OnError (EventArgs e)
{
}
public Control ParseControl (string content)
{
return default(Control);
}
public Control ParseControl (string content, bool ignoreParserFilter)
{
return default(Control);
}
public static Object ReadStringResource (Type t)
{
return default(Object);
}
public Object ReadStringResource ()
{
return default(Object);
}
protected void SetStringResourcePointer (Object stringResourcePointer, int maxResourceOffset)
{
Contract.Requires (stringResourcePointer != null);
}
int System.Web.UI.IFilterResolutionService.CompareFilters (string filter1, string filter2)
{
return default(int);
}
bool System.Web.UI.IFilterResolutionService.EvaluateFilter (string filterName)
{
return default(bool);
}
protected TemplateControl ()
{
}
public virtual new bool TestDeviceFilter (string filterName)
{
return default(bool);
}
protected void WriteUTF8ResourceString (HtmlTextWriter output, int offset, int size, bool fAsciiOnly)
{
Contract.Requires (output != null);
}
protected internal Object XPath (string xPathExpression)
{
Contract.Ensures (!string.IsNullOrEmpty(xPathExpression));
return default(Object);
}
protected internal Object XPath (string xPathExpression, System.Xml.IXmlNamespaceResolver resolver)
{
Contract.Ensures (!string.IsNullOrEmpty(xPathExpression));
return default(Object);
}
protected internal string XPath (string xPathExpression, string format, System.Xml.IXmlNamespaceResolver resolver)
{
Contract.Ensures (!string.IsNullOrEmpty(xPathExpression));
return default(string);
}
protected internal string XPath (string xPathExpression, string format)
{
Contract.Ensures (!string.IsNullOrEmpty(xPathExpression));
return default(string);
}
protected internal System.Collections.IEnumerable XPathSelect (string xPathExpression, System.Xml.IXmlNamespaceResolver resolver)
{
Contract.Ensures (Contract.Result<System.Collections.IEnumerable>() != null);
Contract.Ensures (!string.IsNullOrEmpty(xPathExpression));
return default(System.Collections.IEnumerable);
}
protected internal System.Collections.IEnumerable XPathSelect (string xPathExpression)
{
Contract.Ensures (Contract.Result<System.Collections.IEnumerable>() != null);
Contract.Ensures (!string.IsNullOrEmpty(xPathExpression));
return default(System.Collections.IEnumerable);
}
#endregion
#region Properties and indexers
public string AppRelativeVirtualPath
{
get
{
return default(string);
}
set
{
}
}
protected virtual new int AutoHandlers
{
get
{
return default(int);
}
set
{
}
}
public override bool EnableTheming
{
get
{
return default(bool);
}
set
{
}
}
protected virtual new bool SupportAutoEvents
{
get
{
return default(bool);
}
}
#endregion
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics.Contracts;
using Microsoft.Research.DataStructures;
namespace Microsoft.Research.AbstractDomains.Numerical
{
// **** Important *****
// We have a bunch of invariants in this class, which cannot proven by C# type system but Clousot can do.
// As a consequence we always want to have 0 warnings on this class
[ContractVerification(true)]
public class NonRelationalValueAbstraction<Variable, Expression>
: IAbstractDomainForArraySegmentationAbstraction<NonRelationalValueAbstraction<Variable, Expression>, Variable>
{
#region Object invariant
[ContractInvariantMethod]
private void ObjectInvariant()
{
Contract.Invariant(disInterval != null);
Contract.Invariant(symbolicConditions != null);
Contract.Invariant(weaklyRelationalDomains != null);
Contract.Invariant(weaklyRelationalDomains.Length == WeaklyRelationalDomainsCount);
Contract.Invariant(Contract.ForAll(weaklyRelationalDomains, dom => dom != null));
}
#endregion
#region State
private readonly DisInterval disInterval;
private readonly SymbolicExpressionTracker<Variable, Expression> symbolicConditions;
private const int WeaklyRelationalDomainsCount = 5;
private readonly SetOfConstraints<Variable>[] weaklyRelationalDomains;
public enum ADomains { Equalities = 0, DisEqualities = 1, WeakUpperBounds = 2, StrictUpperBounds = 3, Existential = 4 }
// Meaning:
// weaklyRelationalDomains[0] == Equalities
// weaklyRelationalDomains[1] == DisEqualities
// weaklyRelationalDomains[2] == WeakUpperBounds
// weaklyRelationalDomains[3] == StrictUpperBounds
// weaklyRelationalDomains[4] == Existential
#endregion
#region Constructor
public NonRelationalValueAbstraction(DisInterval interval)
: this(interval, SymbolicExpressionTracker<Variable, Expression>.Unknown,
SetOfConstraints<Variable>.Unknown, SetOfConstraints<Variable>.Unknown,
SetOfConstraints<Variable>.Unknown,
SetOfConstraints<Variable>.Unknown, SetOfConstraints<Variable>.Unknown)
{
Contract.Requires(interval != null);
}
public NonRelationalValueAbstraction(
DisInterval interval, SymbolicExpressionTracker<Variable, Expression> symbolicConditions,
SetOfConstraints<Variable> equalities, SetOfConstraints<Variable> disequalities,
SetOfConstraints<Variable> weakUpperBounds, SetOfConstraints<Variable> strictUpperBounds,
SetOfConstraints<Variable> existential)
{
Contract.Requires(interval != null);
Contract.Requires(symbolicConditions != null);
Contract.Requires(disequalities != null);
Contract.Requires(equalities != null);
Contract.Requires(weakUpperBounds != null);
Contract.Requires(strictUpperBounds != null);
Contract.Requires(existential != null);
disInterval = interval;
this.symbolicConditions = symbolicConditions;
weaklyRelationalDomains = new SetOfConstraints<Variable>[WeaklyRelationalDomainsCount]
{
equalities,
disequalities,
weakUpperBounds,
strictUpperBounds,
existential
};
}
private NonRelationalValueAbstraction(
DisInterval interval, SymbolicExpressionTracker<Variable, Expression> symbolicConditions,
SetOfConstraints<Variable>[] domains)
{
Contract.Requires(interval != null);
Contract.Requires(symbolicConditions != null);
Contract.Requires(domains != null);
Contract.Requires(domains.Length == WeaklyRelationalDomainsCount);
Contract.Requires(Contract.ForAll(domains, el => el != null));
disInterval = interval;
this.symbolicConditions = symbolicConditions;
weaklyRelationalDomains = domains;
}
#endregion
#region Statics
static public NonRelationalValueAbstraction<Variable, Expression> Unknown
{
get
{
Contract.Ensures(Contract.Result<NonRelationalValueAbstraction<Variable, Expression>>() != null);
var allTop = new SetOfConstraints<Variable>[WeaklyRelationalDomainsCount];
for (var i = 0; i < WeaklyRelationalDomainsCount; i++)
{
allTop[i] = SetOfConstraints<Variable>.Unknown;
}
return new NonRelationalValueAbstraction<Variable, Expression>(DisInterval.UnknownInterval, SymbolicExpressionTracker<Variable, Expression>.Unknown, allTop);
}
}
static public NonRelationalValueAbstraction<Variable, Expression> Unreached
{
get
{
Contract.Ensures(Contract.Result<NonRelationalValueAbstraction<Variable, Expression>>() != null);
var allBottom = new SetOfConstraints<Variable>[WeaklyRelationalDomainsCount];
for (var i = 0; i < WeaklyRelationalDomainsCount; i++)
{
allBottom[i] = SetOfConstraints<Variable>.Unreached;
}
return new NonRelationalValueAbstraction<Variable, Expression>(DisInterval.UnreachedInterval, SymbolicExpressionTracker<Variable, Expression>.Unreached, allBottom);
}
}
#endregion
#region Properties
public DisInterval Interval
{
get
{
Contract.Ensures(Contract.Result<DisInterval>() != null);
return disInterval;
}
}
public SetOfConstraints<Variable> Equalities
{
get
{
Contract.Ensures(Contract.Result<SetOfConstraints<Variable>>() != null);
return weaklyRelationalDomains[(int)ADomains.Equalities];
}
}
public SetOfConstraints<Variable> DisEqualities
{
get
{
Contract.Ensures(Contract.Result<SetOfConstraints<Variable>>() != null);
return weaklyRelationalDomains[(int)ADomains.DisEqualities];
}
}
public SetOfConstraints<Variable> StrictUpperBounds
{
get
{
Contract.Ensures(Contract.Result<SetOfConstraints<Variable>>() != null);
return weaklyRelationalDomains[(int)ADomains.StrictUpperBounds];
}
}
public SetOfConstraints<Variable> WeakUpperBounds
{
get
{
Contract.Ensures(Contract.Result<SetOfConstraints<Variable>>() != null);
return weaklyRelationalDomains[(int)ADomains.WeakUpperBounds];
}
}
public SetOfConstraints<Variable> Existential
{
get
{
Contract.Ensures(Contract.Result<SetOfConstraints<Variable>>() != null);
return weaklyRelationalDomains[(int)ADomains.Existential];
}
}
public SymbolicExpressionTracker<Variable, Expression> SymbolicConditions
{
get
{
Contract.Ensures(Contract.Result<SymbolicExpressionTracker<Variable, Expression>>() != null);
return symbolicConditions;
}
}
#endregion
#region Check For contraddictions
/// <summary>
/// Check for contraddictions.
/// The understanding here is that:
/// - 'this' is interpreted as existential and 'exists' as universal
/// - 'that' is interpreted as universal and 'exists' as existential
/// </summary>
public bool AreInContraddiction(NonRelationalValueAbstraction<Variable, Expression> other)
{
Contract.Requires(other != null);
if (this.Interval.Meet(other.Interval).IsBottom)
return true;
if (!this.DisEqualities.Join(other.Equalities).IsTop)
return true;
if (!this.Equalities.Join(other.DisEqualities).IsTop)
return true;
if (!this.Equalities.Join(other.StrictUpperBounds).IsTop)
return true;
if (!this.StrictUpperBounds.Join(other.Equalities).IsTop)
return true;
return false;
}
#endregion
#region Assumptions
public NonRelationalValueAbstraction<Variable, Expression> TestTrueEqual(Variable v)
{
if (this.DisEqualities.Contains(v) || this.StrictUpperBounds.Contains(v))
{
return this.Bottom;
}
var equalities = this.Equalities.Add(v);
var weakupperbounds = this.WeakUpperBounds.Add(v);
return new NonRelationalValueAbstraction<Variable, Expression>(
this.Interval, this.SymbolicConditions,
equalities, // updated
this.DisEqualities,
weakupperbounds, // updated
this.StrictUpperBounds, this.Existential);
}
#endregion
#region IAbstractDomain Members
public bool IsBottom
{
get
{
return disInterval.IsBottom || symbolicConditions.IsBottom || weaklyRelationalDomains.Any(x => x.IsBottom);
}
}
public bool IsTop
{
get
{
return disInterval.IsTop && symbolicConditions.IsTop && weaklyRelationalDomains.All(x => x.IsTop);
}
}
public bool LessEqual(NonRelationalValueAbstraction<Variable, Expression> other)
{
Contract.Requires(other != null);
if (!disInterval.LessEqual(other.Interval))
{
return false;
}
Contract.Assert(other.symbolicConditions != null);
if (!symbolicConditions.LessEqual(other.symbolicConditions))
{
return false;
}
// F: Assuming the object invariant for other
Contract.Assert(other.weaklyRelationalDomains != null);
Contract.Assume(Contract.ForAll(other.weaklyRelationalDomains, dom => dom != null));
Contract.Assume(weaklyRelationalDomains.Length == other.weaklyRelationalDomains.Length, "assuming object invariant");
for (var i = 0; i < weaklyRelationalDomains.Length; i++)
{
if (!weaklyRelationalDomains[i].LessEqual(other.weaklyRelationalDomains[i]))
return false;
}
return true;
}
public NonRelationalValueAbstraction<Variable, Expression> Bottom
{
get
{
Contract.Ensures(Contract.Result<NonRelationalValueAbstraction<Variable, Expression>>() != null);
var allBottom = new SetOfConstraints<Variable>[WeaklyRelationalDomainsCount];
for (var i = 0; i < WeaklyRelationalDomainsCount; i++)
{
allBottom[i] = SetOfConstraints<Variable>.Unreached;
}
return new NonRelationalValueAbstraction<Variable, Expression>(DisInterval.UnreachedInterval, SymbolicExpressionTracker<Variable, Expression>.Unreached, allBottom);
}
}
public NonRelationalValueAbstraction<Variable, Expression> Top
{
get
{
Contract.Ensures(Contract.Result<NonRelationalValueAbstraction<Variable, Expression>>() != null);
var allTop = new SetOfConstraints<Variable>[WeaklyRelationalDomainsCount];
for (var i = 0; i < WeaklyRelationalDomainsCount; i++)
{
allTop[i] = SetOfConstraints<Variable>.Unknown;
}
return new NonRelationalValueAbstraction<Variable, Expression>(DisInterval.UnknownInterval, SymbolicExpressionTracker<Variable, Expression>.Unknown, allTop);
}
}
[Pure]
public NonRelationalValueAbstraction<Variable, Expression> Join(NonRelationalValueAbstraction<Variable, Expression> other)
{
Contract.Requires(other != null);
Contract.Ensures(Contract.Result<NonRelationalValueAbstraction<Variable, Expression>>() != null);
NonRelationalValueAbstraction<Variable, Expression> result;
if (AbstractDomainsHelper.TryTrivialJoin(this, other, out result))
{
return result;
}
var intv = disInterval.Join(other.Interval);
var symbolicConditions = this.symbolicConditions.Join(other.symbolicConditions);
Contract.Assume(weaklyRelationalDomains.Length == other.weaklyRelationalDomains.Length);
var newWeaklyDomains = ParallelOperation(weaklyRelationalDomains, other.weaklyRelationalDomains, (x, y) => x.Join(y));
return new NonRelationalValueAbstraction<Variable, Expression>(intv, symbolicConditions, newWeaklyDomains);
}
[Pure]
public NonRelationalValueAbstraction<Variable, Expression> Meet(NonRelationalValueAbstraction<Variable, Expression> other)
{
Contract.Requires(other != null);
Contract.Ensures(Contract.Result<NonRelationalValueAbstraction<Variable, Expression>>() != null);
NonRelationalValueAbstraction<Variable, Expression> result;
if (AbstractDomainsHelper.TryTrivialMeet(this, other, out result))
{
return result;
}
var intv = disInterval.Meet(other.Interval);
Contract.Assert(other.symbolicConditions != null);
var symbolicConditions = this.symbolicConditions.Meet(other.symbolicConditions);
Contract.Assert(other.weaklyRelationalDomains != null);
Contract.Assume(weaklyRelationalDomains.Length == other.weaklyRelationalDomains.Length);
var newWeaklyDomains = ParallelOperation(weaklyRelationalDomains, other.weaklyRelationalDomains, (x, y) => x.Meet(y));
return new NonRelationalValueAbstraction<Variable, Expression>(intv, symbolicConditions, newWeaklyDomains);
}
[Pure]
public NonRelationalValueAbstraction<Variable, Expression> Widening(NonRelationalValueAbstraction<Variable, Expression> prev)
{
Contract.Requires(prev != null);
Contract.Ensures(Contract.Result<NonRelationalValueAbstraction<Variable, Expression>>() != null);
NonRelationalValueAbstraction<Variable, Expression> result;
if (AbstractDomainsHelper.TryTrivialJoin(this, prev, out result))
{
return result;
}
var intv = disInterval.Widening(prev.Interval);
var symbolicConditions = this.symbolicConditions.Join(prev.symbolicConditions);
Contract.Assume(weaklyRelationalDomains.Length == prev.weaklyRelationalDomains.Length);
var newWeaklyDomains = ParallelOperation(weaklyRelationalDomains, prev.weaklyRelationalDomains, (x, y) => x.Widening(y));
return new NonRelationalValueAbstraction<Variable, Expression>(intv, SymbolicConditions, newWeaklyDomains);
}
#endregion
#region To
public T To<T>(IFactory<T> factory)
{
var result = factory.And(disInterval.To(factory), symbolicConditions.To(factory));
T name;
if (factory.TryGetName(out name))
{
for (var i = 0; i < weaklyRelationalDomains.Length; i++)
{
if (weaklyRelationalDomains[i].IsNormal())
{
result = factory.And(result, To(i, factory, name));
}
}
}
return result;
}
private T To<T>(int i, IFactory<T> factory, T name)
{
Contract.Requires(i >= 0);
Contract.Requires(i < weaklyRelationalDomains.Length);
Contract.Requires(factory != null);
var result = factory.IdentityForAnd;
var constraints = weaklyRelationalDomains[i];
switch (i)
{
// weaklyRelationalDomains[0] == Equalities
case 0:
return MakeFact<T>(name, result, constraints.Values, factory, factory.EqualTo);
// weaklyRelationalDomains[1] == DisEqualities
case 1:
return MakeFact<T>(name, result, constraints.Values, factory, factory.NotEqualTo);
// weaklyRelationalDomains[2] == WeakUpperBounds
case 2:
return MakeFact<T>(name, result, constraints.Values, factory, factory.LessEqualThan);
// weaklyRelationalDomains[3] == StrictUpperBounds
case 3:
return MakeFact<T>(name, result, constraints.Values, factory, factory.LessThan);
// weaklyRelationalDomains[4] == Existential
case 4:
return result;
default:
Contract.Assert(false);
return factory.IdentityForAnd;
}
}
private static T MakeFact<T>(T name, T result, IEnumerable<Variable> constraints,
IFactory<T> factory, Func<T, T, T> op)
{
Contract.Requires(constraints != null);
Contract.Requires(factory != null);
Contract.Requires(op != null);
foreach (var x in constraints)
{
result = factory.And(result, op(name, factory.Variable(x)));
}
return result;
}
#endregion
#region ICloneable Members
public object Clone()
{
return this.DuplicateMe();
}
public NonRelationalValueAbstraction<Variable, Expression> DuplicateMe()
{
Contract.Ensures(Contract.Result<NonRelationalValueAbstraction<Variable, Expression>>() != null);
var newArr = new SetOfConstraints<Variable>[weaklyRelationalDomains.Length];
Array.Copy(weaklyRelationalDomains, newArr, weaklyRelationalDomains.Length);
return new NonRelationalValueAbstraction<Variable, Expression>(disInterval, symbolicConditions, newArr);
}
#endregion
#region To Please the compiler
bool IAbstractDomain.LessEqual(IAbstractDomain a)
{
var other = a as NonRelationalValueAbstraction<Variable, Expression>;
Contract.Assume(other != null);
return this.LessEqual(other);
}
IAbstractDomain IAbstractDomain.Bottom
{
get { return this.Bottom; }
}
IAbstractDomain IAbstractDomain.Top
{
get { return this.Top; }
}
IAbstractDomain IAbstractDomain.Join(IAbstractDomain a)
{
var other = a as NonRelationalValueAbstraction<Variable, Expression>;
Contract.Assume(other != null);
return this.Join(other);
}
IAbstractDomain IAbstractDomain.Meet(IAbstractDomain a)
{
var other = a as NonRelationalValueAbstraction<Variable, Expression>;
Contract.Assume(other != null);
return this.Meet(other);
}
IAbstractDomain IAbstractDomain.Widening(IAbstractDomain prev)
{
var other = prev as NonRelationalValueAbstraction<Variable, Expression>;
Contract.Assume(other != null);
return this.Widening(other);
}
#endregion
#region ToString
public override string ToString()
{
if (this.IsTop)
{
return "Top";
}
if (this.IsBottom)
{
return "_|_";
}
var result = disInterval.ToString();
result += symbolicConditions.IsTop ? "" : string.Format("({0})", symbolicConditions.ToString());
for (var i = 0; i < weaklyRelationalDomains.Length; i++)
{
var dom = weaklyRelationalDomains[i];
if (!dom.IsTop)
{
result = result + " " + OperatorFor((ADomains)i) + "{" + dom.ToString() + "}";
}
}
return result;
}
#endregion
#region IAbstractDomainWithRenaming<NonRelationalValueAbstraction<Variable,Expression>,Variable> Members
[Pure]
public NonRelationalValueAbstraction<Variable, Expression> Rename(Dictionary<Variable, FList<Variable>> renaming)
{
// Rename the symbolic conditions
var renamedExpressions = symbolicConditions.Rename(renaming);
// Rename the set of constraints
var renamedConstraints = new SetOfConstraints<Variable>[weaklyRelationalDomains.Length];
for (var i = 0; i < weaklyRelationalDomains.Length; i++)
{
var dom = weaklyRelationalDomains[i];
if (dom.IsNormal())
{
var renamedStrict = new Set<Variable>();
foreach (var prev in dom.Values)
{
FList<Variable> targets;
if (renaming.TryGetValue(prev, out targets))
{
foreach (var next in targets.GetEnumerable())
{
renamedStrict.Add(next);
}
}
}
renamedConstraints[i] = new SetOfConstraints<Variable>(renamedStrict, false);
}
else
{
renamedConstraints[i] = dom;
}
}
return new NonRelationalValueAbstraction<Variable, Expression>(this.Interval, renamedExpressions, renamedConstraints);
}
#endregion
#region Helper functions
[Pure]
static private SetOfConstraints<Variable>[] ParallelOperation(
SetOfConstraints<Variable>[] left, SetOfConstraints<Variable>[] right,
Func<SetOfConstraints<Variable>, SetOfConstraints<Variable>, SetOfConstraints<Variable>> op)
{
Contract.Requires(left != null);
Contract.Requires(right != null);
Contract.Requires(left.Length == right.Length);
Contract.Requires(op != null);
Contract.Ensures(Contract.Result<SetOfConstraints<Variable>[]>() != null);
Contract.Ensures(Contract.Result<SetOfConstraints<Variable>[]>().Length == left.Length);
Contract.Ensures(
Contract.ForAll(Contract.Result<SetOfConstraints<Variable>[]>(), el => el != null));
var result = new SetOfConstraints<Variable>[left.Length];
for (var i = 0; i < left.Length; i++)
{
var r = op(left[i], right[i]);
Contract.Assume(r != null);
result[i] = r;
}
return result;
}
[Pure]
[ContractVerification(true)]
private static string OperatorFor(ADomains index)
{
Contract.Ensures(Contract.Result<string>() != null);
Contract.Assert(index >= 0);
Contract.Assert((int)index < WeaklyRelationalDomainsCount);
switch (index)
{
case ADomains.Equalities:
return "=";
case ADomains.DisEqualities:
return "!=";
case ADomains.StrictUpperBounds:
return "<";
case ADomains.WeakUpperBounds:
return "<=";
case ADomains.Existential:
return "E";
default:
{
Contract.Assert(false); // should be unreachable
return "";
}
}
}
#endregion
#region IAbstractDomainForArraySegmentationAbstraction<NonRelationalValueAbstraction<Variable,Expression>,Variable> Members
/// <summary>
/// We only add less equals
/// </summary>
public NonRelationalValueAbstraction<Variable, Expression> AssumeInformationFrom<Exp>(INumericalAbstractDomainQuery<Variable, Exp> oracle)
{
var result = this;
if (this.IsNormal())
{
#region Update <
if (this.StrictUpperBounds.IsNormal())
{
var newConstraints = new Set<Variable>(this.StrictUpperBounds.Values);
foreach (var x in this.StrictUpperBounds.Values)
{
// Add S such that x <= S
var newBounds = oracle.UpperBoundsFor(x, true).ApplyToAll(oracle.ToVariable);
Contract.Assert(newBounds != null);
newConstraints.AddRange(newBounds);
}
result = result.Update(ADomains.StrictUpperBounds, new SetOfConstraints<Variable>(newConstraints, false));
}
#endregion
#region Update <=
if (this.WeakUpperBounds.IsNormal())
{
var newConstraints = new Set<Variable>(this.WeakUpperBounds.Values);
foreach (var x in this.WeakUpperBounds.Values)
{
// Add S such that x <= S
var newBounds = oracle.UpperBoundsFor(x, false).ApplyToAll(oracle.ToVariable);
Contract.Assert(newBounds != null);
newConstraints.AddRange(newBounds);
}
result = result.Update(ADomains.WeakUpperBounds, new SetOfConstraints<Variable>(newConstraints, false));
}
#endregion
}
return result;
}
#endregion
#region Update
public NonRelationalValueAbstraction<Variable, Expression> UpdateDisInterval(DisInterval disIntv)
{
#region Contracts
Contract.Requires(disIntv != null);
Contract.Ensures(Contract.Result<NonRelationalValueAbstraction<Variable, Expression>>() != null);
#endregion
return new NonRelationalValueAbstraction<Variable, Expression>(
disIntv,
symbolicConditions, weaklyRelationalDomains);
}
public NonRelationalValueAbstraction<Variable, Expression> UpdateSymbolicCondition(SymbolicExpressionTracker<Variable, Expression> sc)
{
#region Contracts
Contract.Requires(sc != null);
Contract.Ensures(Contract.Result<NonRelationalValueAbstraction<Variable, Expression>>() != null);
#endregion
return new NonRelationalValueAbstraction<Variable, Expression>(disInterval,
sc,
weaklyRelationalDomains);
}
public NonRelationalValueAbstraction<Variable, Expression> Update(ADomains what, SetOfConstraints<Variable> value)
{
#region Contracts
Contract.Requires(value != null);
Contract.Ensures(Contract.Result<NonRelationalValueAbstraction<Variable, Expression>>() != null);
Contract.Assert(Enum.IsDefined(typeof(ADomains), what));
#endregion
var copy = new SetOfConstraints<Variable>[weaklyRelationalDomains.Length];
Array.Copy(weaklyRelationalDomains, copy, weaklyRelationalDomains.Length);
copy[(int)what] = value;
return new NonRelationalValueAbstraction<Variable, Expression>(disInterval, symbolicConditions, copy);
}
#endregion
}
public class SymbolicExpressionTracker<Variable, Expression>
: IAbstractDomainWithRenaming<SymbolicExpressionTracker<Variable, Expression>, Variable>
{
#region Object invariant
[ContractInvariantMethod]
private void ObjectInvariant()
{
Contract.Invariant(symbolicConditions != null);
}
#endregion
#region State
private readonly Variable slackVar;
private readonly SetOfConstraints<Expression> symbolicConditions;
public delegate Expression Renaming(Expression exp, Dictionary<Variable, FList<Variable>> renaming);
public delegate Expression ReplaceVariable(Expression exp, Variable oldVar, Variable newVar);
// It can be set only once
[ThreadStatic]
private static Renaming expressionRenamer;
public static Renaming ExpressionRenamer
{
set
{
Contract.Requires(value != null);
expressionRenamer = value;
}
}
// Removed the ThreadStatic as this should run be set only once, and we run some code below in parallel, which will cause a to have a fresh, thread-local, value for variableReplacer
//[ThreadStatic]
private static ReplaceVariable variableReplacer;
public static ReplaceVariable VariableReplacer
{
set
{
Contract.Requires(value != null);
variableReplacer = value;
}
}
#endregion
#region Constructor
public SymbolicExpressionTracker(Variable slackVar, SetOfConstraints<Expression> symbolicConditions)
{
Contract.Requires(symbolicConditions != null);
this.slackVar = slackVar;
this.symbolicConditions = symbolicConditions;
}
public SymbolicExpressionTracker(Variable slackVar, Expression exp)
: this(slackVar, new SetOfConstraints<Expression>(exp))
{
}
#endregion
#region Statics
public static SymbolicExpressionTracker<Variable, Expression> Unknown
{
get
{
Contract.Ensures(Contract.Result<SymbolicExpressionTracker<Variable, Expression>>() != null);
return new SymbolicExpressionTracker<Variable, Expression>(default(Variable), SetOfConstraints<Expression>.Unknown);
}
}
public static SymbolicExpressionTracker<Variable, Expression> Unreached
{
get
{
Contract.Ensures(Contract.Result<SymbolicExpressionTracker<Variable, Expression>>() != null);
return new SymbolicExpressionTracker<Variable, Expression>(default(Variable), SetOfConstraints<Expression>.Unreached);
}
}
#endregion
#region Getters
public Variable SlackVariable
{
get
{
return slackVar;
}
}
public SetOfConstraints<Expression> Conditions
{
get
{
Contract.Ensures(Contract.Result<SetOfConstraints<Expression>>() != null);
return symbolicConditions;
}
}
#endregion
#region IAbstractDomainWithRenaming<SymbolicExpressionTracker<Variable,Expression>,Variable> Members
public SymbolicExpressionTracker<Variable, Expression> Rename(Dictionary<Variable, FList<Variable>> renaming)
{
return RenameInternal(renaming, slackVar);
}
private SymbolicExpressionTracker<Variable, Expression> RenameInternal(Dictionary<Variable, FList<Variable>> renaming, Variable slackVar)
{
Contract.Requires(renaming != null);
Contract.Ensures(Contract.Result<SymbolicExpressionTracker<Variable, Expression>>() != null);
Contract.Ensures(renaming.Count == Contract.OldValue(renaming.Count));
if (symbolicConditions.IsNormal())
{
renaming[slackVar] = FList<Variable>.Cons(slackVar, FList<Variable>.Empty);
Set<Expression> result = new Set<Expression>();
foreach (var exp in symbolicConditions.Values)
{
result.AddIfNotNull(expressionRenamer(exp, renaming));
}
var renamedExpressions =
result.Count != 0 ?
new SetOfConstraints<Expression>(result, false) :
SetOfConstraints<Expression>.Unknown;
renaming.Remove(slackVar); // We should remove the slack variable!
return new SymbolicExpressionTracker<Variable, Expression>(this.slackVar, symbolicConditions);
}
else
{
return this;
}
}
#endregion
#region Abstract operations
public bool LessEqual(SymbolicExpressionTracker<Variable, Expression> other)
{
Contract.Requires(other != null);
bool result;
if (AbstractDomainsHelper.TryTrivialLessEqual(this, other, out result))
{
return result;
}
other = this.UnifySlackVariableWith(other);
return symbolicConditions.LessEqual(other.symbolicConditions);
}
public SymbolicExpressionTracker<Variable, Expression> Bottom
{
get { return new SymbolicExpressionTracker<Variable, Expression>(default(Variable), SetOfConstraints<Expression>.Unreached); }
}
public SymbolicExpressionTracker<Variable, Expression> Top
{
get { return new SymbolicExpressionTracker<Variable, Expression>(default(Variable), SetOfConstraints<Expression>.Unknown); }
}
public SymbolicExpressionTracker<Variable, Expression> Join(SymbolicExpressionTracker<Variable, Expression> other)
{
Contract.Requires(other != null);
Contract.Ensures(Contract.Result<SymbolicExpressionTracker<Variable, Expression>>() != null);
SymbolicExpressionTracker<Variable, Expression> result;
if (AbstractDomainsHelper.TryTrivialJoin(this, other, out result))
{
return result;
}
other = UnifySlackVariableWith(other);
return new SymbolicExpressionTracker<Variable, Expression>(slackVar, symbolicConditions.Join(other.symbolicConditions));
}
public SymbolicExpressionTracker<Variable, Expression> Meet(SymbolicExpressionTracker<Variable, Expression> other)
{
Contract.Requires(other != null);
Contract.Ensures(Contract.Result<SymbolicExpressionTracker<Variable, Expression>>() != null);
SymbolicExpressionTracker<Variable, Expression> result;
if (AbstractDomainsHelper.TryTrivialMeet(this, other, out result))
{
return result;
}
other = UnifySlackVariableWith(other);
return new SymbolicExpressionTracker<Variable, Expression>(slackVar, symbolicConditions.Meet(other.symbolicConditions));
}
public SymbolicExpressionTracker<Variable, Expression> Widening(SymbolicExpressionTracker<Variable, Expression> other)
{
Contract.Requires(other != null);
Contract.Ensures(Contract.Result<SymbolicExpressionTracker<Variable, Expression>>() != null);
return this.Join(other);
}
#endregion
#region IAbstractDomain Members
public bool IsBottom
{
get { return symbolicConditions.IsBottom; }
}
public bool IsTop
{
get { return symbolicConditions.IsTop; }
}
bool IAbstractDomain.LessEqual(IAbstractDomain a)
{
var other = a as SymbolicExpressionTracker<Variable, Expression>;
Contract.Assume(a != null);
return this.LessEqual(other);
}
IAbstractDomain IAbstractDomain.Bottom
{
get { return this.Bottom; }
}
IAbstractDomain IAbstractDomain.Top
{
get { return this.Top; }
}
IAbstractDomain IAbstractDomain.Join(IAbstractDomain a)
{
var other = a as SymbolicExpressionTracker<Variable, Expression>;
Contract.Assume(a != null);
return this.Join(other);
}
IAbstractDomain IAbstractDomain.Meet(IAbstractDomain a)
{
var other = a as SymbolicExpressionTracker<Variable, Expression>;
Contract.Assume(a != null);
return this.Meet(other);
}
IAbstractDomain IAbstractDomain.Widening(IAbstractDomain prev)
{
var other = prev as SymbolicExpressionTracker<Variable, Expression>;
Contract.Assume(prev != null);
return this.Widening(other);
}
public T To<T>(IFactory<T> factory)
{
return symbolicConditions.To(factory);
}
#endregion
#region ICloneable Members
object ICloneable.Clone()
{
return this;
}
#endregion
#region Utils
private SymbolicExpressionTracker<Variable, Expression> UnifySlackVariableWith(SymbolicExpressionTracker<Variable, Expression> other)
{
Contract.Requires(other != null);
Contract.Ensures(Contract.Result<SymbolicExpressionTracker<Variable, Expression>>() != null);
if (!other.IsNormal() || object.Equals(other.slackVar, slackVar))
{
return other;
}
var result = new Set<Expression>();
foreach (var exp in other.symbolicConditions.Values)
{
result.AddIfNotNull(variableReplacer(exp, other.slackVar, slackVar));
}
return result.Count != 0 ?
new SymbolicExpressionTracker<Variable, Expression>(slackVar, new SetOfConstraints<Expression>(result, false)) :
this.Top;
}
#endregion
#region ToString
public override string ToString()
{
if (this.IsBottom)
return "_|_";
if (this.IsTop)
return "Top";
return string.Format("({0} -> {1})",
slackVar != null ? slackVar.ToString() : "null", symbolicConditions.ToString());
}
#endregion
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.